text stringlengths 14 6.51M |
|---|
unit tgraphiclabel;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ExtCtrls, Graphics, Controls;
type
{ TTGraphicLabel }
TTGraphicLabel = class(TImage)
private
{ Private declarations }
FAlignment: TAlignment;
DBOverPict: TPicture;
DBDownPict: TPicture;
DBUpPict: TPicture;
DBDisPict: TPicture;
DBEnabled: Boolean;
Down: Boolean;
Up: Boolean;
Ftext:String;
ffont:tfont;
fdfont:tfont;
procedure SetAlignment(Value: TAlignment);
procedure Setdfont(Value: tfont);
procedure SetDownPict(Value: TPicture);
procedure Setfont(Value: tfont);
procedure SetUpPict(Value: TPicture);
procedure SetDisPict(Value: TPicture);
Procedure SetText(value:string);
function GetAlignment: TAlignment;
public
{ Public declarations }
procedure SetEnabled(Value: Boolean); override;
constructor Create(AOwner: TComponent); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
destructor Destroy; override;
procedure Paint; override;
published
{ Published declarations }
property Alignment: TAlignment read GetAlignment write SetAlignment default taLeftJustify;
property UpPict: TPicture read DBUpPict write SetUpPict;
property DownPict: TPicture read DBDownPict write SetDownPict;
property DisPict: TPicture read DBDisPict write SetDisPict;
property Enabled: Boolean read DBEnabled write SetEnabled default true;
Property Text:string read ftext write settext;
Property Font:tfont read ffont write Setfont;
Property DisabledFont:tfont read ffont write Setdfont;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Touch', [TTGraphicLabel]);
end;
procedure TTGraphicLabel.SetEnabled(Value: Boolean);
begin
if Value = True then
Picture:=DBUpPict
else Picture:=DBDisPict;
DBEnabled:=Value;
end;
constructor TTGraphicLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DBOverPict:= TPicture.Create;
DBDownPict:= TPicture.Create;
DBUpPict := TPicture.Create;
DBDisPict := TPicture.Create;
Picture:= DBUpPict;
ffont:=tfont.create;
fdfont:=tfont.create;
Down:= False;
SetEnabled(true);
end;
procedure TTGraphicLabel.SetUpPict(Value: TPicture);
begin
DBUpPict.Assign(Value);
end;
procedure TTGraphicLabel.SetDownPict(Value: TPicture);
begin
DBDownPict.Assign(Value);
end;
procedure TTGraphicLabel.Setfont(Value: tfont);
begin
ffont.assign(value);
invalidate;
end;
procedure TTGraphicLabel.SetAlignment(Value: TAlignment);
begin
if FAlignment <> Value then
begin
FAlignment := Value;
Invalidate;
end;
end;
procedure TTGraphicLabel.Setdfont(Value: tfont);
begin
fdfont.assign(value);
invalidate;
end;
procedure TTGraphicLabel.SetDisPict(Value: TPicture);
begin
DBDisPict.Assign(Value);
end;
procedure TTGraphicLabel.SetText(value: string);
begin
ftext:=value;
invalidate;
end;
function TTGraphicLabel.GetAlignment: TAlignment;
begin
Result := FAlignment;
end;
procedure TTGraphicLabel.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
if DBEnabled=True then
if Up then
if (X<0)or(X>Width)or(Y<0)or(Y>Height) then
begin
SetCaptureControl(Self);
Picture:=DBUpPict;
end;
end;
procedure TTGraphicLabel.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if (Button=mbLeft)and(DBEnabled=True) then
begin
Picture:=DownPict;
Down:=True;
end;
inherited MouseDown(Button, Shift, X, Y);
end;
procedure TTGraphicLabel.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if (Button=mbLeft)and(Enabled=True) then
begin
Picture:=UpPict;
SetCaptureControl(nil);
end;
inherited MouseUp(Button, Shift, X, Y);
Down:=False;
end;
destructor TTGraphicLabel.Destroy;
begin
DBDownPict.Free;
DBUpPict.Free;
DBDisPict.Free;
ffont.free;
fdfont.destroy;
inherited Destroy;
end;
procedure TTGraphicLabel.Paint;
var
w,h,y,x:integer;
begin
inherited Paint;
canvas.GetTextSize(ftext,w,h);
x:=(Width div 2) - (w div 2);
y:=(height div 2) - (h div 2);
if DBEnabled then canvas.font.Assign(ffont) else canvas.font.assign(fdfont);
if FAlignment=taLeftJustify then canvas.TextOut(0,y,ftext);
if FAlignment=taRightJustify then canvas.TextOut(canvas.width-w,y,ftext);
if FAlignment=taCenter then canvas.TextOut(x,y,ftext);
end;
end.
|
unit UAccessClient;
interface
uses Classes, UAccessConstant, DBClient, DB, MidasLib, CRTL, IniFiles,
UAccessPattern,
PluginAPI;
type
TVersionString = string[30];
{ TSAVAccessFileProc = function(const rNew, rOld: TClientFile;
const aDir, aSID: string; const aPath: string = ''): Boolean;}
{ TSAVAccessFileAction = class
private
procedure SetFileAction(const Value: Integer);
procedure SetFileExt(const Value: string);
procedure SetFileType(const Value: string);
protected
FFileType: string;
FFileAction: Integer;
FFileExt: string;
FFileProc: TSAVAccessFileProc;
public
property FileType: string read FFileType write SetFileType;
property FileAction: Integer read FFileAction write SetFileAction;
property FileExt: string read FFileExt write SetFileExt;
property FileProc: TSAVAccessFileProc read FFileProc write FFileProc;
constructor Create(const AFileType, AFileExt: string; const AFileAct:
Integer; AFunc: TSAVAccessFileProc);
end; }
TSAVAccessClient = class(TObject)
private
FUser: string;
FDomain: string;
FSID: string;
FIniFile: TIniFile;
FWorkstation: string;
FDataSet: TClientDataSet;
FConfigDir: string;
FJournalsDir: string;
FUsersDir: string;
FGroupsDir: string;
FADGroupsDir: string;
FTemplate: TPathTemplate;
FDomainsDir: string;
FActions: TList;
procedure SetDataSet(const Value: TClientDataSet);
procedure SetIniFile(const Value: TIniFile);
procedure SetActions(const Value: TList);
procedure SetADGroupsDir(const Value: string);
public
property ConfigDir: string read FConfigDir;
property Domain: string read FDomain;
property SID: string read FSID;
property Actions: TList read FActions write SetActions;
property User: string read FUser;
property DataSet: TClientDataSet read FDataSet write SetDataSet;
property JournalsDir: string read FJournalsDir;
property UsersDir: string read FUsersDir;
property GroupsDir: string read FGroupsDir;
property ADGroupsDir: string read FADGroupsDir write SetADGroupsDir;
property DomainsDir: string read FDomainsDir;
property Workstation: string read FWorkstation;
property IniFile: TIniFile read FIniFile write SetIniFile;
procedure LoadFromFile(const aFileName: string);
procedure SortListVal(Source: TStrings);
function Record2ClientFile(table1: TDataSet; const aSID, aSource: string;
const DefaultAction: Integer = -1):
TClientFile;
procedure ClientFile2Record(table1: TDataSet; const ClntFile1: TClientFile);
function CheckDomainVersion: Boolean; //True = Equal
function CheckUserVersion: Boolean;
function GetDirBySource(const aSource: Char): string;
function CheckGroupVersion(const aSID: string): Boolean;
function FileProcessing(const aOld, aNew: TClientFile; const DeleteOnly:
Boolean = False): Boolean;
function AddedProc(const aOld, aNew: TClientFile; const aDir, aSID, aPath:
string):
Boolean;
function UpdateContainerFile(const aDir, aSID, aVersion: string;
aTableFileName: string = csTableFiles; aReverse: boolean = False):
boolean;
procedure DeleteContainerFile(const aDir, aSID: string;
aTableFileName: string = csTableFiles; aReverse: boolean = False);
function Update: Boolean;
function ReverseUpdate: Boolean;
function FindPlugin(const AFileType: Char; AExt: string; AID: Integer; const
AGUID:
TGUID; out Obj): Boolean;
constructor Create(const aConfDirName: string = ''); overload;
destructor Destroy; override;
end;
implementation
uses SAVLib, SysUtils, SPGetSid, MsAD, VKDBFDataSet, SAVLib_DBF, Variants,
KoaUtils, Windows, PluginManager;
{ TSAVAccessContainer }
function TSAVAccessClient.AddedProc(const aOld,
aNew: TClientFile; const aDir, aSID, aPath: string): Boolean;
var
{i: Integer;
b: Byte;}
Plugin: ISAVAccessFileAct;
begin
// b := 0;
Result := False;
// i := 0;
if FindPlugin(Char(aNew.TypeF), aNew.Ext, aNew.Action, ISAVAccessFileAct,
Plugin) then
begin
Result := Plugin.ProcessedFile(aNew, aOld, aDir, aSID, aPath) > 0
end;
end;
function TSAVAccessClient.CheckDomainVersion: Boolean;
var
ini: TIniFile;
s: string;
begin
ini := TIniFile.Create(DomainsDir + Domain + '\' + csContainerCfg);
s := ini.ReadString('main', 'version', '');
FreeAndNil(ini);
Result := (s <> '') and (s = FIniFile.ReadString('version', 'domain', ''));
end;
function TSAVAccessClient.CheckGroupVersion(const aSID: string): Boolean;
var
ini: TIniFile;
s: string;
begin
ini := TIniFile.Create(GroupsDir + aSID + '\' + csContainerCfg);
s := ini.ReadString('main', 'version', '');
FreeAndNil(ini);
Result := (s <> '') and (s = FIniFile.ReadString('version', 'gr' + aSID, ''));
end;
function TSAVAccessClient.CheckUserVersion: Boolean;
var
ini: TIniFile;
s: string;
begin
ini := TIniFile.Create(UsersDir + SID + '\' + csContainerCfg);
s := ini.ReadString('main', 'version', '');
FreeAndNil(ini);
Result := (s <> '') and (s = FIniFile.ReadString('version', 'user', ''));
end;
procedure TSAVAccessClient.ClientFile2Record(table1: TDataSet;
const ClntFile1: TClientFile);
begin
end;
constructor TSAVAccessClient.Create(const aConfDirName: string);
var
datFile: string;
procedure CreatDS;
begin
with FDataSet.FieldDefs.AddFieldDef as TFieldDef do
begin
DisplayName := csFieldSrvrFile;
DataType := ftString;
Size := 50;
end;
with FDataSet.FieldDefs.AddFieldDef as TFieldDef do
begin
DisplayName := csFieldVersion;
DataType := ftString;
Size := 30;
end;
with FDataSet.FieldDefs.AddFieldDef as TFieldDef do
begin
DisplayName := csFieldClntFile;
DataType := ftString;
Size := 2047;
end;
with FDataSet.FieldDefs.AddFieldDef as TFieldDef do
begin
DisplayName := csFieldExt;
DataType := ftString;
Size := 10;
end;
with FDataSet.FieldDefs.AddFieldDef as TFieldDef do
begin
DisplayName := csFieldType;
DataType := ftString;
Size := 1;
end;
with FDataSet.FieldDefs.AddFieldDef as TFieldDef do
begin
DisplayName := csFieldAction;
DataType := ftInteger;
end;
with FDataSet.FieldDefs.AddFieldDef as TFieldDef do
begin
DisplayName := csFieldMD5;
DataType := ftString;
Size := 32;
end;
with FDataSet.FieldDefs.AddFieldDef as TFieldDef do
begin
DisplayName := csFieldSID;
DataType := ftString;
Size := 50;
end;
with FDataSet.FieldDefs.AddFieldDef as TFieldDef do
begin
DisplayName := csFieldSource;
DataType := ftString;
Size := 1;
end;
FDataSet.CreateDataSet;
end;
begin
{if aConfDirName = '' then
s := 'SAVAccessClient'
else
s := aConfDirName;
FConfigDir := GetSpecialFolderLocation(CSIDL_APPDATA,
FOLDERID_RoamingAppData);
if FConfigDir = '' then
FConfigDir := GetCurrentDir;
FConfigDir :=
IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(FConfigDir) + s);
}
FConfigDir := IncludeTrailingPathDelimiter(aConfDirName);
if not (DirectoryExists(ConfigDir)) then
ForceDirectories(ConfigDir);
FSID := SPGetSid.GetCurrentUserSid;
FWorkstation := MsAD.GetCurrentComputerName;
FUser := MsAD.GetCurrentUserName;
FDomain := MsAD.CurrentDomainName;
FDataSet := TClientDataSet.Create(nil);
datFile := FConfigDir + csClientData;
if FileExists(datFile) then
try
FDataSet.LoadFromFile(datFile);
except
FDataSet.Close;
Windows.DeleteFile(PChar(datFile));
CreatDS;
end
else
CreatDS;
FDataSet.Open;
FDataSet.LogChanges := False;
FDataSet.FileName := datFile;
FIniFile := TIniFile.Create(FConfigDir + csContainerCfg);
FActions := TList.Create;
end;
function TSAVAccessClient.FindPlugin(const AFileType: Char; AExt: string; AID:
Integer; const AGUID:
TGUID; out Obj): Boolean;
var
X: Integer;
begin
Result := False;
for X := 0 to Plugins.Count - 1 do
if (Plugins[X].ActionID = AID) and (Plugins[X].Extension = AExt) and
(Plugins[x].FileType = AFileType) then
begin
Result := Supports(Plugins[X], AGUID, Obj);
if Result then
Break;
end;
end;
destructor TSAVAccessClient.Destroy;
var
I: Integer;
begin
if Assigned(FDataSet) then
begin
if FDataSet.Active then
FDataSet.ApplyUpdates(-1);
FDataSet.Close;
FreeAndNil(FDataset);
end;
if Assigned(FTemplate) then
FreeAndNil(FTemplate);
if Assigned(FIniFile) then
begin
FIniFile.WriteDateTime('option', 'LastChange', Now);
FreeAndNil(Finifile);
end;
if Assigned(FActions) then
begin
for i := 0 to FACtions.Count - 1 do
TObject(FACtions[i]).Free;
FreeAndNil(FACtions);
end;
inherited;
end;
function TSAVAccessClient.FileProcessing(const aOld,
aNew: TClientFile; const DeleteOnly: Boolean = False): Boolean;
var
hFile: Cardinal;
sf, ContDir: string;
begin
Result := True;
sf := FTemplate.GetPath(aNew.ClntFile);
ContDir := IncludeTrailingPathDelimiter(GetDirBySource(char(aNew.Source))) +
aNew.SID
+ '\f\';
case aNew.TypeF of
'F': //Файловая операция
begin
if (aNew.Ext = '') or (AddedProc(aOld, aNew, ContDir, aNew.SID, sf) =
False) then
case aNew.Action of
0: // Удаление
begin
if FileExists(sf) then
Result := Windows.DeleteFile(PChar(sf));
end;
1: // Копирование
begin
try
fCopyFile(ContDir + aNew.SrvrFile, sf);
except
Result := False;
end;
end;
2: // Создать файл пустой
begin
hFile := CreateFile(PChar(sf), GENERIC_WRITE,
FILE_SHARE_WRITE or FILE_SHARE_READ, nil,
OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, 0);
Result := hFile <> INVALID_HANDLE_VALUE;
CloseHandle(hFile);
end;
end
end;
'D': //Операция с каталогом
begin
if DeleteOnly = False then
case aNew.Action of
0: // Удаление
begin
if DirectoryExists(sf) then
Result := fRemoveDir(sf)
end;
{ 1: // Копирование -
begin
fCopyDir();
end;}
2: // Создать пустую директорию
begin
Result := ForceDirectories(ExcludeTrailingPathDelimiter(sf));
end;
else
begin
;
end;
end
end;
else
begin
AddedProc(aOld, aNew, ContDir, aNew.SID, sf);
end;
end;
end;
function TSAVAccessClient.GetDirBySource(const aSource: Char): string;
begin
Result := '';
case aSource of
'D': Result := FDomainsDir;
'G': Result := FGroupsDir;
'U': Result := FUsersDir;
'A': Result := FADGroupsDir;
end;
end;
procedure TSAVAccessClient.LoadFromFile(const aFileName: string);
var
list: TStringList;
begin
if FileExists(aFileName) then
begin
list := TStringList.Create;
list.LoadFromFile(aFileName);
FUsersDir := list.Values['users'];
FJournalsDir := list.Values['journals'];
FGroupsDir := list.Values['groups'];
FADGroupsDir := list.Values['adgroups'];
FDomainsDir := list.Values['domains'];
FreeAndNil(list);
if Assigned(FTemplate) then
FreeAndNil(FTemplate);
FTemplate := TPathTemplate.Create(IncludeTrailingPathDelimiter(FJournalsDir)
+ csTemplateMain, False);
end
else
raise Exception.Create('Нет доступа к файлу ' + aFileName);
end;
function TSAVAccessClient.Record2ClientFile(table1: TDataSet; const aSID,
aSource: string; const DefaultAction: Integer = -1): TClientFile;
begin
Result.SrvrFile := table1.fieldbyname(csFieldSrvrFile).AsString;
Result.Ext := table1.fieldbyname(csFieldExt).AsString;
Result.Version := table1.fieldbyname(csFieldVersion).AsString;
Result.ClntFile := table1.fieldbyname(csFieldClntFile).AsString;
Result.TypeF := WideChar(table1.fieldbyname(csFieldType).AsString[1]);
if DefaultAction > -1 then
Result.Action := DefaultAction
else
Result.Action := table1.FieldByName(csFieldAction).AsInteger;
Result.MD5 := table1.fieldbyname(csFieldMD5).AsString;
Result.Source := WideChar(aSource[1]);
Result.SID := aSID;
end;
procedure TSAVAccessClient.SetActions(const Value: TList);
begin
FActions := Value;
end;
procedure TSAVAccessClient.SetDataSet(const Value: TClientDataSet);
begin
FDataSet := Value;
end;
procedure TSAVAccessClient.SetIniFile(const Value: TIniFile);
begin
FIniFile := Value;
end;
//основная ф-ция обновления
procedure TSAVAccessClient.SortListVal(Source: TStrings);
var
ListWork, ListRes: TStringList;
j: Integer;
function GetMinListNumb(List1: TStrings): Integer;
var
vMin: integer;
i, x: Integer;
begin
if List1.Count > 1 then
begin
Result := 0;
vMin := StrToIntDef(List1.ValueFromIndex[Result], Result);
for i := 1 to pred(List1.Count) do
begin
x := StrToIntDef(List1.ValueFromIndex[i], 0);
if vMin > x then
begin
Result := i;
vMin := x;
end;
end;
end
else
Result := 0;
end;
begin
if Source.Count > 1 then
begin
ListWork := TStringList.Create;
ListRes := TStringList.Create;
ListWork.Assign(Source);
while ListWork.Count > 0 do
begin
j := GetMinListNumb(ListWork);
ListRes.Add(ListWork[j]);
ListWork.Delete(j);
end;
FreeAndNil(ListWork);
Source.Clear;
Source.Assign(ListRes);
FreeAndNil(ListRes);
end
end;
function TSAVAccessClient.Update: Boolean;
var
ini: TIniFile;
list1, oldGroups, ADGroups, ADOldGroups: TStringList;
sUserIni, WorkLst, ADWorkLst, sDNS: string;
i, j, n: Integer;
b,
Changed // были изменения, обновляем все полностью
: Boolean;
begin
{ TODO : Надо реализовать обработку реверсивных таблиц }
Result := True;
WorkLst := FConfigDir + csWorkGroupsLst;
ADWorkLst := FConfigDir + csWorkADGroupsLst;
sUserIni := IncludeTrailingPathDelimiter(FUsersDir) + FSID + '\' +
csContainerCfg;
sDNS := GetDNSDomainName(Domain);
list1 := TStringList.Create;
ADGroups := TStringList.Create;
Changed := False;
b := FileExists(sUserIni);
if b then
begin
ini := TIniFile.Create(sUserIni);
ini.ReadSectionValues(csIniGroups, list1);
FreeAndNil(ini);
end;
GetAllUserGroups(User, GetDomainController(Domain), ADGroups);
for i := 0 to pred(ADGroups.Count) do
ADGroups[i] := GetSID(ADGroups[i], sdns) + '=' + ADGroups[i];
if FileExists(ADWorkLst) then
begin
ADOldGroups := TStringList.Create;
ADOldGroups.LoadFromFile(ADWorkLst);
for i := Pred(ADOldGroups.Count) downto 0 do
begin
j := 0;
while j < ADGroups.Count do
if ADGroups.Names[j] = ADOldGroups.Names[i] then
begin
ADOldGroups.Delete(i);
j := ADGroups.Count;
end
else
Inc(j);
end;
if ADOldGroups.Count > 0 then
// есть группы из которых пользователь был удален
begin
for i := 0 to pred(ADOldGroups.Count) do
DeleteContainerFile(FADGroupsDir, ADOldGroups.Names[i]);
Changed := True;
end;
FreeAndNil(ADOldGroups);
end;
SortListVal(list1);
if FileExists(WorkLst) then
begin
oldGroups := TStringList.Create;
oldGroups.LoadFromFile(WorkLst);
for i := Pred(oldGroups.Count) downto 0 do
begin
j := 0;
while j < list1.Count do
if list1.Names[j] = oldGroups.Names[i] then
begin
oldGroups.Delete(i);
j := list1.Count;
end
else
Inc(j);
end;
if oldGroups.Count > 0 then // есть группы из которых пользователь был удален
begin
for i := 0 to pred(oldGroups.Count) do
DeleteContainerFile(FGroupsDir, oldGroups.Names[i]);
Changed := True;
end;
FreeAndNil(oldGroups);
end;
try
ADGroups.SaveToFile(ADWorkLst);
list1.SaveToFile(WorkLst);
except
Result := False;
end;
if Changed then
begin
UpdateContainerFile(FDomainsDir, Domain, '');
n := pred(ADGroups.Count);
for i := 0 to n do
UpdateContainerFile(FADGroupsDir, ADGroups.Names[i], '');
n := pred(list1.Count);
for i := 0 to n do
UpdateContainerFile(FGroupsDir, list1.Names[i], '');
end
else
begin
Changed := UpdateContainerFile(FDomainsDir, Domain, FIniFile.ReadString('D',
Domain,
''));
n := pred(ADGroups.Count);
for i := 0 to n do
begin
if Changed = False then
Changed := UpdateContainerFile(FADGroupsDir, ADGroups.Names[i],
FIniFile.ReadString('A', ADGroups.Names[i], ''))
else
UpdateContainerFile(FADGroupsDir, ADGroups.Names[i], '');
end;
n := pred(list1.Count);
for i := 0 to n do
begin
if Changed = False then
Changed := UpdateContainerFile(FGroupsDir, list1.Names[i],
FIniFile.ReadString('G',
list1.Names[i], ''))
else
UpdateContainerFile(FGroupsDir, list1.Names[i], '');
end
end;
FreeAndNil(ADGroups);
FreeAndNil(list1);
if b then
begin
if Changed then
UpdateContainerFile(FUsersDir, SID, '')
else
UpdateContainerFile(FUsersDir, SID, FIniFile.ReadString('U', SID, ''));
end;
FDataSet.ApplyUpdates(-1);
FDataSet.Close;
FDataSet.Open;
end;
//Обновление файлов определенного контейнера хранилища переданного в aDir+aSID
function TSAVAccessClient.UpdateContainerFile(const aDir, aSID, aVersion:
string; aTableFileName: string = csTableFiles; aReverse: boolean = False):
boolean;
var
ini: TIniFile;
c: Char;
s, vers: string;
sPath, sLocIni: string;
table1: TVKDBFNTX;
procedure FileInfoMove(aFrom, aTo: TDataSet; const aFull: Boolean);
begin
if aFull then
begin
aTo.fieldbyname(csFieldSrvrFile).AsString :=
aFrom.fieldbyname(csFieldSrvrFile).AsString;
aTo.fieldbyname(csFieldExt).AsString :=
aFrom.fieldbyname(csFieldExt).AsString;
aTo.fieldbyname(csFieldType).AsString :=
aFrom.fieldbyname(csFieldType).AsString;
aTo.FieldByName(csFieldSource).AsString := c;
aTo.FieldByName(csFieldSID).AsString := aSID;
end;
aTo.fieldbyname(csFieldClntFile).AsString :=
aFrom.fieldbyname(csFieldClntFile).AsString;
aTo.fieldbyname(csFieldVersion).AsString :=
aFrom.fieldbyname(csFieldVersion).AsString;
aTo.fieldbyname(csFieldMD5).AsString :=
aFrom.fieldbyname(csFieldMD5).AsString;
aTo.fieldbyname(csFieldAction).AsInteger :=
aFrom.fieldbyname(csFieldAction).AsInteger;
end;
begin
Result := False;
s := '';
sPath := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(aDir) +
aSID);
sLocIni := sPath + csContainerCfg;
if FileExists(sLocIni) then
begin
ini := TIniFile.Create(sLocIni);
c := Ini.ReadString('main', 'type', ' ')[1];
vers := Ini.ReadString('main', 'version', '');
FreeAndNil(ini);
if (FileExists(sPath + aTableFileName)) and (vers <> aVersion) then
begin
table1 := TVKDBFNTX.Create(nil);
InitOpenDBF(table1, sPath + aTableFileName, 64);
table1.Open;
while not (table1.Eof) do
begin
if FDataSet.Locate(csFieldSrvrFile + ';' + csFieldExt + ';' + csFieldType
+ ';' + csFieldSource + ';' + csFieldSID,
varArrayOf([table1.fieldbyname(csFieldSrvrFile).AsString,
table1.fieldbyname(csFieldExt).AsString,
table1.fieldbyname(csFieldType).AsString, c, aSID]), []) then
begin
if (FDataSet.fieldbyname(csFieldVersion).AsString <>
table1.fieldbyname(csFieldVersion).AsString) or (aVersion = '') then
begin
if FileProcessing(Record2ClientFile(FDataSet, aSID, c),
Record2ClientFile(table1, aSID, c)) then
begin
FDataSet.Edit;
FileInfoMove(table1, FDataSet, False);
FDataSet.Post;
Result := True;
end;
end
end
else
begin
if FileProcessing(Record2ClientFile(table1, aSID, c),
Record2ClientFile(table1, aSID, c)) then
begin
FDataSet.Insert;
FileInfoMove(table1, FDataSet, True);
FDataSet.Post;
Result := True;
end;
end;
table1.Next;
end;
table1.Close;
FreeAndNil(table1);
FIniFile.WriteString(c, aSID, vers);
end;
FDataSet.ApplyUpdates(-1);
// FDataSet.Close;
// FDataSet.Open;
end;
end;
procedure TSAVAccessClient.DeleteContainerFile(const aDir, aSID: string;
aTableFileName: string = csTableFiles; aReverse: boolean = False);
var
ini: TIniFile;
c: Char;
s: string;
sPath, sPathIni: string;
table1: TVKDBFNTX;
begin
sPath := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(aDir) +
aSID);
sPathINI := sPath + csContainerCfg;
if FileExists(sPathIni) then
begin
s := '';
ini := TIniFile.Create(sPathIni);
c := Ini.ReadString('main', 'type', ' ')[1];
FreeAndNil(ini);
if FileExists(sPath + aTableFileName) {and (vers <> aVersion)} then
begin
table1 := TVKDBFNTX.Create(nil);
InitOpenDBF(table1, sPath + aTableFileName, 64);
table1.Open;
while not (table1.Eof) do
begin
if FileProcessing(Record2ClientFile(table1, aSID, c, 0),
Record2ClientFile(table1, aSID, c, 0), True) then
begin
while FDataSet.Locate(csFieldClntFile + ';' + csFieldType,
varArrayOf([table1.fieldbyname(csFieldClntFile).AsString,
table1.fieldbyname(csFieldType).AsString]), []) do
FDataSet.Delete;
end;
table1.Next;
end;
table1.Close;
FreeAndNil(table1);
FDataSet.ApplyUpdates(-1);
end;
if c <> ' ' then
FIniFile.DeleteKey(c, aSID);
end;
end;
procedure TSAVAccessClient.SetADGroupsDir(const Value: string);
begin
FADGroupsDir := Value;
end;
function TSAVAccessClient.ReverseUpdate: Boolean;
var
ini: TIniFile;
list1, oldGroups, ADGroups, ADOldGroups: TStringList;
sUserIni, WorkLst, ADWorkLst, sDNS: string;
i, j, n: Integer;
b,
Changed // были изменения, обновляем все полностью
: Boolean;
begin
{ TODO : Надо реализовать обработку реверсивных таблиц }
Result := True;
WorkLst := FConfigDir + csWorkGroupsLst;
ADWorkLst := FConfigDir + csWorkADGroupsLst;
sUserIni := IncludeTrailingPathDelimiter(FUsersDir) + FSID + '\' +
csContainerCfg;
sDNS := GetDNSDomainName(Domain);
list1 := TStringList.Create;
ADGroups := TStringList.Create;
Changed := False;
b := FileExists(sUserIni);
if b then
begin
ini := TIniFile.Create(sUserIni);
ini.ReadSectionValues(csIniGroups, list1);
FreeAndNil(ini);
end;
GetAllUserGroups(User, GetDomainController(Domain), ADGroups);
for i := 0 to pred(ADGroups.Count) do
ADGroups[i] := GetSID(ADGroups[i], sdns) + '=' + ADGroups[i];
{if FileExists(ADWorkLst) then
begin
ADOldGroups := TStringList.Create;
ADOldGroups.LoadFromFile(ADWorkLst);
for i := Pred(ADOldGroups.Count) downto 0 do
begin
j := 0;
while j < ADGroups.Count do
if ADGroups.Names[j] = ADOldGroups.Names[i] then
begin
ADOldGroups.Delete(i);
j := ADGroups.Count;
end
else
Inc(j);
end;
if ADOldGroups.Count > 0 then
// есть группы из которых пользователь был удален
begin
for i := 0 to pred(ADOldGroups.Count) do
DeleteContainerFile(FADGroupsDir, ADOldGroups.Names[i]);
Changed := True;
end;
FreeAndNil(ADOldGroups);
end;}
SortListVal(list1);
{if FileExists(WorkLst) then
begin
oldGroups := TStringList.Create;
oldGroups.LoadFromFile(WorkLst);
for i := Pred(oldGroups.Count) downto 0 do
begin
j := 0;
while j < list1.Count do
if list1.Names[j] = oldGroups.Names[i] then
begin
oldGroups.Delete(i);
j := list1.Count;
end
else
Inc(j);
end;
if oldGroups.Count > 0 then // есть группы из которых пользователь был удален
begin
for i := 0 to pred(oldGroups.Count) do
DeleteContainerFile(FGroupsDir, oldGroups.Names[i]);
Changed := True;
end;
FreeAndNil(oldGroups);
end;
try
ADGroups.SaveToFile(ADWorkLst);
list1.SaveToFile(WorkLst);
except
Result := False;
end;}
if Changed then
begin
UpdateContainerFile(FDomainsDir, Domain, '');
n := pred(ADGroups.Count);
for i := 0 to n do
UpdateContainerFile(FADGroupsDir, ADGroups.Names[i], '');
n := pred(list1.Count);
for i := 0 to n do
UpdateContainerFile(FGroupsDir, list1.Names[i], '');
end
else
begin
Changed := UpdateContainerFile(FDomainsDir, Domain, FIniFile.ReadString('D',
Domain,
''));
n := pred(ADGroups.Count);
for i := 0 to n do
begin
if Changed = False then
Changed := UpdateContainerFile(FADGroupsDir, ADGroups.Names[i],
FIniFile.ReadString('A', ADGroups.Names[i], ''))
else
UpdateContainerFile(FADGroupsDir, ADGroups.Names[i], '');
end;
n := pred(list1.Count);
for i := 0 to n do
begin
if Changed = False then
Changed := UpdateContainerFile(FGroupsDir, list1.Names[i],
FIniFile.ReadString('G',
list1.Names[i], ''))
else
UpdateContainerFile(FGroupsDir, list1.Names[i], '');
end
end;
FreeAndNil(ADGroups);
FreeAndNil(list1);
if b then
begin
if Changed then
UpdateContainerFile(FUsersDir, SID, '')
else
UpdateContainerFile(FUsersDir, SID, FIniFile.ReadString('U', SID, ''));
end;
FDataSet.ApplyUpdates(-1);
FDataSet.Close;
FDataSet.Open;
end;
end.
|
unit kwIF;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwIF.pas"
// Начат: 26.04.2011 20:08
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::TkwIF
//
// Зарезервированное слов IF. Переход с проверкой условия.
// *Пример:*
// {code}
// : SIGN
// DUP >0 IF 'ПОЛОЖИТЕЛЬНОЕ ЧИСЛО' . DROP
// ELSE =0
// IF 'НОЛЬ' .
// ELSE 'ОТРИЦАТЕЛЬНОЕ ЧИСЛО' .
// ENDIF
// ENDIF
// ;
//
// : SIGN1
// ?DUP =0 IF
// 'НОЛЬ' .
// ELSE
// >0 IF
// 'ПОЛОЖИТЕЛЬНОЕ ЧИСЛО' . ELSE
// 'ОТРИЦАТЕЛЬНОЕ ЧИСЛО' . ENDIF
// ENDIF
// ;
//
// -1 SIGN
// 0 SIGN
// 1 SIGN
//
// -1 SIGN1
// 0 SIGN1
// 1 SIGN1
// {code}
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
tfwScriptingInterfaces,
kwCompiledWord,
kwDualCompiledWordContainer,
l3Interfaces,
l3ParserInterfaces
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\tfwDualWord.imp.pas}
TkwIF = class(_tfwDualWord_)
{* Зарезервированное слов IF. Переход с проверкой условия.
*Пример:*
[code]
: SIGN
DUP >0 IF 'ПОЛОЖИТЕЛЬНОЕ ЧИСЛО' . DROP
ELSE =0
IF 'НОЛЬ' .
ELSE 'ОТРИЦАТЕЛЬНОЕ ЧИСЛО' .
ENDIF
ENDIF
;
: SIGN1
?DUP =0 IF
'НОЛЬ' .
ELSE
>0 IF
'ПОЛОЖИТЕЛЬНОЕ ЧИСЛО' . ELSE
'ОТРИЦАТЕЛЬНОЕ ЧИСЛО' . ENDIF
ENDIF
;
-1 SIGN
0 SIGN
1 SIGN
-1 SIGN1
0 SIGN1
1 SIGN1
[code] }
protected
// realized methods
function EndBracket(const aContext: TtfwContext): AnsiString; override;
function MedianBracket: AnsiString; override;
function MakeDualCompiled(const aContext: TtfwContext;
aCompiled: TkwCompiledWord;
aCompiled2: TkwCompiledWord;
aMedianNum: Integer): TkwDualCompiledWordContainer; override;
function MedianBracket2: AnsiString; override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwIF
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
kwCompiledIF,
SysUtils,
l3Parser,
kwInteger,
kwString,
TypInfo,
l3Base,
kwIntegerFactory,
kwStringFactory,
l3String,
l3Chars,
tfwAutoregisteredDiction,
tfwScriptEngine
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwIF;
{$Include ..\ScriptEngine\tfwDualWord.imp.pas}
// start class TkwIF
function TkwIF.EndBracket(const aContext: TtfwContext): AnsiString;
//#UC START# *4DB6C99F026E_4DB6EDEF00BF_var*
//#UC END# *4DB6C99F026E_4DB6EDEF00BF_var*
begin
//#UC START# *4DB6C99F026E_4DB6EDEF00BF_impl*
Result := 'ENDIF';
//#UC END# *4DB6C99F026E_4DB6EDEF00BF_impl*
end;//TkwIF.EndBracket
function TkwIF.MedianBracket: AnsiString;
//#UC START# *4DBAC41301F2_4DB6EDEF00BF_var*
//#UC END# *4DBAC41301F2_4DB6EDEF00BF_var*
begin
//#UC START# *4DBAC41301F2_4DB6EDEF00BF_impl*
Result := 'ELSE';
//#UC END# *4DBAC41301F2_4DB6EDEF00BF_impl*
end;//TkwIF.MedianBracket
function TkwIF.MakeDualCompiled(const aContext: TtfwContext;
aCompiled: TkwCompiledWord;
aCompiled2: TkwCompiledWord;
aMedianNum: Integer): TkwDualCompiledWordContainer;
//#UC START# *4DBAC44D02CC_4DB6EDEF00BF_var*
//#UC END# *4DBAC44D02CC_4DB6EDEF00BF_var*
begin
//#UC START# *4DBAC44D02CC_4DB6EDEF00BF_impl*
Result := TkwCompiledIF.Create(aCompiled, aCompiled2);
//#UC END# *4DBAC44D02CC_4DB6EDEF00BF_impl*
end;//TkwIF.MakeDualCompiled
function TkwIF.MedianBracket2: AnsiString;
//#UC START# *4DBADF3E02CC_4DB6EDEF00BF_var*
//#UC END# *4DBADF3E02CC_4DB6EDEF00BF_var*
begin
//#UC START# *4DBADF3E02CC_4DB6EDEF00BF_impl*
Result := '';
//#UC END# *4DBADF3E02CC_4DB6EDEF00BF_impl*
end;//TkwIF.MedianBracket2
class function TkwIF.GetWordNameForRegister: AnsiString;
//#UC START# *4DB0614603C8_4DB6EDEF00BF_var*
//#UC END# *4DB0614603C8_4DB6EDEF00BF_var*
begin
//#UC START# *4DB0614603C8_4DB6EDEF00BF_impl*
Result := 'IF';
//#UC END# *4DB0614603C8_4DB6EDEF00BF_impl*
end;//TkwIF.GetWordNameForRegister
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\tfwDualWord.imp.pas}
{$IfEnd} //not NoScripts
end. |
{ Date Created: 6/6/00 9:10:06 AM }
unit InfoSYSTEMSETTINGSTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoSYSTEMSETTINGSRecord = record
PIndex: Integer;
PFloppyDiskDrive: String[1];
PPCAnywhereVersion: String[5];
PEndHostModeFirst: Boolean;
PUTLRetensionDays: Integer;
PFFSHost: Boolean;
PClient: String[10];
PSite: String[10];
PRemitText1: String[35];
PRemitText2: String[35];
PRemitText3: String[35];
PRemitText4: String[35];
PRemitAbbreviation: String[6];
PNextClaimNumber: String[6];
End;
TInfoSYSTEMSETTINGSBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoSYSTEMSETTINGSRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoSYSTEMSETTINGS = (InfoSYSTEMSETTINGSPrimaryKey);
TInfoSYSTEMSETTINGSTable = class( TDBISAMTableAU )
private
FDFIndex: TAutoIncField;
FDFFloppyDiskDrive: TStringField;
FDFPCAnywhereVersion: TStringField;
FDFEndHostModeFirst: TBooleanField;
FDFUTLRetensionDays: TIntegerField;
FDFFFSHost: TBooleanField;
FDFClient: TStringField;
FDFSite: TStringField;
FDFRemitText1: TStringField;
FDFRemitText2: TStringField;
FDFRemitText3: TStringField;
FDFRemitText4: TStringField;
FDFRemitAbbreviation: TStringField;
FDFNextClaimNumber: TStringField;
procedure SetPFloppyDiskDrive(const Value: String);
function GetPFloppyDiskDrive:String;
procedure SetPPCAnywhereVersion(const Value: String);
function GetPPCAnywhereVersion:String;
procedure SetPEndHostModeFirst(const Value: Boolean);
function GetPEndHostModeFirst:Boolean;
procedure SetPUTLRetensionDays(const Value: Integer);
function GetPUTLRetensionDays:Integer;
procedure SetPFFSHost(const Value: Boolean);
function GetPFFSHost:Boolean;
procedure SetPClient(const Value: String);
function GetPClient:String;
procedure SetPSite(const Value: String);
function GetPSite:String;
procedure SetPRemitText1(const Value: String);
function GetPRemitText1:String;
procedure SetPRemitText2(const Value: String);
function GetPRemitText2:String;
procedure SetPRemitText3(const Value: String);
function GetPRemitText3:String;
procedure SetPRemitText4(const Value: String);
function GetPRemitText4:String;
procedure SetPRemitAbbreviation(const Value: String);
function GetPRemitAbbreviation:String;
procedure SetPNextClaimNumber(const Value: String);
function GetPNextClaimNumber:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIInfoSYSTEMSETTINGS);
function GetEnumIndex: TEIInfoSYSTEMSETTINGS;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoSYSTEMSETTINGSRecord;
procedure StoreDataBuffer(ABuffer:TInfoSYSTEMSETTINGSRecord);
property DFIndex: TAutoIncField read FDFIndex;
property DFFloppyDiskDrive: TStringField read FDFFloppyDiskDrive;
property DFPCAnywhereVersion: TStringField read FDFPCAnywhereVersion;
property DFEndHostModeFirst: TBooleanField read FDFEndHostModeFirst;
property DFUTLRetensionDays: TIntegerField read FDFUTLRetensionDays;
property DFFFSHost: TBooleanField read FDFFFSHost;
property DFClient: TStringField read FDFClient;
property DFSite: TStringField read FDFSite;
property DFRemitText1: TStringField read FDFRemitText1;
property DFRemitText2: TStringField read FDFRemitText2;
property DFRemitText3: TStringField read FDFRemitText3;
property DFRemitText4: TStringField read FDFRemitText4;
property DFRemitAbbreviation: TStringField read FDFRemitAbbreviation;
property DFNextClaimNumber: TStringField read FDFNextClaimNumber;
property PFloppyDiskDrive: String read GetPFloppyDiskDrive write SetPFloppyDiskDrive;
property PPCAnywhereVersion: String read GetPPCAnywhereVersion write SetPPCAnywhereVersion;
property PEndHostModeFirst: Boolean read GetPEndHostModeFirst write SetPEndHostModeFirst;
property PUTLRetensionDays: Integer read GetPUTLRetensionDays write SetPUTLRetensionDays;
property PFFSHost: Boolean read GetPFFSHost write SetPFFSHost;
property PClient: String read GetPClient write SetPClient;
property PSite: String read GetPSite write SetPSite;
property PRemitText1: String read GetPRemitText1 write SetPRemitText1;
property PRemitText2: String read GetPRemitText2 write SetPRemitText2;
property PRemitText3: String read GetPRemitText3 write SetPRemitText3;
property PRemitText4: String read GetPRemitText4 write SetPRemitText4;
property PRemitAbbreviation: String read GetPRemitAbbreviation write SetPRemitAbbreviation;
property PNextClaimNumber: String read GetPNextClaimNumber write SetPNextClaimNumber;
published
property Active write SetActive;
property EnumIndex: TEIInfoSYSTEMSETTINGS read GetEnumIndex write SetEnumIndex;
end; { TInfoSYSTEMSETTINGSTable }
procedure Register;
implementation
function TInfoSYSTEMSETTINGSTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TInfoSYSTEMSETTINGSTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TInfoSYSTEMSETTINGSTable.GenerateNewFieldName }
function TInfoSYSTEMSETTINGSTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TInfoSYSTEMSETTINGSTable.CreateField }
procedure TInfoSYSTEMSETTINGSTable.CreateFields;
begin
FDFIndex := CreateField( 'Index' ) as TAutoIncField;
FDFFloppyDiskDrive := CreateField( 'FloppyDiskDrive' ) as TStringField;
FDFPCAnywhereVersion := CreateField( 'PCAnywhereVersion' ) as TStringField;
FDFEndHostModeFirst := CreateField( 'EndHostModeFirst' ) as TBooleanField;
FDFUTLRetensionDays := CreateField( 'UTLRetensionDays' ) as TIntegerField;
FDFFFSHost := CreateField( 'FFSHost' ) as TBooleanField;
FDFClient := CreateField( 'Client' ) as TStringField;
FDFSite := CreateField( 'Site' ) as TStringField;
FDFRemitText1 := CreateField( 'RemitText1' ) as TStringField;
FDFRemitText2 := CreateField( 'RemitText2' ) as TStringField;
FDFRemitText3 := CreateField( 'RemitText3' ) as TStringField;
FDFRemitText4 := CreateField( 'RemitText4' ) as TStringField;
FDFRemitAbbreviation := CreateField( 'RemitAbbreviation' ) as TStringField;
FDFNextClaimNumber := CreateField( 'NextClaimNumber' ) as TStringField;
end; { TInfoSYSTEMSETTINGSTable.CreateFields }
procedure TInfoSYSTEMSETTINGSTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoSYSTEMSETTINGSTable.SetActive }
procedure TInfoSYSTEMSETTINGSTable.SetPFloppyDiskDrive(const Value: String);
begin
DFFloppyDiskDrive.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPFloppyDiskDrive:String;
begin
result := DFFloppyDiskDrive.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPPCAnywhereVersion(const Value: String);
begin
DFPCAnywhereVersion.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPPCAnywhereVersion:String;
begin
result := DFPCAnywhereVersion.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPEndHostModeFirst(const Value: Boolean);
begin
DFEndHostModeFirst.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPEndHostModeFirst:Boolean;
begin
result := DFEndHostModeFirst.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPUTLRetensionDays(const Value: Integer);
begin
DFUTLRetensionDays.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPUTLRetensionDays:Integer;
begin
result := DFUTLRetensionDays.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPFFSHost(const Value: Boolean);
begin
DFFFSHost.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPFFSHost:Boolean;
begin
result := DFFFSHost.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPClient(const Value: String);
begin
DFClient.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPClient:String;
begin
result := DFClient.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPSite(const Value: String);
begin
DFSite.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPSite:String;
begin
result := DFSite.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPRemitText1(const Value: String);
begin
DFRemitText1.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPRemitText1:String;
begin
result := DFRemitText1.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPRemitText2(const Value: String);
begin
DFRemitText2.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPRemitText2:String;
begin
result := DFRemitText2.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPRemitText3(const Value: String);
begin
DFRemitText3.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPRemitText3:String;
begin
result := DFRemitText3.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPRemitText4(const Value: String);
begin
DFRemitText4.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPRemitText4:String;
begin
result := DFRemitText4.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPRemitAbbreviation(const Value: String);
begin
DFRemitAbbreviation.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPRemitAbbreviation:String;
begin
result := DFRemitAbbreviation.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.SetPNextClaimNumber(const Value: String);
begin
DFNextClaimNumber.Value := Value;
end;
function TInfoSYSTEMSETTINGSTable.GetPNextClaimNumber:String;
begin
result := DFNextClaimNumber.Value;
end;
procedure TInfoSYSTEMSETTINGSTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Index, AutoInc, 0, N');
Add('FloppyDiskDrive, String, 1, N');
Add('PCAnywhereVersion, String, 5, N');
Add('EndHostModeFirst, Boolean, 0, N');
Add('UTLRetensionDays, Integer, 0, N');
Add('FFSHost, Boolean, 0, N');
Add('Client, String, 10, N');
Add('Site, String, 10, N');
Add('RemitText1, String, 35, N');
Add('RemitText2, String, 35, N');
Add('RemitText3, String, 35, N');
Add('RemitText4, String, 35, N');
Add('RemitAbbreviation, String, 6, N');
Add('NextClaimNumber, String, 6, N');
end;
end;
procedure TInfoSYSTEMSETTINGSTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Index, Y, Y, N, N');
end;
end;
procedure TInfoSYSTEMSETTINGSTable.SetEnumIndex(Value: TEIInfoSYSTEMSETTINGS);
begin
case Value of
InfoSYSTEMSETTINGSPrimaryKey : IndexName := '';
end;
end;
function TInfoSYSTEMSETTINGSTable.GetDataBuffer:TInfoSYSTEMSETTINGSRecord;
var buf: TInfoSYSTEMSETTINGSRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PIndex := DFIndex.Value;
buf.PFloppyDiskDrive := DFFloppyDiskDrive.Value;
buf.PPCAnywhereVersion := DFPCAnywhereVersion.Value;
buf.PEndHostModeFirst := DFEndHostModeFirst.Value;
buf.PUTLRetensionDays := DFUTLRetensionDays.Value;
buf.PFFSHost := DFFFSHost.Value;
buf.PClient := DFClient.Value;
buf.PSite := DFSite.Value;
buf.PRemitText1 := DFRemitText1.Value;
buf.PRemitText2 := DFRemitText2.Value;
buf.PRemitText3 := DFRemitText3.Value;
buf.PRemitText4 := DFRemitText4.Value;
buf.PRemitAbbreviation := DFRemitAbbreviation.Value;
buf.PNextClaimNumber := DFNextClaimNumber.Value;
result := buf;
end;
procedure TInfoSYSTEMSETTINGSTable.StoreDataBuffer(ABuffer:TInfoSYSTEMSETTINGSRecord);
begin
DFFloppyDiskDrive.Value := ABuffer.PFloppyDiskDrive;
DFPCAnywhereVersion.Value := ABuffer.PPCAnywhereVersion;
DFEndHostModeFirst.Value := ABuffer.PEndHostModeFirst;
DFUTLRetensionDays.Value := ABuffer.PUTLRetensionDays;
DFFFSHost.Value := ABuffer.PFFSHost;
DFClient.Value := ABuffer.PClient;
DFSite.Value := ABuffer.PSite;
DFRemitText1.Value := ABuffer.PRemitText1;
DFRemitText2.Value := ABuffer.PRemitText2;
DFRemitText3.Value := ABuffer.PRemitText3;
DFRemitText4.Value := ABuffer.PRemitText4;
DFRemitAbbreviation.Value := ABuffer.PRemitAbbreviation;
DFNextClaimNumber.Value := ABuffer.PNextClaimNumber;
end;
function TInfoSYSTEMSETTINGSTable.GetEnumIndex: TEIInfoSYSTEMSETTINGS;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoSYSTEMSETTINGSPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoSYSTEMSETTINGSTable, TInfoSYSTEMSETTINGSBuffer ] );
end; { Register }
function TInfoSYSTEMSETTINGSBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..14] of string = ('INDEX','FLOPPYDISKDRIVE','PCANYWHEREVERSION','ENDHOSTMODEFIRST','UTLRETENSIONDAYS','FFSHOST'
,'CLIENT','SITE','REMITTEXT1','REMITTEXT2','REMITTEXT3'
,'REMITTEXT4','REMITABBREVIATION','NEXTCLAIMNUMBER' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 14) and (flist[x] <> s) do inc(x);
if x <= 14 then result := x else result := 0;
end;
function TInfoSYSTEMSETTINGSBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftAutoInc;
2 : result := ftString;
3 : result := ftString;
4 : result := ftBoolean;
5 : result := ftInteger;
6 : result := ftBoolean;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
11 : result := ftString;
12 : result := ftString;
13 : result := ftString;
14 : result := ftString;
end;
end;
function TInfoSYSTEMSETTINGSBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PIndex;
2 : result := @Data.PFloppyDiskDrive;
3 : result := @Data.PPCAnywhereVersion;
4 : result := @Data.PEndHostModeFirst;
5 : result := @Data.PUTLRetensionDays;
6 : result := @Data.PFFSHost;
7 : result := @Data.PClient;
8 : result := @Data.PSite;
9 : result := @Data.PRemitText1;
10 : result := @Data.PRemitText2;
11 : result := @Data.PRemitText3;
12 : result := @Data.PRemitText4;
13 : result := @Data.PRemitAbbreviation;
14 : result := @Data.PNextClaimNumber;
end;
end;
end.
|
unit VirtDisk;
interface
// Microsoft SDKs v7.0 - VirtDisk.h convert to pascal
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd323654(v=vs.85).aspx
// kyypbd@gmail.com
// http://yypbd.tistory.com
uses
Windows;
{$MINENUMSIZE 4}
// OpenVirtualDisk & CreateVirtualDisk
type
PVirtualStorageType = ^TVirtualStorageType;
_VIRTUAL_STORAGE_TYPE = record
DeviceId: ULONG;
VendorId: TGUID;
end;
TVirtualStorageType = _VIRTUAL_STORAGE_TYPE;
VIRTUAL_STORAGE_TYPE = _VIRTUAL_STORAGE_TYPE;
const
VIRTUAL_STORAGE_TYPE_VENDOR_UNKNOWN: TGUID =
'{00000000-0000-0000-0000-000000000000}';
VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT: TGUID =
'{EC984AEC-A0F9-47e9-901F-71415A66345B}';
VIRTUAL_STORAGE_TYPE_DEVICE_UNKNOWN = 0;
VIRTUAL_STORAGE_TYPE_DEVICE_ISO = 1;
VIRTUAL_STORAGE_TYPE_DEVICE_VHD = 2;
CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_BLOCK_SIZE = 0;
CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_SECTOR_SIZE = $200;
type
TCREATE_VIRTUAL_DISK_VERSION = (
CREATE_VIRTUAL_DISK_VERSION_UNSPECIFIED = 0,
CREATE_VIRTUAL_DISK_VERSION_1 = 1
);
TCreateVirtualDiskParametersVersion1 = record
UniqueId: TGUID;
MaximumSize: ULONGLONG;
BlockSizeInBytes: ULONG;
SectorSizeInBytes: ULONG;
ParentPath: LPCWSTR;
SourcePath: LPCWSTR;
end;
PCreateVirtualDiskParameters = ^TCreateVirtualDiskParameters;
_CREATE_VIRTUAL_DISK_PARAMETERS = record
Version: TCREATE_VIRTUAL_DISK_VERSION;
case Integer of
0: ( Version1: TCreateVirtualDiskParametersVersion1; );
end;
TCreateVirtualDiskParameters = _CREATE_VIRTUAL_DISK_PARAMETERS;
CREATE_VIRTUAL_DISK_PARAMETERS = _CREATE_VIRTUAL_DISK_PARAMETERS;
TCREATE_VIRTUAL_DISK_FLAG = (
CREATE_VIRTUAL_DISK_FLAG_NONE = $00000000,
CREATE_VIRTUAL_DISK_FLAG_FULL_PHYSICAL_ALLOCATION = $00000001
);
const
OPEN_VIRTUAL_DISK_RW_DEPTH_DEFAULT = 1;
type
TOPEN_VIRTUAL_DISK_VERSION = (
OPEN_VIRTUAL_DISK_VERSION_UNSPECIFIED = 0,
OPEN_VIRTUAL_DISK_VERSION_1 = 1
);
TOPEN_VIRTUAL_DISK_PARAMETERS_VERSION1 = record
RWDepth: ULONG;
end;
POpenVirtualDiskParameters = ^TOpenVirtualDiskParameters;
_OPEN_VIRTUAL_DISK_PARAMETERS = record
Version: TOPEN_VIRTUAL_DISK_VERSION;
case Integer of
0: ( Version1: TOPEN_VIRTUAL_DISK_PARAMETERS_VERSION1;
);
end;
TOpenVirtualDiskParameters = _OPEN_VIRTUAL_DISK_PARAMETERS;
OPEN_VIRTUAL_DISK_PARAMETERS = _OPEN_VIRTUAL_DISK_PARAMETERS;
TVIRTUAL_DISK_ACCESS_MASK = (
VIRTUAL_DISK_ACCESS_ATTACH_RO = $00010000,
VIRTUAL_DISK_ACCESS_ATTACH_RW = $00020000,
VIRTUAL_DISK_ACCESS_DETACH = $00040000,
VIRTUAL_DISK_ACCESS_GET_INFO = $00080000,
VIRTUAL_DISK_ACCESS_CREATE = $00100000,
VIRTUAL_DISK_ACCESS_METAOPS = $00200000,
VIRTUAL_DISK_ACCESS_READ = $000d0000,
VIRTUAL_DISK_ACCESS_ALL = $003f0000,
VIRTUAL_DISK_ACCESS_WRITABLE = $00320000
);
TOPEN_VIRTUAL_DISK_FLAG = (
OPEN_VIRTUAL_DISK_FLAG_NONE = $00000000,
OPEN_VIRTUAL_DISK_FLAG_NO_PARENTS = $00000001,
OPEN_VIRTUAL_DISK_FLAG_BLANK_FILE = $00000002,
OPEN_VIRTUAL_DISK_FLAG_BOOT_DRIVE = $00000004
);
function OpenVirtualDisk(
VirtualStorageType: PVirtualStorageType;
Path: LPCWSTR;
VirtualDiskAccessMask: TVIRTUAL_DISK_ACCESS_MASK;
Flags: TOPEN_VIRTUAL_DISK_FLAG;
Parameters: POpenVirtualDiskParameters;
var Handle: THandle
): DWORD; stdcall;
function CreateVirtualDisk(
VirtualStorageType: PVirtualStorageType;
Path: LPCWSTR;
VirtualDiskAccessMask: TVIRTUAL_DISK_ACCESS_MASK;
SecurityDescriptor: PSECURITY_DESCRIPTOR;
Flags: TCREATE_VIRTUAL_DISK_FLAG;
ProviderSpecificFlags: ULONG;
Parameters: PCreateVirtualDiskParameters;
Overlapped: POverlapped;
var Handle: THandle
): DWORD; stdcall;
// AttachVirtualDisk
type
TATTACH_VIRTUAL_DISK_VERSION = (
ATTACH_VIRTUAL_DISK_VERSION_UNSPECIFIED = 0,
ATTACH_VIRTUAL_DISK_VERSION_1 = 1
);
TAttachVirtualDiskParametersVersion1 = record
Reserved: ULONG;
end;
PAttachVirtualDiskParameters = ^TAttachVirtualDiskParameters;
_ATTACH_VIRTUAL_DISK_PARAMETERS = record
Version: TATTACH_VIRTUAL_DISK_VERSION;
case Integer of
0: ( Version1: TAttachVirtualDiskParametersVersion1; );
end;
TAttachVirtualDiskParameters = _ATTACH_VIRTUAL_DISK_PARAMETERS;
ATTACH_VIRTUAL_DISK_PARAMETERS = _ATTACH_VIRTUAL_DISK_PARAMETERS;
TATTACH_VIRTUAL_DISK_FLAG = (
ATTACH_VIRTUAL_DISK_FLAG_NONE = $00000000,
ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY = $00000001,
ATTACH_VIRTUAL_DISK_FLAG_NO_DRIVE_LETTER = $00000002,
ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME = $00000004,
ATTACH_VIRTUAL_DISK_FLAG_NO_LOCAL_HOST = $00000008
);
function AttachVirtualDisk(
VirtualDiskHandle: THandle;
SecurityDescriptor: PSECURITY_DESCRIPTOR;
Flags: TATTACH_VIRTUAL_DISK_FLAG;
ProviderSpecificFlags: ULONG;
Parameters: PAttachVirtualDiskParameters;
Overlapped: POverlapped
): DWORD; stdcall;
// DetachVirtualDisk
type
TDETACH_VIRTUAL_DISK_FLAG = (
DETACH_VIRTUAL_DISK_FLAG_NONE = $00000000
);
function DetachVirtualDisk(
VirtualDiskHandle: THandle;
Flags: TDETACH_VIRTUAL_DISK_FLAG;
ProviderSpecificFlags: ULONG
): DWORD; stdcall;
// GetVirtualDiskPhysicalPath
function GetVirtualDiskPhysicalPath(
VirtualDiskHandle: THandle;
DiskPathSizeInBytes: PULONG;
DiskPath: LPWSTR
): DWORD; stdcall;
// GetStorageDependencyInformation
type
TDEPENDENT_DISK_FLAG = (
DEPENDENT_DISK_FLAG_NONE = $00000000,
DEPENDENT_DISK_FLAG_MULT_BACKING_FILES = $00000001,
DEPENDENT_DISK_FLAG_FULLY_ALLOCATED = $00000002,
DEPENDENT_DISK_FLAG_READ_ONLY = $00000004,
DEPENDENT_DISK_FLAG_REMOTE = $00000008,
DEPENDENT_DISK_FLAG_SYSTEM_VOLUME = $00000010,
DEPENDENT_DISK_FLAG_SYSTEM_VOLUME_PARENT = $00000020,
DEPENDENT_DISK_FLAG_REMOVABLE = $00000040,
DEPENDENT_DISK_FLAG_NO_DRIVE_LETTER = $00000080,
DEPENDENT_DISK_FLAG_PARENT = $00000100,
DEPENDENT_DISK_FLAG_NO_HOST_DISK = $00000200,
DEPENDENT_DISK_FLAG_PERMANENT_LIFETIME = $00000400
);
TSTORAGE_DEPENDENCY_INFO_VERSION = (
STORAGE_DEPENDENCY_INFO_VERSION_UNSPECIFIED = 0,
STORAGE_DEPENDENCY_INFO_VERSION_1 = 1,
STORAGE_DEPENDENCY_INFO_VERSION_2 = 2
);
PStorageDependencyInfoType1 = ^TStorageDependencyInfoType1;
_STORAGE_DEPENDENCY_INFO_TYPE_1 = record
DependencyTypeFlags: TDEPENDENT_DISK_FLAG;
ProviderSpecificFlags: ULONG;
VirtualStorageType: TVirtualStorageType;
end;
TStorageDependencyInfoType1 = _STORAGE_DEPENDENCY_INFO_TYPE_1;
STORAGE_DEPENDENCY_INFO_TYPE_1 = _STORAGE_DEPENDENCY_INFO_TYPE_1;
PStorageDependencyInfoType2 = ^TStorageDependencyInfoType2;
_STORAGE_DEPENDENCY_INFO_TYPE_2 = record
DependencyTypeFlags: TDEPENDENT_DISK_FLAG;
ProviderSpecificFlags: ULONG;
VirtualStorageType: TVirtualStorageType;
AncestorLevel: ULONG;
DependencyDeviceName: LPWSTR;
HostVolumeName: LPWSTR;
DependentVolumeName: LPWSTR;
DependentVolumeRelativePath: LPWSTR;
end;
TStorageDependencyInfoType2 = _STORAGE_DEPENDENCY_INFO_TYPE_2;
STORAGE_DEPENDENCY_INFO_TYPE_2 = _STORAGE_DEPENDENCY_INFO_TYPE_2;
PStorageDependencyInfo = ^TStorageDependencyInfo;
_STORAGE_DEPENDENCY_INFO = record
Version: TSTORAGE_DEPENDENCY_INFO_VERSION;
NumberEntries: ULONG;
case Integer of
0: (
Version1Entries: PStorageDependencyInfoType1;
Version2Entries: PStorageDependencyInfoType2;
);
end;
TStorageDependencyInfo = _STORAGE_DEPENDENCY_INFO;
STORAGE_DEPENDENCY_INFO = _STORAGE_DEPENDENCY_INFO;
TGET_STORAGE_DEPENDENCY_FLAG = (
GET_STORAGE_DEPENDENCY_FLAG_NONE = $00000000,
GET_STORAGE_DEPENDENCY_FLAG_HOST_VOLUMES = $00000001,
GET_STORAGE_DEPENDENCY_FLAG_DISK_HANDLE = $00000002
);
const
GET_STORAGE_DEPENDENCY_FLAG_PARENTS = GET_STORAGE_DEPENDENCY_FLAG_HOST_VOLUMES;
function GetStorageDependencyInformation(
ObjectHandle: THandle;
Flags: TGET_STORAGE_DEPENDENCY_FLAG;
StorageDependencyInfoSize: ULONG;
var StorageDependencyInfo: TStorageDependencyInfo;
var SizeUsed: ULONG
): DWORD; stdcall;
// GetVirtualDiskInformation
type
TGET_VIRTUAL_DISK_INFO_VERSION = (
GET_VIRTUAL_DISK_INFO_UNSPECIFIED = 0,
GET_VIRTUAL_DISK_INFO_SIZE = 1,
GET_VIRTUAL_DISK_INFO_IDENTIFIER = 2,
GET_VIRTUAL_DISK_INFO_PARENT_LOCATION = 3,
GET_VIRTUAL_DISK_INFO_PARENT_IDENTIFIER = 4,
GET_VIRTUAL_DISK_INFO_PARENT_TIMESTAMP = 5,
GET_VIRTUAL_DISK_INFO_VIRTUAL_STORAGE_TYPE = 6,
GET_VIRTUAL_DISK_INFO_PROVIDER_SUBTYPE = 7
);
TSize = record
VirtualSize: ULONGLONG;
PhysicalSize: ULONGLONG;
BlockSize: ULONG;
SectorSize: ULONG;
end;
TParentLocation = record
ParentResolved: BOOL;
ParentLocationBuffer: array[0..0] of WCHAR; // MultiSz string
end;
PGetVirtualDiskInfo = ^TGetVirtualDiskInfo;
_GET_VIRTUAL_DISK_INFO = record
Version: TGET_VIRTUAL_DISK_INFO_VERSION;
case Integer of
0: (
Size: TSize;
Identifier: TGUID;
ParentLocation: TParentLocation;
ParentIdentifier: TGUID;
ParentTimestamp: ULONG;
VirtualStorageType: TVirtualStorageType;
ProviderSubtype: ULONG;
);
end;
TGetVirtualDiskInfo = _GET_VIRTUAL_DISK_INFO;
GET_VIRTUAL_DISK_INFO = _GET_VIRTUAL_DISK_INFO;
function GetVirtualDiskInformation(
VirtualDiskHandle: THandle;
var VirtualDiskInfoSize: ULONG;
var VirtualDiskInfo: TGetVirtualDiskInfo;
var SizeUsed: ULONG
): DWORD; stdcall;
// SetVirtualDiskInformation
type
TSET_VIRTUAL_DISK_INFO_VERSION = (
SET_VIRTUAL_DISK_INFO_UNSPECIFIED = 0,
SET_VIRTUAL_DISK_INFO_PARENT_PATH = 1,
SET_VIRTUAL_DISK_INFO_IDENTIFIER = 2
);
PSetVirtualDiskInfo = ^TSetVirtualDiskInfo;
_SET_VIRTUAL_DISK_INFO = record
Version: TSET_VIRTUAL_DISK_INFO_VERSION;
case Integer of
0: (
ParentFilePath: LPWSTR;
UniqueIdentifier: TGUID;
);
end;
TSetVirtualDiskInfo = _SET_VIRTUAL_DISK_INFO;
SET_VIRTUAL_DISK_INFO = _SET_VIRTUAL_DISK_INFO;
function SetVirtualDiskInformation(
VirtualDiskHandle: THandle;
VirtualDiskInfo: PSetVirtualDiskInfo
): DWORD; stdcall;
// GetVirtualDiskOperationProgress
type
PVirtualDiskProgress = ^TVirtualDiskProgress;
_VIRTUAL_DISK_PROGRESS = record
OperationStatus: DWORD;
CurrentValue: ULONGLONG;
CompletionValue: ULONGLONG;
end;
TVirtualDiskProgress = _VIRTUAL_DISK_PROGRESS;
VIRTUAL_DISK_PROGRESS = _VIRTUAL_DISK_PROGRESS;
function GetVirtualDiskOperationProgress(
VirtualDiskHandle: THandle;
Overlapped: POverlapped;
var Progress: TVirtualDiskProgress
): DWORD; stdcall;
// CompactVirtualDisk
type
TCOMPACT_VIRTUAL_DISK_VERSION = (
COMPACT_VIRTUAL_DISK_VERSION_UNSPECIFIED = 0,
COMPACT_VIRTUAL_DISK_VERSION_1 = 1
);
TCOMPACT_VIRTUAL_DISK_PARAMETERS_VERSION1 = record
Reserved: ULONG;
end;
PCompactVirtualDiskParameters = ^TCompactVirtualDiskParameters;
_COMPACT_VIRTUAL_DISK_PARAMETERS = record
Version: TCOMPACT_VIRTUAL_DISK_VERSION;
case Integer of
0: ( Version1: TCOMPACT_VIRTUAL_DISK_PARAMETERS_VERSION1; );
end;
TCompactVirtualDiskParameters = _COMPACT_VIRTUAL_DISK_PARAMETERS;
COMPACT_VIRTUAL_DISK_PARAMETERS = _COMPACT_VIRTUAL_DISK_PARAMETERS;
TCOMPACT_VIRTUAL_DISK_FLAG = (
COMPACT_VIRTUAL_DISK_FLAG_NONE = $00000000
);
function CompactVirtualDisk(
VirtualDiskHandle: THandle;
Flags: TCOMPACT_VIRTUAL_DISK_FLAG;
Parameters: PCompactVirtualDiskParameters;
Overlapped: POverlapped
): DWORD; stdcall;
// MergeVirtualDisk
type
TMERGE_VIRTUAL_DISK_VERSION = (
MERGE_VIRTUAL_DISK_VERSION_UNSPECIFIED = 0,
MERGE_VIRTUAL_DISK_VERSION_1 = 1
);
const
MERGE_VIRTUAL_DISK_DEFAULT_MERGE_DEPTH = 1;
type
TMergeVirtualDiskParametersVersion1 = record
MergeDepth: ULONG;
end;
PMergeVirtualDiskParameters = ^TMergeVirtualDiskParameters;
_MERGE_VIRTUAL_DISK_PARAMETERS = record
Version: TMERGE_VIRTUAL_DISK_VERSION;
case Integer of
0: ( Version1: TMergeVirtualDiskParametersVersion1; );
end;
TMergeVirtualDiskParameters = _MERGE_VIRTUAL_DISK_PARAMETERS;
MERGE_VIRTUAL_DISK_PARAMETERS = _MERGE_VIRTUAL_DISK_PARAMETERS;
TMERGE_VIRTUAL_DISK_FLAG = (
MERGE_VIRTUAL_DISK_FLAG_NONE = $00000000
);
function MergeVirtualDisk(
VirtualDiskHandle: THandle;
Flags: TMERGE_VIRTUAL_DISK_FLAG;
Parameters: PMergeVirtualDiskParameters;
Overlapped: POverlapped
): DWORD; stdcall;
// ExpandVirtualDisk
type
TEXPAND_VIRTUAL_DISK_VERSION = (
EXPAND_VIRTUAL_DISK_VERSION_UNSPECIFIED = 0,
EXPAND_VIRTUAL_DISK_VERSION_1 = 1
);
TExpandVirtualDiskParametersVersion1 = record
NewSize: ULONGLONG;
end;
PExpandVirtualDiskParameters = ^TExpandVirtualDiskParameters;
_EXPAND_VIRTUAL_DISK_PARAMETERS = record
Version: TEXPAND_VIRTUAL_DISK_VERSION;
case Integer of
0: ( Version1: TExpandVirtualDiskParametersVersion1; );
end;
TExpandVirtualDiskParameters = _EXPAND_VIRTUAL_DISK_PARAMETERS;
EXPAND_VIRTUAL_DISK_PARAMETERS = _EXPAND_VIRTUAL_DISK_PARAMETERS;
TEXPAND_VIRTUAL_DISK_FLAG = (
EXPAND_VIRTUAL_DISK_FLAG_NONE = $00000000
);
function ExpandVirtualDisk(
VirtualDiskHandle: THANDLE;
Flags: TEXPAND_VIRTUAL_DISK_FLAG;
Parameters: PExpandVirtualDiskParameters;
Overlapped: POverlapped
): DWORD; stdcall;
implementation
const
VirtDiskDLLName = 'VirtDisk.dll';
function OpenVirtualDisk; external VirtDiskDLLName name 'OpenVirtualDisk';
function CreateVirtualDisk; external VirtDiskDLLName name 'CreateVirtualDisk';
function AttachVirtualDisk; external VirtDiskDLLName name 'AttachVirtualDisk';
function DetachVirtualDisk; external VirtDiskDLLName name 'DetachVirtualDisk';
function GetVirtualDiskPhysicalPath; external VirtDiskDLLName name 'GetVirtualDiskPhysicalPath';
function GetStorageDependencyInformation; external VirtDiskDLLName name 'GetStorageDependencyInformation';
function GetVirtualDiskInformation; external VirtDiskDLLName name 'GetVirtualDiskInformation';
function SetVirtualDiskInformation; external VirtDiskDLLName name 'SetVirtualDiskInformation';
function GetVirtualDiskOperationProgress; external VirtDiskDLLName name 'GetVirtualDiskOperationProgress';
function CompactVirtualDisk; external VirtDiskDLLName name 'CompactVirtualDisk';
function MergeVirtualDisk; external VirtDiskDLLName name 'MergeVirtualDisk';
function ExpandVirtualDisk; external VirtDiskDLLName name 'ExpandVirtualDisk';
end.
|
unit UserUtils;
interface
function FormatUserName( const aUser : string ) : string;
implementation
uses
SysUtils;
function FormatUserName( const aUser : string ) : string;
var
UpStr, LoStr : string;
begin
UpStr := UpperCase( aUser );
LoStr := LowerCase( aUser );
if ( aUser = LoStr ) or ( aUser = UpStr )
then
if length( aUser ) > 3
then Result := UpStr[1] + copy( LoStr, 2, length( LoStr ) )
else Result := UpStr
else Result := aUser;
end;
end.
|
unit ncsGetTaskDescriptionReply;
// Модуль: "w:\common\components\rtl\Garant\cs\ncsGetTaskDescriptionReply.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TncsGetTaskDescriptionReply" MUID: (546B442D0343)
{$Include w:\common\components\rtl\Garant\cs\CsDefine.inc}
interface
{$If NOT Defined(Nemesis)}
uses
l3IntfUses
, ncsMessage
, ncsFileDescHelper
, k2Base
;
type
TncsGetTaskDescriptionReply = class(TncsReply)
protected
function pm_GetLocalFolder: AnsiString;
procedure pm_SetLocalFolder(const aValue: AnsiString);
function pm_GetRemoteFolder: AnsiString;
procedure pm_SetRemoteFolder(const aValue: AnsiString);
function pm_GetFileDesc: FileDescHelper;
public
class function GetTaggedDataType: Tk2Type; override;
public
property LocalFolder: AnsiString
read pm_GetLocalFolder
write pm_SetLocalFolder;
property RemoteFolder: AnsiString
read pm_GetRemoteFolder
write pm_SetRemoteFolder;
property FileDesc: FileDescHelper
read pm_GetFileDesc;
end;//TncsGetTaskDescriptionReply
{$IfEnd} // NOT Defined(Nemesis)
implementation
{$If NOT Defined(Nemesis)}
uses
l3ImplUses
, csGetTaskDescriptionReply_Const
//#UC START# *546B442D0343impl_uses*
//#UC END# *546B442D0343impl_uses*
;
function TncsGetTaskDescriptionReply.pm_GetLocalFolder: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrLocalFolder]);
end;//TncsGetTaskDescriptionReply.pm_GetLocalFolder
procedure TncsGetTaskDescriptionReply.pm_SetLocalFolder(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrLocalFolder, nil] := (aValue);
end;//TncsGetTaskDescriptionReply.pm_SetLocalFolder
function TncsGetTaskDescriptionReply.pm_GetRemoteFolder: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrRemoteFolder]);
end;//TncsGetTaskDescriptionReply.pm_GetRemoteFolder
procedure TncsGetTaskDescriptionReply.pm_SetRemoteFolder(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrRemoteFolder, nil] := (aValue);
end;//TncsGetTaskDescriptionReply.pm_SetRemoteFolder
function TncsGetTaskDescriptionReply.pm_GetFileDesc: FileDescHelper;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := TFileDescHelper.Make(TaggedData.cAtom(k2_attrFileDesc));
end;//TncsGetTaskDescriptionReply.pm_GetFileDesc
class function TncsGetTaskDescriptionReply.GetTaggedDataType: Tk2Type;
begin
Result := k2_typcsGetTaskDescriptionReply;
end;//TncsGetTaskDescriptionReply.GetTaggedDataType
{$IfEnd} // NOT Defined(Nemesis)
end.
|
unit uDiaBoxMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, XPMan, ImgList, ComCtrls, ToolWin, StdCtrls, Grids, Menus;
type
TExplodeResult = array of string;
TfDiaBoxMain = class(TForm)
XPManifest1: TXPManifest;
ToolBar1: TToolBar;
bNew: TToolButton;
bSave: TToolButton;
bOpen: TToolButton;
ToolbarImageList: TImageList;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
ToolButton5: TToolButton;
bClose: TToolButton;
StatusBar1: TStatusBar;
MenuImageList: TImageList;
HC: THeaderControl;
SG: TStringGrid;
bTest: TToolButton;
bAddLine: TToolButton;
ToolButton10: TToolButton;
MainMenu1: TMainMenu;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
N5: TMenuItem;
N6: TMenuItem;
bEditLine: TToolButton;
N7: TMenuItem;
N8: TMenuItem;
N9: TMenuItem;
N11: TMenuItem;
N12: TMenuItem;
N13: TMenuItem;
N10: TMenuItem;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
N14: TMenuItem;
N15: TMenuItem;
N16: TMenuItem;
N17: TMenuItem;
N18: TMenuItem;
bDown: TToolButton;
bUp: TToolButton;
ToolButton6: TToolButton;
N19: TMenuItem;
N20: TMenuItem;
N21: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure bNewClick(Sender: TObject);
procedure bSaveClick(Sender: TObject);
procedure bOpenClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure HCSectionResize(HeaderControl: THeaderControl;
Section: THeaderSection);
procedure FormResize(Sender: TObject);
procedure bSaveAsClick(Sender: TObject);
procedure SGDblClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure bAddLineClick(Sender: TObject);
procedure bEditLineClick(Sender: TObject);
procedure N15Click(Sender: TObject);
procedure N16Click(Sender: TObject);
procedure bTestClick(Sender: TObject);
procedure N18Click(Sender: TObject);
procedure N4Click(Sender: TObject);
procedure bDownClick(Sender: TObject);
procedure bUpClick(Sender: TObject);
private
{ Private declarations }
CurrentFileName: string;
procedure HintHandler(Sender: TObject);
procedure New();
procedure Edit();
function Save: Boolean;
function SaveAs: Boolean;
procedure Load();
function CheckSaved: Boolean;
procedure Display;
procedure Move(M: ShortInt);
public
{ Public declarations }
Saved: Boolean;
Dialog: TStringList;
procedure UpdateText;
function Explode(const StringSeparator: string; const Source: string): TExplodeResult;
end;
var
fDiaBoxMain: TfDiaBoxMain;
implementation
uses uDiaBoxEdit, uDiaBoxTest;
{$R *.dfm}
{ TfDiaBoxMain }
procedure TfDiaBoxMain.Display;
var
I: Integer;
V: TExplodeResult;
begin
for I := 0 to Dialog.Count - 1 do
begin
V := Explode(string('|'), Dialog[I]);
SG.Cells[0, I] := IntToStr(I + 1);
if (V[0] = '0') then SG.Cells[1, I] := 'PC'
else SG.Cells[1, I] := 'NPC';
SG.Cells[2, I] := V[1];
SG.Cells[3, I] := V[2];
SG.Cells[4, I] := V[3];
end;
SG.RowCount := I;
end;
function TfDiaBoxMain.Explode(const StringSeparator,
Source: string): TExplodeResult;
var
I: Integer;
S: string;
begin
S := Source;
SetLength(Result, 0);
I := 0;
while Pos(StringSeparator, S) > 0 do
begin
SetLength(Result, Length(Result) + 1);
Result[I] := Copy(S, 1, Pos(StringSeparator, S) - 1);
Inc(I);
S := Copy(S, Pos(StringSeparator, S) + Length(StringSeparator), Length(S));
end;
SetLength(Result, Length(Result) + 1);
Result[I] := Copy(S, 1, Length(S));
end;
function TfDiaBoxMain.CheckSaved: Boolean;
var
I: Integer;
begin
if not Saved then
begin
result := false;
I := Application.MessageBox(
'Сохранить изменения в диалоге?', 'Диалог изменен', MB_YESNOCANCEL);
if I = ID_YES then
result := Save
else if I = ID_NO then
result := true;
end else
result := true;
Saved := Result;
end;
procedure TfDiaBoxMain.Load;
begin
if CheckSaved and OpenDialog.Execute then
begin
New;
CurrentFilename := OpenDialog.FileName;
Dialog.LoadFromFile(OpenDialog.FileName);
Display;
Saved := true;
UpdateText;
end;
end;
procedure TfDiaBoxMain.New;
var
I: Integer;
begin
Dialog.Clear;
for I := 0 to (SG.RowCount - 1) do
begin
SG.Cells[0, I] := '';
SG.Cells[1, I] := '';
SG.Cells[2, I] := '';
SG.Cells[3, I] := '';
SG.Cells[4, I] := '';
end;
SG.RowCount := 0;
CurrentFilename := '';
Saved := true;
UpdateText;
end;
function TfDiaBoxMain.Save: Boolean;
begin
if CurrentFilename <> '' then
begin
Dialog.SaveToFile(CurrentFilename);
result := true;
Saved := true;
end else
result := SaveAs;
UpdateText;
end;
function TfDiaBoxMain.SaveAs: Boolean;
begin
result := false;
if SaveDialog.Execute then
begin
CurrentFilename := ChangeFileExt(SaveDialog.FileName, '.dlg');
Dialog.SaveToFile(CurrentFilename);
Saved := true;
result := true;
end;
UpdateText;
end;
procedure TfDiaBoxMain.UpdateText;
var
S: string;
begin
if CurrentFilename <> '' then S := ExtractFileName(CurrentFilename) + ' - ';
Caption := S + 'DiaBox';
if (CurrentFilename = '') then Caption := '*.dlg - ' + Caption;
if not Saved then Caption := Caption + '*';
Application.Title := Caption;
end;
procedure TfDiaBoxMain.FormCreate(Sender: TObject);
begin
Dialog := TStringList.Create;
Application.OnHint := HintHandler;
New;
HintHandler(Sender);
end;
procedure TfDiaBoxMain.bNewClick(Sender: TObject);
begin
if CheckSaved then New;
end;
procedure TfDiaBoxMain.bSaveClick(Sender: TObject);
begin
Save;
end;
procedure TfDiaBoxMain.bOpenClick(Sender: TObject);
begin
Load;
end;
procedure TfDiaBoxMain.FormDestroy(Sender: TObject);
begin
Dialog.Free;
end;
procedure TfDiaBoxMain.HCSectionResize(HeaderControl: THeaderControl;
Section: THeaderSection);
begin
SG.ColWidths[Section.Index] := HC.Sections.Items[Section.Index].Width - SG.GridLineWidth;
end;
procedure TfDiaBoxMain.FormResize(Sender: TObject);
var
i: integer;
begin
SG.ColCount := HC.Sections.Count;
for i := 0 to HC.Sections.Count - 1 do
SG.ColWidths[i] := HC.Sections.Items[i].Width - SG.GridLineWidth;
end;
procedure TfDiaBoxMain.bSaveAsClick(Sender: TObject);
begin
SaveAs;
end;
procedure TfDiaBoxMain.HintHandler(Sender: TObject);
begin
Statusbar1.Panels[0].Text := Application.Hint;
if Saved then Statusbar1.Panels[1].Text := '' else Statusbar1.Panels[1].Text := 'Изменен';
Statusbar1.Panels[2].Text := 'Строк: ' + IntToStr(SG.RowCount);
end;
procedure TfDiaBoxMain.Edit;
var
P: TExplodeResult;
begin
if (SG.Row >= 0) then
with fDiaBoxEdit do
begin
Edit2.Visible := False;
if (SG.Cells[1, SG.Row] = 'PC') then RadioGroup1.ItemIndex := 0
else RadioGroup1.ItemIndex := 1;
Edit1.Text := SG.Cells[2, SG.Row];
//
ComboBox1.ItemIndex := 0;
P := Explode(string('/'), SG.Cells[3, SG.Row]);
if (P[0] = '-1') then ComboBox1.ItemIndex := 2
else if (P[0] <> '') then
begin
ComboBox1.ItemIndex := 1;
Edit2.Visible := True;
Edit2.Text := P[0];
end;
if (High(P) > 0) then Edit4.Text := P[1]
else Edit4.Text := '';
//
Edit3.Text := SG.Cells[4, SG.Row];
ShowModal;
end;
end;
procedure TfDiaBoxMain.SGDblClick(Sender: TObject);
begin
Edit;
end;
procedure TfDiaBoxMain.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose := CheckSaved;
end;
procedure TfDiaBoxMain.bAddLineClick(Sender: TObject);
begin
if (Dialog.Count - 1 >= SG.RowCount - 1) then
begin
SG.RowCount := SG.RowCount + 1;
Saved := False;
SG.SetFocus;
end;
SG.Row := SG.RowCount - 1;
Edit;
end;
procedure TfDiaBoxMain.bEditLineClick(Sender: TObject);
begin
Edit();
end;
procedure TfDiaBoxMain.N15Click(Sender: TObject);
begin
N15.Checked := not N15.Checked;
ToolBar1.Visible := N15.Checked;
end;
procedure TfDiaBoxMain.N16Click(Sender: TObject);
begin
N16.Checked := not N16.Checked;
StatusBar1.Visible := N16.Checked;
end;
procedure TfDiaBoxMain.bTestClick(Sender: TObject);
begin
with fDiaBoxTest do
begin
Level := 0;
Display;
ShowModal;
end;
end;
procedure TfDiaBoxMain.N18Click(Sender: TObject);
begin
Windows.MessageBox(0, PChar('DiaBox - pедактор диалогов HoD (C) 2013 - 2014, HoD Team'), PChar('О программе...'), 0)
end;
procedure TfDiaBoxMain.N4Click(Sender: TObject);
begin
Close;
end;
procedure TfDiaBoxMain.bDownClick(Sender: TObject);
begin
if (SG.Row >= 0)
and (SG.Row < SG.RowCount - 1) then Move(1);
end;
procedure TfDiaBoxMain.bUpClick(Sender: TObject);
begin
// Up
if (SG.Row <= SG.RowCount - 1)
and (SG.Row > 0) then Move(-1);
end;
procedure TfDiaBoxMain.Move(M: ShortInt);
const
C = 4;
var
I: Integer;
P: array [0..C] of string;
begin
for I := 0 to C do
begin
P[I] := SG.Cells[I, SG.Row];
SG.Cells[I, SG.Row] := SG.Cells[I, SG.Row + M];
SG.Cells[I, SG.Row + M] := P[I];
end;
SG.Row := SG.Row + M;
Saved := False;
UpdateText;
end;
end.
|
unit RadioGroupWordsPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\RadioGroupWordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "RadioGroupWordsPack" MUID: (54F58770000F)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, ExtCtrls
, tfwPropertyLike
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *54F58770000Fimpl_uses*
//#UC END# *54F58770000Fimpl_uses*
;
type
TkwPopRadioGroupItemIndex = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:RadioGroup:ItemIndex }
private
function ItemIndex(const aCtx: TtfwContext;
aRadioGroup: TRadioGroup): Integer;
{* Реализация слова скрипта pop:RadioGroup:ItemIndex }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopRadioGroupItemIndex
function TkwPopRadioGroupItemIndex.ItemIndex(const aCtx: TtfwContext;
aRadioGroup: TRadioGroup): Integer;
{* Реализация слова скрипта pop:RadioGroup:ItemIndex }
begin
Result := aRadioGroup.ItemIndex;
end;//TkwPopRadioGroupItemIndex.ItemIndex
class function TkwPopRadioGroupItemIndex.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:RadioGroup:ItemIndex';
end;//TkwPopRadioGroupItemIndex.GetWordNameForRegister
function TkwPopRadioGroupItemIndex.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwPopRadioGroupItemIndex.GetResultTypeInfo
function TkwPopRadioGroupItemIndex.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopRadioGroupItemIndex.GetAllParamsCount
function TkwPopRadioGroupItemIndex.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TRadioGroup)]);
end;//TkwPopRadioGroupItemIndex.ParamsTypes
procedure TkwPopRadioGroupItemIndex.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
var l_RadioGroup: TRadioGroup;
begin
try
l_RadioGroup := TRadioGroup(aCtx.rEngine.PopObjAs(TRadioGroup));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра RadioGroup: TRadioGroup : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
l_RadioGroup.ItemIndex := aValue.AsInt;
end;//TkwPopRadioGroupItemIndex.SetValuePrim
procedure TkwPopRadioGroupItemIndex.DoDoIt(const aCtx: TtfwContext);
var l_aRadioGroup: TRadioGroup;
begin
try
l_aRadioGroup := TRadioGroup(aCtx.rEngine.PopObjAs(TRadioGroup));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aRadioGroup: TRadioGroup : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(ItemIndex(aCtx, l_aRadioGroup));
end;//TkwPopRadioGroupItemIndex.DoDoIt
initialization
TkwPopRadioGroupItemIndex.RegisterInEngine;
{* Регистрация pop_RadioGroup_ItemIndex }
TtfwTypeRegistrator.RegisterType(TypeInfo(TRadioGroup));
{* Регистрация типа TRadioGroup }
TtfwTypeRegistrator.RegisterType(TypeInfo(Integer));
{* Регистрация типа Integer }
{$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
(*
JCore WebServices, Request Handler Classes
Copyright (C) 2015 Joao Morais
See the file LICENSE.txt, included in this distribution,
for details about the copyright.
This library 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.
*)
unit JCoreWSRequest;
{$I jcore.inc}
{$WARN 5024 OFF} // hint 'parameter not used'
interface
uses
Classes,
fgl,
HTTPDefs,
JCoreLogger,
JCoreWSIntf,
JCoreWSController;
type
{ TJCoreWSRequest }
TJCoreWSRequest = class helper for TRequest
public
function MatchNextPathInfoToken(const APattern: string): Boolean;
end;
{ TJCoreWSResponse }
TJCoreWSResponse = class helper for TResponse
protected
function StatusCode(const ACode: Integer): string;
public
procedure Send(const ACode: Integer; const AContent: string = ''; const AContentType: string = 'text/plain');
end;
{ TJCoreWSRequestHandlerItem }
TJCoreWSRequestHandlerItem = class(TObject)
private
FRequestHandler: IJCoreWSRequestHandler;
FPattern: string;
public
constructor Create(const ARequestHandler: IJCoreWSRequestHandler; const APattern: string);
property RequestHandler: IJCoreWSRequestHandler read FRequestHandler;
property Pattern: string read FPattern;
end;
TJCoreWSRequestHandlerList = specialize TFPGObjectList<TJCoreWSRequestHandlerItem>;
{ TJCoreWSAbstractRequestRouter }
TJCoreWSAbstractRequestRouter = class(TInterfacedObject, IJCoreWSRequestRouter)
private
class var FLogger: IJCoreLogger;
FHandlerList: TJCoreWSRequestHandlerList;
protected
function PatternMatch(const ARequest: TRequest; APattern: string): Boolean; virtual; abstract;
class property Logger: IJCoreLogger read FLogger;
public
destructor Destroy; override;
procedure AfterConstruction; override;
procedure AddRequestHandler(const ARequestHandler: IJCoreWSRequestHandler; const APattern: string);
procedure RouteRequest(const ARequest: TRequest; const AResponse: TResponse);
end;
{ TJCoreWSSimpleMatchRequestRouter }
TJCoreWSSimpleMatchRequestRouter = class(TJCoreWSAbstractRequestRouter)
protected
function PatternMatch(const ARequest: TRequest; APattern: string): Boolean; override;
end;
{ TJCoreWSRESTRequestRouter }
TJCoreWSRESTRequestRouter = class(TJCoreWSAbstractRequestRouter)
protected
function PatternMatch(const ARequest: TRequest; APattern: string): Boolean; override;
end;
{ TJCoreWSRESTRequestHandler }
TJCoreWSRESTRequestHandler = class(TInterfacedObject, IJCoreWSRequestHandler)
private
class var FDefaultInvokersRegistered: Boolean;
FControllers: TJCoreWSControllerClassList;
protected
function FindMethod(const AControllerURLFrag, AMethodURLFrag: string): TJCoreWSControllerMethod;
procedure HandleRequest(const ARequest: TRequest; const AResponse: TResponse);
procedure InternalRegisterDefaultInvokers; virtual;
public
destructor Destroy; override;
procedure AfterConstruction; override;
function AddController(const AControllerClass: TClass; const AControllerName: string = ''): TJCoreWSControllerClass;
end;
implementation
uses
sysutils,
JCoreUtils,
JCoreConsts,
JCoreDIC,
JCoreWSInvokers;
{ TJCoreWSRequest }
function TJCoreWSRequest.MatchNextPathInfoToken(const APattern: string): Boolean;
function ReadToken(var ARef: Integer; const AExpression: string): string;
var
VStarting: Integer;
begin
if ARef <= Length(AExpression) then
begin
while (ARef <= Length(AExpression)) and (AExpression[ARef] = '/') do
Inc(ARef);
VStarting := ARef;
while (ARef <= Length(AExpression)) and (AExpression[ARef] <> '/') do
Inc(ARef);
Result := Copy(AExpression, VStarting, ARef - VStarting);
end else
Result := '';
end;
var
VPatternRef, VPathInfoRef, I: Integer;
VPatternToken, VPathInfoToken, VPathInfo: string;
VQuery: TStrings;
begin
VPathInfo := PathInfo;
VPatternRef := 1;
VPathInfoRef := Length(ReturnedPathInfo) + 1;
VPatternToken := ReadToken(VPatternRef, APattern);
if VPatternToken <> '' then
VPathInfoToken := ReadToken(VPathInfoRef, VPathInfo)
else
VPathInfoToken := '';
VQuery := nil;
Result := False;
try
while (VPatternToken <> '') and (VPathInfoToken <> '') do
begin
if VPatternToken[1] = ':' then
begin
if not Assigned(VQuery) then
VQuery := TStringList.Create;
// adding two strings: key and value pair
VQuery.AddStrings([Copy(VPatternToken, 2, Length(VPatternToken)), VPathInfoToken]);
end else if VPatternToken <> VPathInfoToken then
Exit;
VPatternToken := ReadToken(VPatternRef, APattern);
if VPatternToken <> '' then
VPathInfoToken := ReadToken(VPathInfoRef, VPathInfo);
end;
Result := VPatternToken = '';
// only change the request object if the pattern matches
if Result then
begin
if Assigned(VQuery) then
for I := 0 to Pred(VQuery.Count div 2) do
QueryFields.Values[VQuery[2*I]] := VQuery[2*I+1];
ReturnedPathInfo := Copy(VPathInfo, 1, VPathInfoRef - 1);
end;
finally
FreeAndNil(VQuery);
end;
end;
{ TJCoreWSResponse }
function TJCoreWSResponse.StatusCode(const ACode: Integer): string;
begin
case ACode of
100: Result := 'Continue';
101: Result := 'Switching Protocols';
200: Result := 'OK';
201: Result := 'Created';
202: Result := 'Accepted';
203: Result := 'Non-Authoritative Information';
204: Result := 'No Content';
205: Result := 'Reset Content';
206: Result := 'Partial Content';
300: Result := 'Multiple Choices';
301: Result := 'Moved Permanently';
302: Result := 'Found';
303: Result := 'See Other';
304: Result := 'Not Modified';
305: Result := 'Use Proxy';
307: Result := 'Temporary Redirect';
400: Result := 'Bad Request';
401: Result := 'Unauthorized';
402: Result := 'Payment Required';
403: Result := 'Forbidden';
404: Result := 'Not Found';
405: Result := 'Method Not Allowed';
406: Result := 'Not Acceptable';
407: Result := 'Proxy Authentication Required';
408: Result := 'Request Time-out';
409: Result := 'Conflict';
410: Result := 'Gone';
411: Result := 'Length Required';
412: Result := 'Precondition Failed';
413: Result := 'Request Entity Too Large';
414: Result := 'Request-URI Too Large';
415: Result := 'Unsupported Media Type';
416: Result := 'Requested range not satisfiable';
417: Result := 'Expectation Failed';
500: Result := 'Internal Server Error';
501: Result := 'Not Implemented';
502: Result := 'Bad Gateway';
503: Result := 'Service Unavailable';
504: Result := 'Gateway Time-out';
505: Result := 'HTTP Version not supported';
else
Result := Format(JCoreFormatMessage(3602, S3602_UnknownStatus), [ACode]);
end;
end;
procedure TJCoreWSResponse.Send(const ACode: Integer; const AContent: string; const AContentType: string);
begin
Code := ACode;
CodeText := StatusCode(ACode);
Content := AContent;
ContentType := AContentType;
end;
{ TJCoreWSRequestHandlerItem }
constructor TJCoreWSRequestHandlerItem.Create(const ARequestHandler: IJCoreWSRequestHandler;
const APattern: string);
begin
inherited Create;
FRequestHandler := ARequestHandler;
FPattern := APattern;
end;
{ TJCoreWSAbstractRequestRouter }
destructor TJCoreWSAbstractRequestRouter.Destroy;
begin
FreeAndNil(FHandlerList);
inherited Destroy;
end;
procedure TJCoreWSAbstractRequestRouter.AfterConstruction;
var
VLogFactory: IJCoreLogFactory;
begin
inherited AfterConstruction;
if not Assigned(FLogger) then
begin
TJCoreDIC.Locate(IJCoreLogFactory, VLogFactory);
FLogger := VLogFactory.GetLogger('jcore.ws.request.router');
end;
end;
procedure TJCoreWSAbstractRequestRouter.AddRequestHandler(const ARequestHandler: IJCoreWSRequestHandler;
const APattern: string);
begin
if not Assigned(FHandlerList) then
FHandlerList := TJCoreWSRequestHandlerList.Create(True);
FHandlerList.Add(TJCoreWSRequestHandlerItem.Create(ARequestHandler, APattern));
end;
procedure TJCoreWSAbstractRequestRouter.RouteRequest(const ARequest: TRequest; const AResponse: TResponse);
var
I: Integer;
begin
try
if Assigned(FHandlerList) then
for I := 0 to Pred(FHandlerList.Count) do
if PatternMatch(ARequest, FHandlerList[I].Pattern) then
begin
FHandlerList[I].RequestHandler.HandleRequest(ARequest, AResponse);
Exit;
end;
AResponse.Send(404);
except
on E: Exception do
begin
Logger.Error('Internal server error', E);
AResponse.Send(500, JCoreFormatMessage(3601, S3601_InternalServerError500));
end;
end;
end;
{ TJCoreWSSimpleMatchRequestRouter }
function TJCoreWSSimpleMatchRequestRouter.PatternMatch(const ARequest: TRequest; APattern: string): Boolean;
var
VPatternLength, VPathLength, VPos, I: Integer;
VPathInfo: string;
begin
VPathInfo := ARequest.PathInfo;
if (VPathInfo <> '') and (VPathInfo[1] <> '/') and (APattern <> '') and (APattern[1] = '/') then
VPathInfo := '/' + VPathInfo;
Result := APattern = VPathInfo;
if Result then
Exit;
// Path+'*' should be greater than or equal Pattern
VPatternLength := Length(APattern);
VPathLength := Length(VPathInfo);
Result := VPathLength + 1 >= VPatternLength;
if not Result then
Exit;
// No '*', no match
VPos := Pos('*', APattern);
Result := VPos <> 0;
if not Result then
Exit;
// Matching before and after '*'
Result := False;
for I := 1 to Pred(VPos) do
if APattern[I] <> VPathInfo[I] then
Exit;
for I := VPatternLength downto Succ(VPos) do
if APattern[I] <> VPathInfo[VPathLength + I - VPatternLength] then
Exit;
Result := True;
end;
{ TJCoreWSRESTRequestRouter }
function TJCoreWSRESTRequestRouter.PatternMatch(const ARequest: TRequest; APattern: string): Boolean;
begin
Result := ARequest.MatchNextPathInfoToken(APattern);
end;
{ TJCoreWSRESTRequestHandler }
function TJCoreWSRESTRequestHandler.FindMethod(
const AControllerURLFrag, AMethodURLFrag: string): TJCoreWSControllerMethod;
var
I: Integer;
begin
for I := 0 to Pred(FControllers.Count) do
if FControllers[I].ControllerURLFrag = AControllerURLFrag then
begin
Result := FControllers[I].FindMethod(AMethodURLFrag);
Exit;
end;
Result := nil;
end;
procedure TJCoreWSRESTRequestHandler.HandleRequest(const ARequest: TRequest;
const AResponse: TResponse);
var
VMethod: TJCoreWSControllerMethod;
VControllerURLFrag: string;
VMethodURLFrag: string;
begin
if ARequest.MatchNextPathInfoToken(':' + SJCoreController) then
begin
VControllerURLFrag := ARequest.QueryFields.Values[SJCoreController];
if ARequest.MatchNextPathInfoToken(':' + SJCoreMethod) then
VMethodURLFrag := ARequest.QueryFields.Values[SJCoreMethod]
else
VMethodURLFrag := LowerCase(ARequest.Method);
VMethod := FindMethod(VControllerURLFrag, VMethodURLFrag);
end else
VMethod := nil;
if Assigned(VMethod) and ARequest.MatchNextPathInfoToken(VMethod.MethodPattern) and
(ARequest.PathInfo = ARequest.ReturnedPathInfo) then
begin
if VMethod.AcceptRequestMethod(ARequest.Method) then
VMethod.HandleRequest(ARequest, AResponse)
else
AResponse.Send(405,
Format(JCoreFormatMessage(3604, S3604_URLNotAllowed), [ARequest.PathInfo, ARequest.Method]));
end else
AResponse.Send(404, Format(JCoreFormatMessage(3603, S3603_URLNotFound), [ARequest.PathInfo]));
end;
procedure TJCoreWSRESTRequestHandler.InternalRegisterDefaultInvokers;
var
FMethodRegistry: IJCoreWSMethodRegistry;
begin
TJCoreDIC.Locate(IJCoreWSMethodRegistry, FMethodRegistry);
FMethodRegistry.AddInvoker([TJCoreWSProcObjectInvoker, TJCoreWSFncObjectInvoker]);
end;
destructor TJCoreWSRESTRequestHandler.Destroy;
begin
FreeAndNil(FControllers);
inherited Destroy;
end;
procedure TJCoreWSRESTRequestHandler.AfterConstruction;
begin
inherited AfterConstruction;
if not FDefaultInvokersRegistered then
begin
InternalRegisterDefaultInvokers;
FDefaultInvokersRegistered := True;
end;
end;
function TJCoreWSRESTRequestHandler.AddController(const AControllerClass: TClass;
const AControllerName: string): TJCoreWSControllerClass;
begin
if not Assigned(FControllers) then
FControllers := TJCoreWSControllerClassList.Create(True);
Result := TJCoreWSControllerClass.Create(AControllerClass, AControllerName);
FControllers.Add(Result);
end;
initialization
TJCoreDIC.LazyRegister(IJCoreWSRequestRouter, TJCoreWSRESTRequestRouter, jdsApplication);
finalization
TJCoreDIC.Unregister(IJCoreWSRequestRouter, TJCoreWSRESTRequestRouter);
end.
|
unit Should.Constraint.CoreMatchers;
interface
uses
System.SysUtils,
System.Rtti, System.TypInfo,
System.Generics.Defaults,
Should
;
function BeNil: TValueConstraintOp;
function BeTrue: TValueConstraintOp;
function BeEqualTo(expected: TValue): TValueConstraintOp;
function BeGraterThan(expected: TValue): TValueConstraintOp;
function BeGraterThanOrEqualTo(expected: TValue): TValueConstraintOp;
function BeLessThan(expected: TValue): TValueConstraintOp;
function BeLessThanOrEqualTo(expected: TValue): TValueConstraintOp;
type ExceptionClass = class of Exception;
function BeThrowenException(exType: ExceptionClass): TCallConstraintOp; overload;
function BeThrowenException(exType: ExceptionClass; const expectMsg: string): TCallConstraintOp; overload;
implementation
uses
StructureEnumeration
;
function ValueToString(const value: TValue): string;
begin
if value.Kind in [tkClass, tkRecord, tkInterface] then begin
Result := StructureToJson(value).ToString;
end
else begin
Result := value.ToString;
end;
end;
function BeNil: TValueConstraintOp;
begin
Result := TValueConstraintOp.Create(TDelegateValueConstraint.Create(
TValue.Empty,
procedure (actual, expected: TValue; negate: boolean; fieldName: string; var outEvalResult: TEvalResult)
begin
outEvalResult :=
TMaybeEvalResult.Create(
function: TEvalResult
begin
if (not (actual.Kind in [tkClass, tkInterface])) and (not actual.IsClass) then begin
Result.Status := TEvalResult.TEvalStatus.Fatal;
Result.Message := Format('A Pointer must be passed. [%s:%s]', [fieldName, 'actual']);
end
else begin
Result.Status := TEvalResult.TEvalStatus.Pass;
end;
end
)
.Next(
function: TEvalResult
var
n: string;
msg: string;
begin
Result.Status := TEvalResult.TEvalStatus.Pass;
if actual.IsEmpty = negate then begin
if negate then n:= '' else n:='not';
msg := Format('The actual value (%s) was %s nil.'#10#9'-actual: %s', [
fieldName, n, actual.ToString, expected.ToString
]);
Result.Status := TEvalResult.TEvalStatus.Falure;
Result.Message := msg;
end;
end
)
.Result
;
end
));
end;
function BeTrue: TValueConstraintOp;
begin
Result := TValueConstraintOp.Create(TDelegateValueConstraint.Create(
TValue.Empty,
procedure (actual, expected: TValue; negate: boolean; fieldName: string; var outEvalResult: TEvalResult)
begin
outEvalResult :=
TMaybeEvalResult.Create(
function: TEvalResult
begin
if not actual.IsType<boolean> then begin
Result.Status := TEvalResult.TEvalStatus.Fatal;
Result.Message := Format('A boolean value must be passed. [%s:%s]', [fieldName, 'actual']);
end
else begin
Result.Status := TEvalResult.TEvalStatus.Pass;
end;
end
)
.Next(
function: TEvalResult
var
n: string;
msg: string;
begin
Result.Status := TEvalResult.TEvalStatus.Pass;
if actual.AsType<boolean> = negate then begin
if negate then n:= '' else n:='not';
msg := Format('The actual value (%s) was %s true.', [
fieldName, n, actual.ToString, expected.ToString
]);
Result.Status := TEvalResult.TEvalStatus.Falure;
Result.Message := msg;
end;
end
)
.Result
;
end
));
end;
function BeEqualToInternal(actual, expected: TValue): boolean;
function CompareAsRecord(const actual, expected: TValue): boolean;
var
ctx: TRttiContext;
t: TRttiType;
fields: TArray<TRttiField>;
f: TRttiField;
same: boolean;
begin
if actual.TypeInfo <> expected.TypeInfo then Exit(false);
ctx := TRttiContext.Create;
try
t := ctx.GetType(actual.TypeInfo);
fields := t.AsRecord.GetDeclaredFields;
for f in fields do begin
same := BeEqualToInternal(
f.GetValue(actual.GetReferenceToRawData),
f.GetValue(expected.GetReferenceToRawData)
);
if not same then Exit(false);
end;
Result := true;
finally
ctx.Free;
end;
end;
function CompareAsObject(const actual, expected: TObject): boolean;
begin
if (not Assigned(actual)) and (not Assigned((expected))) then Exit(true);
if not Assigned(actual) then begin
expected.Equals(actual);
end
else begin
actual.Equals(expected);
end;
end;
function CompareAsArray(const actual, expected: TValue): boolean;
var
i, len: integer;
begin
len := actual.GetArrayLength;
if len <> expected.GetArrayLength then Exit(false);
for i := 0 to len-1 do begin
if not BeEqualToInternal(actual.GetArrayElement(i), expected.GetArrayElement(i)) then Exit(false);
end;
Result := true;
end;
begin
if actual.IsType<string> then begin
Result := (TStringComparer.Ordinal as IComparer<string>).Compare(actual.ToString, expected.ToString) = 0;
end
else if actual.IsObject then begin
Result := CompareAsObject(actual.AsObject, expected.AsObject);
end
else if actual.Kind = tkInterface then begin
Result := CompareAsObject(TObject(actual.AsInterface), TObject(expected.AsInterface));
end
else if actual.Kind = tkRecord then begin
Result := CompareAsRecord(actual, expected);
end
else if actual.Kind in [tkArray, tkDynArray] then begin
Result := CompareAsArray(actual, expected);
end
else begin
Result := TEqualityComparer<string>.Default.Equals(actual.ToString(), expected.ToString());
end;
end;
function BeEqualTo(expected: TValue): TValueConstraintOp;
begin
Result := TValueConstraintOp.Create(TDelegateValueConstraint.Create(
expected,
procedure (actual, expected: TValue; negate: boolean; fieldName: string; var outEvalResult: TEvalResult)
var
n: string;
msg: string;
begin
if BeEqualToInternal(actual, expected) = negate then begin
if negate then n:= '' else n:='not';
msg := Format('The actual value (%s) was %s equal to a expected value.'#10#9'-actual: %s'#10#9'-expected: %s', [
fieldName, n, ValueToString(actual), ValueToString(expected)
]);
outEvalResult.Status := TEvalResult.TEvalStatus.Falure;
outEvalResult.Message := msg;
end;
end
));
end;
function ValidateOrdinaryValue(val: TValue; comments: array of const): TEvalResult;
begin
if ((val.Kind in [tkClass, tkInterface]) or val.IsClass or val.IsArray or val.IsEmpty) then begin
Result.Status := TEvalResult.TEvalStatus.Fatal;
Result.Message := Format('Ordinary value must be passed. [%s:%s]', comments);
end
else begin
Result.Status := TEvalResult.TEvalStatus.Pass;
end;
end;
type
TEvaluateAsOrdinaryFunc = reference to function (compared: integer): TEvalResult;
function EvaluateAsOrdinary(actual, expected: TValue; fieldName: string; fn: TEvaluateAsOrdinaryFunc): TMaybeEvalResult;
begin
Result := TMaybeEvalResult.Create(ValidateOrdinaryValue(actual, [fieldName, 'actual']))
.Next(
function: TEvalResult
begin
Result := ValidateOrdinaryValue(expected, [fieldName, 'expected']);
end
)
.Next(
function: TEvalResult
var
n: integer;
begin
if actual.IsType<string> then begin
n := (TStringComparer.Ordinal as IComparer<string>).Compare(actual.AsType<string>, expected.AsType<string>);
end
else begin
n := TComparer<string>.Default.Compare(actual.ToString, expected.ToString);
end;
Result := fn(n);
end
)
;
end;
function BeGraterThan(expected: TValue): TValueConstraintOp;
begin
Result := TValueConstraintOp.Create(TDelegateValueConstraint.Create(
expected,
procedure (actual, expected: TValue; negate: boolean; fieldName: string; var outEvalResult: TEvalResult)
begin
outEvalResult :=
EvaluateAsOrdinary(actual, expected, fieldName,
function (compared: integer): TEvalResult
var
n: string;
msg: string;
begin
Result.Status := TEvalResult.TEvalStatus.Pass;
if (compared <= 0) or negate then begin
if negate then n:= '' else n:='not';
msg := Format('The actual value (%s) was %s grater than a expected value.'#10#9'-actual: %s'#10#9'-expected: %s', [
fieldName, n, actual.ToString, expected.ToString
]);
Result.Status := TEvalResult.TEvalStatus.Falure;
Result.Message := msg;
end;
end
)
.Result
;
end
));
end;
function BeGraterThanOrEqualTo(expected: TValue): TValueConstraintOp;
begin
Result := TValueConstraintOp.Create(TDelegateValueConstraint.Create(
expected,
procedure (actual, expected: TValue; negate: boolean; fieldName: string; var outEvalResult: TEvalResult)
begin
outEvalResult :=
EvaluateAsOrdinary(actual, expected, fieldName,
function (compared: integer): TEvalResult
var
n: string;
msg: string;
begin
Result.Status := TEvalResult.TEvalStatus.Pass;
if (compared >= 0) = negate then begin
if negate then n:= '' else n:='not';
msg := Format('The actual value (%s) was %s greater than or %s equal to a expected value.'#10#9'-actual: %s'#10#9'-expected: %s', [
fieldName, n, n, actual.ToString, expected.ToString
]);
Result.Status := TEvalResult.TEvalStatus.Falure;
Result.Message := msg;
end;
end
)
.Result
;
end
));
end;
function BeLessThan(expected: TValue): TValueConstraintOp;
begin
Result := TValueConstraintOp.Create(TDelegateValueConstraint.Create(
expected,
procedure (actual, expected: TValue; negate: boolean; fieldName: string; var outEvalResult: TEvalResult)
begin
outEvalResult :=
EvaluateAsOrdinary(actual, expected, fieldName,
function (compared: integer): TEvalResult
var
n: string;
msg: string;
begin
Result.Status := TEvalResult.TEvalStatus.Pass;
if (compared < 0) = negate then begin
if negate then n:= '' else n:='not';
msg := Format('The actual value (%s) was %s less than a expected value.'#10#9'-actual: %s'#10#9'-expected: %s', [
fieldName, n, actual.ToString, expected.ToString
]);
Result.Status := TEvalResult.TEvalStatus.Falure;
Result.Message := msg;
end;
end
)
.Result
;
end
));
end;
function BeLessThanOrEqualTo(expected: TValue): TValueConstraintOp;
begin
Result := TValueConstraintOp.Create(TDelegateValueConstraint.Create(
expected,
procedure (actual, expected: TValue; negate: boolean; fieldName: string; var outEvalResult: TEvalResult)
begin
outEvalResult :=
EvaluateAsOrdinary(actual, expected, fieldName,
function (compared: integer): TEvalResult
var
n: string;
msg: string;
begin
Result.Status := TEvalResult.TEvalStatus.Pass;
if (compared >= 0) = negate then begin
if negate then n:= '' else n:='not';
msg := Format('The actual value (%s) was %s less than or %s equal to a expected value.'#10#9'-actual: %s'#10#9'-expected: %s', [
fieldName, n, n, actual.ToString, expected.ToString
]);
Result.Status := TEvalResult.TEvalStatus.Falure;
Result.Message := msg;
end;
end
)
.Result
end
));
end;
function BeThrowenException(exType: ExceptionClass): TCallConstraintOp;
var
n: string;
msg: string;
begin
Result := TCallConstraintOp.Create(TDelegateCallConstraint.Create(
procedure (actual: TProc; negate: boolean; fieldName: string; var outEvalResult: TEvalResult)
var
actualEx, expectedEx: string;
begin
try
actual;
if negate then begin
outEvalResult.Status := TEvalResult.TEvalStatus.Pass;
Exit;
end;
msg := Format('This call (%s) must be thrown exception.', [fieldName]);
except
on ex: Exception do begin
if (ex is exType) = negate then begin
if negate then n:= '' else n:='not';
actualEx := TValue.From(ex).ToString;
expectedEx := TValue.From(exType).ToString;
msg := Format(
'This call (%s) was %s thrown specified exception. '#10#9'-actual: %s'#10#9'-expected: %s', [
fieldName, n, actualEx, expectedEx
]);
end
else begin
outEvalResult.Status := TEvalResult.TEvalStatus.Pass;
Exit;
end;
end;
end;
outEvalResult.Status := TEvalResult.TEvalStatus.Falure;
outEvalResult.Message := msg;
end
));
end;
function BeThrowenException(exType: ExceptionClass; const expectMsg: string): TCallConstraintOp;
var
n: string;
msg: string;
begin
Result := TCallConstraintOp.Create(TDelegateCallConstraint.Create(
procedure (actual: TProc; negate: boolean; fieldName: string; var outEvalResult: TEvalResult)
begin
try
actual;
if negate then begin
outEvalResult.Status := TEvalResult.TEvalStatus.Pass;
Exit;
end;
msg := Format('This call (%s) must be thrown exception.', [fieldName]);
except
on ex: Exception do begin
if ((ex is exType) = negate) and (ex.Message = expectMsg) then begin
if negate then n:= '' else n:='not';
msg := Format('This call (%s) was %s thrown specified exception. '#10#9'-expected: %s', [fieldName, n, TValue.From(exType).ToString]);
end
else begin
outEvalResult.Status := TEvalResult.TEvalStatus.Pass;
Exit;
end;
end;
end;
outEvalResult.Status := TEvalResult.TEvalStatus.Falure;
outEvalResult.Message := msg;
end
));
end;
end.
|
program pcopy;
{
Program: Pascal Copy Utility
Function: Yet another alternative to Windows copy, xcopy, and robocopy
Language: Free Pascal and Lazarus IDE
Copyright: Copyright (C) 2018 by James O. Dreher
License: https://opensource.org/licenses/MIT
Created: 8/10/2018
LazProject: project inspector, add lazUtils
Compiler Options, Config and Target, UNcheck win32 gui
Usage: pcopy /h
pcopy [-options|/options] [@list|source] target
Source file(s) copied to target file(s)
If target path doesn't exist, it is created.
c:\target is a file
c:\target\ is a folder
}
{$mode objfpc}{$H+}
uses
Classes, SysUtils, CustApp, FileUtil, LazFileUtils, StrUtils;
type
{ TMyApplication }
TMyApplication = class(TCustomApplication)
protected
procedure DoRun; override;
private
FOptAll : boolean;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
property OptAll: boolean read FOptAll write FOptAll;
procedure DoHelp;
function HasOpt(Opt: string): boolean;
function DoCopy(sPath, tPath: string): boolean;
function DoCopyList(aTextFile, aTargetDir: string): boolean;
function DoInstall: boolean;
function DoUnInstall: boolean;
end;
const
DS=DirectorySeparator;
LE=LineEnding;
{ TMyApplication }
{procedure DebugLn(aLine: string);
begin
Writeln('DEBUG: '+aLine)
end;
}
function RestoreAttributes(aFile: string; Attributes: LongInt): LongInt;
begin
Result:=FileSetAttrUTF8(aFile, Attributes);
end;
function RemoveAttributes(aFile: string; attrArray: Array of LongInt): LongInt;
var
i: integer;
attrSave: LongInt;
begin
attrSave:=FileGetAttrUTF8(aFile);
for i:=Low(attrArray) to High(attrArray) do begin
if (attrSave and attrArray[i])>0 then
FileSetAttrUTF8(aFile, attrSave-attrArray[i]);
end;
Result:=attrSave;
end;
function ChildPath(aPath: string): string;
begin
aPath:=ExpandFileName(ChompPathDelim(aPath));
Result:=Copy(aPath,aPath.LastIndexOf(DS)+2);
end;
function ParentPath(aPath: string): string;
begin
Result:=ExpandFileName(IncludeTrailingPathDelimiter(aPath) + '..');
end;
function JoinPath(aDir, aFile: string): string;
begin
Result:=CleanAndExpandDirectory(aDir)+Trim(aFile);
end;
function TMyApplication.DoInstall: boolean;
var
sPath, tPath: string;
begin
sPath:=ExeName;
tPath:=JoinPath(GetEnvironmentVariable('SystemRoot'),ExtractFilename(sPath));
if not FileUtil.CopyFile(sPath, tPath, [cffOverwriteFile]) then
Writeln('Error installing '+sPath+' - run as Admin')
else
Writeln('Success installing to '+tPath);
end;
function TMyApplication.DoUnInstall: boolean;
var
sPath, tPath: string;
begin
sPath:=ExeName;
tPath:=JoinPath(GetEnvironmentVariable('SystemRoot'),ExtractFilename(sPath));
if not SysUtils.FileExists(tPath) then
Writeln('Not installed')
else if not DeleteFileUTF8(tPath) then
Writeln('Error Un-installing '+sPath+' - run as Admin')
else
Writeln('Success Un-installing from '+sPath);
end;
function TMyApplication.DoCopyList(aTextFile, aTargetDir: string): boolean;
var
i: integer;
aList: TStringList;
aLine, sPath, tPath: String;
begin
i:=0;
aList:=TStringList.Create;
if ExtractFileExt(aTextFile)='' then
aTextFile:=aTextFile+'.txt';
if not FileExists(aTextFile) then begin
writeln('Error '+aTextFile+' does not exist');
Exit;
end;
aList.LoadFromFile(aTextFile);
for aLine in aList do begin
Inc(i);
if (not aLine.isEmpty) and (not aLine.StartsWith('//')) then begin
sPath:=Trim(ExtractWord(1,aLine,[',']));
tPath:=Trim(ExtractWord(2,aLine,[',']));
if aLine.StartsWith(',') or sPath.IsEmpty then begin
Writeln('Error in '+aTextFile+' line '+i.ToString+' no source file: ' + aLine);
Continue;
end;
if tPath.IsEmpty then
tPath:=aTargetDir;
if aLine.EndsWith(',') or tPath.IsEmpty then begin
Writeln('Error in '+aTextFile+' line '+i.ToString+' no target file: ' + aLine);
Continue;
end;
if not DoCopy(sPath,tPath) then
Writeln('Error copying '+sPath+' to '+tPath);
end;
end;
aList.Free;
end;
function TMyApplication.DoCopy(sPath, tPath: string): boolean;
var
i: integer;
src: TSearchRec;
sDir, tDir, sFile, tFile, fMask: String; //s=source, t=target
Flags: TCopyFileFlags;
ans: string;
sFileAttr, tFileAttr: LongInt;
aExt: string;
begin
Result:=false;
if ChildPath(sPath).Contains('*') or ChildPath(sPath).Contains('?') then begin
sDir:=ParentPath(sPath);
fMask:=ChildPath(sPath);
tDir:=tPath;
end else if FileExists(sPath) then begin
sDir:=ExtractFileDir(sPath);
fMask:=ExtractFileName(sPath);
tDir:=tPath;
end else begin
if DirectoryExists(sPath) then begin
sDir:=sPath;
fMask:=GetAllFilesMask;
tDir:=tPath;
end else begin
Writeln('Error path not found: '+sPath);
Terminate;
Exit;
end;
end;
if (fMask<>GetAllFilesMask) and
(not sPath.Contains('*')) and
(not sPath.Contains('?')) then
if not FileExists(sPath) then begin
writeln('Error file not found: '+sPath);
Terminate;
Exit;
end;
if FindFirst(JoinPath(sDir,fMask),faAnyFile,src)=0 then begin
repeat
if (src.Name<>'.') and (src.Name<>'..') and (src.Name<>'') then begin
sFile:=JoinPath(sDir,src.Name);
if ChildPath(tDir).Contains('*') then begin
if (ChildPath(tDir)='*.*') or (ChildPath(tDir)='*') then begin
tDir:=ParentPath(tDir);
tFile:=JoinPath(tDir, ExtractFileName(sFile))
end else if ChildPath(tDir).StartsWith('*.') then
tFile:=JoinPath(ParentPath(tDir), ExtractFileNameOnly(sFile)+ExtractFileExt(tDir))
else if ChildPath(tDir).EndsWith('.*') then
tFile:=JoinPath(ParentPath(tDir),ExtractFileNameOnly(tDir)+ExtractFileExt(sFile));
end else begin
if ExtractFileExt(tDir)='' then
tFile:=JoinPath(tDir,src.Name)
else begin
tFile:=tDir;
tDir:=ExtractFileDir(tFile);
end;
end;
if (src.Attr and faDirectory)>0 then begin
if HasOpt('S') then begin
if (not HasOpt('L')) and (not ForceDirectoriesUTF8(tDir)) then
writeln('Error creating directory: '+tDir);
if not DoCopy(sFile,tFile) then exit;
end;
end else begin
if (not HasOpt('L')) and (not ForceDirectoriesUTF8(tDir)) then
writeln('Error creating directory: '+tDir);
if HasOpt('L') then begin
ans:='N';
Writeln('Copy '+sFile+' to '+tFile);
end else if (HasOpt('Y') or optAll) then
ans:='Y'
else if FileExistsUTF8(tFile) then begin
write('Overwrite '+tFile+'? (Yes/[No]/All): ');
readln(ans);
ans:=UpperCase(ans);
if ans.IsEmpty then ans:='N';
if (ans='A') then optAll:=true;
end else
ans:='Y';
if not (ans='N') then begin
if HasOpt('A') then begin
sFileAttr:=FileGetAttrUTF8(sFile);
if FileExists(tFile) then
tFileAttr:=RemoveAttributes(tFile,[faHidden,faReadOnly]);
end;
if not HasOpt('Q') then writeln(sFile);
if HasOpt('Y') or (ans='Y') or optAll then
Flags:=[cffOverwriteFile]
else
Flags:=[];
if not FileUtil.CopyFile(sFile, tFile, Flags) then
Writeln('Error copying '+sFile)
else
if HasOpt('A') then RestoreAttributes(tFile, sFileAttr);
end;
end;
end;
until FindNext(src)<>0;
end;
if not (ans='N') and HasOpt('A') then FileSetAttrUTF8(tDir, FileGetAttrUTF8(sDir));
FindClose(src);
Result:=true;
end;
procedure TMyApplication.DoRun;
var
i: integer;
sPath: string='';
tPath: string='';
begin
if HasOpt('H') or HasOpt('?') then begin
DoHelp;
Terminate;
Exit;
end;
//TODO: Note the hard-coded version
if HasOpt('V') then begin
Writeln(LE+'Pascal Copy Utility (pcopy) version 1.0.0 '+
'Copyright (C) 2018 by Jim Dreher, released under the MIT license.');
Terminate;
Exit;
end;
if HasOpt('I') then begin
DoInstall;
Terminate;
Exit;
end;
if HasOpt('U') then begin
DoUninstall;
Terminate;
Exit;
end;
for i:=1 to ParamCount do begin
if not ParamStr(i).StartsWith('/') and not ParamStr(i).StartsWith('-') then
if sPath.IsEmpty then
sPath:=ParamStr(i)
else
if tPath.IsEmpty then
tPath:=ParamStr(i);
end;
if sPath.StartsWith('@') then begin
Delete(sPath,1,1);
DoCopyList(sPath,tPath);
Terminate;
Exit;
end;
if sPath.IsEmpty then begin
Writeln('Error no source path');
Terminate;
Exit;
end;
if tPath.IsEmpty then begin
Writeln('Error no target path');
Terminate;
Exit;
end;
if not DoCopy(sPath,tPath) then
{Writeln('Error copying '+sPath+' to '+tPath)};
Terminate;
Exit;
end;
procedure TMyApplication.DoHelp;
begin
writeln(LE+
' pcopy [-options|/options] [@list|source] target'+LE+LE+
' a Copy attributes. Default is Y.'+LE+
' h|? List options and how to use them.'+LE+
' i Install on PATH in C:\Windows (run as Admin).'+LE+
' l List files without copying.'+LE+
' q Don''t display filenames during copy.'+LE+
' s Search subdirectories.'+LE+
' u Uninstall from PATH in C:\Windows (run as Admin).'+LE+
' v Display version information.'+LE+
' y Overwrite an existing file.'+LE);
end;
function TMyApplication.HasOpt(Opt: string): boolean;
begin
Result:=false;
OptionChar:='-';
if HasOption(UpperCase(Opt)) or HasOption(LowerCase(Opt)) then Result:=true;
OptionChar:='/';
if HasOption(UpperCase(Opt)) or HasOption(LowerCase(Opt)) then Result:=true;
end;
constructor TMyApplication.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TMyApplication.Destroy;
begin
inherited Destroy;
end;
var
Application: TMyApplication;
{$R *.res}
begin
Application:=TMyApplication.Create(nil);
Application.Run;
Application.Free;
end.
|
unit VendorUnit;
interface
uses
REST.Json.Types, System.Generics.Collections, SysUtils,
JSONNullableAttributeUnit, GenericParametersUnit, NullableBasicTypesUnit,
EnumsUnit;
type
TVendorFeature = class(TGenericParameters)
private
[JSONName('id')]
[Nullable]
FId: NullableString;
[JSONName('name')]
[Nullable]
FName: NullableString;
[JSONName('slug')]
[Nullable]
FSlug: NullableString;
[JSONName('feature_group')]
[Nullable]
FFeatureGroup: NullableString;
public
constructor Create(); override;
property Id: NullableString read FId write FId;
property Name: NullableString read FName write FName;
property Slug: NullableString read FSlug write FSlug;
property FeatureGroup: NullableString read FFeatureGroup write FFeatureGroup;
end;
TVendorFeatureArray = TArray<TVendorFeature>;
TVendorCountry = class(TGenericParameters)
private
[JSONName('id')]
[Nullable]
FId: NullableString;
[JSONName('country_code')]
[Nullable]
FCode: NullableString;
[JSONName('country_name')]
[Nullable]
FName: NullableString;
public
constructor Create(); override;
property Id: NullableString read FId write FId;
property Name: NullableString read FName write FName;
property Code: NullableString read FCode write FCode;
end;
TVendorCountryArray = TArray<TVendorCountry>;
/// <summary>
/// Vendor
/// </summary>
TVendor = class(TGenericParameters)
private
[JSONName('id')]
[Nullable]
FId: NullableString;
[JSONName('name')]
[Nullable]
FName: NullableString;
[JSONName('title')]
[Nullable]
FTitle: NullableString;
[JSONName('slug')]
[Nullable]
FSlug: NullableString;
[JSONName('description')]
[Nullable]
FDescription: NullableString;
[JSONName('website_url')]
[Nullable]
FWebsiteUrl: NullableString;
[JSONName('logo_url')]
[Nullable]
FLogoUrl: NullableString;
[JSONName('api_docs_url')]
[Nullable]
FApiDocsUrl: NullableString;
[JSONName('is_integrated')]
[Nullable]
FIsIntegrated: NullableString;
[JSONName('size')]
[Nullable]
FSize: NullableString;
[JSONNameAttribute('features')]
[NullableArray(TVendorFeature)]
FFeatures: TVendorFeatureArray;
[JSONNameAttribute('countries')]
[NullableArray(TVendorCountry)]
FCountries: TVendorCountryArray;
function GetIsIntegrated: NullableBoolean;
procedure SetIsIntegrated(const Value: NullableBoolean);
function GetSize: TVendorSizeType;
procedure SetSize(const Value: TVendorSizeType);
public
/// <remarks>
/// Constructor with 0-arguments must be and be public.
/// For JSON-deserialization.
/// </remarks>
constructor Create; override;
destructor Destroy; override;
function Equals(Obj: TObject): Boolean; override;
/// <summary>
/// Vendor ID
/// </summary>
property Id: NullableString read FId write FId;
/// <summary>
/// Vendor name
/// </summary>
property Name: NullableString read FName write FName;
/// <summary>
/// Vendor title
/// </summary>
property Title: NullableString read FTitle write FTitle;
/// <summary>
/// Slug
/// </summary>
property Slug: NullableString read FSlug write FSlug;
/// <summary>
/// Description of a vendor
/// </summary>
property Description: NullableString read FDescription write FDescription;
/// <summary>
/// URL to a vendor's logo
/// </summary>
property LogoUrl: NullableString read FLogoUrl write FLogoUrl;
/// <summary>
/// Website URL of a vendor
/// </summary>
property WebsiteUrl: NullableString read FWebsiteUrl write FWebsiteUrl;
/// <summary>
/// URL to a vendor's API documentation.
/// </summary>
property ApiDocsUrl: NullableString read FApiDocsUrl write FApiDocsUrl;
/// <summary>
/// If True, the vendor is integrated in the Route4Me system.
/// </summary>
property IsIntegrated: NullableBoolean read GetIsIntegrated write SetIsIntegrated;
/// <summary>
/// Filter vendors by size. Accepted values: global, regional, local.
/// </summary>
property Size: TVendorSizeType read GetSize write SetSize;
property Features: TVendorFeatureArray read FFeatures;
property Countries: TVendorCountryArray read FCountries;
end;
TVendorArray = TArray<TVendor>;
TVendorList = TObjectList<TVendor>;
implementation
{ TVendor }
constructor TVendor.Create;
begin
Inherited;
FId := NullableString.Null;
FName := NullableString.Null;
FTitle := NullableString.Null;
FSlug := NullableString.Null;
FDescription := NullableString.Null;
FLogoUrl := NullableString.Null;
FWebsiteUrl := NullableString.Null;
FApiDocsUrl := NullableString.Null;
FIsIntegrated := NullableString.Null;
FSize := NullableString.Null;
SetLength(FFeatures, 0);
SetLength(FCountries, 0);
end;
destructor TVendor.Destroy;
var
i: Integer;
begin
for i := High(FFeatures) downto 0 do
FreeAndNil(FFeatures[i]);
Finalize(FFeatures);
for i := High(FCountries) downto 0 do
FreeAndNil(FCountries[i]);
Finalize(FCountries);
inherited;
end;
function TVendor.Equals(Obj: TObject): Boolean;
var
Other: TVendor;
begin
Result := False;
if not (Obj is TVendor) then
Exit;
Other := TVendor(Obj);
Result :=
(FId = Other.FId) and
(FName = Other.FName) and
(FTitle = Other.FTitle) and
(FSlug = Other.FSlug) and
(FDescription = Other.FDescription) and
(FLogoUrl = Other.FLogoUrl) and
(FWebsiteUrl = Other.FWebsiteUrl) and
(FApiDocsUrl = Other.FApiDocsUrl) and
(FSize = Other.FSize) and
(FIsIntegrated = Other.FIsIntegrated);
end;
function TVendor.GetIsIntegrated: NullableBoolean;
begin
if (FIsIntegrated.IsNull) then
Result := NullableBoolean.Null
else
Result := (FIsIntegrated.Value = '1');
end;
function TVendor.GetSize: TVendorSizeType;
var
Size: TVendorSizeType;
begin
Result := TVendorSizeType.vsGlobal;
if FSize.IsNotNull then
for Size := Low(TVendorSizeType) to High(TVendorSizeType) do
if (FSize = TVendorSizeTypeDescription[Size]) then
Exit(Size);
end;
procedure TVendor.SetIsIntegrated(const Value: NullableBoolean);
begin
if Value.IsNull then
FIsIntegrated := NullableString.Null
else
if Value.Value then
FIsIntegrated := '1'
else
FIsIntegrated := '0';
end;
procedure TVendor.SetSize(const Value: TVendorSizeType);
begin
FSize := TVendorSizeTypeDescription[Value];
end;
{ TVendorFeature }
constructor TVendorFeature.Create;
begin
inherited;
FId := NullableString.Null;
FName := NullableString.Null;
FSlug := NullableString.Null;
FFeatureGroup := NullableString.Null;
end;
{ TVendorCountry }
constructor TVendorCountry.Create;
begin
inherited;
FId := NullableString.Null;
FName := NullableString.Null;
FCode := NullableString.Null;
end;
end.
|
// Original Author: Piotr Likus
// Replace Components data storage objects
unit GX_ReplaceCompData;
interface
uses
Classes, SysUtils, Contnrs,
OmniXML,
Gx_GenericClasses;
const
// Default values for mapping flags
CompRepDefDisabled = False;
CompRepDefBiDirEnabled = True;
CompRepDefUseConstValue = False;
CompRepDefLogValuesEnabled = False;
CompRepDefLogOnlyDefValuesEnabled = False;
type
TCompRepMapList = class;
TCompRepMapItem = class;
TCompRepMapGroupItem = class
private
FName: string;
FItems: TCompRepMapList;
public
constructor Create;
destructor Destroy; override;
function Add(const SourceClassName, DestClassName: string;
const SourcePropName, DestPropName: string;
DisabledFlag, BiDirFlag: Boolean;
UseConstValue: Boolean; const ConstValue: string;
LogValuesEnabled: Boolean;
LogOnlyDefValuesEnabled: Boolean): TCompRepMapItem;
procedure AddItem(Item: TCompRepMapItem);
procedure ExtractItem(Item: TCompRepMapItem);
property Name: string read FName write FName;
property Items: TCompRepMapList read FItems;
end;
TCompRepMapGroupList = class(TGxObjectDictionary)
private
function GetItem(Index: Integer): TCompRepMapGroupItem;
public
function Add(const MapGroupName: string): TCompRepMapGroupItem;
property Items[Index: Integer]: TCompRepMapGroupItem read GetItem; default;
end;
TCompRepMapItem = class
private
FBiDirEnabled: Boolean;
FDisabled: Boolean;
FDestClassName: string;
FDestPropName: string;
FSourceClassName: string;
FSourcePropName: string;
FGroup: TCompRepMapGroupItem;
FUseConstValue: Boolean;
FLogOnlyDefValuesEnabled: Boolean;
FLogValuesEnabled: Boolean;
FConstValue: string;
function GetGroupName: string;
procedure SetGroup(const Value: TCompRepMapGroupItem);
function GetDestText: string;
function GetSourceText: string;
function GetIndex: Integer;
function GetDestCorePropName: string;
function GetSourceCorePropName: string;
public
constructor Create;
procedure Reverse;
procedure AssignMapping(ASource: TCompRepMapItem); virtual;
function ExtractCorePropName(const AName: string): string;
property Group: TCompRepMapGroupItem read FGroup write SetGroup;
property GroupName: string read GetGroupName;
property Disabled: Boolean read FDisabled write FDisabled;
property BiDirEnabled: Boolean read FBiDirEnabled write FBiDirEnabled;
property SourceClassName: string read FSourceClassName write FSourceClassName;
property SourcePropName: string read FSourcePropName write FSourcePropName;
property DestClassName: string read FDestClassName write FDestClassName;
property DestPropName: string read FDestPropName write FDestPropName;
property UseConstValue: Boolean read FUseConstValue write FUseConstValue;
property ConstValue: string read FConstValue write FConstValue;
property LogValuesEnabled: Boolean read FLogValuesEnabled write FLogValuesEnabled;
property LogOnlyDefValuesEnabled: Boolean read FLogOnlyDefValuesEnabled write FLogOnlyDefValuesEnabled;
property SourceText: string read GetSourceText;
property SourceCorePropName: string read GetSourceCorePropName;
property DestText: string read GetDestText;
property DestCorePropName: string read GetDestCorePropName;
property Index: Integer read GetIndex;
end;
TCompRepMapList = class(TObjectList)
private
function GetItem(Index: Integer): TCompRepMapItem;
public
property Items[Index: Integer]: TCompRepMapItem read GetItem; default;
end;
TReplaceCompData = class
private
FRootConfigurationKey: string;
function GetXmlFileName: string;
procedure LoadError(const E: Exception);
procedure LoadMapGroup(const Doc: IXMLDocument; const MapGroupNode: IXMLNode);
function GetNodeProperty(const ANode: IXMLNode; const APropName: string; const ADefaultValue: string = ''): string;
function AddMapGroup(const MapGroupName: string): TCompRepMapGroupItem;
procedure LoadMapItem(const MapItemNode: IXMLNode; MapGroup: TCompRepMapGroupItem);
procedure SaveMapGroup(const Doc: IXMLDocument; const MapGroupNode: IXMLNode; MapGroupItem: TCompRepMapGroupItem);
function GetNodeAttrib(const ANode: IXMLNode; const APropName: string; const ADefaultValue: string = ''): string;
function GetNodeBoolProperty(const ANode: IXMLNode; const APropName: string; ADefaultValue: Boolean): Boolean;
procedure LoadDefaultPropertyMaps;
protected
FMapGroupList: TCompRepMapGroupList;
public
constructor Create;
destructor Destroy; override;
procedure SaveData;
procedure ReloadData;
procedure AppendFrom(const FileName: string);
procedure SaveTo(const FileName: string; GroupNames: TStringList = nil);
function PrepareMapGroup(const MapGroupName: string): TCompRepMapGroupItem;
property MapGroupList: TCompRepMapGroupList read FMapGroupList;
property RootConfigurationKey: string read FRootConfigurationKey write FRootConfigurationKey;
end;
TCompRepEvent = class
public
FileName: string;
SourceClassName: string;
DestClassName: string;
StackText: string;
ObjectSearchName: string;
ComponentName: string;
ObjectClass: string;
When: TDateTime;
Text: string;
ErrorClass: string;
Context: string;
function IsError: Boolean;
function ObjectText: string;
function FlatText: string;
function FormatEventAsText(const ATemplate: string): string;
function EventType: string;
end;
TCompRepEventList = class(TObjectList)
private
function GetItem(Index: Integer): TCompRepEvent;
procedure SaveLogEvent(const Doc: IXMLDocument; const ItemNode: IXMLNode; Event: TCompRepEvent);
public
procedure SaveAsXML(const AFileName: string; SelectedList: TList);
property Items[Index: Integer]: TCompRepEvent read GetItem; default;
end;
TDefaultMap = record
SourceClass: string;
DestClass: string;
SourceProp: string;
DestProp: string;
Disabled: Boolean;
BiDi: Boolean;
UseConst: Boolean;
ConstValue: string;
end;
const
DefaultMaps: packed array[0..6] of TDefaultMap = (
(
SourceClass: 'TEdit';
DestClass: 'TMemo';
SourceProp: 'Text';
DestProp: 'Lines';
Disabled: False;
BiDi: True;
UseConst: False;
ConstValue: '';
),
(
SourceClass: 'TStringGrid';
DestClass: 'TListView';
SourceProp: '';
DestProp: 'ViewStyle';
Disabled: False;
BiDi: False;
UseConst: True;
ConstValue: 'vsReport';
),
(
SourceClass: 'TGroupBox';
DestClass: 'TPanel';
SourceProp: '';
DestProp: 'Caption';
Disabled: False;
BiDi: False;
UseConst: True;
ConstValue: '';
),
(
SourceClass: 'TDBText';
DestClass: 'TDBEdit';
SourceProp: '';
DestProp: 'BorderStyle';
Disabled: False;
BiDi: False;
UseConst: True;
ConstValue: 'bsNone';
),
(
SourceClass: 'TDBText';
DestClass: 'TDBEdit';
SourceProp: '';
DestProp: 'ReadOnly';
Disabled: False;
BiDi: False;
UseConst: True;
ConstValue: 'True';
),
(
SourceClass: 'TDBText';
DestClass: 'TDBEdit';
SourceProp: '';
DestProp: 'TabStop';
Disabled: False;
BiDi: False;
UseConst: True;
ConstValue: 'False';
),
(
SourceClass: 'TButton';
DestClass: 'TBitBtn';
SourceProp: 'Style';
DestProp: 'Style';
Disabled: True;
BiDi: True;
UseConst: False;
ConstValue: '';
)
);
procedure AddNodeProperty(const Doc: IXMLDocument; const Node: IXMLNode; const PropName, Value: string);
implementation
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
GX_GenericUtils, GX_ConfigurationInfo, GX_XmlUtils, GX_ReplaceCompUtils;
const // Do not localize any of the strings in this const section:
cXmlNodeRoot = 'ReplaceCompMapping';
cXmlNodeMapGroup = 'MapGroup';
cXmlNodeMapItem = 'MapItem';
cXmlNodeMapGrpName = 'Name';
cXmlNodeMapItemSrcClassName = 'SourceClassName';
cXmlNodeMapItemSrcPropName = 'SourcePropName';
cXmlNodeMapItemDestClassName = 'DestClassName';
cXmlNodeMapItemDestPropName = 'DestPropName';
cXmlNodeMapItemDisabled = 'Disabled';
cXmlNodeMapItemBiDirEnabled = 'BiDirEnabled';
cXmlNodeMapItemUseConstValue = 'UseConstValue';
cXmlNodeMapItemConstValue = 'ConstValue';
cXmlNodeMapItemLogValuesEnabled = 'LogValuesEnabled';
cXmlNodeMapItemLogOnlyDefValuesEnabled = 'LogOnlyDefValuesEnabled';
cXmlPropValueBool: array[Boolean] of string = ('false', 'true');
cXmlNodeLogRoot = 'LogEventList';
cXmlNodeLogEvent = 'LogEvent';
cXmlNodeEventWhen = 'When';
cXmlNodeEventType = 'EventType';
cXmlNodeEventText = 'Text';
cXmlNodeEventErrorClass = 'ErrorClass';
cXmlNodeEventContext = 'Context';
cXmlNodeEventObjSearchName = 'ObjectSearchName';
cXmlNodeEventObjClassName = 'ObjectClassName';
cXmlNodeEventComponentName = 'ComponentName';
cXmlNodeEventChildStack = 'ChildStack';
cXmlNodeEventFileName = 'FileName';
cXmlNodeEventSourceClassName = 'SourceClassName';
cXmlNodeEventDestClassName = 'DestClassName';
type
EReplaceCompError = class(Exception);
procedure AddNodeProperty(const Doc: IXMLDocument; const Node: IXMLNode; const PropName, Value: string);
var
ChildNode: IXMLNode;
begin
ChildNode := Doc.CreateElement(PropName);
Node.AppendChild(ChildNode);
ChildNode.Text := Value;
end;
{ TCompRepMapGroupItem }
constructor TCompRepMapGroupItem.Create;
begin
inherited Create;
FItems := TCompRepMapList.Create;
end;
destructor TCompRepMapGroupItem.Destroy;
begin
FreeAndNil(FItems);
inherited;
end;
procedure TCompRepMapGroupItem.AddItem(Item: TCompRepMapItem);
begin
if FItems.IndexOf(Item)<0 then
FItems.Add(Item);
end;
procedure TCompRepMapGroupItem.ExtractItem(Item: TCompRepMapItem);
begin
FItems.Extract(Item);
end;
function TCompRepMapGroupItem.Add(const SourceClassName, DestClassName,
SourcePropName, DestPropName: string; DisabledFlag, BiDirFlag: Boolean;
UseConstValue: Boolean; const ConstValue: string; LogValuesEnabled: Boolean;
LogOnlyDefValuesEnabled: Boolean): TCompRepMapItem;
begin
Result := TCompRepMapItem.Create;
Result.SourceClassName := SourceClassName;
Result.DestClassName := DestClassName;
Result.SourcePropName := SourcePropName;
Result.DestPropName := DestPropName;
Result.Disabled := DisabledFlag;
Result.BiDirEnabled := BiDirFlag;
Result.UseConstValue := UseConstValue;
Result.ConstValue := ConstValue;
Result.LogValuesEnabled := LogValuesEnabled;
Result.LogOnlyDefValuesEnabled := LogOnlyDefValuesEnabled;
FItems.Add(Result);
Result.Group := Self;
end;
{ TCompRepMapList }
function TCompRepMapList.GetItem(Index: Integer): TCompRepMapItem;
begin
Result := (inherited Items[Index]) as TCompRepMapItem;
end;
{ TCompRepMapGroupList }
function TCompRepMapGroupList.Add(const MapGroupName: string): TCompRepMapGroupItem;
begin
Result := TCompRepMapGroupItem.Create;
Result.Name := MapGroupName;
AddWithCode(MapGroupName, Result);
end;
function TCompRepMapGroupList.GetItem(
Index: Integer): TCompRepMapGroupItem;
begin
Result := (inherited Items[Index]) as TCompRepMapGroupItem;
end;
{ TReplaceCompData }
constructor TReplaceCompData.Create;
begin
inherited Create;
FMapGroupList := TCompRepMapGroupList.Create;
end;
destructor TReplaceCompData.Destroy;
begin
FreeAndNil(FMapGroupList);
inherited;
end;
function TReplaceCompData.GetXmlFileName: string;
begin
Result := AddSlash(ConfigInfo.ConfigPath) + 'ReplaceComponents.xml'
end;
procedure TReplaceCompData.LoadError(const E: Exception);
resourcestring
SLoadError = 'Error while loading %s' + sLineBreak;
begin
GxLogAndShowException(E, Format(SLoadError, [GetXmlFileName]));
end;
procedure TReplaceCompData.AppendFrom(const FileName: string);
var
Doc: IXMLDocument;
MapGroupNodes: IXMLNodeList;
MapGroupNode: IXMLNode;
i: Integer;
begin
Doc := CreateXMLDoc;
Doc.Load(FileName);
MapGroupNodes := Doc.DocumentElement.SelectNodes(cXmlNodeMapGroup);
{$IFOPT D+} SendDebug(Format('ReplaceComp - %d groups found', [MapGroupNodes.Length])); {$ENDIF}
for i := 0 to MapGroupNodes.Length - 1 do
begin
MapGroupNode := MapGroupNodes.Item[i];
try
LoadMapGroup(Doc, MapGroupNode);
except
on e: EReplaceCompError do
LoadError(e);
on e: EConvertError do
LoadError(e);
end;
end;
end;
procedure TReplaceCompData.ReloadData;
var
FileName: string;
begin
FileName := GetXmlFileName;
if not FileExists(FileName) then
begin
{$IFOPT D+} SendDebug('ReplaceComp map file not found: ' + FileName); {$ENDIF}
LoadDefaultPropertyMaps;
end
else
begin
{$IFOPT D+} SendDebug('ReplaceComp map file found: ' + FileName); {$ENDIF}
FMapGroupList.Clear;
AppendFrom(FileName);
end;
end;
function TReplaceCompData.GetNodeProperty(const ANode: IXMLNode;
const APropName: string; const ADefaultValue: string): string;
var
ChildNode: IXMLNode;
begin
ChildNode := ANode.SelectSingleNode(APropName);
if Assigned(ChildNode) then
Result := ChildNode.Text
else
Result := ADefaultValue;
end;
function TReplaceCompData.GetNodeBoolProperty(const ANode: IXMLNode;
const APropName: string; ADefaultValue: Boolean): Boolean;
var
StrValue: string;
begin
StrValue := GetNodeProperty(ANode, APropName,
cXmlPropValueBool[ADefaultValue]);
Result := (StrValue = cXmlPropValueBool[True]);
end;
function TReplaceCompData.GetNodeAttrib(const ANode: IXMLNode;
const APropName: string; const ADefaultValue: string): string;
var
ChildNode: IXMLNode;
begin
ChildNode := ANode.Attributes.GetNamedItem(APropName);
if Assigned(ChildNode) then
Result := ChildNode.Text
else
Result := ADefaultValue;
end;
function TReplaceCompData.AddMapGroup(
const MapGroupName: string): TCompRepMapGroupItem;
begin
Result := FMapGroupList.Add(MapGroupName);
end;
function TReplaceCompData.PrepareMapGroup(const MapGroupName: string): TCompRepMapGroupItem;
begin
Result := (FMapGroupList.FindObject(MapGroupName) as TCompRepMapGroupItem);
if Result = nil then
Result := AddMapGroup(MapGroupName);
end;
procedure TReplaceCompData.LoadMapItem(const MapItemNode: IXMLNode; MapGroup: TCompRepMapGroupItem);
var
SourceClassName, DestClassName, SourcePropName, DestPropName: string;
DisabledFlag: Boolean;
BiDirFlag: Boolean;
UseConstValue, LogValuesEnabled, LogOnlyDefValuesEnabled: Boolean;
ConstValue: string;
begin
try
Assert(MapItemNode.NodeType = ELEMENT_NODE);
Assert(MapItemNode.NodeName = cXmlNodeMapItem);
Assert(MapGroup <> nil);
SourceClassName := GetNodeProperty(MapItemNode, cXmlNodeMapItemSrcClassName);
DestClassName := GetNodeProperty(MapItemNode, cXmlNodeMapItemDestClassName);
SourcePropName := GetNodeProperty(MapItemNode, cXmlNodeMapItemSrcPropName);
DestPropName := GetNodeProperty(MapItemNode, cXmlNodeMapItemDestPropName);
DisabledFlag := GetNodeBoolProperty(MapItemNode, cXmlNodeMapItemDisabled, CompRepDefDisabled);
BiDirFlag := GetNodeBoolProperty(MapItemNode, cXmlNodeMapItemBiDirEnabled, CompRepDefBiDirEnabled);
UseConstValue := GetNodeBoolProperty(MapItemNode, cXmlNodeMapItemUseConstValue, CompRepDefUseConstValue);
ConstValue := GetNodeProperty(MapItemNode, cXmlNodeMapItemConstValue);
LogValuesEnabled := GetNodeBoolProperty(MapItemNode, cXmlNodeMapItemLogValuesEnabled, CompRepDefLogValuesEnabled);
LogOnlyDefValuesEnabled := GetNodeBoolProperty(MapItemNode, cXmlNodeMapItemLogOnlyDefValuesEnabled, CompRepDefLogOnlyDefValuesEnabled);
MapGroup.Add(SourceClassName, DestClassName, SourcePropName, DestPropName,
DisabledFlag, BiDirFlag, UseConstValue, ConstValue, LogValuesEnabled,
LogOnlyDefValuesEnabled);
except
on e: EReplaceCompError do
LoadError(e);
on e: EConvertError do
LoadError(e);
end;
end;
procedure TReplaceCompData.LoadMapGroup(const Doc: IXMLDocument; const MapGroupNode: IXMLNode);
var
MapItemNodes: IXMLNodeList;
MapItemNode: IXMLNode;
i: Integer;
MapGroup: TCompRepMapGroupItem;
GroupName: string;
begin
GroupName := GetNodeAttrib(MapGroupNode, cXmlNodeMapGrpName);
{$IFOPT D+} SendDebug('Map Group name = '+GroupName); {$ENDIF}
MapGroup := PrepareMapGroup(GroupName);
{$IFOPT D+} SendDebug('Map Assigned Group name = '+MapGroup.Name); {$ENDIF}
MapItemNodes := MapGroupNode.SelectNodes(cXmlNodeMapItem);
for i := 0 to MapItemNodes.Length - 1 do
begin
MapItemNode := MapItemNodes.Item[i];
LoadMapItem(MapItemNode, MapGroup);
end;
end;
procedure TReplaceCompData.SaveMapGroup(const Doc: IXMLDocument;
const MapGroupNode: IXMLNode; MapGroupItem: TCompRepMapGroupItem);
var
i: Integer;
MapItem: TCompRepMapItem;
MapItemNode: IXMLElement;
begin
for i := 0 to MapGroupItem.Items.Count - 1 do
begin
MapItem := MapGroupItem.Items[i];
MapItemNode := Doc.CreateElement(cXmlNodeMapItem);
MapGroupNode.AppendChild(MapItemNode);
AddNodeProperty(Doc, MapItemNode, cXmlNodeMapItemSrcClassName, MapItem.SourceClassName);
AddNodeProperty(Doc, MapItemNode, cXmlNodeMapItemDestClassName, MapItem.DestClassName);
AddNodeProperty(Doc, MapItemNode, cXmlNodeMapItemSrcPropName, MapItem.SourcePropName);
AddNodeProperty(Doc, MapItemNode, cXmlNodeMapItemDestPropName, MapItem.DestPropName);
if MapItem.Disabled <> CompRepDefDisabled then
AddNodeProperty(Doc, MapItemNode, cXmlNodeMapItemDisabled, cXmlPropValueBool[MapItem.Disabled]);
if MapItem.BiDirEnabled <> CompRepDefBiDirEnabled then
AddNodeProperty(Doc, MapItemNode, cXmlNodeMapItemBiDirEnabled, cXmlPropValueBool[MapItem.BiDirEnabled]);
if MapItem.UseConstValue <> CompRepDefUseConstValue then
AddNodeProperty(Doc, MapItemNode, cXmlNodeMapItemUseConstValue, cXmlPropValueBool[MapItem.UseConstValue]);
if MapItem.ConstValue <> '' then
AddNodeProperty(Doc, MapItemNode, cXmlNodeMapItemConstValue, MapItem.ConstValue);
if MapItem.LogValuesEnabled <> CompRepDefLogValuesEnabled then
AddNodeProperty(Doc, MapItemNode, cXmlNodeMapItemLogValuesEnabled, cXmlPropValueBool[MapItem.LogValuesEnabled]);
if MapItem.LogOnlyDefValuesEnabled <> CompRepDefLogOnlyDefValuesEnabled then
AddNodeProperty(Doc, MapItemNode, cXmlNodeMapItemLogOnlyDefValuesEnabled, cXmlPropValueBool[MapItem.LogOnlyDefValuesEnabled]);
end;
end;
procedure TReplaceCompData.SaveTo(const FileName: string; GroupNames: TStringList);
var
Doc: IXMLDocument;
RootNode, MapGroupNode: IXMLElement;
i: Integer;
begin
Doc := CreateXMLDoc;
AddXMLHeader(Doc);
RootNode := Doc.CreateElement(cXmlNodeRoot);
Doc.DocumentElement := RootNode;
for i := 0 to FMapGroupList.Count-1 do
begin
if Assigned(GroupNames) and (GroupNames.IndexOf(FMapGroupList[i].Name) < 0) then
Continue;
MapGroupNode := Doc.CreateElement(cXmlNodeMapGroup);
MapGroupNode.SetAttribute(cXmlNodeMapGrpName, FMapGroupList[i].Name);
RootNode.AppendChild(MapGroupNode);
SaveMapGroup(Doc, MapGroupNode, FMapGroupList[i]);
end;
Doc.Save(FileName, ofIndent);
end;
procedure TReplaceCompData.SaveData;
begin
SaveTo(GetXmlFileName);
end;
procedure TReplaceCompData.LoadDefaultPropertyMaps;
const
DefaultGroupName = 'Default VCL Mappings';
var
i: Integer;
MapGroup: TCompRepMapGroupItem;
DM: TDefaultMap;
begin
MapGroup := FMapGroupList.Add(DefaultGroupName);
for i := Low(DefaultMaps) to High(DefaultMaps) do
begin
DM := DefaultMaps[i];
MapGroup.Add(DM.SourceClass, DM.DestClass, DM.SourceProp, DM.DestProp,
DM.Disabled, DM.BiDi, DM.UseConst, DM.ConstValue, False, False);
end;
end;
{ TCompRepMapItem }
function TCompRepMapItem.GetGroupName: string;
begin
if Assigned(FGroup) then
Result := FGroup.Name
else
Result := '';
end;
function TCompRepMapItem.GetDestText: string;
begin
if Trim(FDestPropName)='' then
Result := FDestClassName
else
Result := FDestClassName + '.' + FDestPropName;
end;
function TCompRepMapItem.GetSourceText: string;
resourcestring
SConst = 'const';
begin
if Trim(FSourcePropName)='' then
begin
if UseConstValue then
Result := FSourceClassName + ' / ' + SConst + ' ' + FConstValue
else
Result := FSourceClassName;
end
else
Result := FSourceClassName + '.' + FSourcePropName;
end;
procedure TCompRepMapItem.SetGroup(const Value: TCompRepMapGroupItem);
begin
if FGroup <> Value then
begin
if Assigned(FGroup) then
FGroup.ExtractItem(Self);
FGroup := Value;
if Assigned(FGroup) then
FGroup.AddItem(Self);
end;
end;
function TCompRepMapItem.GetIndex: Integer;
begin
if Assigned(FGroup) then
Result := FGroup.Items.IndexOf(Self)
else
Result := -1;
end;
constructor TCompRepMapItem.Create;
begin
inherited Create;
FBiDirEnabled := CompRepDefBiDirEnabled;
FDisabled := CompRepDefDisabled;
FUseConstValue := CompRepDefUseConstValue;
FLogValuesEnabled := CompRepDefLogValuesEnabled;
FLogOnlyDefValuesEnabled := CompRepDefLogOnlyDefValuesEnabled;
end;
procedure TCompRepMapItem.Reverse;
procedure ExchangeStrings(var S1, S2: string);
var
TmpStr: string;
begin
TmpStr := S1;
S1 := S2;
S2 := TmpStr;
end;
begin
ExchangeStrings(FSourceClassName, FDestClassName);
ExchangeStrings(FSourcePropName, FDestPropName);
end;
function TCompRepMapItem.ExtractCorePropName(const AName: string): string;
var
TmpName: string;
begin
TmpName := AName;
Result := ExtractToken(TmpName, '.');
end;
function TCompRepMapItem.GetSourceCorePropName: string;
begin
Result := ExtractCorePropName(SourcePropName);
end;
function TCompRepMapItem.GetDestCorePropName: string;
begin
Result := ExtractCorePropName(DestPropName);
end;
procedure TCompRepMapItem.AssignMapping(ASource: TCompRepMapItem);
begin
Self.SourceClassName := ASource.SourceClassName;
Self.SourcePropName := ASource.SourcePropName;
Self.DestClassName := ASource.DestClassName;
Self.DestPropName := ASource.DestPropName;
Self.BiDirEnabled := ASource.BiDirEnabled;
Self.Disabled := ASource.Disabled;
Self.UseConstValue := ASource.UseConstValue;
Self.ConstValue := ASource.ConstValue;
Self.LogValuesEnabled := ASource.LogValuesEnabled;
Self.LogOnlyDefValuesEnabled := ASource.LogOnlyDefValuesEnabled;
end;
{ TCompRepEventList }
function TCompRepEventList.GetItem(Index: Integer): TCompRepEvent;
begin
Result := (inherited Items[Index]) as TCompRepEvent;
end;
procedure TCompRepEventList.SaveAsXML(const AFileName: string; SelectedList: TList);
var
Doc: IXMLDocument;
RootNode, ItemNode: IXMLElement;
i: Integer;
begin
Doc := CreateXMLDoc;
AddXMLHeader(Doc);
RootNode := Doc.CreateElement(cXmlNodeLogRoot);
Doc.DocumentElement := RootNode;
for i := 0 to Count-1 do
begin
if Assigned(SelectedList) and (SelectedList.IndexOf(Self[i]) < 0) then
Continue;
ItemNode := Doc.CreateElement(cXmlNodeLogEvent);
RootNode.AppendChild(ItemNode);
SaveLogEvent(Doc, ItemNode, Items[i]);
end;
Doc.Save(AFileName, ofIndent);
end;
procedure TCompRepEventList.SaveLogEvent(const Doc: IXMLDocument;
const ItemNode: IXMLNode; Event: TCompRepEvent);
begin
AddNodeProperty(Doc, ItemNode, cXmlNodeEventWhen, DateTimeToStr(Event.When));
AddNodeProperty(Doc, ItemNode, cXmlNodeEventType, Event.EventType);
AddNodeProperty(Doc, ItemNode, cXmlNodeEventText, Event.Text);
if Event.IsError then
AddNodeProperty(Doc, ItemNode, cXmlNodeEventErrorClass, Event.ErrorClass);
AddNodeProperty(Doc, ItemNode, cXmlNodeEventContext, Event.Context);
AddNodeProperty(Doc, ItemNode, cXmlNodeEventObjSearchName, Event.ObjectSearchName);
AddNodeProperty(Doc, ItemNode, cXmlNodeEventObjClassName, Event.ObjectClass);
AddNodeProperty(Doc, ItemNode, cXmlNodeEventComponentName, Event.ComponentName);
AddNodeProperty(Doc, ItemNode, cXmlNodeEventChildStack, Event.StackText);
AddNodeProperty(Doc, ItemNode, cXmlNodeEventFileName, Event.FileName);
AddNodeProperty(Doc, ItemNode, cXmlNodeEventSourceClassName, Event.SourceClassName);
AddNodeProperty(Doc, ItemNode, cXmlNodeEventDestClassName, Event.DestClassName);
end;
{ TCompRepEvent }
function TCompRepEvent.FlatText: string;
begin
Result := FlatLine(Text);
end;
function TCompRepEvent.IsError: Boolean;
begin
Result := (ErrorClass <> '');
end;
function TCompRepEvent.ObjectText: string;
resourcestring
SNone = 'none';
begin
if ObjectSearchName <> '' then
Result := ObjectClass + ':' + ObjectSearchName
else
Result := SNone;
end;
function TCompRepEvent.FormatEventAsText(const ATemplate: string): string;
resourcestring
SErrorLayout = 'Error: %ErrorClass%'+#10;
var
ErrorPart: string;
begin
Result := ATemplate;
Result := StringReplace(Result, '%When%', DateTimeToStr(Self.When), [rfReplaceAll, rfIgnoreCase]);
if Self.IsError then
ErrorPart := SErrorLayout
else
ErrorPart := '';
Result := StringReplace(Result, '%EventType%', EventType, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%Text%', Self.Text, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%FlatText%', Self.FlatText, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%FileName%', Self.FileName, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%SourceClassName%', Self.SourceClassName, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%DestClassName%', Self.DestClassName, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%ObjectSearchName%', Self.ObjectSearchName, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%ObjectClass%', Self.ObjectClass, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%ComponentName%', Self.ComponentName, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%ChildStack%', Self.StackText, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%ErrorPart%', ErrorPart, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%ErrorClass%', Self.ErrorClass, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%Context%', Self.Context, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '%FlatContext%', FlatLine(Self.Context), [rfReplaceAll, rfIgnoreCase]);
end;
function TCompRepEvent.EventType: string;
begin
if IsError then
Result := 'Error'
else
Result := 'Info';
end;
end.
|
unit ICDtranslator;
interface
type
TICDlng = (lng_fr, lng_nl);
TICDtranslator = class
class function GUItranslate(const aICDlng: TICDlng): string;
class function ADOtranslate(const aICDlng: TICDlng): string;
end;
implementation
uses
ICDconst;
class function TICDtranslator.GUItranslate(const aICDlng: TICDlng): string;
begin
result := 'français';
case aICDlng of
lng_fr: result := 'français';
lng_nl: result := 'néerlandais';
end;
end;
class function TICDtranslator.ADOtranslate(const aICDlng: TICDlng): string;
begin
result := CST_FR_DESC_FIELD;
case aICDlng of
lng_fr: result := CST_FR_DESC_FIELD;
lng_nl: result := CST_NL_DESC_FIELD;
end;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.11 11/12/2004 11:30:20 AM JPMugaas
Expansions for IPv6.
Rev 1.10 11/11/2004 10:25:26 PM JPMugaas
Added OpenProxy and CloseProxy so you can do RecvFrom and SendTo functions
from the UDP client with SOCKS. You must call OpenProxy before using
RecvFrom or SendTo. When you are finished, you must use CloseProxy to close
any connection to the Proxy. Connect and disconnect also call OpenProxy and
CloseProxy.
Rev 1.9 11/10/2004 9:40:42 PM JPMugaas
Timeout error fix. Thanks Bas.
Rev 1.8 11/9/2004 8:18:00 PM JPMugaas
Attempt to add SOCKS support in UDP.
Rev 1.7 11/8/2004 5:03:00 PM JPMugaas
Eliminated Socket property because we probably do not need it after all.
Binding should work just as well. I also made some minor refinements to
Disconnect and Connect.
Rev 1.6 11/7/2004 11:50:36 PM JPMugaas
Fixed a Send method I broke. If FSocket is not assigned, it will call the
inherited SendBuffer method. That should prevent code breakage. The connect
method should be OPTIONAL because UDP may be used for simple one-packet
query/response protocols.
Rev 1.5 11/7/2004 11:33:30 PM JPMugaas
Now uses Connect, Disconnect, Send, and Receive similarly to the TCP Clients.
This should prevent unneeded DNS name to IP address conversions that SendTo
was doing.
Rev 1.4 2004.02.03 4:17:02 PM czhower
For unit name changes.
Rev 1.3 2004.01.21 2:35:40 PM czhower
Removed illegal characters from file.
Rev 1.2 21.1.2004 ã. 12:31:02 DBondzhev
Fix for Indy source. Workaround for dccil bug
now it can be compiled using Compile instead of build
Rev 1.1 10/22/2003 04:41:00 PM JPMugaas
Should compile with some restored functionality. Still not finished.
Rev 1.0 11/13/2002 09:02:16 AM JPMugaas
}
unit IdUDPClient;
interface
{$I IdCompilerDefines.inc}
//Put FPC into Delphi mode
uses
Classes,
IdUDPBase,
IdGlobal,
IdSocketHandle,
IdCustomTransparentProxy;
type
EIdMustUseOpenProxy = class(EIdUDPException);
TIdUDPClient = class(TIdUDPBase)
protected
FBoundIP: string;
FBoundPort: TIdPort;
FBoundPortMin: TIdPort;
FBoundPortMax: TIdPort;
FProxyOpened : Boolean;
FOnConnected : TNotifyEvent;
FOnDisconnected: TNotifyEvent;
FConnected : Boolean;
FTransparentProxy: TIdCustomTransparentProxy;
function UseProxy : Boolean;
procedure RaiseUseProxyError;
procedure DoOnConnected; virtual;
procedure DoOnDisconnected; virtual;
procedure InitComponent; override;
//property methods
procedure SetIPVersion(const AValue: TIdIPVersion); override;
procedure SetHost(const AValue : String); override;
procedure SetPort(const AValue : TIdPort); override;
procedure SetTransparentProxy(AProxy : TIdCustomTransparentProxy);
function GetBinding: TIdSocketHandle; override;
function GetTransparentProxy: TIdCustomTransparentProxy;
public
destructor Destroy; override;
procedure OpenProxy;
procedure CloseProxy;
procedure Connect; virtual;
procedure Disconnect; virtual;
function Connected: Boolean;
function ReceiveBuffer(var ABuffer : TIdBytes;
const AMSec: Integer = IdTimeoutDefault): Integer; overload; override;
function ReceiveBuffer(var ABuffer : TIdBytes;
var VPeerIP: string; var VPeerPort: TIdPort;
AMSec: Integer = IdTimeoutDefault): integer; overload; override;
function ReceiveBuffer(var ABuffer : TIdBytes;
var VPeerIP: string; var VPeerPort: TIdPort; var VIPVersion: TIdIPVersion;
const AMSec: Integer = IdTimeoutDefault): integer; overload; override;
procedure Send(const AData: string; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
); overload;
procedure SendBuffer(const AHost: string; const APort: TIdPort; const ABuffer : TIdBytes); overload; override;
procedure SendBuffer(const ABuffer: TIdBytes); reintroduce; overload;
procedure SendBuffer(const AHost: string; const APort: TIdPort;
const AIPVersion: TIdIPVersion; const ABuffer: TIdBytes);overload; override;
published
property BoundIP: string read FBoundIP write FBoundIP;
property BoundPort: TIdPort read FBoundPort write FBoundPort default DEF_PORT_ANY;
property BoundPortMin: TIdPort read FBoundPortMin write FBoundPortMin default DEF_PORT_ANY;
property BoundPortMax: TIdPort read FBoundPortMax write FBoundPortMax default DEF_PORT_ANY;
property IPVersion;
property Host;
property Port;
property ReceiveTimeout;
property ReuseSocket;
property TransparentProxy: TIdCustomTransparentProxy read GetTransparentProxy write SetTransparentProxy;
property OnConnected: TNotifyEvent read FOnConnected write FOnConnected;
property OnDisconnected: TNotifyEvent read FOnDisconnected write FOnDisconnected;
end;
implementation
uses
IdComponent, IdResourceStringsCore, IdSocks, IdStack, IdStackConsts,
SysUtils;
{ TIdUDPClient }
procedure TIdUDPClient.CloseProxy;
begin
if UseProxy and FProxyOpened then begin
FTransparentProxy.CloseUDP(Binding);
FProxyOpened := False;
end;
end;
procedure TIdUDPClient.Connect;
var
LIP : String;
begin
if Connected then begin
Disconnect;
end;
if Assigned(FTransparentProxy) then begin
if FTransparentProxy.Enabled then begin
//we don't use proxy open because we want to pass a peer's hostname and port
//in case a proxy type in the future requires this.
FTransparentProxy.OpenUDP(Binding, Host, Port);
FProxyOpened := True;
FConnected := True;
Exit; //we're done, the transparentProxy takes care of the work.
end;
end;
if not GStack.IsIP(Host) then begin
if Assigned(OnStatus) then begin
DoStatus(hsResolving, [Host]);
end;
LIP := GStack.ResolveHost(Host, FIPVersion);
end else begin
LIP := Host;
end;
Binding.SetPeer(LIP, Port);
Binding.Connect;
DoStatus(hsConnected, [Host]);
DoOnConnected;
FConnected := True;
end;
function TIdUDPClient.Connected: Boolean;
begin
Result := FConnected;
if Result then begin
if Assigned(FBinding) then begin
Result := FBinding.HandleAllocated;
end else begin
Result := False;
end;
end;
end;
procedure TIdUDPClient.Disconnect;
begin
if Connected then begin
DoStatus(hsDisconnecting);
if UseProxy and FProxyOpened then begin
CloseProxy;
end;
FBinding.CloseSocket;
DoOnDisconnected;
DoStatus(hsDisconnected);
FConnected := False;
end;
end;
procedure TIdUDPClient.DoOnConnected;
begin
if Assigned(OnConnected) then begin
OnConnected(Self);
end;
end;
procedure TIdUDPClient.DoOnDisconnected;
begin
if Assigned(OnDisconnected) then begin
OnDisconnected(Self);
end;
end;
function TIdUDPClient.GetBinding: TIdSocketHandle;
begin
if FBinding = nil then begin
FBinding := TIdSocketHandle.Create(nil);
end;
with FBinding do
begin
if not HandleAllocated then begin
IPVersion := Self.FIPVersion;
{$IFDEF LINUX}
AllocateSocket(LongInt(Id_SOCK_DGRAM));
{$ELSE}
AllocateSocket(Id_SOCK_DGRAM);
{$ENDIF}
IP := FBoundIP;
Port := FBoundPort;
ClientPortMin := FBoundPortMin;
ClientPortMax := FBoundPortMax;
ReuseSocket := Self.FReuseSocket;
Bind;
BroadcastEnabledChanged;
end;
end;
Result := FBinding;
end;
function TIdUDPClient.GetTransparentProxy: TIdCustomTransparentProxy;
begin
// Necessary at design time for Borland SOAP support
if FTransparentProxy = nil then begin
FTransparentProxy := TIdSocksInfo.Create(nil); //default
end;
Result := FTransparentProxy;
end;
procedure TIdUDPClient.InitComponent;
begin
inherited InitComponent;
FProxyOpened := False;
FConnected := False;
FBoundPort := DEF_PORT_ANY;
FBoundPortMin := DEF_PORT_ANY;
FBoundPortMax := DEF_PORT_ANY;
end;
procedure TIdUDPClient.OpenProxy;
begin
if UseProxy and (not FProxyOpened) then begin
FTransparentProxy.OpenUDP(Binding);
FProxyOpened := True;
end;
end;
function TIdUDPClient.ReceiveBuffer(var ABuffer: TIdBytes;
const AMSec: Integer): Integer;
var
LMSec : Integer;
LHost : String;
LPort : TIdPort;
LIPVersion: TIdIPVersion;
begin
Result := 0;
if AMSec = IdTimeoutDefault then begin
if ReceiveTimeout = 0 then begin
LMSec := IdTimeoutInfinite;
end else begin
LMSec := ReceiveTimeout;
end;
end else begin
LMSec := AMSec;
end;
if UseProxy then begin
if not FProxyOpened then begin
RaiseUseProxyError;
end;
Result := FTransparentProxy.RecvFromUDP(Binding, ABuffer, LHost, LPort, LIPVersion, LMSec);
end else
begin
if Connected then begin
if FBinding.Readable(LMSec) then begin //Select(LMSec) then
Result := FBinding.Receive(ABuffer);
end;
end else begin
Result := inherited ReceiveBuffer(ABuffer, LMSec);
end;
end;
end;
procedure TIdUDPClient.RaiseUseProxyError;
begin
raise EIdMustUseOpenProxy.Create(RSUDPMustUseProxyOpen);
end;
function TIdUDPClient.ReceiveBuffer(var ABuffer: TIdBytes;
var VPeerIP: string; var VPeerPort: TIdPort; AMSec: Integer): integer;
var
VoidIPVersion: TidIPVersion;
begin
Result := ReceiveBuffer(ABuffer, VPeerIP, VPeerPort, VoidIPVersion, AMSec);
end;
procedure TIdUDPClient.Send(const AData: string; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
);
begin
Send(Host, Port, AData, AByteEncoding{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF});
end;
procedure TIdUDPClient.SendBuffer(const ABuffer : TIdBytes);
begin
if UseProxy then begin
if not FProxyOpened then begin
RaiseUseProxyError;
end;
FTransparentProxy.SendToUDP(Binding, Host, Port, IPVersion, ABuffer);
end else
begin
if Connected then begin
FBinding.Send(ABuffer, 0, -1);
end else begin
inherited SendBuffer(Host, Port, IPVersion, ABuffer);
end;
end;
end;
procedure TIdUDPClient.SendBuffer(const AHost: string; const APort: TIdPort;
const ABuffer: TIdBytes);
begin
if UseProxy then begin
if not FProxyOpened then begin
RaiseUseProxyError;
end;
FTransparentProxy.SendToUDP(Binding, AHost, APort, IPVersion, ABuffer);
end else begin
inherited SendBuffer(AHost, APort, ABuffer);
end;
end;
procedure TIdUDPClient.SetHost(const AValue: String);
begin
if FHost <> AValue then begin
Disconnect;
end;
inherited SetHost(AValue);
end;
procedure TIdUDPClient.SetIPVersion(const AValue: TIdIPVersion);
begin
if FIPVersion <> AValue then begin
Disconnect;
end;
inherited SetIPVersion(AValue);
end;
procedure TIdUDPClient.SetPort(const AValue: TIdPort);
begin
if FPort <> AValue then begin
Disconnect;
end;
inherited SetPort(AValue);
end;
procedure TIdUDPClient.SetTransparentProxy(AProxy: TIdCustomTransparentProxy);
var
LClass: TIdCustomTransparentProxyClass;
begin
// All this is to preserve the compatibility with old version
// In the case when we have SocksInfo as object created in runtime without owner form it is treated as temporary object
// In the case when the ASocks points to an object with owner it is treated as component on form.
if Assigned(AProxy) then begin
if not Assigned(AProxy.Owner) then begin
if Assigned(FTransparentProxy) and Assigned(FTransparentProxy.Owner) then begin
FTransparentProxy.RemoveFreeNotification(Self);
FTransparentProxy := nil;
end;
LClass := TIdCustomTransparentProxyClass(AProxy.ClassType);
if Assigned(FTransparentProxy) and (FTransparentProxy.ClassType <> LClass) then begin
FreeAndNil(FTransparentProxy);
end;
if not Assigned(FTransparentProxy) then begin
FTransparentProxy := LClass.Create(nil);
end;
FTransparentProxy.Assign(AProxy);
end else begin
if Assigned(FTransparentProxy) then begin
if not Assigned(FTransparentProxy.Owner) then begin
FreeAndNil(FTransparentProxy);
end else begin
FTransparentProxy.RemoveFreeNotification(Self);
end;
end;
FTransparentProxy := AProxy;
FTransparentProxy.FreeNotification(Self);
end;
end
else if Assigned(FTransparentProxy) then begin
if not Assigned(FTransparentProxy.Owner) then begin
FreeAndNil(FTransparentProxy);
end else begin
FTransparentProxy.RemoveFreeNotification(Self);
FTransparentProxy := nil; //remove link
end;
end;
end;
function TIdUDPClient.UseProxy: Boolean;
begin
if Assigned(FTransparentProxy) then begin
Result := FTransparentProxy.Enabled;
end else begin
Result := False;
end;
end;
destructor TIdUDPClient.Destroy;
begin
if UseProxy and FProxyOpened then begin
CloseProxy;
end;
if Connected then begin
Disconnect;
end;
inherited Destroy;
end;
function TIdUDPClient.ReceiveBuffer(var ABuffer: TIdBytes;
var VPeerIP: string; var VPeerPort: TIdPort; var VIPVersion: TIdIPVersion;
const AMSec: Integer): integer;
var
LMSec : Integer;
begin
if AMSec = IdTimeoutDefault then begin
if ReceiveTimeout = 0 then begin
LMSec := IdTimeoutInfinite;
end else begin
LMSec := ReceiveTimeout;
end;
end else begin
LMSec := AMSec;
end;
if UseProxy then begin
if not FProxyOpened then begin
RaiseUseProxyError;
end;
Result := FTransparentProxy.RecvFromUDP(Binding, ABuffer, VPeerIP, VPeerPort, VIPVersion, LMSec);
end else begin
Result := inherited ReceiveBuffer(ABuffer, VPeerIP, VPeerPort, VIPVersion, LMSec);
end;
end;
procedure TIdUDPClient.SendBuffer(const AHost: string; const APort: TIdPort;
const AIPVersion: TIdIPVersion; const ABuffer: TIdBytes);
begin
if UseProxy then begin
if not FProxyOpened then begin
RaiseUseProxyError;
end;
FTransparentProxy.SendToUDP(Binding, AHost, APort, AIPVersion, ABuffer);
end else begin
inherited SendBuffer(AHost, APort, AIPVersion, ABuffer);
end;
end;
end.
|
unit fmuFindDevice;
interface
uses
// VCL
Windows, Forms, ComCtrls, StdCtrls, Controls, Classes, SysUtils, Messages,
Buttons,
// This
untPages, untUtil, untDriver;
type
{ TfmFindDevice }
TfmFindDevice = class(TPage)
Memo: TMemo;
btnRead: TBitBtn;
procedure btnReadClick(Sender: TObject);
end;
implementation
{$R *.DFM}
function IntToBaudRate(Value: Integer): Integer;
begin
case Value of
0: Result := CBR_2400;
1: Result := CBR_4800;
2: Result := CBR_9600;
3: Result := CBR_19200;
4: Result := CBR_38400;
5: Result := CBR_57600;
6: Result := CBR_115200;
else
Result := CBR_4800;
end;
end;
{ TfmFindDevice }
procedure TfmFindDevice.btnReadClick(Sender: TObject);
begin
EnableButtons(False);
Memo.Lines.BeginUpdate;
try
Memo.Clear;
if Driver.FindDevice = 0 then
begin
Memo.Lines.Add('Устройство найдено.');
Memo.Lines.Add(Format('Порт: COM%d, Скорость: %d',
[Driver.ComNumber, IntToBaudRate(Driver.BaudRate)]))
end else
Memo.Lines.Add('Устройство не найдено.');
finally
Memo.Lines.EndUpdate;
EnableButtons(True);
end;
end;
end.
|
unit Error;
interface
uses
ErrorIntf;
type
TError = class(TInterfacedObject, IError)
private
FMessage: string;
function GetMessage: string;
procedure SetMessage(const Value: string);
public
property Message: string read GetMessage write SetMessage;
end;
implementation
function TError.GetMessage: string;
begin
Result := FMessage;
end;
procedure TError.SetMessage(const Value: string);
begin
FMessage := Value;
end;
end.
|
unit UDataComboListViewFrame;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.ListBox, UDataComboBox, FMX.ListView.Types, FMX.ListView, UDataListView,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, REST.Response.Adapter,
REST.Client, UDetailInitThread, FMX.Objects, FMX.Controls.Presentation;
type
TDataComboListViewFrame = class(TFrame)
TopToolBar: TToolBar;
TopPrevButton: TButton;
TopNextButton: TButton;
TopDataComboBox: TDataComboBox;
DataListView: TDataListView;
TopMasterToolBar: TToolBar;
TopMasterLabel: TLabel;
DataAniIndicator: TAniIndicator;
procedure TopPrevButtonClick(Sender: TObject);
procedure TopNextButtonClick(Sender: TObject);
procedure TopDataComboBoxChange(Sender: TObject);
procedure DataListViewItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure DataListViewButtonClick(const Sender: TObject;
const AItem: TListViewItem; const AObject: TListItemSimpleControl);
procedure DoneInitDetail(Sender: TObject); virtual;
procedure FrameResize(Sender: TObject);
private
{ Private declarations }
fNoDataFoundToggle: Boolean;
fMasterDataSet: TDataSet;
fMasterDataFieldName: String;
fMasterRESTRequest: TRESTRequest;
fMasterRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
fDetailDataSet: TDataSet;
fDetailDataFieldName: String;
fDetailRESTRequest: TRESTRequest;
fDetailRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
fDetailDataStringList: TStringList;
fMasterDetailLinkFieldName: String;
// fWorkingForm: TWorkingForm;
fDetailInitThread: TDetailInitThread;
procedure stopSpinner;
procedure startSpinner;
public
{ Public declarations }
procedure init(lMasterDataSet: TDataSet; lMasterDataFieldName: string;
lMasterRESTRequest: TRESTRequest;
lMasterRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
lDetailDataSet: TDataSet; lDetailDataFieldName: string;
lDetailDataStringList: TStringList; lDetailRESTRequest: TRESTRequest;
lDetailRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
lMasterDetailLinkFieldName: String); overload;
procedure init(lMasterDataSet: TDataSet; lMasterDataFieldName: string;
lMasterRESTRequest: TRESTRequest;
lMasterRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
lDetailDataSet: TDataSet; lDetailDataFieldName: string;
lDetailRESTRequest: TRESTRequest;
lDetailRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
lMasterDetailLinkFieldName: String); overload;
procedure init(lMasterDetailLinkFieldName: String); overload;
procedure initDataListView; virtual;
procedure initTopDataComboBox;
Constructor Create(AOwner: TComponent); override;
published
{ Published declarations }
Property MasterDetailLinkFieldName: String read fMasterDetailLinkFieldName
write fMasterDetailLinkFieldName;
end;
implementation
uses
UWorking;
{$R *.fmx}
constructor TDataComboListViewFrame.Create(AOwner: TComponent);
begin
// Execute the parent (TObject) constructor first
inherited; // Call the parent Create method
// if not Assigned(WorkingForm) then
// begin
// WorkingForm := TWorkingForm.Create(self);
// WorkingForm.Parent := self;
// end;
end;
procedure TDataComboListViewFrame.startSpinner;
begin
// Call the working spinner
DataListView.Enabled := false;
DataAniIndicator.Visible := true;
DataAniIndicator.Enabled := true;
end;
procedure TDataComboListViewFrame.stopSpinner;
begin
DataAniIndicator.Visible := false;
DataAniIndicator.Enabled := false;
DataListView.Enabled := true;
end;
procedure TDataComboListViewFrame.DoneInitDetail(Sender: TObject);
begin
// For some nebulous reason this is triggered twice
// which we do not want
fNoDataFoundToggle := not fNoDataFoundToggle;
if (fDetailInitThread.ExceptionMessage <> '') and fNoDataFoundToggle then
begin
MessageDlg('No Data found!', System.UITypes.TMsgDlgType.mtInformation,
[System.UITypes.TMsgDlgBtn.mbOK], 0);
end;
// fDetailInitThread := nil;
// WorkingForm.WorkingMsg('Loading ...', false);
self.Show;
end;
// --------------------------------------------------
// To ensure the Working spinner is always centered
// --------------------------------------------------
procedure TDataComboListViewFrame.FrameResize(Sender: TObject);
begin
// if Assigned(WorkingForm) then
// begin
// FreeAndNil(WorkingForm);
// WorkingForm := TWorkingForm.Create(self);
// WorkingForm.Parent := self;
// end;
end;
procedure TDataComboListViewFrame.init(lMasterDataSet: TDataSet;
lMasterDataFieldName: string; lMasterRESTRequest: TRESTRequest;
lMasterRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
lDetailDataSet: TDataSet; lDetailDataFieldName: string;
lDetailDataStringList: TStringList; lDetailRESTRequest: TRESTRequest;
lDetailRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
lMasterDetailLinkFieldName: String);
begin
fDetailDataStringList := lDetailDataStringList;
init(lMasterDataSet, lMasterDataFieldName, lMasterRESTRequest,
lMasterRESTResponseDataSetAdapter, lDetailDataSet, lDetailDataFieldName,
lDetailRESTRequest, lDetailRESTResponseDataSetAdapter,
lMasterDetailLinkFieldName);
end;
procedure TDataComboListViewFrame.init(lMasterDataSet: TDataSet;
lMasterDataFieldName: string; lMasterRESTRequest: TRESTRequest;
lMasterRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
lDetailDataSet: TDataSet; lDetailDataFieldName: string;
lDetailRESTRequest: TRESTRequest;
lDetailRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
lMasterDetailLinkFieldName: String);
begin
fMasterDataSet := lMasterDataSet;
TopDataComboBox.DataSet := fMasterDataSet;
fMasterDataFieldName := lMasterDataFieldName;
TopDataComboBox.DataFieldName := lMasterDataFieldName;
fMasterRESTRequest := lMasterRESTRequest;
fMasterRESTResponseDataSetAdapter := lMasterRESTResponseDataSetAdapter;
fDetailDataSet := lDetailDataSet;
DataListView.DataSet := lDetailDataSet;
fDetailDataFieldName := lDetailDataFieldName;
DataListView.DataFieldName := lDetailDataFieldName;
fDetailRESTRequest := lDetailRESTRequest;
fDetailRESTResponseDataSetAdapter := lDetailRESTResponseDataSetAdapter;
init(lMasterDetailLinkFieldName);
end;
// -----------------------------------
// Sync Dataset with itemnumber
// -----------------------------------
procedure TDataComboListViewFrame.DataListViewButtonClick(const Sender: TObject;
const AItem: TListViewItem; const AObject: TListItemSimpleControl);
begin
fDetailDataSet.RecNo := DataListView.ItemIndex + 1;
end;
procedure TDataComboListViewFrame.DataListViewItemClick(const Sender: TObject;
const AItem: TListViewItem);
begin
fDetailDataSet.RecNo := DataListView.ItemIndex + 1;
end;
procedure TDataComboListViewFrame.initTopDataComboBox;
var
lidx: integer;
begin
if not fMasterDataSet.Active then
begin
fMasterRESTResponseDataSetAdapter.FieldDefs.Clear;
fMasterRESTRequest.Execute;
TopDataComboBox.init;
end
else
begin
lidx := fMasterDataSet.RecNo;
// speed optimisation
if TopDataComboBox.Items.Count = 0 then
begin
TopDataComboBox.init;
end;
fMasterDataSet.RecNo := lidx;
TopDataComboBox.ItemIndex := lidx - 1;
end;
if TopDataComboBox.Items.Count > 1 then
begin
TopPrevButton.Visible := true;
TopNextButton.Visible := true;
end
else
begin
TopPrevButton.Visible := false;
TopNextButton.Visible := false;
end;
end;
procedure TDataComboListViewFrame.initDataListView;
var
lDefaultServiceReference: String;
begin
lDefaultServiceReference := fMasterDataSet.FieldByName
(fMasterDetailLinkFieldName).AsString;
if fDetailDataSet.Active then
begin
fDetailRESTResponseDataSetAdapter.ClearDataSet;
fDetailRESTResponseDataSetAdapter.Active := false;
fDetailDataSet.Close;
end;
fDetailRESTResponseDataSetAdapter.FieldDefs.Clear;
// sRef parameter
fDetailRESTRequest.Params[0].Value := lDefaultServiceReference;
// start the spinner
startSpinner;
// WorkingForm.WorkingMsg('Loading ...', true);
Application.ProcessMessages;
// fDetailInitThread := TDetailInitThread.Create(DataAniIndicator,
// fMasterDataSet, fDetailDataStringList, fDetailRESTRequest, DataListView,
// DoneInitDetail);
// fDetailInitThread.OnTerminate := DoneInitDetail;
try
try
fDetailRESTRequest.Execute;
except
if fMasterDataSet.State = dsBrowse then
begin
fMasterDataSet.Close;
end;
fDetailRESTRequest.Execute;
end;
if assigned(fDetailDataStringList) then
begin
DataListView.init(fDetailDataStringList);
end
else
begin
DataListView.init;
end;
except
// stop the spinner
stopSpinner;
MessageDlg('No Data found!', System.UITypes.TMsgDlgType.mtInformation,
[System.UITypes.TMsgDlgBtn.mbOK], 0);
end;
// stop the spinner
stopSpinner;
end;
procedure TDataComboListViewFrame.init(lMasterDetailLinkFieldName: String);
begin
fMasterDetailLinkFieldName := lMasterDetailLinkFieldName;
initTopDataComboBox;
// initDataListView;
end;
procedure TDataComboListViewFrame.TopDataComboBoxChange(Sender: TObject);
begin
fMasterDataSet.RecNo := TopDataComboBox.ItemIndex + 1;
TopNextButton.Enabled :=
not(TopDataComboBox.ItemIndex = (TopDataComboBox.Items.Count - 1));
TopPrevButton.Enabled := not(TopDataComboBox.ItemIndex = 0);
try
initDataListView;
except
end;
end;
procedure TDataComboListViewFrame.TopNextButtonClick(Sender: TObject);
begin
if TopDataComboBox.Items.Count > 1 then
begin
TopDataComboBox.ItemIndex := TopDataComboBox.ItemIndex + 1;
end;
end;
procedure TDataComboListViewFrame.TopPrevButtonClick(Sender: TObject);
begin
if TopDataComboBox.Items.Count > 1 then
begin
TopDataComboBox.ItemIndex := TopDataComboBox.ItemIndex - 1;
end;
end;
end.
|
unit registryuserpreferences;
{
$Id: registryuserpreferences.pas,v 1.1 2004/09/30 22:35:47 savage Exp $
}
{******************************************************************************}
{ }
{ JEDI-SDL : Pascal units for SDL - Simple DirectMedia Layer }
{ Wrapper class for Windows Register and INI Files }
{ }
{ The initial developer of this Pascal code was : }
{ Dominqiue Louis <Dominique@SavageSoftware.com.au> }
{ }
{ Portions created by Dominqiue Louis are }
{ Copyright (C) 2000 - 2001 Dominqiue Louis. }
{ }
{ }
{ Contributor(s) }
{ -------------- }
{ }
{ }
{ Obtained through: }
{ Joint Endeavour of Delphi Innovators ( Project JEDI ) }
{ }
{ You may retrieve the latest version of this file at the Project }
{ JEDI home page, located at http://delphi-jedi.org }
{ }
{ The contents of this file are used with permission, subject to }
{ the Mozilla Public License Version 1.1 (the "License"); you may }
{ not use this file except in compliance with the License. You may }
{ obtain a copy of the License at }
{ http://www.mozilla.org/MPL/MPL-1.1.html }
{ }
{ Software distributed under the License is distributed on an }
{ "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or }
{ implied. See the License for the specific language governing }
{ rights and limitations under the License. }
{ }
{ Description }
{ ----------- }
{ }
{ }
{ }
{ }
{ }
{ }
{ }
{ Requires }
{ -------- }
{ The SDL Runtime libraris on Win32 : SDL.dll on Linux : libSDL.so }
{ They are available from... }
{ http://www.libsdl.org . }
{ }
{ Programming Notes }
{ ----------------- }
{ }
{ }
{ }
{ }
{ Revision History }
{ ---------------- }
{ September 23 2004 - DL : Initial Creation }
{
$Log: registryuserpreferences.pas,v $
Revision 1.1 2004/09/30 22:35:47 savage
Changes, enhancements and additions as required to get SoAoS working.
}
{******************************************************************************}
interface
uses
{$IFDEF REG}
Registry,
{$ELSE}
IniFiles,
{$ENDIF}
Classes,
userpreferences;
type
TRegistryUserPreferences = class( TUserPreferences )
private
protected
function GetSection( const Index : Integer ) : string; virtual; abstract;
function GetIdentifier( const Index : Integer ) : string; virtual; abstract;
function GetDefaultBoolean( const Index : Integer ) : Boolean; override;
function GetBoolean( const Index : Integer ) : Boolean; override;
procedure SetBoolean( const Index : Integer; const Value : Boolean ); override;
function GetDefaultDateTime( const Index : Integer ) : TDateTime; override;
function GetDateTime( const Index : Integer ) : TDateTime; override;
procedure SetDateTime( const Index : Integer; const Value : TDateTime ); override;
function GetDefaultInteger( const Index : Integer ) : Integer; override;
function GetInteger( const Index : Integer ) : Integer; override;
procedure SetInteger( const Index : Integer; const Value : Integer ); override;
function GetDefaultFloat( const Index : Integer ) : single; override;
function GetFloat( const Index : Integer ) : single; override;
procedure SetFloat( const Index : Integer; const Value : single ); override;
function GetDefaultString( const Index : Integer ) : string; override;
function GetString( const Index : Integer ) : string; override;
procedure SetString( const Index : Integer; const Value : string ); override;
public
Registry : {$IFDEF REG}TRegIniFile{$ELSE}TIniFile{$ENDIF};
constructor Create( const FileName : string = '' ); reintroduce;
destructor Destroy; override;
procedure Update; override;
end;
implementation
uses
SysUtils;
{ TRegistryUserPreferences }
constructor TRegistryUserPreferences.Create( const FileName : string );
var
defFileName : string;
begin
inherited Create;
if FileName <> '' then
defFileName := FileName
else
defFileName := ChangeFileExt( ParamStr( 0 ), '.ini' );
Registry := {$IFDEF REG}TRegIniFile{$ELSE}TIniFile{$ENDIF}.Create( defFileName );
end;
destructor TRegistryUserPreferences.Destroy;
begin
Update;
Registry.Free;
Registry := nil;
inherited;
end;
function TRegistryUserPreferences.GetBoolean( const Index : Integer ) : Boolean;
begin
Result := Registry.ReadBool( GetSection( Index ), GetIdentifier( Index ), GetDefaultBoolean( Index ) );
end;
function TRegistryUserPreferences.GetDateTime( const Index : Integer ): TDateTime;
begin
Result := Registry.ReadDateTime( GetSection( Index ){$IFNDEF REG}, GetIdentifier( Index ), GetDefaultDateTime( Index ){$ENDIF} );
end;
function TRegistryUserPreferences.GetDefaultBoolean( const Index : Integer ) : Boolean;
begin
result := false;
end;
function TRegistryUserPreferences.GetDefaultDateTime( const Index: Integer ) : TDateTime;
begin
result := Now;
end;
function TRegistryUserPreferences.GetDefaultFloat( const Index: Integer ) : single;
begin
result := 0.0;
end;
function TRegistryUserPreferences.GetDefaultInteger(const Index : Integer ) : Integer;
begin
result := 0;
end;
function TRegistryUserPreferences.GetDefaultString( const Index : Integer ) : string;
begin
result := '';
end;
function TRegistryUserPreferences.GetFloat( const Index : Integer ): single;
begin
Result := Registry.ReadFloat( GetSection( Index ){$IFNDEF REG}, GetIdentifier( Index ), GetDefaultFloat( Index ){$ENDIF} );
end;
function TRegistryUserPreferences.GetInteger( const Index : Integer ) : Integer;
begin
Result := Registry.ReadInteger( GetSection( Index ), GetIdentifier( Index ), GetDefaultInteger( Index ) );
end;
function TRegistryUserPreferences.GetString( const Index : Integer ): string;
begin
Result := Registry.ReadString( GetSection( Index ), GetIdentifier( Index ), GetDefaultString( Index ) );
end;
procedure TRegistryUserPreferences.SetBoolean( const Index : Integer; const Value : Boolean );
begin
Registry.WriteBool( GetSection( Index ), GetIdentifier( Index ), Value );
inherited;
end;
procedure TRegistryUserPreferences.SetDateTime( const Index: Integer; const Value: TDateTime );
begin
Registry.WriteDateTime( GetSection( Index ){$IFNDEF REG}, GetIdentifier( Index ){$ENDIF}, Value );
inherited;
end;
procedure TRegistryUserPreferences.SetFloat(const Index: Integer; const Value: single);
begin
Registry.WriteFloat( GetSection( Index ){$IFNDEF REG}, GetIdentifier( Index ){$ENDIF}, Value );
inherited;
end;
procedure TRegistryUserPreferences.SetInteger( const Index, Value : Integer );
begin
Registry.WriteInteger( GetSection( Index ), GetIdentifier( Index ), Value );
inherited;
end;
procedure TRegistryUserPreferences.SetString( const Index : Integer; const Value : string );
begin
Registry.WriteString( GetSection( Index ), GetIdentifier( Index ), Value );
inherited;
end;
procedure TRegistryUserPreferences.Update;
begin
{$IFDEF REG}
Registry.CloseKey;
{$ELSE}
Registry.UpdateFile;
{$ENDIF}
end;
end.
|
{
This is a personal project that I give to community under this licence:
Copyright 2016 Eric Buso (Alias Caine_dvp)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
}
unit UMain;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids,Shellapi,
UFiles, ComCtrls, ExtCtrls,UCommons,UDataEngine;
type
{ TfmMain }
TfmMain = class(TForm)
btOpen: TButton;
edPathFile: TEdit;
mmLogInfos: TMemo;
odgFile: TOpenDialog;
PageControl1: TPageControl;
pnLogHistory: TPanel;
pnTrafficTable: TPanel;
stgDatas: TStringGrid;
stgRobots: TStringGrid;
tbsSaw: TTabSheet;
tsbRobots: TTabSheet;
procedure FormCreate(Sender: TObject);
procedure edPathFileChange(Sender: TObject);
procedure btOpenClick(Sender: TObject);
procedure BtUnzipClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Déclarations privées }
FLogParser : TLogParser;
FExePath : String;
public
{ Déclarations publiques }
end;
var
fmMain: TfmMain;
implementation
{$R *.dfm}
Uses FileUtil;
Function ExtractToken(Const S : String;Const Separator: String;Var Token : String) : string;
Var
P : Integer;
Begin
P := Pos(Separator,S);
Result := Copy(S,P+1,Length(S)-1);
Token := Copy(S,0,P-1);
End;
Procedure ReplaceToken(Var S : String;Const Separator,Token: String);
Var
p : Integer;
Temp,Current: String;
Begin
P := 0;
Current := S;
Temp := '';
Repeat
P := Pos(Separator,Current);
If P <> 0 Then
Begin
Temp := Copy(Current,1,P-1);
Temp := Temp + Token;
Current := Copy(Current,P+Length(Separator),Length(Current));
End;
Until P = 0;
If Temp <> '' Then
S := Temp + Current;
End;
procedure TfmMain.btOpenClick(Sender: TObject);
var Reader : TTextFiles;
I,Row1,Col1,Row2,Col2 : Integer;
Cnt,Col : ^Integer;
Error,Tokens : String;
Line,Tail : String;
IpAddress,Date: String;
CurrentGrid : TStringGrid;
B : Boolean;
Path : String;
GeolocData: TGeolocData;
GeoCountry :String;
begin
Row1 := stgDatas.FixedRows;
Col1 := stgDatas.FixedCols;
Row2 := stgRobots.FixedRows;
Col2 := stgRobots.FixedCols;
CurrentGrid := nil;
If odgFile.Execute Then
edPathFile.Text := OdgFile.FileName
Else Exit;
Reader := TTextFiles.Create(OdgFile.FileName,False,Error);
CurrentGrid := stgDatas;
//Creation de la base Geoloc
try
GeolocData := nil;
Path := FExepath ;
If Not Assigned(GeolocData) Then
GeolocData:= TGeolocData.Create(Path + '\GeoLite2.db');
If Not Assigned(GeolocData) Then
Raise Exception.Create('Impossible d''initialiser GeolocData');
finally
end;
Try
Repeat
Reader.ReadLine(Line,Error);
B := FLogParser.ParseLine(Line);
If Not B Then Continue;
If FlogParser.IsBot Then Begin
CurrentGrid := stgRobots;
Cnt := @Row1;
Col := @Col1;
End
Else
Begin
CurrentGrid := stgDatas;
Cnt := @Row2;
Col := @Col2;
End;
With FlogParser.LogInfos Do
Begin
{Pour le trafic humain uniquement, si le code diffère de 404}
If ( Not IsBot ) And (Code <> 404) Then
Begin
{Chercher la géolocalisation de l'adresse IP}
Try
If (GeolocData.IsTheLastIPAddress(IPAddress)=False) Then Begin
//If (CurrentGrid.Cols[Col^].IndexOf(IPAddress)=-1) Then Begin
//mmLogInfos.Append(IPAddress);
GeoCountry := GeolocData.GetCountryName(IPAddress);
end;
finally
If GeoCountry <> EmptyStr Then
Begin
//mmLogInfos.Append(GeoCountry);
If (CurrentGrid.RowCount > Cnt^) Then CurrentGrid.Cells[Col^,Cnt^] := GeoCountry;
end;
GeoCountry := EmptyStr;
end;
End;
{Remplir la grille avec les information extraitent de la ligne}
If (CurrentGrid.RowCount > Cnt^) Then Begin
CurrentGrid.Cells[Col^+1 ,Cnt^] := IPAddress;
CurrentGrid.Cells[Col^+2 ,Cnt^] := Domain;
CurrentGrid.Cells[Col^+3 ,Cnt^] := DateTime;
CurrentGrid.Cells[Col^+4 ,Cnt^] := FileRequest;
CurrentGrid.Cells[Col^+5 ,Cnt^] := IntToStr(FileSize);
CurrentGrid.Cells[Col^+6 ,Cnt^] := IntToStr(Code);
If Isbot Then
Currentgrid.Cells[Col^+7 ,Cnt^] := BotName
Else
Currentgrid.Cells[Col^+7 ,Cnt^] := Referrer;
{ Currentgrid.Cells[Col^+8 ,Cnt^] := Country;
Currentgrid.Cells[Col^+9 ,Cnt^] := Browser;
Currentgrid.Cells[Col^+10 ,Cnt^] := Os;
}
Currentgrid.Cells[Col^+8 ,Cnt^] := UserAgentInfos;
end;
End;
Inc(Cnt^,1);
Until Reader.IsEOF;
Finally
FreeAndNil(GeolocData);
End;
end;
procedure TfmMain.BtUnzipClick(Sender: TObject);
Var FromFiles,ToFolder : String;
begin
ToFolder := ' "C:\temp\Moved\"';
FromFiles := '/C move "' +edPathFile.Text + '\*.gz"' + ToFolder;
If FromFiles <> EmptyStr Then
ShellExecute(0,'open','cmd',PChar(FromFiles), PChar(edPathFile.Text) ,SW_SHOW)
Else Exit;
FromFiles := '/K ' + '.\gzip.exe -ad '+ ToFolder+'\*.gz';
If (FromFiles <> EmptyStr) and (ToFolder <> EmptyStr) Then
ShellExecute(0,'open','cmd',PChar(FromFiles), PChar(ToFolder) ,SW_SHOW)
end;
procedure TfmMain.edPathFileChange(Sender: TObject);
begin
odgFile.InitialDir := edPathFile.Text;
end;
procedure TfmMain.FormCreate(Sender: TObject);
begin
//edPathFile.text := 'C:\Documents and Settings\caine\Mes documents\VosLogiciels.com\Logs OVH';
edPathFile.text := 'C:\temp\Logs OVH';
odgFile.InitialDir := edPathFile.Text;
FLogParser := TLogParser.Create;
//Stoquer le chemin vers l'executable.
FExepath := ProgramDirectory;
stgDatas.RowCount := 10000;
end;
procedure TfmMain.FormDestroy(Sender: TObject);
begin
FreeAndNil(FLogParser);
end;
end.
|
unit GetVendorsResponseUnit;
interface
uses
REST.Json.Types,
GenericParametersUnit, VendorUnit;
type
TGetVendorsResponse = class(TGenericParameters)
private
[JSONName('vendors')]
FVendors: TVendorArray;
public
constructor Create;
destructor Destroy; override;
property Vendors: TVendorArray read FVendors write FVendors;
end;
implementation
{ TGetVendorsResponse }
constructor TGetVendorsResponse.Create;
begin
Inherited;
SetLength(FVendors, 0);
end;
destructor TGetVendorsResponse.Destroy;
begin
Finalize(FVendors);
inherited;
end;
end.
|
unit appdelegate_iphoneu;
{$modeswitch ObjectiveC1}
interface
uses
Classes,
BufDataset,
iPhoneAll,
SysUtils,
TableData;
type
TTableViewDelegate = objcclass;
{ TAppDelegate_iPhone }
TAppDelegate_iPhone = objcclass(NSObject, UIApplicationDelegateProtocol)
UISearchBar1: UISearchBar;
UITableView1: UITableView;
UIWindow1: UIWindow;
procedure applicationDidFinishLaunching(application: UIApplication); message 'applicationDidFinishLaunching:';
private
objectListTableViewDelegate: TTableViewDelegate;
public
procedure dealloc; override;
end;
{ TTableViewDelegate }
TTableViewDelegate = objcclass(NSObject, UISearchBarDelegateProtocol, UITableViewDataSourceProtocol)
private
FDataStrings: TStrings;
FData: TBufDataset;
FTableView: UITableView;
procedure DatasetToStringlist; message 'DatasetToStringlist';
public
function initWithData(ATableView: UITableView): TTableViewDelegate; message 'initWithData:';
function tableView_numberOfRowsInSection(tableView: UITableView; section: NSInteger): NSInteger; message 'tableView:numberOfRowsInSection:';
function tableView_cellForRowAtIndexPath(tableView: UITableView; indexPath: NSIndexPath): UITableViewCell; message 'tableView:cellForRowAtIndexPath:';
procedure searchBarSearchButtonClicked(searchBar: UISearchBar); message 'searchBarSearchButtonClicked:';
procedure dealloc; override;
end;
implementation
{ TTableViewDelegate }
procedure TTableViewDelegate.DatasetToStringlist;
begin
FDataStrings.Clear;
FData.First;
while not FData.EOF do
begin
FDataStrings.Append(FData.FieldByName('name').asstring);
FData.Next;
end;
end;
function TTableViewDelegate.initWithData(ATableView: UITableView
): TTableViewDelegate;
var
AnAlertView: UIAlertView;
begin
result := init;
FData:= CreateDataset;
FDataStrings := TStringList.Create;
FTableView := ATableView;
DatasetToStringlist;
end;
function TTableViewDelegate.tableView_numberOfRowsInSection(
tableView: UITableView; section: NSInteger): NSInteger;
begin
result := FDataStrings.Count;
end;
function TTableViewDelegate.tableView_cellForRowAtIndexPath(
tableView: UITableView; indexPath: NSIndexPath): UITableViewCell;
var
s: nsstring;
begin
result := tableview.dequeueReusableCellWithIdentifier(NSSTR('DefTableItem'));
if not assigned(result) then
result := UITableViewCell.alloc.initWithStyle_reuseIdentifier(UITableViewStylePlain,NSSTR('DefTableItem'));
s := NSString.alloc.initWithUTF8String(pchar(FDataStrings[indexPath.row]));
result.textLabel.setText(s);
end;
procedure TTableViewDelegate.searchBarSearchButtonClicked(searchBar: UISearchBar);
var
AnAlertView: UIAlertView;
begin
FData.Filter:='name="*'+searchBar.text.cString+'*"';
FData.Filtered:=true;
DatasetToStringlist;
FTableView.reloadData;
end;
procedure TTableViewDelegate.dealloc;
begin
FData.Free;
end;
procedure TAppDelegate_iPhone.applicationDidFinishLaunching(
application: UIApplication);
begin
objectListTableViewDelegate:=TTableViewDelegate.alloc.initWithData(UITableView1);
UITableView1.setDataSource(objectListTableViewDelegate);
UISearchBar1.setDelegate(objectListTableViewDelegate);
end;
procedure TAppDelegate_iPhone.dealloc;
begin
objectListTableViewDelegate.release;
UISearchBar1.release;
UITableView1.release;
UIWindow1.release;
inherited dealloc;
end;
{$FakeResource *.xib}
end.
|
namespace Sugar.Cryptography;
interface
uses
Sugar,
{$IF NETFX_CORE}
Windows.Security.Cryptography.Core;
{$ELSEIF ECHOES}
System.Security.Cryptography;
{$ELSEIF COOPER}
java.security;
{$ELSEIF TOFFEE}
rtl;
{$ENDIF}
type
DigestAlgorithm = public (MD5, SHA1, SHA256, SHA384, SHA512);
MessageDigest = public class {$IF COOPER}mapped to java.security.MessageDigest{$ELSEIF NETFX_CORE}mapped to CryptographicHash{$ELSEIF ECHOES}mapped to System.Security.Cryptography.HashAlgorithm{$ELSEIF TOFFEE}{$ENDIF}
public
constructor(Algorithm: DigestAlgorithm);
method Reset; virtual;
method Update(Data: array of Byte; Offset: Integer; Count: Integer); virtual;
method Update(Data: array of Byte; Count: Integer);
method Update(Data: array of Byte);
method Digest(Data: array of Byte; Offset: Integer; Count: Integer): array of Byte; virtual;
method Digest(Data: array of Byte; Count: Integer): array of Byte;
method Digest(Data: array of Byte): array of Byte;
class method ComputeHash(Data: array of Byte; Algorithm: DigestAlgorithm): array of Byte;
end;
implementation
constructor MessageDigest(Algorithm: DigestAlgorithm);
begin
{$IF COOPER}
case Algorithm of
DigestAlgorithm.MD5: exit java.security.MessageDigest.getInstance("MD5");
DigestAlgorithm.SHA1: exit java.security.MessageDigest.getInstance("SHA-1");
DigestAlgorithm.SHA256: exit java.security.MessageDigest.getInstance("SHA-256");
DigestAlgorithm.SHA384: exit java.security.MessageDigest.getInstance("SHA-384");
DigestAlgorithm.SHA512: exit java.security.MessageDigest.getInstance("SHA-512");
else
raise new SugarNotImplementedException;
end;
{$ELSEIF NETFX_CORE}
case Algorithm of
DigestAlgorithm.MD5: exit HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5).CreateHash;
DigestAlgorithm.SHA1: exit HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1).CreateHash;
DigestAlgorithm.SHA256: exit HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256).CreateHash;
DigestAlgorithm.SHA384: exit HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha384).CreateHash;
DigestAlgorithm.SHA512: exit HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512).CreateHash;
else
raise new SugarNotImplementedException;
end;
{$ELSEIF WINDOWS_PHONE}
case Algorithm of
DigestAlgorithm.MD5: exit new Sugar.Cryptography.MD5Managed;
DigestAlgorithm.SHA1: exit new SHA1Managed;
DigestAlgorithm.SHA256: exit new SHA256Managed;
DigestAlgorithm.SHA384: exit new Sugar.Cryptography.SHA384Managed;
DigestAlgorithm.SHA512: exit new Sugar.Cryptography.SHA512Managed;
else
raise new SugarNotImplementedException;
end;
{$ELSEIF ECHOES}
case Algorithm of
DigestAlgorithm.MD5: exit MD5.Create();
DigestAlgorithm.SHA1: exit SHA1.Create;
DigestAlgorithm.SHA256: exit SHA256.Create;
DigestAlgorithm.SHA384: exit SHA384.Create;
DigestAlgorithm.SHA512: exit SHA512.Create;
else
raise new SugarNotImplementedException;
end;
{$ELSEIF TOFFEE}
case Algorithm of
DigestAlgorithm.MD5: result := new MD5;
DigestAlgorithm.SHA1: result := new SHA1;
DigestAlgorithm.SHA256: result := new SHA256;
DigestAlgorithm.SHA384: result := new SHA384;
DigestAlgorithm.SHA512: result := new SHA512;
else
raise new SugarNotImplementedException;
end;
result.Reset;
{$ENDIF}
end;
method MessageDigest.Update(Data: array of Byte; Offset: Integer; Count: Integer);
begin
if Data = nil then
raise new SugarArgumentNullException("Data");
if not ((Offset = 0) and (Count = 0)) then
RangeHelper.Validate(Range.MakeRange(Offset, Count), Data.Length);
{$IF COOPER}
mapped.update(Data, Offset, Count);
{$ELSEIF NETFX_CORE}
var lData := new Byte[Count];
Array.Copy(Data, Offset, lData, 0, Count);
var Buffer := Windows.Security.Cryptography.CryptographicBuffer.CreateFromByteArray(lData);
mapped.Append(Buffer);
{$ELSEIF ECHOES}
mapped.TransformBlock(Data, Offset, Count, nil, 0);
{$ELSEIF TOFFEE}
{$ENDIF}
end;
method MessageDigest.Update(Data: array of Byte; Count: Integer);
begin
Update(Data, 0, Count);
end;
method MessageDigest.Update(Data: array of Byte);
begin
if Data = nil then
raise new SugarArgumentNullException("Data");
Update(Data, 0, Data.Length);
end;
method MessageDigest.Digest(Data: array of Byte; Offset: Integer; Count: Integer): array of Byte;
begin
if Data = nil then
raise new SugarArgumentNullException("Data");
if not ((Offset = 0) and (Count = 0)) then
RangeHelper.Validate(Range.MakeRange(Offset, Count), Data.Length);
{$IF COOPER}
mapped.update(Data, Offset, Count);
result := mapped.digest;
{$ELSEIF NETFX_CORE}
var lData := new Byte[Count];
Array.Copy(Data, Offset, lData, 0, Count);
var Buffer := Windows.Security.Cryptography.CryptographicBuffer.CreateFromByteArray(lData);
mapped.Append(Buffer);
Buffer := mapped.GetValueAndReset;
result := new Byte[Buffer.Length];
Windows.Security.Cryptography.CryptographicBuffer.CopyToByteArray(Buffer, result);
{$ELSEIF ECHOES}
mapped.TransformFinalBlock(Data, Offset, Count);
result := mapped.Hash;
mapped.Initialize;
{$ELSEIF TOFFEE}
{$ENDIF}
end;
method MessageDigest.Digest(Data: array of Byte; Count: Integer): array of Byte;
begin
exit Digest(Data, 0, Count);
end;
method MessageDigest.Digest(Data: array of Byte): array of Byte;
begin
if Data = nil then
raise new SugarArgumentNullException("Data");
exit Digest(Data, 0, Data.Length);
end;
method MessageDigest.Reset;
begin
{$IF COOPER}
mapped.reset;
{$ELSEIF NETFX_CORE}
mapped.GetValueAndReset;
{$ELSEIF ECHOES}
mapped.Initialize;
{$ELSEIF TOFFEE}
{$ENDIF}
end;
class method MessageDigest.ComputeHash(Data: array of Byte; Algorithm: DigestAlgorithm): array of Byte;
begin
var lDigest := new MessageDigest(Algorithm);
exit lDigest.Digest(Data);
end;
end. |
(* ***** BEGIN LICENSE BLOCK *****
* Version: GNU GPL 2.0
*
* The contents of this file are subject to the
* GNU General Public License Version 2.0; 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/licenses/gpl.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is GuiMain (https://code.google.com/p/escan-notifier/)
*
* The Initial Developer of the Original Code is
* Yann Papouin <yann.papouin at @ gmail.com>
*
* ***** END LICENSE BLOCK ***** *)
unit GuiMain;
interface
uses
JvGnugettext,
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
Mapi,
JclFileUtils,
ActnList,
SpTBXItem,
SpTBXControls,
StdCtrls,
SpTBXEditors,
Generics.Collections,
ExtCtrls,
JvComponentBase,
JvTrayIcon,
ImgList,
PngImageList,
Menus,
TB2Item,
JvAppStorage,
JvAppIniStorage,
ACS_Classes,
ACS_DXAudio,
ACS_WinMedia,
ACS_smpeg,
ACS_Vorbis,
ACS_Wave,
ACS_Converters,
NewACDSAudio,
JvAppXMLStorage,
JvAppInst,
GuiUpdateManager, IdContext, IdBaseComponent, IdComponent, IdCustomTCPServer,
IdTCPServer, IdCmdTCPServer, IdExplicitTLSClientServerBase, IdSMTPServer,
IdEMailAddress, IdTCPConnection, IdTCPClient, IdMessageClient, IdSMTPBase, IdSMTP,
IdAttachmentFile,
IdMessage, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL;
type
TWindow = class
Title: string;
Classname: string;
Handle: cardinal;
PID: cardinal;
end;
TWindowList = TObjectList<TWindow>;
TEpsonStatus = (es_unknown, es_idle, es_preview, es_scanning);
TMainForm = class(TForm)
Actions: TActionList;
FindProgress: TAction;
Checker: TTimer;
Tray: TJvTrayIcon;
Images: TPngImageList;
TrayPopupMenu: TSpTBXPopupMenu;
Quit: TAction;
SpTBXItem1: TSpTBXItem;
Settings: TAction;
SpTBXItem2: TSpTBXItem;
SpTBXSeparatorItem1: TSpTBXSeparatorItem;
MP3In: TMP3In;
ApplySettings: TAction;
ApplicationRun: TAction;
DSAudioOut: TDSAudioOut;
AudioCache: TAudioCache;
AppStorage: TJvAppXMLFileStorage;
AppInstances: TJvAppInstances;
MouseIdleCheck: TTimer;
SpTBXItem3: TSpTBXItem;
NewVersionAvailable: TAction;
About: TAction;
SpTBXItem4: TSpTBXItem;
SMTP: TIdSMTP;
MailMessage: TIdMessage;
SSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
test: TAction;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FindProgressExecute(Sender: TObject);
procedure CheckerTimer(Sender: TObject);
procedure QuitExecute(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure SettingsExecute(Sender: TObject);
procedure ApplySettingsExecute(Sender: TObject);
procedure ApplicationRunExecute(Sender: TObject);
procedure MouseIdleCheckTimer(Sender: TObject);
procedure NewVersionAvailableExecute(Sender: TObject);
procedure AboutExecute(Sender: TObject);
procedure testExecute(Sender: TObject);
private
FWindowList: TWindowList;
FChildrenList: TWindowList;
FPreviewWindow: TWindow;
FRunningWindow: TWindow;
FMouseIdleCount: integer;
FLastPosition: TPoint;
FStatus: TEpsonStatus;
FEpsonStatus: TEpsonStatus;
procedure SetEpsonStatus(const Value: TEpsonStatus);
procedure SetMouseIdleCount(const Value: integer);
procedure UpdateReply(Sender: TObject; Result: TUpdateResult);
function MailSend(Subject: string; Body: string = ''): Boolean;
public
AppPath, DataPath, SharePath, SoundPath: string;
MailAttachments: TStringList;
MailBody: TStringList;
procedure Play;
property EpsonStatus: TEpsonStatus read FEpsonStatus write SetEpsonStatus;
property MouseIdleCount: integer read FMouseIdleCount write SetMouseIdleCount;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
GuiAbout,
GuiSettings,
ComObj,
PsAPI,
TlHelp32;
const
ICO_IDLE = 5;
ICO_PREVIEW = 6;
ICO_SCANNING = 1;
const
RsSystemIdleProcess = 'System Idle Process';
RsSystemProcess = 'System Process';
function IsWinXP: Boolean;
begin
Result := (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion = 5) and (Win32MinorVersion = 1);
end;
function IsWin2k: Boolean;
begin
Result := (Win32MajorVersion >= 5) and (Win32Platform = VER_PLATFORM_WIN32_NT);
end;
function IsWinNT4: Boolean;
begin
Result := Win32Platform = VER_PLATFORM_WIN32_NT;
Result := Result and (Win32MajorVersion = 4);
end;
function IsWin3X: Boolean;
begin
Result := Win32Platform = VER_PLATFORM_WIN32_NT;
Result := Result and (Win32MajorVersion = 3) and ((Win32MinorVersion = 1) or (Win32MinorVersion = 5) or (Win32MinorVersion = 51));
end;
function RunningProcessesList(const List: TStrings; FullPath: Boolean): Boolean;
function ProcessFileName(PID: DWORD): string;
var
Handle: THandle;
begin
Result := '';
Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID);
if Handle <> 0 then
try
SetLength(Result, MAX_PATH);
if FullPath then
begin
if GetModuleFileNameEx(Handle, 0, PChar(Result), MAX_PATH) > 0 then
SetLength(Result, StrLen(PChar(Result)))
else
Result := '';
end
else
begin
if GetModuleBaseNameA(Handle, 0, PAnsiChar(Result), MAX_PATH) > 0 then
SetLength(Result, StrLen(PChar(Result)))
else
Result := '';
end;
finally
CloseHandle(Handle);
end;
end;
function BuildListTH: Boolean;
var
SnapProcHandle: THandle;
ProcEntry: TProcessEntry32;
NextProc: Boolean;
FileName: string;
begin
SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
Result := (SnapProcHandle <> INVALID_HANDLE_VALUE);
if Result then
try
ProcEntry.dwSize := SizeOf(ProcEntry);
NextProc := Process32First(SnapProcHandle, ProcEntry);
while NextProc do
begin
if ProcEntry.th32ProcessID = 0 then
begin
FileName := RsSystemIdleProcess;
end
else
begin
if IsWin2k or IsWinXP then
begin
FileName := ProcessFileName(ProcEntry.th32ProcessID);
if FileName = '' then
FileName := ProcEntry.szExeFile;
end
else
begin
FileName := ProcEntry.szExeFile;
if not FullPath then
FileName := ExtractFileName(FileName);
end;
end;
List.AddObject(FileName, Pointer(ProcEntry.th32ProcessID));
NextProc := Process32Next(SnapProcHandle, ProcEntry);
end;
finally
CloseHandle(SnapProcHandle);
end;
end;
function BuildListPS: Boolean;
var
PIDs: array [0 .. 1024] of DWORD;
Needed: DWORD;
I: integer;
FileName: string;
begin
Result := EnumProcesses(@PIDs, SizeOf(PIDs), Needed);
if Result then
begin
for I := 0 to (Needed div SizeOf(DWORD)) - 1 do
begin
case PIDs[I] of
0:
FileName := RsSystemIdleProcess;
2:
if IsWinNT4 then
FileName := RsSystemProcess
else
FileName := ProcessFileName(PIDs[I]);
8:
if IsWin2k or IsWinXP then
FileName := RsSystemProcess
else
FileName := ProcessFileName(PIDs[I]);
else
FileName := ProcessFileName(PIDs[I]);
end;
if FileName <> '' then
List.AddObject(FileName, Pointer(PIDs[I]));
end;
end;
end;
begin
if IsWin3X or IsWinNT4 then
Result := BuildListPS
else
Result := BuildListTH;
end;
function GetProcessNameFromWnd(Wnd: HWND): string;
var
List: TStringList;
PID: DWORD;
I: integer;
begin
Result := '';
if IsWindow(Wnd) then
begin
PID := INVALID_HANDLE_VALUE;
GetWindowThreadProcessId(Wnd, @PID);
List := TStringList.Create;
try
if RunningProcessesList(List, True) then
begin
I := List.IndexOfObject(Pointer(PID));
if I > -1 then
Result := List[I];
end;
finally
List.Free;
end;
end;
end;
function EnumChildren(hHwnd: THandle; var lParam: THandle): Boolean; stdcall;
var
pPid: DWORD;
Title, Classname: string;
AWindow: TWindow;
begin
// if the returned value in null the
// callback has failed, so set to false and exit.
if (hHwnd = NULL) then
begin
Result := False;
end
else
begin
// additional functions to get more
// information about a process.
// get the Process Identification number.
GetWindowThreadProcessId(hHwnd, pPid);
// set a memory area to receive
// the process class name
SetLength(Classname, 255);
// get the class name and reset the
// memory area to the size of the name
SetLength(Classname, GetClassName(hHwnd, PChar(Classname), Length(Classname)));
SetLength(Title, 255);
// get the process title; usually displayed
// on the top bar in visible process
SetLength(Title, GetWindowText(hHwnd, PChar(Title), Length(Title)));
// Display the process information
// by adding it to a list box
AWindow := TWindow.Create;
AWindow.Title := Title;
AWindow.Classname := Classname;
AWindow.Handle := hHwnd;
AWindow.PID := pPid;
MainForm.FChildrenList.Add(AWindow);
Result := True;
end;
end;
function EnumProcess(hHwnd: THandle; var lParam: THandle): Boolean; stdcall;
var
pPid: DWORD;
Title, Classname: string;
AWindow: TWindow;
begin
// if the returned value in null the
// callback has failed, so set to false and exit.
if (hHwnd = NULL) then
begin
Result := False;
end
else
begin
// additional functions to get more
// information about a process.
// get the Process Identification number.
GetWindowThreadProcessId(hHwnd, pPid);
// set a memory area to receive
// the process class name
SetLength(Classname, 255);
// get the class name and reset the
// memory area to the size of the name
SetLength(Classname, GetClassName(hHwnd, PChar(Classname), Length(Classname)));
SetLength(Title, 255);
// get the process title; usually displayed
// on the top bar in visible process
SetLength(Title, GetWindowText(hHwnd, PChar(Title), Length(Title)));
// Display the process information
// by adding it to a list box
AWindow := TWindow.Create;
AWindow.Title := Title;
AWindow.Classname := Classname;
AWindow.Handle := hHwnd;
AWindow.PID := pPid;
MainForm.FWindowList.Add(AWindow);
Result := True;
end;
end;
procedure SendMail(const Subject: string; const Body: string);
var
SMTP: TIdSMTP;
Email: TIdMessage;
SSLHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
SMTP := TIdSMTP.Create(nil);
Email := TIdMessage.Create(nil);
SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
try
//SSLHandler.MaxLineAction := maException;
SSLHandler.SSLOptions.Method := sslvTLSv1;
SSLHandler.SSLOptions.Mode := sslmUnassigned;
SSLHandler.SSLOptions.VerifyMode := [];
SSLHandler.SSLOptions.VerifyDepth := 0;
SMTP.IOHandler := SSLHandler;
SMTP.Host := SettingsForm.SmtpHost.Text;
SMTP.Port := SettingsForm.SmtpPort.SpinOptions.ValueAsInteger;
SMTP.Username := SettingsForm.SmtpUsername.Text;
SMTP.Password := SettingsForm.SmtpPassword.Text;
SMTP.UseTLS := utUseExplicitTLS;
Email.From.Address := SettingsForm.EMailAddress.Text;
Email.Recipients.EmailAddresses := SettingsForm.EMailAddress.Text;
Email.Subject := Subject;
Email.Body.Text := Body;
SMTP.Connect;
SMTP.Send(Email);
SMTP.Disconnect;
finally
SMTP.Free;
Email.Free;
SSLHandler.Free;
end;
end;
function TMainForm.MailSend(Subject: string; Body: string = ''): Boolean;
var
i: integer;
MailItem: TIdEMailAddressItem;
begin
Result := False;
// Setup SMTP
SMTP.Host := SettingsForm.SmtpHost.Text;
SMTP.Port := SettingsForm.SmtpPort.SpinOptions.ValueAsInteger;
SMTP.Username := SettingsForm.SmtpUsername.Text;
SMTP.Password := SettingsForm.SmtpPassword.Text;
// Setup mail message
MailMessage.Clear;
MailMessage.From.Address := SettingsForm.EMailAddress.Text;
MailItem := MailMessage.Recipients.Add;
MailItem.Text := SettingsForm.EMailAddress.Text;
MailMessage.Subject := Format('[EScanNotifier] %s', [Subject]);
if MailBody.Count > 0 then
MailMessage.Body.Text := MailBody.Text
else
if Body <> EmptyStr then
MailMessage.Body.Text := Body
else
if MailAttachments.Count > 0 then
MailMessage.Body.Text := _('(See attachments)');
for i := 0 to MailAttachments.Count-1 do
if FileExists(MailAttachments[i]) then
TIdAttachmentFile.Create(MailMessage.MessageParts, MailAttachments[i]);
// Send mail
try
try
SMTP.ReadTimeout := 10000;
SMTP.Connect;
SMTP.Send(MailMessage);
Result := True;
except on E:Exception do
Showmessage( 'ERROR: ' + E.Message + SysErrorMessage(GetLastError));
end;
finally
try
if SMTP.Connected then
SMTP.Disconnect;
except on E:Exception do
Showmessage( 'ERROR: ' + E.Message + SysErrorMessage(GetLastError));
end;
end;
MailBody.Clear;
MailAttachments.Clear;
end;
procedure TMainForm.CheckerTimer(Sender: TObject);
var
Info: tagWINDOWINFO;
begin
FindProgress.Execute;
if FPreviewWindow <> nil then
begin
if GetWindowInfo(FPreviewWindow.Handle, Info) then
begin
EpsonStatus := es_preview;
end
else
FPreviewWindow := nil;
end
else if FRunningWindow <> nil then
begin
if GetWindowInfo(FRunningWindow.Handle, Info) then
begin
EpsonStatus := es_scanning;
end
else
FRunningWindow := nil;
end
else
begin
EpsonStatus := es_idle;
end;
end;
procedure TMainForm.FindProgressExecute(Sender: TObject);
var
ProcId: cardinal;
I, j: integer;
AWindow, CWindow: TWindow;
begin
FPreviewWindow := nil;
FRunningWindow := nil;
FWindowList.Clear;
EnumWindows(@EnumProcess, 0);
AWindow := nil;
CWindow := nil;
I := 0;
while I <= FWindowList.Count - 1 do
begin
AWindow := FWindowList[I];
// if (Pos('escndv.exe', GetProcessNameFromWnd(AWindow.Handle)) > 0) then
begin
FChildrenList.Clear;
EnumChildWindows(AWindow.Handle, @EnumChildren, 0);
for j := 0 to FChildrenList.Count - 1 do
begin
CWindow := FChildrenList[j];
if AWindow.Classname = '#32770' then
begin
if Pos('Pré-numérisation', CWindow.Title) > 0 then
FPreviewWindow := AWindow
else if Pos('Numérisation', CWindow.Title) > 0 then
FRunningWindow := AWindow;
end;
end;
end;
inc(I);
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
AppPath := ExtractFilePath(Application.ExeName);
DataPath := PathExtractPathDepth(AppPath, PathGetDepth(AppPath) - 1) + 'data\';
SharePath := PathExtractPathDepth(AppPath, PathGetDepth(AppPath) - 1) + 'share\';
SoundPath := SharePath + 'sounds\';
AppStorage.FileName := DataPath + 'settings.xml';
FWindowList := TWindowList.Create;
FChildrenList := TWindowList.Create;
MailAttachments := TStringList.Create;
MailBody := TStringList.Create;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
MailBody.Free;
MailAttachments.Free;
FChildrenList.Free;
FWindowList.Free;
end;
procedure TMainForm.MouseIdleCheckTimer(Sender: TObject);
var
CurrentPosition: TPoint;
begin
GetCursorPos(CurrentPosition);
if (CurrentPosition.X = FLastPosition.X) and (CurrentPosition.Y = FLastPosition.Y) then
begin
MouseIdleCount := MouseIdleCount + 1;
end
else
begin
MouseIdleCheck.Enabled := False;
end;
FLastPosition := CurrentPosition;
end;
procedure TMainForm.NewVersionAvailableExecute(Sender: TObject);
begin
UpdateManagerForm.ShowModal;
end;
procedure TMainForm.QuitExecute(Sender: TObject);
begin
Checker.Enabled := False;
Close;
end;
procedure TMainForm.testExecute(Sender: TObject);
begin
MailSend('Test', 'Test message');
end;
procedure TMainForm.SetEpsonStatus(const Value: TEpsonStatus);
begin
if Value <> FEpsonStatus then
begin
case Value of
es_idle:
begin
Tray.IconIndex := ICO_IDLE;
if FEpsonStatus = es_scanning then
begin
DSAudioOut.Run;
MouseIdleCount := 0;
MouseIdleCheck.Enabled := True;
GetCursorPos(FLastPosition);
if SettingsForm.SendMail.Checked then
begin
MailSend('Notification', 'Job completed');
end;
end
else if FEpsonStatus = es_preview then
begin
Beep;
end;
end;
es_preview:
begin
Tray.IconIndex := ICO_PREVIEW;
DSAudioOut.Stop;
MouseIdleCheck.Enabled := False;
end;
es_scanning:
begin
Tray.IconIndex := ICO_SCANNING;
DSAudioOut.Stop;
MouseIdleCheck.Enabled := False;
end;
end;
end;
FEpsonStatus := Value;
end;
procedure TMainForm.Play;
begin
if FileExists(MP3In.FileName) then
begin
if not(DSAudioOut.Status = tosPlaying) then
DSAudioOut.Run
end
else
Beep;
end;
procedure TMainForm.SetMouseIdleCount(const Value: integer);
begin
if (DSAudioOut.Status = tosPlaying) then
FMouseIdleCount := 0
else
FMouseIdleCount := Value;
if (FMouseIdleCount >= 30) then
begin
FMouseIdleCount := 0;
Play;
end;
end;
procedure TMainForm.AboutExecute(Sender: TObject);
begin
AboutForm.ShowModal;
end;
procedure TMainForm.ApplicationRunExecute(Sender: TObject);
begin
FStatus := es_unknown;
SettingsForm.FormStorage.RestoreFormPlacement;
ApplySettings.Execute;
UpdateManagerForm.OnUpdateReply := UpdateReply;
UpdateManagerForm.Check.Execute;
end;
procedure TMainForm.SettingsExecute(Sender: TObject);
begin
SettingsForm.ModalResult := mrNone;
if SettingsForm.ShowModal = mrOk then
begin
ApplySettings.Execute;
end;
end;
procedure TMainForm.ApplySettingsExecute(Sender: TObject);
begin
MP3In.FileName := SettingsForm.ScanSound.Text;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
DSAudioOut.Stop(False);
end;
procedure TMainForm.UpdateReply(Sender: TObject; Result: TUpdateResult);
begin
NewVersionAvailable.Enabled := True;
if Result = rs_UpdateFound then
begin
if not NewVersionAvailable.Visible then
begin
NewVersionAvailable.Visible := True;
NewVersionAvailable.Execute;
end
else
NewVersionAvailable.Visible := True;
end
else
begin
NewVersionAvailable.Visible := False;
end;
end;
end.
|
(*************************************************)
(** CSI 2111 (October,1995). TC2111 **)
(*************************************************)
program tc2111 (input, output) ;
uses Crt; (* Under Windows: uses WinCrt *)
(* the following constants give symbolic names for the opcodes *)
const lda = $0091 ; (* Load Accumulator from memory *)
sta = $0039 ; (* Store Accumulator into memory *)
cla = $0008 ; (* Clear (set to zero) the Accumulator *)
inc = $0010 ; (* Increment (add 1 to) the Accumulator *)
add = $0099 ; (* Add to the Accumulator *)
cp2 = $0060 ; (* (2's) Complement the Accumulator *)
jmp = $0015 ; (* Jump ("go to ") *)
jz = $0017 ; (* Jump if the Zero status bit is TRUE *)
jn = $0019 ; (* Jump if the Negative status bit is TRUE *)
dsp = $0001 ; (* Display (write on the screen) *)
hlt = $0064 ; (* Halt *)
(* Size of manipulated data *)
byteSize = false;
wordSize = true;
type bit = boolean ;
byte = $00..$FF ; (* $80..$7F , in 2's CF *)
word = $0000..$FFFF ; (* $8000..$7FFF, in 2's CF *)
memorySize = $0000..$1000;
var
program_name: string;
input_file: text ; (* Your machine language program *)
memory: array[memorySize] of byte ;
(* the following are the registers in the CPU *)
pc: word ; (* Program Counter *)
a: word ; (* Accumulator *)
opCode: word ; (* the OPCODE of the current instruction *)
opAddr: word ; (* the ADDRESS of the operand of the current instruction *)
z: bit ; (* "Zero" status bit *)
n: bit ; (* "Negative" status bit *)
h: bit ; (* "Halt" status bit *)
mar: word ; (* Memory Address Register *)
mdr: word ; (* Memory Data Register *)
rw: bit ; (* Read/Write bit. Read = True; Write = False *)
ds: bit ; (* Data Size bit. ByteSize = false; WordSize = true *)
(***************************************************************************)
function Int2Hex(int: word) : string;
(* Converts an integer to an hexadecimal string *)
var
hexDigit : byte;
hexString: string ;
begin
hexDigit := int MOD 16;
if hexDigit < $A
then hexString := chr(48+hexDigit)
else hexString := chr(55+hexDigit);
if int >= 16
then hexString := Int2Hex (int DIV 16) + hexString;
Int2Hex := hexString
end;
(***************************************************************************)
procedure loader ;
(* Reads a machine language program into memory from a file *)
var address: word ;
first_character, ch: char ;
begin
address := $0000 ;
while (not eof(input_file))
do begin
read(input_file,first_character);
if first_character <> ' ' (* non-blank indicates a comment *)
then repeat (* skip over comment *)
read(input_file,ch)
until (ch = first_character) or eoln(input_file) ;
while (not eoln(input_file))
do begin
read(input_file,memory[address]) ;
address := address + $0001
end ;
readln(input_file)
end;
writeln ('Program loaded. ', address,' bytes in memory.');
end ;
(***************************************************************************)
procedure access_memory;
begin
if rw
then begin
(* TRUE = read = copy a value from memory into the CPU *)
if ds = byteSize
then mdr := memory[mar]
else (* wordSize *) mdr := memory[mar] * $100 + memory[mar+1];
end
else begin
(* FALSE = write = copy a value into memory from the CPU *)
if ds = byteSize
then memory[mar] := mdr MOD $100 (* LSB *)
else begin (* wordSize *)
memory[mar] := mdr DIV $100; (* MSB *)
memory[mar+1] := mdr MOD $100; (* LSB *)
end
end
end ;
(***************************************************************************)
procedure controller ;
(* This implements the Fetch-Execute cycle *)
begin
pc := $0000 ; (* always start execution at location $0000 *)
h := false ; (* clear the Halt status bit *)
repeat
(* FETCH OPCODE *)
mar := pc ;
ds := wordSize ; (* OpCodes are Words *)
pc := pc + $0002 ; (* NOTE that pc is incremented immediately *)
rw := true ; (* Read *)
access_memory ;
opCode := mdr ; (* OpCode fetched from memory. *)
(* If the opcode is odd, it needs an operand. *)
(* FETCH THE ADDRESS OF THE OPERAND *)
if (opCode mod 2) = $0001 (* odd *)
then begin
mar := pc ;
ds := wordSize ;
pc := pc + $0002;(* NOTE that pc is incremented immediately *)
rw := true ;
access_memory ;
opAddr := mdr (* opAddr fetched from memory *)
end ;
(* EXECUTE THE OPERATION *)
case opCode of
lda: begin
mar := opAddr ; (* Get the Operand's value from memory *)
rw := true ;
ds := byteSize ; (* (value is a byte) *)
access_memory ;
a := mdr (* and load it in the Accumulator *)
end;
sta: begin
mdr := a ; (* Store the Accumulator *)
mar := opAddr ; (* into the Operand's address *)
rw := false ; (* False means "write" *)
ds := byteSize ; (* (value is a byte) *)
access_memory
end;
cla: begin
a := $0000 ; (* Clear (set to zero) the Accumulator *)
z := true ; (* set the Status Bits appropriately *)
n := false
end;
inc: begin
a := a + $0001 ; (* Increment (add 1 to) the Accumulator *)
z := (a = $0000); (* set the Status Bits appropriately *)
n := (a >= $8000)
end;
add: begin
mar := opAddr ; (* Get the Operand's value from memory *)
rw := true ;
ds := byteSize ;
access_memory ;
a := a + mdr ; (* and add it to the Accumulator *)
z := (a = $0000) ; (* set the Status Bits appropriately *)
n := (a >= $8000)
end;
cp2: begin
a := $FFFF - a + $0001 ;(* (2's) Complement the Accumulator *)
z := (a = $0000) ; (* set the Status Bits appropriately *)
n := (a >= $8000)
end;
jmp: pc := opAddr ; (* opAddr is the address of the next
instruction to execute *)
jz : if z then pc := opAddr ;(* Jump if the Z status bit is true *)
jn : if n then pc := opAddr ;(* Jump if the N status bit is true *)
hlt: h := true ; (* set the Halt status bit *)
dsp: begin
mar := opAddr ; (* Get the Operand's value from memory *)
rw := true ;
ds := byteSize ;
access_memory ;
writeln('memory location $',Int2Hex(mar):4,
' contains the value $', Int2Hex(mdr):2)
end
else
writeln('*** ERROR *** Unknown opCode $', Int2Hex(opCode):4,
' at address $', Int2Hex(pc-2):4)
end
until h (* continue the Fetch-Execute cycle until Halt bit is set *)
end ;
(***************************************************************************)
procedure identify_myself ; (**** CHANGE THIS TO DESCRIBE YOURSELF ****)
begin
clrscr;
writeln ;
writeln('CSI 2111 (December,1995) Project.') ;
writeln('first and last name, student# 0123456.') ;
writeln
end ;
(***************************************************************************)
begin { main program }
identify_myself ;
write('Program name: ');
readln(program_name);
assign(input_file, program_name) ;
reset(input_file) ;
loader ;
close(input_file);
controller ;
writeln ('End of program execution.');
readln ;
end.
|
unit SheetHandlerRegistry;
interface
uses
ObjectInspectorInterfaces;
procedure RegisterSheetHandler(aName : string; aFunct : TSheetHandlerCreatorFunction);
function GetSheetHandler(aName : string) : IPropertySheetHandler;
implementation
uses
SysUtils, Classes;
var
Handlers : TStringList = nil;
type
TRegHandler =
class
fFunct : TSheetHandlerCreatorFunction;
end;
procedure RegisterSheetHandler(aName : string; aFunct : TSheetHandlerCreatorFunction);
var
obj : TRegHandler;
begin
obj := TRegHandler.Create;
obj.fFunct := aFunct;
Handlers.AddObject(uppercase(aName), obj);
end;
function GetSheetHandler(aName : string) : IPropertySheetHandler;
var
index : integer;
obj : TRegHandler;
begin
index := Handlers.IndexOf(aName);
if index <> -1
then
begin
obj := TRegHandler(Handlers.Objects[index]);
if Assigned(obj.fFunct)
then result := obj.fFunct
else result := nil;
end
else result := nil;
end;
procedure ReleaseHandlers;
var
i : integer;
begin
for i := 0 to pred(Handlers.Count) do
Handlers.Objects[i].Free;
Handlers.Free;
end;
initialization
Handlers := TStringList.Create;
Handlers.Sorted := true;
Handlers.Duplicates := dupIgnore;
finalization
ReleaseHandlers;
end.
|
unit kwPopEditorWheelScroll;
{* *Формат:* aUp aVeritcal anEditorControl pop:editor:WheelScroll
*Описание:* Прокручивает документ к позиции скроллера. aVeritcal - если true, то скроллируем повертикали. aUp - сроллировать вверх, если true
*Пример:*
[code]
false true focused:control:push anEditorControl pop:editor:WheelScroll
[code] }
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwPopEditorWheelScroll.pas"
// Стереотип: "ScriptKeyword"
// Элемент модели: "pop_editor_WheelScroll" MUID: (4F4F5A730085)
// Имя типа: "TkwPopEditorWheelScroll"
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, kwEditorFromStackWord
, tfwScriptingInterfaces
, evCustomEditorWindow
;
type
TkwPopEditorWheelScroll = {final} class(TkwEditorFromStackWord)
{* *Формат:* aUp aVeritcal anEditorControl pop:editor:WheelScroll
*Описание:* Прокручивает документ к позиции скроллера. aVeritcal - если true, то скроллируем повертикали. aUp - сроллировать вверх, если true
*Пример:*
[code]
false true focused:control:push anEditorControl pop:editor:WheelScroll
[code] }
protected
procedure DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow); override;
class function GetWordNameForRegister: AnsiString; override;
end;//TkwPopEditorWheelScroll
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, Windows
{$If NOT Defined(NoVCL)}
, Controls
{$IfEnd} // NOT Defined(NoVCL)
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
//#UC START# *4F4F5A730085impl_uses*
//#UC END# *4F4F5A730085impl_uses*
;
procedure TkwPopEditorWheelScroll.DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow);
//#UC START# *4F4CB81200CA_4F4F5A730085_var*
var
l_Up : Boolean;
l_Vertical : Boolean;
//#UC END# *4F4CB81200CA_4F4F5A730085_var*
begin
//#UC START# *4F4CB81200CA_4F4F5A730085_impl*
if aCtx.rEngine.IsTopBool then
l_Vertical := aCtx.rEngine.PopBool
else
Assert(False, 'Не задана ориентация прокрукти!');
if aCtx.rEngine.IsTopBool then
l_Up := aCtx.rEngine.PopBool
else
Assert(False, 'Не задано направление прокрукти!');
with anEditor.View.Scroller[l_Vertical] do
if l_Up then
WheelUp
else
WheelDown;
//#UC END# *4F4CB81200CA_4F4F5A730085_impl*
end;//TkwPopEditorWheelScroll.DoWithEditor
class function TkwPopEditorWheelScroll.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:editor:WheelScroll';
end;//TkwPopEditorWheelScroll.GetWordNameForRegister
initialization
TkwPopEditorWheelScroll.RegisterInEngine;
{* Регистрация pop_editor_WheelScroll }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
PROGRAM Demo2;
{*******************************************************
** **
** DEMO2: Just some wild drawing... **
** **
*******************************************************}
USES
Crt,
VESA256;
PROCEDURE ExitRoutine;
{leave demo}
BEGIN
ScrollToPage(0,1.0);
HALT;
END; {ExitRoutine}
PROCEDURE WaitForUser;
{returns the moment something changes (mouse buttons and keyboard)}
BEGIN
ShowMouse;
REPEAT
MoveMouse
UNTIL NOT IsMouseButtonDown;
REPEAT
MoveMouse;
IF KeyPressed THEN
BEGIN
IF ReadKey = #27 THEN ExitRoutine ELSE BREAK;
END;
UNTIL IsMouseButtonDown;
HideMouse;
END; {WaitForUser}
PROCEDURE DrawSomething;
{a truly random drawing routine}
VAR Color,Pattern,
Width,BitBlit,
Index,Routine :BYTE;
X,Y :ARRAY[1..4] OF INTEGER;
S :PCHAR;
BEGIN
{style first}
Color := Random(256);
BitBlit := Random(8);
IF Random > 0.5 THEN
BEGIN
Pattern := Random(8);
Width := Random(3);
SetLineMode(Color,Pattern,Width,BitBlit);
END
ELSE
BEGIN
Pattern := Random(14);
SetFillMode(Color,Pattern,BitBlit);
END;
{random coordinates}
FOR Index := 1 TO 4 DO
BEGIN
X[Index] := Random(GetScreenWidth);
Y[Index] := Random(GetScreenHeight);
END;
{finally some kind of drawing routine}
Routine := Random(8);
CASE Routine OF
0 : Line(X[1],Y[1],X[2],Y[2]);
1 : Box(X[1],Y[1],X[2],Y[2]);
2 : Circle(X[1],Y[1],Random(150));
3 : Bezier(X[1],Y[1],X[2],Y[2],X[3],Y[3],X[4],Y[4]);
4 : Ellipse(X[1],Y[1],Random(150),Random(150));
5 : Bleed(X[1],Y[1],Color);
6 : CopyBox(X[1],Y[1],X[2],Y[2],Random(150),Random(150),BitBlit);
7 : PutText(X[1],Y[1],'Just a piece of Text',BOOLEAN(Random(2)),
Random(62),Color,Random(256),BitBlit);
END;
{tell what it was}
CASE Routine OF
0 : S := ' A Line ';
1 : S := ' A Box ';
2 : S := ' A Circle ';
3 : S := ' A Bezier Curve ';
4 : S := ' An Ellipse ';
5 : S := ' A Bleed Fill ';
6 : S := ' Copying a Box ';
7 : S := ' A Text ';
END;
PutText(10,10,S,FALSE,1,Yellow,Black,CopyBlit);
END; {DrawSomething}
BEGIN
Randomize;
TextColor(Yellow);
WriteLn;
WriteLn('Welcome to this simple VESA256 DEMO.');
WriteLn;
WriteLn('Simply push a key or a mouse button to continue the demo...');
WriteLn;
WriteLn('And press [Esc] to stop...');
WaitForUser;
IF StartVESA256(VESA640x480,Black) THEN
BEGIN
SetActivePage(1);
ClearGraphics(Black);
SetVisualPage(1);
SetMousePointers(0,0,'BIG.PCX','BIG.PCX','BIG.PCX');
REPEAT
DrawSomething;
WaitForUser;
UNTIL FALSE;
END
ELSE WriteLn('Your video card does not support VESA640x480.');
END.
|
{****************************************************************************}
{* SETUP.PAS: This file contains the routines to either put the board in *}
{* its normal start of game setup or a custom user defined setup. *}
{****************************************************************************}
{****************************************************************************}
{* Default Board Set Pieces: Puts the pieces on the board for the normal *}
{* initial configuration. *}
{****************************************************************************}
procedure DefaultBoardSetPieces;
var row, col : RowColType;
begin
{*** put in the row of pawns for each player ***}
for col := 1 to BOARD_SIZE do begin
Board[2,col].image := PAWN;
Board[7,col].image := PAWN;
end;
{*** blank out the middle of the board ***}
for row := 3 to 6 do
for col := 1 to BOARD_SIZE do
Board[row,col].image := BLANK;
{*** put in white's major pieces and then copy for black ***}
Board[1,1].image := ROOK;
Board[1,2].image := KNIGHT;
Board[1,3].image := BISHOP;
Board[1,4].image := QUEEN;
Board[1,5].image := KING;
Board[1,6].image := BISHOP;
Board[1,7].image := KNIGHT;
Board[1,8].image := ROOK;
for col := 1 to BOARD_SIZE do
Board[8,col] := Board[1,col];
{*** set the piece colors for each side ***}
for row := 1 to 4 do
for col := 1 to BOARD_SIZE do begin
Board[row,col].color := C_WHITE;
Board[row,col].HasMoved := false;
Board[row+4,col].color := C_BLACK;
Board[row+4,col].HasMoved := false;
end;
end; {DefaultBoardSetPieces}
{****************************************************************************}
{* Default Board: Sets the pieces in their default positions and sets *}
{* some of the player attributes to their defaults. Some of the *}
{* attributes of the game are also set to their startup values. *}
{****************************************************************************}
procedure DefaultBoard;
var row,col : RowColType;
begin
DefaultBoardSetPieces;
{*** player attributes ***}
with Player[C_WHITE] do begin
CursorRow := 2;
CursorCol := 4;
InCheck := false;
KingRow := 1;
KingCol := 5;
ElapsedTime := 0;
LastMove.FromRow := NULL_MOVE;
end;
with Player[C_BLACK] do begin
CursorRow := 7;
CursorCol := 4;
InCheck := false;
KingRow := 8;
KingCol := 5;
ElapsedTime := 0;
LastMove.FromRow := NULL_MOVE;
end;
{*** game attributes ***}
Game.MoveNum := 1;
Game.MovesStored := 0;
Game.GameFinished := false;
Game.MovesPointer := 0;
Game.InCheck[0] := false;
Game.NonDevMoveCount[0] := 0;
end; {DefaultBoard}
{****************************************************************************}
{* Setup Board: Input a custom configuration of the pieces on the board *}
{* from the user. Will anyone actually read these comments. The user *}
{* moves the cursor to the square to be changed, and presses the key to *}
{* select the piece to put there. The standards K Q R B N P select a *}
{* piece and SPACE blanks out the square. The user can also clear the *}
{* board or ask for the default setup. RETURN saves the changes and asks *}
{* the user for the move number to continue the game from. ESCAPE *}
{* restores the setup upon entry to this routine and exits back to the *}
{* main menu. This routine is called from the main menu. *}
{****************************************************************************}
{$ifdef FPCHESS_DISPLAY_ON}
procedure SetupBoard;
var row, col, ClearRow, ClearCol : RowColType;
key : char;
image : PieceImageType;
LegalKey, InvalidSetup : boolean;
KingCount, Attacked, _Protected, Error, NewMoveNum : integer;
TempStr : string80;
SaveGame : GameType;
{----------------------------------------------------------------------------}
{ Put Piece On Board: Puts the global Image onto the board at the cursor }
{ position. If the image is not a blank, then the user is asked for the }
{ color (B or W). If the piece is a rook or king being placed in the }
{ piece's startup position, the user is asked if the piece has been moved }
{ since the start of the game. }
{----------------------------------------------------------------------------}
procedure PutPieceOnBoard;
var KingHomeRow, PawnHomeRow : RowColType;
begin
Board[row,col].image := image;
if (image = BLANK) then begin
Board[row,col].color := C_WHITE;
Board[row,col].HasMoved := false;
end else begin
{*** get color ***}
DisplayInstructions (INS_SETUP_COLOR);
repeat
key := GetKey;
until (key = 'B') or (key = 'W');
{*** check if piece has moved ***}
if key = 'W' then begin
Board[row,col].color := C_WHITE;
KingHomeRow := 1;
PawnHomeRow := 2;
end else begin
Board[row,col].color := C_BLACK;
KingHomeRow := 8;
PawnHomeRow := 7;
end;
{*** may have to ask if piece has been moved ***}
if ((image = KING) and (row = KingHomeRow) and (col = 5))
or ((image = ROOK) and (row = KingHomeRow) and ((col = 1) or (col = 8))) then begin
DisplayInstructions (INS_SETUP_MOVED);
repeat
key := GetKey;
until (key = 'Y') or (key = 'N');
Board[row,col].HasMoved := key = 'Y';
end else
Board[row, col].HasMoved := not ((image = PAWN) and (row = PawnHomeRow));
DisplaySquare (row, col, false);
DisplayInstructions (INS_SETUP);
end;
end; {PutPieceOnBoard}
{----------------------------------------------------------------------------}
{ Check Valid Setup: Makes sure that each player has exactly one king on }
{ the board and updates the Player's King location attributes. Both kings }
{ cannot be in check. The other relevant player attributes are set to. }
{----------------------------------------------------------------------------}
procedure CheckValidSetup;
const NULL_ROW = NULL_MOVE;
var row, col : RowColType;
begin
{*** locate kings ***}
Player[C_WHITE].KingRow := NULL_ROW;
Player[C_BLACK].KingRow := NULL_ROW;
KingCount := 0;
for row := 1 to BOARD_SIZE do
for col := 1 to BOARD_SIZE do
if (Board[row, col].image = KING) then begin
KingCount := KingCount + 1;
Player[Board[row, col].color].KingRow := row;
Player[Board[row, col].color].KingCol := col;
end;
InvalidSetup := (KingCount <> 2) or (Player[C_WHITE].KingRow = NULL_ROW)
or (Player[C_BLACK].KingRow = NULL_ROW);
{*** make sure both kings are not in check ***}
if not InvalidSetup then begin
AttackedBy (Player[C_WHITE].KingRow, Player[C_WHITE].KingCol, Attacked, _Protected);
Player[C_WHITE].InCheck := (Attacked <> 0);
AttackedBy (Player[C_BLACK].KingRow, Player[C_BLACK].KingCol, Attacked, _Protected);
Player[C_BLACK].InCheck := (Attacked <> 0);
InvalidSetup := (Player[C_WHITE].InCheck) and (Player[C_BLACK].InCheck);
end;
{*** set other player attributes ***}
Game.GameFinished := false;
with Player[C_WHITE] do begin
CursorRow := 2;
CursorCol := 4;
LastMove.FromRow := NULL_MOVE;
end;
with Player[C_BLACK] do begin
CursorRow := 7;
CursorCol := 4;
LastMove.FromRow := NULL_MOVE;
end;
DisplayConversationArea;
{*** report invalid setup ***}
if InvalidSetup then begin
SetColor (White);
SetFillStyle (SolidFill, Black);
Bar (0,INSTR_LINE, GetMaxX, GetMaxY);
SetTextStyle (TriplexFont, HorizDir, 3);
OutTextXY (0,INSTR_LINE, 'Illegal Setup - King(s) not set correctly. Press Key.');
MakeSound (false);
while GetKey = 'n' do ;
DisplayInstructions (INS_SETUP);
end;
end; {CheckValidSetup}
{----------------------------------------------------------------------------}
{ Get Move Num: Asks the user for the next move number of the game and }
{ whose turn it is to move next. If one of the players is in check, then }
{ that player is the one who must move next and the latter question is not }
{ asked. }
{----------------------------------------------------------------------------}
procedure GetMoveNum;
const ex = 190; ey = 40;
var cx, cy : integer;
begin
DisplayInstructions (INS_SETUP_MOVENUM);
Game.MovesStored := 0;
Game.MovesPointer := 0;
Game.InCheck[0] := (Player[C_WHITE].InCheck) or (Player[C_BLACK].InCheck);
{*** open up 'window' ***}
cx := (BOARD_X1 + BOARD_X2) div 2;
cy := (BOARD_Y1 + BOARD_Y2) div 2;
SetFillStyle (SolidFill, DarkGray);
Bar (cx - ex, cy - ey, cx + ex, cy + ey);
{*** ask for move number ***}
SetTextStyle (DefaultFont, HorizDir, 2);
SetColor (Yellow);
Str ((Game.MoveNum + 1) div 2, TempStr);
UserInput (67, cy - 18, 4, 'Move Number: ', TempStr);
Val (TempStr, NewMoveNum, Error);
if Error <> 0 then
NewMoveNum := 1
else
NewMoveNum := NewMoveNum * 2 - 1;
{*** ask for whose turn to move next if not in check ***}
if Game.InCheck[0] then begin
if Player[C_BLACK].InCheck then NewMoveNum := NewMoveNum + 1
end else begin
if Game.MoveNum mod 2 = 1 then
TempStr := 'W'
else
TempStr := 'B';
UserInput (67, cy + 4, 1, 'Next Player (B/W): ', TempStr);
if TempStr = 'B' then NewMoveNum := NewMoveNum + 1;
end;
Game.MoveNum := NewMoveNum;
Game.NonDevMoveCount[0] := 0;
DisplayWhoseMove;
end; {GetMoveNum}
{----------------------------------------------------------------------------}
begin {SetupBoard}
DisplayInstructions (INS_SETUP);
{*** remember old setup incase of escape ***}
SaveGame := Game;
SaveGame.Player := Player;
SaveGame.FinalBoard := Board;
row := 4;
col := 4;
repeat
repeat
{*** move cursor and get key ***}
MoveCursor (row, col, C_WHITE, false, key);
LegalKey := true;
{*** interpret key ***}
case key of
'K': image := KING;
'Q': image := QUEEN;
'R': image := ROOK;
'B': image := BISHOP;
'N': image := KNIGHT;
'P': begin
image := PAWN;
if (row = 1) or (row = 8) then begin
LegalKey := false;
MakeSound (false);
end;
end;
' ': image := BLANK;
{*** clear board ***}
'C': begin
for ClearRow := 1 to BOARD_SIZE do
for ClearCol := 1 to BOARD_SIZE do
Board[ClearRow, ClearCol].image := BLANK;
DisplayBoard;
LegalKey := false;
end;
{*** default setup of pieces ***}
'D': begin
DefaultBoardSetPieces;
DisplayBoard;
LegalKey := false;
end;
else LegalKey := false;
end;
if LegalKey then PutPieceOnBoard;
until (key = 'e') or (key = 'x');
{*** make sure setup is valid and repeat above if not ***}
if (key = 'x') then
InvalidSetup := false
else
CheckValidSetup;
until not InvalidSetup;
if (key = 'x') then begin
{*** restore the old setup if user presses escape ***}
Game := SaveGame;
Player := SaveGame.Player;
Board := SaveGame.FinalBoard;
end else
GetMoveNum;
DisplayBoard;
end; {SetupBoard}
{$endif}
{*** end of SETUP.PAS include file ***}
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_UIVirtualKeyboard
* Implements a virtual keyboard widget
***********************************************************************************************************************
}
Unit TERRA_UIVirtualKeyboard;
{$I terra.inc}
Interface
Uses TERRA_String, TERRA_UI, TERRA_Utils, TERRA_Color, TERRA_Log, TERRA_Localization;
Const
// key types
keyNormal = 0;
keySpecial = 1;
keyLarge = 2;
MaxKeyboardRows = 16;
MaxKeyboardLines = 5;
Type
KeyboardLayoutKey = Record
Value:TERRAChar;
Alt:TERRAChar;
End;
KeyboardLayout = Class(TERRAObject)
Protected
_Desc:TERRAString;
_Lines:Array[0..Pred(MaxKeyboardRows), 0..MaxKeyboardLines-2] Of KeyboardLayoutKey;
_HasShift:Boolean;
_HasPinyin:Boolean;
Public
End;
UIVirtualKeyboardKey = Class(Widget)
Protected
_Label:TERRAString;
_Suggestion:Integer;
_Row:Integer;
_Line:Integer;
_KeyType:Integer;
Procedure StartHighlight; Override;
Procedure StopHighlight; Override;
Function HasMouseOver():Boolean; Override;
Function GetKeyWidth():Integer;
Function GetKeyHeight():Integer;
Procedure OnLanguageChange(); Override;
Public
Callback:WidgetEventHandler;
Constructor Create(Parent:Widget; UI:UI; X, Y, Z: Single);
Procedure Render; Override;
Procedure UpdateRects; Override;
Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override;
Function OnMouseUp(X,Y:Integer;Button:Word):Boolean; Override;
End;
VirtualKeyboard = Class(Widget)
Protected
_KbScale:Single;
_PreviousLayout:Integer;
_CurrentLayout:Integer;
_QueuedLayout:Integer;
_LayoutContext:Integer;
_ShiftMode:Boolean;
_Keys:Array[0..Pred(MaxKeyboardRows), 0..Pred(MaxKeyboardLines)] Of UIVirtualKeyboardKey;
_BackKey:UIVirtualKeyboardKey;
_EnterKey:UIVirtualKeyboardKey;
_PreviousHighlight:Widget;
_Pinyin:PinyinConverter;
Function AddKey(Row, Line:Integer):UIVirtualKeyboardKey; Overload;
Function AddKey(KeyType:Integer; Name:TERRAString; Row, Line:Integer; Callback:WidgetEventHandler):UIVirtualKeyboardKey; Overload;
Procedure StartHighlight; Override;
Procedure StopHighlight; Override;
Function HasMouseOver():Boolean; Override;
Procedure Enable;
Function GetKeyAdvance(Key:UIVirtualKeyboardKey):Single;
Procedure DoKeyEvent(Row,Line:Integer);
Procedure UpdatePinyin();
Public
Constructor Create(Name:TERRAString; UI:UI; Z:Single);
Procedure Release; Override;
Procedure Render; Override;
Procedure UpdateRects; Override;
Function OnMouseDown(X,Y:Integer; Button:Word):Boolean; Override;
Function OnMouseUp(X,Y:Integer;Button:Word):Boolean; Override;
Procedure RestorePosition();
Procedure SelectKeyboardLayout(Index:Integer);
Function GetKeyValue(Row, Line:Integer):Word;
Procedure ShowFocus();
Procedure Close;
End;
Procedure AddDefaultKeyboardLayout();
Procedure AddKeyboardLayout(SourceFile:TERRAString);
Procedure AddKeyboardLayoutFromString(Src:TERRAString);
Function GetKeyboardLayout(ID:TERRAString):KeyboardLayout;
Procedure ClearKeyboardLayouts();
Const
DefaultKeyboardLayout = 'ABC|qwertyuiop|asdfghjkl||zxcvbnm!?|QWERTYUIOP|ASDFGHJKL||ZXCVBNM!?';
DefaultSymbolLayout = '123|1234567890|_#&$ELY()/||-+*":;=%[]';
Implementation
Uses TERRA_Vector2D, TERRA_Vector3D, TERRA_SpriteManager, TERRA_SoundManager,
TERRA_Widgets, TERRA_Texture, TERRA_Application, TERRA_OS, TERRA_FileManager,
TERRA_Stream;
Var
_KeyboardLayouts:Array Of KeyboardLayout;
_KeyboardLayoutCount:Integer;
_KeyboardLayoutContext:Integer;
Function KeyEventDispatcher(W:Widget):Boolean; Cdecl;
Var
Key:UIVirtualKeyboardKey;
VKB:VirtualKeyboard;
I:Integer;
Begin
Result := True;
Key := UIVirtualKeyboardKey(W);
If (Key = Nil) Then
Exit;
VKB := VirtualKeyboard(Key.Parent);
SoundManager.Instance.Play('ui_key');
If Assigned(Key.Callback) Then
Key.Callback(Key)
Else
If Assigned(Application.Instance()) Then
Begin
If (Key._Label<>'') Then
Begin
For I:=1 To Length(Key._Label) Do
Application.Instance.OnKeyPress(Ord(Key._Label[I]));
End Else
VKB.DoKeyEvent(Key._Row, Key._Line);
End;
End;
Function StringToValue(S:TERRAString):Integer;
Begin
If (S='') Then
Result := 0
Else
Result := Ord(S[1]);
End;
{ VirtualKeyboard }
Function VirtualKeyboard.AddKey(Row, Line:Integer):UIVirtualKeyboardKey;
Begin
Result := AddKey(keyNormal, '', Row, Line, Nil);
End;
Function VirtualKeyboard.AddKey(KeyType:Integer; Name:TERRAString; Row, Line:Integer; Callback:WidgetEventHandler):UIVirtualKeyboardKey;
Var
I:Integer;
Key:UIVirtualKeyboardKey;
Begin
Key := UIVirtualKeyboardKey.Create(Self, UI, 0, 0, 0.5);
Key._KeyType := KeyType;
Key.Callback := Callback;
Key._Suggestion := -1;
Key._Key := StringUpper('key_'+IntToString(Row)+'_'+IntToString(Line));
Key._Label := Name;
Key._Row := Row;
Key._Line := Line;
_Keys[Row, Line] := Key;
Result := Key;
End;
Function BackCallback(W:Widget):Boolean; Cdecl;
Var
Key:UIVirtualKeyboardKey;
VKB:VirtualKeyboard;
Begin
Result := True;
Key := UIVirtualKeyboardKey(W);
If (Key = Nil) Then
Exit;
VKB := VirtualKeyboard(Key.Parent);
If (VKB = Nil) Then
Exit;
If Assigned(Application.Instance()) Then
Begin
Application.Instance.OnKeyPress(keyBackspace);
VKB.UpdatePinyin();
End;
End;
Function EnterCallback(W:Widget):Boolean; Cdecl;
Var
Key:UIVirtualKeyboardKey;
VKB:VirtualKeyboard;
Begin
Result := True;
Key := UIVirtualKeyboardKey(W);
If (Key = Nil) Then
Exit;
VKB := VirtualKeyboard(Key.Parent);
If (VKB = Nil) Then
Exit;
Application.Instance.OnKeyPress(keyEnter);
If (VKB.UI.Focus<>Nil) And (VKB.UI.Focus Is UIEditText) And (UIEditText(VKB.UI.Focus).LineCount=1) Then
VKB.Close();
End;
Function CloseCallback(W:Widget):Boolean; Cdecl;
Var
Key:UIVirtualKeyboardKey;
VKB:VirtualKeyboard;
Begin
Result := True;
Key := UIVirtualKeyboardKey(W);
If (Key = Nil) Then
Exit;
VKB := VirtualKeyboard(Key.Parent);
If (VKB = Nil) Then
Exit;
VKB.Close();
End;
Function ShiftCallback(W:Widget):Boolean; Cdecl;
Var
Key:UIVirtualKeyboardKey;
VKB:VirtualKeyboard;
Begin
Result := True;
Key := UIVirtualKeyboardKey(W);
If (Key = Nil) Then
Exit;
VKB := VirtualKeyboard(Key.Parent);
If (VKB = Nil) Then
Exit;
VKB._ShiftMode := Not VKB._ShiftMode;
End;
Function LanguageCallback(W:Widget):Boolean; Cdecl;
Var
Key:UIVirtualKeyboardKey;
VKB:VirtualKeyboard;
Begin
Result := True;
Key := UIVirtualKeyboardKey(W);
If (Key = Nil) Then
Exit;
VKB := VirtualKeyboard(Key.Parent);
If (VKB = Nil) Then
Exit;
Inc(VKB._CurrentLayout);
If (VKB._CurrentLayout>=_KeyboardLayoutCount) Then
VKB._CurrentLayout := 1;
VKB.SelectKeyboardLayout(VKB._CurrentLayout);
End;
Function SymbolsCallback(W:Widget):Boolean; Cdecl;
Var
Key:UIVirtualKeyboardKey;
VKB:VirtualKeyboard;
Begin
Result := True;
Key := UIVirtualKeyboardKey(W);
If (Key = Nil) Then
Exit;
VKB := VirtualKeyboard(Key.Parent);
If (VKB = Nil) Then
Exit;
If (VKB._CurrentLayout=0) Then
VKB.SelectKeyboardLayout(VKB._PreviousLayout)
Else
Begin
VKB._PreviousLayout := VKB._CurrentLayout;
VKB.SelectKeyboardLayout(0);
End;
End;
Constructor VirtualKeyboard.Create(Name:TERRAString; UI:UI; Z: Single);
Var
I:Integer;
Begin
Inherited Create(Name, UI, Parent);
Self.UpdateRects();
Self._LayoutContext := -1;
Self._TabIndex := -1;
Self.RestorePosition();
Self._Layer := Z;
Self.LoadComponent('ui_kb_bg');
_CurrentLayout := 0;
For I:=0 To (MaxKeyboardRows-2) Do
AddKey(I, 0);
_BackKey := AddKey(keySpecial, 'Back', Pred(MaxKeyboardrows), 0, BackCallback);
For I:=0 To (MaxKeyboardRows-2) Do
AddKey(I, 1);
_EnterKey := AddKey(keySpecial, 'Enter', Pred(MaxKeyboardrows), 1, EnterCallback);
For I:=0 To Pred(MaxKeyboardRows) Do
AddKey(I, 2);
AddKey(keySpecial, 'Shift', 0, 3, ShiftCallback);
For I:=1 To (MaxKeyboardRows-1) Do
AddKey(I, 3);
AddKey(keySpecial, '?123', 0, 4, SymbolsCallback);
AddKey(keySpecial, 'Lang', 1, 4, LanguageCallback);
AddKey(keySpecial, '@', 2, 4, Nil);
AddKey(keyLarge, ' ', 3, 4, Nil);
AddKey(keySpecial, ',', 4, 4, Nil);
AddKey(keySpecial, '.', 5, 4, Nil);
AddKey(keySpecial, 'Close', 6, 4, CloseCallback);
_QueuedLayout := -1;
_CurrentLayout := -1;
Visible := False;
End;
{Class Function VirtualKeyboard.Instance: VirtualKeyboard;
Begin
If (_VKB = Nil) Then
Begin
_VKB := VirtualKeyboard.Create('_vkb', 97);
_VKB.Visible := False;
End;
Result := _VKB;
End;}
Function VirtualKeyboard.OnMouseUp(X, Y: Integer; Button: Word): Boolean;
Var
I,J:Integer;
Begin
For J:=0 To Pred(MaxKeyboardLines) Do
For I:=0 To Pred(MaxKeyboardRows) Do
If (_Keys[I,J]<>Nil) And (_Keys[I,J].Visible) And (_Keys[I,J].OnMouseUp(X, Y, Button)) Then
Begin
Result := True;
Exit;
End;
Result := False;
End;
Procedure VirtualKeyboard.Render;
Var
I,J:Integer;
Begin
If (Self.Visible) And (_QueuedLayout>=0) Then
Begin
Self.SelectKeyboardLayout(_QueuedLayout);
_QueuedLayout := -1;
End;
If (Self._LayoutContext <> _KeyboardLayoutContext) Then
Self.SelectKeyboardLayout(_CurrentLayout);
Self._ColorTable := TextureManager.Instance.DefaultColorTable;
If (UI.Highlight <> Nil) And (Not (UI.Highlight Is UIVirtualKeyboardKey)) Then
UI.Highlight := Nil;
Self.UpdateTransform();
For I:=0 To 31 Do
Self.DrawComponent(0, VectorCreate(I*32, 0, 0), 0.0, 0.0, 1.0, 1.0, ColorWhite);
For J:=0 To Pred(MaxKeyboardLines) Do
For I:=0 To Pred(MaxKeyboardRows) Do
If (_Keys[I,J]<>Nil) And (_Keys[I,J].Visible) Then
Begin
_Keys[I,J].Scale := _KbScale;
_Keys[I,J].Render();
End;
End;
Procedure VirtualKeyboard.RestorePosition;
Var
Y:Single;
Begin
Y := UIManager.Instance.Height - Self.Size.Y;
Self._Position := VectorCreate2D(0, Y);
End;
Procedure VirtualKeyboard.ShowFocus;
Begin
If (_KeyboardLayoutCount<=0) Then
AddDefaultKeyboardLayout();
If (Not Self.Visible) Then
Begin
Self.RestorePosition();
Self.Show(widgetAnimatePosY_Bottom);
Enable();
End;
If (Self._CurrentLayout<0) Then
SelectKeyboardLayout(1);
End;
Procedure VirtualKeyboard.UpdateRects;
Begin
_Size.X := 960;
_Size.Y := 260;
End;
Function VirtualKeyboard.OnMouseDown(X, Y: Integer; Button: Word): Boolean;
Begin
RemoveHint(X+Y+Button); //TODO - check this stupid hint
Result := False;
End;
Procedure VirtualKeyboard.Enable;
Begin
_PreviousHighlight := UI.Highlight;
If (UI.Highlight<>Nil) Then
UI.Highlight := _Keys[0, 0];
//UI.Modal := Self;
End;
Procedure VirtualKeyboard.StartHighlight; Begin End;
Procedure VirtualKeyboard.StopHighlight; Begin End;
Procedure VirtualKeyboard.Close;
Begin
Self.Hide(widgetAnimatePosY_Bottom);
If (UI.Modal = Self) Then
UI.Modal := Nil;
UI.Highlight := _PreviousHighlight;
End;
Function VirtualKeyboard.HasMouseOver: Boolean;
Begin
Result := False;
End;
Function VirtualKeyboard.GetKeyValue(Row, Line: Integer): Word;
Begin
If (_CurrentLayout<0) Or (_CurrentLayout>=_KeyboardLayoutCount) Then
_CurrentLayout := 0;
If (Line<0) Or (Line>MaxKeyboardLines-2) Then
Line := 0;
If (Row<0) Or (Row>=MaxKeyboardRows) Then
Row := 0;
If (Self._ShiftMode) Then
Result := _KeyboardLayouts[_CurrentLayout]._Lines[Row, Line].Alt
Else
Result := _KeyboardLayouts[_CurrentLayout]._Lines[Row, Line].Value;
End;
Function VirtualKeyboard.GetKeyAdvance(Key:UIVirtualKeyboardKey):Single;
Begin
Result := _KbScale * (4 + Key.GetKeyWidth());
End;
Procedure VirtualKeyboard.SelectKeyboardLayout(Index: Integer);
Var
I,J,N, Rows, PrevRow:Integer;
X, Y:Single;
IsVisible:Boolean;
Begin
If (_KeyboardLayoutCount<=0) Then
Begin
AddDefaultKeyboardLayout();
End;
If (Not Self.Visible) Then
Begin
_QueuedLayout := Index;
Exit;
End;
Self._CurrentLayout := Index;
Self._LayoutContext := _KeyboardLayoutContext;
//OfsX := (UIManager.Instance.Width-960*_KbScale) * 0.5;
Rows := 0;
For J:=0 To Pred(MaxKeyboardLines) Do
Begin
For I:=0 To Pred(MaxKeyboardRows) Do
If (Assigned(_Keys[I,J])) Then
Begin
IsVisible := (GetKeyValue(_Keys[I,J]._Row, _Keys[I,J]._Line)>0) Or (_Keys[I,J]._Label<>'');
If IsVisible Then
Begin
Inc(Rows);
Break;
End;
End;
End;
If (Rows=5) Then
Self._KbScale := 0.8
Else
Self._KbScale := 1.0;
{$IFDEF OUYA}
_KbScale := _KbScale * 0.85;
{$ENDIF}
Y := 64*_KbScale*Rows;
Y := (Self.Size.Y - Y) * 0.5;
PrevRow := -1;
For J:=0 To Pred(MaxKeyboardLines) Do
Begin
X := 0;
For I:=0 To Pred(MaxKeyboardRows) Do
If (Assigned(_Keys[I,J])) Then
Begin
If (J=3) And (_KeyboardLayouts[_CurrentLayout]._HasShift) Then
_Keys[I,J]._Row := Pred(I)
Else
_Keys[I,J]._Row := I;
IsVisible := (GetKeyValue(_Keys[I,J]._Row, _Keys[I,J]._Line)>0) Or (_Keys[I,J]._Label<>'');
If (@_Keys[I,J].Callback = @LanguageCallback) Then
Begin
IsVisible := (_KeyboardLayoutCount>2);
If (Self._CurrentLayout<Pred(_KeyboardLayoutCount)) Then
N := Succ(Self._CurrentLayout)
Else
N := 1;
_Keys[I,J]._Label := _KeyboardLayouts[N]._Desc;
End;
If (I=0) And (J=3) Then
Begin
If (_KeyboardLayouts[_CurrentLayout]._HasShift) Then
Begin
_Keys[I,J].Callback := ShiftCallback;
_Keys[I,J]._Label := 'Shift';
End Else
Begin
_Keys[I,J].Callback := Nil;
_Keys[I,J]._Label := '';
End;
End;
If (@_Keys[I,J].Callback = @ShiftCallback) Then
Begin
IsVisible := (_KeyboardLayouts[_CurrentLayout]._HasShift);
End;
If IsVisible Then
Begin
_Keys[I,J].Visible := True;
X := X + GetKeyAdvance(_Keys[I,J]);
End Else
_Keys[I,J].Visible := False;
End;
If (X<=0) Then
Continue;
PrevRow := J;
X := (Self.Size.X - X) * 0.5;
For I:=0 To Pred(MaxKeyboardRows) Do
If (Assigned(_Keys[I,J])) And (_Keys[I,J].Visible) Then
Begin
_Keys[I,J].Position := VectorCreate2D(X, Y);
X := X + GetKeyAdvance(_Keys[I,J]);
End;
Y := Y + 64 * _KbScale;;
End;
For J:=0 To Pred(MaxKeyboardLines) Do
For I:=0 To Pred(MaxKeyboardRows) Do
Begin
If (I>=Pred(MaxKeyboardRows)) Or (Not _Keys[Succ(I),J].Visible) Then
Break;
N := (I+1) Mod MaxKeyboardRows;
End;
End;
Procedure VirtualKeyboard.Release;
Begin
{ReleaseObject(Pinyin);}
Inherited;
End;
Procedure VirtualKeyboard.DoKeyEvent(Row, Line: Integer);
Var
Value:Word;
Text:TERRAString;
Begin
If (_Keys[Row, Line]._Suggestion>=0) And (Self._Pinyin<>Nil)
And (Assigned(UI.Focus)) And (UI.Focus Is UIEditText) Then
Begin
Text := UIEditText(UI.Focus).Text;
If Self._Pinyin.Replace(Text, _Keys[Row, Line]._Suggestion) Then
Begin
UIEditText(UI.Focus).Text := Text;
Self.UpdatePinyin();
End;
Exit;
End;
Value := Self.GetKeyValue(Row, Line);
If Value>0 Then
Application.Instance.OnKeyPress(Value);
Self.UpdatePinyin();
End;
Procedure VirtualKeyboard.UpdatePinyin;
Var
Text:TERRAString;
N,I:Integer;
Begin
If (_KeyboardLayouts[_CurrentLayout]._HasPinyin)
And (Assigned(UI.Focus)) And (UI.Focus Is UIEditText) Then
Begin
If (_Pinyin = Nil) Then
_Pinyin := PinyinConverter.Create();
Text := UIEditText(UI.Focus).Text;
_Pinyin.GetSuggestions(Text);
For I:=0 To Pred(MaxKeyboardRows) Do
If Assigned(_Keys[I, 3]) Then
_Keys[I, 3]._Suggestion := -1;
N := 0;
For I:=0 To Pred(_Pinyin.Results) Do
If (I>Pred(MaxKeyboardRows)) Or (_Keys[I, 3] = Nil) Then
Break
Else
Begin
_Keys[I, 3]._Suggestion := N;
Inc(N);
End;
End;
End;
{ UIVirtualKeyboardKey }
Constructor UIVirtualKeyboardKey.Create(Parent:Widget; UI:UI; X, Y, Z: Single);
Begin
Inherited Create(Name, UI, Parent);
Self._Visible := True;
Self._TabIndex := -1;
Self._Position := VectorCreate2D(X,Y);
Self._Layer := Z;
Self.LoadComponent('ui_kb_a');
Self.LoadComponent('ui_kb_b');
Self.LoadComponent('ui_kb_c');
Self.OnMouseClick := KeyEventDispatcher;
Self._ColorTable := TextureManager.Instance.DefaultColorTable;
End;
Function UIVirtualKeyboardKey.OnMouseDown(X, Y: Integer; Button: Word): Boolean;
Begin
RemoveHint(X+Y+Button); //TODO - check this stupid hint
Result := False;
End;
Function UIVirtualKeyboardKey.OnMouseUp(X, Y: Integer; Button: Word): Boolean;
Begin
RemoveHint(Button); //TODO - check this stupid hint
If (Not Self.OnRegion(X,Y)) Then
Begin
Result := False;
Exit;
End;
Self.OnMouseClick(Self);
Result := True;
End;
Function UIVirtualKeyboardKey.HasMouseOver():Boolean;
Begin
Result := False;
End;
Function UIVirtualKeyboardKey.GetKeyHeight(): Integer;
Begin
If (_ComponentCount<=0) Then
Result := 0
Else
Result := _ComponentList[_KeyType].Buffer.Height;
End;
Function UIVirtualKeyboardKey.GetKeyWidth(): Integer;
Begin
If (_ComponentCount<=0) Then
Result := 0
Else
Result := _ComponentList[_KeyType].Buffer.Width;
End;
Procedure UIVirtualKeyboardKey.Render;
Var
W, H:Integer;
SS:TERRAString;
MyColor:TERRA_Color.Color;
HG:Widget;
TextScale:Single;
Value:Word;
Begin
HG := UI.Highlight;
If (HG = Nil) Then
UI.Highlight := Self;
_Pivot := VectorCreate2D(0, 0.5);
Self.UpdateRects();
Self.UpdateTransform();
Self.UpdateHighlight();
If (Self.IsHighlighted) Or (UI.Highlight = Nil) Then
MyColor := ColorWhite
Else
MyColor := ColorGrey(32);
DrawComponent(_KeyType, VectorZero, 0.0, 0.0, 1.0, 1.0, MyColor, True);
W := Self.GetKeyWidth();
H := Self.GetKeyHeight();
If (_Label<>'') Then
Begin
SS := _Label;
TextScale := 1.0;
End Else
Begin
Value := VirtualKeyboard(Parent).GetKeyValue(_Row, _Line);
SS := '';
If Value = Ord('@') Then
Begin
If (_Suggestion>=0) And (Assigned(VirtualKeyboard(Parent)._Pinyin)) Then
Begin
Value := VirtualKeyboard(Parent)._Pinyin.GetResult(_Suggestion);
StringAppendChar(SS, Value);
IntToString(_Row+_Line);
End;
TextScale := 1.0;
End Else
Begin
StringAppendChar(SS, Value);
TextScale := 1.0 /Self.Scale;
End;
End;
If (SS<>'') Then
Self.DrawText(SS, VectorCreate((W - _FontRenderer.GetTextWidth(SS, TextScale))*0.5, (H - _FontRenderer.GetTextHeight(SS, TextScale))*0.5,1), ColorWhite, TextScale);
End;
Procedure UIVirtualKeyboardKey.StartHighlight; Begin End;
Procedure UIVirtualKeyboardKey.StopHighlight; Begin End;
Procedure UIVirtualKeyboardKey.OnLanguageChange; Begin End;
Procedure UIVirtualKeyboardKey.UpdateRects;
Begin
_Size.X := GetKeyWidth();
_Size.Y := GetKeyHeight();
End;
Procedure ClearKeyboardLayouts();
Var
I:Integer;
Begin
For I:=0 To Pred(_KeyboardLayoutCount) Do
ReleaseObject(_KeyboardLayouts[I]);
_KeyboardLayoutCount := 0;
End;
Function GetKeyboardLayout(ID:TERRAString):KeyboardLayout;
Var
I:Integer;
Begin
For I:=0 To Pred(_KeyboardLayoutCount) Do
If (_KeyboardLayouts[I]._Desc = ID) Then
Begin
Result :=_KeyboardLayouts[I];
Exit;
End;
Result := Nil;
End;
Procedure AddDefaultKeyboardLayout();
Begin
AddKeyboardLayoutFromString(DefaultSymbolLayout);
AddKeyboardLayoutFromString(DefaultKeyboardLayout);
End;
Procedure AddKeyboardLayout(SourceFile:TERRAString);
Var
Src:Stream;
S,Data:TERRAString;
Begin
Src := FileManager.Instance.OpenStream(SourceFile);
If Src = Nil Then
Exit;
Data := '';
S := '';
While Not Src.EOF Do
Begin
Src.ReadLine(S);
Data := Data + S + '|';
End;
ReleaseObject(Src);
AddKeyboardLayoutFromString(Data);
End;
Procedure AddKeyboardLayoutFromString(Src:TERRAString);
Var
Layout:KeyboardLayout;
I,J,K:Integer;
It:StringIterator;
A,B:Byte;
Value:TERRAChar;
Desc, Line:TERRAString;
IsSymbol:Boolean;
Begin
Desc := StringGetNextSplit(Src, Ord('|'));
IsSymbol := (Desc='123');
Layout := GetKeyboardLayout(Desc);
If Layout = Nil Then
Begin
Layout := KeyboardLayout.Create();
Inc(_KeyboardLayoutCount);
SetLength(_KeyboardLayouts, _KeyboardLayoutCount);
_KeyboardLayouts[Pred(_KeyboardLayoutCount)] := Layout;
Layout._Desc := Desc;
End;
Inc(_KeyboardLayoutContext);
Layout._HasShift := False;
Layout._HasPinyin := False;
For J:=0 To MaxKeyboardLines-2 Do
For I:=0 To Pred(MaxKeyboardRows) Do
Begin
Layout._Lines[I, J].Value := 0;
Layout._Lines[I, J].Alt := 0;
End;
For K:=1 To 2 Do
Begin
For J:=0 To MaxKeyboardLines-2 Do
Begin
Line := StringGetNextSplit(Src, Ord('|'));
If (Line='') And (K=2) Then
Begin
For I:=0 To Pred(MaxKeyboardRows) Do
Layout._Lines[I, J].Alt := Layout._Lines[I, J].Value;
Continue;
End;
I := 0;
StringCreateIterator(Line, It);
While It.HasNext() Do
Begin
Value := It.GetNext();
If (IsSymbol) And (Value = Ord('E')) Then
Value := 8364 // euro symbol
Else
If (IsSymbol) And (Value = Ord('L')) Then
Value := 163 // pound symbol
Else
If (IsSymbol) And (Value = Ord('Y')) Then
Value := 165; // yen symbol
If (Value= Ord('@')) Then
Layout._HasPinyin := True;
If (K=2) Then
Begin
Layout._Lines[I, J].Alt := Value;
Layout._HasShift := True;
End Else
Layout._Lines[I, J].Value := Value;
Inc(I);
If (I>=MaxKeyboardRows) Then
Break;
End;
End;
End;
End;
End.
|
{ Subroutine SST_SYM_VAR_NEW_OUT (DTYPE,SYM_P)
*
* Create a new output symbol that is a variable. The variable name will be
* inferred from the data type, and adjusted as necessary to make it unique.
* DTYPE is the descriptor for the data type of the new variable. SYM_P
* is returned pointing to the new symbol descriptor. The symbol will be
* installed in the output symbol table at the current scope.
}
module sst_SYM_VAR_NEW_OUT;
define sst_sym_var_new_out;
%include 'sst2.ins.pas';
procedure sst_sym_var_new_out ( {create output symbol that is a variable}
in dtype: sst_dtype_t; {descriptor for variable's data type}
out sym_p: sst_symbol_p_t); {points to newly created symbol descriptor}
var
name: string_var80_t; {orignal variable name attempt}
namef: string_var80_t; {variable name guaranteed to be unique}
dt_p: sst_dtype_p_t; {points to base data type descriptor}
dt: sst_dtype_k_t; {base data type ID}
suffix: string_var4_t; {suffix to append to variable name}
pos: string_hash_pos_t; {hash table position handle}
sym_pp: sst_symbol_pp_t; {points to hash table user data area}
begin
name.max := sizeof(name.str); {init local var strings}
namef.max := sizeof(namef.str);
suffix.max := sizeof(suffix.str);
suffix.len := 0;
name.len := 0;
{
* Pick a name based on the data type of the implicit variable.
}
sst_dtype_resolve (dtype, dt_p, dt); {get base data type from DTYPE}
case dt of {what kind of data type is this ?}
sst_dtype_int_k: string_appendn (name, 'int', 3);
sst_dtype_enum_k: string_appendn (name, 'enum', 4);
sst_dtype_float_k: begin
if dt_p^.size_used = sst_config.float_single_p^.size_used
then string_appendn (name, 'sgl', 3)
else if dt_p^.size_used = sst_config.float_double_p^.size_used
then string_appendn (name, 'dbl', 3)
else string_appendn (name, 'flt', 3)
;
;
end;
sst_dtype_bool_k: string_appendn (name, 'bool', 4);
sst_dtype_char_k: string_appendn (name, 'chr', 3);
sst_dtype_rec_k: string_appendn (name, 'rec', 3);
sst_dtype_array_k: begin
if dt_p^.ar_string
then string_appendn (name, 'str', 3) {string, special case of an array}
else string_appendn (name, 'arr', 3); {non-string array}
end;
sst_dtype_set_k: string_appendn (name, 'set', 3);
sst_dtype_range_k: string_appendn (name, 'rng', 5);
sst_dtype_proc_k: string_appendn (name, 'proc', 4);
sst_dtype_pnt_k: string_appendn (name, 'pnt', 3);
otherwise
string_appendn (name, 'xxx', 3);
end;
{
* NAME contains the raw name for this variable.
}
string_appendn (name, '_', 1); {this helps distinguish implicit variables}
if dt = sst_dtype_pnt_k then begin {variable is a pointer ?}
string_appendn (suffix, '_p', 2); {set variable name suffix}
end;
sst_w.name^ ( {make final variable name}
name.str, name.len, {starting variable name}
suffix.str, suffix.len, {variable name suffix}
sst_rename_all_k, {make unique name over all visible scopes}
namef, {returned final variable name}
pos); {returned hash table position for name}
sst_mem_alloc_scope (sizeof(sym_p^), sym_p); {allocate symbol descriptor}
string_hash_ent_add (pos, sym_p^.name_out_p, sym_pp); {add name to symbol table}
sym_pp^ := sym_p; {point hash table entry to symbol descriptor}
sym_p^.name_in_p := nil; {set up symbol descriptor}
sym_p^.next_p := nil;
sym_p^.char_h.crange_p := nil;
sym_p^.scope_p := sst_scope_p;
sym_p^.symtype := sst_symtype_var_k;
sym_p^.flags := [sst_symflag_created_k, sst_symflag_def_k];
sym_p^.var_dtype_p := addr(dtype);
sym_p^.var_val_p := nil;
sym_p^.var_arg_p := nil; {this variable is not a dummy argument}
sym_p^.var_proc_p := nil;
sym_p^.var_com_p := nil;
end;
|
unit BrowseFunc;
{
Inno Setup
Copyright (C) 1997-2010 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Functions for browsing for folders/files
$jrsoftware: issrc/Projects/BrowseFunc.pas,v 1.9 2010/09/10 01:08:44 jr Exp $
}
interface
{$I VERSION.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms;
function BrowseForFolder(const Prompt: String; var Directory: String;
const ParentWnd: HWND; const NewFolderButton: Boolean): Boolean;
function NewGetOpenFileName(const Prompt: String; var FileName: String;
const InitialDirectory, Filter, DefaultExtension: String;
const ParentWnd: HWND): Boolean;
function NewGetOpenFileNameMulti(const Prompt: String; const FileNameList: TStrings;
const InitialDirectory, Filter, DefaultExtension: String;
const ParentWnd: HWND): Boolean;
function NewGetSaveFileName(const Prompt: String; var FileName: String;
const InitialDirectory, Filter, DefaultExtension: String;
const ParentWnd: HWND): Boolean;
implementation
uses
CommDlg, ShlObj, {$IFNDEF Delphi3orHigher} Ole2, {$ELSE} ActiveX, {$ENDIF}
PathFunc;
function BrowseCallback(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer; stdcall;
var
ShouldEnable: Boolean;
Path: array[0..MAX_PATH-1] of Char;
begin
case uMsg of
BFFM_INITIALIZED:
begin
if lpData <> 0 then
SendMessage(Wnd, BFFM_SETSELECTION, 1, lpData);
end;
BFFM_SELCHANGED:
begin
{ In a BIF_NEWDIALOGSTYLE dialog, BIF_RETURNONLYFSDIRS does not cause
the OK button to be disabled automatically when the user clicks a
non-FS item (e.g. My Computer), so do that ourself. }
ShouldEnable := SHGetPathFromIDList(PItemIDList(lParam), Path);
SendMessage(Wnd, BFFM_ENABLEOK, 0, Ord(ShouldEnable));
end;
end;
Result := 0;
end;
function BrowseForFolder(const Prompt: String; var Directory: String;
const ParentWnd: HWND; const NewFolderButton: Boolean): Boolean;
const
BIF_NONEWFOLDERBUTTON = $200;
BIF_NEWDIALOGSTYLE = $0040;
var
InitialDir: String;
Malloc: IMalloc;
BrowseInfo: TBrowseInfo;
DisplayName, Path: array[0..MAX_PATH-1] of Char;
ActiveWindow: HWND;
WindowList: Pointer;
IDList: PItemIDList;
begin
Result := False;
InitialDir := RemoveBackslashUnlessRoot(Directory); { Win95 doesn't allow trailing backslash }
if FAILED(SHGetMalloc(Malloc)) then
Malloc := nil;
FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
with BrowseInfo do begin
hwndOwner := ParentWnd;
pszDisplayName := @DisplayName;
lpszTitle := PChar(Prompt);
ulFlags := BIF_RETURNONLYFSDIRS or BIF_NEWDIALOGSTYLE;
if not NewFolderButton then
ulFlags := ulFlags or BIF_NONEWFOLDERBUTTON;
lpfn := BrowseCallback;
if InitialDir <> '' then
Pointer(lParam) := PChar(InitialDir);
end;
ActiveWindow := GetActiveWindow;
WindowList := DisableTaskWindows(0);
CoInitialize(nil);
try
IDList := SHBrowseForFolder(BrowseInfo);
finally
CoUninitialize();
EnableTaskWindows(WindowList);
{ SetActiveWindow(Application.Handle) is needed or else the focus doesn't
properly return to ActiveWindow }
SetActiveWindow(Application.Handle);
SetActiveWindow(ActiveWindow);
end;
try
if (IDList = nil) or not SHGetPathFromIDList(IDList, Path) then
Exit;
Directory := Path;
finally
if Assigned(Malloc) then
Malloc.Free(IDList);
end;
Result := True;
end;
type
TGetOpenOrSaveFileNameFunc = function(var OpenFile: TOpenFilename): Bool; stdcall;
function NewGetOpenOrSaveFileName(const Prompt: String; var FileName: String;
const InitialDirectory, Filter, DefaultExtension: String;
const ParentWnd: HWND; const GetOpenOrSaveFileNameFunc: TGetOpenOrSaveFileNameFunc;
const Flags: DWORD): Boolean;
function AllocFilterStr(const S: string): string;
var
P: PChar;
begin
Result := '';
if S <> '' then
begin
Result := S + #0; // double null terminators
P := PathStrScan(PChar(Result), '|');
while P <> nil do
begin
P^ := #0;
Inc(P);
P := PathStrScan(P, '|');
end;
end;
end;
function GetMultiSelectString(const P: PChar): String;
var
E: PChar;
begin
E := P;
while E^ <> #0 do
Inc(E, StrLen(E) + 1);
SetString(Result, P, E - P);
end;
var
ofn: TOpenFileName;
lpstrFile: array[0..8191] of Char;
TempFilter: String;
SaveCurDir: String;
ActiveWindow: HWND;
WindowList: Pointer;
FPUControlWord: Word;
begin
StrPLCopy(lpstrFile, FileName, (SizeOf(lpstrFile) div SizeOf(lpstrFile[0])) - 1);
FillChar(ofn, SizeOf(ofn), 0);
ofn.lStructSize := SizeOf(ofn);
ofn.hwndOwner := ParentWnd;
TempFilter := AllocFilterStr(Filter);
ofn.lpstrFilter := PChar(TempFilter);
ofn.lpstrFile := lpstrFile;
ofn.nMaxFile := SizeOf(lpstrFile) div SizeOf(lpstrFile[0]);
ofn.lpstrInitialDir := PChar(InitialDirectory);
ofn.lpstrTitle := PChar(Prompt);
ofn.Flags := Flags or OFN_NOCHANGEDIR;
ofn.lpstrDefExt := Pointer(DefaultExtension);
ActiveWindow := GetActiveWindow;
WindowList := DisableTaskWindows(0);
try
asm
// Avoid FPU control word change in NETRAP.dll, NETAPI32.dll, etc
FNSTCW FPUControlWord
end;
try
SaveCurDir := GetCurrentDir;
if GetOpenOrSaveFileNameFunc(ofn) then begin
if Flags and OFN_ALLOWMULTISELECT <> 0 then
FileName := GetMultiSelectString(lpstrFile)
else
FileName := lpstrFile;
Result := True;
end else
Result := False;
{ Restore current directory. The OFN_NOCHANGEDIR flag we pass is
supposed to do that, but the MSDN docs claim: "This flag is
ineffective for GetOpenFileName." I see no such problem on
Windows 2000 or XP, but to be safe... }
SetCurrentDir(SaveCurDir);
finally
asm
FNCLEX
FLDCW FPUControlWord
end;
end;
finally
EnableTaskWindows(WindowList);
{ SetActiveWindow(Application.Handle) is needed or else the focus doesn't
properly return to ActiveWindow }
SetActiveWindow(Application.Handle);
SetActiveWindow(ActiveWindow);
end;
end;
function NewGetOpenFileName(const Prompt: String; var FileName: String;
const InitialDirectory, Filter, DefaultExtension: String;
const ParentWnd: HWND): Boolean;
begin
Result := NewGetOpenOrSaveFileName(Prompt, FileName, InitialDirectory, Filter, DefaultExtension,
ParentWnd, GetOpenFileName, OFN_HIDEREADONLY or OFN_PATHMUSTEXIST or OFN_FILEMUSTEXIST);
end;
function NewGetOpenFileNameMulti(const Prompt: String; const FileNameList: TStrings;
const InitialDirectory, Filter, DefaultExtension: String;
const ParentWnd: HWND): Boolean;
function ExtractStr(var P: PChar): String;
var
L: Integer;
begin
L := StrLen(P);
SetString(Result, P, L);
if L > 0 then
Inc(P, L + 1);
end;
var
Files, Dir, FileName: String;
P: PChar;
begin
Result := NewGetOpenOrSaveFileName(Prompt, Files, InitialDirectory, Filter, DefaultExtension,
ParentWnd, GetOpenFileName, OFN_HIDEREADONLY or OFN_PATHMUSTEXIST or OFN_FILEMUSTEXIST or
OFN_ALLOWMULTISELECT or OFN_EXPLORER);
if Result then begin
FileNameList.Clear;
P := PChar(Files);
Dir := ExtractStr(P);
FileName := ExtractStr(P);
if FileName = '' then begin
{ When only one file is selected, the list contains just a file name }
FileNameList.Add(Dir);
end
else begin
repeat
{ The filenames can include paths if the user typed them in manually }
FileNameList.Add(PathCombine(Dir, FileName));
FileName := ExtractStr(P);
until FileName = '';
end;
end;
end;
function NewGetSaveFileName(const Prompt: String; var FileName: String;
const InitialDirectory, Filter, DefaultExtension: String;
const ParentWnd: HWND): Boolean;
begin
Result := NewGetOpenOrSaveFileName(Prompt, FileName, InitialDirectory, Filter, DefaultExtension,
ParentWnd, GetSaveFileName, OFN_OVERWRITEPROMPT or OFN_HIDEREADONLY or OFN_PATHMUSTEXIST);
end;
end.
|
unit CleanLibrary;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls,
ComCtrls, ExtCtrls;
type
strArray = array of string;
ptrStrArray = ^strArray;
type
{ TFrmCleanLibrary }
TFrmCleanLibrary = class(TForm)
btnBack: TButton;
btnReset: TButton;
btnRemove: TButton;
btnDisplay: TButton;
btnBack2: TButton;
btnUnselect: TButton;
btnRemoveFromDisk: TButton;
chkFolders: TCheckBox;
Label3: TLabel;
lstRemove: TListBox;
Panel2: TPanel;
pnlProgress: TPanel;
txtNotToRemove: TEdit;
Label1: TLabel;
dirlistview: TListBox;
Label2: TLabel;
Panel1: TPanel;
procedure btnBack2Click(Sender: TObject);
procedure btnBackClick(Sender: TObject);
procedure btnDisplayClick(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
procedure btnRemoveFromDiskClick(Sender: TObject);
procedure btnResetClick(Sender: TObject);
procedure btnUnselectClick(Sender: TObject);
procedure dirlistviewClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lstRemoveClick(Sender: TObject);
private
{ private declarations }
procedure Recursive_AddDir
(dir: String; strExtension: ptrStrArray; var bContainesFiles: Boolean);
public
{ public declarations }
end;
var
FrmCleanLibrary: TFrmCleanLibrary;
implementation
uses
mediacol, functions, config, mainform;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure TFrmCleanLibrary.FormCreate(Sender: TObject);
Var i: integer;
Begin
dirlistview.Clear;
For i:= 0 To MediaCollection.dirlist.Count-1 Do
Begin
dirlistview.Items.Add(MediaCollection.dirlist[i]);
End;
btnReset.Enabled := false;
dirlistviewClick(Sender);
txtNotToRemove.Text := CactusConfig.strCleanLibNotToRemove;
End;
procedure TFrmCleanLibrary.FormDestroy(Sender: TObject);
begin
CactusConfig.strCleanLibNotToRemove := txtNotToRemove.Text;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.lstRemoveClick(Sender: TObject);
begin
if (lstRemove.ItemIndex = -1 )
then
btnUnselect.Enabled := false
else
btnUnselect.Enabled := true;
if lstRemove.Items.Count = 0
then
btnRemove.Enabled := false
else
btnRemove.Enabled := true;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnResetClick(Sender: TObject);
begin
FormCreate(Sender);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnUnselectClick(Sender: TObject);
var
i: integer;
begin
i := lstRemove.ItemIndex;
if i <> -1
then
begin
lstRemove.Items.Delete(i);
if lstRemove.Items.Count > i-1
then
lstRemove.ItemIndex := i;
lstRemoveClick(Sender);
end;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.dirlistviewClick(Sender: TObject);
var i: integer;
begin
if (dirlistview.ItemIndex = -1 )
then
btnRemove.Enabled := false
else
btnRemove.Enabled := true;
if (dirlistview.Items.Count <> 0)
then
btnDisplay.Enabled := true;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnRemoveClick(Sender: TObject);
begin
if (dirlistview.ItemIndex <> -1 )
then
begin
dirlistview.Items.Delete(dirlistview.ItemIndex);
btnReset.Enabled := true;
end;
if (dirlistview.Items.Count = 0)
then
btnDisplay.Enabled := false;
end;
procedure TFrmCleanLibrary.btnRemoveFromDiskClick(Sender: TObject);
var
i, index: integer;
begin
pnlProgress.Visible := true;
btnBack2.Enabled := false;
btnUnselect.Enabled := false;
// remove from disk & collection
for i := 1 to lstRemove.Items.Count do
begin
if DirectoryExists(lstRemove.Items[i-1])
then
RemoveDir(lstRemove.Items[i-1])
else
begin
DeleteFile(lstRemove.Items[i-1]);
index := MediaCollection.getIndexByPath(lstRemove.Items[i-1]);
if index > 0 then
MediaCollection.remove(index);
end;
end;
lstRemove.Clear;
lstRemoveClick(Sender);
btnBack2.Enabled := true;
pnlProgress.Visible := false;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnBackClick(Sender: TObject);
begin
Close;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnBack2Click(Sender: TObject);
begin
Panel2.Visible:= false;
Panel1.Visible:= true;
btnBack.Cancel:= true;
btnDisplay.Default:=true;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnDisplayClick(Sender: TObject);
var
strExtension: array of string;
strTmp: string;
i, j: integer;
bDummy: Boolean;
begin
Panel1.Visible:= false;
Panel2.Visible:= true;
btnBack2.Cancel:= true;
btnRemoveFromDisk.Default:= true;
lstRemove.Clear;
btnBack2.Enabled:= false;
pnlProgress.Visible := true;
Application.ProcessMessages;
// enumerate file extensions to skip
i := 0;
SetLength(strExtension, 0);
strTmp := Trim(txtNotToRemove.Text);
strTmp := lowercase(strTmp);
while (strlen(PChar(strTmp)) <> 0) do
begin
inc(i);
SetLength(strExtension, i);
j := Pos(' ', strTmp);
if j > 0
then
begin
strExtension[i-1] := Copy(strTmp, 1, j-1);
Delete(strTmp, 1, j)
end
else
begin
strExtension[i-1] := strTmp;
strTmp := '';
end;
end;
// start searching the folders
for i := 1 to dirlistview.Items.Count do
Recursive_AddDir(dirlistview.Items[i-1], @strExtension, bDummy);
pnlProgress.Visible := false;
btnBack2.Enabled:= true;
lstRemoveClick(Sender);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure TFrmCleanLibrary.Recursive_AddDir
(dir: String; strExtension: ptrStrArray; var bContainesFiles: Boolean);
Var
mp3search,dirsearch: TSearchrec;
tmps: string;
i: integer;
bContinue: Boolean;
bContainesFiles_lokal: Boolean;
files, folders: TStringList;
Begin
dir := IncludeTrailingPathDelimiter(dir);
bContainesFiles := false;
files := TStringList.Create;
folders := TStringList.Create;
// list files with non-matching extensions
If FindFirst(dir+'*', faAnyFile - faDirectory, mp3search)=0 Then
Repeat
Begin
if ((mp3search.name = '.') or (mp3search.name = '..')) then
continue;
tmps := lowercase(ExtractFileExt(mp3search.name));
Delete(tmps, 1, 1);
bContinue := false;
for i := 1 to Length(strExtension^) do
if tmps = strExtension^[i-1] then
begin
bContainesFiles := true;
bContinue := true;
continue;
end;
if bContinue then continue;
tmps := dir + mp3search.name;
files.Add(tmps);
End;
Until FindNext(mp3search)<>0;
Findclose(mp3search);
BubbleSort(TStrings(files));
for i := 1 to files.Count do
lstRemove.Items.Add(files[i-1]);
// walk into subfolders
If Findfirst(dir+'*', FaDirectory, dirsearch)=0 Then
Repeat
If (dirsearch.name<>'..') And (dirsearch.name<>'.') Then
if (dirsearch.attr And FaDirectory)=FaDirectory Then
begin
Recursive_AddDir(dir+dirsearch.name, strExtension, bContainesFiles_lokal);
if (NOT bContainesFiles_lokal) and (chkFolders.Checked) then
folders.Add(IncludeTrailingPathDelimiter(dir+dirsearch.name))
else
bContainesFiles := true;
end;
Until FindNext(dirsearch)<>0;
Findclose(dirsearch);
BubbleSort(TStrings(folders));
for i := 1 to folders.Count do
lstRemove.Items.Add(folders[i-1]);
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
initialization
{$I cleanlibrary.lrs}
end.
unit CleanLibrary;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls,
ComCtrls, ExtCtrls;
type
strArray = array of string;
ptrStrArray = ^strArray;
type
{ TFrmCleanLibrary }
TFrmCleanLibrary = class(TForm)
btnBack: TButton;
btnReset: TButton;
btnRemove: TButton;
btnDisplay: TButton;
btnBack2: TButton;
btnUnselect: TButton;
btnRemoveFromDisk: TButton;
chkFolders: TCheckBox;
Label3: TLabel;
lstRemove: TListBox;
Panel2: TPanel;
pnlProgress: TPanel;
txtNotToRemove: TEdit;
Label1: TLabel;
dirlistview: TListBox;
Label2: TLabel;
Panel1: TPanel;
procedure btnBack2Click(Sender: TObject);
procedure btnBackClick(Sender: TObject);
procedure btnDisplayClick(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
procedure btnRemoveFromDiskClick(Sender: TObject);
procedure btnResetClick(Sender: TObject);
procedure btnUnselectClick(Sender: TObject);
procedure dirlistviewClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lstRemoveClick(Sender: TObject);
private
{ private declarations }
procedure Recursive_AddDir
(dir: String; strExtension: ptrStrArray; var bContainesFiles: Boolean);
public
{ public declarations }
end;
var
FrmCleanLibrary: TFrmCleanLibrary;
implementation
uses
mediacol, functions, config, mainform;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure TFrmCleanLibrary.FormCreate(Sender: TObject);
Var i: integer;
Begin
dirlistview.Clear;
For i:= 0 To MediaCollection.dirlist.Count-1 Do
Begin
dirlistview.Items.Add(MediaCollection.dirlist[i]);
End;
btnReset.Enabled := false;
dirlistviewClick(Sender);
txtNotToRemove.Text := CactusConfig.strCleanLibNotToRemove;
End;
procedure TFrmCleanLibrary.FormDestroy(Sender: TObject);
begin
CactusConfig.strCleanLibNotToRemove := txtNotToRemove.Text;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.lstRemoveClick(Sender: TObject);
begin
if (lstRemove.ItemIndex = -1 )
then
btnUnselect.Enabled := false
else
btnUnselect.Enabled := true;
if lstRemove.Items.Count = 0
then
btnRemove.Enabled := false
else
btnRemove.Enabled := true;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnResetClick(Sender: TObject);
begin
FormCreate(Sender);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnUnselectClick(Sender: TObject);
var
i: integer;
begin
i := lstRemove.ItemIndex;
if i <> -1
then
begin
lstRemove.Items.Delete(i);
if lstRemove.Items.Count > i-1
then
lstRemove.ItemIndex := i;
lstRemoveClick(Sender);
end;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.dirlistviewClick(Sender: TObject);
var i: integer;
begin
if (dirlistview.ItemIndex = -1 )
then
btnRemove.Enabled := false
else
btnRemove.Enabled := true;
if (dirlistview.Items.Count <> 0)
then
btnDisplay.Enabled := true;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnRemoveClick(Sender: TObject);
begin
if (dirlistview.ItemIndex <> -1 )
then
begin
dirlistview.Items.Delete(dirlistview.ItemIndex);
btnReset.Enabled := true;
end;
if (dirlistview.Items.Count = 0)
then
btnDisplay.Enabled := false;
end;
procedure TFrmCleanLibrary.btnRemoveFromDiskClick(Sender: TObject);
var
i, index: integer;
begin
pnlProgress.Visible := true;
btnBack2.Enabled := false;
btnUnselect.Enabled := false;
// remove from disk & collection
for i := 1 to lstRemove.Items.Count do
begin
if DirectoryExists(lstRemove.Items[i-1])
then
RemoveDir(lstRemove.Items[i-1])
else
begin
DeleteFile(lstRemove.Items[i-1]);
index := MediaCollection.getIndexByPath(lstRemove.Items[i-1]);
if index > 0 then
MediaCollection.remove(index);
end;
end;
lstRemove.Clear;
lstRemoveClick(Sender);
btnBack2.Enabled := true;
pnlProgress.Visible := false;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnBackClick(Sender: TObject);
begin
Close;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnBack2Click(Sender: TObject);
begin
Panel2.Visible:= false;
Panel1.Visible:= true;
btnBack.Cancel:= true;
btnDisplay.Default:=true;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFrmCleanLibrary.btnDisplayClick(Sender: TObject);
var
strExtension: array of string;
strTmp: string;
i, j: integer;
bDummy: Boolean;
begin
Panel1.Visible:= false;
Panel2.Visible:= true;
btnBack2.Cancel:= true;
btnRemoveFromDisk.Default:= true;
lstRemove.Clear;
btnBack2.Enabled:= false;
pnlProgress.Visible := true;
Application.ProcessMessages;
// enumerate file extensions to skip
i := 0;
SetLength(strExtension, 0);
strTmp := Trim(txtNotToRemove.Text);
strTmp := lowercase(strTmp);
while (strlen(PChar(strTmp)) <> 0) do
begin
inc(i);
SetLength(strExtension, i);
j := Pos(' ', strTmp);
if j > 0
then
begin
strExtension[i-1] := Copy(strTmp, 1, j-1);
Delete(strTmp, 1, j)
end
else
begin
strExtension[i-1] := strTmp;
strTmp := '';
end;
end;
// start searching the folders
for i := 1 to dirlistview.Items.Count do
Recursive_AddDir(dirlistview.Items[i-1], @strExtension, bDummy);
pnlProgress.Visible := false;
btnBack2.Enabled:= true;
lstRemoveClick(Sender);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure TFrmCleanLibrary.Recursive_AddDir
(dir: String; strExtension: ptrStrArray; var bContainesFiles: Boolean);
Var
mp3search,dirsearch: TSearchrec;
tmps: string;
i: integer;
bContinue: Boolean;
bContainesFiles_lokal: Boolean;
files, folders: TStringList;
Begin
dir := IncludeTrailingPathDelimiter(dir);
bContainesFiles := false;
files := TStringList.Create;
folders := TStringList.Create;
// list files with non-matching extensions
If FindFirst(dir+'*', faAnyFile - faDirectory, mp3search)=0 Then
Repeat
Begin
if ((mp3search.name = '.') or (mp3search.name = '..')) then
continue;
tmps := lowercase(ExtractFileExt(mp3search.name));
Delete(tmps, 1, 1);
bContinue := false;
for i := 1 to Length(strExtension^) do
if tmps = strExtension^[i-1] then
begin
bContainesFiles := true;
bContinue := true;
continue;
end;
if bContinue then continue;
tmps := dir + mp3search.name;
files.Add(tmps);
End;
Until FindNext(mp3search)<>0;
Findclose(mp3search);
BubbleSort(files);
for i := 1 to files.Count do
lstRemove.Items.Add(files[i-1]);
// walk into subfolders
If Findfirst(dir+'*', FaDirectory, dirsearch)=0 Then
Repeat
If (dirsearch.name<>'..') And (dirsearch.name<>'.') Then
if (dirsearch.attr And FaDirectory)=FaDirectory Then
begin
Recursive_AddDir(dir+dirsearch.name, strExtension, bContainesFiles_lokal);
if (NOT bContainesFiles_lokal) and (chkFolders.Checked) then
folders.Add(IncludeTrailingPathDelimiter(dir+dirsearch.name))
else
bContainesFiles := true;
end;
Until FindNext(dirsearch)<>0;
Findclose(dirsearch);
BubbleSort(folders);
for i := 1 to folders.Count do
lstRemove.Items.Add(folders[i-1]);
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
initialization
{$I cleanlibrary.lrs}
end.
|
unit UConexao;
interface
uses
IniFiles, SysUtils, Forms, FireDAC.Comp.Client, Dialogs;
type
TConexao = class
private
Fcx_ProtocolFB: String;
Fcx_SQLDialectFB: String;
Fcx_DatabaseFB: String;
Fcx_PasswordFB: String;
Fcx_UserNameFB: String;
Fcx_CaminhoINI: String;
Fcx_Secao: String;
procedure Setcx_DatabaseFB(const Value: String);
procedure Setcx_PasswordFB(const Value: String);
procedure Setcx_ProtocolFB(const Value: String);
procedure Setcx_SQLDialectFB(const Value: String);
procedure Setcx_UserNameFB(const Value: String);
procedure Setcx_CaminhoINI(const Value: String);
procedure Setcx_Secao(const Value: String);
public
property cx_DatabaseFB : String read Fcx_DatabaseFB write Setcx_DatabaseFB;
property cx_UserNameFB : String read Fcx_UserNameFB write Setcx_UserNameFB;
property cx_PasswordFB : String read Fcx_PasswordFB write Setcx_PasswordFB;
property cx_ProtocolFB : String read Fcx_ProtocolFB write Setcx_ProtocolFB;
property cx_SQLDialectFB : String read Fcx_SQLDialectFB write Setcx_SQLDialectFB;
property cx_CaminhoINI : String read Fcx_CaminhoINI write Setcx_CaminhoINI;
property cx_Secao : String read Fcx_Secao write Setcx_Secao;
constructor Create(Path: string; Secao: string);
procedure LeINI(); virtual;
procedure Conectar(var Conexao: TFDConnection); virtual;
end;
implementation
{ TConexao }
procedure TConexao.Conectar(var Conexao: TFDConnection);
begin
LeINI();
try
//Passa os parâmetros para o objeto Conexão
Conexao.Connected := False;
Conexao.LoginPrompt := False;
Conexao.Params.Clear;
Conexao.Params.Add('Protocol=TCPIP');
Conexao.Params.Add('User_Name='+ cx_UserNameFB);
Conexao.Params.Add('password='+ cx_PasswordFB);
Conexao.Params.Add('Database='+ cx_DatabaseFB);
Conexao.Params.Add('SQLDialect='+ cx_SQLDialectFB);
Conexao.Params.Add('DriverID=FB');
Conexao.Connected := True;
Except
on E:Exception do
ShowMessage('Erro ao carregar parâmetros de conexão!'#13#10 + E.Message);
end;
end;
constructor TConexao.Create(Path, Secao: string);
begin
if FileExists(Path) then
begin
Self.Fcx_CaminhoINI := Path;
Self.Fcx_Secao := Secao;
end
else
raise Exception.Create('Arquivo INI para configuração não encontrado.'#13#10'Aplicação será finalizada.');
end;
procedure TConexao.LeINI;
var
ArqIni : TIniFile;
begin
ArqIni := TIniFile.Create(cx_CaminhoINI);
try
cx_DatabaseFB := ArqIni.ReadString(cx_Secao, 'Database', '');
cx_PasswordFB := ArqIni.ReadString(cx_Secao, 'Password', '');
cx_UserNameFB := ArqIni.ReadString(cx_Secao, 'User_Name', '');
cx_SQLDialectFB := ArqIni.ReadString(cx_Secao, 'SQLDialect', '');
cx_ProtocolFB := 'TCPIP';
finally
ArqIni.Free;
end;
end;
procedure TConexao.Setcx_CaminhoINI(const Value: String);
begin
Fcx_CaminhoINI := Value;
end;
procedure TConexao.Setcx_DatabaseFB(const Value: String);
begin
Fcx_DatabaseFB := Value;
end;
procedure TConexao.Setcx_PasswordFB(const Value: String);
begin
Fcx_PasswordFB := Value;
end;
procedure TConexao.Setcx_ProtocolFB(const Value: String);
begin
Fcx_ProtocolFB := Value;
end;
procedure TConexao.Setcx_Secao(const Value: String);
begin
Fcx_Secao := Value;
end;
procedure TConexao.Setcx_SQLDialectFB(const Value: String);
begin
Fcx_SQLDialectFB := Value;
end;
procedure TConexao.Setcx_UserNameFB(const Value: String);
begin
Fcx_UserNameFB := Value;
end;
end.
|
unit selBalance;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, seleccion, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, dxRibbonSkins, cxStyles, cxCustomData,
cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData,
cxClasses, cxLocalization, Datasnap.Provider, Datasnap.DBClient, Vcl.DBActns,
System.Actions, Vcl.ActnList, JvAppStorage, JvAppIniStorage, JvComponentBase,
JvFormPlacement, Vcl.ImgList, dxBar, cxGridLevel, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
dxStatusBar, dxRibbonStatusBar, dxRibbon;
type
TFSelBalance = class(TFSeleccion)
cdsID: TAutoIncField;
cdsFECHA: TDateTimeField;
cdsGADM: TStringField;
cdsGCOM: TStringField;
vistaID: TcxGridDBColumn;
vistaFECHA: TcxGridDBColumn;
cdsFECHAANT: TDateTimeField;
vistaFECHAANT: TcxGridDBColumn;
private
{ Private declarations }
FFecini: TDateTime;
FFecfin: TDateTime;
procedure SetFecfin(const Value: TDateTime);
procedure SetFecini(const Value: TDateTime);
public
{ Public declarations }
property Fecini: TDateTime read FFecini write SetFecini;
property Fecfin: TDateTime read FFecfin write SetFecfin;
procedure getResultado; override;
end;
var
FSelBalance: TFSelBalance;
implementation
uses
DMIng;
{$R *.dfm}
procedure TFSelBalance.getResultado;
begin
inherited;
FFecFin := cdsFECHA.value;
FFecIni := cdsFECHAANT.Value;
end;
procedure TFSelBalance.SetFecfin(const Value: TDateTime);
begin
FFecfin := Value;
end;
procedure TFSelBalance.SetFecini(const Value: TDateTime);
begin
FFecini := Value;
end;
end.
|
unit D_PublIn;
{ $Id: D_PublIn.pas,v 1.26 2014/08/13 12:50:00 dinishev Exp $ }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls, Mask,
k2Interfaces, k2Tags,
DT_Types, DT_Const, dt_AttrSchema, DT_Dict,
BottomBtnDlg, ToolEdit, tb97GraphicControl, TB97Ctls, vtSpeedButton,
ActnList,
l3Variant
;
type
TPublishedInEditDlg = class(TBottomBtnDlg)
Label3: TLabel;
edtPageNumbers: TEdit;
Label4: TLabel;
edtComment: TEdit;
Bevel4: TBevel;
Label7: TLabel;
lblPubSource: TLabel;
ActionList1: TActionList;
acAddIssueImage: TAction;
vtSpeedButton1: TvtSpeedButton;
cbClone: TCheckBox;
procedure acAddIssueImageExecute(Sender: TObject);
private
fRec : Il3TagRef; //PPublishDataRec;
fDocID : TDocID;
procedure CheckImageIcon;
public
function Execute(const aPubSourceName : AnsiString; aRec : Tl3Tag; aDocID : TDocID) : Boolean; reintroduce;
end;
function RunPublishedInEditDlg(aOwner: TComponent; const aPubSourceName : AnsiString; aRec : Tl3Tag; aDocID : TDocID): Boolean;
implementation
{$R *.DFM}
uses
l3Base, l3Tree, l3Nodes, l3Tree_TLB, l3Date, l3String, l3IniFile,
l3FileUtils,
IniShop, StrShop, ResShop,
vtDialogs,
DT_DocImages,
DictMetaForm, TreeDWin, D_ShowInfo,
arInterfaces;
function RunPublishedInEditDlg(aOwner: TComponent; const aPubSourceName : String; aRec : Tl3Tag; aDocID : TDocID): Boolean;
begin
with TPublishedInEditDlg.Create(aOwner) do
try
Result := Execute(aPubSourceName, aRec, aDocID);
finally
Free;
end;
end;
function TPublishedInEditDlg.Execute(const aPubSourceName : AnsiString; aRec : Tl3Tag; aDocID : TDocID) : Boolean;
begin
fDocID := aDocID;
fRec := aRec.AsRef;
with aRec do
begin
edtPageNumbers.Text := StrA[k2_tiPages];
edtComment.Text := StrA[k2_tiLinkComment];
cbClone.Checked := (IntA[k2_tiFlags] and pinfClone) > 0;
lblPubSource.Caption := aPubSourceName;
end;
ActionList1.Images := ArchiResources.CommonImageList;
//acAddIssueImage.Enabled := not fNonPeriodic;
CheckImageIcon;
Result := ShowModal = mrOk;
if Result then
with aRec do
begin
AttrW[k2_tiName, nil] := nil;
StrA[k2_tiPages] := edtPageNumbers.Text;
StrA[k2_tiLinkComment] := edtComment.Text;
if cbClone.Checked then
IntA[k2_tiFlags] := IntA[k2_tiFlags] or pinfClone
else
IntA[k2_tiFlags] := IntA[k2_tiFlags] and not pinfClone;
end;
end;
procedure TPublishedInEditDlg.CheckImageIcon;
begin
try
with fRec.AsObject do
if DocImageServer.IsImageExists(Attr[k2_tiSource].IntA[k2_tiHandle], IntA[k2_tiStart], IntA[k2_tiFinish],
StrA[k2_tiNumber], not BoolA[k2_tiIsPeriodic], fDocID) then
//if DocImageServer.IsImageExists(fRec) then
acAddIssueImage.ImageIndex := picSrcCheck
else
acAddIssueImage.ImageIndex := picPublishSrc;
except
acAddIssueImage.ImageIndex := picPublishSrc;
end;
end;
procedure TPublishedInEditDlg.acAddIssueImageExecute(Sender: TObject);
var
lFileName: AnsiString;
begin
UserConfig.Section := PrefSectName;
lFileName := UserConfig.ReadParamStrDef('ImageOpenInitialDir','');
if vtExecuteOpenDialog(lFileName, sidDocImageDlgFilter) then
begin
try
with fRec.AsObject do
DocImageServer.AddImageFile(lFileName, Attr[k2_tiSource].IntA[k2_tiHandle], IntA[k2_tiStart], IntA[k2_tiFinish],
StrA[k2_tiNumber], not BoolA[k2_tiIsPeriodic], fDocID);
except
On E : Exception do
begin
Application.ShowException(E);
Exit;
end;
end;
UserConfig.WriteParamStr('ImageOpenInitialDir',ExtractDirName(lFileName)+'\');
end;
CheckImageIcon;
end;
end.
|
unit ufmMainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, RasHelperClasses,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ImgList, Vcl.ComCtrls, Vcl.StdCtrls,
Ras, Vcl.ToolWin, Vcl.Menus, uRASMngrCommon, Vcl.ExtCtrls, System.ImageList,
Vcl.AppEvnts;
type
TfrmMainForm = class(TForm)
mmMainMenu: TMainMenu;
mniFile1: TMenuItem;
mniNew1: TMenuItem;
mniOpen1: TMenuItem;
mniSave1: TMenuItem;
mniN1: TMenuItem;
mniExit1: TMenuItem;
mniAdditional: TMenuItem;
pmPopup: TPopupMenu;
mniConnectPopup: TMenuItem;
mniDisconnectPopup: TMenuItem;
tvConnections: TTreeView;
mniN2: TMenuItem;
mniAddConnection: TMenuItem;
mniDeleteConnection: TMenuItem;
mniEditConnection: TMenuItem;
mniN3: TMenuItem;
mniAbout1: TMenuItem;
statStatus: TStatusBar;
mniEditConnectionPopup: TMenuItem;
spl1: TSplitter;
mmoLog: TMemo;
ilImages: TImageList;
trycnTray: TTrayIcon;
aplctnvntsEvents: TApplicationEvents;
pmTray: TPopupMenu;
Show1: TMenuItem;
Exit1: TMenuItem;
procedure aplctnvntsEventsMinimize(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure mniNew1Click(Sender: TObject);
procedure mniConnectPopupClick(Sender: TObject);
procedure tvConnectionsMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure mniDisconnectPopupClick(Sender: TObject);
// procedure tmrUpdTimerTimer(Sender: TObject);
procedure mniOpen1Click(Sender: TObject);
procedure mniSave1Click(Sender: TObject);
procedure mniExit1Click(Sender: TObject);
procedure mniEditConnectionClick(Sender: TObject);
procedure mniAddConnectionClick(Sender: TObject);
procedure mniAdditionalClick(Sender: TObject);
procedure mniselected1Click(Sender: TObject);
procedure mniEditConnectionPopupClick(Sender: TObject);
procedure Show1Click(Sender: TObject);
procedure trycnTrayDblClick(Sender: TObject);
private
FSelConnectionInd: Integer;
FOperationStatus: TOperationStatus;
FAddRoute: Boolean;
FRDPConnect: Boolean;
FRouteNodeAddr: string;
FRouteMask: string;
FRDPFile: string;
private
procedure StoreSelConnectionInd;
procedure ReStoreSelConnectionInd;
procedure UpdateConnectionView(ANode: TTreeNode;
APhonebookEntry: TRasPhonebookEntry);
private
function GetSelectedConnection: TRasPhonebookEntry;
procedure UpdatePhonebookView;
procedure Connect; overload;
procedure Disconnect; overload;
procedure EditConnection(AEntry: TRasPhonebookEntry); overload;
procedure EditConnection; overload;
procedure AddRouteToConnection(AEntry: TRasPhonebookEntry); overload;
procedure AppendToLog(const AText: string);
private
procedure SaveSettings;
procedure ReadSettings;
private
procedure OnMsgChangeState(var Msg: TMessage); message WM_CHANGESTATE;
procedure OnMsgConnectionState(var Msg: TMessage); message WM_CONNSTATE;
procedure OnMsgConnectionMessage(var Msg: TMessage); message WM_CONNMESSAGE;
public
// FPhonebook: TPhonebook;
end;
var
frmMainForm: TfrmMainForm;
implementation
uses Winapi.CommCtrl, RasUtils, ufmAdditional, Winapi.ShlObj,
System.IniFiles, RasDlg, System.UITypes;
function GetSpecialPath(CSIDL: Word): string;
var
S: string;
begin
SetLength(S, MAX_PATH);
if not SHGetSpecialFolderPath(0, PChar(S), CSIDL, True) then
S := GetSpecialPath(CSIDL_APPDATA);
Result := IncludeTrailingPathDelimiter(PChar(S));
end;
{$R *.dfm}
{ TfrmMainForm }
procedure TfrmMainForm.AddRouteToConnection(AEntry: TRasPhonebookEntry);
begin
if AEntry.Connection.Connected then
AddRoute(Application.Handle, FRouteNodeAddr, FRouteMask,
AEntry.Connection.IPAddress);
end;
procedure TfrmMainForm.aplctnvntsEventsMinimize(Sender: TObject);
begin
Hide();
WindowState := wsMinimized;
trycnTray.Visible := True;
trycnTray.Animate := True;
trycnTray.ShowBalloonHint;
end;
procedure TfrmMainForm.AppendToLog(const AText: string);
var
LText: string;
begin
LText := Trim(AText);
if LText = '' then
Exit;
statStatus.Panels[0].Text := LText;
LText := FormatDateTime('yyyy.mm.dd hh:nn:ss.zzz', Now) + #9 + LText;
mmoLog.Lines.Add(LText);
end;
procedure TfrmMainForm.Connect;
var
SelConnection: TRasPhonebookEntry;
begin
SelConnection := GetSelectedConnection;
if SelConnection = nil then
Exit;
SelConnection.NeedConnect := True;
end;
procedure TfrmMainForm.Disconnect;
var
SelConnection: TRasPhonebookEntry;
begin
SelConnection := GetSelectedConnection;
if SelConnection = nil then
Exit;
SelConnection.NeedConnect := False;
end;
procedure TfrmMainForm.EditConnection(AEntry: TRasPhonebookEntry);
var
LEntry: TRasEntryDlg;
begin
FillChar(LEntry, SizeOf(TRasEntryDlg), 0);
LEntry.dwFlags := 0;
LEntry.dwSize := SizeOf(TRasEntryDlg);
RasEntryDlg(nil, PWideChar(AEntry.Name), LEntry);
end;
procedure TfrmMainForm.EditConnection;
var
SelConnection: TRasPhonebookEntry;
begin
SelConnection := GetSelectedConnection;
if SelConnection = nil then
Exit;
EditConnection(SelConnection);
Phonebook.Refresh;
end;
procedure TfrmMainForm.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TfrmMainForm.FormCreate(Sender: TObject);
begin
NotifyWnd := Self.Handle;
FSelConnectionInd := -1;
FOperationStatus := osUnknown;
FAddRoute := False;
FRDPConnect := False;
FRouteNodeAddr := '';
FRouteMask := '';
FRDPFile := '';
Phonebook := TPhonebook.Create(Self.Handle);
tvConnections.Perform(TVM_SETITEMHEIGHT, 21, 0);
ReadSettings;
UpdatePhonebookView;
end;
procedure TfrmMainForm.FormDestroy(Sender: TObject);
begin
SaveSettings;
FreeAndNil(Phonebook);
end;
function TfrmMainForm.GetSelectedConnection: TRasPhonebookEntry;
var
SelNode: TTreeNode;
begin
Result := nil;
SelNode := tvConnections.Selected;
if SelNode = nil then
Exit;
if SelNode.Level = 0 then
Exit;
while SelNode.Level <> 1 do
SelNode := SelNode.Parent;
Result := TRasPhonebookEntry(SelNode.Data);
end;
procedure TfrmMainForm.mniAddConnectionClick(Sender: TObject);
begin
RasCreatePhonebookEntry(Self.Handle, nil);
end;
procedure TfrmMainForm.mniAdditionalClick(Sender: TObject);
begin
with TfrmAdditional.Create(Self) do
try
chkAddRoute.Checked := FAddRoute;
chkRDPConnect.Checked := FRDPConnect;
edtNodeAddr.Text := FRouteNodeAddr;
edtMask.Text := FRouteMask;
edtRDPFile.Text := FRDPFile;
if IsPositiveResult(ShowModal) then
begin
FAddRoute := chkAddRoute.Checked;
FRDPConnect := chkRDPConnect.Checked;
FRouteNodeAddr := edtNodeAddr.Text;
FRouteMask := edtMask.Text;
FRDPFile := edtRDPFile.Text;
SaveSettings;
end;
finally
Free;
end;
end;
procedure TfrmMainForm.mniConnectPopupClick(Sender: TObject);
begin
Connect;
end;
procedure TfrmMainForm.mniDisconnectPopupClick(Sender: TObject);
begin
Disconnect;
end;
procedure TfrmMainForm.mniEditConnectionClick(Sender: TObject);
begin
EditConnection;
end;
procedure TfrmMainForm.mniEditConnectionPopupClick(Sender: TObject);
begin
EditConnection;
end;
procedure TfrmMainForm.mniExit1Click(Sender: TObject);
begin
Close;
end;
procedure TfrmMainForm.mniNew1Click(Sender: TObject);
begin
Phonebook.Refresh;
end;
procedure TfrmMainForm.mniOpen1Click(Sender: TObject);
begin
Connect;
end;
procedure TfrmMainForm.mniSave1Click(Sender: TObject);
begin
Disconnect;
end;
procedure TfrmMainForm.mniselected1Click(Sender: TObject);
begin
ShowMessage(IntToStr(tvConnections.Selected.AbsoluteIndex));
tvConnections.Selected := tvConnections.Items
[tvConnections.Selected.AbsoluteIndex];
end;
procedure TfrmMainForm.OnMsgChangeState(var Msg: TMessage);
var
I: Integer;
Root, Node: TTreeNode;
LItem: TRasPhonebookEntry;
begin
if tvConnections.Items.Count = 0 then
Exit;
LItem := TRasPhonebookEntry(Msg.WParam);
Root := tvConnections.Items[0];
for I := 0 to Root.Count - 1 do
begin
Node := Root.Item[I];
if Node.Data <> nil then
begin
if TRasPhonebookEntry(Node.Data) = LItem then
UpdateConnectionView(Node, LItem);
end;
end;
end;
procedure TfrmMainForm.OnMsgConnectionMessage(var Msg: TMessage);
begin
AppendToLog(PChar(Msg.LParam));
end;
procedure TfrmMainForm.OnMsgConnectionState(var Msg: TMessage);
begin
AppendToLog(GetOperationStatusDescr(TOperationStatus(Msg.LParam)));
end;
procedure TfrmMainForm.ReadSettings;
var
FileName: string;
DirName: string;
IniFile: TIniFile;
begin
FileName := GetSpecialPath(CSIDL_COMMON_APPDATA) + SettingsFileName;
DirName := ExtractFilePath(FileName);
ForceDirectories(DirName);
IniFile := TIniFile.Create(FileName);
try
FAddRoute := IniFile.ReadBool('OPTIONS', 'AddRoute', False);
FRDPConnect := IniFile.ReadBool('OPTIONS', 'RDPConnect', False);
FRouteNodeAddr := IniFile.ReadString('OPTIONS', 'RouteNodeAddr', '');
FRouteMask := IniFile.ReadString('OPTIONS', 'RouteMask', '');
FRDPFile := IniFile.ReadString('OPTIONS', 'RDPFile', '');
finally
IniFile.Free;
end;
end;
procedure TfrmMainForm.ReStoreSelConnectionInd;
begin
if (FSelConnectionInd >= 0) and (tvConnections.Items.Count > FSelConnectionInd)
then
begin
tvConnections.Enabled := True;
tvConnections.Selected := tvConnections.Items[FSelConnectionInd];
// ProcessMessages;
tvConnections.SetFocus;
end;
end;
procedure TfrmMainForm.SaveSettings;
var
FileName: string;
DirName: string;
IniFile: TIniFile;
// I: Integer;
begin
FileName := GetSpecialPath(CSIDL_COMMON_APPDATA) + SettingsFileName;
DirName := ExtractFilePath(FileName);
ForceDirectories(DirName);
IniFile := TIniFile.Create(FileName);
try
IniFile.WriteBool('OPTIONS', 'AddRoute', FAddRoute);
IniFile.WriteBool('OPTIONS', 'RDPConnect', FRDPConnect);
IniFile.WriteString('OPTIONS', 'RouteNodeAddr', FRouteNodeAddr);
IniFile.WriteString('OPTIONS', 'RouteMask', FRouteMask);
IniFile.WriteString('OPTIONS', 'RDPFile', FRDPFile);
finally
IniFile.Free;
end;
end;
procedure TfrmMainForm.Show1Click(Sender: TObject);
begin
trycnTrayDblClick(Sender);
end;
procedure TfrmMainForm.StoreSelConnectionInd;
begin
if tvConnections.Selected <> nil then
FSelConnectionInd := tvConnections.Selected.AbsoluteIndex
else
FSelConnectionInd := -1;
end;
procedure TfrmMainForm.trycnTrayDblClick(Sender: TObject);
begin
trycnTray.Visible := False;
Show();
WindowState := wsNormal;
Application.BringToFront();
end;
procedure TfrmMainForm.tvConnectionsMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Node: TTreeNode;
begin
Node := TTreeView(Sender).GetNodeAt(X, Y);
if Node = nil then
Exit;
if Button = mbRight then
TTreeView(Sender).Selected := Node;
end;
procedure TfrmMainForm.UpdatePhonebookView;
var
I: Integer;
Root, Node, EntryNode, ConnectionNode: TTreeNode;
begin
StoreSelConnectionInd;
tvConnections.Items.BeginUpdate;
try
tvConnections.Items.Clear;
Root := tvConnections.Items.AddFirst(nil, 'Phonebook');
Root.SelectedIndex := 0;
Root.ImageIndex := 0;
for I := 0 to Phonebook.Count - 1 do
begin
EntryNode := tvConnections.Items.AddChildObject(Root, Phonebook[I].Name,
Phonebook[I]);
EntryNode.SelectedIndex := 1;
EntryNode.ImageIndex := 1;
Node := tvConnections.Items.AddChild(EntryNode,
'Phone number: ' + Phonebook[I].PhoneNumber);
Node.SelectedIndex := 3;
Node.ImageIndex := 3;
Node := tvConnections.Items.AddChild(EntryNode,
'User name: ' + Phonebook[I].UserName);
Node.SelectedIndex := 4;
Node.ImageIndex := 4;
ConnectionNode := tvConnections.Items.AddChild(EntryNode,
'Connected: no');
ConnectionNode.SelectedIndex := 7;
ConnectionNode.ImageIndex := 7;
UpdateConnectionView(EntryNode, Phonebook[I]);
Root.Expand(False);
end;
finally
ReStoreSelConnectionInd;
tvConnections.Items.EndUpdate;
end;
end;
procedure TfrmMainForm.UpdateConnectionView(ANode: TTreeNode;
APhonebookEntry: TRasPhonebookEntry);
var
LConnectionNode, LNode: TTreeNode;
begin
if ANode.Count < 3 then
Exit;
LConnectionNode := ANode.Item[2];
LConnectionNode.DeleteChildren;
if not APhonebookEntry.Connection.Connected then
begin
ANode.SelectedIndex := 1;
ANode.ImageIndex := 1;
LConnectionNode.Text := 'Connected: no';
Exit;
end;
ANode.SelectedIndex := 2;
ANode.ImageIndex := 2;
LConnectionNode.Text := 'Connected: yes';
LNode := tvConnections.Items.AddChild(LConnectionNode,
'Device: ' + APhonebookEntry.Connection.DeviceName);
LNode.SelectedIndex := 5;
LNode.ImageIndex := 5;
LNode := tvConnections.Items.AddChild(LConnectionNode,
'Status: ' + APhonebookEntry.Connection.ConnStatusStr);
LNode.SelectedIndex := 6;
LNode.ImageIndex := 6;
LNode := tvConnections.Items.AddChild(LConnectionNode,
'IP address: ' + APhonebookEntry.Connection.IPAddress);
LNode.SelectedIndex := 8;
LNode.ImageIndex := 8;
if FAddRoute then
AddRouteToConnection(APhonebookEntry);
end;
end.
|
unit SkinEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Menus, MGR32_Image;
type
TFrmSkinEdit = class(TForm)
LstSkin: TListBox;
Label1: TLabel;
EdtName: TEdit;
Label2: TLabel;
EdtId: TEdit;
Label3: TLabel;
LstAction: TListBox;
Label5: TLabel;
LstDir: TListBox;
Label6: TLabel;
EdtAnimDelay: TEdit;
Label7: TLabel;
LstSprite: TListBox;
View: TMPaintBox32;
Label8: TLabel;
PopupSpriteList: TPopupMenu;
MainMenu1: TMainMenu;
File1: TMenuItem;
LoadMonsterSkins1: TMenuItem;
SAveMonsters1: TMenuItem;
EdtVtxColor: TEdit;
Label9: TLabel;
GroupBox1: TGroupBox;
ChkReverse: TCheckBox;
Button1: TButton;
Button2: TButton;
DlgOpen: TOpenDialog;
DlgSave: TSaveDialog;
PopupSkinList: TPopupMenu;
AddSkin1: TMenuItem;
Duplicateskin1: TMenuItem;
N1: TMenuItem;
DeleteSkin1: TMenuItem;
Label4: TLabel;
ComboColorFx: TComboBox;
Label10: TLabel;
EdtMonsterSize: TEdit;
EdtOffX: TEdit;
Label11: TLabel;
Label12: TLabel;
EdtOffY: TEdit;
N2: TMenuItem;
AutoFill1: TMenuItem;
AutoSort1: TMenuItem;
N3: TMenuItem;
ClearList1: TMenuItem;
Sort1: TMenuItem;
procedure SAveMonsters1Click(Sender: TObject);
procedure LoadMonsterSkins1Click(Sender: TObject);
procedure AddSkin1Click(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure DeleteSkin1Click(Sender: TObject);
procedure EdtNameChange(Sender: TObject);
procedure EdtIdChange(Sender: TObject);
procedure LstSkinClick(Sender: TObject);
procedure EdtVtxColorChange(Sender: TObject);
procedure EdtAnimDelayChange(Sender: TObject);
procedure ComboColorFxChange(Sender: TObject);
procedure LstActionClick(Sender: TObject);
procedure LstDirClick(Sender: TObject);
Procedure RefreshView;
procedure LstSpriteDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure LstSpriteDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure LstSpriteClick(Sender: TObject);
procedure EdtMonsterSizeChange(Sender: TObject);
procedure AutoFill1Click(Sender: TObject);
procedure ClearList1Click(Sender: TObject);
procedure Sort1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmSkinEdit: TFrmSkinEdit;
implementation
{$R *.dfm}
uses comctrls,FastStream,udda,IdTypes,globals;
procedure TFrmSkinEdit.FormResize(Sender: TObject);
begin
LstSkin.Height:=(FrmSkinEdit.ClientHeight-LstSkin.Top)-4;
LstSprite.Height:=(FrmSkinEdit.ClientHeight-LstSprite.Top)-4;
GroupBox1.Top:=(FrmSkinEdit.ClientHeight-GroupBox1.Height)-4;
View.Width:=(FrmSkinEdit.ClientWidth-View.Left)-4;
View.Height:=(FrmSkinEdit.ClientHeight-View.Top)-4;
end;
Procedure ReadFrameFromStream(var Fst:TFastStream;Frame:PFrame);
begin
Frame^.SpriteName:=Fst.ReadWordString;
Frame^.Offx:=Fst.ReadWord;
Frame^.Offy:=Fst.ReadWord;
end;
Procedure ReadSoundFromStream(var Fst:TFastStream;Sound:PSoundInfo);
begin
Sound^.SoundName:=Fst.ReadWordString;
Sound^.PitchDev:=Fst.ReadSingle;
end;
Procedure WriteFrameToStream(var Fst:TFastStream;Frame:PFrame);
begin
Fst.WriteWordString(Frame^.SpriteName);
Fst.WriteWord(Word(Frame^.Offx));
Fst.WriteWord(Word(Frame^.Offy));
end;
Procedure WriteSoundToStream(var Fst:TFastStream;Sound:PSoundInfo);
begin
Fst.WriteWordString(Sound^.SoundName);
Fst.WriteSingle(Sound^.PitchDev);
end;
procedure TFrmSkinEdit.LoadMonsterSkins1Click(Sender: TObject);
var i,j,k,Count,Version:longint;
Fst:TFastStream;
Skin:PMonsterSkinInfo;
Frame:PFrame;
Sound:PSoundInfo;
begin
if DlgOpen.Execute then
begin
Fst:=TFastStream.Create;
Fst.LoadFromFile(DlgOpen.FileName);
Version:=Fst.ReadLong;
Count:=Fst.ReadLong;
for i:=0 to Count-1 do
begin
new(Skin);
with Skin^ do
begin
SkinName:=Fst.ReadWordString;
SkinId:=Fst.ReadWord;
VertexColor:=Fst.ReadLong;
ColorFx:=Fst.ReadLong;
AnimationDelay:=Fst.ReadSingle;
MonsterSize:=Fst.ReadSingle;
for j:=0 to 7 do
begin
Walk[j].Reversed:=Fst.ReadLong;
Walk[j].GraphCount:=Fst.ReadLong;
Walk[j].FrameList:=Tlist.Create;
for k:=0 to Walk[j].GraphCount-1 do
begin
new(Frame);
ReadFrameFromStream(Fst,Frame);
Walk[j].FrameList.Add(Frame);
end;
end;
for j:=0 to 7 do
begin
Attack[j].Reversed:=Fst.ReadLong;
Attack[j].GraphCount:=Fst.ReadLong;
Attack[j].FrameList:=Tlist.Create;
for k:=0 to Attack[j].GraphCount-1 do
begin
new(Frame);
ReadFrameFromStream(Fst,Frame);
Attack[j].FrameList.Add(Frame);
end;
end;
Death.Reversed:=Fst.ReadLong;
Death.GraphCount:=Fst.ReadLong;
Death.FrameList:=Tlist.Create;
for k:=0 to Death.GraphCount-1 do
begin
new(Frame);
ReadFrameFromStream(Fst,Frame);
Death.FrameList.Add(Frame);
end;
AtkSoundCount:=Fst.ReadLong;
AtkSounds:=TList.Create;
for j:=0 to AtkSoundCount-1 do
begin
new(Sound);
ReadSoundFromStream(Fst,Sound);
AtkSounds.Add(Sound);
end;
HitSoundCount:=Fst.ReadLong;
HitSounds:=TList.Create;
for j:=0 to HitSoundCount-1 do
begin
new(Sound);
ReadSoundFromStream(Fst,Sound);
HitSounds.Add(Sound);
end;
DieSoundCount:=Fst.ReadLong;
DieSounds:=TList.Create;
for j:=0 to DieSoundCount-1 do
begin
new(Sound);
ReadSoundFromStream(Fst,Sound);
DieSounds.Add(Sound);
end;
IdleSoundCount:=Fst.ReadLong;
IdleSounds:=TList.Create;
for j:=0 to IdleSoundCount-1 do
begin
new(Sound);
ReadSoundFromStream(Fst,Sound);
IdleSounds.Add(Sound);
end;
end;
LstSkin.AddItem(Skin^.SkinName+' : '+IntToStr(Skin^.SkinId),TObject(Skin));
end;
Fst.Free;
end;
end;
procedure TFrmSkinEdit.SaveMonsters1Click(Sender: TObject);
var i,j,k,Count,Version:longint;
Fst:TFastStream;
Skin:PMonsterSkinInfo;
begin
DlgSave.FileName:=DlgOpen.FileName;
if DlgSave.Execute then
begin
Fst:=TFastStream.Create;
Version:=1;
Fst.WriteLong(Version);
Count:=LstSkin.Count;
Fst.WriteLong(Count);
for i:=0 to Count-1 do
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[i]);
with Skin^ do
begin
Fst.WriteWordString(SkinName);
Fst.WriteWord(SkinId);
Fst.WriteLong(VertexColor);
Fst.WriteLong(ColorFx);
Fst.WriteSingle(AnimationDelay);
Fst.WriteSingle(MonsterSize);
for j:=0 to 7 do
begin
Fst.WriteLong(Walk[j].Reversed);
Walk[j].GraphCount:=Walk[j].FrameList.Count;
Fst.WriteLong(Walk[j].GraphCount);
for k:=0 to Walk[j].GraphCount-1 do
begin
WriteFrameToStream(Fst,Walk[j].FrameList[k]);
end;
end;
for j:=0 to 7 do
begin
Fst.WriteLong(Attack[j].Reversed);
Attack[j].GraphCount:=Attack[j].FrameList.Count;
Fst.WriteLong(Attack[j].GraphCount);
for k:=0 to Attack[j].GraphCount-1 do
begin
WriteFrameToStream(Fst,Attack[j].FrameList[k]);
end;
end;
Fst.WriteLong(Death.Reversed);
Death.GraphCount:=Death.FrameList.Count;
Fst.WriteLong(Death.GraphCount);
for k:=0 to Death.GraphCount-1 do
begin
WriteFrameToStream(Fst,Death.FrameList[k]);
end;
AtkSounds.Pack;
AtkSoundCount:=AtkSounds.Count;
Fst.WriteLong(AtkSoundCount);
for j:=0 to AtkSoundCount-1 do
begin
WriteSoundToStream(Fst,AtkSounds.Items[j]);
end;
HitSounds.Pack;
HitSoundCount:=HitSounds.Count;
Fst.WriteLong(HitSoundCount);
for j:=0 to HitSoundCount-1 do
begin
WriteSoundToStream(Fst,HitSounds.Items[j]);
end;
DieSounds.Pack;
DieSoundCount:=DieSounds.Count;
Fst.WriteLong(DieSoundCount);
for j:=0 to DieSoundCount-1 do
begin
WriteSoundToStream(Fst,DieSounds.Items[j]);
end;
IdleSounds.Pack;
IdleSoundCount:=IdleSounds.Count;
Fst.WriteLong(IdleSoundCount);
for j:=0 to IdleSoundCount-1 do
begin
WriteSoundToStream(Fst,IdleSounds.Items[j]);
end;
end;
end;
Fst.WriteToFile(DlgSave.FileName);
Fst.Free;
end;
end;
procedure TFrmSkinEdit.Sort1Click(Sender: TObject);
begin
LstSkin.Sorted:=LstSkin.Sorted xor true;
TMenuItem(sender).Checked:=LstSkin.Sorted;
end;
procedure TFrmSkinEdit.AddSkin1Click(Sender: TObject);
var Skin:PMonsterSkinInfo;
i:longint;
begin
New(Skin);
with Skin^ do
begin
SkinName:='A New Skin';
SkinId:=0;
VertexColor:=$FFFFFFFF;
ColorFx:=0;
AnimationDelay:=0.033;
MonsterSize:=1;
for i:=0 to 7 do
begin
Walk[i].Reversed:=0;
Walk[i].GraphCount:=0;
Walk[i].FrameList:=TList.Create;
Attack[i].Reversed:=0;
Attack[i].GraphCount:=0;
Attack[i].FrameList:=TList.Create;
end;
for i:=5 to 7 do
begin
Walk[i].Reversed:=1;
Attack[i].Reversed:=1;
end;
Death.Reversed:=0;
Death.GraphCount:=0;
Death.FrameList:=TList.Create;
AtkSoundCount:=0;
AtkSounds:=TList.Create;
HitSoundCount:=0;
HitSounds:=TList.Create;
DieSoundCount:=0;
DieSounds:=TList.Create;
IdleSoundCount:=0;
IdleSounds:=TList.Create;
end;
LstSkin.AddItem(Skin^.SkinName+' : '+IntToStr(Skin^.SkinId),TObject(Skin));
end;
procedure TFrmSkinEdit.DeleteSkin1Click(Sender: TObject);
var Skin:PMonsterSkinInfo;
i,j:integer;
begin
if LstSkin.ItemIndex>=0 then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
With Skin^ do
begin
for i:=0 to 7 do
begin
Walk[i].Reversed:=0;
Walk[i].GraphCount:=0;
for j:=0 to Walk[i].FrameList.Count-1 do
begin
Dispose(PFrame(Walk[i].FrameList.Items[j]));
end;
Walk[i].FrameList.Free;
Attack[i].Reversed:=0;
Attack[i].GraphCount:=0;
for j:=0 to Attack[i].FrameList.Count-1 do
begin
Dispose(PFrame(Attack[i].FrameList.Items[j]));
end;
Attack[i].FrameList.Free;
end;
Death.FrameList.free;
for i:=0 to AtkSounds.Count-1 do
Dispose(PSoundInfo(AtkSounds.Items[i]));
AtkSounds.Free;
for i:=0 to HitSounds.Count-1 do
Dispose(PSoundInfo(HitSounds.Items[i]));
HitSounds.Free;
for i:=0 to DieSounds.Count-1 do
Dispose(PSoundInfo(DieSounds.Items[i]));
DieSounds.Free;
for i:=0 to IdleSounds.Count-1 do
Dispose(PSoundInfo(IdleSounds.Items[i]));
IdleSounds.Free;
end;
LstSkin.DeleteSelected;
Dispose(Skin);
end;
end;
function GenerateDeathSuffix(const i:integer):string;
var Sec:string;
begin
Sec:='';
if (i div 26) >0 then
Sec:=chr((i div 26)+48);
result:='c-'+chr((i mod 26)+97)+sec;
end;
Function GenerateWalkSuffix(const Dir,i:integer):string;
var Sec:string;
begin
Sec:='';
if (i div 26) >0 then
Sec:=chr((i div 26)+48);
case Dir of
0:Result:='000-'+chr((i mod 26)+97)+sec;
1:Result:='045-'+chr((i mod 26)+97)+sec;
2:Result:='090-'+chr((i mod 26)+97)+sec;
3:Result:='135-'+chr((i mod 26)+97)+sec;
4:Result:='180-'+chr((i mod 26)+97)+sec;
end;
end;
procedure TFrmSkinEdit.AutoFill1Click(Sender: TObject);
var Skin:PMonsterSkinInfo;
BaseName:string;
SpName:string;
Found:boolean;
Counter:longint;
Sprite:PSprite;
Frame,CpyFrame:PFrame;
Direction,i,CpyDir:integer;
begin //
if LstSkin.ItemIndex>=0 then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
BaseName:=LowerCase(InputBox('Base Sprite Name','Name: ',''));
if BaseName='' then exit;
//Walk sprites
for Direction:=0 to 4 do
begin
Found:=true;
Counter:=0;
repeat
SpName:=BaseName+GenerateWalkSuffix(Direction,Counter);
Sprite:=Index.SpriteHash.SearchByName(SpName);
if Sprite<>nil then
begin
new(Frame);
Frame^.SpriteName:=SpName;
Frame^.Offx:=0;
Frame^.Offy:=0;
GetSpriteOffset(SpName,Frame^.Offx,Frame^.Offy,0);
Skin^.Walk[Direction].FrameList.Add(Frame);
inc(Counter);
end else
begin
Found:=false;
end;
until Found=false;
if counter=0 then break;
end;
//we need to copy the frame for the reversed direction
if counter>0 then
for Direction:=5 to 7 do
begin
CpyDir:=3-(Direction-5);//take the related normal direction
//copy each frame, and take the good offset
for i:=0 to Skin^.Walk[CpyDir].FrameList.Count-1 do
begin
CpyFrame:=Skin^.Walk[CpyDir].FrameList.Items[i];
new(frame);
Frame^.SpriteName:=CpyFrame^.SpriteName;
GetSpriteOffset(Frame^.SpriteName,Frame^.Offx,Frame^.Offy,1);
Skin^.Walk[Direction].FrameList.Add(Frame);
end;
end;
//Attack sprites
for Direction:=0 to 4 do
begin
Found:=true;
Counter:=0;
repeat
SpName:=BaseName+'a'+GenerateWalkSuffix(Direction,Counter);
Sprite:=Index.SpriteHash.SearchByName(SpName);
if Sprite<>nil then
begin
new(Frame);
Frame^.SpriteName:=SpName;
Frame^.Offx:=0;
Frame^.Offy:=0;
GetSpriteOffset(SpName,Frame^.Offx,Frame^.Offy,0);
Skin^.Attack[Direction].FrameList.Add(Frame);
inc(Counter);
end else
begin
Found:=false;
end;
until Found=false;
if counter=0 then break;
end;
//we need to copy the frame for the reversed direction
if counter>0 then
for Direction:=5 to 7 do
begin
CpyDir:=3-(Direction-5);//take the related normal direction
//copy each frame, and take the good offset
for i:=0 to Skin^.Attack[CpyDir].FrameList.Count-1 do
begin
CpyFrame:=Skin^.Attack[CpyDir].FrameList.Items[i];
new(frame);
Frame^.SpriteName:=CpyFrame^.SpriteName;
GetSpriteOffset(Frame^.SpriteName,Frame^.Offx,Frame^.Offy,1);
Skin^.Attack[Direction].FrameList.Add(Frame);
end;
end;
//death sprites
Found:=true;
Counter:=0;
repeat
SpName:=BaseName+GenerateDeathSuffix(Counter);
Sprite:=Index.SpriteHash.SearchByName(SpName);
if Sprite<>nil then
begin
new(Frame);
Frame^.SpriteName:=SpName;
Frame^.Offx:=0;
Frame^.Offy:=0;
GetSpriteOffset(SpName,Frame^.Offx,Frame^.Offy,0);
Skin^.Death.FrameList.Add(Frame);
end else
begin
Found:=false;
end;
inc(Counter);
until Found=false;
end;
RefreshView;
end;
procedure TFrmSkinEdit.LstSkinClick(Sender: TObject);
var Skin:PMonsterSkinInfo;
begin
if LstSkin.ItemIndex>=0 then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
EdtName.Text:=Skin^.SkinName;
EdtId.Text:=IntToStr(Skin^.SkinId);
EdtAnimDelay.Text:=IntToStr(round(Skin^.AnimationDelay*1000));
EdtVtxColor.Text:=IntToHex(Skin^.VertexColor,8);
ComboColorFx.ItemIndex:=Skin^.ColorFx;
EdtMonsterSize.Text:=IntToStr(round(Skin^.MonsterSize*100));
RefreshView;
end;
end;
procedure TFrmSkinEdit.LstActionClick(Sender: TObject);
begin
if LstSkin.ItemIndex>=0 then
begin
RefreshView;
end;
end;
procedure TFrmSkinEdit.LstDirClick(Sender: TObject);
begin
if LstSkin.ItemIndex>=0 then
begin
RefreshView;
end;
end;
procedure TFrmSkinEdit.RefreshView;
var Skin:PMonsterSkinInfo;
Frame:PFrame;
i:longint;
begin
LstSprite.Items.BeginUpdate;
LstSprite.Items.Clear;
if LstSkin.ItemIndex>=0 then
if LstAction.ItemIndex>=0 then
if LstDir.ItemIndex>=0 then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
case LstAction.ItemIndex of
0:begin
ChkReverse.Checked:=Boolean(Skin^.Walk[LstDir.ItemIndex].Reversed);
for i:=0 to Skin^.Walk[LstDir.ItemIndex].FrameList.Count-1 do
begin
Frame:=Skin^.Walk[LstDir.ItemIndex].FrameList.Items[i];
LstSprite.Items.AddObject(Frame.SpriteName,TObject(Frame));
end;
end;
1:begin
ChkReverse.Checked:=Boolean(Skin^.Attack[LstDir.ItemIndex].Reversed);
for i:=0 to Skin^.Attack[LstDir.ItemIndex].FrameList.Count-1 do
begin
Frame:=Skin^.Attack[LstDir.ItemIndex].FrameList.Items[i];
LstSprite.Items.AddObject(Frame.SpriteName,TObject(Frame));
end;
end;
2:begin
ChkReverse.Checked:=boolean(Skin^.Death.Reversed);
for i:=0 to Skin^.Death.FrameList.Count-1 do
begin
Frame:=Skin^.Death.FrameList.Items[i];
LstSprite.Items.AddObject(Frame.SpriteName,TObject(Frame));
end;
end;
end;
end;
LstSprite.Items.EndUpdate;
end;
procedure TFrmSkinEdit.EdtAnimDelayChange(Sender: TObject);
var Skin:PMonsterSkinInfo;
begin
if LstSkin.ItemIndex>=0 then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
if EdtAnimDelay.Text<>'' then
Skin^.AnimationDelay:=StrToInt(EdtAnimDelay.Text)/1000;
end;
end;
procedure TFrmSkinEdit.EdtIdChange(Sender: TObject);
var Skin:PMonsterSkinInfo;
begin
if LstSkin.ItemIndex>=0 then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
if EdtId.Text<>'' then
Skin^.SkinId:=StrToInt(EdtId.Text);
LstSkin.Items[LstSkin.ItemIndex]:=Skin^.SkinName+' : '+IntToStr(Skin^.SkinId);
end;
end;
procedure TFrmSkinEdit.EdtMonsterSizeChange(Sender: TObject);
var Skin:PMonsterSkinInfo;
begin
if LstSkin.ItemIndex>=0 then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
if EdtMonsterSize.Text<>'' then
Skin^.MonsterSize:=StrToInt(EdtMonsterSize.Text)/100;
end;
end;
procedure TFrmSkinEdit.EdtNameChange(Sender: TObject);
var Skin:PMonsterSkinInfo;
begin
if LstSkin.ItemIndex>=0 then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
Skin^.SkinName:=EdtName.Text;
LstSkin.Items[LstSkin.ItemIndex]:=Skin^.SkinName+' : '+IntToStr(Skin^.SkinId);
end;
end;
procedure TFrmSkinEdit.ComboColorFxChange(Sender: TObject);
var Skin:PMonsterSkinInfo;
begin
if LstSkin.ItemIndex>=0 then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
Skin^.ColorFx:=ComboColorFx.ItemIndex;
end;
end;
procedure TFrmSkinEdit.EdtVtxColorChange(Sender: TObject);
var Skin:PMonsterSkinInfo;
begin
if LstSkin.ItemIndex>=0 then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
Skin^.VertexColor:=HexToInt(EdtVtxColor.Text);
end;
end;
procedure TFrmSkinEdit.LstSpriteClick(Sender: TObject);
var Skin:PMonsterSkinInfo;
Rev:Cardinal;
Frame:PFrame;
Sprite:PSprite;
Surface:PCardinal;
begin
if (LstSkin.ItemIndex>=0) and (LstSprite.ItemIndex>=0) then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
if LstAction.ItemIndex>=0 then
if LstDir.ItemIndex>=0 then
begin
case LstAction.ItemIndex of
0:begin
Frame:=Skin^.Walk[LstDir.ItemIndex].FrameList[LstSprite.ItemIndex];
Rev:=Skin^.Walk[LstDir.ItemIndex].Reversed;
end;
1:begin
Frame:=Skin^.Attack[LstDir.ItemIndex].FrameList[LstSprite.ItemIndex];
Rev:=Skin^.Attack[LstDir.ItemIndex].Reversed;
end;
2:begin
Frame:=Skin^.Death.FrameList[LstSprite.ItemIndex];
Rev:=Skin^.Death.Reversed;
end;
end;
EdtOffX.Text:=IntToStr(Frame^.Offx);
EdtOffY.Text:=IntToStr(Frame^.Offy);
//get the sprite
Sprite:=nil;
if Index.SpriteHash<>nil then
Sprite:=Index.SpriteHash.SearchByName(Frame^.SpriteName);
if Sprite=nil then
exit;
Surface:=GetSpriteA8R8G8B8Surface(Sprite);
DrawA8R8G8B8(Surface,Sprite^.Width,Sprite^.Height,Frame^.Offx-16,Frame^.Offy-8,Rev,1,Skin^.VertexColor,Skin^.ColorFx,View);
FreeMem(Surface);
end;
end;
end;
procedure TFrmSkinEdit.ClearList1Click(Sender: TObject);
var Skin:PMonsterSkinInfo;
Rev:Cardinal;
Frame:PFrame;
Sprite:PSprite;
Surface:PCardinal;
begin
if (LstSkin.ItemIndex>=0) then
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
if LstAction.ItemIndex>=0 then
if LstDir.ItemIndex>=0 then
begin
//TODO Dispose the frame !!!!!!
case LstAction.ItemIndex of
0:begin
Skin^.Walk[LstDir.ItemIndex].FrameList.Clear;
end;
1:begin
Skin^.Attack[LstDir.ItemIndex].FrameList.Clear;
end;
2:begin
Skin^.Death.FrameList.Clear;
end;
end;
end;
end;
RefreshView;
end;
procedure TFrmSkinEdit.LstSpriteDragDrop(Sender, Source: TObject; X, Y: Integer);
var TempList:TList;
i:integer;
Tree:TTreeView;
Frame:PFrame;
Skin:PMonsterSkinInfo;
begin //drag a list of graph from the graph editor
Tree:=TTreeView(Source);
if (Tree.SelectionCount>0) and (LstSkin.ItemIndex>=0 ) and (LstAction.ItemIndex>=0) then //we got something selected (sanity check)
begin
Skin:=PMonsterSkinInfo(LstSkin.Items.Objects[LstSkin.ItemIndex]);
for i:=0 to Tree.SelectionCount-1 do
begin
if Tree.Selections[i].ImageIndex=1 then //reject directory
begin
new(Frame);
Frame^.SpriteName:=Tree.Selections[i].Text;
Frame^.Offx:=0;
Frame^.Offy:=0;
case LstAction.ItemIndex of
0:begin
Skin^.Walk[LstDir.ItemIndex].FrameList.Add(Frame);
GetSpriteOffset(Frame^.SpriteName,Frame^.Offx,Frame^.Offy,Skin^.Walk[LstDir.ItemIndex].Reversed);
end;
1:begin
Skin^.Attack[LstDir.ItemIndex].FrameList.Add(Frame);
GetSpriteOffset(Frame^.SpriteName,Frame^.Offx,Frame^.Offy,Skin^.Attack[LstDir.ItemIndex].Reversed);
end;
2:begin
Skin^.Death.FrameList.Add(Frame);
GetSpriteOffset(Frame^.SpriteName,Frame^.Offx,Frame^.Offy,Skin^.Death.Reversed);
end;
end;
end;
end;
RefreshView;
end;
end;
procedure TFrmSkinEdit.LstSpriteDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
var Tree:TTreeView;
begin
Accept:=false;
if Source is TTreeView then
begin
Tree:=TTreeView(Source);
if Tree.Tag=2 then
Accept:=true else
Accept:=false;
end;
end;
end.
|
unit fmCreateContainer;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ADC.Types, ADC.DC, ADC.GlobalVar,
ADC.Common, Vcl.ExtCtrls;
type
TForm_CreateContainer = class(TForm)
Button_SelectContainer: TButton;
Edit_Container: TEdit;
Label_Container: TLabel;
Edit_Name: TEdit;
Label_Name: TLabel;
Button_Cancel: TButton;
Button_OK: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button_SelectContainerClick(Sender: TObject);
procedure Button_CancelClick(Sender: TObject);
procedure Button_OKClick(Sender: TObject);
private
FOnOrganizationalUnitCreate: TCreateOrganizationalUnitProc;
FCallingForm: TForm;
FDomainController: TDCInfo;
FContainer: TADContainer;
procedure ClearTextFields;
procedure SetCallingForm(const Value: TForm);
procedure SetContainer(const Value: TADContainer);
procedure SetDomainController(const Value: TDCInfo);
procedure OnTargetContainerSelect(Sender: TObject; ACont: TADContainer);
public
property CallingForm: TForm write SetCallingForm;
property DomainController: TDCInfo read FDomainController write SetDomainController;
property Container: TADContainer read FContainer write SetContainer;
property OnOrganizationalUnitCreate: TCreateOrganizationalUnitProc read FOnOrganizationalUnitCreate write FOnOrganizationalUnitCreate;
end;
var
Form_CreateContainer: TForm_CreateContainer;
implementation
{$R *.dfm}
uses fmContainerSelection, fmMainForm;
{ TForm_CreateContainer }
procedure TForm_CreateContainer.Button_CancelClick(Sender: TObject);
begin
Close;
end;
procedure TForm_CreateContainer.Button_OKClick(Sender: TObject);
var
res: string;
MsgBoxParam: TMsgBoxParams;
begin
try
if (Edit_Container.Text = '')
or (Edit_Name.Text = '')
then raise Exception.Create(
'Заполнены не все обязательные поля.' + #13#10 +
'Поля "Создать в" и "Имя" должны быть заполнены.'
);
case apAPI of
ADC_API_LDAP: begin
res := ADCreateOU(LDAPBinding, FContainer.DistinguishedName, Edit_Name.Text);
end;
ADC_API_ADSI: begin
res := ADCreateOU(ADSIBinding, FContainer.DistinguishedName, Edit_Name.Text);
end;
end;
except
on E: Exception do
begin
res := '';
with MsgBoxParam do
begin
cbSize := SizeOf(MsgBoxParam);
hwndOwner := Self.Handle;
hInstance := 0;
case apAPI of
ADC_API_LDAP: lpszCaption := PChar('LDAP Exception');
ADC_API_ADSI: lpszCaption := PChar('ADSI Exception');
end;
lpszIcon := MAKEINTRESOURCE(32513);
dwStyle := MB_OK or MB_ICONHAND;
dwContextHelpId := 0;
lpfnMsgBoxCallback := nil;
dwLanguageId := LANG_NEUTRAL;
lpszText := PChar(E.Message);
end;
MessageBoxIndirect(MsgBoxParam);
end;
end;
if (not res.IsEmpty) and Assigned(FOnOrganizationalUnitCreate) then
begin
FOnOrganizationalUnitCreate(res);
Close;
end;
end;
procedure TForm_CreateContainer.Button_SelectContainerClick(Sender: TObject);
const
msgTemplate = 'Выберите контейнер Active Directory в котором будет %s.';
begin
Form_Container.CallingForm := Self;
Form_Container.ContainedClass := 'organizationalUnit';
Form_Container.Description := Format(msgTemplate, ['создана учетная запись пользователя']);
Form_Container.DomainController := FDomainController;
Form_Container.DefaultPath := Edit_Container.Text;
Form_Container.OnContainerSelect := OnTargetContainerSelect;
Form_Container.Position := poMainFormCenter;
Form_Container.Show;
Self.Enabled := False;
end;
procedure TForm_CreateContainer.ClearTextFields;
var
i: Integer;
Ctrl: TControl;
begin
for i := 0 to Self.ControlCount - 1 do
begin
Ctrl := Self.Controls[i];
if Ctrl is TEdit then TEdit(Ctrl).Clear else
if Ctrl is TCheckBox then TCheckBox(Ctrl).Checked := False else
if Ctrl is TMemo then TMemo(Ctrl).Clear
end;
end;
procedure TForm_CreateContainer.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ClearTextFields;
FDomainController := nil;
FContainer.Clear;
FOnOrganizationalUnitCreate := nil;
if FCallingForm <> nil then
begin
FCallingForm.Enabled := True;
FCallingForm.Show;
FCallingForm := nil;
end;
end;
procedure TForm_CreateContainer.OnTargetContainerSelect(Sender: TObject;
ACont: TADContainer);
begin
SetContainer(ACont);
if Sender <> nil
then if Sender is TForm
then TForm(Sender).Close;
end;
procedure TForm_CreateContainer.SetCallingForm(const Value: TForm);
begin
FCallingForm := Value;
end;
procedure TForm_CreateContainer.SetContainer(const Value: TADContainer);
begin
FContainer := Value;
Edit_Container.Text := FContainer.Path;
end;
procedure TForm_CreateContainer.SetDomainController(const Value: TDCInfo);
begin
FDomainController := Value;
end;
end.
|
unit K447392400;
{* [Requestlink:447392400] }
// Модуль: "w:\archi\source\projects\Archi\Tests\K447392400.pas"
// Стереотип: "TestCase"
// Элемент модели: "K447392400" MUID: (515EE345026A)
// Имя типа: "TK447392400"
{$Include w:\archi\source\projects\Archi\arDefine.inc}
interface
{$If Defined(nsTest) AND Defined(InsiderTest)}
uses
l3IntfUses
{$If NOT Defined(NoScripts)}
, ArchiInsiderTest
{$IfEnd} // NOT Defined(NoScripts)
;
type
TK447392400 = class({$If NOT Defined(NoScripts)}
TArchiInsiderTest
{$IfEnd} // NOT Defined(NoScripts)
)
{* [Requestlink:447392400] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK447392400
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest)
implementation
{$If Defined(nsTest) AND Defined(InsiderTest)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *515EE345026Aimpl_uses*
//#UC END# *515EE345026Aimpl_uses*
;
{$If NOT Defined(NoScripts)}
function TK447392400.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'BlockTest';
end;//TK447392400.GetFolder
function TK447392400.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '515EE345026A';
end;//TK447392400.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK447392400.Suite);
{$IfEnd} // NOT Defined(NoScripts)
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest)
end.
|
unit fmuCashControl;
interface
uses
// VCL
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, WinSock, ExtCtrls, Buttons,
// This
untPages, WSockets, untUtil;
type
TfmCashControl = class(TPage)
Memo: TMemo;
btnClear: TBitBtn;
lblCashControl: TLabel;
Bevel1: TBevel;
lblProtocol: TLabel;
rbTCP: TRadioButton;
rbUDP: TRadioButton;
lblPort: TLabel;
edtPort: TEdit;
btnOpenPort: TBitBtn;
btnClosePort: TBitBtn;
procedure btnOpenPortClick(Sender: TObject);
procedure btnClosePortClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure btnOpenPortMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
private
FCount: Integer;
FStrings: TStrings;
FUDPServer: TUDPServer;
FTCPServer: TTCPServer;
procedure ServerData(Sender: TObject; Socket: TSocket);
property UDPServer: TUDPServer read FUDPServer;
property TCPServer: TTCPServer read FTCPServer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
fmCashControl: TfmCashControl;
implementation
{$R *.DFM}
function StrToHex(const S: string): string;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(S) do
begin
if i <> 1 then Result := Result + ' ';
Result := Result + IntToHex(Ord(S[i]), 2);
end;
end;
{ TfmMain }
constructor TfmCashControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FUDPServer := TUDPServer.Create(Self);
FTCPServer := TTCPServer.Create(Self);
FUDPServer.OnData := ServerData;
FTCPServer.OnData := ServerData;
FStrings := TStringList.Create;
end;
destructor TfmCashControl.Destroy;
begin
FStrings.Free;
inherited Destroy;
end;
procedure TfmCashControl.ServerData(Sender: TObject; Socket: TSocket);
var
Data: string;
SockAddrIn: TSockAddrIn;
begin
if Sender is TTCPServer then
begin
Data := (Sender as TTCPServer).Read(Socket);
end else
begin
Data := (Sender as TUDPServer).Read(Socket, SockAddrIn);
end;
Memo.Lines.Text := Memo.Lines.Text + Data;
end;
procedure TfmCashControl.btnOpenPortClick(Sender: TObject);
begin
if rbTCP.Checked then
begin
TCPServer.Close;
TCPServer.Port := edtPort.Text;
TCPServer.Open;
end else
begin
UDPServer.Close;
UDPServer.Port := edtPort.Text;
UDPServer.Open;
end;
end;
procedure TfmCashControl.btnClosePortClick(Sender: TObject);
begin
UDPServer.Close;
TCPServer.Close;
end;
procedure TfmCashControl.btnClearClick(Sender: TObject);
begin
Memo.Clear;
FStrings.Clear;
FCount := 0;
end;
procedure TfmCashControl.FormMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if HighLighting then
begin
rbTCP.Color := clBtnFace;
rbUDP.Color := clBtnFace;
edtPort.Color := clWindow;
end;
end;
procedure TfmCashControl.btnOpenPortMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if HighLighting then
begin
rbTCP.Color := InColor;
rbUDP.Color := InColor;
edtPort.Color := InColor;
end;
end;
end.
|
{******************************************************************************}
{ }
{ Some necessary basic API types missing in WinApi.Windows }
{ }
{******************************************************************************}
unit SChannel.JwaBaseTypes;
interface
uses
Windows;
type
{$EXTERNALSYM PWSTR}
PWSTR = Windows.LPWSTR;
type
{$EXTERNALSYM LPBYTE}
LPBYTE = PByte;
{$EXTERNALSYM GUID}
GUID = TGUID;
{$EXTERNALSYM PVOID}
PVOID = Pointer;
{$EXTERNALSYM LPVOID}
LPVOID = Pointer;
{$EXTERNALSYM LPLPVOID}
LPLPVOID = PPointer;
{$EXTERNALSYM LPLPSTR}
LPLPSTR = PLPSTR;
{$EXTERNALSYM LPLPWSTR}
LPLPWSTR = PLPWSTR;
{$EXTERNALSYM LPLPCSTR}
LPLPCSTR = ^LPCSTR;
{$EXTERNALSYM LPLPCWSTR}
LPLPCWSTR = ^LPCWSTR;
{$EXTERNALSYM LPLPCTSTR}
LPLPCTSTR = ^LPCTSTR;
{$IFNDEF WIN64}
{$EXTERNALSYM ULONG_PTR}
ULONG_PTR = LongWord;
{$EXTERNALSYM size_t}
size_t = LongWord;
{$ELSE}
{$EXTERNALSYM ULONG_PTR}
ULONG_PTR = NativeUInt;
{$EXTERNALSYM size_t}
size_t = NativeUInt;
{$ENDIF}
{$EXTERNALSYM LPINT}
LPINT = ^Integer;
{$EXTERNALSYM LPFILETIME}
LPFILETIME = PFileTime;
{$EXTERNALSYM LONG}
LONG = Longint;
{$EXTERNALSYM HANDLE}
HANDLE = THANDLE;
implementation
end.
|
unit uSqlEditor;
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$ELSE}
LCLIntf, LCLType,
{$ENDIF}
Classes,
Types,
{$IFDEF FPC}
SynSQLEditor,
{$ENDIF}
SynHighlighterSQL,
SynEditRegexSearch,
SynEditSearch,
SynEditTypes,
SynEdit;
type
TJumpToDeclarationEvent = procedure(Sender: TObject; word : string) of object;
TSqlEditor = class({$IFDEF FPC}TCustomSQLEditor{$ELSE}TCustomSynEdit{$ENDIF})
private
FOnJumpToDeclaration: TJumpToDeclarationEvent;
procedure DoSearchReplaceText(AReplace, ABackwards: boolean);
procedure ShowSearchReplaceDialog(AReplace: boolean);
procedure KeyUpHandler(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure SetOnJumpToDeclaration(const Value: TJumpToDeclarationEvent);
protected
SearchRegEx: TSynEditRegexSearch;
Search: TSynEditSearch;
function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
procedure IncreaseFontSize;
procedure DecreaseFontSize;
property OnMouseWheel;
property OnEnter;
property OnJumpToDeclaration: TJumpToDeclarationEvent read FOnJumpToDeclaration write SetOnJumpToDeclaration;
end;
implementation
uses
dlgConfirmReplace,
dlgSearchText,
dlgReplaceText, Math, SysUtils, Controls, Dialogs;
procedure TSqlEditor.DecreaseFontSize;
begin
Font.Size := Max(Font.Size - 2, 8) ;
end;
{ TSqlEditor }
procedure TSqlEditor.AfterConstruction;
begin
inherited;
SearchRegEx := TSynEditRegexSearch.Create(self);
Search := TSynEditSearch.Create({$IFNDEF FPC}nil{$ENDIF});
AddKeyDownHandler(KeyUpHandler);
end;
procedure TSqlEditor.BeforeDestruction;
begin
FreeAndNil(Search);
inherited;
end;
function TSqlEditor.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer;
MousePos: TPoint): Boolean;
begin
Result := False;
if Assigned(OnMouseWheel) then
OnMouseWheel(Self, Shift, WheelDelta, MousePos, Result);
if not Result then
Result := inherited DoMouseWheel(Shift, WheelDelta, MousePos);
end;
var
gbSearchBackwards: boolean;
gbSearchCaseSensitive: boolean;
gbSearchFromCaret: boolean;
gbSearchSelectionOnly: boolean;
gbSearchWholeWords: boolean;
gsSearchText: string;
gsSearchTextHistory: string;
gsReplaceText: string;
gsReplaceTextHistory: string;
bSearchFromCaret: Boolean;
resourcestring
SNoSelectionAvailable = 'The is no selection available, search whole text?';
procedure TSqlEditor.DoSearchReplaceText(AReplace, ABackwards: boolean);
var
Options: TSynSearchOptions;
begin
if AReplace then
Options := [ssoPrompt, ssoReplace, ssoReplaceAll]
else
Options := [];
if ABackwards then
Include(Options, ssoBackwards);
if gbSearchCaseSensitive then
Include(Options, ssoMatchCase);
if not bSearchFromCaret then
Include(Options, ssoEntireScope);
if gbSearchSelectionOnly then
begin
if (not SelAvail) or SameText(SelText, gsSearchText) then
begin
if MessageDlg(SNoSelectionAvailable, mtWarning, [mbYes, mbNo], 0) = mrYes then
gbSearchSelectionOnly := False
else
Exit;
end
else
Include(Options, ssoSelectedOnly);
end;
if gbSearchWholeWords then
Include(Options, ssoWholeWord);
if SearchReplace(gsSearchText, gsReplaceText, Options) = 0 then
begin
{$IFDEF MSWINDOWS}
MessageBeep(MB_ICONASTERISK);
{$ENDIF}
if ssoBackwards in Options then
BlockEnd := BlockBegin
else
BlockBegin := BlockEnd;
CaretXY := BlockBegin;
end;
if ConfirmReplaceDialog <> nil then
ConfirmReplaceDialog.Free;
end;
procedure TSqlEditor.IncreaseFontSize;
begin
Font.Size := Min(Font.Size + 2, 40);
end;
procedure TSqlEditor.KeyUpHandler(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Shift = [ssCtrl] then
begin
if Key = VK_ADD then
begin
IncreaseFontSize;
Key := 0;
end else
if Key = VK_SUBTRACT then
begin
DecreaseFontSize;
Key := 0;
end else
if Key = Ord('F') then
begin
Key := 0;
ShowSearchReplaceDialog(False);
end else
if Key = Ord('H') then
begin
Key := 0;
ShowSearchReplaceDialog(True);
end;
end else
if Shift = [] then
begin
if Key = VK_F3 then
begin
DoSearchReplaceText(FALSE, FALSE);
Key := 0;
end;
if Key = VK_F12 then
begin
if Assigned(FOnJumpToDeclaration) and (WordAtCursor <> '') then
FOnJumpToDeclaration(Self, WordAtCursor);
end;
end;
end;
procedure TSqlEditor.SetOnJumpToDeclaration(const Value: TJumpToDeclarationEvent);
begin
FOnJumpToDeclaration := Value;
end;
procedure TSqlEditor.ShowSearchReplaceDialog(AReplace: boolean);
var
dlg: TTextSearchDialog;
begin
if AReplace then
dlg := TTextReplaceDialog.Create(Self)
else
dlg := TTextSearchDialog.Create(Self);
with dlg do try
// assign search options
SearchBackwards := gbSearchBackwards;
SearchCaseSensitive := gbSearchCaseSensitive;
SearchFromCursor := gbSearchFromCaret;
SearchInSelectionOnly := gbSearchSelectionOnly;
// start with last search text
SearchText := gsSearchText;
SearchTextHistory := gsSearchTextHistory;
if AReplace then with dlg as TTextReplaceDialog do begin
ReplaceText := gsReplaceText;
ReplaceTextHistory := gsReplaceTextHistory;
end;
SearchWholeWords := gbSearchWholeWords;
Top := Self.ClientToScreen(Point(0,5)).y;
Left := Self.ClientToScreen(Point(Self.Width - Width - 20, 0 )).X;
if ShowModal = mrOK then begin
gbSearchSelectionOnly := SearchInSelectionOnly;
gbSearchBackwards := SearchBackwards;
gbSearchCaseSensitive := SearchCaseSensitive;
gbSearchFromCaret := SearchFromCursor;
gbSearchWholeWords := SearchWholeWords;
gsSearchText := SearchText;
gsSearchTextHistory := SearchTextHistory;
if AReplace then with dlg as TTextReplaceDialog do begin
gsReplaceText := ReplaceText;
gsReplaceTextHistory := ReplaceTextHistory;
end;
bSearchFromCaret := gbSearchFromCaret;
if gsSearchText <> '' then begin
DoSearchReplaceText(AReplace, gbSearchBackwards);
bSearchFromCaret := TRUE;
end;
end;
finally
dlg.Free;
end;
end;
end.
|
unit uFrmComment;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ActnList, ImgList, ToolWin, ExtCtrls;
type
TfrmComment = class(TForm)
btnOk: TButton;
btnCancel: TButton;
Editor: TRichEdit;
StandardToolBar: TToolBar;
CutButton: TToolButton;
CopyButton: TToolButton;
PasteButton: TToolButton;
UndoButton: TToolButton;
ToolButton10: TToolButton;
FontName: TComboBox;
ToolButton11: TToolButton;
FontSize: TEdit;
UpDown1: TUpDown;
ToolButton2: TToolButton;
BoldButton: TToolButton;
ItalicButton: TToolButton;
UnderlineButton: TToolButton;
ToolButton16: TToolButton;
LeftAlign: TToolButton;
CenterAlign: TToolButton;
RightAlign: TToolButton;
ToolButton20: TToolButton;
BulletsButton: TToolButton;
ToolbarImages: TImageList;
ActionList2: TActionList;
EditUndoCmd: TAction;
EditCutCmd: TAction;
EditCopyCmd: TAction;
EditPasteCmd: TAction;
Panel1: TPanel;
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure ActionList2Update(Action: TBasicAction;
var Handled: Boolean);
procedure AlignButtonClick(Sender: TObject);
procedure BoldButtonClick(Sender: TObject);
procedure BulletsButtonClick(Sender: TObject);
function CurrText: TTextAttributes;
procedure EditCopy(Sender: TObject);
procedure EditCut(Sender: TObject);
procedure EditPaste(Sender: TObject);
procedure EditUndo(Sender: TObject);
procedure FontNameChange(Sender: TObject);
procedure FontSizeChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure GetFontNames;
procedure ItalicButtonClick(Sender: TObject);
procedure SelectFont(Sender: TObject);
procedure SelectionChange(Sender: TObject);
procedure SetEditRect;
procedure UnderlineButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
function GetComment(const NodeName: string; var pBuf: PChar; var nBufSize: integer): Boolean;
implementation
uses
RichEdit;
{$R *.dfm}
function GetComment(const NodeName: string; var pBuf: PChar; var nBufSize: integer): Boolean;
var
Frm: TfrmComment;
Stream: TMemoryStream;
begin
Result := False;
Frm := TfrmComment.Create(Application);
try
Frm.Caption := NodeName + '--ÆÀÂÛ';
if Frm.ShowModal = mrOk then
begin
//
Stream := TMemoryStream.Create;
try
Frm.Editor.PlainText := False;
Frm.Editor.Lines.SaveToStream(Stream);
nBufSize := Stream.Size;
GetMem(pBuf, nBufSize);
Stream.Position := 0;
Stream.Read(pBuf^, nBufSize);
finally
Stream.Free;
end;
Result := True;
end;
finally
Frm.Free;
end;
end;
procedure TfrmComment.btnOkClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TfrmComment.SelectionChange(Sender: TObject);
begin
with Editor.Paragraph do
try
BoldButton.Down := fsBold in Editor.SelAttributes.Style;
ItalicButton.Down := fsItalic in Editor.SelAttributes.Style;
UnderlineButton.Down := fsUnderline in Editor.SelAttributes.Style;
BulletsButton.Down := Boolean(Numbering);
FontSize.Text := IntToStr(Editor.SelAttributes.Size);
FontName.Text := Editor.SelAttributes.Name;
case Ord(Alignment) of
0: LeftAlign.Down := True;
1: RightAlign.Down := True;
2: CenterAlign.Down := True;
end;
finally
end;
end;
function TfrmComment.CurrText: TTextAttributes;
begin
if Editor.SelLength > 0 then Result := Editor.SelAttributes
else Result := Editor.DefAttributes;
end;
function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric;
FontType: Integer; Data: Pointer): Integer; stdcall;
begin
TStrings(Data).Add(LogFont.lfFaceName);
Result := 1;
end;
procedure TfrmComment.GetFontNames;
var
DC: HDC;
begin
DC := GetDC(0);
EnumFonts(DC, nil, @EnumFontsProc, Pointer(FontName.Items));
ReleaseDC(0, DC);
FontName.Sorted := True;
end;
procedure TfrmComment.SetEditRect;
begin
end;
{ Event Handlers }
procedure TfrmComment.FormCreate(Sender: TObject);
begin
GetFontNames;
CurrText.Name := DefFontData.Name;
CurrText.Size := -MulDiv(DefFontData.Height, 72, Screen.PixelsPerInch);
SelectionChange(Self);
end;
procedure TfrmComment.EditUndo(Sender: TObject);
begin
with Editor do
if HandleAllocated then SendMessage(Handle, EM_UNDO, 0, 0);
end;
procedure TfrmComment.EditCut(Sender: TObject);
begin
Editor.CutToClipboard;
end;
procedure TfrmComment.EditCopy(Sender: TObject);
begin
Editor.CopyToClipboard;
end;
procedure TfrmComment.EditPaste(Sender: TObject);
begin
Editor.PasteFromClipboard;
end;
procedure TfrmComment.SelectFont(Sender: TObject);
begin
SelectionChange(Self);
Editor.SetFocus;
end;
procedure TfrmComment.FormResize(Sender: TObject);
begin
SetEditRect;
SelectionChange(Sender);
end;
procedure TfrmComment.BoldButtonClick(Sender: TObject);
begin
if BoldButton.Down then
CurrText.Style := CurrText.Style + [fsBold]
else
CurrText.Style := CurrText.Style - [fsBold];
end;
procedure TfrmComment.ItalicButtonClick(Sender: TObject);
begin
if ItalicButton.Down then
CurrText.Style := CurrText.Style + [fsItalic]
else
CurrText.Style := CurrText.Style - [fsItalic];
end;
procedure TfrmComment.FontSizeChange(Sender: TObject);
begin
CurrText.Size := StrToInt(FontSize.Text);
end;
procedure TfrmComment.AlignButtonClick(Sender: TObject);
begin
Editor.Paragraph.Alignment := TAlignment(TControl(Sender).Tag);
end;
procedure TfrmComment.FontNameChange(Sender: TObject);
begin
CurrText.Name := FontName.Items[FontName.ItemIndex];
end;
procedure TfrmComment.UnderlineButtonClick(Sender: TObject);
begin
if UnderlineButton.Down then
CurrText.Style := CurrText.Style + [fsUnderline]
else
CurrText.Style := CurrText.Style - [fsUnderline];
end;
procedure TfrmComment.BulletsButtonClick(Sender: TObject);
begin
Editor.Paragraph.Numbering := TNumberingStyle(BulletsButton.Down);
end;
procedure TfrmComment.FormShow(Sender: TObject);
begin
Editor.SetFocus;
end;
procedure TfrmComment.ActionList2Update(Action: TBasicAction;
var Handled: Boolean);
begin
{ Update the status of the edit commands }
EditCutCmd.Enabled := Editor.SelLength > 0;
EditCopyCmd.Enabled := EditCutCmd.Enabled;
if Editor.HandleAllocated then
begin
EditUndoCmd.Enabled := Editor.Perform(EM_CANUNDO, 0, 0) <> 0;
EditPasteCmd.Enabled := Editor.Perform(EM_CANPASTE, 0, 0) <> 0;
end;
end;
procedure TfrmComment.btnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfrmComment.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
end.
|
{ Copyright (C) 2014 Dimitar Paperov,Zdzislaw Dybikowski
This source is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This code is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
A copy of the GNU General Public License is available on the World Wide Web
at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing
to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
}
unit mdTypes;
interface
type
{ Common structures }
PMD_DEVICE_ID = ^TMD_DEVICE_ID;
TMD_DEVICE_ID = record
group: word;
number: word;
end;
PMD_APP_ID = ^TMD_APP_ID;
TMD_APP_ID = record
hiPart: cardinal;
loPart: cardinal;
end;
PMD_ROTOR_CONFIG = ^TMD_ROTOR_CONFIG;
TMD_ROTOR_CONFIG = record
min_angle: single;
max_angle: single;
gear: single;
stop_at: single;
state: byte; // readonly
m_type: byte;
kind: byte; // readonly
input: byte;
start_time: array [0..2] of byte;
start_power: array [0..2] of byte;
stop_time: array [0..2] of byte;
stop_power: array [0..2] of byte;
max_power: byte;
puls_timeout: byte;
end;
PMD_CONFIG = ^TMD_CONFIG;
TMD_CONFIG = record
bTemplate: byte;
bUseShortWay: byte;
bUseElMap: byte;
bConstElMap: byte;
bMouseControl: byte;
bMotorStart: byte;
bMotorStop: byte;
bShowAzimuth: byte;
bControlM1: byte;
bProtocolM1: byte;
bControlM2: byte;
bProtocolM2: byte;
bPairRotors: byte;
end;
{ function md_logon }
{ function md_logout }
PMD_LOGON_PARAMS = ^TMD_LOGON_PARAMS;
TMD_LOGON_PARAMS = record
dev: TMD_DEVICE_ID;
app: TMD_APP_ID;
end;
{ function md_stop_all_rotors }
PMD_STOP_ALL_ROTORS_PARAMS = ^TMD_STOP_ALL_ROTORS_PARAMS;
TMD_STOP_ALL_ROTORS_PARAMS = record
dev: TMD_DEVICE_ID;
app: TMD_APP_ID;
end;
{ function md_stop_rotor }
PMD_STOP_ROTOR_PARAMS = ^TMD_STOP_ROTOR_PARAMS;
TMD_STOP_ROTOR_PARAMS = record
dev: TMD_DEVICE_ID;
app: TMD_APP_ID;
rotor: integer;
end;
{ function md_get_config }
{ function md_set_config }
PMD_CONFIG_PARAMS = ^TMD_CONFIG_PARAMS;
TMD_CONFIG_PARAMS = record
dev: TMD_DEVICE_ID;
config: PMD_CONFIG;
end;
{ function md_get_rotor_config }
{ function md_set_rotor_config }
PMD_ROTOR_CONFIG_PARAMS = ^TMD_ROTOR_CONFIG_PARAMS;
TMD_ROTOR_CONFIG_PARAMS = record
dev: TMD_DEVICE_ID;
rotorIx: integer;
config: PMD_ROTOR_CONFIG;
end;
{ function md_get_rotor_angle }
{ function md_set_rotor_angle }
PMD_ROTOR_ANGLE_PARAMS = ^TMD_ROTOR_ANGLE_PARAMS;
TMD_ROTOR_ANGLE_PARAMS = record
dev: TMD_DEVICE_ID;
rotorIx: integer;
angle: single;
calibration: byte;
end;
{ function md_get_all_rotor_angles }
{ function md_set_all_rotor_angles }
PMD_ALL_ROTOR_ANGLES_PARAMS = ^TMD_ALL_ROTOR_ANGLES_PARAMS;
TMD_ALL_ROTOR_ANGLES_PARAMS = record
dev: TMD_DEVICE_ID;
startMotorIx: integer;
angles: array[0..1] of single;
calibration: integer;
end;
{ function md_get_el_map }
{ function md_set_el_map }
PMD_EL_MAP_PARAMS = ^TMD_EL_MAP_PARAMS;
TMD_EL_MAP_PARAMS = record
dev: TMD_DEVICE_ID;
pElMap: pointer; // pointer to array [0..359] of shortint;
fromAngle: word; // 0..359
toAngle: word; // fromAngle..359
end;
const
{ ERRORS }
MD_NO_ERROR = 0;
MD_BAD_PARAMETERS = 1;
MD_COM_PORT_NOT_OPENED = 2;
MD_DATA_SEND_ERROR = 3;
MD_DATA_RECV_ERROR = 4;
MD_HOST_NOT_EXISTS = 5;
MD_NOT_READY = 6;
MD_BAD_RESPONSE_FROM_DEVICE = 7;
MD_DEVICE_BUSY = 8;
MD_COMMAND_NOT_SUPPRTED = 9;
MD_UNEXPECTED_ERROR = -1;
implementation
end.
|
unit uNanoPowAS;
// unit of Nano currency Proof of Work Android Service
// Copyleft 2019 - Daniel Mazur
interface
uses
DW.Androidapi.JNI.Support, Androidapi.JNIBridge,
Androidapi.JNI.JavaTypes,
System.Android.Service, Androidapi.JNI.Util, Androidapi.JNI.App,
Androidapi.JNI.Widget, Androidapi.JNI.Media,
Androidapi.JNI.Support,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.Os, System.Android.Notification, System.SysUtils,
System.IOUtils, StrUtils,
System.Classes, System.JSON,
System.Generics.Collections, Androidapi.Helpers,
System.Variants, System.net.httpclient,
Math, DW.Android.Helpers, Androidapi.JNI, Androidapi.log;
const
RAI_TO_RAW = '000000000000000000000000';
MAIN_NET_WORK_THRESHOLD = 'ffffffc000000000';
STATE_BLOCK_PREAMBLE =
'0000000000000000000000000000000000000000000000000000000000000006';
STATE_BLOCK_ZERO =
'0000000000000000000000000000000000000000000000000000000000000000';
const
nano_charset = '13456789abcdefghijkmnopqrstuwxyz';
type
TIntegerArray = array of System.uint32;
type
dwSIZE_T = System.uint32;
crypto_generichash_blake2b_state = packed record
h: Array [0 .. 7] of UINT64;
t: Array [0 .. 1] of UINT64;
f: Array [0 .. 1] of UINT64;
buf: Array [0 .. 255] of UINT8;
buflen: dwSIZE_T;
last_node: UINT8;
padding64: array [0 .. 26] of byte;
end;
TDM = class(TAndroidService)
function AndroidServiceStartCommand(const Sender: TObject;
const Intent: JIntent; Flags, StartId: Integer): Integer;
private
{ Private declarations }
public
{ Public declarations }
end;
var
DM: TDM;
var
blake2b_init: function(var state: crypto_generichash_blake2b_state;
const key: Pointer; const keylen: dwSIZE_T; const outlen: dwSIZE_T)
: Integer;
blake2b_update: function(var state: crypto_generichash_blake2b_state;
const inBuf: Pointer; inlen: UINT64): Integer;
blake2b_final: function(var state: crypto_generichash_blake2b_state;
const outBuf: Pointer; const outlen: dwSIZE_T): Integer;
type
TBytes = Array of System.UINT8;
type
TNanoBlock = record
blockType: string;
state: Boolean;
send: Boolean;
Hash: string;
signed: Boolean;
worked: Boolean;
signature: string;
work: string;
blockAmount: string;
blockAccount: string;
blockMessage: string;
origin: string;
immutable: Boolean;
timestamp: System.uint32;
previous: string;
destination: string;
balance: string;
source: string;
representative: string;
account: string;
end;
type
TpendingNanoBlock = record
Block: TNanoBlock;
Hash: string;
end;
type
TNanoBlockChain = array of TNanoBlock;
type
NanoCoin = class(TObject)
pendingChain: TNanoBlockChain;
lastBlock: string;
lastPendingBlock: string;
PendingBlocks: TQueue<TpendingNanoBlock>;
PendingThread: TThread;
lastBlockAmount: string;
UnlockPriv: string;
isUnlocked: Boolean;
sessionKey: string;
chaindir: string;
private
public
procedure removeBlock(Hash: string);
function getPreviousHash: string;
procedure addToChain(Block: TNanoBlock);
function inChain(Hash: string): Boolean;
function isFork(prev: string): Boolean;
function findUnusedPrevious: string;
function BlockByPrev(prev: string): TNanoBlock;
function BlockByHash(Hash: string): TNanoBlock;
function BlockByLink(Hash: string): TNanoBlock;
function nextBlock(Block: TNanoBlock): TNanoBlock;
function prevBlock(Block: TNanoBlock): TNanoBlock;
// procedure loadChain;
function firstBlock: TNanoBlock;
function curBlock: TNanoBlock;
// procedure mineAllPendings(MasterSeed: string = '');
// procedure unlock(MasterSeed: string);
// function getPrivFromSession(): string;
// procedure mineBlock(Block: TpendingNanoBlock;
// MasterSeed: string); overload;
// procedure mineBlock(Block: TpendingNanoBlock); overload;
// procedure tryAddPendingBlock(Block: TpendingNanoBlock);
constructor Create(); overload;
destructor destroy();
end;
type
precalculatedPow = record
Hash: string;
work: string;
end;
type
precalculatedPows = array of precalculatedPow;
procedure nanoPowAndroidStart();
var
pows: precalculatedPows;
notepad: string;
var
LBuilder: DW.Androidapi.JNI.Support.JNotificationCompat_Builder;
var
miningOwner: string;
miningStep: Integer;
LibHandle: THandle;
displayNotifications:boolean;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
uses
System.DateUtils;
{$R *.dfm}
procedure logd(msg: String);
var
M: TMarshaller;
var
ts: tstringlist;
begin
notepad := notepad + #13#10 + DateTimeToStr(Now) + ' ' + msg;
ts := tstringlist.Create();
try
ts.Text := notepad;
ts.SaveToFile(TPath.GetDocumentsPath + '/miner.log');
except
on E: Exception do
begin
end;
end;
ts.Free;
// LOGI(M.AsUtf8(msg).ToPointer);
end;
function findPrecalculated(Hash: string): string;
var
pow: precalculatedPow;
begin
Result := '';
Hash := LowerCase(Hash);
for pow in pows do
if pow.Hash = Hash then
Exit(pow.work);
end;
procedure setPrecalculated(Hash, work: string);
var
i: Integer;
begin
if Length(Hash) <> 64 then
Exit;
Hash := LowerCase(Hash);
for i := 0 to Length(pows) - 1 do
if pows[i].Hash = Hash then
begin
pows[i].work := work;
Exit;
end;
SetLength(pows, Length(pows) + 1);
pows[high(pows)].Hash := Hash;
pows[High(pows)].work := work;
end;
procedure removePow(Hash: string);
var
i: Integer;
begin
for i := 0 to Length(pows) - 1 do
begin
if pows[i].Hash = Hash then
begin
pows[i] := pows[High(pows)];
SetLength(pows, Length(pows) - 1);
Exit;
end;
end;
end;
procedure savePows;
var
ts: tstringlist;
i: Integer;
begin
ts := tstringlist.Create;
try
for i := 0 to Length(pows) - 1 do
begin
if Length(pows[i].Hash) <> 64 then
continue;
ts.Add(pows[i].Hash + ' ' + pows[i].work);
end;
ts.SaveToFile(TPath.GetDocumentsPath + '/nanopows.dat');
finally
ts.Free;
end;
end;
function SplitString(Str: string; separator: char = ' '): tstringlist;
var
ts: tstringlist;
i: Integer;
begin
Str := StringReplace(Str, separator, #13#10, [rfReplaceAll]);
ts := tstringlist.Create;
ts.Text := Str;
Result := ts;
end;
procedure loadPows;
var
ts: tstringlist;
i: Integer;
t: tstringlist;
begin
SetLength(pows, 0);
ts := tstringlist.Create;
try
if FileExists((TPath.GetDocumentsPath + '/nanopows.dat')) then
begin
ts.LoadFromFile(TPath.GetDocumentsPath + '/nanopows.dat');
SetLength(pows, ts.Count);
for i := 0 to ts.Count - 1 do
begin
t := SplitString(ts.Strings[i], ' ');
if t.Count = 1 then
begin
pows[i].Hash := t[0];
pows[i].work := '';
continue;
end;
if t.Count <> 2 then
continue;
pows[i].Hash := t[0];
pows[i].work := t[1];
if pows[i].work = 'MINING' then
pows[i].work := '';
t.Free;
end;
end;
finally
ts.Free;
end;
end;
function hexatotbytes(h: string): TBytes;
var
i: Integer;
b: System.UINT8;
bb: TBytes;
begin
// if not IsHex(h) then
// raise Exception.Create(H + ' is not hex');
SetLength(bb, (Length(h) div 2));
{$IF (DEFINED(ANDROID) OR DEFINED(IOS))}
for i := 0 to (Length(h) div 2) - 1 do
begin
b := System.UINT8(StrToInt('$' + Copy(h, ((i) * 2) + 1, 2)));
bb[i] := b;
end;
{$ELSE}
for i := 1 to (Length(h) div 2) do
begin
b := System.UINT8(StrToInt('$' + Copy(h, ((i - 1) * 2) + 1, 2)));
bb[i - 1] := b;
end;
{$ENDIF}
Result := bb;
end;
procedure saveMiningState(speed: int64);
var
ts: tstringlist;
begin
logd('saveMiningState ' + inttostr(speed) + ' kHash');
ts := tstringlist.Create;
try
ts.Add(miningOwner);
ts.Add(inttostr(miningStep));
ts.Add(inttostr(speed));
ts.SaveToFile(System.IOUtils.TPath.GetDocumentsPath + '/andMining');
except
on E: Exception do
begin
logd('Exception in saveMiningState: ' + E.Message);
end;
end;
ts.Free;
end;
function findwork(Hash: string): string;
var
state: crypto_generichash_blake2b_state;
workbytes: TBytes;
res: array of System.UINT8;
j, i: Integer;
work: string;
hashCounter: int64;
startTime, gone, hashSpeed: int64;
begin
logd('findwork ' + Hash);
loadPows;
work := findPrecalculated(Hash);
if (work <> '') and (work <> 'MINING') then
Exit(work);
randomize;
SetLength(res, 8);
workbytes := hexatotbytes('0000000000000000' + Hash);
hashCounter := 1;
startTime := Round((Now() - 25569) * 86400);
repeat
workbytes[0] := random(255);
workbytes[1] := random(255);
workbytes[2] := random(255);
workbytes[3] := random(255);
workbytes[4] := random(255);
workbytes[5] := random(255);
workbytes[6] := random(255);
for i := 0 to 255 do
begin
workbytes[7] := i;
blake2b_init(state, nil, 0, 8);
blake2b_update(state, workbytes, Length(workbytes));
blake2b_final(state, res, 8);
if res[7] = 255 then
if res[6] = 255 then
if res[5] = 255 then
if res[4] >= 192 then
begin
Result := '';
for j := 7 downto 0 do
Result := Result + inttohex(workbytes[j], 2);
logd('work found ' + Result);
setPrecalculated(Hash, Result);
savePows;
Exit;
end;
end;
if hashCounter mod 32641 = 0 then
begin
gone := (Round((Now() - 25569) * 86400)) - startTime;
if gone > 0 then
begin
// gone := 1;
hashSpeed := ceil(hashCounter / (gone));
saveMiningState(hashSpeed);
hashCounter := 1;
startTime := Round((Now() - 25569) * 86400);
end;
end;
inc(hashCounter, 256);
until true = false;
end;
function nano_builtFromJSON(JSON: TJSONValue): TNanoBlock;
begin
Result.blockType := JSON.GetValue<string>('type');
Result.previous := JSON.GetValue<string>('previous');
Result.account := JSON.GetValue<string>('account');
Result.representative := JSON.GetValue<string>('representative');
Result.balance := JSON.GetValue<string>('balance');
Result.destination := JSON.GetValue<string>('link');
Result.work := JSON.GetValue<string>('work');
Result.signature := JSON.GetValue<string>('signature');
end;
function nano_builtToJSON(Block: TNanoBlock): string;
var
obj: TJSONObject;
begin
obj := TJSONObject.Create();
obj.AddPair(TJSONPair.Create('type', 'state'));
obj.AddPair(TJSONPair.Create('previous', Block.previous));
obj.AddPair(TJSONPair.Create('balance', Block.balance));
obj.AddPair(TJSONPair.Create('account', Block.account));
obj.AddPair(TJSONPair.Create('representative', Block.representative));
obj.AddPair(TJSONPair.Create('link', Block.destination));
obj.AddPair(TJSONPair.Create('work', Block.work));
obj.AddPair(TJSONPair.Create('signature', Block.signature));
Result := obj.tojson;
obj.Free;
end;
function nano_loadChain(dir: string; limitTo: string = ''): TNanoBlockChain;
var
path: string;
ts: tstringlist;
Block: TNanoBlock;
begin
SetLength(Result, 0);
ts := tstringlist.Create;
try
for path in TDirectory.GetFiles(dir) do
begin
ts.LoadFromFile(path);
Block := nano_builtFromJSON(TJSONObject.ParseJSONValue(ts.Text)
as TJSONValue);
if limitTo <> '' then
if Block.account <> limitTo then
continue;
Block.Hash := StringReplace(ExtractFileName(path), '.block.json', '',
[rfReplaceAll]);
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := Block;
end;
finally
ts.Free;
end;
end;
constructor NanoCoin.Create();
begin
PendingBlocks := TQueue<TpendingNanoBlock>.Create();
isUnlocked := false;
end;
destructor NanoCoin.destroy;
begin
inherited;
PendingBlocks.Free;
end;
function NanoCoin.inChain(Hash: string): Boolean;
var
i: Integer;
begin
Result := false;
for i := 0 to Length(pendingChain) - 1 do
if Self.pendingChain[i].Hash = Hash then
Exit(true);
end;
function NanoCoin.isFork(prev: string): Boolean;
var
i: Integer;
begin
Result := false;
for i := 0 to Length(pendingChain) - 1 do
if pendingChain[i].previous = prev then
Exit(true);
end;
procedure NanoCoin.addToChain(Block: TNanoBlock);
begin
if (not inChain(Block.Hash)) and (not isFork(Block.previous)) then
begin
SetLength(pendingChain, Length(pendingChain) + 1);
pendingChain[high(pendingChain)] := Block;
end;
end;
procedure NanoCoin.removeBlock(Hash: string);
var
i: Integer;
begin
for i := 0 to Length(pendingChain) - 1 do
if pendingChain[i].Hash = Hash then
begin
pendingChain[i] := pendingChain[High(pendingChain)];
SetLength(pendingChain, Length(pendingChain) - 1);
DeleteFile(TPath.Combine(chaindir, Hash + '.block.json'));
end;
end;
function NanoCoin.findUnusedPrevious: string;
var
i: Integer;
begin
Result := '0000000000000000000000000000000000000000000000000000000000000000';
for i := 0 to Length(pendingChain) - 1 do
if not isFork(pendingChain[i].Hash) then
Exit(pendingChain[i].Hash);
end;
function NanoCoin.BlockByPrev(prev: string): TNanoBlock;
var
i: Integer;
begin
Result.account := '';
for i := 0 to Length(pendingChain) - 1 do
if pendingChain[i].previous = prev then
Exit(pendingChain[i]);
end;
function NanoCoin.BlockByHash(Hash: string): TNanoBlock;
var
i: Integer;
begin
Result.account := '';
for i := 0 to Length(pendingChain) - 1 do
if pendingChain[i].Hash = Hash then
Exit(pendingChain[i]);
end;
function NanoCoin.BlockByLink(Hash: string): TNanoBlock;
var
i: Integer;
begin
Result.account := '';
for i := 0 to Length(pendingChain) - 1 do
if pendingChain[i].destination = Hash then
Exit(pendingChain[i]);
end;
function NanoCoin.nextBlock(Block: TNanoBlock): TNanoBlock;
begin
Result := BlockByPrev(Block.Hash);
end;
function NanoCoin.prevBlock(Block: TNanoBlock): TNanoBlock;
begin
Result := BlockByHash(Block.previous);
end;
function NanoCoin.firstBlock: TNanoBlock;
var
prev, cur: TNanoBlock;
begin
if Length(Self.pendingChain) = 0 then
Exit;
cur := Self.pendingChain[0];
repeat
prev := prevBlock(cur);
if prev.account <> '' then
cur := prev;
until prev.account = '';
Result := cur;
end;
function NanoCoin.curBlock: TNanoBlock;
var
next, cur: TNanoBlock;
begin
if Length(Self.pendingChain) = 0 then
Exit;
cur := Self.pendingChain[0];
repeat
next := nextBlock(cur);
if next.account <> '' then
cur := next;
until next.account = '';
Result := cur;
end;
function NanoCoin.getPreviousHash(): string;
var
i, l: Integer;
begin
Result := Self.lastPendingBlock;
if Length(Self.pendingChain) > 0 then
Exit(curBlock.Hash);
if Self.lastBlock <> '' then
begin
Result := Self.lastBlock;
Self.lastBlock := '';
Exit;
end;
l := Length(Self.PendingBlocks.ToArray);
if l > 0 then
begin
for i := 0 to l - 1 do
begin
Result := Self.PendingBlocks.ToArray[i].Hash;
end;
end;
end;
function ChangeBits(var data: array of System.uint32;
frombits, tobits: System.uint32; pad: Boolean = true): TIntegerArray;
var
acc: Integer;
bits: Integer;
ret: array of Integer;
maxv: Integer;
maxacc: Integer;
i: Integer;
value: Integer;
j: Integer;
begin
acc := 0;
bits := 0;
ret := [];
maxv := 0;
maxacc := 0;
maxv := (1 shl tobits) - 1;
maxacc := (1 shl (frombits + tobits - 1)) - 1;
for i := 0 to Length(data) - 1 do
begin
value := data[i];
if (value < 0) or ((value shr frombits) <> 0) then
begin
// error
end;
acc := ((acc shl frombits) or value) and maxacc;
bits := bits + frombits;
j := 0;
while bits >= tobits do
begin
bits := bits - tobits;
SetLength(ret, Length(ret) + 1);
ret[Length(ret) - 1] := ((acc shr bits) and maxv);
inc(j);
end;
end;
if pad then
begin
j := 0;
if bits <> 0 then
begin
SetLength(ret, Length(ret) + 1);
ret[Length(ret) - 1] := (acc shl (tobits - bits)) and maxv;
inc(j);
end;
end;
Result := TIntegerArray(ret);
end;
function nano_keyFromAccount(adr: string): string;
var
chk: string;
rAdr, rChk: TIntegerArray;
i: Integer;
begin
Result := adr;
adr := StringReplace(adr, 'xrb_', '', [rfReplaceAll]);
adr := StringReplace(adr, 'nano_', '', [rfReplaceAll]);
chk := Copy(adr, 52 + 1, 100);
adr := '1111' + Copy(adr, 1, 52);
SetLength(rAdr, Length(adr));
SetLength(rChk, Length(chk));
for i := 0 to Length(adr) - 1 do
rAdr[i] := Pos(adr[i{$IFDEF MSWINDOWS} + 1{$ENDIF}], nano_charset) - 1;
for i := 0 to Length(chk) - 1 do
rChk[i] := Pos(chk[i{$IFDEF MSWINDOWS} + 1{$ENDIF}], nano_charset) - 1;
Result := '';
rAdr := ChangeBits(rAdr, 5, 8, true);
for i := 3 to Length(rAdr) - 1 do
Result := Result + inttohex(rAdr[i], 2)
end;
function nano_getPrevious(Block: TNanoBlock): string;
begin
if Block.previous = STATE_BLOCK_ZERO then
begin
if Pos('_', Block.account) > 0 then
Exit(nano_keyFromAccount(Block.account))
else
Exit(Block.account);
end;
Result := Block.previous;
end;
function nano_getWork(var Block: TNanoBlock): string;
begin
Block.work := findwork(nano_getPrevious(Block));
Block.worked := true;
end;
function getDataOverHTTP(aURL: String; useCache: Boolean = true;
noTimeout: Boolean = false): string;
var
req: THTTPClient;
LResponse: IHTTPResponse;
urlHash: string;
begin
req := THTTPClient.Create();
try
LResponse := req.get(aURL);
Result := LResponse.ContentAsString();
except
on E: Exception do
begin
Result := E.Message;
end;
end;
req.Free;
end;
function nano_pushBlock(b: string): string;
begin
logd('nano_pushBlock presend');
Result := getDataOverHTTP('https://hodlernode.net/nano.php?b=' + b,
false, true);
logd('nano_pushBlock postsend: ' + Result);
end;
function IsHex(s: string): Boolean;
var
i: Integer;
begin
// Odd string or empty string is not valid hexstring
if (Length(s) = 0) or (Length(s) mod 2 <> 0) then
Exit(false);
s := UpperCase(s);
Result := true;
for i := 0 to Length(s) - 1 do
if not(char(s[i]) in ['0' .. '9']) and not(char(s[i]) in ['A' .. 'F']) then
begin
Result := false;
Exit;
end;
end;
function reverseHexOrder(s: string): string;
var
v: string;
begin
s := StringReplace(s, '$', '', [rfReplaceAll]);
Result := '';
repeat
if Length(s) >= 2 then
begin
v := Copy(s, 0, 2);
delete(s, 1, 2);
Result := v + Result;
end
else
break;
until 1 = 0;
end;
function hexatotintegerarray(h: string): TIntegerArray;
var
i: Integer;
b: System.UINT8;
bb: TIntegerArray;
begin
SetLength(bb, (Length(h) div 2));
{$IF DEFINED(ANDROID) OR DEFINED(IOS)}
for i := 0 to (Length(h) div 2) - 1 do
begin
b := System.UINT8(strtoIntDef('$' + Copy(h, ((i) * 2) + 1, 2), 0));
bb[i] := b;
end;
{$ELSE}
for i := 1 to (Length(h) div 2) do
begin
b := System.UINT8(strtoIntDef('$' + Copy(h, ((i - 1) * 2) + 1, 2), 0));
bb[i - 1] := b;
end;
{$ENDIF}
Result := bb;
end;
function nano_addressChecksum(M: String): String;
var
state: crypto_generichash_blake2b_state;
res: array of System.UINT8;
i: Integer;
begin
Result := '';
blake2b_init(state, nil, 0, 5);
blake2b_update(state, hexatotbytes(M), Length(M));
blake2b_final(state, res, 5);
for i := Length(res) to 0 do
Result := inttohex(res[i], 2) + Result;
end;
function nano_encodeBase32(values: TIntegerArray): string;
var
i: Integer;
begin
Result := '';
for i := 0 to Length(values) - 1 do
begin
Result := Result + nano_charset[values[i] + low(nano_charset)];
end;
end;
function nano_accountFromHexKey(adr: String): String;
var
data, chk: TIntegerArray;
begin
Result := 'FAILED';
chk := hexatotintegerarray(nano_addressChecksum(adr));
adr := '303030' + adr;
data := hexatotintegerarray(adr);
// Copy(adr,4{$IFDEF MSWINDOWS}+1{$ENDIF},100)
data := ChangeBits(data, 8, 5, true);
chk := ChangeBits(chk, 8, 5, true);
delete(data, 0, 4);
Result := 'nano_' + nano_encodeBase32(data) + nano_encodeBase32(chk);
end;
function nano_mineBuilt64(cc: NanoCoin): Boolean;
var
Block: TNanoBlock;
lastHash, s: string;
isCorrupted: Boolean;
begin
Result := false;
isCorrupted := false;
repeat
Block := cc.firstBlock;
if Block.account <> '' then
begin
if Pos('nano_', Block.account) = 0 then
miningOwner := nano_accountFromHexKey(Block.account)
else
miningOwner := Block.account;
if not isCorrupted then
begin
logd('Title change nano_mineBuilt64 (909) ' + miningOwner);
DM.JavaService.stopForeground(true);
LBuilder.setContentTitle(StrToJCharSequence((miningOwner)));
LBuilder.setContentText(StrToJCharSequence('Working on nano blocks, ' +
inttostr(Length(cc.pendingChain)) + ' left'));
DM.JavaService.StartForeground(1995, LBuilder.build);
logd('Post 909');
miningStep := 1;
nano_getWork(Block);
Result := true;
s := nano_pushBlock(nano_builtToJSON(Block));
lastHash := StringReplace(s, 'https://www.nanode.co/block/', '',
[rfReplaceAll]);
if IsHex(lastHash) = false then
begin
if LeftStr(lastHash, Length('Transaction failed')) = 'Transaction failed'
then
begin
isCorrupted := true;
end;
lastHash := '';
end;
if cc.BlockByPrev(lastHash).account = '' then
if lastHash <> '' then
begin
DM.JavaService.stopForeground(true);
LBuilder.setContentText
(StrToJCharSequence('Working on next block hash'));
DM.JavaService.StartForeground(1995, LBuilder.build);
miningStep := 2;
findwork(lastHash);
Result := true;
end;
end;
end;
cc.removeBlock(Block.Hash);
until Length(cc.pendingChain) = 0;
end;
procedure mineAll;
var
cc: NanoCoin;
path: string;
i: Integer;
workdone: Boolean;
begin
workdone := false;
repeat
for path in TDirectory.GetDirectories
(IncludeTrailingPathDelimiter(System.IOUtils.TPath.GetDocumentsPath)) do
begin
if DirectoryExists(TPath.Combine(path, 'Pendings')) then
begin
cc := NanoCoin.Create();
cc.chaindir := TPath.Combine(path, 'Pendings');
cc.pendingChain := nano_loadChain(TPath.Combine(path, 'Pendings'));
workdone := nano_mineBuilt64(cc);
cc.Free;
end;
Sleep(100);
end;
loadPows;
for i := 0 to Length(pows) - 1 do
if pows[i].work = '' then
begin
logd('Title change mineAll (977)');
DM.JavaService.stopForeground(true);
LBuilder.setContentTitle
(StrToJCharSequence('HODLER - Nano PoW Worker'));
LBuilder.setContentText
(StrToJCharSequence('Working on next block hash'));
DM.JavaService.StartForeground(1995, LBuilder.build);
logd('Post 977');
miningOwner := pows[i].Hash;
miningStep := 3;
findwork(pows[i].Hash);
workdone := true;
end;
if workdone then
begin
miningStep := 4;
saveMiningState(0);
workdone := false;
logd('Title change (995)');
DM.JavaService.stopForeground(true);
LBuilder.setContentText(StrToJCharSequence('Ready to work nano blocks'));
DM.JavaService.StartForeground(1995, LBuilder.build);
logd('Post 995');
end;
// cpu cooldown
Sleep(500);
until true = false;
end;
procedure nanoPowAndroidStart();
var
ts: tstringlist;
var
err, ex: string;
p: pchar;
begin
displayNotifications:=false;
ts := tstringlist.Create();
try
if FileExists(TPath.GetDocumentsPath + '/miner.log') then
begin
ts.LoadFromFile(TPath.GetDocumentsPath + '/miner.log');
if ts.Count < 1000 then
notepad := ts.Text + #13#10;
end;
except
on E: Exception do
begin
end;
end;
ts.Free;
logd('AndroidServiceStartCommand 827');
err := 'la';
try
try
// /system/lib/libsodium.so for HPRO
// TPath.GetDocumentsPath + '/nacl2/libsodium.so'; for normal app
// err := '/system/lib/libsodium.so';
err:= TPath.GetDocumentsPath + '/nacl2/libsodium.so';
if FileExists(err) then
ex := 'isthere'
else
ex := 'uuuuu';
logd(' ' + ex + ' ' + err);
LibHandle := LoadLibrary(PwideChar(err));
if LibHandle <> 0 then
begin
blake2b_init := getprocaddress(LibHandle,
PwideChar('crypto_generichash_blake2b_init'));
logd(' ' + inttohex(Integer(getprocaddress(LibHandle,
PwideChar('crypto_generichash_blake2b_init'))), 8));
blake2b_update := getprocaddress(LibHandle,
'crypto_generichash_blake2b_update');
blake2b_final := getprocaddress(LibHandle,
'crypto_generichash_blake2b_final');
end;
except
on E: Exception do
begin
// no libsodium, so kill yourself
Exit;
end;
end;
finally
end;
logd(' AndroidServiceStartCommand 857');
TThread.CreateAnonymousThread(
procedure
begin
mineAll;
end).Start();
end;
function TDM.AndroidServiceStartCommand(const Sender: TObject;
const Intent: JIntent; Flags, StartId: Integer): Integer;
var
err, ex: string;
channel: JNotificationChannel;
manager: JNotificationManager;
group: JNotificationChannelGroup;
VIntent: JIntent;
resultPendingIntent: JPendingIntent;
var
PEnv: PJNIEnv;
ActivityClass: JNIClass;
NativeMethod: JNINativeMethod;
var
api26: Boolean;
begin
nanoPowAndroidStart();
logd(' AndroidServiceStartCommand 863');
api26 := TAndroidHelperEx.CheckBuildAndTarget(26);
if api26 then
begin
group := TJNotificationChannelGroup.JavaClass.init
(StringToJString('hodler'), StrToJCharSequence('hodler'));
manager := TJNotificationManager.Wrap
((TAndroidHelper.context.getSystemService
(TJContext.JavaClass.NOTIFICATION_SERVICE) as ILocalObject).GetObjectID);
manager.createNotificationChannelGroup(group);
channel := TJNotificationChannel.JavaClass.init(StringToJString('hodler'),
StrToJCharSequence('hodler'), 0);
channel.setGroup(StringToJString('hodler'));
channel.setName(StrToJCharSequence('hodler'));
channel.enableLights(true);
channel.enableVibration(true);
channel.setLightColor(TJColor.JavaClass.GREEN);
channel.setLockscreenVisibility
(TJNotification.JavaClass.VISIBILITY_PRIVATE);
manager.createNotificationChannel(channel);
LBuilder := DW.Androidapi.JNI.Support.TJNotificationCompat_Builder.
JavaClass.init(TAndroidHelper.context, channel.getId)
end
else
LBuilder := DW.Androidapi.JNI.Support.TJNotificationCompat_Builder.
JavaClass.init(TAndroidHelper.context);
LBuilder.setAutoCancel(true);
LBuilder.setGroupSummary(true);
if api26 then
LBuilder.setChannelId(channel.getId);
LBuilder.setContentTitle(StrToJCharSequence('HODLER - Nano PoW Worker'));
LBuilder.setContentText(StrToJCharSequence('Ready to work nano blocks'));
LBuilder.setSmallIcon(TAndroidHelper.context.getApplicationInfo.icon);
LBuilder.setTicker(StrToJCharSequence('HODLER - Nano PoW Worker'));
VIntent := TAndroidHelper.context.getPackageManager()
.getLaunchIntentForPackage(TAndroidHelper.context.getPackageName());
resultPendingIntent := TJPendingIntent.JavaClass.getActivity
(TAndroidHelper.context, 0, VIntent,
TJPendingIntent.JavaClass.FLAG_UPDATE_CURRENT);
LBuilder.setContentIntent(resultPendingIntent);
DM.JavaService.StartForeground(1995, LBuilder.build);
Result := TJService.JavaClass.START_STICKY;
logd(' done');
end;
end.
|
unit UDaoPadrao;
interface
uses
Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON,
Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr,
Data.DBXDBReaders, Data.DBXJSONReflect;
type
TDaoPadrao = class(TDSAdminClient)
private
FCmd: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function Consultar(ATxtClassMt: string): OleVariant;overload;
function Consultar(O: TJSONValue; ATxtClassMt: string): OleVariant;overload;
function Moviventacao(O: TJSONValue; ATxtClassMt: string): Boolean;
end;
implementation
{ TDaoPadrao }
constructor TDaoPadrao.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
function TDaoPadrao.Consultar(ATxtClassMt: string): OleVariant;
begin
if FCmd = nil then
FCmd := FDBXConnection.CreateCommand;
FCmd.CommandType := TDBXCommandTypes.DSServerMethod;
FCmd.Text := ATxtClassMt; //Exemplo: 'TdaoCliente.DsCliente';
FCmd.Prepare;
FCmd.ExecuteUpdate;
Result := FCmd.Parameters[0].Value.AsVariant;
end;
function TDaoPadrao.Consultar(O: TJSONValue; ATxtClassMt: string): OleVariant;
begin
if FCmd = nil then
FCmd := FDBXConnection.CreateCommand;
FCmd.CommandType := TDBXCommandTypes.DSServerMethod;
FCmd.Text := ATxtClassMt; //Exemplo: 'TdaoCliente.DsCliente';
FCmd.Prepare;
FCmd.Parameters[0].Value.SetJSONValue(O, FInstanceOwner);
FCmd.ExecuteUpdate;
Result := FCmd.Parameters[1].Value.AsVariant;
end;
constructor TDaoPadrao.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TDaoPadrao.Destroy;
begin
FreeAndNil(FCmd);
inherited;
end;
function TDaoPadrao.Moviventacao(O: TJSONValue; ATxtClassMt: string): Boolean;
begin
if FCmd = nil then
FCmd := FDBXConnection.CreateCommand;
FCmd.CommandType := TDBXCommandTypes.DSServerMethod;
FCmd.Text := ATxtClassMt; //Exemplo: 'TdaoCliente.DsCliente';
FCmd.Prepare;
FCmd.Parameters[0].Value.SetJSONValue(O, FInstanceOwner);
FCmd.ExecuteUpdate;
Result := FCmd.Parameters[1].Value.GetBoolean;
end;
end.
|
PROGRAM NumberTranslator (input, output);
{ Translate a list of integers from numeric form into
words. The integers must not be negative nor be
greater than the value of maxnumber. The last
integer in the list has the value of terminator.
}
CONST
maxnumber = 999999; {maximum allowable number}
terminator = 0; {last number to read}
VAR
number : integer; {number to be translated}
PROCEDURE Translate (n : integer);
{Translate number n into words.}
VAR
partbefore, {part before the comma}
partafter {part after the comma}
: integer;
PROCEDURE DoPart (part : integer);
{Translate a part of a number into words,
where 1 <= part <= 999.}
VAR
hundredsdigit, {hundreds digit 0..9}
tenspart, {tens part 0..99}
tensdigit, {tens digit 0..9}
onesdigit {ones digit 0..9}
: integer;
PROCEDURE DoOnes (digit : integer);
{Translate a single ones digit into a word,
where 1 <= digit <= 9.}
BEGIN
CASE digit OF
1: write (' one');
2: write (' two');
3: write (' three');
4: write (' four');
5: write (' five');
6: write (' six');
7: write (' seven');
8: write (' eight');
9: write (' nine');
END;
END {DoOnes};
PROCEDURE DoTeens (teens : integer);
{Translate the teens into a word,
where 10 <= teens <= 19.}
BEGIN
CASE teens OF
10: write (' ten');
11: write (' eleven');
12: write (' twelve');
13: write (' thirteen');
14: write (' fourteen');
15: write (' fifteen');
16: write (' sixteen');
17: write (' seventeen');
18: write (' eighteen');
19: write (' nineteen');
END;
END {DoTeens};
PROCEDURE DoTens (digit : integer);
{Translate a single tens digit into a word,
where 2 <= digit <= 9.}
BEGIN
CASE digit OF
2: write (' twenty');
3: write (' thirty');
4: write (' forty');
5: write (' fifty');
6: write (' sixty');
7: write (' seventy');
8: write (' eighty');
9: write (' ninety');
END;
END {DoTens};
BEGIN {DoPart}
{Break up the number part.}
hundredsdigit := part DIV 100;
tenspart := part MOD 100;
{Translate the hundreds digit.}
IF hundredsdigit > 0 THEN BEGIN
DoOnes (hundredsdigit);
write (' hundred');
END;
{Translate the tens part.}
IF (tenspart >= 10)
AND (tenspart <= 19) THEN BEGIN
DoTeens (tenspart);
END
ELSE BEGIN
tensdigit := tenspart DIV 10;
onesdigit := tenspart MOD 10;
IF tensdigit > 0 THEN DoTens (tensdigit);
IF onesdigit > 0 THEN DoOnes (onesdigit);
END;
END {DoPart};
BEGIN {Translate}
{Break up the number.}
partbefore := n DIV 1000;
partafter := n MOD 1000;
IF partbefore > 0 THEN BEGIN
DoPart (partbefore);
write (' thousand');
END;
IF partafter > 0 THEN DoPart (partafter);
END {Translate};
BEGIN {NumberTranslator}
{Loop to read, write, check, and translate the numbers.}
REPEAT
writeln;
write ('Enter a number >= 0 and <= ', maxnumber:0,
' (', terminator:0, ' to stop): ');
read (number);
write (number:6, ' :');
IF number < 0 THEN BEGIN
write (' ***** Error -- number < 0');
END
ELSE IF number > maxnumber THEN BEGIN
write (' ***** Error -- number > ', maxnumber:0);
END
ELSE IF number = terminator THEN BEGIN
write (' zero');
END
ELSE BEGIN
Translate (number);
END;
writeln; {complete output line}
UNTIL number = terminator;
END {NumberTranslator}.
|
unit ncsSynchroClientTransporter;
// Модуль: "w:\common\components\rtl\Garant\cs\ncsSynchroClientTransporter.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TncsSynchroClientTransporter" MUID: (54E339B500F7)
{$Include w:\common\components\rtl\Garant\cs\CsDefine.inc}
interface
{$If NOT Defined(Nemesis)}
uses
l3IntfUses
, ncsSynchroTransporter
, ncsMessageInterfaces
, ncsTCPClient
, idComponent
;
type
TncsSynchroClientTransporter = class(TncsSynchroTransporter, IncsClientTransporter)
private
f_TCPClient: TncsTCPClient;
private
procedure TransportStatus(ASender: TObject;
const AStatus: TIdStatus;
const AStatusText: AnsiString);
procedure TransportConnected;
protected
procedure BeforeHandshake; virtual;
procedure Connect(const aServerHost: AnsiString;
aServerPort: Integer;
const aSessionID: AnsiString);
procedure Disconnect(Immidiate: Boolean = False);
{* Immidiate = True - отрубить сразу
Immidiate = False - дождаться завершения обмена послав ncsDisconnect и дождавшись ответа }
procedure HandShake; override;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure InitFields; override;
public
constructor Create; reintroduce;
class function Make: IncsClientTransporter; reintroduce;
end;//TncsSynchroClientTransporter
{$IfEnd} // NOT Defined(Nemesis)
implementation
{$If NOT Defined(Nemesis)}
uses
l3ImplUses
, csIdIOHandlerAdapter
, csIdIOHandlerAbstractAdapter
, l3Base
, IdException
, SysUtils
, ncsMessage
//#UC START# *54E339B500F7impl_uses*
//#UC END# *54E339B500F7impl_uses*
;
constructor TncsSynchroClientTransporter.Create;
//#UC START# *54E33A870172_54E339B500F7_var*
//#UC END# *54E33A870172_54E339B500F7_var*
begin
//#UC START# *54E33A870172_54E339B500F7_impl*
inherited Create;
//#UC END# *54E33A870172_54E339B500F7_impl*
end;//TncsSynchroClientTransporter.Create
class function TncsSynchroClientTransporter.Make: IncsClientTransporter;
var
l_Inst : TncsSynchroClientTransporter;
begin
l_Inst := Create;
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TncsSynchroClientTransporter.Make
procedure TncsSynchroClientTransporter.TransportStatus(ASender: TObject;
const AStatus: TIdStatus;
const AStatusText: AnsiString);
//#UC START# *54E33B3A02CB_54E339B500F7_var*
//#UC END# *54E33B3A02CB_54E339B500F7_var*
begin
//#UC START# *54E33B3A02CB_54E339B500F7_impl*
case aStatus of
hsConnected: TransportConnected;
hsDisconnected: StopProcessing;
end;
//#UC END# *54E33B3A02CB_54E339B500F7_impl*
end;//TncsSynchroClientTransporter.TransportStatus
procedure TncsSynchroClientTransporter.TransportConnected;
//#UC START# *54E33B5E0245_54E339B500F7_var*
var
l_IOHandler: TcsIdIOHandlerAbstractAdapter;
//#UC END# *54E33B5E0245_54E339B500F7_var*
begin
//#UC START# *54E33B5E0245_54E339B500F7_impl*
if Get_Connected then
Exit;
l_IOHandler := TcsidIOHandlerAdapter.Create(f_TcpClient.IOHandler);
try
IOHandler := l_IOHandler;
finally
FreeAndNil(l_IOHandler)
end;
StartProcessing;
//#UC END# *54E33B5E0245_54E339B500F7_impl*
end;//TncsSynchroClientTransporter.TransportConnected
procedure TncsSynchroClientTransporter.BeforeHandshake;
//#UC START# *54E33EA40163_54E339B500F7_var*
//#UC END# *54E33EA40163_54E339B500F7_var*
begin
//#UC START# *54E33EA40163_54E339B500F7_impl*
// Do nothing
//#UC END# *54E33EA40163_54E339B500F7_impl*
end;//TncsSynchroClientTransporter.BeforeHandshake
procedure TncsSynchroClientTransporter.Connect(const aServerHost: AnsiString;
aServerPort: Integer;
const aSessionID: AnsiString);
//#UC START# *544A1FD802E9_54E339B500F7_var*
//#UC END# *544A1FD802E9_54E339B500F7_var*
begin
//#UC START# *544A1FD802E9_54E339B500F7_impl*
if Get_Connected then
Exit;
IntSessionID := aSessionID;
f_TcpClient.Host := aServerHost;
f_TcpClient.Port := aServerPort;
try
f_TcpClient.Connect;
except
on E: EidException do
l3System.Exception2Log(E);
end;
//#UC END# *544A1FD802E9_54E339B500F7_impl*
end;//TncsSynchroClientTransporter.Connect
procedure TncsSynchroClientTransporter.Disconnect(Immidiate: Boolean = False);
{* Immidiate = True - отрубить сразу
Immidiate = False - дождаться завершения обмена послав ncsDisconnect и дождавшись ответа }
//#UC START# *544A1FF00062_54E339B500F7_var*
var
l_Message: TncsDisconnect;
l_Reply: TncsMessage;
//#UC END# *544A1FF00062_54E339B500F7_var*
begin
//#UC START# *544A1FF00062_54E339B500F7_impl*
if not Get_Connected then
Exit;
if not Immidiate then
begin
l_Message := TncsDisconnect.Create;
try
Send(l_Message);
l_Reply := nil;
WaitForReply(l_Message, l_Reply);
if not (l_Reply is TncsDisconnectReply) then
l3System.Msg2Log('Invalid csDisconnectReply');
FreeAndNil(l_Reply);
finally
FreeAndNil(l_Message);
end;
end;
StopProcessing;
f_TcpClient.IOHandler.WriteBufferClose;
f_TcpClient.Disconnect(True);
IntSessionID := '';
//#UC END# *544A1FF00062_54E339B500F7_impl*
end;//TncsSynchroClientTransporter.Disconnect
procedure TncsSynchroClientTransporter.HandShake;
//#UC START# *54E3353000D8_54E339B500F7_var*
var
l_ID: Integer;
l_IOHandler: TcsIdIOHandlerAbstractAdapter;
//#UC END# *54E3353000D8_54E339B500F7_var*
begin
//#UC START# *54E3353000D8_54E339B500F7_impl*
BeforeHandshake;
IOHandler.WriteLn(IntSessionID);
IOHandler.WriteBufferFlush;
l_ID := IOHandler.ReadInteger;
Assert(l_ID = 104);
//#UC END# *54E3353000D8_54E339B500F7_impl*
end;//TncsSynchroClientTransporter.HandShake
procedure TncsSynchroClientTransporter.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_54E339B500F7_var*
//#UC END# *479731C50290_54E339B500F7_var*
begin
//#UC START# *479731C50290_54E339B500F7_impl*
Disconnect;
FreeAndNil(f_TcpClient);
inherited;
//#UC END# *479731C50290_54E339B500F7_impl*
end;//TncsSynchroClientTransporter.Cleanup
procedure TncsSynchroClientTransporter.InitFields;
//#UC START# *47A042E100E2_54E339B500F7_var*
const
{ В миллисек }
c_ClientConnectTimeout = 10 * 1000;
c_ClientReadTimeout = {$IFDEF CsDebug} 1000 * 1000 {$ELSE} 10 * 1000 {$ENDIF};
//#UC END# *47A042E100E2_54E339B500F7_var*
begin
//#UC START# *47A042E100E2_54E339B500F7_impl*
inherited;
f_TcpClient := TncsTcpClient.Create(nil);
f_TcpClient.ConnectTimeout := c_ClientConnectTimeout;
f_TcpClient.ReadTimeout := c_ClientReadTimeout;
f_TcpClient.OnStatus := TransportStatus;
//#UC END# *47A042E100E2_54E339B500F7_impl*
end;//TncsSynchroClientTransporter.InitFields
{$IfEnd} // NOT Defined(Nemesis)
end.
|
unit ULinkedInDemo;
interface
uses
FMX.TMSCloudBase, FMX.TMSCloudLinkedIn, FMX.Controls, FMX.Objects, TypInfo,
FMX.TMSCloudImage, FMX.StdCtrls, FMX.Memo, FMX.ListBox, FMX.Layouts,
FMX.TabControl, FMX.Edit, System.Classes, FMX.Types, FMX.Dialogs, FMX.Forms, Sysutils,
FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomLinkedIn;
type
TForm1 = class(TForm)
StyleBook1: TStyleBook;
GroupBox1: TGroupBox;
btPostActivity: TButton;
Label2: TLabel;
edActivity: TEdit;
GroupBox2: TGroupBox;
btShare: TButton;
Label1: TLabel;
Title: TEdit;
Descr: TEdit;
Label3: TLabel;
Label4: TLabel;
Hyperlink: TEdit;
Label5: TLabel;
ImageLink: TEdit;
GroupBox3: TGroupBox;
pSearch: TTabControl;
TabSheet1: TTabItem;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
lbTotalPeople: TLabel;
edKeywords: TEdit;
edFirstName: TEdit;
edLastName: TEdit;
edCompany: TEdit;
cbCountries: TComboBox;
btPeopleSearch: TButton;
lbPeople: TListBox;
Companies: TTabItem;
Label11: TLabel;
lbTotalCompanies: TLabel;
btSearchCompanies: TButton;
edCompKeywords: TEdit;
lbCompanies: TListBox;
Jobs: TTabItem;
Label12: TLabel;
lbJobResults: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
edJobKeywords: TEdit;
btSearchJobs: TButton;
lbJobs: TListBox;
edJobTitle: TEdit;
edJobCompany: TEdit;
cbJobCountries: TComboBox;
btNextPeople: TButton;
btNextCompanies: TButton;
btNextJobs: TButton;
btPrevCompanies: TButton;
btPrevJobs: TButton;
btPrevPeople: TButton;
GroupBox4: TGroupBox;
Memo1: TMemo;
Panel1: TPanel;
btConnect: TButton;
TMSFMXCloudLinkedIn1: TTMSFMXCloudLinkedIn;
Label16: TLabel;
cbCompanyCountries: TComboBox;
Label17: TLabel;
Image1: TImage;
btRemove: TButton;
cbIndustryCode: TComboBox;
Panel2: TPanel;
TMSFMXCloudCloudImage1: TTMSFMXCloudImage;
Label18: TLabel;
Profiles: TTabItem;
btConnections: TButton;
DefProf: TButton;
lbConnections: TListBox;
procedure btConnectClick(Sender: TObject);
procedure btShareClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DefProfClick(Sender: TObject);
procedure btConnectionsClick(Sender: TObject);
procedure lbConnectionsClick(Sender: TObject);
procedure btPostActivityClick(Sender: TObject);
procedure TMSFMXCloudLinkedIn1ReceivedAccessToken(Sender: TObject);
procedure btPeopleSearchClick(Sender: TObject);
procedure lbPeopleClick(Sender: TObject);
procedure btSearchCompaniesClick(Sender: TObject);
procedure lbCompaniesClick(Sender: TObject);
procedure btSearchJobsClick(Sender: TObject);
procedure lbJobsClick(Sender: TObject);
procedure btNextPeopleClick(Sender: TObject);
procedure btNextCompaniesClick(Sender: TObject);
procedure btNextJobsClick(Sender: TObject);
procedure btPrevCompaniesClick(Sender: TObject);
procedure btPrevJobsClick(Sender: TObject);
procedure btPrevPeopleClick(Sender: TObject);
procedure btRemoveClick(Sender: TObject);
procedure pSearchChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Connected: boolean;
resultpage: integer;
resultcount: integer;
pagesize: integer;
procedure ToggleControls;
procedure SearchPeople;
procedure SearchCompanies;
procedure SearchJobs;
procedure DisplayProfile(Profile: TLinkedInProfile);
end;
var
Form1: TForm1;
implementation
{$R *.FMX}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// LinkedInAppkey = 'xxxxxxxxx';
// LinkedInAppSecret = 'yyyyyyyy';
{$I APPIDS.INC}
procedure TForm1.TMSFMXCloudLinkedIn1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudLinkedIn1.SaveTokens;
Connected := true;
ToggleControls;
end;
procedure TForm1.btSearchCompaniesClick(Sender: TObject);
begin
resultpage := 0;
resultcount := 0;
SearchCompanies;
end;
procedure TForm1.btSearchJobsClick(Sender: TObject);
begin
resultpage := 0;
resultcount := 0;
SearchJobs;
end;
procedure TForm1.btConnectClick(Sender: TObject);
var
acc: boolean;
begin
TMSFMXCloudLinkedIn1.App.Key := LinkedInAppKey;
TMSFMXCloudLinkedIn1.App.Secret := LinkedInAppSecret;
if TMSFMXCloudLinkedIn1.App.Key <> '' then
begin
TMSFMXCloudLinkedIn1.PersistTokens.Key := ExtractFilePath(ParamStr(0)) + 'linkedin.ini';
TMSFMXCloudLinkedIn1.PersistTokens.Section := 'tokens';
TMSFMXCloudLinkedIn1.LoadTokens;
acc := TMSFMXCloudLinkedIn1.TestTokens;
if not acc then
begin
TMSFMXCloudLinkedIn1.RefreshAccess;
TMSFMXCloudLinkedIn1.DoAuth;
end
else
begin
connected := true;
ToggleControls;
end;
end
else
ShowMessage('Please provide a valid application ID for the client component');
end;
procedure TForm1.DefProfClick(Sender: TObject);
var
lp: TLinkedInProfile;
begin
TMSFMXCloudLinkedIn1.GetDefaultProfile;
lp := TMSFMXCloudLinkedIn1.DefaultProfile;
DisplayProfile(lp);
TMSFMXCloudCloudImage1.URL := lp.PictureURL;
end;
procedure TForm1.DisplayProfile(Profile: TLinkedInProfile);
begin
memo1.Lines.Text :=
'FormattedName: ' + Profile.FormattedName + #13 +
'Headline: ' + Profile.Headline + #13 +
'Summary: ' + Profile.Summary + #13 +
'Email: ' + Profile.EmailAddress + #13 +
'PublicProfileURL: ' + Profile.PublicProfileURL + #13 +
'Location: ' + Profile.Location + #13 +
'CountryCode: ' + Profile.CountryCode;
end;
procedure TForm1.btConnectionsClick(Sender: TObject);
var
i: integer;
begin
TMSFMXCloudLinkedIn1.GetConnections;
lbConnections.Items.Clear;
for i := 0 to TMSFMXCloudLinkedIn1.Connections.Count - 1 do
begin
lbConnections.Items.AddObject(TMSFMXCloudLinkedIn1.Connections.Items[i].Profile.FirstName + ' ' + TMSFMXCloudLinkedIn1.Connections.Items[i].Profile.LastName, TObject(i));
end;
lbConnections.Sorted := true;
end;
procedure TForm1.btShareClick(Sender: TObject);
begin
TMSFMXCloudLinkedIn1.Share(Title.Text, Descr.Text, Hyperlink.Text, ImageLink.Text);
end;
procedure TForm1.btPostActivityClick(Sender: TObject);
begin
TMSFMXCloudLinkedIn1.Activity(edActivity.Text)
end;
procedure TForm1.btPrevCompaniesClick(Sender: TObject);
begin
if resultpage > 0 then
begin
resultpage := resultpage - 1;
SearchCompanies;
end;
end;
procedure TForm1.btPrevJobsClick(Sender: TObject);
begin
if resultpage > 0 then
begin
resultpage := resultpage - 1;
SearchJobs;
end;
end;
procedure TForm1.btPrevPeopleClick(Sender: TObject);
begin
if resultpage > 0 then
begin
resultpage := resultpage - 1;
SearchPeople;
end;
end;
procedure TForm1.btRemoveClick(Sender: TObject);
begin
TMSFMXCloudLinkedIn1.ClearTokens;
Connected := false;
ToggleControls;
end;
procedure TForm1.btNextCompaniesClick(Sender: TObject);
begin
if resultcount >= (pagesize * resultpage) then
begin
btPrevCompanies.Enabled := true;
resultpage := resultpage + 1;
SearchCompanies;
end;
end;
procedure TForm1.btNextJobsClick(Sender: TObject);
begin
if resultcount >= (pagesize * resultpage) then
begin
resultpage := resultpage + 1;
SearchJobs;
end;
end;
procedure TForm1.btNextPeopleClick(Sender: TObject);
begin
if resultcount >= (pagesize * resultpage) then
begin
resultpage := resultpage + 1;
SearchPeople;
end;
end;
procedure TForm1.SearchCompanies;
var
i, maxresult: integer;
cr: TCompanyResults;
sp: TCompanySearchParam;
begin
sp.Keywords := edCompKeywords.Text;
if cbIndustryCode.ItemIndex > 0 then
sp.IndustryCode := Integer(cbIndustryCode.Items.Objects[cbIndustryCode.ItemIndex])
else
sp.IndustryCode := 0;
if cbCompanyCountries.ItemIndex >= 0 then
sp.CountryCode := TISO3166Country(Integer(cbCompanyCountries.Items.Objects[cbCompanyCountries.ItemIndex]))
else
sp.CountryCode := icNone;
cr := TMSFMXCloudLinkedIn1.SearchCompany(sp, resultcount, resultpage);
if resultpage = 0 then
btPrevCompanies.Enabled := false
else
btPrevCompanies.Enabled := true;
maxresult := (pagesize * resultpage) + pagesize;
if resultcount <= maxresult then
begin
maxresult := resultcount;
btNextCompanies.Enabled := false;
end
else
btNextCompanies.Enabled := true;
lbTotalCompanies.Text := 'Results: '
+ IntToStr(pagesize * resultpage) + ' to ' + IntToStr(maxresult) + ' of ' + IntToStr(resultcount);
lbCompanies.Items.Clear;
for i := 0 to cr.Count - 1 do
begin
lbCompanies.Items.AddObject(cr.Items[i].CompanyName, cr.Items[i]);
end;
end;
procedure TForm1.SearchJobs;
var
sp: TJobSearchParam;
i, maxresult: integer;
r: TJobResults;
begin
sp.Keywords := edJobKeywords.Text;
sp.JobTitle := edJobTitle.Text;
sp.CompanyName := edJobCompany.Text;
if cbJobCountries.ItemIndex >= 0 then
sp.CountryCode := TISO3166Country(Integer(cbJobCountries.Items.Objects[cbJobCountries.ItemIndex]))
else
sp.CountryCode := icNone;
r := TMSFMXCloudLinkedIn1.SearchJob(sp, resultcount, resultpage);
if resultpage = 0 then
btPrevJobs.Enabled := false
else
btPrevJobs.Enabled := true;
maxresult := (pagesize * resultpage) + pagesize;
if resultcount <= maxresult then
begin
maxresult := resultcount;
btNextJobs.Enabled := false;
end
else
btNextJobs.Enabled := true;
lbJobResults.Text := 'Results: '
+ IntToStr(pagesize * resultpage) + ' to ' + IntToStr(maxresult) + ' of ' + IntToStr(resultcount);
lbJobs.Items.Clear;
for i := 0 to r.Count - 1 do
begin
lbJobs.Items.AddObject(r.Items[i].Position, r.Items[i]);
end;
end;
procedure TForm1.SearchPeople();
var
sp: TPeopleSearchParam;
pr: TPeopleResults;
i, maxresult: integer;
begin
sp.Keywords := edKeywords.Text;
sp.FirstName := edFirstName.Text;
sp.LastName := edLastName.Text;
sp.CompanyName := edCompany.Text;
if cbCountries.ItemIndex >= 0 then
sp.CountryCode := TISO3166Country(Integer(cbCountries.Items.Objects[cbCountries.ItemIndex]))
else
sp.CountryCode := icNone;
pr := TMSFMXCloudLinkedIn1.SearchPeople(sp, resultcount, resultpage);
if resultpage = 0 then
btPrevPeople.Enabled := false
else
btPrevPeople.Enabled := true;
maxresult := (pagesize * resultpage) + pagesize;
if resultcount <= maxresult then
begin
maxresult := resultcount;
btNextPeople.Enabled := false;
end
else
btNextPeople.Enabled := true;
lbTotalPeople.Text := 'Results: '
+ IntToStr(pagesize * resultpage) + ' to ' + IntToStr(maxresult) + ' of ' + IntToStr(resultcount);
lbPeople.Items.Clear;
for i := 0 to pr.Count - 1 do
begin
lbPeople.Items.AddObject(pr.Items[i].FirstName + ' ' + pr.Items[i].LastName, pr.Items[i]);
end;
end;
procedure TForm1.ToggleControls;
begin
//init search results paging
resultpage := 1;
resultcount := 0;
pagesize := 10;
btNextPeople.Enabled := false;
btPrevPeople.Enabled := false;
btNextCompanies.Enabled := false;
btPrevCompanies.Enabled := false;
btNextJobs.Enabled := false;
btPrevJobs.Enabled := false;
lbPeople.Items.Clear;
lbCompanies.Items.Clear;
lbJobs.Items.Clear;
lbTotalPeople.Text := '';
lbTotalCompanies.Text := '';
lbJobResults.Text := '';
btConnect.Enabled := not Connected;
btRemove.Enabled := Connected;
DefProf.Enabled := Connected;
btPeopleSearch.Enabled := Connected;
btConnections.Enabled := Connected;
btPostActivity.Enabled := Connected;
btShare.Enabled := Connected;
pSearch.Enabled := Connected;
lbConnections.Enabled := Connected;
Memo1.Enabled := Connected;
edActivity.Enabled := Connected;
Title.Enabled := Connected;
Hyperlink.Enabled := Connected;
Descr.Enabled := Connected;
ImageLink.Enabled := Connected;
edKeywords.Enabled := Connected;
edFirstName.Enabled := Connected;
edLastName.Enabled := Connected;
edCompany.Enabled := Connected;
cbCountries.Enabled := Connected;
end;
procedure TForm1.btPeopleSearchClick(Sender: TObject);
begin
resultpage := 0;
resultcount := 0;
SearchPeople;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i: integer;
CountryName: string;
begin
//Fill country comboboxes
cbCountries.Items.Clear;
cbJobCountries.Items.Clear;
cbCompanyCountries.Items.Clear;
for i := Ord(Low(TISO3166Country)) to Ord(High(TISO3166Country)) do
begin
CountryName := GetEnumName(TypeInfo(TISO3166Country), i);
Delete(CountryName, 1, 2);
cbCountries.Items.AddObject(CountryName, TObject(i));
cbJobCountries.Items.AddObject(CountryName, TObject(i));
cbCompanyCountries.Items.AddObject(CountryName, TObject(i));
end;
//Fill industry code combobox
cbIndustryCode.Items.Clear;
cbIndustryCode.Items.AddObject('Any', TObject(-1));
cbIndustryCode.Items.AddObject('Computer & Network Security', TObject(118));
cbIndustryCode.Items.AddObject('Computer Games', TObject(109));
cbIndustryCode.Items.AddObject('Computer Software', TObject(4));
cbIndustryCode.Items.AddObject('Computer Hardware', TObject(3));
cbIndustryCode.Items.AddObject('Computer Networking', TObject(5));
cbIndustryCode.Items.AddObject('Consumer Electronics', TObject(24));
cbIndustryCode.Items.AddObject('Information Technology & Services', TObject(96));
cbIndustryCode.Items.AddObject('Internet', TObject(6));
cbIndustryCode.Items.AddObject('Online Media', TObject(113));
cbIndustryCode.Items.AddObject('Semiconductors', TObject(7));
cbIndustryCode.Items.AddObject('Telecommunications', TObject(8));
cbIndustryCode.Items.AddObject('Wireless', TObject(119));
Connected := false;
ToggleControls;
end;
procedure TForm1.lbCompaniesClick(Sender: TObject);
var
lc: TLinkedInCompany;
cr: TCompanyResult;
begin
if lbCompanies.ItemIndex <> -1 then
begin
cr := (lbCompanies.Items.Objects[lbCompanies.ItemIndex] as TCompanyResult);
lc := TMSFMXCloudLinkedIn1.GetCompanyInfo(cr.ID);
TMSFMXCloudCloudImage1.URL := lc.ImageURL;
memo1.Lines.Text := lc.CompanyName
+ #13 + 'Size: ' + lc.Size
+ #13 + 'Industry: ' + lc.Industries.Items[0].ObjectName
+ #13 + 'Website: ' + lc.Website
+ #13 + lc.Description
;
lc.Free;
end;
end;
procedure TForm1.lbJobsClick(Sender: TObject);
var
r: TJobResult;
lj: TLinkedInJob;
begin
if lbJobs.ItemIndex <> -1 then
begin
r := (lbJobs.Items.Objects[lbJobs.ItemIndex] as TJobResult);
lj := TMSFMXCloudLinkedIn1.GetJobInfo(r.ID);
TMSFMXCloudCloudImage1.URL := '';
memo1.Lines.Text := lj.Position
+ #13 + 'Company: ' + lj.Company.CompanyName
+ #13 + 'Location: ' + lj.Location
+ #13 + 'Job description: ' + lj.Description
;
lj.Free;
end;
end;
procedure TForm1.lbPeopleClick(Sender: TObject);
var
lp: TLinkedInProfile;
pr: TPeopleResult;
begin
if lbPeople.ItemIndex <> -1 then
begin
pr := (lbPeople.Items.Objects[lbPeople.ItemIndex] as TPeopleResult);
lp := TMSFMXCloudLinkedIn1.GetProfile(pr.ID);
TMSFMXCloudCloudImage1.URL := lp.PictureURL;
DisplayProfile(lp);
lp.Free;
end;
end;
procedure TForm1.pSearchChange(Sender: TObject);
begin
ToggleControls;
end;
procedure TForm1.lbConnectionsClick(Sender: TObject);
var
id: string;
lp: TLinkedInProfile;
tag: integer;
begin
if lbConnections.ItemIndex <> -1 then
begin
tag := integer(lbConnections.Items.Objects[lbConnections.ItemIndex]);
id := TMSFMXCloudLinkedIn1.Connections.Items[tag].Profile.ID;
TMSFMXCloudLinkedIn1.Connections.Items[tag].Profile := TMSFMXCloudLinkedIn1.GetProfile(id);
lp := TMSFMXCloudLinkedIn1.Connections.Items[tag].Profile;
TMSFMXCloudCloudImage1.URL := lp.PictureURL;
DisplayProfile(lp);
end;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpIAsn1TaggedObjectParser;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpIProxiedInterface;
type
IAsn1TaggedObjectParser = interface(IAsn1Convertible)
['{AB221E2D-A78A-46F7-85AE-B642D904B705}']
function GetTagNo: Int32;
property TagNo: Int32 read GetTagNo;
function GetObjectParser(tag: Int32; isExplicit: Boolean): IAsn1Convertible;
end;
implementation
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://webserver.averba.com.br/index.soap?wsdl
// >Import : http://webserver.averba.com.br/index.soap?wsdl>0
// Encoding : ISO-8859-1
// Version : 1.0
// (06/07/2017 15:10:57 - - $Rev: 56641 $)
// ************************************************************************ //
unit AtmWebService1;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Embarcadero types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:string - "http://www.w3.org/2001/XMLSchema"[]
// ************************************************************************ //
// Namespace : urn:ATMWebSvr
// soapAction: urn:ATMWebSvr#%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// style : rpc
// use : encoded
// binding : ATMWebSvrBinding
// service : ATMWebSvr
// port : ATMWebSvrPort
// URL : http://webserver.averba.com.br/index.soap
// ************************************************************************ //
ATMWebSvrPortType = interface(IInvokable)
['{7B838219-78E4-EEC2-9CDB-E58C0CBE8435}']
function averbaCTe(const usuario: string; const senha: string; const codatm: string; const xmlCTe: string): string; stdcall;
function averbaCTe20(const usuario: string; const senha: string; const codatm: string; const xmlCTe: string): string; stdcall;
function averbaNFe(const usuario: string; const senha: string; const codatm: string; const xmlNFe: string): string; stdcall;
function averbaNFe20(const usuario: string; const senha: string; const codatm: string; const xmlNFe: string): string; stdcall;
function averbaATM(const usuario: string; const senha: string; const codatm: string; const Serie: string; const Numero: string; const UFOrigem: string;
const UFDestino: string; const Urbano: string; const TipoMercadoria: string; const ValorMercadoria: string; const Placa: string;
const CodigoLiberacao: string; const CPFMotorista: string; const CNPJEmissor: string; const OCD: string; const IC: string;
const RI: string; const TranspProprio: string; const DataEmissao: string; const TipoDocto: string; const TipoTransporte: string;
const TipoMovimento: string; const TaxaRCFDC: string; const PercursoComplementar: string; const PercursoComplementarTransporte: string; const PercursoComplementarUFOrigem: string;
const PercursoComplementarUFDestino: string; const RGMotorista: string; const Ramo: string; const Filial: string; const Rastreado: string;
const Escolta: string; const Observacoes: string; const ValorContainner: string; const ValorAcessorios: string; const MeiosProprios: string;
const DataEmbarque: string; const ValorFrete: string; const ValorDespesas: string; const ValorImpostos: string; const ValorLucrosEsperados: string;
const ValorAvarias: string; const CodigoDaMercadoria: string; const HoraEmbarque: string; const CEPOrigem: string; const CEPDestino: string;
const CNPJDDR: string; const MercadoriaNova: string; const TipoDeViagem: string): string; stdcall;
function listaErros(const usuario: string; const senha: string; const codatm: string): string; stdcall;
function AddBackMail(const usuario: string; const senha: string; const codatm: string; const aplicacao: string; const assunto: string; const remetentes: string;
const destinatarios: string; const corpo: string; const chave: string; const chaveresp: string): string; stdcall;
end;
function GetATMWebSvrPortType(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): ATMWebSvrPortType;
implementation
uses SysUtils;
function GetATMWebSvrPortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): ATMWebSvrPortType;
const
defWSDL = 'http://webserver.averba.com.br/index.soap?wsdl';
defURL = 'http://webserver.averba.com.br/index.soap';
defSvc = 'ATMWebSvr';
defPrt = 'ATMWebSvrPort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as ATMWebSvrPortType);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
initialization
{ ATMWebSvrPortType }
InvRegistry.RegisterInterface(TypeInfo(ATMWebSvrPortType), 'urn:ATMWebSvr', 'ISO-8859-1');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(ATMWebSvrPortType), 'urn:ATMWebSvr#%operationName%');
end. |
unit ErrorMsgUtils;
// Copyright (c) 1998 Jorge Romero Gomez, Merchise
interface
function SysErrorString( ErrorId : integer ) : string;
implementation
uses
Windows;
function SysErrorString( ErrorId : integer ) : string;
var
Len : integer;
begin
SetLength( Result, MAX_PATH );
Len := FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_IGNORE_INSERTS, nil, ErrorId, 0, pchar( Result ), length( Result ), nil );
SetLength( Result, Len );
end;
end.
|
unit SVGAGRPH;
interface
var result:Shortint;
function ismouse:boolean;
function initmouse:boolean;
procedure setsteptopixel(hor,ver:integer);
procedure getsteptopixel(var hor,ver:integer);
procedure setdoblespeed(speed:word);
function getdoblespeed:word;
procedure mousewherexy(var x,y:integer);
function numbutton:byte;
procedure getmousestate(var butt,x,y:integer);
procedure hidemouse;
procedure showmouse;
procedure mousescreen;
procedure mousegraphcur(var scrcur;x,y:byte);
procedure mousebuttpressed(butt:integer;var stat,count,x,y:integer);
procedure mousebuttrelased(butt:integer;var stat,count,x,y:integer);
procedure rectangle(x1,y1,x2,y2:word;fill:boolean);
function readstring(x,y:word):string;
function readint(x,y:word):longint;
function readword(x,y:word):word;
function readreal(x,y:word):real;
procedure Clrscr;
procedure bkcolor(col:longint);
procedure putimage(x1,y1,xsz,ysz:word;bb:byte;var buff;xx,yy:boolean);
function getmaxx:word;
function getmaxy:word;
procedure Vesa;
procedure lineto(x,y:word);
procedure Circle(x,y,r:word);
procedure Done;
procedure GetMaxXY(x,y:word);
procedure Color(col:longint);
procedure TextWrite(x,y:word;txt:string);
procedure SetPixel(x,y:word;col:longint);
procedure OutLine(stx,sty,ex,ey:integer);
procedure mode(m:word);
procedure ellipse(x,y,r:word;mulx,muly:real);
procedure getPix(x,y:word;var col:longint);
procedure MoveTo(x,y:word);
procedure wherexy(x,y:word);
procedure sector(x,y,r,start,finish:word;draw:boolean);
function GetMaxColor:longint;
procedure Init(md:word);
function WhiteColor:longint;
implementation
uses supervga,crt,dos;
type
pchar=array[0..255] of array[0..15] of byte;
var oldchip:chips;
colour,bkcol,fill:longint;
coox,cooy:word;
info:modetype;
p:^pchar;
reg:registers;
const
mousepresent:boolean=false;
mousevisible:boolean=false;
x1m:integer=0;
y1m:integer=0;
x2m:integer=639;
y2m:integer=199;
speed2:word=128;
verrat:integer=8;
horrat:integer=8;
nbutton:byte=0;
{---------- Mouse Part ----------}
function ismouse:boolean;
var
p:pointer;
k,x,y:integer;
is:boolean;
begin
if nbutton=0 then
begin
getintvec($33,p);
is:= p<>nil;
if is then with reg do
begin
ax:=$3;
bx:=$ffff;
intr($33,reg);
is:= bx<>$FFFF;
end;
mousepresent:=is;
end;
ismouse:=mousepresent;
end;
function initmouse:boolean;
begin
with reg do
begin
ax:=0;
intr($33,reg);
mousepresent:= ax=$ffff;
nbutton:=bx;
end;
hidemouse;
mousescreen;
end;
procedure setsteptopixel(hor,ver:integer);
begin
if ismouse then with reg do
begin
ax:=$0f;
cx:= hor and $7fff;
dx:= ver and $7fff;
horrat:=cx;
verrat:=dx;
intr($33,reg);
end;
end;
procedure Getsteptopixel(var hor,ver:integer);
begin
if ismouse then
begin
hor:=horrat;
ver:=verrat;
end;
end;
procedure setdoblespeed(speed:word);
begin
if ismouse then with reg do
begin
ax:=$13;
dx:=speed;
speed2:=speed;
intr($33,reg);
end;
end;
function getdoblespeed:word;
begin
getdoblespeed:=speed2;
end;
procedure mousewherexy(var x,y:integer);
begin
if ismouse then with reg do
begin
ax:=$3;
intr($33,reg);
x:=cx;
y:=dx;
end
else
begin
x:=-1;
y:=-1;
end;
end;
function numbutton:byte;
begin
numbutton:=nbutton;
end;
procedure getmousestate(var butt,x,y:integer);
begin
if ismouse then with reg do
begin
ax:=$3;
intr($33,reg);
x:=cx;
y:=dx;
butt:=bx;
end
else
begin
x:=0;
y:=0;
butt:=0;
end;
end;
procedure mousebuttpressed(butt:integer;var stat,count,x,y:integer);
begin
if ismouse then with reg do
begin
ax:=$05;
bx:=butt;
intr($33,reg);
count:=bx;
x:=cx;
y:=dx;
stat:=bx;
end;
end;
procedure mousebuttrelased(butt:integer;var stat,count,x,y:integer);
begin
if ismouse then with reg do
begin
ax:=$06;
bx:=butt;
intr($33,reg);
count:=bx;
x:=cx;
y:=dx;
stat:=bx;
end;
end;
procedure mousewindow(x1,y1,x2,y2:integer);
begin
if ismouse then
begin
x1m:=x1;
y1m:=y1;
x2m:=x2;
y2m:=y2;
with reg do
begin
ax:=$7;
cx:=x1;
dx:=x2;
intr($33,reg);
ax:=$8;
cx:=y1;
dx:=y2;
intr($33,reg);
end;
end;
end;
procedure mousescreen;
begin
mousewindow(0,0,getmaxx,getmaxy);
end;
procedure showmouse;
begin
if ismouse and not mousevisible then
with reg do begin
ax:=$1;
intr($33,reg);
mousevisible:=true;
end;
end;
procedure hidemouse;
begin
if ismouse and mousevisible then
with reg do begin
ax:=$2;
intr($33,reg);
mousevisible:=true;
end;
end;
procedure mousegraphcur(var scrcur;x,y:byte);
begin
if ismouse then with reg do
begin
ax:=$9;
bx:=x;
cx:=y;
es:=seg(scrcur);
dx:=ofs(scrcur);
intr($33,reg);
end;
end;
{---------- Graphic Part ----------}
procedure rectangle(x1,y1,x2,y2:word;fill:boolean);
var i,j:word;
begin
outline(x1,y1,x1,y2);outline(x1,y1,x2,y1);outline(x2,y2,x1,y2);outline(x2,y2,x2,y1);
if fill then for i:=x1 to x2 do outline(i,y1,i,y2);
end;
procedure PrintChar(ch:char;x,y:word);
var
v:longint;
i,j,z,b:integer;
begin
for j:=0 to 15 do
begin
b:=p^[ord(ch)][j];
for i:=0 to 7 do
begin
if (b and 128)<>0 then v:=colour else v:=bkcol;
setpixel(x+i,y+j,v);
b:=b shl 1;
end;
end;
end;
function readstr(x,y:word):string;
var len,cur:word;
insflag:boolean;
chr:char;
col:longint;
const s:string='';
procedure setcur;
begin
outline(x+(cur-1)*8,y+15,x+cur*8,y+15);
if insflag then outline(x+(cur-1)*8,y+14,x+cur*8,y+14);
end;
procedure delcur;
begin
col:=colour;
colour:=bkcol;
outline(x+(cur-1)*8,y+15,x+cur*8,y+15);
if insflag then outline(x+(cur-1)*8,y+14,x+cur*8,y+14);
colour:=col;
end;
procedure Cursor;
var i:integer;
begin
while not keypressed do
begin
setcur;
for i:=1 to 10 do if not keypressed then delay(10);
delcur;
for i:=1 to 10 do if not keypressed then delay(10);
end;
end;
procedure prints;
var i:integer;
begin
for i:=1 to length(s) do
printchar(s[i],x+(i-1)*8,y);
printchar(' ',x+length(s)*8,y)
end;
procedure Home;
begin
cur:=1;
end;
procedure EndKey;
begin
cur:=len;
end;
procedure left;
begin
if cur<>1 then cur:=cur-1;
end;
procedure Right;
begin
if cur<>(len+1) then cur:=cur+1;
end;
procedure Inse;
begin
insflag:=not(insflag);
end;
procedure bs;
begin
if cur<>1 then begin
cur:=cur-1;
delete(s,cur,1);
len:=len-1;
end;
end;
procedure del;
begin
if cur<>(len+1) then begin
delete(s,cur,1);
len:=len-1;
end;
end;
procedure esc;
begin
s:='';
len:=0;
end;
procedure anychar;
begin
if cur=(len+1) then begin
s:=s+chr;
len:=len+1;
cur:=cur+1;
end
else if insflag then begin
insert(chr,s,cur);
len:=len+1;
cur:=cur+1;
end
else begin
s[cur]:=chr;
len:=len+1;
cur:=cur+1;
end;
end;
begin
cur:=1;
len:=0;
insflag:=true;
repeat
cursor;
prints;
chr:=readkey;
case chr of
#8:bs;
#27:esc;
#0:case ord(readkey) of
71:home;
75:left;
77:right;
79:endkey;
82:inse;
83:del;
else chr:=#0;
end;
else anychar;
end;
if ord(chr)>31 then prints;
until (chr=#13) or (chr=#27);
readstr:=s;
end;
function readint(x,y:word):longint;
var r:integer;
num:longint;
begin
val(readstr(x,y),num,r);
readint:=num;
end;
function readword(x,y:word):word;
var r:integer;
num:word;
begin
val(readstr(x,y),num,r);
readword:=num;
end;
function readreal(x,y:word):real;
var r:integer;
num:real;
begin
val(readstr(x,y),num,r);
readreal:=num;
end;
function readstring(x,y:word):string;
begin
readstring:=readstr(x,y);
end;
procedure putimage;
var image:array[1..MaxInt] of byte absolute buff;
i,f,x,y:word;
adr,color:longint;
begin
for i:=1 to xsz do
for f:=1 to ysz do
begin
x:=i;y:=f;
if xx then x:=xsz+1-i;
if yy then y:=ysz+1-f;
adr:=(x-1)*bb+1+y*bb*xsz;
color:=image[adr];
case bb of
2:color:=color+image[adr+1]*256;
3:begin
color:=color+image[adr+1]*256;
color:=color+image[adr+2]*65536;
end;
end;
setpixel(x1+i-1,y1+f-1,color);
end;
end;
procedure sector(x,y,r,start,finish:word;draw:boolean);
var xx,yy:integer;
i:real;
begin
if finish<start then start:=360-start;
i:=start;
repeat
xx:=round(r*cos(i))+x;
yy:=round(r*sin(i))+y;
if I=start then if draw then outline (x,y,xx,yy);
if xx>=0 then if xx<=pixels then if yy>=0 then if yy<=lins then setpixel(xx,yy,colour);
i:=i+0.05;
until i<finish;
if draw then outline (x,y,xx,yy);
moveto(xx,yy);
end;
function getmaxx:word;
begin
getmaxx:=pixels;
end;
function getmaxy:word;
begin
getmaxy:=lins;
end;
procedure vesa;
begin
if chip=__vesa then chip:=oldchip else chip:=__vesa;
end;
function modeinfo(m:word):boolean;
var i:word;
begin
for i:=1 to nomodes do
if modetbl[i].md=m then begin
pixels:=modetbl[i].xres;
lins:=modetbl[i].yres;
bytes:=modetbl[i].bytes;
memmode:=modetbl[i].memmode;
curmode:=m;
exit;
end;
for i:=1 to novgamodes do
if stdmodetbl[i].md=m then begin
pixels:=stdmodetbl[i].xres;
lins:=stdmodetbl[i].yres;
bytes:=stdmodetbl[i].bytes;
memmode:=stdmodetbl[i].memmode;
curmode:=m;
exit;
end;
vesamodeinfo(m);
end;
procedure loadmodes; {Load extended modes for this chip}
var
t:text;
s,pat:string;
md,x,xres,yres,err,mreq,byt:word;
function unhex(s:string):word;
var x:word;
begin
for x:=1 to 4 do
if s[x]>'9' then
s[x]:=chr(ord(s[x]) and $5f-7);
unhex:=(((word(ord(s[1])-48) shl 4
+ word(ord(s[2])-48)) shl 4
+ word(ord(s[3])-48)) shl 4
+ word(ord(s[4])-48));
end;
function mmode(s:string):mmods;
var x:mmods;
begin
for x:=_text to _p16m do
if s=mmodenames[x] then mmode:=x;
end;
begin
nomodes:=0;
pat:='['+header[chip]+']';
assign(t,'whatvga.lst');
reset(t);
s:=' ';
while (not eof(t)) and (s<>pat) do readln(t,s);
s:=' ';
readln(t,s);
while (s[1]<>'[') and (s<>'') do
begin
md:=unhex(copy(s,1,4));
memmode:=mmode(copy(s,6,4));
val(copy(s,11,5),xres,err);
val(copy(s,17,4),yres,err);
case memmode of
_text,_text4:bytes:=xres*2;
_pl2e, _herc,_cga2,_pl2:bytes:=xres shr 3;
_pk4,_pl4,_cga4:bytes:=xres shr 4;
_pl16,_pk16:bytes:=xres shr 1;
_p256:bytes:=xres;
_p32k,_p64k:bytes:=xres*2;
_p16m:bytes:=xres*3;
else
end;
case dactype of
_dac8:if memmode>_p256 then memmode:=_text;
_dac15:if memmode>_p32k then memmode:=_text;
_dac16:if memmode=_p16m then memmode:=_text;
_dacss24:if memmode=_p64k then memmode:=_text;
end;
val(copy(s,22,5),byt,err);
if (err=0) and (byt>0) then bytes:=byt;
if err<>0 then mreq:=(longint(bytes)*yres+1023) div 1024;
case memmode of
_pl16:bytes:=xres shr 3;
end;
if (memmode>_text4) and (mm>=mreq) then
begin
inc(nomodes);
modetbl[nomodes].xres:=xres;
modetbl[nomodes].yres:=yres;
modetbl[nomodes].md:=md;
modetbl[nomodes].bytes:=bytes;
modetbl[nomodes].memmode:=memmode;
end;
readln(t,s);
end;
close(t);
end;
procedure color(col:longint);
begin
colour:=col;
end;
procedure Bkcolor(col:longint);
begin
bkcol:=col;
end;
procedure Circle(x,y,r:word);
var y1,i1:integer;
i,max:real;
begin
i:=0;
max:=0.75*r;
repeat
y1:=trunc(sqrt(sqr(r)-sqr(i)));
i1:=trunc(i);
setpixel(x+i1,y1+y,colour);
setpixel(x-i1,y1+y,colour);
setpixel(x-i1,y-y1,colour);
setpixel(x+i1,y-y1,colour);
setpixel(x+y1,i1+y,colour);
setpixel(x-y1,i1+y,colour);
setpixel(x-y1,y-i1,colour);
setpixel(x+y1,y-i1,colour);
i:=i+0.25;
until I>max;
end;
procedure ellipse;
var y1,i1:integer;
i,max:real;
begin
i:=0;
max:=0.75*r;
repeat
y1:=trunc(sqrt(sqr(r)-sqr(i)));
i1:=trunc(i);
setpixel(round(x+i1*mulx),round(y+y1*muly),colour);
setpixel(round(x-i1*mulx),round(y+y1*muly),colour);
setpixel(round(x-i1*mulx),round(y-y1*muly),colour);
setpixel(round(x+i1*mulx),round(y-y1*muly),colour);
setpixel(round(x+y1*mulx),round(y+i1*muly),colour);
setpixel(round(x-y1*mulx),round(y+i1*muly),colour);
setpixel(round(x-y1*mulx),round(y-i1*muly),colour);
setpixel(round(x+y1*mulx),round(y-i1*muly),colour);
i:=i+0.25;
until I>max;
end;
procedure Done;
begin
rp.al:=7;
vio(0);
end;
procedure GetMaxXY(x,y:word);
begin
x:=pixels;
y:=lins;
end;
procedure Init(md:word);
begin
findvideo;
if CHIP=__none then begin
Result:=-3;
exit;
end;
oldchip:=chip;
loadmodes;
mode(md);
colour:=whitecolor;
bkcol:=0;
rp.bh:=6;
vio($1130);
p:=ptr(rp.es,rp.bp);
end;
function GetMaxColor:longint;
begin
GetMaxColor:=modecols[memmode]-1;
case memmode of
_text:GetMaxColor:=15;
_text2:getmaxcolor:=1;
_text4:getmaxcolor:=3;
end;
end;
procedure WhereXY(x,y:word);
begin
x:=coox;y:=cooy;
end;
procedure lineto;
begin
outline(coox,cooy,x,y);
end;
procedure moveto;
begin
coox:=x;
cooy:=y;
end;
procedure mode(m:word);
begin
modeinfo(m);
if setmode(m) then result:=0
else result:=-1;
end;
procedure outLine(stx,sty,ex,ey:integer);
var x,y,d,mx,my:integer;
begin
coox:=ex;cooy:=ey;
if sty>ey then
begin
x:=stx;stx:=ex;ex:=x;
x:=sty;sty:=ey;ey:=x;
end;
y:=0;
mx:=abs(ex-stx);
my:=ey-sty;
d:=0;
repeat
y:=(y+1) and 255;
setpixel(stx,sty,colour);
if abs(d+mx)<abs(d-my) then
begin
inc(sty);
d:=d+mx;
end
else begin
d:=d-my;
if ex>stx then inc(stx)
else dec(stx);
end;
until (stx=ex) and (sty=ey);
end;
procedure ClrScr;
var i,f:word;
begin
for i:=0 to getmaxx do
for f:=0 to getmaxy do
setpixel(f,i,colour);
end;
procedure TextWrite(x,y:word;txt:string);
var
z:integer;
begin
for z:=1 to length(txt) do if x+(z-1)*8<=getmaxx then printchar(txt[z],x+(z-1)*8,y);
end;
function WhiteColor:longint;
var col:longint;
begin
case memmode of
_cga2,_pl2e,
_pl2:col:=1;
_cga4,_pk4
,_pl4:col:=3;
_pk16,_pl16,
_p256:col:=15;
_p32k:col:=$7fff;
_p64k:col:=$ffff;
_p16m:col:=$ffffff;
else
end;
whitecolor:=col;
end;
function loword(a:longint):word;
begin
loword:=a mod 65536;
end;
procedure GetPix(x,y:word;var col:longint);
var l:longint;
m,z:word;
b:byte;
begin
case memmode of
_cga2:begin
b:=mem[$b800:((y div 2)*80+ord(odd(y))*$2000+x div 8)];
col:=0;
if b<>0 then col:=1;
end;
_p256:begin
l:=y*bytes+x;
setbank(l shr 16);
col:=mem[vseg:loword(l)];
end;
_p32k,_p64k:
begin
l:=y*bytes+(x shl 1);
setbank(l shr 16);
col:=memw[vseg:loword(l)];
end;
_p16m:begin
l:=y*bytes+(x*3);
z:=word(l);
m:=l shr 16;
setbank(m);
if z<$fffe then move(mem[vseg:z],col,3)
else begin
col:=mem[vseg:z];
if z=$ffff then setbank(m+1);
col:=col+mem[vseg:z+1] shr 8;
if z=$fffe then setbank(m+1);
col:=col+mem[vseg:z+2] shr 16;
end;
end;
else ;
end;
end;
procedure SetPixel(x,y:word;col:longint);
const
msk:array[0..7] of byte=(128,64,32,16,8,4,2,1);
plane :array[0..1] of byte=(5,10);
plane4:array[0..3] of byte=(1,2,4,8);
mscga4:array[0..3] of byte=($3f,$cf,$f3,$fc);
shcga4:array[0..3] of byte=(6,4,2,0);
var l:longint;
m,z:word;
begin
case memmode of
_cga2:begin
z:=(y shr 1)*bytes+(x shr 3);
if odd(y) then inc(z,8192);
mem[$b800:z]:=(mem[$b800:z] and (255 xor msk[x and 7]))
or ((col and 1) shl (7-(x and 7)));
end;
_cga4:begin
z:=(y shr 1)*bytes+(x shr 2);
if odd(y) then inc(z,8192);
mem[$b800:z]:=(mem[$b800:z] and mscga4[x and 3])
or (col and 3) shl shcga4[x and 3];
end;
_pl2:begin
l:=y*bytes+(x shr 3);
wrinx($3ce,3,0);
wrinx($3ce,5,2);
wrinx($3c4,2,1);
wrinx($3ce,8,msk[x and 7]);
setbank(l shr 16);
z:=mem[vseg:word(l)];
mem[vseg:word(l)]:=col;
end;
_pl2e:begin
l:=y*128+(x shr 3);
modinx($3ce,5,3,0);
wrinx($3c4,2,15);
wrinx($3ce,0,col*3);
wrinx($3ce,1,3);
wrinx($3ce,8,msk[x and 7]);
z:=mem[vseg:word(l)];
mem[vseg:word(l)]:=0;
end;
_pl4:begin
l:=y*bytes+(x shr 4);
wrinx($3ce,3,0);
wrinx($3ce,5,2);
wrinx($3c4,2,plane[(x shr 3) and 1]);
wrinx($3ce,8,msk[x and 7]);
setbank(l shr 16);
z:=mem[vseg:word(l)];
mem[vseg:word(l)]:=col;
end;
_pk4:begin
l:=y*bytes+(x shr 2);
setbank(l shr 16);
z:=mem[vseg:word(l)] and mscga4[x and 3];
mem[vseg:word(l)]:=z or (col shl shcga4[x and 3]);
end;
_pl16:begin
l:=y*bytes+(x shr 3);
wrinx($3ce,3,0);
wrinx($3ce,5,2);
wrinx($3ce,8,msk[x and 7]);
setbank(l shr 16);
z:=mem[vseg:word(l)];
mem[vseg:word(l)]:=col;
end;
_pk16:begin
l:=y*bytes+(x shr 1);
setbank(l shr 16);
z:=mem[vseg:word(l)];
if odd(x) then z:=z and $f+(col shl 4)
else z:=z and $f0+col;
mem[vseg:word(l)]:=z;
end;
_p256:begin
l:=y*bytes+x;
setbank(l shr 16);
mem[vseg:word(l)]:=col;
end;
_p32k,_p64k:
begin
l:=y*bytes+(x shl 1);
setbank(l shr 16);
memw[vseg:word(l)]:=col;
end;
_p16m:begin
l:=y*bytes+(x*3);
z:=word(l);
m:=l shr 16;
setbank(m);
if z<$fffe then move(col,mem[vseg:z],3)
else begin
mem[vseg:z]:=lo(col);
if z=$ffff then setbank(m+1);
mem[vseg:z+1]:=lo(col shr 8);
if z=$fffe then setbank(m+1);
mem[vseg:z+2]:=col shr 16;
end;
end;
else ;
end;
end;
end. |
unit MFichas.Model.Entidade.CONFIGURACOES;
interface
uses
DB,
Classes,
SysUtils,
Generics.Collections,
/// orm
ormbr.types.blob,
ormbr.types.lazy,
ormbr.types.mapping,
ormbr.types.nullable,
ormbr.mapping.classes,
ormbr.mapping.register,
ormbr.mapping.attributes;
type
[Entity]
[Table('CONFIGURACOES', '')]
[PrimaryKey('GUUID', NotInc, NoSort, False, 'Chave primária')]
TCONFIGURACOES = class
private
{ Private declarations }
FGUUID: String;
FIMPRESSORA: String;
FNOMEDISPOSITIVO: String;
FGUUIDDISPOSITIVO: TBlob;
FDATACADASTRO: TDateTime;
FDATAALTERACAO: TDateTime;
FDATALIBERACAO: TDateTime;
function GetDATAALTERACAO: TDateTime;
function GetDATACADASTRO: TDateTime;
function GetGUUID: String;
public
{ Public declarations }
[Column('GUUID', ftString, 38)]
[Dictionary('GUUID', 'Mensagem de validação', '', '', '', taLeftJustify)]
property GUUID: String read GetGUUID write FGUUID;
[Column('IMPRESSORA', ftString, 128)]
[Dictionary('IMPRESSORA', 'Mensagem de validação', '', '', '', taLeftJustify)]
property IMPRESSORA: String read FIMPRESSORA write FIMPRESSORA;
[Column('NOMEDISPOSITIVO', ftString, 128)]
[Dictionary('NOMEDISPOSITIVO', 'Mensagem de validação', '', '', '', taLeftJustify)]
property NOMEDISPOSITIVO: String read FNOMEDISPOSITIVO write FNOMEDISPOSITIVO;
[Column('GUUIDDISPOSITIVO', ftBlob)]
[Dictionary('GUUIDDISPOSITIVO', 'Mensagem de validação', '', '', '', taLeftJustify)]
property GUUIDDISPOSITIVO: TBlob read FGUUIDDISPOSITIVO write FGUUIDDISPOSITIVO;
[Column('DATACADASTRO', ftDateTime)]
[Dictionary('DATACADASTRO', 'Mensagem de validação', '', '', '', taCenter)]
property DATACADASTRO: TDateTime read GetDATACADASTRO write FDATACADASTRO;
[Column('DATAALTERACAO', ftDateTime)]
[Dictionary('DATAALTERACAO', 'Mensagem de validação', '', '', '', taCenter)]
property DATAALTERACAO: TDateTime read GetDATAALTERACAO write FDATAALTERACAO;
[Column('DATALIBERACAO', ftDateTime)]
[Dictionary('DATALIBERACAO', 'Mensagem de validação', '', '', '', taCenter)]
property DATALIBERACAO: TDateTime read FDATALIBERACAO write FDATALIBERACAO;
end;
implementation
{ TCONFIGURACOES }
function TCONFIGURACOES.GetDATAALTERACAO: TDateTime;
begin
FDATAALTERACAO := Now;
Result := FDATAALTERACAO;
end;
function TCONFIGURACOES.GetDATACADASTRO: TDateTime;
begin
if FDATACADASTRO = StrToDateTime('30/12/1899') then
FDATACADASTRO := Now;
Result := FDATACADASTRO;
end;
function TCONFIGURACOES.GetGUUID: String;
begin
if FGUUID.IsEmpty then
FGUUID := TGUID.NewGuid.ToString;
Result := FGUUID;
end;
initialization
TRegisterClass.RegisterEntity(TCONFIGURACOES)
end.
|
{
Класс хранилища
}
unit UAccessBase;
interface
uses Classes, VKDBFDataSet, VKDBFNTX, VKDBFIndex, VKDBFSorters;
type
TSAVAccessBase = class(TObject)
private
FStoragePath: string;
FJournalsDir: string;
FJournalsPath: string;
FUsersDir: string;
FGroupsDir: string;
FADGroupsDir: string;
FDomainsDir: string;
FTableUsers: TVKDBFNTX;
FTableDomains: TVKDBFNTX;
FTableGroups: TVKDBFNTX;
FTableADGroups: TVKDBFNTX;
FCaption: string;
procedure SetStoragePath(const Value: string);
function StorageCheck: Boolean;
function GetFullPath(const aDir: string): string;
procedure SetJournalsDir(const Value: string);
procedure SetGroupsDir(const Value: string);
procedure SetUsersDir(const Value: string);
function CreateTableUsers: Boolean;
function CreateTableGroups: Boolean;
//function CreateTableADGroups: Boolean;
function CreateTableDomains: Boolean;
function CreateTableOrgUnits: Boolean;
function CreateTableLinks: Boolean;
function CreateTableSupport: Boolean;
function CreateTableExtension: Boolean;
function CreateTableActions: Boolean;
procedure SetDomainsDir(const Value: string);
procedure GetListByName(List: TStrings; const TableName: string);
procedure SetCaption(const Value: string);
procedure SetTableDomains(const Value: TVKDBFNTX);
procedure SetTableGroups(const Value: TVKDBFNTX);
procedure SetTableUsers(const Value: TVKDBFNTX);
procedure SetADGroupsDir(const Value: string);
procedure SetTableADGroups(const Value: TVKDBFNTX);
protected
public
property StoragePath: string read FStoragePath write SetStoragePath;
property JournalsDir: string read FJournalsDir write SetJournalsDir;
property JournalsPath: string read FJournalsPath;
property UsersDir: string read FUsersDir write SetUsersDir;
property GroupsDir: string read FGroupsDir write SetGroupsDir;
property ADGroupsDir: string read FADGroupsDir write SetADGroupsDir;
property DomainsDir: string read FDomainsDir write SetDomainsDir;
property Caption: string read FCaption write SetCaption;
property TableUsers: TVKDBFNTX read FTableUsers write SetTableUsers;
property TableDomains: TVKDBFNTX read FTableDomains write SetTableDomains;
property TableGroups: TVKDBFNTX read FTableGroups write SetTableGroups;
property TableADGroups: TVKDBFNTX read FTableADGroups write
SetTableADGroups;
constructor Create; overload;
constructor Create(const aPath: string; const bCanCreate: Boolean = False;
const aJournals: string = ''; const aDomains: string = ''; const aGroups:
string = ''; const aUsers: string = ''; const aADGroups: string = '');
overload;
function CreateTableADGroups: Boolean;
function CreateStorage: Boolean;
function IndexCreate(const aFullTableName, aFullIndexName, aIndexKey:
string; const aDesc: boolean = False):
Boolean;
function CheckAndCreateIndex: boolean;
procedure GetGroups(List: TStrings);
procedure GetUsers(List: TStrings);
procedure GetDomains(List: TStrings);
procedure SaveToFile(const aFileName: string);
procedure LoadFromFile(const aFileName: string);
procedure DirectoryInit;
end;
implementation
uses SAVLib, SAVLib_DBF, KoaUtils, SysUtils, UAccessConstant;
{ TSAVAccessBase }
constructor TSAVAccessBase.Create;
begin
FJournalsDir := csDefJournalDir;
FJournalsPath := FJournalsDir + PathDelim;
FGroupsDir := csDefGroupDir;
FDomainsDir := csDefDomainDir;
FUsersDir := csDefUserDir;
FADGroupsDir := csDefADGroupDir;
FCaption := '';
end;
constructor TSAVAccessBase.Create(const aPath: string; const bCanCreate: Boolean
= False; const aJournals: string = ''; const aDomains: string = ''; const
aGroups: string = ''; const aUsers: string = ''; const aADGroups: string =
'');
var
s: string;
begin
Create;
FStoragePath := aPath;
s := IncludeTrailingPathDelimiter(FStoragePath);
if aJournals <> '' then
FJournalsDir := ExcludeTrailingPathDelimiter(aJournals)
else
FJournalsDir := s + FJournalsDir;
FJournalsPath := IncludeTrailingPathDelimiter(FJournalsDir);
if aGroups <> '' then
FGroupsDir := ExcludeTrailingPathDelimiter(aGroups)
else
FGroupsDir := s + FGroupsDir;
if aDomains <> '' then
FDomainsDir := ExcludeTrailingPathDelimiter(aDomains)
else
FDomainsDir := s + FDomainsDir;
if aUsers <> '' then
FUsersDir := ExcludeTrailingPathDelimiter(aUsers)
else
FUsersDir := s + FUsersDir;
if aADGroups <> '' then
FADGroupsDir := ExcludeTrailingPathDelimiter(aADGroups)
else
FADGroupsDir := s + FADGroupsDir;
if bCanCreate then
if not (CreateStorage) then
raise Exception.Create('Ошибка при создании хранилища ' + FStoragePath);
end;
procedure TSAVAccessBase.SetStoragePath(const Value: string);
begin
FStoragePath := Value;
end;
function TSAVAccessBase.GetFullPath(const aDir: string): string;
begin
if (aDir[2] = ':') or (aDir[2] = '\') or (aDir[2] = '/') then
Result := aDir
else
Result := IncludeTrailingPathDelimiter(FStoragePath) + aDir;
end;
procedure TSAVAccessBase.SetGroupsDir(const Value: string);
begin
FGroupsDir := GetFullPath(Value);
end;
procedure TSAVAccessBase.SetJournalsDir(const Value: string);
begin
FJournalsDir := GetFullPath(Value);
FStoragePath := IncludeTrailingPathDelimiter(FJournalsDir);
end;
procedure TSAVAccessBase.SetUsersDir(const Value: string);
begin
FUsersDir := GetFullPath(Value);
end;
function TSAVAccessBase.StorageCheck: Boolean;
begin
Result := (DirectoryExists(FStoragePath)) and (DirectoryExists(FUsersDir)) and
(DirectoryExists(FGroupsDir)) and (DirectoryExists(FJournalsDir)) and
(DirectoryExists(FDomainsDir)) and (DirectoryExists(FADGroupsDir)) and
(FileExists(IncludeTrailingPathDelimiter(FJournalsDir) + csTableDomains));
end;
function TSAVAccessBase.CreateStorage: Boolean;
begin
Result := StorageCheck;
if Result = False then
begin
Result := (ForceDirectories(ExcludeTrailingPathDelimiter(FStoragePath))) and
(ForceDirectories(ExcludeTrailingPathDelimiter(FJournalsDir))) and
(ForceDirectories(ExcludeTrailingPathDelimiter(FUsersDir))) and
(ForceDirectories(ExcludeTrailingPathDelimiter(FGroupsDir))) and
(ForceDirectories(ExcludeTrailingPathDelimiter(FDomainsDir))) and
(ForceDirectories(ExcludeTrailingPathDelimiter(FADGroupsDir)));
if Result then
Result := CreateTableDomains and CreateTableUsers and CreateTableGroups
and CreateTableADGroups and CreateTableOrgUnits and CreateTableLinks and
CreateTableActions and CreateTableExtension and CreateTableSupport;
end;
if Result then
Result := CheckAndCreateIndex;
if Result then
begin
if Assigned(FTableDomains) then
begin
FTableDomains.Close;
ClearStructDBF(FTableDomains);
InitOpenDBF(FTableDomains, FJournalsPath + csTableDomains, 66);
with FTableDomains.Indexes.Add as TVKNTXIndex do
NTXFileName := FJournalsPath + csIndexDomainName;
with FTableDomains.Indexes.Add as TVKNTXIndex do
NTXFileName := FJournalsPath + csIndexDomainVersion;
FTableDomains.Open;
end;
if Assigned(FTableUsers) then
begin
FTableUsers.Close;
ClearStructDBF(FTableUsers);
InitOpenDBF(FTableUsers, FJournalsPath + csTableUsers, 66);
with FTableUsers.Indexes.Add as TVKNTXIndex do
NTXFileName := FJournalsPath + csIndexUserName;
with FTableUsers.Indexes.Add as TVKNTXIndex do
NTXFileName := FJournalsPath + csIndexUserVersion;
FTableUsers.Open;
end;
if Assigned(FTableGroups) then
begin
FTableGroups.Close;
ClearStructDBF(FTableGroups);
InitOpenDBF(FTableGroups, FJournalsPath + csTableGroups, 66);
with FTableGroups.Indexes.Add as TVKNTXIndex do
NTXFileName := FJournalsPath + csIndexGroupName;
with FTableGroups.Indexes.Add as TVKNTXIndex do
NTXFileName := FJournalsPath + csIndexGroupVersion;
FTableGroups.Open;
end;
if Assigned(FTableADGroups) then
begin
FTableADGroups.Close;
ClearStructDBF(FTableADGroups);
InitOpenDBF(FTableADGroups, FJournalsPath + csTableADGroups, 66);
with FTableADGroups.Indexes.Add as TVKNTXIndex do
NTXFileName := FJournalsPath + csIndexADGroupName;
with FTableADGroups.Indexes.Add as TVKNTXIndex do
NTXFileName := FJournalsPath + csIndexADGroupVersion;
FTableADGroups.Open;
end;
end;
end;
function TSAVAccessBase.CreateTableDomains: Boolean;
var
table1: TVKDBFNTX;
begin
table1 := TVKDBFNTX.Create(nil);
table1.DBFFileName := FJournalsPath + csTableDomains;
table1.OEM := True;
table1.AccessMode.AccessMode := 66;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldID;
field_type := 'N';
len := 6;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldSID;
field_type := 'C';
len := 50;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldVersion;
field_type := 'C';
len := 30;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldCaption;
field_type := 'C';
len := 50;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldIni;
field_type := 'C';
len := 250;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldPath;
field_type := 'C';
len := 250;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldDescription;
field_type := 'C';
len := 250;
end;
Result := True;
try
table1.CreateTable;
except
Result := False;
end;
FreeAndNil(table1);
end;
function TSAVAccessBase.CreateTableGroups: Boolean;
var
table1: TVKDBFNTX;
begin
table1 := TVKDBFNTX.Create(nil);
table1.AccessMode.AccessMode := 66;
table1.OEM := True;
table1.DBFFileName := FJournalsPath + csTableGroups;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldID;
field_type := 'N';
len := 6;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldSID;
field_type := 'C';
len := 50;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldVersion;
field_type := 'C';
len := 30;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldCaption;
field_type := 'C';
len := 50;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldDescription;
field_type := 'C';
len := 200;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldPrority;
field_type := 'N';
len := 6;
end;
Result := True;
try
table1.CreateTable;
except
Result := False;
end;
FreeAndNil(table1);
end;
function TSAVAccessBase.CreateTableLinks: Boolean;
var
table1: TVKDBFNTX;
begin
table1 := TVKDBFNTX.Create(nil);
table1.AccessMode.AccessMode := 66;
table1.OEM := True;
table1.DBFFileName := FJournalsPath + csTableOULink;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldParent;
field_type := 'N';
len := 6;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldChild;
field_type := 'N';
len := 6;
end;
Result := True;
try
table1.CreateTable;
except
Result := False;
end;
FreeAndNil(table1);
end;
function TSAVAccessBase.CreateTableOrgUnits: Boolean;
begin
Result := False;
end;
function TSAVAccessBase.CreateTableUsers: Boolean;
var
table1: TVKDBFNTX;
begin
table1 := TVKDBFNTX.Create(nil);
table1.AccessMode.AccessMode := 66;
table1.OEM := True;
table1.DBFFileName := FJournalsPath + csTableUsers;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldID;
field_type := 'N';
len := 6;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldCaption;
field_type := 'C';
len := 50;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldSID;
field_type := 'C';
len := 50;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldVersion;
field_type := 'C';
len := 30;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldDomain;
field_type := 'C';
len := 50;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldDescription;
field_type := 'C';
len := 200;
end;
Result := True;
try
table1.CreateTable;
except
Result := False;
end;
FreeAndNil(table1);
end;
procedure TSAVAccessBase.SetDomainsDir(const Value: string);
begin
FDomainsDir := GetFullPath(Value);
end;
procedure TSAVAccessBase.GetListByName(List: TStrings;
const TableName: string);
var
table1: TVKDBFNTX;
begin
table1 := TVKDBFNTX.Create(nil);
table1.AccessMode.AccessMode := 64;
table1.OEM := True;
table1.DBFFileName := FJournalsPath + TableName;
table1.Open;
while not (table1.Eof) do
begin
List.add(table1.fieldbyname(csFieldCaption).AsString);
table1.Next;
end;
table1.Close;
FreeAndNil(table1);
end;
procedure TSAVAccessBase.GetGroups(List: TStrings);
begin
GetListByName(List, csTableGroups);
end;
procedure TSAVAccessBase.GetUsers(List: TStrings);
begin
GetListByName(List, csTableUsers);
end;
procedure TSAVAccessBase.GetDomains(List: TStrings);
begin
GetListByName(List, csTableDomains);
end;
procedure TSAVAccessBase.LoadFromFile(const aFileName: string);
var
list: TStringList;
begin
if FileExists(aFileName) then
begin
list := TStringList.Create;
list.LoadFromFile(aFileName);
FCaption := list.Values['caption'];
if FCaption = '' then
FCaption := ExtractFileName(aFileName);
FStoragePath := list.Values['base'];
FUsersDir := list.Values['users'];
FJournalsDir := list.Values['journals'];
FJournalsPath := IncludeTrailingPathDelimiter(FJournalsDir);
FGroupsDir := list.Values['groups'];
FADGroupsDir := list.Values['adgroups'];
FDomainsDir := list.Values['domains'];
FreeAndNil(list);
CreateStorage;
end
else
raise Exception.Create('Нет доступа к файлу ' + aFileName);
end;
procedure TSAVAccessBase.SaveToFile(const aFileName: string);
var
list: TStringList;
begin
list := TStringList.Create;
list.Add('caption=' + FCaption);
list.Add('base=' + FStoragePath);
list.Add('journals=' + FJournalsDir);
list.Add('domains=' + FDomainsDir);
list.Add('groups=' + FGroupsDir);
list.Add('adgroups=' + FADGroupsDir);
list.Add('users=' + FUsersDir);
try
list.SaveToFile(aFileName);
except
FreeAndNil(list);
raise Exception.Create('Ошибка при сохранении ' + aFileName + ': ' +
SysErrorMessage(GetLastError));
end;
if Assigned(list) then
FreeAndNil(list);
end;
procedure TSAVAccessBase.SetCaption(const Value: string);
begin
FCaption := Value;
end;
procedure TSAVAccessBase.SetTableDomains(const Value: TVKDBFNTX);
begin
FTableDomains := Value;
end;
procedure TSAVAccessBase.SetTableGroups(const Value: TVKDBFNTX);
begin
FTableGroups := Value;
end;
procedure TSAVAccessBase.SetTableUsers(const Value: TVKDBFNTX);
begin
FTableUsers := Value;
end;
function TSAVAccessBase.CreateTableActions: Boolean;
var
table1: TVKDBFNTX;
begin
table1 := TVKDBFNTX.Create(nil);
table1.AccessMode.AccessMode := 66;
table1.OEM := True;
table1.DBFFileName := FJournalsPath + csTableAction;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldFID;
field_type := 'N';
len := 6;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldAction;
field_type := 'N';
len := 3;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldDescription;
field_type := 'C';
len := 150;
end;
Result := True;
try
table1.CreateTable;
except
Result := False;
end;
FreeAndNil(table1);
end;
function TSAVAccessBase.CreateTableExtension: Boolean;
var
table1: TVKDBFNTX;
begin
table1 := TVKDBFNTX.Create(nil);
table1.AccessMode.AccessMode := 66;
table1.OEM := True;
table1.DBFFileName := FJournalsPath + csTableExt;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldID;
field_type := 'N';
len := 6;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldExt;
field_type := 'C';
len := 10;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldType;
field_type := 'C';
len := 1;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldDescription;
field_type := 'C';
len := 150;
end;
Result := True;
try
table1.CreateTable;
except
Result := False;
end;
FreeAndNil(table1);
end;
function TSAVAccessBase.CreateTableSupport: Boolean;
var
table1: TVKDBFNTX;
begin
table1 := TVKDBFNTX.Create(nil);
table1.AccessMode.AccessMode := 66;
table1.OEM := True;
table1.DBFFileName := FJournalsPath + csTableSupport;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldID;
field_type := 'N';
len := 8;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldAction;
field_type := 'C';
len := 250;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldDescription;
field_type := 'C';
len := 100;
end;
Result := True;
try
table1.CreateTable;
except
Result := False;
end;
FreeAndNil(table1);
end;
function TSAVAccessBase.CreateTableADGroups: Boolean;
var
table1: TVKDBFNTX;
begin
table1 := TVKDBFNTX.Create(nil);
table1.AccessMode.AccessMode := 66;
table1.OEM := True;
table1.DBFFileName := FJournalsPath + csTableADGroups;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldID;
field_type := 'N';
len := 6;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldSID;
field_type := 'C';
len := 50;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldVersion;
field_type := 'C';
len := 30;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldCaption;
field_type := 'C';
len := 50;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldDescription;
field_type := 'C';
len := 200;
end;
with table1.DBFFieldDefs.Add as TVKDBFFieldDef do
begin
Name := csFieldPrority;
field_type := 'N';
len := 6;
end;
Result := True;
try
table1.CreateTable;
except
Result := False;
end;
FreeAndNil(table1);
end;
procedure TSAVAccessBase.SetADGroupsDir(const Value: string);
begin
FADGroupsDir := GetFullPath(Value);
end;
procedure TSAVAccessBase.SetTableADGroups(const Value: TVKDBFNTX);
begin
FTableADGroups := Value;
end;
procedure TSAVAccessBase.DirectoryInit;
var
s: string;
begin
s := IncludeTrailingPathDelimiter(FStoragePath);
if FJournalsDir = '' then
FJournalsDir := s + FJournalsDir;
FJournalsPath := IncludeTrailingPathDelimiter(FJournalsDir);
if FGroupsDir = '' then
FGroupsDir := s + FGroupsDir;
if FADGroupsDir = '' then
FADGroupsDir := s + FADGroupsDir;
if FDomainsDir = '' then
FDomainsDir := s + FDomainsDir;
if FUsersDir = '' then
FUsersDir := s + FUsersDir;
end;
function TSAVAccessBase.IndexCreate(const aFullTableName, aFullIndexName,
aIndexKey: string; const aDesc: boolean = False): Boolean;
var
table1: TVKDBFNTX;
begin
table1 := TVKDBFNTX.Create(nil);
table1.DBFFileName := aFullTableName;
table1.AccessMode.AccessMode := 66;
table1.oem := True;
Result := True;
try
table1.Open;
with table1.Indexes.Add as TVKNTXIndex do
begin
NTXFileName := aFullIndexName;
ClipperVer := v501;
KeyExpresion := aIndexKey;
Desc := aDesc;
CreateIndex(True);
end;
table1.Close;
except
Result := False;
end;
FreeAndNil(table1);
end;
function TSAVAccessBase.CheckAndCreateIndex: boolean;
function ChkAndCrtIndx(const aTableName, aIndexName, aIndexKey: string; const
aDesc: boolean = False):
boolean;
var
s: string;
begin
s := FJournalsPath + aIndexName;
Result := FileExists(s);
if not Result then
Result := IndexCreate(FJournalsPath + aTableName, s, aIndexKey,aDesc);
end;
begin
Result := ChkAndCrtIndx(csTableDomains, csIndexDomainVersion, csFieldVersion,
True)
and ChkAndCrtIndx(csTableDomains, csIndexDomainName, csFieldCaption)
and ChkAndCrtIndx(csTableADGroups, csIndexADGroupVersion, csFieldVersion,
True)
and ChkAndCrtIndx(csTableADGroups, csIndexADGroupName, csFieldCaption)
and ChkAndCrtIndx(csTableGroups, csIndexGroupVersion, csFieldVersion, True)
and ChkAndCrtIndx(csTableGroups, csIndexGroupName, csFieldCaption)
and ChkAndCrtIndx(csTableUsers, csIndexUserVersion, csFieldVersion, True)
and ChkAndCrtIndx(csTableUsers, csIndexUserName, csFieldCaption)
and ChkAndCrtIndx(csTableExt,csIndexExtensExt,csFieldExt);
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpAsn1Generator;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
ClpIProxiedInterface,
ClpIAsn1Generator;
type
TAsn1Generator = class abstract(TInterfacedObject, IAsn1Generator)
strict private
var
F_out: TStream;
function GetOut: TStream; inline;
strict protected
constructor Create(outStream: TStream);
property &Out: TStream read GetOut;
public
procedure AddObject(const obj: IAsn1Encodable); virtual; abstract;
function GetRawOutputStream(): TStream; virtual; abstract;
procedure Close(); virtual; abstract;
end;
implementation
{ TAsn1Generator }
constructor TAsn1Generator.Create(outStream: TStream);
begin
F_out := outStream;
end;
function TAsn1Generator.GetOut: TStream;
begin
result := F_out;
end;
end.
|
unit MatrixCircuits;
interface
uses
Collection,Circuits, LargeMatrix, Windows, BackupInterfaces, ReachMatrix;
type
TMatrixCircuitMap =
class( TCircuitMap )
private
fMatrix : TIntegerLargeMatrix;
fModified : boolean;
public
destructor Destroy; override;
public
procedure CreateSegment( x1, y1, x2, y2 : integer; OwnerId : TOwnerId; out ErrorCode : TCircuitErrorCode ); override;
procedure BreakSegmentInPoint( x, y : integer; OwnerId : TOwnerId; out ErrorCode : TCircuitErrorCode ); override;
procedure NearestCircuitsToArea( Area : TRect; tolerance : integer; var Circuits : TCollection; out ErrorCode : TCircuitErrorCode ); override;
function AreasAreConnected( Area1, Area2 : TRect; tolerance : integer; out ErrorCode : TCircuitErrorCode ) : boolean; override;
function AreaIsClear( Area : TRect ) : boolean; override;
public
procedure Render(Notify : TOnRenderRoadBlock); override;
procedure SetSize( aXsize, aYsize : integer ); override;
protected
procedure LoadFromBackup( Reader : IBackupReader ); override;
procedure StoreToBackup ( Writer : IBackupWriter ); override;
public // for debugging only
property Matrix : TIntegerLargeMatrix read fMatrix;
public
function GetReachMatrix(x1, y1, x2, y2, tolerance : integer) : TReachMatrix; override;
end;
procedure RegisterBackup;
implementation
uses
SysUtils, Logs, CircuitEquivalences;
destructor TMatrixCircuitMap.Destroy;
begin
fMatrix.Free;
inherited;
end;
procedure TMatrixCircuitMap.CreateSegment( x1, y1, x2, y2 : integer; OwnerId : TOwnerId; out ErrorCode : TCircuitErrorCode );
begin
Lock;
try
inherited;
fModified := true;
finally
Unlock;
end;
end;
procedure TMatrixCircuitMap.BreakSegmentInPoint( x, y : integer; OwnerId : TOwnerId; out ErrorCode : TCircuitErrorCode );
begin
Lock;
try
inherited;
fModified := true;
finally
Unlock;
end;
end;
procedure TMatrixCircuitMap.NearestCircuitsToArea( Area : TRect; tolerance : integer; var Circuits : TCollection; out ErrorCode : TCircuitErrorCode );
var
i, j : integer;
Circuit : TCircuit;
begin
Lock;
try
if false // >> fModified
then inherited
else
try
InflateRect( Area, tolerance, tolerance );
for i := Area.Top to Area.Bottom do
for j := Area.Left to Area.Right do
begin
Circuit := TCircuit(fMatrix[i,j]);
if (Circuit <> nil) and (Circuits.IndexOf( Circuit ) = NoIndex)
then Circuits.Insert( Circuit );
end;
except
ErrorCode := CIRCUIT_ERROR_Unknown;
end;
finally
Unlock;
end;
end;
function TMatrixCircuitMap.AreasAreConnected( Area1, Area2 : TRect; tolerance : integer; out ErrorCode : TCircuitErrorCode ) : boolean;
begin
result := inherited AreasAreConnected( Area1, Area2, tolerance, ErrorCode );
end;
function TMatrixCircuitMap.AreaIsClear( Area : TRect ) : boolean;
var
i, j : integer;
begin
Lock;
try
if false // fModified
then result := inherited AreaIsClear( Area )
else
begin
result := true;
i := Area.Top;
j := Area.Left;
while (i <= Area.Bottom) and result do
begin
while (j <= Area.Right) and result do
begin
result := fMatrix[i,j] = 0;
inc( j );
end;
inc( i );
end;
end;
finally
Unlock;
end;
end;
procedure TMatrixCircuitMap.Render(Notify : TOnRenderRoadBlock);
var
Segs : TCollection;
Segment : TSegment;
i, x, y : integer;
Circuit : TCircuit;
Eqs : TEquivalences;
itr : integer;
begin
Lock;
try
inherited;
try
Segs := TCollection.Create( 0, rkUse );
try
Eqs := TEquivalences.Create;
try
itr := 0;
repeat
Eqs.Clear;
fMatrix.Fill( 0 );
FindSegsInArea( 0, 0, fMatrix.Cols, fMatrix.Rows, Segs );
for i := 0 to pred(Segs.Count) do
begin
Segment := TSegment(Segs[i]);
for y := Segment.NodeA.y to Segment.NodeB.y do
for x := Segment.NodeA.x to Segment.NodeB.x do
begin
Circuit := TCircuit(fMatrix[y,x]);
if (circuit <> nil) and (circuit <> Segment.Circuit)
then
begin
Eqs.AddEquivalence(Circuit, Segment.Circuit);
//Logs.Log('Circuits', DateTimeToStr(Now) + Format(' Possible Road Bug at: %d, %d Circuits: %d(%d) and %d(%d)', [x, y, integer(Circuit), Circuit.Segments.Count, integer(Segment.Circuit), Segment.Circuit.Segments.Count]));
end;
fMatrix[y,x] := integer(Segment.Circuit);
Notify(x, y);
end;
end;
for i := 0 to pred(Eqs.Equivalences.Count) do
MixCircuits(TEquivalence(Eqs.Equivalences[i]).Circuits);
inc(itr);
Segs.DeleteAll;
until (itr >= 2) or (Eqs.Equivalences.Count = 0)
finally
Eqs.Free;
end;
fModified := false;
finally
Segs.Free;
end;
except
fModified := true;
end;
finally
Unlock;
end;
end;
procedure TMatrixCircuitMap.SetSize( aXsize, aYsize : integer );
begin
inherited;
fMatrix := TIntegerLargeMatrix.Create( aYSize, aXsize, 10 );
end;
procedure TMatrixCircuitMap.LoadFromBackup( Reader : IBackupReader );
begin
inherited;
fModified := true;
end;
procedure TMatrixCircuitMap.StoreToBackup( Writer : IBackupWriter );
begin
inherited;
end;
function TMatrixCircuitMap.GetReachMatrix(x1, y1, x2, y2, tolerance : integer) : TReachMatrix;
const
minSegs = 10;
minLen = 20;
function ValidCircuit(Circuit : TCircuit) : boolean;
var
i : integer;
len : integer;
begin
if Circuit <> nil
then
if Circuit.Segments.Count > minSegs
then result := true
else
begin
len := 0;
for i := 0 to pred(Circuit.Segments.Count) do
inc(len, TSegment(Circuit.Segments[i]).Length);
result := len > minLen;
end
else result := false;
end;
function ReachPoint(Matrix : TReachMatrix; x, y : integer) : boolean;
var
i, j : integer;
begin
result := false;
i := x - tolerance;
while (i <= x + tolerance) and not result do
begin
j := y - tolerance;
while (j <= y + tolerance) and not result do
begin
result := Matrix[i, j] <> rchNone;
inc(j);
end;
inc(i);
end;
end;
var
Roads : TReachMatrix;
x, y : integer;
i, j : integer;
begin
Lock;
try
result := TReachMatrix.Create(x2 - x1 + 1, y2 - y1 + 1);
Roads := TReachMatrix.Create(2*tolerance + x2 - x1, 2*tolerance + y2 - y1);
try
// browse the road matrix
i := 0;
for x := x1 - tolerance to x2 + tolerance do
begin
j := 0;
for y := y1 - tolerance to y2 + tolerance do
begin
if ValidCircuit(TCircuit(fMatrix[y, x]))
then Roads[i, j] := rchRoad;
inc(j);
end;
inc(i);
end;
// fill the resulting matrix
for i := 0 to x2 - x1 do
for j := 0 to y2 - y1 do
if ReachPoint(Roads, i + tolerance, j + tolerance)
then result[i, j] := rchRoad;
finally
Roads.Free;
end;
finally
Unlock;
end;
end;
// RegisterBackup
procedure RegisterBackup;
begin
RegisterClass( TMatrixCircuitMap );
end;
end.
|
unit EditAttributeForma;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OkCancel_frame, DB, FIBDataSet, pFIBDataSet, DBGridEh, StdCtrls,
DBCtrls, Mask, DBCtrlsEh, DBLookupEh, CnErrorProvider, FIBQuery,
PrjConst, System.UITypes;
type
TEditAttributForm = class(TForm)
OkCancelFrame1: TOkCancelFrame;
srcAttributes: TDataSource;
dsAttributes: TpFIBDataSet;
dbluAttribute: TDBLookupComboboxEh;
memNotice: TDBMemoEh;
Label1: TLabel;
lblAttribute: TLabel;
Label2: TLabel;
dbValue: TDBEditEh;
CnErrors: TCnErrorProvider;
dsCustAttribut: TpFIBDataSet;
srcCustAttribut: TDataSource;
cbbList: TDBComboBoxEh;
procedure OkCancelFrame1bbOkClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure dbluAttributeChange(Sender: TObject);
private
FCID: Integer;
FAID: Integer;
public
end;
function EditAttribute(const Customer_ID: Integer; const Attribut: string; const CA_ID: Integer = -1): Boolean;
implementation
uses DM, CF, RegularExpressions, pFIBQuery;
{$R *.dfm}
function EditAttribute(const Customer_ID: Integer; const Attribut: string; const CA_ID: Integer = -1): Boolean;
var
ForSelected: Boolean;
NOTICE: string;
VALUE: string;
bm: TBookmark;
Save_Cursor: TCursor;
i: Integer;
begin
with TEditAttributForm.Create(Application) do
try
if Attribut = '' then begin
dsAttributes.ParamByName('IS_OLD').AsInteger := 0;
end
else begin
dsAttributes.ParamByName('IS_OLD').AsInteger := 1;
dbluAttribute.Enabled := false;
end;
FCID := Customer_ID;
FAID := CA_ID;
dsAttributes.ParamByName('CID').AsInt64 := FCID;
dsAttributes.Open;
dsCustAttribut.ParamByName('CA_ID').AsInteger := CA_ID;
dsCustAttribut.Open;
if CA_ID = -1 then
dsCustAttribut.Insert
else
dsCustAttribut.Edit;
if ShowModal = mrOk then begin
ForSelected := false;
if Assigned(CustomersForm) then begin
if (CustomersForm.dbgCustomers.SelectedRows.Count > 0) then
ForSelected := (MessageDlg(rsProcessAllSelectedRows, mtConfirmation, [mbYes, mbNo], 0) = mrYes);
end;
if ForSelected and (dsAttributes['O_UNIQ'] <> 1) then begin
Save_Cursor := Screen.Cursor;
Screen.Cursor := crHourGlass;
FAID := dbluAttribute.VALUE;
NOTICE := memNotice.Lines.Text;
VALUE := dbValue.Text;
dsCustAttribut.Cancel;
dsCustAttribut.DisableControls;
bm := CustomersForm.dbgCustomers.DataSource.DataSet.GetBookmark;
CustomersForm.dbgCustomers.DataSource.DataSet.DisableControls;
for i := 0 to CustomersForm.dbgCustomers.SelectedRows.Count - 1 do begin
CustomersForm.dbgCustomers.DataSource.DataSet.Bookmark := CustomersForm.dbgCustomers.SelectedRows[i];
try
FCID := CustomersForm.dbgCustomers.DataSource.DataSet['CUSTOMER_ID'];
dsCustAttribut.Insert;
dsCustAttribut.FieldByName('O_ID').AsInteger := FAID;
dsCustAttribut.FieldByName('CA_VALUE').AsString := VALUE;
dsCustAttribut.FieldByName('NOTICE').AsString := NOTICE;
dsCustAttribut.FieldByName('CUSTOMER_ID').AsInteger := FCID;
dsCustAttribut.Post;
except
//
end;
end;
dsCustAttribut.EnableControls;
CustomersForm.dbgCustomers.DataSource.DataSet.GotoBookmark(bm);
CustomersForm.dbgCustomers.DataSource.DataSet.EnableControls;
Screen.Cursor := Save_Cursor;
end
else begin
dsCustAttribut.FieldByName('CUSTOMER_ID').AsInteger := Customer_ID;
dsCustAttribut.Post;
end;
result := true;
end
else begin
dsCustAttribut.Cancel;
result := false;
end;
if dsAttributes.Active then
dsAttributes.Close;
finally
free
end;
end;
procedure TEditAttributForm.dbluAttributeChange(Sender: TObject);
begin
cbbList.Items.Clear;
cbbList.KeyItems.Clear;
cbbList.Items.Text := dsAttributes['VLIST'];
cbbList.KeyItems.Text := dsAttributes['VLIST'];
cbbList.Visible := (dsAttributes['VLIST'] <> '');
dbValue.Visible := not cbbList.Visible;
end;
procedure TEditAttributForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then
OkCancelFrame1bbOkClick(Sender);
end;
procedure TEditAttributForm.OkCancelFrame1bbOkClick(Sender: TObject);
var
errors: Boolean;
s: string;
reg: string;
fq: TpFIBQuery;
begin
errors := false;
if (dbluAttribute.Text = '') then begin
errors := true;
CnErrors.SetError(dbluAttribute, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink);
end
else
CnErrors.Dispose(dbluAttribute);
if ((dbluAttribute.Text <> '')) then begin
if dsAttributes['REGEXP'] <> '' then begin
s := dbValue.Text;
reg := '^' + dsAttributes['REGEXP'] + '$';
errors := not TRegEx.IsMatch(s, reg);
if errors then
CnErrors.SetError(dbValue, rsInputIncorrect, iaMiddleLeft, bsNeverBlink)
else
CnErrors.Dispose(dbValue);
end
end;
if (dsAttributes['O_UNIQ'] = 1) then begin
fq := TpFIBQuery.Create(Self);
try
fq.Database := dmMain.dbTV;
fq.Transaction := dmMain.trReadQ;
with fq.sql do begin
Clear;
add('select first 1');
add(' c.Account_No || '' код '' || c.Cust_Code || '' ФИО '' || c.Firstname || '' '' || c.Initials as who');
add('from Customer_Attributes a');
add(' inner join customer c on (a.Customer_Id = c.Customer_Id)');
add('where a.O_Id = :aid');
add(' and a.Customer_Id <> :cid');
add(' and upper(a.Ca_Value) = upper(:val)');
end;
fq.ParamByName('cid').AsInteger := FCID;
fq.ParamByName('aid').AsInteger := dbluAttribute.VALUE;
if cbbList.Visible then
fq.ParamByName('val').AsString := cbbList.Text
else
fq.ParamByName('val').AsString := dbValue.Text;
fq.Transaction.StartTransaction;
fq.ExecQuery;
s := '';
if not fq.FieldByName('who').IsNull then
s := fq.FieldByName('who').AsString;
fq.Transaction.Commit;
fq.Close;
finally
fq.free;
end;
if s <> '' then begin
errors := true;
s := format(rsERROR_UNIQUE, [s]);
if cbbList.Visible then
CnErrors.SetError(cbbList, s, iaMiddleLeft, bsNeverBlink)
else
CnErrors.SetError(dbValue, s, iaMiddleLeft, bsNeverBlink);
end;
end;
if not errors then
ModalResult := mrOk
else
ModalResult := mrNone;
end;
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StBits.pas 4.04 *}
{*********************************************************}
{* SysTools: Bit set class *}
{*********************************************************}
{$I StDefine.inc}
{Notes:
CopyBits, OrBits, AndBits, and SubBits require that the parameter B have
the same Max value as the current object, or an exception is generated.
Use the inherited Count property to get the number of bits currently set.
TStBits takes advantage of the suballocator whenever the bit set is
small enough to allow it. Changing the Max property of the class
allocates a new data area, copies the old data into it, and then
deallocates the old data area.
Supports up to 2**34 bits, if they will fit into memory.
When Windows 3.1 is used, it requires enhanced mode operation.
}
unit StBits;
interface
uses
Windows, Classes, SysUtils,
StBase, StConst;
type
TStBits = class;
TBitIterateFunc =
function(Container : TStBits; N : Integer; OtherData : Pointer) : Boolean;
TStBits = class(TStContainer)
{.Z+}
protected
{property instance variables}
FMax : Integer; {highest element number}
{private instance variables}
btBlockSize : Integer; {bytes allocated to data area}
btBits : PByte; {pointer to data area}
{undocumented protected methods}
procedure btSetMax(Max : Integer);
procedure btRecount;
function btByte(I : Integer) : PByte;
procedure SetByte(I: Integer; B: Byte);
function GetByte(I: Integer): Byte;
function GetAsString: AnsiString;
procedure SetAsString(S: AnsiString);
{.Z-}
public
constructor Create(Max : Integer); virtual;
{-Initialize an empty bitset with highest element number Max}
destructor Destroy; override;
{-Free a bitset}
procedure LoadFromStream(S : TStream); override;
{-Read a bitset from a stream}
procedure StoreToStream(S : TStream); override;
{-Write a bitset to a stream}
procedure Clear; override;
{-Clear all bits in set but leave instance intact}
procedure CopyBits(B : TStBits);
{-Copy all bits in B to this bitset}
procedure SetBits;
{-Set all bits}
procedure InvertBits;
{-Invert all bits}
procedure OrBits(B : TStBits);
{-Or the specified bitset into this one (create the union)}
procedure AndBits(B : TStBits);
{-And the specified bitset with this one (create the intersection)}
procedure SubBits(B : TStBits);
{-Subtract the specified bitset from this one (create the difference)}
procedure SetBit(N : Integer);
{-Set bit N}
procedure ClearBit(N : Integer);
{-Clear bit N}
procedure ToggleBit(N : Integer);
{-Toggle bit N}
procedure ControlBit(N : Integer; State : Boolean);
{-Set or clear bit N according to State}
procedure MoveBit(SrcBitset : TStBits; SrcN, DestN: Integer);
{used to remap bit positions}
procedure MapBits(SrcBitSet: TStBits; DestMap : Array of Integer);
{copy bit set, and move bits into different positions in the new bitset}
function BitIsSet(N : Integer) : Boolean;
{-Return True if bit N is set}
function FirstSet : Integer;
{-Return the index of the first set bit, -1 if none}
function LastSet : Integer;
{-Return the index of the last set bit, -1 if none}
function FirstClear : Integer;
{-Return the index of the first clear bit, -1 if none}
function LastClear : Integer;
{-Return the index of the last clear bit, -1 if none}
function NextSet(N : Integer) : Integer;
{-Return the index of the next set bit after N, -1 if none}
function PrevSet(N : Integer) : Integer;
{-Return the index of the previous set bit after N, -1 if none}
function NextClear(N : Integer) : Integer;
{-Return the index of the next set bit after N, -1 if none}
function PrevClear(N : Integer) : Integer;
{-Return the index of the previous set bit after N, -1 if none}
function Iterate(Action : TBitIterateFunc;
UseSetBits, Up : Boolean;
OtherData : Pointer) : Integer;
{-Call Action for all the matching bits, returning the last bit visited}
function IterateFrom(Action : TBitIterateFunc;
UseSetBits, Up : Boolean;
OtherData : Pointer;
From : Integer) : Integer;
{-Call Action for all the matching bits starting with bit From}
property Max : Integer
{-Read or write the maximum element count in the bitset}
read FMax
write btSetMax;
property Items[N : Integer] : Boolean
{-Read or write Nth bit in set}
read BitIsSet
write ControlBit;
default;
property Bytes[N : Integer] : byte {gives direct access to bytes}
{-Read or write Nth byte in set}
read GetByte
write SetByte;
property AsString : AnsiString {gives access as longstring}
read GetAsString
write SetAsString;
end;
{======================================================================}
implementation
{$IFDEF ThreadSafe}
var
ClassCritSect : TRTLCriticalSection;
{$ENDIF}
procedure EnterClassCS;
begin
{$IFDEF ThreadSafe}
EnterCriticalSection(ClassCritSect);
{$ENDIF}
end;
procedure LeaveClassCS;
begin
{$IFDEF ThreadSafe}
LeaveCriticalSection(ClassCritSect);
{$ENDIF}
end;
function MinLong(A, B : Integer) : Integer;
begin
if A < B then
Result := A
else
Result := B;
end;
function MaxLong(A, B : Integer) : Integer;
begin
if A > B then
Result := A
else
Result := B;
end;
{----------------------------------------------------------------------}
procedure TStBits.AndBits(B : TStBits);
var
I : Integer;
P : PByte;
begin
{$IFDEF ThreadSafe}
EnterClassCS;
EnterCS;
B.EnterCS;
try
{$ENDIF}
if (not Assigned(B)) or (B.Max <> FMax) then
RaiseContainerError(stscBadType);
for I := 0 to btBlockSize-1 do begin
P := btByte(I);
P^ := P^ and B.btByte(I)^;
end;
btRecount;
{$IFDEF ThreadSafe}
finally
B.LeaveCS;
LeaveCS;
LeaveClassCS;
end;
{$ENDIF}
end;
procedure TStBits.MoveBit(SrcBitset : TStBits; SrcN, DestN: Integer);
begin
{$IFDEF ThreadSafe}
EnterClassCS;
EnterCS;
SrcBitSet.EnterCS;
try
{$ENDIF}
if (not Assigned(SrcBitSet)) or (SrcN > FMax) or (SrcBitSet.Max < SrcN) then
RaiseContainerError(stscBadType);
if SrcBitset.BitIsSet(SrcN)
then SetBit(DestN)
else ClearBit(DestN);
//btRecount;
{$IFDEF ThreadSafe}
finally
SrcBitSet.LeaveCS;
LeaveCS;
LeaveClassCS;
end;
{$ENDIF}
end;
function TStBits.BitIsSet(N : Integer) : Boolean;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (N < 0) or (N > FMax) then
RaiseContainerError(stscBadIndex);
{$ENDIF}
Result := (btByte(N shr 3)^ and (1 shl (Byte(N) and 7)) <> 0);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TStBits.btByte(I : Integer) : PByte;
begin
Result := PByte(PAnsiChar(btBits)+I);
end;
function TStBits.GetByte(I : Integer) : Byte;
var P : PByte;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (I < 0) or (I >= btBlockSize) then
RaiseContainerError(stscBadIndex);
{$ENDIF}
P := btByte(I);
Result := P^;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TStBits.GetAsString : ansistring;
{very inefficient!}
var P : PByte; i:Integer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Result:='';
for i:=0 to btBlockSize-1 do begin
P := btByte(I);
Result := Result+ ansichar(P^);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.SetAsString(S:AnsiString);
{very inefficient!}
var P : PByte; I: Integer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (length(S) <> btBlockSize) then
RaiseContainerError(stscBadType);
{$ENDIF}
for i:=1 to length(S) do begin
P:=btByte(i-1);
P^:=byte(S[i]);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.SetByte(I : Integer; B:byte);
var P : PByte;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (I < 0) or (I >= btBlockSize) then
RaiseContainerError(stscBadIndex);
{$ENDIF}
P := btByte(I);
P^ := B;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.MapBits(SrcBitset: TStBits; DestMap : Array of Integer);
var N: Integer;
begin
if (not Assigned(SrcBitset)) or (SrcBitset.Max <> FMax) then
RaiseContainerError(stscBadType);
for N:=0 to High(DestMap) do begin
MoveBit(SrcBitset, N, DestMap[N]);
end;
end;
procedure TStBits.btRecount;
const
{number of bits set in every possible byte}
BitCount : array[Byte] of Byte = (
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8);
var
N : Integer;
P : PByte;
B : Byte;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{Clear unused bits in last byte}
B := Byte(FMax) and 7;
if B < 7 then begin
P := btByte(btBlockSize-1);
P^ := P^ and ((1 shl (B+1))-1);
end;
{Add up the bits in each byte}
FCount := 0;
for N := 0 to btBlockSize-1 do
inc(FCount, BitCount[btByte(N)^]);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.btSetMax(Max : Integer);
var
BlockSize, OldBlockSize, OldMax : Integer;
OldBits : PByte;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{Validate new size}
if Max < 0 then
RaiseContainerError(stscBadSize);
BlockSize := (Max+8) div 8;
{Save old size settings}
OldBlockSize := btBlockSize;
OldMax := FMax;
{Assign new size settings}
FMax := Max;
btBlockSize := BlockSize;
if BlockSize <> OldBlockSize then begin
{Get new data area and transfer data}
OldBits := btBits;
try
GetMem(Pointer(btBits), btBlockSize);
except
btBlockSize := OldBlockSize;
btBits := OldBits;
FMax := OldMax;
raise;
end;
if OldBlockSize < btBlockSize then begin
FillChar(btByte(OldBlockSize)^, btBlockSize-OldBlockSize, 0);
BlockSize := OldBlockSize;
end else
BlockSize := btBlockSize;
Move(OldBits^, btBits^, BlockSize);
{Free old data area}
FreeMem(Pointer(OldBits), OldBlockSize);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.Clear;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
FillChar(btBits^, btBlockSize, 0);
FCount := 0;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.ClearBit(N : Integer);
var
P : PByte;
M : Byte;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (N < 0) or (N > FMax) then
RaiseContainerError(stscBadIndex);
{$ENDIF}
P := btByte(N shr 3);
M := 1 shl (Byte(N) and 7);
if (P^ and M) <> 0 then begin
P^ := P^ and not M;
dec(FCount);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.ControlBit(N : Integer; State : Boolean);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if State then
SetBit(N)
else
ClearBit(N);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.CopyBits(B : TStBits);
begin
{$IFDEF ThreadSafe}
EnterClassCS;
EnterCS;
B.EnterCS;
try
{$ENDIF}
if (not Assigned(B)) or (B.Max <> FMax) then
RaiseContainerError(stscBadType);
Move(B.btBits^, btBits^, btBlockSize);
FCount := B.FCount;
{$IFDEF ThreadSafe}
finally
B.LeaveCS;
LeaveCS;
LeaveClassCS;
end;
{$ENDIF}
end;
constructor TStBits.Create(Max : Integer);
begin
{Validate size}
if Max < 0 then
RaiseContainerError(stscBadSize);
CreateContainer(TStNode, 0);
FMax := Max;
btBlockSize := (Max+8) div 8;
GetMem(Pointer(btBits), btBlockSize);
Clear;
end;
destructor TStBits.Destroy;
begin
if Assigned(btBits) then
FreeMem(Pointer(btBits), btBlockSize);
{Prevent calling Clear}
IncNodeProtection;
inherited Destroy;
end;
function StopImmediately(Container : TStBits; N : Integer;
OtherData : Pointer) : Boolean; far;
{-Iterator function used to stop after first found bit}
begin
Result := False;
end;
function TStBits.FirstClear : Integer;
begin
Result := IterateFrom(StopImmediately, False, True, nil, 0);
end;
function TStBits.FirstSet : Integer;
begin
Result := IterateFrom(StopImmediately, True, True, nil, 0);
end;
procedure TStBits.InvertBits;
var
I : Integer;
P : PByte;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
for I := 0 to btBlockSize-1 do begin
P := btByte(I);
P^ := not P^;
end;
FCount := FMax-FCount+1;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TStBits.Iterate(Action : TBitIterateFunc;
UseSetBits, Up : Boolean;
OtherData : Pointer) : Integer;
begin
if Up then
Result := IterateFrom(Action, UseSetBits, True, OtherData, 0)
else
Result := IterateFrom(Action, UseSetBits, False, OtherData, FMax);
end;
function TStBits.IterateFrom(Action : TBitIterateFunc;
UseSetBits, Up : Boolean;
OtherData : Pointer;
From : Integer) : Integer;
var
I, N, F : Integer;
O : ShortInt;
B, TB : Byte;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if UseSetBits then
TB := 0
else
TB := $FF;
if Up then begin
{do the first possibly-partial byte}
N := MaxLong(From, 0);
F := MinLong(btBlockSize-1, N shr 3);
O := ShortInt(N) and 7;
B := btByte(F)^;
while (N <= FMax) and (O <= ShortInt(7)) do begin
if not (UseSetBits xor ((B and (1 shl O)) <> 0)) then
if not Action(Self, N, OtherData) then begin
Result := N;
Exit;
end;
inc(O);
inc(N);
end;
{do the rest of the bytes}
for I := F+1 to btBlockSize-1 do begin
B := btByte(I)^;
if B <> TB then begin
{byte has bits of interest}
O := 0;
while (N <= FMax) and (O < ShortInt(8)) do begin
if not (UseSetBits xor ((B and (1 shl O)) <> 0)) then
if not Action(Self, N, OtherData) then begin
Result := N;
Exit;
end;
inc(O);
inc(N);
end;
end else
inc(N, 8);
end;
end else begin
{do the last possibly-partial byte}
N := MinLong(From, FMax);
F := MaxLong(N, 0) shr 3;
O := ShortInt(N) and 7;
B := btByte(F)^;
while (N >= 0) and (O >= ShortInt(0)) do begin
if not (UseSetBits xor ((B and (1 shl O)) <> 0)) then
if not Action(Self, N, OtherData) then begin
Result := N;
Exit;
end;
dec(O);
dec(N);
end;
{do the rest of the bytes}
for I := F-1 downto 0 do begin
B := btByte(I)^;
if B <> TB then begin
{byte has bits of interest}
O := 7;
while (N >= 0) and (O >= ShortInt(0)) do begin
if not (UseSetBits xor ((B and (1 shl O)) <> 0)) then
if not Action(Self, N, OtherData) then begin
Result := N;
Exit;
end;
dec(O);
dec(N);
end;
end else
dec(N, 8);
end;
end;
{Iterated all bits}
Result := -1;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TStBits.LastClear : Integer;
begin
Result := IterateFrom(StopImmediately, False, False, nil, FMax);
end;
function TStBits.LastSet : Integer;
begin
Result := IterateFrom(StopImmediately, True, False, nil, FMax);
end;
function TStBits.NextClear(N : Integer) : Integer;
begin
Result := IterateFrom(StopImmediately, False, True, nil, N+1);
end;
function TStBits.NextSet(N : Integer) : Integer;
begin
Result := IterateFrom(StopImmediately, True, True, nil, N+1);
end;
procedure TStBits.OrBits(B : TStBits);
var
I : Integer;
P : PByte;
begin
{$IFDEF ThreadSafe}
EnterClassCS;
EnterCS;
B.EnterCS;
try
{$ENDIF}
if (not Assigned(B)) or (B.Max <> FMax) then
RaiseContainerError(stscBadType);
for I := 0 to btBlockSize-1 do begin
P := btByte(I);
P^ := P^ or B.btByte(I)^;
end;
btRecount;
{$IFDEF ThreadSafe}
finally
B.LeaveCS;
LeaveCS;
LeaveClassCS;
end;
{$ENDIF}
end;
function TStBits.PrevClear(N : Integer) : Integer;
begin
Result := IterateFrom(StopImmediately, False, False, nil, N-1);
end;
function TStBits.PrevSet(N : Integer) : Integer;
begin
Result := IterateFrom(StopImmediately, True, False, nil, N-1);
end;
procedure TStBits.SetBit(N : Integer);
var
P : PByte;
M : Byte;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (N < 0) or (N > FMax) then
RaiseContainerError(stscBadIndex);
{$ENDIF}
P := btByte(N shr 3);
M := 1 shl (Byte(N) and 7);
if (P^ and M) = 0 then begin
P^ := P^ or M;
inc(FCount);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.SetBits;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
FillChar(btBits^, btBlockSize, $FF);
FCount := FMax+1;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.SubBits(B : TStBits);
var
I : Integer;
P : PByte;
begin
{$IFDEF ThreadSafe}
EnterClassCS;
EnterCS;
B.EnterCS;
try
{$ENDIF}
if (not Assigned(B)) or (B.Max <> FMax) then
RaiseContainerError(stscBadType);
for I := 0 to btBlockSize-1 do begin
P := btByte(I);
P^ := P^ and not B.btByte(I)^;
end;
btRecount;
{$IFDEF ThreadSafe}
finally
B.LeaveCS;
LeaveCS;
LeaveClassCS;
end;
{$ENDIF}
end;
procedure TStBits.ToggleBit(N : Integer);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if BitIsSet(N) then
ClearBit(N)
else
SetBit(N);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.LoadFromStream(S : TStream);
var
Reader : TReader;
StreamedClass : TPersistentClass;
StreamedClassName : String;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Clear;
Reader := TReader.Create(S, 1024);
try
with Reader do
begin
StreamedClassName := ReadString;
StreamedClass := GetClass(StreamedClassName);
if (StreamedClass = nil) then
RaiseContainerErrorFmt(stscUnknownClass, [StreamedClassName]);
if (not IsOrInheritsFrom(StreamedClass, Self.ClassType)) or
(not IsOrInheritsFrom(TStBits, StreamedClass)) then
RaiseContainerError(stscWrongClass);
Max := ReadInteger;
FCount := ReadInteger;
Read(btBits^, btBlockSize);
end;
finally
Reader.Free;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStBits.StoreToStream(S : TStream);
var
Writer : TWriter;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Writer := TWriter.Create(S, 1024);
try
with Writer do
begin
WriteString(Self.ClassName);
WriteInteger(Max);
WriteInteger(Count);
Write(btBits^, btBlockSize);
end;
finally
Writer.Free;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
{$IFDEF ThreadSafe}
initialization
Windows.InitializeCriticalSection(ClassCritSect);
finalization
Windows.DeleteCriticalSection(ClassCritSect);
{$ENDIF}
end.
|
program funnyJeep(input, output);
const
MULTIPLIER = 500;
var
bound : integer;
function getDistance(n : integer) : real;
var
i : integer;
ans : real;
begin
ans := 0.0;
i := 1;
while i <> (2 * n - 1) do
begin
ans += 1 / (2 * i - 1);
i := succ(i);
end;
getDistance := ans;
end;
begin
write('N: '); read(bound);
writeln(getDistance(bound):5:2)
end. |
// --------------------------------------------------------------------------
// Archivo del Proyecto Ventas
// Página del proyecto: http://sourceforge.net/projects/ventas
// --------------------------------------------------------------------------
// Este archivo puede ser distribuido y/o modificado bajo lo terminos de la
// Licencia Pública General versión 2 como es publicada por la Free Software
// Fundation, Inc.
// --------------------------------------------------------------------------
unit Unidades;
interface
uses
SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs,
QStdCtrls, QGrids, QDBGrids, QExtCtrls, QComCtrls, QButtons, QMenus,
QTypes, Inifiles, QcurrEdit;
type
TfrmUnidades = class(TForm)
MainMenu1: TMainMenu;
Archivo1: TMenuItem;
mnuInsertar: TMenuItem;
mnuEliminar: TMenuItem;
mnuModificar: TMenuItem;
N3: TMenuItem;
mnuGuardar: TMenuItem;
mnuCancelar: TMenuItem;
N2: TMenuItem;
Salir1: TMenuItem;
mnuConsulta: TMenuItem;
mnuAvanza: TMenuItem;
mnuRetrocede: TMenuItem;
btnInsertar: TBitBtn;
btnEliminar: TBitBtn;
btnModificar: TBitBtn;
btnGuardar: TBitBtn;
btnCancelar: TBitBtn;
gddListado: TDBGrid;
lblRegistros: TLabel;
txtRegistros: TcurrEdit;
grpUnidade: TGroupBox;
Label1: TLabel;
txtNombre: TEdit;
Label8: TLabel;
cmbTipo: TComboBox;
procedure btnInsertarClick(Sender: TObject);
procedure btnEliminarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnGuardarClick(Sender: TObject);
procedure btnModificarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Salir1Click(Sender: TObject);
procedure mnuAvanzaClick(Sender: TObject);
procedure mnuRetrocedeClick(Sender: TObject);
procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormCreate(Sender: TObject);
private
sModo : String;
iClave : integer;
procedure LimpiaDatos;
procedure ActivaControles;
function VerificaDatos:boolean;
function VerificaIntegridad:boolean;
procedure GuardaDatos;
procedure RecuperaConfig;
procedure RecuperaDatos;
procedure Listar;
public
end;
var
frmUnidades: TfrmUnidades;
implementation
uses dm;
{$R *.xfm}
procedure TfrmUnidades.btnInsertarClick(Sender: TObject);
begin
LimpiaDatos;
sModo := 'Insertar';
Height := 300;
ActivaControles;
cmbTipo.ItemIndex := 3;
txtNombre.SetFocus;
end;
procedure TfrmUnidades.LimpiaDatos;
begin
txtNombre.Clear;
end;
procedure TfrmUnidades.ActivaControles;
begin
if( (sModo = 'Insertar') or (sModo = 'Modificar') ) then begin
btnInsertar.Enabled := false;
btnModificar.Enabled := false;
btnEliminar.Enabled := false;
mnuInsertar.Enabled := false;
mnuModificar.Enabled := false;
mnuEliminar.Enabled := false;
btnGuardar.Enabled := true;
btnCancelar.Enabled := true;
mnuGuardar.Enabled := true;
mnuCancelar.Enabled := true;
mnuConsulta.Enabled := false;
txtNombre.ReadOnly := false;
txtNombre.TabStop := true;
cmbTipo.Enabled := true;
end;
if(sModo = 'Consulta') then begin
btnInsertar.Enabled := true;
mnuInsertar.Enabled := true;
if(txtRegistros.Value > 0) then begin
btnModificar.Enabled := true;
btnEliminar.Enabled := true;
mnuModificar.Enabled := true;
mnuEliminar.Enabled := true;
end
else begin
btnModificar.Enabled := false;
btnEliminar.Enabled := false;
mnuModificar.Enabled := false;
mnuEliminar.Enabled := false;
end;
btnGuardar.Enabled := false;
btnCancelar.Enabled := false;
mnuGuardar.Enabled := false;
mnuCancelar.Enabled := false;
mnuConsulta.Enabled := true;
txtNombre.ReadOnly := true;
txtNombre.TabStop := false;
cmbTipo.Enabled := false;
end;
end;
procedure TfrmUnidades.btnEliminarClick(Sender: TObject);
var
sTipo : String;
begin
sTipo := 'null';
if(Application.MessageBox('Se eliminará la unidad seleccionada','Eliminar',[smbOK]+[smbCancel]) = smbOK) then begin
with dmDatos.qryModifica do begin
Close;
SQL.Clear;
SQL.Add('UPDATE articulos SET tipo = ' + sTipo);
SQL.Add('WHERE unidade = ' + dmDatos.cdsCliente.FieldByName('clave').AsString);
ExecSQL;
Close;
SQL.Clear;
SQL.Add('DELETE FROM unidades WHERE clave = ' + dmDatos.cdsCliente.FieldByName('clave').AsString);
ExecSQL;
Close;
end;
btnCancelarClick(Sender);
end;
end;
procedure TfrmUnidades.btnCancelarClick(Sender: TObject);
begin
sModo := 'Consulta';
LimpiaDatos;
Listar;
ActivaControles;
Height := 224;
btnInsertar.SetFocus;
end;
procedure TfrmUnidades.btnGuardarClick(Sender: TObject);
begin
if(VerificaDatos) then begin
GuardaDatos;
btnCancelarClick(Sender);
end;
end;
function TfrmUnidades.VerificaDatos:boolean;
var
bRegreso : boolean;
begin
bRegreso := true;
if(Length(txtNombre.Text) = 0) then begin
Application.MessageBox('Introduce el nombre del unidad','Error',[smbOK],smsCritical);
txtNombre.SetFocus;
bRegreso := false;
end
else if(cmbTipo.ItemIndex = -1) then begin
Application.MessageBox('Introduce el tipo de la unidad de medida','Error',[smbOK],smsCritical);
cmbTipo.SetFocus;
bRegreso := false;
end
else if(not VerificaIntegridad) then
bRegreso := false;
Result := bRegreso;
end;
function TfrmUnidades.VerificaIntegridad:boolean;
var
bRegreso : boolean;
begin
bRegreso := true;
with dmDatos.qryConsulta do begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM unidades WHERE nombre = ''' + txtNombre.Text + '''');
Open;
if(not Eof) and ((sModo = 'Insertar') or
((FieldByName('clave').AsInteger <> iClave) and
(sModo = 'Modificar'))) then begin
bRegreso := false;
Application.MessageBox('La unidad ya existe','Error',[smbOK],smsCritical);
txtNombre.SetFocus;
end;
Close;
end;
Result := bRegreso;
end;
procedure TfrmUnidades.GuardaDatos;
var
sClave, sTipo : String;
begin
sTipo := IntToStr(cmbTipo.ItemIndex);
if(sModo = 'Insertar') then begin
with dmDatos.qryModifica do begin
Close;
SQL.Clear;
SQL.Add('SELECT CAST(GEN_ID(unidades,1) AS integer) AS Clave');
SQL.Add('from RDB$DATABASE');
Open;
sClave := FieldByName('clave').AsString;
Close;
SQL.Clear;
SQL.Add('INSERT INTO unidades (nombre, clave, tipo, NombreTipo,fecha_umov) VALUES(');
SQL.Add('''' + txtNombre.Text + ''',' + sClave + ',' + sTipo + ',');
SQL.Add(''''+ cmbTipo.Text +''',');
SQL.Add(''''+ FormatDateTime('mm/dd/yyyy hh:nn:ss',Now) + ''')');
ExecSQL;
Close;
end;
end
else begin
with dmDatos.qryModifica do begin
Close;
SQL.Clear;
SQL.Add('UPDATE unidades SET nombre = ''' + txtNombre.Text + ''',');
SQL.Add('tipo = ' + sTipo + ',');
SQL.Add('NombreTipo = '''+ cmbTipo.Text +''',');
SQL.Add('fecha_umov = ''' + FormatDateTime('mm/dd/yyyy hh:nn:ss',Now) + '''');
SQL.Add('WHERE clave = ' + IntToStr(iClave));
ExecSQL;
Close;
// actualiza articulos
SQL.Clear;
SQL.Add('UPDATE articulos SET tipo = ' + sTipo);
SQL.Add('WHERE unidade = ' + IntToStr(iClave));
ExecSQL;
Close;
end;
end;
end;
procedure TfrmUnidades.btnModificarClick(Sender: TObject);
begin
if(txtRegistros.Value > 0) then begin
sModo := 'Modificar';
RecuperaDatos;
ActivaControles;
Height := 300;
txtNombre.SetFocus;
end;
end;
procedure TfrmUnidades.FormShow(Sender: TObject);
begin
btnCancelarClick(Sender);
end;
procedure TfrmUnidades.RecuperaConfig;
var
iniArchivo : TIniFile;
sIzq, sArriba : String;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
with iniArchivo do begin
//Recupera la posición Y de la ventana
sArriba := ReadString('Unidades', 'Posy', '');
//Recupera la posición X de la ventana
sIzq := ReadString('Unidades', 'Posx', '');
if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin
Left := StrToInt(sIzq);
Top := StrToInt(sArriba);
end;
Free;
end;
end;
procedure TfrmUnidades.FormClose(Sender: TObject; var Action: TCloseAction);
var
iniArchivo : TIniFile;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
with iniArchivo do begin
// Registra la posición y de la ventana
WriteString('Unidades', 'Posy', IntToStr(Top));
// Registra la posición X de la ventana
WriteString('Unidades', 'Posx', IntToStr(Left));
Free;
end;
dmDatos.cdsCliente.Active := false;
dmDatos.qryListados.Close;
end;
procedure TfrmUnidades.RecuperaDatos;
begin
with dmDatos.cdsCliente do begin
if(Active) then begin
iClave := FieldByName('clave').AsInteger;
txtNombre.Text := Trim(FieldByName('nombre').AsString);
cmbTipo.ItemIndex := FieldByName('tipo').AsInteger;
end;
end;
end;
procedure TfrmUnidades.Listar;
var
sBM : String;
begin
with dmDatos.qryListados do begin
sBM := dmDatos.cdsCliente.Bookmark;
dmDatos.cdsCliente.Active := false;
Close;
SQL.Clear;
//SQL.Add('SELECT clave, nombre, tipo, ');
//SQL.Add(' CASE tipo');
//SQL.Add(' WHEN 0 THEN ''A GRANEL'' ');
//SQL.Add(' WHEN 1 THEN ''JUEGOS'' ');
//SQL.Add(' WHEN 2 THEN ''SIN TIPO DEFINIDO'' ');
//SQL.Add(' ELSE ''NORMAL'' ');
//SQL.Add(' END as NombreTipo');
// Esto corrige el probelma de unidades
SQL.Add('SELECT clave, nombre, tipo, NombreTipo ');
SQL.Add('FROM unidades ORDER BY nombre');
Open;
dmDatos.cdsCliente.Active := true;
dmDatos.cdsCliente.FieldByName('clave').Visible := false;
dmDatos.cdsCliente.FieldByName('tipo').Visible := false;
dmDatos.cdsCliente.FieldByName('nombre').DisplayLabel := 'Unidad';
dmDatos.cdsCliente.FieldByName('nombretipo').DisplayLabel := 'Tipo';
dmDatos.cdsCliente.FieldByName('nombretipo').DisplayWidth := 25;
txtRegistros.Value := dmDatos.cdsCliente.RecordCount;
try
dmDatos.cdsCliente.Bookmark := sBM;
except
txtRegistros.Value := txtRegistros.Value;
end;
end;
RecuperaDatos;
end;
procedure TfrmUnidades.Salir1Click(Sender: TObject);
begin
Close;
end;
procedure TfrmUnidades.mnuAvanzaClick(Sender: TObject);
begin
dmDatos.cdsCliente.Next;
end;
procedure TfrmUnidades.mnuRetrocedeClick(Sender: TObject);
begin
dmDatos.cdsCliente.Prior;
end;
procedure TfrmUnidades.Salta(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
{Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)}
if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then
if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then
SelectNext(Sender as TWidgetControl, true, true);
end;
procedure TfrmUnidades.FormCreate(Sender: TObject);
begin
RecuperaConfig;
end;
// TODO la existencia del campo TIPO en articulos no atende el estandar de programación.
end.
|
program lista;
uses crt;
{
Programa Lista Telefônica
Nome: Carlos Kazuo Mochizuki Ishizaka - 12100152
Nome: David Cechini -
Obs: Acentos foram removidos de mensagens de saída para não imprimir
caracteres indesejáveis caso compilar via TurboPascal.
}
{
Cada registro telefônico segue a estrutura de tipo
tRegistro:
nome: String[10]
telefone: Int
prox: ponteiro pro próximo registro | nil caso for último
}
type
tPtRegistro = ^tRegistro;
tRegistro = record
nome: String[10];
telefone: Integer;
prox: tPtRegistro;
end;
{
Função utilizada para converter inteiro pra string.
Parâmetros:
I - Integer - inteiro a ser convertido
Retorno:
String - inteiro convertido em string
}
function IntToStr(I:Integer):String;
var
S:String;
begin
Str(I, S);
IntToStr := S;
end;
{
1) Função para inserir registro.
Cria novo registro após o último registro existente.
Caso o registro atual estiver ocupado, tentar próximo até encontrar um vazio (último).
Parâmetros:
p - ponteiro para um registro
nome - String - nome do sujeito que será inserido, valor será truncado em 10 posições
telefone - Integer - valor a ser guardado como telefone
Retorno:
Devolve string contendo mensagem de registro incluído com sucesso.
}
function inserir(var p:tPtRegistro; nome:String; telefone:Integer):String;
begin
if p <> nil then
{ se registro não for nulo, acessar próximo }
inserir := inserir(p^.prox, nome, telefone)
else
begin
{ inserir quando o registro atual for nil }
new(p);
p^.nome := nome;
p^.telefone := telefone;
p^.prox := nil;
inserir := 'Numero inserido com sucesso.';
end;
end;
{
2) Remove a primeira ocorrência exata do string nome na lista telefônica.
Caso o registro atual não for igual ao nome fornecido, avançar para o próximo registro.
Fornecer um erro caso não encontrou nenhum nome e é o último registro da lista.
Parâmetros:
p - ponteiro para um registro
nome - String - Nome a ser buscado para apagar
Retorno:
Retorna mensagem de sucesso ou de registro não encontrado.
}
function remover(var p:tPtRegistro; nome:String):String;
var
reg:tPtRegistro;
begin
if p <> nil then
begin
if p^.nome = nome then
begin
{ rotina para remoção de registro }
reg := p;
p := p^.prox;
dispose(reg);
remover := 'Registro removido com sucesso!';
end
else
{ se o nome não for encontrado, acessar o próximo }
remover := remover(p^.prox, nome);
end
else
{ chegou no último registro sem encontrar o nome buscado }
remover := 'Registro nao encontrado.';
end;
{
3) Altera um registro dado o nome (ocorrência exata).
Parâmetros:
p - ponteiro para um registro
nome - String - Nome a ser buscado para alterar
Retorno:
Retorna que o registro foi alterado após preenchimento ou retorna que o registro
não foi encontrado, caso o nome fornecido não for igual a algum registro da lista.
}
function alterar(var p:tPtRegistro; nome:String):String;
begin
if p <> nil then
begin
if p^.nome = nome then
begin
{ nome encontrado. tela de alteração e escreve direto na variável }
writeln('Informe o novo nome ou redigite o anterior (', p^.nome, '):');
readln(p^.nome);
writeln('Informe o novo telefone ou redigite o anterior (', p^.telefone, '):');
readln(p^.telefone);
alterar := 'Registro alterado com sucesso!';
end
else
{ se o nome não for encontrado, acessar o próximo }
alterar := alterar(p^.prox, nome);
end
else
{ chegou no último registro sem encontrar o nome buscado }
alterar := 'Registro nao encontrado.';
end;
{
4) Lista todos os registros da lista.
A cada registro, ele imprime o nome e o telefone do sujeito.
Parâmetros:
p - ponteiro para um registro
i - Int - Numeração de cada registro ao imprimir
Retorno:
String dizendo que chegou ao fim da lista ou se a lista está vazia.
}
function listar(p:tPtRegistro; i:Integer):String;
begin
if p <> nil then
begin
{ impressão de cada registro }
writeln('Registro ', i, ':');
writeln('Nome: ', p^.nome);
writeln('Telefone: ', p^.telefone);
writeln('');
{ acessar o próximo }
listar := listar(p^.prox, i + 1);
end
else
begin
if i = 1 then
{ se o item for vazio e é o primeiro ítem, a lista está vazia }
listar := 'Lista vazia.'
else
{ senão informar final da listagem }
listar := 'Fim da lista.'
end;
end;
{
5) Pesquisa na lista telefônica por parte do nome.
Caso encontrar um nome que contenha a substring pesquisada, imprime o registro na tela.
Parâmetros:
p - ponteiro para um registro
part - String - Parte de nome pra busca
ocorrencias - Int - Acumulador de ocorrências
Retorno:
String indicando fim da pesquisa.
}
function pesquisar(var p:tPtRegistro; part:String; ocorrencias:Integer):String;
begin
if p <> nil then
begin
{ se parte da string for encontrada, imprimir }
if Pos(part, p^.nome) > 0 then
begin
{ imprimindo registro }
writeln('Ocorrencia ', ocorrencias, ':');
writeln('Nome: ', p^.nome);
writeln('Telefone: ', p^.telefone);
writeln('');
ocorrencias := ocorrencias + 1;
end;
{ partir pro próximo registro }
pesquisar := pesquisar(p^.prox, part, ocorrencias);
end
else
begin
{ mostrar no final da listagem quantas ocorrências foram encontradas }
if ocorrencias = 0 then
pesquisar := 'Fim da pesquisa. Nenhuma ocorrencia encontrada.'
else if ocorrencias = 1 then
pesquisar := 'Fim da pesquisa. Foi encontrada 1 ocorrencia.'
else
pesquisar := Concat('Fim da Pesquisa. Foram encontradas ',
IntToStr(ocorrencias),
' ocorrencias de nomes contendo "',
part,
'".');
end
end;
{
6) Varre a lista e quando chegar no final, imprime quantos registros a lista possui.
Parâmetros:
p - ponteiro para um registro
qtd - Int - Quantidade de registros até o registro atual
}
function total(var p:tPtRegistro; qtd:Integer):String;
begin
if p <> nil then
{ enquanto registro não for vazio, acessar próximo e incrementar quantidade }
total := total(p^.prox, qtd + 1)
else
begin
{ chegou ao fim da lista. mostra quantos cadastros existem }
if qtd = 0 then
total := 'Lista vazia.'
else if qtd = 1 then
total := 'Ha apenas 1 registro cadastrado na lista.'
else
begin
total := Concat('Ha ', IntToStr(qtd), ' registros cadastrados na lista.');
end;
end;
end;
{ Programa principal }
var
l:tPtRegistro;
menuopt, telefone:Integer;
ret:String;
nome:String[10];
begin
l := nil;
{ Banner }
clrscr;
writeln('Bem vindo ao programa de Lista Telefonica.');
writeln('');
menuopt := -1;
repeat
if menuopt > -1 then
clrscr;
{ Imprime menu e habilita ao usuário a escolha das opções }
writeln('==================================================');
writeln('MENU PRINCIPAL');
writeln('1) Inserir');
writeln('2) Remover');
writeln('3) Alterar');
writeln('4) Listar');
writeln('5) Pesquisar');
writeln('6) Quantidade de Registros');
writeln('0) Sair');
writeln('');
writeln('Escolha sua opcao abaixo:');
readln(menuopt);
writeln('');
ret := '';
case menuopt OF
{ Opção 0: sair }
0 : menuopt := menuopt;
{ Opção 1: inserir }
1 : begin
writeln('Digite o nome:');
readln(nome);
writeln('Digite o telefone:');
readln(telefone);
ret := inserir(l, nome, telefone);
end;
{ Opção 2: remover }
2 : begin
writeln('Digite o nome:');
readln(nome);
ret := remover(l, nome);
end;
{ Opção 3: alterar }
3 : begin
writeln('Digite o nome:');
readln(nome);
ret := alterar(l, nome);
end;
{ Opção 4: listar registros }
4 : begin
writeln('Listando registros...');
writeln('');
ret := listar(l, 1);
end;
{ Opção 5: pesquisar }
5 : begin
writeln('Digite o nome ou parte:');
readln(nome);
ret := pesquisar(l, nome, 0);
end;
{ Opção 6: total de registros }
6 : begin
ret := total(l, 0);
end;
{ Mostrar erro caso nenhuma opção for escolhida }
else writeln('Opcao invalida.');
end;
{ Se o retorno não for vazio, mostrar a mensagem }
if ret <> '' then
begin
writeln('--------------------------------------------------');
writeln(ret);
end;
{ Mostra mensagem e prompt antes de voltar ao menu inicial }
if menuopt <> 0 then
begin
writeln('');
writeln('Digite qualquer tecla para voltar ao menu inicial.');
readkey;
end;
until(menuopt = 0);
writeln('Obrigado por utilizar o programa.');
end.
|
program ch2(input, output);
{
Chapter 2 Assignment
Alberto Villalobos
February 6, 2014
Description: Calculates mowing time
}
const
housewidth = 40;
houselength = 40;
lawnwidth = 100;
lawnlength = 150;
ftperhour = 50;
var
area, time: Integer;
begin
area := lawnlength * lawnwidth - houselength * housewidth;
time := area div ftperhour;
writeln('Area to be mowed ', area, ' time required ', time);
end. |
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
2005-04-22 BTaylor
Fixed AV from incorrect object being freed
Fixed memory leak
Improved parsing
Rev 1.6 1/3/05 4:48:24 PM RLebeau
Removed reference to StrUtils unit, not being used.
Rev 1.5 12/1/2004 1:57:50 PM JPMugaas
Updated with some code posted by:
Interpulse Systeemontwikkeling
Interpulse Automatisering B.V.
http://www.interpulse.nl
Rev 1.1 2004.11.25 06:17:00 PM EDMeester
Rev 1.0 2002.11.12 10:30:44 PM czhower
}
unit IdAuthenticationDigest;
{
Implementation of the digest authentication as specified in RFC2617
rev 1.1: Edwin Meester (systeemontwikkeling@interpulse.nl)
Author: Doychin Bondzhev (doychin@dsoft-bg.com)
Copyright: (c) Chad Z. Hower and The Winshoes Working Group.
}
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdAuthentication,
IdException,
IdGlobal,
IdHashMessageDigest,
IdHeaderList;
type
EIdInvalidAlgorithm = class(EIdException);
TIdDigestAuthentication = class(TIdAuthentication)
protected
FRealm: String;
FStale: Boolean;
FOpaque: String;
FDomain: TStringList;
FNonce: String;
FNonceCount: integer;
FAlgorithm: String;
FMethod, FUri: string; //needed for digest
FEntityBody: String; //needed for auth-int, Somebody make this nice :D
FQopOptions: TStringList;
FOther: TStringList;
function DoNext: TIdAuthWhatsNext; override;
function GetSteps: Integer; override;
public
constructor Create; override;
destructor Destroy; override;
function Authentication: String; override;
procedure SetRequest(const AMethod, AUri: String); override;
property Method: String read FMethod write FMethod;
property Uri: String read FUri write FUri;
property EntityBody: String read FEntityBody write FEntityBody;
end;
// RLebeau 4/17/10: this forces C++Builder to link to this unit so
// RegisterAuthenticationMethod can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdAuthenticationDigest"'*)
implementation
uses
IdGlobalProtocols, IdFIPS, IdHash, IdResourceStrings, IdResourceStringsProtocols,
SysUtils;
{ TIdDigestAuthentication }
constructor TIdDigestAuthentication.Create;
begin
inherited Create;
CheckMD5Permitted;
end;
destructor TIdDigestAuthentication.Destroy;
begin
FreeAndNil(FDomain);
FreeAndNil(FQopOptions);
inherited Destroy;
end;
procedure TIdDigestAuthentication.SetRequest(const AMethod, AUri: String);
begin
FMethod := AMethod;
FUri := AUri;
end;
function TIdDigestAuthentication.Authentication: String;
function Hash(const S: String): String;
begin
with TIdHashMessageDigest5.Create do try
Result := LowerCase(HashStringAsHex(S));
finally Free end;
end;
var
LA1, LA2, LCNonce, LResponse, LQop: string;
begin
Result := ''; {do not localize}
case FCurrentStep of
0:
begin
//Just be save with this one
Result := 'Digest'; {do not localize}
end;
1:
begin
//Build request
LCNonce := Hash(DateTimeToStr(Now));
LA1 := Username + ':' + FRealm + ':' + Password; {do not localize}
if TextIsSame(FAlgorithm, 'MD5-sess') then begin {do not localize}
LA1 := Hash(LA1) + ':' + FNonce + ':' + LCNonce; {do not localize}
end;
LA2 := FMethod + ':' + FUri; {do not localize}
//Qop header present
if FQopOptions.IndexOf('auth-int') > -1 then begin {do not localize}
LQop := 'auth-int'; {do not localize}
LA2 := LA2 + ':' + Hash(FEntityBody); {do not localize}
end
else if FQopOptions.IndexOf('auth') > -1 then begin {do not localize}
LQop := 'auth'; {do not localize}
end;
if LQop <> '' then begin
LResponse := IntToHex(FNonceCount, 8) + ':' + LCNonce + ':' + LQop + ':'; {do not localize}
end;
LResponse := Hash( Hash(LA1) + ':' + FNonce + ':' + LResponse + Hash(LA2) ); {do not localize}
Result := 'Digest ' + {do not localize}
'username="' + Username + '", ' + {do not localize}
'realm="' + FRealm + '", ' + {do not localize}
'nonce="' + FNonce + '", ' + {do not localize}
'algorithm="' + FAlgorithm + '", ' + {do not localize}
'uri="' + FUri + '", ';
//Qop header present
if LQop <> '' then begin {do not localize}
Result := Result +
'qop="' + LQop + '", ' + {do not localize}
'nc=' + IntToHex(FNonceCount, 8) + ', ' + {do not localize}
'cnonce="' + LCNonce + '", '; {do not localize}
end;
Result := Result + 'response="' + LResponse + '"'; {do not localize}
if FOpaque <> '' then begin
Result := Result + ', opaque="' + FOpaque + '"'; {do not localize}
end;
Inc(FNonceCount);
FCurrentStep := 0;
end;
end;
end;
function Unquote(var S: String): String;
var
I, Len: Integer;
begin
Len := Length(S);
I := 2; // skip first quote
while I <= Len do
begin
if S[I] = '"' then begin
Break;
end;
if S[I] = '\' then begin
Inc(I);
end;
Inc(I);
end;
Result := Copy(S, 2, I-2);
S := Copy(S, I+1, MaxInt);
end;
function TIdDigestAuthentication.DoNext: TIdAuthWhatsNext;
var
S, LName, LValue, LTempNonce: String;
LParams: TStringList;
begin
Result := wnDoRequest;
case FCurrentStep of
0:
begin
//gather info
if not Assigned(FDomain) then begin
FDomain := TStringList.Create;
end else begin
FDomain.Clear;
end;
if not Assigned(FQopOptions) then begin
FQopOptions := TStringList.Create;
end else begin
FQopOptions.Clear;
end;
S := ReadAuthInfo('Digest'); {do not localize}
Fetch(S);
LParams := TStringList.Create;
try
while Length(S) > 0 do begin
// RLebeau: Apache sends a space after each comma, but IIS does not!
LName := Trim(Fetch(S, '=')); {do not localize}
S := TrimLeft(S);
if TextStartsWith(S, '"') then begin {do not localize}
LValue := Unquote(S); {do not localize}
Fetch(S, ','); {do not localize}
end else begin
LValue := Trim(Fetch(S, ','));
end;
LParams.Add(LName + '=' + LValue);
S := TrimLeft(S);
end;
FRealm := LParams.Values['realm']; {do not localize}
LTempNonce := LParams.Values['nonce']; {do not localize}
if FNonce <> LTempNonce then
begin
FNonceCount := 1;
FNonce := LTempNonce;
end;
S := LParams.Values['domain']; {do not localize}
while Length(S) > 0 do begin
FDomain.Add(Fetch(S));
end;
FOpaque := LParams.Values['opaque']; {do not localize}
FStale := TextIsSame(LParams.Values['stale'], 'True'); {do not localize}
FAlgorithm := LParams.Values['algorithm']; {do not localize}
FQopOptions.CommaText := LParams.Values['qop']; {do not localize}
if FAlgorithm = '' then begin
FAlgorithm := 'MD5'; {do not localize}
end
else if PosInStrArray(FAlgorithm, ['MD5', 'MD5-sess'], False) = -1 then begin {do not localize}
raise EIdInvalidAlgorithm.Create(RSHTTPAuthInvalidHash);
end;
finally
FreeAndNil(LParams);
end;
if Length(Username) > 0 then begin
FCurrentStep := 1;
Result := wnDoRequest;
end else begin
Result := wnAskTheProgram;
end;
end;
end;
end;
function TIdDigestAuthentication.GetSteps: Integer;
begin
Result := 1;
end;
initialization
RegisterAuthenticationMethod('Digest', TIdDigestAuthentication); {do not localize}
finalization
UnregisterAuthenticationMethod('Digest'); {do not localize}
end.
|
unit uAutoFreeObjsForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, BaseForms;
type
TLogObject = class(TObject)
constructor Create;
destructor Destroy; override;
end;
TTestAutoFree = class(TBaseForm)
procedure BaseFormCreate(Sender: TObject);
procedure BaseFormShow(Sender: TObject);
procedure BaseFormClose(Sender: TObject; var Action: TCloseAction);
procedure BaseFormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure BaseFormHide(Sender: TObject);
procedure BaseFormDestroy(Sender: TObject);
private
{ Private declarations }
FA, FB, FC: TLogObject;
public
{ Public declarations }
end;
implementation
{$R *.dfm}
uses
uMainForm;
{ TLogObject }
constructor TLogObject.Create;
begin
LogAF(Format(' %d created', [Integer(Self)]));
end;
destructor TLogObject.Destroy;
begin
LogAF(Format(' %d destroyed', [Integer(Self)]));
inherited;
end;
{ TTestAutoFree }
procedure TTestAutoFree.BaseFormClose(Sender: TObject; var Action: TCloseAction);
begin
LogAF('Form.OnClose');
end;
procedure TTestAutoFree.BaseFormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
LogAF('Form.OnCloseQuery');
end;
procedure TTestAutoFree.BaseFormCreate(Sender: TObject);
begin
LogAF('Form.OnCreate');
FA := AutoFree(TLogObject.Create);
FB := AutoFree(TLogObject.Create);
end;
procedure TTestAutoFree.BaseFormDestroy(Sender: TObject);
begin
LogAF('Form.OnDestroy');
end;
procedure TTestAutoFree.BaseFormHide(Sender: TObject);
begin
LogAF('Form.OnHide');
end;
procedure TTestAutoFree.BaseFormShow(Sender: TObject);
begin
LogAF('Form.OnShow');
FC := AutoFree(TLogObject.Create);
end;
end.
|
program Lab6_Var9;
uses Math;
const eps = 1e-3;
var i, j :Integer; res, ds, s :Real;
begin
res := 0;
for i := 1 to 12 do
begin
j := 1;
ds := eps;
s := 0;
writeln('Iter. ', i, ' result = ', res:0:6);
while abs(ds) > eps do
begin
ds := tan(1/(i*j))/(j*j*j);
s := s + ds;
writeln(' |Iter. ', j, ' ds = ', ds:0:6, ' s = ', s:0:6);
j := j + 1;
end;
res := res + i*i*s;
end;
writeln('Result: ', res:0:6);
end.
|
unit MainDbf;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, DB, DBClient, DBTables, ComCtrls, StdCtrls,
ExtCtrls;
type
TMainForm = class(TForm)
LastLotGrid: TStringGrid;
LotLabel: TLabel;
ResultGrid: TStringGrid;
ResultLabel: TLabel;
TipGrid: TStringGrid;
TipLabel: TLabel;
LotDateLabel: TLabel;
ResultDateLabel: TLabel;
TipDateLabel: TLabel;
Bevel1: TBevel;
Button1: TButton;
TipSuccGrid: TStringGrid;
SuccAllLabel: TLabel;
Succ365Label: TLabel;
Succ180Label: TLabel;
Succ90Label: TLabel;
Succ30Label: TLabel;
SuccLabel: TLabel;
TipSuccAllLabel: TLabel;
TipSucc365Label: TLabel;
TipSucc180Label: TLabel;
TipSucc90Label: TLabel;
TipSucc30Label: TLabel;
TipRich: TRichEdit;
Button2: TButton;
Button3: TButton;
procedure LastLotGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure FormCreate(Sender: TObject);
procedure ResultGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure TipGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure LoadData;
procedure SaveData;
procedure UpdateLastLotGrid;
procedure UpdateResultGrid;
procedure UpdateTipGrid;
procedure UpdateTipRich;
end;
var
MainForm: TMainForm;
St10Dir: string;
implementation
{$R *.dfm}
uses
IniFiles,
TipCalc, TipConf, TipList, TipAnlz;
var
LastLotError: string;
ResultError: string;
TipError: string;
procedure TMainForm.LoadData;
procedure LoadDefaults;
var
St10Ini: TIniFile;
begin
if FileExists(St10Dir+'st10.ini') then
begin
St10Ini:=TIniFile.Create(St10Dir+'st10.ini');
TipSet.CalculType:=TCalcul(St10Ini.ReadInteger('TipSet', 'CalculType', integer(ccSum)));
TipSet.IsInstance:= St10Ini.ReadBool ('TipSet', 'IsInstance', False);
TipSet.InstancePoint:= St10Ini.ReadInteger('TipSet', 'InstancePoint', 1);
TipSet.IsPartialInstance:= St10Ini.ReadBool ('TipSet', 'IsPartialInstance', False);
TipSet.PartialCount:= St10Ini.ReadInteger('TipSet', 'PartialCount', 100);
TipSet.PartialPoint:= St10Ini.ReadInteger('TipSet', 'PartialPoint', 1);
TipSet.IsNoLot:= St10Ini.ReadBool ('TipSet', 'IsNoLot', False);
TipSet.NoLotPoint:= St10Ini.ReadInteger('TipSet', 'NoLotPoint', 1);
TipSet.NoLotExp:= St10Ini.ReadBool ('TipSet', 'NoLotExp', False);
TipSet.IsProjection:= St10Ini.ReadBool ('TipSet', 'IsProjection', False);
TipSet.ProjectionCount:= St10Ini.ReadInteger('TipSet', 'ProjectionCount', 20);
TipSet.ProjectionNo:= St10Ini.ReadInteger('TipSet', 'ProjectionNo', 15);
TipSet.ProjectionAve:= St10Ini.ReadInteger('TipSet', 'ProjectionAve', 0);
TipSet.ProjectionAll:= St10Ini.ReadInteger('TipSet', 'ProjectionAll', 15);
TipSet.IsNewton:= St10Ini.ReadBool ('TipSet', 'IsNewton', False);
TipSet.NewtonDepth:= St10Ini.ReadInteger('TipSet', 'NewtonDepth', 10);
TipSet.NewtonPoint:= St10Ini.ReadInteger('TipSet', 'NewtonPoint', 1);
St10Ini.Destroy;
end;
end;
procedure LoadLotData;
var
TableLots: TTable;
lotIdx: integer;
numIdx: integer;
begin
if FileExists(St10Dir+'stastnych10.dbf') then
begin
TableLots:=TTable.Create(nil);
TableLots.TableType:=ttFoxPro;
TableLots.Active:=False;
TableLots.TableName:=St10Dir+'stastnych10.dbf';
TableLots.Active:=True;
SetLength(Lottery, TableLots.RecordCount+1);
TableLots.First;
for lotIdx:=0 to High(Lottery)-1 do
begin
Lottery[lotIdx].Date:=TableLots.Fields[0].AsDateTime;
Lottery[lotIdx].IsLot:=True;
for numIdx:=1 to 20 do
Lottery[lotIdx].Lot[numIdx]:=TableLots.Fields[numIdx].AsInteger;
TableLots.Next;
end;
Lottery[High(Lottery)].Date:=Lottery[High(Lottery)-1].Date+1;
TableLots.Active:=False;
TableLots.Destroy;
end
else
LastLotError:='Chybí databáze losovaných čísel!';
end;
procedure LoadTipData;
var
TableTips: TTable;
tipIdx: integer;
numIdx: integer;
newProg: boolean;
begin
if FileExists(St10Dir+'st10tipy.dbf') then
begin
TableTips:=TTable.Create(nil);
TableTips.TableType:=ttFoxPro;
TableTips.Active:=False;
TableTips.TableName:=St10Dir+'st10tipy.dbf';
TableTips.Active:=True;
TableTips.First;
newProg:=False;
for tipIdx:=0 to High(Lottery) do
begin
if (Lottery[tipIdx].Date = TableTips.Fields[0].AsDateTime) then
begin
Lottery[tipIdx].IsTip:=True;
for numIdx:=1 to 80 do
Lottery[tipIdx].Rating.Values[numIdx]:=TableTips.Fields[numIdx].AsFloat;
TableTips.Next;
end
else
newProg:=True;
end;
TableTips.Active:=False;
TableTips.Destroy;
if (newProg) then AllPrognoses(Lottery, TipSet, 0, 1);
MakeTips(Lottery);
SuccAnalysis(Lottery, TipSet);
end
else
begin
ResultError:='Chybí databáze tipovaných čísel!';
TipError:='Chybí databáze tipovaných čísel!';
end;
end;
begin
LastLotError:='';
ResultError:='';
TipError:='';
LoadDefaults;
LoadLotData;
LoadTipData;
end;
procedure TMainForm.SaveData;
procedure SaveDefaults;
var
St10Ini: TIniFile;
begin
St10Ini:=TIniFile.Create(St10Dir+'st10.ini');
St10Ini.WriteInteger('TipSet', 'CalculType', integer(TipSet.CalculType));
St10Ini.WriteBool ('TipSet', 'IsInstance', TipSet.IsInstance);
St10Ini.WriteInteger('TipSet', 'InstancePoint', TipSet.InstancePoint);
St10Ini.WriteBool ('TipSet', 'IsPartialInstance', TipSet.IsPartialInstance);
St10Ini.WriteInteger('TipSet', 'PartialCount', TipSet.PartialCount);
St10Ini.WriteInteger('TipSet', 'PartialPoint', TipSet.PartialPoint);
St10Ini.WriteBool ('TipSet', 'IsNoLot', TipSet.IsNoLot);
St10Ini.WriteInteger('TipSet', 'NoLotPoint', TipSet.NoLotPoint);
St10Ini.WriteBool ('TipSet', 'NoLotExp', TipSet.NoLotExp);
St10Ini.WriteBool ('TipSet', 'IsProjection', TipSet.IsProjection);
St10Ini.WriteInteger('TipSet', 'ProjectionCount', TipSet.ProjectionCount);
St10Ini.WriteInteger('TipSet', 'ProjectionNo', TipSet.ProjectionNo);
St10Ini.WriteInteger('TipSet', 'ProjectionAve', TipSet.ProjectionAve);
St10Ini.WriteInteger('TipSet', 'ProjectionAll', TipSet.ProjectionAll);
St10Ini.WriteBool ('TipSet', 'IsNewton', TipSet.IsNewton);
St10Ini.WriteInteger ('TipSet', 'NewtonDepth', TipSet.NewtonDepth);
St10Ini.WriteInteger ('TipSet', 'NewtonPoint', TipSet.NewtonPoint);
St10Ini.Destroy;
end;
procedure SaveTipData;
var
TableTips: TTable;
tipIdx: integer;
numIdx: integer;
begin
TableTips:=TTable.Create(nil);
TableTips.TableType:=ttFoxPro;
TableTips.Active:=False;
if FileExists(St10Dir+'st10tipy.dbf') then
begin
TableTips.TableName:=St10Dir+'st10tipy.dbf';
TableTips.EmptyTable;
end
else
begin
TableTips.TableName:=St10Dir+'st10tipy.dbf';
TableTips.FieldDefs.Add('datum', ftDate);
for numIdx:=1 to 80 do
TableTips.FieldDefs.Add('H'+IntToStr(numIdx), ftFloat);
TableTips.CreateTable;
end;
TableTips.Active:=True;
for tipIdx:=0 to High(Lottery) do
begin
TableTips.AppendRecord([]);
TableTips.Edit;
TableTips.Fields[0].AsDateTime:=Lottery[tipIdx].Date;
for numIdx:=1 to 80 do
TableTips.Fields[numIdx].AsFloat:=Lottery[tipIdx].Rating.Values[numIdx];
TableTips.Post;
end;
TableTips.Active:=False;
TableTips.Destroy;
end;
begin
SaveDefaults;
SaveTipData;
end;
procedure TMainForm.UpdateLastLotGrid;
var
numIdx, lotIdx: integer;
begin
LastLotError:='';
if (Lottery <> nil) then
begin
lotIdx:=Length(Lottery)-2;
LotDateLabel.Caption:=DateToStr(Lottery[lotIdx].Date)+' :';
if (Lottery[lotIdx].IsLot) then
begin
for numIdx:=1 to 20 do
LastLotGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)]:=IntToStr(Lottery[lotIdx].Lot[numIdx])
end
else
begin
for numIdx:=1 to 20 do
LastLotGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)]:='';
LastLotError:='V databázi chybí čísla tohoto losování';
end;
end
else
begin
LotDateLabel.Caption:='dd.mm.yyyy :';
for numIdx:=1 to 20 do
LastLotGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)]:='';
LastLotError:='Chybí databáze losovaných čísel!';
end;
end;
procedure TMainForm.UpdateResultGrid;
var
lotIdx, numIdx: integer;
begin
ResultError:='';
if (Lottery <> nil) then
begin
lotIdx:=Length(Lottery)-2;
ResultDateLabel.Caption:=DateToStr(Lottery[lotIdx].Date)+' :';
if (Lottery[lotIdx].IsTip) then
begin
for numIdx:=1 to 20 do
begin
ResultGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)]:=IntToStr(Lottery[lotIdx].Tip[numIdx]);
if (Lottery[lotIdx].Success[numIdx]) then
ResultGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)+2]:='Pass'
else
ResultGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)+2]:='Fail';
end;
end
else
begin
for numIdx:=1 to 20 do
begin
ResultGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)]:='';
ResultGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)+2]:='Fail';
end;
ResultError:='V databázi chybí tip čísel pro toto losování';
end;
end
else
begin
ResultDateLabel.Caption:='dd.mm.yyyy :';
for numIdx:=1 to 20 do
begin
ResultGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)]:='';
ResultGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)+2]:='Fail';
end;
ResultError:='Chybí databáze tipovaných čísel!';
end;
end;
procedure TMainForm.UpdateTipGrid;
var
tipIdx, numIdx: integer;
begin
TipError:='';
if (Lottery <> nil) then
begin
tipIdx:=Length(Lottery)-1;
TipDateLabel.Caption:=DateToStr(Lottery[tipIdx].Date)+' :';
if (Lottery[tipIdx].IsTip) then
begin
for numIdx:=1 to 20 do
TipGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)]:=IntToStr(Lottery[tipIdx].Tip[numIdx]);
end
else
begin
for numIdx:=1 to 20 do
TipGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)]:='';
TipError:='V databázi chybí tip čísel pro další losování';
end;
end
else
begin
TipDateLabel.Caption:='dd.mm.yyyy :';
for numIdx:=1 to 20 do
TipGrid.Cells[(numIdx-1) mod 10, ((numIdx-1) div 10)]:='';
TipError:='Chybí databáze tipovaných čísel!';
end;
for numIdx:=0 to 20 do
begin
TipSuccGrid.Cells[numIdx+1, 1]:=IntToStr(TipSet.SuccessTableOfAll[numIdx]);
TipSuccGrid.Cells[numIdx+1, 2]:=IntToStr(TipSet.SuccessTableOf365[numIdx]);
TipSuccGrid.Cells[numIdx+1, 3]:=IntToStr(TipSet.SuccessTableOf180[numIdx]);
TipSuccGrid.Cells[numIdx+1, 4]:=IntToStr(TipSet.SuccessTableOf90[numIdx]);
TipSuccGrid.Cells[numIdx+1, 5]:=IntToStr(TipSet.SuccessTableOf30[numIdx]);
end;
TipSuccAllLabel.Caption:=Format('%4.3f', [TipSet.SuccessAll])+' %';
TipSucc365Label.Caption:=Format('%4.3f', [TipSet.Success365])+' %';
TipSucc180Label.Caption:=Format('%4.3f', [TipSet.Success180])+' %';
TipSucc90Label.Caption:=Format('%4.3f', [TipSet.Success90])+' %';
TipSucc30Label.Caption:=Format('%4.3f', [TipSet.Success30])+' %';
end;
procedure TMainForm.UpdateTipRich;
var
str1, str2, str3, str4: string;
predpona: string;
st1, st2: integer;
procedure SetAttributes(Len: integer; aColor: TColor; aStyle: TFontStyles);
begin
TipRich.SelStart:=st1;
TipRich.SelLength:=Len;
TipRich.SelAttributes.Color:=aColor;
TipRich.SelAttributes.Style:=aStyle;
TipRich.SelStart:=st2;
TipRich.SelLength:=0;
end;
begin
TipRich.Clear;
st1:=TipRich.SelStart;
TipRich.Lines.Add('Prognóza se sestává z těchto částí :');
st2:=TipRich.SelStart;
SetAttributes(36, clWindowText, [fsBold, fsUnderline]);
TipRich.Lines.Add('');
case (TipSet.CalculType) of
ccSingle, ccSum:
TipRich.Lines.Add('Výpočet je dán součtem bodového hodnocení jednotlivých prognóz.');
ccAverage:
TipRich.Lines.Add('Výpočet je dán aritmetickým průměrem procentuálního hodnocení jednotlivých prognóz.');
ccOrder:
TipRich.Lines.Add('Výpočet je dán součtem bodových hodnocení za umístění v jednotlivých prognózách.');
end;
TipRich.Lines.Add('');
if (TipSet.IsInstance) then
begin
str1:=IntToStr(TipSet.InstancePoint);
st1:=TipRich.SelStart;
TipRich.Lines.Add('* Výskyt čísla v databázi ze všech losování. Bodové hodnocení : '+str1);
st2:=TipRich.SelStart;
st1:=st1+64;
SetAttributes(Length(str1), clWindowText, [fsBold]);
end;
if (TipSet.IsPartialInstance) then
begin
str1:=IntToStr(TipSet.PartialCount);
str2:=IntToStr(TipSet.PartialPoint);
st1:=TipRich.SelStart;
TipRich.Lines.Add('* Výskyt čísla v databázi za posledních '+str1+' losování. Bodové hodnocení : '+str2);
st2:=TipRich.SelStart;
st1:=st1+40;
SetAttributes(Length(str1), clWindowText, [fsBold]);
st1:=st1+30+Length(str1);
SetAttributes(Length(str2), clWindowText, [fsBold]);
end;
predpona:='';
if (not TipSet.NoLotExp) then predpona:='ne';
if (TipSet.IsNoLot) then
begin
str1:=IntToStr(TipSet.NoLotPoint);
st1:=TipRich.SelStart;
TipRich.Lines.Add('* Nevylosovaná čísla během posledních losování. Bodové hodnocení : '+
str1+'. Body se '+predpona+'zvyšují exponenciálně.');
st2:=TipRich.SelStart;
st1:=st1+67;
SetAttributes(Length(str1), clWindowText, [fsBold]);
end;
if (TipSet.IsProjection) then
begin
str1:=IntToStr(TipSet.ProjectionCount);
str2:=IntToStr(TipSet.ProjectionNo);
str3:=IntToStr(TipSet.ProjectionAve);
str4:=IntToStr(TipSet.ProjectionAll);
st1:=TipRich.SelStart;
TipRich.Lines.Add('* Projekce čísel z posledních '+str1+' losování. Bodové hodnocení: ('+
str2+' - '+str3+' - '+str4+')');
st2:=TipRich.SelStart;
st1:=st1+30;
SetAttributes(Length(str1), clWindowText, [fsBold]);
st1:=st1+30+Length(str1);
SetAttributes(Length(str2), clWindowText, [fsBold]);
st1:=st1+3+Length(str2);
SetAttributes(Length(str3), clWindowText, [fsBold]);
st1:=st1+3+Length(str3);
SetAttributes(Length(str4), clWindowText, [fsBold]);
end;
if (TipSet.IsNewton) then
begin
str1:=IntToStr(TipSet.NewtonDepth);
str2:=IntToStr(TipSet.NewtonPoint);
st1:=TipRich.SelStart;
TipRich.Lines.Add('* Newtonův polynom '+str1+'. řádu. Bodové hodnocení : '+str2);
st2:=TipRich.SelStart;
st1:=st1+19;
SetAttributes(Length(str1), clWindowText, [fsBold]);
st1:=st1+27+Length(str1);
SetAttributes(Length(str2), clWindowText, [fsBold]);
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
idx: integer;
Rect: TGridRect;
begin
LoadData;
for idx:=1 to 21 do
TipSuccGrid.Cells[idx, 0]:=Format('%4d',[idx-1]);
TipSuccGrid.Cells[0, 1]:='Celé';
TipSuccGrid.Cells[0, 2]:='Roční';
TipSuccGrid.Cells[0, 3]:='Půlroční';
TipSuccGrid.Cells[0, 4]:='Čtvrletní';
TipSuccGrid.Cells[0, 5]:='Měsíční';
Rect.Left:=23; Rect.Top:=0; Rect.Right:=24; Rect.Bottom:=1;
TipSuccGrid.Selection:=Rect;
LastLotGrid.Canvas.Font:=LastLotGrid.Font;
ResultGrid.Canvas.Font:=ResultGrid.Font;
TipGrid.Canvas.Font:=TipGrid.Font;
UpdateLastLotGrid;
UpdateResultGrid;
UpdateTipGrid;
UpdateTipRich;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
SaveData;
end;
procedure DrawBall(Canvas: TCanvas; Rect: TRect; Number: string; blColor: TColor; bgColor: TColor);
var
xDiff, yDiff: integer;
xCent, yCent: integer;
begin
xCent:=(Rect.Right-Rect.Left) div 2;
yCent:=(Rect.Bottom-Rect.Top) div 2;
xDiff:=xCent-(Canvas.TextWidth(Number) div 2);
yDiff:=yCent-(Canvas.TextHeight(Number) div 2);
Canvas.Brush.Color:=bgColor;
Canvas.Pen.Color:=bgColor;
Canvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom);
Canvas.Brush.Color:=blColor;
Canvas.Pen.Color:=clBlack;
Canvas.Ellipse(Rect.Left+xCent-13, Rect.Top+yCent-13, Rect.Left+xCent+14, Rect.Top+xCent+14);
Canvas.Font.Color:=clWindowText;
Canvas.TextOut(Rect.Left+xDiff, Rect.Top+yDiff, Number);
end;
procedure DrawError(Canvas: TCanvas; Rect: TRect; Error: string; bgColor: TColor);
var
xDiff, yDiff: integer;
xCent, yCent: integer;
begin
xCent:=(Rect.Right-Rect.Left) div 2;
yCent:=(Rect.Bottom-Rect.Top) div 2;
xDiff:=xCent-(Canvas.TextWidth(Error) div 2);
yDiff:=yCent-(Canvas.TextHeight(Error) div 2);
Canvas.Brush.Color:=bgColor;
Canvas.Font.Color:=clRed;
Canvas.TextOut(xDiff, yDiff, Error);
end;
procedure TMainForm.LastLotGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
begin
if (LastLotError = '') then
DrawBall((Sender as TStringGrid).Canvas, Rect, (Sender as TStringGrid).Cells[ACol, ARow], clYellow, clSkyBlue)
else
begin
if (ACol = 0) and (ARow = 0) then
DrawError((Sender as TStringGrid).Canvas, (Sender as TStringGrid).ClientRect, LastLotError, clSkyBlue);
end;
end;
procedure TMainForm.ResultGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
begin
if (ResultError = '') then
begin
if ((Sender as TStringGrid).Cells[ACol, ARow+2] = 'Pass') then
DrawBall((Sender as TStringGrid).Canvas, Rect, (Sender as TStringGrid).Cells[ACol, ARow], clLime, clSkyBlue)
else
DrawBall((Sender as TStringGrid).Canvas, Rect, (Sender as TStringGrid).Cells[ACol, ARow], clRed, clSkyBlue);
end
else
begin
if (ACol = 0) and (ARow = 0) then
DrawError((Sender as TStringGrid).Canvas, (Sender as TStringGrid).ClientRect, ResultError, clSkyBlue);
end;
end;
procedure TMainForm.TipGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
begin
if (TipError = '') then
DrawBall((Sender as TStringGrid).Canvas, Rect, (Sender as TStringGrid).Cells[ACol, ARow], clYellow, clMoneyGreen)
else
begin
if (ACol = 0) and (ARow = 0) then
DrawError((Sender as TStringGrid).Canvas, (Sender as TStringGrid).ClientRect, TipError, clMoneyGreen);
end;
end;
procedure TMainForm.Button1Click(Sender: TObject);
var
DoProg: boolean;
begin
DoProg:=False;
FillConfForm(TipSet);
if (TipConfForm.ShowModal = mrOk) then
begin
if (TakeConfForm(TipSet)) then
DoProg:=True
else
if (MessageDlg('Nastavení prognózy nebylo změněno.'#13'Chceš přepočítat prognózy?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
DoProg:=True;
end;
if (DoProg) then
begin
MainForm.Repaint;
AllPrognoses(Lottery, TipSet, 0, 1);
UpdateResultGrid;
UpdateTipGrid;
UpdateTipRich;
end;
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
ShowLotsAndTips(Lottery, TipSet);
end;
procedure TMainForm.Button3Click(Sender: TObject);
begin
StartAnalyze(Lottery);
end;
initialization
LastLotError:='';
ResultError:='';
TipError:='';
finalization
end.
|
unit uXPListView_orig;
interface
{ TODO : Add more functionality }
uses Classes, Types, QControls, QStdCtrls,
QGraphics, QExtCtrls, uGraphics,
Qt, uXPImageList, QForms, QFileCtrls, Sysutils;
type
TXPListView=class;
TXPListItem=class(TObject)
private
FCaption: string;
FImageIndex: integer;
FColumnData: TStrings;
procedure SetCaption(const Value: string);
procedure SetImageIndex(const Value: integer);
procedure SetColumnData(const Value: TStrings);
public
constructor Create; virtual;
destructor Destroy;override;
property Caption:string read FCaption write SetCaption;
property ImageIndex:integer read FImageIndex write SetImageIndex;
property ColumnData: TStrings read FColumnData write SetColumnData;
end;
TXPListItems=class(TObject)
private
FItems: TList;
FOwner: TXPListView;
procedure destroyItems;
function GetCount: integer;
public
function Add: TXPListItem;
function Insert(const Index: integer): TXPListItem;
constructor Create(AOwner:TXPListView); virtual;
destructor Destroy;override;
property Items: TList read FItems;
property Count: integer read GetCount;
end;
TXPListViewGetImageIndexEvent=function (Sender:TObject; const itemindex:integer): integer of object;
TXPListView=class(TCustomControl)
private
FBorderStyle: TBorderStyle;
FBorderWidth: integer;
FImageList: TXPImageList;
FItems: TXPListItems;
FIconHSpacing: integer;
FIconVSpacing: integer;
FRowHeight: integer;
FColWidth: integer;
FIconsPerRow: integer;
FVertScrollBar: TScrollBar;
FItemCount: integer;
FRows: integer;
FBuffer: TBitmap;
FOnGetImageIndex: TXPListViewGetImageIndexEvent;
procedure SetBorderStyle(const Value: TBorderStyle);
procedure SetBorderWidth(const Value: integer);
procedure SetImageList(const Value: TXPImageList);
procedure SetIconHSpacing(const Value: integer);
procedure SetIconVSpacing(const Value: integer);
procedure SetItemCount(const Value: integer);
procedure SetOnGetImageIndex(const Value: TXPListViewGetImageIndexEvent);
procedure InternalCalc;
procedure RecreateBuffer;
protected
function WidgetFlags: Integer; override;
procedure BorderStyleChanged; dynamic;
function GetClientOrigin: TPoint; override;
function GetClientRect: TRect; override;
procedure InvalidateEvent(Sender: TObject);
public
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer);override;
procedure paint;override;
property Bitmap;
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
published
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsNone;
property BorderWidth: integer read FBorderWidth write SetBorderWidth;
property ImageList: TXPImageList read FImageList write SetImageList;
property Items: TXPListItems read FItems;
property ItemCount: integer read FItemCount write SetItemCount;
property IconHSpacing: integer read FIconHSpacing write SetIconHSpacing;
property IconVSpacing: integer read FIconVSpacing write SetIconVSpacing;
property VertScrollBar: TScrollBar read FVertScrollBar;
property OnGetImageIndex: TXPListViewGetImageIndexEvent read FOnGetImageIndex write SetOnGetImageIndex;
end;
implementation
{ TXPListItem }
constructor TXPListItem.Create;
begin
FColumnData:=TStringList.create;
FImageIndex:=-1;
FCaption:='';
end;
destructor TXPListItem.Destroy;
begin
FColumnData.free;
inherited;
end;
procedure TXPListItem.SetCaption(const Value: string);
begin
if Value<>FCaption then begin
FCaption := Value;
end;
end;
procedure TXPListItem.SetColumnData(const Value: TStrings);
begin
if Value<>FColumnData then begin
FColumnData.assign(Value);
end;
end;
procedure TXPListItem.SetImageIndex(const Value: integer);
begin
if Value<>FImageIndex then begin
FImageIndex := Value;
end;
end;
{ TXPListItems }
function TXPListItems.Add: TXPListItem;
begin
result:=TXPListItem.create;
FItems.add(result);
end;
constructor TXPListItems.Create(AOwner:TXPListView);
begin
FItems:=TList.create;
FOwner:=AOwner;
end;
destructor TXPListItems.Destroy;
begin
destroyItems;
FItems.free;
inherited;
end;
procedure TXPListItems.destroyItems;
var
i:longint;
item: TXPListItem;
begin
for i:=FItems.count-1 downto 0 do begin
item:=FItems[i];
item.free;
end;
end;
function TXPListItems.GetCount: integer;
begin
result:=fitems.Count;
end;
function TXPListItems.Insert(const Index: integer): TXPListItem;
begin
result:=TXPListItem.create;
FItems.Insert(Index,result);
end;
{ TXPListView }
procedure TXPListView.BorderStyleChanged;
begin
//Notification
end;
constructor TXPListView.Create(AOwner: TComponent);
begin
inherited;
FBuffer:=TBitmap.create;
FOnGetImageIndex:=nil;
IconHSpacing:=43;
IconVSpacing:=43;
FItems:=TXPListItems.Create(self);
FImageList:=nil;
FBorderStyle:=bsSunken3D;
FBorderWidth:=1;
FVertScrollBar:=TScrollBar.create(nil);
FVertScrollBar.Kind:=sbVertical;
FVertScrollBar.OnChange:=InvalidateEvent;
color:=clWindow;
end;
destructor TXPListView.Destroy;
begin
FBuffer.free;
FVertScrollBar.free;
FItems.free;
inherited;
end;
function TXPListView.GetClientOrigin: TPoint;
begin
Result.X := FBorderWidth*2;
Result.Y := Result.X;
QWidget_mapToGlobal(Handle, @Result, @Result);
end;
function TXPListView.GetClientRect: TRect;
var
FW: Integer;
begin
Result := inherited GetClientRect;
FW := FBorderWidth*2;
InflateRect(Result, -FW, -FW);
end;
procedure TXPListView.InternalCalc;
begin
FIconsPerRow:=(clientwidth div FColWidth);
FRows:=FItemCount div FIConsPerRow;
FVertScrollBar.Max:=FRows*FRowHeight;
FVertScrollBar.SmallChange:=1;
FVertScrollBar.LargeChange:=FRowHeight;
end;
procedure TXPListView.InvalidateEvent(Sender: TObject);
begin
invalidate;
end;
procedure TXPListView.paint;
const
cColor: array [Boolean] of Integer = (clBtnShadow, clBtnHighlight);
var
aRect: TRect;
dRect: TRect;
x,y: integer;
i: integer;
imageIndex: integer;
dtop: integer;
rownum: integer;
begin
exit;
aRect:=Rect(0,0,width,height);
draw3DRect(Canvas, aRect, FBorderStyle);
dRect:=clientrect;
canvas.SetClipRect(dRect);
y:=dRect.top-(fvertscrollbar.Position);
rownum:=abs(y) div FRowHeight;
i:=rownum*FIconsPerRow;
dtop:=rownum*FRowHeight;
y:=y+dtop;
// application.mainform.caption:=' i '+inttostr(i)+' rownum:'+inttostr(rownum)+' iconsperrow:'+inttostr(FIconsPerRow);
if (FItemCount>=1) then begin
while y<dRect.Bottom do begin
x:=dRect.left+1;
while x<dRect.right do begin
if (i<FItemCount) and (x+fcolwidth<dRect.right) then begin
if assigned(FImageList) then begin
if assigned(FOnGetImageIndex) then imageIndex:=FOnGetImageIndex(self,i)
else imageIndex:=-1;
fbuffer.canvas.CopyRect(Rect(0,0,FColWidth,FRowHeight), bitmap.canvas, rect(x,y,x+fcolwidth,y+frowheight));
if imageindex<>-1 then begin
FImageList.Draw(fbuffer.canvas,(FIconHSpacing div 2),1,imageIndex);
canvas.Draw(x,y,fbuffer);
end
else begin
canvas.Draw(x,y,fbuffer);
end;
end;
inc(i);
end
else begin
fbuffer.canvas.CopyRect(Rect(0,0,FColWidth,FRowHeight), bitmap.canvas, rect(x,y,x+fcolwidth,y+frowheight));
canvas.Draw(x,y,fbuffer);
//InvalidateRect(rect(x,y,x+fcolwidth,y+frowheight),true);
end;
inc(x,FColWidth);
//if (i>FItemCount) then exit;
end;
inc(y,FRowHeight);
end;
end;
end;
procedure TXPListView.RecreateBuffer;
begin
fbuffer.Width:=FColWidth;
fbuffer.Height:=FRowHeight;
end;
procedure TXPListView.SetBorderStyle(const Value: TBorderStyle);
begin
if FBorderStyle <> Value then begin
FBorderStyle := Value;
Invalidate;
BorderStyleChanged;
end;
end;
procedure TXPListView.SetBorderWidth(const Value: integer);
begin
if (Value<>FBorderWidth) then begin
FBorderWidth := Value;
invalidate;
end;
end;
procedure TXPListView.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited;
FVertScrollBar.parentcolor:=false;
if FVertScrollbar.parent<>self then FVertScrollBar.parent:=self;
FVertScrollBar.Align:=alRight;
InternalCalc;
end;
procedure TXPListView.SetIconHSpacing(const Value: integer);
begin
if value<>FIconHSpacing then begin
FIconHSpacing := Value;
FColWidth:=FIconHSpacing+32;
recreateBuffer;
invalidate;
end;
end;
procedure TXPListView.SetIconVSpacing(const Value: integer);
begin
if value<>FIconVSpacing then begin
FIconVSpacing := Value;
FRowHeight:=FIconVSpacing+32;
recreateBuffer;
invalidate;
end;
end;
procedure TXPListView.SetImageList(const Value: TXPImageList);
begin
if value<>FImageList then begin
FImageList := Value;
end;
end;
procedure TXPListView.SetItemCount(const Value: integer);
begin
if value<>FItemCount then begin
FItemCount := Value;
InternalCalc;
invalidate;
end;
end;
procedure TXPListView.SetOnGetImageIndex(const Value: TXPListViewGetImageIndexEvent);
begin
FOnGetImageIndex := Value;
end;
function TXPListView.WidgetFlags: Integer;
begin
Result := Inherited WidgetFlags or Integer(WidgetFlags_WRepaintNoErase) or Integer(WidgetFlags_WResizeNoErase);
end;
end.
|
{ Subroutine SST_W_C_DOIT (GNAM, STAT)
*
* Do the backend phase. This routine is specific to the C backend.
* GNAM is the full treename of the output file. All the file suffix
* stuff has already been handled.
}
module sst_w_c_doit;
define sst_w_c_doit;
%include 'sst_w_c.ins.pas';
procedure sst_w_c_doit ( {do the whole back end phase}
in gnam: univ string_var_arg_t; {raw output file name}
out stat: sys_err_t); {completion status code}
var
conn: file_conn_t; {connection handle to output file}
stack_loc: util_stack_loc_handle_t; {stack location handle}
univ_p: univ_ptr; {used for resetting stack to empty}
include: boolean; {TRUE if writing include file}
{
********************************************************************
*
* Local subroutine WRITE_STRING (S, STAT)
*
* Write the Pascal string S to the output file. S may be NULL terminated.
}
procedure write_string ( {write Pascal/C string to output file}
in s: string; {string to write, may be NULL terminated}
out stat: sys_err_t); {completion status code}
val_param;
var
vstr: string_var80_t; {var string version of S}
begin
vstr.max := sizeof(vstr.str); {init local var string}
string_vstring (vstr, s, sizeof(s)); {make var string version of input string}
file_write_text (vstr, conn, stat); {write string to file}
end;
{
********************************************************************
*
* Start of main routine.
}
begin
include := sst_ins or sst_writeall; {TRUE if writing an include file}
{
* Set up output file.
}
file_open_write_text ( {open the output file for write}
gnam, {output file tree name}
'', {mandatory file name suffix}
conn, {returned connection handle}
stat);
if sys_error(stat) then return;
{
* Make a pass over all the data, and rearrange it if neccessary to conform
* to C language requirements.
}
sst_w_c_rearrange; {rearrange internal data structures for C}
{
* Reset the state after the rearrange phase. Most of this should not be
* neccessary, but is done here to be defensive.
}
sst_scope_p := sst_scope_root_p; {reset the current scope to the root scope}
sst_names_p := sst_scope_p;
sst_opc_p := sst_opc_first_p; {reset the current opcode to first in list}
util_stack_loc_start (sst_stack, stack_loc, univ_p); {reset the stack to empty}
util_stack_popto (sst_stack, univ_p);
{
* Init the state for writing the C source code into memory.
}
util_stack_push ( {create stack frame for starting scope}
sst_stack, sizeof(frame_scope_p^), frame_scope_p);
frame_scope_p^.prev_p := nil; {init stack frame for base scope}
frame_scope_p^.pos_decll := sst_out.dyn_p^;
frame_scope_p^.pos_exec := sst_out.dyn_p^;
frame_scope_p^.scope_p := sst_scope_p;
frame_scope_p^.funcval_sym_p := nil;
frame_scope_p^.const_p := nil;
frame_scope_p^.scope_type := scope_type_global_k;
frame_scope_p^.sment_type := sment_type_declg_k;
frame_sment_p := nil; {not currently in an executable statement}
pos_declg := sst_out.dyn_p^; {init position for global declarations}
sst_out.dyn_p := addr(pos_declg); {init to use position for global declarations}
{
* Write the output source code into the in-memory list of output lines.
}
sst_w_c_symbols (false); {declare any symbols used from root scope}
sst_w_c_opcodes (sst_opc_first_p); {process opcodes and write output lines}
if include then begin {writing include file ?}
write_string ('#ifdef __cplusplus', stat); if sys_error(stat) then return;
write_string ('extern "C" {', stat); if sys_error(stat) then return;
write_string ('#endif', stat); if sys_error(stat) then return;
write_string ('', stat); if sys_error(stat) then return;
end;
{
* Write the in-memory list of source lines to the output file.
}
sst_w.write^ (conn, stat); {write in-memory output lines to output file}
if include then begin {writing include file ?}
write_string ('#ifdef __cplusplus', stat); if sys_error(stat) then return;
write_string ('}', stat); if sys_error(stat) then return;
write_string ('#endif', stat); if sys_error(stat) then return;
end;
file_close (conn); {truncate and close output file}
end;
|
unit MVCFramework.Console;
interface
type
TConsoleMode = (Normal, Bright);
TConsoleColor = (
Black = 30,
Red = 31,
Green = 32,
Yellow = 33,
Blue = 34,
Magenta = 35,
Cyan = 36,
White = 37);
procedure ResetConsole;
procedure TextColor(const Color: TConsoleColor);
procedure TextBackground(const Color: TConsoleColor);
procedure SetMode(const ConsoleMode: TConsoleMode);
implementation
uses
{$IFDEF MSWINDOWS}
WinApi.Windows,
{$ENDIF}
System.SysUtils;
const
ESC = Chr(27);
var
GForeGround: TConsoleColor;
GBackGround: TConsoleColor;
GMode: TConsoleMode = TConsolemode.Normal;
function ToBackGround(const ForeGround: Byte): Byte;
begin
if (GMode = TConsoleMode.Bright) and (ForeGround <> Byte(TConsoleColor.Black)) then
begin
Result := ForeGround + 10 + 60;
end
else
begin
Result := ForeGround + 10;
end;
end;
{$IFDEF LINUX}
procedure EnableVirtualTerminalProcessing; inline;
begin
// do nothing
end;
{$ELSE}
procedure EnableVirtualTerminalProcessing; inline;
const
ENABLE_VIRTUAL_TERMINAL_PROCESSING = $0004;
var
hOut: THandle;
dwMode: UInt32;
begin
hOut := GetStdHandle(STD_OUTPUT_HANDLE);
if hOut = INVALID_HANDLE_VALUE then
raise Exception.CreateFmt('GetLastError() = %d', [GetLastError]);
dwMode := 0;
if (not GetConsoleMode(hOut, &dwMode)) then
raise Exception.CreateFmt('GetLastError() = %d', [GetLastError]);
dwMode := dwMode or ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (not SetConsoleMode(hOut, dwMode)) then
raise Exception.CreateFmt('GetLastError() = %d', [GetLastError]);
end;
{$ENDIF}
procedure ResetConsole;
begin
write(ESC + '[0m');
end;
function GetColorString: string;
begin
if GMode = TConsoleMode.Bright then
Result := Format('[%d;1;%dm', [Byte(GForeGround), ToBackGround(Byte(GBackGround))])
else
Result := Format('[%d;%dm', [Byte(GForeGround), ToBackGround(Byte(GBackGround))]);
end;
procedure TextColor(const Color: TConsoleColor);
begin
GForeGround := Color;
write(ESC + GetColorString);
end;
procedure TextBackground(const Color: TConsoleColor);
begin
GBackGround := Color;
write(ESC + GetColorString);
end;
procedure SetMode(const ConsoleMode: TConsoleMode);
begin
GMode := ConsoleMode;
end;
procedure InitDefault;
begin
GForeGround := TConsoleColor.White;
GBackGround := TConsoleColor.Black;
end;
initialization
EnableVirtualTerminalProcessing;
InitDefault;
finalization
end.
|
// Editor expert for expanding a macro template
unit GX_MacroTemplatesExpert;
interface
uses
Classes, ToolsAPI, GX_EditorExpert, GX_MacroTemplates,
GX_MacroFile, GX_ConfigurationInfo, GX_Actions, GX_MacroExpandNotifier;
type
TMacroTemplatesExpert = class;
TExpandTemplateSettings = class(TTemplateSettings)
public
procedure LoadSettings; override;
procedure SaveSettings; override;
procedure Reload; override;
end;
TInsertTemplateEvent = procedure(Sender: TObject; const ACode: string) of object;
TTemplateShortCut = class
protected
FAction: IGxAction;
FCode: string;
FOnExecute: TInsertTemplateEvent;
FOnUpdate: TNotifyEvent;
procedure HandleExecute(Sender: TObject);
procedure HandleUpdate(Sender: TObject);
procedure SetAction(Value: IGxAction);
public
destructor Destroy; override;
property Code: string read FCode write FCode;
property Action: IGxAction read FAction write SetAction;
property OnExecute: TInsertTemplateEvent read FOnExecute write FOnExecute;
property OnUpdate: TNotifyEvent read FOnUpdate write FOnUpdate;
end;
TMacroTemplatesExpert = class(TEditorExpert)
private
FMacroFile: TMacroFile;
FSettings: TExpandTemplateSettings;
FShortCuts: TList;
FExpandNotifier: IMacroExpandNotifier;
procedure AddUsesToUnit(ATemplateObject: TMacroObject);
function AddLeadingSpaces(const AString: string;
ASpacesCount: Integer; AInsertCol: Integer): string;
function PrefixLines(const Lines, Prefix: string; AStartLine: Integer = 1): string;
function PrepareWhitePrefix(AInsertCol: Integer): string;
procedure PrepareNewCursorPos(var VTemplateText: string;
AInsertPos: TOTAEditPos; var VNewPos: TOTAEditPos; ConsiderPipe: Boolean);
procedure ClearTemplShortCuts;
procedure AddTemplShortCut(const AName: string; AShortCut: TShortCut);
procedure TemplateActionExecute(Sender: TObject; const ACode: string);
function OffsetToEditPos(AOffset: Integer): TOTAEditPos;
procedure PrepareTemplateText(var VText: string;
ACurrentPos: TOTAEditPos; AAfterLen: Integer;
var InsertOffset: Integer; var InsertPos: TOTAEditPos);
procedure HandleExpandTemplate(const AName, AText: string; var Accepted: Boolean);
procedure RegisterExpandNotifier;
procedure RemoveExpandNotifier;
procedure ConfigAutoExpand;
protected
function GetTemplate(const ATemplateName: string; APromptForUnknown: Boolean = True): Integer;
procedure SetNewCursorPos(ANewEditPos: TOTAEditPos);
function CalculateNewCursorPos(const AString: string; ACursorPos: TOTAEditPos): TOTAEditPos;
procedure CalculateInsertPos(AInsertOption: TTemplateInsertPos;
var VInsertOffset: Integer; var VInsertPos: TOTAEditPos);
function GetProgrammerInfo(var VInfo: TProgrammerInfo): Boolean;
function CharPosToEditPos(ACharPos: TOTACharPos): TOTAEditPos;
procedure LoadTemplates;
procedure ExpandTemplate(const AForcedCode: string = '');
procedure CreateDefaultTemplates;
procedure SetAutoExpandActive(Value: Boolean);
public
constructor Create; override;
destructor Destroy; override;
procedure Execute(Sender: TObject); override;
procedure Configure; override;
function GetDefaultShortCut: TShortCut; override;
function GetDisplayName: string; override;
class function GetName: string; override;
function GetHelpString: string; override;
procedure InternalLoadSettings(Settings: TExpertSettings); override;
procedure InternalSaveSettings(Settings: TExpertSettings); override;
procedure ReloadSettings;
property Settings: TExpandTemplateSettings read FSettings;
property MacroFile: TMacroFile read FMacroFile;
end;
function GetExpandMacroExpert: TMacroTemplatesExpert;
function GetExpandMacroExpertReq: TMacroTemplatesExpert;
implementation
uses
SysUtils, Forms, Dialogs,
GX_GenericUtils, GX_MacroParser, GX_OtaUtils,
GX_ActionBroker, GX_MacroSelect, GX_UsesManager;
resourcestring
SFormOpenError = 'Config window already open ! (minimized ?)'#10 +
'Cannot open it this way';
type
TMacroDetails = record
Name: string;
Desc: string;
ImplUnit: string;
InsertPos: TTemplateInsertPos;
Text: string;
end;
const
CommonConfigurationKey = 'Common';
ShortCutIdent = 'ShortCut';
// Registry sections
ProgrammerIDKey = 'ProgammerID';
ProgrammerNameIdent = 'ProgrammerName';
ProgrammerInitialsIdent = 'ProgrammerInitials';
ExpandWithCharIdent = 'ExpandWithChar';
ExpandDelayIdent = 'ExpandDelay';
{$IFDEF GX_BCB}
CommentBegin = '/*';
CommentEnd = '*/';
{$ELSE GX_DELPHI}
CommentBegin = '{';
CommentEnd = '}';
{$ENDIF GX_DELPHI}
DefaultMacros: array[0..10] of TMacroDetails = (
( // 0
Name: '_';
Desc: 'embed _() for gettext()';
ImplUnit: 'gnugettext';
InsertPos: tipCursorPos;
Text:
'_(%SELECTION%|)';
),
( // 1
Name: 'ph';
Desc: 'Procedure Header';
ImplUnit: '';
InsertPos: tipLineStart;
Text:
CommentBegin + '-----------------------------------------------------------------------------' +sLineBreak+
' Procedure: %PROCNAME%' +sLineBreak+
' Author: %USER%' +sLineBreak+
' Date: %DAY%-%MONTHSHORTNAME%-%YEAR%' +sLineBreak+
' Arguments: %ARGUMENTS%' +sLineBreak+
' Result: %RESULT%' +sLineBreak+
'-----------------------------------------------------------------------------' + CommentEnd + sLineBreak + sLineBreak;
),
( // 2
Name: 'uh';
Desc: 'Unit Header';
ImplUnit: '';
InsertPos: tipUnitStart;
Text:
CommentBegin + '-----------------------------------------------------------------------------' +sLineBreak+
' Unit Name: %UNIT%' +sLineBreak+
' Author: %USER%' +sLineBreak+
' Date: %DAY%-%MONTHSHORTNAME%-%YEAR%' +sLineBreak+
' Purpose:' +sLineBreak+
' History:' +sLineBreak+
'-----------------------------------------------------------------------------' + CommentEnd + sLineBreak + sLineBreak;
),
( // 3
Name: 'sd';
Desc: 'Send Debug Message';
ImplUnit: 'DbugIntf';
InsertPos: tipCursorPos;
Text: '{$IFOPT D+} SendDebug(''|''); {$ENDIF}';
),
( // 4
Name: 'sdme';
Desc: 'Send Debug Method Enter/Exit';
ImplUnit: 'DbugIntf';
InsertPos: tipLineStart;
Text:
' %BEFORE%SendMethodEnter(''%METHODCLASS%'');' + sLineBreak +
' try' + sLineBreak +
' |' + sLineBreak +
' finally' + sLineBreak +
' SendMethodExit(''%METHODCLASS%'');' + sLineBreak +
' end;' + sLineBreak;
),
( // 5
Name: 'xdoc';
Desc: 'XML Method Documentation';
InsertPos: tipCursorPos;
Text:
'/// <summary>' + sLineBreak +
'/// |' + sLineBreak +
'/// </summary>' + sLineBreak +
'/// %BEGINPARAMLIST%<param name="%PARAMNAME%"></param>' + sLineBreak +
'/// %ENDPARAMLIST%<returns>%RESULT%</returns>';
),
( // 6
Name: 'begin';
Desc: 'Embed begin/end';
InsertPos: tipCursorPos;
Text:
'begin' + sLineBreak +
' %SELECTION%|' + sLineBreak +
'end;';
),
( // 7
Name: 'tryf';
Desc: 'Embed try/finally';
InsertPos: tipCursorPos;
Text:
'try' + sLineBreak +
' %SELECTION%|' + sLineBreak +
'finally' + sLineBreak +
'end;';
),
( // 8
Name: 'for';
Desc: 'For loop (basic)';
InsertPos: tipCursorPos;
Text: 'for | := 0 to do';
),
( // 9
Name: 'fori';
Desc: 'For loop with counter/embedding';
InsertPos: tipCursorPos;
Text:
'for i := 0 to |.Count - 1 do' + sLineBreak +
'begin' + sLineBreak +
' %SELECTION%' + sLineBreak +
'end;';
),
( // 10
Name: 'while';
Desc: 'Embed while/do/begin/end loop';
InsertPos: tipCursorPos;
Text:
'while | do' + sLineBreak +
'begin' + sLineBreak +
' %SELECTION%' + sLineBreak +
'end;';
)
);
var
GlobalExpandMacroExpert: TMacroTemplatesExpert = nil;
procedure RegisterExpandMacroExpert(AExpert: TMacroTemplatesExpert);
begin
if GlobalExpandMacroExpert = nil then
GlobalExpandMacroExpert := AExpert;
end;
procedure UnregisterExpandMacroExpert(AExpert: TMacroTemplatesExpert);
begin
if GlobalExpandMacroExpert = AExpert then
GlobalExpandMacroExpert := nil;
end;
function GetExpandMacroExpert: TMacroTemplatesExpert;
begin
Result := GlobalExpandMacroExpert;
end;
function GetExpandMacroExpertReq: TMacroTemplatesExpert;
resourcestring
SNoExpandMacroExpert = 'Macro Templates expert not found !';
begin
Result := GetExpandMacroExpert;
if Result = nil then
raise Exception.Create(SNoExpandMacroExpert);
end;
// Replaces a template in editor's buffer with a given template code
procedure InsertTemplateIntoEditor(const ATemplateName, ATemplateCode: string;
ATemplateOffset, AInsertOffset: Integer);
var
CodeLen: Integer;
InsertOff: Integer;
begin
CodeLen := Length(ATemplateName);
if ATemplateOffset = AInsertOffset then
begin
InsertOff := AInsertOffset + CodeLen;
GxOtaInsertTextIntoEditorAtCharPos(ATemplateCode, InsertOff);
// Delete template code (done after the insert to avoid problems)
if CodeLen > 0 then
GxOtaDeleteTextFromPos(ATemplateOffset, CodeLen);
end
else
begin
InsertOff := AInsertOffset;
if CodeLen > 0 then
GxOtaDeleteTextFromPos(ATemplateOffset, CodeLen);
GxOtaInsertTextIntoEditorAtCharPos(ATemplateCode, InsertOff);
end;
end;
destructor TTemplateShortCut.Destroy;
begin
FAction := nil;
inherited;
end;
procedure TTemplateShortCut.HandleExecute(Sender: TObject);
begin
if Assigned(FOnExecute) then
FOnExecute(Sender, FCode);
end;
procedure TTemplateShortCut.HandleUpdate(Sender: TObject);
begin
if Assigned(FOnUpdate) then
FOnUpdate(Sender);
end;
procedure TTemplateShortCut.SetAction(Value: IGxAction);
begin
FAction := Value;
if Assigned(FAction) then
begin
FAction.OnExecute := HandleExecute;
FAction.OnUpdate := HandleUpdate;
end;
end;
{ TMacroTemplatesExpert }
constructor TMacroTemplatesExpert.Create;
begin
Assert(GlobalExpandMacroExpert = nil, 'Expand Macro Expert already created!');
inherited Create;
RegisterExpandMacroExpert(Self);
RegisterProgrammerInfoProc(Self.GetProgrammerInfo);
FShortCuts := TList.Create;
FSettings := TExpandTemplateSettings.Create(Self);
try
FSettings.FMacroFileName := BuildFileName(ConfigInfo.ConfigPath, DefaultMacroFileName);
FMacroFile := TMacroFile.Create;
try
FMacroFile.FileName := FSettings.MacroFileName;
LoadTemplates;
except
FreeAndNil(FMacroFile);
raise;
end;
except
FreeAndNil(FSettings);
raise;
end;
end;
destructor TMacroTemplatesExpert.Destroy;
begin
RemoveExpandNotifier;
UnregisterExpandMacroExpert(Self);
FreeAndNil(FSettings);
FreeAndNil(FMacroFile);
ClearTemplShortCuts;
FreeAndNil(FShortCuts);
inherited Destroy;
end;
procedure TMacroTemplatesExpert.Configure;
var
fmMacroTemplates: TfmMacroTemplates;
begin
if FSettings.Form <> nil then
MessageDlg(SFormOpenError, mtInformation, [mbOk], 0)
else
begin
fmMacroTemplates := TfmMacroTemplates.Create(nil);
try
ConvertBitmapToIcon(GetBitmap, fmMacroTemplates.Icon);
fmMacroTemplates.Settings := FSettings;
fmMacroTemplates.ShowModal;
except // Free only on error (we free on close otherwise)
FreeAndNil(fmMacroTemplates);
raise;
end;
end;
end;
// Load the saved macro templates
procedure TMacroTemplatesExpert.LoadTemplates;
var
i: Integer;
begin
FMacroFile.LoadFromFile;
if FMacroFile.MacroCount < 1 then
CreateDefaultTemplates;
ClearTemplShortCuts;
for i := 0 to FMacroFile.MacroCount - 1 do
if FMacroFile[i].ShortCut <> EmptyShortCut then
AddTemplShortCut(FMacroFile[i].Name, FMacroFile[i].ShortCut);
end;
procedure TMacroTemplatesExpert.ClearTemplShortCuts;
var
Obj: TObject;
begin
while FShortCuts.Count > 0 do
begin
Obj := FShortCuts[FShortCuts.Count - 1];
FShortCuts.Delete(FShortCuts.Count - 1);
FreeAndNil(Obj);
end;
end;
procedure TMacroTemplatesExpert.AddTemplShortCut(const AName: string; AShortCut: TShortCut);
const
EditorExpertPrefix = 'EditorExpert'; // Do not localize.
TemplateActionPrefix = 'Macro template: ';
var
NewActionName: string;
NewGxAction: IGxAction;
NewShortCut: TTemplateShortCut;
begin
if AName = '' then
Exit;
NewActionName := EditorExpertPrefix + GetName + AName;
NewGxAction := GxActionBroker.RequestAction(NewActionName, GetBitmap);
NewGxAction.Caption := TemplateActionPrefix + AName;
NewGxAction.ShortCut := AShortCut;
NewShortCut := TTemplateShortCut.Create;
NewShortCut.Code := AName;
NewShortCut.Action := NewGxAction;
NewShortCut.OnExecute := TemplateActionExecute;
NewShortCut.OnUpdate := ActionOnUpdate;
FShortCuts.Add(NewShortCut);
end;
procedure TMacroTemplatesExpert.TemplateActionExecute(Sender: TObject; const ACode: string);
begin
ExpandTemplate(ACode);
end;
// Prepare white-space prefix for a template that is not inserted into
// the first column. AInsertCol is one-based.
function TMacroTemplatesExpert.PrepareWhitePrefix(AInsertCol: Integer): string;
var
EditView: IOTAEditView;
Idx: Integer;
begin
Result := '';
if not GxOtaTryGetTopMostEditView(EditView) then
Exit;
Result := GxOtaGetPreceedingCharactersInLine(EditView);
// Find the token start, if there is one under the cursor
Idx := AInsertCol - 1;
Result := Copy(Result, 1, Idx);
// Peplace all non-whitespace characters
for Idx := 1 to Length(Result) do
if not (IsCharWhiteSpace(Result[Idx])) then
Result[Idx] := ' ';
end;
function TMacroTemplatesExpert.AddLeadingSpaces(const AString: string;
ASpacesCount: Integer; AInsertCol: Integer): string;
var
WhiteString: string;
begin
if ASpacesCount < 1 then
begin
Result := AString;
Exit;
end;
WhiteString := PrepareWhitePrefix(AInsertCol);
Result := PrefixLines(AString, WhiteString);
end;
function TMacroTemplatesExpert.PrefixLines(const Lines, Prefix: string; AStartLine: Integer): string;
var
LastEOLFound: Boolean;
i: Integer;
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.Text := Lines;
LastEOLFound := HasTrailingEOL(Lines);
for i := AStartLine to SL.Count - 1 do
SL.Strings[i] := Prefix + SL.Strings[i];
Result := SL.Text;
// Workaround for TStrings limitation - it always adds
// an EOL when using the Text property
if (not LastEOLFound) and HasTrailingEOL(Result) then
RemoveLastEOL(Result);
finally
FreeAndNil(SL);
end;
end;
// Expand the macros in the template text, embed/delete selection, etc.
procedure TMacroTemplatesExpert.PrepareTemplateText(var VText: string;
ACurrentPos: TOTAEditPos; AAfterLen: Integer; var InsertOffset: Integer;
var InsertPos: TOTAEditPos);
var
PosAfter: TOTAEditPos;
DoParseSource: Boolean;
ReplaceSelection: Boolean;
BlockStart, BlockEnd: TOTAEditPos;
SelStart, SelLen: Integer;
OffsetPos: Integer;
LeadingText: string;
EOLOnEndOfTemp, EOLOnEndOfSel: Boolean;
begin
PosAfter := ACurrentPos;
PosAfter.Col := PosAfter.Col + AAfterLen;
Inc(PosAfter.Col);
OffsetPos := 0;
LeadingText := '';
EOLOnEndOfSel := False;
EOLOnEndOfTemp := False;
ReplaceSelection := StrContains('%SELECTION%', VText, False);
if ReplaceSelection then
begin
LeadingText := GxOtaGetLeadingWhiteSpaceInSelection;
EOLOnEndOfTemp := HasTrailingEOL(VText);
EOLOnEndOfSel := HasTrailingEOL(GxOtaGetCurrentSelection);
end;
DoParseSource := GxOtaGetCurrentSyntaxHighlighter = gxpPAS;
// Cursor moving is disabled for now, since it clears %SELECTION% in Delphi 7
//SetNewCursorPos(PosAfter);
try
VText := ReplaceStrings(VText, DoParseSource);
finally
//SetNewCursorPos(ACurrentPos);
end;
if ReplaceSelection and GxOtaGetSelection(nil, BlockStart, BlockEnd, SelStart, SelLen) then
begin
if (GxOtaCompareEditPos(BlockStart, ACurrentPos)<0) or
(GxOtaCompareEditPos(BlockEnd, ACurrentPos)<0)
then
begin
if (InsertOffset >= SelStart) and (InsertOffset < SelStart + SelLen) then
OffsetPos := SelStart - InsertOffset
else
OffsetPos := -SelLen;
if OffsetPos<>0 then
InsertOffset := InsertOffset + OffsetPos;
end;
// Clear old selection
GxOtaDeleteSelection;
end;
if OffsetPos <> 0 then
InsertPos := OffsetToEditPos(InsertOffset);
if ReplaceSelection then
begin
VText := PrefixLines(VText, LeadingText, 0);
if (not EOLOnEndOfSel) and EOLOnEndOfTemp then
RemoveLastEOL(VText);
end;
end;
function TMacroTemplatesExpert.CharPosToEditPos(ACharPos: TOTACharPos): TOTAEditPos;
var
EditView: IOTAEditView;
begin
Result.Col := 1;
Result.Line := 1;
if not GxOtaTryGetTopMostEditView(EditView) then
Exit;
EditView.ConvertPos(False, Result, ACharPos);
end;
function TMacroTemplatesExpert.OffsetToEditPos(AOffset: Integer): TOTAEditPos;
var
EditView: IOTAEditView;
CharPos: TOTACharPos;
begin
if not GxOtaTryGetTopMostEditView(EditView) then
raise Exception.Create('No edit view present');
CharPos := GxOtaGetCharPosFromPos(AOffset, EditView);
EditView.ConvertPos(False, Result, CharPos);
end;
procedure TMacroTemplatesExpert.Execute(Sender: TObject);
begin
ExpandTemplate;
end;
procedure TMacroTemplatesExpert.ExpandTemplate(const AForcedCode: string);
var
TemplateName: string;
TemplateText: string;
TemplateIdx: Integer;
InsertOffset: Integer;
CodeOffset: Integer;
AfterLen: Integer;
InsertPos, CurrentPos: TOTAEditPos; // In characters
NewCursorPos: TOTAEditPos; // Standard cursor position
CharPos: TOTACharPos;
TemplateObject: TMacroObject;
InsertWhiteCnt: Integer;
CodeForced, CodeInEditor: Boolean;
CursorPos: TOTAEditPos;
TemplateContainsPipe: Boolean;
begin
// Retrieve the template from the editor window
GxOtaGetCurrentIdentEx(TemplateName, CodeOffset, InsertPos, CurrentPos, AfterLen);
// CodeOffset: Offset of the identifier in the character stream (Integer)
// InsertPos: Position where the identifier starts (line/col, 1-based)
// CurrentPos: Current caret position (line/col)
// AfterLen: Length of the part of the identifier that is after cursor
// AForcedCode is set when a macro's shortcut is pressed or when the space expand
// notifier triggers (though the macro text is pre-deleted in this case)
if AForcedCode <> '' then
begin
TemplateName := AForcedCode;
AfterLen := 0;
CodeForced := True;
end
else
CodeForced := False;
// TODO 3 -oAnyone -cBug: Fix when pressing Shift+Alt+T or the template's shortcut with a non-template identifier under the cursor, but choosing another template to insert inserts the text before the identifier
// Locate the named template, or prompt for one if it does not exist
TemplateIdx := GetTemplate(TemplateName, not CodeForced);
if TemplateIdx < 0 then
Exit
else
begin
// Figure out how to make this work without messing up offsets with multi-line selections
//if not StrContains('%SELECTION%', TemplateText) then
// GxOtaDeleteSelection;
TemplateObject := FMacroFile.MacroItems[TemplateIdx];
TemplateText := TemplateObject.Text;
TemplateContainsPipe := StrContains('|', TemplateText);
// Convert to CRLF on Windows
if sLineBreak = #13#10 then
TemplateText := AdjustLineBreaks(TemplateText);
// Insert the macro into the editor
if TemplateText <> '' then
begin
CodeInEditor := (CurrentPos.Col + 1 <> InsertPos.Col) and (not CodeForced);
if CodeForced and (TemplateObject.InsertPos = tipCursorPos) then
begin
// For when the template is to be inserted directly at the end of a non-template-name identifier via a shortcut
// This was causing problems with templates like raise and is disabled
//CodeOffset := CodeOffset + Length(TemplateName);
//InsertPos := CurrentPos;
//InsertPos.Col := InsertPos.Col + 1;
end;
InsertOffset := CodeOffset;
// This does nothing for tipCursorPos:
CalculateInsertPos(TemplateObject.InsertPos, InsertOffset, InsertPos);
// Expand the macros in the template text, embed/delete selection, etc.
PrepareTemplateText(TemplateText, CurrentPos, AfterLen, InsertOffset, InsertPos);
if TemplateObject.InsertPos = tipCursorPos then
begin
InsertWhiteCnt := InsertPos.Col - 1; // insert pos is one-based
if InsertWhiteCnt > 0 then
TemplateText := AddLeadingSpaces(TemplateText, InsertWhiteCnt, InsertPos.Col)
else
begin
if CodeInEditor then
CursorPos := InsertPos // start of code in editor
else
CursorPos := GxOtaGetCurrentEditPos;
if CursorPos.Col > 1 then // Trim trailing blanks is on, and the user is not in the first column
TemplateText := PrefixLines(TemplateText, StringOfChar(' ', CursorPos.Col - 1), 0);
end;
end;
PrepareNewCursorPos(TemplateText, InsertPos, NewCursorPos, TemplateContainsPipe);
if CodeForced or (not SameText(TemplateName, TemplateObject.Name)) then
InsertTemplateIntoEditor('', TemplateText, CodeOffset, InsertOffset)
else
InsertTemplateIntoEditor(TemplateName, TemplateText, CodeOffset, InsertOffset);
CharPos.CharIndex := NewCursorPos.Col - 1;
CharPos.Line := NewCursorPos.Line;
CurrentPos := CharPosToEditPos(CharPos);
SetNewCursorPos(CurrentPos);
AddUsesToUnit(TemplateObject);
end;
end;
end;
procedure TMacroTemplatesExpert.AddUsesToUnit(ATemplateObject: TMacroObject);
begin
with TUsesManager.Create(GxOtaGetCurrentSourceEditor) do
try
AddUnits(ATemplateObject.PrivUnits, True);
AddUnits(ATemplateObject.PubUnits, False);
finally
Free;
end;
end;
function TMacroTemplatesExpert.GetTemplate(const ATemplateName: string;
APromptForUnknown: Boolean): Integer;
begin
Result := FMacroFile.IndexOf(ATemplateName);
if (Result < 0) and APromptForUnknown then
Result := GetTemplateFromUser(ATemplateName, FMacroFile);
end;
function TMacroTemplatesExpert.GetHelpString: string;
begin
Result := ' This expert expands templates that can include %-delimited macros. ' +
'It can be used in similar way to the IDE code templates, but is much more powerful because you can define custom shortcuts, insert positions, and include text-replacement macros. ' +
'The supported macros are available via the context menu in the template editor. See the help file for more complete documentation.';
end;
procedure TMacroTemplatesExpert.InternalLoadSettings(Settings: TExpertSettings);
var
SettingStorage: TMacroTemplatesIni;
begin
SettingStorage := TMacroTemplatesIni.Create;
try
FSettings.ProgrammerName := SettingStorage.ReadString(ProgrammerIDKey,
ProgrammerNameIdent, EmptyString);
if FSettings.ProgrammerName = EmptyStr then
FSettings.ProgrammerName := GetCurrentUser;
FSettings.ProgrammerInitials := SettingStorage.ReadString(ProgrammerIDKey,
ProgrammerInitialsIdent, EmptyString);
if FSettings.ProgrammerInitials = EmptyString then
FSettings.ProgrammerInitials := GetInitials(FSettings.ProgrammerName);
ShortCut := SettingStorage.ReadInteger(CommonConfigurationKey, ShortCutIdent, ShortCut);
FSettings.ExpandWithChar := SettingStorage.ReadBool(CommonConfigurationKey, ExpandWithCharIdent, FSettings.ExpandWithChar);
FSettings.ExpandDelay := SettingStorage.ReadInteger(CommonConfigurationKey, ExpandDelayIdent, -1);
ConfigAutoExpand;
finally
FreeAndNil(SettingStorage);
end;
end;
procedure TMacroTemplatesExpert.InternalSaveSettings(Settings: TExpertSettings);
var
SettingStorage: TMacroTemplatesIni;
begin
SettingStorage := TMacroTemplatesIni.Create;
try
SettingStorage.WriteInteger(CommonConfigurationKey, ShortCutIdent, ShortCut);
SettingStorage.WriteString(ProgrammerIDKey, ProgrammerNameIdent, FSettings.ProgrammerName);
SettingStorage.WriteString(ProgrammerIDKey, ProgrammerInitialsIdent, FSettings.ProgrammerInitials);
SettingStorage.WriteBool(CommonConfigurationKey, ExpandWithCharIdent, FSettings.ExpandWithChar);
if FSettings.ExpandDelay >= 0 then // Non-default
SettingStorage.WriteInteger(CommonConfigurationKey, ExpandDelayIdent, FSettings.ExpandDelay);
finally
FreeAndNil(SettingStorage);
end;
end;
// Prepare the new cursor position after insertion of a template
// Fix the template's text if a cursor indicator was found
procedure TMacroTemplatesExpert.PrepareNewCursorPos(var VTemplateText: string;
AInsertPos: TOTAEditPos; var VNewPos: TOTAEditPos; ConsiderPipe: Boolean);
var
CursorMarkIndex: Integer;
begin
// Calculate new cursor offset if it is assumed in macro code
CursorMarkIndex := Pos('|', VTemplateText);
if (CursorMarkIndex > 0) and ConsiderPipe then
begin // This does not account for any embedded pipes in a %SELECTION%
VNewPos := CalculateNewCursorPos(VTemplateText, AInsertPos);
Delete(VTemplateText, CursorMarkIndex, 1);
end
else
VNewPos := AInsertPos;
end;
procedure TMacroTemplatesExpert.SetNewCursorPos(ANewEditPos: TOTAEditPos);
resourcestring
SNoEditView = 'No edit view (you have found a bug!)';
var
EditView: IOTAEditView;
begin
if GxOtaTryGetTopMostEditView(EditView) then
EditView.CursorPos := ANewEditPos
else
raise Exception.Create(SNoEditView);
EditView.MoveViewToCursor;
EditView.Paint;
end;
// Calculate the new cursor postition using the old cursor
// position and position cursor marker "|" in AString
function TMacroTemplatesExpert.CalculateNewCursorPos(const AString: string;
ACursorPos: TOTAEditPos): TOTAEditPos;
var
i: Integer;
MarkIndex: Integer;
SL: TStringList;
begin
Result := ACursorPos;
SL := TStringList.Create;
try
SL.Text := AString;
for i := 0 to SL.Count - 1 do
begin
MarkIndex := Pos('|', SL.Strings[i]);
if MarkIndex > 0 then
begin
Result.Line := ACursorPos.Line + i;
if i > 0 then
Result.Col := MarkIndex
else
Result.Col := ACursorPos.Col + MarkIndex - 1;
end;
end;
finally
FreeAndNil(SL);
end;
end;
// Calculate the insert position based on AInsertOption
procedure TMacroTemplatesExpert.CalculateInsertPos(AInsertOption: TTemplateInsertPos;
var VInsertOffset: Integer; var VInsertPos: TOTAEditPos);
begin
case AInsertOption of
tipUnitStart:
begin
VInsertOffset := 0;
VInsertPos.Line := 1;
VInsertPos.Col := 1;
end;
tipLineStart:
begin
VInsertOffset := VInsertOffset - VInsertPos.Col + 1;
VInsertPos.Col := 1;
end;
tipLineEnd:
begin
// TODO 4 -oAnyone -cFeature: Complete line end template support
end;
// Otherwise, use the existing/current insert position
end;
end;
procedure TMacroTemplatesExpert.ReloadSettings;
begin
LoadSettings;
LoadTemplates;
end;
procedure TMacroTemplatesExpert.ConfigAutoExpand;
var
DelayMS: Integer;
begin
SetAutoExpandActive(FSettings.ExpandWithChar);
if FSettings.ExpandWithChar then
begin
DelayMS := FSettings.ExpandDelay * ExpandDelayNumerator;
if DelayMS < 0 then
DelayMS := DefExpandDelay
else if DelayMS < MinExpandDelay then
DelayMS := MinExpandDelay;
FExpandNotifier.SetExpandDelay(DelayMS);
end;
end;
function TMacroTemplatesExpert.GetProgrammerInfo(var VInfo: TProgrammerInfo): Boolean;
begin
VInfo.FullName := FSettings.ProgrammerName;
VInfo.Initials := FSettings.ProgrammerInitials;
Result := True;
end;
function TMacroTemplatesExpert.GetDefaultShortCut: TShortCut;
begin
Result := scShift + scAlt + Ord('T');
end;
function TMacroTemplatesExpert.GetDisplayName: string;
resourcestring
SMacroDisplayName = 'Expand Macro Template';
begin
Result := SMacroDisplayName;
end;
class function TMacroTemplatesExpert.GetName: string;
begin
Result := 'MacroTemplates';
end;
procedure TMacroTemplatesExpert.CreateDefaultTemplates;
var
Macro: TMacroObject;
i: Integer;
Default: TMacroDetails;
begin
MacroFile.Clear;
for i := Low(DefaultMacros) to High(DefaultMacros) do
begin
Default := DefaultMacros[i];
Macro := TMacroObject.Create(Default.Name);
Macro.Desc := Default.Desc;
Macro.Text := Default.Text;
Macro.InsertPos := Default.InsertPos;
Macro.PrivUnits.Text := Default.ImplUnit;
MacroFile.AddMacro(Macro);
end;
if PrepareDirectoryForWriting(ExtractFileDir(MacroFile.FileName)) then
MacroFile.SaveToFile(MacroFile.FileName);
end;
procedure TMacroTemplatesExpert.SetAutoExpandActive(Value: Boolean);
begin
if Value then
RegisterExpandNotifier
else
RemoveExpandNotifier;
end;
procedure TMacroTemplatesExpert.RegisterExpandNotifier;
begin
if not Assigned(FExpandNotifier) then
FExpandNotifier := PrepareNewExpandMacroNotifier(Self.HandleExpandTemplate);
end;
procedure TMacroTemplatesExpert.RemoveExpandNotifier;
begin
if Assigned(FExpandNotifier) then
begin
(FExpandNotifier as IMacroExpandNotifier).Detach;
FExpandNotifier := nil;
end;
end;
procedure TMacroTemplatesExpert.HandleExpandTemplate(const AName, AText: string; var Accepted: Boolean);
var
TemplateIdx: Integer;
TemplateOffset: Integer;
TextLen: Integer;
begin
Accepted := False;
TemplateIdx := GetTemplate(AName, False);
if TemplateIdx < 0 then
Exit;
TextLen := Length(AText);
TemplateOffset := GxOtaGetCurrentEditBufferPos - TextLen;
if TemplateOffset < 0 then
Exit;
GxOtaDeleteByteFromPos(TemplateOffset, TextLen);
ExpandTemplate(AName);
Accepted := True;
end;
{ TExpandTemplateSettings }
procedure TExpandTemplateSettings.LoadSettings;
begin
(FOwner as TMacroTemplatesExpert).LoadSettings;
end;
procedure TExpandTemplateSettings.SaveSettings;
begin
(FOwner as TMacroTemplatesExpert).SaveSettings;
end;
procedure TExpandTemplateSettings.Reload;
begin
(FOwner as TMacroTemplatesExpert).ReloadSettings;
end;
initialization
RegisterEditorExpert(TMacroTemplatesExpert);
end.
|
{ 2020/05/11 5.01 Move tests from unit flcTests into seperate units. }
{$INCLUDE flcTCPTest.inc}
unit flcTCPTest_Server;
interface
{ }
{ Test }
{ }
{$IFDEF TCPSERVER_TEST}
procedure Test;
{$ENDIF}
implementation
{$IFDEF TCPSERVER_TEST}
uses
SysUtils,
flcStdTypes,
flcSocketLib,
flcSocket,
flcTCPUtils,
flcTCPConnection,
flcTCPServer;
{$ENDIF}
{ }
{ Test }
{ }
{$IFDEF TCPSERVER_TEST}
{$ASSERTIONS ON}
procedure Test_Server_StartStop;
var S : TF5TCPServer;
I : Integer;
begin
S := TF5TCPServer.Create(nil);
try
// init
S.AddressFamily := iaIP4;
S.ServerPort := 10549;
S.MaxClients := -1;
Assert(S.State = ssInit);
Assert(not S.Active);
// activate
S.Active := True;
Assert(S.Active);
I := 0;
repeat
Inc(I);
Sleep(1);
until (S.State <> ssStarting) or (I >= 5000);
Assert(S.State = ssReady);
Assert(S.ClientCount = 0);
// shut down
S.Active := False;
Assert(not S.Active);
Assert(S.State = ssClosed);
finally
S.Finalise;
FreeAndNil(S);
end;
S := TF5TCPServer.Create(nil);
try
// init
S.AddressFamily := iaIP4;
S.ServerPort := 10545;
S.MaxClients := -1;
Assert(S.State = ssInit);
Assert(not S.Active);
// activate (wait for startup)
S.Start(True, 30000);
Assert(S.Active);
Assert(S.State = ssReady);
Assert(S.ClientCount = 0);
// shut down
S.Stop;
Assert(not S.Active);
Assert(S.State = ssClosed);
finally
S.Finalise;
FreeAndNil(S);
end;
S := TF5TCPServer.Create(nil);
try
// init
S.AddressFamily := iaIP4;
S.ServerPort := 10545;
S.MaxClients := -1;
Assert(S.State = ssInit);
for I := 1 to 10 do
begin
// activate
Assert(not S.Active);
S.Active := True;
Assert(S.Active);
// deactivate
S.Active := False;
Assert(not S.Active);
Assert(S.State = ssClosed);
end;
finally
S.Finalise;
FreeAndNil(S);
end;
end;
procedure Test_Server_Connections;
const
MaxConns = 10;
var
T : Word32;
S : TF5TCPServer;
C : array[1..MaxConns] of TSysSocket;
I : Integer;
begin
S := TF5TCPServer.Create(nil);
S.AddressFamily := iaIP4;
S.BindAddress := '127.0.0.1';
S.ServerPort := 12649;
S.MaxClients := -1;
S.Active := True;
Sleep(1000);
for I := 1 to MaxConns do
begin
C[I] := TSysSocket.Create(iaIP4, ipTCP, False);
C[I].Bind('127.0.0.1', 0);
C[I].SetBlocking(False);
end;
T := TCPGetTick;
for I := 1 to MaxConns do
begin
C[I].Connect('127.0.0.1', '12649');
Sleep(5);
if I mod 100 = 0 then
Writeln(I, ' ', Word32(TCPGetTick - T) / I:0:2);
end;
I := 0;
repeat
Sleep(10);
Inc(I, 10);
until (S.ClientCount = MaxConns) or (I > 12000);
Assert(S.ClientCount = MaxConns);
T := Word32(TCPGetTick - T);
Writeln(T / MaxConns:0:2);
for I := 1 to MaxConns do
C[I].Close;
for I := 1 to MaxConns do
FreeAndNil(C[I]);
S.Active := False;
Sleep(100);
S.Finalise;
S.Free;
end;
procedure Test_Server_MultiServers_Connections;
const
MaxSrvrs = 20;
MaxConns = 10;
var
T : Word32;
S : array[1..MaxSrvrs] of TF5TCPServer;
C : array[1..MaxSrvrs] of array[1..MaxConns] of TSysSocket;
SySo : TSysSocket;
I, J : Integer;
begin
for I := 1 to MaxSrvrs do
begin
S[I] := TF5TCPServer.Create(nil);
S[I].AddressFamily := iaIP4;
S[I].BindAddress := '127.0.0.1';
S[I].ServerPort := 12820 + I;
S[I].MaxClients := -1;
S[I].Active := True;
end;
Sleep(1000);
for J := 1 to MaxSrvrs do
for I := 1 to MaxConns do
begin
SySo := TSysSocket.Create(iaIP4, ipTCP, False);
C[J][I] := SySo;
SySo.Bind('127.0.0.1', 0);
SySo.SetBlocking(False);
end;
T := TCPGetTick;
for J := 1 to MaxSrvrs do
for I := 1 to MaxConns do
begin
C[J][I].Connect('127.0.0.1', RawByteString(IntToStr(12820 + J)));
if I mod 2 = 0 then
Sleep(50);
if I mod 100 = 0 then
Writeln(J, ' ', I, ' ', Word32(TCPGetTick - T) / (I + (J - 1) * MaxConns):0:2);
end;
I := 0;
Sleep(1000);
repeat
Sleep(1);
Inc(I);
until (S[MaxSrvrs].ClientCount = MaxConns) or (I > 10000);
Assert(S[MaxSrvrs].ClientCount = MaxConns);
T := Word32(TCPGetTick - T);
Writeln(T / (MaxConns * MaxSrvrs):0:2);
Sleep(1000);
for J := 1 to MaxSrvrs do
for I := 1 to MaxConns do
begin
C[J][I].Close;
C[J][I].Free;
end;
for I := 1 to MaxSrvrs do
S[I].Active := False;
for I := 1 to MaxSrvrs do
begin
S[I].Finalise;
S[I].Free;
end;
end;
procedure Test;
begin
Test_Server_StartStop;
Test_Server_Connections;
Test_Server_MultiServers_Connections;
end;
{$ENDIF}
end.
|
unit Document_Module;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "View"
// Модуль: "Document_Module.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: VCMFormsPack::Class Shared Delphi Sand Box$UC::Document::View::Document::Document
//
// Документ
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{$Include w:\common\components\SandBox\VCM\sbDefine.inc}
interface
uses
vcmExternalInterfaces {a},
vcmInterfaces {a},
vcmModule {a}
;
type
TDocumentModule = {formspack} class(TvcmModule)
{* Документ }
public
// public methods
class function DocumentPrintAndExportDefaultSetting: Boolean;
{* Метод для получения значения настройки "Печать и экспорт"."Использовать для экспорта и печати размер шрифта, отображаемого на экране" }
class function DocumentPrintAndExportCustomSetting: Boolean;
{* Метод для получения значения настройки "Печать и экспорт"."Использовать для экспорта и печати следующий размер шрифта" }
class function DocumentPrintAndExportFontSizeSetting: Integer;
{* Метод для получения значения настройки "Использовать для экспорта и печати следующий размер шрифта" }
class procedure WriteDocumentPrintAndExportFontSizeSetting(aValue: Integer);
{* Метод для записи значения настройки "Использовать для экспорта и печати следующий размер шрифта" }
end;//TDocumentModule
implementation
uses
afwFacade,
DocumentPrintAndExportSettingRes,
DocumentPrintAndExportFontSizeSettingRes,
stDocumentPrintAndExportFontSizeItem,
vcmFormSetFactory {a},
StdRes {a}
;
// start class TDocumentModule
class function TDocumentModule.DocumentPrintAndExportDefaultSetting: Boolean;
{-}
begin
if (afw.Settings = nil) then
Result := false
else
Result := afw.Settings.LoadBoolean(pi_Document_PrintAndExport_Default, false);
end;//TDocumentModule.DocumentPrintAndExportDefaultSetting
class function TDocumentModule.DocumentPrintAndExportCustomSetting: Boolean;
{-}
begin
if (afw.Settings = nil) then
Result := false
else
Result := afw.Settings.LoadBoolean(pi_Document_PrintAndExport_Custom, false);
end;//TDocumentModule.DocumentPrintAndExportCustomSetting
class function TDocumentModule.DocumentPrintAndExportFontSizeSetting: Integer;
{-}
begin
if (afw.Settings = nil) then
Result := dv_Document_PrintAndExportFontSize
else
Result := afw.Settings.LoadInteger(pi_Document_PrintAndExportFontSize, dv_Document_PrintAndExportFontSize);
end;//TDocumentModule.DocumentPrintAndExportFontSizeSetting
class procedure TDocumentModule.WriteDocumentPrintAndExportFontSizeSetting(aValue: Integer);
{-}
begin
if (afw.Settings <> nil) then
afw.Settings.SaveInteger(pi_Document_PrintAndExportFontSize, aValue);
end;//TDocumentModule.WriteDocumentPrintAndExportFontSizeSetting
end. |
unit UpdateLocationUnit;
interface
uses SysUtils, BaseExampleUnit, AddressBookContactUnit;
type
TUpdateLocation = class(TBaseExample)
public
procedure Execute(Contact: TAddressBookContact);
end;
implementation
procedure TUpdateLocation.Execute(Contact: TAddressBookContact);
var
ErrorString: String;
UpdatedContact: TAddressBookContact;
begin
UpdatedContact := Route4MeManager.AddressBookContact.Update(Contact, ErrorString);
try
WriteLn('');
if (UpdatedContact <> nil) then
WriteLn('UpdateLocation executed successfully')
else
WriteLn(Format('UpdateLocation error: "%s"', [ErrorString]));
finally
FreeAndNil(UpdatedContact);
end;
end;
end.
|
unit LUX.GPU.Vulkan.Framer;
interface //#################################################################### ■
uses System.Generics.Collections,
vulkan_core;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
TVkFramers<TVkSwapch_:class> = class;
TVkFramer<TVkSwapch_:class> = class;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkFramer
TVkFramer<TVkSwapch_:class> = class
private
type TVkFramers_ = TVkFramers<TVkSwapch_>;
protected
_Framers :TVkFramers_;
_Inform :VkImageViewCreateInfo;
_Handle :VkImageView;
///// アクセス
function GetSwapch :TVkSwapch_;
function GetImager :VkImage;
function GetHandle :VkImageView;
procedure SetHandle( const Handle_:VkImageView );
///// メソッド
procedure CreateHandle;
procedure DestroHandle;
public
constructor Create( const Framers_:TVkFramers_; const Imager_:VkImage );
destructor Destroy; override;
///// プロパティ
property Swapch :TVkSwapch_ read GetSwapch ;
property Framers :TVkFramers_ read _Framers;
property Inform :VkImageViewCreateInfo read _Inform ;
property Imager :VkImage read GetImager ;
property Handle :VkImageView read GetHandle write SetHandle;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkFramers
TVkFramers<TVkSwapch_:class> = class( TObjectList<TVkFramer<TVkSwapch_>> )
private
type TVkFramer_ = TVkFramer<TVkSwapch_>;
protected
_Swapch :TVkSwapch_;
_SelectI :UInt32;
///// アクセス
function GetSelect :TVkFramer_;
///// メソッド
procedure FindImages;
public
constructor Create( const Swapch_:TVkSwapch_ );
destructor Destroy; override;
///// プロパティ
property Swapch :TVkSwapch_ read _Swapch ;
property SelectI :UInt32 read _SelectI;
property Select :TVkFramer_ read GetSelect ;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
uses LUX.GPU.Vulkan;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkFramer
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TVkFramer<TVkSwapch_>.GetSwapch :TVkSwapch_;
begin
Result := _Framers.Swapch;
end;
//------------------------------------------------------------------------------
function TVkFramer<TVkSwapch_>.GetImager :VkImage;
begin
Result := _Inform.image;
end;
//------------------------------------------------------------------------------
function TVkFramer<TVkSwapch_>.GetHandle :VkImageView;
begin
if _Handle = 0 then CreateHandle;
Result := _Handle;
end;
procedure TVkFramer<TVkSwapch_>.SetHandle( const Handle_:VkImageView );
begin
if _Handle <> 0 then DestroHandle;
_Handle := Handle_;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TVkFramer<TVkSwapch_>.CreateHandle;
begin
Assert( vkCreateImageView( TVkSwapch( Swapch ).Device.Handle, @_Inform, nil, @_Handle ) = VK_SUCCESS );
end;
procedure TVkFramer<TVkSwapch_>.DestroHandle;
begin
vkDestroyImageView( TVkSwapch( Swapch ).Device.Handle, _Handle, nil );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TVkFramer<TVkSwapch_>.Create( const Framers_:TVkFramers_; const Imager_:VkImage );
begin
inherited Create;
_Handle := 0;
_Framers := Framers_;
_Framers.Add( Self );
with _Inform do
begin
sType := VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
pNext := nil;
flags := 0;
image := Imager_;
viewType := VK_IMAGE_VIEW_TYPE_2D;
format := TVkFramers( _Framers ).Swapch.Device.Format;
with components do
begin
r := VK_COMPONENT_SWIZZLE_R;
g := VK_COMPONENT_SWIZZLE_G;
b := VK_COMPONENT_SWIZZLE_B;
a := VK_COMPONENT_SWIZZLE_A;
end;
with subresourceRange do
begin
aspectMask := Ord( VK_IMAGE_ASPECT_COLOR_BIT );
baseMipLevel := 0;
levelCount := 1;
baseArrayLayer := 0;
layerCount := 1;
end;
end;
end;
destructor TVkFramer<TVkSwapch_>.Destroy;
begin
Handle := 0;
inherited;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkFramers
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
function TVkFramers<TVkSwapch_>.GetSelect :TVkFramer_;
begin
Result := Items[ _SelectI ];
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
procedure TVkFramers<TVkSwapch_>.FindImages;
var
VsN, I :UInt32;
Vs :TArray<VkImage>;
begin
Assert( vkGetSwapchainImagesKHR( TVkSwapch( _Swapch ).Device.Handle, TVkSwapch( _Swapch ).Handle, @VsN, nil ) = VK_SUCCESS );
Assert( VsN > 0 );
SetLength( Vs, VsN );
Assert( vkGetSwapchainImagesKHR( TVkSwapch( _Swapch ).Device.Handle, TVkSwapch( _Swapch ).Handle, @VsN, @Vs[0] ) = VK_SUCCESS );
for I := 0 to VsN-1 do TVkFramer.Create( TVkFramers( Self ), Vs[I] );
_SelectI := 0;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TVkFramers<TVkSwapch_>.Create( const Swapch_:TVkSwapch_ );
begin
inherited Create;
_Swapch := Swapch_;
FindImages;
end;
destructor TVkFramers<TVkSwapch_>.Destroy;
begin
inherited;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■
|
{
TForge Library
Copyright (c) Sergey Kasandrov 1997, 2018
-------------------------------------------------------
# DES block cipher algorithm
# NB: the code follows original hardware implementation:
# - block encryption and decryption functions are identical;
# - key expansion depends on block operation (encryption or decryption).
# This is a little cumbersome for software implementation, because
# CFB, OFB and CTR modes of operation use block encryption
# for decryption operation, and the key is expanded for encryption;
# that is why ExpandKey method has additional boolean parameter.
}
unit tfAlgDES;
{$I TFL.inc}
interface
uses
tfTypes;
type
PDESAlgorithm = ^TDESAlgorithm;
TDESAlgorithm = record
private type
PDESBlock = ^TDESBlock;
TDESBlock = record
case Byte of
0: (Bytes: array[0..7] of Byte);
1: (LWords: array[0..1] of UInt32);
end;
public type
PExpandedKey = ^TExpandedKey;
TExpandedKey = array[0..31] of UInt32;
public
FSubKeys: TExpandedKey;
// class procedure DoExpandKey(Key: PByte; var SubKeys: TExpandedKey; Encryption: Boolean); static;
// class procedure DoEncryptBlock(var SubKeys: TExpandedKey; Data: PByte); static;
function ExpandKey(Key: PByte; KeySize: Cardinal; Encryption: Boolean): TF_RESULT;
// function EncryptBlock(Data: PByte): TF_RESULT;
end;
PDES3Algorithm = ^TDES3Algorithm;
TDES3Algorithm = record
public
FSubKeys: array[0..2] of TDESAlgorithm.TExpandedKey;
function ExpandKey(Key: PByte; KeySize: Cardinal; Encryption: Boolean): TF_RESULT;
// function EncryptBlock(Data: PByte): TF_RESULT;
end;
procedure DesEncryptBlock(CPtr: PUint32; Data: PByte);
implementation
procedure DesExpandKey(Key: PByte; var SubKeys: TDESAlgorithm.TExpandedKey;
Encryption: Boolean);
const
PC1 : array [0..55] of Byte =
(56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26,
18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21,
13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3);
PC2 : array [0..47] of Byte =
(13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7,
15, 6, 26, 19, 12, 1, 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47,
43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31);
CTotRot : array [0..15] of Byte = (1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28);
CBitMask : array [0..7] of Byte = (128, 64, 32, 16, 8, 4, 2, 1);
var
PC1M : array [0..55] of Byte;
PC1R : array [0..55] of Byte;
KS : array [0..7] of Byte;
I, J, L, M : Int32;
begin
{convert PC1 to bits of key}
for J := 0 to 55 do begin
L := PC1[J];
M := L mod 8;
PC1M[J] := Ord((Key[L div 8] and CBitMask[M]) <> 0);
end;
{key chunk for each iteration}
for I := 0 to 15 do begin
{rotate PC1 the right amount}
for J := 0 to 27 do begin
L := J + CTotRot[I];
if (L < 28) then begin
PC1R[J] := PC1M[L];
PC1R[J + 28] := PC1M[L + 28];
end else begin
PC1R[J] := PC1M[L - 28];
PC1R[J + 28] := PC1M[L];
end;
end;
{select bits individually}
FillChar(KS, SizeOf(KS), 0);
for J := 0 to 47 do
if Boolean(PC1R[PC2[J]]) then begin
L := J div 6;
KS[L] := KS[L] or CBitMask[J mod 6] shr 2;
end;
{now convert to odd/even interleaved form for use in F}
if Encryption then begin
SubKeys[I * 2] := (Int32(KS[0]) shl 24) or (Int32(KS[2]) shl 16) or
(Int32(KS[4]) shl 8) or (Int32(KS[6]));
SubKeys[I * 2 + 1] := (Int32(KS[1]) shl 24) or (Int32(KS[3]) shl 16) or
(Int32(KS[5]) shl 8) or (Int32(KS[7]));
end
else begin
SubKeys[31 - (I * 2 + 1)] := (Int32(KS[0]) shl 24) or (Int32(KS[2]) shl 16) or
(Int32(KS[4]) shl 8) or (Int32(KS[6]));
SubKeys[31 - (I * 2)] := (Int32(KS[1]) shl 24) or (Int32(KS[3]) shl 16) or
(Int32(KS[5]) shl 8) or (Int32(KS[7]));
end;
end;
end;
const
SPBox: array[0..7,0..63] of UInt32 = ({$I DES_SPBoxes.inc});
procedure SplitBlock(Block: PByte; var L, R: UInt32);
{$IFDEF ASM86}
asm
PUSH EBX
PUSH EAX
MOV EAX,[EAX]
MOV BH,AL
MOV BL,AH
ROL EBX,16 // Block.Bytes[0] --> L.Bytes[3]
SHR EAX,16 // Block.Bytes[1] --> L.Bytes[2]
MOV BH,AL // Block.Bytes[2] --> L.Bytes[1]
MOV BL,AH // Block.Bytes[3] --> L.Bytes[0]
MOV [EDX],EBX
POP EAX
MOV EAX,[EAX+4]
MOV BH,AL
MOV BL,AH
ROL EBX,16 // Block.Bytes[4] --> R.Bytes[3]
SHR EAX,16 // Block.Bytes[5] --> R.Bytes[2]
MOV BH,AL // Block.Bytes[6] --> R.Bytes[1]
MOV BL,AH // Block.Bytes[7] --> R.Bytes[0]
MOV [ECX],EBX
POP EBX
end;
{$ELSE}
var
P: PByte;
begin
P:= PByte(@L) + 3;
P^:= Block^; Inc(Block); Dec(P);
P^:= Block^; Inc(Block); Dec(P);
P^:= Block^; Inc(Block); Dec(P);
P^:= Block^; Inc(Block);
P:= PByte(@R) + 3;
P^:= Block^; Inc(Block); Dec(P);
P^:= Block^; Inc(Block); Dec(P);
P^:= Block^; Inc(Block); Dec(P);
P^:= Block^;
end;
{$ENDIF}
procedure JoinBlock(const L, R: UInt32; Block: PByte);
{$IFDEF ASM86}
asm
PUSH EBX
MOV BH,AL
MOV BL,AH
ROL EBX,16 // L.Bytes[0] --> Block.Bytes[7]
SHR EAX,16 // L.Bytes[1] --> Block.Bytes[6]
MOV BH,AL // L.Bytes[2] --> Block.Bytes[5]
MOV BL,AH // L.Bytes[3] --> Block.Bytes[4]
MOV [ECX+4],EBX
MOV BH,DL
MOV BL,DH
ROL EBX,16 // R.Bytes[0] --> Block.Bytes[3]
SHR EDX,16 // R.Bytes[1] --> Block.Bytes[2]
MOV BH,DL // R.Bytes[2] --> Block.Bytes[1]
MOV BL,DH // R.Bytes[3] --> Block.Bytes[0]
MOV [ECX],EBX
POP EBX
end;
{$ELSE}
var
P: PByte;
begin
P:= PByte(@R) + 3;
Block^:= P^; Inc(Block); Dec(P);
Block^:= P^; Inc(Block); Dec(P);
Block^:= P^; Inc(Block); Dec(P);
Block^:= P^; Inc(Block);
P:= PByte(@L) + 3;
Block^:= P^; Inc(Block); Dec(P);
Block^:= P^; Inc(Block); Dec(P);
Block^:= P^; Inc(Block); Dec(P);
Block^:= P^;
end;
{$ENDIF}
procedure IPerm(var L, R : UInt32);
var
Work : UInt32;
begin
Work := ((L shr 4) xor R) and $0F0F0F0F;
R := R xor Work;
L := L xor Work shl 4;
Work := ((L shr 16) xor R) and $0000FFFF;
R := R xor Work;
L := L xor Work shl 16;
Work := ((R shr 2) xor L) and $33333333;
L := L xor Work;
R := R xor Work shl 2;
Work := ((R shr 8) xor L) and $00FF00FF;
L := L xor Work;
R := R xor Work shl 8;
R := (R shl 1) or (R shr 31);
Work := (L xor R) and $AAAAAAAA;
L := L xor Work;
R := R xor Work;
L := (L shl 1) or (L shr 31);
end;
procedure FPerm(var L, R : UInt32);
var
Work : UInt32;
begin
L := L;
R := (R shl 31) or (R shr 1);
Work := (L xor R) and $AAAAAAAA;
L := L xor Work;
R := R xor Work;
L := (L shr 1) or (L shl 31);
Work := ((L shr 8) xor R) and $00FF00FF;
R := R xor Work;
L := L xor Work shl 8;
Work := ((L shr 2) xor R) and $33333333;
R := R xor Work;
L := L xor Work shl 2;
Work := ((R shr 16) xor L) and $0000FFFF;
L := L xor Work;
R := R xor Work shl 16;
Work := ((R shr 4) xor L) and $0F0F0F0F;
L := L xor Work;
R := R xor Work shl 4;
end;
procedure DesEncryptBlock(CPtr: PUint32; //var SubKeys: TDesAlgorithm.TExpandedKey;
Data: PByte);
var
I, L, R, Work : UInt32;
// CPtr : PUInt32;
begin
SplitBlock(Data, L, R);
IPerm(L, R);
// CPtr := @SubKeys;
for I := 0 to 7 do begin
Work := (((R shr 4) or (R shl 28)) xor CPtr^);
Inc(CPtr);
L := L xor SPBox[6, Work and $3F];
L := L xor SPBox[4, Work shr 8 and $3F];
L := L xor SPBox[2, Work shr 16 and $3F];
L := L xor SPBox[0, Work shr 24 and $3F];
Work := (R xor CPtr^);
Inc(CPtr);
L := L xor SPBox[7, Work and $3F];
L := L xor SPBox[5, Work shr 8 and $3F];
L := L xor SPBox[3, Work shr 16 and $3F];
L := L xor SPBox[1, Work shr 24 and $3F];
Work := (((L shr 4) or (L shl 28)) xor CPtr^);
Inc(CPtr);
R := R xor SPBox[6, Work and $3F];
R := R xor SPBox[4, Work shr 8 and $3F];
R := R xor SPBox[2, Work shr 16 and $3F];
R := R xor SPBox[0, Work shr 24 and $3F];
Work := (L xor CPtr^);
Inc(CPtr);
R := R xor SPBox[7, Work and $3F];
R := R xor SPBox[5, Work shr 8 and $3F];
R := R xor SPBox[3, Work shr 16 and $3F];
R := R xor SPBox[1, Work shr 24 and $3F];
end;
FPerm(L, R);
JoinBlock(L, R, Data);
end;
{ TDESAlgorithm }
function TDesAlgorithm.ExpandKey(Key: PByte; KeySize: Cardinal;
Encryption: Boolean): TF_RESULT;
begin
if KeySize <> 8 then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
DesExpandKey(Key, FSubKeys, Encryption);
Result:= TF_S_OK;
end;
{ TDES3Algorithm }
function TDES3Algorithm.ExpandKey(Key: PByte; KeySize: Cardinal;
Encryption: Boolean): TF_RESULT;
begin
if (KeySize <> 8) and (KeySize <> 16) and (KeySize <> 24) then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
if Encryption then begin
DesExpandKey(Key, FSubKeys[0], True);
if KeySize > 8 then
DesExpandKey(Key + 8, FSubKeys[1], False)
else
DesExpandKey(Key, FSubKeys[1], False);
if KeySize > 16 then
DesExpandKey(Key + 16, FSubKeys[2], True)
else
DesExpandKey(Key, FSubKeys[2], True);
end
else begin
if KeySize > 16 then
DesExpandKey(Key + 16, FSubKeys[0], False)
else
DesExpandKey(Key, FSubKeys[0], False);
if KeySize > 8 then
DesExpandKey(Key + 8, FSubKeys[1], True)
else
DesExpandKey(Key, FSubKeys[1], True);
DesExpandKey(Key, FSubKeys[2], False);
end;
Result:= TF_S_OK;
end;
end.
|
unit define_datetime;
interface
type
PDatePack = ^TDatePack;
TDatePack = packed record
Year : Word;
Month : Word;
Day : Word;
end;
PTimePack = ^TTimePack;
TTimePack = packed record
Hour : Word;
Minute : Word;
Second : Word;
MSecond : Word;
end;
PDateTimePack = ^TDateTimePack;
TDateTimePack = packed record
Date : TDatePack;
Time : TTimePack;
end;
PDateStock = ^TDateStock;
TDateStock = packed record
Value : Word;
end;
PTimeStock = ^TTimeStock;
TTimeStock = packed record
Value : Word;
end;
PDateTimeStock = ^TDateTimeStock;
TDateTimeStock = packed record // 4
Date : TDateStock; // 2
Time : TTimeStock; // 2
end;
PRT_DateTime = ^TRT_DateTime;
TRT_DateTime = packed record
Value : double; // 8
end;
(*//
DayTime M0 模式
6:00 开始计算
06:00 -- 24:00 计算到秒
18 * 3600 = 64800
65565 - 64800 = 765
00:00 -- 06:00 以分钟计
6 * 60 = 360
00:01
00:02
765 - 360 = 405
1 -- 06:00:00
2 -- 06:00:01
60 -- 06:00:59
61 -- 06:01:00
//*)
PDayTimeM0 = ^TDayTimeM0;
TDayTimeM0 = packed record // 4
Value : Word;
end;
PDateTimeM0 = ^TDayTimeM0;
TDateTimeM0 = packed record // 4
Date : Word;
Time : TDayTimeM0;
end;
procedure Date2DatePack(ADate: Integer; ADatePack: PDatePack);
procedure Time2TimePack(ATime: TDateTime; ATimePack: PTimePack);
function Time2TimeStock(ATime: TDateTime; ATimeStock: PTimeStock): Boolean;
function TimeStock2Time(ATimeStock: PTimeStock): TDateTime;
function DateTime2DateTimeStock(ATime: TDateTime; ADateTimeStock: PDateTimeStock): Boolean;
function DateTimeStock2DateTime(ADateTimeStock: PDateTimeStock): TDateTime;
function GetTimeText(ATime: PTimeStock): AnsiString;
function DecodeTimeStock(AStockTime: TTimeStock; var AHour: integer; var AMinute: integer; var ASecond: integer): Boolean;
function EncodeDayTime0(AHour: Byte; AMinute: Byte; ASecond: Byte): Word;
function DecodeDayTime0(ADayTimeM0: Word; var AHour: Byte; var AMinute: Byte; var ASecond: Byte): Boolean;
implementation
uses
Sysutils;
{$IFNDEF RELEASE}
const
LOGTAG = 'define_datetime.pas';
{$ENDIF}
//(*//
function DecodeTimeStock(AStockTime: TTimeStock; var AHour: integer; var AMinute: integer; var ASecond: integer): Boolean;
begin
Result := false;
if 0 < AStockTime.Value then
begin
AHour := Trunc(AStockTime.Value div 3600);
if AHour < 7 {16 - 9} then
begin
ASecond := AStockTime.Value - AHour * 3600;
AMinute := Trunc(ASecond div 60);
ASecond := ASecond - AMinute * 60;
AHour := AHour + 9;
Result := true;
end;
end;
end;
//*)
procedure Date2DatePack(ADate: Integer; ADatePack: PDatePack);
begin
DecodeDate(ADate, ADatePack.Year, ADatePack.Month, ADatePack.Day);
end;
procedure Time2TimePack(ATime: TDateTime; ATimePack: PTimePack);
begin
DecodeTime(ATime, ATimePack.Hour, ATimePack.Minute, ATimePack.Second, ATimePack.MSecond);
end;
function GetTimeText(ATime: PTimeStock): AnsiString;
var
tmpHour: Integer;
tmpMinute: Integer;
tmpSecond: Integer;
begin
Result := '';
if nil <> ATime then
begin
tmpHour := Trunc(ATime.Value div 3600);
tmpSecond := ATime.Value - tmpHour * 3600;
tmpMinute := Trunc(tmpSecond div 60);
tmpSecond := tmpSecond - tmpMinute * 60;
Result := IntToStr(tmpHour + 9) + ':' + IntToStr(tmpMinute) + ':' + IntToStr(tmpSecond);
end;
end;
function Time2TimeStock(ATime: TDateTime; ATimeStock: PTimeStock): Boolean;
var
tmpTimePack: TTimePack;
begin
result := false;
if nil = ATimeStock then
Exit;
Time2TimePack(ATime, @tmpTimePack);
// 9 点开始 3600 秒
ATimeStock.Value := 0;
if (8 < tmpTimePack.Hour) and (16 > tmpTimePack.Hour) then
begin
ATimeStock.Value := (3600 * (tmpTimePack.Hour - 9)) + (60 * tmpTimePack.Minute) + tmpTimePack.Second;
result := true;
end;
end;
function TimeStock2Time(ATimeStock: PTimeStock): TDateTime;
var
tmpTimePack: TTimePack;
tmpValue: Word;
begin
tmpValue := ATimeStock.Value;
tmpTimePack.Hour := tmpValue div 3600;
tmpValue := tmpValue - tmpTimePack.Hour * 3600;
tmpTimePack.Minute := tmpValue div 60;
tmpValue := tmpValue - tmpTimePack.Minute * 60;
tmpTimePack.Second := tmpValue;
tmpTimePack.MSecond := 0;
tmpTimePack.Hour := tmpTimePack.Hour + 9;
Result := EncodeTime(tmpTimePack.Hour, tmpTimePack.Minute, tmpTimePack.Second, tmpTimePack.MSecond);
end;
function DateTime2DateTimeStock(ATime: TDateTime; ADateTimeStock: PDateTimeStock): Boolean;
begin
ADateTimeStock.Date.Value := Trunc(ATime);
Result := Time2TimeStock(ATime, @ADateTimeStock.Time);
end;
function DateTimeStock2DateTime(ADateTimeStock: PDateTimeStock): TDateTime;
begin
Result := ADateTimeStock.Date.Value + TimeStock2Time(@ADateTimeStock.Time);
end;
function EncodeDayTime0(AHour: Byte; AMinute: Byte; ASecond: Byte): Word;
begin
Result := 0;
if AHour < 6 then
begin
(*
00:00:00 -- 1
00:01:00 -- 2
00:59:00 -- 60
01:00:00 -- 61
01:59:00 -- 120
02:00:00 -- 121
03:00:00 -- 181
04:00:00 -- 241
05:00:00 -- 301
06:00:00 -- 361
*)
if (AMinute < 60) and (ASecond < 60) then
begin
Result := AHour * 60 + AMinute + 1;
end;
end else
begin
{
06:00:01 -- 362
06:00:02 -- 363
}
if (AHour < 24) and (AMinute < 60) and (ASecond < 60) then
begin
Result := (AHour - 6) * 3600 + (AMinute * 60) + ASecond + 361;
end;
end;
end;
function DecodeDayTime0(ADayTimeM0: Word; var AHour: Byte; var AMinute: Byte; var ASecond: Byte): Boolean;
begin
Result := false;
if 360 < ADayTimeM0 then
begin
Result := true;
AHour := (ADayTimeM0 - 361) div 3600;
ADayTimeM0 := (ADayTimeM0 - 361) - AHour * 3600;
AHour := AHour + 6;
ASecond := ADayTimeM0 mod 60;
AMinute := ADayTimeM0 div 60;
end else
begin
if 0 < ADayTimeM0 then
begin
Result := true;
AHour := (ADayTimeM0 - 1) div 60;
AMinute := (ADayTimeM0 - 1) mod 60;
ASecond := 0;
end;
end;
end;
(*//
procedure TfrmSDConsole.btn1Click(Sender: TObject);
procedure AddTimeLog(AHour, AMinute, ASecond: Byte);
var
dayTime: Word;
tmpHour: Byte;
tmpMinute: Byte;
tmpSecond: Byte;
tmpStr: string;
begin
dayTime := EncodeDayTime0(AHour, AMinute, ASecond);
DecodeDayTime0(dayTime, tmpHour, tmpMinute, tmpSecond);
tmpStr := IntToStr(AHour) + ':' + IntToStr(AMinute) + ':' + IntToStr(ASecond) + ' -- ' +
IntToStr(dayTime) + ' -- ' +
IntToStr(tmpHour) + ':' + IntToStr(tmpMinute) + ':' + IntToStr(tmpSecond);
mmo1.Lines.Add(tmpStr);
end;
begin
inherited;
mmo1.Lines.Clear;
mmo1.Lines.BeginUpdate;
try
AddTimeLog(0, 0, 0);
AddTimeLog(1, 0, 0);
AddTimeLog(2, 0, 0);
AddTimeLog(3, 0, 0);
AddTimeLog(4, 0, 0);
AddTimeLog(5, 0, 0);
AddTimeLog(6, 0, 0);
AddTimeLog(6, 0, 1);
AddTimeLog(6, 0, 2);
AddTimeLog(6, 0, 59);
AddTimeLog(6, 1, 1);
AddTimeLog(6, 2, 1);
AddTimeLog(6, 3, 1);
AddTimeLog(6, 4, 1);
AddTimeLog(6, 5, 1);
AddTimeLog(6, 10, 59);
AddTimeLog(10, 40, 59);
AddTimeLog(10, 58, 59);
AddTimeLog(10, 59, 59);
AddTimeLog(23, 0, 0);
AddTimeLog(23, 1, 1);
AddTimeLog(23, 1, 59);
AddTimeLog(23, 2, 59);
AddTimeLog(23, 3, 59);
AddTimeLog(23, 4, 59);
AddTimeLog(23, 5, 59);
AddTimeLog(23, 10, 1);
AddTimeLog(23, 20, 1);
AddTimeLog(23, 55, 1);
AddTimeLog(23, 59, 58);
AddTimeLog(23, 59, 59); // -- 65160
finally
mmo1.Lines.EndUpdate;
end;
end;
//*)
end.
|
unit multiple_dm;
interface
uses
Windows, Messages, SysUtils, Classes, HTTPApp, WebModu, HTTPProd,
WebAdapt, WebComp, CompProd, PagItems, SiteProd, MidItems, WebForm;
type
Tmultiple = class(TWebPageModule)
AdapterPageProducer: TAdapterPageProducer;
PagedAdapter1: TPagedAdapter;
NumbersList: TStringsValuesList;
AdapterForm1: TAdapterForm;
AdapterGrid1: TAdapterGrid;
AdapterCommandGroup1: TAdapterCommandGroup;
CmdPrevPage: TAdapterActionButton;
CmdGotoPage: TAdapterActionButton;
CmdNextPage: TAdapterActionButton;
Number: TAdapterMultiValueField;
Square: TAdapterMultiValueField;
ColNumber: TAdapterDisplayColumn;
ColSquare: TAdapterDisplayColumn;
AdapterField: TAdapterField;
procedure WebPageModuleActivate(Sender: TObject);
procedure NumberGetValues(Sender: TObject;
Index: Integer; var Value: Variant);
procedure NumberGetValueCount(Sender: TObject;
var Count: Integer);
procedure SquareGetValues(Sender: TObject; Index: Integer;
var Value: Variant);
procedure PagedAdapter1GetRecordCount(Sender: TObject;
var Count: Integer);
procedure PagedAdapter1GetNextRecord(Sender: TObject;
var EOF: Boolean);
procedure PagedAdapter1GetFirstRecord(Sender: TObject;
var EOF: Boolean);
procedure PagedAdapter1GetEOF(Sender: TObject; var EOF: Boolean);
procedure PagedAdapter1GetRecordIndex(Sender: TObject;
var Index: Integer);
procedure AdapterFieldGetValue(Sender: TObject; var Value: Variant);
private
CurrentPos: Integer;
public
{ Public declarations }
end;
function multiple: Tmultiple;
implementation
{$R *.dfm} {*.html}
uses WebReq, WebCntxt, WebFact, Variants;
function multiple: Tmultiple;
begin
Result := Tmultiple(WebContext.FindModuleClass(Tmultiple));
end;
procedure Tmultiple.WebPageModuleActivate(Sender: TObject);
var
i: Integer;
begin
for i := 1 to 100 do
NumbersList.Strings.Add(
IntToStr(i) + '=' + IntToStr (Sqr(i)));
end;
procedure Tmultiple.NumberGetValues(Sender: TObject;
Index: Integer; var Value: Variant);
begin
Value := NumbersList.Strings.Names [Index];
end;
procedure Tmultiple.NumberGetValueCount(Sender: TObject;
var Count: Integer);
begin
Count := NumbersList.Strings.Count;
end;
procedure Tmultiple.SquareGetValues(Sender: TObject; Index: Integer;
var Value: Variant);
begin
with NumbersList.Strings do
Value := Values [Names [Index]];
end;
procedure Tmultiple.PagedAdapter1GetRecordCount(Sender: TObject;
var Count: Integer);
begin
Count := NumbersList.Strings.Count;
end;
procedure Tmultiple.PagedAdapter1GetNextRecord(Sender: TObject;
var EOF: Boolean);
begin
Inc (CurrentPos);
EOF := (CurrentPos = NumbersList.Strings.Count - 1);
end;
procedure Tmultiple.PagedAdapter1GetFirstRecord(Sender: TObject;
var EOF: Boolean);
begin
CurrentPos := 0;
end;
procedure Tmultiple.PagedAdapter1GetEOF(Sender: TObject; var EOF: Boolean);
begin
EOF := (CurrentPos = NumbersList.Strings.Count);
end;
procedure Tmultiple.PagedAdapter1GetRecordIndex(Sender: TObject;
var Index: Integer);
begin
CurrentPos := Index;
end;
procedure Tmultiple.AdapterFieldGetValue(Sender: TObject;
var Value: Variant);
begin
Value := NumbersList.Strings.Names [CurrentPos];
end;
initialization
if WebRequestHandler <> nil then
WebRequestHandler.AddWebModuleFactory(TWebPageModuleFactory.Create(Tmultiple, TWebPageInfo.Create([wpPublished {, wpLoginRequired}], '.html'), crOnDemand, caCache));
end.
|
unit fTester;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Trakce, Spin, ExtCtrls;
type
TF_Tester = class(TForm)
M_Log: TMemo;
E_Path: TEdit;
B_Load: TButton;
B_Unload: TButton;
B_DCC_Go: TButton;
B_DCC_Stop: TButton;
B_Show_Config: TButton;
B_Open: TButton;
B_Close: TButton;
Label1: TLabel;
CB_Loglevel: TComboBox;
SE_Loco_Addr: TSpinEdit;
Label2: TLabel;
B_Loco_Acquire: TButton;
B_Loco_Release: TButton;
SE_Speed: TSpinEdit;
Label3: TLabel;
RG_Direction: TRadioGroup;
B_Set_Speed: TButton;
SE_Func_Mask: TSpinEdit;
Label4: TLabel;
Label5: TLabel;
SE_Func_State: TSpinEdit;
B_Set_Func: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure B_LoadClick(Sender: TObject);
procedure B_UnloadClick(Sender: TObject);
procedure M_LogDblClick(Sender: TObject);
procedure B_Show_ConfigClick(Sender: TObject);
procedure B_DCC_GoClick(Sender: TObject);
procedure B_DCC_StopClick(Sender: TObject);
procedure B_OpenClick(Sender: TObject);
procedure B_CloseClick(Sender: TObject);
procedure B_Loco_AcquireClick(Sender: TObject);
procedure B_Loco_ReleaseClick(Sender: TObject);
procedure B_Set_SpeedClick(Sender: TObject);
procedure B_Set_FuncClick(Sender: TObject);
private
{ Private declarations }
public
trakce: TTrakceIFace;
procedure Log(Sender: TObject; logLevel:TTrkLogLevel; msg:string);
procedure OnAppException(Sender: TObject; E: Exception);
procedure OnTrackStatusChanged(Sender: TObject; status: TTrkStatus);
procedure OnLocoStolen(Sender: TObject; addr: Word);
procedure OnTrkSetOk(Sender: TObject; data: Pointer);
procedure OnTrkSetError(Sender: TObject; data: Pointer);
procedure OnTrkLocoAcquired(Sender: TObject; LocoInfo: TTrkLocoInfo);
procedure OnTrkBeforeOpen(Sender: TObject);
procedure OnTrkAfterOpen(Sender: TObject);
procedure OnTrkBeforeClose(Sender: TObject);
procedure OnTrkAfterClose(Sender: TObject);
end;
var
F_Tester: TF_Tester;
implementation
{$R *.dfm}
procedure TF_Tester.B_CloseClick(Sender: TObject);
begin
trakce.Disconnect();
end;
procedure TF_Tester.B_DCC_GoClick(Sender: TObject);
begin
trakce.SetTrackStatus(TTrkStatus.tsOn, TTrakceIFace.Callback(Self.OnTrkSetOk),
TTrakceIFace.Callback(Self.OnTrkSetError));
end;
procedure TF_Tester.B_DCC_StopClick(Sender: TObject);
begin
trakce.SetTrackStatus(TTrkStatus.tsOff, TTrakceIFace.Callback(Self.OnTrkSetOk),
TTrakceIFace.Callback(Self.OnTrkSetError));
end;
procedure TF_Tester.B_LoadClick(Sender: TObject);
var unbound, lib: string;
begin
Self.Log(Self, llInfo, 'Loading library...');
trakce.LoadLib(Self.E_Path.Text);
Self.Log(Self, llInfo, 'Library loaded');
unbound := '';
for lib in trakce.unbound do
unbound := unbound + lib + ', ';
if (unbound <> '') then
Self.Log(Self, llErrors, 'Unbound: ' + unbound);
end;
procedure TF_Tester.B_Loco_AcquireClick(Sender: TObject);
begin
trakce.LocoAcquire(Self.SE_Loco_Addr.Value, Self.OnTrkLocoAcquired, TTrakceIFace.Callback(Self.OnTrkSetError));
end;
procedure TF_Tester.B_Loco_ReleaseClick(Sender: TObject);
begin
trakce.LocoRelease(Self.SE_Loco_Addr.Value, TTrakceIFace.Callback(Self.OnTrkSetOk));
end;
procedure TF_Tester.B_OpenClick(Sender: TObject);
begin
trakce.Connect();
end;
procedure TF_Tester.B_Set_FuncClick(Sender: TObject);
begin
trakce.LocoSetFunc(Self.SE_Loco_Addr.Value, Self.SE_Func_Mask.Value, Self.SE_Func_State.Value,
TTrakceIFace.Callback(Self.OnTrkSetOk), TTrakceIFace.Callback(Self.OnTrkSetError));
end;
procedure TF_Tester.B_Set_SpeedClick(Sender: TObject);
begin
trakce.LocoSetSpeed(Self.SE_Loco_Addr.Value, Self.SE_Speed.Value, Self.RG_Direction.ItemIndex = 1,
TTrakceIFace.Callback(Self.OnTrkSetOk), TTrakceIFace.Callback(Self.OnTrkSetError));
end;
procedure TF_Tester.B_Show_ConfigClick(Sender: TObject);
begin
trakce.ShowConfigDialog();
end;
procedure TF_Tester.B_UnloadClick(Sender: TObject);
begin
Self.Log(Self, llInfo, 'Unloading library...');
trakce.UnloadLib();
Self.Log(Self, llInfo, 'Library unloaded');
end;
procedure TF_Tester.FormCreate(Sender: TObject);
begin
Application.OnException := Self.OnAppException;
Self.trakce := TTrakceIFace.Create();
Self.trakce.OnLog := Self.Log;
Self.trakce.OnTrackStatusChanged := Self.OnTrackStatusChanged;
Self.trakce.OnLocoStolen := Self.OnLocoStolen;
Self.trakce.BeforeOpen := Self.OnTrkBeforeOpen;
Self.trakce.AfterOpen := Self.OnTrkAfterOpen;
Self.trakce.BeforeClose := Self.OnTrkBeforeClose;
Self.trakce.AfterClose := Self.OnTrkAfterClose;
end;
procedure TF_Tester.FormDestroy(Sender: TObject);
begin
Self.trakce.Free();
end;
procedure TF_Tester.M_LogDblClick(Sender: TObject);
begin
Self.M_Log.Clear();
end;
procedure TF_Tester.Log(Sender: TObject; logLevel:TTrkLogLevel; msg:string);
begin
if (Integer(logLevel) <= Self.CB_Loglevel.ItemIndex) then
Self.M_Log.Lines.Insert(0, FormatDateTime('hh:nn:ss,zzz', Now) + ': ' +
trakce.LogLevelToString(logLevel) + ': ' + msg);
end;
procedure TF_Tester.OnAppException(Sender: TObject; E: Exception);
begin
Self.Log(Self, llErrors, 'Exception: ' + E.Message);
end;
procedure TF_Tester.OnTrackStatusChanged(Sender: TObject; status: TTrkStatus);
begin
case (status) of
tsUnknown: Self.Log(Self, llInfo, 'Track status changed: UNKNOWN');
tsOff: Self.Log(Self, llInfo, 'Track status changed: OFF');
tsOn: Self.Log(Self, llInfo, 'Track status changed: ON');
tsProgramming: Self.Log(Self, llInfo, 'Track status changed: PROGRAMMING');
end;
end;
procedure TF_Tester.OnLocoStolen(Sender: TObject; addr: Word);
begin
Self.Log(Self, llInfo, 'Loco stolen: ' + IntToStr(addr));
end;
procedure TF_Tester.OnTrkSetOk(Sender: TObject; data: Pointer);
begin
Self.Log(Self, llInfo, 'OK, data: ' + IntToStr(Integer(data)));
end;
procedure TF_Tester.OnTrkSetError(Sender: TObject; data: Pointer);
begin
Self.Log(Self, llErrors, 'ERR, data: ' + IntToStr(Integer(data)));
end;
procedure TF_Tester.OnTrkBeforeOpen(Sender: TObject);
begin
Self.Log(Self, llInfo, 'BeforeOpen');
end;
procedure TF_Tester.OnTrkAfterOpen(Sender: TObject);
begin
Self.Log(Self, llInfo, 'AfterOpen');
end;
procedure TF_Tester.OnTrkBeforeClose(Sender: TObject);
begin
Self.Log(Self, llInfo, 'BeforeClose');
end;
procedure TF_Tester.OnTrkAfterClose(Sender: TObject);
begin
Self.Log(Self, llInfo, 'AfterClose');
end;
procedure TF_Tester.OnTrkLocoAcquired(Sender: TObject; LocoInfo: TTrkLocoInfo);
begin
Self.Log(Self, llInfo, 'Get loco info: addr: ' + IntToStr(LocoInfo.addr) +
', speed: ' + IntToStr(LocoInfo.speed) + ', dir: ' + BoolToStr(LocoInfo.direction) +
', func: ' + IntToStr(LocoInfo.functions));
end;
end.
|
unit PoligonForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, WormsWorld, Grids, Vcl.ExtCtrls,
System.ImageList, Vcl.ImgList, wwFullScreenForm;
type
TPoligonMainForm = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
MapSizeCombo: TComboBox;
WormsCountCombo: TComboBox;
TargetCountCombo: TComboBox;
Label3: TLabel;
Label2: TLabel;
StartButton: TButton;
StopButton: TButton;
GroupBox2: TGroupBox;
StatisticView: TListView;
MapButton: TButton;
MapGrid: TDrawGrid;
CheckBox1: TCheckBox;
Worms8ImageList: TImageList;
procedure StartButtonClick(Sender: TObject);
procedure StopButtonClick(Sender: TObject);
procedure MapButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure MapGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure CheckBox1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FWorld: TWormsField;
FCAncel: Boolean;
FMapVisible: Boolean;
FShowIdeas: Boolean;
f_FSForm: TFSForm;
procedure NewIdea(Sender: TObject);
public
{ Public declarations }
end;
var
PoligonMainForm: TPoligonMainForm;
implementation
{$R *.dfm}
Uses
Types, wwClasses, wwTypes, wwUtils;
procedure TPoligonMainForm.StartButtonClick(Sender: TObject);
var
Bounds: TRect;
i: Integer;
Itm: TListItem;
begin
Bounds.Left:= 0; Bounds.Top:= 0;
case MapSizeCombo.ItemIndex of
0:
begin
Bounds.Right:= 640 div 16;
Bounds.Bottom:= 480 div 16;
end;
1:
begin
Bounds.Right:= 800 div 16;
Bounds.Bottom:= 600 div 16;
end;
2:
begin
Bounds.Right:= 1024 div 16;
Bounds.Bottom:= 768 div 16;
end;
3:
begin
Bounds.Right:= 1280 div 16;
Bounds.Bottom:= 1024 div 16;
end;
4:
begin
Bounds.Right:= 1920 div 16;
Bounds.Bottom:= 1080 div 16;
end;
5:
begin
Bounds.Right:= 3860 div 16;
Bounds.Bottom:= 2160 div 16;
end;
end;
with MapGrid do
begin
ColCount:= Bounds.Right+1;
DefaultColWidth:= (Width - ColCount) div ColCount;
RowCount:= Bounds.Bottom+1;
DefaultRowHeight:= (Height - RowCount) div RowCount;
end;
StatisticView.Items.Clear;
for i:= 0 to 4 do
begin
Itm:= StatisticView.Items.Add;
Itm.Caption:= '';
Itm.SubItems.Add('');
Itm.SubItems.Add('');
Itm.SubItems.Add('');
Itm.SubItems.Add('');
end; // for i
FCancel:= False;
StartButton.Enabled:= False;
StopButton.Enabled:= True;
MapButton.Enabled:= True;
GroupBox1.Enabled:= False;
FWorld:= TWormsField.Create(Bounds);
try
FWorld.MaxTargetCount:= Succ(TargetCountCombo.ItemIndex);
FWorld.MaxWormsCount:= Succ(WormsCountCombo.ItemIndex);
FWorld.InstantRessurectTargets:= True;
FWorld.InstantRessurectWorms:= True;
FWorld.OnNewIdea:= NewIdea;
f_FSForm:= TFSForm.Create(Application);
try
f_FSForm.World:= fWorld;
FCancel:= False; FShowIdeas:= False;
repeat
FWorld.Update;
for i:= 0 to Pred(FWorld.WormsCount) do
begin
itm:= StatisticView.Items[i];
itm.Caption:= FWorld.Worms[i].Mind.Caption;
itm.SubItems.Strings[0]:= IntToStr(FWorld.Worms[i].Length);
itm.SubItems.Strings[1]:= IntToStr(FWorld.Worms[i].Mind.MaxThingLength);
itm.SubItems.Strings[2]:= IntToStr(FWorld.Worms[i].Mind.Weight)+'%';
Itm.SubItems.Strings[3]:= IntToStr(FWorld.Worms[i].Age);
end; // for i
if FMapVisible then
begin
// MapGrid.Invalidate;
// WorldPaintBox.Invalidate;
if f_FSForm.Visible then
f_FSForm.Invalidate
else
FMapVisible:= False;
end;
Application.ProcessMessages;
Sleep(25);
until FCancel;
finally
FreeAndNil(f_FSForm);
end;
FWorld.MindCenter.Resort;
StatisticView.Items.Clear;
for i:= Pred(FWorld.MindCenter.Count) downto 0 do
begin
Itm:= StatisticView.Items.Add;
Itm.Caption:= FWorld.MindCenter.Minds[i].Caption;
Itm.SubItems.Add(IntToStr(FWorld.MindCenter.Minds[i].AverageLength));
Itm.SubItems.Add(IntToStr(FWorld.MindCenter.Minds[i].MaxThingLength));
Itm.SubItems.Add(IntToStr(FWorld.MindCenter.Minds[i].Weight)+'%');
end; // for i
finally
FWorld.Free;
MapButton.Enabled:= False;
StopButton.Enabled:= False;
StartButton.Enabled:= True;
GroupBox1.Enabled:= True;
end;
end;
procedure TPoligonMainForm.StopButtonClick(Sender: TObject);
begin
FCancel:= True;
end;
procedure TPoligonMainForm.MapButtonClick(Sender: TObject);
var
l_Form: TFSForm;
begin
FMapVisible:= not FMapVisible;
if FMapVisible then
begin
f_FSForm.Show;
end;
(*
if FMapVisible then
begin
ClientHeight:= MapGrid.Top + MapGrid.Height + 10;
Width:=550;
end
else
begin
ClientHeight:= GroupBox2.Top+GroupBox2.Height+10;
Width:=550;
end;
*)
end;
procedure TPoligonMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
StopButton.Click;
end;
procedure TPoligonMainForm.FormCreate(Sender: TObject);
begin
DoubleBuffered:= True;
Randomize;
ClientHeight:= GroupBox2.Top+GroupBox2.Height+10;
//Width:=550;
FMapVisible:= False;
end;
const
WormColor : array[0..4] of TColor = (clBlue, clGreen, clTeal, clPurple, clGray);
TargetColor : array[-1..1] of TColor = (clLtGray, clRed, clMaroon);
procedure TPoligonMainForm.MapGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
l_T: TwwThing;
begin
if not FCancel and FMapVisible then
begin
MapGrid.Canvas.Brush.Color:= clWhite;
l_T:= FWorld.ThingAt(Point(aCol, aRow));
if l_T <> nil then
begin
if l_T.Entity = weLive then
MapGrid.Canvas.Brush.Color:= WormColor[l_T.Variety]
else
MapGrid.Canvas.Brush.Color:= TargetColor[l_T.Variety];
end; // l_T <> nil
MapGrid.Canvas.FillRect(Rect);
end; // FCancel
end;
procedure TPoligonMainForm.NewIdea(Sender: TObject);
begin
if FMapVisible and FShowIdeas then
MapGrid.Refresh;
Application.ProcessMessages;
end;
procedure TPoligonMainForm.CheckBox1Click(Sender: TObject);
begin
FShowIdeas:= CheckBox1.Checked;
end;
end.
|
unit WorldControl;
interface
uses
Math, TypeControl, FacilityControl, PlayerControl, TerrainTypeControl, VehicleControl, VehicleUpdateControl, WeatherTypeControl;
type
TWorld = class
private
FTickIndex: LongInt;
FTickCount: LongInt;
FWidth: Double;
FHeight: Double;
FPlayers: TPlayerArray;
FNewVehicles: TVehicleArray;
FVehicleUpdates: TVehicleUpdateArray;
FTerrainByCellXY: TTerrainTypeArray2D;
FWeatherByCellXY: TWeatherTypeArray2D;
FFacilities: TFacilityArray;
public
constructor Create(const tickIndex: LongInt; const tickCount: LongInt; const width: Double; const height: Double;
const players: TPlayerArray; const newVehicles: TVehicleArray; const vehicleUpdates: TVehicleUpdateArray;
const terrainByCellXY: TTerrainTypeArray2D; const weatherByCellXY: TWeatherTypeArray2D;
const facilities: TFacilityArray);
function GetTickIndex: LongInt;
property TickIndex: LongInt read GetTickIndex;
function GetTickCount: LongInt;
property TickCount: LongInt read GetTickCount;
function GetWidth: Double;
property Width: Double read GetWidth;
function GetHeight: Double;
property Height: Double read GetHeight;
function GetPlayers: TPlayerArray;
property Players: TPlayerArray read GetPlayers;
function GetNewVehicles: TVehicleArray;
property NewVehicles: TVehicleArray read GetNewVehicles;
function GetVehicleUpdates: TVehicleUpdateArray;
property VehicleUpdates: TVehicleUpdateArray read GetVehicleUpdates;
function GetTerrainByCellXY: TTerrainTypeArray2D;
property TerrainByCellXY: TTerrainTypeArray2D read GetTerrainByCellXY;
function GetWeatherByCellXY: TWeatherTypeArray2D;
property WeatherByCellXY: TWeatherTypeArray2D read GetWeatherByCellXY;
function GetFacilities: TFacilityArray;
property Facilities: TFacilityArray read GetFacilities;
function GetMyPlayer: TPlayer;
function GetOpponentPlayer: TPlayer;
destructor Destroy; override;
end;
TWorldArray = array of TWorld;
implementation
constructor TWorld.Create(const tickIndex: LongInt; const tickCount: LongInt; const width: Double; const height: Double;
const players: TPlayerArray; const newVehicles: TVehicleArray; const vehicleUpdates: TVehicleUpdateArray;
const terrainByCellXY: TTerrainTypeArray2D; const weatherByCellXY: TWeatherTypeArray2D;
const facilities: TFacilityArray);
var
i: LongInt;
begin
FTickIndex := tickIndex;
FTickCount := tickCount;
FWidth := width;
FHeight := height;
if Assigned(players) then begin
FPlayers := Copy(players, 0, Length(players));
end else begin
FPlayers := nil;
end;
if Assigned(newVehicles) then begin
FNewVehicles := Copy(newVehicles, 0, Length(newVehicles));
end else begin
FNewVehicles := nil;
end;
if Assigned(vehicleUpdates) then begin
FVehicleUpdates := Copy(vehicleUpdates, 0, Length(vehicleUpdates));
end else begin
FVehicleUpdates := nil;
end;
if Assigned(terrainByCellXY) then begin
SetLength(FTerrainByCellXY, Length(terrainByCellXY));
for i := High(terrainByCellXY) downto 0 do begin
if Assigned(terrainByCellXY[i]) then begin
FTerrainByCellXY[i] := Copy(terrainByCellXY[i], 0, Length(terrainByCellXY[i]));
end else begin
FTerrainByCellXY[i] := nil;
end;
end;
end else begin
FTerrainByCellXY := nil;
end;
if Assigned(weatherByCellXY) then begin
SetLength(FWeatherByCellXY, Length(weatherByCellXY));
for i := High(weatherByCellXY) downto 0 do begin
if Assigned(weatherByCellXY[i]) then begin
FWeatherByCellXY[i] := Copy(weatherByCellXY[i], 0, Length(weatherByCellXY[i]));
end else begin
FWeatherByCellXY[i] := nil;
end;
end;
end else begin
FWeatherByCellXY := nil;
end;
if Assigned(facilities) then begin
FFacilities := Copy(facilities, 0, Length(facilities));
end else begin
FFacilities := nil;
end;
end;
function TWorld.GetTickIndex: LongInt;
begin
result := FTickIndex;
end;
function TWorld.GetTickCount: LongInt;
begin
result := FTickCount;
end;
function TWorld.GetWidth: Double;
begin
result := FWidth;
end;
function TWorld.GetHeight: Double;
begin
result := FHeight;
end;
function TWorld.GetPlayers: TPlayerArray;
begin
if Assigned(FPlayers) then begin
result := Copy(FPlayers, 0, Length(FPlayers));
end else begin
result := nil;
end;
end;
function TWorld.GetNewVehicles: TVehicleArray;
begin
if Assigned(FNewVehicles) then begin
result := Copy(FNewVehicles, 0, Length(FNewVehicles));
end else begin
result := nil;
end;
end;
function TWorld.GetVehicleUpdates: TVehicleUpdateArray;
begin
if Assigned(FVehicleUpdates) then begin
result := Copy(FVehicleUpdates, 0, Length(FVehicleUpdates));
end else begin
result := nil;
end;
end;
function TWorld.GetTerrainByCellXY: TTerrainTypeArray2D;
var
i: LongInt;
begin
if Assigned(FTerrainByCellXY) then begin
SetLength(result, Length(FTerrainByCellXY));
for i := High(FTerrainByCellXY) downto 0 do begin
if Assigned(FTerrainByCellXY[i]) then begin
result[i] := Copy(FTerrainByCellXY[i], 0, Length(FTerrainByCellXY[i]));
end else begin
result[i] := nil;
end;
end;
end else begin
result := nil;
end;
end;
function TWorld.GetWeatherByCellXY: TWeatherTypeArray2D;
var
i: LongInt;
begin
if Assigned(FWeatherByCellXY) then begin
SetLength(result, Length(FWeatherByCellXY));
for i := High(FWeatherByCellXY) downto 0 do begin
if Assigned(FWeatherByCellXY[i]) then begin
result[i] := Copy(FWeatherByCellXY[i], 0, Length(FWeatherByCellXY[i]));
end else begin
result[i] := nil;
end;
end;
end else begin
result := nil;
end;
end;
function TWorld.GetFacilities: TFacilityArray;
begin
if Assigned(FFacilities) then begin
result := Copy(FFacilities, 0, Length(FFacilities));
end else begin
result := nil;
end;
end;
function TWorld.GetMyPlayer: TPlayer;
var
playerIndex: LongInt;
begin
for playerIndex := High(FPlayers) downto 0 do begin
if FPlayers[playerIndex].GetMe then begin
result := FPlayers[playerIndex];
exit;
end;
end;
result := nil;
end;
function TWorld.GetOpponentPlayer: TPlayer;
var
playerIndex: LongInt;
begin
for playerIndex := High(FPlayers) downto 0 do begin
if not FPlayers[playerIndex].GetMe then begin
result := FPlayers[playerIndex];
exit;
end;
end;
result := nil;
end;
destructor TWorld.Destroy;
var
i: LongInt;
begin
if Assigned(FPlayers) then begin
for i := High(FPlayers) downto 0 do begin
if Assigned(FPlayers[i]) then begin
FPlayers[i].Free;
end;
end;
end;
if Assigned(FNewVehicles) then begin
for i := High(FNewVehicles) downto 0 do begin
if Assigned(FNewVehicles[i]) then begin
FNewVehicles[i].Free;
end;
end;
end;
if Assigned(FVehicleUpdates) then begin
for i := High(FVehicleUpdates) downto 0 do begin
if Assigned(FVehicleUpdates[i]) then begin
FVehicleUpdates[i].Free;
end;
end;
end;
if Assigned(FFacilities) then begin
for i := High(FFacilities) downto 0 do begin
if Assigned(FFacilities[i]) then begin
FFacilities[i].Free;
end;
end;
end;
inherited;
end;
end.
|
UNIT Pseudo_ver2;
INTERFACE
TYPE
SignsPlace = SET OF 1 .. 25;
SignsLine = SET OF 1 .. 250;
FUNCTION FindLetterNumberEn(VAR F: TEXT): INTEGER; { Sets to each letter in F-file equal number in EN_alphabet }
PROCEDURE GetPseudoLetterLine(VAR Number: INTEGER; VAR F: TEXT); { Prepearing alph-file before creating Pseudo-symbol }
PROCEDURE CreatingPseudoLine(VAR F: TEXT); { Makes PseudoLine of signs }
PROCEDURE WritingPseudoLine; { Use it after CreatingPseudoLine proc,
to write out letters in pseudo_graphic style! 10 chars - max }
PROCEDURE WritePseudo(VAR PseudoLetter: SignsPlace); { Writes ONE! letter in pseudo graphics }
IMPLEMENTATION
CONST
Rows = 5;
Columns = 5;
VAR
AlphEn, AlphRu: TEXT;
Pseudos: SignsLine;
LetterAmount: INTEGER;
FUNCTION FindLetterNumberEn(VAR F: TEXT): INTEGER;
VAR
Letter: CHAR;
Number: INTEGER;
BEGIN {FindLetterNumberEn}
Number := -1;
IF NOT EOLN(F)
THEN
BEGIN
READ(F, Letter);
IF (Letter = 'A') OR (Letter = 'a') THEN Number := 1 ELSE
IF (Letter = 'B') OR (Letter = 'b') THEN Number := 2 ELSE
IF (Letter = 'C') OR (Letter = 'c') THEN Number := 3 ELSE
IF (Letter = 'D') OR (Letter = 'd') THEN Number := 4 ELSE
IF (Letter = 'E') OR (Letter = 'e') THEN Number := 5 ELSE
IF (Letter = 'F') OR (Letter = 'f') THEN Number := 6 ELSE
IF (Letter = 'G') OR (Letter = 'g') THEN Number := 7 ELSE
IF (Letter = 'H') OR (Letter = 'h') THEN Number := 8 ELSE
IF (Letter = 'I') OR (Letter = 'i') THEN Number := 9 ELSE
IF (Letter = 'J') OR (Letter = 'j') THEN Number := 10 ELSE
IF (Letter = 'K') OR (Letter = 'k') THEN Number := 11 ELSE
IF (Letter = 'L') OR (Letter = 'l') THEN Number := 12 ELSE
IF (Letter = 'M') OR (Letter = 'm') THEN Number := 13 ELSE
IF (Letter = 'N') OR (Letter = 'n') THEN Number := 14 ELSE
IF (Letter = 'O') OR (Letter = 'o') THEN Number := 15 ELSE
IF (Letter = 'P') OR (Letter = 'p') THEN Number := 16 ELSE
IF (Letter = 'Q') OR (Letter = 'q') THEN Number := 17 ELSE
IF (Letter = 'R') OR (Letter = 'r') THEN Number := 18 ELSE
IF (Letter = 'S') OR (Letter = 's') THEN Number := 19 ELSE
IF (Letter = 'T') OR (Letter = 't') THEN Number := 20 ELSE
IF (Letter = 'U') OR (Letter = 'u') THEN Number := 21 ELSE
IF (Letter = 'V') OR (Letter = 'v') THEN Number := 22 ELSE
IF (Letter = 'W') OR (Letter = 'w') THEN Number := 23 ELSE
IF (Letter = 'X') OR (Letter = 'x') THEN Number := 24 ELSE
IF (Letter = 'Y') OR (Letter = 'y') THEN Number := 25 ELSE
IF (Letter = 'Z') OR (Letter = 'z') THEN Number := 26 ELSE
IF (Letter = '.') THEN Number := 27 ELSE
IF (Letter = ',') THEN Number := 28 ELSE
IF (Letter = '!') THEN Number := 29 ELSE
IF (Letter = '?') THEN Number := 30 ELSE
IF (Letter = '''') THEN Number := 31 ELSE
IF (Letter = '-') THEN Number := 32 ELSE
IF (Letter = '"') THEN Number := 33 ELSE
IF (Letter = ':') THEN Number := 34 ELSE
IF (Letter = ';') THEN Number := 35 ELSE
IF (Letter = '<') THEN Number := 36 ELSE
IF (Letter = '>') THEN Number := 37 ELSE
IF (Letter = '~') THEN Number := 38 ELSE
IF (Letter = '`') THEN Number := 39 ELSE
IF (Letter = '@') THEN Number := 40 ELSE
IF (Letter = '#') THEN Number := 41 ELSE
IF (Letter = '$') THEN Number := 42 ELSE
IF (Letter = '%') THEN Number := 43 ELSE
IF (Letter = '^') THEN Number := 44 ELSE
IF (Letter = '&') THEN Number := 45 ELSE
IF (Letter = '*') THEN Number := 46 ELSE
IF (Letter = '(') THEN Number := 47 ELSE
IF (Letter = ')') THEN Number := 48 ELSE
IF (Letter = '_') THEN Number := 49 ELSE
IF (Letter = '+') THEN Number := 50 ELSE
IF (Letter = '=') THEN Number := 51 ELSE
IF (Letter = '[') THEN Number := 52 ELSE
IF (Letter = ']') THEN Number := 53 ELSE
IF (Letter = '{') THEN Number := 54 ELSE
IF (Letter = '}') THEN Number := 55 ELSE
IF (Letter = '|') THEN Number := 56 ELSE
IF (Letter = '/') THEN Number := 57 ELSE
IF (Letter = '\') THEN Number := 58 ELSE
IF (Letter = '1') THEN Number := 59 ELSE
IF (Letter = '2') THEN Number := 60 ELSE
IF (Letter = '3') THEN Number := 61 ELSE
IF (Letter = '4') THEN Number := 62 ELSE
IF (Letter = '5') THEN Number := 63 ELSE
IF (Letter = '6') THEN Number := 64 ELSE
IF (Letter = '7') THEN Number := 65 ELSE
IF (Letter = '8') THEN Number := 66 ELSE
IF (Letter = '9') THEN Number := 67 ELSE
IF (Letter = '0') THEN Number := 68 ELSE
IF (Letter = ' ') THEN Number := 69
ELSE Number := -1
END
ELSE
WRITELN('Err, file is empty...');
FindLetterNumberEn := Number
END; {FindLetterNumberEn}
PROCEDURE GetPseudoLetterLine(VAR Number: INTEGER; VAR F: TEXT);
{ Leave cursor behind symbol-number - prepeared for reading SignsPlace }
VAR
Symb: CHAR;
BEGIN {GetPseudoLetterLine}
RESET(F);
WHILE NOT EOF(F) AND (Number - 1 <> -1)
DO
BEGIN
READLN(F, Symb);
Number := Number - 1;
END;
READ(F, Symb)
END; {GetPseudoLetterLine}
PROCEDURE CreatingPseudoLine(VAR F: TEXT);
VAR
Number, Sign: INTEGER;
BEGIN {CreatingPseudoLines}
Pseudos := []; { Prepare Line }
LetterAmount := 0;
WHILE NOT EOLN(F)
DO
BEGIN
Number := FindLetterNumberEn(F); { Get char's number }
GetPseudoLetterLine(Number, AlphEn); { Prepare AlphEn for working }
WHILE NOT EOLN(AlphEn)
DO
BEGIN
READ(AlphEn, Sign);
Pseudos := Pseudos + [Sign + LetterAmount * 25];
END;
LetterAmount := LetterAmount + 1
END
END; {CreatingPseudoLines}
PROCEDURE WritingPseudoLine;
VAR
Sign, Line, PositionType: INTEGER;
BEGIN {WritingPseudoLine}
Line := 1;
Sign := 1;
WHILE Sign <= 250
DO
BEGIN
PositionType := Sign MOD 25;
IF ((PositionType >= 1) AND (PositionType <= 5) AND (Line = 1)) OR
((PositionType >= 6) AND (PositionType <= 10) AND (Line = 2)) OR
((PositionType >= 11) AND (PositionType <= 15) AND (Line = 3)) OR
((PositionType >= 16) AND (PositionType <= 20) AND (Line = 4)) OR
(((PositionType = 0) OR ((PositionType >= 21) AND (PositionType <= 24)))
AND (Line = 5))
THEN
BEGIN
IF Sign IN Pseudos
THEN
WRITE('#')
ELSE
WRITE(' ');
IF Sign MOD 5 = 0 THEN WRITE(' ')
END;
IF Sign MOD 250 = 0
THEN
BEGIN
WRITELN;
IF Line = 1 THEN Sign := 5;
IF Line = 2 THEN Sign := 10;
IF Line = 3 THEN Sign := 15;
IF Line = 4 THEN Sign := 20;
Line := Line + 1;
END;
Sign := Sign + 1
END
END; {WritingPseudoLine}
PROCEDURE WritePseudo(VAR PseudoLetter: SignsPlace);
VAR
PositionInRow: INTEGER;
BEGIN {WritePseudo}
FOR PositionInRow := 1 TO (Rows * Columns)
DO
BEGIN
IF PositionInRow IN PseudoLetter
THEN
WRITE('#')
ELSE
WRITE(' ');
IF (PositionInRow MOD 5) = 0
THEN
WRITELN
END;
WRITELN
END; {WritePseudo}
BEGIN {Pseudo}
ASSIGN(AlphEn, 'Letters_EN.txt');
ASSIGN(AlphRu, 'Letters_RU.txt')
END. {Pseudo}
|
unit fb2lit_engine;
interface
uses MSXML2_TLB,Windows,LITGen_TLB,ComObj;
Type
TFB2LITConverter=class
Private
XSLVar1,XSLVar2,DOM:IXMLDOMDocument2;
ProcessorVar1,ProcessorVar2:IXSLProcessor;
ModulePath:String;
Function GetDocumentXSL:IXMLDOMDocument2;
Procedure SetDocumentXSL(AXSL:IXMLDOMDocument2);
Function GetOPFXSL:IXMLDOMDocument2;
Procedure SetOPFXSL(AXSL:IXMLDOMDocument2);
Function GetDocumentProcessor:IXSLProcessor;
Function GetOPFProcessor:IXSLProcessor;
Procedure ConvertDOM(FN:WideString);
Public
TocDeep:Integer;
SkipImg:Boolean;
property DocumentProcessor:IXSLProcessor read GetDocumentProcessor;
property DocumentXSL:IXMLDOMDocument2 read GetDocumentXSL write SetDocumentXSL;
property OPFProcessor:IXSLProcessor read GetOPFProcessor;
property OPFXSL:IXMLDOMDocument2 read GetOPFXSL write SetOPFXSL;
Constructor Create;
Procedure Convert(ADOM:IDispatch;FN:WideString);
Procedure WalkTree(Node:IXMLDOMNode;LitParser:ILITParserHost);
end;
TMyLITCallback = class(TTypedComObject,ILITCallback)
function Message(iType: Integer; iMessageCode: Integer; pwszMessage: PWideChar): HResult; stdcall;
end;
function ExportDOM(document:IDispatch;FileName:String; TocDeep:Integer; SkipImg:Boolean):HResult;
Const
Class_TMyLITCallback:TGUID = '{090F3507-3C0D-45AE-8F73-1AC7CED810F3}';
implementation
uses SysUtils,Classes,ComServ,Variants,ActiveX;
Constructor TFB2LITConverter.Create;
Begin
XSLVar1:=Nil;
XSLVar2:=Nil;
SetLength(ModulePath,2000);
GetModuleFileName(HInstance,@ModulePath[1],1999);
SetLength(ModulePath,Pos(#0,ModulePath)-1);
ModulePath:=ExtractFileDir(ModulePath);
ModulePath:=IncludeTrailingPathDelimiter(ModulePath);
TocDeep:=2;
end;
Function TFB2LITConverter.GetDocumentXSL;
Var
XTmp:IXMLDOMDocument2;
Begin
If XSLVar1=Nil then
Begin
XTmp:=CoFreeThreadedDOMDocument40.Create;
if not XTmp.load(ModulePath+'FB2_2_lit_xhtml.xsl') then
Raise Exception.Create(XTmp.parseError.reason);
DocumentXSL:=XTmp;
end;
Result:=XSLVar1;
end;
Function TFB2LITConverter.GetOPFXSL;
Var
XTmp:IXMLDOMDocument2;
Begin
If XSLVar2=Nil then
Begin
XTmp:=CoFreeThreadedDOMDocument40.Create;
if not XTmp.load(ModulePath+'FB2_2_lit_opf.xsl') then
Raise Exception.Create(XTmp.parseError.reason);
OPFXSL:=XTmp;
end;
Result:=XSLVar2;
end;
Procedure TFB2LITConverter.SetDocumentXSL;
Var
Template:IXSLTemplate;
Begin
XSLVar1:=AXSL;
Template := CoXSLTemplate40.Create;
Template._Set_stylesheet(DocumentXSL);
ProcessorVar1:=Template.createProcessor;
end;
Procedure TFB2LITConverter.SetOPFXSL;
Var
Template:IXSLTemplate;
Begin
XSLVar2:=AXSL;
Template := CoXSLTemplate40.Create;
Template._Set_stylesheet(OPFXSL);
ProcessorVar2:=Template.createProcessor;
end;
Function TFB2LITConverter.GetDocumentProcessor;
Begin
if (ProcessorVar1=Nil) then GetDocumentXSL;
Result:=ProcessorVar1;
end;
Function TFB2LITConverter.GetOPFProcessor;
Begin
if (ProcessorVar2=Nil) then GetOPFXSL;
Result:=ProcessorVar2;
end;
Procedure TFB2LITConverter.ConvertDOM;
Type
TCreateWriterFunc=function (var Writer:IUnknown):HResult;safecall;
TStoreArray=Array of byte;
Var
ImgUseDepth:Integer;
hLitgen:THandle;
LibFileName:String;
CreateWriter:TCreateWriterFunc;
IUnc:IUnknown;
SelectedNode:IXMLDOMNode;
DocAuth,CurFileName:WideString;
I:Integer;
hr:HResult;
LitWriter:ILITWriter;
PackageHost,ContentHost:ILITParserHost;
ImageHost:ILITImageHost;
XDoc,XDoc1:IXMLDOMDocument2;
CallBack:TMyLITCallback;
F:TFileStream;
ImgAsVar:Variant;
TheArr:TStoreArray;
BWritten,BWritten1:Cardinal;
AL:LongWord;
P:Pointer;
Buf:Array[0..511] of byte;
Begin
// this thing is to fix strange DOM from FBE, not knowing that
// http://www.gribuser.ru/xml/fictionbook/2.0 is a default namespace
// for attributes %[ ]
XDoc1:=CoFreeThreadedDOMDocument40.Create;
XDoc1.loadXML(Dom.XML);
Dom:=XDoc1;
DocumentProcessor.addParameter('saveimages',Integer(not SkipImg),'');
DocumentProcessor.addParameter('tocdepth',TocDeep,'');
DocumentProcessor.input:= DOM;
if not DocumentProcessor.transform then
Raise Exception.Create('Error preparing xhtml doc:');
OPFProcessor.addParameter('saveimages',Integer(not SkipImg),'');
OPFProcessor.addParameter('tocdepth',TocDeep,'');
OPFProcessor.input:= DOM;
if not OPFProcessor.transform then
Raise Exception.Create('Error preparing OPF doc:');
Dom.setProperty('SelectionLanguage','XPath');
Dom.setProperty('SelectionNamespaces', 'xmlns:fb="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:xlink="http://www.w3.org/1999/xlink"');
SelectedNode:=Dom.selectSingleNode('//fb:description/fb:title-info/fb:author/fb:last-name');
if SelectedNode<>Nil then
DocAuth:=SelectedNode.text
else
DocAuth:='fb2lit';
TComObjectFactory.Create(ComServer, TMyLITCallback, Class_TMyLITCallback, 'fb2lit callback','ho-ho',
ciMultiInstance, tmApartment);
CallBack:=TMyLITCallback.Create;
LibFileName:=ModulePath+'litgen.dll';
hLitgen:= LoadLibrary(PChar(LibFileName));
CreateWriter:= GetProcAddress(hLitGen, 'CreateWriter');
CreateWriter(IUnc);
if IUnc.QueryInterface(IID_ILITWriter,LitWriter) <> S_OK then
Raise Exception.Create('Invalid interface returned from litgen.dll');
if LitWriter.Create(PWideChar(FN),'c:\',PWideChar(DocAuth),0) <> S_OK then
Raise Exception.Create('Unable to create file');
Try
I:=0;
LitWriter.SetCallback(CallBack);
LitWriter.GetPackageHost(I,IUnc);
if IUnc.QueryInterface(IID_ILITParserHost,PackageHost) <> S_OK then
Raise Exception.Create('Unable to get ILITParserHost interface for Package file!');
XDoc:=CoFreeThreadedDOMDocument40.Create;
XDoc.loadXML(OPFProcessor.output);
// XDoc.save('h:\temp\opf.xml');
WalkTree(XDoc,PackageHost);
hr:=PackageHost.Finish;
if hr <> S_OK then
Raise Exception.Create('Error '+IntToStr(hr)+' finishing opf part!');
LitWriter.GetNextCSSHost(IUnc);
While IUnc <> Nil do
LitWriter.GetNextCSSHost(IUnc);
LitWriter.GetNextContentHost(IUnc);
if IUnc=Nil then
Raise Exception.Create('GetNextContentHost returned nil, lit generation aborted!');
if IUnc.QueryInterface(IID_ILITParserHost,ContentHost) <> S_OK then
Raise Exception.Create('Unable to get ILITParserHost interface for content file!');
ContentHost.GetFilename(CurFileName);
While (CurFileName <> 'file://c:\index.html') do
Begin
LitWriter.GetNextContentHost(IUnc);
if IUnc=Nil then
Raise Exception.Create('GetNextContentHost returned nil, lit generation aborted!');
if IUnc.QueryInterface(IID_ILITParserHost,ContentHost) <> S_OK then
Raise Exception.Create('Unable to get ILITParserHost interface for content file!');
ContentHost.GetFilename(CurFileName);
end;
XDoc:=CoFreeThreadedDOMDocument40.Create;
if not XDoc.loadXML(DocumentProcessor.output) then
Raise Exception.Create('Error loading xhtml doc:'#10+XDoc.parseError.reason);
// XDoc.save('h:\temp\123.html');
WalkTree(XDoc,ContentHost);
hr:=ContentHost.Finish;
if hr <> S_OK then
Raise Exception.Create('Error '+IntToStr(hr)+' finishing xhtml part!');
hr:=LitWriter.GetNextImageHost(IUnc);
if not(hr in [S_OK,s_false]) then
Raise Exception.Create('Error '+IntToStr(hr)+' starting image part!');
While IUnc<>Nil do
Begin
if IUnc.QueryInterface(IID_ILITImageHost,ImageHost) <> S_OK then
Raise Exception.Create('Unable to get ILITImageHost interface!');
ImageHost.GetFilename(CurFileName);
CurFileName:=Copy(CurFileName,11,MaxInt);
SelectedNode:=Dom.selectSingleNode('//fb:binary[@id='''+CurFileName+''']');
if SelectedNode<>Nil then
Begin
SelectedNode.Set_dataType('bin.base64');
ImgAsVar:=SelectedNode.nodeTypedValue;
DynArrayFromVariant(Pointer(TheArr),ImgAsVar,TypeInfo(TStoreArray));
hr:=ImageHost.Write(TheArr[0],Length(TheArr),BWritten);
if hr <> S_OK then
Raise Exception.Create('Error storing image '+CurFileName+'!');
if BWritten<>Length(TheArr) then
MessageBox(0,'Error occurred while storing images, some images could be missing.','Error',mb_ok or MB_ICONWARNING);
end else
MessageBox(0,PChar('Image id '+CurFileName+' is missing'),'Error',mb_Ok or mb_iconerror);
ImageHost:=Nil;
hr:=LitWriter.GetNextImageHost(IUnc);
if hr = s_false then Break;
if hr <> S_OK then
Raise Exception.Create('Error storing images (internal litgen.dll error)!');
end;
LitWriter.Finish();
Except
on E: Exception do
Begin
LitWriter.Fail;
MessageBox(0,PChar(E.Message),'Error',mb_ok and MB_ICONERROR);
end;
end;
end;
Procedure TFB2LITConverter.Convert;
Var
F:TFileStream;
ResultText:String;
OutVar:IXMLDOMDocument2;
Begin
if ADOM=Nil then
Begin
MessageBox(0,'NILL document value, please provide valid IXMLDOMDocument2 on input.','Error',mb_ok or MB_ICONERROR);
Exit;
end;
if ADOM.QueryInterface(IID_IXMLDOMDocument2,OutVar) <> S_OK then
Begin
MessageBox(0,'Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2','Error',MB_OK or MB_ICONERROR);
exit;
end;
DOM:=OutVar;
Try
ConvertDOM(FN);
except
on E: Exception do MessageBox(0,PChar(E.Message),'Error',mb_ok or MB_ICONERROR);
end
end;
Procedure TFB2LITConverter.WalkTree(Node:IXMLDOMNode;LitParser:ILITParserHost);
Var
NodeType:DOMNodeType;
Child:IXMLDOMNode;
IUnc:IUnknown;
LitNode:ILITTag;
Attrs:IXMLDOMNamedNodeMap;
Attr:IXMLDOMNode;
NodeName,NodeValue:WideString;
PWS,PWS1:PWideChar;
fake:Smallint absolute PWS;
hr:HResult;
I:Integer;
Begin
NodeType:=Node.nodeType;
Case NodeType of
NODE_DOCUMENT:Begin
// The NODE_DOCUMENT node can have multiple children - e.g. the
// DTD. We only want the root element, which must be the only one
// of type NODE_ELEMENT.
Child:=Node.firstChild;
While (Child<>Nil) and (Child.nodeType <> NODE_ELEMENT) do
Child:= Child.nextSibling;
if Child<>Nil then WalkTree(Child,LitParser)
end;
NODE_ELEMENT: Begin
LitParser.NewTag(IUnc);
IUnc.QueryInterface(IID_ILITTag,LitNode);
IUnc:=Nil;
NodeName:=Node.nodeName;
PWS:=PWideChar(NodeName);
hr:=LitNode.SetName(NodeName[1],Length(NodeName));
if hr <> S_OK then
Raise exception.Create(Format('Error 0x%x setting tag attribute %S',[hr,NodeName]));
Attrs:=Node.attributes;
if Attrs<>Nil then
For I:=0 to Attrs.length-1 do
Begin
NodeName:=Attrs[I].NodeName;
if Pos(':',NodeName)<>0 then
Continue;
PWS:=PWideChar(NodeName);
NodeValue:=Attrs[I].nodeValue;
PWS1:=PWideChar(nodeValue);
hr:=LitNode.AddAttribute(NodeName[1],Length(NodeName),nodeValue[1],Length(nodeValue));
if hr <> S_OK then
Raise exception.Create(Format('Error 0x%x setting tag attribute %S',[hr,NodeName]));
end;
Child:= Node.firstChild;
LitParser.Tag(LitNode,Integer(CHild <> Nil));
if Child<>Nil then
Begin
Repeat
WalkTree(Child,LitParser);
Child:=Child.nextSibling;
Until Child=Nil;
hr:=LitParser.EndChildren;
if hr <> S_OK then
Raise exception.Create(Format('Error 0x%x closing tag %S',[hr]));
end;
end;
NODE_TEXT,NODE_CDATA_SECTION,NODE_ENTITY_REFERENCE:
Begin
if NodeType=NODE_TEXT then
nodeValue:=Node.xml
else
nodeValue:=Node.text;
PWS:=PWideChar(nodeValue);
if nodeValue <>'' then
Begin
LitParser.Text(nodeValue[1], length(nodeValue));
if hr <> S_OK then
Raise exception.Create(Format('Error 0x%x entering text %S',[hr,nodeValue]));
end;
end
end;
end;
function TMyLITCallback.Message(iType: Integer; iMessageCode: Integer; pwszMessage: PWideChar): HResult;
Begin
If (iType=0) or (iType=1) then
MessageBoxW(0,pwszMessage,'Warning',mb_Ok);
end;
function ExportDOM;
Var
Converter:TFB2LITConverter;
Begin
//(document:IXMLDOMDocument2;FileName:String; TocDeep:Integer; SkipImg:Boolean):HResult
Result:=E_FAIL;
Converter:=TFB2LITConverter.Create;
Converter.TocDeep:=TocDeep;
Converter.SkipImg:=SkipImg;
Converter.Convert(document,FileName);
Result:=S_OK;
end;
end.
|
{*********************************************************}
{* VPCONST.PAS 1.03 *}
{*********************************************************}
{* ***** BEGIN LICENSE BLOCK ***** *}
{* Version: MPL 1.1 *}
{* *}
{* The contents of this file are subject to the Mozilla Public License *}
{* Version 1.1 (the "License"); you may not use this file except in *}
{* compliance with the License. You may obtain a copy of the License at *}
{* http://www.mozilla.org/MPL/ *}
{* *}
{* Software distributed under the License is distributed on an "AS IS" basis, *}
{* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *}
{* for the specific language governing rights and limitations under the *}
{* License. *}
{* *}
{* The Original Code is TurboPower Visual PlanIt *}
{* *}
{* The Initial Developer of the Original Code is TurboPower Software *}
{* *}
{* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *}
{* TurboPower Software Inc. All Rights Reserved. *}
{* *}
{* Contributor(s): *}
{* *}
{* ***** END LICENSE BLOCK ***** *}
{.$I Vp.INC}
unit VpConst;
{-Versioning defines and methods}
interface
uses
{$IFDEF LCL}
Controls,LCLType,LCLProc,
{$ELSE}
Windows,
{$ENDIF}
Forms, StdCtrls;
const
BuildTime = '09/13/2002 09:25 AM';
VpVersionStr = 'v1.03'; {Visual PlanIt library version}
VpProductName = 'Visual PlanIt';
BorderStyles : array[TBorderStyle] of LongInt =
(0, WS_BORDER);
ScrollBarStyles : array [TScrollStyle] of LongInt =
(0, WS_HSCROLL, WS_VSCROLL, WS_HSCROLL or WS_VSCROLL{$IFDEF LCL},0,0,0{$ENDIF});
SecondsInDay = 86400; { Number of seconds in a day }
SecondsInHour = 3600; { Number of seconds in an hour }
SecondsInMinute = 60; { Number of seconds in a minute }
HoursInDay = 24; { Number of hours in a day }
MinutesInHour = 60; { Number of minutes in an hour }
MinutesInDay = 1440; { Number of minutes in a day }
MaxDateLen = 40; { maximum length of date picture strings }
MaxMonthName = 15; { maximum length for month names }
MaxDayName = 15; { maximum length for day names }
TextMargin = 5; { amount of space around text }
MaxVisibleEvents = 1024; { maximum number of events that can be }
{ visible at any one time }
MaxEventDepth = 50; { the maximum number of side by side }
{ events, which can be displayed in the }
{ DayView component. }
ClickDelay : Integer = 500; { the number of milliseconds of delay for }
{ each event click in the TimeGrid }
calDefHeight = 140; { popup calendar default height }
calDefWidth = 200; { popup calendar default width }
ExtraBarWidth = 2; { The extra, draggable area on either side }
{ of the Contact Grid's horizontal bars. }
ResourceTableName = 'Resources';
TasksTableName = 'Tasks';
EventsTableName = 'Events';
ContactsTableName = 'Contacts';
RecordIDTableName = 'RecordIDS';
{virtual key constants not already defined}
VK_NONE = 0;
VK_ALT = VK_MENU;
VK_A = Ord('A'); VK_B = Ord('B'); VK_C = Ord('C'); VK_D = Ord('D');
VK_E = Ord('E'); VK_F = Ord('F'); VK_G = Ord('G'); VK_H = Ord('H');
VK_I = Ord('I'); VK_J = Ord('J'); VK_K = Ord('K'); VK_L = Ord('L');
VK_M = Ord('M'); VK_N = Ord('N'); VK_O = Ord('O'); VK_P = Ord('P');
VK_Q = Ord('Q'); VK_R = Ord('R'); VK_S = Ord('S'); VK_T = Ord('T');
VK_U = Ord('U'); VK_V = Ord('V'); VK_W = Ord('W'); VK_X = Ord('X');
VK_Y = Ord('Y'); VK_Z = Ord('Z'); VK_0 = Ord('0'); VK_1 = Ord('1');
VK_2 = Ord('2'); VK_3 = Ord('3'); VK_4 = Ord('4'); VK_5 = Ord('5');
VK_6 = Ord('6'); VK_7 = Ord('7'); VK_8 = Ord('8'); VK_9 = Ord('9');
{------------------- Windows messages -----------------------}
{Not a message code. Value of the first of the message codes used}
Vp_FIRST = $7F00; {***}
{sent to force a call to RecreateWnd}
Vp_RECREATEWND = Vp_FIRST + 1;
{sent to perform after-enter notification}
Vp_AFTERENTER = Vp_FIRST + 2;
{sent to perform after-exit notification}
Vp_AFTEREXIT = Vp_FIRST + 3;
{sent by a collection to its property editor when a property is changed}
Vp_PROPCHANGE = Vp_FIRST + 4;
{*** Error message codes ***}
oeFirst = 256;
{ XML support }
{The following constants are the tokens needed to parse an XML
document. The tokens are stored in UCS-4 format to reduce the
number of conversions needed by the filter.}
Xpc_BracketAngleLeft : array[0..0] of Longint = (60); {<}
Xpc_BracketAngleRight : array[0..0] of Longint = (62); {>}
Xpc_BracketSquareLeft : array[0..0] of Longint = (91); {[}
Xpc_BracketSquareRight : array[0..0] of Longint = (93); {]}
Xpc_CDATAStart :
array[0..5] of Longint = (67, 68, 65, 84, 65, 91); {CDATA[}
Xpc_CharacterRef : array[0..0] of Longint = (35); {#}
Xpc_CharacterRefHex : array[0..0] of Longint = (120); {x}
Xpc_CommentEnd : array[0..2] of Longint = (45, 45, 62); {-->}
Xpc_CommentStart : array[0..3] of Longint = (60, 33, 45, 45); {<!--}
Xpc_ConditionalEnd : array[0..2] of Longint = (93, 93, 62); {]]>}
Xpc_ConditionalIgnore :
array[0..5] of Longint = (73, 71, 78, 79, 82, 69); {IGNORE}
Xpc_ConditionalInclude :
array[0..6] of Longint = (73, 78, 67, 76, 85, 68, 69); {INCLUDE}
Xpc_ConditionalStart :
array[0..2] of Longint = (60, 33, 91); {<![}
Xpc_Dash : array[0..0] of Longint = (45); {-}
Xpc_DTDAttFixed :
array[0..4] of Longint = (70, 73, 88, 69, 68); {FIXED}
Xpc_DTDAttImplied :
array[0..6] of Longint = (73, 77, 80, 76, 73, 69, 68); {IMPLIED}
Xpc_DTDAttlist :
array[0..8] of Longint =
(60, 33, 65, 84, 84, 76, 73, 83, 84); {<!ATTLIST}
Xpc_DTDAttRequired :
array[0..7] of Longint =
(82, 69, 81, 85, 73, 82, 69, 68); {REQUIRED}
Xpc_DTDDocType :
array[0..8] of Longint =
(60, 33, 68, 79, 67, 84, 89, 80, 69); {<!DOCTYPE}
Xpc_DTDElement :
array[0..8] of Longint =
(60, 33, 69, 76, 69, 77, 69, 78, 84); {<!ELEMENT}
Xpc_DTDElementAny : array[0..2] of Longint = (65, 78, 89); {ANY}
Xpc_DTDElementCharData :
array[0..6] of Longint = (35, 80, 67, 68, 65, 84, 65); {#PCDATA}
Xpc_DTDElementEmpty :
array[0..4] of Longint = (69, 77, 80, 84, 89); {EMPTY}
Xpc_DTDEntity :
array[0..7] of Longint =
(60, 33, 69, 78, 84, 73, 84, 89); {<!ENTITY}
Xpc_DTDNotation :
array[0..9] of Longint =
(60, 33, 78, 79, 84, 65, 84, 73, 79, 78); {<!NOTATION}
Xpc_Encoding : array[0..7] of Longint =
(101, 110, 99, 111, 100, 105, 110, 103); {encoding}
Xpc_Equation : array[0..0] of Longint = (61); {=}
Xpc_ExternalPublic :
array[0..5] of Longint = (80, 85, 66, 76, 73, 67); {PUBLIC}
Xpc_ExternalSystem :
array[0..5] of Longint = (83, 89, 83, 84, 69, 77); {SYSTEM}
Xpc_GenParsedEntityEnd : array[0..0] of Longint = (59); {;}
Xpc_ListOperator : array[0..0] of Longint = (124); {|}
Xpc_MixedEnd : array[0..1] of Longint = (41, 42); {)*}
Xpc_OneOrMoreOpr : array[0..0] of Longint = (42); {*}
Xpc_ParamEntity : array[0..0] of Longint = (37); {%}
Xpc_ParenLeft : array[0..0] of Longint = (40); {(}
Xpc_ParenRight : array[0..0] of Longint = (41); {)}
Xpc_ProcessInstrEnd : array[0..1] of Longint = (63, 62); {?>}
Xpc_ProcessInstrStart : array[0..1] of Longint = (60, 63); {<?}
Xpc_QuoteDouble : array[0..0] of Longint = (34); {"}
Xpc_QuoteSingle : array[0..0] of Longint = (39); {'}
Xpc_Standalone :
array[0..9] of Longint =
(115, 116, 97, 110, 100, 97, 108, 111, 110, 101); {standalone}
Xpc_UnparsedEntity :
array[0..4] of Longint = (78, 68, 65, 84, 65); {NDATA}
Xpc_Version :
array[0..6] of Longint =
(118, 101, 114, 115, 105, 111, 110); {version}
LIT_CHAR_REF = 1;
LIT_ENTITY_REF = 2;
LIT_PE_REF = 4;
LIT_NORMALIZE = 8;
CONTEXT_NONE = 0;
CONTEXT_DTD = 1;
CONTEXT_ENTITYVALUE = 2;
CONTEXT_ATTRIBUTEVALUE = 3;
CONTENT_UNDECLARED = 0;
CONTENT_ANY = 1;
CONTENT_EMPTY = 2;
CONTENT_MIXED = 3;
CONTENT_ELEMENTS = 4;
OCCURS_REQ_NOREPEAT = 0;
OCCURS_OPT_NOREPEAT = 1;
OCCURS_OPT_REPEAT = 2;
OCCURS_REQ_REPEAT = 3;
REL_OR = 0;
REL_AND = 1;
REL_NONE = 2;
ATTRIBUTE_UNDECLARED = 0;
ATTRIBUTE_CDATA = 1;
ATTRIBUTE_ID = 2;
ATTRIBUTE_IDREF = 3;
ATTRIBUTE_IDREFS = 4;
ATTRIBUTE_ENTITY = 5;
ATTRIBUTE_ENTITIES = 6;
ATTRIBUTE_NMTOKEN = 7;
ATTRIBUTE_NMTOKENS = 8;
ATTRIBUTE_ENUMERATED = 9;
ATTRIBUTE_NOTATION = 10;
ATTRIBUTE_DEFAULT_UNDECLARED = 0;
ATTRIBUTE_DEFAULT_SPECIFIED = 1;
ATTRIBUTE_DEFAULT_IMPLIED = 2;
ATTRIBUTE_DEFAULT_REQUIRED = 3;
ATTRIBUTE_DEFAULT_FIXED = 4;
ENTITY_UNDECLARED = 0;
ENTITY_INTERNAL = 1;
ENTITY_NDATA = 2;
ENTITY_TEXT = 3;
CONDITIONAL_INCLUDE = 0;
CONDITIONAL_IGNORE = 1;
{ Version numbers }
VpXSLImplementation = 0.0;
VpXMLSpecification = '1.0';
{ Defaults }
{ MonthView }
vpDefWVRClickChangeDate = True;
implementation
initialization
{$IFNDEF LCL}
ClickDelay := GetDoubleClickTime;
{$ENDIF}
end.
|
unit TestFeature;
interface
uses
TestFramework, Classes, FeatureIntf, Feature, TestBaseClasses, StepIntf;
type
TestTFeature = class(TParseContext)
strict private
FFeature: IFeature;
private
function NovoStep(ADescricao: string): IStep;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure FeatureDeveriaSerInvalidaSeNaoPossuirAoMenosUmCenarioValido;
procedure FeatureDeveriaSerInvalidaSeCenariosNaoForemValidos;
procedure FeatureDeveriaSerInvalidaSeNaoPossuirUmaClasseDeTestesParaCadaScenario;
end;
implementation
uses
Scenario, ScenarioIntf, Step, DummyTests;
procedure TestTFeature.FeatureDeveriaSerInvalidaSeCenariosNaoForemValidos;
begin
FFeature.Scenarios.Add(TScenario.Create('NoTest'));
Specify.That(FFeature.Valid).Should.Be.False;
end;
procedure TestTFeature.FeatureDeveriaSerInvalidaSeNaoPossuirAoMenosUmCenarioValido;
var
LCenarioValido: ITestSuite;
begin
LCenarioValido := TUmCenarioValido.Suite;
RegisterTest(LCenarioValido);
Specify.That(FFeature.Valid).Should.Be.False;
FFeature.Scenarios.Add(TScenario.Create('TUmCenarioValido'));
(FFeature.Scenarios.First as IScenario).Titulo := 'Um Cenário Válido';
(FFeature.Scenarios.First as IScenario).Steps.Add(TStep.Create);
((FFeature.Scenarios.First as IScenario).Steps.First as IStep).Descricao := 'Dado que tenho um step valido';
Specify.That(FFeature.Valid).Should.Be.True;
RegisteredTests.Tests.Remove(LCenarioValido);
end;
procedure TestTFeature.FeatureDeveriaSerInvalidaSeNaoPossuirUmaClasseDeTestesParaCadaScenario;
var
LCenarioCom3Passos: ITestSuite;
LCenarioValidoSuite: ITestSuite;
LScenario: IScenario;
begin
LCenarioValidoSuite := TUmCenarioValido.Suite;
RegisterTest(LCenarioValidoSuite);
LCenarioCom3Passos := TUmCenarioCom3Passos.Suite;
RegisterTest(LCenarioCom3Passos);
LScenario := TScenario.Create('UmCenarioCom3Passos');
LScenario.Titulo := 'Um cenário com 3 passos';
LScenario.Steps.Add(NovoStep('Dado que tenho 3 passos nesse cenário'));
LScenario.Steps.Add(NovoStep('Quando eu validar a Featuare'));
LScenario.Steps.Add(NovoStep('Então ela deve ser válida.'));
FFeature.Scenarios.Add(LScenario);
LScenario := TScenario.Create('UmCenarioValido');
LScenario.Titulo := 'Um cenário Válido';
LScenario.Steps.Add(NovoStep('Dado Que Tenho Um Step Valido'));
FFeature.Scenarios.Add(LScenario);
Specify.That(FFeature.Valid).Should.Be.True;
RegisteredTests.Tests.Remove(LCenarioValidoSuite);
RegisteredTests.Tests.Remove(LCenarioCom3Passos);
end;
function TestTFeature.NovoStep(ADescricao: string): IStep;
begin
Result := TStep.Create;
Result.Descricao := ADescricao;
end;
procedure TestTFeature.SetUp;
begin
FFeature := TFeature.Create;
end;
procedure TestTFeature.TearDown;
begin
FFeature := nil;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTFeature.Suite);
end.
|
{*******************************************************************************
作者: dmzn@163.com 2011-10-29
描述: 运行时调试日志
*******************************************************************************}
unit UFrameRunLog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
UMgrSync, UFrameBase, StdCtrls, ExtCtrls;
type
TfFrameRunLog = class(TfFrameBase)
Panel1: TPanel;
Check1: TCheckBox;
MemoLog: TMemo;
BtnClear: TButton;
BtnCopy: TButton;
procedure Check1Click(Sender: TObject);
procedure BtnCopyClick(Sender: TObject);
procedure BtnClearClick(Sender: TObject);
private
{ Private declarations }
FShowLog: Integer;
//显示日志
FSyncer: TDataSynchronizer;
//同步对象
procedure Showlog(const nMsg: string; const nMustShow: Boolean);
//显示日志
procedure DoSync(const nData: Pointer; const nSize: Cardinal);
procedure DoFree(const nData: Pointer; const nSize: Cardinal);
//同步操作
public
{ Public declarations }
procedure OnCreateFrame; override;
procedure OnDestroyFrame; override;
class function FrameID: integer; override;
end;
implementation
{$R *.dfm}
uses
UMgrControl, USysConst, ULibFun;
const
cNo = $0001;
cYes = $0010;
cBuf = 200;
class function TfFrameRunLog.FrameID: integer;
begin
Result := cFI_FrameRunlog;
end;
procedure TfFrameRunLog.OnCreateFrame;
begin
gDebugLog := Showlog;
FShowLog := cNo;
FSyncer := TDataSynchronizer.Create;
FSyncer.SyncEvent := DoSync;
FSyncer.SyncFreeEvent := DoFree;
end;
procedure TfFrameRunLog.OnDestroyFrame;
begin
gDebugLog := nil;
FSyncer.Free;
end;
procedure TfFrameRunLog.Check1Click(Sender: TObject);
begin
if Check1.Checked then
InterlockedExchange(FShowLog, cYes)
else InterlockedExchange(FShowlog, cNo);
end;
//Desc: 线程调用
procedure TfFrameRunLog.Showlog(const nMsg: string; const nMustShow: Boolean);
var nPtr: PChar;
nLen: Integer;
begin
if nMustShow or (FShowLog = cYes) then
begin
nLen := Length(nMsg);
if nLen > cBuf then
nLen := cBuf;
nLen := nLen + 1;
nPtr := GetMemory(nLen);
StrLCopy(nPtr, PChar(nMsg + #0), nLen);
FSyncer.AddData(nPtr, nLen);
FSyncer.ApplySync;
end;
end;
procedure TfFrameRunLog.DoFree(const nData: Pointer; const nSize: Cardinal);
begin
FreeMem(nData, nSize);
end;
procedure TfFrameRunLog.DoSync(const nData: Pointer; const nSize: Cardinal);
var nStr: string;
begin
if not (csDestroying in ComponentState) then
begin
if MemoLog.Lines.Count > 200 then
MemoLog.Clear;
//clear logs
nStr := Format('【%s】::: %s', [DateTime2Str(Now), StrPas(nData)]);
MemoLog.Lines.Add(nStr);
end;
end;
procedure TfFrameRunLog.BtnCopyClick(Sender: TObject);
begin
MemoLog.SelectAll;
MemoLog.CopyToClipboard;
ShowMsg('已复制到粘贴板', sHint);
end;
procedure TfFrameRunLog.BtnClearClick(Sender: TObject);
begin
MemoLog.Clear;
ShowMsg('日志已清空', sHint);
end;
initialization
gControlManager.RegCtrl(TfFrameRunLog, TfFrameRunLog.FrameID);
end.
|
{!DOCTOPIC}{
Type » T2DExtArray
}
{!DOCREF} {
@method: function T2DExtArray.Len(): Int32;
@desc: Returns the length of the arr. Same as c'Length(Arr)'
}
function T2DExtArray.Len(): Int32;
begin
Result := Length(Self);
end;
{!DOCREF} {
@method: function T2DExtArray.IsEmpty(): Boolean;
@desc: Returns True if the ATEA is empty. Same as c'Length(ATIA) = 0'
}
function T2DExtArray.IsEmpty(): Boolean;
begin
Result := Length(Self) = 0;
end;
{!DOCREF} {
@method: procedure T2DExtArray.Append(const Arr:TExtArray);
@desc: Add another element to the array
}
procedure T2DExtArray.Append(const Arr:TExtArray);
var
l:Int32;
begin
l := Length(Self);
SetLength(Self, l+1);
Self[l] := Arr;
end;
{!DOCREF} {
@method: procedure T2DExtArray.Insert(idx:Int32; Value:TExtArray);
@desc:
Inserts a new item `value` in the array at the given position. If position `idx` is greater then the length,
it will append the item `value` to the end. If it's less then 0 it will substract the index from the length of the array.[br]
`Arr.Insert(0, x)` inserts at the front of the list, and `Arr.Insert(length(a), x)` is equivalent to `Arr.Append(x)`.
}
procedure T2DExtArray.Insert(idx:Int32; Value:TExtArray);
var i,l:Int32;
begin
l := Length(Self);
if (idx < 0) then
idx := math.modulo(idx,l);
if (l <= idx) then begin
self.append(value);
Exit();
end;
SetLength(Self, l+1);
for i:=l downto idx+1 do
Self[i] := Self[i-1];
Self[i] := Value;
end;
{!DOCREF} {
@method: function T2DExtArray.Pop(): TExtArray;
@desc: Removes and returns the last item in the array
}
function T2DExtArray.Pop(): TExtArray;
var
H:Int32;
begin
H := high(Self);
Result := Self[H];
SetLength(Self, H);
end;
{!DOCREF} {
@method: function T2DExtArray.Slice(Start,Stop: Int32; Step:Int32=1): T2DExtArray;
@desc:
Slicing similar to slice in Python, tho goes from 'start to and including stop'
Can be used to eg reverse an array, and at the same time allows you to c'step' past items.
You can give it negative start, and stop, then it will wrap around based on length(..)
If c'Start >= Stop', and c'Step <= -1' it will result in reversed output.
[note]Don't pass positive c'Step', combined with c'Start > Stop', that is undefined[/note]
}
function T2DExtArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): T2DExtArray;
begin
if (Start = DefVar64) then
if Step < 0 then Start := -1
else Start := 0;
if (Stop = DefVar64) then
if Step > 0 then Stop := -1
else Stop := 0;
if Step = 0 then Exit;
try Result := exp_slice(Self, Start,Stop,Step);
except SetLength(Result,0) end;
end;
{!DOCREF} {
@method: procedure T2DExtArray.Extend(Arr:T2DExtArray);
@desc: Extends the 2d-array with a 2d-array
}
procedure T2DExtArray.Extend(Arr:T2DExtArray);
var L,i:Int32;
begin
L := Length(Self);
SetLength(Self, Length(Arr) + L);
for i:=L to High(Self) do
begin
SetLength(Self[i],Length(Arr[i-L]));
MemMove(Arr[i-L][0], Self[i][0], Length(Arr[i-L])*SizeOf(Extended));
end;
end;
{!DOCREF} {
@method: function T2DExtArray.Merge(): TExtArray;
@desc: Merges all the groups in the array, and return a TIA
}
function T2DExtArray.Merge(): TExtArray;
var i,s,l: Integer;
begin
s := 0;
for i:=0 to High(Self) do
begin
L := Length(Self[i]);
SetLength(Result, S+L);
MemMove(Self[i][0], Result[S], L*SizeOf(Extended));
S := S + L;
end;
end;
{!DOCREF} {
@method: function T2DExtArray.Sorted(Key:TSortKey=sort_Default): T2DExtArray;
@desc:
Returns a new sorted array from the input array.
Supported keys: c'sort_Default, sort_Length, sort_Mean, sort_First'
}
function T2DExtArray.Sorted(Key:TSortKey=sort_Default): T2DExtArray;
begin
Result := Self.Slice();
case Key of
sort_Default, sort_Length: se.SortATEAByLength(Result);
sort_Mean: se.SortATEAByMean(Result);
sort_First: se.SortATEAByFirst(Result);
else
WriteLn('TSortKey not supported');
end;
end;
{!DOCREF} {
@method: function T2DExtArray.Sorted(Index:Integer): T2DPointArray; overload;
@desc: Returns a new sorted array from the input array. Sorts by the given index in each group.
}
function T2DExtArray.Sorted(Index:Integer): T2DExtArray; overload;
begin
Result := Self.Slice();
se.SortATEAByIndex(Result, Index);
end;
{!DOCREF} {
@method: procedure T2DExtArray.Sort(Key:TSortKey=sort_Default);
@desc:
Sorts the array with the given key
Supported keys: c'sort_Default, sort_Length, sort_Mean, sort_First'
}
procedure T2DExtArray.Sort(Key:TSortKey=sort_Default);
begin
case Key of
sort_Default, sort_Length: se.SortATEAByLength(Self);
sort_Mean: se.SortATEAByMean(Self);
sort_First: se.SortATEAByFirst(Self);
else
WriteLn('TSortKey not supported');
end;
end;
{!DOCREF} {
@method: procedure T2DExtArray.Sort(Index:Integer); overload;
@desc:
Sorts the array by the given index in each group. If the group is not that the last index in the group is used.
Negative 'index' will result in counting from right to left: High(Arr[i]) - index
}
procedure T2DExtArray.Sort(Index:Integer); overload;
begin
se.SortATEAByIndex(Self, Index);
end;
{!DOCREF} {
@method: function T2DExtArray.Reversed(): T2DExtArray;
@desc: Creates a reversed copy of the array
}
function T2DExtArray.Reversed(): T2DExtArray;
begin
Result := Self.Slice(,,-1);
end;
{!DOCREF} {
@method: procedure T2DExtArray.Reverse();
@desc: Reverses the array
}
procedure T2DExtArray.Reverse();
begin
Self := Self.Slice(,,-1);
end;
{=============================================================================}
// The functions below this line is not in the standard array functionality
//
// By "standard array functionality" I mean, functions that all standard
// array types should have.
{=============================================================================}
{!DOCREF} {
@method: function T2DExtArray.Sum(): Extended;
@desc: Returns the sum of the 2d array
}
function T2DExtArray.Sum(): Extended;
var i,L: Integer;
begin
for i:=0 to High(Self) do
Result := Result + Self[i].Sum();
end;
{!DOCREF} {
@method: function T2DExtArray.Mean(): Extended;
@desc: Returns the mean of the 2d array
}
function T2DExtArray.Mean(): Extended;
var i,L: Integer;
begin
for i:=0 to High(Self) do
Result := Result + Self[i].Mean();
Result := Result / High(Self);
end;
{!DOCREF} {
@method: function T2DExtArray.Stdev(): Extended;
@desc: Returns the standard deviation of the array
}
function T2DExtArray.Stdev(): Extended;
begin
Result := Self.Merge().Stdev();
end;
{!DOCREF} {
@method: function T2DExtArray.Variance(): Extended;
@desc:
Return the sample variance.
Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of the array. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.
}
function T2DExtArray.Variance(): Extended;
var
Arr:TExtArray;
avg:Extended;
i:Int32;
begin
Arr := Self.Merge();
avg := Arr.Mean();
for i:=0 to High(Arr) do
Result := Result + Sqr(Arr[i] - avg);
Result := Result / length(Arr);
end;
{!DOCREF} {
@method: function T2DExtArray.Mode(Eps:Extended=0.0000001): Extended;
@desc:
Returns the sample mode of the array, which is the most frequently occurring value in the array.
When there are multiple values occurring equally frequently, mode returns the smallest of those values.
Takes an extra parameter c'Eps', can be used to allow some tolerance in the floating point comparison.
}
function T2DExtArray.Mode(Eps:Extended=0.0000001): Extended;
begin
Result := Self.Merge().Mode(Eps);
end;
|
// ***************************************************************************
//
// FMXComponents: Firemonkey Opensource Components Set
//
// Copyright 2017 谢顿 (zhaoyipeng@hotmail.com)
//
// https://github.com/zhaoyipeng/FMXComponents
//
// ***************************************************************************
unit FMX.RegComponents;
interface
uses
System.Classes
// 可根据需要注释调不需要的控件单元和注册
, FMX.CircleScoreIndicator
, FMX.ImageSlider
, FMX.RatingBar
, FMX.ScrollableList
, FMX.SimpleBBCodeText
, FMX.GesturePassword
, FMX.CalendarControl
, FMX.Seg7Shape
, FMX.Toast
, FMX.QRCode
, FMX.LoadingIndicator
, FMX.Callout
, FMX.RotatingText
, FMX.BezierAnimation
, FMX.BezierPanel
;
procedure Register;
implementation
const
FMX_COMPONENTS_PALETTE = 'FMXComponents';
procedure Register;
begin
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXCircleScoreIndicator]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXImageSlider]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXRatingBar]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXScrollableList]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXSimpleBBCodeText]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXGesturePassword]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXCalendarControl]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXSeg7Shape]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXToast]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXQRCode]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXLoadingIndicator]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXCallout]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXRotatingText]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXBezierAnimation]);
RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXBezierPanel]);
end;
end.
|
unit eAtasOrais.Model.Consts3;
interface
Const
Modelo_English : string = 'eAtasOrais.English.xlsx';
Modelo_Teen : string = 'eAtasOrais.Teen.xlsx';
Modelo_Espanol : string = 'eAtasOrais.Espanol.xlsx';
Modelo_Kids : string = 'eAtasOrais.Kids.xlsx';
Modelo_Master : string = 'eAtasOrais.Master.xlsx';
implementation
end.
|
unit f2Skins;
interface
uses
SimpleXML,
JclStringLists,
d2dTypes,
d2dInterfaces,
//d2dFont,
d2dGUIButtons,
f2Types;
type
Tf2Skin = class(TObject)
private
f_XML: IXmlDocument;
f_ScreenHeight: Integer;
f_ScreenWidth: Integer;
f_FullScreen: Boolean;
f_TexList: IJclStringList; // textures
f_FntList: IJclStringList; // fonts
f_BFList : IJclStringList; // button frames
f_IsFromPack: Boolean;
f_ResPath: string;
procedure LoadScreenPropetries;
function pm_GetTextures(aName: string): Id2dTexture;
function pm_GetFonts(aName: string): Id2dFont;
function pm_GetFrames(aName: string): Id2dFramedButtonView;
public
constructor Create(aFileName: string; aFromPack: Boolean = False);
procedure LoadResources;
property ScreenHeight: Integer read f_ScreenHeight write f_ScreenHeight;
property ScreenWidth: Integer read f_ScreenWidth write f_ScreenWidth;
property FullScreen: Boolean read f_FullScreen write f_FullScreen;
property Textures[aName: string]: Id2dTexture read pm_GetTextures;
property Fonts[aName: string]: Id2dFont read pm_GetFonts;
property Frames[aName: string]: Id2dFramedButtonView read pm_GetFrames;
property XML: IXmlDocument read f_XML;
end;
implementation
uses
Classes,
SysUtils,
d2dCore,
d2dGUITypes,
f2FontLoad
;
constructor Tf2Skin.Create(aFileName: string; aFromPack: Boolean = False);
var
l_Stream: TStream;
begin
inherited Create;
l_Stream := gD2DE.Resource_CreateStream(aFileName, aFromPack);
try
f_XML := LoadXmlDocument(l_Stream);
finally
FreeAndNil(l_Stream);
end;
if (f_XML = nil) or (f_XML.DocumentElement = nil) then
Fail;
f_TexList := JclStringList;
f_FntList := JclStringList;
f_BFList := JclStringList;
f_BFList.CaseSensitive := False;
f_ResPath := ExtractFilePath(aFileName);
f_IsFromPack := aFromPack;
LoadScreenPropetries;
end;
procedure Tf2Skin.LoadResources;
var
l_ResRoot: IxmlNode;
l_Node: IxmlNode;
l_List: IXmlNodeList;
I: Integer;
l_Tex : Id2dTexture;
l_Name : string;
l_FName: string;
l_Idx: Integer;
l_Font: Id2dFont;
l_TempName: string;
l_TexX: Integer;
l_TexY: Integer;
l_Width: Integer;
l_Height: Integer;
l_LeftW: Integer;
l_MidW: Integer;
l_Frame: Id2dFramedButtonView;
begin
l_ResRoot := f_XML.DocumentElement.SelectSingleNode('resources');
if l_ResRoot <> nil then
begin
l_List := l_ResRoot.SelectNodes('texture');
for I := 0 to l_List.Count - 1 do
begin
l_Node := l_List.Item[I];
l_Name := l_Node.GetAttr('name');
l_FName := l_Node.GetAttr('file');
if (l_Name <> '') and (l_FName <> '') then
begin
l_FName := f_ResPath + l_FName;
l_Tex := gD2DE.Texture_Load(l_FName, f_IsFromPack);
if l_Tex <> nil then
begin
l_Idx := f_TexList.Add(l_Name);
f_TexList.Interfaces[l_Idx] := l_Tex;
end;
end;
end;
l_List := l_ResRoot.SelectNodes('font');
for I := 0 to l_List.Count - 1 do
begin
l_Node := l_List.Item[I];
l_Name := l_Node.GetAttr('name');
l_FName := l_Node.GetAttr('file');
if (l_Name <> '') and (l_FName <> '') then
begin
l_FName := f_ResPath + l_FName;
l_Font := f2LoadFont(l_FName, f_IsFromPack);
if l_Font <> nil then
begin
l_Idx := f_FntList.Add(l_Name);
f_FntList.Interfaces[l_Idx] := l_Font;
end;
end;
end;
l_List := l_ResRoot.SelectNodes('buttonframe');
for I := 0 to l_List.Count - 1 do
begin
l_Node := l_List.Item[I];
l_Name := l_Node.GetAttr('name');
if l_Name <> '' then
begin
l_Idx := f_TexList.IndexOf(l_Node.GetAttr('tex'));
if l_Idx >= 0 then
begin
l_Tex := f_TexList.Interfaces[l_Idx] as Id2dTexture;
l_Idx := f_FntList.IndexOf(l_Node.GetAttr('font'));
if l_Idx >= 0 then
begin
l_Font := f_FntList.Interfaces[l_Idx] as Id2dFont;
l_TexX := l_Node.GetIntAttr('texx');
l_TexY := l_Node.GetIntAttr('texy');
l_Width := l_Node.GetIntAttr('width');
l_Height := l_Node.GetIntAttr('height');
l_LeftW := l_Node.GetIntAttr('leftw');
l_MidW := l_Node.GetIntAttr('midw');
if (l_Width > 0) and (l_Height > 0) and (l_LeftW > 0) and (l_MidW > 0) then
begin
l_Frame := Td2dFramedButtonView.Create(l_Tex, l_TexX, l_TexY, l_Width, l_Height, l_LeftW, l_MidW, l_Font);
with l_Frame do
begin
StateColor[bsNormal] := Td2dColor(l_Node.GetHexAttr('cnormal', $FFA0A0A0));
StateColor[bsFocused] := Td2dColor(l_Node.GetHexAttr('cfocused', $FFA0A0FF));
StateColor[bsDisabled] := Td2dColor(l_Node.GetHexAttr('cdisabled', $FF606060));
StateColor[bsPressed] := Td2dColor(l_Node.GetHexAttr('cpressed', $FFFFFFFF));
end;
l_Idx := f_BFList.Add(l_Name);
f_BFList.Interfaces[l_Idx] := l_Frame;
end;
end;
end;
end;
end;
end;
end;
procedure Tf2Skin.LoadScreenPropetries;
var
l_Node: IXmlNode;
begin
l_Node := f_XML.DocumentElement.SelectSingleNode('screen');
if l_Node <> nil then
begin
f_ScreenWidth := l_Node.GetIntAttr('width', 800);
f_ScreenHeight := l_Node.GetIntAttr('height', 600);
f_FullScreen := l_Node.GetBoolAttr('fullscreen', False);
end
else
begin
f_ScreenWidth := 800;
f_ScreenHeight := 600;
f_FullScreen := False;
end;
end;
function Tf2Skin.pm_GetTextures(aName: string): Id2dTexture;
var
l_Idx: Integer;
begin
l_Idx := f_TexList.IndexOf(aName);
if l_Idx >= 0 then
Result := f_TexList.Interfaces[l_Idx] as Id2dTexture
else
Result := nil;
end;
function Tf2Skin.pm_GetFonts(aName: string): Id2dFont;
var
l_Idx: Integer;
begin
l_Idx := f_FntList.IndexOf(aName);
if l_Idx >= 0 then
Result := f_FntList.Interfaces[l_Idx] as Id2dFont
else
Result := nil;
end;
function Tf2Skin.pm_GetFrames(aName: string): Id2dFramedButtonView;
var
l_Idx: Integer;
begin
l_Idx := f_BFList.IndexOf(aName);
if l_Idx >= 0 then
Result := f_BFList.Interfaces[l_Idx] as Id2dFramedButtonView
else
Result := nil;
end;
end. |
unit uXMLDatasource;
{
Ollivier Civiol - 2019
ollivier@civiol.eu
https://ollivierciviolsoftware.wordpress.com/
}
interface
uses
Windows, Classes, SysUtils, contnrs, UXmlDoc,
MSAccess, cxCustomData, cxGridTableView, cxTLData;
type
{ XML CUSTOM DATASOURCE }
TXMLTvDataSource = class(TcxTreeListCustomDataSource)
private
FXmlDoc: TXMLDoc;
protected
function GetChildCount(AParentHandle: TcxDataRecordHandle): integer; override;
function GetChildRecordHandle(AParentHandle: TcxDataRecordHandle; AChildIndex: integer): TcxDataRecordHandle; override;
function GetRootRecordHandle: TcxDataRecordHandle; override;
function GetValue(ARecordHandle: TcxDataRecordHandle; AItemHandle: TcxDataItemHandle): Variant; override;
public
constructor Create(ADoc: TXMLDoc);
end;
TXMLDataSource = class(TcxCustomDataSource)
private
FXmlElement : TXMLElement;
public
constructor Create(AElement: TXMLElement);
function GetItemHandle(AItemIndex: integer): TcxDataItemHandle; override;
function GetRecordCount: integer; override;
function GetRecordHandle(ARecordIndex: integer): TcxDataRecordHandle; override;
function GetValue(ARecordHandle: TcxDataRecordHandle; AItemHandle: TcxDataItemHandle): Variant; override;
procedure SetValue(ARecordHandle: TcxDataRecordHandle; AItemHandle: TcxDataItemHandle; const AValue: Variant); override;
end;
implementation
constructor TXMLTvDataSource.Create(ADoc: TXMLDoc);
begin
FXmldoc := aDoc;
end;
function TXMLTvDataSource.GetChildCount(AParentHandle: TcxDataRecordHandle): integer;
begin
if not Assigned(AParentHandle) then
result := FXmlDoc.DocumentElement.NbElements
else
result := TXMLElement(AParentHandle).NbElements;
end;
function TXMLTvDataSource.GetChildRecordHandle(AParentHandle: TcxDataRecordHandle; AChildIndex: integer): TcxDataRecordHandle;
begin
result := TcxDataRecordHandle(TXMLElement(AParentHandle).Elements[AChildIndex]);
end;
function TXMLTvDataSource.GetRootRecordHandle: TcxDataRecordHandle;
begin
result := TcxDataRecordHandle(FXmlDoc.DocumentElement);
end;
function TXMLTvDataSource.GetValue(ARecordHandle: TcxDataRecordHandle; AItemHandle: TcxDataItemHandle): Variant;
begin
result := TXMLElement(ARecordHandle).TagName;
end;
{ TXMLDATASOURCE }
constructor TXMLDataSource.Create(AElement: TXMLElement);
begin
FXmlElement := aElement;
end;
function TXMLDataSource.GetItemHandle(AItemIndex: integer): TcxDataItemHandle;
begin
result := TcxDataItemHandle(AItemIndex);
end;
function TXMLDataSource.GetRecordCount: integer;
begin
result := FXmlElement.NbElements;
end;
function TXMLDataSource.GetRecordHandle(ARecordIndex: integer): TcxDataRecordHandle;
begin
result := TcxDataItemHandle(FXmlElement.Elements[ARecordIndex]);
end;
function TXMLDataSource.GetValue(ARecordHandle: TcxDataRecordHandle; AItemHandle: TcxDataItemHandle): Variant;
begin
with TXMLElement(ARecordHandle) do
result := TcxDataItemHandle(GetAttribute(GetAttributeName(AItemHandle)));
end;
procedure TXMLDataSource.SetValue(ARecordHandle: TcxDataRecordHandle; AItemHandle: TcxDataItemHandle; const AValue: Variant);
begin
with TXMLElement(ARecordHandle) do
TcxDataItemHandle(SetAttribute(GetAttributeName(AItemHandle), AValue));
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit frmSynonymProperties;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, dxBar, cxMemo, cxRichEdit, cxLabel, cxContainer, cxEdit,
cxTextEdit, jpeg, cxPC, cxControls, StdCtrls, ExtCtrls, GenelDM, OraSynonym,
VirtualTable, frmBaseform;
type
TSynonymPropertiesFrm = class(TBaseform)
Panel1: TPanel;
imgToolBar: TImage;
lblDescription: TLabel;
pcSequenceProperties: TcxPageControl;
tsSequenceDetails: TcxTabSheet;
dxBarDockControl1: TdxBarDockControl;
edtOwner: TcxTextEdit;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
edtObjectOwner: TcxTextEdit;
cxLabel3: TcxLabel;
edtObjectName: TcxTextEdit;
cxLabel4: TcxLabel;
edtDBLink: TcxTextEdit;
cxLabel8: TcxLabel;
edtName: TcxTextEdit;
tsSequenceScripts: TcxTabSheet;
redtDDL: TcxRichEdit;
dxBarManager1: TdxBarManager;
bbtnCreateSynonym: TdxBarButton;
bbtnDropSynonym: TdxBarButton;
bbtnRefreshSynonym: TdxBarButton;
cxLabel5: TcxLabel;
edtObjectType: TcxTextEdit;
procedure bbtnCreateSynonymClick(Sender: TObject);
procedure bbtnDropSynonymClick(Sender: TObject);
procedure bbtnRefreshSynonymClick(Sender: TObject);
private
{ Private declarations }
FSynonymName, FOwner: string;
Synonyms: TSynonyms;
procedure GetSynonym;
procedure GetSynonymDetail;
public
{ Public declarations }
procedure Init(ObjName, OwnerName: string); override;
end;
var
SynonymPropertiesFrm: TSynonymPropertiesFrm;
implementation
{$R *.dfm}
uses frmSchemaBrowser, Util, OraStorage, frmSchemaPublicEvent, frmSynonyms,
VisualOptions;
procedure TSynonymPropertiesFrm.Init(ObjName, OwnerName: string);
begin
inherited Show;
top := 0;
left := 0;
DMGenel.ChangeLanguage(self);
ChangeVisualGUI(self);
FSynonymName := ObjName;
if ObjectType = dbPublicSynonyms then
FOwner := 'PUBLIC'
else
FOwner := OwnerName;
GetSynonym;
end;
procedure TSynonymPropertiesFrm.GetSynonym;
begin
if Synonyms <> nil then
FreeAndNil(Synonyms);
Synonyms := TSynonyms.Create;
Synonyms.OraSession := TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).OraSession;
Synonyms.SYNONYM_NAME := FSynonymName;
Synonyms.SYNONYM_OWNER := FOwner;
Synonyms.SetDDL;
lblDescription.Caption := Synonyms.Status;
GetSynonymDetail;
redtDDL.Text := Synonyms.GetDDL;
CodeColors(self, 'Default', redtDDL, false);
end;
procedure TSynonymPropertiesFrm.GetSynonymDetail;
begin
edtOwner.Text := Synonyms.SYNONYM_OWNER;
edtName.Text := Synonyms.SYNONYM_NAME;
edtObjectOwner.Text := Synonyms.TABLE_OWNER;
edtObjectName.Text := Synonyms.TABLE_NAME;
edtObjectType.Text := Synonyms.OBJECT_TYPE;
edtDBLink.Text := Synonyms.DB_LINK;
end;
procedure TSynonymPropertiesFrm.bbtnCreateSynonymClick(Sender: TObject);
var
FSynonymList : TSynonymList;
begin
FSynonymList := TSynonymList.Create;
FSynonymList.OraSession := Synonyms.OraSession;
FSynonymList.TableOwner := FOwner;
if SynonymsFrm.Init(FSynonymList) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbSynonyms);
end;
procedure TSynonymPropertiesFrm.bbtnDropSynonymClick(Sender: TObject);
begin
if Synonyms.SYNONYM_NAME= '' then exit;
if Synonyms = nil then exit;
if SchemaPublicEventFrm.Init(Synonyms, oeDrop) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbSynonyms);
end;
procedure TSynonymPropertiesFrm.bbtnRefreshSynonymClick(Sender: TObject);
begin
GetSynonym;
end;
end.
|
unit nscTreeViewHotTruck;
{ $Id: nscTreeViewHotTruck.pas,v 1.6 2011/11/30 12:30:09 lulin Exp $ }
// $Log: nscTreeViewHotTruck.pas,v $
// Revision 1.6 2011/11/30 12:30:09 lulin
// {RequestLink:232098711}.
// - выравниваем галочки.
//
// Revision 1.5 2010/01/28 08:37:03 oman
// - new: обрабатываем пустые списки {RequestLink:182452345}
//
// Revision 1.4 2010/01/28 07:02:20 oman
// - new: развлекаемся с деревами {RequestLink:182452345}
//
// Revision 1.3 2010/01/27 14:03:24 oman
// - new: развлекаемся с деревами {RequestLink:182452345}
//
// Revision 1.2 2010/01/27 13:40:16 oman
// - new: развлекаемся с деревами {RequestLink:182452345}
//
// Revision 1.1 2010/01/27 13:14:56 oman
// - new: развлекаемся с деревами {RequestLink:182452345}
//
//
{$I nscDefine.inc }
interface
uses
l3Interfaces,
nscTreeView,
Messages,
Controls,
Graphics,
vtLister,
Classes
;
type
TOnAllowHotTruck = procedure (Sender: TObject; anIndex: Integer; var Allow: Boolean) of Object;
TnscTreeViewHotTruck = class(TnscTreeView)
private
f_AllowTrucking: Boolean;
f_HotTruckIndex: Integer;
f_OnAllowHotTruck: TOnAllowHotTruck;
private
procedure SetHotTruckIndex(aValue: Integer);
procedure Set_AllowTrucking(aValue: Boolean);
procedure UpdateTruckFromCursor;
private
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
protected
procedure DoOnGetItemStyle(aItemIndex : Integer;
const aFont : Il3Font;
var aTextBackColor : TColor;
var aItemBackColor : TColor;
var aVJustify : TvtVJustify;
var aFocused : Boolean;
var theImageVertOffset : Integer);
override;
{-}
procedure SetCursorForItem(anIndex: Integer);
override;
{-}
public
constructor Create(AOwner: TComponent);
override;
{-}
public
property HotTruckIndex: Integer
read f_HotTruckIndex;
property AllowTrucking: Boolean
read f_AllowTrucking
write Set_AllowTrucking;
property OnAllowHotTruck: TOnAllowHotTruck
read f_OnAllowHotTruck
write f_OnAllowHotTruck;
end;//TnscTreeViewHotTruck
implementation
uses
Windows
;
{ TnscTreeViewHotTruck }
procedure TnscTreeViewHotTruck.CMMouseLeave(var Message: TMessage);
begin
inherited;
SetHotTruckIndex(-1);
end;
procedure TnscTreeViewHotTruck.Set_AllowTrucking(aValue: Boolean);
begin
if (f_AllowTrucking <> aValue) then
begin
f_AllowTrucking := aValue;
if AllowTrucking then
UpdateTruckFromCursor;
Invalidate;
end;
end;
procedure TnscTreeViewHotTruck.SetHotTruckIndex(aValue: Integer);
var
l_Old: Integer;
l_Allow: Boolean;
begin
if (f_HotTruckIndex <> aValue) then
begin
l_Old := f_HotTruckIndex;
if Assigned(f_OnAllowHotTruck) then
begin
l_Allow := True;
f_OnAllowHotTruck(Self, aValue, l_Allow);
if not l_Allow then
begin
aValue := -1;
if aValue = f_HotTruckIndex then
Exit;
end;
end;
f_HotTruckIndex := aValue;
if AllowTrucking then
begin
if l_Old <> -1 then
InvalidateItem(l_Old);
if HotTruckIndex <> -1 then
InvalidateItem(HotTruckIndex);
end;
end;
end;
procedure TnscTreeViewHotTruck.UpdateTruckFromCursor;
var
l_Pos: TPoint;
begin
if AllowTrucking and HandleAllocated then
begin
GetCursorPos(l_Pos);
SetHotTruckIndex(ItemAtPos(l_Pos, True));
end;
end;
procedure TnscTreeViewHotTruck.DoOnGetItemStyle(aItemIndex: Integer;
const aFont: Il3Font; var aTextBackColor, aItemBackColor: TColor;
var aVJustify: TvtVJustify; var aFocused: Boolean;
var theImageVertOffset : Integer);
begin
inherited;
if (HotTruckIndex = aItemIndex) and AllowTrucking then
aFont.Underline := True;
end;
constructor TnscTreeViewHotTruck.Create(AOwner: TComponent);
begin
inherited Create(aOwner);
f_HotTruckIndex := -1;
end;
procedure TnscTreeViewHotTruck.SetCursorForItem(anIndex: Integer);
begin
inherited;
SetHotTruckIndex(anIndex);
end;
end.
|
unit htDataSchemeHelper;
// Модуль: "w:\common\components\rtl\Garant\HT\htDataSchemeHelper.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "ThtDataSchemeHelper" MUID: (555F0C89007D)
{$Include w:\common\components\rtl\Garant\HT\htDefineDA.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, htInterfaces
, htDataProviderParams
, daTypes
;
type
ThtDataSchemeHelper = class(Tl3ProtoObject, IhtDataSchemeHelper)
private
f_Params: ThtDataProviderParams;
protected
function TableFullPath(aTable: TdaTables): AnsiString;
function TablePassword(aTable: TdaTables): AnsiString;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aParams: ThtDataProviderParams); reintroduce;
class function Make(aParams: ThtDataProviderParams): IhtDataSchemeHelper; reintroduce;
end;//ThtDataSchemeHelper
implementation
uses
l3ImplUses
, SysUtils
, l3FileUtils
, daScheme
, daSchemeConsts
//#UC START# *555F0C89007Dimpl_uses*
//#UC END# *555F0C89007Dimpl_uses*
;
constructor ThtDataSchemeHelper.Create(aParams: ThtDataProviderParams);
//#UC START# *555F0CCD008C_555F0C89007D_var*
//#UC END# *555F0CCD008C_555F0C89007D_var*
begin
//#UC START# *555F0CCD008C_555F0C89007D_impl*
inherited Create;
aParams.SetRefTo(f_Params);
//#UC END# *555F0CCD008C_555F0C89007D_impl*
end;//ThtDataSchemeHelper.Create
class function ThtDataSchemeHelper.Make(aParams: ThtDataProviderParams): IhtDataSchemeHelper;
var
l_Inst : ThtDataSchemeHelper;
begin
l_Inst := Create(aParams);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//ThtDataSchemeHelper.Make
function ThtDataSchemeHelper.TableFullPath(aTable: TdaTables): AnsiString;
//#UC START# *555EF7F5009F_555F0C89007D_var*
//#UC END# *555EF7F5009F_555F0C89007D_var*
begin
//#UC START# *555EF7F5009F_555F0C89007D_impl*
if TdaScheme.Instance.Table(aTable).FamilyID = MainTblsFamily then
Result := ConcatDirName(f_Params.TablePath, TdaScheme.Instance.Table(aTable).Code)
else
if aTable in [da_ftAutolinkDocumentsLocal, da_ftAutolinkEditionsLocal, da_ftAutolinkDocumentsRemote, da_ftAutolinkEditionsRemote] then
Result := ConcatDirName(f_Params.DocStoragePath, 'garant\' + TdaScheme.Instance.Table(aTable).Code)
else
Result := ConcatDirName(f_Params.DocStoragePath, 'garant\' + TdaScheme.Instance.Table(aTable).Code + IntToHex(TdaScheme.Instance.Table(aTable).FamilyID, 3));
//#UC END# *555EF7F5009F_555F0C89007D_impl*
end;//ThtDataSchemeHelper.TableFullPath
function ThtDataSchemeHelper.TablePassword(aTable: TdaTables): AnsiString;
//#UC START# *555EF81A03BF_555F0C89007D_var*
const
cIndexMap: array [TdaTables] of Integer = (
1,1,0,0,0,0,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0
);
cPasswordMap : Array [0..1] of AnsiString = ('','corvax');
//#UC END# *555EF81A03BF_555F0C89007D_var*
begin
//#UC START# *555EF81A03BF_555F0C89007D_impl*
Result := cPasswordMap[cIndexMap[aTable]];
//#UC END# *555EF81A03BF_555F0C89007D_impl*
end;//ThtDataSchemeHelper.TablePassword
procedure ThtDataSchemeHelper.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_555F0C89007D_var*
//#UC END# *479731C50290_555F0C89007D_var*
begin
//#UC START# *479731C50290_555F0C89007D_impl*
FreeAndNil(f_Params);
inherited;
//#UC END# *479731C50290_555F0C89007D_impl*
end;//ThtDataSchemeHelper.Cleanup
end.
|
{******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2022 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{******************************************************************************}
unit FB4D.RealTimeDB.Listener;
interface
uses
System.Types, System.Classes, System.SysUtils, System.StrUtils, System.JSON,
System.NetConsts, System.Net.HttpClient, System.Net.URLClient,
System.NetEncoding, System.SyncObjs,
FB4D.Interfaces, FB4D.Helpers;
type
TRTDBListenerThread = class(TThread)
private const
cWaitTimeBeforeReconnect = 5000; // 5 sec
cTimeoutConnection = 60000; // 1 minute
cTimeoutConnectionLost = 61000; // 1 minute and 1sec
cDefTimeOutInMS = 500;
cJSONExt = '.json';
private
class var FNoOfConcurrentThreads: integer;
class constructor ClassCreate;
private
fBaseURL: string;
fURL: string;
fRequestID: string;
fAuth: IFirebaseAuthentication;
fResParams: TRequestResourceParam;
fClient: THTTPClient;
fAsyncResult: IAsyncResult;
fGetFinishedEvent: TEvent;
fStream: TMemoryStream;
fReadPos: Int64;
fOnListenError: TOnRequestError;
fOnStopListening: TOnStopListenEvent;
fOnListenEvent: TOnReceiveEvent;
fOnAuthRevoked: TOnAuthRevokedEvent;
fOnConnectionStateChange: TOnConnectionStateChange;
fDoNotSynchronizeEvents: boolean;
fLastKeepAliveMsg: TDateTime;
fLastReceivedMsg: TDateTime;
fConnected: boolean;
fRequireTokenRenew: boolean;
fStopWaiting: boolean;
fCloseRequest: boolean;
fListenPartialResp: string;
procedure InitListen(FirstInit: boolean);
procedure OnRecData(const Sender: TObject; ContentLength,
ReadCount: Int64; var Abort: Boolean);
procedure OnEndListenerGet(const ASyncResult: IAsyncResult);
procedure OnEndThread(Sender: TObject);
protected
procedure Execute; override;
public
constructor Create(const FirebaseURL: string; Auth: IFirebaseAuthentication);
destructor Destroy; override;
procedure RegisterEvents(ResParams: TRequestResourceParam;
OnListenEvent: TOnReceiveEvent; OnStopListening: TOnStopListenEvent;
OnError: TOnRequestError; OnAuthRevoked: TOnAuthRevokedEvent;
OnConnectionStateChange: TOnConnectionStateChange;
DoNotSynchronizeEvents: boolean);
procedure StopListener(TimeOutInMS: integer = cDefTimeOutInMS);
function IsRunning: boolean;
property ResParams: TRequestResourceParam read fResParams;
property StopWaiting: boolean read fStopWaiting;
property LastKeepAliveMsg: TDateTime read fLastKeepAliveMsg;
property LastReceivedMsg: TDateTime read fLastReceivedMsg;
end;
implementation
resourcestring
rsEvtListenerFailed = 'Event listener for %s failed: %s';
rsEvtStartFailed = 'Event listener start for %s failed: %s';
rsEvtParserFailed = 'Exception in event parser';
{ TRTDBListenerThread }
class constructor TRTDBListenerThread.ClassCreate;
begin
FNoOfConcurrentThreads := 0;
end;
constructor TRTDBListenerThread.Create(const FirebaseURL: string;
Auth: IFirebaseAuthentication);
var
EventName: string;
begin
inherited Create(true);
if FirebaseURL.EndsWith('/') then
fBaseURL := FirebaseURL.Substring(0, FirebaseURL.Length - 1)
else
fBaseURL := FirebaseURL;
fAuth := Auth;
{$IFDEF MSWINDOWS}
EventName := 'RTDBListenerGetFini' + FNoOfConcurrentThreads.ToString;
{$ELSE}
EventName := '';
{$ENDIF}
fGetFinishedEvent := TEvent.Create(nil, false, false, EventName);
OnTerminate := OnEndThread;
FreeOnTerminate := false;
inc(FNoOfConcurrentThreads);
{$IFNDEF LINUX64}
NameThreadForDebugging('FB4D.RTListenerThread', ThreadID);
{$ENDIF}
end;
destructor TRTDBListenerThread.Destroy;
begin
FreeAndNil(fGetFinishedEvent);
inherited;
end;
procedure TRTDBListenerThread.InitListen(FirstInit: boolean);
begin
if FirstInit then
begin
fClient := nil;
fStream := nil;
fStopWaiting := false;
fLastKeepAliveMsg := 0;
fLastReceivedMsg := 0;
fRequireTokenRenew := false;
fConnected := false;
end;
fReadPos := 0;
fListenPartialResp := '';
fCloseRequest := false;
end;
function TRTDBListenerThread.IsRunning: boolean;
begin
result := Started and not Finished;
end;
procedure TRTDBListenerThread.RegisterEvents(ResParams: TRequestResourceParam;
OnListenEvent: TOnReceiveEvent; OnStopListening: TOnStopListenEvent;
OnError: TOnRequestError; OnAuthRevoked: TOnAuthRevokedEvent;
OnConnectionStateChange: TOnConnectionStateChange;
DoNotSynchronizeEvents: boolean);
begin
fResParams := ResParams;
fURL := fBaseURL + TFirebaseHelpers.EncodeResourceParams(fResParams) +
cJSONExt;
fRequestID := TFirebaseHelpers.ArrStrToCommaStr(fResParams);
fOnListenEvent := OnListenEvent;
fOnStopListening := OnStopListening;
fOnListenError := OnError;
fOnAuthRevoked := OnAuthRevoked;
fOnConnectionStateChange := OnConnectionStateChange;
fDoNotSynchronizeEvents := DoNotSynchronizeEvents;
end;
procedure TRTDBListenerThread.StopListener(TimeOutInMS: integer);
var
Timeout: integer;
begin
if not fStopWaiting then
begin
fStopWaiting := true;
if not assigned(fClient) then
raise ERTDBListener.Create('Missing Client in StopListener')
else if not assigned(fAsyncResult) then
raise ERTDBListener.Create('Missing AsyncResult in StopListener')
else
fAsyncResult.Cancel;
end;
Timeout := TimeOutInMS;
while IsRunning and (Timeout > 0) do
begin
TFirebaseHelpers.SleepAndMessageLoop(5);
dec(Timeout, 5);
end;
end;
procedure TRTDBListenerThread.Execute;
var
WaitRes: TWaitResult;
LastWait: TDateTime;
begin
try
InitListen(true);
while not TThread.CurrentThread.CheckTerminated and not fStopWaiting do
begin
fClient := THTTPClient.Create;
fClient.HandleRedirects := true;
fClient.Accept := 'text/event-stream';
fClient.OnReceiveData := OnRecData;
fClient.ConnectionTimeout := cTimeoutConnection * 2;
fStream := TMemoryStream.Create;
try
InitListen(false);
if fRequireTokenRenew then
begin
if assigned(fAuth) and fAuth.CheckAndRefreshTokenSynchronous then
fRequireTokenRenew := false;
if assigned(fOnAuthRevoked) and
not TFirebaseHelpers.AppIsTerminated then
if fDoNotSynchronizeEvents then
fOnAuthRevoked(not fRequireTokenRenew)
else
TThread.Queue(nil,
procedure
begin
fOnAuthRevoked(not fRequireTokenRenew);
end);
end;
fAsyncResult := fClient.BeginGet(OnEndListenerGet,
fURL + TFirebaseHelpers.EncodeToken(fAuth.Token), fStream);
repeat
LastWait := now;
WaitRes := fGetFinishedEvent.WaitFor(cTimeoutConnectionLost);
if (WaitRes = wrTimeout) and (fLastReceivedMsg < LastWait) then
begin
fAsyncResult.Cancel;
{$IFDEF DEBUG}
TFirebaseHelpers.Log('RTDBListenerThread timeout: ' +
TimeToStr(now - fLastReceivedMsg));
{$ENDIF}
end;
until (WaitRes = wrSignaled) or CheckTerminated;
if fCloseRequest and fConnected then
begin
if assigned(fOnConnectionStateChange) then
if fDoNotSynchronizeEvents then
fOnConnectionStateChange(false)
else
TThread.Queue(nil,
procedure
begin
fOnConnectionStateChange(false);
end);
fConnected := false;
end;
finally
FreeAndNil(fStream);
FreeAndNil(fClient);
end;
end;
except
on e: exception do
if assigned(fOnListenError) then
begin
var ErrMsg := e.Message;
if fDoNotSynchronizeEvents then
fOnListenError(fRequestID, ErrMsg)
else
TThread.Queue(nil,
procedure
begin
fOnListenError(fRequestID, ErrMsg);
end)
end else
TFirebaseHelpers.LogFmt('RTDBListenerThread.Listener ' +
rsEvtListenerFailed, [fRequestID, e.Message]);
end;
end;
procedure TRTDBListenerThread.OnEndListenerGet(const ASyncResult: IAsyncResult);
var
Resp: IHTTPResponse;
ErrMsg: string;
begin
try
{$IFDEF DEBUG}
TFirebaseHelpers.Log('RTDBListenerThread.OnEndListenerGet');
{$ENDIF}
if not ASyncResult.GetIsCancelled then
begin
try
Resp := fClient.EndAsyncHTTP(ASyncResult);
if (Resp.StatusCode < 200) or (Resp.StatusCode >= 300) then
begin
fCloseRequest := true;
ErrMsg := Resp.StatusText;
if assigned(fOnListenError) then
begin
if fDoNotSynchronizeEvents then
fOnListenError(fRequestID, ErrMsg)
else
TThread.Queue(nil,
procedure
begin
fOnListenError(fRequestID, ErrMsg);
end)
end else
TFirebaseHelpers.LogFmt('RTDBListenerThread.OnEndListenerGet ' +
rsEvtStartFailed, [fRequestID, ErrMsg]);
end;
finally
Resp := nil;
end;
end;
fGetFinishedEvent.SetEvent;
except
on e: ENetException do
begin
fCloseRequest := true;
{$IFDEF DEBUG}
TFirebaseHelpers.Log(
'RTDBListenerThread.OnEndListenerGet Disconnected by Server: ' +
e.Message);
{$ENDIF}
FreeAndNil(fStream);
fGetFinishedEvent.SetEvent;
end;
on e: exception do
TFirebaseHelpers.Log('RTDBListenerThread.OnEndListenerGet Exception ' +
e.Message);
end;
end;
procedure TRTDBListenerThread.OnEndThread(Sender: TObject);
begin
if assigned(fOnStopListening) and not TFirebaseHelpers.AppIsTerminated then
TThread.ForceQueue(nil,
procedure
begin
fOnStopListening(Sender);
end);
end;
procedure TRTDBListenerThread.OnRecData(const Sender: TObject; ContentLength,
ReadCount: Int64; var Abort: Boolean);
function GetParams(Request: IURLRequest): TRequestResourceParam;
var
Path: string;
begin
Path := Request.URL.Path;
if Path.StartsWith('/') then
Path := Path.SubString(1);
if Path.EndsWith(cJSONExt) then
Path := Path.Remove(Path.Length - cJSONExt.Length);
result := SplitString(Path, '/');
end;
const
cEvent = 'event: ';
cData = 'data: ';
cKeepAlive = 'keep-alive';
cRevokeToken = 'auth_revoked';
var
ss: TStringStream;
Lines: TArray<string>;
EventName, ErrMsg: string;
DataUTF8: RawByteString;
Params: TRequestResourceParam;
JSONObj: TJSONObject;
begin
try
fLastReceivedMsg := now;
if not fConnected then
begin
if assigned(fOnConnectionStateChange) then
if fDoNotSynchronizeEvents then
fOnConnectionStateChange(true)
else
TThread.Queue(nil,
procedure
begin
fOnConnectionStateChange(true);
end);
fConnected := true;
end;
if assigned(fStream) then
begin
if fStopWaiting then
Abort := true
else begin
Abort := false;
Params := GetParams(Sender as TURLRequest);
ss := TStringStream.Create;
try
Assert(fReadPos >= 0, 'Invalid stream read position');
Assert(ReadCount - fReadPos >= 0, 'Invalid stream read count: ' +
ReadCount.ToString + ' - ' + fReadPos.ToString);
fStream.Position := fReadPos;
ss.CopyFrom(fStream, ReadCount - fReadPos);
fListenPartialResp := fListenPartialResp + ss.DataString;
Lines := fListenPartialResp.Split([#10]);
finally
ss.Free;
end;
fReadPos := ReadCount;
if (length(Lines) >= 2) and (Lines[0].StartsWith(cEvent)) then
begin
EventName := Lines[0].Substring(length(cEvent));
if Lines[1].StartsWith(cData) then
DataUTF8 := RawByteString(Lines[1].Substring(length(cData)))
else begin
// resynch
DataUTF8 := '';
fListenPartialResp := '';
end;
if EventName = cKeepAlive then
begin
fLastKeepAliveMsg := now;
fListenPartialResp := '';
end
else if EventName = cRevokeToken then
begin
fRequireTokenRenew := true;
fListenPartialResp := '';
Abort := true;
end else if length(DataUTF8) > 0 then
begin
JSONObj := TJSONObject.ParseJSONValue(UTF8ToString(DataUTF8)) as
TJSONObject;
if assigned(JSONObj) then
begin
fListenPartialResp := '';
if assigned(fOnListenEvent) and
not TFirebaseHelpers.AppIsTerminated then
if fDoNotSynchronizeEvents then
begin
fOnListenEvent(EventName, Params, JSONObj);
JSONObj.Free;
end else
TThread.Queue(nil,
procedure
begin
fOnListenEvent(EventName, Params, JSONObj);
JSONObj.Free;
end);
end;
end;
end;
end;
end else
Abort := true;
except
on e: Exception do
begin
ErrMsg := e.Message;
if assigned(fOnListenError) and not TFirebaseHelpers.AppIsTerminated then
if fDoNotSynchronizeEvents then
fOnListenError(rsEvtParserFailed, ErrMsg)
else
TThread.Queue(nil,
procedure
begin
fOnListenError(rsEvtParserFailed, ErrMsg)
end)
else
TFirebaseHelpers.Log('RTDBListenerThread.OnRecData ' +
rsEvtParserFailed + ': ' + ErrMsg);
end;
end;
end;
end.
|
unit MMO.Packet;
interface
uses
Classes;
type
TPacket = class abstract
private
protected
var m_data: TMemoryStream;
function GetMemory: Pointer;
public
constructor Create;
destructor Destroy; override;
procedure Skip(count: integer);
function Seek(offset, origin: integer): integer;
function GetSize: UInt32;
function CreateStream: TStream;
property Memory: Pointer read GetMemory;
procedure Log;
end;
implementation
constructor TPacket.Create;
begin
inherited;
m_data := TMemoryStream.Create;
end;
destructor TPacket.Destroy;
begin
m_data.Free;
inherited;
end;
procedure TPacket.Skip(count: integer);
begin
Seek(count, 1);
end;
function TPacket.Seek(offset, origin: integer): integer;
begin
Exit(m_data.Seek(offset, origin));
end;
function TPacket.GetSize;
begin
Result := m_data.Size;
end;
function TPacket.CreateStream;
var
stream: TMemoryStream;
savedPos: Int64;
begin
stream := TMemoryStream.Create;
savedPos := m_data.Position;
m_data.Position := 0;
stream.CopyFrom(m_data, m_data.Size);
m_data.Position := savedPos;
stream.Position := 0;
Result := stream;
end;
function TPacket.GetMemory;
begin
Result := m_data.Memory;
end;
procedure TPacket.Log;
begin
end;
end.
|
unit ServerHorse.Routers.Companies;
interface
uses
System.JSON,
Horse,
Horse.Jhonson,
Horse.CORS,
ServerHorse.Controller;
procedure Registry;
implementation
uses
System.Classes,
ServerHorse.Controller.Interfaces,
ServerHorse.Model.Entity.COMPANIES,
System.SysUtils,
ServerHorse.Utils,
Horse.Paginate;
procedure Registry;
begin
THorse
.Use(Paginate)
.Use(Jhonson)
.Use(CORS)
.Get('/companies',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
iController : iControllerEntity<TCOMPANIES>;
begin
iController := TController.New.COMPANIES;
iController.This
.DAO
.SQL
.Fields('COMPANIES.*, ')
.Fields('AREASEXPERTISE.DESCRIPTION AS AREASEXPERTISE, ')
.Fields('COUNTRIES.COUNTRY as COUNTRY, ')
.Fields('STATES.STATE as STATE, ')
.Fields('CITIES.CITY as CITY ')
.Join('LEFT JOIN AREASEXPERTISE ON AREASEXPERTISE.GUUID = COMPANIES.IDAREASEXPERTISE')
.Join('LEFT JOIN COUNTRIES ON COUNTRIES.GUUID = COMPANIES.IDCOUNTRY')
.Join('LEFT JOIN STATES ON STATES.GUUID = COMPANIES.IDSTATE')
.Join('LEFT JOIN CITIES ON CITIES.GUUID = COMPANIES.IDCITY')
.Where(TServerUtils.New.LikeFind(Req))
.OrderBy(TServerUtils.New.OrderByFind(Req))
.&End
.Find;
Res.Send<TJsonArray>(iController.This.DataSetAsJsonArray);
end)
.Get('/companies/:ID',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
iController : iControllerEntity<TCOMPANIES>;
begin
iController := TController.New.COMPANIES;
iController.This
.DAO
.SQL
.Where('GUUID = ' + QuotedStr(Req.Params['ID']))
.&End
.Find;
Res.Send<TJsonArray>(iController.This.DataSetAsJsonArray);
end)
.Post('/companies',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
vBody : TJsonObject;
aGuuid: string;
begin
vBody := TJSONObject.ParseJSONValue(Req.Body) as TJSONObject;
try
if not vBody.TryGetValue<String>('guuid', aGuuid) then
vBody.AddPair('guuid', TServerUtils.New.AdjustGuuid(TGUID.NewGuid.ToString()));
TController.New.COMPANIES.This.Insert(vBody);
Res.Status(200).Send<TJsonObject>(vBody);
except
Res.Status(500).Send('');
end;
end)
.Put('/companies/:ID',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
vBody : TJsonObject;
aGuuid: string;
begin
vBody := TJSONObject.ParseJSONValue(Req.Body) as TJSONObject;
try
if not vBody.TryGetValue<String>('guuid', aGuuid) then
vBody.AddPair('guuid', Req.Params['ID']);
TController.New.COMPANIES.This.Update(vBody);
Res.Status(200).Send<TJsonObject>(vBody);
except
Res.Status(500).Send('');
end;
end)
.Delete('/companies/:id',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
begin
try
TController.New.COMPANIES.This.Delete('guuid', QuotedStr(Req.Params['id']));
Res.Status(200).Send('');
except
Res.Status(500).Send('');
end;
end);
end;
end.
|
unit vcmSettings;
{ Библиотека "vcm" }
{ Автор: Люлин А.В. © }
{ Модуль: vcmSettings - }
{ Начат: 31.07.2003 14:27 }
{ $Id: vcmSettings.pas,v 1.128 2016/09/13 18:32:46 kostitsin Exp $ }
// $Log: vcmSettings.pas,v $
// Revision 1.128 2016/09/13 18:32:46 kostitsin
// {requestlink: 630194905 }
//
// Revision 1.127 2016/08/20 18:29:18 kostitsin
// {requestlink: 444236338 }
//
// Revision 1.126 2015/02/26 09:29:06 kostitsin
// List*ner -> Listener
//
// Revision 1.125 2015/02/25 13:53:27 kostitsin
// List*ner -> Listener
//
// Revision 1.124 2014/07/17 11:49:27 morozov
// {RequestLink: 340174500}
//
// Revision 1.123 2014/07/16 11:59:28 morozov
// {RequestLink: 554580396}
//
// Revision 1.122 2014/07/14 08:33:51 morozov
// {RequestLink: 554580396}
//
// Revision 1.121 2013/11/07 08:07:35 morozov
// {RequestLink: 271750647}
//
// Revision 1.120 2013/05/21 08:14:13 lulin
// - собираем тестовый проект нового генератора под XE3.
//
// Revision 1.119 2013/01/22 15:52:20 kostitsin
// [$424399029]
//
// Revision 1.118 2012/05/28 16:50:07 kostitsin
// [$367201314]
//
// Revision 1.117 2012/04/11 15:28:38 lulin
// - пытаемся разобраться с "галочками".
//
// Revision 1.116 2012/04/09 08:38:54 lulin
// {RequestLink:237994598}
// - думаем о VGScene.
//
// Revision 1.115 2012/04/04 08:56:55 lulin
// {RequestLink:237994598}
//
// Revision 1.114 2012/03/20 09:33:09 lulin
// {RequestLink:333552196}
//
// Revision 1.113 2011/09/21 18:13:31 lulin
// {RequestLink:278836572}.
//
// Revision 1.112 2011/05/18 17:45:28 lulin
// {RequestLink:266409354}.
//
// Revision 1.111 2009/12/21 12:12:05 oman
// - fix: {RequestLink:174719194}
//
// Revision 1.110 2009/09/30 15:22:58 lulin
// - убираем ненужное приведение ко вполне понятным интерфейсам.
//
// Revision 1.109 2009/08/21 07:00:12 oman
// - fix: {RequestLink:159364476}
//
// Revision 1.108 2009/08/17 11:56:11 lulin
// {RequestLink:129240934}. №37.
//
// Revision 1.107 2009/08/04 16:52:59 lulin
// - наконец-то дошли до вызова сравнения редакций, которое падает.
//
// Revision 1.106 2009/03/19 14:20:26 oman
// - fix: Сохраняем размеры пропорциональных панелей (К-139441130)
//
// Revision 1.105 2009/03/18 09:28:41 oman
// - fix: Возвращаем префикс-группу (К-139441026)
//
// Revision 1.104 2009/03/13 13:18:27 oman
// - fix: Писали под одним именем, а читали под другим (К-139436530)
//
// Revision 1.103 2009/02/12 17:09:12 lulin
// - <K>: 135604584. Выделен модуль с внутренними константами.
//
// Revision 1.102 2008/11/11 14:34:07 lulin
// - убран ненужный параметр.
//
// Revision 1.101 2008/06/04 10:51:20 mmorozov
// - new: возможность найстройки доступных для редактирования панели инструментов операций (CQ: OIT5-28281);
//
// Revision 1.100 2008/04/02 14:22:11 lulin
// - cleanup.
//
// Revision 1.99 2008/01/24 11:30:41 oman
// - new: Пишем/читаем размеры пропорционально (cq24598)
//
// Revision 1.98 2008/01/23 08:27:44 oman
// - fix: При записи/чтении размеров зон ищем родителя с подходящим
// выравниванием (cq24598)
//
// Revision 1.97 2007/12/28 17:59:38 lulin
// - удалена ненужная глобальная переменная - ссылка на метод получения настроек.
//
// Revision 1.96 2007/12/28 17:49:41 lulin
// - удален ненужный глобальный метод.
//
// Revision 1.95 2007/09/19 15:40:09 mmorozov
// - bugfix: окно не становилось на место предыдущего закрытого (CQ: OIT5- 26671), подробно см. в K<49513268>;
//
// Revision 1.94 2007/04/05 07:59:23 lulin
// - избавляемся от лишних преобразований строк при записи в настройки.
//
// Revision 1.93 2007/04/04 13:13:59 mmorozov
// - new: в функции работы с настройками добавлена возможность определения Default и Group;
//
// Revision 1.92 2007/02/07 17:48:39 lulin
// - избавляемся от копирования строк при чтении из настроек.
//
// Revision 1.91 2006/04/18 09:03:53 oman
// cleanup (убирание rCaption из vcmPathPair)
//
// Revision 1.90 2006/02/26 15:34:40 mmorozov
// - bugfix: правильно восстанавливаем размер для всячески выровненных компонентов (CQ: 19794);
//
// Revision 1.89 2006/01/18 09:26:08 oman
// - new behavior: для настроек в методы Save добавлен параметр "сделать по умолчанию"
// (по аналогии с Load)
//
// Revision 1.88 2005/12/08 13:16:39 oman
// - new behavior: убран класс TvcmSettings. Модуль vcmGBLInterfaces теперь
// не нужен
//
// Revision 1.87 2005/10/12 05:36:57 lulin
// - bug fix: не записывались строки в настройки (CQ OIT5-16921).
//
// Revision 1.86 2005/09/21 08:35:24 dolgop
// - change: изменения, связанные с появлением IString в Settings
//
// Revision 1.85 2005/08/10 14:01:33 mmorozov
// change: afw.Application.Settings - > _afwSettings;
//
// Revision 1.84 2005/07/14 16:02:46 lulin
// - new behavior: в run-time получаем ID операции по ее имени из информации, содержащейся в MenuManager'е.
//
// Revision 1.83 2005/07/12 07:25:49 mmorozov
// opt: TvcmSettings.LoadParam;
//
// Revision 1.82 2005/07/06 16:40:31 mmorozov
// bugfix: при вызове _vcmLoadParam в списке параметров был пропущен нетипизированный параметр по умолчанию (строка), вместо него подавалось логическое значение, в следствии чего в _vcmLoadParam происходило Invalid pointer _operation;
//
// Revision 1.81 2005/06/30 07:52:43 cyberz
// READY FOR TIE-TEMPLATE GENERATION
//
// Revision 1.80 2005/06/23 16:10:13 mmorozov
// change: afw.Application.Settings не инициализируется в секции инициализации;
// change: сигнатура методов чтения записи настроек;
// change: ходим через одни ворота, _vcmLoadParam и vcmSaveParam используют afw.Application.Settings. Из _vcmLoadParam и vcmSaveParam все нужное перенесено в TvcmSettings.LoadParam, TvcmSettings.SaveParam, исправлены ошибки (для некоторых типов данных не написан код для восстановления из настроек);
//
// Revision 1.79 2005/03/31 09:29:51 dinishev
// Не компилировалась версия
//
// Revision 1.78 2005/03/31 09:24:47 dinishev
// Не компилировалась версия
//
// Revision 1.77 2005/03/31 09:02:55 migel
// - fix: не компилировалось (вынесли `vcmCopyPath` и `vcmCatPath` в интерфейсную секцию - иначе не собирались мониторинги).
//
// Revision 1.76 2005/03/14 14:20:24 lulin
// - bug fix.
//
// Revision 1.75 2005/03/14 14:14:06 lulin
// - new method: IafwSettings._Clone.
//
// Revision 1.74 2005/03/14 14:05:09 lulin
// - транслируем запрос настроек (ISettings) внутреннему объекту.
//
// Revision 1.73 2005/03/14 13:21:23 lulin
// - bug fix: до _Preview-таки не доходило сообщение о необходимости перестроения после смены настроек.
//
// Revision 1.72 2005/03/14 12:22:21 lulin
// - new behavior: теперь диалог настройки печати сохраняет/читает настройки через интерфейс IafwSettings.
//
// Revision 1.71 2005/03/14 11:29:50 lulin
// - new behavior: теперь _Preview реагирует на изменение настроек (в частности колонтитулов).
//
// Revision 1.70 2005/03/14 10:56:44 lulin
// - new methods: IafwSettings.LoadCardinal, SaveCardinal.
//
// Revision 1.69 2005/03/14 10:47:43 lulin
// - new methods: IafwSettings.AddListener, RemoveListener.
//
// Revision 1.68 2005/01/12 12:47:37 lulin
// - перевел модуль afwFacade в глобальных процедур на метакласс.
//
// Revision 1.67 2005/01/11 08:19:52 lulin
// - bug fix: не компилировалось.
//
// Revision 1.66 2004/12/28 18:41:09 lulin
// - new prop: IafwApplication.Settings.
//
// Revision 1.65 2004/12/16 13:52:52 mmorozov
// new: class TvcmSettings;
// new: global function _vcm_Settings;
//
// Revision 1.64 2004/11/12 13:32:21 mmorozov
// new: field _TvcmFormParams.rFloatWindowBounds;
// new: consts cFloatLeft, cFloatTop, cFloatWidth, cFloatHeight;
// new: global func and proc vcmLoadFloatBounds, vcmSaveFloatBounds;
// new: при загрузке, чтении параметров формы читаем положение плавающей формы;
//
// Revision 1.63 2004/11/10 14:19:17 mmorozov
// new: field - _TvcmFormParams.rFloatWindowState;
// new: setting id - cFloatWindowState;
// remove: function AdjustIfOutOfView;
// new: запись, чтение параметра формы FloatWindowState;
//
// Revision 1.62 2004/10/08 04:53:13 mmorozov
// bugfix: не комплировалось (используем define vcmUseSettings);
//
// Revision 1.61 2004/10/07 12:40:10 mmorozov
// change: TForm -> TCustomForm;
// new: functions vcmIsCanMaximized, _vcmIsSetBoundsRect, _vcmLoadFormControls (overload), _vcmLoadFormStateAndBounds;
// new: type TvcmHackCustomForm;
//
// Revision 1.60 2004/09/23 11:47:17 am
// change: в vcmSaveShortcut теперь нужно подавать и дефолтные значения шорткатов тоже.
//
// Revision 1.59 2004/08/18 11:11:33 mmorozov
// bugfix: при чтении положения из настроек игнорируем установленное Maximized для форм у которых BorderStyle = (bsDialog, bsSingle, bsNone), устанавливаем только Left, Top;
//
// Revision 1.58 2004/07/21 09:10:06 mmorozov
// bugfix: восстановление модальных окон, которые при открытии максимизировались приводило с сворачиванию их в трубочку;
//
// Revision 1.57 2004/07/20 11:11:57 am
// bugfix: TvcmToolbarPositions.rFloatX/rFloatY могут быть и отрицательными
//
// Revision 1.56 2004/07/13 07:22:19 am
// change: при сохранении тулбара, независимо от его состояния, сохраняем плавающие координаты
//
// Revision 1.55 2004/06/29 10:49:12 mmorozov
// new behaviour: при вычитывании размеров формы из настроек, проверяем что они являются допустимыми (не выходят за пределы экрана);
//
// Revision 1.54 2004/06/11 07:08:50 mmorozov
// bugfix: не верно сохранялось значение по умолчанию;
// new: группа при чтении, сохранении настройки может быть пустой;
//
// Revision 1.53 2004/06/04 14:49:40 mmorozov
// - переход на новые настройки;
//
// Revision 1.52 2004/05/27 13:04:17 am
// new: vcmCleanShortcut.
// change: vcmSaveShortcut\vcmLoadShortcut
//
// Revision 1.51 2004/05/25 12:00:56 am
// new: vcmSaveShortcut\vcmLoadShortcut
//
// Revision 1.50 2004/04/10 10:42:59 am
// change: доп. параметр (Visible) в SaveIntParam, SaveParam
//
// Revision 1.49 2004/04/07 12:10:30 am
// change: при нажатии "Восстановить всё" сбрасываемся к дефолтным настройкам
//
// Revision 1.48 2004/04/05 13:56:09 nikitin75
// - переходим на IStringOld;
//
// Revision 1.47 2004/03/29 17:07:53 mmorozov
// new: пишем/читаем FloatID формы;
//
// Revision 1.46 2004/03/26 10:46:17 am
// new: LoadFastenMode\SaveFastenMode
//
// Revision 1.45 2004/03/24 12:28:52 law
// - bug fix: неправильно переключались нижние закладки.
//
// Revision 1.44 2004/03/23 17:42:27 law
// - new behavior: при сохранении зон не сохраняем высоту/ширину <= Control.Constraints.
//
// Revision 1.43 2004/03/23 13:42:42 law
// - new behavior: сохраняем размеры зон (CQ OIT5-6694).
//
// Revision 1.42 2004/03/16 17:09:14 mmorozov
// new: устанавливаем размеры для форм у которых BorderStyle = bsSizeable или bsSizeToolWin, остальным высталяем верхний левый;
//
// Revision 1.41 2004/03/16 08:47:56 am
// new: Сохранение формы плавающего тулбара
//
// Revision 1.40 2004/03/15 14:34:19 demon
// - bug fix: по-другому сохраняем состав Toolbar'ов по умолчанию.
//
// Revision 1.39 2004/03/15 12:37:00 law
// - new behavior: не показываем VCM настройки в форме для пользователя.
//
// Revision 1.38 2004/03/11 17:02:38 law
// - bug fix: неправильно показывалась форма выбора атрибутов из ППР.
// - new behavior: запоминаем/восстанавливаем состояние формы Floating.
//
// Revision 1.36 2004/03/11 12:19:32 law
// - bug fix: неправильно определялся путь к контролу, в котором "лежит" плавающая форма.
//
// Revision 1.35 2004/03/10 16:56:51 law
// - extract method: vcmSaveLayout - сохраняет позицию и размеры формы.
//
// Revision 1.34 2004/03/10 14:18:29 am
// new: vcmSaveCardinalParamS, vcmSaveToolbarPos пользует функции с суффиксом S
//
// Revision 1.33 2004/03/05 17:10:24 law
// - new behavior: формы встраиваются в тот док, который был запомнен в настройках.
//
// Revision 1.32 2004/03/05 15:30:30 law
// - change: в vcmLoad*Param передаем массив пар, а не массив строк.
//
// Revision 1.31 2004/03/04 19:32:54 law
// - new behavior: сделано сохранение имени дока для встроенных форм.
//
// Revision 1.30 2004/03/04 18:53:05 law
// - new behavior: изменен алгоритм получения пути для настроек формы.
// - ne procs: _vcmSaveStrParam, vcmSaveStrParamS.
//
// Revision 1.29 2004/03/04 16:09:08 law
// - new behavior: читаем настройки без Exception'ов.
//
// Revision 1.28 2004/03/04 13:00:42 am
// change: признак существования тулбара сохраняем отдельно (cVisibleName)
//
// Revision 1.27 2004/03/04 08:09:14 am
// new: vcmSaveToolbarPos/vcmLoadToolbarPos
//
// Revision 1.26 2004/03/01 17:42:51 law
// - new type: TvcmPath.
//
// Revision 1.25 2004/03/01 17:30:07 law
// - new method: _vcmGetFormPath.
//
// Revision 1.24 2004/03/01 17:10:47 law
// - new proc: _vcmGetFormPathEntry.
//
// Revision 1.23 2004/03/01 16:38:14 law
// - bug fix.
//
// Revision 1.22 2004/03/01 16:33:08 law
// - new type: TvcmPathPairs.
//
// Revision 1.21 2004/03/01 16:21:15 law
// - new behavior: при записи положения и размеров форм указываем осмысленные значения по умолчанию.
//
// Revision 1.20 2004/03/01 15:34:31 law
// - bug fix: в настройки пишем более правильный заголовок осносной формы.
//
// Revision 1.19 2004/03/01 14:44:44 am
// new methods: vcmSaveToolbarPos, vcmLoadToolbarPos
//
// Revision 1.18 2004/03/01 13:53:26 law
// - new behavior: сохраняем/восстанавливаем положение и размеры всех плавающих и модальных форм.
//
// Revision 1.17 2004/03/01 12:09:02 law
// - change: задел на сохранение позиции и размеров всех "плавающих" форм, а не только основной.
//
// Revision 1.16 2004/02/26 16:32:13 law
// - new behavior: сохраняем размеры и положение основной формы.
//
// Revision 1.15 2004/02/26 15:54:22 law
// - new behavior: сохраняем состояние Maximized основной формы.
//
// Revision 1.14 2004/02/20 13:36:01 am
// change: убраны идентификаторы групп
//
// Revision 1.13 2004/02/20 09:34:27 am
// *** empty log message ***
//
// Revision 1.12 2004/02/19 09:51:50 am
// bugfixs: запись значений
//
// Revision 1.11 2004/02/18 09:19:22 am
// *** empty log message ***
//
// Revision 1.10 2004/02/18 09:11:04 am
// new: у message'ей появилось свойство Key - путь, по которому они сохраняются в настройках
// change: в vcmSettings есть возможность сохранять в группу, отличную от _vcmGroup,
// передавая группу в пути и выставляя aGroupInPath
//
// Revision 1.9 2004/02/09 14:00:26 law
// - new behavior: читаем из настроек и информацию об операциях модулей тоже.
//
// Revision 1.8 2004/02/06 12:13:42 law
// - new behavior: сохраняем/читаем необходимость наличия разделителя.
//
// Revision 1.7 2004/02/05 19:40:07 law
// - new behavior: строим Toolbar'ы по сохраненным настройкам. Пока не учитываются разделители, операции модулей, порядок операций и неправильно читается первая копия основного окна. Завтра буду добивать это дело.
//
// Revision 1.6 2004/02/05 17:00:32 law
// - new behavior: вычитываем Toolbar'ы из настроек, но пока плюем на то, что прочитали.
//
// Revision 1.5 2004/01/30 16:32:15 law
// - new behavior: записываем/читаем результат диалога.
//
// Revision 1.4 2003/12/17 14:35:34 dk3
// new settings
//
// Revision 1.3 2003/07/31 16:02:21 law
// - new param: vcmSaveParam - aDefault.
//
// Revision 1.2 2003/07/31 15:43:54 law
// - new behavior: сделано сохранение позиций кнопок.
//
// Revision 1.1 2003/07/31 11:50:00 law
// - new behavior: сохранение настроек toolbar'а в базу (пока не работает GblAdapter).
//
{$Include vcmDefine.inc }
interface
uses
Types,
Classes,
Controls,
Forms,
l3Interfaces,
{$IfDef vcmNeedL3}
l3IID,
{$EndIf vcmNeedL3}
afwInterfaces,
vcmInterfaces,
vcmExternalInterfaces,
vcmBase,
vcmContainerForm,
vcmAction
;
type
TvcmPathPair = record
rName : AnsiString;
end;//TvcmPathPair
TvcmPathPairs = array of TvcmPathPair;
TvcmButtonParams = record
rVisible : Boolean;
rPos : Cardinal;
rNeedSep : Boolean;
rIconText : Boolean;
end;//TvcmButtonParams
TvcmToolbarPositions = record
rPos : Integer;
rRow : Integer;
rFloating : Boolean;
rDock : Cardinal;
rFloatingWidth : Cardinal;
rFloatX : Integer;
rFloatY : Integer;
end;//TvcmToolbarPositions
TvcmFormParams = record
rFloating : Boolean;
rFloatingVisible : Boolean;
rParent : IvcmCString;
rFloatID : Integer;
{* - идентификатор плавающего окна. }
rFloatWindowState : Integer;
{* - состояние плавающего окна. }
rFloatWindowBounds : TRect;
{* - положение плавающей формы. }
end;//TvcmFormParams
const
vcmGroup = 'Настройки форм';
vcmAvailableOpsForCustomizeToolbar = 'vcmAvailableFormOpsForCustomize';
// - доступные для настройки операции;
function vcmPathPair(const aName : AnsiString): TvcmPathPair;
{-}
function vcmLoadParam(const aPath : array of TvcmPathPair;
aType : Byte;
out aValue;
const aDefault;
aLoadDefault : boolean = false;
const aGroup : AnsiString = vcmGroup): Boolean;
{-}
function vcmLoadStrParam(const aPath : array of TvcmPathPair;
out aValue : IvcmCString;
aLoadDefault : boolean = false;
const aGroup : AnsiString = vcmGroup): Boolean;
{-}
function vcmLoadBoolParam(const aPath : array of TvcmPathPair;
out aValue : Boolean;
aLoadDefault : Boolean = false;
const aGroup : AnsiString = vcmGroup): Boolean;
{-}
function vcmLoadIntParam(const aPath : array of TvcmPathPair;
out aValue : Integer;
const aGroup : AnsiString = vcmGroup;
aLoadDefault : Boolean = false;
const aDefault : Integer = 0): Boolean;
{-}
function vcmLoadCardinalParam(const aPath : array of TvcmPathPair;
out aValue : Cardinal;
aLoadDefault : Boolean = false): Boolean;
{-}
procedure vcmSaveParam(const aPath : array of TvcmPathPair;
aType : Byte;
const aValue;
const aDefault;
const aGroup : AnsiString = vcmGroup);
{-}
procedure vcmSaveStrParam(const aPath : array of TvcmPathPair;
const aValue : IvcmCString;
const aDefault : ANSIString = '';
const aGroup : AnsiString = vcmGroup);
{-}
procedure vcmSaveStrParamS(const aPath : array of TvcmPathPair;
const aValue : IvcmCString;
const aGroup : AnsiString = vcmGroup);
{-}
procedure vcmSaveBoolParam(const aPath : array of TvcmPathPair;
aValue : Boolean;
aDefault : Boolean = true;
const aGroup : AnsiString = vcmGroup);
{-}
procedure vcmSaveBoolParamS(const aPath : array of TvcmPathPair;
aValue : Boolean);
{-}
procedure vcmSaveIntParam(const aPath : array of TvcmPathPair;
aValue : Integer;
aDefault : Integer = 0;
const aGroup : AnsiString = vcmGroup);
{-}
procedure vcmSaveIntParamS(const aPath : array of TvcmPathPair;
aValue : Integer;
const aGroup : AnsiString = vcmGroup);
{-}
procedure vcmSaveCardinalParam(const aPath : array of TvcmPathPair;
aValue : Cardinal;
aDefault : Cardinal = 0;
const aGroup : AnsiString = vcmGroup);
{-}
procedure vcmSaveCardinalParamS(const aPath : array of TvcmPathPair;
aValue : Cardinal;
const aGroup : AnsiString = vcmGroup);
{-}
procedure vcmCopyPath(const A : array of TvcmPathPair;
out B : TvcmPathPairs);
{-}
procedure vcmCatPath(const A : array of TvcmPathPair;
const B : array of TvcmPathPair;
out C : TvcmPathPairs);
{-}
function vcmArrayPathPairToString(const aValue : array of TvcmPathPair) : AnsiString;
{* - преобразует "array of TvcmPathPair" в единый строковый идентификатор. }
function vcmLoadToolbarVisible(const aUtName : AnsiString;
const aTbName : AnsiString;
out aVisible : Boolean): Boolean;
{-}
function vcmLoadButtonParams(const aUtName : AnsiString;
const aTbName : AnsiString;
const aEnName : AnsiString;
const aOpName : AnsiString;
out theParams : TvcmButtonParams): Boolean;
{-}
function vcmLoadShortcut(const aContOpName : AnsiString;
const aOpName : AnsiString;
out aShortcut : Cardinal;
out aSecShort : IvcmCString): Boolean;
{-}
procedure vcmSaveShortcut(const aOpContName : AnsiString;
const aOpName : AnsiString;
const aShortcut : Cardinal;
const aSecShort : IvcmCString;
const aDefaultShortcut : Cardinal;
const aDefaultSecShort : AnsiString);
{-}
procedure vcmSaveToolbarAction(const aUtName : AnsiString;
const aTbName : AnsiString;
anAction : TvcmAction;
anEnabled : Boolean;
anIndex : Cardinal = High(Cardinal);
aNeedSep : Boolean = false;
aIconText : Boolean = false); overload;
{-}
procedure vcmSaveToolbarAction(const aUtName : AnsiString;
const aTbName : AnsiString;
anEntityName : AnsiString;
anOpName : AnsiString;
anEnabled : Boolean;
anIndex : Cardinal = High(Cardinal);
aNeedSep : Boolean = false;
aIconText : Boolean = false); overload;
{-}
procedure vcmSaveToolbarPos(const aUtName : AnsiString;
const aTbName : AnsiString;
aParams : TvcmToolbarPositions);
{-}
function vcmLoadToolbarPos(const aUtName : AnsiString;
const aTbName : AnsiString;
out aParams : TvcmToolbarPositions): Boolean;
{-}
procedure vcmCleanToolbar(const aUTName : AnsiString;
const aTBName : AnsiString);
{-}
procedure vcmCleanShortcut(const aOpContName : AnsiString;
const aOpName : AnsiString);
{-}
procedure vcmLoadForm(aForm: TCustomForm);
{-}
procedure vcmSaveForm(aForm: TCustomForm);
{-}
function vcmExtractGroup(aPath: AnsiString): AnsiString;
{-}
function vcmExtractPath(aPath: AnsiString): AnsiString;
{-}
function vcmLoadFormParams(anOwner : TObject;
aForm : TCustomForm;
out theParams : TvcmFormParams): Boolean;
{-}
procedure vcmGetFormPath(aForm : TwinControl;
out thePath : TvcmPathPairs;
aCheckUp : Boolean = true);
{-}
function vcmLoadFastenMode(out theParam : boolean): boolean;
{-}
procedure vcmSaveFastenMode(aMode : boolean);
{-}
procedure vcmLoadFormControls(aForm : TvcmContainerForm);
overload;
{-}
procedure vcmLoadFormControls(const aPath : array of TvcmPathPair;
const aForm : TvcmContainerForm);
overload;
{-}
function vcmLoadFormStateAndBounds(aForm : TCustomForm) : Boolean;
{-}
implementation
uses
TypInfo,
Math,
SysUtils,
{$IfDef vcmNeedL3}
l3Base,
{$EndIf vcmNeedL3}
afwFacade,
afwConsts,
vcmModuleAction,
vcmEntityAction,
vcmDispatcher,
vcmZonesCollectionItem,
vcmEntityForm,
vcmMainForm,
vcmUtils,
vcmInternalConst,
vtPanel
;
type
TvcmHackCustomForm = class(TCustomForm);
{* - сделан для доступа к protected полям TCustomForm. }
function Extract(Var aPath:AnsiString; Var aNewStr:AnsiString):boolean;
Var
l_Pos:integer;
begin
if aPath='' then
begin
Result:=false;
exit;
end;
Result:=true;
l_Pos:=Pos(g_afwPathSep, aPath);
if l_Pos>0 then
begin
aNewStr:=copy(aPath, 1, l_Pos-1);
aPath:=copy(aPath, l_Pos+1, Length(aPath)-l_Pos);
end
else
begin
aNewStr:=aPath;
aPath:='';
end;
end;
function vcmExtractGroup(aPath: AnsiString): AnsiString;
Var
l_Pos:integer;
begin
Result:=aPath;
l_Pos:=Pos(g_afwPathSep, aPath);
if l_Pos>0 then
begin
Result:=copy(aPath, 1, l_Pos-1);
end;
end;
function vcmExtractPath(aPath: AnsiString): AnsiString;
Var
l_Pos:integer;
begin
Result:='';
l_Pos:=Pos(g_afwPathSep, aPath);
if l_Pos>0 then
begin
Result:=copy(aPath, l_Pos+1, Length(aPath)-l_Pos);
end;
end;
function vcmPathPair(const aName : AnsiString): TvcmPathPair;
begin
Result.rName := aName;
end;
function vcmLoadParam(const aPath : array of TvcmPathPair;
aType : Byte;
out aValue;
const aDefault;
aLoadDefault : Boolean;
const aGroup : AnsiString): Boolean;
{$IfDef vcmUseSettings}
var
l_Settings : IafwSettings;
l_Path : AnsiString;
l_Index : Integer;
{$EndIf vcmUseSettings}
begin
Result := False;
{$IfDef vcmUseSettings}
l_Settings := afw.Application.Settings;
if (l_Settings <> nil) then
begin
// Путь настройки
l_Path := '';
for l_Index := Low(aPath) to High(aPath) do
if (l_Path = '') then
l_Path := aPath[l_Index].rName
else
l_Path := l_Path + g_afwPathSep + aPath[l_Index].rName;
if (l_Path <> '') then
begin
if (aGroup <> '') then
l_Path := aGroup + g_afwPathSep + l_Path;
// Читаем
Result := l_Settings.LoadParam(l_Path, aType, aValue, aDefault,
aLoadDefault);
end;//if (l_Path <> '') then
end;//if (l_Settings <> nil) then
{$EndIf vcmUseSettings}
end;
procedure vcmSaveParam(const aPath : array of TvcmPathPair;
aType : Byte;
const aValue;
const aDefault;
const aGroup : AnsiString);
{$IfDef vcmUseSettings}
var
l_Settings : IafwSettings;
l_Path : AnsiString;
l_Index : Integer;
l_Name : AnsiString;
l_NewName : AnsiString;
{$EndIf vcmUseSettings}
begin
{$IfDef vcmUseSettings}
l_Settings := afw.Settings;
if (l_Settings <> nil) then
try
l_Path := '';
for l_Index := Low(aPath) to High(aPath) do
with aPath[l_Index] do
begin
l_Name := rName;
while Extract(l_Name, l_NewName) do
begin
if (l_Path = '') then
l_Path := l_NewName
else
l_Path := l_Path + g_afwPathSep + l_NewName;
if (l_Index = High(aPath)) then
begin
// добавим группу если она определена
if (aGroup <> '') then
l_Path := aGroup + g_afwPathSep + l_Path;
l_Settings.SaveParam(l_Path, aType, aValue, aDefault, False);
end;//l_Index = High(aPath)
end;//while Extract(l_Name, l_NewName)
end;//with aPath[l_Index]
finally
l_Settings := nil;
end;//try..finally
{$EndIf vcmUseSettings}
end;
procedure vcmSaveStrParam(const aPath : array of TvcmPathPair;
const aValue : IvcmCString;
const aDefault : ANSIString = '';
const aGroup : AnsiString = vcmGroup);
{-}
begin
vcmSaveParam(aPath, vtANSIString, aValue, aDefault, aGroup);
end;
procedure vcmSaveStrParamS(const aPath : array of TvcmPathPair;
const aValue : IvcmCString;
const aGroup : AnsiString = vcmGroup);
{-}
begin
vcmSaveStrParam(aPath, aValue, vcmStr(aValue), aGroup);
end;
procedure vcmSaveBoolParam(const aPath : array of TvcmPathPair;
aValue : Boolean;
aDefault : Boolean = true;
const aGroup : AnsiString = vcmGroup);
begin
vcmSaveParam(aPath, vtBoolean, aValue, aDefault, aGroup);
end;
procedure vcmSaveBoolParamS(const aPath : array of TvcmPathPair;
aValue : Boolean);
{-}
begin
vcmSaveBoolParam(aPath, aValue, aValue);
end;
procedure vcmSaveIntParam(const aPath : array of TvcmPathPair;
aValue : Integer;
aDefault : Integer;
const aGroup : AnsiString);
begin
vcmSaveParam(aPath, vtInteger, aValue, aDefault, aGroup);
end;
procedure vcmSaveIntParamS(const aPath : array of TvcmPathPair;
aValue : Integer;
const aGroup : AnsiString = vcmGroup);
{-}
begin
vcmSaveIntParam(aPath, aValue, aValue, aGroup);
end;
procedure vcmSaveCardinalParam(const aPath : array of TvcmPathPair;
aValue : Cardinal;
aDefault : Cardinal = 0;
const aGroup : AnsiString = vcmGroup);
begin
vcmSaveParam(aPath, vtInteger, aValue, aDefault, aGroup);
end;
procedure vcmSaveCardinalParamS(const aPath : array of TvcmPathPair;
aValue : Cardinal;
const aGroup : AnsiString = vcmGroup);
begin
vcmSaveParam(aPath, vtInteger, aValue, aValue, aGroup);
end;
const
cToolbars : TvcmPathPair = (rName: 'Toolbars');
cPosition : TvcmPathPair = (rName: 'Position');
cNeedSep : TvcmPathPair = (rName: 'NeedSep');
cMaximized : TvcmPathPair = (rName: 'Maximized');
cLeft : TvcmPathPair = (rName: 'Left');
cTop : TvcmPathPair = (rName: 'Top');
cWidth : TvcmPathPair = (rName: 'Width');
cHeight : TvcmPathPair = (rName: 'Height');
cParentWidth : TvcmPathPair = (rName: 'ParentWidth');
cParentHeight : TvcmPathPair = (rName: 'ParentHeight');
// Константы для записи положения плавающего окна /////////////////////////////
cFloatLeft : TvcmPathPair = (rName: 'FloatLeft');
cFloatTop : TvcmPathPair = (rName: 'FloatTop');
cFloatWidth : TvcmPathPair = (rName: 'FloatWidth');
cFloatHeight : TvcmPathPair = (rName: 'FloatHeight');
///////////////////////////////////////////////////////////////////////////////
cToolbarPos : TvcmPathPair = (rName: 'Position');
cToolbarRow : TvcmPathPair = (rName: 'Row');
cToolbarDock : TvcmPathPair = (rName: 'Dock');
cToolbarFloat : TvcmPathPair = (rName: 'Floating');
cToolbarWidth : TvcmPathPair = (rName: 'Width');
cToolbarFloatX : TvcmPathPair = (rName: 'FloatX');
cToolbarFloatY : TvcmPathPair = (rName: 'FloatY');
cVisible : TvcmPathPair = (rName: 'Visible');
cZone : TvcmPathPair = (rName: 'Zone');
cIconText : TvcmPathPair = (rName: 'IconText');
cFastenToolbars : TvcmPathPair = (rName: 'FastenToolbars');
cFloatWindowID : TvcmPathPair = (rName: 'FloatWindowID');
cFloatWindowState : TvcmPathPair = (rName: 'FloatWindowState');
cFloatingVisible : TvcmPathPair = (rName: 'FloatingVisible');
cDefaultPositions : TvcmPathPair = (rName: 'DefaultPositions');
cDefaultOperations : TvcmPathPair = (rName: 'DefaultOperations');
cDefaultShortcut : TvcmPathPair = (rName: 'DefaultShortcut');
cShortcuts : TvcmPathPair = (rName: 'Shortcuts');
cShortcut : TvcmPathPair = (rName: 'Shortcut');
cSecondaryShortcut : TvcmPathPair = (rName: 'SecShortcut');
procedure vcmCopyPath(const A : array of TvcmPathPair;
out B : TvcmPathPairs);
{-}
var
l_ALen : Integer;
l_Index : Integer;
begin
l_ALen := Succ(High(A));
SetLength(B, l_ALen);
for l_Index := 0 to Pred(l_ALen) do
B[l_Index] := A[l_Index];
end;
procedure vcmCatPath(const A : array of TvcmPathPair;
const B : array of TvcmPathPair;
out C : TvcmPathPairs);
{-}
var
l_ALen : Integer;
l_BLen : Integer;
l_Index : Integer;
begin
l_ALen := Succ(High(A));
l_BLen := Succ(High(B));
SetLength(C, l_ALen + l_BLen);
for l_Index := 0 to Pred(l_ALen) do
C[l_Index] := A[l_Index];
for l_Index := 0 to Pred(l_BLen) do
C[l_ALen + l_Index] := B[l_Index];
end;
function vcmArrayPathPairToString(const aValue : array of TvcmPathPair) : AnsiString;
{* - преобразует "array of TvcmPathPair" в единый строковый идентификатор. }
var
lIndex : Integer;
begin
Result := '';
for lIndex := Low(aValue) to High(aValue) do
begin
if Result <> '' then
Result := Result + g_afwPathSep;
Result := Result + aValue[lIndex].rName;
end;
end;
function vcmLoadToolbarVisible(const aUtName : AnsiString;
const aTbName : AnsiString;
out aVisible : Boolean): Boolean;
{-}
Var
l_LoadDefault : boolean;
begin
if not vcmLoadBoolParam([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cDefaultOperations
], l_LoadDefault) then
l_LoadDefault := false;
Result := vcmLoadBoolParam([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cVisible
],
aVisible,
l_LoadDefault);
end;
procedure vcmSaveToolbarAction(const aUtName : AnsiString;
const aTbName : AnsiString;
anAction : TvcmAction;
anEnabled : Boolean;
anIndex : Cardinal = High(Cardinal);
aNeedSep : Boolean = false;
aIconText : Boolean = false); overload;
{$IfDef vcmUseSettings}
var
l_Name, l_OpName: AnsiString;
{$endif}
begin
{$IfDef vcmUseSettings}
if (anAction <> nil) then
begin
if (anAction is TvcmEntityAction) then
begin
l_Name := TvcmEntityAction(anAction).EntityDef.Name;
l_OpName := TvcmEntityAction(anAction).OpDef.Name;
end else
if (anAction is TvcmModuleAction) then
begin
l_Name := TvcmDispatcher.Instance.As_IvcmDispatcher.GetModuleByID(TvcmModuleAction(anAction).ModuleID).ModuleDef.Name;
l_OpName := TvcmModuleAction(anAction).OpDef.Name;
end;
vcmSaveToolbarAction(aUtName, aTbName, l_Name, l_OpName, anEnabled, anIndex, aNeedSep, aIconText);
end;
{$endif}
end;
procedure vcmSaveToolbarAction(const aUtName : AnsiString;
const aTbName : AnsiString;
anEntityName : AnsiString;
anOpName : AnsiString;
anEnabled : Boolean;
anIndex : Cardinal = High(Cardinal);
aNeedSep : Boolean = false;
aIconText : Boolean = false); overload;
{-}
begin
{$IfDef vcmUseSettings}
if Assigned(afw.Application.Settings) then
begin
vcmSaveBoolParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cDefaultOperations
],
false);
vcmSaveBoolParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cVisible
],
true);
vcmSaveBoolParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
vcmPathPair(anEntityName),
vcmPathPair(anOpName)
],
anEnabled);
vcmSaveCardinalParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
vcmPathPair(anEntityName),
vcmPathPair(anOpName),
cPosition
],
anIndex);
vcmSaveBoolParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
vcmPathPair(anEntityName),
vcmPathPair(anOpName),
cNeedSep
],
aNeedSep);
vcmSaveBoolParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
vcmPathPair(anEntityName),
vcmPathPair(anOpName),
cIconText
],
aIconText);
end;
{$EndIf vcmUseSettings}
end;
procedure vcmSaveToolbarPos(const aUtName : AnsiString;
const aTbName : AnsiString;
aParams : TvcmToolbarPositions);
{-}
begin
vcmSaveBoolParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cDefaultPositions
],
false);
vcmSaveCardinalParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarPos
],
Cardinal(aParams.rPos));
vcmSaveCardinalParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarRow
],
Cardinal(aParams.rRow));
vcmSaveBoolParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarFloat
],
aParams.rFloating);
vcmSaveCardinalParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarDock
],
aParams.rDock);
vcmSaveCardinalParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarWidth
],
aParams.rFloatingWidth);
vcmSaveCardinalParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarFloatX
],
Cardinal(aParams.rFloatX));
vcmSaveCardinalParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarFloatY
],
Cardinal(aParams.rFloatY));
end;
procedure vcmSaveShortcut(const aOpContName : AnsiString;
const aOpName : AnsiString;
const aShortcut : Cardinal;
const aSecShort : IvcmCString;
const aDefaultShortcut : Cardinal;
const aDefaultSecShort : AnsiString);
{-}
begin
vcmSaveBoolParamS([
cShortcuts,
vcmPathPair(aOpContName),
vcmPathPair(aOpName),
cDefaultShortcut
],
false);
vcmSaveCardinalParam([
cShortcuts,
vcmPathPair(aOpContName),
vcmPathPair(aOpName),
cShortcut
],
aShortcut,
aDefaultShortcut);
vcmSaveStrParam([
cShortcuts,
vcmPathPair(aOpContName),
vcmPathPair(aOpName),
cSecondaryShortcut
],
aSecShort,
aDefaultSecShort);
end;
function vcmLoadToolbarPos(const aUtName : AnsiString;
const aTbName : AnsiString;
out aParams : TvcmToolbarPositions): Boolean;
{-}
Var
l_LoadDefault: boolean;
begin
if not vcmLoadBoolParam([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cDefaultPositions
], l_LoadDefault) then
l_LoadDefault := false;
Result := vcmLoadCardinalParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarPos],
Cardinal(aParams.rPos),
l_LoadDefault) and
vcmLoadCardinalParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarRow],
Cardinal(aParams.rRow),
l_LoadDefault) and
vcmLoadBoolParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarFloat],
aParams.rFloating,
l_LoadDefault) and
vcmLoadCardinalParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarDock],
aParams.rDock,
l_LoadDefault) and
vcmLoadCardinalParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarWidth],
aParams.rFloatingWidth,
l_LoadDefault) and
vcmLoadCardinalParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarFloatX],
Cardinal(aParams.rFloatX),
l_LoadDefault) and
vcmLoadCardinalParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cToolbarFloatY],
Cardinal(aParams.rFloatY),
l_LoadDefault);
end;
function vcmLoadButtonParams(const aUtName : AnsiString;
const aTbName : AnsiString;
const aEnName : AnsiString;
const aOpName : AnsiString;
out theParams : TvcmButtonParams): Boolean;
{-}
Var
l_LoadDefault: boolean;
begin
if not vcmLoadBoolParam([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cDefaultOperations
], l_LoadDefault) then
l_LoadDefault := false;
Result := vcmLoadBoolParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
vcmPathPair(aEnName),
vcmPathPair(aOpName)],
theParams.rVisible,
l_LoadDefault) AND
vcmLoadCardinalParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
vcmPathPair(aEnName),
vcmPathPair(aOpName),
cPosition],
theParams.rPos,
l_LoadDefault) AND
vcmLoadBoolParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
vcmPathPair(aEnName),
vcmPathPair(aOpName),
cNeedSep],
theParams.rNeedSep,
l_LoadDefault) AND
vcmLoadBoolParam([vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
vcmPathPair(aEnName),
vcmPathPair(aOpName),
cIconText],
theParams.rIconText,
l_LoadDefault);
end;
function vcmLoadShortcut(const aContOpName : AnsiString;
const aOpName : AnsiString;
out aShortcut : Cardinal;
out aSecShort : IvcmCString): Boolean;
{-}
Var
l_LoadDefault: boolean;
begin
if not vcmLoadBoolParam([
cShortcuts,
vcmPathPair(aContOpName),
vcmPathPair(aOpName),
cDefaultShortcut],
l_LoadDefault) then
l_LoadDefault := false;
Result := vcmLoadCardinalParam([
cShortcuts,
vcmPathPair(aContOpName),
vcmPathPair(aOpName),
cShortcut],
aShortcut,
l_LoadDefault) AND
vcmLoadStrParam([
cShortcuts,
vcmPathPair(aContOpName),
vcmPathPair(aOpName),
cSecondaryShortcut],
aSecShort,
l_LoadDefault);
end;
function vcmLoadStrParam(const aPath : array of TvcmPathPair;
out aValue : IvcmCString;
aLoadDefault : boolean;
const aGroup : AnsiString): Boolean;
{-}
var
lStr : AnsiString;
begin
lStr := '';
Result := vcmLoadParam(aPath, vtANSIString, aValue, lStr, aLoadDefault, aGroup);
end;
function vcmLoadBoolParam(const aPath : array of TvcmPathPair;
out aValue : Boolean;
aLoadDefault : Boolean = False;
const aGroup : AnsiString = vcmGroup): Boolean;
{-}
var
lBool : Boolean;
begin
lBool := False;
Result := vcmLoadParam(aPath, vtBoolean, aValue, lBool, aLoadDefault, aGroup);
end;
function vcmLoadIntParam(const aPath : array of TvcmPathPair;
out aValue : Integer;
const aGroup : AnsiString;
aLoadDefault : Boolean;
const aDefault : Integer): Boolean;
{-}
begin
Result := vcmLoadParam(aPath, vtInteger, aValue, aDefault, aLoadDefault, aGroup);
end;
function vcmLoadCardinalParam(const aPath : array of TvcmPathPair;
out aValue : Cardinal;
aLoadDefault : Boolean = False): Boolean;
{-}
var
lCar : Cardinal;
begin
lCar := 0;
Result := vcmLoadParam(aPath, vtInteger, aValue, lCar, aLoadDefault);
end;
type
THackWinControl = class(TWinControl);
function vcmGetFormPathEntry(aForm: TWinControl): TvcmPathPair;
begin
if (aForm Is TvcmEntityForm) AND
(TvcmEntityForm(aForm).CurUserTypeDef <> nil) then
begin
with TvcmEntityForm(aForm).CurUserTypeDef do
Result.rName := Name + TvcmEntityForm(aForm).SettingsSuffix;
end//aForm Is TvcmEntityForm
else
begin
if (aForm Is TvcmEntityForm) then
Result.rName := TvcmEntityForm(aForm).FormID.rName
else
Result.rName := THackWinControl(aForm).Caption;
end;//TvcmEntityForm(aForm).CurUserTypeDef <> nil
end;
function vcmLoadFormRect(const aPath : array of TvcmPathPair;
aForm : TCustomForm;
out theRect : TRect): Boolean;
{-}
var
l_PPath : TvcmPathPairs;
begin
Result := false;
vcmCatPath(aPath, cTop, l_PPath);
if vcmLoadIntParam(l_PPath, theRect.Top) then
Result := true
else
theRect.Top := aForm.Top;
vcmCatPath(aPath, cLeft, l_PPath);
if vcmLoadIntParam(l_PPath, theRect.Left) then
Result := true
else
theRect.Left := aForm.Left;
vcmCatPath(aPath, cHeight, l_PPath);
if vcmLoadIntParam(l_PPath, theRect.Bottom) then
Result := true
else
theRect.Bottom := aForm.Height;
theRect.Bottom := theRect.Top + theRect.Bottom;
vcmCatPath(aPath, cWidth, l_PPath);
if vcmLoadIntParam(l_PPath, theRect.Right) then
Result := true
else
theRect.Right := aForm.Width;
theRect.Right := theRect.Left + theRect.Right;
end;
procedure vcmLoadFloatBounds(const aPath : array of TvcmPathPair;
out theRect : TRect);
{* - читает положение плавающей формы, для данной формы. }
var
l_PPath : TvcmPathPairs;
begin
vcmCatPath(aPath, cFloatTop, l_PPath); vcmLoadIntParam(l_PPath, theRect.Top);
vcmCatPath(aPath, cFloatLeft, l_PPath); vcmLoadIntParam(l_PPath, theRect.Left);
vcmCatPath(aPath, cFloatHeight, l_PPath); vcmLoadIntParam(l_PPath, theRect.Bottom);
vcmCatPath(aPath, cFloatWidth, l_PPath); vcmLoadIntParam(l_PPath, theRect.Right);
end;
procedure vcmSaveFloatBounds(const aPath : array of TvcmPathPair;
const theRect : TRect);
{* - записывает положение плавающей формы, для данной формы. }
var
l_PPath : TvcmPathPairs;
begin
// пустой theRect означает, что форма не была плавающей
if IsRectEmpty(theRect) then
Exit;
vcmCatPath(aPath, cFloatTop, l_PPath); vcmSaveIntParam(l_PPath, theRect.Top);
vcmCatPath(aPath, cFloatLeft, l_PPath); vcmSaveIntParam(l_PPath, theRect.Left);
vcmCatPath(aPath, cFloatHeight, l_PPath); vcmSaveIntParam(l_PPath, theRect.Bottom);
vcmCatPath(aPath, cFloatWidth, l_PPath); vcmSaveIntParam(l_PPath, theRect.Right);
end;
function vcmLoadExtent(const aPath : array of TvcmPathPair;
const aControl : TControl) : Boolean;
{-}
var
l_Value : Integer;
l_Path : TvcmPathPairs;
l_ParentValue: Integer;
l_NeedAlign: Boolean;
l_ParentControl: IafwProportionalControl;
begin
Result := false;
l_NeedAlign := False;
if aControl.Align = alClient then
Exit;
if aControl.Parent = nil then
Exit;
Supports(aControl.Parent, IafwProportionalControl, l_ParentControl);
vcmCatPath(aPath, cWidth, l_Path);
if vcmLoadIntParam(l_Path, l_Value) and
(aControl.Align in [alNone, alLeft, alRight]) then
begin
vcmCatPath(aPath, cParentWidth, l_Path);
if Assigned(l_ParentControl) and
vcmLoadIntParam(l_Path, l_ParentValue) and
(l_ParentValue <> aControl.Parent.Width) then
begin
if l_ParentValue = 0 then
l_ParentValue := aControl.Parent.Width;
l_Value := (aControl.Parent.Width * l_Value) div l_ParentValue;
end;//Assigned(l_ParentControl) and vcmLoadIntParam(l_Path, l_ParentValue) and (l_ParentValue <> aControl.Parent.Width)
aControl.Width := l_Value;
l_NeedAlign := True;
end;//vcmLoadIntParam(l_Path, l_Value)
vcmCatPath(aPath, cHeight, l_Path);
if vcmLoadIntParam(l_Path, l_Value) and
(aControl.Align in [alNone, alTop, alBottom]) then
begin
vcmCatPath(aPath, cParentHeight, l_Path);
if Assigned(l_ParentControl) and
vcmLoadIntParam(l_Path, l_ParentValue) and
(l_ParentValue <> aControl.Parent.Height) then
begin
if l_ParentValue = 0 then
l_ParentValue := aControl.Parent.Height;
l_Value := (aControl.Parent.Height * l_Value) div l_ParentValue;
end;//Assigned(l_ParentControl) and vcmLoadIntParam(l_Path, l_ParentValue) and (l_ParentValue <> aControl.Parent.Height)
aControl.Height := l_Value;
l_NeedAlign := True;
end;//vcmLoadIntParam(l_Path, l_Value)
if l_NeedAlign then
Result := true;
if l_NeedAlign and Assigned(l_ParentControl) then
l_ParentControl.NotifyLoaded;
end;
function vcmGetNonClientAlignedControl(const aControl: TControl;
const aForm: TvcmContainerForm): TControl;
begin
Result := aControl;
while (Result <> nil) and (Result <> aForm) and (Result.Align = alClient) do
Result := Result.Parent;
if Result = aForm then
Result := nil;
end;
procedure vcmLoadOwnedControl(const aPath: array of TvcmPathPair;
const aControl: TControl;
const aForm: TvcmContainerForm);
var
l_Path : TvcmPathPairs;
l_Control: TControl;
begin
l_Control := vcmGetNonClientAlignedControl(aControl, aForm);
if Assigned(l_Control) then
begin
vcmCatPath(aPath, [vcmPathPair(l_Control.Name)], l_Path);
if not vcmLoadExtent(l_Path, l_Control) then
begin
(* if (l_Control.Name = 'RightNavigator') then
vcmCatPath(aPath, [vcmPathPair('fRightNavigator')], l_Path)
else
if (l_Control.Name = 'LeftNavigator') then
vcmCatPath(aPath, [vcmPathPair('fLeftNavigator')], l_Path)
else
Exit;
vcmLoadExtent(l_Path, l_Control);*)
end;//not vcmLoadExtent(l_Path, l_Control)
end;//Assigned(l_Control)
end;
procedure vcmLoadFormControls(aForm : TvcmContainerForm);
var
l_Path : TvcmPathPairs;
begin
vcmGetFormPath(aForm, l_Path);
vcmLoadFormControls(l_Path, aForm);
end;
procedure vcmLoadFormControls(const aPath: array of TvcmPathPair;
const aForm: TvcmContainerForm);
{-}
var
l_Index : Integer;
l_Zone : TvcmZonesCollectionItem;
begin
with aForm.Zones do
for l_Index := 0 to Pred(Count) do
begin
l_Zone := TvcmZonesCollectionItem(Items[l_Index]);
if (l_Zone.Control Is TControl) then
vcmLoadOwnedControl(aPath, TControl(l_Zone.Control), aForm);
end;//for l_Index
end;
function vcmIsCanMaximized(aForm : TCustomForm) : Boolean;
var
l_Form: IvcmSizeableForm;
begin
if Supports(aForm, IvcmSizeableForm, l_Form) then
begin
try
Result := l_Form.CanBeMaximized;
finally
l_Form := nil;
end;//try..finally
end
else
Result := (not (aForm.BorderStyle in [bsDialog, bsSingle, bsNone]));
end;
function vcmIsSetBoundsRect(aForm : TCustomForm) : Boolean;
var
l_Form: IvcmSizeableForm;
begin
if Supports(aForm, IvcmSizeableForm, l_Form) then
begin
try
Result := l_Form.CanChangeSize;
finally
l_Form := nil;
end;
end
else
Result := (aForm.BorderStyle in [bsSizeable, bsSizeToolWin]);
end;
function vcmLoadFormStateAndBounds(aForm : TCustomForm) : Boolean;
var
l_Path : TvcmPathPairs;
l_PPath : TvcmPathPairs;
l_Maximized : Boolean;
l_Rect : TRect;
begin
Result := False;
(* Maximized property *)
vcmGetFormPath(aForm, l_Path);
(* Bounds property *)
vcmCatPath(l_Path, cMaximized, l_PPath);
if vcmLoadBoolParam(l_PPath, l_Maximized) and (l_Maximized) and
vcmIsCanMaximized(aForm) then
begin
aForm.WindowState := wsMaximized;
Result := True;
end//vcmLoadBoolParam(l_PPath, l_Maximized) and (l_Maximized)
else
if vcmIsSetBoundsRect(aForm) and
vcmLoadFormRect(l_Path, aForm, l_Rect) then
begin
with aForm do
SetBounds(l_Rect.Left, l_Rect.Top, Width, Height);
Result := True;
end;//vcmIsSetBoundsRect(aForm)
end;
procedure vcmLoadForm(aForm: TCustomForm);
{-}
var
l_Path : TvcmPathPairs;
l_PPath : TvcmPathPairs;
l_Maximized : Boolean;
l_NeedLoad : Boolean;
l_ChangePos : Boolean;
l_Rect : TRect;
l_IsMain : Boolean;
l_IsMainContainer: Boolean;
begin
if (aForm Is TvcmEntityForm) then
if TvcmEntityForm(aForm).NeedSaveInSettings then
begin
vcmGetFormPath(aForm, l_Path);
l_ChangePos := false;
l_IsMain := (aForm Is TvcmMainForm);
l_IsMainContainer := Supports(aForm, IafwMainFormContainer);
if l_IsMain OR l_IsMainContainer then
l_NeedLoad := True
else
l_NeedLoad := (TvcmEntityForm(aForm).ZoneType in vcm_NotContainedForm);
if l_NeedLoad then
begin
vcmCatPath(l_Path, cMaximized, l_PPath);
if vcmLoadBoolParam(l_PPath, l_Maximized) AND l_Maximized then
begin
(* максимизируем *)
if vcmIsCanMaximized(aForm) then
begin
aForm.WindowState := wsMaximized;
l_ChangePos := true;
end//vcmIsCanMaximized(aForm)
(* форма с неизменяемыми размерами установим Left, Top *)
else
if vcmLoadFormRect(l_Path, aForm, l_Rect) then
begin
aForm.Left := l_Rect.Left;
aForm.Top := l_Rect.Top;
end;//vcmLoadFormRect(l_Path, aForm, l_Rect)
end//vcmLoadBoolParam(l_PPath, l_Maximized) AND l_Maximized
else
begin
if vcmLoadFormRect(l_Path, aForm, l_Rect) then
begin
l_Rect := vcmUtils.vcmCheckWindowBounds(l_Rect);
// l_ChangePos := true;
// - это тоже не глупость (!) с включенной этой строчкое неправильно
// показывалось окно выбора атрибута в ППР, при этом с папками все ОК
if vcmIsSetBoundsRect(aForm) then
aForm.BoundsRect := l_Rect
else
begin
aForm.Left := l_Rect.Left;
aForm.Top := l_Rect.Top;
end;//vcmIsSetBoundsRect(aForm)
(* Assert(aForm.Height > 0,
Format('Высота формы %s, считанная из настроек почему-то оказалась <= 0', [aForm.ClassName]));*)
end;//vcmLoadFormRect(l_Path, aForm, l_Rect)
end;//vcmLoadBoolParam(l_PPath, l_Maximized) AND l_Maximized
end//l_NeedLoad
else
if l_IsMain OR l_IsMainContainer then
l_ChangePos := true;
// - это не глупость (!) это серьезно уменьшает время открытия нового окна
if l_ChangePos and
(
// Для главной формы с WindowState = wsMaximized нужно установить
// aForm.Position в котором вызывается RecreateWnd, иначе при создании
// пунктов меню придёт WMSize с SizeType = SIZENORMAL и Maximized слетит:
l_IsMain or
// Для остальных форм (они у нас модальные) не вызываем, потому что в
// этом случае при восстановлении окно сворачивается в трубочку:
(aForm.WindowState <> wsMaximized)
) then
TvcmHackCustomForm(aForm).Position := poDefault;
(* Assert(l_IsMain OR
(aForm.Height > 0) OR
not(aForm.Parent Is TvtCustomPanel),
Format('Высота формы %s почему-то оказалась <= 0', [aForm.ClassName]));*)
if l_IsMain OR (aForm Is TvcmContainerForm) then
vcmLoadFormControls(l_Path, TvcmContainerForm(aForm));
end;//aForm Is TvcmEntityForm
end;//vcmLoadForm
procedure vcmGetFormPath(aForm : TWinControl;
out thePath : TvcmPathPairs;
aCheckUp : Boolean = true);
{-}
var
l_Ofs : Integer;
l_Len : Integer;
l_Index : Integer;
l_Zone : AnsiString;
l_Path : TvcmPathPairs;
l_Cont : IvcmContainer;
begin
l_Ofs := 0;
if (aForm Is TvcmEntityForm) AND not (aForm Is TvcmMainForm) then
begin
if not (TvcmEntityForm(aForm).ZoneType in vcm_NotContainedForm) then
begin
l_Zone := GetEnumName(TypeInfo(TvcmZoneType), Ord(TvcmEntityForm(aForm).ZoneType));
Assert(l_Zone <> '');
SetLength(l_Path, Succ(l_Ofs));
l_Path[l_Ofs] := vcmPathPair(l_Zone);
Inc(l_Ofs);
end;//not (TvcmEntityForm(aForm).ZoneType in vcm_NotContainedForm)
end;//aForm Is TvcmEntityForm..
SetLength(l_Path, Succ(l_Ofs));
l_Path[l_Ofs] := vcmGetFormPathEntry(aForm);
if aCheckUp AND (aForm Is TvcmEntityForm) then
begin
while true do
begin
l_Cont := TvcmEntityForm(aForm).Container;
if (l_Cont = nil) OR l_Cont.IsNull then
break;
l_Len := Length(l_Path);
SetLength(l_Path, Succ(l_Len));
aForm := l_Cont.AsForm.VCLWinControl As TCustomForm;
l_Path[l_Len] := vcmGetFormPathEntry(aForm);
end;//while true
end;//aForm Is TvcmEntityForm
l_Len := Length(l_Path);
if (l_Len = 1) then
thePath := l_Path
else
begin
SetLength(thePath, l_Len);
for l_Index := 0 to Pred(l_Len) do
thePath[l_Index] := l_Path[Pred(l_Len) - l_Index];
end;//l_Len = 1
end;
function vcmLoadFastenMode(out theParam : boolean): boolean;
begin
Result := vcmLoadBoolParam([cFastenToolbars], theParam);
end;
procedure vcmSaveFastenMode(aMode : boolean);
begin
vcmSaveBoolParamS([cFastenToolbars], aMode);
end;
procedure vcmSaveExtent(const aPath : array of TvcmPathPair;
const aControl : TControl);
{-}
var
l_Path : TvcmPathPairs;
l_ControlWidth: Integer;
l_ControlHeight: Integer;
begin
if Assigned(aControl.Parent) and Supports(aControl.Parent, IafwProportionalControl) then
with aControl.Parent do
begin
vcmCatPath(aPath, cParentWidth, l_Path);
vcmSaveIntParamS(l_Path, Width);
vcmCatPath(aPath, cParentHeight, l_Path);
vcmSaveIntParamS(l_Path, Height);
end;
//http://mdp.garant.ru/pages/viewpage.action?pageId=271750647
(*if (aControl.Width >= aControl.Constraints.MinWidth + 5) then
begin*)
vcmCatPath(aPath, cWidth, l_Path);
l_ControlWidth := Max(aControl.Constraints.MinWidth, aControl.Width);
vcmSaveIntParamS(l_Path, l_ControlWidth);
(*end;//..Width..*)
//http://mdp.garant.ru/pages/viewpage.action?pageId=271750647
(* if (aControl.Height >= aControl.Constraints.MinHeight + 5) then
begin*)
vcmCatPath(aPath, cHeight, l_Path);
l_ControlHeight := Max(aControl.Constraints.MinHeight, aControl.Height);
vcmSaveIntParamS(l_Path, l_ControlHeight);
(* end;//..Height.. *)
end;
procedure vcmSaveOwnedControl(const aPath: array of TvcmPathPair;
const aControl: TControl;
const aForm: TvcmContainerForm);
var
l_Path : TvcmPathPairs;
l_Control: TControl;
begin
l_Control := vcmGetNonClientAlignedControl(aControl, aForm);
if Assigned(l_Control) then
begin
vcmCatPath(aPath, [vcmPathPair(l_Control.Name)], l_Path);
vcmSaveExtent(l_Path, l_Control);
end;//Assigned(l_Control) then
end;
procedure vcmSaveLayout(const aPath : array of TvcmPathPair;
aForm : TCustomForm);
{-}
var
l_Path : TvcmPathPairs;
begin
vcmCatPath(aPath, cMaximized, l_Path);
vcmSaveBoolParamS(l_Path, aForm.WindowState = wsMaximized);
vcmCatPath(aPath, cTop, l_Path);
vcmSaveIntParamS(l_Path, aForm.Top);
vcmCatPath(aPath, cLeft, l_Path);
vcmSaveIntParamS(l_Path, aForm.Left);
vcmSaveExtent(aPath, aForm);
end;
procedure vcmSaveFormControls(const aPath: array of TvcmPathPair;
const aForm: TvcmContainerForm);
{-}
var
l_Index : Integer;
l_Zone : TvcmZonesCollectionItem;
begin
with aForm.Zones do
for l_Index := 0 to Pred(Count) do
begin
l_Zone := TvcmZonesCollectionItem(Items[l_Index]);
if (l_Zone.Control Is TControl) then
vcmSaveOwnedControl(aPath, TControl(l_Zone.Control), aForm);
end;//for l_Index
end;
procedure vcmSaveForm(aForm: TCustomForm);
{-}
var
l_NeedSave : Boolean;
l_Path : TvcmPathPairs;
l_PPath : TvcmPathPairs;
l_Parent : TControl;
l_Saved : Boolean;
l_Floating : Boolean;
l_PForm : TCustomForm;
l_IsMainContainer: Boolean;
begin
if (aForm Is TvcmEntityForm) then
if TvcmEntityForm(aForm).NeedSaveInSettings then
begin
vcmGetFormPath(aForm, l_Path);
l_IsMainContainer := Supports(aForm, IafwMainFormContainer);
if ((aForm Is TvcmMainForm) AND (aForm.Parent = nil)) OR l_IsMainContainer then
begin
l_NeedSave := true;
end
else
begin
l_NeedSave := (TvcmEntityForm(aForm).ZoneType in vcm_NotContainedForm);
if not l_NeedSave then
begin
// - это встроенная форма - надо записать позицию ее дока
l_PForm := nil;
l_Saved := false;
l_Floating := false;
l_Parent := aForm.Parent;
while (l_Parent <> nil) do
begin
if (l_Parent.Name <> '') then
begin
if not l_Saved then
begin
l_Saved := true;
vcmCatPath(l_Path, cZone, l_PPath);
vcmSaveStrParamS(l_PPath, vcmCStr(l_Parent.Name));
end;//not l_Saved
end;//l_Parent.Name <> ''
if (l_Parent.Parent = nil) then
begin
if (not l_Saved AND not (l_Parent Is TvcmMainForm)) then
begin
l_Floating := l_Floating OR true;
if (l_PForm = nil) AND (l_Parent Is TCustomForm) then
l_PForm := TCustomForm(l_Parent);
end;//(not l_Saved AND not (l_Parent Is TvcmMainForm))
if (l_Parent.Owner Is TControl) then
l_Parent := TControl(l_Parent.Owner)
else
l_Parent := nil;
end//l_Parent.Parent = nil
else
l_Parent := l_Parent.Parent;
end;//while (l_Parent <> nil)
vcmCatPath(l_Path, cToolbarFloat, l_PPath);
vcmSaveBoolParamS(l_PPath, l_Floating);
if (aForm is TvcmEntityForm) then
begin
{ Идентификатор плавающей формы }
if (TvcmEntityForm(aForm).FloatID > 0) then
begin
vcmCatPath(l_Path, cFloatWindowID, l_PPath);
vcmSaveIntParam(l_PPath, TvcmEntityForm(aForm).FloatID);
end;
{ Состояние плавающей формы }
vcmCatPath(l_Path, cFloatWindowState, l_PPath);
vcmSaveIntParam(l_PPath, TvcmEntityForm(aForm).FloatWindowState);
vcmCatPath(l_Path, cFloatingVisible, l_PPath);
vcmSaveBoolParam(l_PPath, TvcmEntityForm(aForm).FloatingVisible);
{ Расположение плавающей формы, в которой находилась форма }
vcmSaveFloatBounds(l_Path, TvcmEntityForm(aForm).FloatWindowBounds);
end;
if l_Floating then
begin
if (l_PForm = nil) then
l_PForm := aForm;
vcmSaveLayout(l_Path, l_PForm);
end;//l_Floating
end;//not l_NeedSave
end;//aForm Is TvcmMainForm
if l_NeedSave then
vcmSaveLayout(l_Path, aForm);
if (aForm Is TvcmContainerForm) then
vcmSaveFormControls(l_Path, TvcmContainerForm(aForm));
end;//aForm Is TvcmEntityForm
end;
function vcmLoadFormParams(anOwner : TObject;
aForm : TCustomForm;
out theParams : TvcmFormParams): Boolean;
{-}
var
l_OPath : TvcmPathPairs;
l_FPath : TvcmPathPairs;
l_LPath : TvcmPathPairs;
begin
if (anOwner Is TCustomForm) then
vcmGetFormPath(TForm(anOwner), l_OPath);
vcmGetFormPath(aForm, l_FPath, false);
vcmCatPath(l_OPath, l_FPath, l_LPath);
l_FPath := l_LPath;
vcmCatPath(l_FPath, cZone, l_LPath);
Result := vcmLoadStrParam(l_LPath, theParams.rParent);
if Result then
begin
vcmCatPath(l_FPath, cToolbarFloat, l_LPath);
if not vcmLoadBoolParam(l_LPath, theParams.rFloating) then
theParams.rFloating := False;
vcmCatPath(l_FPath, cFloatingVisible, l_LPath);
if not vcmLoadBoolParam(l_LPath, theParams.rFloatingVisible) then
theParams.rFloatingVisible := true;
{ Идентификатор плавающего навигатора }
vcmCatPath(l_FPath, cFloatWindowID, l_LPath);
vcmLoadIntParam(l_LPath, theParams.rFloatID);
{ Состояние плавающего окна }
vcmCatPath(l_FPath, cFloatWindowState, l_LPath);
vcmLoadIntParam(l_LPath, theParams.rFloatWindowState);
{ Положение плавающего окна }
vcmLoadFloatBounds(l_FPath, theParams.rFloatWindowBounds);
end;//Result
end;
procedure vcmCleanToolbar(const aUTName : AnsiString;
const aTBName : AnsiString);
begin
vcmSaveBoolParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cDefaultOperations
],
true);
vcmSaveBoolParamS([
vcmPathPair(aUtName),
cToolbars,
vcmPathPair(aTbName),
cDefaultPositions
],
true);
end;
procedure vcmCleanShortcut(const aOpContName : AnsiString;
const aOpName : AnsiString);
begin
vcmSaveBoolParamS([
cShortcuts,
vcmPathPair(aOpContName),
vcmPathPair(aOpName),
cDefaultShortcut
],
true);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.