text stringlengths 14 6.51M |
|---|
unit UnitFunctions;
interface
uses
Windows, SysUtils, StrUtils, ShellAPI;
function JustL(S: string; Size: integer) : string;
function MyBoolToStr(TmpBool: Boolean): string;
function MyStrToBool(TmpStr: string): Boolean;
function FileSizeToStr(Bytes: LongInt): string;
function FileIconInit(FullInit: BOOL): BOOL; stdcall;
function GetImageIndex(FileName: string): integer;
procedure SetClipboardText(Const S: widestring);
function TmpDir: string;
function ReadKeyString(Key:HKEY; Path:string; Value, Default: string): string;
procedure CreateKeyString(Key: HKEY; Subkey, Name, Value: string);
function MyGetFileSize(Filename: String): Int64;
function MyGetTime(Separator: string): string;
function MyGetDate(Separator: string): string;
procedure CreateTextFile(Filename, Content: string);
procedure WriteTextFile(Filename, Content: string);
function LoadTextFile(Filename: string): string;
function FileToStr(sPath: string; var sFile: string): Boolean;
function WriteResData(sServerFile: string; pFile: pointer; Size: Integer; Name: String): Boolean;
implementation
//P0ke
function WriteResData(sServerFile: string; pFile: pointer; Size: Integer; Name: String): Boolean;
var
hResourceHandle: THandle;
pwServerFile: PWideChar;
pwName: PWideChar;
begin
GetMem(pwServerFile, (Length(sServerFile) + 1) *2);
GetMem(pwName, (Length(Name) + 1) *2);
try
StringToWideChar(sServerFile, pwServerFile, Length(sServerFile) * 2);
StringToWideChar(Name, pwName, Length(Name) * 2);
hResourceHandle := BeginUpdateResourceW(pwServerFile, False);
Result := UpdateResourceW(hResourceHandle, MakeIntResourceW(10), pwName, 0, pFile, Size);
EndUpdateResourceW(hResourceHandle, False);
finally
FreeMem(pwServerFile);
FreeMem(pwName);
end;
end;
//steve10120
function FileToStr(sPath: string; var sFile: string): Boolean;
var
hFile: THandle;
dSize: DWORD;
dRead: DWORD;
begin
Result := FALSE;
hFile := CreateFile(PChar(sPath), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
if hFile <> 0 then
begin
dSize := GetFileSize(hFile, nil);
if dSize <> 0 then
begin
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
SetLength(sFile, dSize);
if ReadFile(hFile, sFile[1], dSize, dRead, nil) then Result := TRUE;
CloseHandle(hFile);
end;
end;
end;
procedure CreateTextFile(Filename, Content: string);
var
hFile, Len, i: Cardinal;
begin
hFile := CreateFile(pchar(Filename),GENERIC_WRITE,FILE_SHARE_WRITE,nil,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
if hFile = INVALID_HANDLE_VALUE then Exit;
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
Len := Length(Content);
WriteFile(hFile, Content[1], Len, i, nil);
CloseHandle(hFile);
end;
procedure WriteTextFile(Filename, Content: string);
var
hFile, Len, i: Cardinal;
begin
hFile := CreateFile(pchar(Filename),GENERIC_WRITE,FILE_SHARE_WRITE,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if hFile = INVALID_HANDLE_VALUE then Exit;
SetFilePointer(hFile, 0, nil, FILE_END);
Len := Length(Content);
WriteFile(hFile, Content[1], Len, i, nil);
CloseHandle(hFile);
end;
function LoadTextFile(Filename: string): string;
var
hFile, Len, i: Cardinal;
p: Pointer;
begin
if not FileExists(Filename) then Exit;
hFile := CreateFile(pchar(Filename),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if hFile = INVALID_HANDLE_VALUE then Exit;
i := GetFileSize(hFile, nil);
GetMem(p, i);
ReadFile(hFile, p^, i, Len, nil);
SetString(Result, PChar(p), i);
FreeMem(p, i);
CloseHandle(hFile);
end;
function MyGetTime(Separator: string): string;
var
MyTime: TSystemTime;
begin
GetLocalTime(MyTime);
Result := inttostr(MyTime.wHour) + Separator + inttostr(MyTime.wMinute) +
Separator + inttostr(MyTime.wSecond);
end;
function MyGetDate(Separator: string): string;
var
MyTime: TSystemTime;
begin
GetLocalTime(MyTime);
Result := inttostr(MyTime.wDay) + Separator + inttostr(MyTime.wMonth) +
Separator + inttostr(MyTime.wYear);
end;
function MyGetFileSize(Filename: string): Int64;
var hFile: THandle;
begin
hFile := CreateFile(pchar(FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,0);
Result := GetFileSize(hFile, nil);
CloseHandle(hFile);
end;
procedure CreateKeyString(Key: HKEY; Subkey, Name, Value: string);
var regkey: Hkey;
begin
RegCreateKey(Key, PChar(subkey), regkey);
RegSetValueEx(regkey, PChar(name), 0, REG_EXPAND_SZ, PChar(value), Length(value));
RegCloseKey(regkey);
end;
function ReadKeyString(Key:HKEY; Path:string; Value, Default: string): string;
Var
Handle:hkey;
RegType:integer;
DataSize:integer;
begin
Result := Default;
if (RegOpenKeyEx(Key, pchar(Path), 0, KEY_QUERY_VALUE, Handle) = ERROR_SUCCESS) then
begin
if RegQueryValueEx(Handle, pchar(Value), nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then
begin
SetLength(Result, Datasize);
RegQueryValueEx(Handle, pchar(Value), nil, @RegType, PByte(pchar(Result)), @DataSize);
SetLength(Result, Datasize - 1);
end;
RegCloseKey(Handle);
end;
end;
function TmpDir: string;
var
DataSize: byte;
begin
SetLength(Result, MAX_PATH);
DataSize := GetTempPath(MAX_PATH, PChar(Result));
if DataSize <> 0 then
begin
SetLength(Result, DataSize);
if Result[Length(Result)] <> '\' then Result := Result + '\';
end;
end;
procedure SetClipboardText(Const S: widestring);
var
Data: THandle;
DataPtr: Pointer;
Size: integer;
begin
Size := length(S);
OpenClipboard(0);
try
Data := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, (Size * 2) + 2);
try
DataPtr := GlobalLock(Data);
try
Move(S[1], DataPtr^, Size * 2);
SetClipboardData(CF_UNICODETEXT{CF_TEXT}, Data);
finally
GlobalUnlock(Data);
end;
except
GlobalFree(Data);
raise;
end;
finally
CloseClipboard;
end;
end;
function GetImageIndex(FileName: string): integer;
var
SHFileInfo: TSHFileInfo;
begin
result := - 1;
try
SHGetFileInfo(PChar(FileName), FILE_ATTRIBUTE_NORMAL, SHFileInfo,
SizeOf(SHFileInfo), SHGFI_SMALLICON or SHGFI_USEFILEATTRIBUTES or SHGFI_SYSICONINDEX);
Result := SHFileInfo.iIcon;
finally
if Result <= 0 then result := - 1;
end;
end;
function FileIconInit(FullInit: BOOL): BOOL; stdcall;
type
TFileIconInit = function(FullInit: BOOL): BOOL; stdcall;
var
PFileIconInit: TFileIconInit;
ShellDLL: integer;
begin
//this forces winNT to load all the icons
Result := False;
if (Win32Platform = VER_PLATFORM_WIN32_NT) then
begin
ShellDLL := LoadLibrary('Shell32.dll');
PFileIconInit := GetProcAddress(ShellDLL, PChar(660));
if (Assigned(PFileIconInit)) then Result := PFileIconInit(FullInit);
end;
end;
function JustL(S: string; Size: integer) : string;
var
i : integer;
begin
i := Size - Length(S);
if i > 0 then S := S + DupeString('.', i);
JustL := S;
end;
function MyBoolToStr(TmpBool: Boolean): string;
begin
if TmpBool = True then Result := 'Yes' else Result := 'No';
end;
function MyStrToBool(TmpStr: string): Boolean;
begin
if TmpStr = 'Yes' then Result := True else Result := False;
end;
function FileSizeToStr(Bytes: LongInt): string;
var
dB, dKB, dMB, dGB, dT: integer;
begin
dB := Bytes;
dKB := 0;
dMB := 0;
dGB := 0;
dT := 1;
while (dB > 1024) do
begin
inc(dKB, 1);
dec(dB , 1024);
dT := 1;
end;
while (dKB > 1024) do
begin
inc(dMB, 1);
dec(dKB, 1024);
dT := 2;
end;
while (dMB > 1024) do
begin
inc(dGB, 1);
dec(dMB, 1024);
dT := 3;
end;
case dT of
1: result := inttostr(dKB) + '.' + copy(inttostr(dB ),1,2) + ' Kb';
2: result := inttostr(dMB) + '.' + copy(inttostr(dKB),1,2) + ' Mb';
3: result := inttostr(dGB) + '.' + copy(inttostr(dMB),1,2) + ' Gb';
end;
end;
end.
|
UNIT fileHistories;
INTERFACE
USES mySys,myGenerics,sysutils,FileUtil,myStringUtil;
PROCEDURE removeNonexistent;
PROCEDURE addToHistory(CONST utfFile1:ansistring; CONST utfFile2:ansistring=''; CONST utfFile3:ansistring=''; CONST utfFile4:ansistring='');
PROCEDURE limitHistory(CONST sizeLimit:longint);
PROCEDURE historyItemRecalled(CONST index:longint);
VAR history:T_arrayOfString;
IMPLEMENTATION
PROCEDURE removeNonexistent;
VAR i,j,i2,j2:longint;
fileSet:T_arrayOfString;
begin
j:=0;
for i:=0 to length(history)-1 do
if fileExists(history[i]) then begin
history[j]:=history[i];
inc(j);
end else if pos('&',history[i])>0 then begin
fileSet:=split(history[i],T_arrayOfString('&'));
j2:=0;
for i2:=0 to length(fileSet)-1 do
if fileExists(fileSet[i2]) then begin
fileSet[j2]:=fileSet[i2];
inc(j2);
end;
setLength(fileSet,j2);
if (j2>0) then begin
history[j]:=join(fileSet,'&');
inc(j);
end;
end;
setLength(history,j);
j:=1;
for i:=1 to length(history)-1 do begin
i2:=0;
while (i2<i) and (history[i2]<>history[i]) do inc(i2);
if i2>=i then begin
history[j]:=history[i];
inc(j);
end;
end;
setLength(history,j);
end;
PROCEDURE addToHistory(CONST utfFile1: ansistring; CONST utfFile2: ansistring; CONST utfFile3: ansistring; CONST utfFile4: ansistring);
VAR historyLine:ansistring;
i,j:longint;
begin
historyLine:=utfFile1;
if utfFile2<>'' then historyLine:=historyLine+'&'+utfFile2;
if utfFile3<>'' then historyLine:=historyLine+'&'+utfFile3;
if utfFile4<>'' then historyLine:=historyLine+'&'+utfFile4;
j:=0;
for i:=0 to length(history)-1 do if history[i]<>historyLine then begin
history[j]:=history[i];
inc(j);
end;
setLength(history,j);
setLength(history,length(history)+1);
for i:=length(history)-1 downto 1 do history[i]:=history[i-1];
history[0]:=historyLine;
removeNonexistent;
end;
PROCEDURE limitHistory(CONST sizeLimit: longint);
begin
if sizeLimit>length(history) then setLength(history,sizeLimit);
end;
PROCEDURE historyItemRecalled(CONST index: longint);
VAR i:longint;
temp:ansistring;
begin
for i:=index-1 downto 0 do begin
temp:=history[i];
history[i]:=history[i+1];
history[i+1]:=temp;
end;
removeNonexistent;
end;
INITIALIZATION
history:=readFile(ChangeFileExt(paramStr(0),'.fileHist'));
removeNonexistent;
FINALIZATION
writeFile(ChangeFileExt(paramStr(0),'.fileHist'),history);
end.
|
unit frmMonitorRestart;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, Spin;
type
TForm1 = class(TForm)
Memo1: TMemo;
Label1: TLabel;
btnStop: TButton;
btnRestart: TButton;
ProgressBar1: TProgressBar;
lblStatus: TLabel;
Label2: TLabel;
seInterval: TSpinEdit;
procedure btnStopClick(Sender: TObject);
procedure btnRestartClick(Sender: TObject);
procedure seIntervalChange(Sender: TObject);
private
{ Private declarations }
public
procedure LogMessage(Msg: string; LogType: Integer = EVENTLOG_ERROR_TYPE);
end;
var
Form1: TForm1;
implementation
uses RestarterDataModule;
{$R *.DFM}
procedure TForm1.LogMessage(Msg: string; LogType: Integer = EVENTLOG_ERROR_TYPE);
var h: THandle;
ss: array [0..0] of pchar;
bRetVal: bytebool;
iErrNo: integer;
begin
bRetVal := true;
Memo1.Lines.Add(DateTimeTostr(Now) + ': ' + Msg);
ss[0] := pchar(Msg);
h := RegisterEventSource(nil, // uses local computer
pchar('MonitorRestartApp')); // source name
if h <> 0 then
begin
bRetVal := ReportEvent(h, // event log handle
LogType, // event type
0, // category zero
0, // event identifier
nil, // no user security identifier
1, // one substitution string
0, // no data
@ss, // pointer to string array
nil); // pointer to data
end;
DeregisterEventSource(h);
if not bRetVal then
begin
iErrNo := GetLastError;
ShowMessage('Report event failed with ' + IntToStr(iErrNo));
end;
end;
procedure TForm1.btnStopClick(Sender: TObject);
begin
DataModule1.tmrCheckRunning.Enabled := false;
LogMessage('User stopped Restarter app', EVENTLOG_INFORMATION_TYPE);
lblStatus.Caption := 'Status: paused';
btnStop.Enabled := false;
btnRestart.Enabled := true;
end;
procedure TForm1.btnRestartClick(Sender: TObject);
begin
DataModule1.tmrCheckRunning.Enabled := true;
LogMessage('User restarted Restarter app', EVENTLOG_INFORMATION_TYPE);
lblStatus.Caption := 'Status: checking';
btnRestart.Enabled := false;
btnStop.Enabled := true;
end;
procedure TForm1.seIntervalChange(Sender: TObject);
begin
DataModule1.tmrCheckRunning.Enabled := false;
if(seInterval.Text = '') then
begin
// seInterval.Text := IntToStr(seInterval.Value);
end else
begin
DataModule1.tmrCheckRunning.Interval := StrToInt(seInterval.Text) * 1000;
end;
DataModule1.tmrCheckRunning.Enabled := true;
end;
end.
unit frmMonitorRestart;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Label1: TLabel;
btnStop: TButton;
btnRestart: TButton;
procedure btnStopClick(Sender: TObject);
procedure btnRestartClick(Sender: TObject);
private
{ Private declarations }
public
procedure LogMessage(Msg: string; LogType: Integer = EVENTLOG_ERROR_TYPE);
end;
var
Form1: TForm1;
implementation
uses RestarterDataModule;
{$R *.DFM}
procedure TForm1.LogMessage(Msg: string; LogType: Integer = EVENTLOG_ERROR_TYPE);
var h: THandle;
ss: array [0..0] of pchar;
bRetVal: bytebool;
iErrNo: integer;
begin
bRetVal := true;
Memo1.Lines.Add(DateTimeTostr(Now) + ': ' + Msg);
ss[0] := pchar(Msg);
h := RegisterEventSource(nil, // uses local computer
pchar('MonitorRestartApp')); // source name
if h <> 0 then
begin
bRetVal := ReportEvent(h, // event log handle
LogType, // event type
0, // category zero
0, // event identifier
nil, // no user security identifier
1, // one substitution string
0, // no data
@ss, // pointer to string array
nil); // pointer to data
end;
DeregisterEventSource(h);
if not bRetVal then
begin
iErrNo := GetLastError;
ShowMessage('Report event failed with ' + IntToStr(iErrNo));
end;
end;
procedure TForm1.btnStopClick(Sender: TObject);
begin
DataModule1.tmrCheckRunning.Enabled := false;
LogMessage('User stopped Restarter app', EVENTLOG_INFORMATION_TYPE);
btnStop.Enabled := false;
btnRestart.Enabled := true;
end;
procedure TForm1.btnRestartClick(Sender: TObject);
begin
DataModule1.tmrCheckRunning.Enabled := true;
LogMessage('User restarted Restarter app', EVENTLOG_INFORMATION_TYPE);
btnRestart.Enabled := false;
btnStop.Enabled := true;
end;
end.
|
unit CBROrderDeskPresenter;
interface
uses CustomPresenter, db, EntityServiceIntf, CoreClasses, CBRConst, sysutils,
variants, ShellIntf;
const
ENT = 'CBR_ORD_DESK';
COMMAND_MENU_OPEN = '{4E9854DA-9576-454F-8880-EAF384FB3DA7}';
COMMAND_ITEM_ADD = '{FBA0B203-BEFE-493A-8A06-22BA9E561BD9}';
COMMAND_ITEM_QTY_INC = '{D397B9F8-8D6E-4E94-9BC6-C716C0380AC6}';
COMMAND_ITEM_QTY_DEC = '{0B452758-1D53-4871-958E-E1790A9B5EC7}';
COMMAND_ITEM_CANCEL = '{7FA180AF-7B6E-431A-AD3C-FB884BD0D5BC}';
COMMAND_ITEM_ADDON = '{BC859346-0415-4FE4-8744-2BAB90D4B192}';
COMMAND_KORD = '{84528DE7-D306-4011-BDD5-A511F0BAD3C5}';
COMMAND_PRECHECK = '{35A920C6-BC75-41D2-A83E-EB0DC44F52F9}';
COMMAND_PAYT = '{D1ADF96C-9003-4C8F-AC1E-347808602886}';
COMMAND_MOVE = '{E8B21D1B-FFCD-4C10-AB8C-B8FA233C4D40}';
type
ICBROrderDeskView = interface
['{1DE7E4AC-1306-4661-87ED-396196986516}']
procedure LinkMenuGrpDataSet(ADataSet: TDataSet);
procedure LinkMenuData(ADataSet: TDataSet);
procedure LinkHeadData(ADataSet: TDataSet);
procedure LinkItemsData(ADataSet: TDataSet);
procedure HideMenu;
end;
TCBROrderDeskPresenter = class(TCustomPresenter)
const
KORDER_REPORT = 'reports.korder';
private
FLastItem: Variant;
function GetEVHead: IEntityView;
function GetEVItems: IEntityView;
function GetEVItemInit: IEntityView;
function GetEVMenuGrp: IEntityView;
function GetEVMenu: IEntityView;
function View: ICBROrderDeskView;
function GetCallerWI: TWorkItem;
procedure ItemsAfterScroll(ADataSet: TDataSet);
procedure UpdateCommandStatus;
function KOrderMakeAndPrint: boolean;
procedure CmdOpenMenu(Sender: TObject);
procedure CmdItemAddon(Sender: TObject);
procedure CmdItemAdd(Sender: TObject);
procedure CmdItemQtyInc(Sender: TObject);
procedure CmdItemQtyDec(Sender: TObject);
procedure SetItemQty(const AValue: Variant);
procedure CmdItemCancel(Sender: TObject);
procedure CmdKORD(Sender: TObject);
procedure CmdPayt(Sender: TObject);
procedure CmdMove(Sender: TObject);
procedure ExecActivityAndClose(const URI: string);
protected
function OnGetWorkItemState(const AName: string; var Done: boolean): Variant; override;
procedure OnViewReady; override;
procedure OnViewClose; override;
end;
implementation
{ TCBROrderDeskPresenter }
procedure TCBROrderDeskPresenter.CmdItemAdd(Sender: TObject);
var
cmd: ICommand;
ds: TDataSet;
dsNew: TDataSet;
i: integer;
field: TField;
begin
Sender.GetInterface(ICommand, cmd);
ds := GetEVItems.DataSet;
if (not ds.IsEmpty)
and (ds['MENU_ID'] = cmd.Data['MENU_ID'])
and (ds['FKORD'] = 0) then
SetItemQty(GetEVItems.DataSet['QTY'] + 1)
else begin
try
ds.Append;
dsNew := GetEVItemInit.Load([WorkItem.State['ID'],
GetEVMenu.DataSet['ID'],
GetEVMenu.DataSet['PARENT_ID']]);
for I := 0 to dsNew.FieldCount - 1 do
begin
field := ds.FindField(dsNew.Fields[I].FieldName);
if assigned(field) then
field.Value := dsNew.Fields[I].Value;
end;
if VarIsNull(ds['PARENT_ID']) then
FLastItem := ds['ID'];
ds.Post;
except
ds.Cancel;
raise;
end;
end;
GetEVHead.Load(true);
// Insert;
end;
procedure TCBROrderDeskPresenter.CmdItemCancel(Sender: TObject);
var
ds: TDataSet;
begin
ds := GetEVItems.DataSet;
if ds['FKORD'] = 0 then
begin
ds.Delete;
end;
GetEVHead.Load(true);
end;
procedure TCBROrderDeskPresenter.CmdItemQtyDec(Sender: TObject);
begin
SetItemQty(GetEVItems.DataSet['QTY'] - 1);
end;
procedure TCBROrderDeskPresenter.CmdItemQtyInc(Sender: TObject);
begin
SetItemQty(GetEVItems.DataSet['QTY'] + 1);
end;
procedure TCBROrderDeskPresenter.CmdKORD(Sender: TObject);
begin
if GetEVItems.DataSet.IsEmpty then Exit;
if KOrderMakeAndPrint then
CloseView(false)
else
App.UI.MessageBox.InfoMessage('Нет заказа!');
end;
procedure TCBROrderDeskPresenter.CmdMove(Sender: TObject);
begin
ExecActivityAndClose(ACTIVITY_ORDER_MOVE);
end;
procedure TCBROrderDeskPresenter.CmdItemAddon(Sender: TObject);
begin
GetEVMenu.Load([null, GetEVItems.DataSet.FieldValues['ID']]);
View.LinkMenuData(GetEVMenu.DataSet);
end;
procedure TCBROrderDeskPresenter.CmdOpenMenu(Sender: TObject);
var
cmd: ICommand;
begin
Sender.GetInterface(ICommand, cmd);
GetEVMenu.Load([cmd.Data['GRP_ID'], null]);
View.LinkMenuData(GetEVMenu.DataSet);
end;
procedure TCBROrderDeskPresenter.CmdPayt(Sender: TObject);
var
activity: IActivity;
begin
if GetEVItems.DataSet.IsEmpty then Exit;
KOrderMakeAndPrint;
App.Entities.Entity['CBR_ORD'].
GetOper('PreCheck', WorkItem).Execute([WorkItem.State['ID']]);
activity := WorkItem.Activities[ACTIVITY_ORDER_PAYT];
activity.Params['ID'] := WorkItem.State['ID'];
activity.Execute(GetCallerWI);
CloseView(false);
end;
procedure TCBROrderDeskPresenter.ExecActivityAndClose(const URI: string);
var
callerWI: TWorkItem;
activity: IActivity;
begin
callerWI := WorkItem.Root.WorkItems.Find(callerURI);
if callerWI = nil then
callerWI := WorkItem.Parent;
activity := WorkItem.Activities[URI];
activity.Params['ORD_ID'] := WorkItem.State['ID'];
activity.Execute(callerWI);
CloseView(false);
end;
function TCBROrderDeskPresenter.GetEVMenu: IEntityView;
begin
Result := (WorkItem.Services[IEntityService] as IEntityService).
Entity[ENT].GetView('Menu', WorkItem);
end;
function TCBROrderDeskPresenter.GetEVMenuGrp: IEntityView;
begin
Result := (WorkItem.Services[IEntityService] as IEntityService).
Entity[ENT].GetView('MenuGrp', WorkItem);
Result.Load(false);
end;
procedure TCBROrderDeskPresenter.ItemsAfterScroll(ADataSet: TDataSet);
begin
UpdateCommandStatus;
end;
function TCBROrderDeskPresenter.KOrderMakeAndPrint: boolean;
var
activity: IActivity;
ds: TDataSet;
begin
App.Entities.Entity['CBR_KORD'].GetOper('Create', WorkItem).
Execute([WorkItem.State['ID']]);
ds := App.Entities.Entity['CBR_KORD'].GetOper('NotPrinted', WorkItem).
Execute([WorkItem.State['ID']]);
Result := not ds.IsEmpty;
while not ds.Eof do
begin
activity := WorkItem.Activities[KORDER_REPORT];
activity.Params['ID'] := ds['ID'];
activity.Params['PRINTER'] := ds['PRINTER'];
activity.Params['LaunchMode'] := 2;
activity.Execute(WorkItem);
ds.Next;
end;
end;
function TCBROrderDeskPresenter.GetCallerWI: TWorkItem;
begin
Result := WorkItem.Root.WorkItems.Find(callerURI);
if Result = nil then
Result := WorkItem.Parent;
end;
function TCBROrderDeskPresenter.GetEVHead: IEntityView;
begin
Result := (WorkItem.Services[IEntityService] as IEntityService).
Entity[ENT].GetView('Header', WorkItem);
end;
function TCBROrderDeskPresenter.GetEVItemInit: IEntityView;
begin
Result := (WorkItem.Services[IEntityService] as IEntityService).
Entity[ENT].GetView('ItemInit', WorkItem);
end;
function TCBROrderDeskPresenter.GetEVItems: IEntityView;
begin
Result := (WorkItem.Services[IEntityService] as IEntityService).
Entity[ENT].GetView('Items', WorkItem);
end;
function TCBROrderDeskPresenter.OnGetWorkItemState(const AName: string;
var Done: boolean): Variant;
begin
{if SameText(AName, 'ID') then
begin
WorkItem.State.
Result := WorkItem.State['ID'];
Done := true;
end;}
end;
procedure TCBROrderDeskPresenter.OnViewClose;
begin
if (ViewInfo.ActivityClass = ACTIVITY_ORDER_NEW) and
GetEVItems.DataSet.IsEmpty then
try
App.Entities.Entity['CBR_ORD'].GetOper('Delete', WorkItem).
Execute([WorkItem.State['ID']]);
except
on E: Exception do
App.UI.MessageBox.ErrorMessage(E.Message);
end;
end;
procedure TCBROrderDeskPresenter.OnViewReady;
begin
ViewTitle := 'Заказ';
if ViewInfo.ActivityClass = ACTIVITY_ORDER_NEW then
begin
WorkItem.State['ID'] :=
(WorkItem.Services[IEntityService] as IEntityService).
Entity[ENT].GetOper('CreateHeader', WorkItem).Execute([
WorkItem.State['TBL_ID']])['ID'];
end;
GetEVHead.Load([WorkItem.State['ID']]);
GetEVItems.ImmediateSave := true;
GetEVItems.Load([WorkItem.State['ID']]);
GetEVItems.DataSet.AfterScroll := ItemsAfterScroll;
View.LinkHeadData(GetEVHead.DataSet);
View.LinkItemsData(GetEVItems.DataSet);
View.LinkMenuGrpDataSet(GetEVMenuGrp.DataSet);
WorkItem.Commands[COMMAND_MENU_OPEN].SetHandler(CmdOpenMenu);
WorkItem.Commands[COMMAND_ITEM_ADD].SetHandler(CmdItemAdd);
WorkItem.Commands[COMMAND_ITEM_QTY_INC].SetHandler(CmdItemQtyInc);
WorkItem.Commands[COMMAND_ITEM_QTY_DEC].SetHandler(CmdItemQtyDec);
WorkItem.Commands[COMMAND_ITEM_CANCEL].SetHandler(CmdItemCancel);
WorkItem.Commands[COMMAND_ITEM_ADDON].SetHandler(CmdItemAddon);
WorkItem.Commands[COMMAND_KORD].SetHandler(CmdKORD);
WorkItem.Commands[COMMAND_PAYT].SetHandler(CmdPayt);
WorkItem.Commands[COMMAND_MOVE].SetHandler(CmdMove);
WorkItem.Commands[COMMAND_MOVE].Status := csUnavailable;
UpdateCommandStatus;
end;
procedure TCBROrderDeskPresenter.SetItemQty(const AValue: Variant);
var
ds: TDataSet;
begin
if AValue <= 0 then Exit;
ds := GetEVItems.DataSet;
try
ds.Edit;
ds['QTY'] := AValue;
ds['SUMM'] := ds['QTY'] * ds['PRICE'];
ds.Post;
finally
ds.Cancel;
end;
GetEVHead.Load(true);
end;
procedure TCBROrderDeskPresenter.UpdateCommandStatus;
begin
WorkItem.Commands[COMMAND_KORD].Status := csDisabled;
WorkItem.Commands[COMMAND_PAYT].Status := csDisabled;
WorkItem.Commands[COMMAND_ITEM_QTY_INC].Status := csDisabled;
WorkItem.Commands[COMMAND_ITEM_QTY_DEC].Status := csDisabled;
WorkItem.Commands[COMMAND_ITEM_CANCEL].Status := csDisabled;
WorkItem.Commands[COMMAND_ITEM_ADDON].Status := csUnavailable;
if not GetEVItems.DataSet.IsEmpty then
begin
if GetEVItems.DataSet['FKORD'] = 0 then
begin
WorkItem.Commands[COMMAND_ITEM_QTY_INC].Status := csEnabled;
WorkItem.Commands[COMMAND_ITEM_QTY_DEC].Status := csEnabled;
WorkItem.Commands[COMMAND_ITEM_CANCEL].Status := csEnabled;
end;
if (GetEVItems.DataSet['FKORD'] = 0) and
(GetEVItems.DataSet['ID'] = FLastItem) then
WorkItem.Commands[COMMAND_ITEM_ADDON].Status := csEnabled;
WorkItem.Commands[COMMAND_KORD].Status := csEnabled;
WorkItem.Commands[COMMAND_PAYT].Status := csEnabled;
end;
end;
function TCBROrderDeskPresenter.View: ICBROrderDeskView;
begin
Result := GetView as ICBROrderDeskView;
end;
end.
|
unit Pacman;
{$MODE Delphi}
interface
USES LCLIntf, LCLType, LMessages, Variants, Classes, SysUtils, Graphics, LinkedList,
Map, MapObject, Animation;
CONST DEFAULT_SPEED = 3;
CONST BONUS_SPEED = 5;
VAR gfx : ARRAY [0 .. 6 * 10 - 1] OF TBitmap;
TYPE TPacman = CLASS(TMobileObject)
PUBLIC
CONSTRUCTOR create(_x, _y, _direction : INTEGER); OVERLOAD;
CLASS PROCEDURE loadGfx();
PROCEDURE setDirection(dir : INTEGER);
PROCEDURE spawn();
FUNCTION getScore() : INTEGER;
FUNCTION getCurrentAnimation() : TAnimation;
FUNCTION isDead() : BOOLEAN;
FUNCTION getLives() : INTEGER;
FUNCTION getType() : TMapObjectType; OVERRIDE;
PROCEDURE onCollide(other : TMapObject; objects : TLinkedList); OVERRIDE;
PROCEDURE move(map : TMap; objects : TLinkedList); OVERRIDE;
PROCEDURE draw(canvas : TCanvas); OVERRIDE;
PRIVATE
startx, starty, startdir : INTEGER;
dead : BOOLEAN;
lives : INTEGER;
score : INTEGER;
nextDirection : INTEGER;
currentAnimation : TAnimation;
animations : ARRAY[0..9] OF TAnimation;
poweruptimer : INTEGER;
END;
IMPLEMENTATION
CONSTRUCTOR TPacman.create(_x, _y, _direction : INTEGER);
VAR i : INTEGER;
BEGIN
INHERITED create(_x, _y, TILE_SIZE, TILE_SIZE, DEFAULT_SPEED, _direction);
startdir := direction;
startx := getLeft();
starty := getTop();
FOR i := 0 TO 4 DO
animations[i] := TAnimation.create(i*6, 6, 3, TRUE);
FOR i := 5 TO 9 DO
animations[i] := TAnimation.create(i*6, 6, 4, FALSE);
lives := 3;
spawn();
END;
CLASS PROCEDURE TPacman.loadGfx();
VAR sheet : TBitmap;
VAR i : INTEGER;
BEGIN
sheet := TBitmap.create();
sheet.LoadFromFile('gfx/pacman_spritesheet.bmp');
loadSpriteSheet(sheet, 0, 0, sheet.width, sheet.height, 6, 10, gfx);
FOR i := 0 TO LENGTH(gfx)-1 DO
gfx[i].Transparent := TRUE;
sheet.destroy();
END;
PROCEDURE TPacman.setDirection(dir : INTEGER);
BEGIN
nextDirection := dir;
END;
PROCEDURE TPacman.spawn();
BEGIN
x := startx;
y := starty;
direction := startdir;
nextDirection := startdir;
score := 0;
dead := FALSE;
speed := DEFAULT_SPEED;
poweruptimer := 0;
currentAnimation := animations[direction].start();
END;
FUNCTION TPacman.getScore() : INTEGER;
BEGIN
getScore := score;
END;
FUNCTION TPacman.getCurrentAnimation() : TAnimation;
BEGIN
getCurrentAnimation := currentAnimation;
END;
FUNCTION TPacman.isDead() : BOOLEAN;
BEGIN
isDead := dead;
END;
FUNCTION TPacman.getLives() : INTEGER;
BEGIN
getLives := lives;
END;
FUNCTION TPacman.getType() : TMapObjectType;
BEGIN
getType := OBJECT_PACMAN;
END;
PROCEDURE TPacman.onCollide(other : TMapObject; objects : TLinkedList);
BEGIN
IF other.getType() = OBJECT_FOOD THEN
BEGIN
score := score + 10;
END
ELSE IF other.getType() = OBJECT_POWERUP THEN
BEGIN
speed := BONUS_SPEED;
powerupTimer := poweruptimer DIV 2 + 350;
END
ELSE IF other.getType() = OBJECT_GHOST THEN
BEGIN
IF NOT dead THEN
BEGIN
dead := TRUE;
lives := lives - 1;
currentAnimation := animations[direction+5].start();
END;
END
END;
PROCEDURE TPacman.move(map : TMap; objects : TLinkedList);
VAR i : INTEGER;
BEGIN
currentAnimation.advance();
IF powerupTimer > 0 THEN
BEGIN
powerupTimer := powerupTimer - 1;
IF powerupTimer <= 0 THEN
BEGIN
speed := DEFAULT_SPEED;
powerupTimer := 0;
END;
END;
FOR i := 1 TO speed DO
BEGIN
IF NOT dead THEN
BEGIN
INHERITED move(map, objects);
IF canMove(x + getDirectionX(nextDirection), y + getDirectionY(nextDirection), map) THEN
IF direction <> nextDirection THEN
BEGIN
direction := nextDirection;
currentAnimation := animations[direction].resume(currentAnimation);
END;
END
END;
END;
PROCEDURE TPacman.draw(canvas : TCanvas);
VAR spriteid : INTEGER;
BEGIN
spriteId := currentAnimation.getSpriteId();
canvas.Draw(getCenterX() - gfx[spriteid].Width DIV 2,
getCenterY() - gfx[spriteid].Height DIV 2,
gfx[spriteid]);
END;
END.
|
{*******************************************************************************
Developer: josking Date: 2009/11/26
Coding standard version NO. :1.0
Copyright(GBM) EMS , All right reserved
*******************************************************************************}
unit clsCommFunction;
interface
uses
classes, clsClientDtSet, SysUtils, DBGrids, StdCtrls;
type
TEnumDatasetOperation = (doExactQuery, doQuery, doAdd, doEdit, doDelete, doInsert);
TclsCommFunction = class(Tobject)
public
{* 根據存儲了數據表字段與對應值的集合,動態的產生SQL語句 *}
function BuildSqlString(const AStrNames, AStrValues: TStringList;
AOperation: TEnumDatasetOperation): string;
end;
// 判斷編輯框輸入一個字符Key后﹐編輯框中的數據還是不是一個合法的整形數
function CheckISInt(Sender: TObject; const Key: Char; const Alength: integer): boolean;
// 判斷編輯框輸入一個字符Key后﹐編輯框中的數據還是不是一個合法的浮點數
function CheckISFloat(Sender: TObject; const Key: Char;
const AintLen, AdecLen: integer): boolean;
// 傳入ADataSet﹐把ADataSet中的數據填入AstrListID,AstrListDesc中 Added by oy 030416
procedure FillStringsByDB(ADataSet: TClientDtSet;
AstrListID, AstrListDesc: TStrings; AIfFillChar: boolean = true; AFillChar: string = '*'); overload;
// 傳入ADataSet﹐把ADataSet中的數據填入AstrListIDDesc中 Added by oy 030416
procedure FillStringsByDB(ADataSet: TClientDtSet;
AstrListIDDesc: TStrings; AIfFillChar: boolean = true; AFillChar: string = '*'); overload;
{ 依照AFieldNames, ADisplayNames, AIsShowList,ADtSet的值﹐
對指定之ADbGrid的Columns屬性進行設定 }
procedure FillGridColumn(AFieldNames, ADisplayNames, AIsShowList: Tstrings;
ADtSet: TClientDtSet; ADbGrid: TDbGrid);
// 將ASource中的所有的數據項移到ADest中
procedure MoveWholeStrings(ASource, ADest: TStrings; ACanRepeat: Boolean = true);
// 將ASource中所有的選中的數據項移到ADest中
procedure MoveSelectedListBoxItem(ASource, ADest: TListBox; ACanRepeat: Boolean = true);
// 取得字串Astr中ASeparator以后的一部分字串
function GetBackStringbySeparator(const Astr, ASeparator: string;
AKeepBackSeparator: Boolean = False): string;
// 取得字串Astr中ASeparator以前的一部分字串
function GetForeStringbySeparator(const Astr, ASeparator: string;
AKeepBackSeparator: Boolean = False): string;
{* 根據 Column的值﹐對DBGrid對應的Dataset的數據集(RecordSet)進行排序,
且重新定位Dataset *}
procedure SortRecordsetByDBGridColumn(const Column: TColumn);
//在DB類GetStrValues中使用﹐簡化TStringList加入實體類的各字段的值。 Added by cy 030416
procedure AddStringListValue(var AStringList: TStringList; const AString: string); overload;
procedure AddStringListValue(var AStringList: TStringList; const AInt: Integer); overload;
procedure AddStringListValue(var AStringList: TStringList; const ADouble: Double); overload; //Added by hong 030418
implementation
uses DB;
{* AStrNames在記錄了數據表欄位名稱的同時,也標記了該欄位的相關特性(是否為主鍵,
是否允許為空,欄位在Update時傳入空串是否會被set Null值).
記錄方法詳見DBClass的Property:FNames.
產生SQL語句時:
由(AStrNames.Values[AStrNames.Names[i]]取出表示第i個欄位的特性的字符串,
其中第1個字符表示該欄位是否為主鍵字段(1-是,其它的字符-不是),
第2個字符表示該欄位是否允許為Null值,(1-不允許,其它的字符-允許),
第3,4個字符預留,
第5個字符表示該欄位在 Update 時傳入空串是否會被set Null值,(1-不允許,其它的字符-允許).
eg: AStrNames.Values[AStrNames.Names[i]] 為'11001'
表示欄位AStrNames.Names[i]為主鍵,不能為Null值,在Update時如傳入空串,
不允許對該欄位進行Set Null的操作(這種情況一般出現在處理Fbuilder,FbDate欄位時)
*}
function TclsCommFunction.BuildSqlString(const AStrNames,
AStrValues: TStringList; AOperation: TEnumDatasetOperation): string;
var
lstrSql, lstrSQLValues, lTableName: string;
i, lMaxColID: integer;
lblnPrimaryKey: boolean;
begin
lblnPrimaryKey := False;
result := '';
if (AStrNames.Count = 0) then
raise exception.Create('The Names is null');
if (AStrValues.Count = 0) then
raise exception.Create('The Values is null');
if (AStrNames.Count <> AStrValues.Count) then
raise exception.Create('The Values or the names is error');
if (AStrValues.Strings[0] = '') then
raise exception.Create('The Table Name is null');
lMaxColID := AStrNames.Count - 1;
lTableName := AStrValues.Strings[0];
//---------------------動態生成SQL語句 -----------------------
try
lstrSql := '';
lstrSqlvalues := '';
case AOperation of
doQuery:
begin
lstrSql := 'Select * from ' + lTableName + ' where 1=1 '; //top 1
for i := 1 to lMaxColID do
begin
if AStrValues.strings[i] <> '' then
lstrSql := lstrsql + ' and ' + AStrNames.Strings[i] + '=' + AStrValues.Strings[i]
else
if AStrNames.Values[AStrNames.Names[i]][2] = '1' then //判斷是否允許為Null值
raise exception.Create('Null values:[Field:' + AStrNames.Names[i] + ']');
end;
end;
doExactQuery:
begin
lstrSql := 'Select * from ' + lTableName + ' where 1=1 '; //top 1
for i := 1 to lMaxColID do
begin
if AStrNames.Values[AStrNames.Names[i]][1] = '1' then //判斷是否為主鍵
begin
if (AStrValues.Strings[i] = '') then
raise exception.Create('No primary key values:[Field:' + AStrNames.Names[i] + ']');
lblnPrimaryKey := True;
lstrSql := lstrSQL + ' and ' + AStrNames.Names[i] + '=' + AStrValues.Strings[i];
end;
end;
if not lblnPrimaryKey then
raise exception.Create('No primary key fields:' + lTableName);
end;
doAdd:
begin
lstrSql := 'insert into ' + lTableName + ' ( ';
lstrsqlvalues := ' values ( ';
for i := 1 to lMaxColID do
begin
if (AStrNames.Values[AStrNames.Names[i]][1] = '1') then // 判斷是否為主鍵
begin
if (AStrValues.Strings[i] = '') then
raise exception.Create('No primary key values:[Field:' + AStrNames.Names[i] + ']');
lblnPrimaryKey := True;
end;
if (AStrValues.Strings[i] <> '') then
begin
lstrSql := lstrsql + '' + AStrNames.Names[i] + ',';
lstrSqlvalues := lstrsqlvalues + AStrValues.Strings[i] + ' ,';
end
else
if AStrNames.Values[AStrNames.Names[i]][2] = '1' then // 判斷是否允許為Null值
raise exception.Create('Null values:[Field:' + AStrNames.Names[i] + ']');
end;
if not lblnPrimaryKey then
raise exception.Create('No primary key fields:' + lTableName);
lstrsql := copy(lstrsql, 0, length(lstrsql) - 1) + ' ) ';
lstrsqlvalues := copy(lstrsqlvalues, 0, length(lstrsqlvalues) - 1) + ' ) ';
lstrsql := lstrsql + lstrsqlvalues;
end;
doEdit:
begin
lstrSql := 'Update ' + lTableName + ' set ';
lstrsqlvalues := ' where 1=1 ';
for i := 1 to lMaxColID do
begin
if AStrNames.Values[AStrNames.Names[i]][1] = '1' then //判斷是否為主鍵
begin
if (AStrValues.Strings[i] = '') then
raise exception.Create('No primary key values:[Field:' + AStrNames.Names[i] + ']');
lstrSqlvalues := lstrsqlvalues + ' and ' + AStrNames.Names[i] + '=' +
AStrValues.strings[i];
lblnPrimaryKey := True;
end
else
if AStrValues.Strings[i] <> '' then
lstrSql := lstrsql + ' ' +
AStrNames.Names[i] + '=' + AStrValues.strings[i] + ','
else
begin
if AStrNames.Values[AStrNames.Names[i]][2] = '1' then //判斷是否允許為Null值
raise exception.Create('Null values:[Field:' + AStrNames.Names[i] + ']');
if AStrNames.Values[AStrNames.Names[i]][5] <> '1' then //cgy 2002/3/7 add
lstrSql := lstrsql + ' ' + AStrNames.Names[i] + '=null,';
end;
end;
if not lblnPrimaryKey then
raise exception.Create('No primary key fields:' + lTableName)
else
begin
lstrsql := copy(lstrsql, 0, length(lstrsql) - 1);
lstrsql := lstrsql + lstrsqlvalues;
end;
end;
doDelete:
begin
lstrSql := 'Delete from ' + lTableName + ' where 1=1 ';
for i := 1 to lMaxColID do
begin
if (AStrValues.Strings[i] <> '') then
lstrSql := lstrsql + ' and ' + AStrNames.Names[i] + '=' +
AStrValues.Strings[i];
end;
end;
end;
Result := lstrsql;
except
raise;
end;
end;
{*
function: CheckISInt(Sender: TObject;const Key: Char;const Alength:integer):boolean;
Description: 判斷編輯框輸入一個字符Key后﹐編輯框中的數據還是不是一個合法的整形數
Return Value: Boolean值﹐True--是合法的整形數,False--不是合法的整形數
Parameters:
Sender﹐以TObject的形式傳入一個編輯框元件(TLabeledEdit﹐TMaskEdit或TEdit﹐都是TCustomEdit子類)
Key﹐預計加入編輯框元件的TEXT中的字符
Alength﹐編輯框中的整數允許的長度
*}
function CheckISInt(Sender: TObject; const Key: Char; const Alength: integer): boolean;
begin
result := true;
if (key = #13) or (key = #8) or (key = #9) then exit;
if (length((sender as TCustomEdit).Text) < Alength) then
begin
if (Key in ['0'..'9']) then exit;
end
else if ((sender as TCustomEdit).SelText <> '') and (Key in ['0'..'9']) then exit;
result := False;
end;
{*
function: CheckISFloat(Sender:TObject;const Key:Char;const AintLen,AdecLen:integer):boolean;
Description: 判斷編輯框輸入一個字符Key后﹐編輯框中的數據還是不是一個合法的浮點數
Return Value: Boolean值﹐True--是合法的整形數,False--不是合法的整形數
Parameters:
Sender﹐以TObject的形式傳入一個編輯框元件(TLabeledEdit﹐TMaskEdit或TEdit﹐都是TCustomEdit子類)
Key﹐預計加入編輯框元件的TEXT中的字符
AintLen﹐編輯框中的浮點數整數部分允許的長度
AdecLen﹐編輯框中的浮點數小數部分允許的長度﹐可以為0﹐則此時編輯框中只能輸入整數部分
*}
function CheckISFloat(Sender: TObject; const Key: Char; const AintLen, AdecLen: integer): boolean;
var
lDotpos, lselBegin, llen: integer;
begin
result := true;
if (key = #13) or (key = #8) or (key = #9) then exit;
if not (key in ['0'..'9', '.']) then
begin
result := False;
exit;
end;
lDotpos := Pos('.', (sender as TCustomEdit).Text); //the position of '.'
lselBegin := (sender as TCustomEdit).SelStart; //the cusor position
llen := length((sender as TCustomEdit).Text); //the length of text
if key = '.' then //key in '.'
begin
// if not '.' and the num of number char after cursor <=decimal num,can accept
// if has '.' but the '.' is selected ,can accept
if ((lDotPos < 1) and (llen - lselBegin <= AdecLen)) or
((lDotPos >= 1) and (Pos('.', (sender as TCustomEdit).SelText) > 0)) then exit;
end
else // key in number char '0'..'9'
begin
{* if some chars are selected,if '.' is not selected then can accept
else
if after accept the number char,
the length of the text is not bigger than the num of integer part *}
if (sender as TCustomEdit).SelText <> '' then
begin
if Pos('.', (sender as TCustomEdit).SelText) < 1 then exit
else if llen - (sender as TCustomEdit).SelLength + 1 <= AintLen then exit;
end;
if lDotpos < 1 then // when not '.'
begin
if AintLen > llen then exit; //if the length of text smaller than the num of integer part,accept
end
else
{* after accept the number char, not beyond the the num of integer part
and the num of decimal part limited,can accept *}
if ((lselBegin < lDotpos) and (lDotpos <= AintLen)) or
((lselBegin >= lDotpos) and (llen - lDotpos < AdecLen)) then exit;
end;
result := False;
end;
{*
procedure: FillStringsByDB(ADataSet:TDtSet;AstrSql: String;
AstrListID,AstrListDesc: TStrings; AIfFillChar:boolean=true;AFillChar:String='*');
Description: 傳入ADataSet﹐把ADataSet中的數據填入AstrListID,AstrListDesc兩個TStrings中﹐
同時根據AIfFillChar與AFillChar在TStrings的第一項插入指定字符
Parameters:
ADataSet, 傳入的資據集
AstrListID﹐將被填充的TStrings(可以是ListBox,ComboBox的Items或Memo的Lines),
將把用AstrSql取得的數據集的第一個欄位的值填入
AstrListDesc﹐將被填充的TStrings﹐將把數據集ADataSet的第二個欄位的值填入﹐
可以為nil﹐則此時不會對AstrListDesc進行數據填入操作
AIfFillChar﹐是否在AstrListID﹐AstrListDesc的第一項寫入
除ADataSet中的數據之外的數據。True--是(默認),False--否。
AFillChar﹐在AIfFillChar為True時﹐在在AstrListID﹐AstrListDesc的第一項寫入的字串
*}
procedure FillStringsByDB(ADataSet: TClientDtSet;
AstrListID, AstrListDesc: TStrings; AIfFillChar: boolean = true; AFillChar: string = '*'); overload;
begin
AstrListID.Clear;
if AstrListDesc <> nil then AstrListDesc.Clear;
if not ADataSet.Active then
ADataSet.Open
else
ADataSet.First;
if AIfFillChar then
begin
AstrListID.Add(AFillChar);
if AstrListDesc <> nil then AstrListDesc.Add(AFillChar);
end;
while not ADataSet.Eof do
begin
AstrListID.Add(trim(ADataSet.Fields[0].AsString));
if AstrListDesc <> nil then
AstrListDesc.Add(trim(ADataSet.Fields[1].AsString));
ADataSet.Next;
end;
end;
{*
procedure: FillStringsByDB(ADataSet:TDtSet;AstrSql: String;
AstrListIDDesc: TStrings; AIfFillChar:boolean=true;AFillChar:String='*');
Description: 傳入ADataSet﹐把ADataSet中的數據填入AstrListIDDesc中﹐
同時根據AIfFillChar與AFillChar在TStrings的第一項插入指定字符
Parameters:
ADataSet﹐傳入的數據集
AstrListIDDesc﹐將被填充的TStrings(可以是ListBox,ComboBox的Items或Memo的Lines),
將把數據集ADataSet的第一個欄位的值(如果傳入數據集有兩個欄位﹐則接上第二個欄位的值)填入
AIfFillChar﹐是否在AstrListID﹐AstrListDesc的第一項寫入
除ADataSet中的數據之外的數據。True--是(默認),False--否。
AFillChar﹐在AIfFillChar為True時﹐在在AstrListIDDesc的第一項寫入的字串
*}
procedure FillStringsByDB(ADataSet: TClientDtSet;
AstrListIDDesc: TStrings; AIfFillChar: boolean = true; AFillChar: string = '*'); overload;
begin
AstrListIDDesc.Clear;
if not ADataSet.Active then
ADataSet.Open
else
ADataSet.First;
if AIfFillChar then AstrListIDDesc.Add(AFillChar);
while not ADataSet.Eof do
begin
if ADataSet.FieldCount > 1 then
AstrListIDDesc.Add(trim(ADataSet.Fields[0].AsString) + ' ('
+ trim(ADataSet.Fields[1].AsString) + ')')
else AstrListIDDesc.Add(trim(ADataSet.Fields[0].AsString));
ADataSet.Next;
end;
end;
{*
procedure: AddGridColumn(AFieldNames, ADisplayNames, AIsShowList: TstringList;
ADtSet: TDtSet;ADbGrid: TDbGrid);
Description: 依照AFieldNames, ADisplayNames, AIsShowList,ADtSet的值﹐
對指定之ADbGrid的Columns屬性進行設定
Parameters:
AFieldNames﹐記錄了數據表欄位名稱的TstringList﹐
AFieldNames可以為nil﹐此時DBGRID的Column取ADtSet的欄位名
ADisplayNames﹐記錄了DBGRID的Columns每一列的標題的TstringList﹐
DBGRID的Columns加入的Column數目以ADisplayNames的Count為准
AIsShowList﹐記錄了DBGRID的Columns每一列是否要顯示的TstringList,
1--不顯示﹐其它字符或無對應的項時不顯示﹐
AIsShowList可以為nil﹐此時DBGRID的Columns中所有的列都顯示
ADtSet﹐ADbGrid.DataSource.Dataset的可能值
ADbGrid﹐要進行處理的DBGRID
*}
procedure FillGridColumn(AFieldNames, ADisplayNames, AIsShowList: Tstrings;
ADtSet: TClientDtSet; ADbGrid: TDbGrid);
var
lDisCount, lShowListCount, lFieldCount, lDtsetFieldCount, i: integer;
begin
//ADisplayNames的數目(以該數目為DBGRID顯示欄數目)
lDisCount := ADisplayNames.Count;
if AIsShowList = nil then lShowListCount := 0
else lShowListCount := AIsShowList.Count; // 儲存 AShowList的數目
if AFieldNames = nil then lFieldCount := 0
else lFieldCount := AFieldNames.Count; // 儲存 AFieldNames的數目
if ADtSet = nil then lDtsetFieldCount := 0
else lDtsetFieldCount := ADtSet.FieldCount;
//
ADbGrid.Columns.Clear;
for i := 0 to lDisCount - 1 do
begin
//如AShowList中有值且為'1'時﹐進行下一個
if lShowListCount - 1 >= i then
if AIsShowList.strings[i] = '1' then Continue;
//
with ADbGrid.Columns.Add do
begin
//如設定的AFieldNames有值
if (lFieldCount - 1 >= i) and (AFieldNames.Strings[i] <> '') then
FieldName := AFieldNames.Strings[i]
else
if lDtsetFieldCount - 1 >= i then
FieldName := ADtSet.FieldDefs.Items[i].Name
else FieldName := '';
//
Title.Caption := ADisplayNames.Strings[i];
end;
end;
end;
{*
procedure: MoveWholeStrings(ASource, ADest: TStrings;ACanRepeat:Boolean=true);
Description: 將ASource中的所有的數據項移到ADest中
Parameters:
ASource﹐該TStrings中的所有數據項﹐將被移走
ADest﹐最后是ASource與ADest的所有數據項的集合
ACanRepeat﹐標明ASource與ADest的數據項有重復時是否同時保留﹐
True--同時保留(默認)﹐False--只取一項
*}
procedure MoveWholeStrings(ASource, ADest: TStrings; ACanRepeat: Boolean = true);
var
i: integer;
begin
if ACanRepeat then
ADest.AddStrings(ASource)
else
for i := 0 to ASource.Count - 1 do
if ADest.IndexOf(ASource.Strings[i]) = -1 then
ADest.Add(ASource.Strings[i]);
ASource.Clear;
end;
{*
procedure: MoveSelectedListBoxItem(ASource, ADest: TListBox;ACanRepeat:Boolean=true);
Description: 將ASource中所有選中的數據項移到ADest中
Parameters:
ASource﹐該TListBox中的所有選中的數據項﹐將被移走
ADest﹐最后是ASource的選中的數據項與ADest的所有數據項的集合
ACanRepeat﹐標明ASource的選中的數據項與ADest的數據項有重復時是否同時保留﹐
True--同時保留(默認)﹐False--只取一項
*}
procedure MoveSelectedListBoxItem(ASource, ADest: TListBox; ACanRepeat: Boolean = true);
var
i: integer;
begin
for i := 0 to ASource.Count - 1 do
if ASource.Selected[i] then
if ACanRepeat or (ADest.Items.IndexOf(ASource.Items[i]) = -1) then
ADest.Items.Add(ASource.Items.Strings[i]);
ASource.DeleteSelected;
end;
function connectStrings(Asel: TStrings; ASeparatorChar: string): string;
var
lstrtemp: string;
i: integer;
begin
lstrtemp := '';
if Asel.Count > 0 then
begin
for i := 0 to Asel.Count - 1 do
lstrtemp := lstrtemp + ASeparatorChar + Asel.Strings[i] + ASeparatorChar + ',';
if lstrtemp[length(lstrtemp)] = ',' then
Delete(lstrtemp, length(lstrtemp), length(lstrtemp));
end;
result := lstrtemp;
end;
{*
function: GetBackStringbySeparator(Const Astr,ASeparator: string;
AKeepBackSeparator:Boolean=False):string;
Description: 取得字串Astr中ASeparator以后的一部分字串
Return Value: 字串﹐返回處理后的字串
Parameters:
Astr:一個字串
ASeparator: 作為界定符的字串
AKeepBackSeparator: 反回的字串中是否包含ASeparator﹐默認為False﹐不包含
*}
function GetBackStringbySeparator(const Astr, ASeparator: string;
AKeepBackSeparator: Boolean = False): string;
var
lpos: integer;
lstr: string;
begin
lpos := pos(ASeparator, Astr);
if lpos > 0 then
begin
if AKeepBackSeparator then lstr := ASeparator
else lstr := '';
result := lstr + trim(Copy(Astr, lpos + length(ASeparator), length(Astr)))
end
else result := '';
end;
{*
function: GetBackStringbySeparator(Const Astr,ASeparator: string;
AKeepBackSeparator:Boolean=False):string;
Description: 取得字串Astr中ASeparator以前的一部分字串
Return Value: 字串﹐返回處理后的字串
Parameters:
Astr:一個字串
ASeparator: 作為界定符的字串
AKeepBackSeparator: 反回的字串中是否包含ASeparator﹐默認為False﹐不包含
*}
function GetForeStringbySeparator(const Astr, ASeparator: string;
AKeepBackSeparator: Boolean = False): string;
var
lpos: integer;
lstr: string;
begin
lpos := pos(ASeparator, Astr);
if lpos > 0 then
begin
if AKeepBackSeparator then lstr := ASeparator
else lstr := '';
result := trim(Copy(Astr, 1, lpos - 1)) + lstr;
end
else result := trim(Astr);
end;
{*
procedure: SortRecordsetByDBGridColumn(const Column: TColumn);
Description: 根據 Column的值﹐對DBGrid對應的Dataset的數據集(RecordSet)進行排序
(根據其中一個欄位進行排序),且重新定位Dataset
Parameters:
Column: 要進行排序的欄位所對應DBGrid中的一個欄位
*}
procedure SortRecordsetByDBGridColumn(const Column: TColumn);
var
lstr, lstrSort, lstrIndexFieldName: string;
lSavePlace: TBookmark;
begin
if Column.Grid.DataSource = nil then exit;
if Column.Grid.DataSource.DataSet = nil then exit;
if not Column.Grid.DataSource.DataSet.Active then exit;
with (Column.Grid.DataSource.DataSet as TClientDtSet) do
begin
lSavePlace := GetBookmark;
try
if IndexFieldCount = 0 then
begin
lstrSort := '';
lstrIndexFieldName := '';
end
else
begin
lstr := GetForeStringbySeparator(IndexFieldNames, ',');
lstrIndexFieldName := GetForeStringbySeparator(lstr, ' ');
lstrSort := GetBackStringbySeparator(lstr, ' ');
end;
if lstrIndexFieldName = Column.FieldName then
begin
if lstrSort = 'ASC' then lstrSort := 'DESC' else lstrSort := 'ASC';
end
else
begin
lstrSort := 'ASC';
lstrIndexFieldName := Column.FieldName;
end;
IndexFieldNames := lstrIndexFieldName + ' ' + lstrSort;
GotoBookmark(lSavePlace);
finally
FreeBookmark(lSavePlace);
end;
end;
end;
{*
如果實體類字段值類型為String﹐則調用第一個AddStringListValue版本﹔
如果實體類字段值類型為Integer﹐則調用第二個AddStringListValue版本﹔
如果實體類字段值類型為Double﹐則調用第二個AddStringListValue版本﹔
*}
procedure AddStringListValue(var AStringList: TStringList; const AString: string); overload;
begin
if Astring <> '' then AStringList.Add(QuotedStr(Astring))
else AStringList.Add('');
end;
procedure AddStringListValue(var AStringList: TStringList; const Aint: Integer); overload;
begin
if AInt > -1 then AStringList.Add(IntToStr(AInt))
else AStringList.Add('');
end;
procedure AddStringListValue(var AStringList: TStringList; const ADouble: Double); overload;
begin
if ADouble > -1 then AStringList.Add(FloatToStr(ADouble))
else AStringList.Add('');
end;
end.
|
unit u_xpl_body;
{==============================================================================
UnitName = uxplmsgbody
UnitDesc = xPL Message Body management object and function
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
Rawdata passed are not transformed to lower case, Body lowers body item keys
but not body item values.
0.98 : Added method to clean empty body elements ('value=')
1.02 : Added auto cut / reassemble of long body variable into multiple lines
1.03 : Added AddKeyValuePairs
1.04 : Class renamed TxPLBody
1.5 : Added fControlInput property to override read/write controls needed for OPC
}
{$i xpl.inc}
interface
uses Classes
, u_xpl_common
;
type // TxPLBody ==============================================================
TxPLBody = class(TComponent, IxPLCommon, IxPLRaw)
private
fControlInput : boolean;
fKeys,
fValues,
fStrings : TStringList;
procedure AddKeyValuePair(const aKey, aValue : string); // This one moved to private because of creation of AddKeyValuePairs
function AppendItem(const aName : string) : integer;
function GetCount: integer; inline;
function IsValidKey(const aKey : string) : boolean;
function IsValidValue(const aValue : string) : boolean;
function Get_RawxPL : string;
function Get_Strings: TStrings;
procedure Set_Keys(const AValue: TStringList);
procedure Set_RawxPL(const AValue: string);
procedure Set_Strings(const AValue: TStrings);
procedure Set_Values(const AValue: TStringList);
public
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
procedure Assign(Source : TPersistent); override;
function IsValid : boolean;
procedure ResetValues;
procedure CleanEmptyValues;
procedure AddKeyValuePairs(const aKeys, aValues : TStringList); overload;
procedure AddKeyValuePairs(const aKeys, aValues : Array of string); overload;
procedure AddKeyValue(const aKeyValuePair : string);
procedure Append(const aBody : TxPLBody);
procedure InsertKeyValuePair(const aIndex : integer; const aKey, aValue : string);
procedure DeleteItem(const aIndex : integer);
function GetValueByKey(const aKeyValue: string; const aDefVal : string = '') : string;
procedure SetValueByKey(const aKeyValue, aDefVal : string);
property ItemCount : integer read GetCount;
property ControlInput : boolean read fControlInput write fControlInput;
published
property Keys : TStringList read fKeys write Set_Keys;
property Values : TStringList read fValues write Set_Values;
property RawxPL : string read Get_RawxPL write Set_RawxPL stored false;
property Strings : TStrings read Get_Strings write Set_Strings stored false;
end;
implementation // =============================================================
uses sysutils
, strutils
;
// ============================================================================
const K_MSG_BODY_FORMAT = '{'#10'%s}'#10;
K_BODY_ELMT_DELIMITER = '=';
// TxPLBody ===================================================================
constructor TxPLBody.Create(aOwner : TComponent);
begin
inherited;
include(fComponentStyle,csSubComponent);
fControlInput := true;
fKeys := TStringList.Create;
fValues := TStringList.Create;
fStrings := TStringList.Create;
end;
destructor TxPLBody.destroy;
begin
fStrings.Free;
fValues.Free;
fKeys.Free;
inherited;
end;
function TxPLBody.GetCount: integer;
begin
result := fKeys.Count;
end;
function TxPLBody.IsValidKey(const aKey: string): boolean;
begin
result := IsValidxPLIdent(aKey) and (length(aKey)<=MAX_KEY_LEN);
end;
function TxPLBody.IsValidValue(const aValue: string): boolean;
begin
result := length(aValue) <= MAX_VALUE_LEN;
end;
procedure TxPLBody.ResetValues;
begin
Keys.Clear;
Values.Clear;
end;
procedure TxPLBody.DeleteItem(const aIndex: integer);
begin
Keys.Delete(aIndex);
Values.Delete(aIndex);
end;
function TxPLBody.AppendItem(const aName : string) : integer;
begin
result := Keys.Add(aName);
Values.Add('');
end;
procedure TxPLBody.Set_Values(const AValue: TStringList);
begin
Values.Assign(aValue);
end;
procedure TxPLBody.Set_Keys(const AValue: TStringList);
begin
Keys.Assign(aValue);
end;
procedure TxPLBody.Assign(Source : TPersistent);
begin
if Source is TxPLBody then begin
Set_Keys(TxPLBody(Source).Keys);
Set_Values(TxPLBody(Source).Values);
fControlInput := TxPLBody(Source).ControlInput;
end else inherited;
end;
function TxPLBody.IsValid: boolean;
var s : string;
begin
if not fControlInput then exit(true);
result := true;
for s in Keys do result := result and IsValidKey(s);
for s in Values do result := result and IsValidValue(s);
end;
procedure TxPLBody.CleanEmptyValues;
var i : integer;
begin
i := 0;
while i<ItemCount do
if Values[i]='' then DeleteItem(i) else inc(i);
end;
function TxPLBody.Get_RawxPL: string;
begin
result := Format(K_MSG_BODY_FORMAT,[AnsiReplaceStr(Strings.Text,#13,'')]);
end;
function TxPLBody.Get_Strings: TStrings;
var i : integer;
begin
fStrings.Assign(fKeys);
if fControlInput then
for i:= 0 to Pred(ItemCount) do
fStrings[i] := fStrings[i] + '=' + Values[i];
result := fStrings;
end;
procedure TxPLBody.Set_Strings(const AValue: TStrings);
begin
RawxPL := AnsiReplaceStr(aValue.Text,#13,#10);
end;
function TxPLBody.GetValueByKey(const aKeyValue: string; const aDefVal : string = '') : string;
var i : integer;
begin
i := Keys.IndexOf(aKeyValue);
if i>=0 then result := Values[i]
else result := aDefVal;
end;
procedure TxPLBody.SetValueByKey(const aKeyValue, aDefVal : string);
var i : integer;
begin
i := Keys.IndexOf(aKeyValue);
if i>=0 then Values[i] := aDefVal // If the key is found, the value is set
else AddKeyValuePair(aKeyValue,aDefVal); // else key added and value set
end;
procedure TxPLBody.AddKeyValuePairs(const aKeys, aValues : TStringList);
var i : integer;
begin
for i := 0 to Pred(aKeys.Count) do AddKeyValuePair(aKeys[i],aValues[i]);
end;
procedure TxPLBody.AddKeyValuePairs(const aKeys, aValues: array of string);
var i : integer;
begin
for i := Low(aKeys) to High(aKeys) do AddKeyValuePair(aKeys[i],aValues[i]);
end;
procedure TxPLBody.InsertKeyValuePair(const aIndex : integer; const aKey, aValue : string);
begin
Keys.Insert(aIndex, aKey);
Values.Insert(aIndex, aValue);
end;
procedure TxPLBody.AddKeyValuePair(const aKey, aValue: string);
begin
Values[AppendItem(aKey)] := aValue;
end;
procedure TxPLBody.AddKeyValue(const aKeyValuePair: string);
var i : integer;
begin
i := AnsiPos(K_BODY_ELMT_DELIMITER,aKeyValuePair);
if i <> 0 then AddKeyValuePair( AnsiLowerCase(Copy(aKeyValuePair,0,i-1)) ,
Copy(aKeyValuePair,i+1,length(aKeyValuePair)-i + 1));
end;
procedure TxPLBody.Append(const aBody: TxPLBody);
var i : integer;
begin
for i:= 0 to pred(aBody.ItemCount) do AddKeyValuePair(aBody.Keys[i],aBody.Values[i]);
end;
procedure TxPLBody.Set_RawxPL(const AValue: string);
var sl : tstringlist;
ch : string;
begin
ResetValues;
sl := TStringList.Create;
sl.Delimiter:=#10; // use LF as delimiter
sl.StrictDelimiter := true;
sl.DelimitedText:=AnsiReplaceStr(aValue,#13,''); // get rid of CR
for ch in sl do
if length(ch)>0 then
if fControlInput then AddKeyValue(ch)
else begin
Keys.Append(ch);
Values.Append('');
end;
sl.free;
end;
// ============================================================================
initialization
Classes.RegisterClass(TxPLBody);
end.
|
unit fODText;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fODBase, StdCtrls, ORCtrls, ComCtrls, ExtCtrls, ORFn, uConst, ORDtTm,
VA508AccessibilityManager;
type
TfrmODText = class(TfrmODBase)
memText: TMemo;
lblText: TLabel;
txtStart: TORDateBox;
txtStop: TORDateBox;
lblStart: TLabel;
lblStop: TLabel;
VA508CompMemOrder: TVA508ComponentAccessibility;
lblOrderSig: TLabel;
procedure FormCreate(Sender: TObject);
procedure ControlChange(Sender: TObject);
procedure cmdAcceptClick(Sender: TObject);
procedure VA508CompMemOrderStateQuery(Sender: TObject; var Text: string);
public
procedure InitDialog; override;
procedure SetupDialog(OrderAction: Integer; const ID: string); override;
procedure Validate(var AnErrMsg: string); override;
end;
var
frmODText: TfrmODText;
implementation
{$R *.DFM}
uses rCore, VAUtils;
const
TX_NO_TEXT = 'Some text must be entered.';
TX_STARTDT = 'Unable to interpret start date.';
TX_STOPDT = 'Unable to interpret stop date.';
TX_GREATER = 'Stop date must be greater than start date.';
{ TfrmODBase common methods }
procedure TfrmODText.FormCreate(Sender: TObject);
begin
inherited;
FillerID := 'OR'; // does 'on Display' order check **KCM**
StatusText('Loading Dialog Definition');
Responses.Dialog := 'OR GXTEXT WORD PROCESSING ORDER'; // loads formatting info
//StatusText('Loading Default Values'); // there are no defaults for text only
//CtrlInits.LoadDefaults(ODForText);
InitDialog;
StatusText('');
end;
procedure TfrmODText.InitDialog;
begin
inherited; // inherited clears dialog controls and responses
ActiveControl := memText; //SetFocusedControl(memText);
end;
procedure TfrmODText.SetupDialog(OrderAction: Integer; const ID: string);
begin
inherited;
if OrderAction in [ORDER_COPY, ORDER_EDIT, ORDER_QUICK] then with Responses do
begin
SetControl(memText, 'COMMENT', 1);
SetControl(txtStart, 'START', 1);
SetControl(txtStop, 'STOP', 1);
end
else txtStart.Text := 'NOW';
end;
procedure TfrmODText.VA508CompMemOrderStateQuery(Sender: TObject;
var Text: string);
begin
inherited;
Text := memOrder.Text;
end;
procedure TfrmODText.Validate(var AnErrMsg: string);
const
SPACE_CHAR = 32;
var
ContainsPrintable: Boolean;
i: Integer;
StartTime, StopTime: TFMDateTime;
procedure SetError(const x: string);
begin
if Length(AnErrMsg) > 0 then AnErrMsg := AnErrMsg + CRLF;
AnErrMsg := AnErrMsg + x;
end;
begin
inherited;
ContainsPrintable := False;
for i := 1 to Length(memText.Text) do if Ord(memText.Text[i]) > SPACE_CHAR then
begin
ContainsPrintable := True;
break;
end;
if not ContainsPrintable then SetError(TX_NO_TEXT);
with txtStart do if Length(Text) > 0
then StartTime := StrToFMDateTime(Text)
else StartTime := 0;
with txtStop do if Length(Text) > 0
then StopTime := StrToFMDateTime(Text)
else StopTime := 0;
if StartTime = -1 then SetError(TX_STARTDT);
if StopTime = -1 then SetError(TX_STARTDT);
if (StopTime > 0) and (StopTime < StartTime) then SetError(TX_GREATER);
//the following is commented out because should be using relative times
//if AnErrMsg = '' then
//begin
// Responses.Update('START', 1, FloatToStr(StartTime), txtStart.Text);
// Responses.Update('STOP', 1, FloatToStr(StopTime), txtStop.Text);
//end;
end;
procedure TfrmODText.cmdAcceptClick(Sender: TObject);
var
ReleasePending: boolean;
Msg: TMsg;
begin
inherited;
ReleasePending := PeekMessage(Msg, Handle, CM_RELEASE, CM_RELEASE, PM_REMOVE);
Application.ProcessMessages; //CQ 14670
memText.Lines.Text := Trim(memText.Lines.Text); //CQ 14670
if ReleasePending then
Release;
end;
procedure TfrmODText.ControlChange(Sender: TObject);
begin
inherited;
if Changing then Exit;
with memText do if GetTextLen > 0 then Responses.Update('COMMENT', 1, TX_WPTYPE, Text);
with txtStart do if Length(Text) > 0 then Responses.Update('START', 1, Text, Text);
with txtStop do if Length(Text) > 0 then Responses.Update('STOP', 1, Text, Text);
memOrder.Text := Responses.OrderText;
end;
end.
|
program lowerCaseAscii(input, output, stdErr);
var
alphabet: set of char;
begin
// as per ISO 7185, 'a'..'z' do not necessarily have to be contiguous
alphabet := [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
];
end.
|
program ArithmeticSequence;
{$mode objfpc}{$H+}
uses {$IFDEF UNIX} {$IFDEF UseCThreads}
cthreads, {$ENDIF} {$ENDIF}
Classes,
SysUtils,
CustApp,
arithmeticsequences { you can add units after this };
type
{ TArithmeticSequence }
TArithmeticSequence = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TArithmeticSequence }
procedure TArithmeticSequence.DoRun;
var
ErrorMsg: string;
A, D, N, Index: integer;
Terms: array of integer;
begin
// quick check parameters
ErrorMsg := CheckOptions('hadn', 'help start difference count');
if ErrorMsg <> '' then
begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
// parse parameters
if HasOption('h', 'help') then
begin
WriteHelp;
Terminate;
Exit;
end;
if HasOption('a', 'start') then
begin
A := StrToInt(GetOptionValue('a', 'start'));
end
else
begin
A := 1;
end;
if HasOption('d', 'difference') then
begin
D := StrToInt(GetOptionValue('d', 'difference'));
end
else
begin
D := 1;
end;
if HasOption('n', 'count') then
begin
N := StrToInt(GetOptionValue('n', 'count'));
end
else
begin
n := 10;
end;
Terms := GetTerms(A, D, N);
for Index := 0 to N - 1 do
begin
Write(Terms[Index]);
if Index <> N - 1 then
begin
Write(', ');
end;
end;
WriteLn();
// stop program loop
Terminate;
end;
constructor TArithmeticSequence.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException := True;
end;
destructor TArithmeticSequence.Destroy;
begin
inherited Destroy;
end;
procedure TArithmeticSequence.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ', ExeName, ' -h');
end;
var
Application: TArithmeticSequence;
begin
Application := TArithmeticSequence.Create(nil);
Application.Title := 'Arithmetic Sequence';
Application.Run;
Application.Free;
end.
|
unit MD.Controller.Client;
interface
uses
Horse,
MD.Model.Classes,
MD.DAO.Client,
REST.Json,
System.JSON,
System.SysUtils;
procedure Insert(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure List(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Find(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Delete(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Update(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Registry;
implementation
procedure Registry;
begin
THorse.Get('client', List);
THorse.Get('client/:id', Find);
THorse.Delete('client/:id', Delete);
THorse.PUT('client/:id', Update);
THorse.Post('client', Insert);
end;
procedure Delete(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
id : Integer;
dao: TDAOClient;
begin
id := Req.Params.Items['id'].ToInteger;
dao:= TDAOClient.create;
try
dao.delete(id);
Res.Status(204);
finally
dao.Free;
end;
end;
procedure Find(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
id : Integer;
dao: TDAOClient;
client: TClient;
begin
id := Req.Params.Items['id'].ToInteger;
dao:= TDAOClient.create;
try
client := dao.find(id);
try
if not Assigned(client) then
begin
Res.Status(404);
raise Exception.CreateFmt('Client %s not found.', [id.ToString]);
end;
Res.Send(TJson.ObjectToJsonString(client))
.ContentType('application/json');
finally
client.Free;
end;
finally
dao.Free;
end;
end;
procedure List(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
jsonArray: TJSONArray;
i: Integer;
query: string;
begin
jsonArray := TJSONArray.Create;
try
for i := 0 to Pred(Clients.Count) do
jsonArray.AddElement(TJson.ObjectToJsonObject(Clients[i]));
Res.Send(query).Send(jsonArray.ToString)
.ContentType('application/json');
finally
jsonArray.Free;
end;
end;
procedure Insert(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
client : TClient;
dao : TDAOClient;
begin
client := TJson.JsonToObject<TClient>(Req.Body);
try
dao := TDAOClient.create;
try
dao.insert(client);
Res.Send(TJson.ObjectToJsonString(client))
.ContentType('application/json')
.Status(201);
THorseHackResponse(Res).GetWebResponse.SetCustomHeader(
'location', client.id.ToString
);
finally
dao.Free;
end;
finally
client.Free;
end;
end;
procedure Update(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
client : TClient;
dao : TDAOClient;
id : Integer;
begin
client := TJson.JsonToObject<TClient>(Req.Body);
try
id := Req.Params['id'].ToInteger;
client.id := id;
dao := TDAOClient.create;
try
dao.update(client);
Res.Send(TJson.ObjectToJsonString(client))
.ContentType('application/json')
.Status(202);
finally
dao.Free;
end;
finally
client.Free;
end;
end;
end.
|
unit UnitDM;
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.SQLite,
FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.FMXUI.Wait, Data.DB,
FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, FireDAC.Comp.DataSet, REST.Types, REST.Client,
REST.Authenticator.Basic, Data.Bind.Components, Data.Bind.ObjectScope,
System.JSON, System.NetEncoding;
type
Tdm = class(TDataModule)
conn: TFDConnection;
qry_config: TFDQuery;
RESTClient: TRESTClient;
RequestLogin: TRESTRequest;
HTTPBasicAuthenticator: THTTPBasicAuthenticator;
RequestListarComanda: TRESTRequest;
RequestListarProduto: TRESTRequest;
RequestListarCategoria: TRESTRequest;
RequestAdicionarProdutoComanda: TRESTRequest;
RequestListarProdutoComanda: TRESTRequest;
RequestExcluirProdutoComanda: TRESTRequest;
RequestEncerrarComanda: TRESTRequest;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function ValidaLogin(usuario: string; out erro: string): boolean;
function ListarComanda(out jsonArray: TJSONArray; out erro: string): boolean;
function ListarProduto(id_categoria: integer; termo_busca: string; pagina: integer;
out jsonArray: TJSONArray; out erro: string): boolean;
function ListarCategoria(out jsonArray: TJSONArray;
out erro: string): boolean;
function AdicionarProdutoComanda(id_comanda: string; id_produto,
qtd: integer; vl_total: double; out erro: string): boolean;
function ListarProdutoComanda(id_comanda: string;
out jsonArray: TJSONArray; out erro: string): boolean;
function ExcluirProdutoCOmanda(id_comanda: string; id_consumo: integer;
out erro: string): boolean;
function EncerrarComanda(id_comanda: string; out erro: string): boolean;
end;
var
dm: Tdm;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
function Tdm.ValidaLogin(usuario: string; out erro: string): boolean;
var
json : string;
jsonObj: TJsonObject;
begin
erro := '';
with RequestLogin do
begin
Params.Clear;
AddParameter('usuario', usuario, TRESTRequestParameterKind.pkGETorPOST);
Execute;
end;
if RequestLogin.Response.StatusCode <> 200 then
begin
Result := false;
erro := 'Erro ao validar login: ' + dm.RequestLogin.Response.StatusCode.ToString;
end
else
begin
json := RequestLogin.Response.JSONValue.ToString;
jsonObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(json), 0) as TJSONObject;
if jsonObj.GetValue('retorno').Value = 'OK' then
Result := true
else
begin
Result := false;
erro := jsonObj.GetValue('retorno').Value;
end;
jsonObj.DisposeOf;
end;
end;
function Tdm.ListarComanda(out jsonArray: TJSONArray; out erro: string): boolean;
var
json : string;
begin
erro := '';
try
with RequestListarComanda do
begin
Params.Clear;
Execute;
end;
except on ex:exception do
begin
Result := false;
erro := 'Erro ao listar comandas: ' + ex.Message;
exit;
end;
end;
if RequestListarComanda.Response.StatusCode <> 200 then
begin
Result := false;
erro := 'Erro ao listar comandas: ' + dm.RequestLogin.Response.StatusCode.ToString;
end
else
begin
json := RequestListarComanda.Response.JSONValue.ToString;
jsonArray := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(json), 0) as TJSONArray;
Result := true;
end;
end;
function Tdm.ListarProduto(id_categoria: integer; termo_busca: string; pagina: integer;
out jsonArray: TJSONArray; out erro: string): boolean;
var
json : string;
begin
erro := '';
try
with RequestListarProduto do
begin
Params.Clear;
AddParameter('id_categoria', id_categoria.ToString, TRESTRequestParameterKind.pkGETorPOST);
AddParameter('termo_busca', termo_busca, TRESTRequestParameterKind.pkGETorPOST);
AddParameter('pagina', pagina.ToString, TRESTRequestParameterKind.pkGETorPOST);
Execute;
end;
except on ex:exception do
begin
Result := false;
erro := 'Erro ao listar produto: ' + ex.Message;
exit;
end;
end;
if RequestListarProduto.Response.StatusCode <> 200 then
begin
Result := false;
erro := 'Erro ao listar produto: ' + RequestListarProduto.Response.StatusCode.ToString;
end
else
begin
json := RequestListarProduto.Response.JSONValue.ToString;
jsonArray := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(json), 0) as TJSONArray;
Result := true;
end;
end;
function Tdm.ListarCategoria(out jsonArray: TJSONArray; out erro: string): boolean;
var
json : string;
begin
erro := '';
try
with RequestListarCategoria do
begin
Params.Clear;
Execute;
end;
except on ex:exception do
begin
Result := false;
erro := 'Erro ao listar categorias: ' + ex.Message;
exit;
end;
end;
if RequestListarCategoria.Response.StatusCode <> 200 then
begin
Result := false;
erro := 'Erro ao listar categorias: ' + RequestListarCategoria.Response.StatusCode.ToString;
end
else
begin
json := RequestListarCategoria.Response.JSONValue.ToString;
jsonArray := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(json), 0) as TJSONArray;
Result := true;
end;
end;
function Tdm.AdicionarProdutoComanda(id_comanda: string; id_produto, qtd: integer; vl_total: double;
out erro: string): boolean;
var
json : string;
jsonObj: TJsonObject;
begin
erro := '';
with RequestAdicionarProdutoComanda do
begin
Params.Clear;
AddParameter('id_comanda', id_comanda, TRESTRequestParameterKind.pkGETorPOST);
AddParameter('id_produto', id_produto.ToString, TRESTRequestParameterKind.pkGETorPOST);
AddParameter('qtd', qtd.ToString, TRESTRequestParameterKind.pkGETorPOST);
AddParameter('vl_total', FormatFloat('0.00', vl_total).Replace(',', '').Replace('.', ''),
TRESTRequestParameterKind.pkGETorPOST);
Execute;
end;
if RequestAdicionarProdutoComanda.Response.StatusCode <> 200 then
begin
Result := false;
erro := 'Erro ao adicionar item: ' + RequestAdicionarProdutoComanda.Response.StatusCode.ToString;
end
else
begin
json := RequestAdicionarProdutoComanda.Response.JSONValue.ToString;
jsonObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(json), 0) as TJSONObject;
if jsonObj.GetValue('retorno').Value = 'OK' then
Result := true
else
begin
Result := false;
erro := jsonObj.GetValue('retorno').Value;
end;
jsonObj.DisposeOf;
end;
end;
function Tdm.ListarProdutoComanda(id_comanda: string;
out jsonArray: TJSONArray; out erro: string): boolean;
var
json : string;
jsonObj: TJsonObject;
begin
erro := '';
try
with RequestListarProdutoComanda do
begin
Params.Clear;
AddParameter('id_comanda', id_comanda, TRESTRequestParameterKind.pkGETorPOST);
Execute;
end;
except on ex:exception do
begin
Result := false;
erro := 'Erro ao listar produtos: ' + ex.Message;
exit;
end;
end;
if RequestListarProdutoComanda.Response.StatusCode <> 200 then
begin
Result := false;
erro := 'Erro ao listar produtos: ' + RequestListarProdutoComanda.Response.StatusCode.ToString;
end
else
begin
json := RequestListarProdutoComanda.Response.JSONValue.ToString;
jsonArray := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(json), 0) as TJSONArray;
Result := true;
end;
end;
function Tdm.ExcluirProdutoCOmanda(id_comanda: string; id_consumo: integer; out erro: string): boolean;
var
json : string;
jsonObj: TJsonObject;
begin
erro := '';
with RequestExcluirProdutoComanda do
begin
Params.Clear;
AddParameter('id_comanda', id_comanda, TRESTRequestParameterKind.pkGETorPOST);
AddParameter('id_consumo', id_consumo.ToString, TRESTRequestParameterKind.pkGETorPOST);
Execute;
end;
if RequestExcluirProdutoComanda.Response.StatusCode <> 200 then
begin
Result := false;
erro := 'Erro ao excluir item: ' + RequestExcluirProdutoComanda.Response.StatusCode.ToString;
end
else
begin
json := RequestExcluirProdutoComanda.Response.JSONValue.ToString;
jsonObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(json), 0) as TJSONObject;
if jsonObj.GetValue('retorno').Value = 'OK' then
Result := true
else
begin
Result := false;
erro := jsonObj.GetValue('retorno').Value;
end;
jsonObj.DisposeOf;
end;
end;
function Tdm.EncerrarComanda(id_comanda: string; out erro: string): boolean;
var
json : string;
jsonObj: TJsonObject;
begin
erro := '';
with RequestEncerrarComanda do
begin
Params.Clear;
AddParameter('id_comanda', id_comanda, TRESTRequestParameterKind.pkGETorPOST);
Execute;
end;
if RequestEncerrarComanda.Response.StatusCode <> 200 then
begin
Result := false;
erro := 'Erro ao encerrar comanda: ' + RequestEncerrarComanda.Response.StatusCode.ToString;
end
else
begin
json := RequestEncerrarComanda.Response.JSONValue.ToString;
jsonObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(json), 0) as TJSONObject;
if jsonObj.GetValue('retorno').Value = 'OK' then
Result := true
else
begin
Result := false;
erro := jsonObj.GetValue('retorno').Value;
end;
jsonObj.DisposeOf;
end;
end;
procedure Tdm.DataModuleCreate(Sender: TObject);
begin
with conn do
begin
Params.Values['DriverID'] := 'SQLite';
{$IFDEF MSWINDOWS}
Params.Values['Database'] := System.SysUtils.GetCurrentDir + '\DB\banco.db';
{$ELSE}
Params.Values['Database'] := TPath.Combine(TPath.GetDocumentsPath, 'banco.db');
{$ENDIF}
try
Connected := true;
except on e:exception do
raise Exception.Create('Erro de conex„o com o banco de dados: ' + e.Message);
end;
end;
end;
end.
|
unit uProcedure;
interface
uses
Graphics, Windows, Controls, Forms;
// процедуры для получения пути к папке System32
function GetSystem32Path: string;
// процедуры для получения пути к папке Windows
function GetWinPath: string;
// процедуры для проверки включеный GUI или нет
function IsGUI: Boolean;
/// <summary>Процедура для редактирования темы</summary>
procedure SetStrToIni(const Section, Ident, Value: string);
/// <summary>Процедура для редактирования темы</summary>
procedure SetIntToIni(const Section, Ident: string; const Value: Integer);
/// <summary>Процедура для рисования системных курсоров</summary>
procedure DrawCursor(ACanvas: TCanvas; ACursor: TCursor); overload;
/// <summary>Процедура для рисования своих курсоров</summary>
procedure DrawCursor(ACanvas: TCanvas; ACursor: String); overload;
/// <summary>Процедура для получения параметров из файла темы</summary>
function GetStrFromIni(const Section, Ident, Value: string): string;
/// <summary>процедура для изминения иконок в теме</summary>
function PickIcon(hwndicon: HWND; var iconfile : string; var iconindex: integer): Boolean;
var
ThemePath: string;
implementation
uses
SHFolder, Inifiles, SysUtils, activex;
/// <summary>Диалог для вибора иконки</summary>
function PickIconDlg(Handle: THandle; FileName: PChar; FileNameSize: integer; var IconIndex: Integer): Boolean; stdcall; external 'shell32.dll' index 62;
function PickIcon(hwndicon: HWND; var iconfile : string; var iconindex: integer): Boolean;
var
buf : widestring;
idx : Integer;
begin
// buf wird mit korrekter Länge angelegt
SetLength(buf, MAX_PATH * 2);
ZeroMemory(@buf[1],length(buf));
//Show open icon dialog
Result := PickIconDlg(hwndicon, PChar(PWideChar(buf)), length (buf), idx);
if Result then
begin
iconfile := WideCharToString(Pwidechar(buf));
iconindex := idx; // return icon index
end;
end;
procedure DrawCursor(ACanvas: TCanvas; ACursor: TCursor);
var
HCursor : THandle;
begin
HCursor := Screen.Cursors[Ord(ACursor)];//Gets the cursor handle.
DrawIcon(ACanvas.Handle, 0, 0, HCursor);//Draws to canvas
end;
procedure DrawCursor(ACanvas: TCanvas; ACursor: String);
var
HCursor : THandle;
begin
HCursor := LoadCursorFromFile(PChar(ACursor));
DrawIcon(ACanvas.Handle, 0, 0, HCursor);//Draws to canvas
end;
function GetStrFromIni(const Section, Ident, Value: string): string;
var
ini: TIniFile;
begin
//Change Theme
ini := TIniFile.Create(ThemePath);
try
Result := ini.ReadString(Section, Ident, '');
finally
FreeAndNil(ini);
end;
end;
procedure SetStrToIni(const Section, Ident, Value: string);
var
ini: TIniFile;
begin
//Change Theme
ini := TIniFile.Create(ThemePath);
try
ini.WriteString(Section, Ident, Value);
finally
FreeAndNil(ini);
end;
end;
procedure SetIntToIni(const Section, Ident: string; const Value: Integer);
var
ini: TIniFile;
begin
//Change Theme
ini := TIniFile.Create(ThemePath);
try
ini.WriteInteger(Section, Ident, Value);
finally
FreeAndNil(ini);
end;
end;
//http://www.sqldoc.net/get-system-folder-in-delphi.html
function GetSpecialFolderPath(folder : integer) : string;
const
SHGFP_TYPE_CURRENT = 0;
var
path: array [0..MAX_PATH] of char;
begin
if SUCCEEDED(SHGetFolderPath(0, folder, 0, SHGFP_TYPE_CURRENT, @path[0])) then
Result := path
else
Result := '';
end;
function GetWinPath: string;
begin
Result := IncludeTrailingPathDelimiter( GetSpecialFolderPath(CSIDL_WINDOWS));
end;
function GetSystem32Path: string;
begin
Result := IncludeTrailingPathDelimiter( GetSpecialFolderPath(CSIDL_SYSTEM));
end;
function IsGUI: Boolean;
var
tmp: string;
begin
tmp := GetWinPath;
Result := CreateDir(tmp + 'test');
if Result then
RemoveDir(tmp + 'test');
end;
end.
|
PROGRAM Verschluesselung;
const str1 = 'ABCADEF';
const str2 = 'SJJSKLM';
const str3 = 'DIREKTEZUORDNUNGIKOG';
const str4 = 'EKVCIBCQMLVEHMHTKILT';
FUNCTION IsPossiblePair(s1: string; s2: string): boolean;
var i, j: integer;
string1Letter, string2Letter: string;
BEGIN (* IsPossiblePair *)
IsPossiblePair := true;
IF (Length(s1) <> Length(s2)) THEN BEGIN
IsPossiblePair := false;
END ELSE BEGIN
FOR i := 1 TO Length(s1) - 1 DO BEGIN
string1Letter := s1[i];
string2Letter := s2[i];
FOR j := i + 1 TO Length(s2) - 1 DO BEGIN
IF (s1[j] = string1Letter) THEN BEGIN
IF (s2[j] <> string2Letter) THEN BEGIN
IsPossiblePair := false;
break;
END; (* IF *)
END ELSE IF (s2[j] = string2Letter) THEN BEGIN
IF (s1[j] <> string1Letter) THEN BEGIN
IsPossiblePair := false;
break;
END; (* IF *)
END; (* IF *)
END; (* FOR *)
END; (* FOR *)
END; (* IF *)
END; (* IsPossiblePair *)
BEGIN (* Verschluesselung *)
WriteLn('String 1: ', str3);
WriteLn('String 2: ', str4);
Write('Sind von der selben Quelle: ', IsPossiblePair(str3, str4));
END. (* Verschluesselung *) |
{***************************************************************
*
* Project : CBClient
* Unit Name: MainForm
* Purpose :
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:12:33
* Author :
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit MainForm;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QComCtrls, QMenus, QButtons,
QExtCtrls, QStdCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, ComCtrls, Menus, Buttons, ExtCtrls,
StdCtrls,
{$ENDIF}
windows, messages, ToolWin, spin, SysUtils, Classes, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient;
type
TForm1 = class(TForm)
Label1: TLabel;
edUserName: TEdit;
Label2: TLabel;
edServer: TEdit;
Label3: TLabel;
lbClients: TListBox;
Label4: TLabel;
memLines: TMemo;
Label5: TLabel;
edMessage: TEdit;
SpeedButton1: TSpeedButton;
IdTCPClient1: TIdTCPClient;
Timer1: TTimer;
Label6: TLabel;
sePort: TSpinEdit;
Button1: TButton;
procedure FormShow(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure IdTCPClient1Connected(Sender: TObject);
procedure edMessageKeyPress(Sender: TObject; var Key: Char);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TForm1.FormShow(Sender: TObject);
begin
width := width + 1;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
Com,
Msg: string;
begin
if not IdTcpClient1.Connected then
exit;
Msg := IdTCPClient1.ReadLn('', 5);
if Msg <> '' then
if Msg[1] <> '@' then
begin
{ Not a system command }
memLines.Lines.Add(Msg);
end
else
begin
{ System command }
Com := UpperCase(Trim(Copy(Msg, 2, Pos(':', Msg) - 2)));
Msg := UpperCase(Trim(Copy(Msg, Pos(':', Msg) + 1, Length(Msg))));
if Com = 'CLIENTS' then
lbClients.Items.CommaText := Msg;
end;
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
if (edUserName.Text <> '') and
(edServer.Text <> '') and
SpeedButton1.Down then
begin
IdTCPClient1.Host := edServer.Text;
IdTCPClient1.Port := sePort.Value;
if SpeedButton1.Down then
IdTCPClient1.Connect;
end
else
begin
if (edUserName.Text = '') or
(edServer.Text = '') then
ShowMessage('You must put in a User Name and server name to connect.');
SpeedButton1.Down := false;
end;
end;
procedure TForm1.IdTCPClient1Connected(Sender: TObject);
begin
IdTCPClient1.WriteLn(edUserName.Text);
end;
procedure TForm1.edMessageKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then
begin
IdTCPClient1.WriteLn(edMessage.Text);
edMessage.Text := '';
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
IdTCPClient1.WriteLn('@' + 'CLIENTS:REQUEST');
end;
end.
|
unit Glblvars;
interface
uses Types, Forms, BtrvDlg, PASTypes, DBTables;
var
GlblApplicationIsClosing : Boolean; {Set when all of PAS is closing.}
GlblClosingAForm : Boolean;{set by childform.onclose, ref by MainPasForm.OnActScreenchg}
{the following items are loaded from the system record when user starts PAS}
GlblDataDir, {path to data for PAS, eg \PASYSTEM\DATA}
GlblErrorFileDir, {SCA error log path for SystemSupport, eg \PASYSTEM\ERRORLOG}
GlblProgramDir, {path to programs for PAS, eg \PASYSTEM}
GlblRPSDataDir, {path to the raw RPS data}
GlblExportDir, {path to where the 995 and 155 files we produce end up}
GlblReportDir : String; {path for reports \PASYSTEM\REPORTS}
GlblDrive : String; {What drive are the PAS directories located on?}
GlblHistYear,
GlblThisYear,
GlblNextYear : String; {contain current year values for ThisYear and NextYear}
{assessment files, loaded from system record}
{variables set during PAS execution after startup}
GlblClosingFormCaption : String;{used by tabs ctl of MDI interface to know when to}
{delete a tab, ref in OnActiveScreenChange event of}
{MainPASForm, set in OnClose of each Child Form}
{...when ClosingAForm is set on exiting a form, tells}
{MainPasForm.OnActScreen which form is closing so }
{it can tell which tab to delete}
GlblTaxYearFlg : Char; {set at startup or while user is in session}
{contains.. 'T' = Thisyear, 'N' = NextYear}
GlblProcessingType : Integer; {ThisYear, NextYear, History}
GlblVersion : String; {What version of PAS is this?}
GlblMunicipalityName,
GlblCountyName : String;
GlblUnitName : String; {used as part of SCA Error Dialog component processing}
GlblUserName : String; {PAS Userid of current user}
GlblSecurityLevel : Integer; {Security level of user from user profile.
10 = highest, 1 = lowest.}
{The mode access levels are controlled in the user profile.}
GlblNextYearAccess,
GlblThisYearAccess : Integer; {raNoAccess, raReadOnly, raReadWrite}
GlblHistoryAccess : Boolean;
{.. user prof for menus}
{name?}
{Parcltab.pas synchronization variables}
GlblParcelPageCloseCancelled : Boolean; {Used in the Parcel Add\Modify\Inquire
to say if a person cancelled the
exit on a page of the parcel notebook.
...See Parcltab.PAS and the child forms
it spawns for detailed usage}
GlblSearchDialogueInProgress : Boolean; {use to skip some OnActiveScreen change
events so SearchDialogue box, when displayed
on screen, is not treated as a 'tab-associated'
form, tested by MainForm.pas}
GlblChildWindowCreateFailed : Boolean; {Did the create of a child window
fail because of memory problems?}
GlblErrorDlgBox : TSCAErrorDialogBox; {We will only have one error
dialog box created in the main
form and freed upon the close of
the main form. This is for convienence
and consistency.}
GlblTraceTable : TTable; {We will have a global trace table which is opened once and maintained
throughout the session. This will reduce the overhead of opening the
trace table on each form.}
GlblCurrentTabNo,
GlblCurrentLinePos : Integer; {For printing directly to the printer.}
GlblPreviewPrint : Boolean; {Do they want to print to screen for this report?
This is only used for printing directly to
the printer.}
{The following variables are stored in the system record
and contain the formatting information for each part of the
SBL key. They are set variables with the possible values of
(fmLeftJustify, fmRightJustify, fmNumeric,
fmAlphaNumeric, fmAlpha, fmShiftRightAddZeroes).}
GlblSectionFormat : TSBLSegmentFormatType;
GlblSubsectionFormat : TSBLSegmentFormatType;
GlblBlockFormat : TSBLSegmentFormatType;
GlblLotFormat : TSBLSegmentFormatType;
GlblSublotFormat : TSBLSegmentFormatType;
GlblSuffixFormat : TSBLSegmentFormatType;
{FXX11021999-12: Allow the # of forced digits in each segment to be specified.}
GlblSectionDigits : Integer;
GlblSubsectionDigits : Integer;
GlblBlockDigits : Integer;
GlblLotDigits : Integer;
GlblSublotDigits : Integer;
GlblSuffixDigits : Integer;
{The following are the separators for the dash dot format
SBL. The seperator is between the named segment and the next
one, i.e. the GlblSectionSeparator is between the section
and subsection.}
GlblSectionSeparator : Char;
GlblSubsectionSeparator : Char;
GlblBlockSeparator : Char;
GlblLotSeparator : Char;
GlblSublotSeparator : Char;
GlblChangingTaxYear : Boolean; {This is a flag to say that we are presently changing
the tax year and closing all MDI children.}
GlblMunicipalityType : Integer; {MTCounty, MTTown, MTCity, MTVillage, MTSchool}
{This is used for places where we are just going to
show one exemption or taxable value type - that of
the municipal entity.}
GlblMunicipalityUsesTwoTaxRates : Boolean; {Even though a municipality has
hstd\non-hstd, they may only
use one rate (i.e. Ramapo),
so can't just rely on classified
indicator.}
{CHG10141997-2: Removed requirement for control number.
Is an option on municipality basis.}
GlblSalesControlNumberRequired : Boolean;
{These variables are used for the parcel locate so that it stays
in the same key as last time and goes to the old parcel.}
GlblLastSwisSBLKey : String;
GlblLastLocateKey : Integer;
{User preferences.}
GlblShowHints : Boolean; {Based on the user profile,
should we show hints on all forms?}
GlblAskSave : Boolean; {In the parcel pages, should we ask AMC
before they post?}
GlblInterleaveTabs : Boolean; {In the parcel pages, should the tabs for different
processing types be all together or interleaved?}
GlblNotesPurgeDefault : Boolean; {When they enter a note, should
we default the purge flag to
true or false - this is an option
is the user profile.}
GlblDefaultSwisCode : String; {The default swis code for the parcel locate.}
GlblConfirmOnExit : Boolean; {Confirm exit of whole PAS system?}
GlblDefaultPreviewZoomPercent : Integer; {What is the default zoom % for the preview form?}
GlblFirstParcelPageShown : Integer; {Either the form number of the summary page or the
or the base page 1 - whatever the user prefers.}
{CHG10281997-1: More work on dual mode modifying.}
GlblModifyBothYears : Boolean;
{CHG11071997-2: Limit menu options for searcher.}
GlblUserIsSearcher : Boolean;
{CHG11181997-1: For the searcher, need a way to exit parcel view.}
GlblUserPressedParcelExit : Boolean;
{FXX11101997-2: Only store traces for fields listed in the
screen label file, since these are all we care about.}
GlblScreenLabelTable : TTable;
GlblMunicipalityCode : String; {The first four digits of each swis in the munic.}
{FXX02061998-5: Allow the automatic addition of enhanced STAR exemptions
when a senior exemption is added be a municipality
decision.}
GlblAutomaticallyAddEnhancedSTARExemptions : Boolean;
{FXX02121998-1: Open the assessment year control table for ThisYear and
NextYear and put the STAR variables into global variables
so that we don't have to open the assessment table
each time to calculate STAR. This was causing a
computer hang sometimes possibly due to going too deep
in the call stack.}
GlblThisYearBasicSalesDifferential : Double;
GlblThisYearBasicLimit : Comp;
GlblThisYearEnhancedSalesDifferential : Double;
GlblThisYearEnhancedLimit : Comp;
GlblNextYearBasicSalesDifferential : Double;
GlblNextYearBasicLimit : Comp;
GlblNextYearEnhancedSalesDifferential : Double;
GlblNextYearEnhancedLimit : Comp;
{FXX04071998-6: Must keep track of whether or not
dual processing mode is on for TY.}
GlblModifyBothYearsCheckedInTY : Boolean;
{FXX04231998-8: Add global var to see if municipality is classified.}
GlblMunicipalityIsClassified : Boolean;
{CHG05011998-2: Add building permit report}
(* GlblShowPermitForms : Boolean;*)
{FXX06241998-1: The veterans maximums need to be at the county and swis level.}
GlblCountyVeteransMax,
GlblCountyCombatVeteransMax,
GlblCountyDisabledVeteransMax : Comp;
GlblIsWestchesterCounty : Boolean;
GlblWarnIfAddEnhancedSTARWithoutSenior : Boolean;
{CHG10121998-1: Add user options for default destination and show vet max msg.}
GlblPrintToScreenDefault,
GlblShowVetMaxMessage : Boolean;
{FXX10231998-2: In order to fix the problem that Peggy has been having, we will make a universal
dialogboxshowing var and not worry about the individual kind.}
GlblDialogBoxShowing : Boolean;
{CHG12011998-1: Allow user ID's that only allow name and addr changes on pg 1.}
GlblNameAddressUpdateOnly : Boolean;
{FXX12291998-2: LB does not use override amounts for condos and we must calc
amount.}
GlblAllowCondoExemptionOverride : Boolean;
{CHG01251999-1 Add floating list capability.}
GlblListDir : String;
GlblSalesApplyToThisYear : Boolean;
{FXX04091999-8: Allow for saving and loading of report options.}
GlblReportOptionsDir : String;
{FXX04161999-5: Allow people to modify other's notes if they want.}
GlblModifyOthersNotes : Boolean;
GlblDisplaySystemExemptionConfirmation : Boolean;
{FXX05181999-2: Trace the add of the system exemption, but only if the
calling job requires it - i.e. running exemptions recalc,
since other jobs automatically insert a trace rec for the
system exemption.}
GlblInsertSystemExemptionTrace : Boolean;
{FXX05021999-1: Place on page where to start address for windowed
envelope.}
GlblLetterAddressStart : Real;
{CHG05131999-2: Let people look up parcels from the parcel list.}
GlblParcelMaintenance : TForm;
GlblLocateParcelFromList : Boolean;
GlblParcelListSBLKey : String;
{CHG06101999-1: Use mailing addr fields a la Mt. Vernon.}
GlblUseMailingAddrFields : Boolean;
{FXX06141999-2: Allow users to see warnings on a parcel right away.}
GlblShowParcelWarnings : Boolean;
{CHG06291999-1: Keep the searcher from seeing next year values.}
SearcherCanSeeNYValues : Boolean;
{CHG07191999-1: Allow municipality to choose which deed type is default.}
GlblDefaultDeedType : String;
{FXX08031999-2: Option to not enforce measurement restrictions.}
GlblEnforceMeasurementRestrictions : Boolean;
{CHG09021999-1: Save sales transmittals in a directory for history.}
GlblSavedSalesDir : String;
{CHG09071999-3: Allow selection of what warning messages are displayed.}
GlblWarningOptions : WarningTypesSet;
{FXX11021999-13: Allow the letter left margin to be customized.}
GlblLetterLeftMargin : Real;
{CHG12081999-1: Option to prompt if legal paper is required.}
GlblRemindForLegalPaper : Boolean;
{FXX12101999-5: Alow them to blank out dates.}
GlblParcelTabChild : TForm;
GlblSearchReportDefaultParcelType : Integer;
{FXX12291999-1: Allow them to specify the number of blank lines at
the bottom of the roll.}
GlblLinesLeftOnRollDotMatrix : Integer;
GlblLinesLeftOnRollLaserJet : Integer;
{FXX01142000-2: Don't ask if want to change assessment if prior to final roll.}
GlblFinalRollDate : TDateTime;
{CHG01182000-1: Option to not have searcher see exemption denials.}
{CHG01182000-2: Allow users to click off the owner change button.}
{FXX01182000-1: Need a default picture directory.}
GlblSearcherViewsDenials : Boolean;
GlblCanTurnOffOwnerChangeFlag : Boolean;
GlblPictureDir : String;
GlblUserSeesReportDialog : Boolean;
{CHG02122000-3: Insert a name\addr audit change record.}
GlblNameAddressTraceTable : TTable;
{CHG03202000-1: For Ramapo remapping.}
GlblLocateByOldParcelID : Boolean;
{CHG04032000-1: Print full market value on rolls.}
GlblPrintFullMarketValue : Boolean;
GlblUseOldParcelIDsForSales : Boolean;
{FXX06012000-1: Try using transactions around roll totals and audits to
reduce 84s and 85s.}
GlblUseTransactions : Boolean;
{CHG01082001-1: Auto detect new pictures / documents.}
GlblAutoDetectNewPictures : Boolean;
GlblAutoDetectNewDocuments : Boolean;
{CHG02282001-1: Allow everybody to everyone elses changes.}
GlblAllowAuditAccessToAll : Boolean;
GlblDocumentDir : String;
{CHG03212001-1: Password protect school code changes.}
{CHG03212001-2: Only allow wholly exempt exemptions on vacant lands.}
GlblPasswordProtectSchoolCode : Boolean;
GlblSchoolCodeChangePassword : String;
GlblAllowOnlyWhollyExemptsOnVacantLand : Boolean;
{CHG04122001-1(MDT): Record removed exemptions.}
GlblRecordRemovedExemptions : Boolean;
{CHG04172001-1: Senior percent calculator.}
GlblUseSeniorExemptionPercentCalculator : Boolean;
{CHG05102001-1: Only let the searcher view summary and pg1}
GlblSearcherOnlySeesSummaryAndPage1 : Boolean;
{CHG06302001-1: Set enhanced options such as collate, duplex, bins.}
GlblAlwaysPrintOnLetterPaper : Boolean;
{CHG07132001-1: Allow searching subdirectories and picture masks.}
GlblPictureMask : String;
GlblSearchSubfoldersForPictures : Boolean;
GlblDocumentMask : String;
GlblSearchSubfoldersForDocuments : Boolean;
GlblApplicationIsTerminatingToDoBackup : Boolean;
{CHG09162001-1: New security option to not allow value changes.}
GlblUserCanMakeValueChanges : Boolean;
{CHG09272001-1: Parcel toolbar.}
GlblUserWantsParcelToolbar : Boolean;
GlblMapDirectory : String;
GlblApplicationIsActive : Boolean;
GlblUserCanSeeComparables : Boolean;
GlblUserCanRunAudits : Boolean;
GlblRecalculateSFLA : Boolean;
GlblBuildingSystemLinkType : Integer;
GlblBuildingSystemDatabaseName,
GlblBuildingSystemTableName,
GlblBuildingSystemIndexName : String;
GlblShowAVChangeBox : Boolean;
GlblShowInventoryValues : Boolean;
GlblShowParcelYearFlipMenuItem : Boolean;
GlblUsesMaps : Boolean;
GlblUsesGrievances : Boolean;
GlblCanCalculateRollTotals : Boolean;
GlblMapInfoFormClosed : Boolean;
GlblMapInfoFormClosingSwisSBLKey : String;
GlblLastGrievanceNumber : Integer;
GlblLetterTemplateDir : String;
GlblUseRAR : Boolean;
GlblShowFullMarketValue : Boolean;
GlblSearcherCanSeeFullMarketValue : Boolean;
{CHG07192002-1: Accomodate a seperate coop roll.}
GlblIconFileName : String;
GlblCaption : String;
GlblIsCoopRoll : Boolean;
GlblLastCertiorariNumber : Integer;
GlblUseRARForResVacantLand : Boolean;
GlblCertiorariOnly : Boolean;
GlblLastLocateInfoRec : GlblLastLocateInfoRecord;
{CHG12202002-1: Additional security for certs.}
GlblCanSeeCertiorari : Boolean;
GlblCanSeeCertNotes : Boolean;
GlblCanSeeCertAppraisals : Boolean;
GlblCanSeeSmallClaimsNotes : Boolean;
GlblDefaultParcelViewPage : Integer;
GlblFormatSegmentToLength : Boolean;
GlblDontZeroFillBlankSegments : Boolean;
GlblUseTFormPrint : Boolean;
GlblUseRestrictSearcherParcelsFeature : Boolean;
GlblSuppressRollTotalsUpdate : Boolean;
GlblUseAccountNumberLookup : Boolean;
GlblAnyUserCanChangeOpenNoteStatus : Boolean;
GlblNoPartialExemptionsOnRollSection8 : Boolean;
GlblSummaryAndPage1ValueInformationIsAlwaysPrior2Years : Boolean;
GlblAllowBankCodeFreeze : Boolean;
GlblExtractAdditionalLotsIn155File : Boolean;
GlblDefaultToNoSwisRequiredOnParcelIDLookup : Boolean;
GlblParcelToolbarIsCreated : Boolean;
GlblUsesSketches : Boolean;
GlblDefaultApexDir : String;
GlblDefaultPictureLoadingDockDirectory : String;
GlblSearcherMapDefault : String;
GlblMapAV_SP_Ratio_Decimals : Integer;
GlblReportReprintLeftMargin : Double;
GlblReportReprintSectionTop : Double;
GlblUsesVillage_Import_Export : Boolean;
GlblVillageHoldingDockFolder : String;
GlblRollTotalsToShow : TRollTotalsToShowType;
GlblAV_BalancingFieldUpdates_AV : Boolean;
GlblCertiorariReportsUseAlternateID : Boolean;
GlblSearcherCreatesSelectedMapLayerLocally : Boolean;
GlblCanPreventExemptionRenewal : Boolean;
{CHG03222004-2(2.08): Option to prevent user from changing exemptions.}
GlblUserCannotChangeExemptions : Boolean;
GlblUseGeneralizedComparisonReport : Boolean;
{CHG03232004-5(2.08): Private notes feature.}
GlblUsePrivateNotes : Boolean;
GlblUserCanEnterAndViewPrivateNotes : Boolean;
{CHG03232004-7(2.08): Link up help.}
GlblHelpDirectory : String;
GlblSkipUnusedSalesFields : Boolean;
GlblUseGlenCoveFormatForCodeEnforcement : Boolean;
GlblBillDLLName : String;
GlblBillRAVEName : String;
GlblGrievanceSeperateRepresentativeInfo : Boolean;
GlblAllUsersCreatesSelectedMapLayerLocally : Boolean;
GlblIncludeFinishedBasementAreaInSFLA : Boolean;
GlblSubtractUnfinishedArea : Boolean;
GlblUseControlNumInsteadOfBook_Page : Boolean;
GlblHideSalesPersonalProperty : Boolean;
GlblHideSalesTransmitFields : Boolean;
GlblNextSalesFieldAfterCondition : Integer;
GlblShowUniformPercentInsteadOfSTARAmountOnSummaryScreen : Boolean;
GlblShowAssessmentNotesOnAVHistoryScreen : Boolean;
GlblPreventSearcherExit : Boolean;
GlblAllowBlankDeedDate : Boolean;
GlblCustomParcelLocate : Boolean;
GlblShowExtendedSDAmounts : Boolean;
GlblParcelLocateDefault : Integer;
GlblCloseButtonIsLocate : Boolean;
GlblParcelMaint_DisplayAccountNumber : Boolean;
GlblParcelMaint_DisplayOldIDUnconverted : Boolean;
GlblUser_Restricted_To_Name_Addr_Change_Can_Change_Owner : Boolean;
GlblAllowSystemShutdown : Boolean;
GlblShowExemptionDescription : Boolean;
GlblShowMortgageOnPage1 : Boolean;
GlblShowExemptionFilingInformation : Boolean;
GlblUseEnhancedPrintDialog : Boolean;
GlblApplicationIsMinimized : Boolean;
GlblUse3DecimalsForDimensions : Boolean;
GlblUser_BankCodeUpdateOnly : Boolean;
GlblPreventParcelLocateMinimize : Boolean;
GlblUsePrintSuitePrintScreen : Boolean;
GlblShowNassauValues : Boolean;
GlblShowSpecialDistrictDescriptions : Boolean;
GlblAllowOldSBLEdit : Boolean;
GlblMergeValuesDuringMerge : Boolean;
GlblAllowSBLRenumber : Boolean;
GlblPrintAccountNumbersOnReports : Boolean;
GlblMunicipalityTypeName : String;
GlblEnableExemptionCapOption : Boolean;
GlblUsesProrata : Boolean;
GlblEnablePermanentRetentionFeature : Boolean;
GlblUseNewBuildingPermitPage : Boolean;
GlblPrintScreenMethod : Integer;
GlblPrintEstimatedTaxLetters : Boolean;
GlblAssessmentYearIsSameAsTaxYearForCounty : Boolean;
GlblAssessmentYearIsSameAsTaxYearForMunicipal : Boolean;
GlblAssessmentYearIsSameAsTaxYearForSchool : Boolean;
GlblUseNewStyleForms : Boolean;
GlblTreatMixedUseParcelsAsResidential : Boolean;
GlblUsesPASPermits : Boolean;
GlblDoNotPrintNextYearOnF5 : Boolean;
GlblLeaveApexActive : Boolean;
GlblDefaultPropertyCardDirectory : String;
GlblSupressDollarSignsOnAssessments : Boolean;
GlblAllowLetterPrint : Boolean;
GlblCurrentSwisSBLKey : String;
GlblPropertyCardsArePDF : Boolean;
GlblCoopBaseSBLHasSubblock : Boolean;
GlblStartPASMaximized : Boolean;
GlblUserCantDeleteExemptions : Boolean;
GlblUsesApexMedina : Boolean;
GlblRAVEBillName : String;
GlblUsesAutoShutdown : Boolean;
GlblDetectPicturesByAccountNumber : Boolean;
GlblDisplayExemptionDescriptions : Boolean;
GlblDisplaySpecialDistrictDescriptions : Boolean;
GlblUserCanViewPermits : Boolean;
GlblSuppressDocumentAutoload : Boolean;
GlblDisplaySplitSchoolSBLs : Boolean;
GlblDisplaySwisOnPrintKey : Boolean;
glblOwnerAddressUpdateFilePath : String;
glblCountyTaxDatabaseName : String;
glblCountyCollectionType : String;
glblCountyCollectionNumber : String;
glblCountyBaseTaxRatePointer : String;
glblSCARFormTemplateFileName : String;
glblPrintSmallClaimsRebateForms : Boolean;
glblDisplayAccountNumberOnCard : Boolean;
glblUsesRAVEBills : Boolean;
glblBillPrintMenuItem1 : Integer;
glblBillPrintMenuItem2 : Integer;
glblShowHistoryOfOwners : Boolean;
glblShowNewOwnerOnSummaryTab : Boolean;
glblShowImprovementValue : Boolean;
glblAutoUpdateNamesAddrs : Boolean;
glblDatabaseToUpdateNameAddrs1 : String;
glblDatabaseToUpdateNameAddrs2 : String;
glblDatabaseToUpdateNameAddrs3 : String;
glblAutoCalcRollTotalsBeforePrint : Boolean;
glblSuppressPrintSizePrompts : Boolean;
glblAutoDuplex : Boolean;
glblAutoVerticalDuplex : Boolean;
glblSuppressIVP : Boolean;
glblAlwaysShowMostCurrentSaleOnSalesPage : Boolean;
glblUseNewOwnerProgressionForm : Boolean;
glblDisplaySuppressFromGIS : Boolean;
glblUseWindowsSaveDlgForReports : Boolean;
glblTracePictureAccess : Boolean;
glblUnfinRoomIsUnfinBsmt : Boolean;
glblUsesSQLTax : Boolean;
glblShowSTARSavingsOnExemptionPage : Boolean;
glblUsesPictometry : Boolean;
glblPreventPASStartup : Boolean;
glblSmallClaimsDefaultYear : String;
glblUsesPictometry_FullSBL : Boolean;
glblShowSketchWithComments : Boolean;
glblFreezeAssessmentDueToGrievance : Boolean;
glblAllowSalesInventoryEdit : Boolean;
glblUsesPictometry_OldPrintKey : Boolean;
glblRemapOldSBLHasSwis : Boolean;
glblUseExactPrintKey : Boolean;
glblLocateDisplaysPrintKey : Boolean;
glblToolbarLaunchesGIS : Boolean;
glblInvDisplaysZoningCode : Boolean;
glblDisplaySchoolShortCodeInSummary : Boolean;
glblUsesTaxBillNameAddr : Boolean;
glblShowExtendedNeighborhoodInfo : Boolean;
implementation
end. |
unit uABOUT;
interface
uses WinApi.Windows, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls,
uRoutine;
type
TAboutBox = class(TForm)
Panel1: TPanel;
ProgramIcon: TImage;
ProductName: TLabel;
Version: TLabel;
Copyright: TLabel;
Comments: TLabel;
OKButton: TButton;
lblProductName: TLabel;
lblVersion: TLabel;
lblCopyRight: TLabel;
lblComment: TLabel;
CompanyName: TLabel;
lblCompanyName: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private 宣言 }
public
{ Public 宣言 }
end;
var
AboutBox: TAboutBox;
implementation
{$R *.dfm}
procedure TAboutBox.FormCreate(Sender: TObject);
var
ExeName: string;
begin
ExeName := Application.ExeName;
lblProductName.Caption := GetVersionInfo(ExeName, vrProductName);
lblVersion.Caption := GetVersionInfo(ExeName, vrFileVersion);
lblCopyRight.Caption := GetVersionInfo(ExeName, vrLegalCopyright);
lblComment.Caption := GetVersionInfo(ExeName, vrComments);
lblCompanyName.Caption := GetVersionInfo(ExeName, vrCompanyName);
end;
end.
|
unit Unit1;
interface
uses
// Windows, Messages,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.Jpeg,
Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls,
//GLS
GLWin32Viewer, GLScene, GLObjects, GLHUDObjects, GLGeomObjects, GLCadencer,
GLBlur, GLTexture, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses,
GLUtils;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLCube1: TGLCube;
GLLightSource1: TGLLightSource;
GLDummyCube1: TGLDummyCube;
GLAnnulus1: TGLAnnulus;
GLBlur1: TGLBlur;
Timer1: TTimer;
GLMaterialLibrary1: TGLMaterialLibrary;
Panel1: TPanel;
edtAdvancedBlurAmp: TEdit;
Label1: TLabel;
Label2: TLabel;
edtAdvancedBlurPasses: TEdit;
trkAdvancedBlurHiClamp: TTrackBar;
Label3: TLabel;
Label4: TLabel;
trkAdvancedBlurLoClamp: TTrackBar;
Label5: TLabel;
Bevel1: TBevel;
GLSphere1: TGLSphere;
TorusImpostor: TGLTorus;
Memo1: TMemo;
GLTorus2: TGLTorus;
LabelFPS: TLabel;
procedure Timer1Timer(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormCreate(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure edtAdvancedBlurAmpChange(Sender: TObject);
procedure trkAdvancedBlurHiClampChange(Sender: TObject);
procedure trkAdvancedBlurLoClampChange(Sender: TObject);
procedure edtAdvancedBlurPassesChange(Sender: TObject);
procedure GLBlur1BeforeTargetRender(Sender: TObject);
procedure GLBlur1AfterTargetRender(Sender: TObject);
private
{ Private declarations }
mx,my:integer;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
// Blur GLDummyCube1and it's children
GLBlur1.TargetObject:=GLDummyCube1;
// point to GLDummyCube1
GLCamera1.TargetObject:=GLDummyCube1;
// load materials
GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile('beigemarble.jpg');
GLMaterialLibrary1.Materials[1].Material.Texture.Image.LoadFromFile('moon.bmp');
end;
procedure TForm1.GLBlur1BeforeTargetRender(Sender: TObject);
begin
TorusImpostor.Visible:=true; // GLBlur1 must render the Torusimpostor
end;
procedure TForm1.GLBlur1AfterTargetRender(Sender: TObject);
begin
TorusImpostor.Visible:=false; // GLSCeneViewer1 must NOT render the Torusimpostor
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
GLSceneViewer1.Invalidate;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if (ssRight in Shift) and (Y > 10) then
GLCamera1.AdjustDistanceToTarget(my/Y);
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my-Y,mx-X);
mx:=X;
my:=Y;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
LabelFPS.Caption :=GLSceneViewer1.FramesPerSecondText(0);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.trkAdvancedBlurHiClampChange(Sender: TObject);
begin
GLBlur1.AdvancedBlurHiClamp:=trkAdvancedBlurHiClamp.Position;
end;
procedure TForm1.trkAdvancedBlurLoClampChange(Sender: TObject);
begin
GLBlur1.AdvancedBlurLowClamp:=trkAdvancedBlurLoClamp.Position;
end;
procedure TForm1.edtAdvancedBlurAmpChange(Sender: TObject);
begin
GLBlur1.AdvancedBlurAmp:=StrToFloat(edtAdvancedBlurAmp.Text);
end;
procedure TForm1.edtAdvancedBlurPassesChange(Sender: TObject);
begin
GLBlur1.AdvancedBlurPasses:=StrToInt(edtAdvancedBlurPasses.Text);
end;
end.
|
unit ufrmSplash;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, dxGDIPlusClasses, cxClasses,
cxLabel, dxImageSlider;
type
TfrmSplash = class(TForm)
imgSplash: TdxImageSlider;
Images: TcxImageCollection;
IrriGranos: TcxImageCollectionItem;
IrriPapa: TcxImageCollectionItem;
IrriCana: TcxImageCollectionItem;
lblLoad: TcxLabel;
IrriNogal: TcxImageCollectionItem;
procedure imgSplashDblClick(Sender: TObject);
private
procedure SetLoad(const Value: String);
{ Private declarations }
public
{ Public declarations }
function ElegirAuto(Param: String): Boolean;
function ElegirManual: String;
published
property Load: String write SetLoad;
end;
var
frmSplash: TfrmSplash;
implementation
{$R *.dfm}
{ TfrmSplash }
function TfrmSplash.ElegirAuto(Param: String): Boolean;
var
Item: TcxImageCollectionItem;
begin
if imgSplash.Images.Items.FindItemByName(Param, Item) then
begin
imgSplash.ItemIndex:= imgSplash.Images.Items.IndexOf(Item);
Exit(True)
end
else
begin
Exit(False)
end;
end;
function TfrmSplash.ElegirManual: String;
begin
ShowModal;
Exit(imgSplash.Images.Items[imgSplash.ItemIndex].Name);
end;
procedure TfrmSplash.imgSplashDblClick(Sender: TObject);
begin
Close;
end;
procedure TfrmSplash.SetLoad(const Value: String);
begin
lblLoad.Caption:= Value;
Refresh;
end;
end.
|
unit ApkBuild;
{ TODO:
- implement TApkBuilder.BringToFrontEmulator for linux }
{$mode objfpc}{$H+}
interface
uses
{$ifdef Windows}Windows,{$endif}
Classes, SysUtils, ProjectIntf, Forms;
type
{ TApkBuilder }
TApkBuilder = class
private
FProj: TLazProject;
FSdkPath, FAntPath, FJdkPath, FNdkPath: string;
FProjPath: string;
FDevice: string;
procedure BringToFrontEmulator;
function CheckAvailableDevices: Boolean;
procedure LoadPaths;
function RunAndGetOutput(const cmd, params: string; Aout: TStrings): Integer;
function TryFixPaths: TModalResult;
public
constructor Create(AProj: TLazProject);
function BuildAPK(Install: Boolean = False): Boolean;
function InstallAPK: Boolean;
procedure RunAPK;
end;
implementation
uses
IDEExternToolIntf, LazIDEIntf, UTF8Process, Controls, EditBtn, StdCtrls,
ButtonPanel, Dialogs, uFormStartEmulator, IniFiles, process, strutils,
laz2_XMLRead, Laz2_DOM, laz2_XMLWrite, LazFileUtils;
function QueryPath(APrompt: string; out Path: string;
ACaption: string = 'Android Wizard: Path Missing!'): Boolean;
var
f: TForm;
l: TLabel;
de: TDirectoryEdit;
begin
Result := False;
f := TForm.Create(nil);
with f do
try
Caption := ACaption;
Position := poScreenCenter;
AutoSize := True;
Constraints.MinWidth := 440;
BorderStyle := bsSingle;
BorderIcons := [biSystemMenu];
l := TLabel.Create(f);
with l do
begin
Parent := f;
Caption := APrompt;
AnchorSideLeft.Control := f;
AnchorSideTop.Control := f;
BorderSpacing.Around := 8;
end;
de := TDirectoryEdit.Create(f);
with de do
begin
Parent := f;
if Pos(':', APrompt) > 0 then
DialogTitle := Copy(APrompt, 1, Pos(':', APrompt) - 1)
else
DialogTitle := APrompt;
AnchorSideLeft.Control := f;
AnchorSideTop.Control := l;
AnchorSideTop.Side := asrBottom;
AnchorSideRight.Control := f;
AnchorSideRight.Side := asrRight;
Anchors := [akTop, akLeft, akRight];
BorderSpacing.Around := 8;
end;
with TButtonPanel.Create(f) do
begin
Parent := f;
ShowButtons := [pbOK, pbCancel];
AnchorSideTop.Control := de;
AnchorSideTop.Side := asrBottom;
Anchors := [akTop, akLeft, akRight];
ShowBevel := False;
end;
if ShowModal = mrOK then
begin
Path := de.Directory;
Result := True;
end;
finally
Free;
end;
end;
{ TApkBuilder }
procedure TApkBuilder.LoadPaths;
begin
with TIniFile.Create(IncludeTrailingPathDelimiter(LazarusIDE.GetPrimaryConfigPath)
+ 'JNIAndroidProject.ini') do
try
FSdkPath := ReadString('NewProject', 'PathToAndroidSDK', '');
FAntPath := ReadString('NewProject', 'PathToAntBin', '');
FJdkPath := ReadString('NewProject', 'PathToJavaJDK', '');
FNdkPath := ReadString('NewProject', 'PathToAndroidNDK', '');
finally
Free
end;
if FAntPath = '' then
if not QueryPath('Path to Ant bin: [ex. C:\adt32\Ant\bin]', FAntPath) then
Exit;
if FSdkPath = '' then
if not QueryPath('Path to Android SDK: [ex. C:\adt32\sdk]', FSdkPath) then
Exit;
if FJdkPath = '' then
if not QueryPath('Path to Java JDK: [ex. C:\Program Files (x86)\Java\jdk1.7.0_21]', FJdkPath) then
Exit;
if FNdkPath = '' then
if not QueryPath('Path to Android NDK: [ex. C:\adt32\ndk10]', FNdkPath) then
Exit;
end;
function TApkBuilder.RunAndGetOutput(const cmd, params: string;
Aout: TStrings): Integer;
var
i: Integer;
ms: TMemoryStream;
buf: array [0..255] of Byte;
begin
with TProcessUTF8.Create(nil) do
try
Options := [poUsePipes, poStderrToOutPut];
Executable := cmd;
Parameters.Text := params;
ShowWindow := swoHIDE;
Execute;
ms := TMemoryStream.Create;
try
repeat
i := Output.Read(buf{%H-}, SizeOf(buf));
if i > 0 then ms.Write(buf, i);
until not Running and (i <= 0);
ms.Position := 0;
Aout.LoadFromStream(ms);
finally
ms.Free;
end;
Result := ExitCode;
finally
Free;
end;
end;
function TApkBuilder.TryFixPaths: TModalResult;
procedure FixArmLinuxAndroidEabiVersion(var path: string);
var
i: Integer;
s, p: string;
dir: TSearchRec;
sl: TStringList;
f: TForm;
lb: TListBox;
begin
if DirectoryExists(path) then Exit;
i := Pos('arm-linux-androideabi-', path);
if i = 0 then Exit;
p := Copy(path, 1, PosEx(PathDelim, path, i));
if DirectoryExists(p) then Exit;
Delete(p, 1, i + 21);
p := Copy(p, 1, Pos(PathDelim, p) - 1);
if p = '' then Exit;
s := Copy(path, 1, i - 1);
if FindFirst(s + 'arm-linux-androideabi-*', faDirectory, dir) = 0 then
begin
sl := TStringList.Create;
try
repeat
sl.Add(dir.Name);
until (FindNext(dir) <> 0);
if sl.Count > 1 then
begin
sl.Sort;
f := TForm.Create(nil);
try
f.Position := poScreenCenter;
f.Caption := 'arm-linux-androideabi';
f.AutoSize := True;
f.BorderIcons := [biSystemMenu];
with TLabel.Create(f) do
begin
Parent := f;
Align := alTop;
BorderSpacing.Around := 6;
Caption := 'Choose arm-linux-androideabi version:';
end;
lb := TListBox.Create(f);
lb.Parent := f;
lb.Align := alClient;
lb.Items.Assign(sl);
lb.BorderSpacing.Around := 6;
lb.Constraints.MinHeight := 200;
lb.ItemIndex := 0;
with TButtonPanel.Create(f) do
begin
Parent := f;
ShowButtons := [pbOK, pbCancel];
ShowBevel := False;
end;
if f.ShowModal <> mrOk then Exit;
s := lb.Items[lb.ItemIndex];
finally
f.Free;
end;
end else
s := sl[0];
finally
sl.Free;
end;
Delete(s, 1, 22);
if s = '' then Exit;
path := StringReplace(path, p, s, [rfReplaceAll]);
end;
FindClose(dir);
end;
procedure FixPrebuiltSys(var path: string);
var
i: Integer;
p, s: string;
dir: TSearchRec;
begin
if DirectoryExists(path) then Exit;
i := Pos(PathDelim + 'prebuilt' + PathDelim, path);
if i = 0 then Exit;
p := path;
Delete(p, 1, i + 9);
p := Copy(p, 1, Pos(PathDelim, p) - 1);
if p = '' then Exit;
s := Copy(path, 1, i + 9);
if FindFirst(s + '*', faDirectory, dir) = 0 then
begin
s := dir.Name;
path := StringReplace(path, p, s, [rfReplaceAll]);
end;
FindClose(dir);
end;
function PosIdent(const str, dest: string): Integer;
var i: Integer;
begin
i := Pos(str, dest);
repeat
if ((i = 1) or not (dest[i - 1] in ['a'..'z', 'A'..'Z']))
and ((i + Length(str) > Length(dest))
or not (dest[i + Length(str)] in ['a'..'z', 'A'..'Z'])) then Break;
i := PosEx(str, dest, i + 1);
until i = 0;
Result := i;
end;
function FixPath(var path: string; const truncBy, newPath: string): Boolean;
begin
if Pos(PathDelim, path) = 0 then
if PathDelim <> '/' then
{%H-}path := StringReplace(path, '/', PathDelim, [rfReplaceAll])
else
{%H-}path := StringReplace(path, '\', PathDelim, [rfReplaceAll]);
Delete(path, 1, PosIdent(truncBy, path));
Delete(path, 1, Pos(PathDelim, path));
path := IncludeTrailingPathDelimiter(newPath) + path;
FixArmLinuxAndroidEabiVersion(path);
FixPrebuiltSys(path);
Result := DirectoryExists(path);
end;
function GetManifestSdkTarget(Manifest: string; out SdkTarget: string): Boolean;
var
ManifestXML: TXMLDocument;
n: TDOMNode;
begin
Result := False;
if not FileExists(Manifest) then Exit;
try
ReadXMLFile(ManifestXML, Manifest);
try
n := ManifestXML.DocumentElement.FindNode('uses-sdk');
if not Assigned(n) then Exit;
n := n.Attributes.GetNamedItem('android:targetSdkVersion');
if not Assigned(n) then Exit;
SdkTarget := n.TextContent;
Result := True;
finally
ManifestXML.Free
end;
except
Exit;
end;
end;
var
sl: TStringList;
i: Integer;
ForceFixPaths: Boolean;
str, prev, pref: string;
xml: TXMLDocument;
n: TDOMNode;
begin
Result := mrAbort;
ForceFixPaths := False;
if not DirectoryExists(FNdkPath) then
raise Exception.Create('NDK path (' + FNdkPath + ') does not exist! '
+ 'Fix NDK path with Path settings in Tools menu.');
sl := TStringList.Create;
try
// Libraries
sl.Delimiter := ';';
sl.DelimitedText := FProj.LazCompilerOptions.Libraries;
for i := 0 to sl.Count - 1 do
begin
if not DirectoryExists(sl[i]) then
begin
str := sl[i];
if not FixPath(str, 'ndk', FNdkPath) then Exit;
if not ForceFixPaths then
begin
case MessageDlg('Path "' + sl[i] + '" does not exist.' + sLineBreak +
'Change it to "' + str + '"?',
mtConfirmation, [mbYes, mbYesToAll, mbCancel], 0) of
mrYesToAll: ForceFixPaths := True;
mrYes:
else Exit;
end;
end;
sl[i] := str;
end;
end;
FProj.LazCompilerOptions.Libraries := sl.DelimitedText;
// Custom options:
sl.Delimiter := ' ';
sl.DelimitedText := FProj.LazCompilerOptions.CustomOptions;
for i := 0 to sl.Count - 1 do
begin
str := sl[i];
pref := Copy(str, 1, 3);
if pref = '-FD' then
begin
Delete(str, 1, 3);
prev := str;
if Pos(';', str) > 0 then Exit;
if not DirectoryExists(str) then
begin
if not FixPath(str, 'ndk', FNdkPath) then Exit;
if not ForceFixPaths then
begin
case MessageDlg('Path "' + prev + '" does not exist.' + sLineBreak +
'Change it to "' + str + '"?',
mtConfirmation, [mbYes, mbYesToAll, mbCancel], 0) of
mrYesToAll: ForceFixPaths := True;
mrYes:
else Exit;
end;
end;
sl[i] := pref + str;
end;
end;
end;
FProj.LazCompilerOptions.CustomOptions := sl.DelimitedText;
finally
sl.Free;
end;
// build.xml
prev := FProjPath + 'build.xml';
ReadXMLFile(xml, prev);
try
with xml.DocumentElement.ChildNodes do
for i := 0 to Count - 1 do
if Item[i].NodeName = 'property' then
begin
n := Item[i].Attributes.GetNamedItem('name');
if Assigned(n) then
begin
if n.TextContent = 'sdk.dir' then
begin
n := Item[i].Attributes.GetNamedItem('location');
if not Assigned(n) then Continue;
str := n.TextContent;
if not DirectoryExists(str) and DirectoryExists(FSdkPath) then
begin
if not ForceFixPaths
and (MessageDlg('build.xml',
'Path "' + str + '" does not exist.' + sLineBreak +
'Change it to "' + FSdkPath + '"?', mtConfirmation,
[mbYes, mbNo], 0) <> mrYes) then Exit;
Item[i].Attributes.GetNamedItem('location').TextContent := FSdkPath;
WriteXMLFile(xml, prev);
end;
end else
if n.TextContent = 'target' then
begin
// fix "target" according to AndroidManifest
n := Item[i].Attributes.GetNamedItem('value');
if not Assigned(n) then Continue;
if not GetManifestSdkTarget(FProjPath + 'AndroidManifest.xml', str) then Continue;
if n.TextContent <> 'android-' + str then
begin
if not ForceFixPaths
and (MessageDlg('build.xml',
'Change target to "android-' + str + '"?',
mtConfirmation, [mbYes, mbNo], 0) <> mrYes) then Exit;
Item[i].Attributes.GetNamedItem('value').TextContent := 'android-' + str;
WriteXMLFile(xml, prev);
end;
end;
end;
end;
finally
xml.Free;
end;
end;
procedure TApkBuilder.BringToFrontEmulator;
var
emul_win: TStringList;
i: Integer;
str: string;
begin
if Pos('emulator-', FDevice) <> 1 then Exit;
emul_win := TStringList.Create;
try
{$ifdef Windows}
EnumWindows(@FindEmulatorWindows, LPARAM(emul_win));
{$endif}
str := FDevice;
Delete(str, 1, Pos('-', str));
i := 1;
while (i <= Length(str)) and (str[i] in ['0'..'9']) do Inc(i);
str := Copy(str, 1, i - 1) + ':';
for i := 0 to emul_win.Count - 1 do
if Pos(str, emul_win[i]) = 1 then
begin
{$ifdef Windows}
SetForegroundWindow(HWND(emul_win.Objects[i]));
{$endif}
Break;
end;
finally
emul_win.Free;
end;
end;
function TApkBuilder.CheckAvailableDevices: Boolean;
var
sl, devs: TStringList;
i: Integer;
dev: Boolean;
str: string;
begin
sl := TStringList.Create;
devs := TStringList.Create;
try
repeat
sl.Clear;
RunAndGetOutput(IncludeTrailingPathDelimiter(FSdkPath) + 'platform-tools'
+ PathDelim + 'adb', 'devices', sl);
dev := False;
for i := 0 to sl.Count - 1 do
if dev then
begin
str := Trim(sl[i]);
if str <> '' then devs.Add(str);
end else
if Pos('List ', sl[i]) = 1 then
dev := True;
if devs.Count = 0 then
with TfrmStartEmulator.Create(FSdkPath, @RunAndGetOutput) do
try
if ShowModal = mrCancel then Exit(False);
finally
Free;
end
else
if devs.Count > 1 then
break;//todo: ChooseDevice(devs);
until devs.Count = 1;
FDevice := devs[0];
Result := True;
finally
devs.Free;
sl.Free;
end;
end;
constructor TApkBuilder.Create(AProj: TLazProject);
begin
FProj := AProj;
FProjPath := ExtractFilePath(ChompPathDelim(ExtractFilePath(FProj.MainFile.Filename)));
LoadPaths;
TryFixPaths;
end;
function TApkBuilder.BuildAPK(Install: Boolean): Boolean;
var
Tool: TIDEExternalToolOptions;
begin
Result := False;
if Install then
if not CheckAvailableDevices then Exit;
Tool := TIDEExternalToolOptions.Create;
try
Tool.Title := 'Building APK... ';
Tool.EnvironmentOverrides.Add('JAVA_HOME=' + FJdkPath);
Tool.WorkingDirectory := FProjPath;
Tool.Executable := IncludeTrailingPathDelimiter(FAntPath) + 'ant'{$ifdef windows}+'.bat'{$endif};
Tool.CmdLineParams := '-Dtouchtest.enabled=true debug';
if Install then
Tool.CmdLineParams := Tool.CmdLineParams + ' install';
Tool.Scanners.Add(SubToolDefault);
if not RunExternalTool(Tool) then
raise Exception.Create('Cannot build APK!');
Result := True;
finally
Tool.Free;
end;
end;
function TApkBuilder.InstallAPK: Boolean;
var
Tool: TIDEExternalToolOptions;
begin
Result := False;
if not CheckAvailableDevices then Exit;
Tool := TIDEExternalToolOptions.Create;
try
Tool.Title := 'Installing APK... ';
Tool.EnvironmentOverrides.Add('JAVA_HOME=' + FJdkPath);
Tool.WorkingDirectory := FProjPath;
Tool.Executable := IncludeTrailingPathDelimiter(FAntPath) + 'ant'{$ifdef windows}+'.bat'{$endif};
Tool.CmdLineParams := 'installd';
Tool.Scanners.Add(SubToolDefault);
if not RunExternalTool(Tool) then
raise Exception.Create('Cannot install APK!');
Result := True;
finally
Tool.Free;
end;
end;
procedure TApkBuilder.RunAPK;
var
xml: TXMLDocument;
f, proj: string;
n: TDOMNode;
Tool: TIDEExternalToolOptions;
begin
f := FProjPath + PathDelim + 'AndroidManifest.xml';
ReadXMLFile(xml, f);
try
n := xml.ChildNodes[0].Attributes.GetNamedItem('package');
if n is TDOMAttr then
proj := UTF8Encode(TDOMAttr(n).Value)
else
raise Exception.Create('Cannot determine package name!');
finally
xml.Free;
end;
Tool := TIDEExternalToolOptions.Create;
try
Tool.Title := 'Starting APK... ';
Tool.ResolveMacros := True;
Tool.Executable := IncludeTrailingPathDelimiter(FSdkPath) + 'platform-tools' + PathDelim + 'adb$(ExeExt)';
Tool.CmdLineParams := 'shell am start -n ' + proj + '/.App';
Tool.Scanners.Add(SubToolDefault);
if not RunExternalTool(Tool) then
raise Exception.Create('Cannot run APK!');
BringToFrontEmulator;
finally
Tool.Free;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC async execution implementation }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Stan.Async;
interface
implementation
uses
{$IFDEF MSWINDOWS}
Winapi.Windows, Winapi.Messages,
{$ENDIF}
System.SysUtils, System.Classes, System.SyncObjs,
FireDAC.Stan.Intf, FireDAC.Stan.Consts, FireDAC.Stan.Error, FireDAC.Stan.Factory,
FireDAC.Stan.Util,
FireDAC.UI.Intf;
type
TFDAsyncThread = class;
TFDStanAsyncExecutor = class;
TFDAsyncThread = class(TThread)
private
FRunThreadId: TThreadID;
FEvent: TEvent;
FExecutor: TFDStanAsyncExecutor;
protected
procedure Execute; override;
public
constructor Create(AExecutor: TFDStanAsyncExecutor);
destructor Destroy; override;
procedure WaitForLaunch;
end;
TFDStanAsyncExecutor = class(TFDObject, IFDStanAsyncExecutor)
private
FOperationIntf: IFDStanAsyncOperation;
FHandlerIntf: IFDStanAsyncHandler;
FAsyncDlg: IFDGUIxAsyncExecuteDialog;
FWait: IFDGUIxWaitCursor;
FTimeout: Cardinal;
FState: TFDStanAsyncState;
FMode: TFDStanAsyncMode;
FThread: TFDAsyncThread;
FException: Exception;
FSilentMode: Boolean;
procedure ExecuteOperation(AStoreException: Boolean);
procedure Cleanup;
protected
// IFDStanAsyncExecutor
function GetState: TFDStanAsyncState;
function GetMode: TFDStanAsyncMode;
function GetTimeout: Cardinal;
function GetOperation: IFDStanAsyncOperation;
function GetHandler: IFDStanAsyncHandler;
procedure Setup(const AOperation: IFDStanAsyncOperation;
const AMode: TFDStanAsyncMode; const ATimeout: Cardinal;
const AHandler: IFDStanAsyncHandler; ASilentMode: Boolean);
procedure Run;
procedure AbortJob;
procedure Launched;
public
destructor Destroy; override;
end;
var
FDStanActiveAsyncsWithUI: Integer;
{-------------------------------------------------------------------------------}
{ TFDAsyncThread }
{-------------------------------------------------------------------------------}
constructor TFDAsyncThread.Create(AExecutor: TFDStanAsyncExecutor);
begin
inherited Create(True);
FRunThreadId := TThread.CurrentThread.ThreadID;
FExecutor := AExecutor;
FExecutor._AddRef;
FreeOnTerminate := True;
FEvent := TEvent.Create(nil, False, False, '');
end;
{-------------------------------------------------------------------------------}
destructor TFDAsyncThread.Destroy;
begin
FDFreeAndNil(FEvent);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
{$WARNINGS OFF}
procedure TFDAsyncThread.WaitForLaunch;
begin
Resume;
if FEvent <> nil then
FEvent.WaitFor(1000);
end;
{$WARNINGS ON}
{-------------------------------------------------------------------------------}
procedure TFDAsyncThread.Execute;
begin
try
FExecutor.ExecuteOperation(True);
finally
FExecutor.Launched;
FExecutor.FThread := nil;
FExecutor._Release;
Sleep(1);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDStanAsyncExecutor }
{-------------------------------------------------------------------------------}
destructor TFDStanAsyncExecutor.Destroy;
begin
Cleanup;
FAsyncDlg := nil;
FWait := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDStanAsyncExecutor.GetMode: TFDStanAsyncMode;
begin
Result := FMode;
end;
{-------------------------------------------------------------------------------}
function TFDStanAsyncExecutor.GetState: TFDStanAsyncState;
begin
Result := FState;
end;
{-------------------------------------------------------------------------------}
function TFDStanAsyncExecutor.GetTimeout: Cardinal;
begin
Result := FTimeout;
end;
{-------------------------------------------------------------------------------}
function TFDStanAsyncExecutor.GetOperation: IFDStanAsyncOperation;
begin
Result := FOperationIntf;
end;
{-------------------------------------------------------------------------------}
function TFDStanAsyncExecutor.GetHandler: IFDStanAsyncHandler;
begin
Result := FHandlerIntf;
end;
{-------------------------------------------------------------------------------}
procedure TFDStanAsyncExecutor.ExecuteOperation(AStoreException: Boolean);
var
eMode: TFDStanAsyncMode;
begin
eMode := FMode;
try
try
try
FState := asExecuting;
FOperationIntf.Execute;
except
on E: Exception do begin
if FState in [asInactive, asExecuting] then
if (E is EFDDBEngineException) and (EFDDBEngineException(E).Kind = ekCmdAborted) then
FState := asAborted
else
FState := asFailed;
if AStoreException and (ExceptObject is Exception) then
FException := Exception(AcquireExceptionObject)
else
raise;
end;
end;
if FState in [asInactive, asExecuting] then
FState := asFinished;
finally
if eMode = amAsync then
if (FHandlerIntf <> nil) and AStoreException then
FHandlerIntf.HandleFinished(nil, FState, FException);
end;
finally
if eMode = amAsync then begin
Cleanup;
_Release;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDStanAsyncExecutor.Setup(const AOperation: IFDStanAsyncOperation;
const AMode: TFDStanAsyncMode; const ATimeout: Cardinal;
const AHandler: IFDStanAsyncHandler; ASilentMode: Boolean);
begin
try
ASSERT(AOperation <> nil);
FOperationIntf := AOperation;
FHandlerIntf := AHandler;
FTimeout := ATimeout;
FMode := AMode;
FState := asInactive;
FSilentMode := ASilentMode;
if FMode in [amNonBlocking, amCancelDialog] then
if FDGUIxSilent() then
FMode := amBlocking
else if FDStanActiveAsyncsWithUI > 0 then
FDException(Self, [S_FD_LStan], er_FD_StanCantNonblocking, [])
else begin
if FAsyncDlg = nil then
FDCreateInterface(IFDGUIxAsyncExecuteDialog, FAsyncDlg);
Inc(FDStanActiveAsyncsWithUI);
end;
if not FSilentMode and (FMode <> amAsync) then
if FWait = nil then
FDCreateInterface(IFDGUIxWaitCursor, FWait);
except
Cleanup;
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDStanAsyncExecutor.Cleanup;
begin
FHandlerIntf := nil;
if (FOperationIntf <> nil) and (FMode in [amNonBlocking, amCancelDialog]) then
Dec(FDStanActiveAsyncsWithUI);
FOperationIntf := nil;
FDFreeAndNil(FException);
end;
{-------------------------------------------------------------------------------}
procedure TFDStanAsyncExecutor.Run;
var
oEx: Exception;
{$IFDEF MSWINDOWS}
H: THandle;
dwRes, dwWakeMask: LongWord;
rMsg: TMsg;
{$ENDIF}
{$IFDEF POSIX}
iStartTime: Cardinal;
{$ENDIF}
begin
ASSERT(FState = asInactive);
// If command execution fails with error, and DBMS disconnects command (eg
// PostgreSQL), then Unprepare releases last reference to TFDStanAsyncExecutor.
// As result FHandlerIntf.HandleFinished raises AV. So, just around execution
// into AddRef / _Release.
_AddRef;
if (FWait <> nil) and not FSilentMode and (FMode <> amAsync) then
FWait.StartWait;
try
try
if (FMode = amBlocking) and (FTimeout = $FFFFFFFF) then
ExecuteOperation(False)
else begin
FThread := TFDAsyncThread.Create(Self);
{$IFDEF MSWINDOWS}
H := FThread.Handle;
{$ENDIF}
FThread.WaitForLaunch;
if FMode = amAsync then
Exit;
if FThread <> nil then
try
if FMode <> amBlocking then begin
if FMode = amCancelDialog then
FAsyncDlg.Show(Self);
{$IFDEF MSWINDOWS}
dwWakeMask := QS_ALLINPUT;
end
else
// Here was QS_POSTMESSAGE, but that may lead to AV. Because WM_PAINT
// is handling too and GUI is not ready when a dataset is inactive.
dwWakeMask := 0;
{$ENDIF}
{$IFDEF POSIX}
end;
{$ENDIF}
try
{$IFDEF MSWINDOWS}
while FThread <> nil do begin
dwRes := MsgWaitForMultipleObjects(1, H, False, FTimeout, dwWakeMask);
case dwRes of
WAIT_FAILED, // most probably - already terminated
WAIT_OBJECT_0:
Break;
WAIT_OBJECT_0 + 1:
while (FThread <> nil) and PeekMessage(rMsg, 0, 0, 0, PM_REMOVE) do
if rMsg.Message = WM_QUIT then begin
AbortJob;
Halt(Byte(rMsg.WParam));
end
else if (FMode = amNonBlocking) or not (
(rMsg.message >= WM_KEYDOWN) and (rMsg.message <= WM_DEADCHAR) and
((FAsyncDlg = nil) or not FAsyncDlg.IsFormActive) or
(rMsg.message >= WM_MOUSEFIRST) and (rMsg.message <= WM_MOUSELAST) and
((FAsyncDlg = nil) or not FAsyncDlg.IsFormMouseMessage(rMsg)) or
(rMsg.message >= WM_SYSKEYDOWN) and (rMsg.message <= WM_SYSDEADCHAR)
) then begin
TranslateMessage(rMsg);
DispatchMessage(rMsg);
end;
WAIT_TIMEOUT:
begin
AbortJob;
FState := asExpired;
Break;
end;
end;
end;
{$ENDIF}
{$IFDEF POSIX}
iStartTime := TThread.GetTickCount;
while (FThread <> nil) and not FThread.Finished and
not FDTimeout(iStartTime, FTimeout) do begin
Sleep(1);
end;
if (FThread <> nil) and not FThread.Finished then begin
AbortJob;
FState := asExpired;
end;
{$ENDIF}
finally
if FMode <> amBlocking then
if FMode = amCancelDialog then
FAsyncDlg.Hide;
end;
if (FException <> nil) and not (
(FException is EFDDBEngineException) and
(EFDDBEngineException(FException).Kind = ekCmdAborted) and
(FState in [asAborted, asExpired])
) then begin
FState := asFailed;
oEx := FException;
FException := nil;
raise oEx;
end
else if FState = asExpired then
FDException(Self, [S_FD_LStan], er_FD_StanTimeout, [])
else if FState = asAborted then
Abort;
except
if FState in [asInactive, asExecuting] then
FState := asFailed;
raise;
end;
if FState in [asInactive, asExecuting] then
FState := asFinished;
end;
finally
if FMode <> amAsync then begin
if (FWait <> nil) and not FSilentMode then
FWait.StopWait;
if FHandlerIntf <> nil then
FHandlerIntf.HandleFinished(nil, FState, FException);
end;
end;
finally
if FMode <> amAsync then begin
Cleanup;
_Release;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDStanAsyncExecutor.AbortJob;
begin
FState := asAborted;
if FThread <> nil then
FThread.Terminate;
if FOperationIntf <> nil then
FOperationIntf.AbortJob;
end;
{-------------------------------------------------------------------------------}
procedure TFDStanAsyncExecutor.Launched;
begin
if FThread <> nil then
FThread.FEvent.SetEvent;
end;
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
initialization
FDStanActiveAsyncsWithUI := 0;
oFact := TFDMultyInstanceFactory.Create(TFDStanAsyncExecutor, IFDStanAsyncExecutor);
finalization
FDReleaseFactory(oFact);
end.
|
unit WkeImpl;
interface
uses
SysUtils, Windows, Classes, Messages, WkeTypes, WkeIntf, WkeApi, TypInfo;
type
TWkeFileSystem = class(TInterfacedObject, IWkeFileSystem)
private
fs: TFileStream;
public
destructor Destroy; override;
function Open(const path: PUtf8): Boolean;
procedure Close;
function Size: Cardinal;
function Read(buffer: Pointer; size: Cardinal): Integer;
function Seek(offset: Integer; origin: Integer): Integer;
end;
TWke = class(TInterfacedObject, IWke)
private
FTerminate: Boolean;
FApi: TWkeAPI;
FSettings: wkeSettings;
FGlobalObjects: IWkeJsObjectList;
FOnGetFileSystem: TWkeGetFileSystemProc;
FOnGetWkeWebBase: TWkeGetWkeWebBaseProc;
FData1: Pointer;
FData2: Pointer;
private
function GetDriverName: WideString;
function GetSettings: wkeSettings;
function GetWkeVersion: WideString;
function GetGlobalObjects(): IWkeJsObjectList;
function GetData1: Pointer;
function GetData2: Pointer;
function GetOnGetFileSystem: TWkeGetFileSystemProc;
function GetOnGetWkeWebBase: TWkeGetWkeWebBaseProc;
procedure SetDriverName(const Value: WideString);
procedure SetSettings(const Value: wkeSettings);
procedure SetData1(const Value: Pointer);
procedure SetData2(const Value: Pointer);
procedure SetOnGetFileSystem(const Value: TWkeGetFileSystemProc);
procedure SetOnGetWkeWebBase(const Value: TWkeGetWkeWebBaseProc);
procedure LoadAPI;
public
constructor Create;
destructor Destroy; override;
procedure Configure(const settings: wkeSettings);
function CreateWebView(const AThis: IWkeWebBase): IWkeWebView; overload;
function CreateWebView(const AThis: IWkeWebBase; const AWebView: TWebView;
const AOwnView: Boolean = True): IWkeWebView; overload;
function CreateWebView(const AFilter: WideString = '';
const ATag: Pointer = nil): IWkeWebView; overload;
function CreateWindow(type_: wkeWindowType; parent: HWND; x, y,
width, height: Integer): IWkeWindow;
function RunAppclition(const MainWnd: HWND): Integer;
procedure ProcessMessages;
procedure Terminate;
function GetString(const str: wkeString): PUtf8;
function GetStringW(const str: wkeString): Pwchar_t;
function CreateExecState(const AExecState: JsExecState): IWkeJsExecState;
function CreateJsValue(const AExecState: JsExecState): IWkeJsValue; overload;
function CreateJsValue(const AExecState: JsExecState; const AValue: jsValue): IWkeJsValue; overload;
function CreateFileSystem(const path: PUtf8): IWkeFileSystem;
function CreateDefaultFileSystem(): IWkeFileSystem;
procedure BindFunction(const name: WideString; fn: jsNativeFunction; argCount: Integer); overload;
procedure BindFunction(es: jsExecState; const name: WideString; fn: jsNativeFunction; argCount: Integer); overload;
procedure UnbindFunction(const name: WideString); overload;
procedure UnbindFunction(es: jsExecState; const name: WideString); overload;
procedure BindGetter(const name: WideString; fn: jsNativeFunction);
procedure BindSetter(const name: WideString; fn: jsNativeFunction);
procedure BindObject(es: jsExecState; const objName: WideString; obj: TObject);
procedure UnbindObject(es: jsExecState; const objName: WideString);
function CreateJsObject(es: jsExecState; obj: TObject): jsValue;
property DriverName: WideString read GetDriverName write SetDriverName;
property Settings: wkeSettings read GetSettings write SetSettings;
property WkeVersion: WideString read GetWkeVersion;
property GlobalObjects: IWkeJsObjectList read GetGlobalObjects;
property Data1: Pointer read GetData1 write SetData1;
property Data2: Pointer read GetData2 write SetData2;
property OnGetFileSystem: TWkeGetFileSystemProc read GetOnGetFileSystem write SetOnGetFileSystem;
property OnGetWkeWebBase: TWkeGetWkeWebBaseProc read GetOnGetWkeWebBase write SetOnGetWkeWebBase;
end;
function FILE_OPEN(const path: PUtf8): Pointer; cdecl;
procedure FILE_CLOSE(handle: Pointer); cdecl;
function FILE_SIZE(handle: Pointer): size_t; cdecl;
function FILE_READ(handle: Pointer; buffer: Pointer; size: size_t): Integer; cdecl;
function FILE_SEEK(handle: Pointer; offset: Integer; origin: Integer): Integer; cdecl;
function _WindowCommand(es_: jsExecState): jsValue;
function _CallNativeFunction(es_: jsExecState): jsValue;
function _CallNativeObjectMethod(es_: jsExecState): jsValue;
function _GetNativeObjectProp(es_: jsExecState): jsValue;
function _SetNativeObjectProp(es_: jsExecState): jsValue;
function _CreateFunctionStr(es: jsExecState; const name: WideString; fn: jsNativeFunction; argCount: Integer): string;
function _CreateObjectStr(es: jsExecState; obj: TObject): string;
function _CreateObject(es: jsExecState; obj: TObject): jsValue;
const
ole32 = 'ole32.dll';
function OleInitialize(pwReserved: Pointer): HResult; stdcall; external ole32 name 'OleInitialize';
procedure OleUninitialize; stdcall; external ole32 name 'OleUninitialize';
function CoInitialize(pvReserved: Pointer): HResult; stdcall; external ole32 name 'CoInitialize';
procedure CoUninitialize; stdcall; external ole32 name 'CoUninitialize';
implementation
uses
WkeWebView, WkeJs, Variants, ObjAutoEx, WkeExportDefs;
var
varWkeDestorying: Boolean = False;
function FILE_OPEN(const path: PUtf8): Pointer; cdecl;
var
fs: IWkeFileSystem;
begin
if varWkeDestorying then
begin
Result := nil;
Exit;
end;
fs := __Wke.CreateFileSystem(path);
if fs = nil then
begin
Result := nil;
Exit;
end;
fs._AddRef;
Result := Pointer(fs);
end;
procedure FILE_CLOSE(handle: Pointer); cdecl;
var
fs: IWkeFileSystem;
begin
try
fs := IWkeFileSystem(handle);
fs.Close;
fs._Release;
fs := nil;
except
on E: Exception do
begin
Trace('[FILE_CLOSE]'+E.Message);
end
end;
end;
function FILE_SIZE(handle: Pointer): size_t; cdecl;
var
fs: IWkeFileSystem;
begin
fs := IWkeFileSystem(handle);
Result := fs.Size;
end;
function FILE_READ(handle: Pointer; buffer: Pointer; size: size_t): Integer; cdecl;
var
fs: IWkeFileSystem;
begin
Result := 0;
try
fs := IWkeFileSystem(handle);
Result := fs.read(buffer, size)
except
on E: Exception do
begin
Trace('[FILE_READ]'+E.Message);
end
end;
end;
function FILE_SEEK(handle: Pointer; offset: Integer; origin: Integer): Integer; cdecl;
var
fs: IWkeFileSystem;
begin
fs := IWkeFileSystem(handle);
Result := fs.Seek(offset, origin)
end;
function _WindowCommand(es_:jsExecState):jsValue;
var
es: IWkeJsExecState;
sCmd: string;
pView: TWebView;
LWebView: TWkeWebView;
begin
Result := WAPI.jsUndefined;
es := Wke.CreateExecState(es_);
if es.ArgCount <> 2 then
Exit;
{$IF CompilerVersion > 18.5}
sCmd := es.Arg[0].ToStringW;
{$ELSE}
sCmd := es.Arg[0].ToStringA;
{$IFEND}
pView := WAPI.jsGetWebView(es_);
LWebView := WAPI.wkeGetUserData(pView);
if LWebView = nil then
Exit;
if not IsWindow(LWebView.This.GetHwnd) then
Exit;
if sCmd = 'min' then
PostMessage(LWebView.This.GetHwnd, WM_SYSCOMMAND, SC_MINIMIZE, 0)
else
if sCmd = 'max' then
PostMessage(LWebView.This.GetHwnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0)
else
if sCmd = 'restore' then
PostMessage(LWebView.This.GetHwnd, WM_SYSCOMMAND, SC_RESTORE, 0)
else
if sCmd = 'close' then
PostMessage(LWebView.This.GetHwnd, WM_SYSCOMMAND, SC_CLOSE, 0)
else
if not IsZoomed(LWebView.This.GetHwnd) then
begin
if sCmd = 'drag' then
begin
ReleaseCapture;
PostMessage(LWebView.This.GetHwnd, WM_NCLBUTTONDOWN, HTCAPTION, 0);
end
else
if sCmd = 'hitTopleft' then
begin
ReleaseCapture;
PostMessage(LWebView.This.GetHwnd, WM_NCLBUTTONDOWN, HTTOPLEFT, 0);
end
else
if sCmd = 'hitLeft' then
begin
ReleaseCapture;
PostMessage(LWebView.This.GetHwnd, WM_NCLBUTTONDOWN, HTLEFT, 0)
end
else
if sCmd = 'hitBottomleft' then
begin
ReleaseCapture;
PostMessage(LWebView.This.GetHwnd, WM_NCLBUTTONDOWN, HTBOTTOMLEFT, 0)
end
else
if sCmd = 'hitTop' then
begin
ReleaseCapture;
PostMessage(LWebView.This.GetHwnd, WM_NCLBUTTONDOWN, HTTOP, 0)
end
else
if sCmd = 'hitBottom' then
begin
ReleaseCapture;
PostMessage(LWebView.This.GetHwnd, WM_NCLBUTTONDOWN, HTBOTTOM, 0)
end
else
if sCmd = 'hitTopright' then
begin
ReleaseCapture;
PostMessage(LWebView.This.GetHwnd, WM_NCLBUTTONDOWN, HTTOPRIGHT, 0)
end
else
if sCmd = 'hitRight' then
begin
ReleaseCapture;
PostMessage(LWebView.This.GetHwnd, WM_NCLBUTTONDOWN, HTRIGHT, 0)
end
else
if sCmd = 'hitBottomright' then
begin
ReleaseCapture;
PostMessage(LWebView.This.GetHwnd, WM_NCLBUTTONDOWN, HTBOTTOMRIGHT, 0);
end;
end;
end;
function _CallNativeFunction(es_:jsExecState):jsValue;
var
es: IWkeJsExecState;
fn: jsNativeFunction;
begin
Result := WAPI.jsUndefined;
es := Wke.CreateExecState(es_);
if es.ArgCount < 1 then
begin
Trace('[_CallNativeFunction]'+Format('参数个数[%d]小于1个!', [es.ArgCount]));
Exit;
end;
@fn := @jsNativeFunction(es.Arg[es.ArgCount - 1].ToInt);
try
Result := fn(es_);
except
on E: Exception do
begin
Trace('[_CallNativeFunction]'+E.Message);
end
end;
end;
function _CallNativeObjectMethod(es_:jsExecState):jsValue;
var
es: IWkeJsExecState;
obj: TObject;
LMethodInfoHeader: PMethodInfoHeader;
rVar: OleVariant;
LParams: array of Variant;
i: Integer;
vValue: OleVariant;
sError: string;
LReturnInfo: PReturnInfo;
LVarData: PVarData;
LObj: TObject;
begin
Result := WAPI.jsUndefined;
es := Wke.CreateExecState(es_);
if es.ArgCount < 2 then
begin
Trace('[_CallNativeObjectMethod]'+Format('参数个数[%d]小于2个!', [es.ArgCount]));
Exit;
end;
obj := TObject(es.Arg[0].ToInt);
LMethodInfoHeader := PMethodInfoHeader(es.Arg[1].ToInt);
SetLength(LParams, es.ArgCount-2);
for i := 2 to es.ArgCount-1 do
begin
if not J2V(es.ExecState, es.Arg[i].Value, vValue, sError) then
begin
Trace('[_CallNativeObjectMethod]'+Format('函数[%s]参数[%d]转换失败!', [LMethodInfoHeader.Name, i-1]));
Exit;
end;
LParams[i-2] := vValue;
end;
LReturnInfo := GetReturnInfo(LMethodInfoHeader);
rVar := ObjectInvoke(obj, LMethodInfoHeader, LParams);
if (LReturnInfo <> nil) and (LReturnInfo.ReturnType <> nil)
and (not VarIsNull(rVar)) then
begin
if LReturnInfo.ReturnType^.Kind = tkClass then
begin
LVarData := @rVar;
LObj := LVarData^.VPointer;
if LObj <> nil then
Result := _CreateObject(es_, LObj);
end
else
if not V2J(es_, rVar, Result, sError) then
begin
Trace('[_CallNativeObjectMethod]'+Format('函数[%s]返回值转换失败!', [LMethodInfoHeader.Name]));
Exit;
end;
end;
end;
function _GetNativeObjectProp(es_:jsExecState):jsValue;
var
es: IWkeJsExecState;
obj: TObject;
LPropInfo: PPropInfo;
rVar: OleVariant;
sError: string;
LVarData: PVarData;
LObj: TObject;
begin
Result := WAPI.jsUndefined;
es := Wke.CreateExecState(es_);
if es.ArgCount < 2 then
begin
Trace('[_GetNativeObjectProp]'+Format('参数个数[%d]小于2个!', [es.ArgCount]));
Exit;
end;
obj := TObject(es.Arg[0]);
LPropInfo := PPropInfo(es.Arg[1]);
{$WARNINGS OFF}
rVar := GetPropValue(obj, LPropInfo.Name);
{$WARNINGS ON}
if (LPropInfo <> nil) and (not VarIsNull(rVar)) then
begin
if LPropInfo^.PropType^.Kind = tkClass then
begin
LVarData := @rVar;
LObj := LVarData^.VPointer;
if LObj <> nil then
Result := _CreateObject(es_, LObj);
end
else
if not V2J(es_, rVar, Result, sError) then
begin
Trace('[_GetNativeObjectProp]'+Format('属性[%s]返回值转换失败!', [LPropInfo.Name]));
Exit;
end;
end;
end;
function _SetNativeObjectProp(es_:jsExecState):jsValue;
var
es: IWkeJsExecState;
obj: TObject;
LPropInfo: PPropInfo;
vValue: OleVariant;
v: jsValue;
sError: string;
begin
Result := WAPI.jsUndefined;
es := Wke.CreateExecState(es_);
if es.ArgCount < 3 then
begin
Trace('[_SetNativeObjectProp]'+Format('参数个数[%d]小于3个!', [es.ArgCount]));
Exit;
end;
obj := TObject(es.Arg[0]);
LPropInfo := PPropInfo(es.Arg[1]);
v := es.Arg[2].Value;
if not J2V(es.ExecState, v, vValue, sError) then
begin
Trace('[_SetNativeObjectProp]'+Format('属性[%s]的值转换失败!', [LPropInfo.Name]));
Exit;
end;
{$WARNINGS OFF}
SetPropValue(obj, LPropInfo.Name, vValue);
{$WARNINGS ON}
end;
function _CreateFunctionStr(es: jsExecState; const name: WideString; fn: jsNativeFunction; argCount: Integer): string;
var
lsFunc: TStrings;
sArgs: string;
iArg: Integer;
begin
sArgs := EmptyStr;
for iArg := 0 to argCount-1 do
begin
sArgs := sArgs + ' arg' + IntToStr(iArg);
if iArg < argCount-1 then
sArgs := sArgs + ',';
end;
lsFunc := TStringList.Create;
try
lsFunc.Add(Format('function %s(%s) {', [name, sArgs]));
if sArgs <> EmptyStr then
sArgs := sArgs + ',';
lsFunc.Add(Format(' return (function(%s method) {', [sArgs]));
lsFunc.Add(Format(' return _CallNativeFunction%d(%s method)', [argCount+1, sArgs]));
lsFunc.Add(Format(' })(%s %d);', [
sArgs, //-->调用参数
Integer(@fn) //-->函数指针
]));
lsFunc.Add(Format('}', []));
//lsFunc.SaveToFile('D:\\func.js');
Result := lsFunc.Text;
finally
lsFunc.Free;
end;
end;
function _CreateObjectStr(es: jsExecState; obj: TObject): string;
var
LMethodInfoArray: TMethodInfoArray;
LMethodInfoHeader, LGetMethod, LSetMethod: PMethodInfoHeader;
LPropList: PPropList;
LPropInfo: PPropInfo;
lsObj: TStrings;
iMethod, iArg, iArgCount, iPropCount, iProp: Integer;
sArgs: string;
pProp: Pointer;
begin
lsObj := TStringList.Create;
try
lsObj.Add('function _CreateNativeObject_5A5DA85372EA() {');
lsObj.Add(' var obj = {');
lsObj.Add(Format(' className: "%s", ', [obj.ClassName]));
lsObj.Add(Format(' instance: %d, ', [Integer(obj)]));
LMethodInfoArray := GetMethods(obj.ClassType);
//定义对象属性
if obj.ClassInfo <> nil then
begin
iPropCount := TypInfo.GetPropList(obj, LPropList);
try
for iProp := 0 to iPropCount-1 do
begin
LPropInfo := LPropList[iProp];
LGetMethod := nil;
LSetMethod := nil;
for iMethod := 0 to High(LMethodInfoArray) do
begin
LMethodInfoHeader := LMethodInfoArray[iMethod];
if LPropInfo^.GetProc = LMethodInfoHeader.Addr then
begin
LGetMethod := LMethodInfoHeader;
end;
if LPropInfo^.SetProc = LMethodInfoHeader.Addr then
begin
LSetMethod := LMethodInfoHeader;
end;
if (LGetMethod<>nil) and (LSetMethod<>nil) then
break;
end;
if LPropInfo^.GetProc <> nil then
begin
sArgs := EmptyStr;
iArgCount := 0;
pProp := LPropInfo;
if LGetMethod <> nil then
begin
pProp := LGetMethod;
iArgCount := GetParamCount(LGetMethod);
for iArg := 0 to iArgCount-1 do
begin
sArgs := sArgs + ' arg' + IntToStr(iArg);
if iArg < iArgCount-1 then
sArgs := sArgs + ',';
end;
end;
lsObj.Add(Format(' get %s(%s) {', [LPropInfo.Name, sArgs]));
if sArgs <> EmptyStr then
sArgs := ',' + sArgs;
lsObj.Add(Format(' return (function(obj, prop %s) {', [sArgs]));
if LGetMethod = nil then
lsObj.Add(Format(' return _GetNativeObjectProp2(obj, prop)', []))
else
lsObj.Add(Format(' return _CallNativeObjectMethod%d(obj, prop %s)', [iArgCount+2, sArgs]));
lsObj.Add(Format(' })(%d, %d %s);', [
Integer(obj), //-->对象指针
Integer(pProp), //-->属性指针
sArgs
]));
lsObj.Add(' },');
end;
if LPropInfo^.SetProc <> nil then
begin
sArgs := EmptyStr;
iArgCount := 0;
pProp := LPropInfo;
if LSetMethod <> nil then
begin
pProp := LSetMethod;
iArgCount := GetParamCount(LSetMethod);
for iArg := 0 to iArgCount-1 do
begin
sArgs := sArgs + ' arg' + IntToStr(iArg);
if iArg < iArgCount-1 then
sArgs := sArgs + ',';
end;
end;
lsObj.Add(Format(' set %s (%s) {', [LPropInfo.Name, sArgs]));
if sArgs <> EmptyStr then
sArgs := ',' + sArgs;
lsObj.Add(Format(' (function(obj, prop %s) {', [sArgs]));
if LGetMethod = nil then
lsObj.Add(Format(' _SetNativeObjectProp3(obj, prop %s)', [sArgs]))
else
lsObj.Add(Format(' _CallNativeObjectMethod%d(obj, prop %s)', [iArgCount+2, sArgs]));
lsObj.Add(Format(' })(%d, %d %s);', [
Integer(obj), //-->对象指针
Integer(pProp), //-->函数指针
sArgs
]));
lsObj.Add(' },');
end;
end;
finally
FreeMem(LPropList)
end;
end;
if lsObj.Strings[lsObj.Count - 1] = ' },' then
lsObj.Strings[lsObj.Count - 1] := ' }';
lsObj.Add(' };');
//定义对象方法
for iMethod := 0 to High(LMethodInfoArray) do
begin
LMethodInfoHeader := LMethodInfoArray[iMethod];
//函数参数
sArgs := EmptyStr;
iArgCount := GetParamCount(LMethodInfoHeader);
for iArg := 0 to iArgCount-1 do
begin
sArgs := sArgs + ' arg' + IntToStr(iArg);
if iArg < iArgCount-1 then
sArgs := sArgs + ',';
end;
//定义函数头
lsObj.Add(Format(' obj.%s = function(%s) {', [LMethodInfoHeader.Name, sArgs]));
if sArgs <> EmptyStr then
sArgs := ',' + sArgs;
lsObj.Add(Format(' return (function(obj, method %s) {', [sArgs]));
lsObj.Add(Format(' return _CallNativeObjectMethod%d(obj, method %s)', [iArgCount+2, sArgs]));
lsObj.Add(Format(' })(%d, %d %s);', [
Integer(obj), //-->对象指针
Integer(LMethodInfoHeader), //-->函数指针
sArgs //-->调用参数
]));
lsObj.Add(' }');
end;
lsObj.Add(' return obj;');
lsObj.Add('}');
// lsObj.SaveToFile('C:\\123.js');
Result := lsObj.Text;
finally
lsObj.Free;
end;
end;
function _CreateObject(es: jsExecState; obj: TObject): jsValue;
var
sObjStr: UnicodeString;
begin
sObjStr := _CreateObjectStr(es, obj);
sObjStr := sObjStr + sLineBreak +
'_CreateNativeObject_5A5DA85372EA();';
Result := WAPI.jsEvalW(es, PUnicodeChar(sObjStr));
end;
{ TWke }
constructor TWke.Create;
begin
FApi := TWkeAPI.Create;
WAPI := FApi;
FGlobalObjects := TWkeJsObjectList.Create;
end;
function TWke.CreateWebView(const AThis: IWkeWebBase): IWkeWebView;
begin
LoadAPI;
Result := TWkeWebView.Create(AThis);
end;
function TWke.CreateWebView(const AThis: IWkeWebBase; const AWebView: TWebView;
const AOwnView: Boolean): IWkeWebView;
begin
LoadAPI;
Result := TWkeWebView.Create(AThis, AWebView, AOwnView);
end;
destructor TWke.Destroy;
begin
varWkeDestorying := True;
FGlobalObjects := nil;
WAPI := nil;
if FApi <> nil then
begin
FApi.wkeSetFileSystem(nil, nil, nil, nil, nil);
FreeAndNil(FApi);
end;
inherited;
end;
function TWke.GetDriverName: WideString;
begin
Result := FApi.DriverFile;
end;
function TWke.GetWkeVersion: WideString;
begin
LoadAPI;
Result := UTF8ToWideString(FApi.wkeGetVersionString);
end;
procedure TWke.SetDriverName(const Value: WideString);
begin
FApi.DriverFile := Value;
end;
function TWke.GetString(const str: wkeString): PUtf8;
begin
LoadAPI;
Result := FApi.wkeGetString(str);
end;
function TWke.GetStringW(const str: wkeString): Pwchar_t;
begin
LoadAPI;
Result := FApi.wkeGetStringW(str);
end;
procedure TWke.LoadAPI;
var
i: Integer;
begin
if varWkeDestorying then
Exit;
if not FApi.Loaded then
begin
FApi.LoadDLL();
if @FApi.wkeSetFileSystem <> nil then
FApi.wkeSetFileSystem(FILE_OPEN, FILE_CLOSE, FILE_SIZE, FILE_READ, FILE_SEEK);
if @FApi.jsBindFunction <> nil then
begin
for i := 1 to 256 do
FApi.jsBindFunction(PAnsiChar(AnsiString('_CallNativeFunction'+IntToStr(i))), @_CallNativeFunction, i);
for i := 2 to 256 do
FApi.jsBindFunction(PAnsiChar(AnsiString('_CallNativeObjectMethod'+IntToStr(i))), @_CallNativeObjectMethod, i);
for i := 2 to 10 do
FApi.jsBindFunction(PAnsiChar(AnsiString('_GetNativeObjectProp'+IntToStr(i))), @_GetNativeObjectProp, i);
for i := 2 to 10 do
FApi.jsBindFunction(PAnsiChar(AnsiString('_SetNativeObjectProp'+IntToStr(i))), @_SetNativeObjectProp, i);
BindFunction('WindowCommand', @_WindowCommand, 1);
end;
end;
end;
function TWke.GetOnGetFileSystem: TWkeGetFileSystemProc;
begin
Result := FOnGetFileSystem;
end;
procedure TWke.SetOnGetFileSystem(const Value: TWkeGetFileSystemProc);
begin
FOnGetFileSystem := Value;
end;
function TWke.CreateDefaultFileSystem(): IWkeFileSystem;
begin
LoadAPI;
Result := TWkeFileSystem.Create;
end;
function TWke.CreateFileSystem(const path: PUtf8): IWkeFileSystem;
var
bHandled: Boolean;
begin
LoadAPI;
Result := nil;
if @FOnGetFileSystem <> nil then
begin
bHandled := False;
Result := FOnGetFileSystem(path, bHandled);
if bHandled then
Exit;
end;
if Result = nil then
Result := CreateDefaultFileSystem;
if not Result.Open(path) then
Result := nil;
end;
function TWke.CreateExecState(
const AExecState: JsExecState): IWkeJsExecState;
begin
LoadAPI;
Result := TWkeJsExecState.Create(AExecState);
end;
function TWke.CreateJsValue(const AExecState: JsExecState): IWkeJsValue;
begin
LoadAPI;
Result := TWkeJsValue.Create(AExecState);
end;
function TWke.CreateJsValue(const AExecState: JsExecState;
const AValue: jsValue): IWkeJsValue;
begin
LoadAPI;
Result := TWkeJsValue.Create(AExecState, AValue);
end;
procedure TWke.BindFunction(const name: WideString; fn: jsNativeFunction;
argCount: Integer);
begin
LoadAPI;
GlobalFunction.AddObject(name+'='+IntToStr(argCount), TObject(@fn));
// WAPI.jsBindFunction(PAnsiChar(AnsiString(name)), fn, argCount);
end;
procedure TWke.BindGetter(const name: WideString; fn: jsNativeFunction);
begin
LoadAPI;
WAPI.jsBindGetter(PAnsiChar(AnsiString(name)), fn);
end;
procedure TWke.BindSetter(const name: WideString; fn: jsNativeFunction);
begin
LoadAPI;
WAPI.jsBindSetter(PAnsiChar(AnsiString(name)), fn);
end;
procedure TWke.BindObject(es: jsExecState; const objName: WideString; obj: TObject);
var
sObjStr: UnicodeString;
begin
LoadAPI;
sObjStr := _CreateObjectStr(es, obj);
sObjStr := sObjStr + sLineBreak +
Format('var %s = _CreateNativeObject_5A5DA85372EA();', [objName]);
WAPI.jsEvalW(es, PUnicodeChar(sObjStr));
end;
procedure TWke.BindFunction(es: jsExecState; const name: WideString;
fn: jsNativeFunction; argCount: Integer);
var
sFuncStr: UnicodeString;
begin
LoadAPI;
//WAPI.jsBindFunction(PAnsiChar(AnsiString(name)), fn, argCount);
sFuncStr := _CreateFunctionStr(es, name, fn, argCount);
WAPI.jsEvalW(es, PUnicodeChar(sFuncStr));
end;
procedure TWke.UnbindObject(es: jsExecState; const objName: WideString);
begin
{$IF CompilerVersion > 18.5 }
WAPI.jsEvalW(es, PUnicodeChar(Format('%s = null;', [objName])));
{$ELSE}
WAPI.jsEvalW(es, PUnicodeChar(WideFormat('%s = null;', [objName])));
{$IFEND}
end;
procedure TWke.UnbindFunction(es: jsExecState; const name: WideString);
begin
//WAPI.jsBindFunction(PAnsiChar(AnsiString(name)), nil, 0);
{$IF CompilerVersion > 18.5 }
WAPI.jsEvalW(es, PUnicodeChar(Format('%s = null;', [name])));
{$ELSE}
WAPI.jsEvalW(es, PUnicodeChar(WideFormat('%s = null;', [name])));
{$IFEND}
end;
function TWke.GetGlobalObjects: IWkeJsObjectList;
begin
Result := FGlobalObjects;
end;
function TWke.GetData1: Pointer;
begin
Result := FData1;
end;
function TWke.GetData2: Pointer;
begin
Result := FData2;
end;
procedure TWke.SetData1(const Value: Pointer);
begin
FData1 := Value;
end;
procedure TWke.SetData2(const Value: Pointer);
begin
FData2 := Value;
end;
function TWke.GetOnGetWkeWebBase: TWkeGetWkeWebBaseProc;
begin
Result := FOnGetWkeWebBase;
end;
procedure TWke.SetOnGetWkeWebBase(const Value: TWkeGetWkeWebBaseProc);
begin
FOnGetWkeWebBase := Value;
end;
function TWke.CreateWebView(const AFilter: WideString;
const ATag: Pointer): IWkeWebView;
var
LWebBase: IWkeWebBase;
begin
if @FOnGetWkeWebBase = nil then
raise EWkeException.Create('OnGetWkeWebBase event not be assigned!');
LWebBase := FOnGetWkeWebBase(AFilter, ATag);
if LWebBase = nil then
raise EWkeException.CreateFmt('OnGetWkeWebBase event Cannot find IWkeWebBase instance which match filter:%s!', [AFilter]);
Result := CreateWebView(LWebBase);
end;
function TWke.CreateJsObject(es: jsExecState; obj: TObject): jsValue;
begin
LoadAPI;
Result := _CreateObject(es, obj)
end;
procedure TWke.UnbindFunction(const name: WideString);
var
i: Integer;
begin
i := GlobalFunction.IndexOfName(name);
if i > 0 then
GlobalFunction.Delete(i);
end;
function TWke.GetSettings: wkeSettings;
begin
Result := FSettings;
end;
procedure TWke.SetSettings(const Value: wkeSettings);
begin
FSettings := Value;
WAPISettings := @FSettings;
end;
procedure TWke.Configure(const settings: wkeSettings);
begin
LoadAPI;
WAPI.wkeConfigure(@settings);
end;
function TWke.CreateWindow(type_: wkeWindowType; parent: HWND; x, y, width,
height: Integer): IWkeWindow;
begin
LoadAPI;
Result := TWkeWindow.Create(type_, parent, x, y, width, height);
end;
function TWke.RunAppclition(const MainWnd: HWND): Integer;
var
msg: TMsg;
begin
while (not FTerminate) and (MainWnd<>0) and IsWindow(MainWnd) do
begin
if not GetMessage(msg, 0, 0, 0) then
break;
Windows.TranslateMessage(msg);
Windows.DispatchMessage(msg);
end;
Result := msg.wParam;
end;
procedure TWke.ProcessMessages;
function _ProcessMessage(var Msg: TMsg): Boolean;
begin
Result := False;
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
Result := True;
if Msg.Message <> WM_QUIT then
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end
else
FTerminate := True;
end;
end;
var
Msg: TMsg;
begin
while _ProcessMessage(Msg) do {loop};
end;
procedure TWke.Terminate;
begin
FTerminate := True;
PostQuitMessage(0);
end;
{ TWkeFileSystem }
procedure TWkeFileSystem.Close;
begin
try
if fs <> nil then
FreeAndNil(fs);
except
on E: Exception do
begin
Trace('[TWkeFileSystem.Close]'+E.Message);
end
end;
end;
destructor TWkeFileSystem.Destroy;
begin
Close;
inherited;
end;
function TWkeFileSystem.Open(const path: PUtf8): Boolean;
var
s: UnicodeString;
begin
Close;
Result := False;
try
s := {$IF CompilerVersion > 18.5}UTF8ToString{$ELSE}UTF8Decode{$IFEND}(path);
if Pos(':', s) <= 0 then
s := CurrentLoadDir + s;
fs := TFileStream.Create(s, fmOpenRead);
Result := True;
except
on E: Exception do
begin
Trace('[TWkeFileSystem.Open]'+E.Message);
end
end;
end;
function TWkeFileSystem.Read(buffer: Pointer; size: Cardinal): Integer;
begin
Result := 0;
try
if fs = nil then
Exit;
Result := fs.read(buffer^, size)
except
on E: Exception do
begin
Trace('[TWkeFileSystem.Read]'+E.Message);
end
end;
end;
function TWkeFileSystem.Seek(offset, origin: Integer): Integer;
begin
if fs <> nil then
Result := fs.Seek(offset, origin)
else
Result := 0
end;
function TWkeFileSystem.Size: Cardinal;
begin
if fs <> nil then
Result := fs.Size
else
Result := 0;
end;
initialization
// OleInitialize(nil);
// CoInitialize(nil);
finalization
// CoUninitialize;
// OleUninitialize;
end.
|
unit ncPrinters;
interface
uses
classes,SysUtils;
type
TncPrinter = class(TObject)
id : integer;
nome : string;
impressora : string;
precopp : double;
Orientation : string;
PaperSizeName : string;
PaperSizeShortName : string;
DefaultSourceDesc : string;
PrintQuality : string;
Color : string;
Duplex : string;
end;
TncPhysicalPrinter = class(TObject)
PrinterIndex : integer;
nome : string;
Orientation : string;
PaperSizeDesc : string;
DefaultSourceDesc : string;
PrintQuality : string;
Color : string;
Duplex : string;
PHYSICALWIDTH : integer;
PHYSICALHEIGHT : integer;
PHYSICALOFFSETX : integer;
PHYSICALOFFSETY : integer;
HORZRES : integer;
VERTRES : integer;
LOGPIXELSX : integer;
LOGPIXELSY : integer;
end;
TncPrinterList = class(TList)
protected
function Get(Index: Integer): TncPrinter;
procedure Put(Index: Integer; Item: TncPrinter);
public
function exists(aName:string): boolean;
function add(aName:string): TncPrinter; overload;
function add(aPrinter:TncPrinter): TncPrinter; overload;
function byId(aIdPrinter:Integer): TncPrinter;
procedure Clear; override;
property Items[Index: Integer]: TncPrinter read Get write Put; default;
destructor Destroy; override;
end;
TncPhysicalPrinterList = class(TList)
protected
function Get(Index: Integer): TncPhysicalPrinter;
procedure Put(Index: Integer; Item: TncPhysicalPrinter);
public
function exists(aName:string): boolean;
function add(aName:string): TncPhysicalPrinter; overload;
function add(aPrinter:TncPhysicalPrinter): TncPhysicalPrinter; overload;
procedure Clear; override;
property Items[Index: Integer]: TncPhysicalPrinter read Get write Put; default;
destructor Destroy; override;
end;
implementation
{ TncPrinterList }
function TncPrinterList.add(aName: string): TncPrinter;
begin
result := nil;
if exists(aName) then exit;
result := TncPrinter.Create;
result.nome := aName;
inherited add(result);
end;
function TncPrinterList.add(aPrinter: TncPrinter): TncPrinter;
begin
result := nil;
if exists(aPrinter.nome) then exit;
inherited add(aPrinter);
result := aPrinter;
end;
function TncPrinterList.byId(aIdPrinter: Integer): TncPrinter;
var
i : integer;
begin
result := nil;
for i:=0 to count-1 do
if aIdPrinter=items[i].id then begin
result := items[i];
break;
end;
end;
procedure TncPrinterList.Clear;
var
i : integer;
begin
for i:=count-1 downto 0 do
TncPrinter(items[i]).free;
inherited;
end;
destructor TncPrinterList.Destroy;
begin
Clear;
inherited;
end;
function TncPrinterList.exists(aName: string): boolean;
var
i : integer;
begin
result := false;
for i:=0 to count-1 do
if sametext(aName, items[i].nome ) then begin
result := true;
break;
end;
end;
function TncPrinterList.Get(Index: Integer): TncPrinter;
begin
result := TncPrinter(inherited Get(Index));
end;
procedure TncPrinterList.Put(Index: Integer; Item: TncPrinter);
begin
inherited Put(Index, Item);
end;
{ TncPhysicalPrinterList }
function TncPhysicalPrinterList.add(aName: string): TncPhysicalPrinter;
begin
result := nil;
if exists(aName) then exit;
result := TncPhysicalPrinter.Create;
result.nome := aName;
inherited add(result);
end;
function TncPhysicalPrinterList.add(aPrinter: TncPhysicalPrinter): TncPhysicalPrinter;
begin
result := nil;
if exists(aPrinter.nome) then exit;
inherited add(aPrinter);
result := aPrinter;
end;
procedure TncPhysicalPrinterList.Clear;
var
i : integer;
begin
for i:=count-1 downto 0 do
TncPhysicalPrinter(items[i]).free;
inherited;
end;
destructor TncPhysicalPrinterList.Destroy;
begin
Clear;
inherited;
end;
function TncPhysicalPrinterList.exists(aName: string): boolean;
var
i : integer;
begin
result := false;
for i:=0 to count-1 do
if sametext(aName, items[i].nome ) then begin
result := true;
break;
end;
end;
function TncPhysicalPrinterList.Get(Index: Integer): TncPhysicalPrinter;
begin
result := TncPhysicalPrinter(inherited Get(Index));
end;
procedure TncPhysicalPrinterList.Put(Index: Integer; Item: TncPhysicalPrinter);
begin
inherited Put(Index, Item);
end;
end.
|
unit TestgCore;
{
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, Classes,gCore, System.Rtti, Windows,
gWebServerController,
gWebUI,
Xml.XMLDoc,
Xml.XMLDom,
Xml.XMLIntf;
type
TIDObject3 = class;
TIDObject2 = class;
// Test methods for class TgBase
/// <summary>
/// This is a example structure which will automaticly limit all
/// assignements to the first 5 characters of the text
/// </summary>
TgString5 = record
strict private
FValue: String;
public
FUNCTION GetValue: String;
procedure SetValue(const AValue: String);
class operator implicit(AValue: Variant): TgString5; overload;
class operator Implicit(AValue: TgString5): Variant; overload;
property Value: String read GetValue write SetValue;
end;
ValidatePhone = class(Validation)
public
procedure Execute(AObject: TgObject; ARTTIProperty: TRttiProperty); override;
end;
/// <summary>
/// This is a example which should automaticly format any value assigned
/// into a phone number
/// </summary>
[ValidatePhone]
TPhoneString = record
strict private
FValue: String;
public
function FormatPhone(AValue : String): String;
function GetValue: String;
procedure SetValue(const AValue: String);
class operator Implicit(AValue: TPhoneString): Variant; overload;
class operator Implicit(AValue: Variant): TPhoneString; overload;
property Value: String read GetValue write SetValue;
end;
TBase2 = class(TgObject)
strict private
FIntegerProperty: Integer;
FStringProperty: TgString5;
published
[DefaultValue(2)]
property IntegerProperty: Integer read FIntegerProperty write FIntegerProperty;
[DefaultValue('12345')]
property StringProperty: TgString5 read FStringProperty write FStringProperty;
End;
TBase2List = Class(TgList<TBase2>)
End;
TBase3 = Class(TBase2)
strict private
FList: TBase2List;
FName: String;
published
property Name: String read FName write FName;
property List: TBase2List read FList;
End;
TBase4 = class(TgBase)
public
type
TBase = class(TgIDObject)
end;
strict private
FBase2: TBase2;
FBase: TBase;
published
property Base2: TBase2 read FBase2;
property Base: TBase read FBase;
end;
TBase = class(TgObject)
public
type
TEnum = (be,beLast,beHello);
strict private
FEnum: TEnum;
FBooleanProperty: Boolean;
FDateProperty: TDate;
FDateTimeProperty: TDateTime;
FIntegerProperty: Integer;
FManuallyConstructedObjectProperty: TBase;
FObjectProperty: TBase2;
FPhone: TPhoneString;
FString5: TgString5;
FStringProperty: String;
FUnconstructedObjectProperty: TgBase;
FUnreadableIntegerProperty: Integer;
FUnwriteableIntegerProperty: Integer;
function GetManuallyConstructedObjectProperty: TBase;
public
destructor Destroy; override;
published
procedure SetUnwriteableIntegerProperty;
property BooleanProperty: Boolean read FBooleanProperty write FBooleanProperty;
[Required]
property DateProperty: TDate read FDateProperty write FDateProperty;
[Required]
property DateTimeProperty: TDateTime read FDateTimeProperty write FDateTimeProperty;
property Enum: TEnum read FEnum write FEnum;
[DefaultValue(5)] [Required]
property IntegerProperty: Integer read FIntegerProperty write FIntegerProperty;
property ManuallyConstructedObjectProperty: TBase read GetManuallyConstructedObjectProperty;
[Required]
property ObjectProperty: TBase2 read FObjectProperty;
[DefaultValue('Test')] [NotSerializable] [NotAssignable] [Required]
property StringProperty: String read FStringProperty write FStringProperty;
[NotAutoCreate]
property UnconstructedObjectProperty: TgBase read FUnconstructedObjectProperty write FUnconstructedObjectProperty;
property UnreadableIntegerProperty: Integer write FUnreadableIntegerProperty;
property UnwriteableIntegerProperty: Integer read FUnwriteableIntegerProperty;
[Required]
property String5: TgString5 read FString5 write FString5;
property Phone: TPhoneString read FPhone write FPhone;
end;
TestTBase = class(TTestCase)
strict private
Base: TBase;
const _ExpectedCommonAppData = 'C:\ProgramData\';
public
procedure PathEndsWithAnObjectProperty;
procedure PathExtendsBeyondOrdinalProperty;
procedure PropertyNotReadable;
procedure PropertyNotWriteable;
procedure SetPathEndsWithAnObjectProperty;
procedure SetPathExtendsBeyondOrdinalProperty;
procedure SetUndeclaredProperty;
procedure SetUp; override;
procedure TearDown; override;
procedure UndeclaredProperty;
published
procedure Location;
procedure GetValue;
procedure SetValue;
procedure Assign;
procedure DeserializeXML;
procedure DeserializeJSON;
procedure DeserializeCSV;
procedure SerializeXML;
procedure SerializeJSON;
procedure SerializeCSV;
procedure TestCreate;
procedure ValidateRequired;
procedure PathValue;
end;
TestTBase4 = class(TTestCase)
protected
FBase4: TBase4;
procedure SetUp; override;
procedure TearDown; override;
published
end;
TestTgString5 = class(TTestCase)
published
procedure TestLength;
end;
TestTgOriginalValues = class(TTestCase)
public
type
TItem = class(TgBase)
private
FBool: Boolean;
FInt: Integer;
FName: String;
published
property Bool: Boolean read FBool write FBool;
property Int: Integer read FInt write FInt;
property Name: String read FName write FName;
end;
protected
FOriginalValues: TgOriginalValues;
procedure SetUp; override;
procedure TearDown; override;
published
procedure Test;
end;
TestTBase2List = class(TTestCase)
strict private
FBase2List: TBase2List;
procedure Add3;
public
procedure CurrentOnEmptyList;
procedure DeleteFromEmptyList;
procedure GetItemInvalidIndex;
procedure SetItemInvalidIndex;
procedure GetValueInvalidIndex;
procedure NextPastEOL;
procedure PreviousBeforeBOL;
procedure SetValueInvalidIndex;
procedure SetCurrentIndexTooHigh;
procedure SetCurrentIndexTooLow;
procedure SetUp; override;
procedure TearDown; override;
published
procedure Add;
procedure Assign;
procedure BOL;
procedure EOL;
procedure CanAdd;
procedure CanNext;
procedure CanPrevious;
procedure Clear;
procedure Count;
procedure Current;
procedure CurrentIndex;
procedure Delete;
procedure First;
procedure GetItem;
procedure SetItem;
procedure Last;
procedure GetValue;
procedure HasItems;
procedure ItemClass;
procedure Next;
procedure Previous;
procedure SerializeXML;
procedure SerializeJSON;
procedure SerializeCSV;
procedure DeserializeXML;
procedure DeserializeJSON;
procedure DeserializeCSV;
procedure Filter;
procedure SetValue;
procedure Sort;
procedure TestCreate(BOL: Integer; const Value: string);
end;
TIdentityObject = class(TgIDObject)
strict private
FName: String;
published
[Required]
property Name: String read FName write FName;
end;
TestTIdentityObject = class(TTestCase)
strict private
FIdentityObject: TIdentityObject;
public
procedure SaveWithoutName;
procedure SetUp; override;
procedure TearDown; override;
published
procedure Delete;
procedure Save;
end;
TIdentityObjectList = class(TgIdentityList<TIdentityObject>)
end;
TestTIdentityObjectList = class(TTestCase)
strict private
FIdentityObjectList: TIdentityObjectList;
procedure Add3;
public
procedure CurrentOnEmptyList;
procedure SetUp; override;
procedure TearDown; override;
published
procedure ForInEmpty;
procedure Add;
procedure BOL;
procedure EOL;
procedure Count;
procedure Current;
procedure Delete;
procedure DeserializeJSON;
procedure DeserializeXML;
procedure DeserializeCSV;
procedure Filter;
procedure SerializeJSON;
procedure SerializeXML;
procedure SerializeCSV;
end;
TestTBase3 = class(TTestCase)
strict private
Base3: TBase3;
procedure Add3;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure SerializeXML;
procedure SerializeCSV;
procedure DeserializeXML;
procedure DeserializeCSV;
end;
TIDObject = class(TgIDObject)
strict private
FName: String;
FName2: String;
published
property Name: String read FName write FName;
property Name2: String read FName2 write FName2;
end;
TestTIDObject = class(TTestCase)
strict private
IDObject: TIDObject;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure Save;
procedure SaveChanges;
end;
TIDObject3 = class(TgIDObject)
strict private
FIDObject2: TIDObject2;
FName: String;
published
property IDObject2: TIDObject2 read FIDObject2;
property Name: String read FName write FName;
end;
TIDObject2 = class(TgIDObject)
strict private
FIDObject: TIDObject;
FIDObjects: TgIdentityList<TIDObject3>;
FName: String;
published
property Name: String read FName write FName;
property IDObject: TIDObject read FIDObject;
property IDObjects: TgIdentityList<TIDObject3> read FIDObjects;
end;
TestTIDObject2 = class(TTestCase)
strict private
FIDObject: TIDObject;
FIDObject2: TIDObject2;
protected
procedure SetUp; override;
procedure TearDown; override;
public
procedure Add3Items;
published
procedure ExtendedWhere;
procedure Save;
procedure SaveItem;
end;
(*
TestTgNodeCSV = class(TTestCase)
protected
FNode: TgNodeCSV;
procedure SetUp; override;
procedure TearDown; override;
published
procedure ColumnName;
procedure NestedColumnName;
end;
*)
TestTSerializeCSV = class(TTestCase)
public
type
TgName = class(TgBase)
private
FName: String;
published
property Name: String read FName write FName;
end;
TgTest = class(TgBase)
private
FName: String;
FPrice: Currency;
FNames: TgList<TgName>;
public
constructor Create(AOwner: TgBase = nil); override;
published
property Name: String read FName write FName;
property Price: Currency read FPrice write FPrice;
property Names: TgList<TgName> read FNames write FNames;
end;
protected
FSerializer: TgSerializerCSV;
procedure SetUp; override;
procedure TearDown; override;
published
procedure Serialize;
procedure Deserialize;
procedure DeserializeArr;
procedure SerializeList;
procedure DeserializeList;
procedure SerializeCRLF;
procedure DeserializeCRLF;
end;
TestHTMLParser = class(TTestCase)
public
type
TEnum1 = (e,ePurse,eBag,eWallet);
TEnum2 = (d,dCalifornia,dDallas,dAustin,dTexas,dAlisoViejo,dShreveport);
TStr20 = string[20];
TEnumSet1 = set of TEnum1;
TEnumSet2 = set of TEnum2;
TCustomer = class(TgObject)
private
FBoolField: Boolean;
FEnum1: TEnum1;
FFirstName: TStr20;
FLastName: TString50;
FWebAddress: TgWebAddress;
FGoodCustomer: Boolean;
FOtherCustomer: TCustomer;
FWebContent: TgHTMLString;
FNotes: String;
FEnum2: TEnum2;
FEnumSet1: TEnumSet1;
FEnumSet2: TEnumSet2;
FIntValue: Integer;
FMiddleInitial: Char;
FSingleValue: Single;
FFileName: TgFileName;
function GetFullName: String;
published
procedure ClickIt;
property BoolField: Boolean read FBoolField write FBoolField;
property Enum1: TEnum1 read FEnum1 write FEnum1;
property Enum2: TEnum2 read FEnum2 write FEnum2;
property EnumSet1: TEnumSet1 read FEnumSet1 write FEnumSet1;
property EnumSet2: TEnumSet2 read FEnumSet2 write FEnumSet2;
property FirstName: TStr20 read FFirstName write FFirstName;
property MiddleInitial: Char read FMiddleInitial write FMiddleInitial;
property LastName: TString50 read FLastName write FLastName;
property FullName: String read GetFullName;
property WebAddress: TgWebAddress read FWebAddress write FWebAddress;
property Notes: String read FNotes write FNotes;
property WebContent: TgHTMLString read FWebContent write FWebContent;
property GoodCustomer: Boolean read FGoodCustomer write FGoodCustomer;
property IntValue: Integer read FIntValue write FIntValue;
property OtherCustomer: TCustomer read FOtherCustomer write FOtherCustomer;
property SingleValue: Single read FSingleValue write FSingleValue;
property FileName: TgFileName read FFileName write FFileName;
end;
TCustomers = TgList<TCustomer>;
TModel = class(TgModel)
private
FCustomers: TCustomers;
published
property Customers: TCustomers read FCustomers;
end;
published
procedure Replace;
procedure Convert1;
procedure ListTag;
procedure IncludeTag;
procedure AssignTag;
procedure WithTag;
procedure ifTag;
procedure HTMLField;
procedure gForm;
end;
[PersistenceManagerClassName('gCore.TgPersistenceManagerIBX')]
TFirebirdObject = class(TgIDObject)
strict private
FName: TString50;
published
property Name: TString50 read FName write FName;
end;
TestTFirebirdObject = class(TTestCase)
strict private
FFirebirdObject: TFirebirdObject;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure Save;
end;
TestEvalHTML = class(TTestCase)
type
TTest = class(TgBase)
strict private
FHTMLString: TgHTMLString;
FNonHTMLString: String;
Published
property HTMLString: TgHTMLString read FHTMLString write FHTMLString;
property NonHTMLString: String read FNonHTMLString write FNonHTMLString;
end;
strict private
TestObject: TTest;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure Eval;
end;
TestMemo = class(TTestCase)
public
type
TTest = class(TgBase)
private
FMemo: TgMemo;
published
property Memo: TgMemo read FMemo write FMemo;
end;
published
procedure Test;
end;
TestClassProperty = class(TTestCase)
public
type
TTest = class(TgBase)
private
FBaseClass: TgBaseClass;
published
property BaseClass: TgBaseClass read FBaseClass write FBaseClass;
end;
published
procedure Test;
end;
TestWebCookie = class(TTestCase)
published
procedure Test;
end;
TestTgDictionary = class(TTestCase)
public
type
TMy = class(TgDictionary)
private
FName: String;
published
property Name: String read FName write FName;
end;
protected
FMy: TMy;
procedure SetUp; override;
procedure TearDown; override;
published
procedure CheckPaths;
end;
TestTgWebServerController = class(TTestCase)
public
type
TWireRims = class(TgIdentityObject)
private
FFirstName: String;
FLastName: String;
published
property LastName: String read FLastName write FLastName;
property FirstName: String read FFirstName write FFirstName;
end;
TModel = class(TgModel)
private
FCustomers: TgIdentityList<TWireRims>;
function GetFirstName: string;
published
property Customers: TgIdentityList<TWireRims> read FCustomers;
property FirstName: string read GetFirstName;
end;
protected
FWebServerController: TgWebServerController;
const DefaulthtmlContent = '<html><body>{FirstName}!</body></html>';
const DefaulthtmContent = '<html><body>{Name}, hello!</body></html>';
const WebConfigurationDataContent = '';
procedure SetUp; override;
procedure TearDown; override;
published
procedure DefaultConfig;
procedure TestNoModel;
procedure TestModel;
procedure TestRest;
end;
TestTgWebUI = class(TTestCase)
protected
procedure SetUp; override;
procedure TearDown; override;
public
type
TEnum1 = (h,hPurse,hCar,hTelephone);
TEnumSet1 = set of TEnum1;
TEnum2 = (f,fCalifornia,fDallas,fAustin,fTexas,fAlisoViejo,fShreveport);
// [BooleanLabel('Off','On')] // Generated AV in RTTI unit
// TOffOn = type boolean;
TOffOn = boolean;
// [BooleanLabel('Off','On')]
// TX = type boolean;
TX = boolean;
TStr10 = string[10];
TOtherObject = class(TgBase)
end;
TMyClass = class(TgBase)
private
FAnsiCharValue: AnsiChar;
FBool: Boolean;
FBool2: Boolean;
FCharValue: Char;
FCurrencyValue: Currency;
FDoubleValue: Double;
FEnum2: TEnum2;
FExtendedValue: Extended;
FInvisible: String;
FHTML: TgHTMLString;
FInt: Integer;
FSingleValue: Single;
FFileName: TgFileName;
FString50: TString50;
FSingleDisplay: Single;
FText: string;
FXBool: TX;
FImage: TgImage;
FOffOn: TOffOn;
FStr10: TStr10;
FEmailAddress: TgEmailAddress;
FWebAddress: TgWebAddress;
FOtherObject: TOtherObject;
FEnum1: TEnum1;
FEnumSet1: TEnumSet1;
published
[Help('This is the help')]
procedure CheckIt;
property Bool: Boolean read FBool write FBool;
property ReadBool: Boolean read FBool;
[NotVisible]
property NotVisibleBool: Boolean read FBool write FBool;
[DisplayOnly]
property DisplayOnlyBool: Boolean read FBool write FBool;
property OffOnBool: TOffOn read FOffOn;
[BooleanLabel('No','Yes')]
property NoYesBool: boolean read FBool;
property XBool: TX read FXBool;
property AnsiCharValue: AnsiChar read FAnsiCharValue write FAnsiCharValue;
property FileName: TgFileName read FFileName write FFileName;
property Image: TgImage read FImage write FImage;
property EmailAddress: TgEmailAddress read FEmailAddress write FEmailAddress;
property WebAddress: TgWebAddress read FWebAddress write FWebAddress;
property OtherObject: TOtherObject read FOtherObject; // Select
// Composite identity object
property Bool2: Boolean read FBool2 write FBool2;
property CharValue: Char read FCharValue write FCharValue;
property CurrencyValue: Currency read FCurrencyValue write FCurrencyValue;
property DoubleValue: Double read FDoubleValue write FDoubleValue;
property Enum1: TEnum1 read FEnum1 write FEnum1;
property EnumSet1: TEnumSet1 read FEnumSet1 write FEnumSet1;
property Enum2: TEnum2 read FEnum2 write FEnum2;
property ExtendedValue: Extended read FExtendedValue write FExtendedValue;
property HTMLText: TgHTMLString read FHTML write FHTML;
property Int: Integer read FInt write FInt;
property SingleValue: Single read FSingleValue write FSingleValue;
[DisplayOnly]
[FormatFloat(',.00')]
property SingleDisplay: Single read FSingleDisplay write FSingleDisplay;
property String50: TString50 read FString50 write FString50;
[Caption('My Text')]
property Text: string read FText write FText;
property Str10: TStr10 read FStr10 write FStr10;
[NotVisible]
[Caption('Invisible Value')]
property Invisible: string read FInvisible write FInvisible;
end;
TMyClass2 = class(TMyClass)
[Visible]
[Caption('Visible Value')]
property Invisible;
end;
TMyModel = class(TgModel)
public
type
TCustomer = class(TgIDObject)
private
FFirstName: string;
FGoodCustomer: Boolean;
FInt: Integer;
FLastName: string;
FReadEMail: Boolean;
FTitle: String;
published
[ListColumn(1)] // Default takes the first non object property
property FirstName: string read FFirstName write FFirstName;
[ListColumn(0)]
property LastName: string read FLastName write FLastName;
property GoodCustomer: Boolean read FGoodCustomer write FGoodCustomer;
property Int: Integer read FInt write FInt;
[DefaultValue('Salesperson')]
property Title: String read FTitle write FTitle;
[PathQuery]
property ReadEMail: Boolean read FReadEMail write FReadEMail;
end;
TCustomers = TgIdentityList<TCustomer>;
TBillingAddress = class(TgObject)
private
FAddress: String;
published
property Address: String read FAddress write FAddress;
end;
TShippingAddress = class(TgIDObject)
private
FAddress: String;
published
property Address: String read FAddress write FAddress;
end;
TCustomer2 = class(TgIDObject)
private
FBillingAddress: TBillingAddress;
FFirstName: string;
FLastName: string;
FShippingAddress: TShippingAddress;
function GetOriginalValues: TCustomer2; {$IFNDEF DEBUG}inline;{$ENDIF}
published
property BillingAddress: TBillingAddress read FBillingAddress;
// Default takes the first non object property
property FirstName: string read FFirstName write FFirstName;
property LastName: string read FLastName write FLastName;
property ShippingAddress: TShippingAddress read FShippingAddress;
[NotAutoCreate] [NotComposite] [NotSerializable] [NotAssignable] [NotVisible]
property OriginalValues: TCustomer2 read GetOriginalValues;
end;
TObjectProperty = class(TgIDObject)
private
FMyObject: TCustomer2;
published
property MyObject: TCustomer2 read FMyObject;
end;
TExhibitor = class;
TShow = class;
TExhibitorShow = class(TgIDObject)
private
FExhibitor: TExhibitor;
FShow: TShow;
published
property Exhibitor: TExhibitor read FExhibitor;
property Show: TShow read FShow;
end;
TShow = class(TgIDObject)
private
FExhibitors: TgIdentityList<TExhibitorShow>;
FName: string;
published
property Name: string read FName write FName;
property Exhibitors: TgIdentityList<TExhibitorShow> read FExhibitors;
end;
TExhibitor = class(TgIDObject)
private
FName: string;
FShows: TgIdentityList<TExhibitorShow>;
published
property Name: string read FName write FName;
property Shows: TgIdentityList<TExhibitorShow> read FShows;
end;
TShows = TgIdentityList<TShow>;
TExhibitors = TgIdentityList<TExhibitor>;
private
FCustomer: TCustomer;
FCustomer2: TCustomer2;
FCustomers: TCustomers;
FList1: TgList<TCustomer>;
FList2: TgList<TCustomer>;
FList3: TgList<TCustomer2>;
FList4: TgList<TObjectProperty>;
FShows: TShows;
FExhibitors: TExhibitors;
FName: String;
published
[Columns('LastName,FirstName')]
property List1: TgList<TCustomer> read FList1;
property List2: TgList<TCustomer> read FList2;
property List3: TgList<TCustomer2> read FList3;
property List4: TgList<TObjectProperty> read FList4;
property Customer: TCustomer read FCustomer;
property Customer2: TCustomer2 read FCustomer2;
property Customers: TCustomers read FCustomers;
property Name: String read FName write FName;
property Shows: TShows read FShows;
property Exhibitors: TExhibitors read FExhibitors;
end;
private
FData: TMyClass;
FModel: TMyModel;
FDataClass: TgBaseClass;
FDocument: TgDocument;
published
procedure InputTagBoolean;
procedure InputTagInt;
procedure InputTagList1_0Int;
procedure gListItem;
procedure gListAdd;
procedure CurrentKeyPathNameAdd;
procedure CurrentObjectPathName;
procedure Composite;
procedure CompositeIdentity;
// procedure CurrentKeyPathName;
procedure Bool;
procedure ReadBool_True;
procedure ReadBool_False;
procedure NotVisibleBool;
procedure NoYesBool;
procedure OffOnBool;
procedure String_;
procedure Method;
procedure CheckBox_True;
procedure Int;
procedure Enum1;
procedure EnumSet1;
procedure Enum2;
procedure gHTMLString;
procedure String50;
procedure Str10;
procedure AnsiChar;
procedure Char;
procedure SingleValue;
procedure SingleDisplay;
procedure DoubleValue;
procedure ExtendedValue;
procedure CurrencyValue;
procedure Invisible;
procedure Invisible2;
procedure FileName;
procedure WebAddress;
procedure Model1;
procedure RestPaths;
end;
implementation
Uses
SysUtils,
Character,
Math
;
procedure TestTBase.GetValue;
begin
// Given a Pathname, return the property value
CheckEquals('Test', Base['StringProperty'], 'Non-Object Property');
CheckEquals('Test', Base['ManuallyConstructedObjectProperty.StringProperty'], 'Object Property');
// If the property doesn't exist, raise an exception
CheckException(UndeclaredProperty, TgBase.EgValue);
// If the path extends beyond an ordinal property, raise an exception
CheckException(PathExtendsBeyondOrdinalProperty, TgBase.EgValue);
// If the path ends with an object property, raise an exception
CheckException(PathEndsWithAnObjectProperty, TgBase.EgValue);
// If the property is not readable, raise an exception
CheckException(PropertyNotReadable, TgBase.EgValue);
// Can we get an Active Value?
Base.String5 := '123456789';
CheckEquals('12345', Base['String5'], 'Active Value');
Base.Phone := '5555555555';
CheckEquals('(555) 555-5555', Base['Phone'], 'Phone');
Base.BooleanProperty := True;
CheckEquals(True, Base['BooleanProperty']);
CheckEquals('True', Base['BooleanProperty']);
Base.BooleanProperty := False;
CheckEquals(False, Base['BooleanProperty']);
CheckEquals('False', Base['BooleanProperty']);
Base.DateProperty := StrToDate('1/1/12');
CheckEquals(StrToDate('1/1/12'), Base['DateProperty'], 'Date as TDate');
CheckEquals(FloatToStr(StrToDate('1/1/12')), Base['DateProperty'], 'Date as String');
Base.DateTimeProperty := StrToDateTime('1/1/12 12:34 am');
CheckEquals(StrToDateTime('1/1/12 12:34 am'), Base['DateTimeProperty'], 'DateTime as TDateTime');
CheckEquals(FloatToStr(StrToDateTime('1/1/12 12:34 am')), Base['DateTimeProperty'], 'DateTime as String');
Base.Enum := beLast;
CheckEquals('beLast',Base['Enum']);
end;
procedure TestTBase.Location;
begin
CheckEquals(_ExpectedCommonAppData,G.SpecialFolder(sfCommonAppData));
CheckEquals(_ExpectedCommonAppData+'G\',G.RootPath);
CheckEquals(_ExpectedCommonAppData+'G\gCore\',TgBase.ApplicationPath);
CheckEquals(_ExpectedCommonAppData+'G\gCore\Data\',TgBase.DataPath);
CheckEquals(_ExpectedCommonAppData+'G\Data\',G.DataPath);
end;
procedure TestTBase.PathEndsWithAnObjectProperty;
begin
Base['ObjectProperty'];
end;
procedure TestTBase.PathExtendsBeyondOrdinalProperty;
begin
Base['IntegerProperty.ThisShouldNotBeHere'];
end;
procedure TestTBase.PropertyNotReadable;
begin
Base['UnreadableIntegerProperty'];
end;
procedure TestTBase.PropertyNotWriteable;
begin
Base['UnwriteableIntegerProperty'] := 5;
end;
procedure TestTBase.SetPathEndsWithAnObjectProperty;
begin
Base['ObjectProperty'] := 'Test';
end;
procedure TestTBase.SetPathExtendsBeyondOrdinalProperty;
begin
Base['IntegerProperty.ThisShouldNotBeHere'] := 'Test';
end;
procedure TestTBase.PathValue;
var
DateTime: TDateTime;
ACount: Integer;
Item: TgBase.TPathValue;
begin
CheckEquals(10,Base.PathCount);
ACount := 0;
for Item in Base do
Inc(ACount);
CheckEquals(10,ACount);
CheckEquals('BooleanProperty',Base.Paths[0]);
CheckEquals('DateProperty',Base.Paths[1]);
CheckEquals('DateTimeProperty',Base.Paths[2]);
CheckEquals('Enum',Base.Paths[3]);
CheckEquals('IntegerProperty',Base.Paths[4]);
CheckEquals('ManuallyConstructedObjectProperty',Base.Paths[5]);
CheckEquals('ObjectProperty',Base.Paths[6]);
CheckEquals('UnconstructedObjectProperty',Base.Paths[7]);
CheckEquals('String5',Base.Paths[8]);
CheckEquals('Phone',Base.Paths[9]);
Base.BooleanProperty := True;
CheckTrue(Base.PathValues[0]);
Base.DateProperty := EncodeDate(2012,5,6);
DateTime := Base.PathValues[1];
CheckEquals('5/6/2012',DateTimeTostr(DateTime));
Base.DateTimeProperty := EncodeDate(2012,5,6)+EncodeTime(12,34,32,0);
DateTime := Base.PathValues[2];
CheckEquals('5/6/2012 12:34:32 PM',DateTimeTostr(DateTime));
Base.IntegerProperty := 1245;
CheckEquals(1245,Base.IntegerProperty);
end;
procedure TestTBase.SetUndeclaredProperty;
begin
Base['ThisPropertyDoesNotExist'] := 'Test';
end;
procedure TestTBase.SetUp;
begin
Base := TBase.Create;
end;
procedure TestTBase.SetValue;
begin
// Given a Pathname, set the property value
Base['StringProperty'] := 'Test2';
CheckEquals('Test2', Base.StringProperty, 'Non-Object Property');
Base['ManuallyConstructedObjectProperty.StringProperty'] := 'Test2';
CheckEquals('Test2', Base.ManuallyConstructedObjectProperty.StringProperty, 'Object Property');
// If the property doesn't exist, raise an exception
CheckException(SetUndeclaredProperty, TgBase.EgValue);
// If the path extends beyond a non-object property, raise an exception
CheckException(SetPathExtendsBeyondOrdinalProperty, TgBase.EgValue);
// If the path ends with an object property, raise an exception
CheckException(SetPathEndsWithAnObjectProperty, TgBase.EgValue);
// If the property is not writeable, raise an exception
CheckException(PropertyNotWriteable, TgBase.EgValue);
// Call a method
Base['SetUnwriteableIntegerProperty'] := '';
CheckEquals(10, Base.UnwriteableIntegerProperty);
Base['ManuallyConstructedObjectProperty.SetUnwriteableIntegerProperty'] := '';
CheckEquals(10, Base.ManuallyConstructedObjectProperty.UnwriteableIntegerProperty);
Base['String5'] := '123456789';
CheckEquals('12345', Base.String5);
Base['BooleanProperty'] := True;
CheckEquals(True, Base.BooleanProperty);
Base['BooleanProperty'] := False;
CheckEquals(False, Base.BooleanProperty);
Base['BooleanProperty'] := 'True';
CheckEquals(True, Base.BooleanProperty);
Base['BooleanProperty'] := 'False';
CheckEquals(False, Base.BooleanProperty);
Base['DateProperty'] := StrToDate('1/1/12');
CheckEquals(StrToDate('1/1/12'), Base.DateProperty, 'Date as TDate');
Base['DateProperty'] := '1/1/12';
CheckEquals(StrToDate('1/1/12'), Base.DateProperty, 'Date as String');
Base['DateTimeProperty'] := StrToDateTime('1/1/12 12:34 am');
CheckEquals(StrToDateTime('1/1/12 12:34 am'), Base.DateTimeProperty, 'DateTime as TDateTime');
Base['DateTimeProperty'] := '1/1/12 12:34 am';
CheckEquals(StrToDateTime('1/1/12 12:34 am'), Base.DateTimeProperty, 'DateTime as String');
end;
procedure TestTBase.TearDown;
begin
FreeAndNil(Base);
end;
procedure TestTBase.Assign;
var
Target: TBase;
begin
Target := TBase.Create(Base);
try
Base.IntegerProperty := 6;
Base.StringProperty := 'Hello';
Base.Phone := '5555555555';
Target.Assign(Base);
CheckEquals(6, Target.IntegerProperty);
CheckNull(Target.Inspect(G.PropertyByName(Target, 'ManuallyConstructedObjectProperty')));
CheckEquals('Test', Target.StringProperty);
CheckEquals('(555) 555-5555', Target.Phone);
finally
Target.Free;
end;
end;
procedure TestTBase.DeserializeXML;
var
XMLString: string;
begin
XMLString :=
'<xml>'#13#10 + //0
' <Base classname="TestgCore.TBase">'#13#10 + //1
' <BooleanProperty>True</BooleanProperty>'#13#10 + //2
' <DateProperty>1/1/2012</DateProperty>'#13#10 + //3
' <DateTimeProperty>1/1/2012 00:34:00</DateTimeProperty>'#13#10 + //4
' <IntegerProperty>5</IntegerProperty>'#13#10 + //5
' <ManuallyConstructedObjectProperty classname="TestgCore.TBase">'#13#10 + //6
' <BooleanProperty>False</BooleanProperty>'#13#10 + //7
' <DateProperty>12/30/1899</DateProperty>'#13#10 + //8
' <DateTimeProperty>12/30/1899 00:00:00</DateTimeProperty>'#13#10 + //9
' <IntegerProperty>6</IntegerProperty>'#13#10 + //10
' <ObjectProperty classname="TestgCore.TBase2">'#13#10 + //11
' <IntegerProperty>2</IntegerProperty>'#13#10 + //12
' <StringProperty>12345</StringProperty>'#13#10 + //13
' </ObjectProperty>'#13#10 + //14
' <String5>98765</String5>'#13#10 + //15
' <Phone>(444) 444-4444</Phone>'#13#10 + //16
' </ManuallyConstructedObjectProperty>'#13#10 + //17
' <ObjectProperty classname="TestgCore.TBase2">'#13#10 + //18
' <IntegerProperty>2</IntegerProperty>'#13#10 + //19
' <StringProperty>12345</StringProperty>'#13#10 + //20
' </ObjectProperty>'#13#10 + //21
' <String5>12345</String5>'#13#10 + //22
' <Phone>(555) 555-5555</Phone>'#13#10 + //23
' </Base>'#13#10 + //24
'</xml>'#13#10; //25
Base.Deserialize(TgSerializerXML, XMLString);
CheckEquals('12345', Base.String5);
CheckEquals('(555) 555-5555', Base.Phone);
CheckEquals(6, Base.ManuallyConstructedObjectProperty.IntegerProperty);
CheckEquals('98765', Base.ManuallyConstructedObjectProperty.String5);
CheckEquals('(444) 444-4444', Base.ManuallyConstructedObjectProperty.Phone);
CheckEquals(True, Base.BooleanProperty);
CheckEquals(StrToDate('1/1/12'), Base.DateProperty);
CheckEquals(StrToDateTime('1/1/12 12:34 am'), Base.DateTimeProperty);
end;
procedure TestTBase.DeserializeCSV;
var
CSVString: string;
begin
CSVString :=
'BooleanProperty,DateProperty,DateTimeProperty,IntegerProperty,StringProperty,String5,Phone,ManuallyConstructedObjectProperty.BooleanProperty,ManuallyConstructedObjectProperty.DateProperty,ManuallyConstructedObjectProperty.DateTimeProperty,'
+'ManuallyConstructedObjectProperty.IntegerProperty,ManuallyConstructedObjectProperty.ObjectProperty.IntegerProperty,ManuallyConstructedObjectProperty.ObjectProperty.StringProperty,ManuallyConstructedObjectProperty.String5,'
+'ManuallyConstructedObjectProperty.Phone,ObjectProperty.IntegerProperty,ObjectProperty.StringProperty'#$D#$A
+'True,1/1/2012,"1/1/2012 00:34:00",5,,,,False,12/30/1899,"12/30/1899 00:00:00",6,2,12345,98765,"(444) 444-4444"'#$D#$A
+',,,,,,,,,,,,,,,2,12345'#$D#$A
+',,,,,12345,"(555) 555-5555"'#$D#$A;
Base.Deserialize(TgSerializerCSV, CSVString);
CheckEquals('12345', Base.String5);
CheckEquals('(555) 555-5555', Base.Phone);
CheckEquals(6, Base.ManuallyConstructedObjectProperty.IntegerProperty);
CheckEquals('98765', Base.ManuallyConstructedObjectProperty.String5);
CheckEquals('(444) 444-4444', Base.ManuallyConstructedObjectProperty.Phone);
CheckEquals(True, Base.BooleanProperty);
CheckEquals(StrToDate('1/1/12'), Base.DateProperty);
CheckEquals(StrToDateTime('1/1/12 12:34 am'), Base.DateTimeProperty);
end;
procedure TestTBase.DeserializeJSON;
var
JSONString: string;
begin
JSONString :=
'{"ClassName":"TestgCore.TBase","BooleanProperty":"True","DateProperty":"1/'+
'1/2012","DateTimeProperty":"1/1/2012 00:34:00","IntegerProperty":"5","Manu'+
'allyConstructedObjectProperty":{"ClassName":"TestgCore.TBase","BooleanProp'+
'erty":"False","DateProperty":"12/30/1899","DateTimeProperty":"12/30/1899 0'+
'0:00:00","IntegerProperty":"6","ObjectProperty":{"ClassName":"TestgCore.TB'+
'ase2","IntegerProperty":"2","StringProperty":"12345"},"String5":"98765","P'+
'hone":"(444) 444-4444"},"ObjectProperty":{"ClassName":"TestgCore.TBase2","'+
'IntegerProperty":"2","StringProperty":"12345"},"String5":"12345","Phone":"'+
'(555) 555-5555"}';
Base.Deserialize(TgSerializerJSON, JSONString);
CheckEquals('12345', Base.String5);
CheckEquals('(555) 555-5555', Base.Phone);
CheckEquals(6, Base.ManuallyConstructedObjectProperty.IntegerProperty);
CheckEquals('98765', Base.ManuallyConstructedObjectProperty.String5);
CheckEquals('(444) 444-4444', Base.ManuallyConstructedObjectProperty.Phone);
CheckEquals(True, Base.BooleanProperty);
CheckEquals(StrToDate('1/1/12'), Base.DateProperty);
CheckEquals(StrToDateTime('1/1/12 12:34 am'), Base.DateTimeProperty);
end;
procedure TestTBase.SerializeXML;
var
XMLString: string;
S: string;
begin
Base.String5 := '123456789';
Base.Phone := '5555555555';
Base.ManuallyConstructedObjectProperty.IntegerProperty := 6;
Base.ManuallyConstructedObjectProperty.String5 := '987654321';
Base.ManuallyConstructedObjectProperty.Phone := '4444444444';
Base.BooleanProperty := True;
Base.DateProperty := StrToDate('1/1/12');
Base.DateTimeProperty := StrToDateTime('1/1/12 12:34 am');
XMLString :=
'<xml>'#13#10 + //0
' <Base>'#13#10 + //1
' <BooleanProperty>True</BooleanProperty>'#13#10 + //2
' <DateProperty>1/1/2012</DateProperty>'#13#10 + //3
' <DateTimeProperty>1/1/2012 00:34:00</DateTimeProperty>'#13#10 + //4
' <Enum>be</Enum>'#13#10 +
' <IntegerProperty>5</IntegerProperty>'#13#10 + //5
' <ManuallyConstructedObjectProperty>'#13#10 + //6
' <BooleanProperty>False</BooleanProperty>'#13#10 + //7
' <DateProperty>12/30/1899</DateProperty>'#13#10 + //8
' <DateTimeProperty>12/30/1899 00:00:00</DateTimeProperty>'#13#10 + //9
' <Enum>be</Enum>'#13#10 +
' <IntegerProperty>6</IntegerProperty>'#13#10 + //10
' <ObjectProperty>'#13#10 + //11
' <IntegerProperty>2</IntegerProperty>'#13#10 + //12
' <StringProperty>12345</StringProperty>'#13#10 + //13
' </ObjectProperty>'#13#10 + //14
' <String5>98765</String5>'#13#10 + //15
' <Phone>(444) 444-4444</Phone>'#13#10 + //16
' </ManuallyConstructedObjectProperty>'#13#10 + //17
' <ObjectProperty>'#13#10 + //18
' <IntegerProperty>2</IntegerProperty>'#13#10 + //19
' <StringProperty>12345</StringProperty>'#13#10 + //20
' </ObjectProperty>'#13#10 + //21
' <String5>12345</String5>'#13#10 + //22
' <Phone>(555) 555-5555</Phone>'#13#10 + //23
' </Base>'#13#10 + //24
'</xml>'#13#10; //25
S := Base.Serialize(TgSerializerXML);
CheckEquals(XMLString, S);
end;
procedure TestTBase.SerializeCSV;
var
CSVString1, CSVString: string;
begin
Base.String5 := '123456789';
Base.Phone := '5555555555';
Base.ManuallyConstructedObjectProperty.IntegerProperty := 6;
Base.ManuallyConstructedObjectProperty.String5 := '987654321';
Base.ManuallyConstructedObjectProperty.Phone := '4444444444';
Base.BooleanProperty := True;
Base.DateProperty := StrToDate('1/1/12');
Base.DateTimeProperty := StrToDateTime('1/1/12 12:34 am');
CSVString1 := Base.Serialize(TgSerializerCSV);
CSVString :=
'BooleanProperty,DateProperty,DateTimeProperty,Enum,IntegerProperty,StringProperty,String5,Phone,ManuallyConstructedObjectProperty.BooleanProperty,ManuallyConstructedObjectProperty.DateProperty,ManuallyConstructedObjectProperty.DateTimeProperty,'
+'ManuallyConstructedObjectProperty.Enum,ManuallyConstructedObjectProperty.IntegerProperty,ManuallyConstructedObjectProperty.ObjectProperty.IntegerProperty,ManuallyConstructedObjectProperty.ObjectProperty.StringProperty,'
+'ManuallyConstructedObjectProperty.String5,ManuallyConstructedObjectProperty.Phone,ObjectProperty.IntegerProperty,ObjectProperty.StringProperty'#$D#$A
+'True,1/1/2012,"1/1/2012 00:34:00",be,5,,,,False,12/30/1899,"12/30/1899 00:00:00",be,6,2,12345,98765,"(444) 444-4444"'#$D#$A
+',,,,,,,,,,,,,,,,,2,12345'#$D#$A
+',,,,,,12345,"(555) 555-5555"'#$D#$A;
CheckEquals(CSVString,CSVString1);
end;
procedure TestTBase.SerializeJSON;
var
JSONString: string;
S: string;
begin
Base.String5 := '123456789';
Base.Phone := '5555555555';
Base.ManuallyConstructedObjectProperty.IntegerProperty := 6;
Base.ManuallyConstructedObjectProperty.String5 := '987654321';
Base.ManuallyConstructedObjectProperty.Phone := '4444444444';
Base.BooleanProperty := True;
Base.DateProperty := StrToDate('1/1/12');
Base.DateTimeProperty := StrToDateTime('1/1/12 12:34 am');
JSONString :=
'{"ClassName":"TestgCore.TBase","BooleanProperty":"True","DateProperty":'
+'"1/1/2012","DateTimeProperty":"1/1/2012 00:34:00","Enum":"be","IntegerP'
+'roperty":"5","ManuallyConstructedObjectProperty":{"ClassName":"TestgCor'
+'e.TBase","BooleanProperty":"False","DateProperty":"12/30/1899","DateTim'
+'eProperty":"12/30/1899 00:00:00","Enum":"be","IntegerProperty":"6","Obj'
+'ectProperty":{"ClassName":"TestgCore.TBase2","IntegerProperty":"2","Str'
+'ingProperty":"12345"},"String5":"98765","Phone":"(444) 444-4444"},"Obje'
+'ctProperty":{"ClassName":"TestgCore.TBase2","IntegerProperty":"2","Stri'
+'ngProperty":"12345"},"String5":"12345","Phone":"(555) 555-5555"}';
S := Base.Serialize(TgSerializerJSON);
CheckEquals(JSONString, S);
end;
procedure TestTBase.TestCreate;
var
Base1: TBase;
Base2: TBase2;
begin
CheckNull(Base.Owner, 'When a constructor is called without a parameter, its owner should be nil.');
CheckNotNull(Base.ObjectProperty, 'Object properties should be constructed automatically if the Exclude([AutoCreate]) attribute is not set.');
CheckNull(Base.UnconstructedObjectProperty, 'Object properties with the Exlude([AutoCreate]) attribute should not be nil.');
Check(Base=Base.ObjectProperty.Owner, 'The owner of an automatically constructed object property shoud be set to the object that created it.');
CheckEquals(5, Base.IntegerProperty, 'Default integer values should be set for properties with a DefaultValue attribute.');
CheckEquals('Test', Base.StringProperty, 'Default string values should be set for properties with a DefaultValue attribute.');
Base2 := TBase2.Create;
try
Base1 := TBase.Create(Base2);
try
Check(Base1.ObjectProperty = Base2, 'Object properties should take the value of an existing owner object if one exists.');
finally
Base1.Free;
end;
finally
Base2.Free;
end;
end;
procedure TestTBase.UndeclaredProperty;
begin
Base['ThisPropertyDoesNotExist'];
end;
procedure TestTBase.ValidateRequired;
begin
Base.DateProperty := Date;
Base.DateTimeProperty := Now;
Base.IntegerProperty := 1;
Base.StringProperty := 'Hello';
Base.String5 := '12345';
Base.Phone := '1234567890';
CheckTrue(Base.IsValid);
Base.DateProperty := 0;
CheckFalse(Base.IsValid, 'Base.IsValid (DateProperty)');
Check(Base.ValidationErrors['DateProperty'] > '', 'Base.ValidationErrors[''DateProperty''] > ''''');
Base.DateProperty := Date;
Base.DateTimeProperty := 0;
CheckFalse(Base.IsValid, 'Base.IsValid (DateTimeProperty)');
Check(Base.ValidationErrors['DateTimeProperty'] > '', 'Base.ValidationErrors[''DateTimeProperty''] > ''''');
Base.DateTimeProperty := Now;
Base.IntegerProperty := 0;
CheckFalse(Base.IsValid, 'Base.IsValid (DateProperty)');
Check(Base.ValidationErrors['IntegerProperty'] > '', 'Base.ValidationErrors[''Integer''] > ''''');
Base.IntegerProperty := 1;
Base.StringProperty := '';
CheckFalse(Base.IsValid, 'Base.IsValid (StringProperty)');
Check(Base.ValidationErrors['StringProperty'] > '', 'Base.ValidationErrors[''StringProperty''] > ''''');
Base.StringProperty := 'Hello';
Base.String5 := '';
CheckFalse(Base.IsValid, 'Base.IsValid (String5)');
Check(Base.ValidationErrors['String5'] > '', 'Base.ValidationErrors[''String5''] > ''''');
end;
destructor TBase.Destroy;
begin
FreeAndNil(FManuallyConstructedObjectProperty);
inherited Destroy;
end;
function TBase.GetManuallyConstructedObjectProperty: TBase;
begin
if Not IsInspecting And Not Assigned(FManuallyConstructedObjectProperty) then
FManuallyConstructedObjectProperty := TBase.Create(Self);
Result := FManuallyConstructedObjectProperty;
end;
procedure TBase.SetUnwriteableIntegerProperty;
begin
FUnwriteableIntegerProperty := 10;
end;
function TgString5.GetValue: String;
begin
Result := FValue;
end;
procedure TgString5.SetValue(const AValue: String);
begin
FValue := Copy(AValue, 1, 5);
end;
class operator TgString5.implicit(AValue: Variant): TgString5;
begin
Result.Value := AValue;
end;
class operator TgString5.Implicit(AValue: TgString5): Variant;
begin
Result := AValue.Value;
end;
procedure TestTgString5.TestLength;
var
String5: TgString5;
begin
String5 := '123456789';
CheckEquals('12345', String5);
end;
function TPhoneString.FormatPhone(AValue : String): String;
Var
CurrentCharacter: Char;
Begin
Result := '';
for CurrentCharacter in AValue do
Begin
if IsNumber(CurrentCharacter) then
Result := Result + CurrentCharacter;
End;
Case Length(Result) Of
7 :
Begin
Insert('( ) ', Result, 1);
Insert('-', Result, 10);
End;
10 :
Begin
Insert('(', Result, 1);
Insert(') ', Result, 5);
Insert('-', Result, 10);
End;
Else
Result := AValue;
End;
End;
function TPhoneString.GetValue: String;
begin
Result := FValue;
end;
procedure TPhoneString.SetValue(const AValue: String);
begin
FValue := FormatPhone(AValue);
end;
class operator TPhoneString.Implicit(AValue: TPhoneString): Variant;
begin
Result := AValue.Value;
end;
class operator TPhoneString.Implicit(AValue: Variant): TPhoneString;
begin
Result.Value := AValue;
end;
procedure TestTBase2List.Add;
begin
Add3;
CheckEquals(3, FBase2List.Count, 'There should be 3 items in the list.');
CheckEquals(3, FBase2List.Current.IntegerProperty, 'The last item added should be the current one.');
CheckEquals(2, FBase2List.CurrentIndex, 'The CurrentIndex value should be one less than the count.');
CheckEquals(TBase2, FBase2List.Current.ClassType, 'Constructs the new list item from ItemClass, which in this case, is the generic class.');
FBase2List.ItemClass := TBase3;
FBase2List.Add;
CheckEquals(TBase3, FBase2List.Current.ClassType, 'Constructs the new list item from the new ItemClass.');
end;
procedure TestTBase2List.Add3;
var
Counter: Integer;
begin
for Counter := 1 to 3 do
Begin
FBase2List.Add;
FBase2List.Current.IntegerProperty := Counter;
End;
end;
procedure TestTBase2List.Assign;
var
NewBase2List: TBase2List;
begin
Add3;
NewBase2List := TBase2List.Create;
try
NewBase2List.Assign(FBase2List);
CheckEquals(3, NewBase2List.Count, 'Should have copied 3 items.');
CheckEquals(3, NewBase2List[2].IntegerProperty, 'Make sure the value got copied.');
finally
NewBase2List.Free;
end;
end;
procedure TestTBase2List.BOL;
begin
CheckTrue(FBase2List.BOL, 'When there are no items, BOL should be true.');
FBase2List.Add;
CheckFalse(FBase2List.BOL, 'When there is one item and it''s the current one, BOL should be false.');
FBase2List.Previous;
CheckTrue(FBase2List.BOL, 'If you try to move before the first item, BOL should be true');
FBase2List.Last;
CheckFalse(FBase2List.BOL, 'This should make the only item current and set EOL, but not BOL.');
FBase2List.First;
CheckTrue(FBase2List.BOL, 'Calling First shoule make BOL true.');
end;
procedure TestTBase2List.EOL;
begin
CheckTrue(FBase2List.EOL, 'When there are no items, EOL should be true.');
FBase2List.Add;
CheckFalse(FBase2List.EOL, 'When there is one item and it''s the current one, EOL should be false.');
FBase2List.Next;
CheckTrue(FBase2List.EOL, 'If you try to move after the only item, EOL should be true');
FBase2List.First;
CheckFalse(FBase2List.EOL, 'This should make the only item current, but not set EOL.');
FBase2List.Last;
CheckTrue(FBase2List.EOL, 'Calling Last shoule make EOL true.');
end;
procedure TestTBase2List.CanAdd;
begin
CheckTrue(FBase2List.CanAdd);
end;
procedure TestTBase2List.CanNext;
begin
CheckFalse(FBase2List.CanNext, 'Always false for an empty list.');
FBase2List.Add;
CheckFalse(FBase2List.CanNext, 'Always false for the last item in the list.');
FBase2List.Add;
FBase2List.Previous;
CheckTrue(FBase2List.CanNext, 'Always true if list not empty and not on the last item.');
end;
procedure TestTBase2List.CanPrevious;
begin
CheckFalse(FBase2List.CanPrevious, 'Always false for an empty list.');
FBase2List.Add;
CheckFalse(FBase2List.CanPrevious, 'Always false for the first item in the list.');
FBase2List.Add;
CheckTrue(FBase2List.CanPrevious, 'Always true if list not empty and not on the first item.');
end;
procedure TestTBase2List.Clear;
begin
Add3;
FBase2List.Clear;
CheckEquals(0, FBase2List.Count);
end;
procedure TestTBase2List.Count;
begin
CheckEquals(0, FBase2List.Count, 'When a list is created it has no items');
Add3;
FBase2List.Delete;
CheckEquals(2, FBase2List.Count, 'The count equals the number of items added minus the number deleted.');
end;
procedure TestTBase2List.Current;
begin
CheckException(CurrentOnEmptyList,TgList.EgList, 'Calling Current on an empty list should cause an exception.');
Add3;
FBase2List.CurrentIndex := 1;
CheckEquals(2, FBase2List.Current.IntegerProperty, 'If there are items in the list, Current returns the item at CurrentIndex (zero based).');
end;
procedure TestTBase2List.CurrentIndex;
begin
CheckEquals(-1, FBase2List.CurrentIndex, 'CurrentIndex should be -1 on an empty list.');
Add3;
while Not FBase2List.BOL do
Begin
Check(InRange(FBase2List.CurrentIndex, 0, FBase2List.Count - 1), Format('%d is not in range 0..%d', [FBase2List.CurrentIndex, FBase2List.Count - 1]));
FBase2List.Previous;
End;
FBase2List.Last;
FBase2List.Delete;
CheckEquals(1, FBase2List.CurrentIndex, 'When Current is Last, and it gets deleted, CurrentIndex matched the new Last');
FBase2List.CurrentIndex := 0;
CheckEquals(0, FBase2List.CurrentIndex, 'Setting CurrentIndex to a valid value should allow you to get that same value.');
CheckException(SetCurrentIndexTooLow, TgList.EgList, 'CurrentIndex must be greater than or equal to 0.');
CheckException(SetCurrentIndexTooHigh, TgList.EgList, 'CurrentIndex must be less than or equal to Count - 1.');
end;
procedure TestTBase2List.CurrentOnEmptyList;
begin
FBase2List.Clear;
FBase2List.Current;
end;
procedure TestTBase2List.Delete;
begin
CheckException(DeleteFromEmptyList, TgList.EgList, 'The Delete method may not be called from an empty list.');
Add3;
FBase2List.CurrentIndex := 1;
FBase2List.Delete;
CheckEquals(2, FBase2List.Count, 'Deleting one of the 3 list items should yield a count of 2.');
CheckEquals(3, FBase2List.Current.IntegerProperty, 'The 3rd item should have taken the place of the 2nd');
end;
procedure TestTBase2List.DeleteFromEmptyList;
begin
FBase2List.Clear;
FBase2List.Delete;
end;
procedure TestTBase2List.First;
begin
Add3;
FBase2List.First;
CheckTrue(FBase2List.BOL, 'First should set BOL');
CheckEquals(0, FBase2List.CurrentIndex, 'CurrentIndex should be at 0.');
end;
procedure TestTBase2List.GetItem;
begin
Add3;
CheckEquals(2, FBase2List.Items[1].IntegerProperty, 'Get the 2nd item in the array');
CheckException(GetItemInvalidIndex, TgList.EgList, 'Invalid Index');
end;
procedure TestTBase2List.SetItem;
begin
Add3;
FBase2List.Items[1].IntegerProperty := 22;
CheckEquals(22, FBase2List.Items[1].IntegerProperty, 'Get the 2nd item in the array');
CheckException(SetItemInvalidIndex, TgList.EgList, 'Invalid Index');
end;
procedure TestTBase2List.GetItemInvalidIndex;
begin
FBase2List.Items[23].IntegerProperty := FBase2List.Items[23].IntegerProperty + 1;
end;
procedure TestTBase2List.SetItemInvalidIndex;
begin
FBase2List.Items[23].IntegerProperty := 22;
end;
procedure TestTBase2List.Last;
begin
Add3;
FBase2List.First;
FBase2List.Last;
CheckTrue(FBase2List.EOL, 'Last should set EOL');
CheckEquals(2, FBase2List.CurrentIndex, 'CurrentIndex should be at 2.');
end;
procedure TestTBase2List.GetValue;
begin
Add3;
CheckEquals(3, FBase2List.Values['Current.IntegerProperty'], 'Testing the inherited GetValue');
CheckEquals(2, FBase2List.Values['[1].IntegerProperty'], 'Testing the overridden GetValues that looks for an index value');
CheckException(GetValueInvalidIndex, TgBase.EgValue, 'Invalid Index');
end;
procedure TestTBase2List.SetValue;
begin
FBase2List.Add;
FBase2List.Values['Current.IntegerProperty'] := 1;
CheckEquals(1, FBase2List.Current.IntegerProperty, 'Testing the inherited SetValue');
FBase2List.Values['[0].IntegerProperty'] := 2;
CheckEquals(2, FBase2List[0].IntegerProperty, 'Testing the overriden SetValue looking for an index value.');
CheckException(SetValueInvalidIndex, TgBase.EgValue, 'Invalid Index');
end;
procedure TestTBase2List.GetValueInvalidIndex;
begin
FBase2List.Values['[xyz].IntegerProperty'];
end;
procedure TestTBase2List.HasItems;
begin
CheckFalse(FBase2List.HasItems, 'Should return False on an empty list.');
FBase2List.Add;
CheckTrue(FBase2List.HasItems, 'Should return True on a non-empty list.');
end;
procedure TestTBase2List.ItemClass;
begin
Check(FBase2List.ItemClass = TBase2, 'The default ItemClass should be the generic type.');
FBase2List.ItemClass := TBase3;
CheckEquals(TBase3, FBase2List.ItemClass, 'Should return the ItemClass that was set.');
end;
procedure TestTBase2List.Next;
begin
CheckException(NextPastEOL, TgList.EgList, 'Exception calling on Empty List');
Add3;
FBase2List.Last;
FBase2List.Previous;
FBase2List.Next;
CheckEquals(2, FBase2List.CurrentIndex, 'Should be CurrentIndex2');
FBase2List.Next;
CheckTrue(FBase2List.EOL);
CheckException(NextPastEOL, TgList.EgList, 'Exception calling on EOL.');
end;
procedure TestTBase2List.Previous;
begin
CheckException(PreviousBeforeBOL, TgList.EgList, 'Exception calling on Empty List');
Add3;
FBase2List.First;
FBase2List.Next;
FBase2List.Previous;
CheckEquals(0, FBase2List.CurrentIndex, 'CurrentIndex should be 0');
FBase2List.Previous;
CheckTrue(FBase2List.BOL);
CheckException(PreviousBeforeBOL, TgList.EgList, 'Exception calling on EOL.');
end;
procedure TestTBase2List.NextPastEOL;
begin
FBase2List.Next;
end;
procedure TestTBase2List.PreviousBeforeBOL;
begin
FBase2List.Previous;
end;
procedure TestTBase2List.SerializeXML;
var
XMLString: string;
begin
Add3;
XMLString :=
'<xml>'#13#10 + //0
' <Base2List>'#13#10 + //1
' <List>'#13#10 + //2
' <Base2>'#13#10 + //3
' <IntegerProperty>1</IntegerProperty>'#13#10 + //4
' <StringProperty>12345</StringProperty>'#13#10 + //5
' </Base2>'#13#10 + //6
' <Base2>'#13#10 + //7
' <IntegerProperty>2</IntegerProperty>'#13#10 + //8
' <StringProperty>12345</StringProperty>'#13#10 + //9
' </Base2>'#13#10 + //10
' <Base2>'#13#10 + //11
' <IntegerProperty>3</IntegerProperty>'#13#10 + //12
' <StringProperty>12345</StringProperty>'#13#10 + //13
' </Base2>'#13#10 + //14
' </List>'#13#10 + //15
' </Base2List>'#13#10 + //16
'</xml>'#13#10; //17
CheckEquals(XMLString, FBase2List.Serialize(TgSerializerXML));
end;
procedure TestTBase2List.SerializeCSV;
var
CSVString: string;
begin
Add3;
CSVString := 'IntegerProperty,StringProperty'#$D#$A'1,12345'#$D#$A'2,12345'#$D#$A'3,12345'#$D#$A;
CheckEquals(CSVString, FBase2List.Serialize(TgSerializerCSV));
end;
procedure TestTBase2List.SerializeJSON;
var
JSONString: string;
begin
Add3;
JSONString :=
'{"ClassName":"TestgCore.TBase2List","List":[{"ClassName":"TestgCore.TBase2'+
'","IntegerProperty":"1","StringProperty":"12345"},{"ClassName":"TestgCore.'+
'TBase2","IntegerProperty":"2","StringProperty":"12345"},{"ClassName":"Test'+
'gCore.TBase2","IntegerProperty":"3","StringProperty":"12345"}]}';
CheckEquals(JSONString, FBase2List.Serialize(TgSerializerJSON));
end;
procedure TestTBase2List.DeserializeXML;
var
XMLString: string;
begin
XMLString :=
'<xml>'#13#10 + //0
' <Base2List classname="TestgCore.TBase2List">'#13#10 + //1
' <List>'#13#10 + //2
' <Base2 classname="TestgCore.TBase2">'#13#10 + //3
' <IntegerProperty>1</IntegerProperty>'#13#10 + //4
' <StringProperty>12345</StringProperty>'#13#10 + //5
' </Base2>'#13#10 + //6
' <Base2 classname="TestgCore.TBase2">'#13#10 + //7
' <IntegerProperty>2</IntegerProperty>'#13#10 + //8
' <StringProperty>12345</StringProperty>'#13#10 + //9
' </Base2>'#13#10 + //10
' <Base2 classname="TestgCore.TBase2">'#13#10 + //11
' <IntegerProperty>3</IntegerProperty>'#13#10 + //12
' <StringProperty>12345</StringProperty>'#13#10 + //13
' </Base2>'#13#10 + //14
' </List>'#13#10 + //15
' </Base2List>'#13#10 + //16
'</xml>'#13#10; //17
FBase2List.Deserialize(TgSerializerXML, XMLString);
CheckEquals(3, FBase2List.Items[2].IntegerProperty);
end;
procedure TestTBase2List.DeserializeCSV;
var
CSVString: string;
begin
CSVString := 'IntegerProperty,StringProperty'#$D#$A'1,12345'#$D#$A'2,12345'#$D#$A'3,12345'#$D#$A;
FBase2List.Deserialize(TgSerializerCSV, CSVString);
CheckEquals(3, FBase2List.Items[2].IntegerProperty);
end;
procedure TestTBase2List.DeserializeJSON;
var
JSONString: string;
begin
JSONString :=
'{"ClassName":"TestgCore.TBase2List","List":[{"ClassName":"TestgCore.TBase2'+
'","IntegerProperty":"1","StringProperty":"12345"},{"ClassName":"TestgCore.'+
'TBase2","IntegerProperty":"2","StringProperty":"12345"},{"ClassName":"Test'+
'gCore.TBase2","IntegerProperty":"3","StringProperty":"12345"}]}';
FBase2List.Deserialize(TgSerializerJSON, JSONString);
CheckEquals(3, FBase2List.Items[2].IntegerProperty);
end;
procedure TestTBase2List.Filter;
begin
Add3;
FBase2List.Where := 'IntegerProperty > 1';
FBase2List.Filter;
CheckEquals(2, FBase2List.Count);
CheckEquals(2, FBase2List.Current.IntegerProperty);
end;
procedure TestTBase2List.SetValueInvalidIndex;
begin
FBase2List.Values['[xyz].IntegerProperty'] := 2;
end;
procedure TestTBase2List.SetCurrentIndexTooHigh;
begin
FBase2List.CurrentIndex := FBase2List.Count;
end;
procedure TestTBase2List.SetCurrentIndexTooLow;
begin
FBase2List.CurrentIndex := -1;
end;
procedure TestTBase2List.SetUp;
begin
FBase2List := TBase2List.Create;
end;
procedure TestTBase2List.Sort;
begin
Add3;
FBase2List.OrderBy := 'StringProperty, IntegerProperty DESC';
FBase2List.Sort;
FBase2List.First;
CheckEquals(3, FBase2List.Current.IntegerProperty);
FBase2List.Next;
CheckEquals(2, FBase2List.Current.IntegerProperty);
FBase2List.Next;
CheckEquals(1, FBase2List.Current.IntegerProperty);
end;
procedure TestTBase2List.TearDown;
begin
FBase2List.Free;
FBase2List := nil;
end;
procedure TestTBase2List.TestCreate(BOL: Integer; const Value: string);
begin
CheckEquals(0, FBase2List.Count, 'A list has no items after it gets created.');
CheckEquals(-1, FBase2List.CurrentIndex, 'The CurrentIndex is set to -1 if there are no list items.');
end;
procedure ValidatePhone.Execute(AObject: TgObject; ARTTIProperty: TRttiProperty);
var
ValueLength: Integer;
begin
ValueLength := Length(AObject[ARTTIProperty.Name]);
if InRange(ValueLength, 1, 6) then
AObject.ValidationErrors[ARTTIProperty.Name] := 'A phone number must contain at least seven digits.';
end;
procedure TestTIdentityObject.Delete;
begin
FIdentityObject.ID := 1;
FIdentityObject.Name := 'One';
FIdentityObject.Save;
FIdentityObject.ID := 2;
FIdentityObject.Name := 'Two';
FIdentityObject.Save;
FIdentityObject.ID := 3;
FIdentityObject.Name := 'Three';
FIdentityObject.Save;
FIdentityObject.ID := 1;
FIdentityObject.Load;
FIdentityObject.Delete;
FIdentityObject.ID := 1;
CheckFalse(FIdentityObject.Load);
FIdentityObject.ID := 3;
CheckTrue(FIdentityObject.Load);
FIdentityObject.Delete;
FIdentityObject.ID := 3;
CheckFalse(FIdentityObject.Load);
end;
procedure TestTIdentityObject.Save;
begin
FIdentityObject.ID := 1;
FIdentityObject.Name := 'One';
FIdentityObject.Save;
FIdentityObject.ID := 2;
FIdentityObject.Name := 'Two';
FIdentityObject.Save;
FIdentityObject.ID := 3;
FIdentityObject.Name := 'Three';
FIdentityObject.Save;
FIdentityObject.ID := 1;
CheckTrue(FIdentityObject.Load);
CheckEquals('One', FIdentityObject.Name);
FIdentityObject.ID := 2;
CheckTrue(FIdentityObject.Load);
CheckEquals('Two', FIdentityObject.Name);
FIdentityObject.ID := 3;
CheckTrue(FIdentityObject.Load);
CheckEquals('Three', FIdentityObject.Name);
CheckException(SaveWithoutName, EgValidation);
end;
procedure TestTIdentityObject.SaveWithoutName;
begin
FIdentityObject.ID := 4;
FIdentityObject.Name := '';
FIdentityObject.Save
end;
procedure TestTIdentityObject.SetUp;
begin
FIdentityObject := TIdentityObject.Create;
FIdentityObject.PersistenceManager.CreatePersistentStorage;
end;
procedure TestTIdentityObject.TearDown;
begin
FIdentityObject.Free;
FIdentityObject := nil;
end;
procedure TestTIdentityObjectList.Add;
begin
Add3;
CheckEquals(3, FIdentityObjectList.Count, 'There should be 3 items in the list.');
CheckEquals(3, FIdentityObjectList.Current.ID, 'The last item added should be the current one.');
CheckEquals(2, FIdentityObjectList.CurrentIndex, 'The CurrentIndex value should be one less than the count.');
CheckEquals(TIdentityObject, FIdentityObjectList.Current.ClassType, 'Constructs the new list item from ItemClass, which in this case, is the generic class.');
end;
procedure TestTIdentityObjectList.Add3;
const
Names : Array[1..3] of String = ('One', 'Two', 'Three');
var
Counter: Integer;
begin
for Counter := 1 to 3 do
Begin
FIdentityObjectList.Add;
FIdentityObjectList.Current.ID := Counter;
FIdentityObjectList.Current.Name := Names[Counter];
FIdentityObjectList.Current.Save;
End;
end;
procedure TestTIdentityObjectList.BOL;
begin
CheckTrue(FIdentityObjectList.BOL, 'When there are no items, BOL should be true.');
Add3;
FIdentityObjectList.Active := False;
CheckTrue(FIdentityObjectList.BOL, 'When a list gets activated its current item should be the the first item');
end;
procedure TestTIdentityObjectList.EOL;
begin
CheckTrue(FIdentityObjectList.EOL, 'When there are no items, EOL should be true.');
Add3;
FIdentityObjectList.Active := False;
CheckFalse(FIdentityObjectList.EOL, 'When a list gets activated its current item should be the the first item');
end;
procedure TestTIdentityObjectList.Count;
begin
CheckEquals(0, FIdentityObjectList.Count, 'When a list is created it has no items');
Add3;
CheckEquals(3, FIdentityObjectList.Count, 'After add3, there should be three items');
CheckFalse(FIdentityObjectList.Active, 'We should be able to get the count from the persistence manager without activating the list.');
FIdentityObjectList.Delete;
CheckTrue(FIdentityObjectList.Active, 'The delete should have called Current which should have activated the list.');
CheckEquals(2, FIdentityObjectList.Count, 'Here, the count should come from the list instead of the persistence manager.');
end;
procedure TestTIdentityObjectList.Current;
begin
CheckException(CurrentOnEmptyList,TgList.EgList, 'Calling Current on an empty list should cause an exception.');
Add3;
FIdentityObjectList.First;
FIdentityObjectList.Next;
CheckEquals(2, FIdentityObjectList.Current.ID, 'If there are items in the list, Current returns the item at CurrentIndex (zero based).');
end;
procedure TestTIdentityObjectList.CurrentOnEmptyList;
begin
FIdentityObjectList.Current;
end;
procedure TestTIdentityObjectList.Delete;
begin
FIdentityObjectList.Active := True; // this list as to be active to do this
Add3;
FIdentityObjectList.CurrentIndex := 1;
CheckEquals(2, FIdentityObjectList.Current.ID, 'The 3rd item should have taken the place of the 2nd');
FIdentityObjectList.Delete;
CheckEquals(2, FIdentityObjectList.Count, 'Deleting one of the 3 list items should yield a count of 2.');
CheckEquals(3, FIdentityObjectList.Current.ID, 'The 3rd item should have taken the place of the 2nd');
end;
procedure TestTIdentityObjectList.DeserializeCSV;
var
CSVString: string;
begin
CSVString :=
'ID,Name'#13#10
+'1,One'#13#10
+'2,Two'#13#10
+'3,Three'#13#10
;
FIdentityObjectList.Deserialize(TgSerializerCSV, CSVString);
CheckEquals(3, FIdentityObjectList.Items[2].ID);
end;
procedure TestTIdentityObjectList.DeserializeJSON;
var
JSONString: string;
begin
JSONString :=
'{"ClassName":"TestgCore.TIdentityObjectList","List":[{"ClassName":"TestgCore'+
'.TIdentityObject","ID":"1","Name":"One"},{"ClassName":"TestgCore.TIdentityOb'+
'ject","ID":"2","Name":"Two"},{"ClassName":"TestgCore.TIdentityObject","ID":"'+
'3","Name":"Three"}]}';
FIdentityObjectList.Deserialize(TgSerializerJSON, JSONString);
CheckEquals(3, FIdentityObjectList.Items[2].ID);
end;
procedure TestTIdentityObjectList.DeserializeXML;
var
XMLString: string;
begin
XMLString :=
'<xml>'#13#10 + //0
' <IdentityObjectList classname="TestgCore.TIdentityObjectList">'#13#10 + //1
' <IdentityObject classname="TestgCore.TIdentityObject">'#13#10 + //3
' <ID>1</ID>'#13#10 + //4
' <Name>One</Name>'#13#10 + //5
' </IdentityObject>'#13#10 + //6
' <IdentityObject classname="TestgCore.TIdentityObject">'#13#10 + //7
' <ID>2</ID>'#13#10 + //8
' <Name>Two</Name>'#13#10 + //9
' </IdentityObject>'#13#10 + //10
' <IdentityObject classname="TestgCore.TIdentityObject">'#13#10 + //11
' <ID>3</ID>'#13#10 + //12
' <Name>Three</Name>'#13#10 + //13
' </IdentityObject>'#13#10 + //14
' </IdentityObjectList>'#13#10 + //16
'</xml>'#13#10; //17
FIdentityObjectList.Deserialize(TgSerializerXML, XMLString);
CheckEquals(3, FIdentityObjectList.Items[2].ID);
end;
procedure TestTIdentityObjectList.Filter;
begin
Add3;
FIdentityObjectList.Active := False;
FIdentityObjectList.Where := 'ID > 1';
CheckEquals(2, FIdentityObjectList.Count);
CheckFalse(FIdentityObjectList.Active, 'We should be able to get the count without activating.');
CheckEquals(2, FIdentityObjectList.Current.ID, 'The filter should have removed ID 1.');
CheckTrue(FIdentityObjectList.Active, 'Calling Current should activate the list.')
end;
procedure TestTIdentityObjectList.ForInEmpty;
var
Item: TgIdentityObject;
Items: TgIdentityList<TIdentityObject>;
begin
Items := TgIdentityList<TIdentityObject>.Create;
for Item in Items do
CheckFalse(True,'The list should be empty');
Items.Free;
end;
procedure TestTIdentityObjectList.SerializeCSV;
var
CSVString: string;
begin
Add3;
CSVString :=
'ID,Name'#13#10
+'1,One'#13#10
+'2,Two'#13#10
+'3,Three'#13#10
;
CheckEquals(CSVString, FIdentityObjectList.Serialize(TgSerializerCSV));
end;
procedure TestTIdentityObjectList.SerializeJSON;
var
JSONString: string;
begin
Add3;
JSONString :=
'{"ClassName":"TestgCore.TIdentityObjectList","List":[{"ClassName":"TestgCore'+
'.TIdentityObject","ID":"1","Name":"One"},{"ClassName":"TestgCore.TIdentityOb'+
'ject","ID":"2","Name":"Two"},{"ClassName":"TestgCore.TIdentityObject","ID":"'+
'3","Name":"Three"}]}';
CheckEquals(JSONString, FIdentityObjectList.Serialize(TgSerializerJSON));
end;
procedure TestTIdentityObjectList.SerializeXML;
var
XMLString: string;
begin
FIdentityObjectList.Active := True;
Add3;
XMLString :=
'<xml>'#13#10 + //0
' <IdentityObjectList>'#13#10 + //1
' <IdentityObject>'#13#10 + //3
' <ID>1</ID>'#13#10 + //4
' <Name>One</Name>'#13#10 + //5
' </IdentityObject>'#13#10 + //6
' <IdentityObject>'#13#10 + //7
' <ID>2</ID>'#13#10 + //8
' <Name>Two</Name>'#13#10 + //9
' </IdentityObject>'#13#10 + //10
' <IdentityObject>'#13#10 + //11
' <ID>3</ID>'#13#10 + //12
' <Name>Three</Name>'#13#10 + //13
' </IdentityObject>'#13#10 + //14
' </IdentityObjectList>'#13#10 + //16
'</xml>'#13#10; //17
CheckEquals(3,FIdentityObjectList.Count);
CheckEquals(XMLString, FIdentityObjectList.Serialize(TgSerializerXML));
end;
procedure TestTIdentityObjectList.SetUp;
begin
FIdentityObjectList := TIdentityObjectList.Create;
FIdentityObjectList.OrderBy := 'ID';
TgIdentityObjectClass(FIdentityObjectList.ItemClass).PersistenceManager.CreatePersistentStorage;
end;
procedure TestTIdentityObjectList.TearDown;
begin
FIdentityObjectList.Free;
FIdentityObjectList := nil;
end;
procedure TestTBase3.Add3;
Const
Letters: Array[1..3] of Char = ('A', 'B', 'C');
var
Counter: Integer;
begin
for Counter := 1 to 3 do
begin
Base3.List.Add;
Base3.List.Current.IntegerProperty := Counter;
Base3.List.Current.StringProperty := Letters[Counter];
end;
end;
procedure TestTBase3.SerializeCSV;
var
CSVString: string;
begin
Base3.Name := 'One';
Add3;
CSVString :=
'IntegerProperty,StringProperty,Name,List.Count,List[0].IntegerProperty,List[0].StringProperty,List[1].IntegerProperty,List[1].StringProperty,List[2].IntegerProperty,List[2].StringProperty'#$D#$A
+'2,12345,One,3,1,A,2,B,3,C'#$D#$A;
CheckEquals(CSVString, Base3.Serialize(TgSerializerCSV));
end;
procedure TestTBase3.SerializeXML;
var
XMLString: string;
begin
Base3.Name := 'One';
Add3;
XMLString :=
'<xml>'#13#10 + //0
' <Base3>'#13#10 + //1
' <IntegerProperty>2</IntegerProperty>'#13#10 + //2
' <StringProperty>12345</StringProperty>'#13#10 + //3
' <Name>One</Name>'#13#10 + //4
' <List>'#13#10 + //5
' <List>'#13#10 + //6
' <Base2>'#13#10 + //7
' <IntegerProperty>1</IntegerProperty>'#13#10 + //8
' <StringProperty>A</StringProperty>'#13#10 + //9
' </Base2>'#13#10 + //10
' <Base2>'#13#10 + //11
' <IntegerProperty>2</IntegerProperty>'#13#10 + //12
' <StringProperty>B</StringProperty>'#13#10 + //13
' </Base2>'#13#10 + //14
' <Base2>'#13#10 + //15
' <IntegerProperty>3</IntegerProperty>'#13#10 + //16
' <StringProperty>C</StringProperty>'#13#10 + //17
' </Base2>'#13#10 + //18
' </List>'#13#10 + //19
' </List>'#13#10 + //20
' </Base3>'#13#10 + //21
'</xml>'#13#10; //22
CheckEquals(XMLString, Base3.Serialize(TgSerializerXML));
end;
procedure TestTBase3.DeserializeCSV;
var
CSVString: string;
begin
CSVString :=
'IntegerProperty,StringProperty,Name,List.Count,List[0].IntegerProperty,List[0].StringProperty,List[1].IntegerProperty,List[1].StringProperty,List[2].IntegerProperty,List[2].StringProperty'#$D#$A
+'2,12345,One,3,1,A,2,B,3,C'#$D#$A;
Base3.Deserialize(TgSerializerCSV, CSVString);
CheckEquals('One', Base3.Name);
CheckEquals('C', Base3.List[2].StringProperty);
end;
procedure TestTBase3.DeserializeXML;
var
XMLString: string;
begin
XMLString :=
'<xml>'#13#10 + //0
' <Base3 classname="TestgCore.TBase3">'#13#10 + //1
' <IntegerProperty>2</IntegerProperty>'#13#10 + //2
' <StringProperty>12345</StringProperty>'#13#10 + //3
' <Name>One</Name>'#13#10 + //4
' <List classname="TestgCore.TBase2List">'#13#10 + //5
' <List>'#13#10 + //6
' <Base2 classname="TestgCore.TBase2">'#13#10 + //7
' <IntegerProperty>1</IntegerProperty>'#13#10 + //8
' <StringProperty>A</StringProperty>'#13#10 + //9
' </Base2>'#13#10 + //10
' <Base2 classname="TestgCore.TBase2">'#13#10 + //11
' <IntegerProperty>2</IntegerProperty>'#13#10 + //12
' <StringProperty>B</StringProperty>'#13#10 + //13
' </Base2>'#13#10 + //14
' <Base2 classname="TestgCore.TBase2">'#13#10 + //15
' <IntegerProperty>3</IntegerProperty>'#13#10 + //16
' <StringProperty>C</StringProperty>'#13#10 + //17
' </Base2>'#13#10 + //18
' </List>'#13#10 + //19
' </List>'#13#10 + //20
' </Base3>'#13#10 + //21
'</xml>'#13#10; //22
Base3.Deserialize(TgSerializerXML, XMLString);
CheckEquals('One', Base3.Name);
CheckEquals('C', Base3.List[2].StringProperty);
end;
procedure TestTBase3.SetUp;
begin
inherited;
Base3 := TBase3.Create;
end;
procedure TestTBase3.TearDown;
begin
Base3.Free;
inherited;
end;
procedure TestTIDObject.Save;
begin
IDObject.Name := 'One';
IDObject.Save;
CheckEquals(1, IDObject.ID);
end;
procedure TestTIDObject.SaveChanges;
var
IDObject1: TIDObject;
IDObject2: TIDObject;
begin
IDObject.Name := 'Name';
IDObject.Name2 := 'Name2';
IDObject.Save;
IDObject1 := TIDObject.Create;
IDObject2 := TIDObject.Create;
try
IDObject1.ID := 1;
IDObject1.Load;
IDObject2.ID := 1;
IDObject2.Load;
IDObject1.Name := 'One';
IDObject1.Save;
IDObject2.Name2 := 'Two';
IDObject2.Save;
finally
IDObject2.Free;
IDObject1.Free;
end;
IDObject.Load;
CheckEquals('One', IDObject.Name, 'Value from first field');
CheckEquals('Two', IDObject.Name2, 'Value from second field');
end;
procedure TestTIDObject.SetUp;
begin
inherited;
TIDObject.PersistenceManager.CreatePersistentStorage;
IDObject := TIDObject.Create;
end;
procedure TestTIDObject.TearDown;
begin
IDObject.Free;
inherited;
end;
procedure TestTIDObject2.Add3Items;
const
Names : Array[1..3] of String = ('One', 'Two', 'Three');
var
Counter: Integer;
begin
for Counter := 1 to 3 do
begin
FIDObject2.IDObjects.Add;
FIDObject2.IDObjects.Current.Name := Names[Counter];
FIDObject2.IDObjects.Current.Save;
end;
end;
procedure TestTIDObject2.ExtendedWhere;
begin
FIDObject2.Name := 'One';
FIDObject2.IDObject.ID := 1;
FIDObject2.Save;
CheckEquals(1,FIDObject2.ID);
Add3Items;
CheckTrue(FIDObject2.IDObjects.Current.IDObject2 = FIDObject2);
FIDObject2.RemoveIdentity;
CheckEquals(0,FIDObject2.ID);
FIDObject2.Name := 'Two';
FIDObject2.IDObject.ID := 2;
CheckEquals(0, FIDObject2.IDObjects.Count);
FIDObject2.Save;
CheckEquals(2,FIDObject2.ID);
Add3Items;
FIDObject2.ID := 1;
FIDObject2.Load;
CheckEquals('One',FIDObject2.Name);
FIDObject2.IDObjects.First;
CheckEquals(3, FIDObject2.IDObjects.Count);
CheckEquals(1, FIDObject2.IDObjects.Current.ID);
FIDObject2.ID := 2;
FIDObject2.Load;
CheckEquals('Two',FIDObject2.Name);
FIDObject2.IDObjects.First;
CheckEquals(3, FIDObject2.IDObjects.Count);
CheckEquals(4, FIDObject2.IDObjects.Current.ID);
end;
procedure TestTIDObject2.Save;
begin
FIDObject2.Name := 'One';
FIDObject2.IDObject.ID := 1;
FIDObject2.Save;
FIDObject2.RemoveIdentity;
FIDObject2.Name := 'Two';
FIDObject2.IDObject.ID := 2;
FIDObject2.Save;
FIDObject2.ID := 1;
FIDObject2.Load;
CheckEquals(1, FIDObject2.IDObject.ID);
end;
procedure TestTIDObject2.SaveItem;
begin
FIDObject2.Name := 'One';
FIDObject2.IDObject.ID := 1;
FIDObject2.Save;
FIDObject2.IDObjects.Add;
FIDObject2.IDObjects.Current.Name := 'One';
FIDObject2.IDObjects.Current.Save;
end;
procedure TestTIDObject2.SetUp;
begin
inherited;
FIDObject := TIDObject.Create;
FIDObject.PersistenceManager.CreatePersistentStorage;
FIDObject.Name := 'A';
FIDObject.Save;
FIDObject.ID := 0;
FIDObject.Name := 'B';
FIDObject.Save;
FIDObject2 := TIDObject2.Create;
FIDObject2.PersistenceManager.CreatePersistentStorage;
TIDObject3.PersistenceManager.CreatePersistentStorage;
end;
procedure TestTIDObject2.TearDown;
begin
FIDObject.Free;
FIDObject2.Free;
inherited;
end;
{ TestTSerializeCSV }
procedure TestTSerializeCSV.SetUp;
begin
inherited;
FSerializer := TgSerializerCSV.Create;
end;
procedure TestTSerializeCSV.Deserialize;
var
Item: TgTest;
begin
Item := TgTest.Create;
FSerializer.Deserialize(Item,'Name,Price'#$D#$A'Judy,34.23'#$D#$A);
CheckEquals('Judy',Item.Name);
CheckEquals(34.23,Item.Price);
FreeAndNil(Item);
end;
procedure TestTSerializeCSV.DeserializeArr;
var
Item: TgTest;
begin
Item := TgTest.Create;
FSerializer.Deserialize(Item,'Name,Price,Names.Count,Names[0].Name,Names[1].Name'#$D#$A'Judy,34.23,2,Hello,There'#$D#$A);
CheckEquals('Judy',Item.Name);
CheckEquals(34.23,Item.Price);
CheckEquals(2,Item.Names.Count);
CheckEquals('Hello',Item.Names[0].Name);
CheckEquals('There',Item.Names[1].Name);
FreeAndNil(Item);
end;
procedure TestTSerializeCSV.DeserializeCRLF;
var
List: TgList<TgTest>;
S: String;
begin
S := 'Name,Price'#$D#$A'"Jim'#$A'Barney",12.3'#$D#$A'"Fred'#$A'Mosbie",50'#$D#$A;
List := TgList<TgTest>.Create;
FSerializer.Deserialize(List,S);
List.First;
CheckFalse(List.EOL);
CheckEquals('Jim'#$A'Barney',List.Current.Name);
CheckEquals(12.30,List.Current.Price);
List.Next;
CheckFalse(List.EOL);
CheckEquals('Fred'#$A'Mosbie',List.Current.Name);
CheckEquals(50,List.Current.Price);
List.Next;
CheckTrue(List.EOL);
FreeAndNil(List);
end;
procedure TestTSerializeCSV.DeserializeList;
var
List: TgList<TgTest>;
S: String;
begin
S := 'Name,Price'#$D#$A'Jim,12.3'#$D#$A'Fred,50'#$D#$A;
List := TgList<TgTest>.Create;
FSerializer.Deserialize(List,S);
List.First;
CheckFalse(List.EOL);
CheckEquals('Jim',List.Current.Name);
CheckEquals(12.30,List.Current.Price);
List.Next;
CheckFalse(List.EOL);
CheckEquals('Fred',List.Current.Name);
CheckEquals(50,List.Current.Price);
List.Next;
CheckTrue(List.EOL);
FreeAndNil(List);
end;
procedure TestTSerializeCSV.Serialize;
var
Item: TgTest;
S: String;
begin
Item := TgTest.Create;
Item.Name := 'Judy';
Item.Price := 34.23;
CheckEquals('Name,Price'#$D#$A'Judy,34.23'#$D#$A,FSerializer.Serialize(Item));
Item.Names.Add;
Item.Names.Current.Name := 'Hello';
Item.Names.Add;
Item.Names.Current.Name := 'There';
S := FSerializer.Serialize(Item);
CheckEquals('Name,Price,Names.Count,Names[0].Name,Names[1].Name'#$D#$A'Judy,34.23,2,Hello,There'#$D#$A,S);
FreeAndNil(Item);
end;
procedure TestTSerializeCSV.SerializeCRLF;
var
List: TgList<TgTest>;
S: String;
begin
List := TgList<TgTest>.Create;
List.Add;
List.Current.Name := 'Jim'#10'Barney';
List.Current.Price := 12.30;
List.Add;
List.Current.Name := 'Fred'#10'Mosbie';
List.Current.Price := 50;
S := FSerializer.Serialize(List);
CheckEquals('Name,Price'#$D#$A'"Jim'#$A'Barney",12.3'#$D#$A'"Fred'#$A'Mosbie",50'#$D#$A,S);
FreeAndNil(List);
end;
procedure TestTSerializeCSV.SerializeList;
var
List: TgList<TgTest>;
S: String;
begin
List := TgList<TgTest>.Create;
List.Add;
List.Current.Name := 'Jim';
List.Current.Price := 12.30;
List.Add;
List.Current.Name := 'Fred';
List.Current.Price := 50;
S := FSerializer.Serialize(List);
CheckEquals('Name,Price'#$D#$A'Jim,12.3'#$D#$A'Fred,50'#$D#$A,S);
FreeAndNil(List);
end;
procedure TestTSerializeCSV.TearDown;
begin
FreeAndNil(FSerializer);
inherited;
end;
(*
{ TestTgNodeCSV }
procedure TestTgNodeCSV.ColumnName;
begin
FNode.Values['Name'] := 'Jim';
FNode.Values['Price'] := '12.50';
end;
procedure TestTgNodeCSV.NestedColumnName;
var Node: TgNodeCSV;
begin
FNode.Add('Name','Jim');
FNode.Add('Price','12.50');
CheckEquals('Name',FNode.ColumnNames[0]);
CheckEquals('Price',FNode.ColumnNames[1]);
Node := FNode.AddChild('SubStuff');
Node.Add('Item','Juice');
Node.Add('Category','Liquid');
CheckEquals('SubStuff.Item',Node.ColumnNames[0]);
CheckEquals('SubStuff.Category',Node.ColumnNames[1]);
end;
procedure TestTgNodeCSV.SetUp;
begin
inherited;
FNode := TgNodeCSV.Create(nil);
end;
procedure TestTgNodeCSV.TearDown;
begin
FNode.Free;
inherited;
end;
*)
{ TestTSerializeCSV.TgTest }
constructor TestTSerializeCSV.TgTest.Create(AOwner: TgBase);
begin
inherited;
FNames := TgList<TgName>.Create(Self);
end;
{ TestHTMLParser }
procedure TestHTMLParser.AssignTag;
var
Text: String;
gCustomer: TCustomer;
begin
gCustomer := TCustomer.Create;
try
CheckEquals('',gCustomer.FirstName);
Text :=
// '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'#13#10+
// '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>Untitled <b>Document</b>S</title></head><body></body></html>';
'<html xmlns="http://www.w3.org/1999/xhtml">'#$D#$A+
' <head xmlns="">'#$D#$A+
' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'#$D#$A+
' <title>Untitled <b>Document</b>'#$D#$A+
' S</title>'#$D#$A+
' </head>'#$D#$A+
' <body>'#$D#$A+
' <assign condition="GoodCustomer" Name="FirstName" value="DeadMeat" />'#$D#$A+
' </body>'#$D#$A+
'</html>'#$D#$A;
gCustomer.GoodCustomer := False;
CheckEquals(
'<html xmlns="http://www.w3.org/1999/xhtml">'#$D#$A
+' <head xmlns="">'#$D#$A
+' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'#$D#$A
+' <title>Untitled <b>Document</b>'#$D#$A
+' '#$D#$A
+' S</title>'#$D#$A
+' </head>'#$D#$A
+' <body xmlns=""/>'#$D#$A
+'</html>'#$D#$A
,TgDocument._ProcessText(Text,gCustomer));
CheckEquals('',gCustomer.FirstName);
gCustomer.GoodCustomer := True;
CheckEquals('',gCustomer['FirstName']);
Text := TgDocument._ProcessText(Text,gCustomer);
CheckEquals(
'<html xmlns="http://www.w3.org/1999/xhtml">'#$D#$A
+' <head xmlns="">'#$D#$A
+' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'#$D#$A
+' <title>Untitled <b>Document</b>'#$D#$A
+' '#$D#$A
+' S</title>'#$D#$A
+' </head>'#$D#$A
+' <body xmlns=""/>'#$D#$A
+'</html>'#$D#$A
,Text);
CheckEquals('DeadMeat',gCustomer.FirstName);
finally
gCustomer.Free;
end;
end;
procedure TestHTMLParser.Convert1;
var
Text: String;
begin
Text :=
// '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'#13#10+
// '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>Untitled <b>Document</b>S</title></head><body></body></html>';
'<html xmlns="http://www.w3.org/1999/xhtml">'#$D#$A+
' <head xmlns="">'#$D#$A+
' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'#$D#$A+
' <title>Untitled <b>Document</b>'#$D#$A+
' S</title>'#$D#$A+
' </head>'#$D#$A+
' <body xmlns=""/>'#$D#$A+
'</html>'#$D#$A;
Text := TgDocument._ProcessText(Text);
CheckEquals(
'<html xmlns="http://www.w3.org/1999/xhtml">'#$D#$A
+' <head xmlns="">'#$D#$A
+' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'#$D#$A
+' <title>Untitled <b>Document</b>'#$D#$A
+' '#$D#$A
+' S</title>'#$D#$A
+' </head>'#$D#$A
+' <body xmlns=""/>'#$D#$A
+'</html>'#$D#$A
,Text);
end;
procedure TestHTMLParser.gForm;
var
Customer: TCustomer;
Text: String;
begin
Customer := TCustomer.Create;
try
Customer.FirstName := 'David';
Customer.MiddleInitial := 'B';
Customer.LastName := 'Harper';
Customer.Webcontent := '<b>{FirstName}</b><br />{LastName}';
Customer.Notes := '<b>{FirstName}'#13#10'{LastName}</b>';
Customer.Enum1 := ePurse;
Customer.IntValue := 2341;
Customer.SingleValue := 342.122;
Customer.EnumSet1 := [ePurse,eBag];
Customer.EnumSet2 := [dCalifornia,dAustin,dTexas,dAlisoViejo];
Customer.GoodCustomer := True;
Text := '<gform/>';
CheckEquals(''
,TgDocument._ProcessText(Text,Customer));
finally
FreeAndNil(Customer);
end;
end;
procedure TestHTMLParser.HTMLField;
var
Customer: TCustomer;
Text: String;
begin
Customer := TCustomer.Create;
try
Customer.FirstName := 'David';
Customer.LastName := 'Harper';
Customer.Webcontent := '<b>{FirstName}</b><br />{LastName}';
Customer.Notes := '<b>{FirstName}'#13#10'{LastName}</b>';
Text := '<html><div>{WebContent}</div><div>{Notes}</div></html>';
CheckEquals('<html>'#$D#$A
+' <div>'#$D#$A
+' <b>David</b>'#$D#$A
+' <br/>'#$D#$A
+' Harper</div>'#$D#$A
+' <div><b>{FirstName}'#$D#$A
+'{LastName}</b></div>'#$D#$A
+'</html>'#$D#$A
,TgDocument._ProcessText(Text,Customer));
finally
FreeAndNil(Customer);
end;
end;
procedure TestTFirebirdObject.Save;
var
NewFirebirdObject: TFirebirdObject;
begin
FFirebirdObject.Name := 'One';
FFirebirdObject.Save;
NewFirebirdObject := TFirebirdObject.Create;
try
NewFirebirdObject.ID := FFirebirdObject.ID;
CheckTrue(NewFirebirdObject.Load);
NewFirebirdObject.Name := 'Two';
NewFirebirdObject.Save;
finally
NewFirebirdObject.Free;
end;
NewFirebirdObject := TFirebirdObject.Create;
try
NewFirebirdObject.ID := FFirebirdObject.ID;
NewFirebirdObject.Load;
CheckEquals('Two', NewFirebirdObject.Name);
NewFirebirdObject.Delete;
finally
NewFirebirdObject.Free;
end;
NewFirebirdObject := TFirebirdObject.Create;
try
NewFirebirdObject.ID := FFirebirdObject.ID;
CheckFalse(NewFirebirdObject.Load);
finally
NewFirebirdObject.Free;
end;
end;
{ TestTFirebirdObject }
procedure TestTFirebirdObject.SetUp;
begin
inherited;
FFirebirdObject := TFirebirdObject.Create;
end;
procedure TestTFirebirdObject.TearDown;
begin
FreeAndNil(FFirebirdObject);
inherited;
end;
procedure TestHTMLParser.ifTag;
var
Text: String;
gCustomer: TCustomer;
begin
gCustomer := TCustomer.Create;
gCustomer.FirstName := 'Steve';
gCustomer.LastName := 'Nooner';
try
Text :=
'<html xmlns="http://www.w3.org/1999/xhtml">'#13#10
+'<if condition="GoodCustomer">'#13#10
+'Hello'#13#10
+'<then>{FirstName}, You are awesome!</then>'#13#10
+'<else>{LastName}, Try to do better :(</else>'#13#10
+'</if>'#13#10
+'</html>';
gCustomer.GoodCustomer := True;
CheckEquals('<html xmlns="http://www.w3.org/1999/xhtml">Steve, You are awesome!</html>'#$D#$A,TgDocument._ProcessText(Text,gCustomer));
gCustomer.GoodCustomer := False;
CheckEquals('<html xmlns="http://www.w3.org/1999/xhtml">Nooner, Try to do better :(</html>'#$D#$A,TgDocument._ProcessText(Text,gCustomer));
Text :=
'<html xmlns="http://www.w3.org/1999/xhtml">'#13#10
+'<if condition="GoodCustomer">'#13#10
+'{FirstName}, You are awesome!'#13#10
+'</if>'#13#10
+'</html>';
gCustomer.GoodCustomer := True;
CheckEquals('<html xmlns="http://www.w3.org/1999/xhtml">'#$D#$A
+'Steve, You are awesome!'#$D#$A
+'</html>'#$D#$A
,TgDocument._ProcessText(Text,gCustomer));
gCustomer.GoodCustomer := False;
CheckEquals('<html xmlns="http://www.w3.org/1999/xhtml"/>'#$D#$A
,TgDocument._ProcessText(Text,gCustomer));
finally
gCustomer.Free;
end;
end;
procedure TestHTMLParser.IncludeTag;
var
gCustomer: TCustomer;
begin
gCustomer := TCustomer.Create;
with TStringList.Create do try
gCustomer := TCustomer.Create;
gCustomer.FirstName := 'Steve';
gCustomer.LastName := '<b>Nooner</b>';
gCustomer.WebContent := '<b>Hello</b>';
Add('<html>{WebContent}{LastName}</html>');
SaveToFile('YYY.hti');
Text :=
// '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'#13#10
'<html xmlns="http://www.w3.org/1999/xhtml">'#13#10
+'<head>'#13#10
+'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'#13#10
+'<title>Untitled<b> Document</b>!</title>'#13#10
+'</head>'#13#10
+'<body>'#13#10
+'<include FileName="YYY.hti" SearchPath=""/>'#13#10
+'</body>'#13#10
+'</html>'#13#10;
CheckEquals(
'<html xmlns="http://www.w3.org/1999/xhtml">'#$D#$A
+' <head xmlns="">'#$D#$A
+' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'#$D#$A
+' <title>Untitled <b> Document</b>'#$D#$A
+' !</title>'#$D#$A
+' </head>'#$D#$A
+' <body xmlns="">'#$D#$A
+' <b>Hello</b>'#$D#$A
+' <b>Nooner</b></body>'#$D#$A
+'</html>'#$D#$A
,TgDocument._ProcessText(Text,gCustomer));
finally
DeleteFile('YYY.hti');
Free;
gCustomer.Free;
end;
with TStringList.Create do try
Add('<b>{2 + 2}</b>');
SaveToFile('YYY.hti');
Text :=
// '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'#13#10
'<html xmlns="http://www.w3.org/1999/xhtml">'#13#10
+'<head>'#13#10
+'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'#13#10
+'<title>Untitled<b> Document</b>!</title>'#13#10
+'</head>'#13#10
+'<body>'#13#10
+'<include FileName="YYY.hti" SearchPath=""/>'#13#10
+'</body>'#13#10
+'</html>'#13#10;
CheckEquals(
'<html xmlns="http://www.w3.org/1999/xhtml">'#$D#$A
+' <head xmlns="">'#$D#$A' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'#$D#$A
+' <title>Untitled <b> Document</b>'#$D#$A
+' !</title>'#$D#$A' </head>'#$D#$A
+' <body xmlns="">'#$D#$A
+' <b>{2 + 2}</b>'#$D#$A
+' </body>'#$D#$A
+'</html>'#$D#$A
{ TODO : What should this do with no gBase? }
,TgDocument._ProcessText(Text));
finally
DeleteFile('YYY.hti');
Free;
end;
end;
procedure TestHTMLParser.ListTag;
var
Text: String;
Model: TModel;
begin
Model := TModel.Create;
try
Model.Customers.Add;
Model.Customers.Current.FirstName := 'Steve<>';
Model.Customers.Current.LastName:= 'Joe & Jerry';
Model.Customers.Current.WebAddress := 'http://www.google.com';
Model.Customers.Add;
Model.Customers.Current.FirstName := 'Jim';
Model.Customers.Current.LastName := '<Bush>';
Model.Customers.Current.WebAddress := 'http://www.yahoo.com';
Text :=
// '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'#13#10
'<html xmlns="http://www.w3.org/1999/xhtml">'#13#10
+'<head>'#13#10
+'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'#13#10
+'<title>Untitled<b> Document</b>!</title>'#13#10
+'</head>'#13#10
+'<body>'#13#10
+' <b conditionSelf="Customers.Count = 1" >Count</b>'
+' <list condition="Customers.Count > 1" object="Customers">'#13#10 //DoList
// +' <a href="{WebAddress}">{if(FirstName <> '',FirstName)}</a><br />'#13#10
+' <a href="{WebAddress}">{FirstName} {LastName}</a><br />'#13#10
// <div conditionself="ValidationErrors.Name" class="Error">Name</div>
+' </list>'#13#10
+'</body>'#13#10
+'</html>'#13#10;
Text := TgDocument._ProcessText(Text,Model);
CheckEquals('<html xmlns="http://www.w3.org/1999/xhtml">'#$D#$A
+' <head xmlns="">'#$D#$A
+' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'#$D#$A
+' <title>Untitled <b> Document</b>'#$D#$A
+' !</title>'#$D#$A
+' </head>'#$D#$A
+' <body xmlns="">Count <a href="http://www.google.com">Steve<> Joe & Jerry</a>'#$D#$A
+' <br/>'#$D#$A
+' <a href="http://www.yahoo.com">Jim <Bush></a>'#$D#$A
+' <br/>'#$D#$A
+' </body>'#$D#$A
+'</html>'#$D#$A
,Text);
// TargetDocument.SaveToXML(TextResult);
finally
Model.Free;
end;
end;
procedure TestHTMLParser.Replace;
var
Customer: TCustomer;
Element: TgElement;
AIsHTML: Boolean;
begin
Customer := TCustomer.Create;
Customer.FirstName := 'Steve';
Customer.LastName := 'Nooner';
Customer.WebContent := 'Hello';
Customer.WebAddress := 'http://www.google.com';
try
Element := TgElement.Create;
try
Element.gBase := Customer;
CheckEquals('Hello',Element.ProcessValue('Hello'));
CheckEquals(Customer.FirstName+Customer.FirstName+'X',Element.ProcessValue('{FirstName}{FirstName}X'));
CheckEquals(Customer.FirstName+'X'+Customer.LastName.Value,Element.ProcessValue('{FirstName}X{LastName}'));
CheckEquals(Customer.FirstName,Element.ProcessValue('{FirstName}'));
CheckEquals(Customer.FirstName+Customer.LastName.Value,Element.ProcessValue('{FirstName}{LastName}'));
CheckEquals('X'+Customer.FirstName+Customer.LastName.Value,Element.ProcessValue('X{FirstName}{LastName}'));
CheckEquals('X'+Customer.FirstName+'X'+Customer.LastName.Value+'X',Element.ProcessValue('X{FirstName}X{LastName}X'));
CheckEquals(Customer.FirstName,Element.ProcessValue('{FirstName}'));
CheckEquals(Customer.WebAddress,Element.ProcessValue('{WebAddress}'));
CheckEquals(Customer.WebAddress,Element.ProcessValue('{WebAddress}'));
CheckEquals('<p>Hi, '+Customer.FirstName+'</p>',Element.ProcessValue('<p>Hi, {FirstName}</p>'));
CheckEquals('<p>Hi, '+Customer.FirstName+' '+Customer.LastName.Value+'</p>',Element.ProcessValue('<p>Hi, {FirstName} {LastName}</p>'));
CheckEquals('<p>Hi, Mr. '+Customer.LastName+'</p>',Element.ProcessValue('<p>Hi, {''Mr. '' + LastName}</p>'));
CheckEquals(Customer.WebAddress,EvalHTML('WebAddress',Customer,AIsHTML));
CheckFalse(AIsHTML);
CheckEquals(Customer.WebContent,EvalHTML('WebContent',Customer,AIsHTML));
CheckTrue(AIsHTML);
//Evaluate('<p>Hello {Name}</p>', Customer)
finally
Element.Free;
end;
finally
Customer.Free;
end;
end;
procedure TestHTMLParser.WithTag;
var
Text: String;
gCustomer: TCustomer;
gCustomer2: TCustomer;
begin
gCustomer := TCustomer.Create;
gCustomer.FirstName := 'Steve';
gCustomer.LastName := 'Nooner';
gCustomer2 := TCustomer.Create;
gCustomer2.FirstName := 'Linda';
gCustomer2.LastName := 'Evans';
gCustomer.OtherCustomer := gCustomer2;
try
Text :=
// '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'#13#10
'<html xmlns="http://www.w3.org/1999/xhtml">'#13#10
+'<head>'#13#10
+'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'#13#10
+'</head>'#13#10
+'<body>'#13#10
+'{FirstName}'#13#10
+'<with object="OtherCustomer">'#13#10
+'{FirstName} {LastName}'#13#10
+'</with>'#13#10
+'{LastName}'#13#10
+'</body>'#13#10
+'</html>'#13#10;
gCustomer.GoodCustomer := True;
CheckEquals('<html xmlns="http://www.w3.org/1999/xhtml">'#$D#$A' <head xmlns="">'#$D#$A' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'#$D#$A' </head>'#$D#$A' <body xmlns="">'#$D#$A'Steve'#$D#$A#$D#$A'Linda Evans'#$D#$A#$D#$A'Nooner'#$D#$A'</body>'#$D#$A'</html>'#$D#$A
,TgDocument._ProcessText(Text,gCustomer));
(*
gCustomer.GoodCustomer := False;
CheckEquals('',TgElement._ProcessText(Text,gCustomer));
*)
finally
gCustomer.OtherCustomer := nil;
gCustomer2.Free;
gCustomer.Free;
end;
end;
procedure TestEvalHTML.Eval;
var
IsHTML: Boolean;
begin
EvalHTML('HTMLString', TestObject, IsHTML);
CheckTrue(IsHTML);
EvalHTML('NonHTMLString', TestObject, IsHTML);
CheckFalse(IsHTML);
end;
procedure TestEvalHTML.SetUp;
begin
TestObject := TTest.Create;
end;
procedure TestEvalHTML.TearDown;
begin
TestObject.Free;
end;
{ TestHTMLParser.TCustomer }
procedure TestHTMLParser.TCustomer.ClickIt;
begin
end;
function TestHTMLParser.TCustomer.GetFullName: String;
begin
Result := Format('%s %s',[FirstName, LastName.Value]);
end;
{ TestMemo }
procedure TestMemo.Test;
var
Data: TTest;
begin
Data := TTest.Create;
Data['Memo'] := 'Hello'#13#10'There';
CheckEquals('Hello'#13#10'There'#13#10,Data['Memo']);
CheckEquals(2,Data.Memo.Count);
CheckEquals('Hello',Data.Memo[0]);
CheckEquals('There',Data.Memo[1]);
CheckEquals(1,Data.Memo.IndexOf('There'));
FreeAndNil(Data);
end;
{ TestClassProperty }
procedure TestClassProperty.Test;
var
Data: TTest;
begin
Data := TTest.Create;
CheckEquals('',Data['BaseClass']);
Data.BaseClass := TTest;
CheckEquals('TestgCore.TestClassProperty.TTest',Data['BaseClass']);
Data.BaseClass := nil;
Data['BaseClass'] := 'TestgCore.TestClassProperty.TTest';
// Data['BaseClass'] := 'TgBase';
CheckEquals(NativeInt(Data.BaseClass),NativeInt(TTest));
FreeAndNil(Data);
end;
{ TestCookie }
procedure TestWebCookie.Test;
var
Cookie: TgWebCookie;
S: String;
begin
Cookie.Expire := StrToDateTime('7/8/2012 12:34:56.789');
Cookie.ID := $F0F0ABCD;
S := Cookie.Value;
CheckEquals('CA4EE22315AF14AF2064E062A4352AAE',S);
FillChar(Cookie,Sizeof(Cookie),0);
Cookie.SetValue(S);
CheckEquals('7/8/2012 12:34:56 PM',DateTimeToStr(Cookie.Expire));
CheckEquals(Integer($F0F0ABCD),Cookie.ID);
end;
{ TestTgDictionary }
procedure TestTgDictionary.CheckPaths;
var
Index: Integer;
PathValue: TgBase.TPathValue;
begin
FMy.Name := 'Name';
FMy['Value8'] := 'Yea!';
Index := 0;
for PathValue in FMy do begin
case Index of
0: CheckEquals('Name',PathValue);
1: CheckEquals('Yea!',PathValue);
end;
Inc(Index);
end;
CheckEquals(0,FMy.GetPathIndexOf('Name'));
CheckEquals(1,FMy.GetPathIndexOf('Value8'));
end;
procedure TestTgDictionary.SetUp;
begin
inherited;
FMy := TMy.Create;
end;
procedure TestTgDictionary.TearDown;
begin
FreeAndNil(FMy);
inherited;
end;
{ TestTgWebServerController }
procedure TestTgWebServerController.DefaultConfig;
begin
FWebServerController.ReadConfigurationData
end;
procedure TestTgWebServerController.SetUp;
begin
inherited;
// Write files to disk
with TStringList.Create do try
Add(DefaultHtmlContent);
SaveToFile(G.DataPath+'default.html',TEncoding.Unicode);
finally
Free;
end;
with TStringList.Create do try
Add(DefaulthtmContent);
SaveToFile(G.DataPath+'default.htm',TEncoding.Unicode);
finally
Free;
end;
with TStringList.Create do try
Add(WebConfigurationDataContent);
TgWebServerController.ReadConfigurationData(procedure(WSCCD: TgWebServerControllerConfigurationData)
begin
SaveToFile(WSCCD.FileName); { TODO : Wrong Folder. for some reason this goes to the root folder with the file }
end);
finally
Free;
end;
FWebServerController := TgWebServerController.Create;
FWebServerController.WriteConfiguationData(procedure(WSCCD: TgWebServerControllerConfigurationData)
var
RM: TgRequestMap;
begin
// Because the WSCCD is
if WSCCD.Hosts.Count > 0 then exit;
WSCCD.TemplateFileExtensions.Add('html');
WSCCD.Hosts.Add;
CheckEquals(1,WSCCD.Hosts.Count);
RM := WSCCD.Hosts.Current;
RM.BasePath := G.DataPath;
RM.SearchPath := '.';
RM.ID := 'g.com';
RM.DefaultPage := 'default.html';
CheckEquals(0,WSCCD.Hosts.IndexOf('g.com'));
WSCCD.Hosts.Add;
CheckEquals(2,WSCCD.Hosts.Count);
RM := WSCCD.Hosts.Current;
RM.BasePath := G.DataPath;
RM.SearchPath := '.';
RM.ID := 'gm.com';
RM.ModelClass := TModel;
RM.DefaultPage := 'default.html';
CheckEquals(0,WSCCD.Hosts.IndexOf('g.com'));
WSCCD.Hosts.Add;
CheckEquals(3,WSCCD.Hosts.Count);
RM := WSCCD.Hosts.Current;
RM.BasePath := G.DataPath;
RM.SearchPath := '.';
RM.ID := 'gmr.com';
RM.ModelClass := TModel;
RM.URLHandler := TgRestURLHandler;
end);
end;
procedure TestTgWebServerController.TearDown;
begin
FreeAndNil(FWebServerController);
inherited;
end;
procedure TestTgWebServerController.TestModel;
var
MyClass: TObject;
Str: AnsiString;
begin
FWebServerController.Request.Method := 'GET';
FWebServerController.Request.Host := 'gm.com';
CheckEquals('gm.com',FWebServerController.Request.Host);
FWebServerController.Request.URI := 'default.html';
FWebServerController.Execute;
Str := FWebServerController.Response.Text;
// String list added the #13#10
// CheckEquals(DefaulthtmlContent+#13#10,SL.Text);
CheckEquals(
'<html>'#13#10
+' <body>Hello!</body>'#13#10
+'</html>'#13#10
,Str);
end;
procedure TestTgWebServerController.TestNoModel;
begin
FWebServerController.Request.Method := 'GET';
FWebServerController.Request.Host := 'g.com';
CheckEquals('g.com',FWebServerController.Request.Host);
FWebServerController.Request.URI := 'default.html';
FWebServerController.Execute;
with TStringList.Create do try
LoadFromStream(FWebServerController.Response.ContentStream);
// String list added the #13#10
CheckEquals(DefaulthtmlContent+#13#10,Text);
finally
Free;
end;
end;
procedure TestTgWebServerController.TestRest;
begin
FWebServerController.Request.Method := 'GET';
FWebServerController.Request.Host := 'gmr.com';
FWebServerController.Request.URI := 'Customers/';
// FWebServerController.Request.QueryFields['ID'] := '3';
FWebServerController.Execute;
// FWebServerController.Response.
with TStringList.Create do try
LoadFromStream(FWebServerController.Response.ContentStream);
// String list added the #13#10
CheckEquals(1,Count);
CheckEquals(DefaulthtmlContent+#13#10,Text);
finally
Free;
end;
FWebServerController.Request.Method := 'GET';
FWebServerController.Request.Host := 'gmr.com';
FWebServerController.Execute;
// FWebServerController.Response.
with TStringList.Create do try
LoadFromStream(FWebServerController.Response.ContentStream);
// String list added the #13#10
CheckEquals(1,Count);
CheckEquals(DefaulthtmlContent+#13#10,Text);
finally
Free;
end;
end;
{ TestTgWebUI }
procedure TestTgWebUI.AnsiChar;
var
S: String;
begin
S := TgWebUIBase.ToString('AnsiCharValue',FDataClass);
CheckEquals('<div name="grpAnsiCharValue"><label id="lblAnsiCharValue" for="AnsiCharValue">Ansi Char Value</label><input type="text" id="AnsiCharValue" name="AnsiCharValue" size="1" maxlength="1" /></div>',S);
FData.AnsiCharValue := 'F';
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpAnsiCharValue">'#$D#$A
+' <label id="lblAnsiCharValue" for="AnsiCharValue">Ansi Char Value</label>'#$D#$A
+' <input type="text" id="AnsiCharValue" name="AnsiCharValue" size="1" maxlength="1" value="F"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.Bool;
var
S: String;
begin
// Generate Template
S := TgWebUIBase.ToString('Bool',FDataClass);
CheckEquals('<div name="grpBool"><label id="lblBool" for="Bool">Bool</label><input type="checkbox" id="Bool" name="Bool" value="true" /></div>',S);
// Run Template evaulator on text
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpBool">'#$D#$A
+' <label id="lblBool" for="Bool">Bool</label>'#$D#$A
+' <input type="hidden" name="Bool" value=""/>'#$D#$A
+' <input type="checkbox" id="Bool" name="Bool" value="true"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.Char;
var
S: String;
begin
S := TgWebUIBase.ToString('CharValue',FDataClass);
CheckEquals('<div name="grpCharValue"><label id="lblCharValue" for="CharValue">Char Value</label><input type="text" id="CharValue" name="CharValue" size="1" maxlength="1" /></div>',S);
FData.CharValue := 'Q';
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpCharValue">'#$D#$A
+' <label id="lblCharValue" for="CharValue">Char Value</label>'#$D#$A
+' <input type="text" id="CharValue" name="CharValue" size="1" maxlength="1" value="Q"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.CheckBox_true;
var
AStr,S: String;
begin
AStr := TgWebUIBase.ToString('Bool',FDataClass);
CheckEquals('<div name="grpBool"><label id="lblBool" for="Bool">Bool</label><input type="checkbox" id="Bool" name="Bool" value="true" /></div>',AStr);
FData.Bool := true;
FDocument.ProcessText('<html>'+AStr+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpBool">'#$D#$A
+' <label id="lblBool" for="Bool">Bool</label>'#$D#$A
+' <input type="hidden" name="Bool" value=""/>'#$D#$A
+' <input type="checkbox" id="Bool" name="Bool" value="true" checked="checked"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.CurrencyValue;
var
S: String;
begin
S := TgWebUIBase.ToString('CurrencyValue',FDataClass);
CheckEquals('<div name="grpCurrencyValue"><label id="lblCurrencyValue" for="CurrencyValue">Currency Value</label><input type="text" id="CurrencyValue" name="CurrencyValue" size="26" maxlength="26" /></div>',S);
FData.CurrencyValue:= 19.95;
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpCurrencyValue">'#$D#$A
+' <label id="lblCurrencyValue" for="CurrencyValue">Currency Value</label>'#$D#$A
+' <input type="text" id="CurrencyValue" name="CurrencyValue" size="26" maxlength="26" value="19.95"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.CurrentKeyPathNameAdd;
var
S: String;
begin
S :=
'<form object="Customers.Current">'
+'<label id="lblTitle" for="inpTitle">Titie</label>'
+'<input type="text" id="inpTitle" name="Title" />'
+'</form>';
// if it has a value then it knows it needs to put a hidden input for current key
// Look to the current and see if it has idenity if it doesn't then its new
FModel.Customers.Active := True; // ToDo: Should I have to do this
FModel.Customers.Buffered := True;
FModel.Customers.Add;
CheckEquals(0,FModel.Customers.CurrentIndex);
FModel.Customers.Add;
CheckEquals(0,FModel.Customers.Current.ID);
FModel.Customers.Current.ID := 1;
FModel.Customers.Current.IsLoaded := True;
CheckEquals(1,FModel.Customers.Current.ID);
CheckEquals(1,FModel.Customers.CurrentIndex);
CheckEquals('',FMOdel.Customers.CurrentKey);
FModel.Customers.Add;
CheckEquals(0,FModel.Customers.Current.ID);
FModel.Customers.Current.ID := 2;
FModel.Customers.Current.IsLoaded := True;
CheckEquals(2,FModel.Customers.Current.ID);
CheckEquals(2,FModel.Customers.CurrentIndex);
FModel.Customers.CurrentKey := '1';
CheckEquals(1,FModel.Customers.Current.ID);
CheckEquals('1', FModel.Customers.CurrentKey);
FDocument.ProcessText('<html>'+S+'</html>',S,FModel);
CheckEquals(
'<html>'#$D#$A
+' <form>'#$D#$A
// <input type="hidden" value="2" name="List1.CurrentIndex">
+' <input type="hidden" value="1" name="Customers.CurrentKey"/>'#$D#$A
+' <label id="lblTitle" for="inpTitle">Titie</label>'#$D#$A
+' <input type="text" id="inpTitle" name="Customers.Current.Title" value="Salesperson"/>'#$D#$A
+' <input type="hidden" name="Customers.Current.OriginalValues.Title" value="Salesperson"/>'#$D#$A
+' </form>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.CurrentObjectPathName;
var
S: String;
begin
S :=
'<div object="Customers">'
+'<form object="Current">'
+'<input type="text" id="inpTitle" name="Title" />'
+'<input type="text" id="inpTitle" name="Owner.Owner.Customer.Title" />' //we shouldn't ever use
+'<input type="text" id="inpTitle" name="Model.Customer.Title" />'
+'</form>'
+'</div>';
FModel.Customer.Title := 'CFO';
FModel.Customers.Add;
FModel.Customers.Current.Title := 'CGO';
FModel.Customers.Save;
CheckTrue(FModel.Customers.Current.Owner = FModel.Customers);
CheckTrue(FModel.Customers.Current.Owner.Owner = FModel);
FDocument.ProcessText('<html>'+S+'</html>',S,FModel);
CheckEquals(
'<html>'#13#10 + //0
' <div>'#13#10 + //1
' <form>'#13#10 + //2
' <input type="hidden" value="" name="Customers.CurrentKey"/>'#13#10 + //3
' <input type="text" id="inpTitle" name="Customers.Current.Title" value="CGO"/>'#13#10 + //4
' <input type="hidden" name="Customers.Current.OriginalValues.Title" value="CGO"/>'#13#10 + //5
' <input type="text" id="inpTitle" name="Owner.Owner.Customer.Title" value="CFO"/>'#13#10 + //6
' <input type="hidden" name="Owner.Owner.Customer.Title" value="CFO"/>'#13#10 + //7
' <input type="text" id="inpTitle" name="Model.Customer.Title" value="CFO"/>'#13#10 + //8
' <input type="hidden" name="Model.Customer.Title" value="CFO"/>'#13#10 + //9
' </form>'#13#10 + //10
' </div>'#13#10 + //11
'</html>'#13#10 //12
,S);
end;
procedure TestTgWebUI.DoubleValue;
var
S: String;
begin
S := TgWebUIBase.ToString('DoubleValue',FDataClass);
CheckEquals('<div name="grpDoubleValue"><label id="lblDoubleValue" for="DoubleValue">Double Value</label><input type="text" id="DoubleValue" name="DoubleValue" size="22" maxlength="22" /></div>',S);
FData.DoubleValue:= 1.2;
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpDoubleValue">'#$D#$A
+' <label id="lblDoubleValue" for="DoubleValue">Double Value</label>'#$D#$A
+' <input type="text" id="DoubleValue" name="DoubleValue" size="22" maxlength="22" value="1.2"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.Enum1;
var
S: String;
begin
S := TgWebUIBase.ToString('Enum1',FDataClass);
CheckEquals(
'<div name="grpEnum1">'
+'<label id="lblEnum1" for="Enum1">Enum 1</label><input type="radio" name="Enum1" id="Enum1_h" value="h" title="(none)"/>'
+'<label id="lblEnum1_h" for="Enum1_h">(none)</label><input type="radio" name="Enum1" id="Enum1_hPurse" value="hPurse" title="Purse"/>'
+'<label id="lblEnum1_hPurse" for="Enum1_hPurse">Purse</label><input type="radio" name="Enum1" id="Enum1_hCar" value="hCar" title="Car"/>'
+'<label id="lblEnum1_hCar" for="Enum1_hCar">Car</label><input type="radio" name="Enum1" id="Enum1_hTelephone" value="hTelephone" title="Telephone"/>'
+'<label id="lblEnum1_hTelephone" for="Enum1_hTelephone">Telephone</label>'
+'</div>' ,S);
FData.Enum1 := hPurse;
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpEnum1">'#$D#$A
+' <label id="lblEnum1" for="Enum1">Enum 1</label>'#$D#$A
+' <input type="radio" name="Enum1" id="Enum1_h" value="h" title="(none)"/>'#$D#$A
+' <label id="lblEnum1_h" for="Enum1_h">(none)</label>'#$D#$A
+' <input type="radio" name="Enum1" id="Enum1_hPurse" value="hPurse" title="Purse" checked="checked"/>'#$D#$A
+' <label id="lblEnum1_hPurse" for="Enum1_hPurse">Purse</label>'#$D#$A
+' <input type="radio" name="Enum1" id="Enum1_hCar" value="hCar" title="Car"/>'#$D#$A
+' <label id="lblEnum1_hCar" for="Enum1_hCar">Car</label>'#$D#$A
+' <input type="radio" name="Enum1" id="Enum1_hTelephone" value="hTelephone" title="Telephone"/>'#$D#$A
+' <label id="lblEnum1_hTelephone" for="Enum1_hTelephone">Telephone</label>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.Enum2;
var
S: String;
begin
S := TgWebUIBase.ToString('Enum2',FDataClass);
CheckEquals(
'<div name="grpEnum2">'
+'<label id="lblEnum2" for="Enum2">Enum 2</label>'
+'<select id="Enum2" Name="Enum2">'
+'<option value="f" title="(none)">(none)</option>'
+'<option value="fCalifornia" title="California">California</option>'
+'<option value="fDallas" title="Dallas">Dallas</option>'
+'<option value="fAustin" title="Austin">Austin</option>'
+'<option value="fTexas" title="Texas">Texas</option>'
+'<option value="fAlisoViejo" title="Aliso Viejo">Aliso Viejo</option>'
+'<option value="fShreveport" title="Shreveport">Shreveport</option>'
+'</select>'
+'</div>'
,S);
FData.Enum2 := fTexas;
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpEnum2">'#$D#$A
+' <label id="lblEnum2" for="Enum2">Enum 2</label>'#$D#$A
+' <select id="Enum2" Name="Enum2">'#$D#$A
+' <option value="f" title="(none)">(none)</option>'#$D#$A
+' <option value="fCalifornia" title="California">California</option>'#$D#$A
+' <option value="fDallas" title="Dallas">Dallas</option>'#$D#$A
+' <option value="fAustin" title="Austin">Austin</option>'#$D#$A
+' <option value="fTexas" title="Texas" selected="true">Texas</option>'#$D#$A
+' <option value="fAlisoViejo" title="Aliso Viejo">Aliso Viejo</option>'#$D#$A
+' <option value="fShreveport" title="Shreveport">Shreveport</option>'#$D#$A
+' </select>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.EnumSet1;
var
S: String;
begin
S := TgWebUIBase.ToString('EnumSet1',FDataClass);
CheckEquals(
'<div name="grpEnumSet1">'
+'<label id="lblEnumSet1" for="EnumSet1">Enum Set 1</label><input type="checkbox" name="EnumSet1" id="EnumSet1_h" value="h" />'
+'<label id="lblEnumSet1_h" for="EnumSet1_h">(none)</label><input type="checkbox" name="EnumSet1" id="EnumSet1_hPurse" value="hPurse" />'
+'<label id="lblEnumSet1_hPurse" for="EnumSet1_hPurse">Purse</label><input type="checkbox" name="EnumSet1" id="EnumSet1_hCar" value="hCar" />'
+'<label id="lblEnumSet1_hCar" for="EnumSet1_hCar">Car</label><input type="checkbox" name="EnumSet1" id="EnumSet1_hTelephone" value="hTelephone" />'
+'<label id="lblEnumSet1_hTelephone" for="EnumSet1_hTelephone">Telephone</label>'
+'</div>' ,S);
FData.Enum1 := hPurse;
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpEnumSet1">'#$D#$A
+' <label id="lblEnumSet1" for="EnumSet1">Enum Set 1</label>'#$D#$A
+' <input type="hidden" name="EnumSet1" value=""/>'#$D#$A
+' <input type="checkbox" name="EnumSet1" id="EnumSet1_h" value="h"/>'#$D#$A
+' <label id="lblEnumSet1_h" for="EnumSet1_h">(none)</label>'#$D#$A
+' <input type="hidden" name="EnumSet1" value=""/>'#$D#$A
+' <input type="checkbox" name="EnumSet1" id="EnumSet1_hPurse" value="hPurse"/>'#$D#$A
+' <label id="lblEnumSet1_hPurse" for="EnumSet1_hPurse">Purse</label>'#$D#$A
+' <input type="hidden" name="EnumSet1" value=""/>'#$D#$A
+' <input type="checkbox" name="EnumSet1" id="EnumSet1_hCar" value="hCar"/>'#$D#$A
+' <label id="lblEnumSet1_hCar" for="EnumSet1_hCar">Car</label>'#$D#$A
+' <input type="hidden" name="EnumSet1" value=""/>'#$D#$A
+' <input type="checkbox" name="EnumSet1" id="EnumSet1_hTelephone" value="hTelephone"/>'#$D#$A
+' <label id="lblEnumSet1_hTelephone" for="EnumSet1_hTelephone">Telephone</label>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.ExtendedValue;
var
S: String;
begin
S := TgWebUIBase.ToString('ExtendedValue',FDataClass);
CheckEquals('<div name="grpExtendedValue"><label id="lblExtendedValue" for="ExtendedValue">Extended Value</label><input type="text" id="ExtendedValue" name="ExtendedValue" size="26" maxlength="26" /></div>',S);
FData.ExtendedValue := 1.3;
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpExtendedValue">'#$D#$A
+' <label id="lblExtendedValue" for="ExtendedValue">Extended Value</label>'#$D#$A
+' <input type="text" id="ExtendedValue" name="ExtendedValue" size="26" maxlength="26" value="1.3"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.FileName;
var
S: String;
begin
S := TgWebUIBase.ToString('FileName',FDataClass);
CheckEquals('<div name="grpFileName"><label id="lblFileName" for="FileName">File Name</label><input id="FileName" name="FileName" type="file" /></div>',S);
FData.FileName := 'This is a Test';
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpFileName">'#$D#$A
+' <label id="lblFileName" for="FileName">File Name</label>'#$D#$A
+' <input id="FileName" name="FileName" type="file" value="This is a Test"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.Str10;
var S: String;
begin
S := TgWebUIBase.ToString('Str10',FDataClass);
CheckEquals('<div name="grpStr10"><label id="lblStr10" for="Str10">Str 10</label><input type="text" id="Str10" name="Str10" size="10" maxlength="10" /></div>',S);
FData.Str10 := 'abcdef123456';
CheckEquals('abcdef1234',FData.Str10);
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpStr10">'#$D#$A
+' <label id="lblStr10" for="Str10">Str 10</label>'#$D#$A
+' <input type="text" id="Str10" name="Str10" size="10" maxlength="10" value="abcdef12"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.String50;
var
S: String;
begin
S := TgWebUIBase.ToString('String50',FDataClass);
// CheckEquals('<td>String 50</td><td><input type="text" id="String50" name="String50" value="{String50}" size="50" maxlength="50"/></td>',S);
CheckEquals('<div name="grpString50"><label id="lblString50" for="String50">String 50</label><input type="text" id="String50" name="String50" size="50" maxlength="50" /></div>',S);
FData.String50 := 'abcd1234';
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpString50">'#$D#$A
+' <label id="lblString50" for="String50">String 50</label>'#$D#$A
+' <input type="text" id="String50" name="String50" size="50" maxlength="50" value="abcd1234"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.String_;
var
S: String;
begin
S := TgWebUIBase.ToString('Text',FDataClass);
CheckEquals('<div name="grpText"><label id="lblText" for="Text">My Text</label><textarea id="txtText" name="Text"></textarea></div>',S);
FData.Text := 'This is a Test';
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpText">'#$D#$A
+' <label id="lblText" for="Text">My Text</label>'#$D#$A
+' <textarea id="txtText" name="Text">This is a Test</textarea>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.gHTMLString;
var
S: String;
begin
FData.HTMLText:= 'This is <b>BOLD</B>!';
S := TgWebUIBase.ToString('HTMLText',FDataClass);
CheckEquals('<div name="grpHTMLText"><label id="lblHTMLText" for="HTMLText">HTML Text</label><textarea id="HTMLText" name="HTMLText" class="HTMLEditor"></textarea></div>',S);
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpHTMLText">'#$D#$A
+' <label id="lblHTMLText" for="HTMLText">HTML Text</label>'#$D#$A
+' <textarea id="HTMLText" name="HTMLText" class="HTMLEditor">This is <b>BOLD</B>!</textarea>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.gListItem;
var
S: String;
begin
S :=
'<form object="List1.Current">'
+'<label id="lblTitle" for="inpTitle">Titie</label>'
+'<input type="text" id="inpTitle" name="Title" />'
+'</form>';
// if it has a value then it knows it needs to put a hidden input for current key
// Look to the current and see if it has idenity if it doesn't then its new
FModel.List1.Add;
CheckEquals(0,FModel.List1.CurrentIndex);
FModel.List1.Current.IsLoaded := True;
FModel.List1.Add;
CheckEquals(1,FModel.List1.CurrentIndex);
FModel.List1.Current.IsLoaded := True;
FModel.List1.Current.Title := 'CEO';
CheckEquals('Salesperson',FModel.List1.Current.OriginalValues['Title']);
FModel.List1.Add;
CheckEquals(2,FModel.List1.CurrentIndex);
FModel.List1.Current.IsLoaded := True;
FModel.List1.CurrentIndex := 1;
CheckTrue(FModel.List1.Current.IsLoaded);
CheckEquals('Salesperson',FModel.List1.Current.OriginalValues['Title']);
FDocument.ProcessText('<html>'+S+'</html>',S,FModel);
CheckEquals(
'<html>'#$D#$A
+' <form>'#$D#$A
+' <input type="hidden" value="1" name="List1.CurrentIndex"/>'#$D#$A
+' <label id="lblTitle" for="inpTitle">Titie</label>'#$D#$A
+' <input type="text" id="inpTitle" name="List1.Current.Title" value="CEO"/>'#$D#$A
+' <input type="hidden" name="List1.Current.OriginalValues.Title" value="Salesperson"/>'#$D#$A
+' </form>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.gListAdd;
var
S: String;
begin
S :=
'<form object="List1.Current">'
+'<label id="lblTitle" for="inpTitle">Titie</label>'
+'<input type="text" id="inpTitle" name="Title" />'
+'</form>';
// if it has a value then it knows it needs to put a hidden input for current key
// Look to the current and see if it has idenity if it doesn't then its new
FModel.List1.Add;
CheckEquals(0,FModel.List1.CurrentIndex);
CheckFalse(FModel.List1.Current.IsLoaded);
// Because isLoaded is false the form should add a hidden input List1.Add to the tags.
FDocument.ProcessText('<html>'+S+'</html>',S,FModel);
CheckEquals(
'<html>'#$D#$A
+' <form>'#$D#$A
+' <input type="hidden" value="" name="List1.Add"/>'#$D#$A
+' <label id="lblTitle" for="inpTitle">Titie</label>'#$D#$A
+' <input type="text" id="inpTitle" name="List1.Current.Title" value="Salesperson"/>'#$D#$A
+' <input type="hidden" name="List1.Current.OriginalValues.Title" value="Salesperson"/>'#$D#$A
+' </form>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.InputTagBoolean;
var
Template: String;
S: String;
begin
Template := '<form object="Customer">'
+'<div name="grpGoodCustomer">'
+'<label id="lblGoodCustomer" for="inpGoodCustomer">Good Customer</label>' // ToDo: is the "For" correct
+'<input type="checkbox" id="inpGoodCustomer" name="GoodCustomer" />'
+'</div>'
+'</form>';
FModel.Customer.GoodCustomer := True;
FDocument.ProcessText('<html>'+Template+'</html>',S,FModel);
CheckEquals(
'<html>'#$D#$A
+' <form>'#$D#$A
+' <div name="grpGoodCustomer">'#$D#$A
+' <label id="lblGoodCustomer" for="inpGoodCustomer">Good Customer</label>'#$D#$A
+' <input type="hidden" name="Customer.GoodCustomer" value=""/>'#$D#$A
+' <input type="checkbox" id="inpGoodCustomer" name="Customer.GoodCustomer" value="true" checked="checked"/>'#$D#$A
+' <input type="hidden" name="Customer.OriginalValues.GoodCustomer" value="false"/>'#$D#$A
+' </div>'#$D#$A
+' </form>'#$D#$A
+'</html>'#$D#$A,S);
FModel.Customer.GoodCustomer := False;
FDocument.Clear;
FDocument.ProcessText('<html>'+Template+'</html>',S,FModel);
CheckEquals(
'<html>'#$D#$A
+' <form>'#$D#$A
+' <div name="grpGoodCustomer">'#$D#$A
+' <label id="lblGoodCustomer" for="inpGoodCustomer">Good Customer</label>'#$D#$A
+' <input type="hidden" name="Customer.GoodCustomer" value=""/>'#$D#$A
+' <input type="checkbox" id="inpGoodCustomer" name="Customer.GoodCustomer" value="true"/>'#$D#$A
+' <input type="hidden" name="Customer.OriginalValues.GoodCustomer" value="false"/>'#$D#$A
+' </div>'#$D#$A
+' </form>'#$D#$A
+'</html>'#$D#$A,S);
end;
procedure TestTgWebUI.InputTagInt;
var
S: String;
begin
S :=
'<form object="Customer">'
+'<div name="grpInt">'
+'<label id="lblInt" for="Int">Int</label>'
+'<input type="text" id="inpInt" name="Int" size="11" maxlength="11" />'
+'</div>'
+'</form>';
FModel.Customer.Int := 1234;
FModel.Customer.Save;
FDocument.ProcessText('<html>'+S+'</html>',S,FModel);
CheckEquals(
'<html>'#$D#$A
+' <form>'#$D#$A
+' <div name="grpInt">'#$D#$A
+' <label id="lblInt" for="Int">Int</label>'#$D#$A
+' <input type="text" id="inpInt" name="Customer.Int" size="11" maxlength="11" value="1234"/>'#$D#$A
+' <input type="hidden" name="Customer.OriginalValues.Int" value="1234"/>'#$D#$A
+' </div>'#$D#$A
+' </form>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.InputTagList1_0Int;
var
S: String;
begin
S :=
'<form object="List1[0]">'
+'<div name="grpInt">'
+'<label id="lblInt" for="Int">Int</label>'
+'<input type="text" id="inpInt" name="Int" size="11" maxlength="11"/>'
+'</div>'
+'</form>';
FModel.FList1.Add;
FModel.FList1[0].Int := 1234;
FModel.FList1.Current.Save;
FDocument.ProcessText('<html>'+S+'</html>',S,FModel);
CheckEquals(
'<html>'#$D#$A
+' <form>'#$D#$A
+' <div name="grpInt">'#$D#$A
+' <label id="lblInt" for="Int">Int</label>'#$D#$A
+' <input type="text" id="inpInt" name="List1[0].Int" size="11" maxlength="11" value="1234"/>'#$D#$A
+' <input type="hidden" name="List1[0].OriginalValues.Int" value="1234"/>'#$D#$A
+' </div>'#$D#$A
+' </form>'#$D#$A
+'</html>'#$D#$A,S);
end;
procedure TestTgWebUI.Int;
var
S: String;
begin
S := TgWebUIBase.ToString('Int',FDataClass);
CheckEquals('<div name="grpInt"><label id="lblInt" for="Int">Int</label><input type="text" id="Int" name="Int" size="11" maxlength="11" /></div>',S);
FData.Int := 1234;
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpInt">'#$D#$A
+' <label id="lblInt" for="Int">Int</label>'#$D#$A
+' <input type="text" id="Int" name="Int" size="11" maxlength="11" value="1234"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.Invisible;
var
S: String;
begin
FData.Invisible := 'Now you don''t';
S := TgWebUIBase.ToString('Invisible',FDataClass);
CheckEquals('',S);
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals('<html/>'#$D#$A,S);
end;
procedure TestTgWebUI.Invisible2;
var
S: String;
Data2: TMyClass2;
begin
Data2 := TMyClass2.Create;
S := TgWebUIBase.ToString('Invisible',FDataClass);
CheckEquals('<div name="grpInvisible"><label id="lblInvisible" for="Invisible">Visible Value</label><textarea id="Invisible" name="Invisible"></textarea></div>',S);
Data2.Invisible:= 'Now you see me';
FDocument.ProcessText('<html>'+S+'</html>',S,Data2);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpInvisible">'#$D#$A
+' <label id="lblInvisible" for="Invisible">Visible Value</label>'#$D#$A
+' <textarea id="Invisible" name="Invisible">Now you see me</textarea>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
FreeAndNil(Data2);
end;
procedure TestTgWebUI.Method;
var
S: String;
begin
S := TgWebUIBase.ToString('CheckIt',FDataClass);
// <input type="hidden" name="controller.actions.checkit" value="CheckIt=,save=,model.controller.response.redirect=checkitlist.html" />
// <input type="submit" name="controller.action" value="CheckIt" />
CheckEquals('<input type="submit" value="CheckIt" title="This is the help" />',S);
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals('<html>'#$D#$A
+'<input type="hidden" name="controller.actions.checkit" value="CheckIt=,save=,model.controller.response.redirect=checkitlist.html" />'
+'<input type="submit" name="controller.action" value="CheckIt" />'
// +' <input type="submit" name="CheckIt" id="CheckIt" value="Check It" title="This is the help"/>'#$D#$A
+'</html>'#$D#$A,S);
end;
procedure TestTgWebUI.Model1;
var
Model: TMyModel;
RTTIProperty: TRttiProperty;
Text: String;
begin
Model := TMyModel.Create;
try
Model.Name := 'Hello world!';
Model.Customer.FirstName := 'David';
Model.Customer.LastName := 'Harper';
Model.List1.Add;
Model.List1.Current.FirstName := 'Jerry';
Model.List1.Current.LastName := 'Devorak';
Model.List1.Add;
Model.List1.Current.FirstName := 'Leo';
Model.List1.Current.LastName := 'Laport';
// Text := '<gForm/>';
// Text := TgDocument._ProcessText(Text,Model);
Text := TgWebUIBase.CreateUITemplate(TMyModel,'');
(*
CheckEquals(
'<ul id="mnuMyModel">' // friendly name of the model
+'<li id="List1"><a href="List1List.html">List1</a></li>'
+'<li id="List2"><a href="List2List.html">List2</a></li>'
+'<li id="Customer"><a href="CustomerForm.html">Customer</a></li>'
+'</ul>'
,Text);
*)
CheckEquals(
'<ul id="mnuModel">'
+'<li id="List1"><a href="List1List.html">List1</a></li>'
+'<li id="List2"><a href="List2List.html">List2</a></li>'
+'<li id="List3"><a href="List3List.html">List3</a></li>'
+'<li id="List4"><a href="List4List.html">List4</a></li>'
+'<li id="Customer"><a href="CustomerForm.html">Customer</a></li>'
+'</ul>'
,Text);
// List
Text := TgWebUIBase.CreateUITemplate(TMyModel,'List1'); // True generates sub structure support files
CheckEquals(
'<table id="lstList1">'
+'<tr>'
+'<th>Last Name</th>'
+'<th>First Name</th>'
+'</tr>'
+'<tr foreach="List1">'
+'<td><a href="List1-estTgWebUI.TMyModel.TCustomerform.html?List1.currentkey={ID}">{LastName}</a></td>'
+'<td><a href="List1-estTgWebUI.TMyModel.TCustomerform.html?List1.currentkey={ID}">{FirstName}</a></td>'
+'</tr>'
+'</table>'
,Text);
Text := TgWebUIBase.CreateUITemplate(TMyModel,'List2'); // True generates sub structure support files
CheckEquals(
'<table id="lstList2">'
+'<tr>'
+'<th>First Name</th>'
+'<th>Last Name</th>'
+'</tr>'
+'<tr foreach="List2">'
+'<td><a href="List2-estTgWebUI.TMyModel.TCustomerform.html?List2.currentkey={ID}">{FirstName}</a></td>'
+'<td><a href="List2-estTgWebUI.TMyModel.TCustomerform.html?List2.currentkey={ID}">{LastName}</a></td>'
+'</tr>'
+'</table>'
,Text);
Text := TgWebUIBase.CreateUITemplate(TMyModel,'List3'); // True generates sub structure support files
CheckEquals(
'<table id="lstList3">'
+'<tr>'
+'<th>First Name</th>'
+'<th>Last Name</th>'
+'</tr>'
+'<tr foreach="List3">'
+'<td><a href="List3-estTgWebUI.TMyModel.TCustomer2form.html?List3.currentkey={ID}">{FirstName}</a></td>'
+'<td><a href="List3-estTgWebUI.TMyModel.TCustomer2form.html?List3.currentkey={ID}">{LastName}</a></td>'
+'</tr>'
+'</table>'
,Text);
Text := TgWebUIBase.CreateUITemplate(TMyModel,'List4'); // True generates sub structure support files
CheckEquals(
'<table id="lstList4">'
+'<tr>'
+'<th>My Object</th>'
+'</tr>'
+'<tr foreach="List4">'
+'<td><a href="List4-estTgWebUI.TMyModel.TObjectPropertyform.html?List4.currentkey={ID}">{MyObject}</a></td>'
+'</tr>'
+'</table>'
,Text);
// Customer Property
Text := TgWebUIBase.CreateUITemplate(TMyModel,'Customer');
CheckEquals(
'<form object="Customer">'
+'<div name="grpFirstName"><label id="lblFirstName" for="FirstName">First Name</label><textarea id="txtFirstName" name="FirstName"></textarea></div>'
+'<div name="grpLastName"><label id="lblLastName" for="LastName">Last Name</label><textarea id="txtLastName" name="LastName"></textarea></div>'
+'<input condition="CanDelete" type="submit" id="inpDelete" value="Delete" />'
+'<input condition="CanSave" type="submit" id="inpSave" value="Save" />'
+'</form>'
,Text);
finally
FreeAndNil(Model);
end;
end;
procedure TestTgWebUI.Composite;
var
S: String;
begin
S :=
'<form object="Customer2">'
+'<label id="lblFirstName" for="inpFirstName">First Name</label>'
+'<input type="text" id="inpFirstName" name="FirstName" />'
+'<fieldset id="fstBillingAddress" object="BillingAddress">'
+'<legend id="legBillingAddress">Billing Address</legend>'
+'<label id="lblBillingAddress_Address" for="inpBillingAddress_Address">Address</label>'
+'<input type="text" id="inpBillingAddress_Address" name="Address" />'
+'</fieldset>'
+'</form>';
FDocument.ProcessText('<html>'+S+'</html>',S,FModel);
CheckEquals(
'<html>'#13#10 + //0
' <form>'#13#10 + //1
' <label id="lblFirstName" for="inpFirstName">First Name</label>'#13#10 + //2
' <input type="text" id="inpFirstName" name="Customer2.FirstName"/>'#13#10 + //3
' <input type="hidden" name="Customer2.OriginalValues.FirstName"/>'#13#10 + //4
' <fieldset id="fstBillingAddress">'#13#10 + //5
' <legend id="legBillingAddress">Billing Address</legend>'#13#10 + //6
' <label id="lblBillingAddress_Address" for="inpBillingAddress_Address">Address</label>'#13#10 + //7
' <input type="text" id="inpBillingAddress_Address" name="Customer2.BillingAddress.Address"/>'#13#10 + //8
' <input type="hidden" name="Customer2.BillingAddress.OriginalValues.Address"/>'#13#10 + //8
' </fieldset>'#13#10 + //9
' </form>'#13#10 + //10
'</html>'#13#10 //11
,S);
end;
procedure TestTgWebUI.CompositeIdentity;
var
S: String;
Text: String;
begin
S :=
'<form object="Customer2">'
+'<label id="lblFirstName" for="inpFirstName">First Name</label>'
+'<input type="text" id="inpFirstName" name="FirstName" />'
+'<fieldset id="fstShippingAddress" object="ShippingAddress">'
+'<legend id="legShippingAddress">Shipping Address</legend>'
+'<label id="lblShippingAddress_Address" for="inpShippingAddress_Address">Address</label>'
+'<input type="text" id="inpShippingAddress_Address" name="Address" />'
+'</fieldset>'
+'</form>';
FDocument.ProcessText('<html>'+S+'</html>',Text,FModel);
(*
Customer2.BillingAddress.Address
Customer2.OriginalValues['BillingAddress.Address']
Customer2.BillingAddress.OrignialValues.Address
TBillingAddress(Customer2.BillingAddress.OriginalValues).Address
Customer2.BillingAddress.OriginalValues['Address'] :=
Customer2.BillingAddress.Address
Customer2.OriginalValues.FirstName
Customer2.OriginalValues.BillingAddress.Address
Customer2.BillingAddress.Changed(Customer.OriginalValues.BillingAddress);
*)
CheckEquals(
'<html>'#$D#$A
+' <form>'#$D#$A
+' <label id="lblFirstName" for="inpFirstName">First Name</label>'#$D#$A
+' <input type="text" id="inpFirstName" name="Customer2.FirstName"/>'#$D#$A
+' <input type="hidden" name="Customer2.OriginalValues.FirstName" value=""/>'#$D#$A
+' <fieldset id="fstShippingAddress">'#$D#$A
+' <legend id="legShippingAddress">Shipping Address</legend>'#$D#$A
+' <label id="lblShippingAddress_Address" for="inpShippingAddress_Address">Address</label>'#$D#$A
+' <input type="text" id="inpShippingAddress_Address" name="Customer2.ShippingAddress.Address"/>'#$D#$A
+' <input type="hidden" name="Customer2.ShippingAddress.OriginalValues.Address" value=""/>'#$D#$A
+' </fieldset>'#$D#$A
+' </form>'#$D#$A
+'</html>'#$D#$A
,Text);
end;
procedure TestTgWebUI.NotVisibleBool;
var
S: String;
begin
// Generate Template
S := TgWebUIBase.ToString('NotVisibleBool',FDataClass);
CheckEquals('',S);
// Run Template evaulator on text
end;
procedure TestTgWebUI.NoYesBool;
var
S,AStr: String;
begin
AStr := TgWebUIBase.ToString('NoYesBool',FDataClass);
CheckEquals('<div name="grpNoYesBool"><label id="lblNoYesBool" for="NoYesBool">No Yes Bool</label><span id="NoYesBool">{NoYesBool}</span></div>',AStr);
FData.Bool := True;
FDocument.ProcessText('<html>'+AStr+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpNoYesBool">'#$D#$A
+' <label id="lblNoYesBool" for="NoYesBool">No Yes Bool</label>'#$D#$A
+' <span id="NoYesBool">True</span>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.OffOnBool;
begin
end;
procedure TestTgWebUI.ReadBool_True;
var
S,AStr: String;
begin
AStr := TgWebUIBase.ToString('ReadBool',FDataClass);
CheckEquals('<div name="grpReadBool"><label id="lblReadBool" for="ReadBool">Read Bool</label><span id="ReadBool">{ReadBool}</span></div>',AStr);
FData.Bool := True;
FDocument.ProcessText('<html>'+AStr+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpReadBool">'#$D#$A
+' <label id="lblReadBool" for="ReadBool">Read Bool</label>'#$D#$A
+' <span id="ReadBool">True</span>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.RestPaths;
var
gBase: TgBase;
Template: String;
begin
CheckTrue(FModel.UseRestPath('',Template,gBase));
CheckEquals(Template,'','the template should return Empty');
CheckTrue(gBase = FModel);
CheckFalse(FModel.UseRestPath('JoeBlow\0\d',Template,gBase));
CheckTrue(FModel.UseRestPath('List1',Template,gBase));
CheckEquals('List1',Template,'the template should return Empty');
CheckTrue(gBase = FModel.List1);
FModel.List1.Add;
CheckEquals(1,FModel.List1.Count);
FModel.List1.Current.FirstName := 'Hi!';
FModel.List1.Current.Save;
CheckTrue(FModel.UseRestPath('List1\0',Template,gBase,'\'));
CheckEquals('List1Form',Template,'Should be Form Template');
CheckTrue(gBase = FModel.List1[0]);
CheckTrue(FModel.UseRestPath('Customer',Template,gBase));
CheckEquals('Customer',Template,'');
CheckTrue(gBase = FModel.Customer);
CheckNotNull(FModel.Shows);
FModel.Shows.Add;
CheckTrue(FModel.UseRestPath('Shows\0\Exhibitors',Template,gBase,'\'));
CheckEquals('Shows-Exhibitors',Template,'');
CheckTrue(gBase = FModel.Shows[0].Exhibitors);
FModel.Shows.Current.Exhibitors.Add;
CheckTrue(FModel.UseRestPath('Shows\0\Exhibitors\0',Template,gBase,'\'));
CheckEquals('Shows-ExhibitorsForm',Template,'');
CheckTrue(gBase = FModel.Shows[0].Exhibitors[0]);
end;
procedure TestTgWebUI.ReadBool_False;
var
S,AStr: String;
begin
AStr := TgWebUIBase.ToString('ReadBool',FDataClass);
CheckEquals('<div name="grpReadBool"><label id="lblReadBool" for="ReadBool">Read Bool</label><span id="ReadBool">{ReadBool}</span></div>',AStr);
FData.Bool := False;
FDocument.ProcessText('<html>'+AStr+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpReadBool">'#$D#$A
+' <label id="lblReadBool" for="ReadBool">Read Bool</label>'#$D#$A
+' <span id="ReadBool">False</span>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.SetUp;
begin
inherited;
FData := TMyClass.Create;
FDataClass := TMyClass;
FDocument := TgDocument.Create(FData);
FModel := TMyModel.Create;
end;
procedure TestTgWebUI.SingleDisplay;
var
S: String;
begin
S := TgWebUIBase.ToString('SingleDisplay',FDataClass);
FData.SingleDisplay := 13412.345;
CheckEquals('<div name="grpSingleDisplay"><label id="lblSingleDisplay" for="SingleDisplay">Single Display</label><span id="SingleDisplay">{FormatFloat('',.00'',SingleDisplay)}</span></div>',S);
FData.Text := 'This is a Test';
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpSingleDisplay">'#$D#$A
+' <label id="lblSingleDisplay" for="SingleDisplay">Single Display</label>'#$D#$A
+' <span id="SingleDisplay">13412.3447265625</span>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.SingleValue;
var
S: String;
begin
S := TgWebUIBase.ToString('SingleValue',FDataClass);
CheckEquals('<div name="grpSingleValue"><label id="lblSingleValue" for="SingleValue">Single Value</label><input type="text" id="SingleValue" name="SingleValue" size="18" maxlength="18" /></div>',S);
FData.SingleValue:= 1.2;
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpSingleValue">'#$D#$A
+' <label id="lblSingleValue" for="SingleValue">Single Value</label>'#$D#$A
+' <input type="text" id="SingleValue" name="SingleValue" size="18" maxlength="18" value="1.20000004768372"/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
procedure TestTgWebUI.TearDown;
begin
FreeAndNil(FModel);
FreeAndNil(FDocument);
FreeAndNil(FData);
inherited;
end;
procedure TestTgWebUI.WebAddress;
var
S: String;
begin
S := TgWebUIBase.ToString('WebAddress',FDataClass);
CheckEquals('<div name="grpWebAddress"><label id="lblWebAddress" for="WebAddress">Web Address</label><input id="WebAddress" name="WebAddress" type="text" /></div>',S);
FData.FileName := 'This is a Test';
FDocument.ProcessText('<html>'+S+'</html>',S,FData);
CheckEquals(
'<html>'#$D#$A
+' <div name="grpWebAddress">'#$D#$A
+' <label id="lblWebAddress" for="WebAddress">Web Address</label>'#$D#$A
+' <input id="WebAddress" name="WebAddress" type="text" value=""/>'#$D#$A
+' </div>'#$D#$A
+'</html>'#$D#$A
,S);
end;
{ TestTgWebUI.TMyClass }
procedure TestTgWebUI.TMyClass.CheckIt;
begin
Int := 14;
end;
procedure TestTBase4.SetUp;
begin
inherited;
FBase4 := TBase4.Create;
end;
procedure TestTBase4.TearDown;
begin
FreeAndNil(FBase4);
inherited;
end;
{ TestTgWebUI.TMyModel.TCustomer2 }
function TestTgWebUI.TMyModel.TCustomer2.GetOriginalValues: TCustomer2;
begin
Result := TCustomer2(inherited OriginalValues)
end;
{ TestTgOriginalValues }
procedure TestTgOriginalValues.SetUp;
begin
inherited;
end;
procedure TestTgOriginalValues.TearDown;
begin
inherited;
FreeAndNil(FOriginalValues);
end;
procedure TestTgOriginalValues.Test;
var
Data: TItem;
begin
Data := TItem.Create;
FOriginalValues := TgOriginalValues.Create(Data);
FOriginalValues.Load;
Checkequals(0,FOriginalValues['Int']);
Checkequals('',FOriginalValues.Values['Name']);
CheckFalse(FOriginalValues.Values['Bool']);
Data.Int := 12;
Data.Name := 'OMG!';
Data.Bool := True;
FOriginalValues.Load;
Checkequals(12,FOriginalValues.Values['Int']);
Checkequals('OMG!',FOriginalValues.Values['Name']);
CheckTrue(FOriginalValues.Values['Bool']);
end;
function TestTgWebServerController.TModel.GetFirstName: string;
begin
// TODO -cMM: TestTgWebServerController.TModel.GetFirstName default body inserted
Result := 'Hello';
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTBase.Suite);
RegisterTest(TestTgString5.Suite);
RegisterTest(TestTBase2List.Suite);
RegisterTest(TestTIdentityObject.Suite);
RegisterTest(TestTIdentityObjectList.Suite);
RegisterTest(TestTBase3.Suite);
RegisterTest(TestTBase4.Suite);
RegisterTest(TestTIDObject.Suite);
RegisterTest(TestTIDObject2.Suite);
// RegisterTest(TestTgNodeCSV.Suite);
RegisterTest(TestTSerializeCSV.Suite);
RegisterTest(TestHTMLParser.Suite);
RegisterTest(TestTFirebirdObject.Suite);
RegisterTest(TestEvalHTML.Suite);
RegisterTest(TestMemo.Suite);
RegisterTest(TestClassProperty.Suite);
RegisterTest(TestWebCookie.Suite);
RegisterTest(TestTgDictionary.Suite);
RegisterTest(TestTgWebServerController.Suite);
RegisterTest(TestTgWebUI.Suite);
RegisterTest(TestTgOriginalValues.Suite);
RegisterRuntimeClasses([TFirebirdObject]);
end.
(*
CheckEquals(
'<a href="CustomerForm.html">New</a>'
+'<label>First Name</label><label>Last Name</label>'
+'<ul object="">' // if it has object for each
+'<li ><a href="CustomerForm.html?id={ID}">{FirstName} {LastName}</a></li>'
+'</ul>'
,Text);
*)
|
{***************************************************************
*
* Project : MailDemo
* Unit Name: smtpauth
* Purpose : Sub form
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:29:06
* Author : Hadi Hari <hadi@pbe.com>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit smtpauth;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons,
{$ENDIF}
windows, messages, SysUtils, Classes;
type
TfrmSMTPAuthentication = class(TForm)
BitBtn1: TBitBtn;
GroupBox1: TGroupBox;
cboAuthType: TComboBox;
lblAuthenticationType: TLabel;
edtAccount: TEdit;
edtPassword: TEdit;
lbAccount: TLabel;
lbPassword: TLabel;
procedure cboAuthTypeChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure EnableControls;
end;
var
frmSMTPAuthentication: TfrmSMTPAuthentication;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
{ TfrmSMTPAuthentication }
procedure TfrmSMTPAuthentication.EnableControls;
begin
edtAccount.Enabled := (cboAuthType.ItemIndex <> 0);
lbAccount.Enabled := (cboAuthType.ItemIndex <> 0);
edtPassword.Enabled := (cboAuthType.ItemIndex <> 0);
lbPassword.Enabled := (cboAuthType.ItemIndex <> 0);
end;
procedure TfrmSMTPAuthentication.cboAuthTypeChange(Sender: TObject);
begin
EnableControls;
end;
end.
|
{***********************************************************}
{ }
{ XML Data Binding }
{ }
{ Generated on: 24.02.2006 13:28:53 }
{ Generated from: Q:\RegExpr\Test\Tests\TestREs.xml }
{ Settings stored in: Q:\RegExpr\Test\TestREs.xdb }
{ }
{***********************************************************}
unit TestREs;
interface
uses xmldom, XMLDoc, XMLIntf;
type
{ Forward Decls }
IXMLRegularExpressionsType = interface;
IXMLRegularExpressionType = interface;
IXMLRegularExpressionTypeList = interface;
IXMLTestCaseType = interface;
IXMLTestCaseTypeList = interface;
IXMLStringType = interface;
IXMLStringTypeList = interface;
IXMLCapturedSubstringsType = interface;
IXMLCapturedSubstringsTypeList = interface;
IXMLSubstitutionType = interface;
IXMLSubstitutionTypeList = interface;
IXMLReplaceType = interface;
IXMLReplaceTypeList = interface;
{ IXMLRegularExpressionsType }
IXMLRegularExpressionsType = interface(IXMLNodeCollection)
['{2B0FFC3A-311C-4705-A96F-4B34A416649B}']
{ Property Accessors }
function Get_RegularExpression(Index: Integer): IXMLRegularExpressionType;
{ Methods & Properties }
function Add: IXMLRegularExpressionType;
function Insert(const Index: Integer): IXMLRegularExpressionType;
property RegularExpression[Index: Integer]: IXMLRegularExpressionType read Get_RegularExpression; default;
end;
{ IXMLRegularExpressionType }
IXMLRegularExpressionType = interface(IXMLNode)
['{D7E7F11F-0777-495B-BEA6-3D6C48FBE13A}']
{ Property Accessors }
function Get_Name: Integer;
function Get_Description: WideString;
function Get_Comment: WideString;
function Get_Expression: WideString;
function Get_TestCase: IXMLTestCaseTypeList;
procedure Set_Name(Value: Integer);
procedure Set_Description(Value: WideString);
procedure Set_Comment(Value: WideString);
procedure Set_Expression(Value: WideString);
{ Methods & Properties }
property Name: Integer read Get_Name write Set_Name;
property Description: WideString read Get_Description write Set_Description;
property Comment: WideString read Get_Comment write Set_Comment;
property Expression: WideString read Get_Expression write Set_Expression;
property TestCase: IXMLTestCaseTypeList read Get_TestCase;
end;
{ IXMLRegularExpressionTypeList }
IXMLRegularExpressionTypeList = interface(IXMLNodeCollection)
['{DEB97A65-17EB-46CA-B8D0-09D9586880AE}']
{ Methods & Properties }
function Add: IXMLRegularExpressionType;
function Insert(const Index: Integer): IXMLRegularExpressionType;
function Get_Item(Index: Integer): IXMLRegularExpressionType;
property Items[Index: Integer]: IXMLRegularExpressionType read Get_Item; default;
end;
{ IXMLTestCaseType }
IXMLTestCaseType = interface(IXMLNode)
['{86A0C71E-BB33-4B1B-9355-CC03FB4EBBC7}']
{ Property Accessors }
function Get_Modifiers: WideString;
function Get_String_: IXMLStringTypeList;
function Get_CapturedSubstrings: IXMLCapturedSubstringsTypeList;
function Get_Substitution: IXMLSubstitutionTypeList;
function Get_Replace: IXMLReplaceTypeList;
procedure Set_Modifiers(Value: WideString);
{ Methods & Properties }
property Modifiers: WideString read Get_Modifiers write Set_Modifiers;
property String_: IXMLStringTypeList read Get_String_;
property CapturedSubstrings: IXMLCapturedSubstringsTypeList read Get_CapturedSubstrings;
property Substitution: IXMLSubstitutionTypeList read Get_Substitution;
property Replace: IXMLReplaceTypeList read Get_Replace;
end;
{ IXMLTestCaseTypeList }
IXMLTestCaseTypeList = interface(IXMLNodeCollection)
['{B44FD942-5016-4B0C-9AE9-A548EB84B179}']
{ Methods & Properties }
function Add: IXMLTestCaseType;
function Insert(const Index: Integer): IXMLTestCaseType;
function Get_Item(Index: Integer): IXMLTestCaseType;
property Items[Index: Integer]: IXMLTestCaseType read Get_Item; default;
end;
{ IXMLStringType }
IXMLStringType = interface(IXMLNode)
['{791F58A4-0C97-4DEB-953B-A56C8C58BAD1}']
{ Property Accessors }
function Get_RepeatCount: Integer;
procedure Set_RepeatCount(Value: Integer);
{ Methods & Properties }
property RepeatCount: Integer read Get_RepeatCount write Set_RepeatCount;
end;
{ IXMLStringTypeList }
IXMLStringTypeList = interface(IXMLNodeCollection)
['{733F9219-F6EA-426E-AA2F-624A901863C0}']
{ Methods & Properties }
function Add: IXMLStringType;
function Insert(const Index: Integer): IXMLStringType;
function Get_Item(Index: Integer): IXMLStringType;
property Items[Index: Integer]: IXMLStringType read Get_Item; default;
end;
{ IXMLCapturedSubstringsType }
IXMLCapturedSubstringsType = interface(IXMLNodeCollection)
['{5F323EE3-EA98-4A1E-9487-01608A5D3E2B}']
{ Property Accessors }
function Get_Substring(Index: Integer): WideString;
{ Methods & Properties }
function Add(const Substring: WideString): IXMLNode;
function Insert(const Index: Integer; const Substring: WideString): IXMLNode;
property Substring[Index: Integer]: WideString read Get_Substring; default;
end;
{ IXMLCapturedSubstringsTypeList }
IXMLCapturedSubstringsTypeList = interface(IXMLNodeCollection)
['{281B9F34-AD12-46FE-8C2B-8274C642DB77}']
{ Methods & Properties }
function Add: IXMLCapturedSubstringsType;
function Insert(const Index: Integer): IXMLCapturedSubstringsType;
function Get_Item(Index: Integer): IXMLCapturedSubstringsType;
property Items[Index: Integer]: IXMLCapturedSubstringsType read Get_Item; default;
end;
{ IXMLSubstitutionType }
IXMLSubstitutionType = interface(IXMLNode)
['{1400A678-BDBB-4192-8277-F686C2B77633}']
{ Property Accessors }
function Get_Template: WideString;
function Get_Result: WideString;
procedure Set_Template(Value: WideString);
procedure Set_Result(Value: WideString);
{ Methods & Properties }
property Template: WideString read Get_Template write Set_Template;
property Result: WideString read Get_Result write Set_Result;
end;
{ IXMLSubstitutionTypeList }
IXMLSubstitutionTypeList = interface(IXMLNodeCollection)
['{F197FB33-514A-49F7-8387-665514F81D40}']
{ Methods & Properties }
function Add: IXMLSubstitutionType;
function Insert(const Index: Integer): IXMLSubstitutionType;
function Get_Item(Index: Integer): IXMLSubstitutionType;
property Items[Index: Integer]: IXMLSubstitutionType read Get_Item; default;
end;
{ IXMLReplaceType }
IXMLReplaceType = interface(IXMLNode)
['{5FD2B4C2-B5AF-4F0C-9AB0-98E29DC151AE}']
{ Property Accessors }
function Get_Template: WideString;
function Get_Result: WideString;
procedure Set_Template(Value: WideString);
procedure Set_Result(Value: WideString);
{ Methods & Properties }
property Template: WideString read Get_Template write Set_Template;
property Result: WideString read Get_Result write Set_Result;
end;
{ IXMLReplaceTypeList }
IXMLReplaceTypeList = interface(IXMLNodeCollection)
['{9E65DB49-66D9-44EF-994C-40D215743388}']
{ Methods & Properties }
function Add: IXMLReplaceType;
function Insert(const Index: Integer): IXMLReplaceType;
function Get_Item(Index: Integer): IXMLReplaceType;
property Items[Index: Integer]: IXMLReplaceType read Get_Item; default;
end;
{ Forward Decls }
TXMLRegularExpressionsType = class;
TXMLRegularExpressionType = class;
TXMLRegularExpressionTypeList = class;
TXMLTestCaseType = class;
TXMLTestCaseTypeList = class;
TXMLStringType = class;
TXMLStringTypeList = class;
TXMLCapturedSubstringsType = class;
TXMLCapturedSubstringsTypeList = class;
TXMLSubstitutionType = class;
TXMLSubstitutionTypeList = class;
TXMLReplaceType = class;
TXMLReplaceTypeList = class;
{ TXMLRegularExpressionsType }
TXMLRegularExpressionsType = class(TXMLNodeCollection, IXMLRegularExpressionsType)
protected
{ IXMLRegularExpressionsType }
function Get_RegularExpression(Index: Integer): IXMLRegularExpressionType;
function Add: IXMLRegularExpressionType;
function Insert(const Index: Integer): IXMLRegularExpressionType;
public
procedure AfterConstruction; override;
end;
{ TXMLRegularExpressionType }
TXMLRegularExpressionType = class(TXMLNode, IXMLRegularExpressionType)
private
FTestCase: IXMLTestCaseTypeList;
protected
{ IXMLRegularExpressionType }
function Get_Name: Integer;
function Get_Description: WideString;
function Get_Comment: WideString;
function Get_Expression: WideString;
function Get_TestCase: IXMLTestCaseTypeList;
procedure Set_Name(Value: Integer);
procedure Set_Description(Value: WideString);
procedure Set_Comment(Value: WideString);
procedure Set_Expression(Value: WideString);
public
procedure AfterConstruction; override;
end;
{ TXMLRegularExpressionTypeList }
TXMLRegularExpressionTypeList = class(TXMLNodeCollection, IXMLRegularExpressionTypeList)
protected
{ IXMLRegularExpressionTypeList }
function Add: IXMLRegularExpressionType;
function Insert(const Index: Integer): IXMLRegularExpressionType;
function Get_Item(Index: Integer): IXMLRegularExpressionType;
end;
{ TXMLTestCaseType }
TXMLTestCaseType = class(TXMLNode, IXMLTestCaseType)
private
FString_: IXMLStringTypeList;
FCapturedSubstrings: IXMLCapturedSubstringsTypeList;
FSubstitution: IXMLSubstitutionTypeList;
FReplace: IXMLReplaceTypeList;
protected
{ IXMLTestCaseType }
function Get_Modifiers: WideString;
function Get_String_: IXMLStringTypeList;
function Get_CapturedSubstrings: IXMLCapturedSubstringsTypeList;
function Get_Substitution: IXMLSubstitutionTypeList;
function Get_Replace: IXMLReplaceTypeList;
procedure Set_Modifiers(Value: WideString);
public
procedure AfterConstruction; override;
end;
{ TXMLTestCaseTypeList }
TXMLTestCaseTypeList = class(TXMLNodeCollection, IXMLTestCaseTypeList)
protected
{ IXMLTestCaseTypeList }
function Add: IXMLTestCaseType;
function Insert(const Index: Integer): IXMLTestCaseType;
function Get_Item(Index: Integer): IXMLTestCaseType;
end;
{ TXMLStringType }
TXMLStringType = class(TXMLNode, IXMLStringType)
protected
{ IXMLStringType }
function Get_RepeatCount: Integer;
procedure Set_RepeatCount(Value: Integer);
end;
{ TXMLStringTypeList }
TXMLStringTypeList = class(TXMLNodeCollection, IXMLStringTypeList)
protected
{ IXMLStringTypeList }
function Add: IXMLStringType;
function Insert(const Index: Integer): IXMLStringType;
function Get_Item(Index: Integer): IXMLStringType;
end;
{ TXMLCapturedSubstringsType }
TXMLCapturedSubstringsType = class(TXMLNodeCollection, IXMLCapturedSubstringsType)
protected
{ IXMLCapturedSubstringsType }
function Get_Substring(Index: Integer): WideString;
function Add(const Substring: WideString): IXMLNode;
function Insert(const Index: Integer; const Substring: WideString): IXMLNode;
public
procedure AfterConstruction; override;
end;
{ TXMLCapturedSubstringsTypeList }
TXMLCapturedSubstringsTypeList = class(TXMLNodeCollection, IXMLCapturedSubstringsTypeList)
protected
{ IXMLCapturedSubstringsTypeList }
function Add: IXMLCapturedSubstringsType;
function Insert(const Index: Integer): IXMLCapturedSubstringsType;
function Get_Item(Index: Integer): IXMLCapturedSubstringsType;
end;
{ TXMLSubstitutionType }
TXMLSubstitutionType = class(TXMLNode, IXMLSubstitutionType)
protected
{ IXMLSubstitutionType }
function Get_Template: WideString;
function Get_Result: WideString;
procedure Set_Template(Value: WideString);
procedure Set_Result(Value: WideString);
end;
{ TXMLSubstitutionTypeList }
TXMLSubstitutionTypeList = class(TXMLNodeCollection, IXMLSubstitutionTypeList)
protected
{ IXMLSubstitutionTypeList }
function Add: IXMLSubstitutionType;
function Insert(const Index: Integer): IXMLSubstitutionType;
function Get_Item(Index: Integer): IXMLSubstitutionType;
end;
{ TXMLReplaceType }
TXMLReplaceType = class(TXMLNode, IXMLReplaceType)
protected
{ IXMLReplaceType }
function Get_Template: WideString;
function Get_Result: WideString;
procedure Set_Template(Value: WideString);
procedure Set_Result(Value: WideString);
end;
{ TXMLReplaceTypeList }
TXMLReplaceTypeList = class(TXMLNodeCollection, IXMLReplaceTypeList)
protected
{ IXMLReplaceTypeList }
function Add: IXMLReplaceType;
function Insert(const Index: Integer): IXMLReplaceType;
function Get_Item(Index: Integer): IXMLReplaceType;
end;
{ Global Functions }
function GetregularExpressions(Doc: IXMLDocument): IXMLRegularExpressionsType;
function LoadregularExpressions(const FileName: WideString): IXMLRegularExpressionsType;
function NewregularExpressions: IXMLRegularExpressionsType;
const
TargetNamespace = '';
implementation
{ Global Functions }
function GetregularExpressions(Doc: IXMLDocument): IXMLRegularExpressionsType;
begin
Result := Doc.GetDocBinding('regularExpressions', TXMLRegularExpressionsType, TargetNamespace) as IXMLRegularExpressionsType;
end;
function LoadregularExpressions(const FileName: WideString): IXMLRegularExpressionsType;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('regularExpressions', TXMLRegularExpressionsType, TargetNamespace) as IXMLRegularExpressionsType;
end;
function NewregularExpressions: IXMLRegularExpressionsType;
begin
Result := NewXMLDocument.GetDocBinding('regularExpressions', TXMLRegularExpressionsType, TargetNamespace) as IXMLRegularExpressionsType;
end;
{ TXMLRegularExpressionsType }
procedure TXMLRegularExpressionsType.AfterConstruction;
begin
RegisterChildNode('regularExpression', TXMLRegularExpressionType);
ItemTag := 'regularExpression';
ItemInterface := IXMLRegularExpressionType;
inherited;
end;
function TXMLRegularExpressionsType.Get_RegularExpression(Index: Integer): IXMLRegularExpressionType;
begin
Result := List[Index] as IXMLRegularExpressionType;
end;
function TXMLRegularExpressionsType.Add: IXMLRegularExpressionType;
begin
Result := AddItem(-1) as IXMLRegularExpressionType;
end;
function TXMLRegularExpressionsType.Insert(const Index: Integer): IXMLRegularExpressionType;
begin
Result := AddItem(Index) as IXMLRegularExpressionType;
end;
{ TXMLRegularExpressionType }
procedure TXMLRegularExpressionType.AfterConstruction;
begin
RegisterChildNode('testCase', TXMLTestCaseType);
FTestCase := CreateCollection(TXMLTestCaseTypeList, IXMLTestCaseType, 'testCase') as IXMLTestCaseTypeList;
inherited;
end;
function TXMLRegularExpressionType.Get_Name: Integer;
begin
Result := AttributeNodes['name'].NodeValue;
end;
procedure TXMLRegularExpressionType.Set_Name(Value: Integer);
begin
SetAttribute('name', Value);
end;
function TXMLRegularExpressionType.Get_Description: WideString;
begin
Result := ChildNodes['Description'].Text;
end;
procedure TXMLRegularExpressionType.Set_Description(Value: WideString);
begin
ChildNodes['Description'].NodeValue := Value;
end;
function TXMLRegularExpressionType.Get_Comment: WideString;
begin
Result := ChildNodes['Comment'].Text;
end;
procedure TXMLRegularExpressionType.Set_Comment(Value: WideString);
begin
ChildNodes['Comment'].NodeValue := Value;
end;
function TXMLRegularExpressionType.Get_Expression: WideString;
begin
Result := ChildNodes['Expression'].Text;
end;
procedure TXMLRegularExpressionType.Set_Expression(Value: WideString);
begin
ChildNodes['Expression'].NodeValue := Value;
end;
function TXMLRegularExpressionType.Get_TestCase: IXMLTestCaseTypeList;
begin
Result := FTestCase;
end;
{ TXMLRegularExpressionTypeList }
function TXMLRegularExpressionTypeList.Add: IXMLRegularExpressionType;
begin
Result := AddItem(-1) as IXMLRegularExpressionType;
end;
function TXMLRegularExpressionTypeList.Insert(const Index: Integer): IXMLRegularExpressionType;
begin
Result := AddItem(Index) as IXMLRegularExpressionType;
end;
function TXMLRegularExpressionTypeList.Get_Item(Index: Integer): IXMLRegularExpressionType;
begin
Result := List[Index] as IXMLRegularExpressionType;
end;
{ TXMLTestCaseType }
procedure TXMLTestCaseType.AfterConstruction;
begin
RegisterChildNode('string', TXMLStringType);
RegisterChildNode('capturedSubstrings', TXMLCapturedSubstringsType);
RegisterChildNode('substitution', TXMLSubstitutionType);
RegisterChildNode('replace', TXMLReplaceType);
FString_ := CreateCollection(TXMLStringTypeList, IXMLStringType, 'string') as IXMLStringTypeList;
FCapturedSubstrings := CreateCollection(TXMLCapturedSubstringsTypeList, IXMLCapturedSubstringsType, 'capturedSubstrings') as IXMLCapturedSubstringsTypeList;
FSubstitution := CreateCollection(TXMLSubstitutionTypeList, IXMLSubstitutionType, 'substitution') as IXMLSubstitutionTypeList;
FReplace := CreateCollection(TXMLReplaceTypeList, IXMLReplaceType, 'replace') as IXMLReplaceTypeList;
inherited;
end;
function TXMLTestCaseType.Get_Modifiers: WideString;
begin
Result := AttributeNodes['Modifiers'].Text;
end;
procedure TXMLTestCaseType.Set_Modifiers(Value: WideString);
begin
SetAttribute('Modifiers', Value);
end;
function TXMLTestCaseType.Get_String_: IXMLStringTypeList;
begin
Result := FString_;
end;
function TXMLTestCaseType.Get_CapturedSubstrings: IXMLCapturedSubstringsTypeList;
begin
Result := FCapturedSubstrings;
end;
function TXMLTestCaseType.Get_Substitution: IXMLSubstitutionTypeList;
begin
Result := FSubstitution;
end;
function TXMLTestCaseType.Get_Replace: IXMLReplaceTypeList;
begin
Result := FReplace;
end;
{ TXMLTestCaseTypeList }
function TXMLTestCaseTypeList.Add: IXMLTestCaseType;
begin
Result := AddItem(-1) as IXMLTestCaseType;
end;
function TXMLTestCaseTypeList.Insert(const Index: Integer): IXMLTestCaseType;
begin
Result := AddItem(Index) as IXMLTestCaseType;
end;
function TXMLTestCaseTypeList.Get_Item(Index: Integer): IXMLTestCaseType;
begin
Result := List[Index] as IXMLTestCaseType;
end;
{ TXMLStringType }
function TXMLStringType.Get_RepeatCount: Integer;
begin
Result := AttributeNodes['repeatCount'].NodeValue;
end;
procedure TXMLStringType.Set_RepeatCount(Value: Integer);
begin
SetAttribute('repeatCount', Value);
end;
{ TXMLStringTypeList }
function TXMLStringTypeList.Add: IXMLStringType;
begin
Result := AddItem(-1) as IXMLStringType;
end;
function TXMLStringTypeList.Insert(const Index: Integer): IXMLStringType;
begin
Result := AddItem(Index) as IXMLStringType;
end;
function TXMLStringTypeList.Get_Item(Index: Integer): IXMLStringType;
begin
Result := List[Index] as IXMLStringType;
end;
{ TXMLCapturedSubstringsType }
procedure TXMLCapturedSubstringsType.AfterConstruction;
begin
ItemTag := 'substring';
ItemInterface := IXMLNode;
inherited;
end;
function TXMLCapturedSubstringsType.Get_Substring(Index: Integer): WideString;
begin
Result := List[Index].Text;
end;
function TXMLCapturedSubstringsType.Add(const Substring: WideString): IXMLNode;
begin
Result := AddItem(-1);
Result.NodeValue := Substring;
end;
function TXMLCapturedSubstringsType.Insert(const Index: Integer; const Substring: WideString): IXMLNode;
begin
Result := AddItem(Index);
Result.NodeValue := Substring;
end;
{ TXMLCapturedSubstringsTypeList }
function TXMLCapturedSubstringsTypeList.Add: IXMLCapturedSubstringsType;
begin
Result := AddItem(-1) as IXMLCapturedSubstringsType;
end;
function TXMLCapturedSubstringsTypeList.Insert(const Index: Integer): IXMLCapturedSubstringsType;
begin
Result := AddItem(Index) as IXMLCapturedSubstringsType;
end;
function TXMLCapturedSubstringsTypeList.Get_Item(Index: Integer): IXMLCapturedSubstringsType;
begin
Result := List[Index] as IXMLCapturedSubstringsType;
end;
{ TXMLSubstitutionType }
function TXMLSubstitutionType.Get_Template: WideString;
begin
Result := ChildNodes['template'].Text;
end;
procedure TXMLSubstitutionType.Set_Template(Value: WideString);
begin
ChildNodes['template'].NodeValue := Value;
end;
function TXMLSubstitutionType.Get_Result: WideString;
begin
Result := ChildNodes['result'].Text;
end;
procedure TXMLSubstitutionType.Set_Result(Value: WideString);
begin
ChildNodes['result'].NodeValue := Value;
end;
{ TXMLSubstitutionTypeList }
function TXMLSubstitutionTypeList.Add: IXMLSubstitutionType;
begin
Result := AddItem(-1) as IXMLSubstitutionType;
end;
function TXMLSubstitutionTypeList.Insert(const Index: Integer): IXMLSubstitutionType;
begin
Result := AddItem(Index) as IXMLSubstitutionType;
end;
function TXMLSubstitutionTypeList.Get_Item(Index: Integer): IXMLSubstitutionType;
begin
Result := List[Index] as IXMLSubstitutionType;
end;
{ TXMLReplaceType }
function TXMLReplaceType.Get_Template: WideString;
begin
Result := ChildNodes['template'].Text;
end;
procedure TXMLReplaceType.Set_Template(Value: WideString);
begin
ChildNodes['template'].NodeValue := Value;
end;
function TXMLReplaceType.Get_Result: WideString;
begin
Result := ChildNodes['result'].Text;
end;
procedure TXMLReplaceType.Set_Result(Value: WideString);
begin
ChildNodes['result'].NodeValue := Value;
end;
{ TXMLReplaceTypeList }
function TXMLReplaceTypeList.Add: IXMLReplaceType;
begin
Result := AddItem(-1) as IXMLReplaceType;
end;
function TXMLReplaceTypeList.Insert(const Index: Integer): IXMLReplaceType;
begin
Result := AddItem(Index) as IXMLReplaceType;
end;
function TXMLReplaceTypeList.Get_Item(Index: Integer): IXMLReplaceType;
begin
Result := List[Index] as IXMLReplaceType;
end;
end. |
Unit PascalCoin.FMX.Frame.Settings.Node;
Interface
Uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
System.Actions, FMX.ActnList, FMX.Controls.Presentation, FMX.Layouts,
FMX.Edit;
Type
TEditNodeFrame = Class(TFrame)
TitleLayout: TLayout;
ButtonLayout: TLayout;
Panel1: TPanel;
Label1: TLabel;
OKButton: TButton;
CancelButton: TButton;
ActionList1: TActionList;
OKAction: TAction;
CancelAction: TAction;
NameLayout: TLayout;
NameLabel: TLabel;
NameEdit: TEdit;
URILayout: TLayout;
URILabel: TLabel;
URIEdit: TEdit;
TestButton: TSpeedButton;
StatusLabel: TLabel;
CheckURIAction: TAction;
Procedure CancelActionExecute(Sender: TObject);
Procedure OKActionExecute(Sender: TObject);
private
FValidatedURI: boolean;
FOriginalName: String;
FOriginalURI: String;
FTestNet: boolean;
Function ValidateNode: boolean;
Function GetNodeName: String;
Function GetURI: String;
Procedure SetNodeName(Const Value: String);
Procedure SetURI(Const Value: String);
Function GetTestNet: boolean;
{ Private declarations }
public
{ Public declarations }
OnCancel: TProc;
OnOk: TProc;
Property NodeName: String read GetNodeName write SetNodeName;
Property URI: String read GetURI write SetURI;
Property TestNet: boolean read GetTestNet;
End;
Implementation
{$R *.fmx}
Uses PascalCoin.FMX.DataModule, PascalCoin.RPC.Interfaces,
System.RegularExpressions, FMX.DialogService, PascalCoin.FMX.Strings;
Procedure TEditNodeFrame.CancelActionExecute(Sender: TObject);
Begin
OnCancel;
End;
Function TEditNodeFrame.ValidateNode: boolean;
resourcestring
SurlRegex = '(https?://.*):(\d*)\/?(.*)';
var
lAPI: IPascalCoinAPI;
Begin
Result := False;
if NameEdit.Text.Trim = '' then
begin
TDialogService.ShowMessage(SPleaseGiveThisNodeAName);
Exit;
end;
Result := TRegex.IsMatch(URIEdit.Text, SurlRegex);
if not Result then
begin
TDialogService.ShowMessage(STheURLEnteredIsNotValid);
FValidatedURI := False;
Exit;
end;
lAPI := MainDataModule.NewAPI(URIEdit.Text);
if lAPI.NodeAvailability <> TNodeAvailability.Avaialable then
begin
TDialogService.ShowMessage('Cannot connect to this node. The error was ' + lAPI.LastError);
FValidatedURI := False;
Exit;
end;
Result := True;
End;
Function TEditNodeFrame.GetNodeName: String;
Begin
Result := NameEdit.Text;
End;
Function TEditNodeFrame.GetTestNet: boolean;
Begin
Result := FTestNet;
End;
Function TEditNodeFrame.GetURI: String;
Begin
Result := URIEdit.Text;
End;
Procedure TEditNodeFrame.OKActionExecute(Sender: TObject);
Begin
If ValidateNode Then
OnOk;
End;
Procedure TEditNodeFrame.SetNodeName(Const Value: String);
Begin
FOriginalName := Value;
NameEdit.Text := Value;
End;
Procedure TEditNodeFrame.SetURI(Const Value: String);
Begin
FOriginalURI := Value;
URIEdit.Text := Value;
End;
End.
|
unit Unit1;
interface
uses
UI.SizeForm, UI.Ani, UI.Frame,
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, UI.Base,
UI.Standard, FMX.Effects, FMX.Controls.Presentation, FMX.StdCtrls;
type
TForm1 = class(TSizeForm)
layTitle: TLinearLayout;
tvTitle: TTextView;
btnMin: TTextView;
btnMax: TTextView;
btnClose: TTextView;
layBackground: TLinearLayout;
btnRestore: TTextView;
layBody: TRelativeLayout;
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure btnMouseEnter(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure btnMaxClick(Sender: TObject);
procedure btnRestoreClick(Sender: TObject);
procedure btnMinClick(Sender: TObject);
procedure btnMouseLeave(Sender: TObject);
procedure layTitleDblClick(Sender: TObject);
procedure ButtonView1Click(Sender: TObject);
private
{ Private declarations }
protected
function GetShadowBackgroundColor: TAlphaColor; override;
function GetShadowColor: TAlphaColor; override;
public
{ Public declarations }
procedure AniTextViewBackgroundColor(Sender: TObject; IsIn: Boolean);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
Unit2;
procedure TForm1.AniTextViewBackgroundColor(Sender: TObject; IsIn: Boolean);
var
SrcColor, DsetColor: TAlphaColor;
begin
SrcColor := TTextView(Sender).Background.ItemHovered.Color;
DsetColor := SrcColor;
if IsIn then begin
TAlphaColorRec(DsetColor).A := $FF;
end else begin
TAlphaColorRec(DsetColor).A := $0;
end;
TFrameAnimator.AnimateColor(TTextView(Sender), 'Background.ItemHovered.Color', DsetColor);
end;
procedure TForm1.btnCloseClick(Sender: TObject);
begin
if TextDialog('Are you sure to quit?') = mrOk then
Close;
end;
procedure TForm1.btnMouseEnter(Sender: TObject);
begin
AniTextViewBackgroundColor(Sender, True);
end;
procedure TForm1.btnMaxClick(Sender: TObject);
begin
btnMax.Visible := False;
btnRestore.Visible := True;
ShowMax();
layTitle.CaptureDragForm := False;
end;
procedure TForm1.btnMinClick(Sender: TObject);
begin
ShowMin();
end;
procedure TForm1.btnMouseLeave(Sender: TObject);
begin
AniTextViewBackgroundColor(Sender, False);
end;
procedure TForm1.btnRestoreClick(Sender: TObject);
begin
btnRestore.Visible := False;
btnMax.Visible := True;
ShowReSize();
layTitle.CaptureDragForm := True;
end;
procedure TForm1.ButtonView1Click(Sender: TObject);
begin
Timer1.Enabled := not Timer1.Enabled;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
tvTitle.Text := Self.Caption;
ShowShadow := True; // ´ò¿ªÒõÓ°
end;
function TForm1.GetShadowBackgroundColor: TAlphaColor;
begin
Result := Fill.Color;
end;
function TForm1.GetShadowColor: TAlphaColor;
begin
Result := $7f101010;
end;
procedure TForm1.layTitleDblClick(Sender: TObject);
begin
if btnMax.Visible then begin
btnMaxClick(Sender);
end else begin
TFrameAnimator.DelayExecute(Self,
procedure (Sender: TObject)
begin
btnRestoreClick(Sender);
end, 0.08);
end;
end;
end.
|
unit Ths.Erp.Database.Table.Ambar;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TAmbar = class(TTable)
private
FAmbarAdi: TFieldDB;
FIsVarsayılanHammaddeAmbari: TFieldDB;
FIsVarsayilanUretimAmbari: TFieldDB;
FIsVarsayilanSatisAmbari: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property AmbarAdi: TFieldDB read FAmbarAdi write FAmbarAdi;
Property IsVarsayılanHammaddeAmbari: TFieldDB read FIsVarsayılanHammaddeAmbari write FIsVarsayılanHammaddeAmbari;
Property IsVarsayilanUretimAmbari: TFieldDB read FIsVarsayilanUretimAmbari write FIsVarsayilanUretimAmbari;
Property IsVarsayilanSatisAmbari: TFieldDB read FIsVarsayilanSatisAmbari write FIsVarsayilanSatisAmbari;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TAmbar.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'ambar';
SourceCode := '1000';
FAmbarAdi := TFieldDB.Create('ambar_adi', ftString, '');
FIsVarsayılanHammaddeAmbari := TFieldDB.Create('is_varsayilan_hammadde_ambari', ftBoolean, 0);
FIsVarsayilanUretimAmbari := TFieldDB.Create('is_varsayilan_uretim_ambari', ftBoolean, 0);
FIsVarsayilanSatisAmbari := TFieldDB.Create('is_varsayilan_satis_ambari', ftBoolean, 0);
end;
procedure TAmbar.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FAmbarAdi.FieldName,
TableName + '.' + FIsVarsayılanHammaddeAmbari.FieldName,
TableName + '.' + FIsVarsayilanUretimAmbari.FieldName,
TableName + '.' + FIsVarsayilanSatisAmbari.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FAmbarAdi.FieldName).DisplayLabel := 'Ambar Adı';
Self.DataSource.DataSet.FindField(FIsVarsayılanHammaddeAmbari.FieldName).DisplayLabel := 'Varsayılan Hammadde Ambarı?';
Self.DataSource.DataSet.FindField(FIsVarsayilanUretimAmbari.FieldName).DisplayLabel := 'Varsayılan Üretim Ambarı?';
Self.DataSource.DataSet.FindField(FIsVarsayilanSatisAmbari.FieldName).DisplayLabel := 'Varsayılan Satış Ambarı?';
end;
end;
end;
procedure TAmbar.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FAmbarAdi.FieldName,
TableName + '.' + FIsVarsayılanHammaddeAmbari.FieldName,
TableName + '.' + FIsVarsayilanUretimAmbari.FieldName,
TableName + '.' + FIsVarsayilanSatisAmbari.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FAmbarAdi.Value := FormatedVariantVal(FieldByName(FAmbarAdi.FieldName).DataType, FieldByName(FAmbarAdi.FieldName).Value);
FIsVarsayılanHammaddeAmbari.Value := FormatedVariantVal(FieldByName(FIsVarsayılanHammaddeAmbari.FieldName).DataType, FieldByName(FIsVarsayılanHammaddeAmbari.FieldName).Value);
FIsVarsayilanUretimAmbari.Value := FormatedVariantVal(FieldByName(FIsVarsayilanUretimAmbari.FieldName).DataType, FieldByName(FIsVarsayilanUretimAmbari.FieldName).Value);
FIsVarsayilanSatisAmbari.Value := FormatedVariantVal(FieldByName(FIsVarsayilanSatisAmbari.FieldName).DataType, FieldByName(FIsVarsayilanSatisAmbari.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TAmbar.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FAmbarAdi.FieldName,
FIsVarsayılanHammaddeAmbari.FieldName,
FIsVarsayilanUretimAmbari.FieldName,
FIsVarsayilanSatisAmbari.FieldName
]);
NewParamForQuery(QueryOfInsert, FAmbarAdi);
NewParamForQuery(QueryOfInsert, FIsVarsayılanHammaddeAmbari);
NewParamForQuery(QueryOfInsert, FIsVarsayilanUretimAmbari);
NewParamForQuery(QueryOfInsert, FIsVarsayilanSatisAmbari);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TAmbar.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FAmbarAdi.FieldName,
FIsVarsayılanHammaddeAmbari.FieldName,
FIsVarsayilanUretimAmbari.FieldName,
FIsVarsayilanSatisAmbari.FieldName
]);
NewParamForQuery(QueryOfUpdate, FAmbarAdi);
NewParamForQuery(QueryOfUpdate, FIsVarsayılanHammaddeAmbari);
NewParamForQuery(QueryOfUpdate, FIsVarsayilanUretimAmbari);
NewParamForQuery(QueryOfUpdate, FIsVarsayilanSatisAmbari);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TAmbar.Clone():TTable;
begin
Result := TAmbar.Create(Database);
Self.Id.Clone(TAmbar(Result).Id);
FAmbarAdi.Clone(TAmbar(Result).FAmbarAdi);
FIsVarsayılanHammaddeAmbari.Clone(TAmbar(Result).FIsVarsayılanHammaddeAmbari);
FIsVarsayilanUretimAmbari.Clone(TAmbar(Result).FIsVarsayilanUretimAmbari);
FIsVarsayilanSatisAmbari.Clone(TAmbar(Result).FIsVarsayilanSatisAmbari);
end;
end.
|
//
// Created by the DataSnap proxy generator.
// 2011-01-29 ¿ÀÈÄ 10:12:30
//
unit Uclientclass;
interface
uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, DBXJSONReflect;
type
TServerMethodsClient = class(TDSAdminClient)
private
FEchoStringCommand: TDBXCommand;
FReverseStringCommand: TDBXCommand;
FInsert_RENTALCommand: TDBXCommand;
FInsert_CustomCommand: TDBXCommand;
FInsert_RESERVATIONCommand: TDBXCommand;
FupdataqueryCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
function Insert_RENTAL(PRENTALID: string; PCAR: string; PCUSTOM: string; PBRANCH: string; PPRICE: string; PUDATE: string; PRENTALDATE: string; PBACKDATE: string; PREVNUM: string; PCARSTATUS: string; PPENALTY: string): Integer;
function Insert_Custom(pid: string; pname: string; ptel: string; paddress: string; plicense: string; pjumin: string; pbigo: string): Integer;
function Insert_RESERVATION(PREV_NUM: string; PCARID: string; pid: string; PREVDATE: string; PUSEDATE: string; PBACKDATE: string; PPRICE: string; PBRANCH: string): Integer;
function updataquery(Value: string): Integer;
end;
implementation
function TServerMethodsClient.EchoString(Value: string): string;
begin
if FEchoStringCommand = nil then
begin
FEchoStringCommand := FDBXConnection.CreateCommand;
FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FEchoStringCommand.Text := 'TServerMethods.EchoString';
FEchoStringCommand.Prepare;
end;
FEchoStringCommand.Parameters[0].Value.SetWideString(Value);
FEchoStringCommand.ExecuteUpdate;
Result := FEchoStringCommand.Parameters[1].Value.GetWideString;
end;
function TServerMethodsClient.ReverseString(Value: string): string;
begin
if FReverseStringCommand = nil then
begin
FReverseStringCommand := FDBXConnection.CreateCommand;
FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FReverseStringCommand.Text := 'TServerMethods.ReverseString';
FReverseStringCommand.Prepare;
end;
FReverseStringCommand.Parameters[0].Value.SetWideString(Value);
FReverseStringCommand.ExecuteUpdate;
Result := FReverseStringCommand.Parameters[1].Value.GetWideString;
end;
function TServerMethodsClient.Insert_RENTAL(PRENTALID: string; PCAR: string; PCUSTOM: string; PBRANCH: string; PPRICE: string; PUDATE: string; PRENTALDATE: string; PBACKDATE: string; PREVNUM: string; PCARSTATUS: string; PPENALTY: string): Integer;
begin
if FInsert_RENTALCommand = nil then
begin
FInsert_RENTALCommand := FDBXConnection.CreateCommand;
FInsert_RENTALCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsert_RENTALCommand.Text := 'TServerMethods.Insert_RENTAL';
FInsert_RENTALCommand.Prepare;
end;
FInsert_RENTALCommand.Parameters[0].Value.SetWideString(PRENTALID);
FInsert_RENTALCommand.Parameters[1].Value.SetWideString(PCAR);
FInsert_RENTALCommand.Parameters[2].Value.SetWideString(PCUSTOM);
FInsert_RENTALCommand.Parameters[3].Value.SetWideString(PBRANCH);
FInsert_RENTALCommand.Parameters[4].Value.SetWideString(PPRICE);
FInsert_RENTALCommand.Parameters[5].Value.SetWideString(PUDATE);
FInsert_RENTALCommand.Parameters[6].Value.SetWideString(PRENTALDATE);
FInsert_RENTALCommand.Parameters[7].Value.SetWideString(PBACKDATE);
FInsert_RENTALCommand.Parameters[8].Value.SetWideString(PREVNUM);
FInsert_RENTALCommand.Parameters[9].Value.SetWideString(PCARSTATUS);
FInsert_RENTALCommand.Parameters[10].Value.SetWideString(PPENALTY);
FInsert_RENTALCommand.ExecuteUpdate;
Result := FInsert_RENTALCommand.Parameters[11].Value.GetInt32;
end;
function TServerMethodsClient.Insert_Custom(pid: string; pname: string; ptel: string; paddress: string; plicense: string; pjumin: string; pbigo: string): Integer;
begin
if FInsert_CustomCommand = nil then
begin
FInsert_CustomCommand := FDBXConnection.CreateCommand;
FInsert_CustomCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsert_CustomCommand.Text := 'TServerMethods.Insert_Custom';
FInsert_CustomCommand.Prepare;
end;
FInsert_CustomCommand.Parameters[0].Value.SetWideString(pid);
FInsert_CustomCommand.Parameters[1].Value.SetWideString(pname);
FInsert_CustomCommand.Parameters[2].Value.SetWideString(ptel);
FInsert_CustomCommand.Parameters[3].Value.SetWideString(paddress);
FInsert_CustomCommand.Parameters[4].Value.SetWideString(plicense);
FInsert_CustomCommand.Parameters[5].Value.SetWideString(pjumin);
FInsert_CustomCommand.Parameters[6].Value.SetWideString(pbigo);
FInsert_CustomCommand.ExecuteUpdate;
Result := FInsert_CustomCommand.Parameters[7].Value.GetInt32;
end;
function TServerMethodsClient.Insert_RESERVATION(PREV_NUM: string; PCARID: string; pid: string; PREVDATE: string; PUSEDATE: string; PBACKDATE: string; PPRICE: string; PBRANCH: string): Integer;
begin
if FInsert_RESERVATIONCommand = nil then
begin
FInsert_RESERVATIONCommand := FDBXConnection.CreateCommand;
FInsert_RESERVATIONCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsert_RESERVATIONCommand.Text := 'TServerMethods.Insert_RESERVATION';
FInsert_RESERVATIONCommand.Prepare;
end;
FInsert_RESERVATIONCommand.Parameters[0].Value.SetWideString(PREV_NUM);
FInsert_RESERVATIONCommand.Parameters[1].Value.SetWideString(PCARID);
FInsert_RESERVATIONCommand.Parameters[2].Value.SetWideString(pid);
FInsert_RESERVATIONCommand.Parameters[3].Value.SetWideString(PREVDATE);
FInsert_RESERVATIONCommand.Parameters[4].Value.SetWideString(PUSEDATE);
FInsert_RESERVATIONCommand.Parameters[5].Value.SetWideString(PBACKDATE);
FInsert_RESERVATIONCommand.Parameters[6].Value.SetWideString(PPRICE);
FInsert_RESERVATIONCommand.Parameters[7].Value.SetWideString(PBRANCH);
FInsert_RESERVATIONCommand.ExecuteUpdate;
Result := FInsert_RESERVATIONCommand.Parameters[8].Value.GetInt32;
end;
function TServerMethodsClient.updataquery(Value: string): Integer;
begin
if FupdataqueryCommand = nil then
begin
FupdataqueryCommand := FDBXConnection.CreateCommand;
FupdataqueryCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FupdataqueryCommand.Text := 'TServerMethods.updataquery';
FupdataqueryCommand.Prepare;
end;
FupdataqueryCommand.Parameters[0].Value.SetWideString(Value);
FupdataqueryCommand.ExecuteUpdate;
Result := FupdataqueryCommand.Parameters[1].Value.GetInt32;
end;
constructor TServerMethodsClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
constructor TServerMethodsClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TServerMethodsClient.Destroy;
begin
FreeAndNil(FEchoStringCommand);
FreeAndNil(FReverseStringCommand);
FreeAndNil(FInsert_RENTALCommand);
FreeAndNil(FInsert_CustomCommand);
FreeAndNil(FInsert_RESERVATIONCommand);
FreeAndNil(FupdataqueryCommand);
inherited;
end;
end.
|
unit fFurBall;
interface
uses
Winapi.Windows,
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Imaging.Jpeg,
//GLS
GLWin32Viewer, GLScene, GLObjects, GLCadencer, ODEImport,
GLTexture, GLExtrusion, GLVectorGeometry, GLShadowPlane, GLNavigator,
GLVerletTypes, GLVerletHairClasses, GLKeyboard, GLColor,
GLCrossPlatform, GLCoordinates, GLBaseClasses, ODEGL, GLVerletClasses;
const
cMaxWindMag = 8;
type
TfrmFurBall = class(TForm)
GLCadencer1: TGLCadencer;
GLScene1: TGLScene;
DC_LightHolder: TGLDummyCube;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
GLSceneViewer1: TGLSceneViewer;
GLShadowPlane_Floor: TGLShadowPlane;
GLShadowPlane_Wall: TGLShadowPlane;
Sphere1: TGLSphere;
DCShadowCaster: TGLDummyCube;
FurBall: TGLSphere;
GLShadowPlane_Floor2: TGLShadowPlane;
GLLines1: TGLLines;
GLShadowPlane_Wall2: TGLShadowPlane;
GLShadowPlane_Wall3: TGLShadowPlane;
Label_FPS: TLabel;
Timer1: TTimer;
Panel1: TPanel;
CheckBox_LockBall: TCheckBox;
CheckBox_Inertia: TCheckBox;
CheckBox_FurGravity: TCheckBox;
CheckBox_WindResistence: TCheckBox;
TrackBar_WindForce: TTrackBar;
CheckBox_Bald: TCheckBox;
Label1: TLabel;
CheckBox_Shadows: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure DC_LightHolderProgress(Sender: TObject; const deltaTime,
newTime: Double);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure CheckBox_FurGravityClick(Sender: TObject);
procedure CheckBox_WindResistenceClick(Sender: TObject);
procedure CheckBox_BaldClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure CheckBox_ShadowsClick(Sender: TObject);
procedure CheckBox_InertiaClick(Sender: TObject);
procedure TrackBar_WindForceChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
odeFurBallBody : PdxBody;
odeFurBallGeom : PdxGeom;
world : PdxWorld;
space : PdxSpace;
contactgroup : TdJointGroupID;
VerletWorld : TVerletWorld;
HairList : TList;
VCSphere : TVCSphere;
PhysicsTime : single;
Gravity : TVFGravity;
AirResistance : TVFAirResistance;
procedure CreateBall;
procedure CreateFur;
end;
var
frmFurBall: TfrmFurBall;
implementation
{$R *.dfm}
procedure nearCallback (data : pointer; o1, o2 : PdxGeom); cdecl;
const
cCOL_MAX = 1;
var
i, numc : integer;
b1,b2 : PdxBody;
contact : array[0..cCOL_MAX-1] of TdContact;
c : TdJointID;
begin
// exit without doing anything if the two bodies are connected by a joint
b1 := dGeomGetBody(o1);
b2 := dGeomGetBody(o2);
if (Assigned(b1) and Assigned(b2) and (dAreConnected (b1,b2)<>0)) then
exit;
for i :=0 to cCOL_MAX-1 do
begin
contact[i].surface.mode := dContactBounce;
// This determines friction, play around with it!
contact[i].surface.mu := 3;//10e9; //dInfinity; SHOULD BE INFINITY!
contact[i].surface.mu2 := 0;
contact[i].surface.bounce := 0.5;//0.5;
contact[i].surface.bounce_vel := 0.1;
end;
numc := dCollide (o1,o2,cCOL_MAX,contact[0].geom,sizeof(TdContact));
if (numc>0) then
begin
for i := 0 to numc-1 do
begin
c := dJointCreateContact (frmFurBall.world,frmFurBall.contactgroup, @contact[i]);
dJointAttach (c,b1,b2);
end;
end;
end;
const
cOffset = 0.03;
procedure TfrmFurBall.FormCreate(Sender: TObject);
begin
Show;
Randomize;
world := dWorldCreate();
space := dHashSpaceCreate(nil);
contactgroup := dJointGroupCreate (1000000);
dWorldSetGravity (world,0,0,-9.81);
CreateODEPlaneFromGLPlane(GLShadowPlane_Floor, space);
CreateODEPlaneFromGLPlane(GLShadowPlane_Floor2, space);
CreateODEPlaneFromGLPlane(GLShadowPlane_Wall, space);
CreateODEPlaneFromGLPlane(GLShadowPlane_Wall2, space);
CreateODEPlaneFromGLPlane(GLShadowPlane_Wall3, space);
// dCreatePlane (space,0,0,1,0);
VerletWorld := TVerletWorld.Create;
VerletWorld.Iterations := 2;
VerletWorld.VerletNodeClass := TGLVerletNode;
CheckBox_FurGravityClick(Sender);
CheckBox_WindResistenceClick(Sender);
CreateVCPlaneFromGLPlane(GLShadowPlane_Floor, VerletWorld, cOffset);
CreateVCPlaneFromGLPlane(GLShadowPlane_Floor2, VerletWorld, cOffset);
CreateVCPlaneFromGLPlane(GLShadowPlane_Wall, VerletWorld, cOffset);
CreateVCPlaneFromGLPlane(GLShadowPlane_Wall2, VerletWorld, cOffset);
CreateVCPlaneFromGLPlane(GLShadowPlane_Wall3, VerletWorld, cOffset);
HairList := TList.Create;
CreateBall;
end;
procedure TfrmFurBall.FormClose(Sender: TObject; var Action: TCloseAction);
begin
GLCadencer1.Enabled := false;
dJointGroupDestroy (contactgroup);
dSpaceDestroy (space);
dWorldDestroy (world);
end;
var
angle : double=0;
procedure TfrmFurBall.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
const
cTIME_STEP = 0.01;
var
i,j : integer;
Delta : single;
Hair : TVerletHair;
GLLines : TGLLines;
begin
Delta := deltaTime;
angle := angle + Delta*3;
while PhysicsTime<newTime do
begin
PhysicsTime := PhysicsTime + cTIME_STEP;
if not CheckBox_LockBall.Checked then
begin
dSpaceCollide (space,nil,nearCallback);
dWorldStep (world, cTIME_STEP);//}
// remove all contact joints
dJointGroupEmpty (contactgroup);
if IsKeyDown(VK_UP) then
dBodyAddForce(odeFurBallBody, 0,0,2.5)
else if IsKeyDown(VK_DOWN) then
dBodyAddForce(odeFurBallBody, 0,0,-2.5);
if IsKeyDown('A') then
dBodyAddForce(odeFurBallBody, 0,-1,0)
else if IsKeyDown('D') then
dBodyAddForce(odeFurBallBody, 0,1,0);
if IsKeyDown('W') then
dBodyAddForce(odeFurBallBody, -1,0,0)
else if IsKeyDown('S') then
dBodyAddForce(odeFurBallBody, 1,0,0);
end;
PositionSceneObject(FurBall, odeFurBallGeom);
VCSphere.Location := FurBall.Position.AsAffineVector;
VerletWorld.Progress(cTIME_STEP, PhysicsTime);
end;
for i := 0 to HairList.Count -1 do
begin
Hair := TVerletHair(HairList[i]);
GLLines := TGLLines(Hair.Data);
for j := 1 to Hair.NodeList.Count-1 do
GLLines.Nodes[j-1].AsAffineVector := Hair.NodeList[j].Location;
end;
end;
procedure TfrmFurBall.DC_LightHolderProgress(Sender: TObject; const deltaTime,
newTime: Double);
begin
// DC_LightHolder.Roll(deltaTime*pi*2*8);
end;
var
FoldMouseX : integer;
FoldMouseY : integer;
procedure TfrmFurBall.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(FoldMouseY-Y, FoldMouseX-X);
FoldMouseX := X;
FoldMouseY := Y;
end;
procedure TfrmFurBall.CreateBall;
var
m : TdMass;
begin
dMassSetSphere (m,1,FurBall.Radius);
odeFurBallGeom := dCreateSphere (space,FurBall.Radius);
odeFurBallBody := dBodyCreate(World);
dGeomSetBody (odeFurBallGeom,odeFurBallBody);
dBodySetMass (odeFurBallBody, @m);
dBodySetLinearVel(odeFurBallBody, 0, 14, 0);
dBodyAddTorque(odeFurBallBody, 0.1,0.1,0.1);
// Add the GLScene object
odeFurBallGeom.Data:=FurBall;
CopyPosFromGeomToGL(odeFurBallGeom, FurBall);
VCSphere := TVCSphere.Create(VerletWorld);
VCSphere.Radius := FurBall.Radius * 1.1;
VCSphere.Location := AffineVectorMake(FurBall.AbsolutePosition);
CreateFur;
end;
const
cRadiusMultiplier = 5;
cSegmentCount = 4;
cHairCount = 200;
cRootDepth = 4;
procedure TfrmFurBall.CreateFur;
// Much, MUCH easier that uniform distribution, and it looks fun.
procedure CreateRandomHair;
var
i : integer;
Dir : TAffineVector;
Hair : TVerletHair;
GLLines : TGLLines;
begin
Dir := AffineVectorMake(random-0.5,random-0.5,random-0.5);
NormalizeVector(Dir);
Hair := TVerletHair.Create(VerletWorld, FurBall.Radius * cRootDepth,
FurBall.Radius*cRadiusMultiplier, cSegmentCount,
VectorAdd(AffineVectorMake(FurBall.AbsolutePosition), VectorScale(Dir, FurBall.Radius)),
Dir, [vhsSkip1Node]);
//GLLines := TGLLines(GLScene1.Objects.AddNewChild(TGLLines));
GLLines := TGLLines(DCShadowCaster.AddNewChild(TGLLines));
GLLines.NodesAspect := lnaInvisible;
GLLines.LineWidth := 2;
GLLines.LineColor.Color := clrBlack;
for i := 0 to Hair.NodeList.Count-1 do
TGLVerletNode(Hair.NodeList[i]).GLBaseSceneObject := FurBall;
for i := 1 to Hair.NodeList.Count-1 do
GLLines.AddNode(Hair.NodeList[i].Location);
for i := 0 to GLLines.Nodes.Count-1 do
TGLLinesNode(GLLines.Nodes[i]).Color.Color := clrBlack;
GLLines.ObjectStyle:=GLLines.ObjectStyle+[osDirectDraw];
GLLines.SplineMode := lsmCubicSpline;
Hair.Data := GLLines;
HairList.Add(Hair);
end;
var
Hair : TVerletHair;
i : integer;
begin
for i := 0 to HairList.Count-1 do
begin
Hair := TVerletHair(HairList[i]);
TGLLines(Hair.Data).Free;
Hair.Free;
end;
HairList.Clear;
for i := 0 to cHairCount-1 do
CreateRandomHair;
end;
procedure TfrmFurBall.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta/120));
end;
procedure TfrmFurBall.CheckBox_FurGravityClick(Sender: TObject);
begin
if not CheckBox_FurGravity.Checked then
FreeAndNil(Gravity)
else
begin
Gravity := TVFGravity.Create(VerletWorld);
Gravity.Gravity := AffineVectorMake(0,0,-9.81);
end;
end;
procedure TfrmFurBall.CheckBox_WindResistenceClick(Sender: TObject);
begin
if not CheckBox_WindResistence.Checked then
FreeAndNil(AirResistance)
else
begin
AirResistance := TVFAirResistance.Create(VerletWorld);
AirResistance.DragCoeff := 0.01;
AirResistance.WindDirection := AffineVectorMake(1,0,0);
AirResistance.WindMagnitude := TrackBar_WindForce.Position/100 * cMaxWindMag;
AirResistance.WindChaos := 0.4;
end;
TrackBar_WindForce.Enabled := CheckBox_WindResistence.Checked;
end;
procedure TfrmFurBall.TrackBar_WindForceChange(Sender: TObject);
begin
if Assigned(AirResistance) then
AirResistance.WindMagnitude := TrackBar_WindForce.Position/100 * cMaxWindMag;
end;
procedure TfrmFurBall.CheckBox_BaldClick(Sender: TObject);
var
i : integer;
begin
for i := 0 to HairList.Count -1 do
begin
with TVerletHair(HairList[i]) do
begin
Anchor.NailedDown := not CheckBox_Bald.Checked;
Anchor.OldLocation := Anchor.Location;
Root.NailedDown := not CheckBox_Bald.Checked;
Root.OldLocation := Root.Location;
end;
end;
if not CheckBox_Bald.Checked then
VerletWorld.PauseInertia(5);
end;
procedure TfrmFurBall.Timer1Timer(Sender: TObject);
begin
Label_FPS.Caption := GLSceneViewer1.FramesPerSecondText;
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TfrmFurBall.CheckBox_ShadowsClick(Sender: TObject);
var
light : TGLLightSource;
begin
if CheckBox_Shadows.Checked then
light := GLLightSource1
else
light := nil;
GLShadowPlane_Floor.ShadowedLight := light;
GLShadowPlane_Floor2.ShadowedLight := light;
GLShadowPlane_Wall.ShadowedLight := light;
GLShadowPlane_Wall2.ShadowedLight := light;
GLShadowPlane_Wall3.ShadowedLight := light;
end;
procedure TfrmFurBall.CheckBox_InertiaClick(Sender: TObject);
begin
VerletWorld.Inertia := CheckBox_Inertia.Checked;
end;
end.
|
{ MIT License
Copyright (c) 2016-2020 Yevhen Loza
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.
}
{ Note that with toroid field the snake tail is buggy when it's the last
part of the snake before leaving the border }
//{$define ToroidField}
unit SnakeUnit;
{$mode objfpc}{$H+}
interface
Uses
Classes, fgl,
CastleSoundEngine, CastleConfig;
Type
{creates and stores Rabbit coordinates}
TRabbit = class(TComponent)
public
x, y: Integer;
{set new Random coordinates}
procedure ResetRabbit;
end;
{different kinds of Tail - referring to different sprites}
type TTailKind = (tkHead, tkStraight, tkTurn, tkTail);
type
{represents a Tail segment}
TTail = class
x, y: Integer;
{actually it's just a number of the sprite in the spritesheet,
TailKind determines the row and Direction determines the column}
TailKind: TTailKind;
Direction: Integer;
end;
{list of Tail segments}
type TSnakeTail = specialize TFPGObjectList<TTail>;
type
{this is our basic class where the game takes place.}
TSnake = class(TComponent)
public
{current coordinates of the Snake head}
x, y: Integer;
{current direction of the Snake}
dx, dy: Integer;
{"next" direction of the Snake / set by keyboard}
next_dx, next_dy: Integer;
{this is all the Snake body from its head (last element) to the Tail end (zero element) }
Tail: TSnakeTail;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{resets Snake to initial values}
procedure ResetSnake;
{hanldes keyboard/mouse input and sets next_dx and next_dy,
returns true if this direction is possible}
function SetDirection(ddx, ddy: Integer): Boolean;
{makes a step towards dx,dy}
procedure Move;
{detects collision with the Snake.}
function DetectCollision(tx,ty: Integer): Boolean;
private
{adds a head segment of the Snake}
procedure AddHead;
{creates the Snake body}
procedure FixTail;
end;
var MaxX,MaxY: Integer;
Snake: TSnake;
Rabbit: TRabbit;
GameOver: Boolean;
Score, BestScore: Integer;
{sounds and music to be used in game}
EatSound, EndSound, Music: TSoundBuffer;
PlaySound: Boolean; //sound on/off
LicenseString: String;
{read high Score from a file.}
procedure ReadHighScore;
{this procedure starts a new game}
procedure NewGame;
{prepare music and sound}
procedure LoadMusic;
{start and stop the music}
procedure ToggleMusic;
{Write High Score to a file}
procedure WriteHighScore;
implementation
uses
SysUtils, CastleVectors, CastleDownload;
procedure TRabbit.ResetRabbit;
begin
repeat
x := Random(MaxX);
y := Random(MaxY);
until (Snake.DetectCollision(x, y) = false) or (Snake.Tail.Count = (MaxX + 1) * (MaxY + 1)); //to avoid plaicing Rabbit inside the Snake
end;
{get sprite number for straight direction}
function GetDirection(dx, dy: Integer): Integer;
begin
if dy > 0 then
Result := 0
else
if dx > 0 then
Result := 1
else
if dy < 0 then
Result := 2
else
Result := 3;
end;
{get sprite number for turn-around direction}
function GetRotation(dx, dy: Integer): Integer;
begin
if dx > 0 then
begin
if dy > 0 then
Result := 0
else
Result := 1;
end else
begin
if dy > 0 then
Result := 3
else
Result := 2;
end;
end;
constructor TSnake.Create(AOwner: TComponent);
begin
inherited;
Tail := TSnakeTail.Create(true);
end;
destructor TSnake.Destroy;
begin
Tail.Clear;
FreeAndNil(Tail);
inherited;
end;
procedure TSnake.AddHead; inline;
var
TmpTail: TTail;
begin
TmpTail := TTail.Create;
TmpTail.x := x;
TmpTail.y := y;
TmpTail.TailKind := tkHead;
TmpTail.Direction := GetDirection(dx, dy);
Tail.Add(tmpTail);
end;
procedure TSnake.ResetSnake;
var
TmpTail: TTail;
begin
{set it to the center of the map facing up}
x := MaxX div 2;
y := MaxY div 2;
dx := 0;
dy := 1;
next_dx := dx;
next_dy := dy;
Tail.Clear; //clear Tail
{add Tail end one space back}
TmpTail := TTail.Create;
TmpTail.x := x - dx;
TmpTail.y := y - dy;
TmpTail.TailKind := tkTail;
TmpTail.Direction := GetDirection(dx, dy);
Tail.Add(tmpTail);
{add head}
AddHead;
end;
procedure TSnake.Move;
begin
{$ifdef ToroidField}
{ warp snake at the borders of the field aka toroid }
if (x + next_dx < 0) then
x := MaxX + 1
else
if (x + next_dx > MaxX) then
x := -1;
if (y + next_dy < 0) then
y := MaxY + 1
else
if (y + next_dy > MaxY) then
y := -1;
{$else}
{ detect collision with screen borders and deflect the Snake randomly }
if (x + next_dx < 0) or (x + next_dx > MaxX) then
begin
next_dx := 0;
if Random(2) = 0 then
next_dy := 1
else
next_dy := -1;
if (y + next_dy < 0) or (y + next_dy > MaxY) then
next_dy := - next_dy;
end;
if (y + next_dy < 0) or (y + next_dy > MaxY) then
begin
next_dy := 0;
if Random(2) = 0 then
next_dx := 1
else
next_dx := -1;
if (x + next_dx < 0) or (x + next_dx > MaxX) then
next_dx := -next_dx;
end;
{$endif}
{assign new dx,dy}
dx := next_dx;
dy := next_dy;
{make a step}
x += dx;
y += dy;
{detect if Snake collides itself}
if DetectCollision(x, y) then
begin
GameOver := true;
{play defeat sound}
if PlaySound then
SoundEngine.PlaySound(EndSound, false, false, 0, 1, 0, 1, TVector3.Zero)
end;
{detect if Snake has eaten a Rabbit}
if (x <> Rabbit.x) or (y <> Rabbit.y) then
begin
//cutting the Tail automatially moves the body one segment back
Snake.Tail.Remove(Snake.Tail[0]);
//add head as the last element
AddHead;
//and replace the first element for a Tail end
Tail[0].TailKind := tkTail;
Tail[0].Direction := GetDirection(Snake.Tail[1].x - Snake.Tail[0].x, Snake.Tail[1].y - Snake.Tail[0].y);
//fix second element
FixTail;
end else
begin
{Snake has eaten a Rabbit}
Inc(Score);
{we don't cut off it's Tail in this case which increases Snake length by 1}
AddHead;
FixTail;
//put a new Rabbit
Rabbit.ResetRabbit;
{play eating sound}
if PlaySound then
SoundEngine.PlaySound(EatSound, false, false, 0, 1, 0, 1, TVector3.Zero)
end;
end;
procedure TSnake.FixTail; inline;
var
ddx, ddy: Integer;
begin
if Tail.Count > 2 then
begin
{get type of Tail junction based on ddx and ddy difference between current
tile (second from the head, which actually replaces previous head).}
ddx := Tail[Tail.Count - 2].x - Tail[Tail.Count - 3].x;
if ddx = 0 then
ddx := Tail[Tail.Count - 2].x - Tail[Tail.Count - 1].x;
ddy := Tail[Tail.Count - 2].y - Tail[Tail.Count - 3].y;
if ddy = 0 then
ddy := Tail[Tail.Count - 2].y - Tail[Tail.Count - 1].y;
{based on ddx and ddy determine the straight or turn of the Tail
and the corresponding sprite to use}
if ddx = 0 then
begin
Tail[Tail.Count - 2].TailKind := tkStraight;
Tail[Tail.Count - 2].Direction := 0;
end else
if ddy = 0 then
begin
Tail[Tail.Count - 2].TailKind := tkStraight;
Tail[Tail.Count - 2].Direction := 1;
end else
begin
Tail[Tail.Count - 2].TailKind := tkTurn;
Tail[Tail.Count - 2].Direction := GetRotation(-ddx, -ddy);
end;
end;
end;
function TSnake.SetDirection(ddx, ddy: Integer): Boolean;
begin
{respond to kepyress and set dx,dy, which will be assigned on next Snake move}
Result := false;
//Snake can actually only turn, so direction 0 deg and 180 deg should are impossible
//one of dx,dy is zero, so we can do it by a simple check
if (dx = -ddx) and (dy = -ddy) then
Exit;
if (dx = ddx) and (dy = ddy) then
Exit;
Result := true;
next_dx := ddx;
next_dy := ddy;
end;
function TSnake.DetectCollision(tx,ty: Integer): Boolean;
var
i: Integer;
begin
Result := false;
{detects if point (tx,ty) collides with any segment of the Snake Tail}
//we don't check Snake Tail end
for i := 1 to Tail.Count - 1 do
if (Tail[i].x = tx) and (Tail[i].y = ty) then
begin
Result := true;
Break;
end;
end;
{read a text file for license and read user config for highScore}
procedure ReadHighScore;
var
FileStream: TStream;
MyStrings: TStringList;
begin
//create the stream to "download"
{ApplicationData files should be treated as read-only in most cases}
FileStream := Download('castle-data:/license.txt');
//create and load TStringList from the stream
MyStrings := TStringList.Create;
MyStrings.LoadFromStream(FileStream);
LicenseString := MyStrings[0];
//clean up everything
FreeAndNil(FileStream);
FreeAndNil(MyStrings);
// read user configuration and looks for string "best_Score"
UserConfig.Load;
BestScore := UserConfig.GetValue('best_Score', Round(2 * Sqrt((MaxX + 1)*(MaxY + 1))));
end;
procedure WriteHighScore;
begin
UserConfig.SetValue('best_Score', BestScore);
UserConfig.Save;
end;
{start a new game}
procedure NewGame;
begin
{set high Score}
if Score > BestScore then
begin
BestScore := Score;
{Save high Score to a file}
WriteHighScore;
end;
{reset Snake and Rabbit}
Snake.ResetSnake;
Rabbit.ResetRabbit;
{game is not over yet}
GameOver := false;
{current Score is zero}
Score := 0;
end;
var CurrentMusic: TSound;
procedure LoadMusic;
begin
PlaySound := true;
{load the sounds and music}
EatSound := SoundEngine.LoadBuffer('castle-data:/EatSound_CC0_by_EugeneLoza.ogg');
EndSound := SoundEngine.LoadBuffer('castle-data:/DieSound_CC0_by_EugeneLoza.ogg');
Music := SoundEngine.LoadBuffer('castle-data:/GreenForest_CC-BY-SA_by_Metaruka.ogg');
{initialize Sound Engine}
SoundEngine.ParseParameters;
//SoundEngine.MinAllocatedSources := 1;
{and start the music looping}
CurrentMusic := SoundEngine.PlaySound(Music, false, true, 10, 1, 0, 1, TVector3.Zero);
end;
{start and stop the music}
procedure ToggleMusic;
begin
if PlaySound then
begin
PlaySound := false;
CurrentMusic.Gain:= 0;
end else
begin
PlaySound := true;
CurrentMusic.Gain:= 1;
end;
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ Workflow Editor Dialog }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit VCLBI.Editor.Workflow;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
VCLBI.Editor.Data, VCLBI.DataManager,
Vcl.ExtCtrls, VCLBI.Grid,
VCL.ComCtrls, BI.DataItem, Vcl.StdCtrls, Vcl.Menus, BI.Workflow,
VCLBI.Editor.WorkflowItem, BI.Persist, VCLBI.NewColumn,
VCLBI.DataSelect, VCLBI.Tree, VCLBI.DataControl, VCLBI.GridForm,
Vcl.Buttons;
type
TBIWorkflowEditor = class(TForm)
PanelSelector: TPanel;
PopupAdd: TPopupMenu;
Splitter1: TSplitter;
Column1: TMenuItem;
Add1: TMenuItem;
Delete1: TMenuItem;
Rename1: TMenuItem;
Sort1: TMenuItem;
Reorder1: TMenuItem;
Filter1: TMenuItem;
ranspose1: TMenuItem;
Change1: TMenuItem;
N1: TMenuItem;
Function1: TMenuItem;
MachineLearning1: TMenuItem;
PanelMain: TPanel;
Panel2: TPanel;
BAdd: TButton;
BDelete: TButton;
SplitterPreview: TSplitter;
Integer32bit1: TMenuItem;
Integer64bit1: TMenuItem;
Singlefloat1: TMenuItem;
Doublefloat1: TMenuItem;
Extendedfloat1: TMenuItem;
ext1: TMenuItem;
DateTime1: TMenuItem;
Boolean1: TMenuItem;
Split1: TMenuItem;
Shuffle1: TMenuItem;
Duplicate1: TMenuItem;
Singlerow1: TMenuItem;
Regression1: TMenuItem;
Normalize1: TMenuItem;
Rank1: TMenuItem;
Gridify1: TMenuItem;
Clone1: TMenuItem;
PopupNew: TPopupMenu;
MenuItem2: TMenuItem;
MenuItem20: TMenuItem;
MenuItem22: TMenuItem;
MenuItem29: TMenuItem;
MenuItem34: TMenuItem;
MenuItem35: TMenuItem;
MenuItem36: TMenuItem;
MenuItem37: TMenuItem;
MenuItem38: TMenuItem;
BNew: TButton;
SBSelector: TSpeedButton;
PanelTree: TPanel;
BITree1: TBITree;
SplitterEditor: TSplitter;
PanelEditor: TPanel;
PanelPreviewButton: TPanel;
BPreview: TButton;
PopupPreview: TPopupMenu;
Grid1: TMenuItem;
Chart1: TMenuItem;
PanelPreview: TPanel;
PanelChart: TPanel;
SplitterChart: TSplitter;
Groupby1: TMenuItem;
Join1: TMenuItem;
Common1: TMenuItem;
Different1: TMenuItem;
CrossTableConfusionMatrix1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure Tree1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure Tree1DragDrop(Sender, Source: TObject; X, Y: Integer);
procedure Add1Click(Sender: TObject);
procedure BAddClick(Sender: TObject);
procedure ranspose1Click(Sender: TObject);
procedure Delete1Click(Sender: TObject);
procedure Rename1Click(Sender: TObject);
procedure Query1Click(Sender: TObject);
procedure Function1Click(Sender: TObject);
procedure BITree1Change(Sender: TObject);
procedure BDeleteClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Change1Click(Sender: TObject);
procedure PopupAddPopup(Sender: TObject);
procedure Boolean1Click(Sender: TObject);
procedure Reorder1Click(Sender: TObject);
procedure Split1Click(Sender: TObject);
procedure Sort1Click(Sender: TObject);
procedure Shuffle1Click(Sender: TObject);
procedure Filter1Click(Sender: TObject);
procedure NewCustomData1Click(Sender: TObject);
procedure Files1Click(Sender: TObject);
procedure DatabaseServer1Click(Sender: TObject);
procedure BIWebServer1Click(Sender: TObject);
procedure Duplicate1Click(Sender: TObject);
procedure Singlerow1Click(Sender: TObject);
procedure Normalize1Click(Sender: TObject);
procedure Rank1Click(Sender: TObject);
procedure Gridify1Click(Sender: TObject);
procedure Clone1Click(Sender: TObject);
procedure BITree1Deleting(Sender: TObject);
procedure Compare1Click(Sender: TObject);
procedure SBSelectorClick(Sender: TObject);
procedure BNewClick(Sender: TObject);
procedure BPreviewClick(Sender: TObject);
procedure Grid1Click(Sender: TObject);
procedure Chart1Click(Sender: TObject);
procedure Groupby1Click(Sender: TObject);
procedure Regression1Click(Sender: TObject);
procedure Join1Click(Sender: TObject);
procedure Common1Click(Sender: TObject);
procedure Different1Click(Sender: TObject);
procedure CrossTableConfusionMatrix1Click(Sender: TObject);
private
{ Private declarations }
Data : TDataSelector;
FWorkflow: TBIWorkflow;
IGrid : TBIGridForm;
ItemEditor : TWorkflowItemEditor;
procedure AddDummy(const AParent:TBITreeNode);
procedure AddItems(const AParent:TBITreeNode; const AData:TDataItem);
procedure AddMachineLearning(Sender: TObject);
procedure AddNewRoot(const AData:TDataItem; const X,Y:Integer);
procedure CheckPreviewSettings;
function ChooseItems(out ASelected:TDataItem):Boolean; overload;
function ChooseItems(out ASelected:TDataArray; const Compatible:Boolean):Boolean; overload;
function DataOf(const ANode:TBITreeNode):TDataItem;
procedure DeleteSelected;
function DirectNewShape(const AParent:TBITreeNode;
const AProvider:TDataProvider;
const AName:String):TBITreeNode;
function DoAddNode(const AParent:TBITreeNode; const AItem:TWorkflowItem):TBITreeNode;
procedure DoChangeWorkflow(const Value: TBIWorkflow);
function DoDummyExpansion(const Node:TBITreeNode):Boolean;
procedure Expanding(Sender: TObject; const Node: TBITreeNode;
var AllowExpansion: Boolean);
procedure FillTree;
procedure FilterSelf(Sender: TComponent; var Valid:Boolean);
function HasDummy(const ANode:TBITreeNode):Boolean;
procedure ItemChanged(Sender: TObject);
function ItemOf(const ANode:TBITreeNode):TWorkflowItem;
function NameOf(const AItem:TWorkflowItem):String;
function NewShape(const AParent:TBITreeNode;
const AData:TDataItem):TBITreeNode; overload;
function NewShape(const AProvider:TDataProvider;
const AName:String):TBITreeNode; overload;
procedure SelectedData(Sender:TObject);
procedure SetWorkflow(const Value: TBIWorkflow);
procedure TryAddModels;
procedure TryImport(const AKind:TDataDefinitionKind);
procedure TryMerge(const AStyle:TMergeStyle; const ACaption:String);
procedure TryPreview;
//procedure TryRefresh(const ANode:TBITreeNode);
//procedure TryRefreshNodes(const AItem:TWorkflowItem);
protected
const
TeeMsg_ItemsWorkflow='...';
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
{ Public declarations }
class function Edit(const AOwner:TComponent; const AWorkflow:TBIWorkflow):Boolean; static;
class function Embedd(const AOwner:TComponent; const AParent:TWinControl;
const AWorkflow:TBIWorkflow):TBIWorkflowEditor; static;
procedure Refresh(const Value: TBIWorkflow);
property Workflow:TBIWorkflow read FWorkflow write SetWorkflow;
end;
implementation
|
unit VCLBI.Editor.DataRank;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
BI.DataItem, BI.Workflow;
type
TDataRankEditor = class(TForm)
CBAscending: TCheckBox;
procedure FormShow(Sender: TObject);
procedure CBAscendingClick(Sender: TObject);
private
{ Private declarations }
FRank : TDataRankItem;
public
{ Public declarations }
end;
implementation
|
unit ANovoLembrete;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
PainelGradiente, ExtCtrls, Componentes1, StdCtrls, Buttons, Localizacao,
ComCtrls, UnDados, UnLembrete, Constantes;
type
TFNovoLembrete = class(TFormularioPermissao)
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
PanelColor3: TPanelColor;
PainelGradiente1: TPainelGradiente;
BGravar: TBitBtn;
BCancelar: TBitBtn;
BFechar: TBitBtn;
Label1: TLabel;
Label2: TLabel;
EData: TEditColor;
EUsuario: TEditLocaliza;
Localiza: TConsultaPadrao;
SpeedButton1: TSpeedButton;
Label3: TLabel;
CAgendar: TCheckBox;
EDatAgendamento: TCalendario;
Label4: TLabel;
PanelColor4: TPanelColor;
RSelecionarTodos: TRadioButton;
RSelecionar: TRadioButton;
BSelecionarUsuarios: TBitBtn;
Label5: TLabel;
ETitulo: TEditColor;
Label6: TLabel;
EDescricao: TMemoColor;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure RSelecionarTodosClick(Sender: TObject);
procedure BGravarClick(Sender: TObject);
procedure BSelecionarUsuariosClick(Sender: TObject);
private
VprOperacao: TRBDOperacaoCadastro;
VprAcao: Boolean;
VprDLembreteCorpo: TRBDLembreteCorpo;
FunLembrete: TRBFuncoesLembrete;
procedure InicializaClasse;
procedure CarDTela;
function DadosValidos: String;
procedure CarDClasse;
procedure BloquearTela(VpaEstado: Boolean);
public
function AlterarLembrete(VpaSeqLembrete, VpaCodUsuario: Integer): Boolean;
function NovoLembrete: Boolean;
procedure LerLembrete(VpaSeqLembrete, VpaCodUsuario: Integer);
end;
var
FNovoLembrete: TFNovoLembrete;
implementation
uses
APrincipal, ConstMsg, FunData, ASelecionarUsuarios, FunObjeto;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFNovoLembrete.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
VprAcao:= False;
FunLembrete:= TRBFuncoesLembrete.Cria(FPrincipal.BaseDados);
VprDLembreteCorpo:= TRBDLembreteCorpo.Cria;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFNovoLembrete.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
FunLembrete.Free;
VprDLembreteCorpo.Free;
Action:= CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFNovoLembrete.BFecharClick(Sender: TObject);
begin
Close;
end;
{******************************************************************************}
function TFNovoLembrete.NovoLembrete: Boolean;
begin
VprOperacao:= ocInsercao;
InicializaClasse;
CarDTela;
ShowModal;
Result:= VprAcao;
end;
{******************************************************************************}
procedure TFNovoLembrete.InicializaClasse;
begin
VprDLembreteCorpo.SeqLembrete:= 0;
VprDLembreteCorpo.CodUsuario:= Varia.CodigoUsuario;
VprDLembreteCorpo.DatLembrete:= Now;
VprDLembreteCorpo.DatAgenda:= IncDia(VprDLembreteCorpo.DatLembrete,1);
VprDLembreteCorpo.IndAgendar:= 'S';
VprDLembreteCorpo.IndTodos:= 'S';
VprDLembreteCorpo.DesTitulo:= '';
VprDLembreteCorpo.DesLembrete:= '';
end;
{******************************************************************************}
procedure TFNovoLembrete.CarDTela;
begin
EData.Text:= FormatDateTime('DD/MM/YYYY HH:MM',VprDLembreteCorpo.DatLembrete);
EUsuario.AInteiro:= VprDLembreteCorpo.CodUsuario;
EUsuario.Atualiza;
CAgendar.Checked:= (VprDLembreteCorpo.IndAgendar = 'S');
EDatAgendamento.DateTime:= VprDLembreteCorpo.DatAgenda;
RSelecionarTodos.Checked:= False;
RSelecionar.Checked:= False;
if VprDLembreteCorpo.IndTodos = 'S' then
RSelecionarTodos.Checked:= True
else
RSelecionar.Checked:= True;
RSelecionarTodosClick(RSelecionarTodos);
ETitulo.Text:= VprDLembreteCorpo.DesTitulo;
EDescricao.Text:= VprDLembreteCorpo.DesLembrete;
end;
{******************************************************************************}
procedure TFNovoLembrete.RSelecionarTodosClick(Sender: TObject);
begin
BSelecionarUsuarios.Enabled:= RSelecionar.Checked;
if RSelecionarTodos.Checked and (VprOperacao in [ocInsercao,ocEdicao]) then
FreeTObjectsList(VprDLembreteCorpo.Usuarios);
end;
{******************************************************************************}
procedure TFNovoLembrete.BGravarClick(Sender: TObject);
var
VpfResultado: String;
begin
VpfResultado:= DadosValidos;
if VpfResultado = '' then
begin
CarDClasse;
VpfResultado:= FunLembrete.GravaDLembrete(VprDLembreteCorpo);
if VpfResultado = '' then
begin
VprAcao:= True;
Close;
end;
end;
if VpfResultado <> '' then
aviso(VpfResultado);
end;
{******************************************************************************}
function TFNovoLembrete.DadosValidos: String;
begin
Result:= '';
if ETitulo.Text = '' then
begin
Result:= 'TÍTULO NÃO PREENCHIDO!!!'#13'É necessário preencher o título do lembrete.';
ActiveControl:= ETitulo;
end
else
if EDescricao.Text = '' then
begin
Result:= 'DESCRIÇÃO NÃO PREENCHIDA!!!'#13'É necessário preencher a descrição do lembrete.';
ActiveControl:= EDescricao;
end
else
if VprDLembreteCorpo.Usuarios.Count < 0 then
begin
Result:= 'SEM USUÁRIOS SELECIONADOS!!!'#13'É necessário selecionar pelo menos um usuário.';
ActiveControl:= PanelColor4;
end
end;
{******************************************************************************}
procedure TFNovoLembrete.CarDClasse;
begin
VprDLembreteCorpo.DatAgenda:= MontaData(1,1,1900);
if CAgendar.Checked then
begin
VprDLembreteCorpo.IndAgendar:= 'S';
VprDLembreteCorpo.DatAgenda:= EDatAgendamento.DateTime;
end
else
VprDLembreteCorpo.IndAgendar:= 'N';
if RSelecionarTodos.Checked then
VprDLembreteCorpo.IndTodos:= 'S'
else
VprDLembreteCorpo.IndTodos:= 'N';
VprDLembreteCorpo.DesTitulo:= ETitulo.Text;
VprDLembreteCorpo.DesLembrete:= EDescricao.Text;
VprDLembreteCorpo.CodUsuario := Varia.CodigoUsuario;
end;
{******************************************************************************}
procedure TFNovoLembrete.BSelecionarUsuariosClick(Sender: TObject);
begin
FSelecionarUsuarios:= TFSelecionarUsuarios.CriarSDI(Application,'',True);
FSelecionarUsuarios.SelecionarUsuarios(VprDLembreteCorpo);
FSelecionarUsuarios.Free;
end;
{******************************************************************************}
procedure TFNovoLembrete.LerLembrete(VpaSeqLembrete, VpaCodUsuario: Integer);
begin
VprOperacao:= ocConsulta;
FunLembrete.CarDLembrete(VpaSeqLembrete,VprDLembreteCorpo);
BloquearTela(True);
CarDTela;
FunLembrete.UsuarioLeuLembrete(VpaSeqLembrete,VpaCodUsuario);
ShowModal;
end;
{******************************************************************************}
procedure TFNovoLembrete.BloquearTela(VpaEstado: Boolean);
begin
CAgendar.Enabled:= not VpaEstado;
EDatAgendamento.Enabled:= not VpaEstado;
PanelColor4.Enabled:= not VpaEstado;
ETitulo.ReadOnly:= not VpaEstado;
EDescricao.ReadOnly:= not VpaEstado;
BGravar.Enabled:= not VpaEstado;
end;
{******************************************************************************}
function TFNovoLembrete.AlterarLembrete(VpaSeqLembrete, VpaCodUsuario: Integer): Boolean;
begin
VprOperacao:= ocInsercao;
FunLembrete.CarDLembrete(VpaSeqLembrete,VprDLembreteCorpo);
CarDTela;
if (VprDLembreteCorpo.CodUsuario = VpaCodUsuario) or
(puAdministrador in Varia.PermissoesUsuario) then
ShowModal
else
aviso('PERMISSÃO INVÁLIDA!!!'#13'Somente o dono deste lembrete pode alterá-lo.');
Result:= VprAcao;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFNovoLembrete]);
end.
|
{*******************************************************}
{ }
{ DESede 加解密单元 (与 Java 、 C# 同步) }
{ }
{ 版权所有 (C) 2016 YangYxd }
{ }
{*******************************************************}
// 注意:C# 默认需要设置 CBCMode = True
// 编解码核心使用 FlyUtils.CSharpJavaDES 修改
unit DESede;
interface
uses
Classes, SysUtils;
type
TPointerStream = class(TCustomMemoryStream)
public
constructor Create(const Data: Pointer; const ASize: NativeInt); overload;
function Write(const Buffer; Count: Longint): Longint; overload; override;
function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; overload; override;
end;
// 根据字符串生成密钥字节数组
function Build3DesKey(const Key: string): TBytes;
// DESede 加密
function DESedeEncrypt(const Data: string; const Key: string): RawByteString; overload;
function DESedeEncrypt(const Data: string; const Key: TBytes): RawByteString; overload;
function DESedeEncrypt(const Data: TBytes; const Key: TBytes): RawByteString; overload;
function DESedeEncrypt(Data: Pointer; Size: Cardinal; const Key: TBytes): RawByteString; overload;
function DESedeEncrypt(const InStream, OutStream: TStream; const Key: TBytes): Boolean; overload;
// DESede 解密
function DESedeDecrypt(const Data: RawByteString; const Key: string): RawByteString; overload;
function DESedeDecrypt(const Data: RawByteString; const Key: TBytes): RawByteString; overload;
function DESedeDecrypt(Data: Pointer; Size: Cardinal; const Key: string): RawByteString; overload;
function DESedeDecrypt(const Data: TBytes; const Key: TBytes): RawByteString; overload;
function DESedeDecrypt(Data: Pointer; Size: Cardinal; const Key: TBytes): RawByteString; overload;
function DESedeDecrypt(const InStream, OutStream: TStream; const Key: TBytes): Boolean; overload;
function DESedeToBytes(Data: Pointer; Size: Cardinal; const Key: string): TBytes; overload;
function DESedeToBytes(const InStream: TStream; const Key: string): TBytes; overload;
function StrToDESede(const Data, Key: string): RawByteString;
function StrToDESedeBytes(const Data, Key: string): TBytes;
function DESedeToStr(const Data: RawByteString; const Key: string): string; overload;
function DESedeToStr(const Data: TBytes; const Key: string): string; overload;
// DES 编码解码
function DESedeStream(const InStream, OutStream: TStream; const Key: TBytes;
EncryptMode: Boolean; IvBytes: TBytes; CBCMode: Boolean = True; PaddingZero: Boolean = False): Boolean;
implementation
function Build3DesKey(const Key: string): TBytes;
var
S: RawByteString;
begin
SetLength(Result, 24);
S := AnsiToUtf8(Key);
if (Length(Result) > Length(S)) then
// 如果temp不够24位
Move(Pointer(S)^, Result[0], Length(S))
else
Move(Pointer(S)^, Result[0], Length(Result));
end;
type
TUint32s = array of UInt32;
procedure des_createKeys(KeyBytes: TBytes; var keys: TUint32s);
const
// declaring this locally speeds things up a bit
pc2bytes0: array [0 .. 15] of UInt32 = (0, $4, $20000000, $20000004, $10000,
$10004, $20010000, $20010004, $200, $204, $20000200, $20000204, $10200,
$10204, $20010200, $20010204);
pc2bytes1: array [0 .. 15] of UInt32 = (0, $1, $100000, $100001, $4000000,
$4000001, $4100000, $4100001, $100, $101, $100100, $100101, $4000100,
$4000101, $4100100, $4100101);
pc2bytes2: array [0 .. 15] of UInt32 = (0, $8, $800, $808, $1000000, $1000008,
$1000800, $1000808, 0, $8, $800, $808, $1000000, $1000008, $1000800,
$1000808);
pc2bytes3: array [0 .. 15] of UInt32 = (0, $200000, $8000000, $8200000, $2000,
$202000, $8002000, $8202000, $20000, $220000, $8020000, $8220000, $22000,
$222000, $8022000, $8222000);
pc2bytes4: array [0 .. 15] of UInt32 = (0, $40000, $10, $40010, 0, $40000,
$10, $40010, $1000, $41000, $1010, $41010, $1000, $41000, $1010, $41010);
pc2bytes5: array [0 .. 15] of UInt32 = (0, $400, $20, $420, 0, $400, $20,
$420, $2000000, $2000400, $2000020, $2000420, $2000000, $2000400, $2000020,
$2000420);
pc2bytes6: array [0 .. 15] of UInt32 = (0, $10000000, $80000, $10080000, $2,
$10000002, $80002, $10080002, 0, $10000000, $80000, $10080000, $2,
$10000002, $80002, $10080002);
pc2bytes7: array [0 .. 15] of UInt32 = (0, $10000, $800, $10800, $20000000,
$20010000, $20000800, $20010800, $20000, $30000, $20800, $30800, $20020000,
$20030000, $20020800, $20030800);
pc2bytes8: array [0 .. 15] of UInt32 = (0, $40000, 0, $40000, $2, $40002, $2,
$40002, $2000000, $2040000, $2000000, $2040000, $2000002, $2040002,
$2000002, $2040002);
pc2bytes9: array [0 .. 15] of UInt32 = (0, $10000000, $8, $10000008, 0,
$10000000, $8, $10000008, $400, $10000400, $408, $10000408, $400, $10000400,
$408, $10000408);
pc2bytes10: array [0 .. 15] of UInt32 = (0, $20, 0, $20, $100000, $100020,
$100000, $100020, $2000, $2020, $2000, $2020, $102000, $102020,
$102000, $102020);
pc2bytes11: array [0 .. 15] of UInt32 = (0, $1000000, $200, $1000200, $200000,
$1200000, $200200, $1200200, $4000000, $5000000, $4000200, $5000200,
$4200000, $5200000, $4200200, $5200200);
pc2bytes12: array [0 .. 15] of UInt32 = (0, $1000, $8000000, $8001000, $80000,
$81000, $8080000, $8081000, $10, $1010, $8000010, $8001010, $80010, $81010,
$8080010, $8081010);
pc2bytes13: array [0 .. 15] of UInt32 = (0, $4, $100, $104, 0, $4, $100, $104,
$1, $5, $101, $105, $1, $5, $101, $105);
// now define the left shifts which need to be done
shifts: array [0 .. 15] of UInt32 = (0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1,
1, 1, 1, 0);
var
lefttemp, righttemp, temp: UInt32;
m, n, j, i: Integer;
left, right: UInt32;
iterations: Integer;
begin
// how many iterations (1 for des, 3 for triple des)
j := Length(KeyBytes);
if j >= 24 then
iterations := 3
else
iterations := 1;
// stores the return keys
n := 32 * iterations;
SetLength(keys, n);
n := 8 * iterations;
SetLength(KeyBytes, n);
for i := j to n - 1 do
KeyBytes[i] := 0;
// other variables
m := 0;
n := 0;
for j := 0 to iterations - 1 do begin // either 1 or 3 iterations
left := (ord(KeyBytes[m + 0]) shl 24) or (ord(KeyBytes[m + 1]) shl 16) or
(ord(KeyBytes[m + 2]) shl 8) or ord(KeyBytes[m + 3]);
right := (ord(KeyBytes[m + 4]) shl 24) or (ord(KeyBytes[m + 5]) shl 16) or
(ord(KeyBytes[m + 6]) shl 8) or ord(KeyBytes[m + 7]);
m := m + 8;
temp := ((left shr 4) xor right) and $0F0F0F0F;
right := right xor temp;
left := left xor (temp shl 4);
temp := ((right shr 16) xor left) and $0000FFFF;
left := left xor temp;
right := right xor (temp shl 16);
temp := ((left shr 2) xor right) and $33333333;
right := right xor temp;
left := left xor (temp shl 2);
temp := ((right shr 16) xor left) and $0000FFFF;
left := left xor temp;
right := right xor (temp shl 16);
temp := ((left shr 1) xor right) and $55555555;
right := right xor temp;
left := left xor (temp shl 1);
temp := ((right shr 8) xor left) and $00FF00FF;
left := left xor temp;
right := right xor (temp shl 8);
temp := ((left shr 1) xor right) and $55555555;
right := right xor temp;
left := left xor (temp shl 1);
// the right side needs to be shifted and to get the last four bits of the left side
temp := (left shl 8) or ((right shr 20) and $000000F0);
// left needs to be put upside down
left := (right shl 24) or ((right shl 8) and $FF0000) or
((right shr 8) and $FF00) or ((right shr 24) and $F0);
right := temp;
// now go through and perform these shifts on the left and right keys
for i := low(shifts) to high(shifts) do begin
// shift the keys either one or two bits to the left
if shifts[i] > 0 then begin
left := (left shl 2) or (left shr 26);
right := (right shl 2) or (right shr 26);
// left := left shl 0;
// right:= right shl 0;
end else begin
left := (left shl 1) or (left shr 27);
right := (right shl 1) or (right shr 27);
// left := left shl 0;
// right:= right shl 0;
end;
left := left and $FFFFFFF0;
right := right and $FFFFFFF0;
// now apply PC-2, in such a way that E is easier when encrypting or decrypting
// this conversion will look like PC-2 except only the last 6 bits of each byte are used
// rather than 48 consecutive bits and the order of lines will be according to
// how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
lefttemp := pc2bytes0[left shr 28] or pc2bytes1[(left shr 24) and $F] or
pc2bytes2[(left shr 20) and $F] or pc2bytes3[(left shr 16) and $F] or
pc2bytes4[(left shr 12) and $F] or pc2bytes5[(left shr 8) and $F] or
pc2bytes6[(left shr 4) and $F];
righttemp := pc2bytes7[right shr 28] or pc2bytes8[(right shr 24) and $F]
or pc2bytes9[(right shr 20) and $F] or pc2bytes10[(right shr 16) and $F]
or pc2bytes11[(right shr 12) and $F] or pc2bytes12[(right shr 8) and $F]
or pc2bytes13[(right shr 4) and $F];
temp := ((righttemp shr 16) xor lefttemp) and $0000FFFF;
keys[n + 0] := lefttemp xor temp;
keys[n + 1] := righttemp xor (temp shl 16);
n := n + 2;
end;
end; // for each iterations
// return the keys we've created
end; // end of des_createKeys
function DESedeStream(const InStream, OutStream: TStream; const Key: TBytes;
EncryptMode: Boolean; IvBytes: TBytes; CBCMode: Boolean = True; PaddingZero: Boolean = False): Boolean;
const
spfunction1: array [0 .. 63] of UInt32 = ($1010400, 0, $10000, $1010404,
$1010004, $10404, $4, $10000, $400, $1010400, $1010404, $400, $1000404,
$1010004, $1000000, $4, $404, $1000400, $1000400, $10400, $10400, $1010000,
$1010000, $1000404, $10004, $1000004, $1000004, $10004, 0, $404, $10404,
$1000000, $10000, $1010404, $4, $1010000, $1010400, $1000000, $1000000,
$400, $1010004, $10000, $10400, $1000004, $400, $4, $1000404, $10404,
$1010404, $10004, $1010000, $1000404, $1000004, $404, $10404, $1010400,
$404, $1000400, $1000400, 0, $10004, $10400, 0, $1010004);
spfunction2: array [0 .. 63] of UInt32 = ($80108020, $80008000, $8000,
$108020, $100000, $20, $80100020, $80008020, $80000020, $80108020,
$80108000, $80000000, $80008000, $100000, $20, $80100020, $108000, $100020,
$80008020, 0, $80000000, $8000, $108020, $80100000, $100020, $80000020, 0,
$108000, $8020, $80108000, $80100000, $8020, 0, $108020, $80100020, $100000,
$80008020, $80100000, $80108000, $8000, $80100000, $80008000, $20,
$80108020, $108020, $20, $8000, $80000000, $8020, $80108000, $100000,
$80000020, $100020, $80008020, $80000020, $100020, $108000, 0, $80008000,
$8020, $80000000, $80100020, $80108020, $108000);
spfunction3: array [0 .. 63] of UInt32 = ($208, $8020200, 0, $8020008,
$8000200, 0, $20208, $8000200, $20008, $8000008, $8000008, $20000, $8020208,
$20008, $8020000, $208, $8000000, $8, $8020200, $200, $20200, $8020000,
$8020008, $20208, $8000208, $20200, $20000, $8000208, $8, $8020208, $200,
$8000000, $8020200, $8000000, $20008, $208, $20000, $8020200, $8000200, 0,
$200, $20008, $8020208, $8000200, $8000008, $200, 0, $8020008, $8000208,
$20000, $8000000, $8020208, $8, $20208, $20200, $8000008, $8020000,
$8000208, $208, $8020000, $20208, $8, $8020008, $20200);
spfunction4: array [0 .. 63] of UInt32 = ($802001, $2081, $2081, $80, $802080,
$800081, $800001, $2001, 0, $802000, $802000, $802081, $81, 0, $800080,
$800001, $1, $2000, $800000, $802001, $80, $800000, $2001, $2080, $800081,
$1, $2080, $800080, $2000, $802080, $802081, $81, $800080, $800001, $802000,
$802081, $81, 0, 0, $802000, $2080, $800080, $800081, $1, $802001, $2081,
$2081, $80, $802081, $81, $1, $2000, $800001, $2001, $802080, $800081,
$2001, $2080, $800000, $802001, $80, $800000, $2000, $802080);
spfunction5: array [0 .. 63] of UInt32 = ($100, $2080100, $2080000, $42000100,
$80000, $100, $40000000, $2080000, $40080100, $80000, $2000100, $40080100,
$42000100, $42080000, $80100, $40000000, $2000000, $40080000, $40080000, 0,
$40000100, $42080100, $42080100, $2000100, $42080000, $40000100, 0,
$42000000, $2080100, $2000000, $42000000, $80100, $80000, $42000100, $100,
$2000000, $40000000, $2080000, $42000100, $40080100, $2000100, $40000000,
$42080000, $2080100, $40080100, $100, $2000000, $42080000, $42080100,
$80100, $42000000, $42080100, $2080000, 0, $40080000, $42000000, $80100,
$2000100, $40000100, $80000, 0, $40080000, $2080100, $40000100);
spfunction6: array [0 .. 63] of UInt32 = ($20000010, $20400000, $4000,
$20404010, $20400000, $10, $20404010, $400000, $20004000, $404010, $400000,
$20000010, $400010, $20004000, $20000000, $4010, 0, $400010, $20004010,
$4000, $404000, $20004010, $10, $20400010, $20400010, 0, $404010, $20404000,
$4010, $404000, $20404000, $20000000, $20004000, $10, $20400010, $404000,
$20404010, $400000, $4010, $20000010, $400000, $20004000, $20000000, $4010,
$20000010, $20404010, $404000, $20400000, $404010, $20404000, 0, $20400010,
$10, $4000, $20400000, $404010, $4000, $400010, $20004010, 0, $20404000,
$20000000, $400010, $20004010);
spfunction7: array [0 .. 63] of UInt32 = ($200000, $4200002, $4000802, 0,
$800, $4000802, $200802, $4200800, $4200802, $200000, 0, $4000002, $2,
$4000000, $4200002, $802, $4000800, $200802, $200002, $4000800, $4000002,
$4200000, $4200800, $200002, $4200000, $800, $802, $4200802, $200800, $2,
$4000000, $200800, $4000000, $200800, $200000, $4000802, $4000802, $4200002,
$4200002, $2, $200002, $4000000, $4000800, $200000, $4200800, $802, $200802,
$4200800, $802, $4000002, $4200802, $4200000, $200800, 0, $2, $4200802, 0,
$200802, $4200000, $800, $4000002, $4000800, $800, $200002);
spfunction8: array [0 .. 63] of UInt32 = ($10001040, $1000, $40000, $10041040,
$10000000, $10001040, $40, $10000000, $40040, $10040000, $10041040, $41000,
$10041000, $41040, $1000, $40, $10040000, $10000040, $10001000, $1040,
$41000, $40040, $10040040, $10041000, $1040, 0, 0, $10040040, $10000040,
$10001000, $41040, $40000, $41040, $40000, $10041000, $1000, $40, $10040040,
$1000, $41040, $10001000, $40, $10000040, $10040000, $10040040, $10000000,
$40000, $10001040, 0, $10041040, $40040, $10000040, $10040000, $10001000,
$10001040, 0, $10041040, $41000, $41000, $1040, $1040, $40040, $10000000,
$10041000);
var
Keys: TUint32s;
i, j, keyslen, iterations: Integer;
m, len, BufLen: Integer;
looping: array of Integer;
endloop, loopinc: Integer;
cbcleft, cbcleft2, cbcright, cbcright2: UInt32;
temp, right1, right2, left, right: UInt32;
ReadCount, ProcessCount, PaddingCount: UInt64;
StrByte, OutByte: array [0..7] of Byte;
begin
if InStream = nil then
raise Exception.Create('Error: InStream is nil.');
if OutStream = nil then
raise Exception.Create('Error: OutStream is nil.');
ProcessCount := InStream.Size - InStream.Position;
if EncryptMode then begin
PaddingCount := 8 - ProcessCount mod 8;
if PaddingCount = 8 then
PaddingCount := 0;
end else
PaddingCount := 0;
j := Length(IvBytes);
SetLength(IvBytes, 8);
for i := j to 7 do
IvBytes[i] := 0;
SetLength(keys, 0);
des_createKeys(Key, keys);
keyslen := length(keys);
if keyslen = 32 then
iterations := 3
else
iterations := 9;
ReadCount := 0;
m := 0;
cbcleft := 0;
cbcleft2 := 0;
cbcright := 0;
cbcright2 := 0;
if iterations = 3 then begin
if EncryptMode then begin
SetLength(looping, 3);
looping[0] := 0;
looping[1] := 32;
looping[2] := 2;
end else begin
SetLength(looping, 3);
looping[0] := 30;
looping[1] := -2;
looping[2] := -2;
end;
end else begin
if EncryptMode then begin
SetLength(looping, 9);
looping[0] := 0;
looping[1] := 32;
looping[2] := 2;
looping[3] := 62;
looping[4] := 30;
looping[5] := -2;
looping[6] := 64;
looping[7] := 96;
looping[8] := 2;
end else begin
SetLength(looping, 9);
looping[0] := 94;
looping[1] := 62;
looping[2] := -2;
looping[3] := 32;
looping[4] := 64;
looping[5] := 2;
looping[6] := 30;
looping[7] := -2;
looping[8] := -2;
end;
end;
if CBCMode then begin // CBC mode (这里也是关键C#DES加密默认是CBC模式)
cbcleft := (ord(IvBytes[0]) shl 24) or (ord(IvBytes[1]) shl 16) or
(ord(IvBytes[2]) shl 8) or ord(IvBytes[3]);
cbcright := (ord(IvBytes[4]) shl 24) or (ord(IvBytes[5]) shl 16) or
(ord(IvBytes[6]) shl 8) or ord(IvBytes[7]);
end;
// loop through each 64 bit chunk of the message
len := ProcessCount + PaddingCount;
while m < len do begin
BufLen := 8;
if (ReadCount + BufLen) > ProcessCount then
BufLen := ProcessCount - ReadCount;
if BufLen > 0 then
InStream.Read(StrByte, BufLen);
if BufLen < 0 then BufLen := 0;
ReadCount := ReadCount + 8;
if BufLen < 8 then begin
// 尾部不足 8,补 PaddingCount
for I := BufLen to 8 - 1 do begin
if PaddingZero then
StrByte[I] := 0
else
StrByte[I] := PaddingCount;
end;
end;
m := m + 8;
left := (ord(StrByte[0]) shl 24) or (ord(StrByte[1]) shl 16) or
(ord(StrByte[2]) shl 8) or ord(StrByte[3]);
right := (ord(StrByte[4]) shl 24) or (ord(StrByte[5]) shl 16) or
(ord(StrByte[6]) shl 8) or ord(StrByte[7]);
// for Cipher Block Chaining mode, xor the message with the previous result
if CBCMode then
begin
if EncryptMode then
begin
left := left xor cbcleft;
right := right xor cbcright;
end
else
begin
cbcleft2 := cbcleft;
cbcright2 := cbcright;
cbcleft := left;
cbcright := right;
end;
end;
// first each 64 but chunk of the message must be permuted according to IP
temp := ((left shr 4) xor right) and $0F0F0F0F;
right := right xor temp;
left := left xor (temp shl 4);
temp := ((left shr 16) xor right) and $0000FFFF;
right := right xor temp;
left := left xor (temp shl 16);
temp := ((right shr 2) xor left) and $33333333;
left := left xor temp;
right := right xor (temp shl 2);
temp := ((right shr 8) xor left) and $00FF00FF;
left := left xor temp;
right := right xor (temp shl 8);
temp := ((left shr 1) xor right) and $55555555;
right := right xor temp;
left := left xor (temp shl 1);
left := ((left shl 1) or (left shr 31));
right := ((right shl 1) or (right shr 31));
// do this either 1 or 3 times for each chunk of the message
j := 0;
while j < iterations do begin
endloop := looping[j + 1];
loopinc := looping[j + 2];
// now go through and perform the encryption or decryption
i := looping[j];
while i <> endloop do begin
if (i >= 0) and (i < keyslen) then
right1 := right xor keys[i]
else
right1 := right xor 0;
if (i >= 0) and (i < keyslen - 1) then
right2 := ((right shr 4) or (right shl 28)) xor keys[i + 1]
else
right2 := ((right shr 4) or (right shl 28)) xor 0;
// the result is attained by passing these bytes through the S selection functions
temp := left;
left := right;
right := temp xor (spfunction2[(right1 shr 24) and $3F] or
spfunction4[(right1 shr 16) and $3F] or spfunction6[(right1 shr 8) and
$3F] or spfunction8[right1 and $3F] or spfunction1[(right2 shr 24) and
$3F] or spfunction3[(right2 shr 16) and $3F] or
spfunction5[(right2 shr 8) and $3F] or spfunction7[right2 and $3F]);
i := i + loopinc;
end;
temp := left;
left := right;
right := temp; // unreverse left and right
j := j + 3;
end; // for either 1 or 3 iterations
// move then each one bit to the right
left := ((left shr 1) or (left shl 31));
right := ((right shr 1) or (right shl 31));
// now perform IP-1, which is IP in the opposite direction
temp := ((left shr 1) xor right) and $55555555;
right := right xor temp;
left := left xor (temp shl 1);
temp := ((right shr 8) xor left) and $00FF00FF;
left := left xor temp;
right := right xor (temp shl 8);
temp := ((right shr 2) xor left) and $33333333;
left := left xor temp;
right := right xor (temp shl 2);
temp := ((left shr 16) xor right) and $0000FFFF;
right := right xor temp;
left := left xor (temp shl 16);
temp := ((left shr 4) xor right) and $0F0F0F0F;
right := right xor temp;
left := left xor (temp shl 4);
// for Cipher Block Chaining mode, xor the message with the previous result
if CBCMode then begin
if EncryptMode then begin
cbcleft := left;
cbcright := right;
end else begin
left := left xor cbcleft2;
right := right xor cbcright2;
end;
end;
OutByte[0] := left shr 24;
OutByte[1] := (left shr 16) and $FF;
OutByte[2] := (left shr 8) and $FF;
OutByte[3] := left and $FF;
OutByte[4] := right shr 24;
OutByte[5] := (right shr 16) and $FF;
OutByte[6] := (right shr 8) and $FF;
OutByte[7] := right and $FF;
BufLen := 8;
if not EncryptMode then begin
PaddingCount := 0;
if (ReadCount >= ProcessCount) then begin
if PaddingZero then begin
for I := 7 downto 0 do begin
if OutByte[I] <> 0 then begin
BufLen := I + 1;
break;
end;
end;
end else begin
PaddingCount := OutByte[7];
if PaddingCount > 8 then PaddingCount := 0;
if PaddingCount > 0 then
BufLen := 8 - PaddingCount;
if BufLen < 0 then BufLen := 0;
end;
end;
end;
if BufLen > 0 then
OutStream.Write(OutByte, BufLen);
end;
SetLength(keys, 0);
Result := True;
end;
function DESedeEncrypt(const Data: string; const Key: string): RawByteString;
var
sKey: TBytes;
begin
sKey := build3DesKey(Key);
Result := DESedeEncrypt(Data, sKey);
end;
function DESedeEncrypt(const Data: string; const Key: TBytes): RawByteString;
var
S: RawByteString;
begin
S := AnsiToUtf8(Data); // 转为 UTF-8
Result := DESedeEncrypt(@S[1], Length(S), Key);
end;
function DESedeEncrypt(const Data: TBytes; const Key: TBytes): RawByteString;
begin
if Length(Data) = 0 then
Result := ''
else
Result := DESedeEncrypt(@Data[0], Length(Data), Key);
end;
function DESedeEncrypt(Data: Pointer; Size: Cardinal; const Key: TBytes): RawByteString;
var
FIn: TPointerStream;
FOut: TPointerStream;
P: Cardinal;
begin
Result := '';
if (Size = 0) or (Length(Key) <> 24) then Exit;
FIn := TPointerStream.Create();
FOut := TPointerStream.Create();
try
FIn.SetPointer(Data, Size);
FIn.Position := 0;
if Size mod 8 > 0 then
P := Size div 8 * 8 + 8
else
P := Size;
SetLength(Result, P);
FOut.SetPointer(Pointer(Result), P);
FOut.Position := 0;
DESedeEncrypt(FIn, FOut, Key);
finally
FIn.Free;
FOut.Free;
end;
end;
function DESedeEncrypt(const InStream, OutStream: TStream; const Key: TBytes): Boolean;
begin
Result := DESedeStream(InStream, OutStream, Key, True, [], False, False);
end;
function DESedeDecrypt(const Data: RawByteString; const Key: string): RawByteString;
var
sKey: TBytes;
begin
sKey := build3DesKey(Key);
Result := DESedeDecrypt(Data, sKey);
end;
function DESedeDecrypt(const Data: RawByteString; const Key: TBytes): RawByteString;
begin
Result := DESedeDecrypt(Pointer(Data), Length(Data), Key);
end;
function DESedeDecrypt(Data: Pointer; Size: Cardinal; const Key: string): RawByteString;
var
sKey: TBytes;
begin
sKey := build3DesKey(Key);
Result := DESedeDecrypt(Data, Size, sKey);
end;
function DESedeDecrypt(const Data: TBytes; const Key: TBytes): RawByteString;
begin
if Length(Data) = 0 then
Result := ''
else
Result := DESedeDecrypt(@Data[0], Length(Data), Key);
end;
function DESedeDecrypt(Data: Pointer; Size: Cardinal; const Key: TBytes): RawByteString;
var
FIn: TPointerStream;
FOut: TPointerStream;
begin
Result := '';
if (Size = 0) or (Length(Key) <> 24) then Exit;
FIn := TPointerStream.Create();
FOut := TPointerStream.Create();
try
FIn.SetPointer(Data, Size);
FIn.Position := 0;
SetLength(Result, Size);
FOut.SetPointer(Pointer(Result), Size);
FOut.Position := 0;
DESedeDecrypt(FIn, FOut, Key);
SetLength(Result, FOut.Position);
finally
FIn.Free;
FOut.Free;
end;
end;
function DESedeDecrypt(const InStream, OutStream: TStream; const Key: TBytes): Boolean;
begin
Result := DESedeStream(InStream, OutStream, Key, False, [], False, False);
end;
function DESedeToStr(const Data: RawByteString; const Key: string): string;
var
S: RawByteString;
begin
S := DESedeDecrypt(Data, Key);
Result := string(Utf8ToAnsi(S));
end;
function DESedeToStr(const Data: TBytes; const Key: string): string;
var
S: RawByteString;
sKey: TBytes;
begin
sKey := build3DesKey(Key);
S := DESedeDecrypt(Data, sKey);
Result := string(Utf8ToAnsi(S));
end;
function DESedeToBytes(Data: Pointer; Size: Cardinal; const Key: string): TBytes;
var
FIn: TPointerStream;
begin
FIn := TPointerStream.Create(Data, Size);
try
Result := DESedeToBytes(FIn, Key);
finally
FreeAndNil(FIn);
end;
end;
function DESedeToBytes(const InStream: TStream; const Key: string): TBytes;
var
sKey: TBytes;
FOut: TPointerStream;
ASize: Int64;
begin
SetLength(Result, 0);
ASize := InStream.Size;
sKey := build3DesKey(Key);
if (ASize = 0) or (Length(sKey) <> 24) then Exit;
FOut := TPointerStream.Create();
try
SetLength(Result, ASize);
FOut.SetPointer(@Result[0], ASize);
FOut.Position := 0;
DESedeDecrypt(InStream, FOut, sKey);
SetLength(Result, FOut.Position);
finally
FOut.Free;
end;
end;
function StrToDESede(const Data, Key: string): RawByteString;
begin
Result := DESedeEncrypt(Data, Key);
end;
function StrToDESedeBytes(const Data, Key: string): TBytes;
var
FIn: TPointerStream;
FOut: TPointerStream;
sKey: TBytes;
S: RawByteString;
P: Cardinal;
begin
SetLength(Result, 0);
sKey := build3DesKey(Key);
if (Data = '') or (Length(sKey) <> 24) then Exit;
S := AnsiToUtf8(Data); // 转为 UTF-8
FIn := TPointerStream.Create();
FOut := TPointerStream.Create();
try
P := length(S);
FIn.SetPointer(Pointer(S), P);
FIn.Position := 0;
if P mod 8 > 0 then
P := P div 8 * 8 + 8;
SetLength(Result, P);
FOut.SetPointer(@Result[0], P);
FOut.Position := 0;
DESedeEncrypt(FIn, FOut, sKey);
finally
FIn.Free;
FOut.Free;
end;
end;
{ TPointerStream }
function TPointerStream.Write(const Buffer; Count: Longint): Longint;
var
Pos: Longint;
begin
if Count > 0 then begin
Pos := Position;
System.Move(Buffer, (PByte(Memory) + Pos)^, Count);
Position := Pos + Count;
end;
Result := Count;
end;
constructor TPointerStream.Create(const Data: Pointer; const ASize: NativeInt);
begin
inherited Create();
SetPointer(Data, ASize);
end;
function TPointerStream.Write(const Buffer: TBytes; Offset,
Count: Longint): Longint;
var
Pos: Longint;
begin
if (Count >= 0) then begin
Pos := Position;
System.Move(Buffer[Offset], (PByte(Memory) + Pos)^, Count);
Position := Pos + Count;
end;
Result := Count;
end;
end.
|
unit IDTempTableQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls,
SequenceQuery, DSWrap;
type
TIDTempTableW = class(TDSWrap)
private
FID: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure AppendData(AField: TField);
property ID: TFieldWrap read FID;
end;
TQueryIDTempTable = class(TQueryBase)
private
FTableName: string;
FW: TIDTempTableW;
function CreateTempTable: string;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
property TableName: string read FTableName;
property W: TIDTempTableW read FW;
{ Public declarations }
end;
implementation
const
temp_table_prefix = 'temp_table';
{$R *.dfm}
constructor TQueryIDTempTable.Create(AOwner: TComponent);
var
ASQL: string;
begin
inherited;
FW := TIDTempTableW.Create(FDQuery);
FTableName := CreateTempTable;
ASQL := String.Format('SELECT ID FROM %s', [FTableName]);
FDQuery.Open(ASQL);
end;
function TQueryIDTempTable.CreateTempTable: string;
var
ASQL: string;
i: Integer;
begin
i := TQuerySequence.NextValue(temp_table_prefix);
Result := String.Format('%s_%d', [temp_table_prefix, i]);
ASQL := String.Format('CREATE TEMP TABLE %s (ID INTEGER)', [Result]);
FDQuery.ExecSQL(ASQL);
end;
constructor TIDTempTableW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
end;
procedure TIDTempTableW.AppendData(AField: TField);
begin
Assert(AField <> nil);
Assert(AField.DataSet <> nil);
Assert(AField.DataSet.Active);
AField.DataSet.DisableControls;
try
AField.DataSet.First;
while not AField.DataSet.Eof do
begin
TryAppend;
ID.F.Value := AField.Value;
TryPost;
AField.DataSet.Next;
end;
finally
AField.DataSet.EnableControls;
end;
end;
end.
|
{ Turbo Pascal 3.0 compatibility unit
Copyright (C) 1998-2005 Free Software Foundation, Inc.
Author: Frank Heckenbach <frank@pascal.gnu.de>
This file is part of GNU Pascal.
GNU Pascal is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2, or (at your
option) any later version.
GNU Pascal is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030412}
{$error This unit requires GPC release 20030412 or newer.}
{$endif}
unit Turbo3;
interface
import GPC only (AssignTFDD);
System (MemAvail => System_MemAvail,
MaxAvail => System_MaxAvail);
CRT (LowVideo => CRT_LowVideo,
HighVideo => CRT_HighVideo);
var
Kbd: Text;
CBreak: Boolean absolute CheckBreak;
procedure AssignKbd (var f: AnyFile);
function MemAvail: Integer;
function MaxAvail: Integer;
function LongFileSize (var f: AnyFile): Real;
function LongFilePos (var f: AnyFile): Real;
procedure LongSeek (var f: AnyFile; aPosition: Real);
procedure LowVideo;
procedure HighVideo;
implementation
function Kbd_Read (var PrivateData; var Buffer; Size: SizeType) = BytesRead: SizeType;
var CharBuf: array [1 .. Size] of Char absolute Buffer;
begin
Discard (PrivateData);
BytesRead := 0;
repeat
Inc (BytesRead);
CharBuf[BytesRead] := ReadKey;
if CharBuf[BytesRead] = #0 then CharBuf[BytesRead] := chEsc
until (BytesRead = Size) or not KeyPressed
end;
procedure AssignKbd (var f: AnyFile);
begin
AssignTFDD (f, nil, nil, nil, Kbd_Read, nil, nil, nil, nil, nil)
end;
function MemAvail: Integer;
begin
MemAvail := System_MemAvail div 16
end;
function MaxAvail: Integer;
begin
MaxAvail := System_MaxAvail div 16
end;
function LongFileSize (var f: AnyFile): Real;
begin
LongFileSize := FileSize (f)
end;
function LongFilePos (var f: AnyFile): Real;
begin
LongFilePos := FilePos (f)
end;
procedure LongSeek (var f: AnyFile; aPosition: Real);
begin
Seek (f, Round (aPosition))
end;
procedure LowVideo;
begin
TextColor (LightGray);
TextBackground (Black)
end;
procedure HighVideo;
begin
TextColor (Yellow);
TextBackground (Black)
end;
to begin do
begin
NormAttr := Yellow + $10 * Black;
AssignKbd (Kbd);
Reset (Kbd)
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
{ osc2.c
A damping effect is given to oscillating objects using a
function of the type A = Ao exp(-t/a) sin(t/b). The total
no. of frames is used to keep track of time elapsed.
(c) Mahesh Venkitachalam 1999. http://home.att.net/~bighesh
}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Dialogs,
SysUtils, OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC: HDC;
hrc: HGLRC;
theta : Integer;
fRot, fOsc : Boolean;
nf : Integer;
n_osc : GLint;
procedure Init;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
const
ell = 1;
cyl = 2;
light_pos : Array [0..3] of GLFloat = (100.0, 100.0, 100.0, 0.0);
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Инициализация}
procedure TfrmGL.Init;
const
light_diffuse : Array [0..3] of GLFloat = (1.0, 1.0, 1.0, 0.0);
light_specular : Array [0..3] of GLFloat = (1.0, 1.0, 1.0, 0.0);
mat_specular : Array [0..3] of GLFloat = (1.0, 1.0, 1.0, 1.0);
mat_shininess : Array [0..0] of GLFloat = (50.0);
var
qobj : GLUquadricObj;
begin
glLightfv(GL_LIGHT0, GL_DIFFUSE, @light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, @light_specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, @mat_specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, @mat_shininess);
glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
glLightfv(GL_LIGHT0,GL_POSITION, @light_pos);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glClearColor(1.0, 1.0, 1.0, 0.0);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_NORMALIZE);
glDepthFunc(GL_LEQUAL);
// glu stuff
qobj := gluNewQuadric;
glNewList(ell, GL_COMPILE);
gluSphere(qobj,1.0,20,20);
glEndList;
glNewList(cyl, GL_COMPILE);
glPushMatrix;
glRotatef(180.0,1.0,0.0,0.0);
gluDisk(qobj,0.0,1.0,20,20);
glPopMatrix;
gluCylinder(qobj,1.0,1.0,4.0,20,20);
glPushMatrix;
glTranslatef(0.0,0.0,4.0);
gluDisk(qobj,0.0,1.0,20,20);
glPopMatrix;
glEndList;
gluDeleteQuadric (qobj);
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
a, b : GLFloat;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
If n_osc > 1000 then fOsc := FALSE;
If fOsc then begin
n_osc := n_osc + 1;
a := 20.0*(1.0 + exp(-n_osc/100.0)*abs(sin(2.0*PI*nf/10.0)));
b := 20.0*(1.0 + exp(-n_osc/50.0)*abs(sin(2.0*PI*nf/10.0)));
glLoadIdentity;
// viewing transform
glTranslatef(0.0,0.0,-200.0);
If fRot then
glRotatef(theta,0.0,0.0,1.0);
// modelling transforms
glPushMatrix;
glTranslatef(0.0,0.0,0.0);
glColor3f(1.0,0.0,0.0);
glPushMatrix;
glTranslatef(-40.0,-40.0,40.0);
glScalef(a,20.0,20.0);
glCallList(ell);
glPopMatrix;
glColor3f(0.0,1.0,0.0);
glPushMatrix;
glTranslatef(20.0,40.0,20.0);
glRotatef(30.0,1.0,0.0,0.0);
glScalef(b,20.0,20.0);
glCallList(cyl);
glPopMatrix;
glPopMatrix;
end;
SwapBuffers(DC); // конец работы
EndPaint(Handle, ps);
nf := nf + 1;
theta := (theta + 2) mod 360;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
nf := 0;
theta := 0;
fRot := False;
fOsc := True;
n_osc := 0;
Init;
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(50.0, 1.0, 10.0, 500.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
glDeleteLists (ell, 2);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
If Key = VK_INSERT
then fRot := not fRot
else begin
n_osc := 0;
fOsc := TRUE;
end;
end;
end.
|
unit DropSource;
// -----------------------------------------------------------------------------
// Project: Drag and Drop Component Suite
// Module: DropSource
// Description: Implements Dragging & Dropping of data
// FROM your application to another.
// Version: 4.0
// Date: 18-MAY-2001
// Target: Win32, Delphi 5-6
// Authors: Anders Melander, anders@melander.dk, http://www.melander.dk
// Copyright © 1997-2001 Angus Johnson & Anders Melander
// -----------------------------------------------------------------------------
// General changes:
// - Some component glyphs has changed.
//
// TDropSource changes:
// - CutToClipboard and CopyToClipboard now uses OleSetClipboard.
// This means that descendant classes no longer needs to override the
// CutOrCopyToClipboard method.
// - New OnGetData event.
// - Changed to use new V4 architecture:
// * All clipboard format support has been removed from TDropSource, it has
// been renamed to TCustomDropSource and the old TDropSource has been
// modified to descend from TCustomDropSource and has moved to the
// DropSource3 unit. TDropSource is now supported for backwards
// compatibility only and will be removed in a future version.
// * A new TCustomDropMultiSource, derived from TCustomDropSource, uses the
// new architecture (with TClipboardFormat and TDataFormat) and is the new
// base class for all the drop source components.
// - TInterfacedComponent moved to DragDrop unit.
// -----------------------------------------------------------------------------
// TODO -oanme -cCheckItOut : OleQueryLinkFromData
// TODO -oanme -cDocumentation : CutToClipboard and CopyToClipboard alters the value of PreferredDropEffect.
// TODO -oanme -cDocumentation : Clipboard must be flushed or emptied manually after CutToClipboard and CopyToClipboard. Automatic flush is not guaranteed.
// TODO -oanme -cDocumentation : Delete-on-paste. Why and How.
// TODO -oanme -cDocumentation : Optimized move. Why and How.
// TODO -oanme -cDocumentation : OnPaste event is only fired if target sets the "Paste Succeeded" clipboard format. Explorer does this for delete-on-paste move operations.
// TODO -oanme -cDocumentation : DragDetectPlus. Why and How.
// -----------------------------------------------------------------------------
interface
uses
DragDrop,
DragDropFormats,
ActiveX,
Controls,
Windows,
Classes;
{$include DragDrop.inc}
type
TDragResult = (drDropCopy, drDropMove, drDropLink, drCancel,
drOutMemory, drAsync, drUnknown);
TDropEvent = procedure(Sender: TObject; DragType: TDragType;
var ContinueDrop: Boolean) of object;
//: TAfterDropEvent is fired after the target has finished processing a
// successfull drop.
// The Optimized parameter is True if the target either performed an operation
// other than a move or performed an "optimized move". In either cases, the
// source isn't required to delete the source data.
// If the Optimized parameter is False, the target performed an "unoptimized
// move" operation and the source is required to delete the source data to
// complete the move operation.
TAfterDropEvent = procedure(Sender: TObject; DragResult: TDragResult;
Optimized: Boolean) of object;
TFeedbackEvent = procedure(Sender: TObject; Effect: LongInt;
var UseDefaultCursors: Boolean) of object;
//: The TDropDataEvent event is fired when the target requests data from the
// drop source or offers data to the drop source.
// The Handled flag should be set if the event handler satisfied the request.
TDropDataEvent = procedure(Sender: TObject; const FormatEtc: TFormatEtc;
out Medium: TStgMedium; var Handled: Boolean) of object;
//: TPasteEvent is fired when the target sends a "Paste Succeeded" value
// back to the drop source after a clipboard transfer.
// The DeleteOnPaste parameter is True if the source is required to delete
// the source data. This will only occur after a CutToClipboard operation
// (corresponds to a move drag/drop).
TPasteEvent = procedure(Sender: TObject; Action: TDragResult;
DeleteOnPaste: boolean) of object;
////////////////////////////////////////////////////////////////////////////////
//
// TCustomDropSource
//
////////////////////////////////////////////////////////////////////////////////
// Abstract base class for all Drop Source components.
// Implements the IDropSource and IDataObject interfaces.
////////////////////////////////////////////////////////////////////////////////
TCustomDropSource = class(TDragDropComponent, IDropSource, IDataObject,
IAsyncOperation)
private
FDragTypes: TDragTypes;
FFeedbackEffect: LongInt;
// Events...
FOnDrop: TDropEvent;
FOnAfterDrop: TAfterDropEvent;
FOnFeedback: TFeedBackEvent;
FOnGetData: TDropDataEvent;
FOnSetData: TDropDataEvent;
FOnPaste: TPasteEvent;
// Drag images...
FImages: TImageList;
FShowImage: boolean;
FImageIndex: integer;
FImageHotSpot: TPoint;
FDragSourceHelper: IDragSourceHelper;
// Async transfer...
FAllowAsync: boolean;
FRequestAsync: boolean;
FIsAsync: boolean;
protected
property FeedbackEffect: LongInt read FFeedbackEffect write FFeedbackEffect;
// IDropSource implementation
function QueryContinueDrag(fEscapePressed: bool;
grfKeyState: LongInt): HRESULT; stdcall;
function GiveFeedback(dwEffect: LongInt): HRESULT; stdcall;
// IDataObject implementation
function GetData(const FormatEtcIn: TFormatEtc;
out Medium: TStgMedium):HRESULT; stdcall;
function GetDataHere(const FormatEtc: TFormatEtc;
out Medium: TStgMedium):HRESULT; stdcall;
function QueryGetData(const FormatEtc: TFormatEtc): HRESULT; stdcall;
function GetCanonicalFormatEtc(const FormatEtc: TFormatEtc;
out FormatEtcout: TFormatEtc): HRESULT; stdcall;
function SetData(const FormatEtc: TFormatEtc; var Medium: TStgMedium;
fRelease: Bool): HRESULT; stdcall;
function EnumFormatEtc(dwDirection: LongInt;
out EnumFormatEtc: IEnumFormatEtc): HRESULT; stdcall;
function dAdvise(const FormatEtc: TFormatEtc; advf: LongInt;
const advsink: IAdviseSink; out dwConnection: LongInt): HRESULT; stdcall;
function dUnadvise(dwConnection: LongInt): HRESULT; stdcall;
function EnumdAdvise(out EnumAdvise: IEnumStatData): HRESULT; stdcall;
// IAsyncOperation implementation
function EndOperation(hResult: HRESULT; const pbcReserved: IBindCtx;
dwEffects: Cardinal): HRESULT; stdcall;
function GetAsyncMode(out fDoOpAsync: LongBool): HRESULT; stdcall;
function InOperation(out pfInAsyncOp: LongBool): HRESULT; stdcall;
function SetAsyncMode(fDoOpAsync: LongBool): HRESULT; stdcall;
function StartOperation(const pbcReserved: IBindCtx): HRESULT; stdcall;
// Abstract methods
function DoGetData(const FormatEtcIn: TFormatEtc;
out Medium: TStgMedium): HRESULT; virtual; abstract;
function DoSetData(const FormatEtc: TFormatEtc;
var Medium: TStgMedium): HRESULT; virtual;
function HasFormat(const FormatEtc: TFormatEtc): boolean; virtual; abstract;
function GetEnumFormatEtc(dwDirection: LongInt): IEnumFormatEtc; virtual; abstract;
// Data format event sink
procedure DataChanging(Sender: TObject); virtual;
// Clipboard
function CutOrCopyToClipboard: boolean; virtual;
procedure DoOnPaste(Action: TDragResult; DeleteOnPaste: boolean); virtual;
// Property access
procedure SetShowImage(Value: boolean);
procedure SetImages(const Value: TImageList);
procedure SetImageIndex(const Value: integer);
procedure SetPoint(Index: integer; Value: integer);
function GetPoint(Index: integer): integer;
function GetPerformedDropEffect: longInt; virtual;
function GetLogicalPerformedDropEffect: longInt; virtual;
procedure SetPerformedDropEffect(const Value: longInt); virtual;
function GetPreferredDropEffect: longInt; virtual;
procedure SetPreferredDropEffect(const Value: longInt); virtual;
function GetInShellDragLoop: boolean; virtual;
function GetTargetCLSID: TCLSID; virtual;
procedure SetInShellDragLoop(const Value: boolean); virtual;
function GetLiveDataOnClipboard: boolean;
procedure SetAllowAsync(const Value: boolean);
// Component management
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
property DragSourceHelper: IDragSourceHelper read FDragSourceHelper;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: TDragResult; virtual;
function CutToClipboard: boolean; virtual;
function CopyToClipboard: boolean; virtual;
procedure FlushClipboard; virtual;
procedure EmptyClipboard; virtual;
property PreferredDropEffect: longInt read GetPreferredDropEffect
write SetPreferredDropEffect;
property PerformedDropEffect: longInt read GetPerformedDropEffect
write SetPerformedDropEffect;
property LogicalPerformedDropEffect: longInt read GetLogicalPerformedDropEffect;
property InShellDragLoop: boolean read GetInShellDragLoop
write SetInShellDragLoop;
property TargetCLSID: TCLSID read GetTargetCLSID;
property LiveDataOnClipboard: boolean read GetLiveDataOnClipboard;
property AsyncTransfer: boolean read FIsAsync;
published
property DragTypes: TDragTypes read FDragTypes write FDragTypes;
// Events
property OnFeedback: TFeedbackEvent read FOnFeedback write FOnFeedback;
property OnDrop: TDropEvent read FOnDrop write FOnDrop;
property OnAfterDrop: TAfterDropEvent read FOnAfterDrop write FOnAfterDrop;
property OnGetData: TDropDataEvent read FOnGetData write FOnGetData;
property OnSetData: TDropDataEvent read FOnSetData write FOnSetData;
property OnPaste: TPasteEvent read FOnPaste write FOnPaste;
// Drag Images...
property Images: TImageList read FImages write SetImages;
property ImageIndex: integer read FImageIndex write SetImageIndex;
property ShowImage: boolean read FShowImage write SetShowImage;
property ImageHotSpotX: integer index 1 read GetPoint write SetPoint;
property ImageHotSpotY: integer index 2 read GetPoint write SetPoint;
// Async transfer...
property AllowAsyncTransfer: boolean read FAllowAsync write SetAllowAsync;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TCustomDropMultiSource
//
////////////////////////////////////////////////////////////////////////////////
// Drop target base class which can accept multiple formats.
////////////////////////////////////////////////////////////////////////////////
TCustomDropMultiSource = class(TCustomDropSource)
private
FFeedbackDataFormat: TFeedbackDataFormat;
FRawDataFormat: TRawDataFormat;
protected
function DoGetData(const FormatEtcIn: TFormatEtc;
out Medium: TStgMedium):HRESULT; override;
function DoSetData(const FormatEtc: TFormatEtc;
var Medium: TStgMedium): HRESULT; override;
function HasFormat(const FormatEtc: TFormatEtc): boolean; override;
function GetEnumFormatEtc(dwDirection: LongInt): IEnumFormatEtc; override;
function GetPerformedDropEffect: longInt; override;
function GetLogicalPerformedDropEffect: longInt; override;
function GetPreferredDropEffect: longInt; override;
procedure SetPerformedDropEffect(const Value: longInt); override;
procedure SetPreferredDropEffect(const Value: longInt); override;
function GetInShellDragLoop: boolean; override;
procedure SetInShellDragLoop(const Value: boolean); override;
function GetTargetCLSID: TCLSID; override;
procedure DoOnSetData(DataFormat: TCustomDataFormat;
ClipboardFormat: TClipboardFormat);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property DataFormats;
// TODO : Add support for delayed rendering with OnRenderData event.
published
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropEmptySource
//
////////////////////////////////////////////////////////////////////////////////
// Do-nothing source for use with TDataFormatAdapter and such
////////////////////////////////////////////////////////////////////////////////
TDropEmptySource = class(TCustomDropMultiSource);
////////////////////////////////////////////////////////////////////////////////
//
// TDropSourceThread
//
////////////////////////////////////////////////////////////////////////////////
// Executes a drop source operation from a thread.
// TDropSourceThread is an alternative to the Windows 2000 Asynchronous Data
// Transfer support.
////////////////////////////////////////////////////////////////////////////////
type
TDropSourceThread = class(TThread)
private
FDropSource: TCustomDropSource;
FDragResult: TDragResult;
protected
procedure Execute; override;
public
constructor Create(ADropSource: TCustomDropSource; AFreeOnTerminate: Boolean);
property DragResult: TDragResult read FDragResult;
property Terminated;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Utility functions
//
////////////////////////////////////////////////////////////////////////////////
function DropEffectToDragResult(DropEffect: longInt): TDragResult;
////////////////////////////////////////////////////////////////////////////////
//
// Component registration
//
////////////////////////////////////////////////////////////////////////////////
procedure Register;
(*******************************************************************************
**
** IMPLEMENTATION
**
*******************************************************************************)
implementation
uses
CommCtrl,
ComObj,
Graphics;
////////////////////////////////////////////////////////////////////////////////
//
// Component registration
//
////////////////////////////////////////////////////////////////////////////////
procedure Register;
begin
RegisterComponents(DragDropComponentPalettePage, [TDropEmptySource]);
end;
////////////////////////////////////////////////////////////////////////////////
//
// Utility functions
//
////////////////////////////////////////////////////////////////////////////////
function DropEffectToDragResult(DropEffect: longInt): TDragResult;
begin
case DropEffect of
DROPEFFECT_NONE:
Result := drCancel;
DROPEFFECT_COPY:
Result := drDropCopy;
DROPEFFECT_MOVE:
Result := drDropMove;
DROPEFFECT_LINK:
Result := drDropLink;
else
Result := drUnknown; // This is probably an error condition
end;
end;
// -----------------------------------------------------------------------------
// TCustomDropSource
// -----------------------------------------------------------------------------
constructor TCustomDropSource.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DragTypes := [dtCopy]; //default to Copy.
// Note: Normally we would call _AddRef or coLockObjectExternal(Self) here to
// make sure that the component wasn't deleted prematurely (e.g. after a call
// to RegisterDragDrop), but since our ancestor class TInterfacedComponent
// disables reference counting, we do not need to do so.
FImageHotSpot := Point(16,16);
FImages := nil;
end;
destructor TCustomDropSource.Destroy;
begin
// TODO -oanme -cImprovement : Maybe FlushClipboard would be more appropiate?
EmptyClipboard;
inherited Destroy;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.GetCanonicalFormatEtc(const FormatEtc: TFormatEtc;
out FormatEtcout: TFormatEtc): HRESULT;
begin
Result := DATA_S_SAMEFORMATETC;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.SetData(const FormatEtc: TFormatEtc;
var Medium: TStgMedium; fRelease: Bool): HRESULT;
begin
// Warning: Ordinarily it would be much more efficient to just call
// HasFormat(FormatEtc) to determine if we support the given format, but
// because we have to able to accept *all* data formats, even unknown ones, in
// order to support the Windows 2000 drag helper functionality, we can't
// reject any formats here. Instead we pass the request on to DoSetData and
// let it worry about the details.
// if (HasFormat(FormatEtc)) then
// begin
try
Result := DoSetData(FormatEtc, Medium);
finally
if (fRelease) then
ReleaseStgMedium(Medium);
end;
// end else
// Result:= DV_E_FORMATETC;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.DAdvise(const FormatEtc: TFormatEtc; advf: LongInt;
const advSink: IAdviseSink; out dwConnection: LongInt): HRESULT;
begin
Result := OLE_E_ADVISENOTSUPPORTED;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.DUnadvise(dwConnection: LongInt): HRESULT;
begin
Result := OLE_E_ADVISENOTSUPPORTED;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.EnumDAdvise(out EnumAdvise: IEnumStatData): HRESULT;
begin
Result := OLE_E_ADVISENOTSUPPORTED;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.GetData(const FormatEtcIn: TFormatEtc;
out Medium: TStgMedium):HRESULT; stdcall;
var
Handled: boolean;
begin
Handled := False;
if (Assigned(FOnGetData)) then
// Fire event to ask user for data.
FOnGetData(Self, FormatEtcIn, Medium, Handled);
// If user provided data, there is no need to call descendant for it.
if (Handled) then
Result := S_OK
else if (HasFormat(FormatEtcIn)) then
// Call descendant class to get data.
Result := DoGetData(FormatEtcIn, Medium)
else
Result:= DV_E_FORMATETC;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.GetDataHere(const FormatEtc: TFormatEtc;
out Medium: TStgMedium):HRESULT; stdcall;
begin
Result := E_NOTIMPL;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.QueryGetData(const FormatEtc: TFormatEtc): HRESULT; stdcall;
begin
if (HasFormat(FormatEtc)) then
Result:= S_OK
else
Result:= DV_E_FORMATETC;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.EnumFormatEtc(dwDirection: LongInt;
out EnumFormatEtc:IEnumFormatEtc): HRESULT; stdcall;
begin
EnumFormatEtc := GetEnumFormatEtc(dwDirection);
if (EnumFormatEtc <> nil) then
Result := S_OK
else
Result := E_NOTIMPL;
end;
// -----------------------------------------------------------------------------
// Implements IDropSource.QueryContinueDrag
function TCustomDropSource.QueryContinueDrag(fEscapePressed: bool;
grfKeyState: LongInt): HRESULT; stdcall;
var
ContinueDrop : Boolean;
DragType : TDragType;
begin
if FEscapePressed then
Result := DRAGDROP_S_CANCEL
// Allow drag and drop with either mouse buttons.
else if (grfKeyState and (MK_LBUTTON or MK_RBUTTON) = 0) then
begin
ContinueDrop := DropEffectToDragType(FeedbackEffect, DragType) and
(DragType in DragTypes);
InShellDragLoop := False;
// If a valid drop then do OnDrop event if assigned...
if ContinueDrop and Assigned(OnDrop) then
OnDrop(Self, DragType, ContinueDrop);
if ContinueDrop then
Result := DRAGDROP_S_DROP
else
Result := DRAGDROP_S_CANCEL;
end else
Result := S_OK;
end;
// -----------------------------------------------------------------------------
// Implements IDropSource.GiveFeedback
function TCustomDropSource.GiveFeedback(dwEffect: LongInt): HRESULT; stdcall;
var
UseDefaultCursors: Boolean;
begin
UseDefaultCursors := True;
FeedbackEffect := dwEffect;
if Assigned(OnFeedback) then
OnFeedback(Self, dwEffect, UseDefaultCursors);
if UseDefaultCursors then
Result := DRAGDROP_S_USEDEFAULTCURSORS
else
Result := S_OK;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.DoSetData(const FormatEtc: TFormatEtc;
var Medium: TStgMedium): HRESULT;
var
Handled: boolean;
begin
Result := E_NOTIMPL;
if (Assigned(FOnSetData)) then
begin
Handled := False;
// Fire event to ask user to handle data.
FOnSetData(Self, FormatEtc, Medium, Handled);
if (Handled) then
Result := S_OK;
end;
end;
// -----------------------------------------------------------------------------
procedure TCustomDropSource.SetAllowAsync(const Value: boolean);
begin
if (FAllowAsync <> Value) then
begin
FAllowAsync := Value;
if (not FAllowAsync) then
begin
FRequestAsync := False;
FIsAsync := False;
end;
end;
end;
function TCustomDropSource.GetAsyncMode(out fDoOpAsync: LongBool): HRESULT;
begin
fDoOpAsync := FRequestAsync;
Result := S_OK;
end;
function TCustomDropSource.SetAsyncMode(fDoOpAsync: LongBool): HRESULT;
begin
if (FAllowAsync) then
begin
FRequestAsync := fDoOpAsync;
Result := S_OK;
end else
Result := E_NOTIMPL;
end;
function TCustomDropSource.InOperation(out pfInAsyncOp: LongBool): HRESULT;
begin
pfInAsyncOp := FIsAsync;
Result := S_OK;
end;
function TCustomDropSource.StartOperation(const pbcReserved: IBindCtx): HRESULT;
begin
if (FRequestAsync) then
begin
FIsAsync := True;
Result := S_OK;
end else
Result := E_NOTIMPL;
end;
function TCustomDropSource.EndOperation(hResult: HRESULT;
const pbcReserved: IBindCtx; dwEffects: Cardinal): HRESULT;
var
DropResult: TDragResult;
begin
if (FIsAsync) then
begin
FIsAsync := False;
if (Assigned(FOnAfterDrop)) then
begin
if (Succeeded(hResult)) then
DropResult := DropEffectToDragResult(dwEffects and DragTypesToDropEffect(FDragTypes))
else
DropResult := drUnknown;
FOnAfterDrop(Self, DropResult,
(DropResult <> drDropMove) or (PerformedDropEffect <> DROPEFFECT_MOVE));
end;
Result := S_OK;
end else
Result := E_FAIL;
end;
function TCustomDropSource.Execute: TDragResult;
function GetRGBColor(Value: TColor): DWORD;
begin
Result := ColorToRGB(Value);
case Result of
clNone: Result := CLR_NONE;
clDefault: Result := CLR_DEFAULT;
end;
end;
var
DropResult: HRESULT;
AllowedEffects,
DropEffect: longint;
IsDraggingImage: boolean;
shDragImage: TSHDRAGIMAGE;
shDragBitmap: TBitmap;
begin
shDragBitmap := nil;
AllowedEffects := DragTypesToDropEffect(FDragTypes);
// Reset the "Performed Drop Effect" value. If it is supported by the target,
// the target will set it to the desired value when the drop occurs.
PerformedDropEffect := -1;
if (FShowImage) then
begin
// Attempt to create Drag Drop helper object.
// At present this is only supported on Windows 2000. If the object can't be
// created, we fall back to the old image list based method (which only
// works within the application).
CoCreateInstance(CLSID_DragDropHelper, nil, CLSCTX_INPROC_SERVER,
IDragSourceHelper, FDragSourceHelper);
// Display drag image.
if (FDragSourceHelper <> nil) then
begin
IsDraggingImage := True;
shDragBitmap := TBitmap.Create;
shDragBitmap.PixelFormat := pfDevice;
FImages.GetBitmap(ImageIndex, shDragBitmap);
shDragImage.hbmpDragImage := shDragBitmap.Handle;
shDragImage.sizeDragImage.cx := shDragBitmap.Width;
shDragImage.sizeDragImage.cy := shDragBitmap.Height;
shDragImage.crColorKey := GetRGBColor(FImages.BkColor);
shDragImage.ptOffset.x := ImageHotSpotX;
shDragImage.ptOffset.y := ImageHotSpotY;
if Failed(FDragSourceHelper.InitializeFromBitmap(shDragImage, Self)) then
begin
FDragSourceHelper := nil;
shDragBitmap.Free;
shDragBitmap := nil;
end;
end else
IsDraggingImage := False;
// Fall back to image list drag image if platform doesn't support
// IDragSourceHelper or if we "just" failed to initialize properly.
if (FDragSourceHelper = nil) then
begin
IsDraggingImage := ImageList_BeginDrag(FImages.Handle, FImageIndex,
FImageHotSpot.X, FImageHotSpot.Y);
end;
end else
IsDraggingImage := False;
if (AllowAsyncTransfer) then
SetAsyncMode(True);
try
InShellDragLoop := True;
try
DropResult := DoDragDrop(Self, Self, AllowedEffects, DropEffect);
finally
// InShellDragLoop is also reset in TCustomDropSource.QueryContinueDrag.
// This is just to make absolutely sure that it is reset (actually no big
// deal if it isn't).
InShellDragLoop := False;
end;
finally
if IsDraggingImage then
begin
if (FDragSourceHelper <> nil) then
begin
FDragSourceHelper := nil;
shDragBitmap.Free;
end else
ImageList_EndDrag;
end;
end;
case DropResult of
DRAGDROP_S_DROP:
(*
** Special handling of "optimized move".
** If PerformedDropEffect has been set by the target to DROPEFFECT_MOVE
** and the drop effect returned from DoDragDrop is different from
** DROPEFFECT_MOVE, then an optimized move was performed.
** Note: This is different from how MSDN states that an optimized move is
** signalled, but matches how Windows 2000 signals an optimized move.
**
** On Windows 2000 an optimized move is signalled by:
** 1) Returning DRAGDROP_S_DROP from DoDragDrop.
** 2) Setting drop effect to DROPEFFECT_NONE.
** 3) Setting the "Performed Dropeffect" format to DROPEFFECT_MOVE.
**
** On previous version of Windows, an optimized move is signalled by:
** 1) Returning DRAGDROP_S_DROP from DoDragDrop.
** 2) Setting drop effect to DROPEFFECT_MOVE.
** 3) Setting the "Performed Dropeffect" format to DROPEFFECT_NONE.
**
** The documentation states that an optimized move is signalled by:
** 1) Returning DRAGDROP_S_DROP from DoDragDrop.
** 2) Setting drop effect to DROPEFFECT_NONE or DROPEFFECT_COPY.
** 3) Setting the "Performed Dropeffect" format to DROPEFFECT_NONE.
*)
if (LogicalPerformedDropEffect = DROPEFFECT_MOVE) or
((DropEffect <> DROPEFFECT_MOVE) and (PerformedDropEffect = DROPEFFECT_MOVE)) then
Result := drDropMove
else
Result := DropEffectToDragResult(DropEffect and AllowedEffects);
DRAGDROP_S_CANCEL:
Result := drCancel;
E_OUTOFMEMORY:
Result := drOutMemory;
else
// This should never happen!
Result := drUnknown;
end;
// Reset PerformedDropEffect if the target didn't set it.
if (PerformedDropEffect = -1) then
PerformedDropEffect := DROPEFFECT_NONE;
// Fire OnAfterDrop event unless we are in the middle of an async data
// transfer.
if (not AsyncTransfer) and (Assigned(FOnAfterDrop)) then
FOnAfterDrop(Self, Result,
(Result = drDropMove) and
((DropEffect <> DROPEFFECT_MOVE) or (PerformedDropEffect <> DROPEFFECT_MOVE)));
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.GetPerformedDropEffect: longInt;
begin
Result := DROPEFFECT_NONE;
end;
function TCustomDropSource.GetLogicalPerformedDropEffect: longInt;
begin
Result := DROPEFFECT_NONE;
end;
procedure TCustomDropSource.SetPerformedDropEffect(const Value: longInt);
begin
// Not implemented in base class
end;
function TCustomDropSource.GetPreferredDropEffect: longInt;
begin
Result := DROPEFFECT_NONE;
end;
procedure TCustomDropSource.SetPreferredDropEffect(const Value: longInt);
begin
// Not implemented in base class
end;
function TCustomDropSource.GetInShellDragLoop: boolean;
begin
Result := False;
end;
function TCustomDropSource.GetTargetCLSID: TCLSID;
begin
Result := GUID_NULL;
end;
procedure TCustomDropSource.SetInShellDragLoop(const Value: boolean);
begin
// Not implemented in base class
end;
procedure TCustomDropSource.DataChanging(Sender: TObject);
begin
// Data is changing - Flush clipboard to freeze the contents
FlushClipboard;
end;
procedure TCustomDropSource.FlushClipboard;
begin
// If we have live data on the clipboard...
if (LiveDataOnClipboard) then
// ...we force the clipboard to make a static copy of the data
// before the data changes.
OleCheck(OleFlushClipboard);
end;
procedure TCustomDropSource.EmptyClipboard;
begin
// If we have live data on the clipboard...
if (LiveDataOnClipboard) then
// ...we empty the clipboard.
OleCheck(OleSetClipboard(nil));
end;
function TCustomDropSource.CutToClipboard: boolean;
begin
PreferredDropEffect := DROPEFFECT_MOVE;
// Copy data to clipboard
Result := CutOrCopyToClipboard;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.CopyToClipboard: boolean;
begin
PreferredDropEffect := DROPEFFECT_COPY;
// Copy data to clipboard
Result := CutOrCopyToClipboard;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.CutOrCopyToClipboard: boolean;
begin
Result := (OleSetClipboard(Self as IDataObject) = S_OK);
end;
procedure TCustomDropSource.DoOnPaste(Action: TDragResult; DeleteOnPaste: boolean);
begin
if (Assigned(FOnPaste)) then
FOnPaste(Self, Action, DeleteOnPaste);
end;
function TCustomDropSource.GetLiveDataOnClipboard: boolean;
begin
Result := (OleIsCurrentClipboard(Self as IDataObject) = S_OK);
end;
// -----------------------------------------------------------------------------
procedure TCustomDropSource.SetImages(const Value: TImageList);
begin
if (FImages = Value) then
exit;
FImages := Value;
if (csLoading in ComponentState) then
exit;
{ DONE -oanme : Shouldn't FShowImage and FImageIndex only be reset if FImages = nil? }
if (FImages = nil) or (FImageIndex >= FImages.Count) then
FImageIndex := 0;
FShowImage := FShowImage and (FImages <> nil) and (FImages.Count > 0);
end;
// -----------------------------------------------------------------------------
procedure TCustomDropSource.SetImageIndex(const Value: integer);
begin
if (csLoading in ComponentState) then
begin
FImageIndex := Value;
exit;
end;
if (Value < 0) or (FImages.Count = 0) or (FImages = nil) then
begin
FImageIndex := 0;
FShowImage := False;
end else
if (Value < FImages.Count) then
FImageIndex := Value;
end;
// -----------------------------------------------------------------------------
procedure TCustomDropSource.SetPoint(Index: integer; Value: integer);
begin
if (Index = 1) then
FImageHotSpot.x := Value
else
FImageHotSpot.y := Value;
end;
// -----------------------------------------------------------------------------
function TCustomDropSource.GetPoint(Index: integer): integer;
begin
if (Index = 1) then
Result := FImageHotSpot.x
else
Result := FImageHotSpot.y;
end;
// -----------------------------------------------------------------------------
procedure TCustomDropSource.SetShowImage(Value: boolean);
begin
FShowImage := Value;
if (csLoading in ComponentState) then
exit;
if (FImages = nil) then
FShowImage := False;
end;
// -----------------------------------------------------------------------------
procedure TCustomDropSource.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FImages) then
Images := nil;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TEnumFormatEtc
//
////////////////////////////////////////////////////////////////////////////////
// Format enumerator used by TCustomDropMultiTarget.
////////////////////////////////////////////////////////////////////////////////
type
TEnumFormatEtc = class(TInterfacedObject, IEnumFormatEtc)
private
FFormats : TClipboardFormats;
FIndex : integer;
protected
constructor CreateClone(AFormats: TClipboardFormats; AIndex: Integer);
public
constructor Create(AFormats: TDataFormats; Direction: TDataDirection);
{ IEnumFormatEtc implentation }
function Next(Celt: LongInt; out Elt; pCeltFetched: pLongInt): HRESULT; stdcall;
function Skip(Celt: LongInt): HRESULT; stdcall;
function Reset: HRESULT; stdcall;
function Clone(out Enum: IEnumFormatEtc): HRESULT; stdcall;
end;
constructor TEnumFormatEtc.Create(AFormats: TDataFormats; Direction: TDataDirection);
var
i, j : integer;
begin
inherited Create;
FFormats := TClipboardFormats.Create(nil, False);
FIndex := 0;
for i := 0 to AFormats.Count-1 do
for j := 0 to AFormats[i].CompatibleFormats.Count-1 do
if (Direction in AFormats[i].CompatibleFormats[j].DataDirections) and
(not FFormats.Contain(TClipboardFormatClass(AFormats[i].CompatibleFormats[j].ClassType))) then
FFormats.Add(AFormats[i].CompatibleFormats[j]);
end;
constructor TEnumFormatEtc.CreateClone(AFormats: TClipboardFormats; AIndex: Integer);
var
i : integer;
begin
inherited Create;
FFormats := TClipboardFormats.Create(nil, False);
FIndex := AIndex;
for i := 0 to AFormats.Count-1 do
FFormats.Add(AFormats[i]);
end;
function TEnumFormatEtc.Next(Celt: LongInt; out Elt;
pCeltFetched: pLongInt): HRESULT;
var
i : integer;
FormatEtc : PFormatEtc;
begin
i := 0;
FormatEtc := PFormatEtc(@Elt);
while (i < Celt) and (FIndex < FFormats.Count) do
begin
FormatEtc^ := FFormats[FIndex].FormatEtc;
Inc(FormatEtc);
Inc(i);
Inc(FIndex);
end;
if (pCeltFetched <> nil) then
pCeltFetched^ := i;
if (i = Celt) then
Result := S_OK
else
Result := S_FALSE;
end;
function TEnumFormatEtc.Skip(Celt: LongInt): HRESULT;
begin
if (FIndex + Celt <= FFormats.Count) then
begin
inc(FIndex, Celt);
Result := S_OK;
end else
begin
FIndex := FFormats.Count;
Result := S_FALSE;
end;
end;
function TEnumFormatEtc.Reset: HRESULT;
begin
FIndex := 0;
Result := S_OK;
end;
function TEnumFormatEtc.Clone(out Enum: IEnumFormatEtc): HRESULT;
begin
Enum := TEnumFormatEtc.CreateClone(FFormats, FIndex);
Result := S_OK;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TCustomDropMultiSource
//
////////////////////////////////////////////////////////////////////////////////
type
TSourceDataFormats = class(TDataFormats)
public
function Add(DataFormat: TCustomDataFormat): integer; override;
end;
function TSourceDataFormats.Add(DataFormat: TCustomDataFormat): integer;
begin
Result := inherited Add(DataFormat);
// Set up change notification so drop source can flush clipboard if data changes.
DataFormat.OnChanging := TCustomDropMultiSource(DataFormat.Owner).DataChanging;
end;
constructor TCustomDropMultiSource.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataFormats := TSourceDataFormats.Create;
FFeedbackDataFormat := TFeedbackDataFormat.Create(Self);
FRawDataFormat := TRawDataFormat.Create(Self);
end;
destructor TCustomDropMultiSource.Destroy;
var
i : integer;
begin
EmptyClipboard;
// Delete all target formats owned by the object
for i := FDataFormats.Count-1 downto 0 do
FDataFormats[i].Free;
FDataFormats.Free;
inherited Destroy;
end;
function TCustomDropMultiSource.DoGetData(const FormatEtcIn: TFormatEtc;
out Medium: TStgMedium): HRESULT;
var
i, j: integer;
DF: TCustomDataFormat;
CF: TClipboardFormat;
begin
// TODO : Add support for delayed rendering with OnRenderData event.
Medium.tymed := 0;
Medium.UnkForRelease := nil;
Medium.hGlobal := 0;
Result := DV_E_FORMATETC;
(*
** Loop through all data formats associated with this drop source to find one
** which can offer the clipboard format requested by the target.
*)
for i := 0 to DataFormats.Count-1 do
begin
DF := DataFormats[i];
// Ignore empty data formats.
if (not DF.HasData) then
continue;
(*
** Loop through all the data format's supported clipboard formats to find
** one which contains data and can provide it in the format requested by the
** target.
*)
for j := 0 to DF.CompatibleFormats.Count-1 do
begin
CF := DF.CompatibleFormats[j];
(*
** 1) Determine if the clipboard format supports the format requested by
** the target.
** 2) Transfer data from the data format object to the clipboard format
** object.
** 3) Determine if the clipboard format object now has data to offer.
** 4) Transfer the data from the clipboard format object to the medium.
*)
if (CF.AcceptFormat(FormatEtcIn)) and
(DataFormats[i].AssignTo(CF)) and
(CF.HasData) and
(CF.SetDataToMedium(FormatEtcIn, Medium)) then
begin
// Once data has been sucessfully transfered to the medium, we clear
// the data in the TClipboardFormat object in order to conserve
// resources.
CF.Clear;
Result := S_OK;
exit;
end;
end;
end;
end;
function TCustomDropMultiSource.DoSetData(const FormatEtc: TFormatEtc;
var Medium: TStgMedium): HRESULT;
var
i, j : integer;
GenericClipboardFormat: TRawClipboardFormat;
begin
Result := E_NOTIMPL;
// Get data for requested source format.
for i := 0 to DataFormats.Count-1 do
for j := 0 to DataFormats[i].CompatibleFormats.Count-1 do
if (DataFormats[i].CompatibleFormats[j].AcceptFormat(FormatEtc)) and
(DataFormats[i].CompatibleFormats[j].GetDataFromMedium(Self, Medium)) and
(DataFormats[i].Assign(DataFormats[i].CompatibleFormats[j])) then
begin
DoOnSetData(DataFormats[i], DataFormats[i].CompatibleFormats[j]);
// Once data has been sucessfully transfered to the medium, we clear
// the data in the TClipboardFormat object in order to conserve
// resources.
DataFormats[i].CompatibleFormats[j].Clear;
Result := S_OK;
exit;
end;
// The requested data format wasn't supported by any of the registered
// clipboard formats, but in order to support the Windows 2000 drag drop helper
// object we have to accept any data which is written to the IDataObject.
// To do this we create a new clipboard format object, initialize it with the
// format information passed to us and copy the data.
GenericClipboardFormat := TRawClipboardFormat.CreateFormatEtc(FormatEtc);
FRawDataFormat.CompatibleFormats.Add(GenericClipboardFormat);
if (GenericClipboardFormat.GetDataFromMedium(Self, Medium)) and
(FRawDataFormat.Assign(GenericClipboardFormat)) then
Result := S_OK;
end;
function TCustomDropMultiSource.GetEnumFormatEtc(dwDirection: Integer): IEnumFormatEtc;
begin
if (dwDirection = DATADIR_GET) then
Result := TEnumFormatEtc.Create(FDataFormats, ddRead)
else if (dwDirection = DATADIR_SET) then
Result := TEnumFormatEtc.Create(FDataFormats, ddWrite)
else
Result := nil;
end;
function TCustomDropMultiSource.HasFormat(const FormatEtc: TFormatEtc): boolean;
var
i ,
j : integer;
begin
Result := False;
for i := 0 to DataFormats.Count-1 do
for j := 0 to DataFormats[i].CompatibleFormats.Count-1 do
if (DataFormats[i].CompatibleFormats[j].AcceptFormat(FormatEtc)) then
begin
Result := True;
exit;
end;
end;
function TCustomDropMultiSource.GetPerformedDropEffect: longInt;
begin
Result := FFeedbackDataFormat.PerformedDropEffect;
end;
function TCustomDropMultiSource.GetLogicalPerformedDropEffect: longInt;
begin
Result := FFeedbackDataFormat.LogicalPerformedDropEffect;
end;
function TCustomDropMultiSource.GetPreferredDropEffect: longInt;
begin
Result := FFeedbackDataFormat.PreferredDropEffect;
end;
procedure TCustomDropMultiSource.SetPerformedDropEffect(const Value: longInt);
begin
FFeedbackDataFormat.PerformedDropEffect := Value;
end;
procedure TCustomDropMultiSource.SetPreferredDropEffect(const Value: longInt);
begin
FFeedbackDataFormat.PreferredDropEffect := Value;
end;
function TCustomDropMultiSource.GetInShellDragLoop: boolean;
begin
Result := FFeedbackDataFormat.InShellDragLoop;
end;
procedure TCustomDropMultiSource.SetInShellDragLoop(const Value: boolean);
begin
FFeedbackDataFormat.InShellDragLoop := Value;
end;
function TCustomDropMultiSource.GetTargetCLSID: TCLSID;
begin
Result := FFeedbackDataFormat.TargetCLSID;
end;
procedure TCustomDropMultiSource.DoOnSetData(DataFormat: TCustomDataFormat;
ClipboardFormat: TClipboardFormat);
var
DropEffect : longInt;
begin
if (ClipboardFormat is TPasteSuccededClipboardFormat) then
begin
DropEffect := TPasteSuccededClipboardFormat(ClipboardFormat).Value;
DoOnPaste(DropEffectToDragResult(DropEffect),
(DropEffect = DROPEFFECT_MOVE) and (PerformedDropEffect = DROPEFFECT_MOVE));
end;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropSourceThread
//
////////////////////////////////////////////////////////////////////////////////
constructor TDropSourceThread.Create(ADropSource: TCustomDropSource;
AFreeOnTerminate: Boolean);
begin
inherited Create(True);
FreeOnTerminate := AFreeOnTerminate;
FDropSource := ADropSource;
FDragResult := drAsync;
end;
procedure TDropSourceThread.Execute;
var
pt: TPoint;
hwndAttach: HWND;
dwAttachThreadID, dwCurrentThreadID : DWORD;
begin
(*
** See Microsoft Knowledgebase Article Q139408 for an explanation of the
** AttachThreadInput stuff.
** http://support.microsoft.com/support/kb/articles/Q139/4/08.asp
*)
// Get handle of window under mouse-cursor.
GetCursorPos(pt);
hwndAttach := WindowFromPoint(pt);
ASSERT(hwndAttach<>0, 'Can''t find window with drag-object');
// Get thread IDs.
dwAttachThreadID := GetWindowThreadProcessId(hwndAttach, nil);
dwCurrentThreadID := GetCurrentThreadId();
// Attach input queues if necessary.
if (dwAttachThreadID <> dwCurrentThreadID) then
AttachThreadInput(dwAttachThreadID, dwCurrentThreadID, True);
try
// Initialize OLE for this thread.
OleInitialize(nil);
try
// Start drag & drop.
FDragResult := FDropSource.Execute;
finally
OleUninitialize;
end;
finally
// Restore input queue settings.
if (dwAttachThreadID <> dwCurrentThreadID) then
AttachThreadInput(dwAttachThreadID, dwCurrentThreadID, False);
// Set Terminated flag so owner knows that drag has finished.
Terminate;
end;
end;
end.
|
{
@html(<b>)
Simple Parser
@html(</b>)
- Copyright (c) Cord Schneider & Danijel Tkalcec
@html(<br><br>)
This unit defines a simple parser which is designed to be used either
stand-alone or hand-in-hand with any of the RTC components. RTC parser uses
a source string as Template and replaces tokens inside TokenOpen and TokenClose.
If you are writing a Web Server, you can use this parser to generate dynamic content
by using HTML templates designed with any Web Page Editor.
}
unit rtcParse;
{$H+}
interface
{$include rtcDefs.inc}
uses
Windows, Classes, SysUtils;
type
{ @exclude
ERtcParse is an exception handler for TRtcParse objects }
ERtcParse = class(Exception);
// @exclude
TString = class(TObject)
public
Value: String;
constructor Create(AValue: String = '');
end;
{ @abstract(Simple Template parser)
Simple parser which is designed to be used either stand-alone or
hand-in-hand with any of the RTC components. RTC parser uses
a source string as Template and replaces tokens inside TokenOpen and TokenClose.
If you are writing a Web Server, you can use this parser to generate dynamic content
by using HTML templates designed with any Web Page Editor. }
TRtcParse = class(TObject)
private
FSource: String;
FSilent: Boolean;
FTokenClose: String;
FTokenOpen: String;
FVariables: TStringList;
// @exclude
function FindPos(const Substr, Str: String; StartPos: Integer = 1): Integer;
// @exclude
function GetCount: Integer;
// @exclude
function GetVariableName(Index: Integer): String;
// @exclude
procedure SetVariableName(Index: Integer; const AValue: String);
// @exclude
function GetVariableValue(Index: Integer): String;
// @exclude
procedure SetVariableValue(Index: Integer; const AValue: String);
// @exclude
function GetValue(Index: String): String;
// @exclude
procedure SetValue(Index: String; const AValue: String);
// @exclude
procedure SetSource(AValue: String);
// @exclude
procedure SetTokenOpen(AValue: String);
// @exclude
procedure SetTokenClose(AValue: String);
protected
{ @exclude
Parses the source string and builds a list of variable names }
procedure GetVariables;
public
{ Constructor: use to create a parser object.
Pass FileName as parameter to load local file as Source template. }
constructor Create(AFilename: String = '');
{ Destructor: when you are done using the parser,
you should destroy it by calling Free. }
destructor Destroy; override;
{ Clears values for all variables parsed from the source string.
Using Clear, you can re-use your Source Template to generate more
outputs with different content, since only values for variables will
be removed, while Source and known variable names remain. }
procedure Clear;
{ Loads the source string from a file }
procedure LoadFromFile(const aFilename: String);
{ Generates the output, replacing all variables with their associated values }
function Output: String;
{ Gets count of variables parsed from the source string }
property Count: Integer read GetCount default 0;
{ Name of the 'index'-th variable parsed from the source string (starting from 0) }
property VariableName[Index: Integer]: String read GetVariableName write SetVariableName;
{ Value of the 'index'-th variable parsed from the source string (starting from 0) }
property VariableValue[Index: Integer]: String read GetVariableValue write SetVariableValue;
{ Value of the variable with the name 'Index' parsed from the source String }
property Value[Index: String]: String read GetValue write SetValue; default;
{ Source string (Template) to use when generating the output }
property Source: String read FSource write SetSource;
{ Prevents an exception from being raised when trying to set the value
of a non-existent variable }
property Silent: Boolean read FSilent write FSilent default False;
{ String to use for opening token. Default is <% }
property TokenOpen: String read FTokenOpen write SetTokenOpen;
{ String to use for closing token. Default is %> }
property TokenClose: String read FTokenClose write SetTokenClose;
end;
implementation
{ TString }
constructor TString.Create(AValue: String = '');
begin
inherited Create;
Value := AValue;
end;
{ TRtcParse }
function TRtcParse.FindPos(const Substr, Str: String; StartPos: Integer = 1): Integer;
var
lenStr: Integer;
lenSubstr: Integer;
x, y: Integer;
begin
lenStr := Length(Str);
lenSubstr := Length(Substr);
case lenSubstr of
0: Result := 0;
1: begin
Result := 0;
for x:= StartPos to lenStr do
if (Substr[1] = Str[x]) then
begin
Result := x;
Break;
end;
end;
2: begin
Result := 0;
for x := StartPos to lenStr-1 do
if ((Substr[1] = Str[x]) and (SubStr[2] = Str[x+1])) then
begin
Result := x;
Break;
end;
end;
else
begin
Result := 0;
for x := StartPos to lenStr-lenSubstr+1 do
if ((Substr[1] = Str[x]) and (Substr[2] = Str[x+1]) and (Substr[3] = Str[x+2])) then
begin
Result := x;
for y := 3 to lenSubstr-1 do
if (Substr[1+y] <> Str[x+y]) then
begin
Result := 0;
Break;
end;
if Result > 0 then
Break;
end;
end;
end;
end;
function TRtcParse.GetCount: Integer;
begin
if Assigned(FVariables) then
Result := FVariables.Count
else
Result := 0;
end;
function TRtcParse.GetVariableName(Index: Integer): String;
begin
// return the selected variable's name
if Assigned(FVariables) and (Index >= 0) and (Index < FVariables.Count) then
Result := FVariables.Strings[Index]
else
Result := '';
end;
procedure TRtcParse.SetVariableName(Index: Integer; const AValue: String);
begin
// set the selected variable's name
if Assigned(FVariables) and (Index >= 0) and (Index < FVariables.Count) then
FVariables.Strings[Index] := AValue;
end;
function TRtcParse.GetVariableValue(Index: Integer): String;
begin
// return the selected variable's value
if Assigned(FVariables) and (Index >= 0) and (Index < FVariables.Count) and
Assigned(FVariables.Objects[Index]) then
Result := TString(FVariables.Objects[Index]).Value
else
Result := '';
end;
procedure TRtcParse.SetVariableValue(Index: Integer; const AValue: String);
begin
// set the selected variable's value
if Assigned(FVariables) and (Index >= 0) and (Index < FVariables.Count) then
if Assigned(Fvariables.Objects[Index]) then
TString(FVariables.Objects[Index]).Value := AValue
else
FVariables.Objects[Index]:=TString.Create(AValue);
end;
function TRtcParse.GetValue(Index: String): String;
var
idx: Integer;
begin
// return the value of variable named 'Index'
if Assigned(FVariables) then
begin
{$IFDEF AnsiUpperCase}
Index := AnsiUpperCase(Trim(Index));
{$ELSE}
Index := UpperCase(Trim(Index));
{$ENDIF}
idx := FVariables.IndexOf(Index);
if (idx >= 0) and Assigned(FVariables.Objects[idx]) then
Result := TString(FVariables.Objects[idx]).Value
else
Result := '';
end
else
Result := '';
end;
procedure TRtcParse.SetValue(Index: String; const AValue: String);
var
idx: Integer;
begin
if Assigned(FVariables) then
begin
{$IFDEF AnsiUpperCase}
Index := AnsiUpperCase(Trim(Index));
{$ELSE}
Index := UpperCase(Trim(Index));
{$ENDIF}
// set the value of variable named 'Index'
idx := FVariables.IndexOf(Index);
if idx >= 0 then
begin
if Assigned(Fvariables.Objects[idx]) then
TString(FVariables.Objects[idx]).Value := AValue
else
FVariables.Objects[idx]:=TString.Create(AValue);
end
else
if not Silent then
raise ERtcParse.Create('Unknown Variable: ' + Index);
end;
end;
procedure TRtcParse.SetSource(AValue: String);
begin
// set the new source string and (re)build the variables list
if FSource <> AValue then
begin
FSource := AValue;
GetVariables;
end;
end;
procedure TRtcParse.SetTokenOpen(AValue: String);
begin
// set the new open token delimiter and (re)build the variables list
if (AValue <> '') and (FTokenOpen <> AValue) then
begin
FTokenOpen := Trim(AValue);
GetVariables;
end;
end;
procedure TRtcParse.SetTokenClose(AValue: String);
begin
// set the new close token delimiter and (re)build the variables list
if (AValue <> '') and (FTokenClose <> AValue) then
begin
FTokenClose := Trim(AValue);
GetVariables;
end;
end;
procedure TRtcParse.GetVariables;
var
lTokenOpen: Integer;
posStart: Integer;
posEnd: Integer;
variable: String;
idx: Integer;
begin
if (FSource <> '') then
begin
// clear/create the existing variable list
if Assigned(FVariables) then
begin
Clear;
FVariables.Clear;
end
else
FVariables := TStringList.Create;
lTokenOpen := Length(FTokenOpen);
// look for the tokens in the source string and extract the variables
posStart := FindPos(FTokenOpen, FSource, 1);
while posStart > 0 do
begin
posEnd := FindPos(FTokenClose, FSource, posStart+lTokenOpen);
if (posEnd <= 0) then Break;
// extract the variable name from the source string
variable := Copy(FSource, posStart+lTokenOpen, posEnd-(posStart+lTokenOpen));
if variable <> '' then
begin
{$IFDEF AnsiUpperCase}
variable := AnsiUpperCase(Trim(variable));
{$ELSE}
variable := UpperCase(Trim(variable));
{$ENDIF}
// we don't want duplicated variable names
idx := FVariables.IndexOf(variable);
if (idx < 0) then
FVariables.AddObject(variable, TString.Create);
end;
posStart := FindPos(FTokenOpen, FSource, posEnd+1);
end;
end;
end;
constructor TRtcParse.Create(AFilename: String = '');
begin
inherited Create;
// set the default values for the parser
FSource := '';
FSilent := False;
FTokenOpen := '<%';
FTokenClose := '%>';
FVariables := nil;
// load the source string from a file
if AFilename <> '' then
try
LoadFromFile(AFilename);
except
end;
end;
destructor TRtcParse.Destroy;
begin
// clear the variable list and clean up any allocated memory
Clear;
FVariables.Free;
FVariables:=nil;
inherited;
end;
procedure TRtcParse.Clear;
var
count: Integer;
begin
// clear all variables parsed from source string
if Assigned(FVariables) then
begin
for count := 0 to FVariables.Count-1 do
if Assigned(FVariables.Objects[count]) then
begin
FVariables.Objects[count].Free;
FVariables.Objects[count] := nil;
end;
end;
end;
function Read_File(const fname:string; Loc,Size:int64):string; overload;
var
fHandle: Integer;
sRead: Int64;
begin
Result := '';
fHandle := FileOpen(fname, fmOpenRead+fmShareDenyNone);
if fHandle < 0 then
raise ERtcParse.Create('Unable to open file: ' + fname)
else
begin
if Loc < 0 then
Loc := 0;
try
if Size < 0 then
Size := FileSeek(fHandle, Int64(0), 2) - Loc;
if FileSeek(fHandle, Loc, 0) <> Loc then
raise ERtcParse.Create('Unable to seek to location: ' + IntToStr(Loc));
SetLength(Result, Size);
sRead := FileRead(fHandle, Result[1], Size);
if sRead < Size then
SetLength(Result, sRead);
finally
FileClose(fHandle);
end;
end;
end;
function Read_File(const fname:string):string; overload;
begin
Result:=Read_File(fname,0,-1);
end;
procedure TRtcParse.LoadFromFile(const aFilename: String);
begin
if FileExists(aFileName) then
begin
FSource:=Read_File(aFileName);
// build the variable list
GetVariables;
end
else
raise ERtcParse.Create('File not found: ' + aFilename);
end;
function TRtcParse.Output: String;
var
lSource: Integer;
lTokenOpen: Integer;
lTokenClose: Integer;
copyStart: Integer;
posStart: Integer;
posEnd: Integer;
variable: String;
idx: Integer;
begin
if FSource <> '' then
begin
lSource := Length(FSource);
lTokenOpen := Length(FTokenOpen);
lTokenClose := Length(FTokenClose);
copyStart := 1;
Result := '';
// look for the tokens and replace matching variables with their values
posStart := FindPos(FTokenOpen, FSource, 1);
while posStart > 0 do
begin
Result := Result + Copy(FSource, copyStart, posStart-copyStart);
posEnd := FindPos(FTokenClose, FSource, posStart+1);
if posEnd <= 0 then Break;
// extract the variable name from the source string
variable := Copy(FSource, posStart+lTokenOpen, posEnd-(posStart+lTokenOpen));
if variable <> '' then
begin
{$IFDEF AnsiUpperCase}
variable := AnsiUpperCase(Trim(variable));
{$ELSE}
variable := UpperCase(Trim(variable));
{$ENDIF}
// only replace the variable if it is present in list
idx := FVariables.IndexOf(variable);
if idx > -1 then Result := Result + VariableValue[idx];
end;
copyStart := posEnd + lTokenClose;
posStart := FindPos(FTokenOpen, FSource, posEnd+1);
end;
// make sure that remaining part of FSource is returned
if copyStart < lSource then
Result := Result + Copy(FSource, copyStart, lSource-copyStart+1);
end;
end;
end.
|
UNIT SingleLinkedIntListUnit;
INTERFACE
TYPE ListNodePtr = ^ListNode;
ListNode = RECORD
val: integer;
next: ListNodePtr;
END;
List = ListNodePtr;
PROCEDURE Prepand(var l: List; n: ListNodePtr);
PROCEDURE Append(var l: List; n: ListNodePtr);
PROCEDURE InitList(var l: List);
FUNCTION NumNodes(l: List): longint;
FUNCTION NewNode(val: integer): ListNodePtr;
PROCEDURE WriteList(l: List);
PROCEDURE DisposeList(var l: List);
FUNCTION FindNode(l: List; x: integer): ListNodePtr;
PROCEDURE InsertSorted(var l: List; n: ListNodePtr);
FUNCTION IsSorted(l: List): boolean;
IMPLEMENTATION
PROCEDURE InitList(var l: List);
BEGIN (* InitList *)
l := nil;
END; (* InitList *)
FUNCTION IsSorted(l: List): boolean;
var prev: ListNodePtr;
BEGIN
IsSorted := true;
if (l <> NIL) AND (l^.next <> NIL) then begin
prev := l^.next;
while prev^.next <> NIL do begin
if l^.val > prev^.val then
IsSorted := false;
l := prev;
prev := l^.next;
end; (* WHILE *)
end; (* IF *)
{ Ideal Lösung }
while (l <> NIL) AND (l^.next <> NIL) AND (l^.val <= l^.next^.val) do begin
l := l^.next;
end; (* WHILE *)
IsSorted := (l = NIL) OR (l^.next = NIL);
END;
PROCEDURE InsertSorted(var l: List; n: ListNodePtr);
var prev: ListNodePtr;
BEGIN
if NOT(IsSorted(l)) OR (n = NIL) then begin
WriteLn('List not sorted');
HALT;
end else begin
if (l = NIL) OR (l^.val >= n^.val) then begin
Prepand(l, n);
end else begin
prev := l;
while (prev^.next <> NIL) AND (prev^.next^.val < n^.val) do begin
prev := prev^.next;
end; (* WHILE *)
n^.next := prev^.next;
prev^.next := n;
end; (* IF *)
end; (* IF *)
END; (* InsertSorted *)
FUNCTION FindNode(l: List; x: integer): ListNodePtr;
BEGIN
while (l <> NIL) AND (l^.val <> x) do
l := l^.next;
FindNode := l;
END;
PROCEDURE DisposeList(var l: List);
var next: ListNodePtr;
BEGIN
while l <> NIL do begin
next := l^.next;
Dispose(l);
l := next;
end; (* while *)
END;
PROCEDURE Append(var l: List; n: ListNodePtr);
var cur: ListNodePtr;
BEGIN (* Append *)
if l = nil then begin
Prepand(l, n);
end else begin
cur := l;
while cur^.next <> nil do
cur := cur^.next;
cur^.next := n;
end;
END; (* Append *)
PROCEDURE WriteList(l: List);
BEGIN (* WriteList *)
while l <> nil do begin
Write(' -> ');
Write(l^.val);
l := l^.next;
end;
Write(' -| ');
END; (* WriteList *)
FUNCTION NumNodes(l: List): longint;
var count: longint;
BEGIN (* NumNode *)
count := 0;
while l <> nil do begin
Inc(count);
l := l^.next;
end;
NumNodes := count;
END; (* NumNode *)
PROCEDURE Prepand(var l: List; n: ListNodePtr);
BEGIN (* Prepand *)
n^.next := l;
l := n;
END; (* Prepand *)
FUNCTION NewNode(val: integer): ListNodePtr;
var node: ListNodePtr;
BEGIN (* NewNode *)
New(node);
node^.val := val;
node^.next := NIL;
NewNode := node;
END; (* NewNode *)
BEGIN
END. |
unit xExerciseAction;
interface
uses xDBActionBase, xExerciseInfo, System.Classes, System.SysUtils, FireDAC.Stan.Param,
xFunction;
type
/// <summary>
/// 练习题数据库操作
/// </summary>
TExerciseAction = class(TDBActionBase)
public
/// <summary>
/// 获取最大编号
/// </summary>
function GetMaxSN : Integer;
/// <summary>
/// 添加
/// </summary>
procedure AddExercise(AExercise : TExerciseInfo);
/// <summary>
/// 删除
/// </summary>
procedure DelExercise(nExerciseID: Integer); overload;
/// <summary>
/// 删除
/// </summary>
/// <param name="bIsDelPath">如果是目录,是否删除目录</param>
procedure DelExercise(AExercise : TExerciseInfo; bIsDelPath: Boolean); overload;
/// <summary>
/// 修改
/// </summary>
procedure EditExercise(AExercise : TExerciseInfo);
/// <summary>
/// 清空
/// </summary>
procedure ClearExercise;
/// <summary>
/// 加载指定目录
/// </summary>
procedure LoadExercise(sPath : string; slList :TStringList);
/// <summary>
/// 加载所有
/// </summary>
procedure LoadExerciseAll(slList :TStringList);
end;
implementation
{ TExerciseAction }
procedure TExerciseAction.AddExercise(AExercise: TExerciseInfo);
const
C_SQL ='insert into Exercise ( ID, Path, PType, EName, ImageIndex,' + #13#10 +
'Code1, Code2, Remark ) values ( %d, :Path, :PType, :EName,' + #13#10 +
'%d, :Code1, :Code2, :Remark )';
begin
if Assigned(AExercise) then
begin
with AExercise, FQuery.Params do
begin
FQuery.Sql.Text := Format( C_SQL, [ Id, Imageindex ] );
ParamByName( 'Path' ).Value := Path ;
ParamByName( 'PType' ).Value := Ptype ;
ParamByName( 'EName' ).Value := Ename ;
ParamByName( 'Code1' ).Value := Code1 ;
ParamByName( 'Code2' ).Value := Code2 ;
ParamByName( 'Remark' ).Value := Remark ;
end;
ExecSQL;
end;
end;
procedure TExerciseAction.ClearExercise;
begin
FQuery.Sql.Text := 'delete from Exercise';
ExecSQL;
end;
procedure TExerciseAction.DelExercise(AExercise: TExerciseInfo; bIsDelPath: Boolean);
const
C_SQL = 'delete from Exercise where Path LIKE ' ;
begin
if Assigned(AExercise) then
begin
// 目录
if AExercise.Ptype = 0 then
begin
FQuery.Sql.Text := C_SQL + AExercise.Path + '''\'+ AExercise.Ename + '%''';
ExecSQL;
if bIsDelPath then
begin
DelExercise(AExercise.Id);
end;
end
else
// 文件
begin
DelExercise(AExercise.Id);
end;
end;
end;
procedure TExerciseAction.DelExercise(nExerciseID: Integer);
const
C_SQL = 'delete from Exercise where ID = %d ';
begin
FQuery.Sql.Text := Format( C_SQL, [ nExerciseID ] );
ExecSQL;
end;
procedure TExerciseAction.EditExercise(AExercise: TExerciseInfo);
const
C_SQL = 'update Exercise set Path = :Path, PType = :PType,' + #13#10 +
'EName = :EName, ImageIndex = %d, Code1 = :Code1,' + #13#10 +
'Code2 = :Code2, Remark = :Remark where ID = %d';
begin
if Assigned(AExercise) then
begin
with AExercise, FQuery.Params do
begin
FQuery.Sql.Text := Format( C_SQL, [Imageindex, Id ] );
ParamByName( 'Path' ).Value := Path ;
ParamByName( 'PType' ).Value := Ptype ;
ParamByName( 'EName' ).Value := Ename ;
ParamByName( 'Code1' ).Value := Code1 ;
ParamByName( 'Code2' ).Value := Code2 ;
ParamByName( 'Remark' ).Value := Remark ;
end;
ExecSQL;
end;
end;
function TExerciseAction.GetMaxSN: Integer;
const
C_SQL = 'select max(ID) as MaxSN from Exercise';
begin
FQuery.Open(C_SQL);
if FQuery.RecordCount = 1 then
Result := FQuery.FieldByName('MaxSN').AsInteger
else
Result := 0;
FQuery.Close;
end;
procedure TExerciseAction.LoadExercise(sPath : string;slList: TStringList);
const
C_SQL = 'select * from Exercise where Path =''%s''';
var
AExerciseInfo : TExerciseInfo;
begin
if Assigned(slList) then
begin
ClearStringList(slList);
FQuery.Open(Format(C_SQL, [ sPath ]));
while not FQuery.Eof do
begin
AExerciseInfo := TExerciseInfo.Create;
with AExerciseInfo, FQuery do
begin
Id := FieldByName( 'ID' ).AsInteger;
Path := FieldByName( 'Path' ).AsString;
Ptype := FieldByName( 'PType' ).AsInteger;
Ename := FieldByName( 'EName' ).AsString;
Imageindex := FieldByName( 'ImageIndex' ).AsInteger;
Code1 := FieldByName( 'Code1' ).AsString;
Code2 := FieldByName( 'Code2' ).AsString;
Remark := FieldByName( 'Remark' ).AsString;
end;
slList.AddObject('', AExerciseInfo);
FQuery.Next;
end;
FQuery.Close;
end;
end;
procedure TExerciseAction.LoadExerciseAll(slList: TStringList);
const
C_SQL = 'select * from Exercise';
var
AExerciseInfo : TExerciseInfo;
begin
if Assigned(slList) then
begin
ClearStringList(slList);
FQuery.Open(C_SQL);
while not FQuery.Eof do
begin
AExerciseInfo := TExerciseInfo.Create;
with AExerciseInfo, FQuery do
begin
Id := FieldByName( 'ID' ).AsInteger;
Path := FieldByName( 'Path' ).AsString;
Ptype := FieldByName( 'PType' ).AsInteger;
Ename := FieldByName( 'EName' ).AsString;
Imageindex := FieldByName( 'ImageIndex' ).AsInteger;
Code1 := FieldByName( 'Code1' ).AsString;
Code2 := FieldByName( 'Code2' ).AsString;
Remark := FieldByName( 'Remark' ).AsString;
end;
slList.AddObject('', AExerciseInfo);
FQuery.Next;
end;
FQuery.Close;
end;
end;
end.
|
{$I RLReport.inc}
unit RLDesign;
interface
uses
Classes, TypInfo, Db, SysUtils,
{$ifdef DELPHI5}
DsgnIntF,
{$else}
DesignEditors, DesignIntf,
{$endif}
{$ifdef VCL}
Forms,
{$endif}
{$ifdef CLX}
QForms,
{$endif}
RLReport, RLConsts, RLUtils, RLTypes,
RLAbout;
type
{$ifdef DELPHI5}
IDesignerClass = IFormDesigner;
{$else}
IDesignerClass = IDesigner;
{$endif}
{ TRLReportDesigner }
TRLReportDesigner = class(TComponentEditor)
protected
FReport: TRLReport;
procedure ShowAboutBox; virtual;
public
constructor Create(AComponent: TComponent; ADesigner: IDesignerClass); override;
procedure Edit; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
{ TRLListEditor }
TRLListEditor = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure GetValueList(List: TStrings); virtual; abstract;
end;
TRLDataEditor = class(TRLListEditor)
public
procedure GetValueList(List: TStrings); override;
function GetDataSource: TDataSource; virtual; abstract;
end;
TRLDataFieldEditor = class(TRLDataEditor)
public
function GetDataSource: TDataSource; override;
end;
TRLDataFieldsEditor = class(TRLDataEditor)
public
function GetDataSource: TDataSource; override;
end;
TRLPaperSizeEditor = class(TRLListEditor)
public
procedure GetValueList(List: TStrings); override;
end;
implementation
{ TRLReportDesigner }
constructor TRLReportDesigner.Create(AComponent: TComponent; ADesigner: IDesignerClass);
begin
inherited;
FReport := AComponent as TRLReport;
end;
function TRLReportDesigner.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := LocaleStrings.LS_AboutTheStr + ' ' + CS_ProductTitleStr + '...';
1: Result := '-';
2: Result := LocaleStrings.LS_PreviewStr;
end;
end;
function TRLReportDesigner.GetVerbCount: Integer;
begin
Result := 3;
end;
procedure TRLReportDesigner.ShowAboutBox;
var
Form: TFormRLAbout;
begin
Form := TFormRLAbout.Create(nil);
try
Form.ShowModal;
finally
Form.Free;
end;
end;
procedure TRLReportDesigner.Edit;
begin
FReport.Preview;
(FReport.Owner as TForm).Invalidate;
end;
procedure TRLReportDesigner.ExecuteVerb(Index: Integer);
begin
case Index of
0: ShowAboutBox;
1: ;
2: Edit;
end;
end;
function GetPropertyValue(Instance: TPersistent; const PropName: string): TPersistent;
var
PropInfo: PPropInfo;
begin
Result := nil;
PropInfo := TypInfo.GetPropInfo(Instance.ClassInfo, PropName);
if (PropInfo <> nil) and (PropInfo^.PropType^.Kind = tkClass) then
Result := TObject(GetOrdProp(Instance, PropInfo)) as TPersistent;
end;
{ TRLListEditor }
function TRLListEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList, paMultiSelect];
end;
procedure TRLListEditor.GetValues(Proc: TGetStrProc);
var
ValuesGot: TStringList;
I: Integer;
begin
ValuesGot := TStringList.Create;
try
GetValueList(ValuesGot);
for I := 0 to ValuesGot.Count - 1 do
Proc(ValuesGot[I]);
finally
ValuesGot.Free;
end;
end;
{ TRLDataEditor }
procedure TRLDataEditor.GetValueList(List: TStrings);
var
DataSource: TDataSource;
begin
DataSource := GetDataSource;
if (DataSource <> nil) and (DataSource.DataSet <> nil) then
DataSource.DataSet.GetFieldNames(List);
end;
{ TRLDataFieldEditor }
function TRLDataFieldEditor.GetDataSource: TDataSource;
begin
Result := GetPropertyValue(GetComponent(0), 'DataSource') as TDataSource;
end;
{ TRLDataFieldsEditor }
function TRLDataFieldsEditor.GetDataSource: TDataSource;
var
Skipper: TRLCustomSkipper;
begin
Skipper := TRLGroup(GetComponent(0)).FindParentSkipper;
if Skipper <> nil then
Result := Skipper.DataSource
else
Result := nil;
end;
{ TRLPaperSizeEditor }
procedure TRLPaperSizeEditor.GetValueList(List: TStrings);
var
PaperSize: TRLPaperSize;
PaperName: string;
begin
for PaperSize := Low(TRLPaperSize) to High(TRLPaperSize) do
begin
PaperName := PaperInfo[PaperSize].Description;
if PaperInfo[PaperSize].Emulated then
PaperName := PaperName + '*';
List.Add(PaperName);
end;
end;
end.
|
unit BrickCamp.Resources.TEmployee;
interface
uses
System.Classes,
System.SysUtils,
Spring.Container.Common,
Spring.Container,
MARS.Core.Registry,
MARS.Core.Attributes,
MARS.Core.MediaType,
MARS.Core.JSON,
MARS.Core.MessageBodyWriters,
MARS.Core.MessageBodyReaders,
BrickCamp.Repositories.IEmployee,
BrickCamp.Resources.IEmployee,
BrickCamp.Model.IEmployee,
BrickCamp.Model.TEmployee;
type
[Path('/employee'), Produces(TMediaType.APPLICATION_JSON_UTF8)]
TEmployeeResource = class(TInterfacedObject, IEmployeeResurce)
public
[GET, Path('/getone/{Id}')]
function GetOne(const [PathParam] Id: Integer): TEmployee;
[GET, Path('/getlist/')]
function GetList: TJSONArray;
[POST]
procedure Insert(const [BodyParam] Employee: TEmployee);
[PUT]
procedure Update(const [BodyParam] Employee: TEmployee);
[DELETE, Path('/{Id}')]
procedure Delete(const [PathParam] Id: Integer);
end;
implementation
{ THelloWorldResource }
function TEmployeeResource.GetOne(const Id: Integer): TEmployee;
begin
Result := GlobalContainer.Resolve<IEmployeeRepository>.GetOne(Id);
end;
procedure TEmployeeResource.Delete(const Id: Integer);
begin
GlobalContainer.Resolve<IEmployeeRepository>.Delete(Id);
end;
procedure TEmployeeResource.Insert(const Employee: TEmployee);
begin
GlobalContainer.Resolve<IEmployeeRepository>.Insert(Employee);
end;
procedure TEmployeeResource.Update(const Employee: TEmployee);
begin
GlobalContainer.Resolve<IEmployeeRepository>.Update(Employee);
end;
function TEmployeeResource.GetList: TJSONArray;
begin
Result := GlobalContainer.Resolve<IEmployeeRepository>.GetList;
end;
initialization
TMARSResourceRegistry.Instance.RegisterResource<TEmployeeResource>;
end.
|
unit Tests_OriDialogs;
{$mode objfpc}{$H+}
interface
uses
FpcUnit, TestRegistry;
type
TTest_OriDialogs = class(TTestCase)
published
procedure ErrorDlg;
end;
implementation
uses
OriDialogs;
procedure TTest_OriDialogs.ErrorDlg;
begin
OriDialogs.ErrorDlg('Test error message');
end;
initialization
RegisterTest(TTest_OriDialogs);
end.
|
unit BCscore.MemberSelection;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, Generics.Collections, Billiards.Member;
type
TMemberSelectionForm = class(TForm)
lblDescription: TLabel;
lvMembers: TListView;
procedure FormShow(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
fMember1: TBilliardMember;
fMember2: TBilliardMember;
fMemberIDs: TList<Integer>;
procedure BuildListOfMembers;
public
function Execute(AMember1, AMember2: TBilliardMember): Integer;
property Member1: TBilliardMember read fMember1 write fMember1;
property Member2: TBilliardMember read fMember2 write fMember2;
end;
var
MemberSelectionForm: TMemberSelectionForm;
implementation
uses Billiards.DataModule, Billiards.GameDay, BCscore.Consts;
{$R *.dfm}
procedure TMemberSelectionForm.BuildListOfMembers;
var
SL: TStringList;
Text: string;
Item: TListItem;
begin
fMemberIDs.Clear;
lvMembers.Clear;
SL := TStringList.Create;
try
SL.Add(' select MEMBERS.ID,');
SL.Add(' MEMBERS.NICKNAME,');
SL.Add(' MEMBERS.LASTNAME,');
SL.Add(' MEMBERS.FIRSTNAME');
SL.Add(' from HANDICAPS, MEMBERS');
SL.Add(' where GAMETYPE_ID = :gametype');
SL.Add(' and PERIOD_ID = :period');
SL.Add(' and HANDICAPS.MEMBER_ID = MEMBERS.ID');
BilliardDataModule.sqlQuery.SQL.Assign(SL);
finally
SL.Free;
end;
BilliardDataModule.sqlQuery.ParamByName('gametype').AsInteger := BilliardGameDay.GameType.ID;
BilliardDataModule.sqlQuery.ParamByName('period').AsInteger := BilliardGameDay.Period.ID;
BilliardDataModule.sqlQuery.Open;
BilliardDataModule.sqlQuery.First;
while not BilliardDataModule.sqlQuery.EOF do
begin
Text := BilliardDataModule.sqlQuery.FieldByName('NICKNAME').AsString;
if Text = '' then
begin
Text := BilliardDataModule.sqlQuery.FieldByName('LASTNAME').AsString;
Text := Text + ', ';
Text := Text + BilliardDataModule.sqlQuery.FieldByName('FIRSTNAME').AsString;
end;
Item := lvMembers.Items.Add;
Item.Caption := Text;
fMemberIDs.Add(BilliardDataModule.sqlQuery.FieldByName('ID').AsInteger);
BilliardDataModule.sqlQuery.Next;
end;
BilliardDataModule.sqlQuery.Close;
if lvMembers.Items.Count > 0 then
lvMembers.ItemIndex := 0
else
lvMembers.ItemIndex := -1;
lvMembers.SetFocus;
end;
function TMemberSelectionForm.Execute(AMember1, AMember2: TBilliardMember): Integer;
begin
fMember1 := AMember1;
fMember2 := fMember2;
BuildListOfMembers;
Result := ShowModal;
end;
procedure TMemberSelectionForm.FormCreate(Sender: TObject);
begin
fMemberIDs := TList<Integer>.Create;
end;
procedure TMemberSelectionForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(fMemberIDs);
end;
procedure TMemberSelectionForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
104: Key := VK_UP;
98: Key := VK_DOWN;
else
inherited;
end;
end;
procedure TMemberSelectionForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
ckEscape:
begin
if Member1.ID <> 0 then
begin
lblDescription.Caption := 'Selecteer de eerste speler en druk op ENTER om te bevestigen of op 0 op te annuleren.';
Member1.Clear;
BuildListOfMembers;
end
else
begin
ModalResult := mrCancel;
end;
end;
ckSelect:
begin
if Member1.ID = 0 then
begin
lblDescription.Caption := 'Selecteer de tweede speler en druk op ENTER om te bevestigen of op 0 op te annuleren.';
Member1.Retrieve(fMemberIDs[lvMembers.ItemIndex]);
fMemberIDs.Delete(lvMembers.ItemIndex);
lvMembers.Items.Delete(lvMembers.ItemIndex);
lvMembers.ItemIndex := 0;
lvMembers.SetFocus;
end
else
begin
Member2.Retrieve(fMemberIDs[lvMembers.ItemIndex]);
ModalResult := mrOk;
end;
end;
else
inherited;
end;
end;
procedure TMemberSelectionForm.FormShow(Sender: TObject);
begin
ClientHeight := 1024;
ClientWidth := 1280;
Color := clBackPanel;
lvMembers.Color := clBackPanel;
BuildListOfMembers;
end;
end.
|
unit zkReportXmlClassesRevenue;
interface
uses
Classes, NativeXml, zkCommandsRC, zkCommandsRCRevenue, zkReportXmlClasses,
zkEntitiesRevenue, dlyConsts;
type
/// <summary>
/// 定义有请求子报文的顶层基类,实现 GetHasSubPackage 赋值
/// </summary>
TSendReportXml_HasSubPackage = class(TSendReportXmlComm)
protected
function GetHasSubPackage: Boolean; override;
end;
/// <summary>
/// 项目信息查询
/// </summary>
TSendReportXml_Project_Get = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
function XmlNode2Component(Node: TXmlNode): TcmdResRmtComm; override;
end;
/// <summary>
/// 项目信息新增、修改、作废
/// </summary>
TSendReportXml_Project_Set = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
end;
/// <summary>
/// 项目下拉,只需要根据开票点过滤
/// </summary>
TSendReportXml_Project_DropDown = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
function XmlNode2Component(Node: TXmlNode): TcmdResRmtComm; override;
end;
/// <summary>
/// 房源信息查询
/// </summary>
TSendReportXml_House_Get = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
function XmlNode2Component(Node: TXmlNode): TcmdResRmtComm; override;
end;
/// <summary>
/// 房源信息新增、修改、作废
/// </summary>
TSendReportXml_House_Set = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
end;
/// <summary>
/// 不动产开票选择房源
/// </summary>
TSendReportXml_House_JECX = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
function XmlNode2Component(Node: TXmlNode): TcmdResRmtComm; override;
end;
/// <summary>
/// 增加不动产合同时选择房源
/// </summary>
TSendReportXml_House_NewHtCx = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
function XmlNode2Component(Node: TXmlNode): TcmdResRmtComm; override;
end;
/// <summary>
/// 不动产合同信息查询
/// </summary>
TSendReportXml_BdcHt_Get = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
function XmlNode2Component(Node: TXmlNode): TcmdResRmtComm; override;
end;
/// <summary>
/// 不动产合同信息新增、修改、作废
/// </summary>
TSendReportXml_BdcHt_Set = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
end;
/// <summary>
/// 建安合同信息查询
/// </summary>
TSendReportXml_JaHt_Get = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
function XmlNode2Component(Node: TXmlNode): TcmdResRmtComm; override;
end;
/// <summary>
/// 建安合同信息新增、修改、作废
/// </summary>
TSendReportXml_JaHt_Set = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
end;
/// <summary>
/// 建安开票选择合同
/// </summary>
TSendReportXml_JaHt_KpCx = class(TSendReportXml_HasSubPackage)
protected
procedure Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm); override;
function XmlNode2Component(Node: TXmlNode): TcmdResRmtComm; override;
end;
implementation
uses zkXmlCreateAndAnalyze, zkRXGroup
{$IFDEF DEBUG}, dlyCodeSiteLogging{$ENDIF};
{ TSendReportXml_HasSubPackage }
function TSendReportXml_HasSubPackage.GetHasSubPackage: Boolean;
begin
Result := True;
end;
{ TSendReportXml_Project_Get }
procedure TSendReportXml_Project_Get.Component2XmlNode(Node: TXmlNode;
aObj: TcmdReqRmtComm);
begin
with Node, TcmdReqRC_Project_Get(aObj), Project do
begin
Node.Name := 'MV_FCYTH_XMDJXX';
NodeNew('XM_MC').ValueUnicode := XM_MC;
end;
end;
function TSendReportXml_Project_Get.XmlNode2Component(
Node: TXmlNode): TcmdResRmtComm;
begin
Result := TcmdResRC_Project_Get.Create;
AnalyzeReportXml_Project(Node, TcmdResRC_Project_Get(Result).Projects);
end;
{ TSendReportXml_JaHt_KpCx_Get }
procedure TSendReportXml_JaHt_KpCx.Component2XmlNode(Node: TXmlNode;
aObj: TcmdReqRmtComm);
begin
with Node, TcmdReqRC_Jaht_Kpcx(aObj) do
begin
Node.Name := 'T_FCYTH_JAHTXX';
NodeNew('XMDJ_DM').ValueUnicode := JaHt.XMDJ_DM;
NodeNew('HT_BH').ValueUnicode := JaHt.HT_BH;
NodeNew('KPD_ID').ValueUnicode := JaHt.KPD_ID;
NodeNew('NSRNBM').ValueUnicode := JaHt.NSRNBM;
NodeNew('NSRBM').ValueUnicode := JaHt.NSRBM;
NodeNew('PAGENOW').ValueAsInt64 := PageNo;
NodeNew('PAGESIZE').ValueAsInt64 := PageSize;
end;
end;
function TSendReportXml_JaHt_KpCx.XmlNode2Component(
Node: TXmlNode): TcmdResRmtComm;
begin
Result := TcmdResRC_Jaht_Kpcx.Create;
TcmdResRC_Jaht_Kpcx(Result).RowCount := Node.ReadAttributeInt64('ROWCOUNT');
AnalyzeReportXml_JaHt_KpCx(Node, TcmdResRC_Jaht_Kpcx(Result).JaHts);
end;
{ TSendReportXml_Project_Set }
procedure TSendReportXml_Project_Set.Component2XmlNode(Node: TXmlNode;
aObj: TcmdReqRmtComm);
begin
with Node, TcmdReqRC_Project_Set(aObj), Project do
begin
Node.Name := 'MV_FCYTH_XMDJXX';
NodeNew('XMDJ_DM').ValueUnicode := XMDJ_DM;
case OperType of
otInsert: ;
otUpdate: ;
end;
end;
end;
{ TSendReportXml_Project_DropDown }
procedure TSendReportXml_Project_DropDown.Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm);
begin
with Node, TcmdReqRC_Project_DropDown(aObj) do
begin
Node.Name := 'MV_FCYTH_XMDJXX';
NodeNew('XMYT_DM').ValueUnicode := Project.XMYT_DM;
NodeNew('NSRNBM').ValueUnicode := Project.NSRNBM;
NodeNew('KPD_ID').ValueUnicode := KPD_ID;
end;
end;
function TSendReportXml_Project_DropDown.XmlNode2Component(Node: TXmlNode): TcmdResRmtComm;
var
I: Integer;
begin
Result := TcmdResRC_Project_DropDown.Create;
if not Assigned(Node.NodeByName('LIST')) then Exit;
with Node.NodeByName('LIST') do
for I := 0 to NodeCount - 1 do
with TzkpProject(TcmdResRC_Project_DropDown(Result).Projects.AddNew), Nodes[I] do
begin
XMDJ_DM := ReadString('XMDJ_DM');
XM_MC := ReadString('XM_MC');
end;
end;
{ TSendReportXml_House_Get }
procedure TSendReportXml_House_Get.Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm);
begin
end;
function TSendReportXml_House_Get.XmlNode2Component(Node: TXmlNode): TcmdResRmtComm;
begin
Result := TcmdResRC_House_Get.Create;
end;
{ TSendReportXml_House_Set }
procedure TSendReportXml_House_Set.Component2XmlNode(Node: TXmlNode;
aObj: TcmdReqRmtComm);
begin
inherited;
end;
{ TSendReportXml_House_JECX }
procedure TSendReportXml_House_JECX.Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm);
begin
with Node, TcmdReqRC_House_JECX(aObj) do
begin
Node.Name := 'T_FCYTH_FYXX';
NodeNew('XMDJ_DM').ValueUnicode := House.XMDJ_DM;
NodeNew('FCBH').ValueUnicode := House.FCBH;
NodeNew('LZH').ValueUnicode := House.LZH;
NodeNew('DYH').ValueUnicode := House.DYH;
NodeNew('LC').ValueUnicode := House.LC;
NodeNew('FH').ValueUnicode := House.FH;
NodeNew('NSRSBH').ValueUnicode := NSRSBM;
NodeNew('PAGENOW').ValueAsInt64 := PageNo;
NodeNew('PAGESIZE').ValueAsInt64 := PageSize;
end;
end;
function TSendReportXml_House_JECX.XmlNode2Component(Node: TXmlNode): TcmdResRmtComm;
var
I: Integer;
begin
Result := TcmdResRC_House_JECX.Create;
TcmdResRC_House_JECX(Result).RowCount := Node.ReadAttributeInteger('ROWCOUNT');
if not Assigned(Node.NodeByName('LIST')) then Exit;
with Node.NodeByName('LIST') do
for I := 0 to NodeCount - 1 do
begin
with TzkpHouse(TcmdResRC_House_JECX(Result).Houses.AddNew), Nodes[I] do
begin
XMDJ_DM := ReadString('XMDJ_DM');
// 这个字段不知道为什么不能赋值,真奇怪
Unique_ID := ReadString('UNIQUE_ID');
FCBH := ReadString('FCBH');
FCDZ := ReadString('FCDZ');
LZH := ReadString('LZH');
DYH := ReadString('DYH');
LC := ReadString('LC');
FH := ReadString('FH');
FX := ReadString('FX');
MJ := ReadFloat('MJ');
XSZT := ReadString('XSZT');
FCJBH := ReadString('FCJBH');
MJ_TN := ReadFloat('MJ_TN');
SJ_MJ := ReadFloat('SJ_MJ');
SJ_TNMJ := ReadFloat('SJ_TNMJ');
ZDSJ := ReadFloat('ZDSJ');
HTZJE := ReadFloat('ZJE');
HTDJ := ReadFloat('DJ');
YKFPJE := ReadFloat('YKFPJE');
KJ_ZJE := ReadFloat('KJ_ZJE');
ZF_BJ := ReadString('ZF_BJ');
CSR_MC := ReadString('MC');
CSR_ZJH := ReadString('CSR_ZJH');
WC_BJ := ReadString('WC_BJ');
JJFS_DM := ReadString('JJFS_DM');
end;
end;
end;
{ TSendReportXml_House_NewHtCx }
procedure TSendReportXml_House_NewHtCx.Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm);
begin
inherited;
end;
function TSendReportXml_House_NewHtCx.XmlNode2Component(Node: TXmlNode): TcmdResRmtComm;
var
I: Integer;
begin
Result := TcmdResRC_House_NewHtCx.Create;
TcmdResRC_House_JECX(Result).RowCount := Node.ReadAttributeInteger('ROWCOUNT');
if not Assigned(Node.NodeByName('LIST')) then Exit;
with Node.NodeByName('LIST') do
for I := 0 to NodeCount - 1 do
begin
with TzkpHouse(TcmdResRC_House_JECX(Result).Houses.AddNew) do
begin
XMDJ_DM := ReadString('XMDJ_DM');
Unique_ID := ReadString('UNIQUE_ID');
FCBH := ReadString('FCBH');
FCDZ := ReadString('FCDZ');
LZH := ReadString('LZH');
DYH := ReadString('DYH');
LC := ReadString('LC');
FH := ReadString('FH');
FX := ReadString('FX');
MJ := ReadFloat('MJ');
XSZT := ReadString('XSZT');
FCJBH := ReadString('FCJBH');
MJ_TN := ReadFloat('MJ_TN');
SJ_MJ := ReadFloat('SJ_MJ');
SJ_TNMJ := ReadFloat('SJ_TNMJ');
ZDSJ := ReadFloat('ZDSJ');
ZF_BJ := ReadString('ZF_BJ');
end;
end;
end;
{ TSendReportXml_BdcHt_Get }
procedure TSendReportXml_BdcHt_Get.Component2XmlNode(Node: TXmlNode; aObj: TcmdReqRmtComm);
begin
inherited;
end;
function TSendReportXml_BdcHt_Get.XmlNode2Component(Node: TXmlNode): TcmdResRmtComm;
begin
Result := TcmdResRC_BdcHt_Get.Create;
end;
{ TSendReportXml_BdcHt_Set }
procedure TSendReportXml_BdcHt_Set.Component2XmlNode(Node: TXmlNode;
aObj: TcmdReqRmtComm);
begin
inherited;
end;
{ TSendReportXml_JaHt_Get }
procedure TSendReportXml_JaHt_Get.Component2XmlNode(Node: TXmlNode;
aObj: TcmdReqRmtComm);
begin
inherited;
end;
function TSendReportXml_JaHt_Get.XmlNode2Component(Node: TXmlNode): TcmdResRmtComm;
begin
Result := TcmdResRC_JaHt_Get.Create;
end;
{ TSendReportXml_JaHt_Set }
procedure TSendReportXml_JaHt_Set.Component2XmlNode(Node: TXmlNode;
aObj: TcmdReqRmtComm);
begin
inherited;
end;
initialization
// 项目相关的远程报文处理
RegisterRXRef(TcmdReqRC_Project_Get, TSendReportXml_Project_Get);
RegisterRXRef(TcmdReqRC_Project_Set, TSendReportXml_Project_Set);
RegisterRXRef(TcmdReqRC_Project_DropDown, TSendReportXml_Project_DropDown);
// 房源相关的远程报文处理
RegisterRXRef(TcmdReqRC_House_Get, TSendReportXml_House_Get);
RegisterRXRef(TcmdReqRC_House_Set, TSendReportXml_House_Set);
RegisterRXRef(TcmdReqRC_House_JECX, TSendReportXml_House_JECX);
RegisterRXRef(TcmdReqRC_House_NewHtCx, TSendReportXml_House_NewHtCx);
// 不动产合同相关的远程报文处理
RegisterRXRef(TcmdReqRC_BdcHt_Get, TSendReportXml_BdcHt_Get);
RegisterRXRef(TcmdReqRC_BdcHt_Set, TSendReportXml_BdcHt_Set);
// 建安合同相关的远程报文处理
RegisterRXRef(TcmdReqRC_JaHt_Get, TSendReportXml_JaHt_Get);
RegisterRXRef(TcmdReqRC_JaHt_Set, TSendReportXml_JaHt_Set);
RegisterRXRef(TcmdReqRC_Jaht_Kpcx, TSendReportXml_JaHt_KpCx);
end.
|
program DjsTemas;
uses crt;
const
MAXDjs=25;
MAXTemasPorDj=35;
MAXTEM=10; {Ahora tiene 10 para cuando probamos no tener que poner los 200 temas, despues hay que cambiarlo}
MAXMIN=10;
MAXSEGS=59;
type
tiDjs=1..MAXDjs;
tiTemasPorDj=1..MAXTemasPorDj;
tiTemas=1..MAXTEM;
tiNomMinSeg=(nombre,minutos,segundos);
tmListaTemas=array [tiTemas,tiNomMinSeg] of string[20];
tvNomDjs=array [tiDjs] of string[40];
tmTemasPorDj=array [tiDjs,tiTemasPorDj] of string[20];
tvDuracion=array[tiTemas] of integer;
tvTemasRepetidos=array [tiTemas] of byte;
tvTotalSegPorDj=array[tiDjs] of integer;
tvPosicion=array[tiDjs] of byte;
Procedure ValidarMinutos(var min:string);
var
minnum:byte;
codigo:byte;
begin
repeat
write('Minutos:');
readln(min);
VAL(min,minnum,codigo);
if (minnum>MAXMIN) then
writeln('Supera los ',MAXMIN,' minutos, vuelva a ingrasar nuevamente');
if (codigo<>0) then
writeln('Ingreso un valor invalido, vuelva a ingresar nuevamente')
until ((codigo=0) and (minnum<=MAXMIN));
end;
Procedure ValidarSegs(var seg:string;min:string);
var
minnum:byte;
codigo1:byte;
segnum:byte;
codigo2:byte;
correcto:byte;
begin
repeat
correcto:=1;
write('Segundos:');
readln(seg);
VAL(min,minnum,codigo1);
VAL(seg,segnum,codigo2);
if (segnum>MAXSEGS) then
writeln('Los segundos superaron los ',MAXSEGS,' segundos, vuelva a ingresar los segundos resantes del tema');
if ((minnum=MAXMIN) and (segnum<>0)) then
begin
writeln('El tema supera los ',MAXMIN,' minutos, vuelva a ingresar los segundos restantes del tema');
correcto:=0;
end;
if (codigo2<>0) then
writeln('Ingreso un valor invalido, vuelva a ingresar nuevamente')
until ((correcto<>0) and (segnum<=MAXSEGS) and (codigo2=0));
end;
Procedure IngreseListaTemas(var listatemas:tmListaTemas);
var
i: tiTemas;
nom: string;
min: string;
seg: string;
begin
writeln('Ingrese la lista de 200 temas con su duracion');
for i:=1 to MAXTEM do
begin
writeln('Ingrese el nombre del tema');
readln(nom);
listatemas[i,nombre]:= nom;
writeln('Duracion del tema, con un maximo de 10 minutos');
ValidarMinutos(min);
listatemas[i,minutos]:= min;
ValidarSegs(seg,min);
listatemas[i,segundos]:=seg;
end;
end;
Procedure IngreseListaDjs(var nomDjs:tvNomDjs; var MLDjs:tiDjs);
var
i:tiDjs;
nombre:string;
begin
writeln('Ingrese la cantidad de Djs que desea agregar en esta lista, con un maximo de 25');
readln(MLDjs);
for i:=1 to MLDjs do
begin
writeln('Ingrese nombre del Dj');
readln(nombre);
nomDjs[i]:=nombre;
end;
end;
Procedure validartema(var tema:string; listatemas:tmListaTemas);
var
i:byte;
boleano:boolean;
begin
boleano:=false;
i:=1;
repeat
if (tema=listatemas[i,nombre]) then
boleano:=true
else
if (i=MAXTEM) then
begin
writeln('El tema ingresado no pertenece a la lista de temas.');
writeln('Reingrese el tema: ');
readln(tema);
i:=1;
end
else
begin
if (tema='0') then
boleano:=true
else i:=i+1;
end;
until(boleano=true);
end;
Procedure comparacionTemas(tema:string; temasPorDj:tmTemasPorDj;var aux:boolean; var boleano:boolean; i,j:byte);
var
k:byte;
begin
aux:=true;
for k:=1 to (j-1) do
begin
if tema=temasPorDj[i,k] then
begin
aux:=false;
boleano:=true;
temasPorDj[i,k+1]:=temasPorDj[i,k];
end
else
begin
boleano:=true;
aux:=true;
end;
end;
end;
Procedure IngreseListaTemasPorDj(listatemas:tmListaTemas; nomDjs:tvNomDjs; var temasPorDj:tmTemasPorDj; MLDjs:tiDjs);
var
i,j:byte;
tema:string;
boleano,aux:boolean;
Begin
writeln('Ingrese la lista de temas para cada Dj. ');
writeln('Ingrese 0 para concluir la lista de cada Dj.');
for i:=1 to MLDjs do
Begin
Write(nomDjs[i],': ');
j:=1;
repeat
write('Tema nro ',j,' ');
readln(tema);
validartema(tema,listatemas);
boleano:=false;
repeat
if j=1 then
begin
boleano:=true;
aux:=true;
end
else comparacionTemas(tema,temasPorDj,aux,boleano,i,j);
if aux=true then
temasPorDj[i,j]:=tema;
until(boleano=true);
if aux=true then
begin
j:=j+1;
if (j=MAXTemasPorDj+1) then
tema:='0';
end
else writeln('Cancion repetida,vuelva a ingresar');
until(tema='0');
end;
end;
Procedure Menu1(var listatemas:tmListaTemas; var nomDjs:tvNomDjs; var temasPorDj:tmTemasPorDj;var opcionmen1:byte;var MLDjs:tiDjs);
var
contadorOpcion1:byte;
contadorOpcion2:byte;
begin
writeln('Ingrese la opcion deseada');
contadorOpcion1:=0;
contadorOpcion2:=0;
repeat
writeln('1- Ingresar lista de temas');
writeln('2- Ingresar lista de Djs');
writeln('3- Ingresar temas que va a tocar cada Dj');
readln(opcionmen1);
case opcionmen1 of
1:
begin
IngreseListaTemas(listatemas);
contadorOpcion1:=contadorOpcion1 + 1;
end;
2:
begin
IngreseListaDjs(nomDjs, MLDjs);
contadorOpcion2:=contadorOpcion2 + 1;
end;
3:
if ((contadorOpcion1>=1) AND (contadorOpcion2>=1)) then
IngreseListaTemasPorDj(listatemas, nomDjs, temasPorDj, MLDjs)
else
begin
writeln('Tiene que ingresar primero la lista de canciones y la de Djs antes de poder completar esta.');
opcionmen1:=0;
end;
else writeln('Ingreso una opcion invalida, vuelva a elegir una opcion');
end;
until (opcionmen1=3);
end;
Procedure OrdenDeIngreso (nomDjs:tvNomDjs;MLDjs:tiDjs);
var
i:tiDjs;
begin
for i:=1 to MLDjs do
writeln(i,'- ', nomDjs[i]);
end;
Procedure OrdenAlfabetico(nomDjs:tvNomDjs; MLDjs:tiDjs);
var
i:byte;
j:byte;
temporal:string[40];
begin
for i:=1 to MLDjs do
begin
for j:=i+1 to MLDjs do
begin
if (nomDjs[i]>nomDjs[j]) then
begin
temporal:=nomDjs[i];
nomDjs[i]:=nomDjs[j];
nomDjs[j]:=temporal;
end;
end;
end;
for i:=1 to MLDjs do
writeln(nomDjs[i]);
end;
Procedure Duracionminseg(var duracion:tvDuracion; listatemas:tmListaTemas);
var
i:byte;
minnum:byte;
segnum:byte;
total:word;
codigo1:byte;
codigo2:byte;
begin
for i:=1 to MAXTEM do
begin
VAL(listatemas[i,minutos],minnum,codigo1);
VAL(listatemas[i,segundos],segnum,codigo2);
total:=(minnum*60)+segnum;
duracion[i]:=total;
end;
end;
Procedure OrdenDuracion(listatemas:tmListaTemas; duracion:tvDuracion);
var
i:byte;
j:byte;
temporal:string [20];
begin
for i:=1 to MAXTEM do
begin
for j:=i+1 to MAXTEM do
begin
if (duracion[i]<duracion[j]) then
begin
temporal:=listatemas[i,nombre];
listatemas[i,nombre]:=listatemas[j,nombre];
listatemas[j,nombre]:=temporal;
end;
end;
end;
for i:=1 to MAXTEM do
writeln(listatemas[i,nombre]);
end;
Procedure OrdenAlfabetico2(listatemas:tmListaTemas);
var
i:byte;
j:byte;
temporal:string[20];
begin
for i:=1 to MAXTEM do
begin
for j:=i+1 to MAXTEM do
begin
if (listatemas[i,nombre]>listatemas[j,nombre]) then
begin
temporal:=listatemas[i,nombre];
listatemas[i,nombre]:=listatemas[j,nombre];
listatemas[j,nombre]:=temporal;
end;
end;
end;
for i:=1 to MAXTEM do
writeln(listatemas[i,nombre]);
end;
Function PosicionDj (nombre:string; nomDjs:tvNomDjs):byte;
var
i:byte;
begin
i:=1;
while nomDjs[i]<>nombre do
i:=i+1;
PosicionDj:=i;
end;
Function PosicionTema(listatemas:tmListaTemas; temasPorDj:tmTemasPorDj;j:byte; i:byte):byte;
var
k:byte;
begin
k:=1;
while (listatemas[k,nombre]<>temasPorDj[i,j]) do
k:=k+1;
PosicionTema:=k;
end;
Function Cantidadtemas(i:byte; temasPorDj:tmTemasPorDj):byte;
var
j:byte;
begin
j:=1;
while (temasPorDj[i,j]<>'0') do
j:=j+1;
Cantidadtemas:=j-1;
end;
Procedure OrdenDuracion2(listatemas:tmListaTemas; temasPorDj:tmTemasPorDj; nombre:string; nomDjs:tvNomDjs; duracion:tvDuracion);
var
i:byte;
temporal:string [20];
l:byte;
j:byte;
g:byte;
MLTemas:byte;
posiciontema1:byte;
posiciontema2:byte;
begin
i:=PosicionDj(nombre,nomDjs);
MLTemas:=Cantidadtemas(i,temasPorDj);
for j:=1 to MLTemas do
begin
for g:=j+1 to MLTemas do
begin
posiciontema1:=PosicionTema(listatemas,temasPorDj,j,i);
posiciontema2:=PosicionTema(listatemas,temasPorDj,g,i);
if (duracion[posiciontema1]>duracion[posiciontema2]) then
begin
temporal:=temasPorDj[i,j];
temasPorDj[i,j]:=temasPorDj[i,g];
temasPorDj[i,g]:=temporal;
end;
end;
end;
for l:=1 to MLTemas do
writeln(temasPorDj[i,l]);
end;
Procedure OrdenDeIngreso2(temasPorDj:tmTemasPorDj; nombre:string;nomDjs:tvNomDjs);
var
i:byte;
k:byte;
j:byte;
begin
i:=PosicionDj(nombre,nomDjs);
j:=1;
k:=1;
while (temasPorDj[i,j]<>'0') do
begin
writeln(k,'- ',temasPorDj[i][j]);
j:=j+1;
k:=k+1;
end;
end;
Procedure Submenu1(nomDjs:TvNomDjs; MLDjs:tiDjs );
var
opcionsubmenu1:byte;
begin
writeln('Ingrese la opcion deseada');
repeat
writeln('1- Orden en que fueron ingresados');
writeln('2- Ordenados alfabeticamente en forma ascendente');
writeln('3- Salir de esta lista');
readln(opcionsubmenu1);
case opcionsubmenu1 of
1: OrdenDeIngreso(nomDjs,MLDjs);
2: OrdenAlfabetico(nomDjs,MLDjs);
3: writeln ('Salio del Listado de Djs');
else writeln('Ingreso una opcion invalida, vuelva a elegir una opcion');
end;
until (opcionsubmenu1=3);
end;
Procedure Submenu2 (listatemas:tmListaTemas; duracion:tvDuracion);
var
opcionsubmenu2:byte;
begin
writeln('Ingrese la opcion deseada');
repeat
writeln('1- Orden por duracion en forma descendente');
writeln('2- Ordenados alfabeticamente en forma ascendente');
writeln('3- Salir de esta lista');
readln(opcionsubmenu2);
case opcionsubmenu2 of
1: OrdenDuracion(listatemas,duracion);
2: OrdenAlfabetico2(listatemas);
3: writeln ('Salio del Listado de Temas');
else writeln('Ingreso una opcion invalida, vuelva a elegir una opcion');
end;
until (opcionsubmenu2=3);
end;
Procedure SalirLista(var opcionsubmenu3:byte);
const
OPMAX=2;
OPMIN=1;
begin
repeat
writeln('¿Desea salir de esta lista?');
writeln('1-Si');
writeln('2-No');
readln (opcionsubmenu3);
until ((opcionsubmenu3<=OPMAX) and (opcionsubmenu3>=OPMIN));
end;
Procedure ValidarNombre(var nombre:string; nomDjs:tvNomDjs; MLDjs:tiDjs);
var
i:byte;
boleano:boolean;
begin
repeat
boleano:=false;
writeln('Ingrese el nombre del Dj que desee para ver los temas que va a tocar');
readln(nombre);
for i:=1 to MLDjs do
if nombre=nomDjs[i] then boleano:=true;
until (boleano=true);
end;
Procedure Submenu3 (listatemas:tmListaTemas; temasPorDj:tmTemasPorDj;nomDjs:tvNomDjs; MLDjs:tiDjs; duracion:tvDuracion);
const
OPMAX=2;
OPMIN=1;
var
opcionsubmenu3:byte;
nombre:string;
begin
repeat
ValidarNombre(nombre,nomDjs,MLDjs);
writeln('Ingrese la opcion deseada');
repeat
writeln('1- Temas ordenados por duracion en forma ascendente');
writeln('2- Temas en el orden de ingreso');
readln(opcionsubmenu3);
case opcionsubmenu3 of
1: OrdenDuracion2(listatemas,temasPorDj,nombre,nomDjs,duracion);
2: OrdenDeIngreso2(temasPorDj,nombre,nomDjs);
else writeln('Ingreso una opcion invalida, vuelva a elegir una opcion');
end;
until ((opcionsubmenu3<=OPMAX) and (opcionsubmenu3>=OPMIN));
SalirLista(opcionsubmenu3);
until (opcionsubmenu3=1);
end;
Procedure Menu2(listatemas:tmListaTemas;nomDjs:tvNomDjs;temasPorDj:tmTemasPorDj;MLDjs:tiDjs; duracion:tvDuracion);
var
opcionmen2:byte;
begin
Duracionminseg(duracion,listatemas);
writeln('Ingrese la opción deseada');
repeat
writeln('1- Listado de Dj');
writeln('2- Listado de Temas');
writeln('3- Listado de Temas de un Dj determinado');
writeln('4- Salir de Listado de Datos');
readln(opcionmen2);
case opcionmen2 of
1: Submenu1(nomDjs,MLDjs);
2: Submenu2(listatemas,duracion);
3: Submenu3(listatemas,temasPorDj,nomDjs,MLDjs,duracion);
4: writeln('Salio del Listado de Datos');
else writeln('Ingreso una opcion invalida, vuelva a elegir una opcion');
end;
until (opcionmen2=4);
end;
Procedure ConversordeSeg(maxdVector:integer);
var
Hor,Min,Seg,cero:string[4];
HorAux,MinAux,SegAux:byte;
begin
cero:='0';
HorAux:=(maxdVector div 3600);
Str(HorAux,Hor);
if HorAux<10 then
insert(cero,Hor,1);
MinAux:=(maxdVector mod 3600) div 60;
Str(Minaux,Min);
if MinAux<10 then
insert(cero,Min,1);
SegAux:=(maxdVector mod 3600) mod 60;
Str(SegAux,Seg);
if SegAux<10 then
insert(cero,Seg,1);
writeln(Hor,':',Min,':',Seg);
end;
Procedure MaxdVector(MLDjs:tiDjs; VecTotalsegPordj:tvTotalsegPorDj; VecPosicion:tvPosicion; nomDjs:tvNomDjs);
var
i,j,k:byte;
maxdVector:integer;
begin
for i:=1 to MLDjs do
begin
if (VecTotalsegPorDj[i]>maxdVector) then
begin
maxdVector:=VecTotalsegPorDj[i];
k:=1;
for j:=i to MLDjs do
if VecTotalsegPorDj[j]=maxdVector then
begin
VecPosicion[k]:=j;
VecPosicion[k+1]:=0;
k:=k+1;
end
end
end;
i:=1;
while VecPosicion[i]<>0 do
begin
if (VecPosicion[2]=0) then
begin
write(nomDjs[VecPosicion[1]],' tocara ');
ConversordeSeg(maxdVector);
end
else
begin
Write(nomDjs[VecPosicion[i]],' tocara ');
ConversordeSeg(maxdVector);
end;
i:=i+1
end;
end;
Procedure DjsQueMasToca(VecTotalsegPordj:tvTotalsegPorDj; listatemas:tmListaTemas; temasPorDj:tmTemasPorDj; MLDjs:tiDjs; VecPosicion:tvPosicion; nomDjs:tvNomDjs);
var
i,j,k,minnum,segnum,codigo:byte;
Total,Parcial:integer;
begin
for i:=1 to MLDjs do
begin
j:=1;
repeat
for k:=1 to MAXTEM do
if temasPorDj[i,j]=listatemas[k,nombre] then
begin
VAL(listatemas[k,minutos],minnum,codigo);
VAL(listatemas[k,segundos],segnum,codigo);
Parcial:=((minnum*60)+segnum);
end;
Total:=Total+Parcial;
j:=j+1;
until(temasPorDj[i,j]='0');
VecTotalsegPorDj[i]:=Total;
Total:=0
end;
MaxdVector(MLDjs,VecTotalsegPordj,VecPosicion,nomDjs);
end;
Procedure Inicializarvector (var temasRepetidos:tvTemasRepetidos);
var
i:byte;
begin
for i:=1 to MAXTEM do
temasRepetidos[i]:=0;
end;
Function MaxRepetidos(temasRepetidos:tvTemasRepetidos):byte;
var
i:byte;
aux:byte;
begin
aux:=0;
for i:=1 to MAXTEM do
if temasRepetidos[i]>aux then
aux:=temasRepetidos[i];
MaxRepetidos:=aux;
end;
Function CantidadMaximos(temasRepetidos:tvTemasRepetidos; maximoRepetidos:byte):byte;
var
i:byte;
aux:byte;
begin
aux:=0;
for i:=1 to MAXTEM do
if temasRepetidos[i]=maximoRepetidos then
aux:=aux+1;
CantidadMaximos:=aux;
end;
Procedure Mostrar(contador:byte; maximoRepetidos:byte; temasRepetidos:tvTemasRepetidos; listatemas:tmListaTemas);
var
i:byte;
begin
if (contador=1) then
for i:=1 to MAXTEM do
if temasRepetidos[i]=maximoRepetidos then
writeln(listatemas[i,nombre], ' es el tema que mas veces sera tocado, con un total de ', maximoRepetidos, ' repeticiones');
if (contador>1) then
for i:=1 to MAXTEM do
if temasRepetidos[i]=maximoRepetidos then
begin
writeln(listatemas[i,nombre],' es uno de los temas que sera mas tocado, con un total de ',maximoRepetidos, ' repeticiones');
writeln('Este tema dura ',listatemas[i,minutos],':',listatemas[i,segundos]);
writeln(' ');
end;
end;
Procedure TemasMasTocados(temasPorDj:tmTemasPorDj; listatemas:tmListaTemas; temasRepetidos:tvTemasRepetidos; MLDjs:tiDjs);
var
i:byte;
j:byte;
k:byte;
maximoRepetidos:byte;
contador:byte;
begin
Inicializarvector(temasRepetidos);
for k:=1 to MLDjs do
begin
i:=1;
while temasPorDj[k,i]<>'0' do
begin
for j:=1 to MAXTEM do
if (temasPorDj[k,i]=listaTemas[j,nombre]) then
temasRepetidos[j]:= temasRepetidos[j] + 1;
i:=i+1;
end;
end;
maximoRepetidos:=MaxRepetidos(temasRepetidos);
contador:=CantidadMaximos(temasRepetidos,maximoRepetidos);
Mostrar(contador,maximoRepetidos,temasRepetidos,listatemas);
end;
var
listatemas:tmListaTemas;
nomDjs:tvNomDjs;
temasPorDj:tmTemasPorDj;
opcionmen1:byte;
MLDjs:tiDjs;
duracion:tvDuracion;
temasRepetidos:tvTemasRepetidos;
vecTotalSegPorDj:tvTotalSegPorDj;
vecPosicion:tvPosicion;
BEGIN
Menu1(listatemas,nomDjs,temasPorDj,opcionmen1,MLDjs);
writeln('Listado de Datos');
Menu2(listatemas,nomDjs,temasPorDj,MLDjs,duracion);
writeln(' ');
writeln('Djs que mas tiempo tocaran:');
DjsQueMasToca(vecTotalsegPordj,listatemas,temasPorDj,MLDjs,vecPosicion,nomDjs);
writeln(' ');
writeln('Temas mas tocados:');
TemasMasTocados(temasPorDj,listatemas,temasRepetidos,MLDjs);
readln();
END.
|
unit VA508AccessibilityConst;
interface
uses
Windows, SysUtils;
// When a component receives focus, the screen reader needs to request data about the
// component. The Call Back proc is called, and the VA app then supplies the info by
// returning the requested values
const
JAWS_REQUIRED_VERSION = '7.10.500';
JAWS_APPLICATION_FILENAME = 'jfw.exe';
// flags sent to and from the screen reader
// if data is not sent from the app, then the screen reader should use it's default mechanism to
// read the data.
DATA_ALL_BITS = $FFFFFF;
DATA_NONE = $000000; // No flags set
DATA_CAPTION = $000001; // Sent both ways indicating data requested / sent
DATA_VALUE = $000002; // Sent both ways indicating data requested / sent
DATA_CONTROL_TYPE = $000004; // Sent both ways indicating data requested / sent
DATA_STATE = $000008; // Sent both ways indicating data requested / sent
DATA_INSTRUCTIONS = $000010; // Sent both ways indicating data requested / sent
DATA_ITEM_INSTRUCTIONS = $000020; // Sent both ways indicating data requested / sent
DATA_DATA = $000040; // Sent both ways indicating data requested / sent
DATA_MASK_DATA = DATA_ALL_BITS - DATA_DATA;
DATA_CHANGE_EVENT = $001000; // Sent by app indicating am item or state change event
DATA_MASK_CHANGE_EVENT = DATA_ALL_BITS - DATA_CHANGE_EVENT;
DATA_ITEM_CHANGED = $002000; // in a change event, indicates a child item has changed
DATA_CUSTOM_KEY_COMMAND = $100000; // custom key command
DATA_CUSTOM_KEY_COMMAND_MASK = DATA_ALL_BITS - $100000;
DATA_ERROR = $800000; // component not found
const
BEHAVIOR_ADD_DICTIONARY_CHANGE = $0001; // pronounce a word differently
BEHAVIOR_ADD_COMPONENT_CLASS = $0002; // add assignment to treat a custom component class as a standard component class
BEHAVIOR_REMOVE_COMPONENT_CLASS = $0003; // remove assignment treat a custom component class as a standard component class
BEHAVIOR_ADD_COMPONENT_MSAA = $0004; // add assignment to use MSAA for class information
BEHAVIOR_REMOVE_COMPONENT_MSAA = $0005; // remove assignment to use MSAA for class information
BEHAVIOR_ADD_CUSTOM_KEY_MAPPING = $0006; // assign a custom key mapping
BEHAVIOR_ADD_CUSTOM_KEY_DESCRIPTION = $0007; // assign a custom key mapping Description
BEHAVIOR_PURGE_UNREGISTERED_KEY_MAPPINGS = $0008; // purge custom key mappings that were not assigned using BEHAVIOR_ADD_CUSTOM_KEY_MAPPING
const
CLASS_BEHAVIOR_BUTTON = 'Button';
CLASS_BEHAVIOR_CHECK_BOX = 'CheckBox';
CLASS_BEHAVIOR_COMBO_BOX = 'ComboBox';
CLASS_BEHAVIOR_DIALOG = 'Dialog';
CLASS_BEHAVIOR_EDIT = 'Edit';
CLASS_BEHAVIOR_EDIT_COMBO = 'EditCombo';
CLASS_BEHAVIOR_GROUP_BOX = 'GroupBox';
CLASS_BEHAVIOR_LIST_VIEW = 'ListView';
CLASS_BEHAVIOR_LIST_BOX = 'ListBox';
CLASS_BEHAVIOR_TREE_VIEW = 'TreeView';
CLASS_BEHAVIOR_STATIC_TEXT = 'StaticText';
const
CRLF = #13#10;
ERROR_INTRO =
'In an effort to more fully comply with Section 508 of the Rehabilitation' + CRLF +
'Act, the software development team has created a special Accessibility' + CRLF +
'Framework that directly communicates with screen reader applications.' + CRLF + CRLF;
type
TConfigReloadProc = procedure of object;
TComponentDataRequestProc = procedure(WindowHandle: HWND; DataRequest: LongInt); stdcall;
TVA508QueryProc = procedure(Sender: TObject; var Text: string);
TVA508ListQueryProc = procedure(Sender: TObject; ItemIndex: integer; var Text: string);
TVA508Exception = Exception;
implementation
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit MaskProp;
interface
uses Windows, Classes, Graphics, Forms, Controls, StdCtrls, ExtCtrls, Buttons,
DesignIntf, DesignEditors, Mask, MaskUtils, SysUtils, Dialogs;
type
{ TMaskProperty
Property editor the Masked Edit Mask property }
TMaskProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
type
TMaskForm = class(TForm)
InputMask: TEdit;
Label1: TLabel;
ListBox1: TListBox;
Label2: TLabel;
Label3: TLabel;
TestEdit: TMaskEdit;
Label4: TLabel;
Blanks: TEdit;
Bevel1: TBevel;
SaveMaskCheck: TCheckBox;
Masks: TButton;
OpenDialog1: TOpenDialog;
OKButton: TButton;
CancelButton: TButton;
HelpButton: TButton;
procedure BlanksChange(Sender: TObject);
procedure InputMaskChange(Sender: TObject);
procedure ListDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
procedure ListBoxSelect(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure MasksClick(Sender: TObject);
procedure HelpButtonClick(Sender: TObject);
private
FInEditChange: Boolean;
function AddBlanks(Value: String): String;
procedure LoadMaskList(const FileName: string);
protected
function GetListMaskValue(Index: Integer): string;
function GetMaskValue(const Value: string): string;
procedure Loaded; override;
public
end;
var
MaskForm: TMaskForm;
function EditInputMask(var InputMask: string; const InitialDir: string): Boolean;
implementation
uses Registry, LibHelp, DsnConst, ToolsAPI;
{$R *.dfm}
function EditInputMask(var InputMask: string; const InitialDir: string): Boolean;
var
Frm : TMaskForm;
begin
Frm := TMaskForm.Create (Application);
try
Frm.InputMask.Text := InputMask;
Frm.TestEdit.EditMask := Frm.InputMask.Text;
if InitialDir <> '' then Frm.OpenDialog1.InitialDir := InitialDir;
Result := Frm.ShowModal = mrOK;
if Result then
begin
InputMask := Frm.InputMask.Text;
if (Length(InputMask) <> 0) and (MaskGetFldSeparator(InputMask) < 0) then
begin
Frm.BlanksChange(Frm);
InputMask := Frm.InputMask.Text;
end;
end;
finally
Frm.Free;
end;
end;
{ TMaskProperty }
function TMaskProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog] - [paSubProperties];
end;
procedure TMaskProperty.Edit;
var
Str : String;
begin
Str := GetValue;
if EditInputMask(Str, GetLocaleDirectory((BorlandIDEServices as IOTAServices).GetTemplateDirectory)) and (GetValue <> Str) then
begin
SetValue(Str);
Modified;
end;
end;
{-----------}
procedure TMaskForm.BlanksChange(Sender: TObject);
Var
Str : String;
begin
Str := InputMask.Text;
if (Length(Str) <> 0) and not FInEditChange then
InputMask.Text := AddBlanks(Str);
end;
function TMaskForm.AddBlanks(Value: string): string;
Var
Pos : Integer;
BlankChar : Char;
SaveChar : Char;
begin
Result := Value;
if Length (Result) <> 0 then
begin
BlankChar := MaskGetMaskBlank (Value);
SaveChar := '1';
if Length (Blanks.Text) > 0 then
BlankChar := Blanks.Text[1];
if not SaveMaskCheck.Checked then
SaveChar := MaskNoSave;
Pos := MaskGetFldSeparator (Result);
if Pos > 0 then SetLength(Result, Pos - 1);
Result := Result + MaskFieldSeparator + SaveChar
+ MaskFieldSeparator + BlankChar;
end;
end;
procedure TMaskForm.InputMaskChange(Sender: TObject);
var
BlankChar: string;
begin
TestEdit.Text := EmptyStr;
TestEdit.EditMask := InputMask.Text;
if TestEdit.EditMask <> GetListMaskValue(ListBox1.ItemIndex) then
ListBox1.ItemIndex := -1;
FInEditChange := True;
SaveMaskCheck.Checked := MaskGetMaskSave(TestEdit.EditMask);
BlankChar := MaskGetMaskBlank (TestEdit.EditMask);
Blanks.Text := Format ('%s', [BlankChar]);
FInEditChange := False;
end;
procedure TMaskForm.ListDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
R: TRect;
CString: array[0..80] of char;
Str, EditMask : String;
X, Temp, StrPos : Integer;
begin
if (Index >= ListBox1.Items.Count) then Exit;
with ListBox1.Canvas do
begin
Str := ListBox1.Items[Index];
StrPos := AnsiPos ('|', Str);
if StrPos = 0 then Exit;
R := Rect;
X := R.Right;
R.Right := R.Right div 2;
ExtTextOut(Handle, R.Left + 1, R.Top + 1, ETO_CLIPPED or ETO_OPAQUE, @R,
PChar(Copy(Str, 1, StrPos)), StrPos - 1, nil);
MoveTo(R.Right, R.Top);
LineTo(R.Right, R.Bottom);
Str := Copy(Str, StrPos + 2, Length (Str) - StrPos - 2);
StrPos := AnsiPos ('|', Str);
if StrPos = 0 then Exit;
Temp := Length(Str);
SetLength(Str, StrPos - 2);
EditMask := GetListMaskValue(Index);
EditMask[Length(EditMask) - 2] := '0';
EditMask := FormatMaskText(EditMask, Str);
StrPLCopy(CString, EditMask, SizeOf(CString) - 1);
SetLength(Str, Temp);
R.Left := R.Right + 1;
R.Right := X;
ExtTextOut(Handle, R.Left + 1, R.Top + 1, ETO_CLIPPED or ETO_OPAQUE, @R,
CString, Length(EditMask), nil);
end;
end;
procedure TMaskForm.ListBoxSelect(Sender: TObject);
begin
if ListBox1.ItemIndex >= 0 then
InputMask.Text := GetListMaskValue(ListBox1.ItemIndex);
end;
function TMaskForm.GetListMaskValue(Index: Integer): string;
begin
if Index >= 0 then Result := GetMaskValue(ListBox1.Items[Index])
else Result := '';
end;
function TMaskForm.GetMaskValue(const Value: string): string;
var
StrPos: Integer;
begin
Result := '';
StrPos := AnsiPos ('|', Value);
if StrPos = 0 then Exit;
Result := Value;
Result := Copy(Result, StrPos + 1, Length (Result) - StrPos);
StrPos := AnsiPos ('|', Result);
if StrPos = 0 then
begin
Result := '';
Exit;
end;
if Result[StrPos+1] = ' ' then
Inc (StrPos);
Result := Copy(Result, StrPos + 1, Length (Result) - StrPos);
end;
procedure TMaskForm.FormCreate(Sender: TObject);
begin
HelpContext := hcDInputMaskEditor;
end;
procedure TMaskForm.MasksClick(Sender: TObject);
var
AppIniFile: TRegIniFile;
begin
OpenDialog1.HelpContext := hcDOpenMaskFile;
if OpenDialog1.Execute then
begin
LoadMaskList(OpenDialog1.FileName);
AppIniFile := TRegIniFile.Create((BorlandIDEServices as IOTAServices).GetBaseRegistryKey);
try
AppIniFile.WriteString (SIniEditorsName, SINIEditMaskName,
OpenDialog1.FileName);
finally
AppIniFile.Free;
end;
end;
end;
procedure TMaskForm.Loaded;
var
AppIniFile: TRegIniFile;
Value: String;
begin
inherited Loaded;
AppIniFile := TRegIniFile.Create((BorlandIDEServices as IOTAServices).GetBaseRegistryKey);
try
Value := AppIniFile.ReadString (SIniEditorsName, SIniEditMaskName, '');
LoadMaskList(Value);
finally
AppIniFile.Free;
end;
end;
procedure TMaskForm.LoadMaskList(const FileName: string);
const
UTF8BOM = $BFBBEF; // reverse order
UTF8BOMSize = 3;
var
I, Size: Integer;
Items: TStringList;
UTF8Str: UTF8String;
Stream: TStream;
BOM: Cardinal;
begin
if (Length(FileName) > 0) and FileExists(FileName) then
begin
Items := TStringList.Create;
try
// Since D8 .DEM files are UTF8 encoded. Test for the
// UTF8 BOM and convert contents if present
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
if Stream.Size >= UTF8BOMSize then
begin
BOM := 0;
Stream.Read(BOM, UTF8BOMSize);
if BOM = UTF8BOM then
begin
Size := Stream.Size - Stream.Position;
SetString(UTF8Str, nil, Size);
Stream.Read(Pointer(UTF8Str)^, Size);
Items.Text := UTF8ToAnsi(UTF8Str);
end
else
begin
Stream.Position := 0;
Items.LoadFromStream(Stream);
end;
end
else
Items.LoadFromStream(Stream);
finally
Stream.Free;
end;
I := 0;
while I < (Items.Count - 1) do
begin
if (Length(Items[I]) = 0) then Items.Delete(I)
else if (GetMaskValue(Items[I]) = '') then
raise EInvalidOperation.Create(SInvalidSampleMask)
else Inc(I);
if I >= Items.Count then break;
end;
ListBox1.Items := Items;
finally
Items.Free;
end;
end;
end;
procedure TMaskForm.HelpButtonClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
end.
|
unit commandline;
{$mode objfpc}
(*
This unit will process command line flags, (/N -N)
a) as present or absent (Is_Param)
b) with an integer (eg. /N54 /X-76) (Param_Int)
c) with a real number (eg /J-987.65) (Param_Real)
d) with strings, including delimited strings with embedded spaces
( eg. /X"This is the story!" /YFred)
Routines are included to count and return the parameters that
aren't flags (Non_Flag_Count), and to return them without
counting the flag parameters (Non_Flag_Param).
So ( /X76 Filename.txt /N"My name is Fred." George ) would count
two non-flag params, #1 = filename.txt and #2 = george.
This is completely public domain, all I want in return for your use
is appreciation. If you improve this unit, please let me know.
Some possible improvements would be to allow embedded strings in
non-flag parameters. I haven't done this because I haven't needed
it.
Jim Walsh CIS:72571,173
*)
INTERFACE
function Is_Param(flag:Char) : Boolean;
{ Responds yes if the flag (ie N) is found in the command line (ie /N or -N) }
function Param_Int(flag:Char) : LongInt;
{ Returns the integer value after the parameter, ie -M100, or -M-123 }
function Param_Real(flag:Char) : Real;
{ Returns the Real value after the parameter, ie -X654.87, or -x-3.14159 }
function Param_Text(flag:Char) : String;
{ Returns the string after the parameter, ie -MHello -> 'Hello', }
{ -m"This is it, baby" -> 'This is it, baby', valid string delims='' "" [] }
function Non_Flag_Param(index:integer) : string;
{ Returns the indexth parameter, not preceded with a flag delimeter }
{ /X Text.txt /Y876.76 /G"Yes sir!" MeisterBrau /? }
{ For this command line 'Text.txt' is Non Flag Param #1, }
{ and 'MeisterBrau is #2. }
{ NB: Delimeted Non flag parameters (eg "Meister Brau") }
{ not currently supported. }
function Non_Flag_Count : integer;
{ Returns the number of non-flag type parameters }
IMPLEMENTATION
const
flag_delims : Set of Char = ['-'];
no_of_string_delims = 3;
type
string_delim_type = Array[1..3] of record
start, stop : char
end;
const
string_delims : string_delim_type = ((start:#39; stop:#39),
(start:#34; stop:#34),
(start:'['; stop:']'));
var
IgnoreCase: boolean;
function LowerCaseChar(c:char):char;
begin
if (c>='A') and (c<='Z') and IgnoreCase Then
LowerCaseChar:=Char(Ord(c)+$20)
else
LowerCaseChar:=c
end;
{----------------------------------------------------------------------------}
function WhereFlagOccurs(flag:Char) : integer;
{ returns the index number of the paramter where the flag occurs }
{ if the flag is never found, it returns 0 }
var
ti1 : integer;
finished : boolean;
paramcnt : integer;
ts1 : string;
begin
flag:=LowerCaseChar(flag);
finished:=false;
ti1:=1;
paramcnt:=ParamCount;
While Not(finished) Do begin
If ti1>paramcnt Then begin
finished:=true;
ti1:=0;
end Else begin
ts1:=ParamStr(ti1);
If (ts1[1] In flag_delims) AND (LowerCaseChar(ts1[2])=flag) Then finished:=true;
end;
If Not(finished) Then Inc(ti1);
end; {While}
WhereFlagOccurs:=ti1;
end;
{----------------------------------------------------------------------------}
function Is_Param(flag:Char) : Boolean;
begin
If WhereFlagOccurs(flag)=0 Then Is_Param:=false Else Is_Param:=true;
end;
{----------------------------------------------------------------------------}
function Param_Int(flag:Char) : LongInt;
var
param_loc : integer;
_result : longint;
ts1 : string;
ti1 : integer;
begin
param_loc:=WhereFlagOccurs(flag);
If param_loc=0 Then _result:=0
Else begin
ts1:=ParamStr(param_loc); { Get the string }
ts1:=Copy(ts1,3,255); { Get rid of the delim and the flag }
Val(ts1,_result,ti1); { Make the value }
If ti1<>0 Then _result:=0; { Make sure there is no error }
end; {If/Else}
Param_Int:=_result
end;
{----------------------------------------------------------------------------}
function Param_Real(flag:Char) : Real;
var
param_loc : integer;
_result : real;
ts1 : string;
ti1 : integer;
begin
param_loc:=WhereFlagOccurs(flag);
If param_loc=0 Then _result:=0.0
Else begin
ts1:=ParamStr(param_loc); { Get the string }
ts1:=Copy(ts1,3,255); { Get rid of the delim and the flag }
Val(ts1,_result,ti1); { Make the value }
If ti1<>0 Then _result:=0.0; { Make sure there is no error }
end; {If/Else}
Param_Real:=_result;
end;
{----------------------------------------------------------------------}
function Which_String_Delim(S:string) : byte;
{ Returns the index of the strings first character in the array
of string_delims, if the first char of S isn't a delim it returns 0 }
var
tc1 : char;
tb1 : byte;
finished : boolean;
_result : byte;
begin
tc1:=S[1];
tb1:=1;
finished:=false;
While Not(finished) Do begin
If tb1>no_of_string_delims Then begin
_result:=0;
finished:=true;
end Else begin
If tc1=string_delims[tb1].start Then begin
_result:=tb1;
finished:=true;
end;
end;
If Not(finished) Then Inc(tb1);
end; {While}
Which_String_Delim:=_result;
end; {function Which_String}
{-------------------------------------------------------------------------}
function Param_Text(flag:Char) : String;
var
param_loc : integer;
param_cnt : integer;
_result : string;
ts1 : string;
{ ti1 : integer; }
s_delim : byte; { This should be 0(no string), 1', 2", 3[ }
finished : boolean;
begin
param_loc:=WhereFlagOccurs(flag);
If param_loc=0 Then _result:=''
Else begin
ts1:=ParamStr(param_loc); { Get the string }
ts1:=Copy(ts1,3,255); { Get rid of the delim and the flag }
{ See if the first char of ts1 is one of the string_delims }
s_delim:=Which_String_Delim(ts1);
If s_delim=0 Then _result:=ts1
Else begin
_result:=Copy(ts1,2,255); { Drop the s_delim }
finished:=false;
param_cnt:=ParamCount;
While Not(finished) Do begin
Inc(param_loc);
If param_loc>param_cnt Then finished:=true
Else begin
ts1:=ParamStr(param_loc);
If ts1[Length(ts1)]=string_delims[s_delim].stop Then finished:=true;
_result:=_result+' '+ts1;
end; { If/Else }
end; { While }
_result[0]:=Char(Length(_result)-1); { Drop the last delimeter }
end; { If/Else a delimited string }
end; { If/Else the flag is found }
Param_Text:=_result;
end;
{---------------------------------------------------------------------------}
function Non_Flag_Param(index:integer) : string;
var
param_cnt : integer;
ti1 : integer;
ts1 : string;
finished : boolean;
cur_index : integer;
begin
param_cnt:=ParamCount;
cur_index:=0;
ti1:=0;
finished:=false;
While Not(finished) Do begin
Inc(ti1);
IF cur_index>param_cnt Then begin
ts1:='';
finished:=true;
end Else begin
ts1:=ParamStr(ti1);
If Not(ts1[1] IN flag_delims) Then begin
Inc(cur_index);
If cur_index=index Then finished:=true;
end;
end; {If/Else}
end; {While}
Non_Flag_Param:=ts1;
end;
{---------------------------------------------------------------------------}
function Non_Flag_Count : integer;
var
param_cnt : integer;
_result : integer;
ti1 : integer;
ts1 : string;
begin
param_cnt:=ParamCount;
_result:=0;
ti1:=0;
For ti1:=1 To param_cnt Do begin
ts1:=ParamStr(ti1);
If Not(ts1[1] IN flag_delims) Then begin
Inc(_result);
end;
end; {For}
Non_Flag_Count:=_result;
end;
begin
IgnoreCase:=true;
END.
|
{**********************************************}
{ TOHLCSeries (derived from TCustomSeries) }
{ Copyright (c) 1995-2004 by David Berneda }
{**********************************************}
unit OHLChart;
{$I TeeDefs.inc}
interface
Uses {$IFDEF CLR}
Borland.VCL.Classes,
{$ELSE}
Classes,
{$IFDEF CLX}
QGraphics,
{$ELSE}
Graphics,
{$ENDIF}
{$ENDIF}
Chart, Series, TeEngine;
{ WARNING:
NOTE FOR TeeChart Pro users since version 4.
The logic in OHLC series has been changed.
Now the default "Y" values correspond to the Close values,
before they were referred to Open values.
This change should be transparent to your code unless you're
accessing directly the "Y" values.
}
{ Used in financial applications, OHLC stands for Open,High,Low & Close.
These are the prices a particular financial product has in a given time
period.
TOHLCSeries extends the basic TCustomSeries adding new lists for
High, Low & Open prices, and preserving the default Y values for Close
prices.
Overrides the basic list functions (Add, Clear & Delete) plus the
FillSampleValues method, used in design mode to show some fictional
values to the user.
Publishes the High, Low & Open values lists and "overrides" the XValues
property to be DateValues and the YValues to be CloseValues.
}
type
TOHLCSeries=class(TCustomSeries)
private { assumed YValues = CloseValues }
FHighValues : TChartValueList;
FLowValues : TChartValueList;
FOpenValues : TChartValueList;
Function GetCloseValues:TChartValueList;
Function GetDateValues:TChartValueList;
Procedure SetCloseValues(Value:TChartValueList);
Procedure SetDateValues(Value:TChartValueList);
Procedure SetHighValues(Value:TChartValueList);
Procedure SetLowValues(Value:TChartValueList);
Procedure SetOpenValues(Value:TChartValueList);
protected
Procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); override;
public
Constructor Create(AOwner: TComponent); override;
Function AddOHLC( Const ADate:TDateTime;
Const AOpen,AHigh,ALow,AClose:Double):Integer; overload;
Function AddOHLC(Const AOpen,AHigh,ALow,AClose:Double):Integer; overload;
// returns random values for Open,Close,High and Low prices. Used for demos
class Procedure GetRandomOHLC(AOpen:Double; Var AClose,AHigh,ALow:Double; Const YRange:Double);
Function IsValidSourceOf(Value:TChartSeries):Boolean; override;
Function MaxYValue:Double; override;
Function MinYValue:Double; override;
Function NumSampleValues:Integer; override;
published
property CloseValues:TChartValueList read GetCloseValues write SetCloseValues;
property DateValues:TChartValueList read GetDateValues write SetDateValues;
property HighValues:TChartValueList read FHighValues write SetHighValues;
property LowValues:TChartValueList read FLowValues write SetLowValues;
property OpenValues:TChartValueList read FOpenValues write SetOpenValues;
end;
implementation
Uses {$IFDEF CLR}
{$ELSE}
Math, SysUtils,
{$ENDIF}
TeCanvas, TeeProCo;
type TValueListAccess=class(TChartValueList);
{ TOHLCSeries }
Constructor TOHLCSeries.Create(AOwner: TComponent);
Begin
inherited;
TValueListAccess(XValues).InitDateTime(True);
XValues.Name:=TeeMsg_ValuesDate;
YValues.Name:=TeeMsg_ValuesClose;
FHighValues :=TChartValueList.Create(Self,TeeMsg_ValuesHigh);
FLowValues :=TChartValueList.Create(Self,TeeMsg_ValuesLow);
FOpenValues :=TChartValueList.Create(Self,TeeMsg_ValuesOpen);
end;
Function TOHLCSeries.GetDateValues:TChartValueList;
Begin
result:=XValues; { overrides default XValues }
end;
Procedure TOHLCSeries.SetDateValues(Value:TChartValueList);
begin
SetXValues(Value); { overrides default XValues }
end;
Function TOHLCSeries.GetCloseValues:TChartValueList;
Begin
result:=YValues; { overrides default YValues }
end;
Procedure TOHLCSeries.SetCloseValues(Value:TChartValueList);
begin
SetYValues(Value); { overrides default YValues }
end;
Procedure TOHLCSeries.SetHighValues(Value:TChartValueList);
Begin
SetChartValueList(FHighValues,Value);
end;
Procedure TOHLCSeries.SetLowValues(Value:TChartValueList);
Begin
SetChartValueList(FLowValues,Value);
end;
Procedure TOHLCSeries.SetOpenValues(Value:TChartValueList);
Begin
SetChartValueList(FOpenValues,Value);
end;
Function TOHLCSeries.AddOHLC( Const ADate:TDateTime;
Const AOpen,AHigh,ALow,AClose:Double):Integer;
Begin
HighValues.TempValue:=AHigh;
LowValues.TempValue:=ALow;
OpenValues.TempValue:=AOpen;
result:=AddXY(ADate,AClose);
end;
Function TOHLCSeries.AddOHLC(Const AOpen,AHigh,ALow,AClose:Double):Integer;
begin
DateValues.DateTime:=False;
HighValues.TempValue:=AHigh;
LowValues.TempValue:=ALow;
OpenValues.TempValue:=AOpen;
result:=Add(AClose);
end;
Function TOHLCSeries.MaxYValue:Double;
Begin
result:=Math.Max(CloseValues.MaxValue,HighValues.MaxValue);
result:=Math.Max(result,LowValues.MaxValue);
result:=Math.Max(result,OpenValues.MaxValue);
End;
Function TOHLCSeries.MinYValue:Double;
Begin
result:=Math.Min(CloseValues.MinValue,HighValues.MinValue);
result:=Math.Min(result,LowValues.MinValue);
result:=Math.Min(result,OpenValues.MinValue);
End;
// Returns random OHLC values
class Procedure TOHLCSeries.GetRandomOHLC(AOpen:Double; Var AClose,AHigh,ALow:Double; Const YRange:Double);
var tmpY : Integer;
tmpFixed : Double;
Begin
tmpY:=Abs(Round(YRange/400.0));
AClose:=AOpen+RandomValue(Round(YRange/25.0))-(YRange/50.0); { imagine a close price... }
{ and imagine the high and low session price }
tmpFixed:=3*Round(Abs(AClose-AOpen)/10.0);
if AClose>AOpen then
Begin
AHigh:=AClose+tmpFixed+RandomValue(tmpY);
ALow:=AOpen-tmpFixed-RandomValue(tmpY);
end
else
begin
AHigh:=AOpen+tmpFixed+RandomValue(tmpY);
ALow:=AClose-tmpFixed-RandomValue(tmpY);
end;
end;
Procedure TOHLCSeries.AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False);
Var AOpen : Double;
AHigh : Double;
ALow : Double;
AClose : Double;
t : Integer;
s : TSeriesRandomBounds;
Begin
s:=RandomBounds(NumValues);
with s do
begin
AOpen:=MinY+RandomValue(Round(DifY)); { starting open price }
for t:=1 to NumValues do
Begin
// Generate random figures
GetRandomOHLC(AOpen,AClose,AHigh,ALow,DifY);
// call the standard add method
AddOHLC(tmpX,AOpen,AHigh,ALow,AClose);
tmpX:=tmpX+StepX; { <-- next point X value }
// Tomorrow, the market will open at today's close plus/minus something }
AOpen:=AClose+RandomValue(10)-5;
end;
end;
end;
Function TOHLCSeries.NumSampleValues:Integer;
begin
result:=40;
end;
Function TOHLCSeries.IsValidSourceOf(Value:TChartSeries):Boolean;
begin
result:=Value is TOHLCSeries;
end;
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/coins.h
// Bitcoin file: src/coins.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TCoinsViewCache;
interface
/** CCoinsView that adds a memory cache for transactions to another CCoinsView */
class CCoinsViewCache : public CCoinsViewBacked
{
protected:
/**
* Make mutable so that we can "fill the cache" even from Get-methods
* declared as "const".
*/
mutable uint256 hashBlock;
mutable CCoinsMap cacheCoins;
/* Cached dynamic memory usage for the inner Coin objects. */
mutable size_t cachedCoinsUsage;
public:
CCoinsViewCache(CCoinsView *baseIn);
/**
* By deleting the copy constructor, we prevent accidentally using it when one intends to create a cache on top of a base cache.
*/
CCoinsViewCache(const CCoinsViewCache &) = delete;
// Standard CCoinsView methods
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
bool HaveCoin(const COutPoint &outpoint) const override;
uint256 GetBestBlock() const override;
void SetBestBlock(const uint256 &hashBlock);
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
CCoinsViewCursor* Cursor() const override {
throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
}
/**
* Check if we have the given utxo already loaded in this cache.
* The semantics are the same as HaveCoin(), but no calls to
* the backing CCoinsView are made.
*/
bool HaveCoinInCache(const COutPoint &outpoint) const;
/**
* Return a reference to Coin in the cache, or coinEmpty if not found. This is
* more efficient than GetCoin.
*
* Generally, do not hold the reference returned for more than a short scope.
* While the current implementation allows for modifications to the contents
* of the cache while holding the reference, this behavior should not be relied
* on! To be safe, best to not hold the returned reference through any other
* calls to this cache.
*/
const Coin& AccessCoin(const COutPoint &output) const;
/**
* Add a coin. Set possible_overwrite to true if an unspent version may
* already exist in the cache.
*/
void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
/**
* Spend a coin. Pass moveto in order to get the deleted data.
* If no unspent output exists for the passed outpoint, this call
* has no effect.
*/
bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
/**
* Push the modifications applied to this cache to its base.
* Failure to call this method before destruction will cause the changes to be forgotten.
* If false is returned, the state of this cache (and its backing view) will be undefined.
*/
bool Flush();
/**
* Removes the UTXO with the given outpoint from the cache, if it is
* not modified.
*/
void Uncache(const COutPoint &outpoint);
//! Calculate the size of the cache (in number of transaction outputs)
unsigned int GetCacheSize() const;
//! Calculate the size of the cache (in bytes)
size_t DynamicMemoryUsage() const;
//! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
bool HaveInputs(const CTransaction& tx) const;
//! Force a reallocation of the cache map. This is required when downsizing
//! the cache because the map's allocator may be hanging onto a lot of
//! memory despite having called .clear().
//!
//! See: https://stackoverflow.com/questions/42114044/how-to-release-unordered-map-memory
void ReallocateCache();
private:
/**
* @note this is marked const, but may actually append to `cacheCoins`, increasing
* memory usage.
*/
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
};
implementation
CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0) {}
size_t CCoinsViewCache::DynamicMemoryUsage() const {
return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
}
CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
CCoinsMap::iterator it = cacheCoins.find(outpoint);
if (it != cacheCoins.end())
return it;
Coin tmp;
if (!base->GetCoin(outpoint, tmp))
return cacheCoins.end();
CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first;
if (ret->second.coin.IsSpent()) {
// The parent only has an empty entry for this outpoint; we can consider our
// version as fresh.
ret->second.flags = CCoinsCacheEntry::FRESH;
}
cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
return ret;
}
bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
if (it != cacheCoins.end()) {
coin = it->second.coin;
return !coin.IsSpent();
}
return false;
}
void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
assert(!coin.IsSpent());
if (coin.out.scriptPubKey.IsUnspendable()) return;
CCoinsMap::iterator it;
bool inserted;
std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
bool fresh = false;
if (!inserted) {
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
}
if (!possible_overwrite) {
if (!it->second.coin.IsSpent()) {
throw std::logic_error("Attempted to overwrite an unspent coin (when possible_overwrite is false)");
}
// If the coin exists in this cache as a spent coin and is DIRTY, then
// its spentness hasn't been flushed to the parent cache. We're
// re-adding the coin to this cache now but we can't mark it as FRESH.
// If we mark it FRESH and then spend it before the cache is flushed
// we would remove it from this cache and would never flush spentness
// to the parent cache.
//
// Re-adding a spent coin can happen in the case of a re-org (the coin
// is 'spent' when the block adding it is disconnected and then
// re-added when it is also added in a newly connected block).
//
// If the coin doesn't exist in the current cache, or is spent but not
// DIRTY, then it can be marked FRESH.
fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
}
it->second.coin = std::move(coin);
it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0);
cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
}
bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
CCoinsMap::iterator it = FetchCoin(outpoint);
if (it == cacheCoins.end()) return false;
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
if (moveout) {
*moveout = std::move(it->second.coin);
}
if (it->second.flags & CCoinsCacheEntry::FRESH) {
cacheCoins.erase(it);
} else {
it->second.flags |= CCoinsCacheEntry::DIRTY;
it->second.coin.Clear();
}
return true;
}
const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
if (it == cacheCoins.end()) {
return coinEmpty;
} else {
return it->second.coin;
}
}
bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
return (it != cacheCoins.end() && !it->second.coin.IsSpent());
}
bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
return (it != cacheCoins.end() && !it->second.coin.IsSpent());
}
uint256 CCoinsViewCache::GetBestBlock() const {
if (hashBlock.IsNull())
hashBlock = base->GetBestBlock();
return hashBlock;
}
void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
hashBlock = hashBlockIn;
}
bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); it = mapCoins.erase(it)) {
// Ignore non-dirty entries (optimization).
if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
continue;
}
CCoinsMap::iterator itUs = cacheCoins.find(it->first);
if (itUs == cacheCoins.end()) {
// The parent cache does not have an entry, while the child cache does.
// We can ignore it if it's both spent and FRESH in the child
if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
// Create the coin in the parent cache, move the data up
// and mark it as dirty.
CCoinsCacheEntry& entry = cacheCoins[it->first];
entry.coin = std::move(it->second.coin);
cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
entry.flags = CCoinsCacheEntry::DIRTY;
// We can mark it FRESH in the parent if it was FRESH in the child
// Otherwise it might have just been flushed from the parent's cache
// and already exist in the grandparent
if (it->second.flags & CCoinsCacheEntry::FRESH) {
entry.flags |= CCoinsCacheEntry::FRESH;
}
}
} else {
// Found the entry in the parent cache
if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) {
// The coin was marked FRESH in the child cache, but the coin
// exists in the parent cache. If this ever happens, it means
// the FRESH flag was misapplied and there is a logic error in
// the calling code.
throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
}
if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
// The grandparent cache does not have an entry, and the coin
// has been spent. We can just delete it from the parent cache.
cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
cacheCoins.erase(itUs);
} else {
// A normal modification.
cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
itUs->second.coin = std::move(it->second.coin);
cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
// NOTE: It isn't safe to mark the coin as FRESH in the parent
// cache. If it already existed and was spent in the parent
// cache then marking it FRESH would prevent that spentness
// from being flushed to the grandparent.
}
}
}
hashBlock = hashBlockIn;
return true;
}
bool CCoinsViewCache::Flush() {
bool fOk = base->BatchWrite(cacheCoins, hashBlock);
cacheCoins.clear();
cachedCoinsUsage = 0;
return fOk;
}
void CCoinsViewCache::Uncache(const COutPoint& hash)
{
CCoinsMap::iterator it = cacheCoins.find(hash);
if (it != cacheCoins.end() && it->second.flags == 0) {
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
cacheCoins.erase(it);
}
}
unsigned int CCoinsViewCache::GetCacheSize() const {
return cacheCoins.size();
}
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
{
if (!tx.IsCoinBase()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (!HaveCoin(tx.vin[i].prevout)) {
return false;
}
}
}
return true;
}
void CCoinsViewCache::ReallocateCache()
{
// Cache should be empty when we're calling this.
assert(cacheCoins.size() == 0);
cacheCoins.~CCoinsMap();
::new (&cacheCoins) CCoinsMap();
}
end.
|
unit ClassComputer;
interface
uses ClassPlayer, Types;
const MAX_DEPTH = 1;
type TTable = array[0..63] of integer;
TCompMove = record
Value : integer;
A, B : integer;
end;
TMoves = record
Items : array[1..200] of record
Move, Best : TCompMove;
end;
Count : integer;
end;
TComp = class( TPlayer )
private
function InitTable( Figures : TFigures ) : TTable;
procedure PohniPesiaka( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
procedure PohniVezu( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
procedure PohniKona( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
procedure PohniStrelca( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
procedure PohniDamu( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
procedure PohniKrala( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
procedure OhodnotTahy( Moves : TMoves; NaTahu : integer );
function FindBestMove( Table : TTable; NaTahu, Depth : integer ) : TCompMove;
function GenerateMoves( Table : TTable; NaTahu : integer ) : TMove;
public
function MakeMove( Figures : TFigures ) : TMove; override;
end;
implementation
//==============================================================================
// Chess
//==============================================================================
function TComp.InitTable( Figures : TFigures ) : TTable;
var I, J : integer;
begin
for I := 1 to 8 do
for J := 1 to 8 do
Result[(J-1)+(I-1)*8] := Figures[J,I];
end;
procedure TComp.PohniPesiaka( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
begin
end;
procedure TComp.PohniVezu( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
begin
end;
procedure TComp.PohniKona( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
begin
end;
procedure TComp.PohniStrelca( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
begin
end;
procedure TComp.PohniDamu( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
begin
end;
procedure TComp.PohniKrala( Table : TTable; NaTahu : integer; Moves : TMoves; Pos : integer );
begin
end;
procedure TComp.OhodnotTahy( Moves : TMoves; NaTahu : integer );
begin
end;
function TComp.FindBestMove( Table : TTable; NaTahu, Depth : integer ) : TCompMove;
var Moves : TMoves;
I : integer;
begin
Moves.Count := 0;
for I := 0 to 63 do
if (Table[I]*NaTahu > 0) then
case Abs(Table[I]) of
1 : PohniPesiaka( Table , NaTahu , Moves , I );
2 : PohniVezu( Table , NaTahu , Moves , I );
3 : PohniKona( Table , NaTahu , Moves , I );
4 : PohniStrelca( Table , NaTahu , Moves , I );
5 : PohniDamu( Table , NaTahu , Moves , I );
6 : PohniKona( Table , NaTahu , Moves , I );
end;
OhodnotTahy( Moves , NaTahu );
for I := 0 to Moves.Count-1 do
Moves.Items[I].Value :=
end;
function TComp.GenerateMoves( Table : TTable; NaTahu : integer ): TMove;
var CompMove : TCompMove;
begin
CompMove := FindBestMove( Table , NaTahu , 0 );
with Result do
begin
A.X := (CompMove.A mod 8)+1;
A.Y := (CompMove.A div 8)+1;
B.X := (CompMove.B mod 8)+1;
B.Y := (CompMove.B div 8)+1;
end;
end;
//==============================================================================
// I N T E R F A C E
//==============================================================================
function TComp.MakeMove( Figures : TFigures ) : TMove;
begin
Result := GenerateMoves( InitTable( Figures ) , 1 );
end;
end.
|
unit vgr_IniStorage;
{$I vtk.inc}
interface
uses
Windows, Classes, SysUtils, IniFiles, Registry;
type
{low-level wrapper for the system registry and functions that operate on the registry}
TRegistryAccess = class(TRegistry)
end;
/////////////////////////////////////////////////
//
// TvgrIniStorage
//
/////////////////////////////////////////////////
{ TvgrIniStorage is the base class for objects that represent ini storages.
TvgrIniStorage contains abstract or, in C++ terminology, pure virtual methods
and should not be directly instantiated. }
TvgrIniStorage = class(TObject)
private
FPath: string;
protected
procedure InternalInit; virtual; abstract;
public
{ Creates a TvgrIniStorage object for an application.
Parameters:
APath identifies file name of ini file for TvgrIniFileStorage or
registry path relative to HKEY_CURRENT_USER for TvgrRegistryStorage. }
constructor Create(const APath: string);
{ Call ReadString to read a string value from an INI file.
Parameters:
ASection identifies the section in the file that contains the desired key.
AIdent is the name of the key from which to retrieve the value.
ADefault is the string value to return if the:
<br>Section does not exist.
<br>Key does not exist.
<br>Data value for the key is not assigned.
Return value:
string value}
function ReadString(const ASection, AIdent, ADefault: string): string; virtual; abstract;
{ Call ReadInteger to read an integer value from an ini file.
Parameters:
ASection identifies the section in the file that contains the desired key.
AIdent is the name of the key from which to retrieve the value.
ADefault is the integer value to return if the:
<br> Section does not exist.
<br> Key does not exist.
<br> Data value for the key is not assigned.
Return value:
integer value}
function ReadInteger(const ASection, AIdent: string; ADefault: Integer): Integer; virtual; abstract;
{ Call ReadBool to read a Boolean value from an ini file.
Parameters:
ASection identifies the section in the file that contains the desired key.
AIdent is the name of the key from which to retrieve the Boolean value.
ADefault is the Boolean value to return if the:
<br>Section does not exist.
<br>Key does not exist.
<br>Data value for the key is not assigned.
Return value:
Boolean value}
function ReadBool(const ASection, AIdent: string; ADefault: Boolean): Boolean; virtual; abstract;
{ Call ReadStrings to read TStrings.Items values from an ini file.
Count of items reads from APrefix + '_Count' key.
Each item reads from APrefix + IntToStr(ItemIndex) key.
Parameters:
ASection - string
APrefix - string
AStrings - TStrings}
procedure ReadStrings(const ASection, APrefix: string; AStrings: TStrings);
{ Call WriteString to write a string value to an ini file.
Parameters:
ASection identifies the section in the file that contain the key to which to write.
AIdent is the name of the key for which to set a value.
AValue is the string value to write. }
procedure WriteString(const ASection, AIdent, AValue: string); virtual; abstract;
{ Call WriteInteger to write a integer value to an ini file.
Parameters:
ASection identifies the section in the file that contain the key to which to write.
AIdent is the name of the key for which to set a value.
AValue is the integer value to write. }
procedure WriteInteger(const ASection, AIdent: string; AValue: Integer); virtual; abstract;
{ Call WriteBool to write a boolean value to an ini file.
Parameters:
ASection identifies the section in the file that contain the key to which to write.
AIdent is the name of the key for which to set a value.
AValue is the boolean value to write. }
procedure WriteBool(const ASection, AIdent: string; AValue: Boolean); virtual; abstract;
{ Call WriteStrings to write a TStrings.Items to an ini file.
Parameters:
ASection identifies the section in the file that contain the key to which to write.
AStrings is the reference to stored TStrings object.
APrefix Count of items stored to APrefix + '_Count' key,
Each item stored to APrefix + IntToStr(ItemIndex) key. }
procedure WriteStrings(const ASection, APrefix: string; AStrings: TStrings);
{ Call EraseSection to remove a section, all its keys,
and their data values from an ini file.
Parameters:
ASection identifies the ini file section to remove. If
a section cannot be removed, an exception is raised. }
procedure EraseSection(const ASection: string); virtual; abstract;
{ Use SectionExists to determine whether a section exists within the ini file specified
in FileName.
Parameters:
ASection is the ini file section SectionExists determines the existence of.
Return value:
Boolean. SectionExists returns a Boolean value that indicates whether the section in question exists. }
function SectionExists(const ASection: string): Boolean; virtual; abstract;
{ Use ValueExists to determine whether a key exists in the ini file specified in FileName.
Parameters:
ASection is the section in the ini file in which to search for the key.
AIdent is the name of the key to search for.
Return value:
ValueExists returns a boolean value that indicates whether the key exists
in the specified section. }
function ValueExists(const ASection, AIdent: string): Boolean; virtual; abstract;
{ Path identifies file name of ini file for TvgrIniFileStorage or
registry path relative to HKEY_CURRENT_USER for TvgrRegistryStorage.
This property initializated in constructor. }
property Path: string read FPath;
end;
/////////////////////////////////////////////////
//
// TvgrIniFileStorage
//
/////////////////////////////////////////////////
TvgrIniFileStorage = class(TvgrIniStorage)
protected
FIniFile: TIniFile;
procedure InternalInit; override;
public
destructor Destroy; override;
function ReadString(const ASection, AIdent, ADefault: string): string; override;
function ReadInteger(const ASection, AIdent: string; ADefault: Integer): Integer; override;
function ReadBool(const ASection, AIdent: string; ADefault: Boolean): Boolean; override;
procedure WriteString(const ASection, AIdent, AValue: string); override;
procedure WriteInteger(const ASection, AIdent: string; AValue: Integer); override;
procedure WriteBool(const ASection, AIdent: string; AValue: Boolean); override;
procedure EraseSection(const ASection: string); override;
function SectionExists(const ASection: string): Boolean; override;
function ValueExists(const ASection, AIdent: string): Boolean; override;
{ Reference to internal TIniFile object. }
property IniFile: TIniFile read FIniFile;
end;
/////////////////////////////////////////////////
//
// TvgrRegistryStorage
//
/////////////////////////////////////////////////
TvgrRegistryStorage = class(TvgrIniStorage)
private
FRegistry: TRegIniFile;
protected
procedure InternalInit; override;
public
destructor Destroy; override;
function ReadString(const ASection, AIdent, ADefault: string): string; override;
function ReadInteger(const ASection, AIdent: string; ADefault: Integer): Integer; override;
function ReadBool(const ASection, AIdent: string; ADefault: Boolean): Boolean; override;
procedure WriteString(const ASection, AIdent, AValue: string); override;
procedure WriteInteger(const ASection, AIdent: string; AValue: Integer); override;
procedure WriteBool(const ASection, AIdent: string; AValue: Boolean); override;
procedure EraseSection(const ASection: string); override;
function SectionExists(const ASection: string): Boolean; override;
function ValueExists(const ASection, AIdent: string): Boolean; override;
{ Reference to internal TRegIniFile object. }
property Registry: TRegIniFile read FRegistry;
end;
implementation
uses
vgr_Functions;
/////////////////////////////////////////////////
//
// TvgrIniStorage
//
/////////////////////////////////////////////////
constructor TvgrIniStorage.Create(const APath: string);
begin
inherited Create;
FPath := APath;
InternalInit;
end;
procedure TvgrIniStorage.ReadStrings(const ASection, APrefix: string; AStrings: TStrings);
var
I, N: Integer;
begin
if ValueExists(ASection, APrefix + '_Count') then
begin
AStrings.Clear;
N := ReadInteger(ASection, APrefix + '_Count', 0);
for I := 0 to N - 1 do
AStrings.Add(ReadString(ASection, APrefix + IntToStr(I), ''));
end;
end;
procedure TvgrIniStorage.WriteStrings(const ASection, APrefix: string; AStrings: TStrings);
var
I: Integer;
begin
WriteInteger(ASection, APrefix + '_Count', AStrings.Count);
for I := 0 to AStrings.Count - 1 do
WriteString(ASection, APrefix + IntToStr(I), AStrings[I]);
end;
/////////////////////////////////////////////////
//
// TvgrIniFileStorage
//
/////////////////////////////////////////////////
destructor TvgrIniFileStorage.Destroy;
begin
FreeAndNil(FIniFile);
inherited;
end;
procedure TvgrIniFileStorage.InternalInit;
begin
FIniFile := TIniFile.Create(Path);
end;
function TvgrIniFileStorage.ReadString(const ASection, AIdent, ADefault: string): string;
begin
Result := IniFile.ReadString(ASection, AIdent, ADefault);
end;
function TvgrIniFileStorage.ReadInteger(const ASection, AIdent: string; ADefault: Integer): Integer;
begin
Result := IniFile.ReadInteger(ASection, AIdent, ADefault);
end;
function TvgrIniFileStorage.ReadBool(const ASection, AIdent: string; ADefault: Boolean): Boolean;
begin
Result := IniFile.ReadBool(ASection, AIdent, ADefault);
end;
procedure TvgrIniFileStorage.WriteString(const ASection, AIdent, AValue: string);
begin
IniFile.WriteString(ASection, AIdent, AValue);
end;
procedure TvgrIniFileStorage.WriteInteger(const ASection, AIdent: string; AValue: Integer);
begin
IniFile.WriteInteger(ASection, AIdent, AValue);
end;
procedure TvgrIniFileStorage.WriteBool(const ASection, AIdent: string; AValue: Boolean);
begin
IniFile.WriteBool(ASection, AIdent, AValue);
end;
procedure TvgrIniFileStorage.EraseSection(const ASection: string);
begin
IniFile.EraseSection(ASection);
end;
function TvgrIniFileStorage.SectionExists(const ASection: string): Boolean;
begin
Result := IniFile.SectionExists(ASection);
end;
function TvgrIniFileStorage.ValueExists(const ASection, AIdent: string): Boolean;
begin
Result := IniFile.ValueExists(ASection, AIdent);
end;
/////////////////////////////////////////////////
//
// TvgrRegistryStorage
//
/////////////////////////////////////////////////
destructor TvgrRegistryStorage.Destroy;
begin
if FRegistry <> nil then
FreeAndNil(FRegistry);
inherited;
end;
procedure TvgrRegistryStorage.InternalInit;
begin
FRegistry := TRegIniFile.Create(Path);
end;
function TvgrRegistryStorage.ReadString(const ASection, AIdent, ADefault: string): string;
begin
Result := Registry.ReadString(ASection, AIdent, ADefault);
end;
function TvgrRegistryStorage.ReadInteger(const ASection, AIdent: string; ADefault: Integer): Integer;
begin
Result := Registry.ReadInteger(ASection, AIdent, ADefault);
end;
function TvgrRegistryStorage.ReadBool(const ASection, AIdent: string; ADefault: Boolean): Boolean;
begin
Result := Registry.ReadBool(ASection, AIdent, ADefault);
end;
procedure TvgrRegistryStorage.WriteString(const ASection, AIdent, AValue: string);
begin
Registry.WriteString(ASection, AIdent, AValue);
end;
procedure TvgrRegistryStorage.WriteInteger(const ASection, AIdent: string; AValue: Integer);
begin
Registry.WriteInteger(ASection, AIdent, AValue);
end;
procedure TvgrRegistryStorage.WriteBool(const ASection, AIdent: string; AValue: Boolean);
begin
Registry.WriteBool(ASection, AIdent, AValue);
end;
procedure TvgrRegistryStorage.EraseSection(const ASection: string);
begin
Registry.EraseSection(ASection);
end;
function TvgrRegistryStorage.SectionExists(const ASection: string): Boolean;
begin
Result := Registry.KeyExists(ASection);
end;
function TvgrRegistryStorage.ValueExists(const ASection, AIdent: string): Boolean;
var
Key, OldKey: HKEY;
begin
Key := TRegistryAccess(Registry).GetKey(ASection);
Result := Key <> 0;
if Result then
try
OldKey := Registry.CurrentKey;
TRegistryAccess(Registry).SetCurrentKey(Key);
try
Result := Registry.ValueExists(AIdent);
finally
TRegistryAccess(Registry).SetCurrentKey(OldKey);
end;
finally
RegCloseKey(Key);
end
end;
end.
|
unit uOraTableExt;
interface
uses
uAbstractTableAccess, uSqlFormat_Oracle, DB, DbTables, Classes, SysUtils;
type
TOraTableExt = class(TOracleTable)
private
function getPhysAttrClauseString(AInit, ANext, APctIncrease, APctFree, APctUsed: integer): string;
function GetExists: Boolean;
procedure SetIndexDefs(Value: TIndexDefs);
procedure GetIndexOptionsFromConstraints;
procedure AddIndexOption(const AIndexName: string;
AOption: TIndexOption);
public
property TableId: integer read FTableId write FTableId;
property StorageInit: integer read FStorageInit write FStorageInit;
property StorageNext: integer read FStorageNext write FStorageNext;
property StoragePctIncrease: integer read FStoragePctIncrease write FStoragePctIncrease;
property StoragePctIndex: integer read FStoragePctIndex write FStoragePctIndex;
property StoragePctFree: integer read FStoragePctFree write FStoragePctFree;
property StoragePctUsed: integer read FStoragePctUsed write FStoragePctUsed;
property IndexTableSpace: string read FIndexTableSpace write FIndexTableSpace;
property DDLChange: boolean read FDDLChange write FDDLChange;
procedure CreateIndex(AName: string; const AFields: string;
AOptions: TIndexOptions; AStorageClause: string = '');
procedure CreateTable;
procedure DeleteTable;
procedure RenameTable(const ANewTableName: string);
procedure EmptyTable;
procedure AddIndex(const AName, AFields: string;
AOptions: TIndexOptions;
const ADescFields: string = '');
procedure DeleteIndex(const AName: string);
property IndexDefs: TIndexDefs read FIndexDefs write SetIndexDefs;
property IndexName: string read GetIndexName write SetIndexName;
end;
implementation
const
CInvalidSynonymSource = 'Invalid synonym source view ''%s''';
const
CSelectEditable = 'SELECT DT.ROWID, DT.* FROM %s DT';
CSelectReadOnly = 'SELECT DT.* FROM %s DT';
CBaseSelect = 'SELECT %sDT.* FROM %s DT ';
//----------------------------------------------------------------------------
procedure TOraTableExt.CreateTable;
function nExistsUniqueConstraint(const AFieldName: string): boolean;
var
j: integer;
begin
Result := false;
for j := 0 to IndexDefs.Count - 1 do
with IndexDefs[j] do
if (Fields = AFieldName) and ((Options * [ixUnique, ixPrimary]) <> []) then
begin
Result := true;
break;
end;
end;
var
lS: string;
i, lNumAutoinc: integer;
lMInitial, lMNext: integer;
lIdxStorage: string;
begin
ToUpperCase(FieldDefs);
ToUpperCase(IndexDefs);
// no inherited (defined here)
lNumAutoInc := 0;
for i := 0 to FieldDefs.Count - 1 do
if FieldDefs[i].DataType = ftAutoInc then
begin
inc(lNumAutoInc);
if lNumAutoInc > 1 then
raise EIntern.fire(self, 'only 1 AutoInc-field allowed');
end;
lS := 'CREATE TABLE ' + TableName + ' (';
for i := 0 to FieldDefs.Count - 1 do
begin
with FieldDefs[i] do
begin
lS := ls + getQuotedName(Name) + ' ' + FSqlFormat.getDataTypeString(DataType, Size);
if Required or (DataType = ftAutoInc) then
lS := ls + ' NOT NULL ';
if (DataType = ftAutoInc) and (not nExistsUniqueConstraint(Name)) then
lS := ls + ' UNIQUE ';
end;
if i < FieldDefs.Count - 1 then
lS := ls + ', ';
end;
lS := lS + ') ' + getPhysAttrClauseString(lMInitial, lMNext, StoragePctIncrease, StoragePctFree, StoragePctUsed);
...
for i := 0 to IndexDefs.Count - 1 do
with IndexDefs[i] do
CreateIndex(Name, Fields, Options, lIdxStorage);
...
end;
//----------------------------------------------------------------------------
procedure TOraTableExt.AddIndex(const AName, AFields: string;
AOptions: TIndexOptions; const ADescFields: string);
begin
// no inherited (defined here)
CreateIndex(AName, AFields, AOptions,
getPhysAttrClauseString(CStorageInit, CStorageNext, CStoragePctIncrease, StoragePctFree, CNoStoragePctUsed));
with IndexDefs.AddIndexDef do
begin
Name := AName;
Fields := AFields;
Options := AOptions;
DescFields := ADescFields;
end;
end;
//----------------------------------------------------------------------------
// C,PS: truncate table used
procedure TOraTableExt.EmptyTable;
begin
// no inherited (defined here)
GetExecutedQuery('TRUNCATE TABLE ' + TableName);
Refresh;
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TOraTableExt.RetrieveIndexInformation;
function nGetIndexQuery: string;
begin
Result :=
'SELECT ' +
'UI.INDEX_NAME, ' +
'UI.UNIQUENESS, ' +
'UC.COLUMN_NAME, ' +
'UC.DESCEND ' +
'FROM ' + FNameIndexes + ' UI, ' + FNameInd_Columns + ' UC ' +
'WHERE UI.TABLE_NAME = ''' + TableName + ''' AND ' +
'UI.INDEX_NAME = UC.INDEX_NAME';
end;
var
lQIndices: TDataSet;
lIndex: TIndexDef;
lIndexNames: TStringList;
lIndexName, lFieldName: string;
lIndexOptions: TIndexOptions;
begin
IndexDefs.Clear; //B5432
lQIndices := GetExecutedQuery(nGetIndexQuery);
lIndexNames := TStringList.Create;
try
with lQIndices do
begin
first;
while not eof do
begin
lIndexName := Fields[CIdx_INDEX_NAME].AsString;
lFieldName := Fields[CIdx_COLUMN_NAME].AsString;
if not lIndexNames.IndexOf(lIndexName) >= 0 then
begin
lIndexOptions := [];
if Fields[CIdx_UNIQUENESS].AsString = 'UNIQUE' then
lIndexOptions := [ixUnique];
lIndexNames.Add(lIndexName);
IndexDefs.Add(lIndexName, lFieldName, lIndexOptions);
end
else
begin
lIndex := IndexDefs.Find(lIndexName);
lIndex.Fields := lIndex.Fields + ';' + lFieldName;
end;
next;
end;
end;
finally
FreeAndNil(lIndexNames);
end;
GetIndexOptionsFromConstraints;
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TOraTableExt.AddIndexOption(const AIndexName: string; AOption: TIndexOption);
var
lDef: TIndexDef;
begin
lDef := IndexDefs.Find(AIndexName);
checkAssigned(lDef, 'No indexDefs found for ' + AIndexName);
lDef.Options := lDef.Options + [AOption];
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TOraTableExt.GetIndexOptionsFromConstraints;
const
CConstraintPrimary = 'P';
CConstraintUnique = 'U';
CIdxIndexName = 0;
CIdxConstraintType = 1;
var
lQConstraints: TDataSet;
begin
lQConstraints := GetExecutedQuery(
'SELECT ' +
'INDEX_NAME, CONSTRAINT_TYPE ' +
'FROM ' + FNameConstraints + ' WHERE ' +
'TABLE_NAME = ''' + TableName + '''' +
' AND INDEX_NAME IS NOT NULL '
);
with lQConstraints do
begin
first;
while not eof do
begin
if Fields[CIdxConstraintType].AsString = CConstraintPrimary then
AddIndexOption(Fields[CIdxIndexName].AsString, ixPrimary)
else
if Fields[CIdxConstraintType].AsString = CConstraintUnique then
AddIndexOption(Fields[CIdxIndexName].AsString, ixUnique);
next;
end;
end;
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TOraTableExt.AddIndexOption(const AIndexName: string; AOption: TIndexOption);
var
lDef: TIndexDef;
begin
lDef := IndexDefs.Find(AIndexName);
checkAssigned(lDef, 'No indexDefs found for ' + AIndexName);
lDef.Options := lDef.Options + [AOption];
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TOraTableExt.CreateIndex(AName: string; const AFields: string;
AOptions: TIndexOptions; AStorageClause: string = '');
var
lQuery, lCstIndex: string;
begin
// no inherited (defined here)
if IndexTableSpace <> '' then
AStorageClause := 'TABLESPACE ' + IndexTableSpace + ' ' + AStorageClause;
lCstIndex :=
' USING INDEX (CREATE UNIQUE INDEX ' + AName + ' ON ' + TableName + //B2548
' (' + IdxFields2Sql(AFields) + ') ' + AStorageClause + ' )';
if (ixPrimary in AOptions) then
begin
if AName = '' then
AName := CProviderTableIndexPfx + intToStr(TableId) + 'PRIMARY';
lQuery := 'ALTER TABLE ' + TableName + ' ADD CONSTRAINT ' + AName +
' PRIMARY KEY ' + '(' + IdxFields2Sql(AFields) + ') ' + lCstIndex
end
else
...
end;
GetExecutedQuery(lQuery);
end;
//----------------------------------------------------------------------------
// N,PS:
function TOraTableExt.IdxFields2Sql(const AFields: string): string;
var
i: integer;
begin
// no inherited (defined here)
with TStringList.Create do
try
Delimiter := CIndexFieldsDelimiter;
DelimitedText := AFields;
Result := '';
for i := 0 to Count - 1 do
Result := SeqStr(Result, COraQueryFieldsDelimiter, getQuotedName(Strings[i]));
finally
Free;
end;
end;
//----------------------------------------------------------------------------
// N,PS:
function TOraTableExt.getPhysAttrClauseString(AInit, ANext, APctIncrease, APctFree, APctUsed: integer): string;
begin
// no inherited (defined here)
Result := '';
if (APctFree <> CStoragePctFree) then
Result := Result + ' PCTFREE ' + IntToStr(APctFree);
if (APctUsed <> CNoStoragePctUsed) and (APctUsed <> CStoragePctUsed) then // ps changed B1408
Result := Result + ' PCTUSED ' + IntToStr(APctUsed);
...
end;
//----------------------------------------------------------------------------
// N,PS:
function TOraTableExt.getAutoIncTriggerName(ATableId: integer): string;
begin
// no inherited (private)
Result := CPfx_Triggers_AutoincFields + intToStr(ATableId);
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TOraTableExt.CreateAutoIncTrigger(const ATriggerName, ATableName,
ASequenceName, AFieldName: string);
begin
// no inherited (private)
GetExecutedQuery(
'CREATE OR REPLACE TRIGGER ' + ATriggerName + ' BEFORE INSERT ON ' + ATableName + ' ' +
'FOR EACH ROW ' +
'BEGIN ' +
' SELECT ' + ASequenceName + '.NEXTVAL INTO :NEW.' + AFieldName + ' FROM DUAL; ' +
'END;'
);
end;
end.
|
program cantidadDeDigitos (input,output);
var
numero, numDigitos : integer;
procedure pedirNumero(var num: integer);
begin
writeln('Introduzca numero:');
readln(num);
end;
function cantidadDigitos(num:integer):integer;
begin
if ((num div 10) = 0) then
cantidadDigitos := 1
else
cantidadDigitos := 1 + cantidadDigitos(num div 10);
end;
begin
pedirNumero(numero);
numDigitos := cantidadDigitos(numero);
writeln('El numero ',numero,' tiene ',numDigitos,' digitos.');
readln();
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.ActnColorMaps;
interface
uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.ActnMan;
type
{ TStandardColorMap }
TStandardColorMap = class(TCustomActionBarColorMap)
protected
procedure SetColor(const Value: TColor); override;
public
procedure UpdateColors; override;
published
// HighlightColor and UnusedColor should stream before Color
property HighlightColor;
property UnusedColor;
property BtnFrameColor default clBtnFace;
property BtnSelectedColor default clBtnFace;
property BtnSelectedFont default clWindowText;
property Color default clBtnFace;
property DisabledFontColor default clGrayText;
property DisabledFontShadow default clBtnHighlight;
property FontColor default clWindowText;
property HotColor default clDefault;
property HotFontColor default clDefault;
property MenuColor default clBtnFace;
property FrameTopLeftInner default clBtnHighlight;
property FrameTopLeftOuter default cl3DLight;
property FrameBottomRightInner default clBtnShadow;
property FrameBottomRightOuter default cl3DDkShadow;
property DisabledColor default clDefault;
property SelectedColor default clMenuHighlight;
property SelectedFontColor default clHighlightText;
property ShadowColor default clBtnShadow;
property OnColorChange;
end;
{ TXPColorMap }
const
cXPFrameOuter = $007A868A;
cXPBtnFrameColor = $00C66931;
cXPSelectedColor = $00EFD3C6;
type
TXPColorMap = class(TCustomActionBarColorMap)
public
procedure UpdateColors; override;
published
property ShadowColor default cl3DDkShadow;
property Color default clBtnFace;
property DisabledColor default clGray;
property DisabledFontColor default clGrayText;
property DisabledFontShadow default clBtnHighlight;
property FontColor default clWindowText;
property HighlightColor;
property HotColor default clDefault;
property HotFontColor default clDefault;
property MenuColor default clWindow;
property FrameTopLeftInner default clWhite;
property FrameTopLeftOuter default cXPFrameOuter;
property FrameBottomRightInner default clWhite;
property FrameBottomRightOuter default cXPFrameOuter;
property BtnFrameColor default cXPBtnFrameColor;
property BtnSelectedColor default clWhite;
property BtnSelectedFont default clWindowText;
property SelectedColor default cXPSelectedColor;
property SelectedFontColor default clBlack;
property UnusedColor;
property OnColorChange;
end;
{ TTwilightColorMap }
TTwilightColorMap = class(TCustomActionBarColorMap)
public
procedure UpdateColors; override;
published
property Color default clBlack;
property DisabledFontColor default clGrayText;
property DisabledFontShadow default clBlack;
property FontColor default clWhite;
property HighlightColor;
property HotColor default clDefault;
property HotFontColor default clWhite;
property FrameTopLeftInner default clBlack;
property FrameTopLeftOuter default cl3DDkShadow;
property FrameBottomRightInner default clBlack;
property FrameBottomRightOuter default cl3DDkShadow;
property BtnFrameColor default cl3DDkShadow;
property BtnSelectedColor default cl3DDkShadow;
property BtnSelectedFont default clBlack;
property MenuColor default clBlack;
property DisabledColor default clDefault;
property SelectedColor default cl3dDkShadow;
property SelectedFontColor default clBlack;
property ShadowColor default clBlack;
property UnusedColor default clBlack;
property OnColorChange;
end;
TThemedColorMap = class(TCustomActionBarColorMap)
public
procedure UpdateColors; override;
published
property ShadowColor default cl3DDkShadow;
property Color default clMenuBar;
property DisabledColor default clGray;
property DisabledFontColor default clGrayText;
property DisabledFontShadow default $00FCF7F4;
property FontColor default clBlack;
property HighlightColor;
property HotColor default clDefault;
property HotFontColor default clDefault;
property MenuColor default clMenu;
property FrameTopLeftInner default $00FCF7F4;
property FrameTopLeftOuter default $00646464;
property FrameBottomRightInner default $00FCF7F4;
property FrameBottomRightOuter default $00646464;
property BtnFrameColor default $00646464;
property BtnSelectedColor default clMenuHighlight;
property BtnSelectedFont default clWindowText;
property SelectedColor default clMenuHighlight;
property SelectedFontColor default clBlack;
property UnusedColor;
property OnColorChange;
end;
implementation
uses Vcl.GraphUtil, Vcl.Themes, Winapi.UxTheme;
{ TStandardColorMap }
procedure TStandardColorMap.SetColor(const Value: TColor);
begin
if Value <> Color then
begin
HighlightColor := GetHighlightColor(Value);
UnusedColor := GetHighlightColor(Value, 10);
end;
inherited;
end;
procedure TStandardColorMap.UpdateColors;
var
FlatMenus: BOOL;
begin
inherited;
FlatMenus := False;
SystemParametersInfo(SPI_GETFLATMENU, 0, {$IFNDEF CLR}@{$ENDIF}FlatMenus, 0);
BtnFrameColor := clBtnFace;
BtnSelectedColor := clBtnFace;
BtnSelectedFont := clWindowText;
Color := clBtnFace;
if FlatMenus then
MenuColor := clMenu
else
MenuColor := clBtnFace;
DisabledFontColor := clGrayText;
DisabledFontShadow := clBtnHighlight;
DisabledColor := clDefault;
FontColor := clWindowText;
FrameTopLeftInner := clBtnHighlight;
FrameTopLeftOuter := cl3DLight;
FrameBottomRightInner := clBtnShadow;
FrameBottomRightOuter := cl3DDkShadow;
HighlightColor := GetHighlightColor(Color);
HotColor := clDefault;
HotFontColor := clDefault;
if FlatMenus then
SelectedColor := clMenuHighlight
else
SelectedColor := clHighlight;
SelectedFontColor := clHighlightText;
ShadowColor := clBtnShadow;
UnusedColor := GetHighlightColor(Color, 18);
end;
{ TXPColorMap }
procedure TXPColorMap.UpdateColors;
begin
inherited;
Color := clBtnFace;
MenuColor := clWindow;
BtnFrameColor := cXPBtnFrameColor;
BtnSelectedColor := clBtnFace;
BtnSelectedFont := clWindowText;
DisabledFontColor := clGrayText;
DisabledFontShadow := clBtnHighlight;
DisabledColor := clGray;
FontColor := clWindowText;
FrameTopLeftInner := clWhite;
FrameTopLeftOuter := cXPFrameOuter;
FrameBottomRightInner := clWhite;
FrameBottomRightOuter := cXPFrameOuter;
HighlightColor := GetHighLightColor(clBtnFace, 15);
HotColor := clDefault;
HotFontColor := clDefault;
SelectedColor := cXPSelectedColor;
SelectedFontColor := clBlack;
ShadowColor := cl3DDkShadow;
UnusedColor := GetHighLightColor(clBtnFace, 15);
end;
{ TTwilightColorMap }
procedure TTwilightColorMap.UpdateColors;
begin
inherited;
Color := clBlack;
MenuColor := clBlack;
DisabledFontColor := clGrayText;
DisabledFontShadow := clBlack;
DisabledColor := cl3DDkShadow;
FontColor := clWhite;
FrameTopLeftInner := clBlack;
FrameTopLeftOuter := cl3DDkShadow;
FrameBottomRightInner := clBlack;
FrameBottomRightOuter := cl3DDkShadow;
HighlightColor := clBlack;
HotColor := clDefault;
HotFontColor := clWhite;
BtnSelectedColor := cl3DDkShadow;
BtnSelectedFont := clBlack;
SelectedColor := cl3DDkShadow;
SelectedFontColor := clBlack;
ShadowColor := clBlack;
UnusedColor := clBlack;
end;
{ TThemedColorMap }
procedure TThemedColorMap.UpdateColors;
var
LColor: TColor;
LStyle: TCustomStyleServices;
LDetails: TThemedElementDetails;
begin
inherited;
// Set default colors (based on Vista Aero Theme)
Color := clMenuBar;
MenuColor := clMenu;
BtnFrameColor := $00646464;
BtnSelectedColor := clMenuHighlight;
BtnSelectedFont := clWindowText;
DisabledFontColor := clGrayText;
DisabledFontShadow := $00FCF7F4;
DisabledColor := clGray;
FontColor := clBlack;
FrameTopLeftInner := $00FCF7F4;
FrameTopLeftOuter := $00646464;
FrameBottomRightInner := $00FCF7F4;
FrameBottomRightOuter := $00646464;
HighlightColor := GetHighLightColor(clBtnFace, 15);
HotColor := clDefault;
HotFontColor := clDefault;
SelectedColor := clMenuHighlight;
SelectedFontColor := clBlack;
ShadowColor := cl3DDkShadow;
UnusedColor := GetHighLightColor(clBtnFace, 15);
// Retrieve themed button colors
LStyle := StyleServices;
LDetails := LStyle.GetElementDetails(tbPushButtonNormal);
if LStyle.GetElementColor(LDetails, ecEdgeDkShadowColor, LColor) and (LColor <> clNone) then
BtnFrameColor := LColor;
if LStyle.GetElementColor(LDetails, ecTextColor, LColor) and (LColor <> clNone) then
FontColor := LColor;
// Retrieve themed menu colors
LDetails := LStyle.GetElementDetails(tmMenuBarBackgroundActive);
if LStyle.GetElementColor(LDetails, ecFillColor, LColor) and (LColor <> clNone) then
Color := LColor;
LDetails := LStyle.GetElementDetails(tmPopupItemHot);
if LStyle.GetElementColor(LDetails, ecTextColor, LColor) and (LColor <> clNone) then
begin
BtnSelectedFont := LColor;
SelectedFontColor := LColor;
end;
LDetails := LStyle.GetElementDetails(tmPopupItemDisabled);
if LStyle.GetElementColor(LDetails, ecTextColor, LColor) and (LColor <> clNone) then
DisabledFontColor := LColor;
if LStyle.GetElementColor(LDetails, ecEdgeHighLightColor, LColor) and (LColor <> clNone) then
DisabledFontShadow := LColor;
LDetails := LStyle.GetElementDetails(tmPopupBackground);
if LStyle.GetElementColor(LDetails, ecEdgeHighLightColor, LColor) and (LColor <> clNone) then
begin
FrameTopLeftInner := LColor;
FrameBottomRightInner := LColor;
end;
if LStyle.GetElementColor(LDetails, ecEdgeDkShadowColor, LColor) and (LColor <> clNone) then
begin
FrameTopLeftOuter := LColor;
FrameBottomRightOuter := LColor;
end;
end;
end.
|
{
Delphi Project Descriptor
=========================
It allow creating:
* Delphi project (*.dpr)
* Delphi unit file (*.pas + *.dfm)
* etc., more delphi stuff in future; such delphi package (*.dpk)
within Lazarus.
Author : x2nie
Years : 2014-05-20
Download/update : https://github.com/x2nie/LazarusDelphiDescriptor
see:
http://forum.lazarus.freepascal.org/index.php/topic,24596.0.html
http://bugs.freepascal.org/view.php?id=26192
Install:
currently, need a patch applied to Lazarus. Download here: http://bugs.freepascal.org/view.php?id=26192
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit delphi_descriptors;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LazIDEIntf, ProjectIntf, Controls, Forms;
type
{ TDelphiApplicationDescriptor }
TDelphiApplicationDescriptor = class(TProjectDescriptor)
public
constructor Create; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function InitProject(AProject: TLazProject): TModalResult; override;
function CreateStartFiles({%H-}AProject: TLazProject): TModalResult; override;
end;
{ TFileDescPascalUnitWithDelphiForm }
TFileDescPascalUnitWithDelphiForm = class(TFileDescPascalUnitWithResource)
public
constructor Create; override;
function GetInterfaceUsesSection: string; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function GetUnitDirectives: string; override;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterProjectFileDescriptor(TFileDescPascalUnitWithDelphiForm.Create,
FileDescGroupName);
RegisterProjectDescriptor(TDelphiApplicationDescriptor.Create);
end;
function FileDescriptorHDForm() : TProjectFileDescriptor;
begin
Result:=ProjectFileDescriptors.FindByName('Delphi Form');
end;
{ TFileDescPascalUnitWithlpForm }
constructor TFileDescPascalUnitWithDelphiForm.Create;
begin
inherited Create;
Name:='Delphi Form';
DefaultResFileExt := '.dfm';
ResourceClass:=TForm;
UseCreateFormStatements:=true;
end;
function TFileDescPascalUnitWithDelphiForm.GetInterfaceUsesSection: string;
begin
Result:='Classes, SysUtils, Forms';
end;
function TFileDescPascalUnitWithDelphiForm.GetLocalizedName: string;
begin
Result:='Delphi Form';
end;
function TFileDescPascalUnitWithDelphiForm.GetLocalizedDescription: string;
begin
Result:='Create a new blank Delphi Form';
end;
function TFileDescPascalUnitWithDelphiForm.GetUnitDirectives: string;
begin
result := inherited GetUnitDirectives();
result := '{$ifdef fpc}'+ LineEnding
+result + LineEnding
+'{$endif}';
end;
{ TProjectApplicationDescriptor }
constructor TDelphiApplicationDescriptor.Create;
begin
inherited;
Name := 'A blank Delphi application';
end;
function TDelphiApplicationDescriptor.CreateStartFiles(
AProject: TLazProject): TModalResult;
begin
Result:=LazarusIDE.DoNewEditorFile(FileDescriptorHDForm,'','',
[nfIsPartOfProject,nfOpenInEditor,nfCreateDefaultSrc]);
end;
function TDelphiApplicationDescriptor.GetLocalizedDescription: string;
begin
Result := 'Delphi Application'+LineEnding+LineEnding
+'A Delphi GUI application compatible with Lazarus.'+LineEnding
+'This files will be automatically maintained by Lazarus.';
end;
function TDelphiApplicationDescriptor.GetLocalizedName: string;
begin
Result := 'Delphi Application';
end;
function TDelphiApplicationDescriptor.InitProject(
AProject: TLazProject): TModalResult;
var
NewSource: String;
MainFile: TLazProjectFile;
begin
Result:=inherited InitProject(AProject);
MainFile:=AProject.CreateProjectFile('project1.dpr');
MainFile.IsPartOfProject:=true;
AProject.AddFile(MainFile,false);
AProject.MainFileID:=0;
AProject.UseAppBundle:=true;
AProject.UseManifest:=true;
AProject.LoadDefaultIcon;
AProject.LazCompilerOptions.SyntaxMode:='Delphi';
// create program source
NewSource:='program Project1;'+LineEnding
+LineEnding
+'{$ifdef fpc}'+LineEnding
+'{$mode delphi}{$H+}'+LineEnding
+'{$endif}'+LineEnding
+LineEnding
+'uses'+LineEnding
+' {$ifdef fpc}'+LineEnding
+' {$IFDEF UNIX}{$IFDEF UseCThreads}'+LineEnding
+' cthreads,'+LineEnding
+' {$ENDIF}{$ENDIF}'+LineEnding
+' Interfaces, // this includes the LCL widgetset'+LineEnding
+' {$endif}'+LineEnding
+' Forms'+LineEnding
+' { you can add units after this };'+LineEnding
+LineEnding
+'begin'+LineEnding
//+' RequireDerivedFormResource := True;'+LineEnding
+' Application.Initialize;'+LineEnding
+' Application.Run;'+LineEnding
+'end.'+LineEnding
+LineEnding;
AProject.MainFile.SetSourceText(NewSource,true);
// add lcl pp/pas dirs to source search path
AProject.AddPackageDependency('FCL');
AProject.LazCompilerOptions.Win32GraphicApp:=true;
AProject.LazCompilerOptions.UnitOutputDirectory:='lib'+PathDelim+'$(TargetCPU)-$(TargetOS)';
AProject.LazCompilerOptions.TargetFilename:='project1';
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Test Server }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit ReqImpl;
interface
uses
Windows, Messages, SysUtils, Classes, HTTPApp, WebLib,
ComObj;
type
TWebRequestImpl = class(TInterfacedObject, IWebRequest)
private
FWebRequest: TWebRequest;
FWebResponse: TWebResponse;
FUsingStub: Boolean;
public
constructor Create(AWebRequest: TWebRequest; AWebResponse: TWebResponse;
AUsingStub: Boolean);
function GetFieldByName(const Name: WideString): WideString; safecall;
function ReadClient(var ABuffer: OleVariant; ACount: Integer): Integer; safecall;
function ReadString(var ABuffer: OleVariant; ACount: Integer): Integer; safecall;
function TranslateURI(const Value: WideString): WideString; safecall;
function WriteClient(Buffer: OleVariant): Integer; safecall;
function GetStringVariable(Index: Integer): OleVariant; safecall;
function WriteHeaders(StatusCode: Integer; StatusText: OleVariant;
Headers: OleVariant): WordBool; safecall;
function UsingStub: WordBool; safecall;
end;
function SearchForCoClass(Request: TWebRequest; var ID: string; var ClsID: TGuid): Boolean;
function FileNameToClassID(const AFileName: string; var AGuid: TGUID): Boolean;
implementation
uses WebCat, ActiveX, Variants;
type
TWebRequestCracker = class(TWebRequest);
TWebResponseCracker = class(TWebResponse);
{ TWebRequestImpl}
constructor TWebRequestImpl.Create(AWebRequest: TWebRequest; AWebResponse: TWebResponse;
AUsingStub: Boolean);
begin
FWebRequest := AWebRequest;
FWebResponse := AWebResponse;
FUsingStub := AUsingStub;
inherited Create;
end;
function TWebRequestImpl.GetFieldByName(
const Name: WideString): WideString;
begin
Result := FWebRequest.GetFieldByName(Name);
end;
function StringToVariantArray(const S: string): OleVariant; forward;
function TWebRequestImpl.GetStringVariable(Index: Integer): OleVariant;
begin
Result := StringToVariantArray(TWebRequestCracker(FWebRequest).GetStringVariable(Index));
end;
function TWebRequestImpl.ReadClient(var ABuffer: OleVariant;
ACount: Integer): Integer;
var
P: Pointer;
begin
ABuffer := VarArrayCreate([0, ACount - 1], varByte);
P := VarArrayLock(Result);
try
Result := FWebRequest.ReadClient(P^, ACount);
finally
VarArrayUnlock(Result);
end;
end;
function VariantArrayToString(const V: OleVariant): string;
var
P: Pointer;
Size: Integer;
begin
Result := '';
if VarIsArray(V) and (VarType(V) and varTypeMask = varByte) then
begin
Size := VarArrayHighBound(V, 1) - VarArrayLowBound(V, 1) + 1;
if Size > 0 then
begin
SetLength(Result, Size);
P := VarArrayLock(V);
try
Move(P^, Result[1], Size);
finally
VarArrayUnlock(V);
end;
end;
end;
end;
function StringToVariantArray(const S: string): OleVariant;
var
P: Pointer;
begin
Result := NULL;
if Length(S) > 0 then
begin
Result := VarArrayCreate([0, Length(S) - 1], varByte);
P := VarArrayLock(Result);
try
Move(S[1], P^, Length(S));
finally
VarArrayUnlock(Result);
end;
end;
end;
function TWebRequestImpl.ReadString(var ABuffer: OleVariant;
ACount: Integer): Integer;
var
S: string;
begin
SetLength(S, ACount);
S := FWebRequest.ReadString(ACount);
ABuffer := StringToVariantArray(S);
end;
function TWebRequestImpl.UsingStub: WordBool;
begin
Result := FUsingStub;
end;
function TWebRequestImpl.TranslateURI(
const Value: WideString): WideString;
begin
Result := FWebRequest.TranslateURI(Value);
end;
function TWebRequestImpl.WriteClient(Buffer: OleVariant): Integer;
var
S: string;
P: Pointer;
Size: Integer;
begin
if VarIsType(Buffer, varOleStr) then
begin
S := Buffer;
Result := FWebRequest.WriteClient(Pointer(S)^, Length(S));
end
else if VarisType(Buffer, varByte) then
begin
Size := VarArrayHighBound(Buffer, 1) - VarArrayLowBound(Buffer, 1) + 1;
if Size > 0 then
begin
P := VarArrayLock(Buffer);
try
Result := FWebRequest.WriteClient(P^, Size);
finally
VarArrayUnlock(Buffer);
end;
end;
end
else
Assert(False, 'Unknown variant type');
end;
function TWebRequestImpl.WriteHeaders(StatusCode: Integer;
StatusText, Headers: OleVariant): WordBool;
begin
Result := FWebRequest.WriteHeaders(StatusCode, VariantArrayToString(StatusText), VariantArrayToString(Headers));
end;
function SearchForCoClass(Request: TWebRequest; var ID: string; var ClsID: TGuid): Boolean;
var
P: Integer;
begin
ID := Request.PathInfo;
if (Length(ID) > 0) and (ID[1] = '/') then
Delete(ID, 1, 1);
P := Pos('/', ID);
if P > 0 then
Delete(ID, P, MaxInt);
Result := False;
if ID <> '' then
begin
if not Result and (ID[1] = '{') then
begin
try
ClsID := StringToGUID(ID);
Result := True;
except
end;
end;
if not Result and (CompareText(ExtractFileExt(ID), '.exe') = 0) then
begin
Result := FileNameToClassID(ID, ClsID);
end;
if not Result and (CompareText(ExtractFileExt(ID), '.js') <> 0) then
begin
try
ClsID := ProgIDToClassID(ID);
Result := True;
except
end;
end;
end;
end;
function FileNameToClassID(const AFileName: string; var AGuid: TGUID): Boolean;
var
EnumGUID: IEnumGUID;
Fetched: Cardinal;
Rslt: HResult;
CatInfo: ICatInformation;
S: string;
begin
Rslt := CoCreateInstance(CLSID_StdComponentCategoryMgr, nil,
CLSCTX_INPROC_SERVER, ICatInformation, CatInfo);
if Succeeded(Rslt) then
begin
OleCheck(CatInfo.EnumClassesOfCategories(1, @CATID_WebAppServer, 0, nil, EnumGUID));
while EnumGUID.Next(1, AGuid, Fetched) = S_OK do
begin
S := SClsid + GuidToString(AGuid) + '\LocalServer32';
if AnsiCompareFileName(AFileName, ExtractFileName(GetRegStringValue(S, ''))) = 0 then
begin
Result := True;
Exit;
end;
end;
end else
begin
Assert(False);
end;
Result := False;
end;
end.
|
(* WG_Histo: MM 2020
Histo test to evaluate quality of RNG *)
PROGRAM WG_Histo;
USES
{$IFDEF FPC}
Windows,
{$ELSE}
WinTypes, WinProcs,
{$ENDIF}
Strings, WinCrt,
WinGraph,
RandUnit;
PROCEDURE HistoTest(dc: HDC; wnd: HWnd; r: TRect); FAR;
CONST
BORDER = 20; (* Padding in pixel *)
SIZE = 5;
MAX = 1000;
VAR
h: array[0..MAX] of integer;
x, y, n, i, randVal: INTEGER;
width, height: INTEGER;
diffValues, maxPerVal: integer;
BEGIN
Randomize;
width := r.right - r.left - 2 * BORDER;
height := r.bottom - r.top - 2 * BORDER;
diffValues := width DIV SIZE;
maxPerVal := height DIV SIZE;
for i := 0 to diffValues do begin
h[i] := 0;
end; (* FOR *)
InitRandSeed(0);
i := 1;
n := diffValues * maxPerVal;
while i <= n do begin
randVal := Random(diffValues);
Inc(h[randVal]);
x := BORDER + randVal * SIZE;
y := BORDER + height - h[randVal] * SIZE;
Ellipse(dc, x, y, x + SIZE, y + SIZE);
if h[randVal] >= maxPerVal then Exit;
Inc(i);
end; (* WHILE *)
END; (*Redraw_Example*)
PROCEDURE Redraw_Example2(dc: HDC; wnd: HWnd; r: TRect); FAR;
BEGIN
(*... draw anything ...*)
END; (*Redraw_Example2*)
PROCEDURE MousePressed_Example(dc: HDC; wnd: HWnd; x, y: INTEGER); FAR;
BEGIN
WriteLn('mouse pressed at: ', x, ', ', y);
(*InvalidateRect(wnd, NIL, TRUE);*)
END; (*MousePressed_Exmple*)
BEGIN (*WG_Test*)
redrawProc := HistoTest;
mousePressedProc := MousePressed_Example;
WGMain;
END. (*WG_Test*)
|
unit FormConnect;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
Buttons, StdCtrls, connection_transaction;
type
{ TConnectForm }
TConnectForm = class(TForm)
BrowseDBPath: TButton;
OkButton: TButton;
CanselButton: TButton;
DBUserName: TLabeledEdit;
DBPassword: TLabeledEdit;
DBPath: TLabeledEdit;
BrowseDBPathDialog: TOpenDialog;
procedure BrowseDBPathClick(Sender: TObject);
procedure CanselButtonClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
end;
var
ConnectForm: TConnectForm;
implementation
{$R *.lfm}
{ TConnectForm }
procedure TConnectForm.FormShow(Sender: TObject);
begin
DBPath.Text := ConTran.DBConnection.DatabaseName;
DBUserName.Text := ConTran.DBConnection.UserName;
DBPassword.Text := '';
ActiveControl := DBPassword;
end;
procedure TConnectForm.BrowseDBPathClick(Sender: TObject);
begin
if BrowseDBPathDialog.Execute then
DBPath.Text := BrowseDBPathDialog.FileName;
end;
procedure TConnectForm.CanselButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
ConnectForm.Hide;
end;
procedure TConnectForm.FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
begin
case Key of
13: OkButtonClick(OkButton);
27: CanselButtonClick(CanselButton);
end;
end;
procedure TConnectForm.OkButtonClick(Sender: TObject);
begin
ModalResult := mrOk;
ConnectForm.Hide;
end;
end.
|
{*****************************************************************************
ApacheInit
The Module Initialization handler is called during the module initialization
phase immediatly after the server is started. This is where your modules will
initialize data, consult configuration files, and do other prep work in the
parent server before any children are forkedoff or threads spawned.
About this demo.
This demo will show how to assign the module initialization handler. It will
Load an ini file and display this data when this module is used.
******************************************************************************}
unit ApacheInit;
interface
uses
{$IFDEF MSWINDOWS}
Windows, Messages,
{$ENDIF}
SysUtils, Classes, HTTPApp, ApacheApp, HTTPD,inifiles;
var
//ApacheInit1: TApacheInit;
ConfigFile: String;
IBLocal_settings: TStringList;
Interbase_Drivers: TStringList;
IniFile: TIniFile;
implementation
procedure Apache_OnInit (server: Pserver_rec; pool: Ppool);
begin
// OK, it's not an error but It's a good place to log this event
// to show that this procedure is in fact being assigned.
ap_log_error(server.error_fname , APLOG_EMERG, APLOG_ALERT, server,
PChar('TWebModule1->Apache_OnInit'));
// Load the InterbaseDrivers from the dbxdrivers file......
{$IFDEF MSWINDOWS}
ConfigFile:= 'C:\Program Files\Common Files\Borland Shared\DBExpress\dbxdrivers.ini';
{$ELSE IFDEF LINUX}
ConfigFile:= '/usr/local/etc/dbxdrivers.conf';
{$ENDIF}
IniFile:=TInifile.Create(ConfigFile);
Interbase_Drivers:= TStringLIst.Create;
Inifile.ReadSectionValues('INTERBASE',Interbase_Drivers);
// Load the IBLocal Settings from the dbxconnections file
{$IFDEF MSWINDOWS}
ConfigFile:= 'C:\Program Files\Common Files\Borland Shared\DBExpress\dbxconnections.ini';
{$ELSE IFDEF LINUX}
ConfigFile:= '/usr/local/etc/dbxconnections.conf';
{$ENDIF}
IniFile:=TInifile.Create(ConfigFile);
IBLocal_Settings:= TStringLIst.Create;
Inifile.ReadSectionValues('IBLocal',IBLocal_Settings);
// done
IniFile.Free;
end;
initialization
// make the assignments here
ApacheOnInit :=Apache_OnInit;
// Other available Handlers.......
//ApacheOnChildInit
//ApacheOnChildExit
//ApacheOnCreateDirConfig
//ApacheOnMergeDirConfig
//ApacheOnCreateServerConfig
//ApacheOnMergeServerConfig
//ApacheOnLogger
//ApacheOnFixerUpper
//ApacheOnTypeChecker
//ApacheOnAuthChecker
//ApacheOnCheckUserId
//ApacheOnHeaderParser
//ApacheOnAccessChecker
//ApacheOnPostReadRequest
//ApacheOnTranslateHandler
end.// end Unit
|
unit UDaoContasReceber;
interface
uses uDao, DB, SysUtils, Messages, UContasReceber, UDaoCliente,
UDaoFormaPagamento, UDaoUsuario;
type DaoContasReceber = class(Dao)
private
protected
umaContasReceber : ContasReceber;
umaDaoCliente : DaoCliente;
umaDaoUsuario : DaoUsuario;
umaDaoFormaPagamento : DaoFormaPagamento;
public
Constructor CrieObjeto;
Destructor Destrua_se;
function Salvar(obj:TObject): string; override;
function GetDS : TDataSource; override;
function Carrega(obj:TObject): TObject; override;
function Buscar(obj : TObject) : Boolean; override;
function Excluir(obj : TObject) : string ; override;
function VerificarNota (obj : TObject) : Boolean;
function VerificarContas (obj : TObject) : Boolean;
function VerificarParcelas (obj : TObject) : Boolean;
procedure VerificarVenda (obj : TObject);
function ContarContasReceber(obj : TObject) : Integer;
procedure AtualizaGrid;
procedure Ordena(campo: string);
end;
implementation
uses UVenda, UCtrlVenda;
{ DaoContasReceber }
function DaoContasReceber.Buscar(obj: TObject): Boolean;
var
prim: Boolean;
sql, e, onde: string;
umaContasReceber: ContasReceber;
begin
e := ' and ';
onde := ' where';
prim := true;
umaContasReceber := ContasReceber(obj);
sql := 'select * from contareceber conta';
if umaContasReceber.getUmCliente.getNome_RazaoSoCial <> '' then
begin
//Buscar a descricao do cliente na tabela cliente
sql := sql+' INNER JOIN cliente c ON conta.idcliente = c.idcliente and c.nome_razaosocial like '+quotedstr('%'+umaContasReceber.getUmCliente.getNome_RazaoSoCial+'%');
if (prim) and (umaContasReceber.getStatus <> '')then
begin
prim := false;
sql := sql+onde;
end
end;
if umaContasReceber.getStatus <> '' then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end;
sql := sql+' conta.status like '+quotedstr('%'+umaContasReceber.getStatus+'%'); //COLOCA CONDIÇAO NO SQL
end;
if (DateToStr(umaContasReceber.getDataEmissao) <> '30/12/1899') and (datetostr(umaContasReceber.getDataPagamento) <> '30/12/1899') then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end
else
sql := sql+e;
sql := sql+' dataemissao between '+QuotedStr(DateToStr(umaContasReceber.getDataEmissao))+' and '+QuotedStr(DateToStr(umaContasReceber.getDataPagamento));
end;
with umDM do
begin
QContasReceber.Close;
QContasReceber.sql.Text := sql+' order by numnota, serienota, numparcela';
QContasReceber.Open;
if QContasReceber.RecordCount > 0 then
result := True
else
result := false;
end;
end;
function DaoContasReceber.VerificarNota(obj: TObject): Boolean;
var sql : string;
umaContaReceber : ContasReceber;
i : integer;
begin
umaContaReceber := ContasReceber(obj);
for i := 1 to 2 do
begin
if i = 1 then
umaContaReceber.setStatus('RECEBIDA')
else
umaContaReceber.setStatus('PENDENTE');
sql := 'select * from contareceber where numnota = '+IntToStr(umaContaReceber.getNumNota)+' and serienota = '''+umaContaReceber.getSerieNota+ ''' and idcliente = '+IntToStr(umaContaReceber.getUmCliente.getId)+' and status = '''+umaContaReceber.getStatus+'''';
with umDM do
begin
QContasReceber.Close;
QContasReceber.sql.Text := sql+' order by numnota, serienota, numparcela';
QContasReceber.Open;
if QContasReceber.RecordCount > 0 then
begin
result := True;
Self.AtualizaGrid;
Exit;
end
else
result := false;
end;
end;
Self.AtualizaGrid;
end;
procedure DaoContasReceber.VerificarVenda (obj : TObject);
var umaCtrlVenda : CtrlVenda;
umaVenda : Venda;
begin
umaContasReceber := ContasReceber(obj);
umaCtrlVenda := CtrlVenda.CrieObjeto;
umaVenda := Venda.CrieObjeto;
umaVenda.setNumNota(umaContasReceber.getNumNota);
umaVenda.setSerieNota(umaContasReceber.getSerieNota);
if (umaCtrlVenda.VerificarNota(umaVenda)) then
begin
umaCtrlVenda.Carrega(umaVenda);
umaVenda.setStatus('CANCELADA');
umaVenda.setTipo(False);
umaCtrlVenda.Salvar(umaVenda)
end;
end;
function DaoContasReceber.VerificarContas(obj: TObject): Boolean;
var sql : string;
umaContaReceber : ContasReceber;
i : Integer;
begin
umaContaReceber := ContasReceber(obj);
sql := 'select * from contareceber where numnota = '+IntToStr(umaContaReceber.getNumNota)+' and serienota = '''+umaContaReceber.getSerieNota+ ''' and status = '''+umaContaReceber.getStatus+'''';
with umDM do
begin
QContasReceber.Close;
QContasReceber.sql.Text := sql+' order by numnota, serienota, numparcela';
QContasReceber.Open;
if QContasReceber.RecordCount > 0 then
result := True
else
result := false;
end;
Self.AtualizaGrid;
end;
function DaoContasReceber.VerificarParcelas (obj : TObject) : Boolean;
var umaContaReceber : ContasReceber;
begin
umaContaReceber := ContasReceber(obj);
with umDM do
begin
QContasReceber.Close;
QContasReceber.sql.Text := 'select * from contareceber where numnota = '+IntToStr(umaContaReceber.getNumNota)+' and serienota = '''+umaContaReceber.getSerieNota+ ''' order by numparcela';;
QContasReceber.Open;
while not QContasReceber.Eof do
begin
if (QContasReceberstatus.AsString = 'PENDENTE') then
if(umaContaReceber.getNumParcela = QContasRecebernumparcela.AsInteger) then
begin
Result := True;
Break;
end
else
begin
Result := False;
Break;
end;
QContasReceber.Next;
end;
Self.AtualizaGrid;
end;
end;
function DaoContasReceber.ContarContasReceber(obj : TObject) : Integer;
var count : Integer;
begin
count := 0;
umaContasReceber := ContasReceber(obj);
with umDM do
begin
QContasReceber.Close;
QContasReceber.SQL.Text := 'select * from contareceber where numnota = '+IntToStr(umaContasReceber.getNumNota)+ ' and serienota = '''+umaContasReceber.getSerieNota+'''';
QContasReceber.Open;
QContasReceber.First;
if umaContasReceber.CountParcelas <> 0 then
umaContasReceber.LimparListaParcelas;
while not QContasReceber.Eof do
begin
count := count + 1;
umaContasReceber.CrieObjetoParcela;
umaContasReceber.addParcelas(umaContasReceber.getUmaParcelas);
umaContasReceber.getParcelas(count-1).setNumParcela(QContasRecebernumparcela.AsInteger);
QContasReceber.Next;
end;
end;
Result := count;
end;
procedure DaoContasReceber.AtualizaGrid;
begin
with umDM do
begin
QContasReceber.Close;
QContasReceber.sql.Text := 'select * from contareceber order by numnota, serienota, numparcela';
QContasReceber.Open;
end;
end;
function DaoContasReceber.Carrega(obj: TObject): TObject;
var
umaContasReceber: ContasReceber;
begin
umaContasReceber := ContasReceber(obj);
with umDM do
begin
if not QContasReceber.Active then
QContasReceber.Open;
//
// if umaContasReceber.getId <> 0 then
// begin
// QContasReceber.Close;
// QContasReceber.SQL.Text := 'select * from estado where idestado = '+IntToStr(umaContasReceber.getId);
// QContasReceber.Open;
// end;
//
umaContasReceber.setNumNota(QContasRecebernumnota.AsInteger);
umaContasReceber.setSerieNota(QContasReceberserienota.AsString);
umaContasReceber.setNumParcela(QContasRecebernumparcela.AsInteger);
umaContasReceber.setDataEmissao(QContasReceberdataemissao.AsDateTime);
umaContasReceber.setDataVencimento(QContasReceberdatavencimento.AsDateTime);
umaContasReceber.setDataPagamento(QContasReceberdatapagamento.AsDateTime);
umaContasReceber.setValor(QContasRecebervalor.AsFloat);
umaContasReceber.setMulta(QContasRecebermulta.AsFloat);
umaContasReceber.setJuros(QContasReceberjuros.AsFloat);
umaContasReceber.setDesconto(QContasReceberdesconto.AsFloat);
umaContasReceber.setStatus(QContasReceberstatus.AsString);
umaContasReceber.setObservacao(QContasReceberobservacao.AsString);
// Busca o Cliente referente ao ContasReceber
umaContasReceber.getUmCliente.setId(QContasReceberidcliente.AsInteger);
umaDaoCliente.Carrega(umaContasReceber.getUmCliente);
// Busca o Usuario referente ao ContasReceber
umaContasReceber.getUmUsuario.setIdUsuario(QContasReceberidusuario.AsInteger);
umaDaoUsuario.Carrega(umaContasReceber.getUmUsuario);
// Busca a Forma de Pagamento referente ao ContasReceber
umaContasReceber.getUmaFormaPagamento.setId(QContasReceberidformapagamento.AsInteger);
umaDaoFormaPagamento.Carrega(umaContasReceber.getUmaFormaPagamento);
//Cria uma Parcela referente a que foi selecionada na grid apenas para percorrer o FOR na hora de salvar
umaContasReceber.getUmaCondicaoPagamento.addParcela;
umaContasReceber.addParcelas(umaContasReceber.getUmaCondicaoPagamento.getParcela);
end;
result := umaContasReceber;
Self.AtualizaGrid;
end;
constructor DaoContasReceber.CrieObjeto;
begin
inherited;
umaDaoCliente := DaoCliente.CrieObjeto;
umaDaoUsuario := DaoUsuario.CrieObjeto;
umaDaoFormaPagamento := DaoFormaPagamento.CrieObjeto;
end;
destructor DaoContasReceber.Destrua_se;
begin
inherited;
end;
function DaoContasReceber.Excluir(obj: TObject): string;
var
umaContasReceber: ContasReceber;
begin
// umaContasReceber := ContasReceber(obj);
// with umDM do
// begin
// try
// beginTrans;
// QContasReceber.SQL := UpdateContasReceber.DeleteSQL;
// QContasReceber.Params.ParamByName('OLD_idestado').Value := umaContasReceber.getId;
// QContasReceber.ExecSQL;
// Commit;
// result := 'ContasReceber excluído com sucesso!';
// except
// on e:Exception do
// begin
// rollback;
// if pos('chave estrangeira',e.Message)>0 then
// result := 'Ocorreu um erro! O ContasReceber não pode ser excluído pois ja está sendo usado pelo sistema.'
// else
// result := 'Ocorreu um erro! ContasReceber não foi excluído. Erro: '+e.Message;
// end;
// end;
// end;
// Self.AtualizaGrid;
end;
function DaoContasReceber.GetDS: TDataSource;
begin
//------Formatar Grid--------//
(umDM.QContasReceber.FieldByName('valor') as TFloatField).DisplayFormat := '0.00'; //Formatar o campo valor do tipo Float
(umDM.QContasReceber.FieldByName('juros') as TFloatField).DisplayFormat := '0.00';
(umDM.QContasReceber.FieldByName('multa') as TFloatField).DisplayFormat := '0.00';
(umDM.QContasReceber.FieldByName('desconto') as TFloatField).DisplayFormat := '0.00';
umDM.QContasReceber.FieldByName('numnota').DisplayLabel := 'NN';
umDM.QContasReceber.FieldByName('serienota').DisplayLabel := 'SN';
umDM.QContasReceber.FieldByName('numparcela').DisplayLabel := 'P';
umDM.QContasReceber.FieldByName('numnota').DisplayWidth := 5;
umDM.QContasReceber.FieldByName('serienota').DisplayWidth := 5;
umDM.QContasReceber.FieldByName('numparcela').DisplayWidth := 5;
umDM.QContasReceber.FieldByName('valor').DisplayWidth := 10;
umDM.QContasReceber.FieldByName('multa').DisplayWidth := 5;
umDM.QContasReceber.FieldByName('juros').DisplayWidth := 5;
umDM.QContasReceber.FieldByName('desconto').DisplayWidth := 5;
//-----------------------------//
AtualizaGrid;
result := umDM.DSContasReceber;
end;
procedure DaoContasReceber.Ordena(campo: string);
begin
umDM.QContasReceber.IndexFieldNames := campo;
end;
function DaoContasReceber.Salvar(obj: TObject): string;
var umaContasReceber : ContasReceber;
i, countParcelas, numParcela : Integer;
valor : Real;
status : string;
cancelar : Boolean;
begin
umaContasReceber := ContasReceber(obj);
with umDM do
begin
try
beginTrans;
QContasReceber.Close;
if (umaContasReceber.getStatus = 'CANCELADA' ) then
begin
countParcelas := ContarContasReceber(umaContasReceber);
status := umaContasReceber.getStatus;
cancelar := True;
end
else
begin
countParcelas := umaContasReceber.CountParcelas;
status := umaContasReceber.getStatus;
cancelar := False;
end;
for i := 1 to countParcelas do
begin
if (cancelar) then
numParcela := umaContasReceber.getParcelas(i-1).getNumParcela
else
numParcela := umaContasReceber.getNumParcela;
if umaContasReceber.getStatus = 'PENDENTE' then
QContasReceber.SQL := UpdateContasReceber.InsertSQL
else
begin
QContasReceber.SQL := UpdateContasReceber.ModifySQL;
QContasReceber.Params.ParamByName('OLD_numnota').Value := umaContasReceber.getNumNota;
QContasReceber.Params.ParamByName('OLD_serienota').Value := umaContasReceber.getSerieNota;
QContasReceber.Params.ParamByName('OLD_numparcela').Value := numParcela;
QContasReceber.Params.ParamByName('OLD_idcliente').Value := umaContasReceber.getUmCliente.getId;
end;
QContasReceber.Params.ParamByName('numnota').Value := umaContasReceber.getNumNota;
QContasReceber.Params.ParamByName('serienota').Value := umaContasReceber.getSerieNota;
QContasReceber.Params.ParamByName('idcliente').Value := umaContasReceber.getUmCliente.getId;
QContasReceber.Params.ParamByName('idusuario').Value := umaContasReceber.getUmUsuario.getIdUsuario;
QContasReceber.Params.ParamByName('idformapagamento').Value := umaContasReceber.getUmaFormaPagamento.getId;
QContasReceber.Params.ParamByName('multa').Value := umaContasReceber.getMulta;
QContasReceber.Params.ParamByName('juros').Value := umaContasReceber.getJuros;
QContasReceber.Params.ParamByName('desconto').Value := umaContasReceber.getDesconto;
QContasReceber.Params.ParamByName('status').Value := status;
QContasReceber.Params.ParamByName('observacao').Value := umaContasReceber.getObservacao;
QContasReceber.Params.ParamByName('dataemissao').Value := umaContasReceber.getDataEmissao;
if (umaContasReceber.getDataPagamento <> StrToDateTime('30/12/1899')) then
QContasReceber.Params.ParamByName('datapagamento').Value := umaContasReceber.getDataPagamento;
if umaContasReceber.getStatus = 'PENDENTE' then
begin
QContasReceber.Params.ParamByName('numparcela').Value := umaContasReceber.getParcelas(i-1).getNumParcela;
valor := StrToFloat(FormatFloat('#0.00',(umaContasReceber.getParcelas(i-1).getPorcentagem/100) * umaContasReceber.getTotalAux));
QContasReceber.Params.ParamByName('valor').Value := valor;
QContasReceber.Params.ParamByName('datavencimento').Value := DateToStr(Date + umaContasReceber.getParcelas(i-1).getDias);
end
else
begin
QContasReceber.Params.ParamByName('numparcela').Value := numParcela;
QContasReceber.Params.ParamByName('valor').Value := umaContasReceber.getValor;
QContasReceber.Params.ParamByName('datavencimento').Value := umaContasReceber.getDataVencimento;
end;
QContasReceber.ExecSQL;
end;
//Chamada para o cancelamento da compra quando uma contas a receber for cancelada pela propria tela
if (status = 'CANCELADA') then
Self.VerificarVenda(umaContasReceber);
Commit;
if umaContasReceber.getStatus = 'CANCELADA' then
result := 'Conta Cancelada com sucesso!'
else
result := 'Conta Recebida com sucesso!';
except
on e: Exception do
begin
rollback;
if umaContasReceber.getStatus = 'CANCELADA' then
Result := 'Ocorreu um erro! Essa Conta não foi cancelada. Erro: '+e.Message
else
Result := 'Ocorreu um erro! Essa Conta não foi salva. Erro: '+e.Message;
end;
end;
end;
Self.AtualizaGrid;
end;
end.
|
PROGRAM Roulette;
FUNCTION SpinTheWheel: integer;
BEGIN (* SpinTheWheel *)
SpinTheWheel := Random(37);
END; (* SpinTheWheel *)
FUNCTION BenefitForLuckyNr(luckyNr, bet: integer): integer;
var randNumber: integer;
BEGIN (* BenefitForLuckyNr *)
randNumber := SpinTheWheel;
IF (luckyNr = randNumber) THEN BEGIN
BenefitForLuckyNr := bet * 36 - bet;
END ELSE BEGIN
BenefitForLuckyNr := -bet;
END; (* IF *)
END; (* BenefitForLuckyNr *)
FUNCTION BenefitForEvenNr(bet: integer): integer;
var randNr: integer;
BEGIN (* BenefitForEvenNr *)
randNr := SpinTheWheel;
IF (randNr = 0) OR (ODD(randNr)) THEN BEGIN
BenefitForEvenNr := -bet;
END ELSE BEGIN
BenefitForEvenNr := bet * 2 - bet;
END; (* IF *)
END; (* BenefitForEvenNr *)
PROCEDURE TestGameLuckyNumber(luckyNr, money: integer);
var gamesLost, gamesWon, maxMoney, newMoney: Longint;
BEGIN (* TestGameLuckyNumber *)
IF (luckyNr < 0) OR (luckyNr > 36) THEN BEGIN
WriteLn('Lucky Number is not valid, terminating program.');
HALT;
END;
gamesWon := 0;
gamesLost := 0;
maxMoney := money;
WHILE (money > 0) DO BEGIN
newMoney := money + BenefitForLuckyNr(luckyNr, 1);
IF (newMoney > money) THEN BEGIN
Inc(gamesWon);
IF (newMoney > maxMoney) THEN BEGIN
maxMoney := newMoney;
END; (* IF *)
END ELSE BEGIN
Inc(gamesLost);
END; (* IF *)
money := newMoney;
END; (* WHILE *)
WriteLn('Games Won: ', gamesWon:9);
WriteLn('Games Lost: ', gamesLost:9);
WriteLn('Max Money: ', maxMoney:9);
END; (* TestGameLuckyNumber *)
PROCEDURE TestGameEven(money: integer);
var gamesLost, gamesWon, maxMoney, newMoney: Longint;
BEGIN (* TestGameEven *)
gamesWon := 0;
gamesLost := 0;
maxMoney := money;
WHILE (money > 0) DO BEGIN
newMoney := money + BenefitForEvenNr(1);
IF (newMoney > money) THEN BEGIN
Inc(gamesWon);
IF (newMoney > maxMoney) THEN BEGIN
maxMoney := newMoney;
END; (* IF *)
END ELSE BEGIN
Inc(gamesLost);
END; (* IF *)
money := newMoney;
END; (* WHILE *)
WriteLn('Games Won: ', gamesWon:9);
WriteLn('Games Lost: ', gamesLost:9);
WriteLn('Max Money: ', maxMoney:9);
END; (* TestGameEven *)
var luckyNr: integer;
BEGIN (* Roulette *)
Randomize;
Write('Enter your lucky number (0 - 36): ');
Read(luckyNr);
TestGameLuckyNumber(luckyNr, 1000);
WriteLn('Test Even Number:');
TestGameEven(1000);
END. (* Roulette *) |
unit Initializer.ReplacedSector;
interface
uses
SysUtils,
OS.EnvironmentVariable, Global.LanguageString, Device.PhysicalDrive,
AverageLogger.Count, AverageLogger,
Support;
type
TMainformReplacedSectorApplier = class
private
ReplacedSectorLog: TAverageCountLogger;
ReplacedSectors: UInt64;
procedure ApplyReplacedSectorsAsTotalWrite;
procedure ApplyTodayUsageByLog;
procedure SetUsageLabelByLogAndAvailableType;
procedure CreateReplacedSectorLog;
procedure FreeReplacedSectorLog;
function IsTotalWriteNotSupported: Boolean;
procedure SetHostWriteLabelAsReplacedSectors;
procedure SetReplacedSectors;
procedure RecoverAnalyticsLabel;
procedure SetAnalyticsLabelAsLifeAnalysis;
procedure ApplyUsageByLog;
procedure ApplyReplacedSector;
procedure RefreshAnalyticsSection;
public
procedure ApplyMainformReplacedSector;
end;
implementation
uses Form.Main;
procedure TMainformReplacedSectorApplier.ApplyMainformReplacedSector;
begin
ApplyReplacedSector;
RefreshAnalyticsSection;
FreeReplacedSectorLog;
end;
procedure TMainformReplacedSectorApplier.ApplyReplacedSector;
begin
SetReplacedSectors;
CreateReplacedSectorLog;
end;
procedure TMainformReplacedSectorApplier.SetReplacedSectors;
begin
ReplacedSectors := fMain.SelectedDrive.SMARTInterpreted.ReplacedSectors;
fMain.lSectors.Caption := CapRepSect[CurrLang];
if fMain.SelectedDrive.SupportStatus.Supported = CDIInsufficient then
fMain.lSectors.Caption := fMain.lSectors.Caption +
CapUnsupported[CurrLang]
else
fMain.lSectors.Caption := fMain.lSectors.Caption +
UIntToStr(ReplacedSectors) + CapCount[CurrLang];
end;
procedure TMainformReplacedSectorApplier.CreateReplacedSectorLog;
begin
ReplacedSectorLog := TAverageCountLogger.Create(
TAverageCountLogger.BuildFileName(
EnvironmentVariable.AppPath,
fMain.SelectedDrive.IdentifyDeviceResult.Serial + 'RSLog'));
ReplacedSectorLog.ReadAndRefresh(UIntToStr(ReplacedSectors));
end;
procedure TMainformReplacedSectorApplier.FreeReplacedSectorLog;
begin
if ReplacedSectorLog <> nil then
FreeAndNil(ReplacedSectorLog);
end;
function TMainformReplacedSectorApplier.IsTotalWriteNotSupported: Boolean;
begin
result :=
fMain.SelectedDrive.SupportStatus.TotalWriteType =
TTotalWriteType.WriteNotSupported;
end;
procedure TMainformReplacedSectorApplier.SetUsageLabelByLogAndAvailableType;
var
MaxPeriodAverage: TPeriodAverage;
begin
MaxPeriodAverage := ReplacedSectorLog.GetMaxPeriodFormattedAverage;
fMain.l1Month.Caption :=
CapAvg[Integer(MaxPeriodAverage.Period)][CurrLang] +
MaxPeriodAverage.FormattedAverageValue +
CapCount[CurrLang] + '/' +
CapDay[CurrLang];
end;
procedure TMainformReplacedSectorApplier.ApplyTodayUsageByLog;
begin
fMain.lTodayUsage.Caption := CapToday[CurrLang] +
ReplacedSectorLog.GetFormattedTodayDelta +
CapCount[CurrLang];
end;
procedure TMainformReplacedSectorApplier.ApplyUsageByLog;
begin
SetUsageLabelByLogAndAvailableType;
ApplyTodayUsageByLog;
end;
procedure TMainformReplacedSectorApplier.ApplyReplacedSectorsAsTotalWrite;
begin
SetAnalyticsLabelAsLifeAnalysis;
SetHostWriteLabelAsReplacedSectors;
ApplyUsageByLog;
end;
procedure TMainformReplacedSectorApplier.SetHostWriteLabelAsReplacedSectors;
begin
fMain.lHost.Caption :=
CapRepSect[CurrLang] + UIntToStr(ReplacedSectors) +
CapCount[CurrLang];
end;
procedure TMainformReplacedSectorApplier.SetAnalyticsLabelAsLifeAnalysis;
begin
fMain.lAnalytics.Caption := BtLifeAnaly[CurrLang];
fMain.lAnaly.Caption := CapLifeAnaly[CurrLang];
end;
procedure TMainformReplacedSectorApplier.RecoverAnalyticsLabel;
begin
fMain.lAnalytics.Caption := BtAnaly[CurrLang];
fMain.lAnaly.Caption := CapAnaly[CurrLang];
end;
procedure TMainformReplacedSectorApplier.RefreshAnalyticsSection;
begin
if IsTotalWriteNotSupported then
ApplyReplacedSectorsAsTotalWrite
else
RecoverAnalyticsLabel;
end;
end.
|
unit Getter.WebPath;
interface
uses
SysUtils, IdHttp;
type
TDownloadFileType = (dftPlain, dftGetFromWeb);
TDownloadFile = record
FFileAddress: String;
FBaseAddress: String;
FPostAddress: String;
FType: TDownloadFileType;
end;
function GetAddressFromWeb(const Address: String): String;
function GetDownloadPath(const Input: TDownloadFile): String;
implementation
function GetAddressFromWeb(const Address: String): String;
var
AddrGetter: TIdHttp;
begin
result := '';
AddrGetter := TIdHttp.Create;
AddrGetter.Request.UserAgent := 'Naraeon SSD Tools';
try
result := AddrGetter.Get(Address);
finally
FreeAndNil(AddrGetter);
end;
end;
function GetDownloadPath(const Input: TDownloadFile): String;
begin
result := Input.FBaseAddress;
case Input.FType of
dftPlain:
begin
result := result + Input.FFileAddress;
end;
dftGetFromWeb:
begin
result := result + GetAddressFromWeb(Input.FFileAddress);
end;
end;
result := result + Input.FPostAddress;
end;
end.
|
{
unit RegisterComp
ES: unidad para registrar los componentes VCL
EN: unit to register the VCL components
=========================================================================
History:
ver 1.0.0
ES:
cambio: ya no registra el componente TGMGeoCode.
EN:
change: TGMGeoCode component no longer registered here.
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con FireMonkey
EN:
new: documentation
new: now compatible with FireMonkey
ver 0.1.8
ES:
nuevo: se registra la clase TGMElevation
EN:
new: TGMElevation class is registered
ver 0.1.6
ES:
nuevo: se registra la clase TGMDirection
EN:
new: TGMDirection class is registered
ver 0.1.5
ES:
nuevo: se registra la clase TGMGeoCode
EN:
new: TGMGeoCode class is registered
ver 0.1.4
ES:
nuevo: se registra la clase TGMCircle
EN:
new: TGMCircle class is registered
ver 0.1.3
ES:
nuevo: se registra la clase TGMRectangle
EN:
new: TGMRectangle class is registered
ver 0.1.2
ES:
nuevo: se registra la clase TGMPolygon
EN:
new: TGMPolygon class is registered
ver 0.1.1
ES:
nuevo: se registra la clase TGMPolyline
EN:
new: TGMPolyline class is registered
ver 0.1:
ES: primera versión
EN: first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2011, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
Unit to register the VCL components.
@author Xavier Martinez (cadetill)
@version 1.5.0
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Unidad para registrar los componentes VCL.
@author Xavier Martinez (cadetill)
@version 1.5.0
-------------------------------------------------------------------------------}
unit RegisterCompVCL;
{.$DEFINE CHROMIUM}
{$I ..\gmlib.inc}
interface
{*------------------------------------------------------------------------------
The Register procedure register the VCL components.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento Register registra los componentes VCL.
-------------------------------------------------------------------------------}
procedure Register;
implementation
uses
{$IFDEF DELPHIXE2}
System.Classes, Vcl.Controls, Vcl.Graphics,
{$ELSE}
Classes, Graphics,
{$ENDIF}
GMMapVCL, GMMarkerVCL, GMPolylineVCL, GMPolygonVCL, GMRectangleVCL,
GMCircleVCL, GMDirectionVCL, GMElevationVCL;
procedure Register;
begin
{$IFDEF DELPHIXE2}
GroupDescendentsWith(TGMMap, Vcl.Controls.TControl);
{$IFDEF CHROMIUM}GroupDescendentsWith(TGMMapChr, Vcl.Controls.TControl);{$ENDIF}
GroupDescendentsWith(TGMMarker, Vcl.Controls.TControl);
GroupDescendentsWith(TGMPolyline, Vcl.Controls.TControl);
GroupDescendentsWith(TGMPolygon, Vcl.Controls.TControl);
GroupDescendentsWith(TGMRectangle, Vcl.Controls.TControl);
GroupDescendentsWith(TGMCircle, Vcl.Controls.TControl);
GroupDescendentsWith(TGMDirection, Vcl.Controls.TControl);
GroupDescendentsWith(TGMElevation, Vcl.Controls.TControl);
{$ENDIF}
RegisterComponents('GoogleMaps', [TGMMap, {$IFDEF CHROMIUM}TGMMapChr,{$ENDIF} TGMMarker,
TGMPolyline, TGMPolygon,
TGMRectangle, TGMCircle,
TGMDirection, TGMElevation
]);
end;
end.
|
unit str_result_1;
interface
implementation
var S1, S2: string;
function GetStr: string;
begin
Result := S1;
end;
procedure Test;
begin
S1 := Copy('string');
S2 := S1 + S1;
if GetStr() = S2 then
S2 := ''
else
S2 := GetStr();
end;
initialization
Test();
finalization
Assert(S1 = S2);
end. |
unit MediaStream.DataSource.Stub;
interface
uses Windows,Classes,SysUtils, SyncObjs, MediaStream.DataSource.Base, MediaProcessing.Definitions;
type
TStubChannel = class;
TMediaStreamDataSource_Stub = class (TMediaStreamDataSource)
private
FDataLock: TCriticalSection;
FChannel : TStubChannel;
FFormat: TMediaStreamDataHeader;
protected
procedure DoConnect(aConnectParams: TMediaStreamDataSourceConnectParams); override;
procedure DoDisconnect; override;
procedure OnDataReceived(aSender: TObject);
public
constructor Create; override;
destructor Destroy; override;
class function CreateConnectParams: TMediaStreamDataSourceConnectParams; override;
function GetConnectionErrorDescription(aError: Exception): string; override;
procedure Start; override;
procedure Stop; override;
function LastStreamDataTime: TDateTime; override;
end;
TMediaStreamDataSourceConnectParams_Stub = class (TMediaStreamDataSourceConnectParams)
private
FFormat: TMediaStreamDataHeader;
FInterval : integer;
public
constructor Create; overload;
constructor Create(const aFormat: TMediaStreamDataHeader; aInterval: integer); overload;
procedure Assign(aSource: TMediaStreamDataSourceConnectParams); override;
function ToString: string; override;
function ToUrl(aIncludeAuthorizationInfo: boolean): string; override;
procedure Parse(const aUrl: string); override;
end;
TStubChannel = class (TThread)
private
FOnData: TNotifyEvent;
FInterval: integer;
protected
procedure Execute; override;
public
constructor Create(aInterval: integer);
property OnData: TNotifyEvent read FOnData write FOnData;
end;
implementation
uses uBaseClasses;
{ TMediaStreamDataSourceConnectParams_Stub }
procedure TMediaStreamDataSourceConnectParams_Stub.Assign(aSource: TMediaStreamDataSourceConnectParams);
var
aSrc: TMediaStreamDataSourceConnectParams_Stub;
begin
TArgumentValidation.NotNil(aSource);
if not (aSource is TMediaStreamDataSourceConnectParams_Stub) then
raise EInvalidArgument.CreateFmt('Тип параметров %s не совместим с типом %s',[aSource.ClassName,self.ClassName]);
aSrc:=TMediaStreamDataSourceConnectParams_Stub(aSource);
Self.FFormat:=aSrc.FFormat;
end;
constructor TMediaStreamDataSourceConnectParams_Stub.Create;
begin
FFormat.Clear;
FFormat.biMediaType:=mtVideo;
FFormat.biStreamType:=0;
FFormat.VideoWidth:=0;
FFormat.VideoHeight:=0;
FInterval:=100;
end;
constructor TMediaStreamDataSourceConnectParams_Stub.Create(const aFormat: TMediaStreamDataHeader;aInterval: integer);
begin
FFormat:=aFormat;
FInterval:=aInterval;
end;
procedure TMediaStreamDataSourceConnectParams_Stub.Parse(const aUrl: string);
begin
inherited;
end;
function TMediaStreamDataSourceConnectParams_Stub.ToString: string;
begin
result:='';
end;
function TMediaStreamDataSourceConnectParams_Stub.ToUrl(
aIncludeAuthorizationInfo: boolean): string;
begin
end;
{ TMediaStreamDataSource_Stub }
procedure TMediaStreamDataSource_Stub.Start;
begin
FDataLock.Enter;
try
FChannel.OnData:=OnDataReceived;
finally
FDataLock.Leave;
end;
end;
procedure TMediaStreamDataSource_Stub.Stop;
begin
FDataLock.Enter;
try
if FChannel<>nil then
FChannel.OnData:=nil;
finally
FDataLock.Leave;
end;
end;
procedure TMediaStreamDataSource_Stub.DoConnect(aConnectParams: TMediaStreamDataSourceConnectParams);
begin
FreeAndNil(FChannel);
FFormat:=(aConnectParams as TMediaStreamDataSourceConnectParams_Stub).FFormat;
FChannel:=TStubChannel.Create((aConnectParams as TMediaStreamDataSourceConnectParams_Stub).FInterval);
end;
procedure TMediaStreamDataSource_Stub.DoDisconnect;
begin
FreeAndNil(FChannel);
end;
constructor TMediaStreamDataSource_Stub.Create;
begin
inherited;
FDataLock:=TCriticalSection.Create;
end;
class function TMediaStreamDataSource_Stub.CreateConnectParams: TMediaStreamDataSourceConnectParams;
begin
result:=TMediaStreamDataSourceConnectParams_Stub.Create;
end;
destructor TMediaStreamDataSource_Stub.Destroy;
begin
Disconnect;
inherited;
FreeAndNil(FDataLock);
end;
function TMediaStreamDataSource_Stub.GetConnectionErrorDescription(aError: Exception): string;
begin
result:='';
end;
function TMediaStreamDataSource_Stub.LastStreamDataTime: TDateTime;
begin
if FChannel<>nil then
result:=Now
else
result:=0;
end;
procedure TMediaStreamDataSource_Stub.OnDataReceived(aSender: TObject);
begin
FDataLock.Enter;
try
if (FChannel=nil) or not Assigned(FChannel.OnData) then
exit;
FFormat.TimeStamp:=Trunc(Now*MSecsPerDay);
RaiseOnData(FFormat,nil,0,nil,0);
finally
FDataLock.Leave;
end;
end;
{ TStubChannel }
constructor TStubChannel.Create(aInterval: integer);
begin
FInterval:=aInterval;
inherited Create(false);
end;
procedure TStubChannel.Execute;
begin
while not Terminated do
begin
Sleep(FInterval);
if Assigned(FOnData) then
FOnData(self);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ Copyright(c) 2012-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Datasnap.DSServerMetadata;
interface
uses
System.Classes,
Data.DBXCommon,
Datasnap.DSCommonServer,
Datasnap.DSServer,
Datasnap.DSCommonProxy,
Datasnap.DSMetadata,
Datasnap.DSServerResStrs;
type
TDSServerMetaDataProvider = class(TDSCustomMetaDataProvider)
private
FServer: TDSServer;
procedure SetServer(const Value: TDSServer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
function HasProvider: Boolean; override;
function GetProvider: IDSProxyMetaDataLoader; override;
published
property Server: TDSServer read FServer write SetServer;
end;
implementation
{ TDSServerMetaDataProvider }
function TDSServerMetaDataProvider.GetProvider: IDSProxyMetaDataLoader;
begin
if HasProvider then
begin
if csDesigning in ComponentState then
raise TDSProxyException.CreateFmt(SNoMetaDataAtDesignTime, [FServer.Name]);
Result := TDSProxyMetaDataLoader.Create(
function: TDBXConnection
var
LProps: TDBXProperties;
begin
LProps := TDBXProperties.Create;
try
// Create in-process connection
Result := TDSServerConnection(FServer.GetServerConnection(LProps));
finally
LProps.Free;
end;
end,
procedure(C: TDBXConnection)
begin
// Special handling for local connection (RAID 276563). Handler will free connection.
// TDSServerConnection(C).ServerConnectionHandler.Free
c.Free;
end);
end;
end;
function TDSServerMetaDataProvider.HasProvider: Boolean;
begin
Result := FServer <> nil;
end;
procedure TDSServerMetaDataProvider.Notification(
AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FServer) then
FServer := nil;
end;
procedure TDSServerMetaDataProvider.SetServer(
const Value: TDSServer);
begin
if Value <> FServer then
begin
if Assigned(FServer) then
FServer.RemoveFreeNotification(Self);
FServer := Value;
if Value <> nil then
begin
Value.FreeNotification(Self);
end;
end;
end;
end.
|
unit Processor.ReadmeMarkdown;
interface
uses
System.SysUtils,
System.StrUtils;
type
TReadmeMarkdownProcessor = class
private
public
class function ProcessReadme(const aSource: string;
const aNewVersion: string; const aSearchPattern: string): string; static;
end;
implementation
uses
Processor.Utils;
class function TReadmeMarkdownProcessor.ProcessReadme(const aSource: string;
const aNewVersion: string; const aSearchPattern: string): string;
var
idx1: Integer;
len: Integer;
idx2: Integer;
idx3: Integer;
begin
// ---------------------------------------------------------------------
// 
// ^----------- search pattern -------^
// ---------------------------------------------------------------------
idx1 := aSource.IndexOf(aSearchPattern);
len := length(aSearchPattern);
if idx1 = -1 then
raise Processor.Utils.EProcessError.Create
('No version pattern found in main README file. Please update configuration file.');
idx2 := aSource.IndexOf('-', idx1 + len);
idx3 := aSource.IndexOf('-', idx2+1);
if (idx2 = -1) or (idx3 = -1) then
raise Processor.Utils.EProcessError.Create
('Invalid format of version stored in main README');
Result := aSource.Substring(0, idx2+1) + '%20'+aNewVersion +
aSource.Substring(idx3, 9999999);
end;
end.
|
unit UBullsCows;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus;
type
TFCowsAndBulls = class(TForm)
Memo1: TMemo;
Memo2: TMemo;
Label1: TLabel;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Edit4: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Edit5: TEdit;
BRefresh: TButton;
MainMenu1: TMainMenu;
Fichiers1: TMenuItem;
Newgame1: TMenuItem;
N1: TMenuItem;
Quit1: TMenuItem;
Label5: TLabel;
Edit6: TEdit;
BCheck: TButton;
procedure FormCreate(Sender: TObject);
procedure Newgame1Click(Sender: TObject);
procedure Newgame();
procedure à(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
FCowsAndBulls: TFCowsAndBulls;
solution: string;
proposition: string;
cptEssai: integer;
tailleMot: integer;
cptErreur: integer;
implementation
{$R *.dfm}
function checkLongmot(proposition: string): boolean;
var
check: boolean;
begin
if length(proposition) > length(solution) then begin
ShowMessage('Mot trop long ! La proposition doit contenir autant de lettres que le mot à trouver. Veuillez recommencer.');
end
else begin
if length(proposition) < length(solution) then begin
ShowMessage('Mot trop court ! La proposition doit contenir autant de lettres que le mot à trouver. Veuillez recommencer.');
end
else begin
check:=false;
checkLongMot:=check;
end;
end;
check:=true;
checkLongMot:=check;
end;
function checkIsogramme(proposition: string): boolean;
var
i,j: integer;
currentLetter,compareLetter: string;
check: boolean;
begin
check := true;
for i := 1 to length(proposition) do begin
currentLetter := proposition[i];
for j := 1 to length(proposition) do begin
compareLetter := proposition[j];
if i <> j then begin
if currentLetter = compareLetter then begin
check := false;
checkIsogramme := check;
end;
end;
end;
end;
checkIsogramme := check;
end;
function countBulls(proposition,solution: string): integer;
var
i,cpt: integer;
begin
cpt:=0;
for i := 1 to length(solution) do begin
if proposition[i] = solution[i] then begin
cpt:=cpt+1;
end;
end;
countBulls:=cpt;
end;
function countCows(proposition,solution: string): integer;
var
i,j,cpt: integer;
begin
cpt:=0;
for i := 1 to length(solution) do begin
for j := 1 to length(solution) do begin
if (i<>j) and (solution[i]=proposition[j]) then begin
cpt:=cpt+1;
end;
end;
end;
countCows:=cpt;
end;
procedure TFCowsAndBulls.à(Sender: TObject);
var
checkLong,isogramme,minuscule: boolean;
cptCows,cptBulls: integer;
begin
//premiere verification (longueur mot)
proposition := Memo2.Lines[0];
checkLong := checkLongMot(proposition);
//deuxieme verification (isogramme)
isogramme := checkIsogramme(proposition);
if isogramme = false then begin
ShowMessage('La proposition doit contenir une seule fois chaque lettre ! Veuillez recommencer.');
end;
//troisieme verification (mot minuscule)
if proposition <> lowercase(proposition) then begin
minuscule:=false;
Showmessage('Votre mot doit être écrit en minuscule ! Veuillez recommencer.');
end
else begin
minuscule:=true;
end;
if checkLong = true and isogramme = true and minuscule = true then begin
cptEssai := cptEssai+1;
Edit4.Text := inttostr(cptEssai);
end
else begin
Memo2.Text := '';
end;
cptBulls:=countBulls(proposition,solution);
Edit1.Text:=inttostr(cptBulls);
cptCows:=countCows(proposition,solution);
Edit2.Text:=inttostr(cptCows);
if cptBulls = length(solution) then begin
ShowMessage('Gagné !');
Newgame();
end
else begin
cptErreur:=cptErreur+1;
Edit3.Text:=inttostr(cptErreur);
end;
end;
procedure TFCowsAndBulls.FormCreate(Sender: TObject);
begin
Memo1.Lines.LoadFromFile('C:\Users\Lenny\Documents\Embarcadero\Studio\Projets\dico.txt');
Memo2.Lines.Text := '';
Edit1.Text := '';
Edit2.Text := '';
Edit3.Text := '';
Edit4.Text := '';
Edit5.Text := '';
Edit6.Text := '';
end;
function creerMot(nouveauMot: string; Memo1: TMemo): string;
begin
randomize;
nouveauMot := Memo1.Lines[random((Memo1.Lines.Count))];
creerMot := nouveauMot;
end;
procedure TFCowsAndBulls.Newgame();
begin
cptErreur:=0;
Memo2.Lines.Text := '';
Edit1.Text := '';
Edit2.Text := '';
Edit3.Text := '';
Edit4.Text := '';
Edit6.Text := '';
Edit5.Text := '';
cptEssai := 1;
Edit4.Text := inttostr(cptEssai);
solution := creerMot(solution,Memo1);
tailleMot := length(solution);
Edit6.Text := inttostr(tailleMot);
end;
procedure TFCowsAndBulls.Newgame1Click(Sender: TObject);
begin
Newgame();
end;
end.
|
unit XMLutils;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, xmldom, XMLIntf, msxmldom, XMLDoc, ComCtrls, TypInfo, StrUtils,
uStrings, uLog;
type eNodeType = (ntRoot, ntHeader, ntData,
ntPage, ntFolder, ntDefFolder,
ntItem, ntDefItem, ntField, ntNone);
type eFieldFormat = (ffTitle, ffText, ffPass, ffWeb, ffComment, ffDate, ffMail, ffFile, ffNone);
function GetBaseTitle(x:IXMLDocument): String;
function NodeByPath(x:IXMLDocument; const fNodePath: String): IXMLNode;
function GetNodeType(Node: IXMLNode): eNodeType;
function GetFieldFormat(Field: IXMLNode): eFieldFormat;
function GetAttribute(Node: IXMLNode; attrName: String): String;
function SetAttribute(Node: IXMLNode; attrName: String; attrValue: String): Boolean;
function RemoveAttribute(Node: IXMLNode; attrName: String) : Boolean;
function GetNodeTitle(Node:IXMLNode): String;
function SetNodeTitle(Node:IXMLNode; Title: String): Boolean;
procedure LogNodeInfo(Node: IXMLNode; Msg: String='');
function GetNodeValue(Node: IXMLNode): String;
function SetNodeValue(Node: IXMLNode; Value: String): Boolean;
type
TTreeToXML = Class
private
FDOC: TXMLDocument;
FRootNode: IXMLNode;
FTree: TTreeView;
procedure IterateRoot;
procedure WriteNode(N: TTreeNode; ParentXN: IXMLNode);
Public
Constructor Create(Tree: TTreeView);
Procedure SaveToFile(const fn: String);
Destructor Destroy; override;
End;
TXMLToTree = Class
private
FTree: TTreeView;
//FNodeList: TNodeList;
Procedure IterateNodes(xn: IXMLNode; ParentNode: TTreeNode);
Public
Procedure XMLToTree(Tree: TTreeView; Const Doc: IXMLDocument);
Procedure XMLFileToTree(Tree: TTreeView; const FileName: String);
Procedure XMLStreamToTree(Tree: TTreeView; Const FileStream: TStream);
//Function XMLNodeFromTreeText(const cText: string): IXMLNode;
End;
implementation
uses Logic;
{$REGION 'Неиспользуемые классы - удалить позже'}
{$REGION 'TTreeToXML'}
{ TTreeToXML }
constructor TTreeToXML.Create(Tree: TTreeView);
begin
FTree := Tree;
FDOC := TXMLDocument.Create(nil);
FDOC.Options := FDOC.Options + [doNodeAutoIndent];
FDOC.Active := true;
FDOC.Encoding := 'UTF-8';
FRootNode := FDOC.CreateElement('Treeview', '');
FDOC.DocumentElement := FRootNode;
IterateRoot;
end;
Procedure TTreeToXML.WriteNode(N: TTreeNode; ParentXN: IXMLNode);
var
CurrNode: IXMLNode;
Child: TTreeNode;
begin
CurrNode := ParentXN.AddChild(N.Text);
CurrNode.Attributes['NodeLevel'] := N.Level;
CurrNode.Attributes['Index'] := N.Index;
Child := N.getFirstChild;
while Assigned(Child) do
begin
WriteNode(Child, CurrNode);
Child := Child.getNextSibling;
end;
end;
Procedure TTreeToXML.IterateRoot;
var
N: TTreeNode;
begin
N := FTree.Items[0];
while Assigned(N) do
begin
WriteNode(N, FRootNode);
N := N.getNextSibling;
end;
end;
procedure TTreeToXML.SaveToFile(const fn: String);
begin
FDOC.SaveToFile(fn);
end;
destructor TTreeToXML.Destroy;
begin
if Assigned(FDOC) then
FDOC.Free;
inherited;
end;
{$ENDREGION}
{$REGION 'TXMLToTree'}
{ TXMLToFree }
Procedure TXMLToTree.XMLFileToTree(Tree: TTreeView; const FileName: String);
var
FileStream : TFileStream;
begin
try
FileStream := TFileStream.Create(FileName, fmOpenReadWrite);
except
FileStream := TFileStream.Create(FileName, fmOpenRead);
end;
try
XMLStreamToTree(Tree, FileStream);
finally
FileStream.Free;
end;
end;
Procedure TXMLToTree.XMLToTree(Tree: TTreeView; Const Doc: IXMLDocument);
begin
FTree:= Tree;
try IterateNodes(Doc.DocumentElement, FTree.Items.AddFirst(nil, Doc.DocumentElement.NodeName));
finally end;
end;
Procedure TXMLToTree.XMLStreamToTree(Tree: TTreeView; Const FileStream: TStream);
var
Doc: TXMLDocument;
begin
Doc := TXMLDocument.Create(Application);
try
Doc.LoadFromStream(FileStream, xetUTF_8);
Doc.Active := true;
XMLToTree(Tree, Doc);
finally
Doc.Free;
end;
end;
Procedure TXMLToTree.IterateNodes(xn: IXMLNode; ParentNode: TTreeNode);
var
ChildTreeNode: TTreeNode;
i: Integer;
begin
For i := 0 to xn.ChildNodes.Count - 1 do
begin
ChildTreeNode := FTree.Items.AddChild(ParentNode, xn.ChildNodes[i].NodeName);
if xn.IsTextElement then ChildTreeNode.Text:=xn.Text;
IterateNodes(xn.ChildNodes[i], ChildTreeNode);
end;
for i := 0 to xn.AttributeNodes.Count - 1 do
begin
ChildTreeNode := FTree.Items.AddChild(ParentNode, xn.AttributeNodes[i].NodeName);
ChildTreeNode.ImageIndex:=1;
ChildTreeNode.SelectedIndex:=1;
end;
end;
//function TXMLToTree.XMLNodeFromTreeText(const cText: string): IXMLNode;
//var LCount: Integer;
// LList: TPointerList;
// i:integer;
//begin
// LCount:= FNodeList.Count;
// LList :=FNodeList.List;
// for i := 0 to LCount - 1 do
// begin
// if PNodeRecord(LList[i])^.TrNode.Text=cText then
// begin
// Result:=PNodeRecord(LList[i])^.XMLNode;
// break;
// end;
// end;
//end;
{$ENDREGION}
{$ENDREGION}
function GetNodeValue(Node: IXMLNode): String;
//Чтение значения узла
begin
result:='';
case GetNodeType(Node) of
ntNone:
Exit;
ntField: begin
result:=VarToStr(Node.NodeValue);
end;
else
result:= GetNodeTitle(Node);
end;
end;
function SetNodeValue(Node: IXMLNode; Value: String): Boolean;
//Установка значения узла
begin
result:=False;
case GetNodeType(Node) of
ntNone:
Exit;
ntField: begin
Node.NodeValue:=Value;
end;
else
SetNodeTitle(Node, Value);
end;
result:=True;
end;
function GetBaseTitle(x:IXMLDocument): String;
//Deprecated
begin
result:= NodeByPath(x, 'Root\Header\Title').Text;
end;
function GetNodeTitle(Node:IXMLNode): String;
//Возвращает строковое имя ноды
//Можно использовать для ntPage, ntFolder, ntItem, ntField
var i: Integer;
begin
case GetNodeType(Node) of
ntNone:
result:='';
ntField:
result:=VarToStr(Node.Attributes['name']);
ntItem,
ntDefItem:
for i := 0 to Node.ChildNodes.Count - 1 do begin
if GetFieldFormat(Node.ChildNodes[i]) = ffTitle then begin
result:=Node.ChildNodes[i].Text;
Exit;
end;
end;
ntPage,
ntFolder,
ntDefFolder: begin
if Node.ChildNodes[0].NodeType = ntText then
result:=Trim(VarToStr(Node.ChildNodes['#text'].NodeValue))
else
result:='Undefined'
end;
end;
end;
function SetNodeTitle(Node:IXMLNode; Title: String): Boolean;
//Установка заголовка узла
var i: Integer;
begin
Log('SetNodeTitle');
case GetNodeType(Node) of
ntField:
SetAttribute(Node, 'name', Title);
ntItem,
ntDefItem:
for i := 0 to Node.ChildNodes.Count - 1 do begin
if GetFieldFormat(Node.ChildNodes[i]) = ffTitle then begin
Node.ChildNodes[i].Text:=Title;
Result:=True;
Exit;
end;
end;
ntFolder,
ntDefFolder,
ntPage: begin
LogNodeInfo(Node, 'OldInfo');
if Node.ChildValues['#text'] = Null then
Node.ChildNodes.Insert(0, Node.OwnerDocument.
CreateNode(Title, ntText))
else Node.ChildValues['#text']:= Title;
LogNodeInfo(Node, 'NewInfo:');
end;
end;
result:=True;
end;
function NodeByPath(x:IXMLDocument; const fNodePath: String): IXMLNode;
//Отладочная функция
//Возвращает ноду через путь к ней.
//Путь задается через разделители (. \ | /)
//Цифра в скобках указывает индекс атрибута с таким именем
//Примерно так Node:=NodeByPath(MyXML, 'Root\Header\Owner')
// или так 'Root.Data'
//Возвращает nil если не найдет путь.
var
fNode: IXMLNode;
pth: TStringList;
begin
pth:= TStringList.Create();
pth.AddStrings(fNodePath.Split(['\', '/', '|', '.']));
fNode:= x.Node;
LogNodeInfo(fNode);
Log(FNode.NodeName);
while pth.Count<>0 do begin
fNode:=fNode.ChildNodes[pth[0]];
pth.Delete(0);
end;
pth.Free;
result:=fNode;
end;
function GetNodeType(Node: IXMLNode): eNodeType;
//Возвращает тип ноды в виде перечисления (Корень, Заголовок, Папка, Данные,
// Запись, Поле)
begin
//result:=eNodeType(AnsiIndexStr(GetAttribute(Node, 'type'), arrNodeTypes));
result:=eNodeType(AnsiIndexStr(LowerCase(Node.NodeName), arrNodeTypes));
//Log('GetNodeType(' + Node.NodeName +') = ', GetEnumName(TypeInfo(eNodeType), Ord(result)));
end;
function GetFieldFormat(Field: IXMLNode): eFieldFormat;
//Возвращает формат поля в виде перечисления
//eFieldFormat (Заголовок, Текст, Пароль и т.д.)
begin
result:=eFieldFormat(AnsiIndexStr(GetAttribute(Field, 'format'), arrFieldFormats));
//Log('GetFieldFormat(' + Field.NodeName +') = ', GetEnumName(TypeInfo(eFieldFormat), Ord(result)));
end;
function GetAttribute(Node: IXMLNode; attrName: String): String;
//Чтение атрибута в узле
begin
//Log('GetAttribute('+ Node.NodeName + ',' + attrName + ')');
//Log(Node.NodeName + ' всего атрибутов:' , Node.AttributeNodes.Count);
//Log(Node.NodeName + ' имеет атрибут ' + attrName + ':', Node.HasAttribute(attrName));
result:=VarToStr(Node.Attributes[attrName]);
//Log('GetAttribute('+ Node.NodeName + ',' + attrName + ') =', result);
//LogNodeInfo(Node, 'GetAttribute');
end;
function SetAttribute(Node: IXMLNode; attrName: String; attrValue: String): Boolean;
//Установка-добавление атрибута в узле
begin
Node.Attributes[attrName]:=attrValue;
result:=True;
end;
function RemoveAttribute(Node: IXMLNode; attrName: String) : Boolean;
//Удаление атрибута у узла
var
attr: iXMLNode;
begin
attr:= Node.AttributeNodes.FindNode(attrName);
if attr <> nil then begin
Node.AttributeNodes.Remove(attr);
result:=True;
end else result:= False;
end;
procedure LogNodeInfo(Node: IXMLNode; Msg: String='');
//Подробная информация об узле
var isTVal: iXMLnode;
Vl: String;
begin
isTVal:= Node.ChildNodes.FindNode('#text');
if isTVal <> nil then Vl:=VarToStr(Node.ChildNodes['#text'].NodeValue);
Log(Msg + ': NodeInfo: Title= ' + GetNodeTitle(Node) + ':');
Log(' Value= ' + Vl);
Log(' Type= ' + GetEnumName(TypeInfo(eNodeType), Ord(GetNodeType(Node))));
Log(' @=' + IntToStr(NativeInt(Node)));
Log(' BasicType=' + GetEnumName(TypeInfo(TNodeType), Ord(Node.NodeType)));
Log(' Childs= ' + IntToStr(Node.ChildNodes.Count));
Log(' isTextElem= ' + BoolToStr(Node.IsTextElement, True));
//Log(Msg + ': NodeInfo: Title= ' + GetNodeTitle(Node) + ':' +
// ', Value= ' + Vl +
// ', Type= ' + GetEnumName(TypeInfo(eNodeType), Ord(GetNodeType(Node))) +
// ', @=' + IntToStr(NativeInt(Node)) +
//
// ', BasicType=' + GetEnumName(TypeInfo(TNodeType), Ord(Node.NodeType)) +
// ', Childs= ' + IntToStr(Node.ChildNodes.Count) +
// ', isTextElem= ' + BoolToStr(Node.IsTextElement, True));
end;
end.
|
{
作为子程序参数的文件
Pascal可以被用来作为标准的和用户定义的子程序的参数在文件中的变量。下面的例子演示了这一概念。该程序创建一个文件名为rainfall.txt,
并存储一些降雨量数据。接下来,打开该文件,读取数据,并计算平均降雨量。
请注意,如果您使用的是文件的子程序的参数,它必须被声明为一个var参数。
下面的代码编译和执行时,它会产生以下结果:
Enter the File Name:
rainfall.txt
Enter rainfall data:
34
Enter rainfall data:
45
Enter rainfall data:
56
Enter rainfall data:
78
Average Rainfall: 53.25
************************************}
program addFiledata;
const
MAX = 4;
type
raindata = file of real;
var
rainfile: raindata;
filename: string;
procedure writedata(var f: raindata);
var
data: real;
i: integer;
begin
rewrite(f, sizeof(data));
for i:=1 to MAX do
begin
writeln('Enter rainfall data: ');
readln(data);
write(f, data);
end;
close(f);
end;
procedure computeAverage(var x: raindata);
var
d, sum: real;
average: real;
begin
reset(x);
sum:= 0.0;
while not eof(x) do
begin
read(x, d);
sum := sum + d;
end;
average := sum/MAX;
close(x);
writeln('Average Rainfall: ', average:7:2);
end;
begin
writeln('Enter the File Name: ');
readln(filename);
assign(rainfile, filename);
writedata(rainfile);
computeAverage(rainfile);
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit ColEdit;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, LibHelp;
type
TColInfo = class(TObject)
private
FOwner: TList;
FCaption: string;
FWidth: Integer;
FIndex: Integer;
FAlignment: TAlignment;
FWidthType: TWidth;
function GetIndex: Integer;
public
constructor Create(AOwner: TList; Column: TListColumn);
destructor Destroy; override;
property Index: Integer read GetIndex;
property Owner: TList read FOwner;
end;
type
TListViewColumns = class(TForm)
ColumnGroupBox: TGroupBox;
PropGroupBox: TGroupBox;
ColumnListBox: TListBox;
New: TButton;
Delete: TButton;
Ok: TButton;
Cancel: TButton;
Apply: TButton;
Help: TButton;
Label1: TLabel;
Label4: TLabel;
TextEdit: TEdit;
AlignmentEdit: TComboBox;
GroupBox1: TGroupBox;
WidthEdit: TEdit;
HWidthBtn: TRadioButton;
IWidthBtn: TRadioButton;
WidthBtn: TRadioButton;
procedure ValueChanged(Sender: TObject);
procedure DeleteClick(Sender: TObject);
procedure TextEditExit(Sender: TObject);
procedure IndexEditExit(Sender: TObject);
procedure WidthEditExit(Sender: TObject);
procedure ColumnListBoxClick(Sender: TObject);
procedure NewClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ApplyClick(Sender: TObject);
procedure AlignmentEditExit(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ColumnListBoxDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure ColumnListBoxDragDrop(Sender, Source: TObject; X,
Y: Integer);
procedure ColumnListBoxStartDrag(Sender: TObject;
var DragObject: TDragObject);
procedure ColumnListBoxEndDrag(Sender, Target: TObject; X, Y: Integer);
procedure ColumnListBoxMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure HWidthBtnClick(Sender: TObject);
procedure HelpClick(Sender: TObject);
private
FInfoList: TList;
FDefaultText: string;
FDragIndex: Integer;
FColumns: TListColumns;
procedure FlushControls;
procedure GetItem(Value: TListColumn);
function GetColInfo(Index: Integer): TColInfo;
function ListBoxText(Value: TColInfo): string;
procedure SetItem(Value: TColInfo);
procedure SetListBoxText(Index: Integer; const S: string);
procedure SetStates;
public
property ColItems[Index: Integer]: TColInfo read GetColInfo;
property Columns: TListColumns read FColumns;
property DefaultText: string read FDefaultText;
property InfoList: TList read FInfoList;
end;
function EditListViewColumns(AColumns: TListColumns): Boolean;
implementation
{$R *.dfm}
uses DsnConst;
function EditListViewColumns(AColumns: TListColumns): Boolean;
var
I: Integer;
begin
with TListViewColumns.Create(Application) do
try
FColumns := AColumns;
for I := 0 to Columns.Count - 1 do
begin
TColInfo.Create(InfoList, Columns.Items[I]);
ColumnListBox.Items.Add(ListBoxText(InfoList[I]));
end;
if InfoList.Count > 0 then
begin
ColumnListBox.ItemIndex := 0;
ColumnListBoxClick(nil);
end;
SetStates;
Result := ShowModal = mrOk;
if Result and Apply.Enabled then ApplyClick(nil);
finally
Free;
end;
end;
procedure ConvertError(Value: TEdit);
begin
with Value do
begin
SetFocus;
SelectAll;
end;
end;
{ TColInfo }
constructor TColInfo.Create(AOwner: TList; Column: TListColumn);
begin
inherited Create;
FOwner := AOwner;
AOwner.Add(Self);
if Column <> nil then
with Column do
begin
FCaption := Caption;
FWidth := Width;
FWidthType := WidthType;
FIndex := Index;
FAlignment := Alignment;
end
else begin
FWidth := 50;
FIndex := Index;
FAlignment := taLeftJustify;
end;
end;
destructor TColInfo.Destroy;
begin
Owner.Remove(Self);
inherited Destroy;
end;
function TColInfo.GetIndex: Integer;
begin
Result := Owner.IndexOf(Self);
end;
{ TListViewColumns }
procedure TListViewColumns.ValueChanged(Sender: TObject);
begin
Apply.Enabled := True;
if Sender = TextEdit then TextEditExit(Sender);
end;
procedure TListViewColumns.DeleteClick(Sender: TObject);
var
I, OldIndex: Integer;
begin
with ColumnListBox do
if ItemIndex <> -1 then
begin
OldIndex := ItemIndex;
ColItems[ItemIndex].Free;
Items.Delete(ItemIndex);
if Items.Count > 0 then
begin
if OldIndex = Items.Count then Dec(OldIndex);
for I := OldIndex to Items.Count - 1 do
SetListBoxText(I, ListBoxText(ColItems[I]));
ItemIndex := OldIndex;
end;
ColumnListBoxClick(nil);
end;
SetStates;
Apply.Enabled := True;
end;
procedure TListViewColumns.SetListBoxText(Index: Integer; const S: string);
var
TempIndex: Integer;
begin
with ColumnListBox do
begin
TempIndex := ItemIndex;
Items[Index] := S;
ItemIndex := TempIndex;
end;
end;
procedure TListViewColumns.TextEditExit(Sender: TObject);
begin
with ColumnListBox do
if ItemIndex <> -1 then
begin
ColItems[ItemIndex].FCaption := TextEdit.Text;
SetListBoxText(ItemIndex, ListBoxText(ColItems[ItemIndex]));
end;
end;
procedure TListViewColumns.IndexEditExit(Sender: TObject);
begin
{if ActiveControl <> Cancel then
try
with ColumnListBox do
if (ItemIndex <> -1) and (IndexEdit.Text <> '') then
ColItems[ItemIndex].FIndex := StrToInt(IndexEdit.Text);
except
ConvertError(IndexEdit);
raise;
end;}
end;
procedure TListViewColumns.WidthEditExit(Sender: TObject);
begin
if ActiveControl <> Cancel then
try
with ColumnListBox do
if (ItemIndex <> -1) and (WidthEdit.Text <> '') then
ColItems[ItemIndex].FWidth := StrToInt(WidthEdit.Text);
except
ConvertError(WidthEdit);
raise;
end;
end;
procedure TListViewColumns.AlignmentEditExit(Sender: TObject);
begin
with ColumnListBox do
if ItemIndex <> -1 then
ColItems[ItemIndex].FAlignment := TAlignment(AlignmentEdit.ItemIndex);
end;
procedure TListViewColumns.FlushControls;
begin
TextEditExit(nil);
IndexEditExit(nil);
WidthEditExit(nil);
AlignmentEditExit(nil);
end;
procedure TListViewColumns.GetItem(Value: TListColumn);
var
ColInfo: TColInfo;
begin
with Value do
begin
ColInfo := InfoList[Index];
Caption := ColInfo.FCaption;
if ColInfo.FWidthType = ColumnTextWidth then
Width := ColumnTextWidth
else if ColInfo.FWidthType = ColumnHeaderWidth then
Width := ColumnHeaderWidth
else Width := ColInfo.FWidth;
ColInfo.FWidth := Width;
Alignment := ColInfo.FAlignment;
end
end;
procedure TListViewColumns.SetItem(Value: TColInfo);
begin
if Value <> nil then
with Value do
begin
TextEdit.Text := FCaption;
WidthEdit.Text := IntToStr(FWidth);
if FWidthType = ColumnHeaderWidth then
HWidthBtn.Checked := True
else if FWidthType = ColumnTextWidth then
IWidthBtn.Checked := True
else WidthBtn.Checked := True;
{IndexEdit.Text := IntToStr(FIndex);}
AlignmentEdit.ItemIndex := Ord(FAlignment);
AlignmentEdit.Enabled := FIndex <> 0;
end
else begin
TextEdit.Text := '';
WidthEdit.Text := '';
WidthBtn.Checked := True;
{IndexEdit.Text := '';}
AlignmentEdit.ItemIndex := -1;
end;
end;
procedure TListViewColumns.ColumnListBoxClick(Sender: TObject);
var
TempEnabled: Boolean;
begin
TempEnabled := Apply.Enabled;
with ColumnListBox do
if ItemIndex <> -1 then SetItem(ColItems[ItemIndex])
else SetItem(nil);
Apply.Enabled := TempEnabled;
end;
procedure TListViewColumns.NewClick(Sender: TObject);
var
ColInfo: TColInfo;
begin
FlushControls;
ColInfo := TColInfo.Create(FInfoList, nil);
with ColumnListBox do
begin
Items.Add(ListBoxText(ColInfo));
ItemIndex := ColInfo.Index;
end;
SetItem(ColInfo);
SetStates;
TextEdit.SetFocus;
Apply.Enabled := True;
end;
procedure TListViewColumns.SetStates;
begin
Delete.Enabled := ColumnListBox.Items.Count > 0;
PropGroupBox.Enabled := Delete.Enabled;
Apply.Enabled := False;
AlignmentEdit.Enabled := ColumnListBox.ItemIndex > 0;
end;
function TListViewColumns.ListBoxText(Value: TColInfo): string;
begin
with Value do
begin
Result := FCaption;
if Result = '' then Result := DefaultText;
FmtStr(Result, '%d - %s', [InfoList.IndexOf(Value), Result])
end;
end;
procedure TListViewColumns.FormCreate(Sender: TObject);
begin
FDefaultText := SUntitled;
FInfoList := TList.Create;
HelpContext := hcDListViewColEdit;
end;
procedure TListViewColumns.FormDestroy(Sender: TObject);
begin
while FInfoList.Count > 0 do TColInfo(FInfoList.Last).Free;
FInfoList.Free;
end;
procedure TListViewColumns.ApplyClick(Sender: TObject);
var
I: Integer;
begin
FlushControls;
Columns.Clear;
for I := 0 to InfoList.Count - 1 do
begin
GetItem(Columns.Add);
SetListBoxText(I, ListBoxText(InfoList[I]));
end;
Apply.Enabled := False;
with TListView(Columns.Owner) do UpdateItems(0, Items.Count -1);
ColumnListBoxClick(nil);
end;
function TListViewColumns.GetColInfo(Index: Integer): TColInfo;
begin
Result := InfoList[Index];
end;
procedure TListViewColumns.ColumnListBoxDragOver(Sender, Source: TObject;
X, Y: Integer; State: TDragState; var Accept: Boolean);
var
Index: Integer;
begin
with ColumnListBox do
begin
Index := ItemAtPos(Point(X, Y), True);
Accept := Index <> FDragIndex;
if Index <> LB_ERR then ItemIndex := Index;
end;
end;
procedure TListViewColumns.ColumnListBoxDragDrop(Sender, Source: TObject;
X, Y: Integer);
var
I, Index, StartIndex: Integer;
begin
with ColumnListBox do
begin
Index := ItemAtPos(Point(X, Y), True);
StartIndex := Index;
if (Index <> LB_ERR) and (FDragIndex <> LB_ERR) then
begin
Items.Move(FDragIndex, Index);
InfoList.Move(FDragIndex, Index);
if FDragIndex < Index then Index := FDragIndex;
for I := Index to Items.Count - 1 do
SetListBoxText(I, ListBoxText(ColItems[I]));
Apply.Enabled := True;
ItemIndex := StartIndex;
end;
end;
end;
procedure TListViewColumns.ColumnListBoxStartDrag(Sender: TObject;
var DragObject: TDragObject);
begin
FDragIndex := ColumnListBox.ItemIndex;
end;
procedure TListViewColumns.ColumnListBoxEndDrag(Sender, Target: TObject; X,
Y: Integer);
begin
FDragIndex := LB_ERR;
end;
procedure TListViewColumns.ColumnListBoxMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
with ColumnListBox do
if ItemAtPos(Point(X, Y), True) = ItemIndex then BeginDrag(False);
end;
procedure TListViewColumns.HWidthBtnClick(Sender: TObject);
begin
with ColumnListBox do
if ItemIndex <> -1 then
with ColItems[ItemIndex] do
begin
if Sender = HWidthBtn then FWidthType := ColumnHeaderWidth
else if Sender = IWidthBtn then FWidthType := ColumnTextWidth
else if Sender = WidthBtn then
begin
FWidth := StrToInt(WidthEdit.Text);
FWidthType := FWidth;
end;
WidthEdit.Enabled := Sender = WidthBtn;
Apply.Enabled := True;
end;
end;
procedure TListViewColumns.HelpClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
end.
|
///// <summary>
///// Функция ищет файлы и, если необходимо, добавляет информацию о них.
///// </summary>
/////
///// <param name="StartPath">С этого каталога начинается поиск.</param>
/////
///// <param name="Pattern">Шаблон поиска. Для большей информации
///// смотрите "регулярные выражения".</param>
/////
///// <param name="Recursive">=TRUE, поиск по всем подкаталогам.
///// =FALSE, искать только в каталоге StartPath.</param>
/////
///// <param name="AddInfo">=TRUE, добавить информацию о файле
///// (размер, атрибуты, время: создания, модификации, доступа). Для подробностей
///// см. <see cref="shared.FileUtils.TFindFileInfo"/></param>
/////
///// <param name="RemoveStartPath">=TRUE, из имени найденного файла
///// удаляется стартовый каталог.</param>
/////
///// <param name="StatProc">Необязательный. По умолчанию = nil. Процедура для
///// отобажения прогресса операции. Для подробностей - смотрите описание
///// класса <see cref="shared.ProgressMessage.TProgressMessage"/>.
///// </param>
/////
///// <param name="StatUpdateInterval">Необязательный. Значение по умолчанию = 1500.
///// Время, через которое нужно вызывать функцию StatProc.</param>
/////
///// <returns>
///// Функция возвращает список имён файлов, в объекте <see cref="System.SysUtils.TStringList"/>.
///// </returns>
/////
///// <remarks>Рекомендуется задавать StatUpdateInterval = 1000-1500.</remarks>
//function FindFiles(const StartPath: String;
// const Pattern: String;
// Options: TFindFilesOptions;
// StatProc: TProgressMessageProc = nil;
// StatUpdateInterval: Cardinal = 1500): TFileList;
//function FindFiles(const StartPath: String;
// const Pattern: String;
// Options: TFindFilesOptions;
// StatProc: TProgressMessageProc = nil;
// StatUpdateInterval: Cardinal = 1500): TFileList;
//var
// CurrentPath: String;
// FileInfo: TFileCharacteristics;
// //
// S: TProgressMessage;
// RegEx: TRegEx;
//
//procedure FindHelper;
//var
// FF: THandle;
// WS: WIN32_FIND_DATA;
// SaveLength: Integer;
// //
// FullFileName: String;
//begin
//{ DONE -cvery important :
//Объединить part1 и part2, т.к. сигнатуры поиска ( путь + '*' ) одинаковые.
//А в текущий момент поиск происходит 2 раза: первый проход - файлы, второй проход - каталоги
//===ИСПРАВЛЕНО}
//
// // Проверка: а вдруг в пути уже присутствует расширенный префикс ?
// if TPath.IsExtendedPrefixed(CurrentPath) then
// FF := FindFirstFileW( PChar(CurrentPath + ALL_FILES_MSDOSMASK), WS)
// else
// FF := FindFirstFileW( PChar(EXTENDED_PATH_PREFIX + CurrentPath + ALL_FILES_MSDOSMASK), WS);
// if FF <> INVALID_HANDLE_VALUE then
// begin
// repeat
// // Обрабатываем ФАЙЛ
// if (WS.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) = 0 then
// begin
// // Сравниваем с маской (используем нашу процедуру сравнения, т.к.
// // системная для маски *.md5 находит файлы checksum.md5, checksum.md5abc)
// // 30/10/2016 YS UPDATE: Теперь используем шаблоны RegEx
// if NOT RegEx.IsMatch(WS.cFileName) then Continue;
// // Нашли файл
// S[0] := S[0] + 1;
// // Добавляем информацию о файле
// if ffoptAddInfo in Options then
// begin
// FileInfo := TFileCharacteristics.Create;
// FileInfo.Attr.Assign(WS);
// end else FileInfo := nil;
// // Вычисляем путь к файлу
// FullFileName := CurrentPath + WS.cFileName;
// if ffoptRemoveStartPath in Options then FullFileName := GetLocalFileName(StartPath, FullFileName);
// //
// Result.AddObject(FullFileName, FileInfo);
// //
// end else if (WS.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) = FILE_ATTRIBUTE_DIRECTORY then
// begin
// // Only if recursive!!!
// if ffoptRecursive in Options then
// begin
// // Папки с именами '.' и '..' не нужны!
// if IsRootOrPrevCatalog(WS) then Continue;
//
// // Нашли папку
// S[1] := S[1] + 1;
//
// // Сформировать новый текущий путь
// SaveLength := CurrentPath.Length;
// CurrentPath := CurrentPath + WS.cFileName + PathDelim;
//
// // recursive scan
// FindHelper;
//
// // Восстановить старый путь
// SetLength(CurrentPath, SaveLength);
// end;
// end;
// S.Show(smNORMAL);
// until NOT FindNextFile( FF, WS );
// FindClose(FF);
// end;
//end;
//
//begin
// // Инициализация переменных
// S := TProgressMessage.Create(StatProc, StatUpdateInterval);
// Result := TFileList.Create;
// Result.OwnsObjects := TRUE;
// //
// RegEx := TRegEx.Create(Pattern, [roIgnoreCase, roCompiled, roSingleLine]);
// // Готовим стартовый путь
// CurrentPath := IncludeTrailingPathDelimiter(StartPath);
// // Поехали!
// S.Show(smNORMAL);
// FindHelper;
// S.Show(smDONE);
// // Заключительная обработка
// //Result.Sort;
// S.Free;
//end;
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Importer for legacy XML Schema files }
{ }
{ Copyright (c) 2000-2001 Borland Software Corporation }
{ }
{*******************************************************}
unit XMLSchema99;
interface
uses SysUtils, XMLSchema, xmldom, XMLDoc, XMLIntf;
type
{ TXMLSchema1999TranslatorFactory }
TXMLSchema1999TranslatorFactory = class(TXMLSchemaTranslatorFactory)
protected
function CanImportFile(const FileName: WideString): Boolean; override;
end;
{ TXMLSchema1999Translator }
TXMLSchema1999Translator = class(TXMLSchemaTranslator)
private
FOldSchema: IXMLSchemaDef;
protected
procedure CopyAttrNodes(const SourceNode, DestNode: IXMLNode);
procedure CopyChildNodes(const SourceNode, DestNode: IXMLNode);
procedure CopyComplexType(const ComplexTypeDef: IXMLComplexTypeDef;
const DestNode: IXMLNode);
procedure CopySimpleType(const SimpleTypeDef: IXMLSimpleTypeDef;
const DestNode: IXMLNode);
{ Data member access }
property OldSchema: IXMLSchemaDef read FOldSchema;
public
procedure Translate(const FileName: WideString; const SchemaDef: IXMLSchemaDef); override;
end;
{ TXMLComplexTypeDef99 }
TXMLComplexTypeDef99 = class(TXMLComplexTypeDef)
public
procedure AfterConstruction; override;
end;
{ TXMLSchemaDoc99 }
TXMLSchemaDoc99 = class(TXMLSchemaDoc)
protected
function GetChildNodeClass(const Node: IDOMNode): TXMLNodeClass; override;
procedure CheckSchemaVersion; override;
procedure LoadData; override;
public
procedure AfterConstruction; override;
end;
implementation
uses XMLSchemaTags;
var
TranslatorFactory: IXMLSchemaTranslatorFactory;
resourcestring
SDescription = '1999 XML Schema Translator (.xsd <-> .xsd)';
{ TXMLSchema1999TranslatorFactory }
function TXMLSchema1999TranslatorFactory.CanImportFile(
const FileName: WideString): Boolean;
var
Doc: IXMLDocument;
begin
Result := inherited CanImportFile(FileName);
if Result then
try
Doc := LoadXMLDocument(FileName);
Result := not Doc.IsEmptyDoc and (Doc.DocumentElement.FindNamespaceDecl(SXMLSchemaURI_1999) <> nil);
except
Result := False;
end;
end;
{ TXMLSchema1999Translator }
procedure TXMLSchema1999Translator.CopyAttrNodes(const SourceNode,
DestNode: IXMLNode);
var
I: Integer;
TypeName, AttrName: DOMString;
begin
for I := 0 to SourceNode.AttributeNodes.Count - 1 do
begin
AttrName := SourceNode.AttributeNodes[I].NodeName;
{ Don't copy attribute if it's name is 'base' or if it's already there }
if (AttrName <> SBase) and not DestNode.HasAttribute(AttrName) then
DestNode.AttributeNodes.Add(SourceNode.AttributeNodes[I].CloneNode(True));
{ Fixup and "type" attributes that point to built in types }
if AttrName = SType then
begin
TypeName := SourceNode.Attributes[SType];
if ExtractPrefix(TypeName) = SourceNode.Prefix then
DestNode.Attributes[SType] := MakeNodeName(DestNode.Prefix, ExtractLocalName(TypeName));
end;
end;
end;
procedure TXMLSchema1999Translator.CopyChildNodes(const SourceNode,
DestNode: IXMLNode);
var
I: Integer;
DestChild, ChildNode: IXMLNode;
ComplexTypeDef: IXMLComplexTypeDef;
SimpleTypeDef: IXMLSimpleTypeDef;
begin
for I := 0 to SourceNode.ChildNodes.Count - 1 do
begin
ChildNode := SourceNode.ChildNodes[I];
if Supports(ChildNode, IXMLComplexTypeDef, ComplexTypeDef) then
{ ComplexTypes have to be copied specially }
CopyComplexType(ComplexTypeDef, DestNode)
else if Supports(ChildNode, IXMLSimpleTypeDef, SimpleTypeDef) then
{ as do SimpleTypes }
CopySimpleType(SimpleTypeDef, DestNode)
else
begin
if ChildNode.NodeType = ntElement then
begin
{ Need to copy elements this way to avoid getting the source namespace }
DestChild := DestNode.AddChild(ChildNode.LocalName);
CopyAttrNodes(ChildNode, DestChild);
end else
{ Everything else we can just clone }
DestNode.ChildNodes.Add(ChildNode.CloneNode(False));
if ChildNode.HasChildNodes then
{ Going down... }
CopyChildNodes(ChildNode, DestChild);
end;
end;
end;
procedure TXMLSchema1999Translator.CopyComplexType(
const ComplexTypeDef: IXMLComplexTypeDef; const DestNode: IXMLNode);
var
I: Integer;
NewChild, ChildNode: IXMLNode;
ElementGroup: IXMLElementGroup;
ElementDef: IXMLElementDef;
NewComplexType: IXMLComplexTypeDef;
ContentModel: TContentModel;
Annotation: IXMLAnnotation;
begin
NewComplexType := DestNode.AddChild(SComplexType) as IXMLComplexTypeDef;
ContentModel := cmSequence;
{ Content Model is based on existing compositor when there is only one }
if (ComplexTypeDef.ElementCompositors.Count = 1) then
case ComplexTypeDef.ElementCompositors[0].CompositorType of
ctAll: ContentModel := cmAll;
ctChoice: ContentModel := cmChoice;
end
{ If no compositor and no direct elements and one group then use the group }
else if (ComplexTypeDef.ElementCompositors.Count = 0) and
(ComplexTypeDef.ElementDefs.Count = 0) and
(ComplexTypeDef.ElementGroups.Count = 1) then
ContentModel := cmGroupRef;
{ Set the new content model }
NewcomplexType.ContentModel := ContentModel;
if not ComplexTypeDef.IsAnonymous then
NewcomplexType.Name := ComplexTypeDef.Name;
{ Copy the contents }
for I := 0 to ComplexTypeDef.ChildNodes.Count - 1 do
begin
ChildNode := ComplexTypeDef.ChildNodes[I];
if Supports(ChildNode, IXMLElementDef, ElementDef) then
begin
{ Copy Elements appearing directly below the type }
if ElementDef.RefName <> '' then
NewChild := NewComplexType.ElementDefs.Add(ElementDef.RefName)
else if ElementDef.DataType.IsAnonymous then
NewChild := NewComplexType.ElementDefs.Add(ElementDef.Name, '')
else
NewChild := NewComplexType.ElementDefs.Add(ElementDef.Name,
ExtractLocalName(ElementDef.DataTypeName));
end
else if Supports(ChildNode, IXMLElementGroup, ElementGroup) then
{ Groups need to be copied by hand as well }
NewChild := NewComplexType.ElementGroups.Add(ElementGroup.RefName)
else if Supports(ChildNode, IXMLAnnotation, Annotation) then
{ Annotations must go first into the list }
NewChild := NewComplexType.AddChild(SAnnotation, 0)
else
{ All other child node we can copy directly }
NewChild := NewComplexType.AddChild(ChildNode.LocalName);
CopyAttrNodes(ChildNode, NewChild);
if ChildNode.HasChildNodes then
CopyChildNodes(ChildNode, NewChild);
end;
end;
procedure TXMLSchema1999Translator.CopySimpleType(
const SimpleTypeDef: IXMLSimpleTypeDef; const DestNode: IXMLNode);
var
NewSimpleType: IXMLSimpleTypeDef;
begin
NewSimpleType := DestNode.AddChild(SSimpleType) as IXMLSimpleTypeDef;
NewSimpleType.BaseTypeName := ExtractLocalName(SimpleTypeDef.Attributes[SBase]);
if not SimpleTypeDef.IsAnonymous then
NewSimpleType.Name := SimpleTypeDef.Name;
{ Copy Enumerations and Facets }
CopyChildNodes(SimpleTypeDef, NewSimpleType.RestrictionNode);
end;
procedure TXMLSchema1999Translator.Translate(const FileName: WideString;
const SchemaDef: IXMLSchemaDef);
var
OldSchemaDoc: IXMLSchemaDoc;
begin
inherited;
OldSchemaDoc := TXMLSchemaDoc99.Create(FileName);
FOldSchema := OldSchemaDoc.SchemaDef;
CopyChildNodes(FOldSchema, SchemaDef);
end;
{ TXMLComplexTypeDef99 }
procedure TXMLComplexTypeDef99.AfterConstruction;
begin
inherited;
{ Unregister ComplexContent and SimpleContent that are not valid in this version }
RegisterChildNodes([SComplexContent, SSimpleContent], [nil, nil]);
{ Complextypes in this version can have direct child elements }
RegisterChildNode(SElement, TXMLElementDef);
end;
{ TXMLSchemaDoc99 }
procedure TXMLSchemaDoc99.AfterConstruction;
begin
inherited;
end;
procedure TXMLSchemaDoc99.CheckSchemaVersion;
begin
{ Disable validation }
end;
function TXMLSchemaDoc99.GetChildNodeClass(const Node: IDOMNode): TXMLNodeClass;
begin
if NodeMatches(Node, SComplexType, SXMLSchemaURI_1999) then
Result := TXMLComplexTypeDef99
else
Result := nil;
end;
procedure TXMLSchemaDoc99.LoadData;
begin
{ Prevent recursion when we load the old schema document }
EnableTranslation := False;
inherited;
{ Register the default class, but with the older namespace }
RegisterDocBinding(SSchema, TXMLSchemaDef, SXMLSchemaURI_1999);
// GetSchemaDef.SimpleTypes.Add(MakeNodeName(GetSchemaDef.Prefix, 'decimal'), 'number');
end;
initialization
TranslatorFactory := TXMLSchema1999TranslatorFactory.Create(
TXMLSchema1999Translator, nil, SXMLSchemaExt, SDescription);
RegisterSchemaTranslator(TranslatorFactory);
finalization
UnRegisterSchemaTranslator(TranslatorFactory);
end.
|
{ ---------------------------------------------------------------------------- }
{ BulbTracer for MB3D }
{ Copyright (C) 2016-2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit VectorMath;
interface
uses
SysUtils, Classes, Contnrs;
type
TD3Vector = packed record
X, Y, Z: Double;
end;
TPD3Vector = ^TD3Vector;
TDVectorMath = class
public
class procedure Clear(const V: TPD3Vector);
class procedure Normalize(const V: TPD3Vector);
class function Length(const V: TPD3Vector): Double;
class procedure Flip(const V: TPD3Vector);
class procedure NormalizeAndScalarMul(const V: TPD3Vector; const Factor: Double);
class procedure Add(const A, B, Dest: TPD3Vector);
class procedure Subtract(const A, B, Dest: TPD3Vector);
class procedure AddTo(const Dest, Other: TPD3Vector);
class procedure ScalarMul(const A: Double; const B: TPD3Vector; const Product: TPD3Vector);
class procedure Assign(const Dest, Src: TPD3Vector);
class function DotProduct(const A, B: TPD3Vector): Double;
class procedure CrossProduct(const A, B, Product: TPD3Vector);
class procedure NonParallel(const Dest, V: TPD3Vector);
class function IsNull(const V: TPD3Vector): Boolean;
class procedure SetValue(const V: TPD3Vector; const X, Y, Z: Double);
end;
TS3Vector = packed record
X, Y, Z: Single;
end;
TPS3Vector = ^TS3Vector;
TS4Vector = packed record
X, Y, Z, W: Single;
end;
TPS4Vector = ^TS4Vector;
TSMI3Vector = packed record
X, Y, Z: Smallint;
end;
TPSMI3Vector = ^TSMI3Vector;
TSVectorMath = class
public
class procedure Subtract(const A, B, Dest: TPS3Vector);
class procedure Normalize(const V: TPS3Vector);
class function Length(const V: TPS3Vector): Double;
class procedure AddTo(const Dest, Other: TPS3Vector);
class procedure CrossProduct(const A, B, Product: TPS3Vector);
class function DotProduct(const A, B: TPS3Vector): Double;
class procedure ScalarMul(const A: Double; const B: TPS3Vector; const Product: TPS3Vector);
class procedure SetValue(const V: TPS3Vector; const X, Y, Z: Single);
class procedure Clear(const V: TPS3Vector);
end;
TD3Matrix = packed record
M: Array [0..2, 0..2] of Double;
end;
TPD3Matrix = ^TD3Matrix;
TDMatrixMath = class
public
class procedure Identity(const M: TPD3Matrix);
class procedure Multiply(const A, B, Product: TPD3Matrix);overload;
class procedure ScalarMul(const A: Double; const B, Product: TPD3Matrix);
class procedure Add(const A, B, Sum: TPD3Matrix);overload;
class procedure VMultiply(const A: TPD3Vector; const B: TPD3Matrix; const Product: TPD3Vector);overload;
end;
implementation
{ ----------------------------- TDVectorMath --------------------------------- }
const
EPS = 1e-100;
class procedure TDVectorMath.Clear(const V: TPD3Vector);
begin
with V^ do begin
X := 0.0;
Y := 0.0;
Z := 0.0;
end;
end;
class function TDVectorMath.Length(const V: TPD3Vector): Double;
begin
with V^ do begin
Result := Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z));
end;
end;
class procedure TDVectorMath.Normalize(const V: TPD3Vector);
var
L: Double;
begin
with V^ do begin
L := 1.0 / Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z) + EPS);
X := X * L;
Y := Y * L;
Z := Z * L;
end;
end;
class function TDVectorMath.IsNull(const V: TPD3Vector): Boolean;
begin
with V^ do begin
Result := (Abs(X) <= EPS) and (Abs(Y) <= EPS) and (Abs(Z) <= EPS);
end;
end;
class procedure TDVectorMath.SetValue(const V: TPD3Vector; const X, Y, Z: Double);
begin
V^.X := X;
V^.Y := Y;
V^.Z := Z;
end;
class procedure TDVectorMath.Flip(const V: TPD3Vector);
begin
with V^ do begin
X := 0.0 - X;
Y := 0.0 - Y;
Z := 0.0 - Z;
end;
end;
class procedure TDVectorMath.NormalizeAndScalarMul(const V: TPD3Vector; const Factor: Double);
var
S: Double;
begin
with V^ do begin
S := Factor / Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z) + 1e-100);
X := X * S;
X := Y * S;
Z := Z * S;
end;
end;
class procedure TDVectorMath.ScalarMul(const A: Double; const B: TPD3Vector; const Product: TPD3Vector);
begin
with Product^ do begin
X := A * B^.X;
Y := A * B^.Y;
Z := A * B^.Z;;
end;
end;
class procedure TDVectorMath.Assign(const Dest, Src: TPD3Vector);
begin
with Dest^ do begin
X := Src^.X;
Y := Src^.Y;
Z := Src^.Z;
end;
end;
class procedure TDVectorMath.NonParallel(const Dest, V: TPD3Vector);
var
C: TD3Vector;
begin
if IsNull(V) then begin
Dest^.X := 0.0;
Dest^.Y := 0.0;
Dest^.Z := 1.0;
exit;
end;
while True do begin
Dest^.X := 0.5 - Random;
Dest^.Y := 0.5 - Random;
Dest^.Z := 0.5 - Random;
CrossProduct(Dest, V, @C);
if not IsNull(@C) then
break;
end;
end;
class procedure TDVectorMath.Add(const A, B, Dest: TPD3Vector);
begin
with Dest^ do begin
X := A^.X + B^.X;
Y := A^.Y + B^.Y;
Z := A^.Z + B^.Z;
end;
end;
class procedure TDVectorMath.Subtract(const A, B, Dest: TPD3Vector);
begin
with Dest^ do begin
X := A^.X - B^.X;
Y := A^.Y - B^.Y;
Z := A^.Z - B^.Z;
end;
end;
class procedure TDVectorMath.AddTo(const Dest, Other: TPD3Vector);
begin
with Dest^ do begin
X := X + Other^.X;
Y := Y + Other^.Y;
Z := Z + Other^.Z;
end;
end;
class function TDVectorMath.DotProduct(const A, B: TPD3Vector): Double;
begin
Result := A^.X * B^.X + A^.Y * B^.Y + A^.Z * B^.Z;
end;
class procedure TDVectorMath.CrossProduct(const A, B, Product: TPD3Vector);
begin
with Product^ do begin
X := A^.Y * B^.Z - A^.Z * B^.Y;
Y := A^.Z * B^.X - A^.X * B^.Z;
Z := A^.X * B^.Y - A^.Y * B^.X;
end;
end;
{ ----------------------------- TSVectorMath --------------------------------- }
class procedure TSVectorMath.Clear(const V: TPS3Vector);
begin
with V^ do begin
X := 0.0;
Y := 0.0;
Z := 0.0;
end;
end;
class procedure TSVectorMath.Normalize(const V: TPS3Vector);
var
L: Double;
begin
with V^ do begin
L := 1.0 / Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z) + EPS);
X := X * L;
Y := Y * L;
Z := Z * L;
end;
end;
class function TSVectorMath.Length(const V: TPS3Vector): Double;
begin
with V^ do begin
Result := Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z));
end;
end;
class procedure TSVectorMath.SetValue(const V: TPS3Vector; const X, Y, Z: Single);
begin
V^.X := X;
V^.Y := Y;
V^.Z := Z;
end;
class procedure TSVectorMath.ScalarMul(const A: Double; const B: TPS3Vector; const Product: TPS3Vector);
begin
with Product^ do begin
X := A * B^.X;
Y := A * B^.Y;
Z := A * B^.Z;;
end;
end;
class procedure TSVectorMath.Subtract(const A, B, Dest: TPS3Vector);
begin
with Dest^ do begin
X := A^.X - B^.X;
Y := A^.Y - B^.Y;
Z := A^.Z - B^.Z;
end;
end;
class function TSVectorMath.DotProduct(const A, B: TPS3Vector): Double;
begin
Result := A^.X * B^.X + A^.Y * B^.Y + A^.Z * B^.Z;
end;
class procedure TSVectorMath.CrossProduct(const A, B, Product: TPS3Vector);
begin
with Product^ do begin
X := A^.Y * B^.Z - A^.Z * B^.Y;
Y := A^.Z * B^.X - A^.X * B^.Z;
Z := A^.X * B^.Y - A^.Y * B^.X;
end;
end;
class procedure TSVectorMath.AddTo(const Dest, Other: TPS3Vector);
begin
with Dest^ do begin
X := X + Other^.X;
Y := Y + Other^.Y;
Z := Z + Other^.Z;
end;
end;
{ ----------------------------- TDMatrixMath --------------------------------- }
class procedure TDMatrixMath.ScalarMul(const A: Double; const B, Product: TPD3Matrix);
var
I, J: Integer;
begin
with Product^ do begin
for I := 0 to 2 do begin
for J:=0 to 2 do begin
M[I, J] := A * B^.M[I, J];
end;
end;
end;
end;
class procedure TDMatrixMath.Identity(const M: TPD3Matrix);
begin
with M^ do begin
M[0, 0] := 1.0;
M[0, 1] := 0.0;
M[0, 2] := 0.0;
M[1, 0] := 0.0;
M[1, 1] := 1.0;
M[1, 2] := 0.0;
M[2, 0] := 0.0;
M[2, 1] := 0.0;
M[2, 2] := 1.0;
end;
end;
class procedure TDMatrixMath.Add(const A, B, Sum: TPD3Matrix);
var
I, J: Integer;
begin
with Sum^ do begin
for I := 0 to 2 do begin
for J := 0 to 2 do begin
M[I, J] := A^.M[I, J] + B^.M[I, J];
end;
end;
end;
end;
class procedure TDMatrixMath.Multiply(const A, B, Product: TPD3Matrix);
var
I, J, S: Integer;
begin
with Product^ do begin
for I := 0 to 2 do begin
for J := 0 to 2 do begin
M[I, J] := 0.0;
for S := 0 to 2 do begin
M[I, J] := M[I, J] + A^.M[I, S] * B^.M[S, J];
end;
end;
end;
end;
end;
class procedure TDMatrixMath.VMultiply(const A: TPD3Vector; const B: TPD3Matrix; const Product: TPD3Vector);
begin
with Product^ do begin
X := A^.X * B^.M[0, 0] + A^.Y * B^.M[0, 1] + A^.Z * B^.M[0, 2];
Y := A^.X * B^.M[1, 0] + A^.Y * B^.M[1, 1] + A^.Z * B^.M[1, 2];
Z := A^.X * B^.M[2, 0] + A^.Y * B^.M[2, 1] + A^.Z * B^.M[2, 2];
end;
end;
end.
|
{ Compute the cosine using the expansion:
cos(x) = 1 - x**2/(2*1) + x**4/(4*3*2*1) - ...
This file verifies a simple unit that exports one function.
}
unit MyCosineUnit;
interface
function mycosine(x : real) : real;
implementation
function mycosine(x : real) : real;
const
eps = 1e-14;
var
sx, s, t : real;
i, k : integer;
begin
t := 1;
k := 0;
s := 1;
sx := sqr(x);
while abs(t) > eps*abs(s) do
begin
k := k + 2;
t := -t * sx / (k * (k - 1));
s := s + t;
end;
mycosine := s
end; { mycosine }
end.
|
//******************************************************************************
// File : Lua_Object.pas (rev. 1.1)
//
// Description : Access from Lua scripts to TObject Classes
//
//******************************************************************************
// Exported functions :
//
// CreateObject(string className, bool CanFree [, param1, ..paramN]) return a new TObject.
// GetObject(string Name) return an existing TObject.
//
// TObject.PropertyName return Property Value as Variant.
// TObject.PropertyName = (variant Value) set Property Value.
// TObject:<method name>([param1, .., paramN]) call <method name>, return Result as Variant.
// TObject:Free() free the object, return True on success.
// TO-DO :
// funzioni lua da esportare :
// enumval(Type :???, value :string) enumstr(Type :???, value :Integer???)
// nei metodi dove c'è var, come lo torno in Lua?
// * gestione del garbage collector (metafunction _gc)
// COMMENTARE IL CODICE MENTRO ME LO RICORDO
unit Lua_System;
interface
uses Lua, Script_System;
procedure RegisterFunctions(L: Plua_State);
implementation
uses ObjAuto, ScriptableObject, TypInfo, SysUtils, LuaUtils, lauxlib, Variants, VarUtils;
const
OBJHANDLE_STR ='Lua_TObjectHandle';
ARRAYPROP_STR ='Lua_TObjectArrayProp';
ARRAYPROPNAME_STR ='Lua_TObjectArrayPropName';
SETPROP_VALUE ='Lua_TObjectSetPropvalue';
SETPROP_INFO ='Lua_TObjectSetPropINFO';
type
//Record stored in lua stack to mantain TScriptObject
TScriptObjectData = packed record
ID : String[20];
Obj :TScriptObject;
end;
PScriptObjectData =^TScriptObjectData;
TLuaArrayPropData = record
ID : String[20];
Obj :TScriptObject;
PropName :string;
end;
TLuaSetPropData = record
ID :String[20];
Info :PTypeInfo;
Value :string;
end;
PLuaSetPropData = ^TLuaSetPropData;
//==============================================================================
// "Push a Value in the Stack" Functions
function GetPropertyArrayObject(var Data : TLuaArrayPropData; L: Plua_State; Index: Integer): boolean; forward;
function LuaPush_TScriptObject(L :Plua_State; theParams :array of Variant;
Obj :TObject=nil; ObjClassName :String='';
CanFree :Boolean=True) :boolean; forward;
function LuaPushPropertyArrayObject(L: Plua_State; Obj :TScriptObject; PropName :string): boolean; forward;
function LuaPushPropertySet(L: Plua_State; TypeInfo :PTypeInfo; PropValue :Variant): boolean; forward;
function PushProperty(L :Plua_State; scripter :TScriptObject;
PropName :string; PropValue :Variant; PropType :PTypeInfo) :Integer;
begin
Result :=0;
if (PropType^.Kind = tkClass)
then begin
//If this property is a class, push a TScriptObject in the stack
if LuaPush_TScriptObject(L, [], TObject(Integer(PropValue)))
then Result := 1;
end
else
if (PropType^.Kind =tkArray)
then begin //If this property is an array, push an ArrayPropObject in the stack
if LuaPushPropertyArrayObject(L, scripter, PropName)
then Result := 1;
end
else
if (PropType^.Kind =tkSet)
then begin //If this property is an array, push an ArrayPropObject in the stack
if LuaPushPropertySet(L, PropType, PropValue)
then Result := 1;
end
else
begin //Push the PropValue
LuaPushVariant(L, PropValue);
Result := 1;
end;
end;
function PushMethodResult(L :Plua_State; scripter :TScriptObject; Value :Variant; ValueType :PReturnInfo) :Integer;
begin
Result :=0;
if (ValueType^.ReturnType^.Kind = tkClass)
then begin
//If this property is a class, push a TScriptObject in the stack
if LuaPush_TScriptObject(L, [], TObject(Integer(Value)))
then Result := 1;
end
else
if (ValueType^.ReturnType^.Kind =tkSet)
then begin //If this property is an array, push an ArrayPropObject in the stack
if LuaPushPropertySet(L, ValueType^.ReturnType^, Value)
then Result := 1;
end
else
begin //Push the PropValue
LuaPushVariant(L, Value);
Result := 1;
end;
end;
//==============================================================================
// Array Properties Support
function Lua_IsPropertyArrayObject(L: Plua_State; Index: Integer): boolean;
begin
Result :=False;
try
Result :=(LuaGetTableString(L, Index, 'ID')=ARRAYPROP_STR);
except
end;
end;
function GetPropertyArrayObject(var Data : TLuaArrayPropData; L: Plua_State; Index: Integer): boolean;
begin
Result :=false;
try
Data.Obj :=TScriptObject(LuaGetTableLightUserData(L, Index, ARRAYPROP_STR));
Data.PropName :=LuaGetTableString(L, Index, ARRAYPROPNAME_STR);
Result :=true;
except
end;
end;
function Lua_ArrayProp_Get(L: Plua_State): Integer; cdecl;
Var
indice,
PropValue :Variant;
PropType :PTypeInfo;
GetPropOK :Boolean;
NParams :Integer;
Data :TLuaArrayPropData;
begin
Result := 0;
NParams := lua_gettop(L);
if (NParams=2) then
try
GetPropertyArrayObject(Data, L, 1);
indice :=LuaToVariant(L, 2);
if (indice<>NULL)
then begin
PropType :=Data.Obj.GetArrayPropType(Data.PropName, indice);
GetPropOK := (PropType<>nil);
if GetPropOK
then PropValue :=Data.Obj.GetArrayProp(Data.PropName, indice)
else PropValue :=NULL;
Result :=PushProperty(L, Data.Obj, Data.PropName, PropValue, PropType);
end
else raise Exception.CreateFmt('Trying to index %s.%s with a NULL index', [Data.Obj.InstanceObj.ClassName, Data.PropName]);
except
On E:Exception do begin
LuaError(L, ERR_Script+E.Message);
end;
end;
end;
function Lua_ArrayProp_Set(L: Plua_State): Integer; cdecl;
begin
end;
function LuaPushPropertyArrayObject(L: Plua_State; Obj :TScriptObject; PropName :string): boolean;
begin
lua_newtable(L);
LuaSetTableString(L, -1, 'ID', ARRAYPROP_STR);
LuaSetTableLightUserData(L, -1, ARRAYPROP_STR, Obj);
LuaSetTableString(L, -1, ARRAYPROPNAME_STR, PropName);
LuaSetTablePropertyFuncs(L, -1, Lua_ArrayProp_Get, Lua_ArrayProp_Set);
Result :=true;
end;
//==============================================================================
//Set Properties Support
function Lua_IsPropertySet(L: Plua_State; Index: Integer): boolean;
begin
Result :=False;
try
Result :=lua_istable(L, Index) and (LuaGetTableString(L, Index, 'ID')=SETPROP_VALUE);
except
end;
end;
function GetPropertySet(Data :PLuaSetPropData; L: Plua_State; Index: Integer): String;
begin
Result :='';
if Data<>nil then FillChar(Data^, Sizeof(TLuaSetPropData), 0);
try
if lua_istable(L, Index)
then begin
Result :=LuaGetTableString(L, Index, SETPROP_VALUE);
if Data<>nil then
begin
Data^.ID :=LuaGetTableString(L, Index, 'ID');
Data^.Info :=LuaGetTableLightUserData(L, Index, SETPROP_INFO);
end;
end
else begin
if (lua_isString(L, Index)=1)
then Result :=LuaToString(L, Index);
end;
if Data<>nil
then Data^.Value :=Result;
except
end;
end;
function Lua_SetProp_Add(L: Plua_State): Integer; cdecl;
Var
Val1, Val2,
EnumName,
xResult :String;
NParams :Integer;
pVal2 :PChar;
begin
Result := 0;
NParams := lua_gettop(L);
if (NParams=2) then
try
//TO-DO : Controllare se TypeInfo in PLuaSetPropData è nil, in questo caso
// il valore è un intero e non una stringa
// (xchè è stato tornato da un metodo e non da una property)
Val1 :=GetPropertySet(nil, L, 1);
if (Val1='')
then raise Exception.Create('Left Side is Not a Set');
Val2 :=GetPropertySet(nil, L, 2);
if (Val2='')
then raise Exception.Create('Right Side is Not a Set');
//Operation is : xResult := Val1 + Val2
xResult :=Val1;
pVal2 :=PChar(Val2);
EnumName := SetNextWord(pVal2);
while (EnumName<>'') do
begin
//If this Value (Val2) is not already present in Result, add it
if (Pos(EnumName, xResult)<1)
then xResult :=xResult+','+EnumName;
EnumName := SetNextWord(pVal2);
end;
LuaPushPropertySet(L, nil, xResult);
Result :=1;
except
On E:Exception do begin
LuaError(L, ERR_Script+E.Message);
end;
end;
end;
function Lua_SetProp_Sub(L: Plua_State): Integer; cdecl;
Var
Val1, Val2,
EnumName,
xResult :String;
NParams :Integer;
pVal2 :PChar;
xPos :Integer;
begin
Result := 0;
NParams := lua_gettop(L);
if (NParams=2) then
try
//TO-DO : Controllare se TypeInfo in PLuaSetPropData è nil, in questo caso
// il valore è un intero e non una stringa
// (xchè è stato tornato da un metodo e non da una property)
Val1 :=GetPropertySet(nil, L, 1);
if (Val1='')
then raise Exception.Create('Left Side is Not a Set');
Val2 :=GetPropertySet(nil, L, 2);
if (Val2='')
then raise Exception.Create('Right Side is Not a Set');
//Operation is : xResult := Val1 - Val2
xResult :=Val1;
pVal2 :=PChar(Val2);
EnumName := SetNextWord(pVal2);
while (EnumName<>'') do
begin
xPos := Pos(EnumName, xResult);
//Delete all the occurence of this Value (Val2) in Result
while (xPos>0) do
begin
Delete(xResult, xPos, Length(EnumName)+1);
xPos := Pos(EnumName, xResult);
end;
EnumName := SetNextWord(pVal2);
end;
LuaPushPropertySet(L, nil, xResult);
Result :=1;
except
On E:Exception do begin
LuaError(L, ERR_Script+E.Message);
end;
end;
end;
function LuaPushPropertySet(L: Plua_State; TypeInfo :PTypeInfo; PropValue :Variant): boolean;
begin
lua_newtable(L);
LuaSetTableString(L, -1, 'ID', SETPROP_INFO);
LuaSetTableLightUserData(L, -1, SETPROP_INFO, TypeInfo);
if (TVarData(PropValue).VType = varString) or
(TVarData(PropValue).VType = varOleStr) or
(TypeInfo = nil)
then LuaSetTableString(L, -1, SETPROP_VALUE, PropValue)
else LuaSetTableString(L, -1, SETPROP_VALUE, Script_System.SetToString(TypeInfo, PropValue, false));
LuaSetMetaFunction(L, -1, '__add', Lua_SetProp_Add);
LuaSetMetaFunction(L, -1, '__sub', Lua_SetProp_Sub);
Result :=true;
end;
//==============================================================================
function GetTScriptObject(L: Plua_State; Index: Integer): TScriptObject;
Var
pObjData :PScriptObjectData;
begin
//Result := TScriptObject(LuaGetTableLightUserData(L, Index, OBJHANDLE_STR));
Result :=nil;
try
if (lua_isuserdata(L, Index)=1) then
begin
pObjData :=lua_touserdata(L, Index);
if (pObjData^.ID=OBJHANDLE_STR)
then Result :=pObjData^.Obj;
end;
except
end;
end;
//=== Methods Access functions =================================================
procedure VariantToByRef(Source :Variant; var Dest :Variant);
begin
VarClear(Dest);
TVarData(Dest).VType :=TVarData(Source).VType or varByRef;
if ((TVarData(Source).VType and varByRef)<>0)
then TVarData(Dest).VPointer := TVarData(Source).VPointer
else begin
case (TVarData(Source).VType and varTypeMask) of // strip off modifier flags
varEmpty, varNull: TVarData(Dest).VPointer :=nil;
varSmallint:begin
GetMem(TVarData(Dest).VPointer, sizeof(Smallint));
PSmallInt(TVarData(Dest).VPointer)^ :=TVarData(Source).VSmallInt;
end;
varInteger:begin
GetMem(TVarData(Dest).VPointer, sizeof(Integer));
PInteger(TVarData(Dest).VPointer)^ :=TVarData(Source).VInteger;
end;
varSingle:begin
GetMem(TVarData(Dest).VPointer, sizeof(Single));
PSingle(TVarData(Dest).VPointer)^ :=TVarData(Source).VSingle;
end;
varDouble:begin
GetMem(TVarData(Dest).VPointer, sizeof(Double));
PDouble(TVarData(Dest).VPointer)^ :=TVarData(Source).VDouble;
end;
varCurrency:begin
GetMem(TVarData(Dest).VPointer, sizeof(Currency));
PCurrency(TVarData(Dest).VPointer)^ :=TVarData(Source).VCurrency;
end;
varDate:begin
GetMem(TVarData(Dest).VPointer, sizeof(Date));
PDate(TVarData(Dest).VPointer)^ :=TVarData(Source).VDate;
end;
varOleStr:begin
GetMem(TVarData(Dest).VPointer, sizeof(PWideChar));
PPWideChar(TVarData(Dest).VPointer)^ :=TVarData(Source).VOleStr;
end;
varDispatch:begin
GetMem(TVarData(Dest).VPointer, sizeof(IDispatch));
PDispatch(TVarData(Dest).VPointer)^ :=IDispatch(TVarData(Source).VDispatch);
end;
varError:begin
GetMem(TVarData(Dest).VPointer, sizeof(Cardinal));
PDate(TVarData(Dest).VPointer)^ :=TVarData(Source).VError;
end;
varBoolean:begin
GetMem(TVarData(Dest).VPointer, sizeof(WordBool));
PWordBool(TVarData(Dest).VPointer)^ :=TVarData(Source).VBoolean;
end;
varVariant:begin
GetMem(TVarData(Dest).VPointer, sizeof(Variant));
PVariant(TVarData(Dest).VPointer)^ :=Source;
end;
varUnknown:begin
GetMem(TVarData(Dest).VPointer, sizeof(IInterface));
PUnknown(TVarData(Dest).VPointer)^ :=IInterface(TVarData(Source).VUnknown);
end;
varShortInt:begin
GetMem(TVarData(Dest).VPointer, sizeof(ShortInt));
PShortInt(TVarData(Dest).VPointer)^ :=TVarData(Source).VShortInt;
end;
varByte:begin
GetMem(TVarData(Dest).VPointer, sizeof(Byte));
PByte(TVarData(Dest).VPointer)^ :=TVarData(Source).VByte;
end;
varWord:begin
GetMem(TVarData(Dest).VPointer, sizeof(Word));
PWord(TVarData(Dest).VPointer)^ :=TVarData(Source).VWord;
end;
varLongWord:begin
GetMem(TVarData(Dest).VPointer, sizeof(LongWord));
PLongWord(TVarData(Dest).VPointer)^ :=TVarData(Source).VLongWord;
end;
end;
end;
end;
function ParamSameType(VarParam :Variant; ParamISOBJ, ParamISSET :Boolean;
ParamType :PPTypeInfo):Boolean;
begin
if (ParamType<>nil)
then
Case ParamType^.Kind of
tkUnknown : Result := (TVarData(VarParam).VType and varTypeMask) in [varEmpty, varNull, varUnknown];
tkInteger : Result := (TVarData(VarParam).VType and varTypeMask) in [varByte, varShortInt, varWord, varInteger, varLongWord];
tkChar : Result := (TVarData(VarParam).VType and varTypeMask) in [varByte, varShortInt];
//tkEnumeration,
tkFloat : Result := (TVarData(VarParam).VType and varTypeMask) in [varByte, varShortInt, varWord, varInteger, varLongWord,
varSingle, varDouble];
tkWChar,
tkLString,
tkWString,
tkString : Result := ((TVarData(VarParam).VType and varTypeMask) in [varOleStr, varStrArg]) or
((TVarData(VarParam).VType and varTypeMask)=varString) ;
tkSet : Result := ParamISSET;
tkClass : Result := ParamISOBJ or (VarParam=NULL);
//tkMethod,
tkVariant : Result :=True;
tkDynArray,
tkArray : Result := (TVarData(VarParam).VType and varArray)<>0;
//tkRecord,
//tkInterface,
tkInt64 : Result := (TVarData(VarParam).VType and varTypeMask) in [varByte, varShortInt, varWord, varInteger, varLongWord, varInt64];
else Result :=true;
end
else Result :=true;
end;
function Lua_TObject_Methods(L: Plua_State): Integer; cdecl;
var
NParams,
iParams,
invParams :Integer;
theParams :array of Variant;
xResult,
xVarResult,
xTryResult :Variant;
ParamISOBJ,
ParamISSET :Boolean;
MethodName :String;
curComponent :TObject;
NewObj,
LuaObj :TScriptObject;
PropSetData :TLuaSetPropData;
retValue :Variant;
MethodInfo: PMethodInfoHeader;
ReturnInfo: PReturnInfo;
ParamInfos: TParamInfos;
curParamInfo :PParamInfo;
VarIndexes :array of Integer;
NVarIndexes :Integer;
CheckParams :Boolean;
begin
Result :=0;
NParams := lua_gettop(L);
try
LuaObj :=GetTScriptObject(L, 1);
MethodName :=LuaGetCurrentFuncName(L);
//Get Infos about the Method
SetLength(ParamInfos, 0);
LuaObj.GetMethodInfos(MethodName, MethodInfo, ReturnInfo, ParamInfos);
SetLength(VarIndexes, 0);
NVarIndexes :=0;
CheckParams :=(MethodInfo<>nil) and (High(ParamInfos)>0);
//Fill Params for Method call in inverse sequense (why???)
SetLength(theParams, (NParams-1));
invParams :=0;
for iParams :=NParams downto 2 do
begin
//If Param[iParams] is an Object get it's real value
ParamISOBJ :=false;
NewObj :=GetTScriptObject(L, iParams);
ParamISOBJ :=(NewObj<>nil);
if ParamISOBJ
then xResult :=Integer(NewObj.InstanceObj)
else begin
ParamISSET :=Lua_IsPropertySet(L, iParams);
if ParamISSET
then begin
xResult :=GetPropertySet(@PropSetData, L, iParams);
try
//try to convert string value to Real Set Value
if (PropSetData.Info<>nil)
then xTryResult :=Script_System.StringToSet(PropSetData.Info, xResult);
xResult :=xTryResult;
except
end;
end
else xResult :=LuaToVariant(L, iParams);
end;
if CheckParams
then begin
curParamInfo :=ParamInfos[NParams-invParams-2];
if (curParamInfo<>nil) then
begin
//Check the Param Type...
if not(ParamSameType(xResult, ParamISOBJ, ParamISSET, PPTypeInfo(curParamInfo^.ParamType)))
then raise Exception.CreateFmt('%s Param %d type mismatch', [MethodName, invParams]);
(* if ((xResult=NULL) or ParamISOBJ) and
(curParamInfo^.ParamType^.Kind=tkClass)
then xResult :=VarAsType(xResult, vtClass); *)
if (ObjAuto.pfVar in curParamInfo^.Flags) or
(ObjAuto.pfOut in curParamInfo^.Flags)
then begin //Convert Param passed by Value to a Var Value
SetLength(VarIndexes, NVarIndexes+1);
VarIndexes[NVarIndexes] :=invParams;
VariantToByRef(xResult, theParams[invParams]);
inc(NVarIndexes);
end
else theParams[invParams] :=xResult;
end else theParams[invParams] :=xResult;
end
else begin
(* if (ParamISOBJ)
then xResult :=VarAsType(xResult, vtClass); *)
theParams[invParams] :=xResult;
end;
inc(invParams);
end;
retValue := LuaObj.CallMethod(MethodName, theParams, true);
//Push Vars on The Stack
for iParams :=0 to High(VarIndexes) do
begin
VariantCopyInd(TVarData(xResult), TVarData(theParams[iParams]));
LuaPushVariant(L, xResult);
Inc(Result);
FreeMem(TVarData(theParams[iParams]).VPointer);
end;
SetLength(VarIndexes, 0);
//Push Function Result on the Stack
if (retValue<>NULL)
then Inc(Result, PushMethodResult(L, LuaObj, retValue, ReturnInfo));
except
On E:Exception do begin
LuaError(L, ERR_Script+E.Message);
end;
end;
end;
function Lua_TObject_GetProp(L: Plua_State): Integer; cdecl; forward;
function Lua_TObject_SetProp(L: Plua_State): Integer; cdecl; forward;
function Lua_TObject_Free(L: Plua_State): Integer; cdecl; forward;
function LuaPush_TScriptObject(L :Plua_State; theParams :array of Variant;
Obj :TObject=nil; ObjClassName :String='';
CanFree :Boolean=True) :boolean;
var
NParams,
iParams :Integer;
xResult :Variant;
retValue :Variant;
ClassData :PScriptClassesListData;
LuaObj :TScriptObject;
NewObj :TObject;
CanCreate :Boolean;
LuaClass :TScriptObjectClass;
pObjData :PScriptObjectData;
scripter :TScriptableObject;
begin
Result :=false;
CanCreate := (Obj=nil);
if CanCreate
then ClassData :=ScriptClassesList.Find(ObjClassName)
else ClassData :=ScriptClassesList.Find(Obj.ClassType);
if (ClassData=nil)
then LuaClass :=TScriptObject
else LuaClass :=ClassData^.LuaClass;
pObjData :=lua_newuserdata(L, sizeof(TScriptObjectData));
if CanCreate
then begin
if (LuaClass<>nil)
then begin
LuaObj :=LuaClass.Create(nil, false);
theParams[High(theParams)] :=Integer(ClassData^.ObjClass);
try
retValue :=LuaObj.CallMethod('ScriptCreate', theParams, true);
if (retValue<>NULL)
then NewObj :=TObject(Integer(retValue))
else NewObj :=ClassData^.ObjClass.Create;
except
NewObj :=ClassData^.ObjClass.Create;
end;
LuaObj.Free;
LuaObj :=LuaClass.Create(NewObj, CanFree);
end
else begin
NewObj :=ClassData^.ObjClass.Create;
LuaObj :=LuaClass.Create(NewObj, CanFree);
end;
end
else begin
if (LuaClass<>nil)
then LuaObj :=LuaClass.Create(Obj, false)
else LuaObj :=TScriptObject.Create(Obj, false);
end;
pObjData^.ID :=OBJHANDLE_STR;
pObjData^.Obj :=LuaObj;
LuaSetTablePropertyFuncs(L, -1, Lua_TObject_GetProp, Lua_TObject_SetProp);
LuaSetMetaFunction(L, -1, '__gc', Lua_TObject_Free);
Result :=true;
end;
//=== Properties Access methods ================================================
(*
//NON FUNZIONA!!!!!!! PERCHE' FA LA LISTA SOLO DELLE PROPERTY PUBLISHED
function FindPredefArrayProp(AComponent :TObject):String;
Var
Props :PPropList;
i, n :Integer;
curPropInfo :PPropInfo;
begin
Result :='';
n :=GetPropList(AComponent, Props);
for i:=0 to n-1 do
begin
curPropInfo :=PPropInfo(Props^[i]);
if ((curPropInfo^.Default and $80000000)<>0) and
(curPropInfo^.PropType^^.Kind = tkArray)
then begin
Result :=curPropInfo^.Name;
end;
end;
end;
*)
function Lua_TObject_GetProp(L: Plua_State): Integer; cdecl;
Var
ty :Integer;
PropName :String;
PropValue :Variant;
PropInfo :PPropInfo;
PropType :PTypeInfo;
GetPropOK :Boolean;
NParams :Integer;
ClassData :PScriptClassesListData;
LuaObj :TScriptObject;
NewObj :TObject;
function TryGetProp(AComponent :TObject; PropName :String; PropKind :TTypeKinds):Boolean;
Var
AsString :Boolean;
begin
Result :=false;
try
PropInfo :=GetPropInfo(AComponent, PropName, PropKind);
if (PropInfo<>nil)
then begin //This Name is a Property
PropType :=PropInfo^.PropType^;
//Return as String only if the property is a Set or an Enum, exclude the Boolean
if (PropType^.Kind=tkEnumeration)
then AsString := not(GetTypeData(PropType)^.BaseType^ = TypeInfo(Boolean))
else AsString := (PropType^.Kind=tkSet);
PropValue :=GetPropValue(AComponent, PropInfo, AsString);
Result :=true;
end;
except
end;
end;
function TryGetPublicProp:Boolean;
Var
AsString :Boolean;
begin
Result :=false;
try
PropInfo :=LuaObj.GetPublicPropInfo(PropName);
if (PropInfo<>nil)
then begin //This Name is a Property
PropType :=PropInfo^.PropType^;
//Return as String only if the property is a Set or an Enum, exclude the Boolean
if (PropType^.Kind=tkEnumeration)
then AsString := not(GetTypeData(PropType)^.BaseType^ = TypeInfo(Boolean))
else AsString := (PropType^.Kind=tkSet);
if (PropType^.Kind<>tkArray)
then PropValue :=GetPropValue(LuaObj.InstanceObj, PropInfo, AsString);
Result :=true;
end;
except
end;
end;
procedure GetPredefArrayProp(Index: Integer);
var
indice :Variant;
begin
GetPropOK :=false;
try
indice :=LuaToVariant(L, Index);
PropName :=LuaObj.GetDefaultArrayProp;
PropType :=LuaObj.GetArrayPropType(PropName, indice);
GetPropOK := (PropType<>nil);
except
end;
if GetPropOK
then PropValue :=LuaObj.GetArrayProp(PropName, indice)
else PropValue :=NULL;
end;
begin
Result := 0;
GetPropOK := false;
NParams := lua_gettop(L);
if (NParams>0) then
try
LuaObj :=GetTScriptObject(L, 1);
ty := lua_type(L, 2);
if (ty = LUA_TNUMBER)
then GetPredefArrayProp(2)
else begin
PropName :=LuaToString(L, 2);
GetPropOK :=TryGetProp(LuaObj, PropName, tkProperties);
if not(GetPropOK)
then begin //Is not a Property published in the TScriptObject, try the TObject
GetPropOK :=TryGetProp(LuaObj.InstanceObj, PropName, tkProperties);
if not(GetPropOK)
then begin //Try with public Properties using scripter.GetPublicXXX
GetPropOK :=TryGetPublicProp;
end;
if not(GetPropOK)
then begin //Try with public elements using scripter.GetElementXXX
try
PropType :=LuaObj.GetElementType(PropName);
GetPropOK := (PropType<>nil);
except
end;
if GetPropOK and (PropType^.Kind<>tkArray)
then PropValue :=LuaObj.GetElement(PropName);
end;
end;
end;
if (GetPropOK)
then begin //This Name is a Property
Result :=PushProperty(L, LuaObj, PropName, PropValue, PropType);
end
else begin //This Name may be a Method or an Event ???????????
//TO-DO : Testare se è un evento (OnXXXX), in questo caso
// tornare l' eventuale nome della funzione lua
// (this code is for method)
//LuaRawSetTableNil(L, 1, PropName);
//LuaRawSetTableFunction(L, 1, PropName, Lua_TObject_Methods);
lua_pushcfunction(L, Lua_TObject_Methods);
Result := 1;
end;
except
On E:Exception do begin
LuaError(L, ERR_Script+E.Message);
end;
end;
end;
// TObject:SetProp(string PropName, variant Value) set Property Value.
function Lua_TObject_SetProp(L: Plua_State): Integer; cdecl;
Var
curComponent :TObject;
ty :Integer;
PropName :String;
PropInfo :PPropInfo;
PropType :PTypeInfo;
SetPropOK :Boolean;
NewVal :Variant;
NParams :Integer;
ClassData :PScriptClassesListData;
LuaObj :TScriptObject;
NewObj :TScriptObject;
NewValISPropertySet,
NewValISOBJ :Boolean;
PropertySetData :TLuaSetPropData;
function TrySetProp(AComponent :TObject; PropName :String; PropKind :TTypeKinds):Boolean;
begin
Result :=false;
try
PropInfo :=GetPropInfo(AComponent, PropName, PropKind);
if (PropInfo<>nil)
then begin //This Name is a Property
curComponent :=AComponent;
PropType :=PropInfo^.PropType^;
Result :=true;
end;
except
end;
end;
function TrySetPublicProp:Boolean;
begin
Result :=false;
try
PropInfo :=LuaObj.GetPublicPropInfo(PropName);
if (PropInfo<>nil)
then begin //This Name is a Property
curComponent :=LuaObj.InstanceObj;
PropType :=PropInfo^.PropType^;
Result :=true;
end;
except
end;
end;
procedure SetPredefArray(Index: Integer);
var
indice :Variant;
begin
indice :=LuaToVariant(L, Index);
PropName :=LuaObj.GetDefaultArrayProp;
PropType :=LuaObj.GetArrayPropType(PropName, indice);
if (PropType^.Kind=tkClass)
then begin
if NewValISOBJ
then LuaObj.SetArrayProp(PropName, indice, Integer(NewObj.InstanceObj))
else raise Exception.Createfmt('Cannot assign %s to %s.%s', [NewVal, curComponent.ClassName, PropName]);
end
else LuaObj.SetArrayProp(PropName, indice, NewVal);
end;
begin
Result := 0;
ty :=lua_type(L, 3);
if (ty <> LUA_TFUNCTION) then
try
LuaObj :=GetTScriptObject(L, 1);
//If the new Value is an Object get it's real value
NewValISOBJ :=false;
NewObj :=GetTScriptObject(L, 3);
NewValISOBJ :=(NewObj<>nil);
if not(NewValISOBJ)
then begin
NewValISPropertySet :=Lua_IsPropertySet(L, 3);
if NewValISPropertySet
then NewVal :=GetPropertySet(@PropertySetData, L, 3)
else NewVal :=LuaToVariant(L, 3);
end;
ty := lua_type(L, 2);
if (ty = LUA_TNUMBER)
then SetPredefArray(2)
else begin
PropName :=LuaToString(L, 2);
SetPropOK :=TrySetProp(LuaObj, PropName, tkProperties);
if not(SetPropOK)
then begin //Is not a Property published in the TScriptObject, try the TObject
SetPropOK :=TrySetProp(LuaObj.InstanceObj, PropName, tkProperties);
if not(SetPropOK)
then begin //Try with public Properties using scripter.GetPublicPropInfo
SetPropOK :=TrySetPublicProp;
end;
if not(SetPropOK)
then begin //Try with public elements using scripter.SetElementXXX
try
PropType :=LuaObj.GetElementType(PropName);
SetPropOK := (PropType<>nil);
except
end;
if SetPropOK then
begin
if (PropType^.Kind=tkClass)
then begin
if NewValISOBJ
then LuaObj.SetElement(PropName, Integer(NewObj.InstanceObj))
else raise Exception.Createfmt('Cannot assign %s to %s.%s', [NewVal, LuaObj.InstanceObj.ClassName, PropName]);
end
else begin
if NewValISPropertySet //convert string to real Value
then NewVal :=Script_System.StringToSet(PropertySetData.Info, NewVal);
LuaObj.SetElement(PropName, NewVal);
end;
Exit;
end;
end;
end;
if SetPropOK
then begin
if (PropType^.Kind=tkClass)
then begin
if NewValISOBJ
then MySetPropValue(curComponent, PropInfo, Integer(NewObj.InstanceObj))
else raise Exception.Createfmt('Cannot assign %s to %s.%s', [NewVal, curComponent.ClassName, PropName]);
end
else MySetPropValue(curComponent, PropInfo, NewVal);
end
else begin //This Name may be a Method or an Event ???????????
//TO-DO : se è un evento potremmo mantenere una Lista
// che associa un oggetto con il nome di una
// funzione Lua. Settiamo come evento un
// nostro metodo che cerca nella Lista l' oggetto
// e chiama la relativa funzione lua
end;
end;
except
On E:Exception do begin
LuaError(L, ERR_Script+E.Message);
end;
end;
end;
// TObject:Free() free the object.
function Lua_TObject_Free(L: Plua_State): Integer; cdecl;
Var
theObject :TScriptObject;
NParams :Integer;
begin
Result := 0;
NParams := lua_gettop(L);
if (NParams=1)
then begin
try
theObject :=GetTScriptObject(L, 1);
//LuaEventsList.Del(theObject.InstanceObj);
theObject.Free;
//LuaSetTableClear(L, 1);
except
On E:Exception do begin
LuaError(L, ERR_Script+E.Message);
end;
end;
end;
end;
//==============================================================================
// Main Functions
function Lua_CreateObject(L: Plua_State): Integer; cdecl;
var
NParams,
iParams,
invParams :Integer;
theParams :array of Variant;
xResult,
xTryResult :Variant;
retValue :PVariant;
ObjClassName :String;
ClassData :PScriptClassesListData;
scripter :TScriptObject;
NewObj :TScriptObject;
CanFree,
ParamISOBJ :Boolean;
PropSetData :TLuaSetPropData;
begin
Result :=0;
NParams := lua_gettop(L);
if (NParams>1)
then begin
try
ObjClassName :=LuaToString(L, 1);
CanFree :=LuaToBoolean(L, 2);
//Fill Params for Create call in inverse sequense (why???)
SetLength(theParams, NParams-1);
invParams :=0;
for iParams :=NParams downto 3 do
begin
//If Param[iParams] is an Object get it's real value
ParamISOBJ :=false;
NewObj :=GetTScriptObject(L, iParams);
ParamISOBJ :=(NewObj<>nil);
if ParamISOBJ
then xResult :=Integer(NewObj.InstanceObj)
else begin
if Lua_IsPropertySet(L, iParams)
then begin
xResult :=GetPropertySet(@PropSetData, L, iParams);
try
//try to convert string value to Real Set Value
if (PropSetData.Info<>nil)
then xTryResult :=Script_System.StringToSet(PropSetData.Info, xResult);
xResult :=xTryResult;
except
end;
end
else xResult :=LuaToVariant(L, iParams);
end;
theParams[invParams] :=xResult;
inc(invParams);
end;
//LuaPush_TScriptObject sets the last parameter with the Class
theParams[invParams] :=1234;
if LuaPush_TScriptObject(L, theParams, nil, ObjClassName, CanFree)
then Result :=1
else raise Exception.Createfmt('Cannot Create class %s', [ObjClassName])
except
On E:Exception do begin
LuaError(L, ERR_Script+E.Message);
end;
end;
end;
end;
function Lua_GetObject(L: Plua_State): Integer; cdecl;
var
NParams,
iParams,
invParams :Integer;
theParams :array of Variant;
xResult :Variant;
retValue :PVariant;
ObjName :String;
ObjData :PScriptExistingObjListData;
scripter :TScriptObject;
NewObj :TObject;
begin
Result :=0;
NParams := lua_gettop(L);
if (NParams>0)
then begin
try
ObjName :=LuaToString(L, 1);
ObjData := ScriptExistingObjList.Find(ObjName);
if (ObjData<>nil)
then begin
if LuaPush_TScriptObject(L, [], ObjData^.Obj)
then Result :=1
else raise Exception.Createfmt('Cannot Interface with class %s', [ObjData^.Obj.ClassName]);
end
else raise Exception.Createfmt('Object "%s" not found', [ObjName]);
except
On E:Exception do begin
LuaError(L, ERR_Script+E.Message);
end;
end;
end;
end;
procedure RegisterFunctions(L: Plua_State);
begin
LuaRegister(L, 'CreateObject', Lua_CreateObject);
LuaRegister(L, 'GetObject', Lua_GetObject);
end;
end.
|
unit SMCnst;
interface
{ Language:
Spanish (Mexican) strings
Translator:
Daniel Ramirez Jaime
E-Mail:
rdaniel2000@hotmail.com
}
const
strMessage = 'Imprimir...';
strSaveChanges = '¿En readlidad desea guardar los cambios a la Base de Datos?';
strErrSaveChanges = 'No se puede guardar los datos, verifique la conección'+
' con el Servidor o la validación de datos';
strDeleteWarning = '¿En readlidad desea eliminar de la tabla %s?';
strEmptyWarning = '¿En realidad desea vaciar la Tabla %s?';
const
PopUpCaption: array [0..22] of string[33] =
('Agregar registro',
'Insertar registro',
'Modificar registro',
'Eliminar registro',
'-',
'Imprimir ...',
'Exportar ...',
'-',
'Guardar cambios',
'Cancelar cambios',
'Actualizar',
'-',
'Seleccionar/Deseleccionar registros',
'Selecccionar registros',
'Seleccionar Todos los registros',
'-',
'Deseleccionar registro',
'Deseleccionar Todos los registro',
'-',
'Guardar el esquema de la columna',
'Restaurar el esquema de la columna',
'-',
'Configurar...');
const //for TSMSetDBGridDialog
SgbTitle = ' TŒtulo ';
SgbData = ' Dato ';
STitleCaption = 'Descripci‘n:';
STitleAlignment = 'Alinear:';
STitleColor = 'Fondo:';
STitleFont = 'Fuente:';
SWidth = 'Ancho:';
SWidthFix = 'caracteres';
SAlignLeft = 'izquierdo';
SAlignRight = 'derecho';
SAlignCenter = 'centro';
const //for TSMDBFilterDialog
strEqual = 'equal';
strNonEqual = 'not equal';
strNonMore = 'no greater';
strNonLess = 'no less';
strLessThan = 'less than';
strLargeThan = 'greater than';
strExist = 'empty';
strNonExist = 'not empty';
strIn = 'in list';
strBetween = 'between';
strOR = 'OR';
strAND = 'AND';
strField = 'Field';
strCondition = 'Condition';
strValue = 'Value';
strAddCondition = ' Define the additional condition:';
strSelection = ' Select the records by the next conditions:';
strAddToList = 'Add to list';
strDeleteFromList = 'Delete from list';
strTemplate = 'Filter template dialog';
strFLoadFrom = 'Load from...';
strFSaveAs = 'Save as..';
strFDescription = 'Description';
strFFileName = 'File name';
strFCreate = 'Created: %s';
strFModify = 'Modified: %s';
strFProtect = 'Protect for rewrite';
strFProtectErr = 'File is protected!';
const //for SMDBNavigator
SFirstRecord = 'Primer registro';
SPriorRecord = 'Anterior registro';
SNextRecord = 'Siguiente registro';
SLastRecord = 'Ultimo registro';
SInsertRecord = 'Insertar registro';
SCopyRecord = 'Copiar registro';
SDeleteRecord = 'Eliminar registro';
SEditRecord = 'Modificar registro';
SFilterRecord = 'Filtrar condiciones';
SFindRecord = 'Buscar el registro';
SPrintRecord = 'Imprimir los registros';
SExportRecord = 'Exportar los registros';
SPostEdit = 'Guardar cambios';
SCancelEdit = 'Cancelar cambios';
SRefreshRecord = 'Actualiar datos';
SChoice = 'Escojer registro';
SClear = 'Borrar el registro selecionado';
SDeleteRecordQuestion = '¿Eliminar registro?';
SDeleteMultipleRecordsQuestion = '¿En realidad desea Eliminar los registros seleccionados?';
SRecordNotFound = 'Registro no encontrado';
SFirstName = 'Primer';
SPriorName = 'Anterior';
SNextName = 'Siguiente';
SLastName = 'Ultimo';
SInsertName = 'Insertar';
SCopyName = 'Copiar';
SDeleteName = 'Eliminar';
SEditName = 'Modificar';
SFilterName = 'Filtrar';
SFindName = 'Encontrar';
SPrintName = 'Imprimir';
SExportName = 'Exportar';
SPostName = 'Guardar';
SCancelName = 'Cancelar';
SRefreshName = 'Actualizar';
SChoiceName = 'Escojer';
SClearName = 'Borrar';
SBtnOk = '&Aceptar';
SBtnCancel = '&Cancelar';
SBtnLoad = 'Abrir';
SBtnSave = 'Guardar';
SBtnCopy = 'Copiar';
SBtnPaste = 'Pegar';
SBtnClear = 'Limpiar';
SRecNo = 'reg.';
SRecOf = ' de ';
const //for EditTyped
etValidNumber = 'número válido';
etValidInteger = 'número entero válido';
etValidDateTime = 'fecha/hora válido';
etValidDate = 'fecha válido';
etValidTime = 'hora válido';
etValid = 'válido';
etIsNot = 'no es';
etOutOfRange = 'Valor %s fuera de rango %s..%s';
implementation
end.
|
unit WisePin;
interface
uses
Windows, cbw, WiseHardware, WiseDaq, WisePort, Contnrs, SysUtils;
type TWisePin = class(TWiseObject)
private
Daq: TWiseDaq;
Pin: Integer;
public
constructor Create(Name: string; did: TDaqId; Pin: Integer);
destructor Destroy(); override;
procedure SetOn(); // sets the corresponding bit to 1
procedure SetOff(); // sets the corresponding bit to 0
function IsOn(): boolean;
end;
implementation
constructor TWisePin.Create(Name: string; did: TDaqId; Pin: Integer);
var
daq: TWiseDaq;
b, p, d: integer;
daqname: string;
begin
if not Pin in [0 .. 7] then
raise EWisePinError.CreateFmt('[%s]: %s: Invalid pin number "%d", must be in [0 .. 7]', ['TWisePin.Create', Name, Pin]);
reverseDaqId(did, b, p, d);
daqname := Format('board%d.%s[%d]', [b, WiseDaqPortNames[p], Pin]);
Inherited Create(Name + '@' + daqname);
daq := lookupDaq(did);
if daq <> nil then
Self.Daq := daq
else
Self.Daq := TWiseDaq.Create(daqname, did);
Self.Pin := Pin;
Self.Daq.IncRef;
end;
destructor TWisePin.Destroy();
begin
Self.Daq.DecRef;
inherited Destroy;
end;
procedure TWisePin.SetOn();
begin
Self.Daq.Value := Self.Daq.Value OR (1 SHL Self.Pin);
end;
procedure TWisePin.SetOff();
begin
Self.Daq.Value := Self.Daq.Value AND NOT (1 SHL Self.Pin);
end;
function TWisePin.IsOn(): boolean;
begin
Result := (Self.Daq.Value AND (1 SHL Self.Pin)) <> 0;
end;
end.
|
unit TestDelphiNetRecordProcs;
interface
type
TSomeRecord = record
i,j,k,l: integer;
function Sum: integer;
procedure Clear;
constructor Create(iValue: integer);
end;
// a record with operator overloads
TOpRecord = record
i: integer;
s: string;
class operator Add(A,B: TOpRecord): TOpRecord;
class operator Equal(A, B: TOpRecord) : Boolean;
class operator Implicit(A: TOpRecord): Integer;
class operator Implicit(A: integer): TOpRecord;
end;
TPropertyRecord = record
private
fi, fj: integer;
function GetTwiceI: integer;
function GetTwiceJ: integer;
procedure SetTWiceI(const Value: integer);
public
property I: integer read fi write fi;
property TwiceI: integer read GetTwiceI write SetTWiceI;
property TwiceJ: integer read GetTwiceJ;
end;
implementation
{ TSomeRecord }
procedure TSomeRecord.Clear;
begin
i := 0;
j := 0;
k := 0;
l := 0;
end;
constructor TSomeRecord.Create(iValue: integer);
begin
Clear;
i := iValue;
end;
function TSomeRecord.Sum: integer;
begin
Result := i + j + k + l;
end;
{ TOpRecord }
class operator TOpRecord.Add(A, B: TOpRecord): TOpRecord;
begin
Result.i := A.i + B.i;
Result.s := a.s + b.s;
end;
class operator TOpRecord.Equal(A, B: TOpRecord): Boolean;
begin
Result := (a.i = b.i) and (a.s = b.s);
end;
class operator TOpRecord.Implicit(A: integer): TOpRecord;
begin
Result.i := A;
Result.s := '';
end;
class operator TOpRecord.Implicit(A: TOpRecord): Integer;
begin
Result := A.i;
end;
{ TPropertyRecord }
function TPropertyRecord.GetTwiceI: integer;
begin
Result := fi * 2;
end;
function TPropertyRecord.GetTwiceJ: integer;
begin
Result := fj * 2;
end;
procedure TPropertyRecord.SetTWiceI(const Value: integer);
begin
fi := Value div 2;
end;
end.
|
unit ClassNewImage;
interface
uses Controls, Classes, ExtCtrls, Messages, Graphics;
type TNewImage = class( TImage )
private
FAutoChange : boolean;
FAllowPress : boolean;
FBitmapOn : TBitmap;
FBitmapOff : TBitmap;
FPressed : boolean;
FOnMouseEnter : TNotifyEvent;
FOnMouseLeave : TNotifyEvent;
procedure SetBitmapOn( Bitmap : TBitmap );
procedure SetBitmapOff( Bitmap : TBitmap );
procedure SetPressed( Value : boolean );
procedure Enter( var Message : TMessage ); message CM_MOUSEENTER;
procedure Leave( var Message : TMessage ); message CM_MOUSELEAVE;
protected
procedure Click( var Message : TMessage ); reintroduce; message WM_LBUTTONDOWN;
public
constructor Create( AOwner : TComponent ); override;
destructor Destroy; override;
published
property AutoChange : boolean read FAutoChange write FAutoChange default FALSE;
property AllowPress : boolean read FAllowPress write FAllowPress default FALSE;
property BitmapOn : TBitmap read FBitmapOn write SetBitmapOn;
property BitmapOff : TBitmap read FBitmapOff write SetBitmapOff;
property Pressed : boolean read FPressed write SetPressed default FALSE;
property OnMouseEnter : TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
property OnMouseLeave : TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
end;
procedure Register;
implementation
//==============================================================================
//==============================================================================
//
// Register
//
//==============================================================================
//==============================================================================
procedure Register;
begin
RegisterComponents( 'My' , [TNewImage] );
end;
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
constructor TNewImage.Create( AOwner : TComponent );
begin
inherited;
FBitmapOn := TBitmap.Create;
FBitmapOff := TBitmap.Create
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
destructor TNewImage.Destroy;
begin
FBitmapOff.Free;
FBitmapOn.Free;
inherited;
end;
//==============================================================================
//==============================================================================
//
// Events
//
//==============================================================================
//==============================================================================
procedure TNewImage.Enter( var Message : TMessage );
begin
if (AutoChange) and not
(Pressed) then
Picture.Bitmap := FBitmapOn;
inherited;
if Assigned( FOnMouseEnter ) then
FOnMouseEnter( Self );
end;
procedure TNewImage.Leave( var Message : TMessage );
begin
if (AutoChange) and not
(Pressed) then
Picture.Bitmap := FBitmapOff;
inherited;
if Assigned( FOnMouseLeave ) then
FOnMouseLeave( Self );
end;
procedure TNewImage.Click( var Message : TMessage );
begin
if (AllowPress) then Pressed := not Pressed;
inherited;
end;
procedure TNewImage.SetBitmapOn( Bitmap : TBitmap );
begin
FBitmapOn.Assign( Bitmap );
end;
procedure TNewImage.SetBitmapOff( Bitmap : TBitmap );
begin
FBitmapOff.Assign( Bitmap );
Picture.Bitmap.Assign( Bitmap );
end;
procedure TNewImage.SetPressed( Value : boolean );
begin
if not AllowPress then exit;
FPressed := Value;
if FPressed then Picture.Bitmap := FBitmapOn
else Picture.Bitmap := FBitmapOff;
end;
end.
|
unit ImageProcessingMethodsUnit;
////////////////////////////////////////////////////////////////////////////////
// //
// Description: //
// Container for Image Processing Methods variables //
// Provides a way to pattern behavior for image resizing //
// //
// Defaults: //
// FSourceMethod - zsmDirectory (we're working with a root directory) //
// FFileTypeMethod - zftmPreserve (preserve file type after resize) //
// FScalingMethod - zsmCalculate (calculate scale from height/width) //
// FFiletypeConversion - zftcJPEG (if we convert filetypes, go to JPEG) //
// FFileHandling - zfhSkip (skip over if a resized image exists) //
// //
////////////////////////////////////////////////////////////////////////////////
interface
uses
Classes, ResizerCommonTypesUnit, ImageCommonTypesUnit;
type
TImageProcessingMethods = class
private
FSourceMethod: TSourceMethod;
FFiletypeMethod: TFiletypeMethod;
FScalingMethod: TScalingMethod;
FFiletypeConversion: TFiletypeConversion;
FFileHandling: TFileHandling;
public
////////////////////////////
// Constructor/Destructor //
////////////////////////////
constructor Create;
destructor Destroy; reintroduce; overload;
published
property SourceMethod: TSourceMethod read FSourceMethod write FSourceMethod;
property FileTypeMethod: TFiletypeMethod read FFiletypeMethod write FFiletypeMethod;
property ScalingMethod: TScalingMethod read FScalingMethod write FScalingMethod;
property FiletypeConversion: TFiletypeConversion read FFiletypeConversion write FFiletypeConversion;
property FileHandling: TFileHandling read FFileHandling write FFileHandling;
end; // TImageProcessingMethods
implementation
{ TImageProcessingMethods }
////////////////////////////
// Constructor/Destructor //
////////////////////////////
constructor TImageProcessingMethods.Create;
begin
inherited;
///////////////////////////
// Initialize everything //
///////////////////////////
SourceMethod := zsmDirectory;
FileTypeMethod := zftmPreserve;
ScalingMethod := zsmCalculate;
FiletypeConversion := zftcJPEG;
FileHandling := zfhSkip;
end;
destructor TImageProcessingMethods.Destroy;
begin
//////////////
// Clean up //
//////////////
inherited;
end;
end.
|
(*
Name: main
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 20 Jun 2006
Modified Date: 26 Jun 2012
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 20 Jun 2006 - mcdurdin - Initial version
03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
26 Jun 2012 - mcdurdin - I3379 - KM9 - Remove old Winapi references now in Delphi libraries
*)
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, ComObj, shlobj;
procedure Run;
function IsAdministrator_Groups: string;
function IsAdministrator_SecurityPriv: string;
function IsAdministrator_AccessPriv: string;
function AppendSlash(s: string): string;
function DirectoryExists(const Name: string): Boolean;
implementation
uses
Winapi.ActiveX,
ErrorControlledRegistry,
KeymanPaths,
RegistryKeys;
{-------------------------------------------------------------------------------
- IsAdministrator -
------------------------------------------------------------------------------}
{$R-}
function GetFolderPath(csidl: Integer): string;
var
buf: array[0..260] of Char;
idl: PItemIDList;
mm: IMalloc;
begin
Result := '';
if SHGetMalloc(mm) = NOERROR then
begin
if SHGetSpecialFolderLocation(0, csidl, idl) = NOERROR then
begin
if SHGetPathFromIDList(idl, buf) then
begin
Result := Buf;
end;
mm.Free(idl);
end;
mm._Release;
end;
if (Result = '') and (csidl = CSIDL_PROGRAM_FILES) then
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_LOCAL_MACHINE;
if not OpenKeyReadOnly('Software\Microsoft\Windows\CurrentVersion') then // I2890
RaiseLastRegistryError;
Result := ReadString('ProgramFilesDir');
finally
Free;
end;
if Result <> '' then
if Result[Length(Result)] <> '\' then Result := Result + '\';
end;
function IsAdministrator_AccessPriv: string;
var
s: string;
hFile: THandle;
begin
if (GetVersion and $80000000) = $80000000 then
begin
Result := 'IsAdmin - Win98';
Exit; // Win95/98, not NT
end;
{ Check registry access permissions - both system\ccs\... and Keyman keys }
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_LOCAL_MACHINE;
if not OpenKey(SRegKey_KeyboardLayouts, False) then
begin
Result := 'NotAdmin - Could not open HKLM\System\CurrentControlSet\Control\keyboard layouts';
Exit;
end;
CloseKey;
if not OpenKey(SRegKey_Software, False) then
begin
Result := 'NotAdmin - Could not open HKLM\Software';
Exit;
end;
{ Get the Keyman keyboard install path }
s := TKeymanPaths.KeyboardsInstallDir;
if not DirectoryExists(s) then
{ Don't want to create any directories, so check for write access to CSIDL_COMMON_APPDATA instead }
s := ExtractFileDir(AppendSlash(GetFolderPath(CSIDL_COMMON_APPDATA)));
{ Check for write access to this path }
if FileExists(PChar(s+'\kmcheck.tmp')) then DeleteFile(PChar(s+'\kmcheck.tmp'));
hFile := CreateFile(PChar(s+'\kmcheck.tmp'), GENERIC_READ or GENERIC_WRITE, 0,
nil, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, 0);
if hFile = INVALID_HANDLE_VALUE then
begin
Result := 'NotAdmin - Could not create file in '+s+'.';
Exit;
end;
CloseHandle(hFile);
finally
Free;
end;
Result := 'IsAdmin - Has write permissions where required';
end;
function accesspriv_details: string;
var
s: string;
hFile: THandle;
begin
{ Check registry access permissions - both system\ccs\... and Keyman keys }
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_LOCAL_MACHINE;
if not OpenKey(SRegKey_KeyboardLayouts, False)
then Result := Result + ' 1. NotAdmin - Could not open HKLM\System\CurrentControlSet\Control\keyboard layouts'#13#10
else Result := Result + ' 1. IsAdmin - Opened HKLM\System\CurrentControlSet\Control\keyboard layouts successfully'#13#10;
CloseKey;
if not OpenKey(SRegKey_Software, False)
then Result := Result + ' 2. NotAdmin - Could not open HKLM\Software'#13#10
else Result := Result + ' 2. IsAdmin - Opened HKLM\Software successfully'#13#10;
{ Get the Keyman keyboard install path }
s := TKeymanPaths.KeyboardsInstallDir;
if not DirectoryExists(s) then
{ Don't want to create any directories, so check for write access to CSIDL_COMMON_APPDATA instead }
s := ExtractFileDir(AppendSlash(GetFolderPath(CSIDL_COMMON_APPDATA)));
{ Check for write access to this path }
if FileExists(PChar(s+'\kmcheck.tmp')) then DeleteFile(PChar(s+'\kmcheck.tmp'));
hFile := CreateFile(PChar(s+'\kmcheck.tmp'), GENERIC_READ or GENERIC_WRITE, 0,
nil, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, 0);
if hFile = INVALID_HANDLE_VALUE
then Result := Result + ' 3. NotAdmin - Could not create file in '+s+'.'
else Result := Result + ' 3. IsAdmin - Created file in '+s+' successfully.';
CloseHandle(hFile);
finally
Free;
end;
end;
function IsAdministrator_SecurityPriv: string;
var
priv: TTokenPrivileges;
luid: TLargeInteger;
hAccessToken: THandle;
dw: DWord;
const
SE_SECURITY_NAME = 'SeSecurityPrivilege';
begin
if (GetVersion and $80000000) = $80000000 then
begin
Result := 'IsAdmin - Win98';
Exit; // Win95/98, not NT
end;
if not OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES, TRUE, hAccessToken) then
begin
if GetLastError <> ERROR_NO_TOKEN then
begin
Result := 'NotAdmin - OpenThreadToken - Error '+IntToStr(GetLastError);
Exit;
end;
if not OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, hAccessToken) then
begin
Result := 'NotAdmin - OpenProcessToken - Error '+IntToStr(GetLastError);
Exit;
end;
end;
try
if LookupPrivilegeValue(nil, SE_SECURITY_NAME, luid) then
begin
priv.PrivilegeCount := 1;
priv.Privileges[0].luid := luid;
priv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
if AdjustTokenPrivileges(hAccessToken, FALSE, priv, 0, nil, dw) then
begin
if GetLastError = ERROR_NOT_ALL_ASSIGNED then
begin
Result := 'NotAdmin - AdjustTokenPrivileges -- cannot adjust to SeSecurityPrivilege privilege';
Exit;
end;
Result := 'IsAdmin - Has SeSecurityPrivilege privilege';
end;
end;
finally
CloseHandle(hAccessToken);
end;
end;
function IsAdministrator_Groups: string;
const SECURITY_NT_AUTHORITY: SID_IDENTIFIER_AUTHORITY = (Value:(0,0,0,0,0,5));
const SECURITY_BUILTIN_DOMAIN_RID: DWord = $00000020;
const DOMAIN_ALIAS_RID_ADMINS: DWord = $00000220;
var
hAccessToken: THandle;
InfoBuffer: PChar;
ptgGroups: PTokenGroups;
dwInfoBufferSize: DWord;
psidAdministrators: PSID;
siaNtAuthority: SID_IDENTIFIER_AUTHORITY;
x: UINT;
err: Integer;
bSuccess: Boolean;
begin
if (GetVersion and $80000000) = $80000000 then
begin
Result := 'IsAdmin - Win98';
Exit; // Win95/98, not NT
end;
InfoBuffer := AllocMem(1024);
try
ptgGroups := PTokenGroups(InfoBuffer);
siaNtAuthority := SECURITY_NT_AUTHORITY;
if not OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, hAccessToken) then
begin
if GetLastError <> ERROR_NO_TOKEN then
begin
Result := 'NotAdmin - OpenThreadToken - Error '+IntToStr(GetLastError);
Exit;
end;
//
// retry against process token if no thread token exists
//
if not OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, hAccessToken) then
begin
Result := 'NotAdmin - OpenProcessToken - Error '+IntToStr(GetLastError);
Exit;
end;
end;
bSuccess := GetTokenInformation(hAccessToken, TokenGroups, InfoBuffer, 1024, dwInfoBufferSize);
err := GetLastError;
if not bSuccess and (dwInfoBufferSize > 1024) then
begin
FreeMem(InfoBuffer);
InfoBuffer := AllocMem(dwInfoBufferSize);
ptgGroups := PTokenGroups(InfoBuffer);
bSuccess := GetTokenInformation(hAccessToken, TokenGroups, InfoBuffer, dwInfoBufferSize, dwInfoBufferSize);
end;
CloseHandle(hAccessToken);
if not bSuccess then
begin
Result := 'NotAdmin - GetTokenInformation -- error = ' + IntToStr(err);
Exit;
end;
if not AllocateAndInitializeSid(siaNtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdministrators) then
begin
Result := 'NotAdmin - Could not AllocateAndInitializeSid for DOMAIN_ALIAS_RID_ADMINS -- error = '+IntToStr(GetLastError);
Exit;
end;
// assume that we don't find the admin SID.
bSuccess := FALSE;
for x := 0 to ptgGroups.GroupCount - 1 do
if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then
begin
bSuccess := True;
Break;
end;
FreeSid(psidAdministrators);
if bSuccess
then Result := 'IsAdmin - Is a member of local Administrator group'
else Result := 'NotAdmin - Not a member of local Administrator group.';
finally
FreeMem(InfoBuffer);
end;
end;
procedure Run;
begin
writeln('IsAdministrator_AccessPriv: '+IsAdministrator_AccessPriv);
writeln('IsAdministrator_SecurityPriv: '+IsAdministrator_SecurityPriv);
writeln('IsAdministrator_Groups: '+IsAdministrator_Groups);
writeln;
writeln('IsAdministrator_AccessPriv details:'#13#10+accesspriv_details);
end;
function AppendSlash(s: string): string;
begin
if s = '' then Result := ''
else if s[Length(s)] <> '\' then Result := s + '\'
else Result := s;
end;
function DirectoryExists(const Name: string): Boolean;
var
Code: Dword;
begin
Code := GetFileAttributes(PChar(Name));
Result := (Code <> $FFFFFFFF) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0);
end;
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the GNU General Public 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.gnu.org/copyleft/gpl.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Initial Developer of the Original Code is Michael Elsdörfer.
All Rights Reserved.
$Id$
You may retrieve the latest version of this file at the Corporeal
Website, located at http://www.elsdoerfer.info/corporeal
Known Issues:
-----------------------------------------------------------------------------}
unit OpenStoreFormUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, pngimage, ExtCtrls, JvExControls, JvLabel,
JvGradientProgressBarEx, JvExStdCtrls, JvCheckBox, gnugettext, Buttons,
PngSpeedButton, JvEdit;
type
TOpenStoreMode = (osmLoad, osmCreate, osmChangeKey);
TOpenStoreForm = class(TForm)
Bevel2: TBevel;
Panel1: TPanel;
FormHeaderLabel: TLabel;
Bevel1: TBevel;
LoadButton: TButton;
SelectedStoreLabel: TLabel;
StoreFilenameLabel: TJvLabel;
KeyLabel: TLabel;
CreateNewButton: TButton;
ChangeButton: TButton;
KeyEdit: TJvEdit;
SelectStoreDialog: TOpenDialog;
CreateStoreDialog: TSaveDialog;
QualityLabel: TLabel;
Image1: TImage;
MakeDefaultCheckBox: TJvCheckBox;
TogglePasswordCharButton: TPngSpeedButton;
CancelButton: TButton;
procedure ChangeButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CreateNewButtonClick(Sender: TObject);
procedure KeyEditChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure LoadButtonClick(Sender: TObject);
procedure TogglePasswordCharButtonClick(Sender: TObject);
private
QualityIndicatorBar: TJvGradientProgressBarEx;
NewStoreKey: string;
private
FCurrentDefaultFile: string;
FSelectedStoreFile: string;
FMode: TOpenStoreMode;
FConfirmationMode: Boolean;
FDefaultMode: TOpenStoreMode;
procedure SetKey(const Value: string);
procedure SetCurrentDefaultFile(const Value: string);
function GetMakeDefault: Boolean;
procedure SetMakeDefault(const Value: Boolean);
procedure SetSelectedStoreFile(const Value: string);
function GetKey: string;
procedure SetMode(const Value: TOpenStoreMode);
procedure SetConfirmationMode(const Value: Boolean);
procedure SetDefaultMode(const Value: TOpenStoreMode);
protected
procedure CreateParams(var Params: TCreateParams); override;
protected
procedure UpdateInterface;
procedure UpdateQualityIndicator;
protected
// Some modes, like osmCreate and osmChange, require a key to be confirmed
property ConfirmationMode: Boolean read FConfirmationMode write SetConfirmationMode;
public
constructor Create(AOwner: TComponent; ADefaultMode: TOpenStoreMode); reintroduce;
public
procedure Reset;
public
property SelectedStoreFile: string read FSelectedStoreFile write SetSelectedStoreFile;
property CurrentDefaultFile: string read FCurrentDefaultFile write SetCurrentDefaultFile;
property Key: string read GetKey write SetKey;
property Mode: TOpenStoreMode read FMode write SetMode;
property DefaultMode: TOpenStoreMode read FDefaultMode write SetDefaultMode;
property MakeDefault: Boolean read GetMakeDefault write SetMakeDefault;
end;
var
OpenStoreForm: TOpenStoreForm;
implementation
uses
TaskDialog,
Core, Utilities, VistaCompat;
{$R *.dfm}
constructor TOpenStoreForm.Create(AOwner: TComponent; ADefaultMode: TOpenStoreMode);
begin
DefaultMode := ADefaultMode;
FMode := DefaultMode;
// calls FormCreate
inherited Create(AOwner);
end;
procedure TOpenStoreForm.CreateNewButtonClick(Sender: TObject);
begin
if CreateStoreDialog.Execute then
begin
SelectedStoreFile := CreateStoreDialog.Filename;
Mode := osmCreate;
KeyEdit.SetFocus;
end;
end;
procedure TOpenStoreForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
// Show taskbar button, except when in "change key" mode
if Mode <> osmChangeKey then
Params.ExStyle := Params.ExStyle and not WS_EX_TOOLWINDOW or WS_EX_APPWINDOW;
end;
procedure TOpenStoreForm.ChangeButtonClick(Sender: TObject);
begin
if SelectStoreDialog.Execute then
begin
SelectedStoreFile := SelectStoreDialog.Filename;
Mode := osmLoad;
KeyEdit.SetFocus;
end;
end;
procedure TOpenStoreForm.FormCreate(Sender: TObject);
begin
// localize
TranslateComponent(Self);
// use font setting of os (mainly intended for new vista font)
SetDesktopIconFonts(Self.Font);
// create quality indicater control
QualityIndicatorBar := TJvGradientProgressBarEx.Create(Self);
QualityIndicatorBar.BarColorFrom := $000080FF; // orange
QualityIndicatorBar.BarColorTo := clLime;
QualityIndicatorBar.SetBounds(126, 116, 257, 19);
QualityIndicatorBar.Parent := Self;
// init dialogs
SelectStoreDialog.Filter := _(CorporealFilter)+'|*.corporeal;*.patronus|'+_(AllFilesFilter)+'|*.*';
SelectStoreDialog.DefaultExt := 'corporeal';
CreateStoreDialog.Filter := SelectStoreDialog.Filter;
CreateStoreDialog.DefaultExt := SelectStoreDialog.DefaultExt;
// init some other stuff
TogglePasswordCharButton.Hint := _(TogglePasswordCharHint);
CancelButton.Left := LoadButton.Left - CancelButton.Width - 5;
// default values
Reset;
end;
procedure TOpenStoreForm.FormShow(Sender: TObject);
begin
// Auto set focus to key input for convienience
if KeyEdit.Visible then
KeyEdit.SetFocus;
end;
function TOpenStoreForm.GetKey: string;
begin
Result := KeyEdit.Text;
end;
function TOpenStoreForm.GetMakeDefault: Boolean;
begin
Result := MakeDefaultCheckBox.Checked;
end;
procedure TOpenStoreForm.KeyEditChange(Sender: TObject);
begin
UpdateQualityIndicator;
end;
procedure TOpenStoreForm.LoadButtonClick(Sender: TObject);
begin
// for some modes, we do need to confirm the entered key
if ((Mode = osmCreate) or (Mode = osmChangeKey)) and (not ConfirmationMode) then
begin
NewStoreKey := Key;
ConfirmationMode := True;
end
// otherwise, check if keys match, and if yes, return OK
else if ((Mode = osmCreate) or (Mode = osmChangeKey)) then
begin
if NewStoreKey = Key then
ModalResult := mrOk
else
begin
with TAdvTaskDialog.Create(Self) do begin
DialogPosition := dpScreenCenter;
Title := _('Error');
Instruction := _('Keys do not match.');
if Mode = osmCreate then
Content := _('You entered two different keys for the new store. Please '+
'try again, or click ''Create New'' to restart the procedure and choose '+
'a new key.')
else
Content := _('You entered two different keys. Please try again. Click cancel '+
'if you decide not to change the master key of this store.');
Icon := tiError;
Execute;
end;
Key := '';
KeyEdit.SetFocus;
end;
end
// if mode = load, then go ahead and try with current key
else if Mode = osmLoad then
begin
ModalResult := mrOk;
end;
end;
procedure TOpenStoreForm.Reset;
begin
// Default values
SelectedStoreFile := '';
CurrentDefaultFile := '';
Mode := DefaultMode;
Key := '';
NewStoreKey := '';
ConfirmationMode := False;
end;
procedure TOpenStoreForm.SetConfirmationMode(const Value: Boolean);
begin
FConfirmationMode := Value;
// clear current key
Key := '';
// update the interface and focus the key edit automatically
UpdateInterface;
if KeyEdit.CanFocus then KeyEdit.SetFocus;
end;
procedure TOpenStoreForm.SetCurrentDefaultFile(const Value: string);
begin
if FileExists(Value) then
begin
FCurrentDefaultFile := Value;
// if no store is selected yet, auto use the default
if SelectedStoreFile = '' then
SelectedStoreFile := Value;
end;
end;
procedure TOpenStoreForm.SetDefaultMode(const Value: TOpenStoreMode);
begin
FDefaultMode := Value;
end;
procedure TOpenStoreForm.SetKey(const Value: string);
begin
// bug in JvEdit? if ProtectedPasswords=True, this doesn't function.
// try to work around it for now, but maybe we should fix it later.
// TODO 1 -cworkaround : bug: check for update
KeyEdit.ProtectPassword := False;
KeyEdit.Text := Value;
KeyEdit.ProtectPassword := True;
end;
procedure TOpenStoreForm.SetMakeDefault(const Value: Boolean);
begin
MakeDefaultCheckBox.Checked := Value;
end;
procedure TOpenStoreForm.SetMode(const Value: TOpenStoreMode);
begin
FMode := Value;
// Reset entered key value
Key := '';
NewStoreKey := '';
// Reset Password Char setting
TogglePasswordCharButton.Down := True;
TogglePasswordCharButtonClick(nil);
UpdateInterface;
end;
procedure TOpenStoreForm.SetSelectedStoreFile(const Value: string);
begin
FSelectedStoreFile := Value;
UpdateInterface;
MakeDefaultCheckBox.Checked := Value = CurrentDefaultFile;
end;
procedure TOpenStoreForm.TogglePasswordCharButtonClick(Sender: TObject);
begin
KeyEdit.ThemedPassword := TogglePasswordCharButton.Down;
KeyEdit.ProtectPassword := TogglePasswordCharButton.Down;
end;
procedure TOpenStoreForm.UpdateInterface;
begin
// Depending on current mode, change visibility/enabled state of some controls
ChangeButton.Visible := Mode <> osmChangeKey;
CreateNewButton.Visible := Mode <> osmChangeKey;
MakeDefaultCheckBox.Visible := Mode <> osmChangeKey;
CancelButton.Visible := Mode = osmChangeKey;
TogglePasswordCharButton.Visible := (Mode = osmChangeKey) or (Mode = osmCreate);
QualityIndicatorBar.Visible := (Mode = osmChangeKey) or (Mode = osmCreate);
QualityLabel.Visible := (Mode = osmChangeKey) or (Mode = osmCreate);
UpdateQualityIndicator;
// Depending on wether a store is selected, show/hide/disable/enable stuff
if SelectedStoreFile <> '' then
begin
StoreFilenameLabel.Caption := SelectedStoreFile;
StoreFilenameLabel.Hint := SelectedStoreFile;
KeyLabel.Visible := True;
KeyEdit.Visible := True;
LoadButton.Enabled := True;
MakeDefaultCheckBox.Enabled := True;
end
else begin
StoreFilenameLabel.Caption := _('(none)');
QualityLabel.Visible := False;
KeyLabel.Visible := False;
KeyEdit.Visible := False;
LoadButton.Enabled := False;
MakeDefaultCheckBox.Enabled := False;
end;
// Set caption
if Mode = osmChangeKey then
Caption := _('Change Master Key')
else
Caption := _('Choose / Create Password Store');
// Depending on current mode, change captions
if (Mode = osmCreate) then
begin
LoadButton.Caption := _('Create');
FormHeaderLabel.Caption := _('Create New Password Store');
SelectedStoreLabel.Caption := _('Store To Create:');
if not ConfirmationMode then
KeyLabel.Caption := _('Choose Key:')
else
KeyLabel.Caption := _('Confirm Key:');
end
else if Mode = osmChangeKey then
begin
FormHeaderLabel.Caption := Caption;
LoadButton.Caption := _('Change');
SelectedStoreLabel.Caption := _('Current Store:');
KeyLabel.Caption := _('New Key:');
end else
// osmLoad
begin
KeyLabel.Caption := _('Enter Key:');
LoadButton.Caption := _('Load');
SelectedStoreLabel.Caption := _('Selected Store:');
FormHeaderLabel.Caption := _('Open Password Store');
end;
end;
procedure TOpenStoreForm.UpdateQualityIndicator;
const
QualityMaxBits = 132;
var
EstimatedBits: Integer;
begin
EstimatedBits := EstimatePasswordBits(KeyEdit.Text);
with QualityIndicatorBar do begin
Max := QualityMaxBits;
Position := EstimatedBits+1;
end;
QualityLabel.Caption := Format(_('%s bits'), [IntToStr(EstimatedBits)]);
end;
end.
|
unit ComponentsExcelDataModule;
interface
uses
System.SysUtils, System.Classes, ExcelDataModule, Excel2010, Vcl.OleServer,
System.Generics.Collections, FireDAC.Comp.Client, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet,
CustomExcelTable, SearchCategoryQuery, SearchFamily,
SearchComponentOrFamilyQuery;
{$WARN SYMBOL_PLATFORM OFF}
type
TComponentsExcelTable = class(TCustomExcelTable)
private
FBadSubGroup: TList<String>;
FGoodSubGroup: TList<String>;
FProducer: string;
FQuerySearchFamily: TQuerySearchFamily;
FqSearchCategory: TQuerySearchCategory;
FqSearchComponentOrFamily: TQuerySearchComponentOrFamily;
function GetFamilyName: TField;
function GetSubGroup: TField;
function GetComponentName: TField;
procedure SetProducer(const Value: string);
protected
function CheckComponent: Boolean;
function CheckSubGroup: Boolean;
procedure CreateFieldDefs; override;
procedure SetFieldsInfo; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function CheckRecord: Boolean; override;
property FamilyName: TField read GetFamilyName;
property SubGroup: TField read GetSubGroup;
property ComponentName: TField read GetComponentName;
property Producer: string read FProducer write SetProducer;
end;
TComponentsExcelDM = class(TExcelDM)
private
function GetExcelTable: TComponentsExcelTable;
{ Private declarations }
protected
function CreateExcelTable: TCustomExcelTable; override;
procedure ProcessRange2(AExcelRange: ExcelRange);
// TODO: ProcessContent
// procedure ProcessContent; override;
public
procedure ProcessRange(AExcelRange: ExcelRange); override;
property ExcelTable: TComponentsExcelTable read GetExcelTable;
// TODO: ProcessRange0
// procedure ProcessRange0(AExcelRange: ExcelRange);
{ Public declarations }
end;
implementation
{ %CLASSGROUP 'Vcl.Controls.TControl' }
{$R *.dfm}
uses System.Variants, FieldInfoUnit, ProgressInfo, DBRecordHolder, ErrorType,
RecordCheck;
function TComponentsExcelDM.CreateExcelTable: TCustomExcelTable;
begin
Result := TComponentsExcelTable.Create(Self);
end;
function TComponentsExcelDM.GetExcelTable: TComponentsExcelTable;
begin
Result := CustomExcelTable as TComponentsExcelTable;
end;
procedure TComponentsExcelDM.ProcessRange(AExcelRange: ExcelRange);
var
ACell: OleVariant;
AEmptyLines: Integer;
ARange: ExcelRange;
ARow: Integer;
I: Integer;
ma: ExcelRange;
PI: TProgressInfo;
rc: Integer;
V: Variant;
begin
CustomExcelTable.Errors.EmptyDataSet;
CustomExcelTable.EmptyDataSet;
CustomExcelTable.Filtered := False;
CustomExcelTable.Filter := '';
AEmptyLines := 0;
I := 0;
// пока не встретится 5 пустых линий подряд загружать
rc := AExcelRange.Rows.Count;
PI := TProgressInfo.Create;
try
PI.TotalRecords := rc;
CallOnProcessEvent(PI);
while (AEmptyLines <= 5) and (I < rc) do
begin
ARow := AExcelRange.Row + I;
if IsEmptyRow(ARow) then
begin
// увеличить количество пустых линий подряд
Inc(AEmptyLines);
Continue;
end;
// Получаем диапазон объединения в первом столбце
ACell := EWS.Cells.Item[ARow, Indent + 1];
V := ACell.Value;
ma := EWS.Range[ACell, ACell].MergeArea;
// Возможно в этом диапазоне несколько строк - их будем обрабатывать отдельно
// если для этого диапазона указан корпус
if not VarToStrDef(ACell.Value, '').IsEmpty then
begin
ARange := GetExcelRange(ma.Row, Indent + 1, ma.Row + ma.Rows.Count - 1,
Indent + FLastColIndex);
ProcessRange2(ARange);
end;
Inc(I, ma.Rows.Count);
PI.ProcessRecords := I;
CallOnProcessEvent(PI);
end;
finally
FreeAndNil(PI);
end;
end;
// Обработка объединения
procedure TComponentsExcelDM.ProcessRange2(AExcelRange: ExcelRange);
var
ARow: Integer;
Arr: Variant;
dc: Integer;
hight: Integer;
I: Integer;
low: Integer;
R: Integer;
RH: TRecordHolder;
begin
RH := TRecordHolder.Create();
try
// Копируем весь диапазон в вариантный массив
Arr := AExcelRange.Value2;
R := 0;
dc := VarArrayDimCount(Arr);
Assert(dc = 2);
low := VarArrayLowBound(Arr, 1);
hight := VarArrayHighBound(Arr, 1);
// Цикл по всем строкам диапазона
for I := low to hight do
begin
ARow := AExcelRange.Row + R;
// Добавляем новую строку в таблицу с excel-данными
ExcelTable.AppendRow(ARow, Arr, I);
if RH.Count > 0 then
ExcelTable.SetUnionCellValues(RH);
// Проверяем запись на наличие ошибок
ExcelTable.CheckRecord;
// Запоминаем текущие значения как значения по умолчанию
RH.Attach(ExcelTable);
Inc(R);
end;
finally
FreeAndNil(RH);
end;
end;
constructor TComponentsExcelTable.Create(AOwner: TComponent);
begin
inherited;
FqSearchCategory := TQuerySearchCategory.Create(Self);
FQuerySearchFamily := TQuerySearchFamily.Create(Self);
FqSearchComponentOrFamily := TQuerySearchComponentOrFamily.Create(Self);
FGoodSubGroup := TList<String>.Create;
FBadSubGroup := TList<String>.Create;
end;
destructor TComponentsExcelTable.Destroy;
begin
FreeAndNil(FGoodSubGroup);
FreeAndNil(FBadSubGroup);
inherited;
end;
function TComponentsExcelTable.CheckComponent: Boolean;
var
ARecordCheck: TRecordCheck;
begin
Assert(not Producer.IsEmpty);
// Ищем такой компонент и производителя в базе
Result := FqSearchComponentOrFamily.SearchComponentWithProducer
(ComponentName.AsString, Producer) = 0;
// Если нашли такой компонент с таким производителем
if not Result then
begin
// Наш компонент уже есть в базе, и относится к семейству с другим именем
if FqSearchComponentOrFamily.W.FamilyValue.F.AsString <> FamilyName.AsString
then
begin
ARecordCheck.ErrorType := etError;
ARecordCheck.Row := ExcelRow.AsInteger;
ARecordCheck.Col := FamilyName.Index + 1;
ARecordCheck.ErrorMessage := FamilyName.AsString;
ARecordCheck.Description :=
Format('Компонент %s не может принадлежать двум семействам: %s и %s',
[ComponentName.AsString,
FqSearchComponentOrFamily.W.FamilyValue.F.AsString,
FamilyName.AsString]);
ProcessErrors(ARecordCheck);
end
else
begin
// Наш компонент и его семейство уже есть в базе
ARecordCheck.ErrorType := etWarring;
ARecordCheck.Row := ExcelRow.AsInteger;
ARecordCheck.Col := FamilyName.Index + 1;
ARecordCheck.ErrorMessage := ComponentName.AsString;
ARecordCheck.Description :=
Format('Компонент %s и его семейство %s уже занесёно в БД',
[ComponentName.AsString, FamilyName.AsString]);
ProcessErrors(ARecordCheck);
end;
// Запоминаем код семейства
{
Edit;
IDFamily.Value := FQuerySearchFamily.W.PK.Value;
Post;
}
end;
end;
function TComponentsExcelTable.CheckRecord: Boolean;
begin
Result := inherited;
if Result then
begin
Result := CheckSubGroup;
CheckComponent;
end;
end;
function TComponentsExcelTable.CheckSubGroup: Boolean;
var
ARecordCheck: TRecordCheck;
IsBad: Boolean;
IsGood: Boolean;
s: String;
Splitted: TArray<String>;
ss: string;
x: Integer;
begin
Result := True;
ARecordCheck.ErrorType := etError;
ARecordCheck.Row := ExcelRow.AsInteger;
ARecordCheck.Col := SubGroup.Index + 1;
Splitted := SubGroup.AsString.Split([',']);
for ss in Splitted do
begin
s := ss.Trim;
x := StrToIntDef(s, -1);
if x <> -1 then
begin
IsBad := (FBadSubGroup.Indexof(s) >= 0);
IsGood := (FGoodSubGroup.Indexof(s) >= 0);
if (not IsGood) and (not IsBad) then
begin
// Ищем категорию компонента по внешнему идентификатору
IsGood := FqSearchCategory.SearchByExternalID(s) = 1;
if IsGood then
begin
FGoodSubGroup.Add(s);
end
else
begin
IsBad := True;
FBadSubGroup.Add(s);
end;
end;
if IsBad then
begin
ARecordCheck.ErrorMessage := s;
ARecordCheck.Description :=
'Не найдена категория с таким идентификатором';
ProcessErrors(ARecordCheck);
Result := False;
end;
end
else
begin
ARecordCheck.ErrorMessage := s;
ARecordCheck.Description := 'Неверный идентификатор категории';
ProcessErrors(ARecordCheck);
Result := False;
end;
end;
end;
procedure TComponentsExcelTable.CreateFieldDefs;
begin
inherited;
// при проверке будем заполнять код родительского компонента
FieldDefs.Add('IDFamily', ftInteger);
end;
function TComponentsExcelTable.GetFamilyName: TField;
begin
Result := FieldByName('FamilyName');
end;
function TComponentsExcelTable.GetSubGroup: TField;
begin
Result := FieldByName('SubGroup');
end;
function TComponentsExcelTable.GetComponentName: TField;
begin
Result := FieldByName('ComponentName');
end;
procedure TComponentsExcelTable.SetFieldsInfo;
begin
FieldsInfo.Add(TFieldInfo.Create('FamilyName', False, '', True));
FieldsInfo.Add(TFieldInfo.Create('ComponentName', True,
'Наименование компонента не должно быть пустым'));
FieldsInfo.Add(TFieldInfo.Create('SubGroup', False, '', True));
end;
procedure TComponentsExcelTable.SetProducer(const Value: string);
begin
Assert(not Value.IsEmpty);
FProducer := Value;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 78 Simulating;
}
program
LinearPrinter;
const
MaxL = 255;
var
L : Integer;
T : string;
TP : Integer;
S : string [MaxL div 2];
SN : Integer;
Time : Longint;
I, J : Integer;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Readln(T);
Close(Input);
Assign(Input, 'file.txt');
Reset(Input);
end;
procedure WriteOutput;
begin
Close(Input);
Writeln(Time);
end;
procedure Simulate;
begin
TP := -1;
Time := -2;
while not Eof do
begin
Readln(S);
TP := (TP + 1) mod Length(T);
Inc(Time);
SN := Length(S);
while SN > 0 do
begin
for I := 1 to Length(S) do
if S[I] = T[(I + TP - 1) mod Length(T) + 1] then
begin
S[I] := #0;
Dec(SN);
end;
Inc(Time);
TP := (TP + 1) mod Length(T);
end;
end;
end;
begin
ReadInput;
Simulate;
WriteOutput;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.Backend.ParseApi;
interface
uses
System.Classes, System.SysUtils, System.Generics.Collections, System.JSON,
REST.Client, REST.Types, REST.Backend.Exception;
{$SCOPEDENUMS ON}
type
EParseAPIError = class(EBackendError)
private
FCode: Integer;
FError: string;
public
constructor Create(ACode: Integer; const AError: String); overload;
property Code: Integer read FCode;
property Error: string read FError;
end;
TParseAPIErrorClass = class of EParseAPIError;
/// <summary>
/// <para>
/// TParseApi implements REST requests based on Parse's REST API. See
/// <see href="https://parse.com/docs/rest" />
/// </para>
/// </summary>
TParseApi = class(TComponent)
private const
sClasses = 'classes';
sInstallations = 'installations';
sFiles = 'files';
sUsers = 'users';
sPush = 'push';
public const
cDefaultApiVersion = '1';
cDefaultBaseURL = 'https://api.parse.com/{ApiVersion}'; // do not localize
public type
TDeviceNames = record
public
const IOS = 'ios';
const Android = 'android';
end;
TConnectionInfo = record
public
ApiVersion: string;
ApplicationID: string;
RestApiKey: string;
MasterKey: string;
ProxyPassword: string;
ProxyPort: Integer;
ProxyServer: string;
ProxyUsername: string;
constructor Create(const AApiVersion, AApplicationID: string);
end;
TUpdatedAt = record
private
FUpdatedAt: TDateTime;
FObjectID: string;
FBackendClassName: string;
public
constructor Create(const ABackendClassName, AObjectID: string; AUpdatedAt: TDateTime);
property UpdatedAt: TDateTime read FUpdatedAt;
property ObjectID: string read FObjectID;
property BackendClassName: string read FBackendClassName;
end;
TObjectID = record
private
FCreatedAt: TDateTime;
FUpdatedAt: TDateTime;
FObjectID: string;
FBackendClassName: string;
public
constructor Create(const ABackendClassName: string; AObjectID: string);
property CreatedAt: TDateTime read FCreatedAt;
property UpdatedAt: TDateTime read FUpdatedAt;
property ObjectID: string read FObjectID;
property BackendClassName: string read FBackendClassName;
end;
TUser = record
private
FCreatedAt: TDateTime;
FUpdatedAt: TDateTime;
FObjectID: string;
FUserName: string;
public
constructor Create(const AUserName: string);
property CreatedAt: TDateTime read FCreatedAt;
property UpdatedAt: TDateTime read FUpdatedAt;
property ObjectID: string read FObjectID;
property UserName: string read FUserName;
end;
TLogin = record
private
FSessionToken: string;
FUser: TUser;
public
constructor Create(const ASessionToken: string; const AUser: TUser);
property SessionToken: string read FSessionToken;
property User: TUser read FUser;
end;
TFile = record
private
FName: string;
FFileName: string;
FDownloadURL: string;
public
constructor Create(const AName: string);
property FileName: string read FFileName;
property DownloadURL: string read FDownloadURL;
property Name: string read FName;
end;
TAuthentication = (Default, MasterKey, APIKey, Session, None);
TAuthentications = set of TAuthentication;
TDefaultAuthentication = (APIKey, MasterKey, Session, None);
TFindObjectProc = reference to procedure(const AID: TObjectID; const AObj: TJSONObject);
TQueryUserNameProc = reference to procedure(const AUser: TUser; const AUserObject: TJSONObject);
TLoginProc = reference to procedure(const ALogin: TLogin; const AUserObject: TJSONObject);
TRetrieveUserProc = reference to procedure(const AUser: TUser; const AUserObject: TJSONObject);
TRetrieveJSONProc = reference to procedure(const AUserObject: TJSONObject);
public
const
DateTimeIsUTC = True;
public
class var
EmptyConnectionInfo: TConnectionInfo;
private
FRESTClient: TRESTClient;
FRequest: TRESTRequest;
FResponse: TRESTResponse;
FOwnsResponse: Boolean;
FBaseURL: string;
FConnectionInfo: TConnectionInfo;
FSessionToken: string;
FAuthentication: TAuthentication;
FDefaultAuthentication: TDefaultAuthentication;
procedure SetConnectionInfo(const Value: TConnectioninfo);
procedure SetBaseURL(const Value: string);
function GetLoggedIn: Boolean;
protected
procedure AddMasterKey(const AKey: string); overload;
procedure AddAPIKey(const AKey: string); overload;
procedure AddSessionToken(const AAPIKey, ASessionToken: string); overload;
procedure ApplyConnectionInfo;
procedure CheckAuthentication(AAuthentication: TAuthentications);
function GetActualAuthentication: TAuthentication;
function CreateException(const ARequest: TRESTRequest;
const AClass: TParseAPIErrorClass): EParseAPIError;
procedure CheckForResponseError(AValidStatusCodes: array of Integer); overload;
procedure CheckForResponseError; overload;
procedure CheckForResponseError(const ARequest: TRESTRequest); overload;
procedure CheckForResponseError(const ARequest: TRESTRequest;
AValidStatusCodes: array of Integer); overload;
procedure PostResource(const AResource: string;
const AJSON: TJSONObject; AReset: Boolean);
procedure PutResource(const AResource: string;
const AJSONObject: TJSONObject; AReset: Boolean);
function DeleteResource(const AResource: string; AReset: Boolean): Boolean; overload;
function ObjectIDFromObject(const ABackendClassName, AObjectID: string;
const AJSONObject: TJSONObject): TObjectID; overload;
function FileIDFromObject(const AFileName: string; const AJSONObject: TJSONObject): TFile;
procedure AddAuthParameters; overload;
procedure AddAuthParameters(AAuthentication: TAuthentication); overload;
function FindClass(const ABackendClassName, AObjectID: string; out AFoundObject: TObjectID; const AJSON: TJSONArray; AProc: TFindObjectProc): Boolean; overload;
function QueryUserName(const AUserName: string; out AUser: TUser; const AJSON: TJSONArray; AProc: TQueryUserNameProc): Boolean; overload;
function LoginFromObject(const AUserName: string; const AJSONObject: TJSONObject): TLogin;
function UserFromObject(const AUserName: string; const AJSONObject: TJSONObject): TUser; overload;
function UpdatedAtFromObject(const ABackendClassName, AObjectID: string; const AJSONObject: TJSONObject): TUpdatedAt;
procedure QueryResource(const AResource: string; const AQuery: array of string; const AJSONArray: TJSONArray; AReset: Boolean);
function RetrieveCurrentUser(const ASessionToken: string; out AUser: TUser; const AJSON: TJSONArray; AProc: TRetrieveUserProc): Boolean; overload;
function RetrieveUser(const ASessionID, AObjectID: string; out AUser: TUser; const AJSON: TJSONArray; AProc: TRetrieveUserProc; AReset: Boolean): Boolean; overload;
procedure UpdateUser(const ASessionID, AObjectID: string; const AUserObject: TJSONObject; out AUpdatedAt: TUpdatedAt); overload;
/// <summary>Retrieve an installation object. Return false if the installation object was not found. </summary>
function DoRetrieveInstallation(const AObjectID: string; const AJSON: TJSONArray; AProc: TRetrieveJSONProc; AReset: Boolean): Boolean; overload;
property RestClient: TRESTClient read FRESTClient;
property Request: TRESTRequest read FRequest;
public
constructor Create(AOwner: TComponent;
const AResponse: TRESTResponse = nil); reintroduce; overload;
destructor Destroy; override;
function UserFromObject(const AJSONObject: TJSONObject): TUser; overload;
function ObjectIDFromObject(const ABackendClassName: string;
const AJSONObject: TJSONObject): TObjectID; overload;
// Objects
procedure CreateClass(const ABackendClassName: string; const AJSON: TJSONObject; out ANewObject: TObjectID); overload;
procedure CreateClass(const ABackendClassName: string; const AACL, AJSON: TJSONObject; out ANewObject: TObjectID); overload;
function DeleteClass(const AID: TObjectID): Boolean; overload;
function DeleteClass(const ABackendClassName, AObjectID: string): Boolean; overload;
function FindClass(const ABackendClassName, AObjectID: string; AProc: TFindObjectProc): Boolean; overload;
function FindClass(const ABackendClassName, AObjectID: string; out AFoundObjectID: TObjectID; const AFoundJSON: TJSONArray = nil): Boolean; overload;
function FindClass(const AID: TObjectID; AProc: TFindObjectProc): Boolean; overload;
function FindClass(const AID: TObjectID; out AFoundObjectID: TObjectID; const AFoundJSON: TJSONArray = nil): Boolean; overload;
procedure UpdateClass(const ABackendClassName, AObjectID: string; const AJSONObject: TJSONObject; out AUpdatedAt: TUpdatedAt); overload;
procedure UpdateClass(const AID: TObjectID; const AJSONObject: TJSONObject; out AUpdatedAt: TUpdatedAt); overload;
procedure QueryClass(const ABackendClassName: string; const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryClass(const ABackendClassName: string; const AQuery: array of string; const AJSONArray: TJSONArray; out AObjects: TArray<TObjectID>); overload;
// Installations
function CreateAndroidInstallationObject(const AInstallationID, ADeviceToken: string; AChannels: array of string): TJSONObject; overload;
function CreateAndroidInstallationObject(const AInstallationID, ADeviceToken: string; const AProperties: TJSONObject): TJSONObject; overload;
function CreateAndroidInstallationObject(const AGCMAppID, AInstallationID, ADeviceToken: string; const AProperties: TJSONObject): TJSONObject; overload;
function CreateIOSInstallationObject(const ADeviceToken: string; ABadge: Integer; AChannels: array of string): TJSONObject; overload;
function CreateIOSInstallationObject(const ADeviceToken: string; const AProperties: TJSONObject): TJSONObject; overload;
procedure UploadInstallation(const AJSON: TJSONObject; out ANewObject: TObjectID);
procedure UpdateInstallation(const AObjectID: string; const AJSONObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
function DeleteInstallation(const AObjectID: string): Boolean; overload;
procedure QueryInstallation(const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryInstallation(const AQuery: array of string; const AJSONArray: TJSONArray; out AObjects: TArray<TObjectID>); overload;
/// <summary>Retrieve an installation object. Return false if the installation object was not found. </summary>
function RetrieveInstallation(const AObjectID: string; const AJSON: TJSONArray = nil): Boolean; overload;
// Push
procedure PushBody(const AMessage: TJSONObject);
procedure PushToDevices(const ADevices: array of string; const AData: TJSONObject);
procedure PushBroadcast(const AData: TJSONObject); overload;
procedure PushBroadcast(const AData, AFilter: TJSONObject); overload;
procedure PushToChannels(const AChannels: array of string; const AData: TJSONObject);
procedure PushWhere(const AWhere: TJSONObject; const AData: TJSONObject);
// Files
procedure UploadFile(const AFileName: string; const AContentType: string; out ANewFile: TFile); overload;
procedure UploadFile(const AFileName: string; const AStream: TStream; const AContentType: string; out ANewFile: TFile); overload;
function DeleteFile(const AFileID: TFile): Boolean;
// Users
function QueryUserName(const AUserName: string; AProc: TQueryUserNameProc): Boolean; overload;
function QueryUserName(const AUserName: string; out AUser: TUser; const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveUser(const AObjectID: string; AProc: TRetrieveUserProc): Boolean; overload;
function RetrieveUser(const AObjectID: string; out AUser: TUser; const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveUser(const ALogin: TLogin; AProc: TRetrieveUserProc): Boolean; overload;
function RetrieveUser(const ALogin: TLogin; out AUser: TUser; const AJSON: TJSONArray): Boolean; overload;
procedure SignupUser(const AUserName, APassword: string; const AUserFields: TJSONObject; out ANewUser: TLogin);
procedure LoginUser(const AUserName, APassword: string; AProc: TLoginProc); overload;
procedure LoginUser(const AUserName, APassword: string; out ALogin: TLogin; const AJSONArray: TJSONArray = nil); overload;
function RetrieveCurrentUser(AProc: TRetrieveUserProc): Boolean; overload;
function RetrieveCurrentUser(out AUser: TUser; const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveCurrentUser(const ALogin: TLogin; AProc: TRetrieveUserProc): Boolean; overload;
function RetrieveCurrentUser(const ALogin: TLogin; const AJSON: TJSONArray): Boolean; overload;
procedure UpdateUser(const AObjectID: string; const AUserObject: TJSONObject; out AUpdatedAt: TUpdatedAt); overload;
procedure UpdateUser(const ALogin: TLogin; const AUserObject: TJSONObject; out AUpdatedAt: TUpdatedAt); overload;
function DeleteUser(const AObjectID: string): Boolean; overload;
function DeleteUser(const ALogin: TLogin): Boolean; overload;
procedure QueryUsers(const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryUsers(const AQuery: array of string; const AJSONArray: TJSONArray; out AUsers: TArray<TUser>); overload;
procedure Login(const ASessionToken: string); overload;
procedure Login(const ALogin: TLogin); overload;
procedure Logout;
property LoggedIn: Boolean read GetLoggedIn;
property Authentication: TAuthentication read FAuthentication write FAuthentication;
property DefaultAuthentication: TDefaultAuthentication read FDefaultAuthentication write FDefaultAuthentication;
property Response: TRESTResponse read FResponse;
property BaseURL: string read FBaseURL write SetBaseURL;
property ConnectionInfo: TConnectioninfo read FConnectionInfo write SetConnectionInfo;
end;
implementation
uses System.DateUtils, System.Rtti, REST.JSON.Types, System.TypInfo,
REST.Backend.Consts;
procedure CheckObjectID(const AObjectID: string);
begin
if AObjectID = '' then
raise EParseAPIError.Create(sObjectIDRequired);
end;
procedure CheckMasterKey(const AMasterKey: string);
begin
if AMasterKey = '' then
raise EParseAPIError.Create(sMasterKeyRequired);
end;
procedure CheckSessionID(const SessionID: string);
begin
if SessionID = '' then
raise EParseAPIError.Create(sSessionIDRequired);
end;
procedure CheckAPIKey(const AKey: string);
begin
if AKey = '' then
raise EParseAPIError.Create(sAPIKeyRequired);
end;
procedure CheckBackendClass(const ABackendClassName: string);
begin
if ABackendClassName = '' then
raise EParseAPIError.Create(sBackendClassNameRequired);
end;
procedure CheckJSONObject(const AJSON: TJSONObject);
begin
if AJSON = nil then
raise EParseAPIError.Create(sJSONObjectRequired);
end;
constructor TParseApi.Create(AOwner: TComponent;
const AResponse: TRESTResponse);
begin
inherited Create(AOwner);
FConnectionInfo := TConnectionInfo.Create(cDefaultApiVersion, '');
FRESTClient := TRESTClient.Create(nil);
FRESTClient.SynchronizedEvents := False;
FRequest := TRESTRequest.Create(nil);
FRequest.SynchronizedEvents := False;
FRequest.Client := FRESTClient;
FOwnsResponse := AResponse = nil;
if FOwnsResponse then
FResponse := TRESTResponse.Create(nil)
else
FResponse := AResponse;
FRequest.Response := FResponse;
BaseURL := cDefaultBaseURL;
ApplyConnectionInfo;
end;
// Parse installation json
//deviceType "ios" or "android"
//installationId android
//deviceToken ios
//badge ios
//timeZone both
//channels both
function TParseApi.CreateIOSInstallationObject(const ADeviceToken: string; ABadge: Integer;
AChannels: array of string): TJSONObject;
var
LArray: TJSONArray;
S: string;
LProperties: TJSONObject;
begin
LProperties := TJSONObject.Create;
try
LProperties.AddPair('badge', TJSONNumber.Create(ABadge)); // Do not localize
LArray := TJSONArray.Create;
for S in AChannels do
LArray.AddElement(TJSONString.Create(S));
LProperties.AddPair('channels', LArray);
// LProperties.AddPair('timeZone', TJSONString.Create(????));
Result := CreateIOSInstallationObject(ADeviceToken, LProperties);
finally
LProperties.Free;
end;
end;
function TParseApi.CreateIOSInstallationObject(const ADeviceToken: string;
const AProperties: TJSONObject): TJSONObject;
var
LPair: TJSONPair;
begin
Result := TJSONObject.Create;
Result.AddPair('deviceType', TJSONString.Create(TDeviceNames.IOS)); // Do not localize
Result.AddPair('deviceToken', TJSONString.Create(ADeviceToken)); // Do not localize
if AProperties <> nil then
for LPair in AProperties do
Result.AddPair(LPair.Clone as TJSONPair);
end;
function TParseApi.CreateAndroidInstallationObject(const AInstallationID, ADeviceToken: string; AChannels: array of string): TJSONObject;
var
LArray: TJSONArray;
S: string;
LProperties: TJSONObject;
begin
LProperties := TJSONObject.Create;
try
LArray := TJSONArray.Create;
for S in AChannels do
LArray.AddElement(TJSONString.Create(S));
LProperties.AddPair('channels', LArray);
Result := CreateAndroidInstallationObject(AInstallationID, ADeviceToken, LProperties);
finally
LProperties.Free;
end;
end;
function TParseApi.CreateAndroidInstallationObject(const AInstallationID, ADeviceToken: string; const AProperties: TJSONObject): TJSONObject;
begin
Result := CreateAndroidInstallationObject('', AInstallationID, ADeviceToken, AProperties);
end;
function TParseApi.CreateAndroidInstallationObject(const AGCMAppID, AInstallationID, ADeviceToken: string; const AProperties: TJSONObject): TJSONObject;
var
LPair: TJSONPair;
begin
Result := TJSONObject.Create;
Result.AddPair('deviceType', TJSONString.Create(TDeviceNames.Android)); // Do not localize
Result.AddPair('pushType', 'gcm'); // Do not localize
Result.AddPair('deviceToken', TJSONString.Create(ADeviceToken)); // Do not localize
Result.AddPair('GCMSenderId', TJSONString.Create(AGCMAppID));
Result.AddPair('installationId', TJSONString.Create(AInstallationID)); // Do not localize
if AProperties <> nil then
for LPair in AProperties do
Result.AddPair(LPair.Clone as TJSONPair);
end;
const
sApiVersion = 'ApiVersion';
sApplicationId = 'X-Parse-Application-Id';
sRESTAPIKey = 'X-Parse-REST-API-Key';
sMasterKey = 'X-Parse-Master-Key';
sSessionToken = 'X-Parse-Session-Token';
procedure AddHeaderParam(AParams: TRESTRequestParameterList; const AName, AValue: string);
begin
AParams.AddItem(AName, AValue,
TRESTRequestParameterKind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]);
end;
procedure TParseApi.ApplyConnectionInfo;
begin
FRESTClient.Params.AddUrlSegment(sApiVersion, FConnectionInfo.ApiVersion);
AddHeaderParam(FRESTClient.Params, sApplicationId, FConnectionInfo.ApplicationID);
FRESTClient.ProxyPort := FConnectionInfo.ProxyPort;
FRESTClient.ProxyPassword := FConnectionInfo.ProxyPassword;
FRESTClient.ProxyUsername := FConnectionInfo.ProxyUsername;
FRESTClient.ProxyServer := FConnectionInfo.ProxyServer;
end;
procedure TParseApi.AddMasterKey(const AKey: string);
begin
CheckMasterKey(AKey);
AddHeaderParam(FRequest.Params, sMasterKey, AKey);
end;
procedure TParseApi.AddSessionToken(const AAPIKey, ASessionToken: string);
begin
CheckSessionID(ASessionToken);
AddHeaderParam(FRequest.Params, sSessionToken, ASessionToken);
AddAPIKey(AAPIKey); // Need REST API Key with session token
end;
procedure TParseApi.AddAPIKey(const AKey: string);
begin
CheckAPIKey(AKey);
AddHeaderParam(FRequest.Params, sRESTAPIKey, AKey);
end;
procedure TParseAPI.CheckAuthentication(AAuthentication: TAuthentications);
var
LAuthentication: TAuthentication;
LInvalid: string;
LValid: string;
LValidItems: TStrings;
begin
LAuthentication := GetActualAuthentication;
if not (LAuthentication in AAuthentication) then
begin
LInvalid := System.TypInfo.GetEnumName(TypeInfo(TAuthentication), Integer(LAuthentication));
LValidItems := TStringList.Create;
try
for LAuthentication in AAuthentication do
LValidItems.Add(System.TypInfo.GetEnumName(TypeInfo(TAuthentication), Integer(LAuthentication)));
if LValidItems.Count = 1 then
LValid := Format(sUseValidAuthentication, [LValidItems[0]])
else
begin
LValid := LValidItems[LValidItems.Count - 1];
LValidItems.Delete(LValidItems.Count-1);
LValidItems.Delimiter := ',';
LValid := Format(sUseValidAuthentications, [LValidItems.DelimitedText, LValid])
end;
finally
LValidItems.Free;
end;
raise EParseAPIError.CreateFmt(sInvalidAuthenticationForThisOperation, [LInvalid, LValid]);
end;
end;
function TParseAPI.GetActualAuthentication: TAuthentication;
var
LAuthentication: TAuthentication;
begin
LAuthentication := FAuthentication;
if LAuthentication = TAuthentication.Default then
case FDefaultAuthentication of
TDefaultAuthentication.MasterKey:
LAuthentication := TAuthentication.MasterKey;
TDefaultAuthentication.APIKey:
LAuthentication := TAuthentication.ApiKey;
TParseApi.TDefaultAuthentication.Session:
LAuthentication := TAuthentication.Session;
TParseApi.TDefaultAuthentication.None:
LAuthentication := TAuthentication.None;
else
Assert(False);
end;
Result := LAuthentication;
end;
procedure TParseApi.AddAuthParameters;
var
LAuthentication: TAuthentication;
begin
LAuthentication := GetActualAuthentication;
AddAuthParameters(LAuthentication);
end;
procedure TParseApi.AddAuthParameters(AAuthentication: TAuthentication);
begin
case AAuthentication of
TParseApi.TAuthentication.APIKey:
AddAPIKey(ConnectionInfo.RestApiKey);
TParseApi.TAuthentication.MasterKey:
AddMasterKey(ConnectionInfo.MasterKey);
TParseApi.TAuthentication.Session:
AddSessionToken(ConnectionInfo.RESTApiKey, FSessionToken);
TParseApi.TAuthentication.None:
;
else
Assert(False);
end;
end;
function TParseApi.CreateException(const ARequest: TRESTRequest;
const AClass: TParseAPIErrorClass): EParseAPIError;
var
LCode: Integer;
LMessage: string;
LJSONCode: TJSONValue;
LJSONMessage: TJSONValue;
begin
if ARequest.Response.JSONValue <> nil then
begin
LJSONCode := (ARequest.Response.JSONValue as TJSONObject).GetValue('code'); // Do not localize
if LJSONCode <> nil then
LCode := StrToInt(LJSONCode.Value)
else
LCode := 0;
LJSONMessage := (ARequest.Response.JSONValue as TJSONObject).GetValue('error'); // Do not localize
if LJSONMessage <> nil then
LMessage := LJSONMessage.Value;
if (LJSONCode <> nil) and (LJSONMessage <> nil) then
Result := TParseAPIErrorClass.Create(LCode, LMessage)
else if LJSONMessage <> nil then
Result := TParseAPIErrorClass.Create(LMessage)
else
Result := TParseAPIErrorClass.Create(ARequest.Response.Content);
end
else
Result := TParseAPIErrorClass.Create(ARequest.Response.Content);
end;
procedure TParseApi.CheckForResponseError;
begin
CheckForResponseError(FRequest);
end;
procedure TParseApi.CheckForResponseError(const ARequest: TRESTRequest);
begin
if ARequest.Response.StatusCode >= 300 then
begin
if (ARequest.Response.StatusCode >= 400) and (ARequest.Response.StatusCode < 500)
and (ARequest.Response.JSONValue <> nil) then
begin
raise CreateException(ARequest, EParseAPIError);
end
else
raise EParseAPIError.Create(ARequest.Response.Content);
end
end;
procedure TParseApi.CheckForResponseError(AValidStatusCodes: array of Integer);
begin
CheckForResponseError(FRequest, AValidStatusCodes);
end;
procedure TParseApi.CheckForResponseError(const ARequest: TRESTRequest; AValidStatusCodes: array of Integer);
var
LCode: Integer;
LResponseCode: Integer;
begin
LResponseCode := ARequest.Response.StatusCode;
for LCode in AValidStatusCodes do
if LResponseCode = LCode then
Exit; // Code is valid, exit with no exception
CheckForResponseError(ARequest);
end;
function TParseApi.DeleteClass(const AID: TObjectID): Boolean;
begin
Result := DeleteClass(AID.BackendClassName, AID.ObjectID);
end;
function TParseApi.DeleteResource(const AResource: string; AReset: Boolean): Boolean;
begin
Assert(AResource <> '');
if AReset then
begin
FRequest.ResetToDefaults;
AddAuthParameters;
end;
FRequest.Method := TRESTRequestMethod.rmDELETE;
FRequest.Resource := AResource;
FRequest.Execute;
CheckForResponseError([404]);
Result := FRequest.Response.StatusCode <> 404
end;
function TParseApi.DeleteClass(const ABackendClassName: string; const AObjectID: string): Boolean;
begin
CheckBackendClass(ABackendClassName);
CheckObjectID(AObjectID);
FRequest.ResetToDefaults;
AddAuthParameters;
Result := DeleteResource(sClasses + '/' + ABackendClassname + '/' + AObjectID, False);
end;
function TParseApi.DeleteInstallation(const AObjectID: string): Boolean;
begin
FRequest.ResetToDefaults;
AddAuthParameters(TAuthentication.MasterKey); // Required
Result := DeleteResource(sInstallations + '/' + AObjectID, False);
end;
////curl -X GET \
//// -H "X-Parse-Application-Id: appidgoeshere" \
//// -H "X-Parse-Master-Key: masterkeygoeshere" \
//// https://api.parse.com/1/installations
procedure TParseApi.QueryInstallation(const AQuery: array of string; const AJSONArray: TJSONArray);
begin
FRequest.ResetToDefaults;
AddAuthParameters(TAuthentication.MasterKey); // Master required
QueryResource(sInstallations, AQuery, AJSONArray, False);
end;
procedure TParseApi.QueryInstallation(const AQuery: array of string; const AJSONArray: TJSONArray; out AObjects: TArray<TObjectID>);
var
LJSONValue: TJSONValue;
LList: TList<TObjectID>;
LInstallation: TObjectID;
begin
FRequest.ResetToDefaults;
AddAuthParameters(TAuthentication.MasterKey); // Master required
QueryResource(sInstallations, AQuery, AJSONArray, False);
LList := TList<TObjectID>.Create;
try
for LJSONValue in AJSONArray do
begin
if LJSONValue is TJSONObject then
begin
// Blank backend class name
LInstallation := ObjectIDFromObject('', TJSONObject(LJSONValue));
LList.Add(LInstallation);
end
else
raise EParseAPIError.Create(sJSONObjectExpected);
end;
AObjects := LList.ToArray;
finally
LList.Free;
end;
end;
function TParseAPI.RetrieveInstallation(const AObjectID: string; const AJSON: TJSONArray = nil): Boolean;
begin
Result := DoRetrieveInstallation(AObjectID, AJSON, nil, True);
end;
//curl -X GET \
// -H "X-Parse-Application-Id: cIj01OkQeJ8LUzFZjMnFyJQD6qx0OehYep0mMdak" \
// -H "X-Parse-REST-API-Key: yVVIeShrcZrdr3e4hMLodfnvLckWBZfTonCYlBsq" \
// https://api.parse.com/1/installations/mrmBZvsErB
function TParseAPI.DoRetrieveInstallation(const AObjectID: string; const AJSON: TJSONArray; AProc: TRetrieveJSONProc; AReset: Boolean): Boolean;
var
LResponse: TJSONObject;
begin
Result := False;
CheckObjectID(AObjectID);
if AReset then
begin
FRequest.ResetToDefaults;
AddAuthParameters;
end;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := sInstallations + '/' + AObjectID;
FRequest.Execute;
CheckForResponseError([404]); // 404 = not found
if FRequest.Response.StatusCode <> 404 then
begin
Result := True;
// '{"createdAt":"2013-10-16T20:21:57.326Z","objectId":"5328czuo2e"}'
LResponse := FRequest.Response.JSONValue as TJSONObject;
if AJSON <> nil then
AJSON.AddElement(LResponse.Clone as TJSONObject);
if Assigned(AProc) then
AProc(LResponse);
end
end;
destructor TParseApi.Destroy;
begin
FRESTClient.Free;
FRequest.Free;
if FOwnsResponse then
FResponse.Free;
inherited;
end;
procedure TParseApi.QueryResource(const AResource: string; const AQuery: array of string; const AJSONArray: TJSONArray; AReset: Boolean);
var
LRoot: TJSONArray;
S: string;
I: Integer;
LJSONValue: TJSONValue;
begin
if AReset then
begin
FRequest.ResetToDefaults;
AddAuthParameters;
end;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := AResource;
for S in AQuery do
begin
I := S.IndexOf('=');
if I > 0 then
FRequest.AddParameter(S.Substring(0, I).Trim, S.Substring(I+1).Trim);
end;
FRequest.Execute;
CheckForResponseError([404]); // 404 = not found
if FRequest.Response.StatusCode <> 404 then
begin
// {"results":[{"Age":1,"age":42,"name":"Elmo","createdAt":"2013-11-02T18:09:30.751Z","updatedAt":"2013-11-02T18:11:27.910Z","objectId":"dB9jr8Su8u"},{"age":43,"name":"Elmo","createdAt":"2013-11-02T18:17:48.564Z","updatedAt":"2013-11-02T18:18:03.863Z","objectId":"cT7blzwGxV"},
LRoot := (FRequest.Response.JSONValue as TJSONObject).GetValue('results') as TJSONArray; // Do not localize
for LJSONValue in LRoot do
AJSONArray.AddElement(TJSONValue(LJSONValue.Clone))
end;
end;
procedure TParseApi.QueryClass(const ABackendClassName: string; const AQuery: array of string; const AJSONArray: TJSONArray);
begin
QueryResource(sClasses + '/' + ABackendClassname, AQuery, AJSONArray, True);
end;
procedure TParseApi.QueryClass(const ABackendClassName: string; const AQuery: array of string; const AJSONArray: TJSONArray; out AObjects: TArray<TObjectID>);
var
LJSONValue: TJSONValue;
LList: TList<TObjectID>;
LObjectID: TObjectID;
begin
CheckBackendClass(ABackendClassName);
FRequest.ResetToDefaults;
AddAuthParameters;
QueryResource(sClasses + '/' + ABackendClassname, AQuery, AJSONArray, False);
LList := TList<TObjectID>.Create;
try
for LJSONValue in AJSONArray do
begin
if LJSONValue is TJSONObject then
begin
LObjectID := ObjectIDFromObject(ABackendClassName, TJSONObject(LJSONValue));
LList.Add(LObjectID);
end
else
raise EParseAPIError.Create(sJSONObjectExpected);
end;
AObjects := LList.ToArray;
finally
LList.Free;
end;
end;
function ValueToJsonValue(AValue: TValue): TJSONValue;
begin
if AValue.IsType<Int64> then
Result := TJSONNumber.Create(AValue.AsInt64)
else if AValue.IsType<Extended> then
Result := TJSONNumber.Create(AValue.AsExtended)
else if AValue.IsType<string> then
Result := TJSONString.Create(AValue.AsString)
else
Result := TJSONString.Create(AValue.ToString)
end;
function TParseApi.FindClass(const ABackendClassName, AObjectID: string; out AFoundObject: TObjectID; const AJSON: TJSONArray; AProc: TFindObjectProc): Boolean;
var
LResponse: TJSONObject;
begin
CheckBackendClass(ABackendClassName);
CheckObjectID(AObjectID);
Result := False;
FRequest.ResetToDefaults;
AddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := sClasses + '/' + ABackendClassname + '/' + AObjectID;
FRequest.Execute;
CheckForResponseError([404]); // 404 = not found
if FRequest.Response.StatusCode <> 404 then
begin
Result := True;
// '{"createdAt":"2013-10-16T20:21:57.326Z","objectId":"5328czuo2e"}'
LResponse := FRequest.Response.JSONValue as TJSONObject;
AFoundObject := ObjectIDFromObject(ABackendClassName, LResponse);
if Assigned(AJSON) then
AJSON.AddElement(LResponse.Clone as TJSONObject);
if Assigned(AProc) then
begin
AProc(AFoundObject, LResponse);
end;
end;
end;
function TParseApi.FindClass(const ABackendClassName, AObjectID: string; AProc: TFindObjectProc): Boolean;
var
LObjectID: TObjectID;
begin
Result := FindClass(ABackendClassName, AObjectID, LObjectID, nil, AProc);
end;
function TParseApi.FindClass(const ABackendClassName, AObjectID: string; out AFoundObjectID: TObjectID; const AFoundJSON: TJSONArray): Boolean;
begin
Result := FindClass(ABackendClassName, AObjectID, AFoundObjectID, AFoundJSON, nil);
end;
function TParseApi.FindClass(const AID: TObjectID; out AFoundObjectID: TObjectID; const AFoundJSON: TJSONArray): Boolean;
begin
Result := FindClass(AID.BackendClassName, AID.ObjectID, AFoundObjectID, AFoundJSON, nil);
end;
function TParseApi.FindClass(const AID: TObjectID; AProc: TFindObjectProc): Boolean;
var
LObjectID: TObjectID;
begin
Result := FindClass(AID.BackendClassName, AID.ObjectID, LObjectID, nil, AProc);
end;
function TParseApi.GetLoggedIn: Boolean;
begin
Result := FSessionToken <> '';
end;
procedure TParseApi.PushBody(const AMessage: TJSONObject);
begin
if (AMessage.GetValue('where') = nil) and
(AMessage.GetValue('channels') = nil) then
begin
// channels or where required required. Empty where means Everyone.
AMessage.AddPair('where', TJSONObject.Create); // Do not localize
end;
FRequest.ResetToDefaults;
AddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmPOST;
FRequest.Resource := sPush;
FRequest.AddBody(AMessage);
FRequest.Execute;
CheckForResponseError;
end;
//curl -X POST \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "Content-Type: application/json" \
// -d '{
// "where": {
// "devicetype": "ios,android",
/// },
// "data": {
// "alert": "The Giants won against the Mets 2-3."
// }
// }' \
// https://api.parse.com/1/push
procedure TParseApi.PushBroadcast(const AData: TJSONObject);
begin
PushBroadcast(AData, nil);
end;
procedure TParseApi.PushBroadcast(const AData, AFilter: TJSONObject);
var
LJSON: TJSONObject;
LPair: TJSONPair;
begin
LJSON := TJSONObject.Create;
try
if AData <> nil then
LJSON.AddPair('data', AData.Clone as TJSONObject); // Do not localize
if AFilter <> nil then
for LPair in AFilter do
// such as "where" and "channels"
LJSON.AddPair(LPair.Clone as TJSONPair);
PushBody(LJSON);
finally
LJSON.Free;
end;
end;
//curl -X POST \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "Content-Type: application/json" \
// -d '{
// "channels": [
// "Giants",
// "Mets"
// ],
// "data": {
// "alert": "The Giants won against the Mets 2-3."
// }
// }' \
// https://api.parse.com/1/push
procedure TParseApi.PushToChannels(const AChannels: array of string; const AData: TJSONObject);
var
LJSON: TJSONObject;
LChannels: TJSONArray;
S: string;
begin
if Length(AChannels) = 0 then
raise EParseAPIError.Create(sChannelNamesExpected);
LJSON := TJSONObject.Create;
try
LChannels := TJSONArray.Create;
for S in AChannels do
LChannels.Add(S);
LJSON.AddPair('channels', LChannels); // Do not localize
LJSON.AddPair('data', AData.Clone as TJSONObject); // Do not localize
PushBody(LJSON);
finally
LJSON.Free;
end;
end;
//curl -X POST \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "Content-Type: application/json" \
// -d '{
// "where": {
// {"deviceType":{"$in":["ios", "android"]}}
// },
// "data": {
// "alert": "The Giants won against the Mets 2-3."
// }
// }' \
// https://api.parse.com/1/push
procedure TParseApi.PushWhere(const AWhere: TJSONObject; const AData: TJSONObject);
var
LJSON: TJSONObject;
begin
LJSON := TJSONObject.Create;
try
if AWhere <> nil then
LJSON.AddPair('where', AWhere.Clone as TJSONObject); // Do not localize
if AData <> nil then
LJSON.AddPair('data', AData.Clone as TJSONObject); // Do not localize
PushBody(LJSON);
finally
LJSON.Free;
end;
end;
//curl -X POST \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "Content-Type: application/json" \
// -d '{
// "where": {
// {"deviceType":{"$in":["ios", "android"]}}
// },
// "data": {
// "alert": "The Giants won against the Mets 2-3."
// }
// }' \
// https://api.parse.com/1/push
// where={"score":{"$in":[1,3,5,7,9]}}
procedure TParseApi.PushToDevices(const ADevices: array of string; const AData: TJSONObject);
var
LDevices: TJSONArray;
LWhere: TJSONObject;
LQuery: TJSONObject;
S: string;
begin
if Length(ADevices) = 0 then
raise EParseAPIError.Create(sDeviceNamesExpected);
LDevices := TJSONArray.Create;
for S in ADevices do
LDevices.Add(S);
LQuery := TJSONObject.Create;
LQuery.AddPair('$in', LDevices); // Do not localize
LWhere := TJSONObject.Create;
try
LWhere.AddPair('deviceType', LQuery); // Do not localize
PushWhere(LWhere, AData);
finally
LWhere.Free;
end;
end;
function TParseApi.ObjectIDFromObject(const ABackendClassName: string; const AJSONObject: TJSONObject): TObjectID;
var
LObjectID: string;
begin
LObjectID := AJSONObject.GetValue('objectId').Value; // Do not localize
Result := ObjectIDFromObject(ABackendClassName, LObjectID, AJSONObject);
end;
function TParseApi.ObjectIDFromObject(const ABackendClassName, AObjectID: string; const AJSONObject: TJSONObject): TObjectID;
begin
Result := TObjectID.Create(ABackendClassName, AObjectID);
if AJSONObject.GetValue('createdAt') <> nil then // Do not localize
Result.FCreatedAt := TJSONDates.AsDateTime(AJSONObject.GetValue('createdAt'), TJSONDates.TFormat.ISO8601, DateTimeIsUTC); // Do not localize
if AJSONObject.GetValue('updatedAt') <> nil then
Result.FUpdatedAt := TJSONDates.AsDateTime(AJSONObject.GetValue('updatedAt'), TJSONDates.TFormat.ISO8601, DateTimeIsUTC); // Do not localize
end;
function TParseApi.FileIDFromObject(const AFileName: string; const AJSONObject: TJSONObject): TFile;
var
LName: string;
begin
if AJSONObject.GetValue('name') <> nil then // Do not localize
LName := AJSONObject.GetValue('name').Value; // Do not localize
Result := TFile.Create(LName);
Result.FFileName := AFileName;
if AJSONObject.GetValue('url') <> nil then // Do not localize
Result.FDownloadURL := AJSONObject.GetValue('url').Value; // Do not localize
end;
procedure TParseApi.Login(const ALogin: TLogin);
begin
Login(ALogin.SessionToken);
end;
procedure TParseApi.Login(const ASessionToken: string);
begin
FSessionToken := ASessionToken;
FAuthentication := TAuthentication.Session;
end;
function TParseApi.LoginFromObject(const AUserName: string; const AJSONObject: TJSONObject): TLogin;
var
LUser: TUser;
LSessionToken: string;
begin
LUser := UserFromObject(AUserName, AJSONObject);
if AJSONObject.GetValue('sessionToken') <> nil then // Do not localize
LSessionToken := AJSONObject.GetValue('sessionToken').Value; // Do not localize
Assert(LSessionToken <> '');
Result := TLogin.Create(LSessionToken, LUser);
end;
function TParseApi.UpdatedAtFromObject(const ABackendClassName, AObjectID: string; const AJSONObject: TJSONObject): TUpdatedAt;
var
LUpdatedAt: TDateTime;
begin
if AJSONObject.GetValue('updatedAt') <> nil then // Do not localize
LUpdatedAt := TJSONDates.AsDateTime(AJSONObject.GetValue('updatedAt'), TJSONDates.TFormat.ISO8601, DateTimeIsUTC) // Do not localize
else
LUpdatedAt := 0;
Result := TUpdatedAt.Create(ABackendClassName, AObjectID, LUpdatedAt);
end;
function TParseApi.UserFromObject(const AUserName: string; const AJSONObject: TJSONObject): TUser;
begin
Result := TUser.Create(AUserName);
if AJSONObject.GetValue('createdAt') <> nil then // Do not localize
Result.FCreatedAt := TJSONDates.AsDateTime(AJSONObject.GetValue('createdAt'), TJSONDates.TFormat.ISO8601, DateTimeIsUTC); // Do not localize
if AJSONObject.GetValue('updatedAt') <> nil then // Do not localize
Result.FUpdatedAt := TJSONDates.AsDateTime(AJSONObject.GetValue('updatedAt'), TJSONDates.TFormat.ISO8601, DateTimeIsUTC); // Do not localize
if AJSONObject.GetValue('objectId') <> nil then // Do not localize
Result.FObjectID := AJSONObject.GetValue('objectId').Value; // Do not localize
end;
function TParseApi.UserFromObject(const AJSONObject: TJSONObject): TUser;
var
LUserName: string;
begin
if AJSONObject.GetValue('username') <> nil then // Do not localize
LUserName := AJSONObject.GetValue('username').Value; // Do not localize
Assert(LUserName <> '');
Result := UserFromObject(LUserName, AJSONObject);
end;
procedure TParseApi.PostResource(const AResource: string; const AJSON: TJSONObject; AReset: Boolean);
begin
CheckJSONObject(AJSON);
// NEW : POST
if AReset then
begin
FRequest.ResetToDefaults;
AddAuthParameters;
end;
FRequest.Method := TRESTRequestMethod.rmPOST;
FRequest.Resource := AResource;
FRequest.AddBody(AJSON);
FRequest.Execute;
CheckForResponseError;
end;
procedure TParseApi.CreateClass(const ABackendClassName: string; const AJSON: TJSONObject;
out ANewObject: TObjectID);
begin
CreateClass(ABackendClassName, nil, AJSON, ANewObject);
end;
procedure TParseApi.CreateClass(const ABackendClassName: string; const AACL, AJSON: TJSONObject;
out ANewObject: TObjectID);
var
LResponse: TJSONObject;
LJSON: TJSONObject;
begin
CheckBackendClass(ABackendClassName);
LJSON := nil;
try
if (AACL <> nil) and (AJSON <> nil) then
begin
LJSON := AJSON.Clone as TJSONObject;
LJSON.AddPair('ACL', AACL.Clone as TJSONObject); // Do not localize
end
else if AACL <> nil then
LJSON := AACL
else
LJSON := AJSON;
FRequest.ResetToDefaults;
AddAuthParameters;
PostResource(sClasses + '/' + ABackendClassName, LJSON, False);
// '{"createdAt":"2013-10-16T20:21:57.326Z","objectId":"5328czuo2e"}'
LResponse := FRequest.Response.JSONValue as TJSONObject;
ANewObject := ObjectIDFromObject(ABackendClassName, LResponse);
finally
if (LJSON <> AACL) and (LJSON <> AJSON) then
LJSON.Free;
end;
end;
procedure TParseApi.PutResource(const AResource: string; const AJSONObject: TJSONObject; AReset: Boolean);
begin
CheckJSONObject(AJSONObject);
if AReset then
begin
FRequest.ResetToDefaults;
AddAuthParameters;
end;
FRequest.Method := TRESTRequestMethod.rmPUT;
FRequest.Resource := AResource;
FRequest.AddBody(AJSONObject);
FRequest.Execute;
CheckForResponseError;
end;
procedure TParseApi.UpdateClass(const ABackendClassName, AObjectID: string; const AJSONObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
var
LResponse: TJSONObject;
begin
CheckBackendClass(ABackendClassName);
CheckObjectID(AObjectID);
FRequest.ResetToDefaults;
AddAuthParameters;
PutResource(sClasses + '/' + ABackendClassname + '/' + AObjectID, AJSONObject, False);
LResponse := FRequest.Response.JSONValue as TJSONObject;
// '{"updatedAt":"2013-10-16T20:21:57.326Z"}'
AUpdatedAt := UpdatedAtFromObject(ABackendClassName, AObjectID, LResponse);
end;
procedure TParseApi.UpdateClass(const AID: TObjectID; const AJSONObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
begin
UpdateClass(AID.BackendClassName, AID.ObjectID, AJSONObject, AUpdatedAt);
end;
procedure TParseApi.SetBaseURL(const Value: string);
begin
FBaseURL := Value;
FRESTClient.BaseURL := Value;
end;
procedure TParseApi.SetConnectionInfo(const Value: TConnectioninfo);
begin
FConnectionInfo := Value;
ApplyConnectionInfo;
end;
procedure TParseApi.UploadFile(const AFileName: string; const AContentType: string; out ANewFile: TFile);
var
LStream: TFileStream;
begin
LStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
UploadFile(AFileName, LStream, AContentType, ANewFile);
finally
LStream.Free;
end;
end;
//curl -X POST \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "Content-Type: text/plain" \
// -d 'Hello, World!' \
// https://api.parse.com/1/files/hello.txt
procedure TParseApi.UploadFile(const AFileName: string; const AStream: TStream; const AContentType: string; out ANewFile: TFile);
var
LResponse: TJSONObject;
LContentType: TRESTContentType;
begin
FRequest.ResetToDefaults;
AddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmPOST;
FRequest.Resource := sFiles + '/' + AFileName;
if AContentType = '' then
LContentType := TRESTContentType.ctAPPLICATION_OCTET_STREAM
else
LContentType := ContentTypeFromString(AContentType);
FRequest.AddBody(AStream, LContentType);
FRequest.Execute;
LResponse := FRequest.Response.JSONValue as TJSONObject;
ANewFile := FileIDFromObject(AFileName, LResponse);
end;
//curl -X DELETE \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-Master-Key: masterkeygoeshere" \
// https://api.parse.com/1/files/...profile.png
function TParseApi.DeleteFile(const AFileID: TFile): Boolean;
begin
FRequest.ResetToDefaults;
AddAuthParameters(TAuthentication.MasterKey); //Required
Result := DeleteResource(sFiles + '/' + AFileID.Name, False);
end;
//curl -X POST \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "Content-Type: application/json" \
// -d '{
// "deviceType": "ios",
// "deviceToken": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
// "channels": [
// ""
// ]
// }' \
// https://api.parse.com/1/installations
procedure TParseApi.UploadInstallation(const AJSON: TJSONObject; out ANewObject: TObjectID);
var
LResponse: TJSONObject;
begin
PostResource(sInstallations, AJSON, True);
// '{"createdAt":"2013-10-16T20:21:57.326Z","objectId":"5328czuo2e"}'
LResponse := FRequest.Response.JSONValue as TJSONObject;
ANewObject := ObjectIDFromObject('', LResponse);
end;
//curl -X PUT \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "Content-Type: application/json" \
// -d '{
// "deviceType": "ios",
// "deviceToken": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
// "channels": [
// "",
// "foo"
// ]
// }' \
// https://api.parse.com/1/installations/mrmBZvsErB
procedure TParseApi.UpdateInstallation(const AObjectID: string; const AJSONObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
var
LResponse: TJSONObject;
begin
CheckObjectID(AObjectID);
PutResource(sInstallations + '/' + AObjectID, AJSONObject, True);
LResponse := FRequest.Response.JSONValue as TJSONObject;
// '{"updatedAt":"2013-10-16T20:21:57.326Z"}'
AUpdatedAt := UpdatedAtFromObject('', AObjectID, LResponse);
end;
//curl -X DELETE \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "X-Parse-Session-Token: sessiontokengoeshere" \
// https://api.parse.com/1/users/g7y9tkhB7Oprocedure TParseApi.UserDelete(const AUser: IBackendUser);
//curl -X DELETE \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: masterkeygoeshere" \
// https://api.parse.com/1/users/g7y9tkhB7Oprocedure TParseApi.UserDelete(const AUser: IBackendUser);
function TParseApi.DeleteUser(const AObjectID: string): Boolean;
begin
CheckObjectID(AObjectID);
FRequest.ResetToDefaults;
// This operation require masterkey or session authentication
CheckAuthentication([TAuthentication.MasterKey, TAuthentication.Session]);
AddAuthParameters;
Result := DeleteResource(sUsers + '/' + AObjectID, False);
end;
function TParseApi.DeleteUser(const ALogin: TLogin): Boolean;
begin
CheckObjectID(ALogin.User.ObjectID);
FRequest.ResetToDefaults;
AddSessionToken(ConnectionInfo.RestApiKey, ALogin.SessionToken);
// This operation require masterkey or session authentication
Result := DeleteResource(sUsers + '/' + ALogin.User.ObjectID, False);
end;
//curl -X GET \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// https://api.parse.com/1/users/g1234567
function TParseAPI.RetrieveUser(const ASessionID, AObjectID: string; out AUser: TUser; const AJSON: TJSONArray; AProc: TRetrieveUserProc; AReset: Boolean): Boolean;
var
LResponse: TJSONObject;
begin
Result := False;
CheckObjectID(AObjectID);
if AReset then
begin
FRequest.ResetToDefaults;
if ASessionID <> '' then
AddSessionToken(ConnectionInfo.RestApiKey, ASessionID)
else
AddAuthParameters;
end;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := sUsers + '/' + AObjectID;
FRequest.Execute;
CheckForResponseError([404]); // 404 = not found
if FRequest.Response.StatusCode <> 404 then
begin
Result := True;
// '{"createdAt":"2013-10-16T20:21:57.326Z","objectId":"5328czuo2e"}'
LResponse := FRequest.Response.JSONValue as TJSONObject;
AUser := UserFromObject(LResponse);
if AJSON <> nil then
AJSON.AddElement(LResponse.Clone as TJSONObject);
if Assigned(AProc) then
AProc(AUser, LResponse);
end
end;
function TParseAPI.RetrieveUser(const AObjectID: string; AProc: TRetrieveUserProc): Boolean;
var
LUser: TUser;
begin
Result := RetrieveUser('', AObjectID, LUser, nil, AProc, True);
end;
function TParseAPI.RetrieveUser(const ALogin: TLogin; AProc: TRetrieveUserProc): Boolean;
var
LUser: TUser;
begin
Result := RetrieveUser(ALogin.SessionToken, ALogin.User.ObjectID, LUser, nil, AProc, True);
end;
function TParseAPI.RetrieveUser(const ALogin: TLogin; out AUser: TUser; const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveUser(ALogin.SessionToken, ALogin.User.ObjectID, AUser, AJSON, nil, True);
end;
function TParseAPI.RetrieveUser(const AObjectID: string; out AUser: TUser; const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveUser('', AObjectID, AUser, AJSON, nil, True);
end;
//curl -X GET \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "X-Parse-Session-Token: sessiontokengoeshere" \
// https://api.parse.com/1/users/me
function TParseAPI.RetrieveCurrentUser(const ASessionToken: string; out AUser: TUser; const AJSON: TJSONArray; AProc: TRetrieveUserProc): Boolean;
begin
Result := RetrieveUser(ASessionToken, 'me', AUser, AJSON, AProc, True); // Do not localize
end;
function TParseAPI.RetrieveCurrentUser(AProc: TRetrieveUserProc): Boolean;
var
LUser: TUser;
begin
Result := RetrieveCurrentUser('', LUser, nil, AProc);
end;
function TParseAPI.RetrieveCurrentUser(const ALogin: TLogin; AProc: TRetrieveUserProc): Boolean;
var
LUser: TUser;
begin
Result := RetrieveCurrentUser(ALogin.SessionToken, LUser, nil, AProc);
end;
function TParseAPI.RetrieveCurrentUser(const ALogin: TLogin; const AJSON: TJSONArray): Boolean;
var
LUser: TUser;
begin
Result := RetrieveCurrentUser(ALogin.SessionToken, LUser, AJSON, nil);
end;
function TParseAPI.RetrieveCurrentUser(out AUser: TUser; const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveCurrentUser('', AUser, AJSON, nil);
end;
function TParseApi.QueryUserName(const AUserName: string; out AUser: TUser; const AJSON: TJSONArray; AProc: TQueryUserNameProc): Boolean;
var
LUsers: TJSONArray;
LUser: TJSONObject;
begin
Result := False;
FRequest.ResetToDefaults;
AddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := sUsers;
FRequest.AddParameter('where', TJsonObject.Create.AddPair('username', AUserName)); // do not localize
FRequest.Execute;
CheckForResponseError;
FRequest.Response.RootElement := 'results'; // do not localize
try
LUsers := FRequest.Response.JSONValue as TJSONArray;
if LUsers.Count > 1 then
raise EParseAPIError.Create(sOneUserExpected);
Result := LUsers.Count = 1;
if Result then
begin
LUser := LUsers.Items[0] as TJSONObject;
AUser := UserFromObject(LUser);
if Assigned(AJSON) then
AJSON.AddElement(LUser.Clone as TJSONObject);
if Assigned(AProc) then
AProc(AUser, LUser);
end;
finally
FRequest.Response.RootElement := '';
end;
end;
function TParseApi.QueryUserName(const AUserName: string; AProc: TQueryUserNameProc): Boolean;
var
LUser: TUser;
begin
Result := QueryUserName(AUserName, LUser, nil, AProc);
end;
function TParseApi.QueryUserName(const AUserName: string; out AUser: TUser; const AJSON: TJSONArray = nil): Boolean;
begin
Result := QueryUserName(AUserName, AUser, AJSON, nil);
end;
//curl -X GET \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -G \
// --data-urlencode 'username=passwordgoeshere' \
// --data-urlencode 'password=passwordgoeshere' \
// https://api.parse.com/1/login
procedure TParseApi.LoginUser(const AUserName, APassword: string; AProc: TLoginProc);
var
LResponse: TJsonObject;
LLogin: TLogin;
begin
FRequest.ResetToDefaults;
AddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := 'login'; // do not localize
FRequest.Params.AddItem('username', AUserName, TRESTRequestParameterKind.pkGETorPOST); // do not localize
FRequest.Params.AddItem('password', APassword, TRESTRequestParameterKind.pkGETorPOST); // do not localize
FRequest.Execute;
CheckForResponseError;
LResponse := FRequest.Response.JSONValue as TJSONObject;
if Assigned(AProc) then
begin
LLogin := LoginFromObject(AUserName, LResponse);
AProc(LLogin, LResponse);
end;
end;
procedure TParseApi.Logout;
begin
FSessionToken := '';
if FAuthentication = TAuthentication.Session then
FAuthentication := TAuthentication.Default;
end;
procedure TParseApi.LoginUser(const AUserName, APassword: string; out ALogin: TLogin; const AJSONArray: TJSONArray);
var
LLogin: TLogin;
begin
LoginUser(AUserName, APassword,
procedure(const ALocalLogin: TLogin; const AUserObject: TJSONObject)
begin
LLogin := ALocalLogin;
if Assigned(AJSONArray) then
AJSONArray.Add(AUserObject);
end);
ALogin := LLogin;
end;
//curl -X POST \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "Content-Type: application/json" \
// -d '{"username":"usernamegoeshere","password":"passwordgoeshere","phone":"123-456-7890"}' \
// https://api.parse.com/1/users
procedure TParseApi.SignupUser(const AUserName, APassword: string; const AUserFields: TJSONObject;
out ANewUser: TLogin);
var
LResponse: TJsonObject;
LUser: TJSONObject;
begin
FRequest.ResetToDefaults;
AddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmPOST;
FRequest.Resource := sUsers;
if AUserFields <> nil then
LUser := AUserFields.Clone as TJSONObject
else
LUser := TJSONObject.Create;
try
LUser.AddPair('username', AUserName); // Do not localize
LUser.AddPair('password', APassword); // Do not localize
FRequest.AddBody(LUser);
FRequest.Execute;
CheckForResponseError([201]);
LResponse := FRequest.Response.JSONValue as TJSONObject;
ANewUser := LoginFromObject(AUserName, LResponse);
finally
LUser.Free;
end;
end;
//curl -X PUT \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// -H "X-Parse-Session-Token: sessiontokengoeshere" \
// -H "Content-Type: application/json" \
// -d '{"phone":"123-456-7890"}' \
// https://api.parse.com/1/users/g1234567
procedure TParseApi.UpdateUser(const ASessionID, AObjectID: string; const AUserObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
var
LResponse: TJSONObject;
begin
FRequest.ResetToDefaults;
// Check session or master
if ASessionID <> '' then
AddSessionToken(ConnectionInfo.RestApiKey, ASessionID)
else
AddAuthParameters;
PutResource(sUsers + '/' + AObjectID, AUserObject, False);
LResponse := FRequest.Response.JSONValue as TJSONObject;
// '{"updatedAt":"2013-10-16T20:21:57.326Z"}'
AUpdatedAt := UpdatedAtFromObject('', AObjectID, LResponse);
end;
procedure TParseApi.UpdateUser(const AObjectID: string; const AUserObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
begin
UpdateUser('', AObjectID, AUserObject, AUpdatedAt);
end;
procedure TParseApi.UpdateUser(const ALogin: TLogin; const AUserObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
begin
UpdateUser(ALogin.SessionToken, ALogin.User.ObjectID, AUserObject, AUpdatedAt);
end;
//curl -X GET \
// -H "X-Parse-Application-Id: appidgoeshere" \
// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
// https://api.parse.com/1/users
procedure TParseApi.QueryUsers(const AQuery: array of string; const AJSONArray: TJSONArray);
begin
QueryResource(sUsers, AQuery, AJSONArray, True);
end;
procedure TParseApi.QueryUsers(const AQuery: array of string; const AJSONArray: TJSONArray; out AUsers: TArray<TUser>);
var
LJSONValue: TJSONValue;
LList: TList<TUser>;
LUser: TUser;
begin
QueryResource(sUsers, AQuery, AJSONArray, True);
LList := TList<TUser>.Create;
try
for LJSONValue in AJSONArray do
begin
if LJSONValue is TJSONObject then
begin
LUser := UserFromObject(TJSONObject(LJSONValue));
LList.Add(LUser);
end
else
raise EParseAPIError.Create(sJSONObjectExpected);
end;
AUsers := LList.ToArray;
finally
LList.Free;
end;
end;
////curl -X POST \
//// -H "X-Parse-Application-Id: appidgoeshere" \
//// -H "X-Parse-REST-API-Key: restapikeygoeshere" \
//// -H "Content-Type: application/json" \
//// -d '{"email":"coolguy@iloveapps.com"}' \
//// https://api.parse.com/1/requestPasswordReset
//function TParseApi.ResetUserPassword(const AUserName, APassword: string): IBackendUser;
//begin
//end;
{ EParseException }
constructor EParseAPIError.Create(ACode: Integer; const AError: string);
begin
FCode := ACode;
FError := AError;
inherited CreateFmt(sFormatParseError, [Self.Error, Self.Code]);
end;
{ TParseApi.TConnectionInfo }
constructor TParseApi.TConnectionInfo.Create(const AApiVersion, AApplicationID: string);
begin
ApiVersion := AApiVersion;
ApplicationID := AApplicationID;
end;
{ TParseApi.TObjectID }
constructor TParseApi.TObjectID.Create(const ABackendClassName: string;
AObjectID: string);
begin
FBackendClassName := ABackendClassName;
FObjectID := AObjectID;
end;
{ TParseApi.TFileID }
constructor TParseApi.TFile.Create(const AName: string);
begin
FName := AName;
end;
{ TParseApi.TUserID }
constructor TParseApi.TUser.Create(const AUserName: string);
begin
FUserName := AUserName;
end;
{ TParseApi.TLogin }
constructor TParseApi.TLogin.Create(const ASessionToken: string;
const AUser: TUser);
begin
FSessionToken := ASessionToken;
FUser := AUser;
end;
{ TParseApi.TUpdatedAt}
constructor TParseApi.TUpdatedAt.Create(const ABackendClassName, AObjectID: string; AUpdatedAt: TDateTime);
begin
FUpdatedAt := AUpdatedAt;
FBackendClassName := ABackendClassName;
FObjectID := AObjectID;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
September '1999
Problem 24 O(N2) The Only Method!
}
program
EdgeDisjointCycles;
const
MaxN = 100;
var
N, E, N1, E1 : Integer;
G, V : array [1 .. MaxN, 1 .. MaxN] of Integer;
D, Pat : array [1 .. MaxN] of Integer;
M, M1 : array [1 .. MaxN] of Boolean;
I, J, K, P, Q, R, S : Integer;
Fl : Boolean;
F, FO : Text;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Assign(FO, 'output.txt');
Rewrite(FO);
Readln(F, N); N1 := N;
for I := 2 to N do
begin
for J := 1 to I - 1 do
begin
Read(F, G[I, J]); G[J, I] := G[I, J];
if G[I, J] = 1 then
begin
Inc(D[I]); Inc(D[J]); Inc(E); Inc(E1);
if E >= N + 4 then
begin Close(F); Exit; end;
end;
end;
Readln(F);
end;
Writeln(#7'Number of Edges Must Be Greater than or Equal to V + 4.');
Halt;
end;
procedure WriteOutput;
begin
Close(FO);
end;
procedure WritePath (A, B : Integer);
begin
G[A, B] := 0; G[B, A] := 0;
if V[A, B] = 0 then
Write(FO, A, ' ')
else
begin
WritePath(A, V[A, B]);
WritePath(V[A, B], B);
end;
end;
function Dfs (V, P : Integer) : Integer;
var
I, J : Integer;
begin
Dfs := 0;
M[V] := True;
for I := 1 to N do
if M1[I] and (G[V, I] = 1) then
if not M[I] then
begin
J := Dfs(I, V);
Dfs := J;
if J < 0 then Exit else
if J > 0 then
begin
WritePath(I, V);
if V = J then
Dfs := -J;
Exit;
end;
end
else
if I <> P then
begin
WritePath(I, V);
Dfs := I;
Exit;
end;
end;
procedure FindAnotherCycle;
var
I : Integer;
begin
FillChar(M, SizeOf(M), 0);
for I := 1 to N do
if not M[I] then
if Dfs(I, 0) <> 0 then
Exit;
end;
procedure FindCycle3 (A, B, C : Integer);
begin
WritePath(A, B);
WritePath(B, C);
WritePath(C, A);
Writeln(FO);
FindAnotherCycle;
WriteOutput;
Halt;
end;
procedure FindCycle4 (A, B, C, D : Integer);
begin
WritePath(A, B);
WritePath(B, C);
WritePath(C, D);
WritePath(D, A);
Writeln(FO);
FindAnotherCycle;
WriteOutput;
Halt;
end;
procedure FindMinCycle;
var
I, J, K, L : Integer;
begin
for I := 1 to N do if M1[I] then
for J := 1 to N do if M1[J] and (G[I, J] = 1) then
for K := 1 to N do if M1[K] and (K <> I) and (G[J, K] = 1) then
begin
if G[K, I] = 1 then
begin
FindCycle3(I, J, K)
end
else
for L := 1 to N do if M1[L] and (L <> J) and (G[K, L] = 1) and (G[L, I] = 1) then
FindCycle4(I, J, K, L);
end;
end;
procedure ReduceGraph;
begin
repeat
Fl := True;
for I := 1 to N do
if D[I] = 1 then
begin
Fl := False;
Break;
end;
if not Fl then
begin
for J := 1 to N do
if G[I, J] = 1 then
Break;
G[I, J] := 0; G[J, I] := 0; Dec(D[I]); Dec(D[J]); Dec(E1); Dec(N1);
end;
until Fl;
for I := 1 to N do
if D[I] > 2 then
M1[I] := True;
for I := 1 to N do
if D[I] = 2 then
begin
for J := 1 to N - 1 do if G[I, J] = 1 then Break; P := J;
for J := P + 1 to N do if G[I, J] = 1 then Break; Q := J;
if G[P, Q] = 1 then
begin
FindCycle3(I, P, Q);
FindAnotherCycle;
WriteOutput;
Halt;
end;
G[P, I] := 0; G[I, P] := 0; G[Q, I] := 0; G[I, Q] := 0;
G[P, Q] := 1; G[Q, P] := 1; V[P, Q] := I; V[Q, P] := I;
end;
end;
begin
ReadInput;
ReduceGraph;
FindMinCycle;
WriteOutput;
end.
|
unit SpectrumSettings;
interface
uses
// Windows, Classes, Controls, Graphics, Forms, Dialogs, ActnList, StdCtrls,
// Grids,
// TB2Toolbar,
// OriUtils,
// PropSaver, OriCombos, OriUtilsTChart
Classes,
OriIniFile,
SpectrumTypes;
type
//------------------------------------------------------------------------------
// тут содержатся только часто используемые настройки
// редко используемые при необходимости читаются из файла
// (например, фильтры для открытия папки)
TPreferences = class
public
LoadDefChartSetting: Boolean; // Загружать настройки графиков по умолчанию
AnimatedChartZoom: Boolean; // Анимированное масштабирование графиков
AxisDblClickLimits: Boolean; // двойной клик по оси - пределы, иначе свойства
ScrollAxesByMouse: Boolean; // Прокручивать оси мышью
NoConfirmDelete: Boolean; // Не подтверждать удаление графиков
SelectJustAdded: Boolean; // выделять добавленные графики cелектором
// PlotReaders settings
ValueSeparators: String;
DecSeparator: TDecimalSeparator;
SkipFirstLines: Integer;
OneColumnFirst: TValue;
OneColumnInc: TValue;
TablePreviewLines: Integer;
RSReadLowValues: Boolean;
RSFileVersion: Byte;
// горячие клавиши команд выделения, инициализируются в главном окне
// используются некоторыми окнами, обладающими аналогичными командами,
// чтобы сочетания клавиш в каждом конкретном окне были одинаковыми
//scSelectAll: TShortCut;
//scSelectNone: TShortCut;
//scSelectInv: TShortCut;
//scEditCopy: TShortCut;
// для экспорта или копирования
ExportParams: record
// ChartCopyFormat: TCopyImageFormat;
DecSeparator: TDecimalSeparator;
LineDelimiter: TLineDelimiter;
ValueDelimiter: TValueDelimiter;
LineDelimSpec: String;
ValueDelimSpec: String;
end;
// States
ProjectOpenCurDir: String;
ProjectOpenFilter: Integer;
GraphsOpenCurDir: String;
GraphsOpenFilter: Integer;
GraphsOpenFilterTable: Integer;
TitlePresets: TStringList; // Templates of axes and chart titles
constructor Create;
destructor Destroy; override;
procedure Load(Ini: TOriIniFile);
procedure Save(Ini: TOriIniFile);
procedure LoadStates(Ini: TOriIniFile);
procedure SaveStates(Ini: TOriIniFile);
end;
{%region Program States}
type
TSaveStateProcedure = procedure (Ini: TOriIniFile);
TSaveStateProcedures = array of TSaveStateProcedure;
procedure RegisterSaveStateProc(AProc: TSaveStateProcedure);
procedure SaveAllStates(Ini: TOriIniFile);
{%endregion}
var
Preferences: TPreferences;
{
//------------------------------------------------------------------------------
// шаблоны заголовков
type
TTemplateKind = (tkNone, tkAxesNames, tkGraphTitles);
//------------------------------------------------------------------------------
// клавиатурные сокращения
type
TKeyboardShortCut = record
Action: TAction;
ShortCut: TShortCut;
end;
TKeyboardShortCutArray = array of TKeyboardShortCut;
procedure AssignShortCutsToMenus(var ShortCuts: TKeyboardShortCutArray; MenuBar: TTBCustomToolbar);
procedure ResetFactoryDefaultShortCuts(var ShortCuts: TKeyboardShortCutArray; ActionList: TActionList);
procedure WriteShortCuts(ASaver: TPropSaver; const ASection: String; var ShortCuts: TKeyboardShortCutArray);
procedure ReadShortCuts(ASaver: TPropSaver; const ASection: String; var ShortCuts: TKeyboardShortCutArray; ActionList: TActionList);
var
KeyboardShortCuts: TKeyboardShortCutArray;
KeyboardShortCutsReserved: TKeyboardShortCutArray;
//------------------------------------------------------------------------------
// окна ввода/вывода текста
type
TMultiLineOpt = (mloNone, mloNl, mloNlCr);
TTextFileViewOption = (
tfvFileNameInCaption, // отображать имя файла в заголовке окна
tfvFileNamePanel, // отображать имя файла в специальном поле
tfvCaptionContainsFileName // параметр Caption содержит имя файла
);
TTextFileViewOptions = set of TTextFileViewOption;
function EnterText(const ACaption: String; var Value: String;
Options: TMultiLineOpt = mloNlCr; Templates: TTemplateKind = tkNone): Boolean; overload;
function EnterText(const ACaption: String; Value: TStrings; Templates: TTemplateKind = tkNone): Boolean; overload;
//function EnterString(const ACaption: String; var Value: String): Boolean;
//function EnterStringDK(const ACaptionKey: String; var Value: String): Boolean;
procedure TextView(const ACaption, AFileName: String; AOptions: TTextFileViewOptions = []); overload;
procedure TextView(const ACaption: String; AStream: TStream; AOptions: TTextFileViewOptions = []); overload;
//------------------------------------------------------------------------------
// Файловые диалоги
function OpenGraphsDialog(AFileNames: TStrings; var AFilterIndex: Integer): Boolean;
function OpenTableDialog(var AFileName: String): Boolean;
function OpenFolderDialog: Boolean;
//------------------------------------------------------------------------------
procedure SaveFilePacked(const Data, FileName: String);
// Возвращает список путей для поиска скриптов.
function GetScriptPaths: TStringArray;
}
//------------------------------------------------------------------------------
const
CSomeStates = 'STT_SOMESTATES';
//APP_MAIL = 'spectrum@orion-project.org';
//APP_HOME = 'www.spectrum.orion-project.org';
//PATH_SCRIPTS = 'scripts';
//ACTN_HIDDEN_CTGR = 'Reserved';
//ACTN_DEBUG_CMD = 999;
implementation
uses
// SysUtils, Menus, StrUtils, Clipbrd, ComCtrls, ZLib, WinInet,
OriUtils;
// WinTextView, WinEnterText, PlotReaders;
{%region TPreferences}
{конструктор заполняет некоторые поля настроек по умолчанию.
Стуация: непосредственно перед Preferences.Load возникает
исключение и Load не выполняется (такое было, когда DKLang
не нашел константу) в итоге Preferences заполнен нулями,
в не дефолтовыми значениями. Чтобы такого не было при инициализации
модуля заполняем поля по дефолту (те поля, которые по дефолту
нулевые или не страшно, что они будут нулями, сюда можно не включать )}
constructor TPreferences.Create;
begin
TitlePresets := TStringList.Create;
OneColumnFirst := 0;
OneColumnInc := 1;
end;
destructor TPreferences.Destroy;
begin
TitlePresets.Free;
end;
procedure TPreferences.Load(Ini: TOriIniFile);
begin
with Ini do
begin
Section := CMainSection;
LoadDefChartSetting := ReadBool('LoadDefChartSetting', False);
AxisDblClickLimits := ReadBool('AxisDblClickShowLimits', False);
ScrollAxesByMouse := ReadBool('ScrollAxesByMouse', False);
AnimatedChartZoom := ReadBool('AnimatedChartZoom', True);
NoConfirmDelete := ReadBool('NoConfirmDelete', False);
SelectJustAdded := ReadBool('SelectJustAdded', True);
Section := 'EXPORT_PARAMS';
//ExportParams.ChartCopyFormat := TCopyImageFormat(ReadInteger('ChartCopyFormat', Ord(cifWmf)));
ExportParams.DecSeparator := TDecimalSeparator(ReadInteger('DecimalSeparator', Ord(dsSystem)));
ExportParams.LineDelimiter := TLineDelimiter(ReadInteger('LineDelimiter', Ord(ldWindows)));
ExportParams.ValueDelimiter := TValueDelimiter(ReadInteger('ValueDelimiter', Ord(vdTab)));
ExportParams.LineDelimSpec := ReadString('LineDelimiterSpec', '');
ExportParams.ValueDelimSpec := ReadString('ValueDelimiterSpec', '');
// PlotReader settings
Section := 'DATA_READERS';
ValueSeparators := ReadString('ValueSeparators', '');
DecSeparator := TDecimalSeparator(ReadInteger('DecimalSeparator', Ord(dsAuto)));
SkipFirstLines := ReadInteger('SkipFirstLines', 0);
OneColumnFirst := ReadFloat('OneColumnFirst', 1);
OneColumnInc := ReadFloat('OneColumnInc', 1);
TablePreviewLines := ReadInteger('PreviewLineCountTable', 25);
RSReadLowValues := ReadBool('RSReadLowValues', False);
RSFileVersion := ReadInteger('RSFileVersion', 0);
end;
end;
procedure TPreferences.Save(Ini: TOriIniFile);
begin
with Ini do
begin
Section := CMainSection;
WriteBool('LoadDefChartSetting', LoadDefChartSetting);
WriteBool('AxisDblClickShowLimits', AxisDblClickLimits);
WriteBool('ScrollAxesByMouse', ScrollAxesByMouse);
WriteBool('AnimatedChartZoom', AnimatedChartZoom);
WriteBool('NoConfirmDelete', NoConfirmDelete);
WriteBool('SelectJustAdded', SelectJustAdded);
// export
Section := 'EXPORT_PARAMS';
//WriteInteger('ChartCopyFormat', Ord(ExportParams.ChartCopyFormat));
WriteInteger('DecimalSeparator', Ord(ExportParams.DecSeparator));
WriteInteger('LineDelimiter', Ord(ExportParams.LineDelimiter));
WriteInteger('ValueDelimiter', Ord(ExportParams.ValueDelimiter));
WriteString('LineDelimiterSpec', ExportParams.LineDelimSpec);
WriteString('ValueDelimiterSpec', ExportParams.ValueDelimSpec);
// PlotReader settings
Section := 'DATA_READERS';
WriteString('ValueSeparators', ValueSeparators);
WriteInteger('DecimalSeparator', Ord(DecSeparator));
WriteInteger('SkipFirstLines', SkipFirstLines);
WriteFloat('OneColumnFirst', OneColumnFirst);
WriteFloat('OneColumnInc', OneColumnInc);
WriteInteger('PreviewLineCountTable', TablePreviewLines);
end;
end;
procedure TPreferences.LoadStates(Ini: TOriIniFile);
begin
with Ini do
begin
Section := CSomeStates;
ProjectOpenCurDir := EnsurePath(ReadString('ProjectOpenCurDir', ''));
ProjectOpenFilter := ReadInteger('ProjectOpenFilter', 1);
GraphsOpenCurDir := EnsurePath(ReadString('GraphsOpenCurDir', ''));
GraphsOpenFilter := ReadInteger('GraphsOpenFilter', 1);
GraphsOpenFilterTable := ReadInteger('GraphsOpenFilterTable', 1);
//ReadTextSection('TITLE_PRESETS', TitlePresets);
end;
end;
procedure TPreferences.SaveStates(Ini: TOriIniFile);
begin
with Ini do
begin
Section := CSomeStates;
WriteString('ProjectOpenCurDir', ProjectOpenCurDir);
WriteInteger('ProjectOpenFilter', ProjectOpenFilter);
WriteString('GraphsOpenCurDir', GraphsOpenCurDir);
WriteInteger('GraphsOpenFilter', GraphsOpenFilter);
WriteInteger('GraphsOpenFilterTable', GraphsOpenFilterTable);
//WriteTextSection('TITLE_PRESETS', TitlePresets);
end;
end;
{%endregion TPreferences}
{%region Program States}
var
SaveStateProcs: TSaveStateProcedures;
procedure RegisterSaveStateProc(AProc: TSaveStateProcedure);
var L: Integer;
begin
for L := 0 to Length(SaveStateProcs)-1 do
if Addr(AProc) = Addr(SaveStateProcs[L]) then Exit;
L := Length(SaveStateProcs);
SetLength(SaveStateProcs, L+1);
SaveStateProcs[L] := AProc;
end;
procedure SaveAllStates(Ini: TOriIniFile);
var I: Integer;
begin
for I := 0 to Length(SaveStateProcs)-1 do SaveStateProcs[I](Ini);
end;
{%endregion}
//{$region 'Shortcuts'}
//procedure WriteShortCuts(ASaver: TPropSaver; const ASection: String;
// var ShortCuts: TKeyboardShortCutArray);
//var
// I: Integer;
// Strs: TStringList;
//begin
// ASaver.DeleteSection(ASection);
// ASaver.Section := ASection;
// Strs := TStringList.Create;
// try
// // нельзя пользоваться WriteInteger(Action, ShortCut) т.к.
// // одна команда может иметь несколько сочетаний клавиш,
// for I := 0 to Length(ShortCuts)-1 do
// with ShortCuts[I] do
// if Assigned(Action) and (ShortCut <> 0) then
// Strs.Add(Action.Name + '=' + IntToStr(ShortCut));
// ASaver.SetStrings(Strs);
// finally
// Strs.Free;
// end;
//end;
//
//procedure ReadShortCuts(ASaver: TPropSaver; const ASection: String;
// var ShortCuts: TKeyboardShortCutArray; ActionList: TActionList);
//var
// Strs: TStringList;
// I, J, L, P: Integer;
// Str, Name, Value: String;
//begin
// ShortCuts := nil;
// Strs := TStringList.Create;
// try
// ASaver.GetSectionValues(ASection, Strs);
// for I := 0 to Strs.Count-1 do
// begin
// // нельзя пользоваться ShortCut := ReadInteger(Action) т.к.
// // одна команда может иметь несколько сочетаний клавиш,
// Str := Strs[I];
// P := CharPos(Str, '=');
// if P < 2 then Continue;
// Name := Copy(Str, 1, P-1);
// Value := Copy(Str, P+1, Length(Str)-P);
// for J := 0 to ActionList.ActionCount-1 do
// if ActionList.Actions[J].Name = Name then
// begin
// L := Length(ShortCuts);
// SetLength(ShortCuts, L+1);
// ShortCuts[L].Action := TAction(ActionList.Actions[J]);
// ShortCuts[L].ShortCut := TShortCut(StrToIntDef(Value, 0));
// Break;
// end;
// end;
// finally
// Strs.Free;
// end;
//end;
//
//procedure ResetFactoryDefaultShortCuts(var ShortCuts: TKeyboardShortCutArray; ActionList: TActionList);
//var
// Strs: TStringList;
// Stream: TResourceStream;
// Saver: TPropSaver;
//begin
// Saver := nil;
// Stream := TResourceStream.Create(HInstance, 'DefaultShortCuts', RT_RCDATA);
// Strs := TStringList.Create;
// try
// Strs.LoadFromStream(Stream);
// Saver := TPropSaver.CreateInMemory;
// Saver.SetStrings(Strs);
// ReadShortCuts(Saver, 'SHORTCUTS', ShortCuts, ActionList);
// finally
// Strs.Free;
// Saver.Free;
// Stream.Free;
// end;
//end;
//
//procedure AssignShortCutsToMenus(var ShortCuts: TKeyboardShortCutArray; MenuBar: TTBCustomToolbar);
//var
// L: Integer;
//
// procedure GetUserShortCut(Item: TTBCustomItem);
// var
// I: Integer;
// begin
// for I := 0 to L do
// if Item.Action = ShortCuts[I].Action then
// begin
// Item.ShortCut := ShortCuts[I].ShortCut;
// Exit;
// end;
// Item.ShortCut := 0;
// end;
//
// procedure AssignShortCutsToBranch(Item: TTBCustomItem);
// var
// I: Integer;
// S: String;
// begin
// for I := 0 to Item.Count-1 do
// begin
// S := Item.Items[I].Caption;
// if Item.Items[I].Count <> 0
// then AssignShortCutsToBranch(Item.Items[I])
// else GetUserShortCut(Item.Items[I]);
// end;
// end;
//
//var
// I: Integer;
//begin
// L := Length(ShortCuts)-1;
// with MenuBar do
// for I := 0 to Items.Count-1 do
// if Items[I].Count <> 0 then
// AssignShortCutsToBranch(Items[I]);
//end;
//{$endregion}
//{$region 'EnterText / EnterString / TextView'}
//function EnterText(const ACaption: String; var Value: String;
// Options: TMultiLineOpt = mloNlCr; Templates: TTemplateKind = tkNone): Boolean;
//begin
// with TwndEnterText.Create(Application) do
// try
// if ACaption <> '' then
// Caption := ACaption;
// LoadTemplates(Templates);
// Memo1.Lines.Text := Value;
// Result := ShowModal = mrOk;
// if Result then
// case Options of
// mloNone: Value := AnsiReplaceStr(Memo1.Lines.Text, #$D#$A, ' ');
// mloNl: Value := AnsiReplaceStr(Memo1.Lines.Text, #$A, '');
// mloNlCr: Value := Memo1.Lines.Text;
// end;
// finally
// Free;
// end;
//end;
//
//function EnterText(const ACaption: String; Value: TStrings; Templates: TTemplateKind = tkNone): Boolean;
//begin
// with TwndEnterText.Create(Application) do
// try
// if ACaption <> '' then
// Caption := ACaption;
// LoadTemplates(Templates);
// Memo1.Lines.Assign(Value);
// Result := ShowModal = mrOk;
// if Result then
// Value.Assign(Memo1.Lines);
// finally
// Free;
// end;
//end;
//
//procedure TextView(const ACaption, AFileName: String; AOptions: TTextFileViewOptions = []);
//begin
// TwndTextView.Create(ACaption, AFileName, AOptions).Show;
//end;
//
//// Если выставлена опция tfvCaptionContainsFileName, то заголовок может включать
//// имя файла после переноса строки, например: ACaption := "Заголовок окна"#13"Имя файла"
//// Для этой функции опции tfvFileNameInCaption, tfvFileNamePanel работают только
//// вместе с tfvCaptionContainsFileName
//procedure TextView(const ACaption: String; AStream: TStream; AOptions: TTextFileViewOptions = []);
//begin
// TwndTextView.Create(ACaption, AStream, AOptions).Show;
//end;
//{$endregion}
//procedure SaveFilePacked(const Data, FileName: String);
//var
//// OutBuf: Pointer;
//// OutSize: Integer;
// Buf: Pointer;
// OutFile: TFileStream;
// Zip: TCompressionStream;
//begin
// OutFile := TFileStream.Create(FileName, fmCreate, fmShareExclusive);
// Zip := TCompressionStream.Create(clMax, outFile);
// try
// Buf := PAnsiChar(Data);
// Zip.Write(Buf, Length(Data));
//// CompressBuf(PAnsiChar(Data), Length(Data), OutBuf, OutSize);
//// OutFile.Write(OutBuf, OutSize);
// finally
// Zip.Free;
// OutFile.Free;
//// if Assigned(OutBuf) then FreeMem(OutBuf);
// end
//end;
//
//// для процедуры OriUtils.ShowHelp
//function GetHelpFileName: String;
//var
// HelpFile: String;
//begin
// case LangManager.LanguageID of
// 1049: HelpFile := 'Spectrum.ru.chm';
// else HelpFile := 'Spectrum.en.chm';
// end;
// Result := ExtractFilePath(Application.ExeName) + HelpFile;
//end;
//
//function GetScriptPaths: TStringArray;
//begin
// SetLength(Result, 1);
// Result[0] := JoinPaths(ExtractFilePath(ParamStr(0)), PATH_SCRIPTS);
//end;
initialization
Preferences := TPreferences.Create;
//OriUtils.GetHelpFileName := GetHelpFileName;
Randomize;
finalization
Preferences.Free;
end.
|
unit MathRewrite;
interface
uses
Rewrite,
MyMath;
var
VMathMatcher: TMatcher;
implementation //===============================================================
initialization //===============================================================
VMathMatcher := TMatcher.Create;
with VMathMatcher, VMathFactory do
begin
AddRule(TRule.Create(
'Left unit add',
MakeBinExp(
MakeConst(0),
MakeBinOp(boPlus),
MakeMeta('A')),
MakeMeta('A')
));
AddRule(TRule.Create(
'Right unit add',
MakeBinExp(
MakeMeta('A'),
MakeBinOp(boPlus),
MakeConst(0)),
MakeMeta('A')
));
AddRule(TRule.Create(
'Comm add',
MakeBinExp(
MakeMeta('A'),
MakeBinOp(boPlus),
Makemeta('B')),
MakeBinExp(
MakeMeta('B'),
MakeBinOp(boPlus),
MakeMeta('A'))
));
AddRule(TRule.Create(
'Left zero mul',
MakeBinExp(
MakeConst(0),
MakeBinOp(boTimes),
MakeMeta('A')),
MakeConst(0)
));
AddRule(TRule.Create(
'Left zero mul',
MakeBinExp(
MakeMeta('A'),
MakeBinOp(boTimes),
MakeConst(0)),
MakeConst(0)
));
AddRule(TRule.Create(
'Left unit mul',
MakeBinExp(
MakeConst(1),
MakeBinOp(boTimes),
MakeMeta('A')),
MakeMeta('A')
));
AddRule(TRule.Create(
'Right unit mul',
MakeBinExp(
MakeMeta('A'),
MakeBinOp(boTimes),
MakeConst(1)),
MakeMeta('A')
));
AddRule(TRule.Create(
'Comm mul',
MakeBinExp(
MakeMeta('A'),
MakeBinOp(boTimes),
Makemeta('B')),
MakeBinExp(
MakeMeta('B'),
MakeBinOp(boTimes),
MakeMeta('A'))
));
AddRule(TRule.Create(
'Left distr mul add',
MakeBinExp(
MakeMeta('A'),
MakeBinOp(boTimes),
MakeBinExp(
MakeMeta('B'),
MakeBinOp(boPlus),
Makemeta('C'))),
MakeBinExp(
MakeBinExp(
MakeMeta('A'),
MakeBinOp(boTimes),
MakeMeta('B')),
MakeBinOp(boPlus),
MakeBinExp(
MakeMeta('A'),
MakeBinOp(boTimes),
MakeMeta('C')))
));
end;
end.
|
unit variant_array_1;
interface
implementation
var
Arr: array of Variant;
procedure Test;
begin
SetLength(Arr, 3);
Arr[0] := 1;
Arr[1] := copy('variant');
Arr[2] := 5.7;
end;
initialization
Test();
finalization
Assert(Arr[0] = 1);
Assert(Arr[1] = 'variant');
Assert(Arr[2] = 5.7);
end. |
unit UFuncoes;
interface
// Classes necessárias
uses
Windows, SysUtils, Forms, Dialogs;
// Declaração das funções
procedure Log(Mensagem: String);
implementation
// Implementação das funções
// LOG - Baseado de http://imasters.uol.com.br/artigo/2718/delphi/manipulando_arquivos_textos/
procedure Log(Mensagem: String);
const
NomArquivo: String = 'LOG.TXT';
var
Path: String;
Arquivo: TextFile;
begin
Path := ExtractFilePath(Application.ExeName);
AssignFile(Arquivo, Path + NomArquivo);
if not FileExists(Path + NomArquivo) then
ReWrite(Arquivo)
else Append(Arquivo);
Write(Arquivo, DateTimeToStr(Now));
Write(Arquivo, ' - ');
WriteLn(Arquivo, Mensagem);
CloseFile(Arquivo);
end;
end.
|
unit u_xpl_collection;
{$ifdef fpc}
{ $ mode objfpc}{$H+}
{$mode delphi}
{$endif}
interface
uses
Classes, SysUtils;
type
{ TxPLCollectionItem }
TxPLCollectionItem = class(TCollectionItem)
protected
fDisplayName : string;
fCreateTS : TDateTime;
fModifyTS : TDateTime;
fValue : string;
fComment : string;
procedure Set_Value(const AValue: string); virtual;
public
constructor Create(aOwner: TCollection); override;
procedure Assign(Source: TPersistent); reintroduce; dynamic;
function GetDisplayName: string; override;
procedure SetDisplayName(const Value: string); override;
published
property DisplayName : string read GetDisplayName write SetDisplayName;
property CreateTS : TDateTime read fCreateTS write fCreateTS;
property ModifyTS : TDateTime read fModifyTS write fModifyTS;
property Value : string read fValue write Set_Value;
property Comment : string read fComment write fComment;
end;
TxPLCollection<T {$ifndef fpc}: TxPLCollectionItem{$endif}> = class(TCollection)
private
fOwner : TPersistent;
procedure Set_Items(Index : integer; const aValue : T);
function Get_Items(Index : integer) : T;
protected
function GetOwner : TPersistent; override;
public
constructor Create(aOwner : TPersistent);
function Add(const aName : string) : T;
function FindItemName(const aName : string) : T;
function GetItemID(const aName : string) : integer;
property Items[Index : integer] : T read Get_Items write Set_Items; default;
end;
TxPLCustomCollection = TxPLCollection<TxPLCollectionItem>;
implementation // =============================================================
// ============================================================================
function IsValidName(const Ident: string): boolean;
var i, len: integer;
begin
result := false;
len := length(Ident);
if len <> 0 then begin
result := Ident[1] in ['a'..'z','A'..'Z'];
i := 1;
while (result) and (i < len) do begin
inc(i);
result := result and (Ident[i] in ['a'..'z', '0'..'9','A'..'Z','.','-']);
end ;
end ;
end ;
// TxPLCollectionItem =========================================================
function TxPLCollectionItem.GetDisplayName: string;
begin
Result:=fDisplayName;
end;
procedure TxPLCollectionItem.SetDisplayName(const Value: string);
var ci : TCollectionItem;
begin
if (fDisplayName<>Value) then begin // Ensure that the name doesn't already
if not IsValidName(Value) then Raise Exception.CreateFmt('Invalid name : ''%s''',[Value])
else begin
for ci in Collection do if ci.DisplayName = Value then
Raise Exception.CreateFmt('Duplicate name : ''%s''',[Value]); // exists in the parent collection - can't
fDisplayName:=Value; // use directly TxPLCollection.GetItemID as this is a generic class
Changed(false);
end;
end;
end;
procedure TxPLCollectionItem.Set_Value(const AValue: string);
begin
if aValue = fValue then exit;
fModifyTS := now;
fValue:=AValue;
Changed(false);
end;
constructor TxPLCollectionItem.Create(aOwner: TCollection);
begin
inherited Create(aOwner);
fCreateTS := now;
fModifyTS := fCreateTS;
end;
procedure TxPLCollectionItem.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TxPLCollectionItem then begin
fDisplayName := TxPLCollectionItem(Source).DisplayName;
fModifyTS := TxPLCollectionItem(Source).ModifyTS;
end;
end;
// TxPLCollection =============================================================
constructor TxPLCollection<T>.Create(aOwner : TPersistent);
begin
inherited Create(T);
fOwner := aOwner;
end;
function TxPLCollection<T>.GetOwner : TPersistent;
begin
Result := fOwner;
end;
function TxPLCollection<T>.Get_Items(index : integer) : T;
begin
Result := T(inherited Items[index]);
end;
Procedure TxPLCollection<T>.Set_Items(Index : integer; const aValue : T);
begin
Items[index] := aValue;
end;
Function TxPLCollection<T>.Add(const aName : string) : T;
var i : integer;
s : string;
begin
i := GetItemId(aName);
if i = -1 then begin
Result := T(inherited Add);
i := Count;
repeat
s := 'Item' + IntToStr(i);
inc(i);
until GetItemId(s)=-1;
if aName<>'' then Result.DisplayName := aName
else Result.DisplayName := s;
end
else
Result := Get_Items(i);
end;
Function TxPLCollection<T>.FindItemName(const aName : string) : T;
var i : longint;
begin
for i:=0 to Count-1 do begin
Result := T(items[i]);
if AnsiCompareText(Result.DisplayName,aName)=0 then exit;
end;
Result := {$ifdef fpc}nil{$else}Default(T){$endif};
end;
function TxPLCollection<T>.GetItemId(const aName: string): integer;
begin
for Result := 0 to Count - 1 do
if T(items[Result]).DisplayName = aName then exit;
Result := -1;
end;
initialization
Classes.RegisterClass(TxPLCollectionItem);
end.
|
unit Support.Sandforce;
interface
uses
SysUtils, Math,
Support, Device.SMART.List;
type
TSandforceNSTSupport = class abstract(TNSTSupport)
private
InterpretingSMARTValueList: TSMARTValueList;
function GetTotalWrite: TTotalWrite;
protected
function GetSemiSupport: TSupportStatus;
public
function GetSMARTInterpreted(SMARTValueList: TSMARTValueList):
TSMARTInterpreted; override;
end;
implementation
{ TSandforceNSTSupport }
function TSandforceNSTSupport.GetSemiSupport: TSupportStatus;
begin
result.Supported := Supported;
result.FirmwareUpdate := false;
result.TotalWriteType := TTotalWriteType.WriteSupportedAsValue;
end;
function TSandforceNSTSupport.GetTotalWrite: TTotalWrite;
const
GiBtoMiB: Double = 1024;
IDOfHostWrite = 241;
var
RAWValue: UInt64;
begin
result.InValue.TrueHostWriteFalseNANDWrite := true;
RAWValue :=
InterpretingSMARTValueList.GetRAWByID(IDOfHostWrite);
result.InValue.ValueInMiB := Floor(RAWValue * GiBtoMiB);
end;
function TSandforceNSTSupport.GetSMARTInterpreted(
SMARTValueList: TSMARTValueList): TSMARTInterpreted;
const
IDOfEraseError = 172;
IDOfReplacedSector = 5;
IDOfUsedHour = 9;
ReplacedSectorThreshold = 50;
EraseErrorThreshold = 10;
begin
InterpretingSMARTValueList := SMARTValueList;
result.TotalWrite := GetTotalWrite;
//Sandforce uses only 4 bytes for UsedHour RAW
result.UsedHour :=
InterpretingSMARTValueList.GetRAWByID(IDOfUsedHour) and $FFFFFFFF;
result.ReadEraseError.TrueReadErrorFalseEraseError := false;
result.ReadEraseError.Value :=
InterpretingSMARTValueList.GetRAWByID(IDOfEraseError);
result.SMARTAlert.ReadEraseError :=
result.ReadEraseError.Value >= EraseErrorThreshold;
result.ReplacedSectors :=
InterpretingSMARTValueList.GetRAWByID(IDOfReplacedSector);
result.SMARTAlert.ReplacedSector :=
result.ReplacedSectors >= ReplacedSectorThreshold;
end;
end.
|
unit FGLAbout;
interface
uses
Winapi.Windows, Winapi.Messages, Winapi.ShellAPI,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Imaging.jpeg,
//
FGLDialog;
type
TGLAbout = class(TGLDialog)
LabelCopyright: TLabel;
PanelYears: TPanel;
imgOpenGL: TImage;
imgSourceForge: TImage;
imgGLScene: TImage;
LabelVersion: TLabel;
StaticTextVersion: TStaticText;
LabelGeoblock: TLabel;
Label1: TLabel;
Label3: TLabel;
FreeAndOpenSource: TLabel;
Label2: TLabel;
procedure imgSourceForgeDblClick(Sender: TObject);
procedure imgGLSceneDblClick(Sender: TObject);
procedure imgOpenGLDblClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BuiltWithDelphiDblClick(Sender: TObject);
public
{ Public declarations }
private
{ Private declarations }
function GetFileInfo(const FileName: TFileName): TVSFixedFileInfo;
function ReadVersionInfo(FileName: TFileName): TFileName;
end;
var
GLAbout: TGLAbout;
implementation
{$R *.dfm}
procedure GotoURL(Handle: integer; const URL: string);
var
S: array[0..255] of char;
begin
ShellExecute(Handle, 'Open', StrPCopy(S, URL), nil, nil, SW_SHOW);
end;
procedure TGLAbout.BuiltWithDelphiDblClick(Sender: TObject);
begin
inherited;
GotoURL(Handle, 'http://www.embarcadero.com');
end;
procedure TGLAbout.FormCreate(Sender: TObject);
begin
inherited;
StaticTextVersion.Caption := ReadVersionInfo(Application.ExeName);
end;
function TGLAbout.GetFileInfo(const FileName: TFileName): TVSFixedFileInfo;
var
Handle, VersionSize: DWord;
SubBlock: string;
Temp: Pointer;
Data: Pointer;
begin
SubBlock := '\';
VersionSize := GetFileVersionInfoSize(PChar(FileName), Handle);
if VersionSize > 0 then
begin
GetMem(Temp, VersionSize);
try
if GetFileVersionInfo(PChar(FileName), Handle, VersionSize, Temp) then
if VerQueryValue(Temp, PChar(SubBlock), Data, VersionSize) then
Result := PVSFixedFileInfo(Data)^;
finally
FreeMem(Temp);
end;
end;
end;
procedure TGLAbout.imgGLSceneDblClick(Sender: TObject);
begin
GotoURL(Handle, 'http://www.glscene.org/');
end;
procedure TGLAbout.imgOpenGLDblClick(Sender: TObject);
begin
GotoURL(Handle, 'http://www.opengl.org/');
end;
procedure TGLAbout.imgSourceForgeDblClick(Sender: TObject);
begin
GotoURL(Handle, 'http://www.sourceforge.net/projects/glscene/');
end;
function TGLAbout.ReadVersionInfo(FileName: TFileName): TFileName;
type
TGetWords = record
case boolean of
True: (C: cardinal);
False: (Lo, Hi: word);
end;
var
VerSize, Wnd: cardinal;
Buf, Value: Pointer;
MS, LS: TGetWords;
begin
VerSize := GetFileVersionInfoSize(PChar(FileName), Wnd);
if VerSize > 0 then
begin
GetMem(Buf, VerSize);
GetFileVersionInfo(PChar(Application.ExeName), 0, VerSize, Buf);
VerQueryValue(Buf, '\', Value, VerSize);
with TVSFixedFileInfo(Value^) do
begin
MS.C := dwFileVersionMS;
LS.C := dwFileVersionLS;
Result := Format('%d.%d.%d Build %d', [MS.Hi, MS.Lo, LS.Hi, LS.Lo]);
end;
FreeMem(Buf);
end
else
Result := 'Unknown'; // or LoadResString(@sUnknown);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.