text stringlengths 14 6.51M |
|---|
unit CpList0;
interface
uses classes,
util1, listG, stmObj;
type
TCPlist= class
CouplingON: boolean; // true signifie que les objets envoient des messages aux objets couplés
Blocked: boolean; // true signifie que la liste ne fonctionne pas du tout. Elle devra être reconstruite.
listCp: Tlist; // liste des coeff
listL: Tlist; // liste des listes d'objets
listLast: Tlist; // liste des derniers objets modifiés pour chaque coeff
constructor create;
destructor destroy;override;
procedure clear;
procedure add(n:integer; uo:typeUO);
procedure remove(n:integer; uo:typeUO);
procedure setUO(oldN,NewN:integer; uo:typeUO);
procedure SetUOrebuild(NewN: integer; uo: typeUO);
procedure sendMessage(n:integer;UOmsg: integer; source: typeUO);
function FindLimits(n:integer;UOmsg: integer; var Amin, Amax: float): boolean;
procedure suspend;
procedure UpdateCp(UOmsg: integer) ;
end;
implementation
{ TCPlist }
constructor TCPlist.create;
begin
CouplingON:= true;
listCp:= Tlist.create;
listL:= Tlist.create;
listLast:= Tlist.create;
end;
destructor TCPlist.destroy;
begin
clear;
listCp.Free;
listL.Free;
ListLast.Free;
end;
procedure TCPlist.clear;
var
i:integer;
begin
with listL do
for i:=0 to Count-1 do
TUOlist(items[i]).Free;
listCP.Clear;
listL.clear;
listLast.clear;
end;
procedure TCPlist.add(n: integer; uo: typeUO);
var
k:integer;
uoList:TUOlist;
begin
k:= listCP.indexOf(pointer(n));
if k<0 then
begin
listCP.Add(pointer(n));
uoList:= TUOlist.create;
k:=listL.Add(uoList);
listLast.Add(nil);
end;
uoList:=listL[k];
uoList.add(uo);
end;
procedure TCPlist.remove(n: integer; uo: typeUO);
var
k:integer;
uoList:TUOlist;
begin
k:= listCP.indexOf(pointer(n));
if k>=0 then
begin
uoList:=listL[k];
uoList.Remove(uo);
if uolist.count=0 then
begin
uoList.free;
listCP.delete(k);
listL.Delete(k);
listLast.Delete(k);
end;
end;
end;
procedure TCPlist.sendMessage(n, UOmsg: integer; source: typeUO);
var
i,k:integer;
uoList:TUOlist;
begin
k:= listCP.indexOf(pointer(n));
if k>=0 then
if CouplingON then
begin
with TUOlist(listL[k]) do
begin
for i:=0 to count-1 do
items[i].processmessage(UOmsg,source,nil);
end;
end
else listLast[k]:=source;
end;
function TCPlist.FindLimits(n, UOmsg: integer; var Amin, Amax: float):boolean;
var
i,k:integer;
uoList:TUOlist;
begin
result:=false;
if not CouplingON then exit;
k:= listCP.indexOf(pointer(n));
if k>=0 then
with TUOlist(listL[k]) do
begin
for i:=0 to count-1 do
if items[i].FindLimits(UOmsg,Amin,Amax) then
begin
result:=true;
exit;
end;
end;
end;
procedure TCPlist.setUO(oldN,NewN: integer; uo: typeUO);
begin
if Blocked or (oldN=newN) then exit;
if oldN<>0 then remove(oldN,uo);
if NewN<>0 then add(newN,uo);
end;
procedure TCPlist.SetUOrebuild(NewN: integer; uo: typeUO);
begin
if NewN<>0 then add(newN,uo);
end;
procedure TCPlist.suspend;
var
i: integer;
begin
CouplingON:= false;
for i:=0 to listLast.Count-1 do listLast[i]:=nil; // Utile ?
end;
procedure TCPlist.UpdateCp(UOmsg: integer);
var
i: integer;
begin
for i:=0 to ListCp.Count-1 do
if listLast[i]<>nil then
begin
sendMessage(intG(listCp[i]), UOmsg, typeUO(listLast[i]));
listLast[i]:=nil;
end;
CouplingON:=true;
end;
end.
|
unit ModPowOpTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
uIntX;
type
{ TTestModPowOp }
TTestModPowOp = class(TTestCase)
published
procedure ModPowIntX();
end;
implementation
{ TTestModPowOp }
procedure TTestModPowOp.ModPowIntX;
var
res: TIntX;
begin
res := TIntX.ModPow(11, 13, 19);
AssertTrue(res = 11);
res := TIntX.ModPow(123, 4567, 789);
AssertTrue(res = 687);
res := TIntX.ModPow(9876, 2457, 6457);
AssertTrue(res = 3238);
end;
initialization
RegisterTest(TTestModPowOp);
end.
|
{*******************************************************************************
Title: T2TiPDV
Description: Pesquisa por produto e importação para a venda.
The MIT License
Copyright: Copyright (C) 2012 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
alberteije@gmail.com
@author T2Ti.COM
@version 1.0
*******************************************************************************}
unit UImportaProduto;
{$mode objfpc}{$H+}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, StdCtrls, Buttons, ExtCtrls, DB, FMTBcd,
ZAbstractRODataset, ZAbstractDataset, ZDataset, ACBrBase, ACBrEnterTab, UBase, Tipos;
type
TCustomDBGridCracker = class(TCustomDBGrid);
{ TFImportaProduto }
TFImportaProduto = class(TFBase)
ACBrEnterTab1: TACBrEnterTab;
Image1: TImage;
botaoConfirma: TBitBtn;
botaoCancela: TBitBtn;
GridPrincipal: TDBGrid;
Image2: TImage;
Panel1: TPanel;
Label1: TLabel;
EditLocaliza: TEdit;
SpeedButton1: TSpeedButton;
DSProduto: TDataSource;
Label2: TLabel;
procedure botaoCancelaClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
procedure Localiza;
procedure Confirma;
procedure SpeedButton1Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure GridPrincipalKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
procedure botaoConfirmaClick(Sender: TObject);
procedure EditLocalizaKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
procedure EditLocalizaKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
QuemChamou: string;
end;
var
FImportaProduto: TFImportaProduto;
QProduto: TZQuery;
implementation
uses UDataModule, ProdutoController, UCaixa;
{$R *.lfm}
{$REGION 'Infra'}
procedure TFImportaProduto.FormActivate(Sender: TObject);
begin
Color := StringToColor(Sessao.Configuracao.CorJanelasInternas);
end;
procedure TFImportaProduto.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
FCaixa.editCodigo.SetFocus;
CloseAction := caFree;
end;
procedure TFImportaProduto.EditLocalizaKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
begin
if (Key = VK_RETURN) or (Key = VK_UP) or (Key = VK_DOWN) then
GridPrincipal.SetFocus;
end;
procedure TFImportaProduto.FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
begin
if Key = VK_F2 then
Localiza;
if Key = VK_F12 then
Confirma;
if key = VK_ESCAPE then
botaoCancela.Click;
end;
procedure TFImportaProduto.GridPrincipalKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
begin
if Key = VK_RETURN then
EditLocaliza.SetFocus;
end;
procedure TFImportaProduto.botaoCancelaClick(Sender: TObject);
begin
Close;
end;
{$ENDREGION 'Infra'}
{$REGION 'Pesquisa e Confirmação'}
procedure TFImportaProduto.SpeedButton1Click(Sender: TObject);
begin
Localiza;
end;
procedure TFImportaProduto.botaoConfirmaClick(Sender: TObject);
begin
if GridPrincipal.DataSource.DataSet.Active then
begin
if GridPrincipal.DataSource.DataSet.RecordCount > 0 then
Confirma
else
begin
Application.MessageBox('Não produto para importação!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
EditLocaliza.SetFocus;
end;
end
else
begin
Application.MessageBox('Não produto para importação!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
EditLocaliza.SetFocus;
end;
end;
procedure TFImportaProduto.Confirma;
begin
if QProduto.FieldByName('VALOR_VENDA').AsFloat > 0 then
begin
if (Sessao.StatusCaixa = scVendaEmAndamento) then
begin
FCaixa.editCodigo.Text := QProduto.FieldByName('ID').AsString;
end;
Close;
end
else
Application.MessageBox('Produto não pode ser vendido com valor zerado ou negativo.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
end;
procedure TFImportaProduto.EditLocalizaKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
begin
if Length(trim(EditLocaliza.Text)) > 1 then
Localiza;
end;
procedure TFImportaProduto.localiza;
var
ProcurePor, Filtro: string;
begin
ProcurePor := '%' + EditLocaliza.Text + '%';
Filtro := 'NOME LIKE ' + QuotedStr(ProcurePor);
QProduto := TProdutoController.Consulta(Filtro, '-1');
QProduto.Active := True;
DSproduto.DataSet := QProduto;
end;
{$ENDREGION 'Pesquisa e Confirmação'}
end.
|
program InstalledApps;
{$APPTYPE CONSOLE}
uses
Windows,
Classes,
SysUtils,
Registry;
const
UNINST_PATH = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall';
var
Registry: TRegistry;
Keys: TStrings;
Key: string;
AppName: string;
AppLookingFor: string;
IsAppInstalled: Boolean;
begin
Write('application''s name you''re looking for: ');
Readln(AppLookingFor);
Registry := TRegistry.Create;
Registry.RootKey := HKEY_LOCAL_MACHINE;
if Registry.OpenKeyReadOnly(UNINST_PATH) then
begin
Keys := TStringList.Create;
try
Registry.GetKeyNames(Keys);
Registry.CloseKey();
for Key in Keys do
begin
if Registry.OpenKeyReadOnly(Format('%s\%s', [UNINST_PATH, Key])) then
begin
try
AppName := Registry.ReadString('DisplayName');
IsAppInstalled := Pos(AnsiUpperCase(AppLookingFor), AnsiUpperCase(AppName)) > 0;
if IsAppInstalled then Break;
finally
Registry.CloseKey();
end;
end;
end;
finally
Keys.Free();
end;
if IsAppInstalled then
Writeln(AppLookingFor + ' is installed!')
else
Writeln(AppLookingFor + ' is unavailable or not installed!');
ReadLn; //don't close the window, wait for [Enter]
end;
end. |
unit tvl_ubehavebinder;
{$mode objfpc}{$H+}
interface
uses
SysUtils, tvl_ibindings, tvl_ucontrolbinder, tvl_ubehavebinders,
Controls, ComCtrls, fgl, SynEdit;
type
{ TRBBehavioralBinder }
TRBBehavioralBinder = class(TInterfacedObject, IRBBehavioralBinder)
private type
TBehaveBinderItems = specialize TFPGObjectList<TControlBinder>;
private
fBinders: TBehaveBinderItems;
fContainer: TWinControl;
protected
// IRBBehavioralBinder
procedure Bind(AContainer: TWinControl);
procedure Unbind;
protected
procedure ActualizeItems;
procedure MakeBinders(AContainer: TWinControl);
procedure AddBinderForControl(AControl: TWinControl);
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
implementation
{ TRBBehavioralBinder }
procedure TRBBehavioralBinder.Bind(AContainer: TWinControl);
begin
fContainer := AContainer;
ActualizeItems;
end;
procedure TRBBehavioralBinder.Unbind;
begin
fBinders.Clear;
end;
procedure TRBBehavioralBinder.ActualizeItems;
begin
fBinders.Clear;
MakeBinders(fContainer);
end;
procedure TRBBehavioralBinder.MakeBinders(AContainer: TWinControl);
var
i: integer;
begin
for i := 0 to AContainer.ControlCount - 1 do
begin
if not (AContainer.Controls[i] is TWinControl) then
Continue;
MakeBinders(AContainer.Controls[i] as TWinControl);
AddBinderForControl(AContainer.Controls[i] as TWinControl);
end;
end;
procedure TRBBehavioralBinder.AddBinderForControl(AControl: TWinControl);
var
mBinder: TControlBinder;
begin
if AControl is TCustomTabControl then begin
mBinder := TPageControlBehaveBinder.Create;
fBinders.Add(mBinder);
mBinder.Bind(AControl);
end
else
if AControl is TCustomSynEdit then begin
mBinder := TSynEditBinder.Create;
fBinders.Add(mBinder);
mBinder.Bind(AControl);
end;
end;
procedure TRBBehavioralBinder.AfterConstruction;
begin
inherited AfterConstruction;
fBinders := TBehaveBinderItems.Create;
end;
procedure TRBBehavioralBinder.BeforeDestruction;
begin
FreeAndNil(fBinders);
inherited BeforeDestruction;
end;
end.
|
unit CatMatch;
{
Catarinka - Regular Expression and various other useful matching functions
Copyright (c) 2003-2020 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
Uses the RegExpr library by Andrey V. Sorokin.
MatchWildcard function by Arsne von Wyss
CompareVersionNumber() function by Martin Prikryl (@martinprikryl) with small
changes and suggestions by Tithen-Firion
CompareVersionString() function is my extension to Martin's function
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
System.Classes, System.SysUtils, RegExpr;
{$ELSE}
Classes, SysUtils, RegExpr;
{$ENDIF}
type
TCatRegExpr = TRegExpr;
const
VERSTG_RELEASE = 5;
VERSTG_RELEASECANDIDATE = 4;
VERSTG_BETA = 3;
VERSTG_ALPHA = 2;
VERSTG_PREALPHA = 1;
type
TVersionParts = record
originalstring: string;
version: string;
ext:string;
extnum: string;
hasletter: boolean;
stage:integer;
end;
function RegExpFind(const s, re: string): string;
function RegExpReplace(const s, re, sreplacement: string): string; overload;
function RegExpReplace(const s, re: string; refunc: TRegExprReplaceFunction): string; overload;
function CatCaseWildOf(const s: string; labels: array of string;
const casesensitive: Boolean = true): integer;
function CatCaseWildXOf(const s: string; labels: array of string;
const casesensitive: Boolean = true): integer;
function CatMatchSignature(const sigpattern, s: string): boolean;
function CompareVersionNumber(const version1, version2: string;
const Silent:boolean=true): Integer;
function CompareVersionString(const version1, version2: string;
const Silent:boolean=true): Integer;
function CrackVersionString(const ver: string): TVersionParts;
function IsWildCardString(const s:string):boolean;
function IsValidEmail(email: string): boolean;
function ExtractVersionFromString(s:string):string;
function MatchStrInSepStr(const s,tags:string;separator:string=','):boolean;
function MatchVersion(curver, vercheck:string):boolean;
function MatchVersionRange(curver, vercheck:string):boolean;
function MatchVersionEx(curver, vercheck:string):boolean;
function MatchWildcard(s, Mask: string; IgnoreCase: Boolean = false): Boolean;
function MatchWildcardX(s, Mask: string; IgnoreCase: Boolean = false): Boolean;
implementation
uses CatStrings, CatStringLoop;
{
Case Statement with wildcard matching
Usage examples:
case CatCaseWildOf(inputstring, ['1:do?', '2:c*', '3:b??d']) of
1: result := ...
2: result := ...
3: result := ...
else
result := 'nomatch';
end;
case CatCaseWildOf(a, ['1:http://*', '2:https://*']) of
1: result := 'http URL';
2: result := 'https URL';
else
result := 'nomatch';
end;
Check CatStrings.pas for non-wildcard version of this function
}
function CatCaseWildOf(const s: string; labels: array of string;
const casesensitive: Boolean = true): integer;
var
i: integer;
begin
result := -1; // label not found
for i := low(labels) to high(labels) do
begin
if MatchWildcard(s, after(labels[i],':'), not casesensitive) = true then
result := StrToIntDef(before(labels[i],':'), -1);
if result <> -1 then
break;
end;
end;
function CatCaseWildXOf(const s: string; labels: array of string;
const casesensitive: Boolean = true): integer;
var
i: integer;
begin
result := -1; // label not found
for i := low(labels) to high(labels) do
begin
if MatchWildcardX(s, after(labels[i],':'), not casesensitive) = true then
result := StrToIntDef(before(labels[i],':'), -1);
if result <> -1 then
break;
end;
end;
function RegExpReplace(const s, re, sreplacement: string): string;
var
r: TRegExpr;
begin
r := TRegExpr.Create;
try
r.Expression := re;
result := r.Replace(s, sreplacement, true);
finally
r.Free;
end;
end;
function RegExpReplace(const s, re: string; refunc: TRegExprReplaceFunction): string;
var
r: TRegExpr;
begin
r := TRegExpr.Create;
try
r.Expression := re;
result := r.ReplaceEx(s, refunc);
finally
r.Free;
end;
end;
function RegExpFind(const s, re: string): string;
var
r: TRegExpr;
begin
result := emptystr;
r := TRegExpr.Create;
try
r.Expression := re;
if r.Exec(s) then
repeat
result := result + r.Match[0] + ', ';
until not r.ExecNext;
finally
r.Free;
end;
end;
// Allows to match a string using different methods:
// [somestring] -- case sensitive contains
// wild:[somestring] -- case sensitive wild match
// regexp:[expression] -- regular expression
// icase:[somestring] -- case insensitive contains
// icase:wild:[somestring] -- case insensitive wild match (* and ?)
function CatMatchSignature(const sigpattern, s: string): boolean;
const
cIgnoreCase = 'icase:';
cReEx = 'regexp:';
cWild = 'wild:';
var
sig, content, pat: string;
begin
sig := sigpattern;
content := s;
if BeginsWith(sig,cIgnoreCase) then
begin
sig := after(sig, cIgnoreCase);
sig := lowercase(sig);
content := lowercase(content);
end;
if BeginsWith(sig,cReEx) then
begin
pat := after(sig, cReEx);
result := (RegExpFind(content, pat) <> emptystr);
end
else
if BeginsWith(sig,cWild) then
begin
pat := after(sig, cWild);
result := MatchWildcard(content, pat);
end
else
begin
result := (pos(sig, content) <> 0);
end;
end;
// Thanks ffert2907
function IsValidEmail(email: string): boolean;
const
charslist = ['_', '-', '.', '0'..'9', 'A'..'Z', 'a'..'z'];
var
Arobasc, lastpoint : boolean;
i, n : integer;
c : char;
begin
n := Length(email);
i := 1;
Arobasc := false;
lastpoint := false;
result := true;
while (i <= n) do begin
c := email[i];
if c = '@' then
begin
if Arobasc then // Only 1 Arobasc
begin
result := false;
exit;
end;
Arobasc := true;
end
else if (c = '.') and Arobasc then // at least 1 . after arobasc
begin
lastpoint := true;
end
else if not(c in charslist) then // valid chars
begin
result := false;
exit;
end;
inc(i);
end;
if not(lastpoint) or (email[n] = '.')then // not finish by . and have a . after arobasc
result := false;
end;
function ExtractVersionFromString(s:string):string;
begin
result := RegExpFind(s, '\d+(\.\d+)+');
if pos(',', result) <> 0 then
result := before(result, ',');
end;
function NextIntFromVersion(var S: string;const Silent:boolean=true): Integer;
var
P: integer;
begin
P := Pos('.', S);
if P > 0 then
begin
if silent = true then
result := StrToIntDef(Copy(S, 1, P - 1), 0)
else
result := StrToInt(Copy(S, 1, P - 1));
Delete(S, 1, P);
end
else
if S <> emptystr then
begin
if silent = true then
result := StrToIntDef(S, 0) else
result := StrToInt(S);
S := emptystr;
end
else
begin
result := 0;
end;
end;
{
Compares version numbers
Returns 0, if the versions are equal.
Returns -1, if the V1 is older than the V2.
Returns 1, if the V1 is newer than the V2.
1.12 is considered newer than 1.1.
1.1 is considered the same as 1.1.0.
If silent is false, throws an exception, when a version is syntactically invalid (only digits and dots are allowed).
}
// Thanks Martin Prikryl (@martinprikryl) and Tithen-Firion
function CompareVersionNumber(const version1, version2: string;
const Silent:boolean=true): Integer;
var
v1, v2:string;
N1, N2: Integer;
begin
Result := 0;
v1 := version1;
v2 := version2;
while (Result = 0) and ((V1 <> EmptyStr) or (V2 <> EmptyStr)) do
begin
N1 := NextIntFromVersion(V1);
N2 := NextIntFromVersion(V2);
if N1 < N2 then Result := -1
else
if N1 > N2 then Result := 1;
end;
end;
function GetVersionStage(const ver:string):integer;
var lv:string;
begin
lv := lowercase(ver);
result := VERSTG_RELEASE;
if pos('rc', lv) <> 0 then
result := VERSTG_RELEASECANDIDATE;
if pos('pre', lv) <> 0 then // pre-release
result := VERSTG_RELEASECANDIDATE;
if pos('beta', lv) <> 0 then
result := VERSTG_BETA;
if pos('preview', lv) <> 0 then
result := VERSTG_BETA;
if pos('alpha', lv) <> 0 then
result := VERSTG_ALPHA;
// pre-alpha
if (pos('pre', lv) <> 0) and (pos('alpha', lv) <> 0) then
result := VERSTG_PREALPHA;
end;
function CrackVersionString(const ver: string): TVersionParts;
begin
result.ext := emptystr;
result.extnum := emptystr;
result.originalstring := ver;
result.version := ver;
result.hasletter := false;
result.stage := VERSTG_RELEASE;
if IsAlphaNumeric(ver) then begin
result.version := ExtractVersionFromString(ver);
result.ext := After(ver, result.version);
result.extnum := ExtractNumbers(result.ext);
result.hasletter := (length(result.ext) = 1) and (result.ext[1] in ['a'..'z','A'..'Z']);
result.stage := GetVersionStage(ver);
end;
end;
// This function I wrote extends the CompareVersion function by martinprikryl (above)
// to compare versions that contain alphanumeric extensions like:
// v1.0 versus V1.1
// 1.0 RC1 versus 1.0 RC2
// 1.0a versus 1.0B or 1.0b
// 1.5.0-rc1 versus 1.5.0-beta1 and similar
function CompareVersionString(const version1, version2: string;
const Silent:boolean=true): Integer;
var
v1,v2: TVersionParts;
function CompareVersionAlphaExtension(curver, vercheck:string):integer;
begin
result := 0;
if curver < vercheck then
result := -1
else if curver > vercheck then
result := 1;
end;
begin
v1 := CrackVersionString(version1);
v2 := CrackVersionString(version2);
result := CompareVersionNumber(v1.version, v2.version, silent);
// If versions are identical and extended version information is available
// conclude by comparing numbers from extension part
if result = 0 then begin
// Compares case like 1.5.0-beta.10 versus 1.5.0-beta.11
if (v1.ext <> emptystr) and (v2.ext <> emptystr) then
result := CompareVersionNumber(v1.extnum, v2.extnum, silent);
// Assign letter if required and compare cases like
//1.0 versus 1.0a
//1.0.1a versus 1.0.1b
if (v1.hasletter = true) and (v2.ext = emptystr) then
result := 1;
if (v2.hasletter = true) and (v1.ext = emptystr) then
result := -1;
if (length(v1.ext) =1) and (length(v2.ext) = 1) then
result := CompareVersionAlphaExtension(lowercase(v1.ext), lowercase(v2.ext));
// if the development stage is different, the result must be the stage comparison
if (v1.stage <> v2.stage) then
result := CompareVersionNumber(IntToStr(v1.stage), IntToStr(v2.stage));
end;
end;
// Matches a string against a separated string (comma-based if separator is ommited)
function MatchStrInSepStr(const s,tags:string;separator:string=','):boolean;
var Tag: TSepStringLoop;
begin
result := false;
if tags <> emptystr then
begin
Tag := TSepStringLoop.Create(tags, separator);
while Tag.Found do
begin
if Tag.Current = s then
result := true;
end;
Tag.Free;
end;
end;
function IsWildCardString(const s:string):boolean;
begin
result := ContainsAnyOfChars(s, ['*','?']);
end;
// expects expression like:
// <3.4.0
// <=3.4.0
// when using just the equal sign, can be followed by a wildcard, ex:
// =* (matches any version)
// =3.*
// =3.1.??
function MatchVersion(curver, vercheck:string):boolean;
var
outver: string;
compres: integer;
begin
result := false;
compres := -1; // avoid compiler message
outver := ExtractVersionFromString(vercheck);
if beginswith(vercheck, '=') = false then
compres := CompareVersionNumber(curver, outver);
if beginswith(vercheck, '>=') then begin
//if curver >= outver then
if (compres = 1) or (compres = 0) then
result := true;
end else
if beginswith(vercheck, '<=') then begin
//if curver <= outver then
if (compres = -1) or (compres = 0) then
result := true;
end else
if beginswith(vercheck, '<') then begin
//if curver < outver then
if (compres = -1) then
result := true;
end else
if beginswith(vercheck, '>') then begin
//if curver > outver then
if (compres = 1) then
result := true;
end else
if beginswith(vercheck, '=') then begin
outver := after(vercheck, '=');
if IsWildCardString(outver) = false then begin
compres := CompareVersionNumber(curver, outver);
if (compres = 0) then
result := true;
end else begin
if matchwildcard(curver, outver) = true then
result := true;
end;
end;
end;
// expects multiple version checks separated by spaces like:
// >=1.4.2 <1.6.2
// will return true if all are matched, false otherwise
function MatchVersionRange(curver, vercheck:string):boolean;
var
s: TSepStringLoop;
begin
result := true;
s := TSepStringLoop.Create(vercheck,' ');
while s.Found do begin
if MatchVersion(curver,s.Current) = false then
result := false;
end;
s.Free;
end;
// expects version check list separated by commas like:
// <1.12.2,>=1.12.3 <2.2.2,>=2.2.3 <3.0.0
// must match at least one of the checks to return true
// wildcards can be used when using just equal sign, ex:
// usage examples:
// MatchVersionEx('2.2.3','<1.12.2,>=1.12.3 <2.2.2,>=2.2.3 <3.0.0') -> true
// MatchVersionEx('3.0.1','<1.12.2,>=1.12.3 <2.2.2,>=2.2.3 <3.0.0') -> false
// MatchVersionEx('2.1.11','=2.1.??,=3.*') -> true
function MatchVersionEx(curver, vercheck:string):boolean;
var
s: TSepStringLoop;
begin
result := false;
s := TSepStringLoop.Create(vercheck,',');
while s.Found do begin
if MatchVersionRange(curver,s.Current) = true then begin
result := true;
s.Stop;
end;
end;
s.Free;
end;
function MatchWildcard_Pos(const substr, s: string; Start: integer): integer;
var
i, J, len: integer;
begin
len := length(substr);
if len = 0 then
begin
result := 1;
Exit;
end;
for i := Start to Succ(length(s) - len) do
begin
J := 1;
while J <= len do
begin
if not((substr[J] = '?') or (substr[J] = s[Pred(i + J)])) then
break;
inc(J);
end;
if J > len then
begin
result := i;
Exit;
end;
end;
result := 0;
end;
{
This function takes two strings and compares them. The first string
can be anything, but should not contain pattern characters (* or ?).
The pattern string can have as many of these pattern characters as you want.
For example: MatchStrings('Pascal','*as*') would return True.
Contributed by Arsne von Wyss (1999)
}
function MatchWildcard(s, Mask: string; IgnoreCase: Boolean = false): Boolean;
const
WildSize = 0; { minimal number of characters representing a "*" }
var
Min, Max, At, MaskSTart, MaskEnd: integer;
T: string;
begin
if IgnoreCase then
begin
s := uppercase(s);
mask := uppercase(mask);
end;
s := s + #0;
Mask := Mask + #0;
Min := 1;
Max := 1;
MaskEnd := 0;
while length(Mask) >= MaskEnd do
begin
MaskSTart := MaskEnd + 1;
repeat
inc(MaskEnd);
until (MaskEnd > length(Mask)) or (Mask[MaskEnd] = '*');
T := Copy(Mask, MaskSTart, MaskEnd - MaskSTart);
At := MatchWildcard_Pos(T, s, Min);
if (At = 0) or (At > Max) then
begin
result := false;
Exit;
end;
Min := At + length(T) + WildSize;
Max := length(s);
end;
result := true;
end;
function MatchWildcardX_Pos(const substr, s: string; Start: integer): integer;
var
i, J, len: integer;
begin
len := length(substr);
if len = 0 then
begin
result := 1;
Exit;
end;
for i := Start to Succ(length(s) - len) do
begin
J := 1;
while J <= len do
begin
if (substr[J] = '#') and (IsInteger(s[Pred(i + J)]) <> true) then
break;
if (substr[J] = '¿') and (IsAlpha(s[Pred(i + J)]) <> true) then
break;
if not(ContainsAnyOfChars(substr[J], ['?','#','¿']) or (substr[J] = s[Pred(i + J)])) then
break;
inc(J);
end;
if J > len then
begin
result := i;
Exit;
end;
end;
result := 0;
end;
// Extended version of MatchWildcard() function that allows the following
// additional chars to be used as part of the mask:
// # (hash) to match a number
// ¿ (inverted interrogation) to match a letter (A..Z, a..z)
// by Felipe Daragon
function MatchWildcardX(s, Mask: string; IgnoreCase: Boolean = false): Boolean;
const
WildSize = 0; { minimal number of characters representing a "*" }
var
Min, Max, At, MaskSTart, MaskEnd: integer;
T: string;
begin
if IgnoreCase then
begin
s := uppercase(s);
mask := uppercase(mask);
end;
s := s + #0;
Mask := Mask + #0;
Min := 1;
Max := 1;
MaskEnd := 0;
while length(Mask) >= MaskEnd do
begin
MaskSTart := MaskEnd + 1;
repeat
inc(MaskEnd);
until (MaskEnd > length(Mask)) or (Mask[MaskEnd] = '*');
T := Copy(Mask, MaskSTart, MaskEnd - MaskSTart);
At := MatchWildcardX_Pos(T, s, Min);
if (At = 0) or (At > Max) then
begin
result := false;
Exit;
end;
Min := At + length(T) + WildSize;
Max := length(s);
end;
result := true;
end;
// ------------------------------------------------------------------------//
end.
|
// Printer Font Metrics
unit fi_pfm;
interface
implementation
uses
fi_common,
fi_info_reader,
fi_utils,
classes,
strutils,
streamex,
sysutils;
const
PFM_VERSION = 256;
MAX_COPYRIGHT_LEN = 60;
WEIGHT_POS = 83;
FACE_OFFSET_POS = 105;
DRIVER_INFO_OFFSET_POS = 139;
type
TPFMHeader = packed record
version: Word;
size: LongWord;
end;
procedure ReadPFMInfo(stream: TStream; var info: TFontInfo);
var
header: TPFMHeader;
copyright: String;
p: SizeInt;
begin
stream.ReadBuffer(header, SizeOf(header));
{$IFDEF ENDIAN_BIG}
with header do
begin
version := SwapEndian(version);
size := SwapEndian(size);
end;
{$ENDIF}
if header.version <> PFM_VERSION then
raise EStreamError.Create('Not a PFM font');
if header.size <> stream.Size then
raise EStreamError.CreateFmt(
'Size in PFM header (%u) does not match the file size (%d)',
[header.size, stream.Size]);
SetLength(copyright, MAX_COPYRIGHT_LEN);
stream.ReadBuffer(copyright[1], MAX_COPYRIGHT_LEN);
info.copyright := TrimRight(copyright);
stream.Seek(WEIGHT_POS, soBeginning);
info.style := GetWeightName(stream.ReadWordLE);
stream.Seek(FACE_OFFSET_POS, soBeginning);
stream.Seek(stream.ReadDWordLE, soBeginning);
info.fullName := ReadCStr(stream);
// Strip style if font uses PS name as a Full Name.
p := RPos('-', info.fullName);
if p <> 0 then
info.family := Copy(info.fullName, 1, p - 1)
else
info.family := info.fullName;
stream.Seek(DRIVER_INFO_OFFSET_POS, soBeginning);
stream.Seek(stream.ReadDWordLE, soBeginning);
info.psName := ReadCStr(stream);
info.format := 'PFM';
end;
initialization
RegisterReader(@ReadPFMInfo, ['.pfm']);
end.
|
unit uEditProductUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBClient, StdCtrls, DBCtrls, Mask, RzEdit, RzDBEdit,
RzButton, RzLabel, ExtCtrls, RzPanel, Buttons,CommonLIB;
type
TfrmEditProductUnit = class(TForm)
pnAllClients: TRzPanel;
btnSave: TRzBitBtn;
btnCancel: TRzBitBtn;
DBCheckBox1: TDBCheckBox;
cdsProdUni: TClientDataSet;
dsProdUni: TDataSource;
edPrdCode: TRzEdit;
btnSearchWh: TSpeedButton;
edPrdName: TRzEdit;
RzLabel6: TRzLabel;
edUnitCode: TRzEdit;
spdSearchUnit: TSpeedButton;
edUnitName: TRzEdit;
RzLabel1: TRzLabel;
edPackingCode: TRzEdit;
spdSearchPacking: TSpeedButton;
edPackingName: TRzEdit;
RzLabel2: TRzLabel;
RzLabel3: TRzLabel;
edPackingRate: TRzEdit;
procedure btnCancelClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure spdSearchUnitClick(Sender: TObject);
procedure spdSearchPackingClick(Sender: TObject);
procedure edUnitCodeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edPackingCodeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FProductUnitCode: integer;
FProductCode: integer;
FProductPackingCode: integer;
FPackingRate : integer;
FAppParameter: TDLLParameter;
procedure SetProductCode(const Value: integer);
procedure SetProductPackingCode(const Value: integer);
procedure SetProductUnitCode(const Value: integer);
procedure SetAppParameter(const Value: TDLLParameter);
{ Private declarations }
public
{ Public declarations }
property ProductCode:integer read FProductCode write SetProductCode;
property ProductUnitCode : integer read FProductUnitCode write SetProductUnitCode;
property ProductPackingCode : integer read FProductPackingCode write SetProductPackingCode;
property AppParameter : TDLLParameter read FAppParameter write SetAppParameter;
end;
var
frmEditProductUnit: TfrmEditProductUnit;
implementation
uses CommonUtils, CdeLIB, STDLIB, STK_LIB;
{$R *.dfm}
{ TfrmEditProductUnit }
procedure TfrmEditProductUnit.SetProductCode(const Value: integer);
begin
FProductCode := Value;
edPrdCode.Text := getMTTCDE('PRD',IntToStr(FProductCode));
edPrdName.Text := getMTTFValue('PRD','PRDNAT',IntToStr(FProductCode));
cdsProdUni.Data := GetDataSet('select * from ICMTTPRU where PRUPRD='+IntToStr(FProductCode)+' and PRUUNI='+IntToStr(FProductUnitCode)+' and PRUPAC='+IntToStr(FProductPackingCode));
end;
procedure TfrmEditProductUnit.SetProductPackingCode(const Value: integer);
begin
FProductPackingCode := Value;
edPackingCode.Text := getMTTCDE('PAC',IntToStr(FProductPackingCode));
edPackingName.Text := getMTTFValue('PAC','PACNAM',IntToStr(FProductPackingCode));
edPackingRate.Text := getMTTFValue('PAC','PACRAT',IntToStr(FProductPackingCode));
if Trim(edPackingRate.Text)='' then
FPackingRate := 0
else
FPackingRate := StrToInt(edPackingRate.Text);
end;
procedure TfrmEditProductUnit.SetProductUnitCode(const Value: integer);
begin
FProductUnitCode := Value;
edUnitCode.Text := getMTTCDE('UNI',IntToStr(FProductUnitCode));
edUnitName.Text := getMTTFValue('UNI','UNINAM',IntToStr(FProductUnitCode));
end;
procedure TfrmEditProductUnit.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmEditProductUnit.btnSaveClick(Sender: TObject);
var IsNew : boolean;
begin
if (FProductUnitCode=0) then
begin
Application.MessageBox(pchar('กรุณาระบุหน่วยสินค้าให้ถูกต้อง!!!'),pchar('Warning'),MB_OK or MB_ICONWARNING);
Exit;
end;
if (FProductCode=0) then
begin
Application.MessageBox(pchar('กรุณาระบุสินค้าให้ถูกต้อง!!!'),pchar('Warning'),MB_OK or MB_ICONWARNING);
Exit;
end;
if (FProductPackingCode=0) then
begin
Application.MessageBox(pchar('กรุณาขนาดบรรจุให้ถูกต้อง!!!'),pchar('Warning'),MB_OK or MB_ICONWARNING);
Exit;
end;
if (FPackingRate=0) then
begin
Application.MessageBox(pchar('Packing Rate ไม่ถูกต้อง!!!'),pchar('Warning'),MB_OK or MB_ICONWARNING);
Exit;
end;
{
if (FProductUnitCode=0) or (FProductCode=0) or (FProductPackingCode=0) or (FPackingRate=0) then
begin
Application.MessageBox(pchar('กรุณาตรวจสอบข้อมูลให้ถูกต้อง!!!'),pchar('Warning'),MB_OK or MB_ICONWARNING);
Exit;
end;
}
if cdsProdUni.State in [dsinsert] then
begin
IsNew := true;
//cdsProdUni.FieldByName('PRUCOD').AsInteger :=getCdeRun('SETTING','RUNNING','PRUCOD','CDENM1');
if cdsProdUni.FieldByName('PRUACT').IsNull then
cdsProdUni.FieldByName('PRUACT').AsString:='A';
setEntryUSRDT(cdsProdUni,FAppParameter.UserID);
setSystemCMP(cdsProdUni,FAppParameter.Company,FAppParameter.Branch,FAppParameter.Department,FAppParameter.Section);
end;
if not (cdsProdUni.State in [dsedit,dsinsert]) then cdsProdUni.Edit;
//begin
// IsNew := true;
if cdsProdUni.State in [dsinsert,dsedit] then
setModifyUSRDT(cdsProdUni,FAppParameter.UserID);
cdsProdUni.FieldByName('PRUUNI').AsInteger :=FProductUnitCode;
cdsProdUni.FieldByName('PRUPRD').AsInteger :=FProductCode;
cdsProdUni.FieldByName('PRUPAC').AsInteger :=FProductPackingCode;
cdsProdUni.FieldByName('PRUUNA').AsString :=edUnitName.Text;
cdsProdUni.FieldByName('PRUPNA').AsString :=edPackingName.Text;
cdsProdUni.FieldByName('PRURAT').AsInteger :=FPackingRate;
//end;
if cdsProdUni.State in [dsedit,dsinsert] then cdsProdUni.Post;
if cdsProdUni.ChangeCount>0 then
begin
UpdateDataset(cdsProdUni,'select * from ICMTTPRU where PRUPRD='+IntToStr(FProductCode)+' and PRUUNI='+IntToStr(FProductUnitCode)+' and PRUPAC='+IntToStr(FProductPackingCode)) ;
//if IsNew then
// setCdeRun('SETTING','RUNNING','LOCCOD','CDENM1');
end;
Close;
end;
procedure TfrmEditProductUnit.spdSearchUnitClick(Sender: TObject);
var
Parameter,_Parameter:TDLLParameter;
_SearchType,_Cols,_ColsWidth:TList;
_SQL:string;
begin
_SearchType:=TList.Create;
_SearchType.Add(TStringValue.Create('UNICOD','รหัส'));
_SearchType.Add(TStringValue.Create('UNINAM','ชื่อไทย'));
_Cols:=TList.Create;
_Cols.Add(TStringValue.Create('UNICOD','รหัส'));
_Cols.Add(TStringValue.Create('UNINAM','ชื่อไทย'));
_ColsWidth:=TList.Create;
_ColsWidth.Add(TStringValue.Create('1','80'));
_ColsWidth.Add(TStringValue.Create('2','150'));
Parameter.SearchTitle:='รายชื่อหน่วยสินค้า';
executilsdxInitialize;
_SQL :=' select UNICOD,UNINAM from ICMTTUNI where UNIACT=''A'' order by UNICOD ';
SelSearch(Application,swModal,Parameter,_Parameter,_SearchType,_Cols,_ColsWidth,'UNICOD',_SQL);
if Trim(_Parameter.SelectCode)<>'' then
begin
ProductUnitCode := StrToInt(_Parameter.SelectCode);
end;
end;
procedure TfrmEditProductUnit.spdSearchPackingClick(Sender: TObject);
var
Parameter,_Parameter:TDLLParameter;
_SearchType,_Cols,_ColsWidth:TList;
_SQL:string;
begin
_SearchType:=TList.Create;
_SearchType.Add(TStringValue.Create('PACCOD','รหัส'));
_SearchType.Add(TStringValue.Create('PACNAM','ชื่อขนาดบรรจุ'));
_SearchType.Add(TStringValue.Create('PACRAT','ขนาดบรรจุ'));
_Cols:=TList.Create;
_Cols.Add(TStringValue.Create('PACCOD','รหัส'));
_Cols.Add(TStringValue.Create('PACNAM','ชื่อขนาดบรรจุ'));
_Cols.Add(TStringValue.Create('PACRAT','ขนาดบรรจุ'));
_ColsWidth:=TList.Create;
_ColsWidth.Add(TStringValue.Create('1','80'));
_ColsWidth.Add(TStringValue.Create('2','150'));
_ColsWidth.Add(TStringValue.Create('3','50'));
Parameter.SearchTitle:='รายชื่อหน่วยสินค้า';
executilsdxInitialize;
_SQL :=' select PACCOD,PACNAM,PACRAT from ICMTTPAC where PACACT=''A'' and PACUNI='+IntToStr(FProductUnitCode)+' order by PACCOD ';
SelSearch(Application,swModal,Parameter,_Parameter,_SearchType,_Cols,_ColsWidth,'PACCOD',_SQL);
if Trim(_Parameter.SelectCode)<>'' then
begin
ProductPackingCode := StrToInt(_Parameter.SelectCode);
end;
end;
procedure TfrmEditProductUnit.edUnitCodeKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
if trim(edUnitCode.Text)<>'' then
begin
if getExistMTTCode('UNI',trim(edUnitCode.Text)) then
begin
ProductUnitCode := getMTTCOD('UNI',trim(edUnitCode.Text));
end
else
Application.MessageBox(pchar('ไม่พบหน่วยสินค้าต้องการค้นหา !!!'),pchar('Warning'), MB_OK or MB_ICONWARNING);
end else
spdSearchUnitClick(sender);
end;
end;
procedure TfrmEditProductUnit.edPackingCodeKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
if trim(edPackingCode.Text)<>'' then
begin
if getExistMTTCode('PAC',trim(edPackingCode.Text)) then
begin
ProductPackingCode := getMTTCOD('PAC',trim(edPackingCode.Text));
end
else
Application.MessageBox(pchar('ไม่พบขนาดบรรจุที่ต้องการค้นหา !!!'),pchar('Warning'), MB_OK or MB_ICONWARNING);
end else
spdSearchPackingClick(sender);
end;
end;
procedure TfrmEditProductUnit.FormCreate(Sender: TObject);
begin
SetChildTaborders(pnAllClients);
end;
procedure TfrmEditProductUnit.FormKeyPress(Sender: TObject; var Key: Char);
begin
If (Key = #13) then
Begin
if not (ActiveControl is TRzButton) then
begin
SelectNext(ActiveControl as TWinControl, True, True);
end;
End;
end;
procedure TfrmEditProductUnit.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=VK_ESCAPE then btnCancelClick(nil);
if Key=VK_F11 then btnSaveClick(nil);
end;
procedure TfrmEditProductUnit.SetAppParameter(const Value: TDLLParameter);
begin
FAppParameter := Value;
end;
end.
|
unit uDadosCep;
interface
uses
System.SysUtils, System.Classes, Data.FMTBcd, Data.DB, Datasnap.DBClient,
Datasnap.Provider, Data.SqlExpr, Vcl.Dialogs, System.UITypes,
Data.DBXCommon;
type
TdmDadosCep = class(TDataModule)
sqlTblcep: TSQLDataSet;
dspTblcep: TDataSetProvider;
cdsTblcep: TClientDataSet;
cdsTblcepcepcep: TStringField;
cdsTblcepcepmunicipio: TStringField;
cdsTblcepcepeuf: TStringField;
procedure dspTblcepUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
procedure cdsTblcepAfterInsert(DataSet: TDataSet);
procedure cdsTblcepcepcepValidate(Sender: TField);
procedure cdsTblcepcepmunicipioValidate(Sender: TField);
procedure cdsTblcepcepeufValidate(Sender: TField);
private
{ Private declarations }
public
{ Public declarations }
procedure FiltrarCeps(ACep: String = ''; AMunicipio: String = ''; AUf: String = '');
procedure PosicionarCep(ACEP: String);
procedure AdicionarCep;
procedure EditarCep;
procedure ExcluirCep;
procedure SalvarCep;
procedure CalcelarCep;
// Método específico para o cadastro de um novo CEP a partir da tela de
// cadastro de assinante, quando já tem uma transação em aberto.
// Este método instacia uma nova conexao e transação exclusiva para este método.
procedure AdicionarNovoCep(ACep: String; AMunicipio: String; AUf: String);
end;
var
dmDadosCep: TdmDadosCep;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
uses uConexao, uDadosGlobal;
{$R *.dfm}
{ TdmDadosCep }
procedure TdmDadosCep.AdicionarCep;
begin
if not cdsTblcep.Active then
FiltrarCeps;
CalcelarCep;
cdsTblcep.Append;
end;
procedure TdmDadosCep.AdicionarNovoCep(ACep, AMunicipio, AUf: String);
var
lTransaction: TDBXTransaction;
begin
// Verifica se o CEP já existe.
FiltrarCeps(ACep);
// Se já existe, não precisa fazer nada
if cdsTblcep.RecordCount > 0 then
exit;
// Adiciona uma nova linha no ClientDataSet
AdicionarCep;
cdsTblcepcepcep.Value := ACep;
cdsTblcepcepmunicipio.Value := AMunicipio;
cdsTblcepcepeuf.Value := AUf;
lTransaction := nil;
try
lTransaction := dmConexao.SQLConnection.BeginTransaction(TDBXIsolations.ReadCommitted);
// Salva o ClientDataSet no banco
SalvarCep;
// Finaliza a transação
dmConexao.SQLConnection.CommitFreeAndNil(lTransaction);
finally
if Assigned(lTransaction) then
if dmConexao.SQLConnection.InTransaction then
dmConexao.SQLConnection.RollbackFreeAndNil(lTransaction);
end;
end;
procedure TdmDadosCep.CalcelarCep;
begin
if not cdsTblcep.Active then
exit;
if cdsTblcep.State in [dsEdit, dsInsert] then
cdsTblcep.Cancel;
if cdsTblcep.ChangeCount > 0 then
cdsTblcep.CancelUpdates;
end;
procedure TdmDadosCep.cdsTblcepAfterInsert(DataSet: TDataSet);
begin
cdsTblcep.Tag := 1;
try
cdsTblcepcepeuf.Value := 'RS';
finally
cdsTblcep.Tag := 0;
end;
end;
procedure TdmDadosCep.cdsTblcepcepcepValidate(Sender: TField);
begin
if cdsTblcep.Tag = 1 then
exit;
if trim(cdsTblcepcepcep.AsString) = EmptyStr then
raise Exception.Create('CEP não pode ser nulo.');
end;
procedure TdmDadosCep.cdsTblcepcepeufValidate(Sender: TField);
begin
if cdsTblcep.Tag = 1 then
exit;
if trim(cdsTblcepcepeuf.AsString) = EmptyStr then
raise Exception.Create('UF não pode ser nulo.');
end;
procedure TdmDadosCep.cdsTblcepcepmunicipioValidate(Sender: TField);
begin
if cdsTblcep.Tag = 1 then
exit;
if trim(cdsTblcepcepmunicipio.AsString) = EmptyStr then
raise Exception.Create('Município não pode ser nulo.');
end;
procedure TdmDadosCep.dspTblcepUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
raise Exception.Create(e.Message);
end;
procedure TdmDadosCep.EditarCep;
begin
if not cdsTblcep.Active then
raise Exception.Create('Nenhum CEP está selecionado.');
if cdsTblcep.RecordCount = 0 then
raise Exception.Create('Nenhum CEP está selecionado.');
cdsTblcep.Edit;
end;
procedure TdmDadosCep.ExcluirCep;
begin
if not cdsTblcep.Active then
raise Exception.Create('Nenhum CEP está selecionado.');
if cdsTblcep.RecordCount = 0 then
raise Exception.Create('Nenhum CEP está selecionado.');
if MessageDlg('Deseja realmente excluir o CEP selecionado?', mtConfirmation,[mbYes, mbNo],0) <> mrYes then
exit;
cdsTblcep.Delete;
try
cdsTblcep.Tag := 1;
SalvarCep;
finally
cdsTblcep.Tag := 0;
end;
end;
procedure TdmDadosCep.FiltrarCeps(ACep, AMunicipio, AUf: String);
var
SQL: String;
CepSelecionado: String;
begin
// Será utilizado para posicionar na lista
if cdsTblcep.Active then
CepSelecionado := cdsTblcepcepcep.AsString
else
CepSelecionado := '';
ACep := trim(ACep);
AMunicipio := trim(AMunicipio);
AUf := trim(AUf);
if ACep = '-' then
ACep := '';
SQL := 'select * from tblcep';
if (ACep = EmptyStr) and (AMunicipio = EmptyStr) and (AUf = EmptyStr) then
begin
SQL := SQL + ' where 1 = 2';
end
else
begin
SQL := SQL + ' where 1 = 1';
if ACep <> EmptyStr then
SQL := SQL + ' and cepcep = "' + ACep + '"';
if AMunicipio <> EmptyStr then
SQL := SQL + ' and cepmunicipio like "%' + AMunicipio + '%"';
if AUf <> EmptyStr then
SQL := SQL + ' and cepeuf = "' + AUf + '"';
end;
SQL := SQL + ' order by cepmunicipio';
sqlTblcep.Close;
sqlTblcep.CommandText := SQL;
cdsTblcep.DisableControls;
try
cdsTblcep.Close;
cdsTblcep.Open;
PosicionarCep(CepSelecionado);
finally
cdsTblcep.EnableControls;
end;
end;
procedure TdmDadosCep.PosicionarCep(ACEP: String);
begin
if not cdsTblcep.Active then
exit;
if cdsTblcep.RecordCount = 0 then
exit;
if trim(ACEP) = '-' then
exit;
cdsTblcep.Locate('cepcep', ACEP, []);
end;
procedure TdmDadosCep.SalvarCep;
begin
if not cdsTblcep.Active then
raise Exception.Create('Nenhum CEP está selecionado.');
// ---------------------------------------------------------------------------
// Aplica mais uma vez os métodos de validação
// ---------------------------------------------------------------------------
if cdsTblcep.State in [dsInsert] then
cdsTblcepcepcepValidate(cdsTblcepcepcep);
cdsTblcepcepmunicipioValidate(cdsTblcepcepmunicipio);
cdsTblcepcepeufValidate(cdsTblcepcepeuf);
try
if cdsTblcep.State in [dsEdit, dsInsert] then
cdsTblcep.Post;
cdsTblcep.ApplyUpdates(0);
except
on E: Exception do
begin
if cdsTblcep.ChangeCount > 0 then
cdsTblcep.Cancel;
if pos('key violation', LowerCase(e.Message)) > 0 then
raise Exception.Create('CEP informado já está cadastrado.')
else if pos('duplicate entry', LowerCase(e.Message)) > 0 then
raise Exception.Create('CEP informado já está cadastrado.')
else if pos('foreign key constraint fails', LowerCase(e.Message)) > 0 then
raise Exception.Create('Não é possível excluir este CEP, pois existem assinantes que utilizam este CEP.')
else
raise Exception.Create(e.Message);
end;
end;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Need a short description of what it does here.
}
unit FPlugInManagerEditor;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.StdCtrls,
FMX.Layouts,
FMX.ListBox,
FMX.Objects,
FMX.Memo,
FMX.ScrollBox,
FMX.Controls.Presentation,
VXS.PlugInIntf,
VXS.PlugInManager;
type
TVXPlugInManagerEditor = class(TForm)
OpenDialog: TOpenDialog;
ListBox: TListBox;
Label1: TLabel;
GroupBox1: TGroupBox;
DescriptionMemo: TMemo;
Label2: TLabel;
Label3: TLabel;
DateLabel: TLabel;
SizeLabel: TLabel;
Label4: TLabel;
Label5: TLabel;
ServiceBox: TComboBox;
NameBox: TComboBox;
ToolBar1: TToolBar;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
Image1: TImage;
Image2: TImage;
Image3: TImage;
procedure OKButtonClick(Sender: TObject);
procedure LoadButtonClick(Sender: TObject);
procedure ListBoxClick(Sender: TObject);
procedure UnloadButtonClick(Sender: TObject);
procedure ServiceBoxChange(Sender: TObject);
private
FManager: TVXPlugInManager;
public
class procedure EditPlugIns(AManager: TVXPlugInManager);
end;
var
PlugInManagerEditor: TVXPlugInManagerEditor;
//=======================================================================
implementation
//=======================================================================
{$R *.fmx}
procedure TVXPlugInManagerEditor.OKButtonClick(Sender: TObject);
begin
Close;
end;
procedure TVXPlugInManagerEditor.LoadButtonClick(Sender: TObject);
var
I, Index: Integer;
begin
with OpenDialog do
if Execute then
for I := 0 to Files.Count - 1 do
begin
Index := FManager.AddPlugIn(Files[I]);
if Index > -1 then
if Index >= ListBox.Items.Count then
begin
FManager.PlugIns.Objects[Index];
ListBox.Items.Add(FManager.PlugIns.Strings[I]);
end
else
else
MessageDlg(Format('Error while loading %s' + #13 +
'not a valid plug-in', [Files[I]]),
TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);
end;
end;
class procedure TVXPlugInManagerEditor.EditPlugIns(AManager: TVXPlugInManager);
begin
// ensure only one instance
if assigned(PlugInManagerEditor) then
PlugInManagerEditor.Free;
PlugInManagerEditor := TVXPlugInManagerEditor.Create(Application);
with PlugInManagerEditor do
begin
ListBox.Items := AManager.PlugIns;
FManager := AManager;
ShowModal;
Free;
end;
PlugInManagerEditor := nil;
end;
procedure TVXPlugInManagerEditor.ListBoxClick(Sender: TObject);
var
Entry: Integer;
Service: TPIServiceType;
Services: TPIServices;
begin
Entry := ListBox.ItemIndex;
if Entry > -1 then
begin
SizeLabel.Text := Format('%n KB',
[FManager.PlugIns[Entry].FileSize / 1000]);
SizeLabel.Enabled := True;
DateLabel.Text := DateToStr(FManager.PlugIns[Entry].FileDate);
DateLabel.Enabled := True;
DescriptionMemo.Lines.Text :=
string(FManager.PlugIns[Entry].GetDescription);
ServiceBox.Items.Clear;
ServiceBox.Enabled := True;
Services := FManager.PlugIns[Entry].GetServices;
for Service := Low(TPIServiceType) to High(TPIServiceType) do
if Service in Services then
case Service of
stRaw:
begin
Entry := ServiceBox.Items.Add('Raw');
ServiceBox.Items.Objects[Entry] := Pointer(stRaw);
end;
stObject:
begin
Entry := ServiceBox.Items.Add('Object');
ServiceBox.Items.Objects[Entry] := Pointer(stObject);
end;
stBitmap:
begin
Entry := ServiceBox.Items.Add('Bitmap');
ServiceBox.Items.Objects[Entry] := Pointer(stBitmap);
end;
stTexture:
begin
Entry := ServiceBox.Items.Add('Texture');
ServiceBox.Items.Objects[Entry] := Pointer(stTexture);
end;
stImport:
begin
Entry := ServiceBox.Items.Add('Import');
ServiceBox.Items.Objects[Entry] := Pointer(stImport);
end;
stExport:
begin
Entry := ServiceBox.Items.Add('Export');
ServiceBox.Items.Objects[Entry] := Pointer(stExport);
end;
end;
ServiceBox.ItemIndex := 0;
ServiceBox.OnChange(ServiceBox);
end;
end;
procedure TVXPlugInManagerEditor.UnloadButtonClick(Sender: TObject);
var
I: Integer;
begin
for I := 0 to ListBox.Items.Count - 1 do
// if ListBox.Selected then
begin
FManager.RemovePlugIn(I);
ListBox.Items.Delete(I);
end;
DescriptionMemo.Lines.Clear;
DateLabel.Text := '???';
DateLabel.Enabled := False;
SizeLabel.Text := '???';
SizeLabel.Enabled := False;
ServiceBox.ItemIndex := -1;
ServiceBox.Enabled := False;
NameBox.ItemIndex := -1;
NameBox.Enabled := False;
end;
// ------------------------------------------------------------------------------
procedure NameCallback(Name: PAnsiChar); stdcall;
begin
PlugInManagerEditor.NameBox.Items.Add(string(StrPas(Name)));
end;
// ------------------------------------------------------------------------------
procedure TVXPlugInManagerEditor.ServiceBoxChange(Sender: TObject);
begin
NameBox.Items.Clear;
with ServiceBox, Items do
FManager.PlugIns[ListBox.ItemIndex].EnumResourceNames
(TPIServiceType(Objects[ItemIndex]), NameCallback);
NameBox.ItemIndex := 0;
NameBox.Enabled := True;
end;
end.
|
unit ModBusLoad;
interface
uses
Windows;
type
// TParity = ( None, Odd, Even, Mark, Space );
// TStopBits = ( _1, _1_5, _2 );
// TByteSize = ( _5, _6, _7, _8 );
TOpen = function(Comm:string;BaudRate,Parity,ByteSize,StopBits,BeginAddress,EndAddress,MacAddress,ReadTime,WaitTimes:Integer):Integer;stdcall;
TClose = function:Integer;stdcall;
TSetCallBack = function(CallBack: Pointer):Integer;stdcall;
TCloseByComm = function(Comm:string):Integer;stdcall;
TCallBack = procedure(Comm:string;MacAddress,Address,Value:Integer) of object;
TModLoad = class(TObject)
private
FillName:string;
PDllName: HMODULE;
POpen : Pointer;
PClose : Pointer;
PSetCallBack : Pointer;
PCloseByComm : Pointer;
FCallback: TCallBack;
public
constructor Create(PFileName:string;PCallBack:TCallBack;var IsSuccess:Boolean); overload;
destructor Destroy; override;
function Open(Comm:string;BaudRate,Parity,ByteSize,StopBits,BeginAddress,EndAddress,MacAddress,ReadTime,WaitTimes:Integer):Boolean;
function Close:Boolean;
function CloseByComm(Comm:string):Boolean;
end;
var
ModLoad :TModLoad;
implementation
procedure FunCallBack(Comm:string;MacAddress,Address,Value:Integer);stdcall;
begin
ModLoad.FCallback(Comm,MacAddress,Address,Value);
end;
constructor TModLoad.Create(PFileName:string;PCallBack:TCallBack;var IsSuccess:Boolean);
begin
FillName := PFileName;
PDllName := LoadLibrary(PChar(FillName));
IsSuccess := False;
if PDllName > 32 then
begin
POpen := GetProcAddress(PDllName, PChar('Open'));
PClose := GetProcAddress(PDllName, PChar('Close'));
PSetCallBack := GetProcAddress(PDllName, PChar('SetCallBack'));
PCloseByComm := GetProcAddress(PDllName, PChar('CloseByComm'));
FCallback := PCallBack;
IsSuccess := True;
end;
end;
destructor TModLoad.Destroy;
begin
if PDllName > 32 then
begin
Close;
FreeLibrary(PDllName);
PDllName := 0;
end;
end;
function TModLoad.Open(Comm:string;BaudRate,Parity,ByteSize,StopBits,BeginAddress,EndAddress,MacAddress,ReadTime,WaitTimes:Integer):Boolean;
begin
Result := False;
if PDllName > 32 then
begin
Result := TOpen(POpen)(Comm,BaudRate,Parity,ByteSize,StopBits,BeginAddress,EndAddress,MacAddress,ReadTime,WaitTimes) = 1;
if Result then
Result := TSetCallBack(PSetCallBack)(@FunCallBack) = 1;
end;
// Result := MM.Open(Comm,BaudRate,Parity,ByteSize,StopBits,BeginAddress,EndAddress,MacAddress,ReadTime,WaitTimes) = 1;
end;
function TModLoad.Close:Boolean;
begin
Result := False;
if PDllName > 32 then
Result := TClose(PClose) = 1;
end;
function TModLoad.CloseByComm(Comm:string):Boolean;
begin
Result := False;
if PDllName > 32 then
Result := TCloseByComm(PCloseByComm)(Comm) = 1;
end;
end.
|
unit uUtils;
interface
uses Dialogs, Forms, StdCtrls, SysUtils, uParser, Controls, uArrayList, uStringMap;
type StringList = Array of String;
{
Used to switch objects
}
type Discarder = class
public
objects: StringMap;
constructor Create();
procedure switch(name: String);
procedure OnSelect(o: TObject); virtual; abstract;
procedure OnUnselect(o: TObject); virtual; abstract;
end;
{
Like messageDLG but better
}
function customMessageDLG(const msg, title: String; dlgType: TMsgDlgType; Buttons: TMsgDlgButtons; captions: Array of String): integer;
{
showMessage
}
procedure pout(v: String); overload;
procedure pout(v: integer); overload;
procedure pout(v: real); overload;
procedure pout(v: boolean); overload;
procedure pout2(v: real);
{
Splits str into array of str
}
function split(str: String; t: String): StringList;
{
Removes all controls
}
procedure clearChildren(c: TWinControl);
{
Creates a new file if it does not exist
}
procedure newFile(path: String);
implementation
// Discarder
constructor Discarder.Create();
begin
objects := StringMap.Create();
end;
// Discarder
procedure Discarder.switch(name: String);
var
i: integer;
arr: ArrayList;
o: TObject;
begin
arr := objects.getValues();
for i := 0 to arr.size() - 1 do
OnUnselect(arr.get(i));
o := objects.get(name);
OnSelect(o);
end;
function customMessageDLG(const msg, title: String; dlgType: TMsgDlgType; Buttons: TMsgDlgButtons; captions: Array of String): integer;
var
aMsgDlg: TForm;
i: integer;
dlgButton: TButton;
captionIndex, left: integer;
begin
aMsgDlg := CreateMessageDialog(msg, dlgType, buttons);
captionIndex := 0;
left := 15;
for i := 0 to aMsgDlg.componentCount - 1 do begin
if aMsgDlg.components[i] is TButton then begin
dlgButton := TButton (aMsgDlg.components[i]);
if captionIndex > High(captions) then break;
dlgButton.Caption := captions[captionIndex];
dlgButton.Width := 40 + length(dlgButton.Caption) * 5;
dlgButton.Left := left;
left := left + dlgButton.Width + 15;
inc(captionIndex);
end;
end;
aMsgDlg.Width := left;
aMsgDlg.Caption := title;
customMessageDlg := aMsgDlg.showModal();
end;
procedure pout(v: String); overload;
begin
showMessage(v);
end;
procedure pout(v: integer); overload;
begin
showMessage(intToStr(v));
end;
procedure pout(v: real); overload;
begin
showMessage(getNum(v));
end;
procedure pout(v: boolean); overload;
begin
showMessage(getBool(v));
end;
procedure pout2(v: real);
begin
showMessage(getNum2(v));
end;
function split(str: String; t: String): StringList;
var
n, i: integer;
sub: String;
l: StringList;
begin
// find amount
sub := str;
n := 1;
while pos(t, sub) > 0 do begin
delete(sub, 1, pos(t, sub) + length(t) - 1);
n := n + 1;
end;
// fill
SetLength(l, n);
for i := 0 to n - 1 do begin
if pos(t, str) > 0 then begin
l[i] := copy(str, 1, pos(t, str) - 1);
delete(str, 1, pos(t, str) + length(t) - 1);
end else
l[i] := str;
end;
split := l;
end;
procedure clearChildren(c: TWinControl);
var i: integer;
begin
for i := 0 to c.ControlCount - 1 do
c.controls[0].Free;
end;
procedure newFile(path: String);
var f: TextFile;
begin
AssignFile(f, path);
rewrite(f);
close(f);
end;
end.
|
unit uVistaFuncs;
interface
uses
System.Types,
System.Classes,
System.HelpIntfs,
Winapi.Windows,
Winapi.Messages,
Winapi.MultiMon,
Vcl.Forms,
Vcl.StdCtrls,
Vcl.Dialogs,
Vcl.Graphics,
Vcl.Themes,
Dmitry.Utils.System,
{$IFNDEF EXTERNAL}
uTranslate,
{$ENDIF}
uConstants;
type
TChangeWindowMessageFilter = function(msg: Cardinal; action: Word): BOOL; stdcall;
procedure SetVistaFonts(const AForm: TCustomForm);
procedure SetVistaContentFonts(const AFont: TFont; Increment: Integer = 2);
procedure SetDesktopIconFonts(const AFont: TFont);
procedure ExtendGlass(const AHandle: THandle; const AMargins: TRect);
function CompositingEnabled: Boolean;
function TaskDialog(Handle: THandle; AContent, ATitle, ADescription: string; Buttons, Icon: Integer): Integer;
procedure SetVistaTreeView(const AHandle: THandle);
function DoTaskMessageDlgPosHelpEx(const Instruction, Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer;
const HelpFileName: string; DefaultButton: TMsgDlgBtn): Integer; overload;
function DoTaskMessageDlgPosHelpEx(const Instruction, Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer;
const HelpFileName: string): Integer; overload;
procedure AllowDragAndDrop;
const
VistaFont = 'Segoe UI';
VistaContentFont = 'Calibri';
XPContentFont = 'Verdana';
XPFont = 'Tahoma';
var
CheckOSVerForFonts: Boolean = True;
implementation
uses
SysUtils,
Controls,
UxTheme;
{$IFDEF EXTERNAL}
function TA(S: string): string;
begin
Result := S;
end;
{$ENDIF}
procedure SetVistaTreeView(const AHandle: THandle);
begin
if IsWindowsVista then
SetWindowTheme(AHandle, 'explorer', nil);
end;
procedure AllowDragAndDrop;
var
User32Handle: THandle;
ChangeWindowMessageFilter: TChangeWindowMessageFilter;
const
MSGFLT_ALLOW = 1;
begin
User32Handle := LoadLibrary(user32);
@ChangeWindowMessageFilter := GetProcAddress(User32Handle, 'ChangeWindowMessageFilter');
if Assigned(ChangeWindowMessageFilter) then
begin
//WM_COMMAND for taskbar
ChangeWindowMessageFilter (WM_COMMAND, MSGFLT_ALLOW);
ChangeWindowMessageFilter (WM_DROPFILES, MSGFLT_ALLOW);
ChangeWindowMessageFilter (WM_COPYDATA, MSGFLT_ALLOW);
ChangeWindowMessageFilter ($0049, MSGFLT_ALLOW);
end;
FreeLibrary(User32Handle);
end;
procedure SetVistaFonts(const AForm: TCustomForm);
begin
if (IsWindowsVista or not CheckOSVerForFonts)
and not SameText(AForm.Font.Name, VistaFont)
and (Screen.Fonts.IndexOf(VistaFont) >= 0) then
begin
AForm.Font.Size := AForm.Font.Size + 1;
AForm.Font.Name := VistaFont;
end;
end;
procedure SetVistaContentFonts(const AFont: TFont; Increment: Integer = 2);
begin
if (IsWindowsVista or not CheckOSVerForFonts)
and not SameText(AFont.Name, VistaContentFont)
and (Screen.Fonts.IndexOf(VistaContentFont) >= 0) then
begin
AFont.Size := AFont.Size + Increment;
AFont.Name := VistaContentFont;
end;
end;
procedure SetDefaultFonts(const AFont: TFont);
begin
AFont.Handle := GetStockObject(DEFAULT_GUI_FONT);
end;
procedure SetDesktopIconFonts(const AFont: TFont);
var
LogFont: TLogFont;
begin
if SystemParametersInfo(SPI_GETICONTITLELOGFONT, SizeOf(LogFont),
@LogFont, 0) then
AFont.Handle := CreateFontIndirect(LogFont)
else
SetDefaultFonts(AFont);
end;
const
dwmapi = 'dwmapi.dll';
DwmIsCompositionEnabledSig = 'DwmIsCompositionEnabled';
DwmExtendFrameIntoClientAreaSig = 'DwmExtendFrameIntoClientArea';
TaskDialogSig = 'TaskDialog';
function CompositingEnabled: Boolean;
var
DLLHandle: THandle;
DwmIsCompositionEnabledProc: function(pfEnabled: PBoolean): HRESULT; stdcall;
Enabled: Boolean;
begin
Result := False;
if IsWindowsVista then
begin
DLLHandle := LoadLibrary(dwmapi);
if DLLHandle <> 0 then
begin
@DwmIsCompositionEnabledProc := GetProcAddress(DLLHandle,
DwmIsCompositionEnabledSig);
if (@DwmIsCompositionEnabledProc <> nil) then
begin
DwmIsCompositionEnabledProc(@Enabled);
Result := Enabled;
end;
FreeLibrary(DLLHandle);
end;
end;
end;
//from http://www.delphipraxis.net/topic93221,next.html
procedure ExtendGlass(const AHandle: THandle; const AMargins: TRect);
type
_MARGINS = packed record
cxLeftWidth: Integer;
cxRightWidth: Integer;
cyTopHeight: Integer;
cyBottomHeight: Integer;
end;
PMargins = ^_MARGINS;
TMargins = _MARGINS;
var
DLLHandle: THandle;
DwmExtendFrameIntoClientAreaProc: function(destWnd: HWND; const pMarInset:
PMargins): HRESULT; stdcall;
Margins: TMargins;
begin
if IsWindowsVista and CompositingEnabled then
begin
DLLHandle := LoadLibrary(dwmapi);
if DLLHandle <> 0 then
begin
@DwmExtendFrameIntoClientAreaProc := GetProcAddress(DLLHandle,
DwmExtendFrameIntoClientAreaSig);
if (@DwmExtendFrameIntoClientAreaProc <> nil) then
begin
ZeroMemory(@Margins, SizeOf(Margins));
Margins.cxLeftWidth := AMargins.Left;
Margins.cxRightWidth := AMargins.Right;
Margins.cyTopHeight := AMargins.Top;
Margins.cyBottomHeight := AMargins.Bottom;
DwmExtendFrameIntoClientAreaProc(AHandle, @Margins);
end;
FreeLibrary(DLLHandle);
end;
end;
end;
function GetButtonCaption(DlgBtn: TMsgDlgBtn): string;
begin
Result := '';
case DlgBtn of
TMsgDlgBtn.mbYes:
Result := TA('Yes');
TMsgDlgBtn.mbNo:
Result := TA('No');
TMsgDlgBtn.mbOK:
Result := TA('Ok');
TMsgDlgBtn.mbCancel:
Result := TA('Cancel');
TMsgDlgBtn.mbAbort:
Result := TA('Abort');
TMsgDlgBtn.mbRetry:
Result := TA('Retry');
TMsgDlgBtn.mbIgnore:
Result := TA('Ignore');
TMsgDlgBtn.mbAll:
Result := TA('All');
TMsgDlgBtn.mbNoToAll:
Result := TA('No to all');
TMsgDlgBtn.mbYesToAll:
Result := TA('Yes to all');
TMsgDlgBtn.mbHelp:
Result := TA('Help');
TMsgDlgBtn.mbClose:
Result := TA('Close');
end;
end;
function GetCaptions(MsgDlgType: TMsgDlgType): string;
begin
case MsgDlgType of
mtWarning:
Result := TA('Warning');
mtError:
Result := TA('Error');
mtInformation:
Result := TA('Information');
mtConfirmation:
Result := TA('Confirm');
mtCustom:
Result := TA('Custom');
end;
end;
// Captions: array[TMsgDlgType] of Pointer = (@SMsgDlgWarning, @SMsgDlgError,
// @SMsgDlgInformation, @SMsgDlgConfirm, nil);
{ TaskDialog based message dialog; requires Windows Vista or later }
type
TTaskMessageDialog = class(TCustomTaskDialog)
private
FHelpFile: string;
FParentWnd: HWND;
FPosition: TPoint;
strict protected
procedure DoOnButtonClicked(AModalResult: Integer; var CanClose: Boolean); override;
procedure DoOnDialogCreated; override;
procedure DoOnHelp; override;
public
function Execute(ParentWnd: HWND): Boolean; overload; override;
property HelpFile: string read FHelpFile write FHelpFile;
property Position: TPoint read FPosition write FPosition;
end;
const
tdbHelp = -1;
procedure TTaskMessageDialog.DoOnButtonClicked(AModalResult: Integer;
var CanClose: Boolean);
begin
if AModalResult = tdbHelp then
begin
CanClose := False;
DoOnHelp;
end;
end;
procedure TTaskMessageDialog.DoOnDialogCreated;
var
Rect: TRect;
LX, LY: Integer;
LHandle: HMONITOR;
LMonitorInfo: TMonitorInfo;
begin
LX := Position.X;
LY := Position.Y;
LHandle := MonitorFromWindow(FParentWnd, MONITOR_DEFAULTTONEAREST);
LMonitorInfo.cbSize := SizeOf(LMonitorInfo);
if GetMonitorInfo(LHandle, {$IFNDEF CLR}@{$ENDIF}LMonitorInfo) then
with LMonitorInfo do
begin
GetWindowRect(Handle, Rect);
if LX < 0 then
LX := ((rcWork.Right - rcWork.Left) - (Rect.Right - Rect.Left)) div 2;
if LY < 0 then
LY := ((rcWork.Bottom - rcWork.Top) - (Rect.Bottom - Rect.Top)) div 2;
Inc(LX, rcWork.Left);
Inc(LY, rcWork.Top);
SetWindowPos(Handle, 0, LX, LY, 0, 0, SWP_NOACTIVATE or SWP_NOSIZE or SWP_NOZORDER);
end;
end;
procedure TTaskMessageDialog.DoOnHelp;
var
LHelpFile: string;
LHelpSystem: IHelpSystem;
begin
if HelpContext <> 0 then
begin
if FHelpFile = '' then
LHelpFile := Application.HelpFile
else
LHelpFile := HelpFile;
if System.HelpIntfs.GetHelpSystem(LHelpSystem) then
try
LHelpSystem.Hook(Application.Handle, LHelpFile, HELP_CONTEXT, HelpContext);
except
on E: Exception do
ShowHelpException(E);
end;
end;
end;
function TTaskMessageDialog.Execute(ParentWnd: HWND): Boolean;
begin
FParentWnd := ParentWnd;
Result := inherited Execute(ParentWnd);
end;
function DoTaskMessageDlgPosHelpEx(const Instruction, Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer;
const HelpFileName: string; DefaultButton: TMsgDlgBtn): Integer;
const
IconMap: array[TMsgDlgType] of TTaskDialogIcon = (tdiWarning, tdiError,
tdiInformation, tdiInformation, tdiNone);
LModalResults: array[TMsgDlgBtn] of Integer = (mrYes, mrNo, mrOk, mrCancel,
mrAbort, mrRetry, mrIgnore, mrAll, mrNoToAll, mrYesToAll, tdbHelp, mrClose);
var
DlgBtn: TMsgDlgBtn;
LTaskDialog: TTaskMessageDialog;
begin
Application.ModalStarted;
LTaskDialog := TTaskMessageDialog.Create(nil);
try
// Assign buttons
for DlgBtn := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
if DlgBtn in Buttons then
with LTaskDialog.Buttons.Add do
begin
{$IF DEFINED(CLR)}
Caption := ButtonCaptions[DlgBtn];
{$ELSE}
Caption := GetButtonCaption(DlgBtn);
{$IFEND}
if DlgBtn = DefaultButton then
Default := True;
ModalResult := LModalResults[DlgBtn];
end;
// Set dialog properties
with LTaskDialog do
begin
if DlgType <> mtCustom then
{$IF DEFINED(CLR)}
Caption := Captions[DlgType]
{$ELSE}
Caption := GetCaptions(DlgType)
{$IFEND}
else
Caption := Application.Title;
CommonButtons := [];
if Application.UseRightToLeftReading then
Flags := Flags + [tfRtlLayout];
HelpContext := HelpCtx;
HelpFile := HelpFileName;
MainIcon := IconMap[DlgType];
Position := Point(X, Y);
Text := Msg;
Title := Instruction;
end;
// Show dialog and return result
Result := mrNone;
if LTaskDialog.Execute then
Result := LTaskDialog.ModalResult;
finally
LTaskDialog.Free;
Application.ModalFinished;
end;
end;
function DoTaskMessageDlgPosHelpEx(const Instruction, Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer;
const HelpFileName: string): Integer;
var
DefaultButton: TMsgDlgBtn;
begin
if mbOk in Buttons then DefaultButton := mbOk else
if mbYes in Buttons then DefaultButton := mbYes else
DefaultButton := mbRetry;
Result := DoTaskMessageDlgPosHelpEx(Instruction, Msg, DlgType, Buttons, HelpCtx,
X, Y, HelpFileName, DefaultButton);
end;
function DoMessageDlgPosHelpEx(MessageDialog: TForm; HelpCtx: Longint; X, Y: Integer;
const HelpFileName: string): Integer;
begin
with MessageDialog do
try
HelpContext := HelpCtx;
HelpFile := HelpFileName;
if X >= 0 then Left := X;
if Y >= 0 then Top := Y;
if (Y < 0) and (X < 0) then Position := poScreenCenter;
Result := ShowModal;
finally
Free;
end;
end;
function MessageDlgPosHelpEx(const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer;
const HelpFileName: string): Integer;
var
Frm: TForm;
Button: TButton;
I: Integer;
S, NS: string;
begin
if TOSVersion.Check(6) and UseLatestCommonDialogs and
StyleServices.Enabled and StyleServices.IsSystemStyle then
Result := DoTaskMessageDlgPosHelpEx('', Msg, DlgType, Buttons,
HelpCtx, X, Y, HelpFileName)
else
begin
Frm := CreateMessageDialog(Msg, DlgType, Buttons);
Frm.Caption := GetCaptions(DlgType);
{$IFNDEF EXTERNAL}
for I := 0 to Frm.ComponentCount - 1 do
begin
{ If the object is of type TButton, then }
{ Wenn es ein Button ist, dann... }
if (Frm.Components[I] is TButton) then
begin
Button := TButton(Frm.Components[I]);
S := StringReplace(Button.Caption, '&', '', []);
NS := TA(S);
if NS <> S then
Button.Caption := NS;
end;
end;
{$ENDIF}
Result := DoMessageDlgPosHelpEx(Frm, HelpCtx, X, Y, HelpFileName);
end;
end;
function MessageDlgEx(const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint): Integer;
begin
Result := MessageDlgPosHelpEx(Msg, DlgType, Buttons, HelpCtx, -1, -1, '');
end;
function TaskDialog(Handle: THandle; AContent, ATitle, ADescription: string;
Buttons, Icon: Integer): Integer;
var
VerInfo: TOSVersioninfo;
DLLHandle: THandle;
res: integer;
wTitle,wDescription,wContent: array[0..1024] of widechar;
Btns: TMsgDlgButtons;
DlgType: TMsgDlgType;
TaskDialogProc: function(HWND: THandle; hInstance: THandle; cTitle, cDescription, cContent: pwidechar; Buttons: Integer; Icon: integer;
ResButton: pinteger): integer; cdecl stdcall;
begin
Result := 0;
VerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
GetVersionEx(verinfo);
if (verinfo.dwMajorVersion >= 6) and not TStyleManager.IsCustomStyleActive then
begin
DLLHandle := LoadLibrary('comctl32.dll');
if DLLHandle >= 32 then
begin
@TaskDialogProc := GetProcAddress(DLLHandle,'TaskDialog');
if Assigned(TaskDialogProc) then
begin
StringToWideChar(ATitle, wTitle, sizeof(wTitle));
StringToWideChar(ADescription, wDescription, sizeof(wDescription));
StringToWideChar(AContent, wContent, sizeof(wContent));
TaskDialogProc(Handle, 0, wTitle, wDescription, wContent, Buttons,Icon,@res);
Result := ID_OK;
case res of
TD_RESULT_CANCEL : Result := ID_Cancel;
TD_RESULT_RETRY : Result := ID_Retry;
TD_RESULT_YES : Result := ID_Yes;
TD_RESULT_NO : Result := ID_No;
TD_RESULT_CLOSE : Result := ID_Abort;
end;
end;
FreeLibrary(DLLHandle);
end;
end
else
begin
Btns := [];
if Buttons and TD_BUTTON_OK = TD_BUTTON_OK then
Btns := Btns + [MBOK];
if Buttons and TD_BUTTON_YES = TD_BUTTON_YES then
Btns := Btns + [MBYES];
if Buttons and TD_BUTTON_NO = TD_BUTTON_NO then
Btns := Btns + [MBNO];
if Buttons and TD_BUTTON_CANCEL = TD_BUTTON_CANCEL then
Btns := Btns + [MBCANCEL];
if Buttons and TD_BUTTON_RETRY = TD_BUTTON_RETRY then
Btns := Btns + [MBRETRY];
if Buttons and TD_BUTTON_CLOSE = TD_BUTTON_CLOSE then
Btns := Btns + [MBABORT];
DlgType := mtCustom;
case Icon of
TD_ICON_WARNING:
DlgType := mtWarning;
TD_ICON_QUESTION:
DlgType := mtConfirmation;
TD_ICON_ERROR:
DlgType := mtError;
TD_ICON_INFORMATION:
DlgType := mtInformation;
end;
Result := MessageDlgEx(AContent, DlgType, Btns, 0);
end;
end;
end.
|
unit uCaixa;
interface
type
TCaixa = class
private
fEntradas : Double;
fSaidas : Double;
fSaldo : Double;
public
procedure GetSaldoAtual(Dataini, Datafim : String);
property Entradas: Double read fEntradas write fEntradas;
property Saidas: Double read fSaidas write fSaidas;
property Saldo: Double read fSaldo write fSaldo;
end;
implementation
{ TCaixa }
uses uSQL, System.SysUtils;
procedure TCaixa.GetSaldoAtual(Dataini, Datafim: String);
var
sDataIni, sDataFim : String;
begin
sDataIni := Dataini;
sDataFim := Datafim;
if (sDataIni = '') and (sDataFim = '') then
begin
sDataIni := FormatDateTime('yyyy/MM/dd', now);
sDataFim := FormatDateTime('yyyy/MM/dd', now);
end;
with TSql.Create(nil) do
try
//Entradas
sql.Add('select sum(valor) from caixa where tipo = ''C''');
sql.Add(' and dt_cadastro between :dataini and :datafim');
Params[0].AsString := sDataIni;
Params[1].AsString := sDataFim;
Open;
fEntradas := Fields[0].AsCurrency;
Close;
sql.Clear;
//Saidas
sql.Add('select sum(valor) from caixa where tipo = ''D''');
sql.Add(' and dt_cadastro between :dataini and :datafim');
Params[0].AsString := sDataIni;
Params[1].AsString := sDataFim;
Open;
fSaidas := Fields[0].AsCurrency;
fSaldo := fEntradas - fSaidas;
finally
Close;
Free;
end;
end;
end.
|
unit uUpload;
interface
uses
System.SysUtils,
SynCommons,
uPnHttpSys.Comm;
type
TUpBuf = record
buf: array of AnsiChar;
buflen: Cardinal;
end;
//文件上传进度
PUploadProcessInfo = ^TUploadProcessInfo;
TUploadProcessInfo = record
public
TotalBytes: Int64;
UploadedBytes: Int64;
StartTime: Int64;
LastActivity: Int64;
ReadyState: string;
boundaryStr: SockString;
bufs: array of TUpBuf;
procedure InitObj;
//已上传秒数
function GetElapsedSeconds: Int64;
//已上传时间
function GetElapsedTime: string;
//传输速率
function GetTransferRate: string;
//完成百分比
function GetPercentage: string;
//估计剩余时间
function TimeLeft: string;
end;
implementation
{ TUploadProcessInfo }
procedure TUploadProcessInfo.InitObj;
begin
TotalBytes := 0;
UploadedBytes := 0;
StartTime := GetTickCount64;
LastActivity := GetTickCount64;
ReadyState := 'uninitialized'; //uninitialized,loading,loaded,interactive,complete
end;
function TUploadProcessInfo.GetElapsedSeconds: Int64;
begin
Result := (GetTickCount64 - StartTime) div 1000;
end;
function TUploadProcessInfo.GetElapsedTime: string;
var
LElapsedSeconds: Int64;
begin
LElapsedSeconds := GetElapsedSeconds;
if LElapsedSeconds>3600 then
begin
Result := Format('%d 时 %d 分 %d 秒', [LElapsedSeconds div 3600, (LElapsedSeconds mod 3600) div 60, LElapsedSeconds mod 60]);
end
else if LElapsedSeconds>60 then
begin
Result := Format('%d 分 %d 秒', [LElapsedSeconds div 60, LElapsedSeconds mod 60]);
end
else begin
Result := Format('%d 秒', [LElapsedSeconds mod 60]);
end;
end;
function TUploadProcessInfo.GetTransferRate: string;
var
LElapsedSeconds: Int64;
begin
LElapsedSeconds := GetElapsedSeconds;
if LElapsedSeconds>0 then
begin
Result := Format('%.2f K/秒', [UploadedBytes/1024/LElapsedSeconds]);
end
else
Result := '0 K/秒';
end;
function TUploadProcessInfo.GetPercentage: string;
begin
if TotalBytes>0 then
Result := Format('%.2f', [UploadedBytes / TotalBytes * 100])+'%'
else
Result := '0%';
end;
function TUploadProcessInfo.TimeLeft: string;
var
SecondsLeft: Int64;
begin
if UploadedBytes>0 then
begin
SecondsLeft := GetElapsedSeconds * (TotalBytes div UploadedBytes - 1);
if SecondsLeft > 3600 then
begin
Result := Format('%d 时 %d 分 %d 秒', [SecondsLeft div 3600, (SecondsLeft mod 3600) div 60, SecondsLeft mod 60]);
end
else if SecondsLeft > 60 then
begin
Result := Format('%d 分 %d 秒', [SecondsLeft div 60, SecondsLeft mod 60]);
end
else begin
Result := Format('%d 秒', [SecondsLeft mod 60]);
end;
end
else begin
Result := '未知';
end;
end;
end.
|
unit uLog;
interface
const
LOGFILE = 'main.log';
var
iLog: Integer;
//Инкапсуляция функций логгера в специфические для данного проекта
procedure logWriteMessage(Msg: String; DateTime: Boolean = True;
NewLine: Boolean = True);
procedure logWriteWarning(Msg: String; DateTime: Boolean = True;
NewLine: Boolean = True);
procedure logWriteError (Msg: String; DateTime: Boolean = True;
NewLine: Boolean = True;
Critical: Boolean = False);
//внутренние функции инициализации и деинициализации логгера
function LogInit(): Integer;
function LogDeinit(): Integer;
implementation
uses
dfLogger;
procedure logWriteMessage(Msg: String; DateTime: Boolean = True;
NewLine: Boolean = True);
begin
if DateTime then
LoggerWriteDateTime(iLog, '');
LoggerWriteUnFormated(ilog, PWideChar(Msg));
if NewLine then
LoggerWriteEndL(iLog);
end;
procedure logWriteWarning(Msg: String; DateTime: Boolean = True;
NewLine: Boolean = True);
begin
if DateTime then
LoggerWriteDateTime(iLog, '');
LoggerWriteWarning(ilog, PWideChar(Msg));
if NewLine then
LoggerWriteEndL(iLog);
end;
procedure logWriteError (Msg: String; DateTime: Boolean = True;
NewLine: Boolean = True;
Critical: Boolean = False);
begin
if DateTime then
LoggerWriteDateTime(iLog, '');
if Critical then
LoggerWriteError(ilog, PWideChar(' :CRITICAL: ' + Msg))
else
LoggerWriteError(ilog, PWideChar(Msg));
if NewLine then
LoggerWriteEndL(iLog);
end;
function LogInit(): Integer;
begin
LoggerAddLog(LOGFILE);
iLog := LoggerFindLog(LOGFILE);
LoggerWriteHeader(iLog, 'Старт логгирования');
Result := 0;
end;
function LogDeinit(): Integer;
begin
LoggerWriteBottom(iLog, 'Окончание логгирования');
LoggerDelLog(LOGFILE);
Result := 0;
end;
initialization
LogInit();
finalization
LogDeInit();
end.
|
(*
Category: SWAG Title: MATH ROUTINES
Original name: 0011.PAS
Description: PERMUTA2.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:50
*)
{
I'm working on some statistical process control Charts and am
learning/using Pascal. The current Chart Uses permutations and
I have been successful in determing the number of combinations
possible, but I want to be able to choose a few of those possible
combinations at random For testing purposes.
Through some trial and error, I've written the following Program
which calculates the number of possible combinations of x digits
with a certain number of digits in each combination. For example
a set of 12 numbers With 6 digits in each combination gives an
answer of 924 possible combinations. After all that, here is the
question: Is there a Formula which would calculate what those 924
combinations are? (ie: 1,2,3,4,5,6 then 1,2,3,4,5,7 then 1,2,3,4,5,8
... 1,2,3,4,5,12 and so on? Any help would be appreciated and any
criticism will be accepted.
}
Program permutations;
Uses Crt;
Type hold_em_here = Array[1..15] of Integer;
Var numbers,combs,bot2a : Integer;
ans,top,bot1,bot2b : Real;
hold_Array : hold_em_here;
Function permutate_this(number1 : Integer) : Real;
Var i : Integer;
a : Real;
begin
a := number1;
For i := (number1 - 1) doWNto 1 do a := a * i;
permutate_this := a;
end;
Procedure input_numbers(Var hold_Array : hold_em_here; counter : Integer);
Var i,j : Integer;
begin
For i := 1 to counter do begin
Write(' Input #',i:2,': ');
READLN(j);
hold_Array[i] := j;
end;
end;
Procedure show_numbers(hold_Array : hold_em_here; counter : Integer);
Var i{,j} : Integer;
begin
WriteLN;
Write('Array looks like this: ');
For i := 1 to counter do Write(hold_Array[i]:3);
WriteLN
end;
begin
ClrScr;
WriteLN;
WriteLN(' Permutations');
WriteLN;
Write(' Enter number of digits (1-15): ');
READLN(numbers);
Write('Enter number in combination (2-10): ');
READLN(combs);
top := permutate_this(numbers);
bot1 := permutate_this(combs);
bot2a := numbers - combs;
bot2b := permutate_this(bot2a);
ans := top/(bot1*bot2b);
WriteLN(' total permutations For above is: ',ans:3:0);
WriteLN;
input_numbers(hold_Array,numbers);
show_numbers(hold_Array,numbers);
END.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit uCodeTemplate;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ConTEXTSynEdit, SynEdit, StdCtrls, SynEditHighlighter, Math, uCommon,
ComCtrls, fCodeTemplateEdit, SynEditAutoComplete, uMultiLanguage;
type
TTemplate = record
Changed :boolean;
Name :string;
Code :TStringList;
HL :TSynCustomHighlighter;
end;
pTTemplate = ^TTemplate;
type
TfmCodeTemplate = class(TForm)
memo: TConTEXTSynEdit;
labHighlighter: TLabel;
cbHL: TComboBox;
lvSh: TListView;
labTemplate: TLabel;
labCode: TLabel;
btnAdd: TButton;
btnEdit: TButton;
btnDelete: TButton;
btnOK: TButton;
btnCancel: TButton;
procedure FormShow(Sender: TObject);
procedure cbHLChange(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lvShSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure memoChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
OldCurrTemplate :pTTemplate;
procedure Init;
procedure Done;
procedure ApplyEditorOptions(HL:TSynCustomHighLighter);
procedure ClearForm;
procedure TplToForm(tpl:pTTemplate);
procedure FormToTpl(tpl:pTTemplate);
function CurrTemplate:pTTemplate;
procedure SelectItem(n:integer);
public
ActiveHighlighter :pointer;
end;
function CreateCodeTemplate(HL:pTHighlighter):TSynAutoComplete;
procedure AddMemoToList(memo:TSynEdit);
procedure RemoveMemoFromList(memo:TSynEdit);
procedure DestroyAllTemplates;
implementation
{$R *.DFM}
const
CTPL_EXT = '.ctpl'; // ConTEXT Template
CTPL_DIR = 'Template\';
////////////////////////////////////////////////////////////////////////////////////////////
// Static functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
function GetTemplateFileName(LanguageName:string):string;
const
INVALID_CHARS = [':',';','/','|','\','*'];
var
i :integer;
begin
for i:=1 to Length(LanguageName) do
if (LanguageName[i] in INVALID_CHARS) then
LanguageName[i]:='_';
result:=ApplicationDir+CTPL_DIR+LanguageName+CTPL_EXT;
end;
//------------------------------------------------------------------------------------------
procedure CT_LoadFromFile(CT:TSynAutoComplete; fname:string);
begin
if FileExists(fname) then begin
try
CT.AutoCompleteList.LoadFromFile(fname);
except
end;
end;
end;
//------------------------------------------------------------------------------------------
function CreateCodeTemplate(HL:pTHighlighter):TSynAutoComplete;
var
fname :string;
begin
result:=nil;
if not Assigned(HL) then EXIT;
if not Assigned(HL^.CT) then begin
fname:=GetTemplateFileName(HL^.name);
HL^.CT:=TSynAutoComplete.Create(Application);
if FileExists(fname) then
CT_LoadFromFile(HL^.CT,fname);
end;
result:=HL^.CT;
end;
//------------------------------------------------------------------------------------------
procedure AddMemoToList(memo:TSynEdit);
var
CT :TSynAutoComplete;
HL :pTHighlighter;
begin
RemoveMemoFromList(memo);
HL:=GetHighlighterRec(memo.Highlighter);
if Assigned(HL) then begin
CT:=CreateCodeTemplate(HL);
if Assigned(CT) then
CT.AddEditor(memo);
end;
end;
//------------------------------------------------------------------------------------------
procedure RemoveMemoFromList(memo:TSynEdit);
var
i :integer;
begin
for i:=0 to HIGHLIGHTERS_COUNT-1 do begin
if Assigned(Highlighters[i].CT) then begin
Highlighters[i].CT.RemoveEditor(memo);
end;
end;
end;
//------------------------------------------------------------------------------------------
procedure DestroyAllTemplates;
var
i :integer;
begin
for i:=0 to HIGHLIGHTERS_COUNT-1 do begin
if Assigned(Highlighters[i].CT) then begin
Highlighters[i].CT.Free;
end;
end;
end;
//------------------------------------------------------------------------------------------
procedure ReloadTemplate(HL:TSynCustomHighlighter);
var
pHL :pTHighlighter;
begin
pHL:=GetHighlighterRec(HL);
if (Assigned(pHL) and Assigned(pHL^.CT)) then
CT_LoadFromFile(pHL^.CT, GetTemplateFileName(pHL^.name));
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.Init;
var
i :integer;
tpl :pTTemplate;
begin
for i:=0 to HIGHLIGHTERS_COUNT-1 do begin
tpl:=AllocMem(SizeOf(TTemplate));
tpl^.Code:=TStringList.Create;
tpl^.Name:=HighLighters[i].Name;
tpl^.HL:=HighLighters[i].HL;
if FileExists(GetTemplateFileName(tpl^.Name)) then
try
tpl.Code.LoadFromFile(GetTemplateFileName(tpl^.Name));
except
end;
cbHL.Items.AddObject(tpl^.Name,pointer(tpl));
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.Done;
var
i :integer;
tpl :pTTemplate;
begin
for i:=0 to cbHL.Items.Count-1 do begin
tpl:=pTTemplate(cbHL.Items.Objects[i]);
if Assigned(tpl) then begin
tpl.Code.Free;
FreeMem(tpl);
end;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.ApplyEditorOptions(HL:TSynCustomHighLighter);
begin
memo.Highlighter:=HL;
memo.BeginUpdate;
try
with EditorCfg do begin
memo.Options:=Options;
memo.ExtraLineSpacing:=ExtraLineSpacing;
memo.InsertCaret:=InsertCaret;
memo.OverwriteCaret:=OverwriteCaret;
memo.Font.Name:=FontName;
memo.Font.Size:=FontSize;
memo.TabWidth:=EditorCfg.BlockIndent;
if Assigned(HL) then begin
memo.SelectedColor.Foreground:=HL.Attribute[FindAttrIndex(ATTR_SELECTION_STR,HL)].Foreground;
memo.SelectedColor.Background:=HL.Attribute[FindAttrIndex(ATTR_SELECTION_STR,HL)].Background;
memo.RightEdgeColor:=HL.Attribute[FindAttrIndex(ATTR_RIGHTEDGE_STR,HL)].Foreground;
end;
end;
finally
memo.EndUpdate;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.ClearForm;
var
i :integer;
begin
lvSh.Items.BeginUpdate;
try
for i:=0 to lvSh.Items.Count-1 do
TStringList(lvSh.Items[i].Data).Free;
lvSh.Items.Clear;
memo.Lines.Clear;
memo.Modified:=FALSE;
finally
lvSh.Items.EndUpdate;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.TplToForm(tpl:pTTemplate);
var
n :integer;
ss :TStringList;
ShName :string;
ShDescr :string;
s :string;
divpos :integer;
procedure AddSh(Name,Descr:string; Code:TStringList);
begin
with lvSh.Items.Add do begin
Caption:=Name;
SubItems.Add(Descr);
Data:=Code;
end;
end;
begin
ClearForm;
if not Assigned(tpl) then EXIT;
n:=0;
while (n<tpl.Code.Count) do begin
ShName:='';
ShDescr:='';
s:=tpl.Code[n];
if (Length(s)>0) then begin
if (s[1]='[') then begin
divpos:=Pos('|',s);
if (divpos>0) then begin
ShName:=Trim(Copy(s,2,divpos-2));
ShDescr:=Trim(Copy(s,divpos+1,Length(s)));
while (Length(ShDescr)>0) and (ShDescr[Length(ShDescr)] in [']',' ',#09]) do
SetLength(ShDescr,Length(ShDescr)-1);
inc(n);
ss:=TStringList.Create;
// linije
while (n<tpl.Code.Count) do begin
s:=tpl.Code[n];
if (Length(s)>0) and (s[1]='[') then begin
AddSh(ShName,ShDescr,ss);
dec(n);
BREAK;
end else begin
ss.Add(s);
inc(n);
if (n=tpl.Code.Count) then begin
AddSh(ShName,ShDescr,ss);
end;
end;
end;
end;
end;
end;
inc(n);
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.FormToTpl(tpl:pTTemplate);
var
i,ii :integer;
ss :TStringList;
begin
if not Assigned(tpl) then EXIT;
tpl.Code.Clear;
if Assigned(lvSh.Selected) then
TStringList(lvSh.Selected.Data).Assign(memo.Lines);
if memo.Modified then
tpl^.Changed:=TRUE;
for i:=0 to lvSh.Items.Count-1 do begin
tpl.Code.Add(Format('[%s | %s]',[lvSh.Items[i].Caption,lvSh.Items[i].SubItems[0]]));
ss:=TStringList(lvSh.Items[i].Data);
// obriši prazne retke na kraju
for ii:=0 to ss.Count-1 do
ss[ii]:=TrimRight(ss[ii]);
while (ss.Count>0) and (Length(ss[ss.Count-1])=0) do
ss.Delete(ss.Count-1);
tpl.Code.AddStrings(ss);
tpl.Code.Add('');
end;
end;
//------------------------------------------------------------------------------------------
function TfmCodeTemplate.CurrTemplate:pTTemplate;
begin
result:=pTTemplate(cbHL.Items.Objects[cbHL.ItemIndex]);
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.SelectItem(n:integer);
begin
n:=Max(n,0);
n:=Min(n,lvSh.Items.Count-1);
if (n>-1) and Assigned(lvSh.Items[n]) then begin
lvSh.SetFocus;
lvSh.Selected:=lvSh.Items[n];
lvSh.ItemFocused:=lvSh.Selected;
lvSh.Selected.MakeVisible(FALSE);
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Buttons
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.btnAddClick(Sender: TObject);
var
fm :TfmCodeTemplateEdit;
begin
Application.CreateForm(TfmCodeTemplateEdit, fm);
fm.ShowModal;
if (fm.modal_result=mrOK) and (Length(fm.ShShortcut)>0) then begin
with lvSh.Items.Add do begin
Caption:=fm.ShShortcut;
SubItems.Add(fm.ShDescr);
Data:=TStringList.Create;
SelectItem(Index);
memo.SetFocus;
end;
CurrTemplate^.Changed:=TRUE;
end;
fm.Free;
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.btnEditClick(Sender: TObject);
var
fm :TfmCodeTemplateEdit;
begin
if not Assigned(lvSh.Selected) then EXIT;
Application.CreateForm(TfmCodeTemplateEdit, fm);
fm.ShShortcut:=lvSh.Selected.Caption;
fm.ShDescr:=lvSh.Selected.SubItems[0];
fm.ShowModal;
if (fm.modal_result=mrOK) and (Length(fm.ShShortcut)>0) then begin
with lvSh.Selected do begin
Caption:=fm.ShShortcut;
SubItems[0]:=fm.ShDescr;
SelectItem(Index);
end;
CurrTemplate^.Changed:=TRUE;
end;
fm.Free;
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.btnDeleteClick(Sender: TObject);
var
n :integer;
begin
if not Assigned(lvSh.Selected) then EXIT;
n:=lvSh.Selected.Index;
TStringList(lvSh.Selected.Data).Free;
lvSh.Selected.Delete;
CurrTemplate^.Changed:=TRUE;
SelectItem(n);
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.btnOKClick(Sender: TObject);
var
i :integer;
tpl :pTTemplate;
fname :string;
begin
FormToTpl(CurrTemplate);
// save templates
for i:=0 to cbHL.Items.Count-1 do begin
tpl:=pTTemplate(cbHL.Items.Objects[i]);
if Assigned(tpl) and (tpl^.Changed) then begin
try
fname:=GetTemplateFileName(tpl^.Name);
tpl.Code.SaveToFile(fname);
ReloadTemplate(tpl^.HL);
except
DlgErrorSaveFile(fname);
end;
end;
end;
Close;
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.btnCancelClick(Sender: TObject);
begin
Close;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.cbHLChange(Sender: TObject);
var
tpl :pTTemplate;
begin
FormToTpl(OldCurrTemplate);
tpl:=CurrTemplate;
ApplyEditorOptions(tpl^.HL);
TplToForm(tpl);
OldCurrTemplate:=tpl;
if (lvSh.Items.Count>0) then
lvSh.Selected:=lvSh.Items[0];
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.lvShSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
memo.Lines.BeginUpdate;
try
memo.Lines.Clear;
if Selected then begin
memo.Lines.AddStrings(TStringList(Item.Data));
memo.Tag:=integer(Item.Data);
end;
finally
memo.Lines.EndUpdate;
end;
memo.Modified:=FALSE;
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.memoChange(Sender: TObject);
begin
if not Assigned(lvSh.Selected) then EXIT;
TStringList(lvSh.Selected.Data).Assign(memo.Lines);
CurrTemplate^.Changed:=TRUE;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Form events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.FormCreate(Sender: TObject);
begin
mlApplyLanguageToForm(SELF,Name);
lvSh.Columns[0].Caption:=mlStr(ML_CODETEMPLATE_LV_NAME,'Name');
lvSh.Columns[1].Caption:=mlStr(ML_CODETEMPLATE_LV_DESCR,'Description');
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.FormShow(Sender: TObject);
var
i :integer;
begin
Init;
// selektiraj aktivni highlighter
cbHL.ItemIndex:=0;
i:=0;
while (i<HIGHLIGHTERS_COUNT) do begin
if (ActiveHighlighter=HighLighters[i].HL) then begin
cbHL.ItemIndex:=i;
BREAK;
end;
inc(i);
end;
OldCurrTemplate:=nil;
cbHLChange(SELF);
////////////////
SelectItem(0);
end;
//------------------------------------------------------------------------------------------
procedure TfmCodeTemplate.FormDestroy(Sender: TObject);
begin
ClearForm;
Done;
end;
//------------------------------------------------------------------------------------------
end.
|
unit Objekt.SepaFormat;
interface
uses
SysUtils, Classes;
type
TSepaFormat = class
private
public
constructor Create;
destructor Destroy; override;
function SepaDateToDateTime(aSepaDate: string): TDateTime;
function DateToSepaDate(aDateTime: TDateTime): string;
function SepaStrToInt(aValue: string): Integer;
function SepaCurrStrToCurr(aValue: string): Currency;
function SepaCurrToCurrStr(aValue: Currency): String;
function IsoDateTime: string;
end;
implementation
{ TSepaFormat }
constructor TSepaFormat.Create;
begin
end;
destructor TSepaFormat.Destroy;
begin
inherited;
end;
function TSepaFormat.IsoDateTime: string;
begin
Result := FormatDateTime('YYYY-MM-DD', now) + 'T' + FormatDateTime('hh:nn:ss', now);
end;
function TSepaFormat.SepaDateToDateTime(aSepaDate: string): TDateTime;
var
sJahr: string;
sMonat: string;
sTag: string;
sDatum: string;
begin
sJahr := copy(aSepaDate, 1, 4);
sMonat := copy(aSepaDate, 6,2);
sTag := copy(aSepaDate, 9,2);
sDatum := sTag + '.' + sMonat + '.' + sJahr;
if not TryStrToDate(sDatum, Result) then
Result := StrToDate('01.01.1999');
end;
function TSepaFormat.SepaCurrStrToCurr(aValue: string): Currency;
var
s: string;
begin
s := StringReplace(aValue, ',', '', [rfReplaceAll]);
s := StringReplace(aValue, '.', ',', [rfReplaceAll]);
if not TryStrToCurr(s, Result) then
Result := 0;
end;
function TSepaFormat.SepaCurrToCurrStr(aValue: Currency): String;
begin
Result := CurrToStr(aValue);
Result := StringReplace(Result, ',', '.', [rfReplaceAll]);
end;
function TSepaFormat.SepaStrToInt(aValue: string): Integer;
begin
if not TryStrToInt(aValue, Result) then
Result := 0;
end;
function TSepaFormat.DateToSepaDate(aDateTime: TDateTime): string;
var
Jahr: Word;
Monat: Word;
Tag: Word;
sMonat: string;
sTag: string;
begin
DecodeDate(aDateTime, Jahr, Monat, Tag);
sMonat := IntToStr(Monat);
sTag := IntToStr(Tag);
if Length(sTag) = 1 then
sTag := '0' + sTag;
if Length(sMonat) = 1 then
sMonat := '0' + sMonat;
Result := IntToStr(Jahr) + '-' + sMonat + '-' + sTag;
end;
end.
|
program InsertionSort;
{*
Insertion Sort
This method is widely used by card players. It is a stable sort, it leaves the order of items with equal keys unchanged.
The number of key comparisons in the i-th sift is at most i - 1, at least 1, and -assuming that all permutations of the n keys are equally probable- 1/2 in average.
C_min = n - 1
C_max = 1/2(n^2 + n) -1
The least numbers occur if the items are originally in order; the worst case occurs if the items are originally in reverse order.
O(n^2)
Divergence from Wirth:
Because there are two termination conditions, Wirth uses the "sentinel technique" of setting the current item in the iteration as a terminating value at index zero. This increases the index range by one. This seems unnecessarily complicated than simply checking both termination conditions and introduces a duplicate value in the data, which, itself could lead to subsequent errors.
*}
{$mode objfpc}{$H+}
uses {$IFDEF UNIX} {$IFDEF UseCThreads}
cthreads, {$ENDIF} {$ENDIF}
TypeUtils,
Classes { you can add units after this };
type
item = record
key: integer;
Value: string;
end;
type
itemArray = array of item;
type
index = integer;
{* ------------------------------------------------------------------ shuffle
The Fisher-Yates shuffle, in its original form, was described in 1938
by Ronald Fisher and Frank Yates in their book Statistical tables for
biological, agricultural and medical research.
The modern version of the Fisher-Yates shuffle, designed for computer use,
was introduced by Richard Durstenfeld in 1964 and popularized by
Donald E. Knuth in The Art of Computer Programming.
O(n)
*}
function shuffle(arr: itemArray): itemArray;
var
i, j: index;
r: integer;
a: item;
b: item;
begin
for i := (length(arr) - 1) downto 1 do
begin
r := random(i);
a := arr[i];
b := arr[r];
arr[i] := b;
arr[r] := a;
end;
Result := arr;
end;
{ -------------------------------------------------------- straightInsertion }
function straightinsertion(a: itemArray): itemArray;
var
i, j: index;
var
x: item;
begin
for i := 1 to (length(a) - 1) do
begin
x := a[i];
j := i - 1;
while ((j >= 0) and (a[j].key >= x.key)) do
begin
a[j + 1] := a[j];
j := j - 1;
end;
a[j + 1] := x;
end;
Result := a;
end;
var
a: array[0..9] of item = ((key: 0; Value: 'A'), (key: 1; Value: 'B'), (key: 2;
Value: 'C'), (key: 3; Value: 'D'), (key: 4; Value: 'E'), (key: 5;
Value: 'F'), (key: 6; Value: 'G'), (key: 7; Value: 'H'), (key: 8;
Value: 'I'), (key: 9; Value: 'J'));
b: itemArray;
begin
b := shuffle(a);
Writeln(ToStr(b, TypeInfo(b)));
b := straightinsertion(b);
Writeln(ToStr(b, TypeInfo(b)));
end.
|
{*****************************************************************}
{ ceosclient is part of Ceos middleware/n-tier JSONRPC components }
{ }
{ Beta version }
{ }
{ 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. }
{ }
{ by Jose Benedito - josebenedito@gmail.com }
{ www.jbsolucoes.net }
{*****************************************************************}
unit ceosclient;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics,
fpjson, jsonparser, fphttpclient, ceostypes;
type
{ TCeosClient }
TCeosClient = class(TComponent)
private
FHost: string;
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Call(AMethod: string; Args: array of variant; AID: integer): string; overload;
function Call(ARequest: TCeosRequestContent): string; overload;
function JSONCall(AMethod: string; Args: array of variant; AID: integer): TJSONObject;
function JSONCall(ARequest: TCeosRequestContent): TJSONObject; overload;
published
property Host: string read FHost write FHost;
{ Published declarations }
end;
procedure Register;
implementation
uses ceosconsts;
procedure Register;
begin
{$I ceosclient_icon.lrs}
RegisterComponents('Ceos',[TCeosClient]);
end;
{ TCeosClient }
constructor TCeosClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TCeosClient.Destroy;
begin
inherited Destroy;
end;
function TCeosClient.Call(AMethod: string; Args: array of variant; AID: integer): string;
var
response: TMemoryStream;
joContent: TJSONObject;
joArgs: TJSONArray;
slRes: TStringList;
httpcli: TFPHTTPClient;
begin
try
httpcli := TFPHTTPClient.Create(self);
slRes := TStringList.Create;
response := TMemoryStream.Create;
joContent := TJSONObject.Create;
joContent.Add('jsonrpc', JSONRPC_VERSION);
joContent.Add('method', AMethod);
joArgs := GetJSONArray(Args);
joContent.Add('params', joArgs);
joContent.Add('id',AID);
httpcli.FormPost(Host,joContent.AsJSON, response);
if (response <> nil) then
begin
response.Seek(0, soFromBeginning);
slRes.LoadFromStream(response);
Result := slRes.text;
end;
finally
joContent.free;
freeandnil(response);
freeandnil(slRes);
freeandnil(httpcli);
end;
end;
function TCeosClient.Call(ARequest: TCeosRequestContent): string;
var
response: TMemoryStream;
slRes: TStringList;
httpcli: TFPHTTPClient;
begin
try
httpcli := TFPHTTPClient.Create(self);
slRes := TStringList.Create;
response := TMemoryStream.Create;
httpcli.FormPost(Host,ARequest.AsJSON, response);
if (response <> nil) then
begin
response.Seek(0, soFromBeginning);
slRes.LoadFromStream(response);
Result := slRes.text;
end;
finally
freeandnil(response);
freeandnil(slRes);
freeandnil(httpcli);
end;
end;
function TCeosClient.JSONCall(AMethod: string; Args: array of variant; AID: integer): TJSONObject;
begin
Result := (TJSONParser.Create(Call(AMethod,Args,AID)).Parse as TJSONObject);
end;
function TCeosClient.JSONCall(ARequest: TCeosRequestContent): TJSONObject;
begin
Result := (TJSONParser.Create(Call(ARequest)).Parse as TJSONObject);
end;
end.
|
{*******************************************************************************
* uEnumControl *
* *
* Библиотека компонентов для работы с формой редактирования (qFControls) *
* Работа со списоком (TqFEnumControl) *
* Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uEnumControl;
interface
uses
SysUtils, Classes, Controls, uFControl, StdCtrls, Graphics, uLabeledFControl, Registry;
type
TqFEnumControl = class(TqFLabeledControl)
private
FOldOnEnterEvent: TNotifyEvent;
FCombo: TComboBox;
FValues: array of Integer;
procedure CloseCombo(Sender: TObject);
protected
procedure PrepareRest; override;
procedure SetValue(Val: Variant); override;
function GetValue: Variant; override;
procedure Loaded; override;
function GetItems: TStrings;
procedure SetItems(const ValItems: TStrings);
procedure SetValuesString(ValStr: string);
function GetValuesString: string;
function GetKeyDown: TKeyEvent;
procedure SetKeyDown(e: TKeyEvent);
function GetKeyUp: TKeyEvent;
procedure SetKeyUp(e: TKeyEvent);
public
constructor Create(AOwner: TComponent); override;
function Check: string; override;
procedure Highlight(HighlightOn: Boolean); override;
procedure ShowFocus; override;
function ToString: string; override;
procedure Block(Flag: Boolean); override;
procedure LoadFromRegistry(reg: TRegistry); override; // vallkor
procedure SaveIntoRegistry(reg: TRegistry); override; // vallkor
published
property Items: TStrings read GetItems write SetItems;
property ValuesString: string read GetValuesString write SetValuesString;
property OnKeyDown: TKeyEvent read GetKeyDown write SetKeyDown;
property OnKeyUp: TKeyEvent read GetKeyUp write SetKeyUp;
end;
procedure Register;
{$R *.res}
implementation
uses qFStrings, Variants, qFTools;
function TqFEnumControl.GetKeyDown: TKeyEvent;
begin
Result := FCombo.OnKeyDown;
end;
procedure TqFEnumControl.SetKeyDown(e: TKeyEvent);
begin
FCombo.OnKeyDown := e;
end;
function TqFEnumControl.GetKeyUp: TKeyEvent;
begin
Result := FCombo.OnKeyUp;
end;
procedure TqFEnumControl.SetKeyUp(e: TKeyEvent);
begin
FCombo.OnKeyUp := e;
end;
function TqFEnumControl.Check: string;
begin
if Required then
if VarIsNull(Value) then
Check := qFFieldIsEmpty + '"' + DisplayName + '"!'
else
Check := ''
else
Check := '';
end;
procedure TqFEnumControl.CloseCombo(Sender: TObject);
var
ctrl: TControl;
begin
// qFErrorDialog(qFControlBlocked);
if (Sender is TControl) then
begin
ctrl := Sender as TControl;
if (ctrl.Parent <> nil) then
qFSafeFocusControl(ctrl.Parent);
end;
end;
procedure TqFEnumControl.Block(Flag: Boolean);
begin
inherited Block(Flag);
if Flag then
begin
FOldOnEnterEvent := FCombo.OnEnter;
FCombo.OnEnter := CloseCombo;
FCombo.Color := qFBlockedColor;
end
else
begin
FCombo.OnEnter := FOldOnEnterEvent;
FCombo.Color := FOldColor;
end;
end;
function TqFEnumControl.GetItems: TStrings;
begin
Result := FCombo.Items;
end;
procedure TqFEnumControl.SetItems(const ValItems: TStrings);
var
cnt, val, i: Integer;
begin
FCombo.Items := ValItems;
cnt := Length(FValues);
SetLength(FValues, ValItems.Count);
if Length(FValues) > cnt then
begin
if cnt = 0 then
val := 0
else
val := FValues[cnt - 1];
for i := cnt to High(FValues) do
FValues[i] := val + i - cnt + 1;
end;
end;
procedure TqFEnumControl.Highlight(HighlightOn: Boolean);
begin
inherited Highlight(HighlightOn);
if HighlightOn then
FCombo.Color := qFHighlightColor
else
if FOldColor <> 0 then
FCombo.Color := FOldColor;
Repaint;
end;
procedure TqFEnumControl.ShowFocus;
begin
inherited ShowFocus;
qFSafeFocusControl(FCombo);
end;
procedure TqFEnumControl.SetValuesString(ValStr: string);
var
i, val, p: Integer;
s, numstr: string;
begin
i := 0;
val := 0;
s := ValStr;
while s <> '' do
begin
p := Pos(',', s);
if p = 0 then
begin
numStr := s;
s := '';
end
else
begin
numstr := Copy(s, 1, p - 1);
s := Copy(s, p + 1, Length(s) - p);
end;
val := StrToIntDef(Trim(numStr), val + 1);
if i > High(FValues) then
SetLength(FValues, i + 1);
FValues[i] := val;
inc(i);
end;
end;
function TqFEnumControl.GetValuesString: string;
var
i: Integer;
begin
Result := '';
for i := 0 to High(FValues) do
if Result = '' then
Result := Result + IntToStr(FValues[i])
else
Result := Result + ',' + IntToStr(FValues[i]);
end;
function TqFEnumControl.ToString: string;
begin
if VarIsNull(Value) then
Result := 'Null'
else
Result := IntToStr(Value);
end;
procedure TqFEnumControl.SetValue(Val: Variant);
var
i: Integer;
begin
inherited SetValue(Val);
if VarIsNull(Val) then
FCombo.ItemIndex := -1
else
begin
for i := 0 to High(FValues) do
if FValues[i] = Val then
FCombo.ItemIndex := i;
end;
end;
function TqFEnumControl.GetValue: Variant;
begin
if (FCombo.ItemIndex < 0) or (FCombo.ItemIndex > High(FValues)) then
Result := Null
else
Result := FValues[FCombo.ItemIndex];
end;
constructor TqFEnumControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCombo := TComboBox.Create(Self);
FCombo.Parent := Self;
FCombo.Style := csDropDownList;
SetLength(FValues, 0);
PrepareRest;
FOldColor := FCombo.Color;
end;
procedure TqFEnumControl.Loaded;
begin
FCombo.OnChange := FOnChange;
inherited Loaded;
end;
procedure TqFEnumControl.PrepareRest;
begin
FCombo.Width := Width - Interval - 3;
FCombo.Height := qFDefaultHeight;
FCombo.Left := Interval;
FCombo.Top := (Height - FCombo.Height) div 2;
FCombo.Repaint;
end;
procedure Register;
begin
RegisterComponents('qFControls', [TqFEnumControl]);
end;
procedure TqFEnumControl.LoadFromRegistry(reg: TRegistry); // vallkor
begin
inherited LoadFromRegistry(reg);
Value := Reg.ReadInteger('Value');
end;
procedure TqFEnumControl.SaveIntoRegistry(reg: TRegistry); // vallkor
begin
inherited SaveIntoRegistry(reg);
Reg.WriteInteger('Value', Value);
end;
end.
|
unit fre_feed_client;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(§LIC_END)
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,fre_base_client,FOS_TOOL_INTERFACES,FRE_APS_INTERFACE,FRE_DB_INTERFACE,fre_dbbusiness,fre_system;
type
{ TFRE_SAMPLE_FEED_CLIENT }
TFRE_SAMPLE_FEED_CLIENT=class(TFRE_BASE_CLIENT)
private
FEED_Timer : IFRE_APSC_TIMER;
FFeeding : Boolean;
FFeedAppClass : TFRE_DB_String;
FFeedAppUid : TFRE_DB_GUid;
public
procedure MySessionEstablished (const chanman : IFRE_APSC_CHANNEL_MANAGER); override;
procedure MySessionDisconnected (const chanman : IFRE_APSC_CHANNEL_MANAGER); override;
procedure QueryUserPass (out user, pass: string); override;
procedure RegisterRemoteMethods (var remote_method_array : TFRE_DB_RemoteReqSpecArray); override;
procedure MyInitialize ; override;
procedure MyFinalize ; override;
procedure GenerateFeedDataTimer (const TIM : IFRE_APSC_TIMER ; const flag1,flag2 : boolean); // Timout & CMD Arrived & Answer Arrived
procedure MyConnectionTimer ; override;
procedure MyRegisterClasses ; override;
procedure WorkRemoteMethods (const rclassname,rmethodname : TFRE_DB_NameType ; const command_id : Qword ; const input : IFRE_DB_Object ; const cmd_type : TFRE_DB_COMMANDTYPE); override;
function ListDirLevel (const basepath : string):IFRE_DB_Object;
function GetFileDirInfo (const fileid : string):IFRE_DB_Object;
procedure SubfeederEvent (const id:string; const dbo:IFRE_DB_Object);override;
published
procedure REM_TestMethod (const command_id : Qword ; const input : IFRE_DB_Object ; const cmd_type : TFRE_DB_COMMANDTYPE);
procedure REM_TestTimeout (const command_id : Qword ; const input : IFRE_DB_Object ; const cmd_type : TFRE_DB_COMMANDTYPE);
procedure REM_TestError (const command_id : Qword ; const input : IFRE_DB_Object ; const cmd_type : TFRE_DB_COMMANDTYPE);
end;
implementation
procedure TFRE_SAMPLE_FEED_CLIENT.MySessionEstablished(const chanman: IFRE_APSC_CHANNEL_MANAGER);
begin
inherited; // Create and Activate Session Channel Timer
if Get_AppClassAndUid('TFRE_DB_TEST_APP',FFeedAppClass,FFeedAppUid) then begin
FFeeding := True;
end;
FEED_Timer := chanman.AddChannelManagerTimer('FEED_'+chanman.GetID,2000,@GenerateFeedDataTimer,true); // Beside the "normal 1 sec" Timer a 5 sec timer in the channel context
writeln('Generated Feedtimer ',FEED_Timer.cs_GetID);
end;
procedure TFRE_SAMPLE_FEED_CLIENT.MySessionDisconnected(const chanman: IFRE_APSC_CHANNEL_MANAGER);
begin
writeln('FINALIZING FEED FROM CM_'+chanman.GetID);
FEED_Timer.cs_Finalize;
FFeeding := false;
inherited;
end;
procedure TFRE_SAMPLE_FEED_CLIENT.QueryUserPass(out user, pass: string);
begin
user := cFRE_Feed_User;
pass := cFRE_Feed_Pass;
end;
procedure TFRE_SAMPLE_FEED_CLIENT.RegisterRemoteMethods(var remote_method_array: TFRE_DB_RemoteReqSpecArray);
var base_idx : NativeInt;
begin
inherited;
// THIS IS A SAMPLE FOR NON-STANDARD REMOTE REGISTRATIONS (non REM_* methods)
// add virtual methods
base_idx := Length(remote_method_array);
SetLength(remote_method_array,base_idx+2);
with remote_method_array[base_idx] do
begin
classname := 'SAMPLEFEEDER';
methodname := 'BROWSEPATH';
invokationright := ''; //unsafe
end;
with remote_method_array[base_idx+1] do
begin
classname := 'SAMPLEFEEDER';
methodname := 'GETFILEDIRINFO';
invokationright := ''; //unsafe
end;
end;
procedure TFRE_SAMPLE_FEED_CLIENT.MyInitialize;
begin
//GFRE_DBI.Initialize_Extension_Objects;
FREDB_LoadMimetypes('');
if cFRE_SUBFEEDER_IP='' then
AddSubFeederEventViaUX('samplesub')
else
AddSubFeederEventViaTCP(cFRE_SUBFEEDER_IP,'44100','samplesub');
end;
procedure TFRE_SAMPLE_FEED_CLIENT.MyFinalize;
begin
end;
procedure TFRE_SAMPLE_FEED_CLIENT.GenerateFeedDataTimer(const TIM: IFRE_APSC_TIMER; const flag1, flag2: boolean);
var vmo : IFRE_DB_Object;
begin
writeln('SEND SUPPRESSED');
exit;
if FFeeding then
begin
try
vmo := GFRE_DBI.NewObject;
vmo.Field('LIVE STATUS FEED').AsString := 'LSF_0.0.1';
vmo.Field('TIMESTAMP').AsDateTimeUTC := GFRE_DT.Now_UTC;
vmo.Field('SAMPLE_VALUE').AsInt32 := Random(1000)-500;
SendServerCommand(FFeedAppClass,'RAW_DATA_FEED',TFRE_DB_GUIDArray.Create(FFeedAppUid),vmo);
writeln('LIVE UPDATE SENT! ' , GFRE_DT.Now_UTC);
except on e:exception do begin
writeln('FEED EXCEPTION : ',e.Message);
end;end;
end;
end;
procedure TFRE_SAMPLE_FEED_CLIENT.MyConnectionTimer;
begin
inherited;
end;
procedure TFRE_SAMPLE_FEED_CLIENT.MyRegisterClasses;
begin
inherited;
fre_dbbusiness.Register_DB_Extensions;
//fre_hal_schemes.Register_DB_Extensions;
end;
procedure TFRE_SAMPLE_FEED_CLIENT.WorkRemoteMethods(const rclassname, rmethodname: TFRE_DB_NameType; const command_id: Qword; const input: IFRE_DB_Object; const cmd_type: TFRE_DB_COMMANDTYPE);
var reply_data : IFRE_DB_Object;
begin
// THIS IS A SAMPLE FOR NON-STANDARD REMOTE REGISTRATIONS (non REM_* methods)
GFRE_LOG.Log('>TRY INVOKE '+rclassname+'.'+rmethodname,' CID='+inttostr(command_id));
if (rclassname='SAMPLEFEEDER') and (rmethodname='BROWSEPATH') then
begin
reply_data := ListDirLevel(input.Field('level').AsString);
input.Finalize;
GFRE_LOG.Log('REPLY ON REQUEST SAMPLEFEEDER.BROWSEPATH ','FEEDER');
AnswerSyncCommand(command_id,reply_data);
end
else
if (rclassname='SAMPLEFEEDER') and (rmethodname='GETFILEDIRINFO') then
begin
reply_data := GetFileDirInfo(input.Field('fileid').AsString);
input.Finalize;
GFRE_LOG.Log('REPLY ON REQUEST SAMPLEFEEDER.GETFILEDIRINFO ','FEEDER');
AnswerSyncCommand(command_id,reply_data);
end
else
inherited;
GFRE_LOG.Log('<TRY INVOKE '+rclassname+'.'+rmethodname,' CID='+inttostr(command_id));
end;
function TFRE_SAMPLE_FEED_CLIENT.ListDirLevel(const basepath: string): IFRE_DB_Object;
var Info : TSearchRec;
//entry : TFRE_DB_FS_ENTRY;
count : NativeInt;
begin
result := GFRE_DBI.NewObject;
count := 0;
If FindFirst (basepath+'*',faAnyFile and faDirectory,Info)=0 then
Repeat
With Info do
begin
if (name='.') or (name='..') then
Continue;
//entry := TFRE_DB_FS_ENTRY.CreateForDB;
//entry.SetProperties(name,(Attr and faDirectory) <> faDirectory,Size,mode,Time);
//result.Field(inttostr(count)).AsObject := entry;
inc(count);
end;
Until FindNext(info)<>0;
FindClose(Info);
end;
function TFRE_SAMPLE_FEED_CLIENT.GetFileDirInfo(const fileid: string): IFRE_DB_Object;
var
Info : TSearchRec;
//entry : TFRE_DB_FS_ENTRY;
begin
result := GFRE_DBI.NewObject;
If FindFirst(fileid,faAnyFile and faDirectory,Info)=0 then
With Info do
begin
//entry := TFRE_DB_FS_ENTRY.CreateForDB;
//entry.SetProperties(name,(Attr and faDirectory) <> faDirectory,Size,mode,Time);
//result.Field('info').AsObject := entry;
end;
FindClose(Info);
end;
procedure TFRE_SAMPLE_FEED_CLIENT.SubfeederEvent(const id: string; const dbo: IFRE_DB_Object);
begin
writeln('GOT FROM SF ',id);
writeln(dbo.DumpToString());
end;
procedure TFRE_SAMPLE_FEED_CLIENT.REM_TestMethod(const command_id: Qword; const input: IFRE_DB_Object; const cmd_type: TFRE_DB_COMMANDTYPE);
var reply_data : IFRE_DB_Object;
begin
reply_data := GFRE_DBI.NewObject;
reply_data.Field('Hello').AsString := 'World!';
reply_data.Field('SampleField').AsInt16 := 12345;
AnswerSyncCommand(command_id,reply_data);
input.Finalize;
end;
procedure TFRE_SAMPLE_FEED_CLIENT.REM_TestTimeout(const command_id: Qword; const input: IFRE_DB_Object; const cmd_type: TFRE_DB_COMMANDTYPE);
begin
writeln('>> A METHOD THAT TIMES OUT WITHOUT SENDING ANSWER');
input.Finalize;
end;
procedure TFRE_SAMPLE_FEED_CLIENT.REM_TestError(const command_id: Qword; const input: IFRE_DB_Object; const cmd_type: TFRE_DB_COMMANDTYPE);
begin
writeln('CALLED TestError Method, excepting ...');
raise EFRE_DB_Exception.Create(edb_ERROR,'ARBITRARY TEST FAILURE');
end;
initialization
end.
|
unit ThreeDPointList;
interface
uses BasicDataTypes;
type
P3DPosition = ^T3DPosition;
T3DPosition = record
x,y,z : integer;
Next : P3DPosition;
end;
TGetPositionFunction = function (var _x,_y,_z : integer): boolean of object;
TAddPositionMethod = procedure (_x,_y,_z: integer) of object;
TDeletePositionMethod = procedure of object;
TGetUniquePositionMethod = function: integer of object;
C3DPointList = class
private
Start,Last,Active : P3DPosition;
FullList: aint32;
StartPos,LastPos: integer;
procedure Reset;
public
GetPosition: TGetPositionFunction;
Add: TAddPositionMethod;
Delete: TDeletePositionMethod;
GoToFirstElement: TDeletePositionMethod;
GoToNextElement: TDeletePositionMethod;
GetX, GetY, GetZ: TGetUniquePositionMethod;
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// Add
procedure AddTraditional (_x,_y,_z : integer);
procedure AddWithFixedRAM (_x,_y,_z : integer);
procedure DeleteTraditional;
procedure DeleteFixedRAM;
// Delete
procedure Clear;
procedure ClearFixedRAM;
// Sets
procedure UseSmartMemoryManagement(_value: boolean);
procedure UseFixedRAM(_Value: integer);
// Gets
function GetPositionTraditional (var _x,_y,_z : integer): boolean;
function GetPositionWithDeletion (var _x,_y,_z : integer): boolean;
function GetPositionWithFixedRAM (var _x,_y,_z : integer): boolean;
function GetXTraditional: integer;
function GetXWithFixedRAM: integer;
function GetYTraditional: integer;
function GetYWithFixedRAM: integer;
function GetZTraditional: integer;
function GetZWithFixedRAM: integer;
// Misc
procedure GoToFirstElementTraditional;
procedure GoToFirstElementFixedRAM;
procedure GoToNextElementTraditional;
procedure GoToNextElementFixedRAM;
end;
implementation
constructor C3DPointList.Create;
begin
Reset;
UseSmartMemoryManagement(false);
end;
destructor C3DPointList.Destroy;
begin
Clear;
ClearFixedRAM;
inherited Destroy;
end;
procedure C3DPointList.Reset;
begin
Start := nil;
Last := nil;
Active := nil;
end;
// Add
procedure C3DPointList.AddTraditional (_x,_y,_z : integer);
var
NewPosition : P3DPosition;
begin
New(NewPosition);
NewPosition^.x := _x;
NewPosition^.y := _y;
NewPosition^.z := _z;
NewPosition^.Next := nil;
if Start <> nil then
begin
Last^.Next := NewPosition;
end
else
begin
Start := NewPosition;
Active := Start;
end;
Last := NewPosition;
end;
procedure C3DPointList.AddWithFixedRAM (_x,_y,_z : integer);
begin
if (LastPos+2) < High(FullList) then
begin
FullList[LastPos] := _x;
FullList[LastPos+1] := _y;
FullList[LastPos+2] := _z;
end;
inc(LastPos,3);
end;
// Delete
procedure C3DPointList.DeleteTraditional;
var
Previous : P3DPosition;
begin
if Active <> nil then
begin
Previous := Start;
if Active = Start then
begin
Start := Start^.Next;
end
else
begin
while Previous^.Next <> Active do
begin
Previous := Previous^.Next;
end;
Previous^.Next := Active^.Next;
if Active = Last then
begin
Last := Previous;
end;
end;
Dispose(Active);
end;
end;
procedure C3DPointList.DeleteFixedRAM;
begin
// do nothing.
end;
procedure C3DPointList.Clear;
var
Garbage : P3DPosition;
begin
Active := Start;
while Active <> nil do
begin
Garbage := Active;
Active := Active^.Next;
dispose(Garbage);
end;
end;
procedure C3DPointList.ClearFixedRAM;
begin
SetLength(FullList,0);
StartPos := 0;
LastPos := 0;
end;
// Sets
procedure C3DPointList.UseSmartMemoryManagement(_value: boolean);
begin
ClearFixedRAM;
if _Value then
GetPosition := GetPositionWithDeletion
else
GetPosition := GetPositionTraditional;
Add := AddTraditional;
Delete := DeleteTraditional;
GoToFirstElement := GoToFirstElementTraditional;
GoToNextElement := GoToNextElementTraditional;
GetX := GetXTraditional;
GetY := GetYTraditional;
GetZ := GetZTraditional;
end;
procedure C3DPointList.UseFixedRAM(_Value: integer);
begin
if (_Value > 0) then
begin
Clear;
SetLength(FullList,_Value*3);
GetPosition := GetPositionWithFixedRAM;
Add := AddWithFixedRAM;
Delete := DeleteFixedRAM;
GoToFirstElement := GoToFirstElementFixedRAM;
GoToNextElement := GoToNextElementFixedRAM;
GetX := GetXWithFixedRAM;
GetY := GetYWithFixedRAM;
GetZ := GetZWithFixedRAM;
StartPos := 0;
LastPos := 0;
end;
end;
// Gets
function C3DPointList.GetPositionTraditional (var _x,_y,_z : integer): boolean;
begin
if Active <> nil then
begin
_x := Active^.x;
_y := Active^.y;
_z := Active^.z;
Result := true;
end
else
begin
Result := false;
end;
end;
function C3DPointList.GetPositionWithDeletion (var _x,_y,_z : integer): boolean;
begin
if Start <> nil then
begin
_x := Start^.x;
_y := Start^.y;
_z := Start^.z;
Active := Start;
Start := Start^.Next;
Dispose(Active);
Active := Start;
Result := true;
end
else
begin
Result := false;
end;
end;
function C3DPointList.GetPositionWithFixedRAM (var _x,_y,_z : integer): boolean;
begin
if (StartPos < LastPos) and (StartPos < High(FullList)) then
begin
_x := FullList[StartPos];
_y := FullList[StartPos+1];
_z := FullList[StartPos+2];
inc(StartPos,3);
Result := true;
end
else
begin
Result := false;
end;
end;
function C3DPointList.GetXTraditional: integer;
begin
Result := 0;
if Active <> nil then
begin
Result := Active^.x;
end;
end;
function C3DPointList.GetXWithFixedRAM: integer;
begin
if StartPos < LastPos then
begin
Result := FullList[StartPos];
end
else
begin
Result := 0;
end;
end;
function C3DPointList.GetYTraditional: integer;
begin
Result := 0;
if Active <> nil then
begin
Result := Active^.y;
end;
end;
function C3DPointList.GetYWithFixedRAM: integer;
begin
if StartPos < LastPos then
begin
Result := FullList[StartPos+1];
end
else
begin
Result := 0;
end;
end;
function C3DPointList.GetZTraditional: integer;
begin
Result := 0;
if Active <> nil then
begin
Result := Active^.z;
end;
end;
function C3DPointList.GetZWithFixedRAM: integer;
begin
if StartPos < LastPos then
begin
Result := FullList[StartPos+2];
end
else
begin
Result := 0;
end;
end;
// Misc
procedure C3DPointList.GoToNextElementTraditional;
begin
if Active <> nil then
begin
Active := Active^.Next;
end
end;
procedure C3DPointList.GoToNextElementFixedRAM;
begin
inc(StartPos,3);
end;
procedure C3DPointList.GoToFirstElementTraditional;
begin
Active := Start;
end;
procedure C3DPointList.GoToFirstElementFixedRAM;
begin
StartPos := 0;
end;
end.
|
unit PlayerOutputThread;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ThreadQueue, Pipes, math;
type
{ TPlayerOutputThread }
TPlayerOutputThread = class(TThread)
private
FOutputStream: TInputPipeStream;
FQueue: TThreadQueue; // // queue of eoln-terminated pstrings
protected
procedure Execute; override; // try the best to read from FOutputStream
public
function CanReadLn: Boolean;
function ReadLn: String;
constructor Create(AOutputStream: TInputPipeStream);
destructor Destroy; override;
end;
implementation
{ TPlayerOutputThread }
procedure TPlayerOutputThread.Execute;
var
Current: String = '';
procedure ExtendCurrent;
var
t0: Integer;
Buffer: String[192];
begin
t0 := Min(192, FOutputStream.NumBytesAvailable);
Buffer[0] := Char(FOutputStream.Read(Buffer[1], t0));
Current += Buffer;
end;
function FetchLine: String;
var
t0: Integer;
begin
t0 := Pos(LineEnding, Current);
if t0 = 0 then
exit('');
t0 += Length(LineEnding)-1;
Result := LeftStr(Current, t0);
Delete(Current, 1, t0);
end;
var
Item: String = '';
begin
repeat
if FOutputStream.NumBytesAvailable > 0 then
begin
ExtendCurrent;
repeat
Item := FetchLine;
if Item = '' then
break;
FQueue.Push(NewStr(Item));
until False;
end
else
Sleep(20);
until Terminated;
end;
function TPlayerOutputThread.CanReadLn: Boolean;
begin
Result := Assigned(Self) and (FQueue.Count > 0);
end;
function TPlayerOutputThread.ReadLn: String;
var
Item: PString;
begin
Item := PString(FQueue.Front); FQueue.Pop;
Result := Item^;
if RightStr(Result, Length(LineEnding)) = LineEnding then
Result := LeftStr(Result, Length(Result) - Length(LineEnding));
UniqueString(Result);
DisposeStr(Item);
end;
constructor TPlayerOutputThread.Create(AOutputStream: TInputPipeStream);
begin
inherited Create(False);
FQueue := TThreadQueue.Create;
FOutputStream := AOutputStream;
FreeOnTerminate := False;
end;
destructor TPlayerOutputThread.Destroy;
begin
FreeAndNil(FQueue);
inherited Destroy;
end;
end.
|
program FileDialogTests;
//{IFNDEF UNIX} {r GameLauncher.res} {ENDIF}
uses
Math, SysUtils,
sgUtils,
sgUserInterface, sgAudio, sgGraphics, sgResources, sgText, sgGeometry, sgTypes, sgImages, sgInput;
procedure InitInterface();
begin
DrawGUIAsVectors(true);
GUISetForegroundColor(ColorWhite);
end;
procedure Main();
var
lst: GUIList;
begin
OpenAudio();
OpenGraphicsWindow('File Dialog Test', 800, 600);
InitInterface();
ShowOpenDialog(fdFiles);
repeat
ProcessEvents();
ClearScreen(ColorBlack);
FillRectangle(ColorRed, 0,0, 50, 50);
FillRectangle(ColorGreen, 50,0, 50, 50);
FillRectangle(ColorBlue, 100, 0, 50, 50);
DrawInterface();
UpdateInterface();
DrawFramerate(0,0);
RefreshScreen();
if KeyTyped(sKey) then TakeScreenShot('FileDialogTest');
until WindowCloseRequested() or DialogComplete() or DialogCancelled();
WriteLn(DialogPath());
ReleaseAllResources();
CloseAudio();
end;
begin
Main();
end.
|
unit uMap;
interface
uses LCLIntf, LCLType, SysUtils, Forms, Classes, dialogs,
Graphics, FileUtil, IntfGraphics,
uFrmMessageBox, uLanguage, uColor16bits;
const
MAX_NUM_IMAGES = 999;
FPG_NULL = 255;
FPG1 = 0;
FPG8_DIV2 = 1;
FPG16 = 2;
FPG16_CDIV = 3;
FPG24 = 4;
FPG32 = 5;
type
file_str_map = record
Magic : array [0 .. 2] of char;
MSDOSEnd : array [0 .. 3] of byte;
Version : byte;
width : word;
height : word;
code : dword;
description : array [0 .. 31] of char;
palette : array [0 .. 767] of byte;
gamma : array [0 .. 575] of byte;
ncpoints : Word;
cpoints : array[0..high(Word)*2] of Word;
//maximun value of a Word 65535, need 1 word for x and other word for y.
bmp : TBitMap;
end;
function MAP_Load(filename: string; var ncpoints:word; cpoints:PWord) : TBitmap;
function create_hpal (palette_ar : array of byte) : HPALETTE;
function loadDataBitmap(var f : TStream; palette : PByte ; width , height : longint; bytes_per_pixel : word; is_cdiv: boolean): TBitmap;
function MAP_test(filename :String):Boolean;
implementation
function create_hpal (palette_ar : array of byte) : HPALETTE;
var
pal : PLogPalette;
i : LongInt;
begin
pal := nil;
try
GetMem(pal, sizeof(TLogPalette) + sizeof(TPaletteEntry) * 255);
pal^.palVersion := $300;
pal^.palNumEntries := 256;
for i := 0 to 255 do
begin
pal^.palPalEntry[i].peRed := palette_ar[(i*3) ];
pal^.palPalEntry[i].peGreen := palette_ar[(i*3) + 1];
pal^.palPalEntry[i].peBlue := palette_ar[(i*3) + 2];
pal^.palPalEntry[i].peFlags := 0;
end;
create_hpal := CreatePalette(pal^);
finally
FreeMem(pal);
end;
end;
function loadDataBitmap(var f : TStream; palette : PByte ; width , height : longint; bytes_per_pixel : word; is_cdiv: boolean): TBitmap;
var
lazBMP : TLazIntfImage;
p_bytearray: PByteArray;
i, j, k, z: integer;
byte_line: array [0 .. 16383] of byte;
lenLineBits: integer;
lineBit: byte;
begin
// Se crea la imagen resultante
result := TBitMap.Create;
result.PixelFormat := pf32bit;
result.SetSize(Width, Height);
// Para usar en caso de un bit
if bytes_per_pixel = 0 then
begin
lenLineBits := Width div 8;
if (Width mod 8) <> 0 then
lenLineBits := lenLineBits + 1;
end;
lazBMP := result.CreateIntfImage;
for k := 0 to result.Height - 1 do
begin
p_bytearray := lazBMP.GetDataLineStart(k);
case bytes_per_pixel of
0:
begin
for j := 0 to lenLineBits - 1 do
begin
f.Read(lineBit, 1);
for i := 0 to 7 do
begin
z := (j * 8) + i;
if z < result.Width then
begin
if (lineBit and 128) = 128 then
begin
p_bytearray^[z * 4] := 255;
p_bytearray^[(z * 4) + 1] := 255;
p_bytearray^[(z * 4) + 2] := 255;
p_bytearray^[(z * 4) + 3] := 255;
end
else
begin
p_bytearray^[z * 4] := 0;
p_bytearray^[(z * 4) + 1] := 0;
p_bytearray^[(z * 4) + 2] := 0;
p_bytearray^[(z * 4) + 3] := 0;
end;
lineBit := lineBit shl 1;
end
else
break;
end;
end;
end;
1:
begin
f.Read(byte_line, result.Width * bytes_per_pixel);
for j:=0 to result.Width -1 do
begin
p_bytearray^[j*4] := palette[byte_line[j] * 3 + 2];
p_bytearray^[j*4+1] := palette[byte_line[j] * 3 + 1];
p_bytearray^[j*4+2] := palette[byte_line[j] * 3];
p_bytearray^[j*4+3]:=255;
if byte_line[j]=0 then
p_bytearray^[j*4+3]:=0;
end;
end;
2:
begin
f.Read(byte_line, result.Width * bytes_per_pixel);
for j:=0 to result.Width -1 do
begin
if is_cdiv then
begin
Calculate_RGB(byte_line[j*2+1], byte_line[j*2],
p_bytearray^[j * 4], p_bytearray^[(j * 4) + 1],
p_bytearray^[(j * 4) + 2]);
p_bytearray^[(j * 4) + 3] := 255;
if ( ( p_bytearray^[j * 4] = $F8) and
( p_bytearray^[j * 4 + 1] = 0) and
( p_bytearray^[j * 4 + 2] = $F8) ) then
p_bytearray^[(j * 4) + 3] := 0;
end
else
begin
Calculate_BGR(byte_line[j*2+1], byte_line[j*2 ],
p_bytearray^[j * 4], p_bytearray^[(j * 4) + 1],
p_bytearray^[(j * 4) + 2]);
p_bytearray^[(j * 4) + 3] := 255;
if (byte_line[j*2+1] + byte_line[j*2 ]) = 0 then
p_bytearray^[(j * 4) + 3] := 0;
end;
end;
end;
3:
begin
f.Read(byte_line, result.Width * bytes_per_pixel);
for j:=0 to result.Width -1 do
begin
p_bytearray^[j*4] := byte_line[j*3];
p_bytearray^[j*4+1] := byte_line[j*3+1];
p_bytearray^[j*4+2] := byte_line[j*3+2];
p_bytearray^[j*4+3]:=255;
if (byte_line[j*3+2] + byte_line[j*3+1] + byte_line[j*3 ]) = 0 then
p_bytearray^[(j * 4) + 3] := 0;
end;
end;
else // 32 bits
f.Read(p_bytearray^, result.Width * bytes_per_pixel)
end;
end;
result.LoadFromIntfImage(lazBMP);
lazBMP.Free;
end;
function MAP_test(filename :String):Boolean;
var
Stream : TStream;
header : file_str_map;
begin
Result := False;
if not FileExistsUTF8(filename) { *Converted from FileExists* } then
Exit;
try
Stream := TFileStream.Create(filename, fmOpenRead);
except
Exit;
end;
try
Stream.Read(header.Magic, 3);
Stream.Read(header.MSDOSEnd , 4);
Stream.Read(header.Version, 1);
except
Stream.free;
Exit;
end;
// Ficheros de 1 bit
if (header.Magic[0] = 'm') and (header.Magic[1] = '0') and
(header.Magic[2] = '1') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
Result := True;
end;
// Ficheros de 8 bits para DIV2, FENIX y CDIV
if (header.Magic[0] = 'm') and (header.Magic[1] = 'a') and
(header.Magic[2] = 'p') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
Result := True;
end;
// Ficheros de 16 bits para FENIX
if (header.Magic[0] = 'm') and (header.Magic[1] = '1') and
(header.Magic[2] = '6') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
Result := True;
end;
// Ficheros de 16 bits para CDIV
if (header.Magic[0] = 'c') and (header.Magic[1] = '1') and
(header.Magic[2] = '6') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
Result := True;
end;
// Ficheros de 24 bits
if (header.Magic[0] = 'm') and (header.Magic[1] = '2') and
(header.Magic[2] = '4') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
Result := True;
end;
// Ficheros de 32 bits
if (header.Magic[0] = 'm') and (header.Magic[1] = '3') and
(header.Magic[2] = '2') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
Result := True;
end;
FreeAndNil(Stream);
end;
function MAP_Load(filename: string; var ncpoints:word; cpoints:PWord) : TBitmap;
var
f : TStream;
frames,
length,
speed : word;
bytes_per_pixel : word;
is_cdiv : boolean;
header : file_str_map;
map_hpal : HPALETTE;
i : integer;
begin
result := nil;
if not FileExistsUTF8(filename) { *Converted from FileExists* } then
Exit;
try
f := TFileStream.Create(filename, fmOpenRead);
except
Exit;
end;
try
f.Read(header.Magic, 3);
f.Read(header.MSDOSEnd , 4);
f.Read(header.Version, 1);
except
f.free;
Exit;
end;
bytes_per_pixel := 0;
is_cdiv:=false;
// Ficheros de 1 bit
if (header.Magic[0] = 'm') and (header.Magic[1] = '0') and
(header.Magic[2] = '1') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
bytes_per_pixel := 0;
end;
// Ficheros de 8 bits para DIV2, FENIX y CDIV
if (header.Magic[0] = 'm') and (header.Magic[1] = 'a') and
(header.Magic[2] = 'p') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
bytes_per_pixel := 1;
end;
// Ficheros de 16 bits para FENIX
if (header.Magic[0] = 'm') and (header.Magic[1] = '1') and
(header.Magic[2] = '6') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
bytes_per_pixel := 2;
end;
// Ficheros de 16 bits para CDIV
if (header.Magic[0] = 'c') and (header.Magic[1] = '1') and
(header.Magic[2] = '6') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
bytes_per_pixel := 2;
is_cdiv:=true;
end;
// Ficheros de 24 bits
if (header.Magic[0] = 'm') and (header.Magic[1] = '2') and
(header.Magic[2] = '4') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
bytes_per_pixel := 3;
end;
// Ficheros de 32 bits
if (header.Magic[0] = 'm') and (header.Magic[1] = '3') and
(header.Magic[2] = '2') and (header.MSDOSEnd [0] = 26 ) and
(header.MSDOSEnd [1] = 13 ) and (header.MSDOSEnd [2] = 10 ) and
(header.MSDOSEnd [3] = 0) then begin
bytes_per_pixel := 4;
end;
if (bytes_per_pixel > 4) then
begin
feMessageBox(LNG_STRINGS[LNG_ERROR], LNG_STRINGS[LNG_WRONG_FPG], 0, 0);
f.free;
Exit;
end;
try
f.Read(header.width,2);
f.Read(header.height,2);
f.Read(header.code,4);
f.Read(header.description, 32);
if (bytes_per_pixel = 1) then
begin
f.Read(header.palette, 768);
f.Read(header.gamma, 576);
for i := 0 to 767 do
header.palette[i] := header.palette[i] shl 2;
map_hpal := create_hpal(header.palette);
end;
f.Read(ncpoints, 2);
//ncpoints:=header.ncpoints;
// Leemos los puntos de control del bitmap
if ncpoints > 0 then
begin
f.Read(header.cpoints, ncpoints * 4);
for i:=0 to (ncpoints*2)-1 do
begin
cpoints[i]:=header.cpoints[i];
end;
end;
//else
// FillChar(cpoints,High(Word)*4,0); //borramos los puntos de control.
(* BennuGD no controla que si ncpoints = 4096 haga algo distinto,
Habría que revistar esta funcionalidad en DIV si se quiere implementar
if ((header.ncpoints > 0) and (header.ncpoints <> 4096)) then
begin
f.Read(header.cpoints, header.ncpoints * 4);
end;
if (header.ncpoints = 4096) then
begin
f.Read(frames, 2);
f.Read(length, 2);
f.Read(speed , 2);
f.Seek(length * 2, soFromCurrent);
end;
*)
// Se crea la imagen resultante
result:=loadDataBitmap(f,header.palette, header.width,header.height, bytes_per_pixel, is_cdiv);
finally
f.free;
end;
end;
end.
|
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
//
// Programa: MultiFind
//
// Propósito Modulo IconosAsociados:
// Definir un descendiente de TImageList que gestione la recuperación de iconos asociados
// controlando almacenar un solo icono por cada tipo, y reutilizando este icono
// para mostrarlo cuando sea necesario.
//
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
unit IconosAsociados;
interface
uses controls, windows, classes, graphics, imgList;
type
//
// Esta clase representa un icono (HIcon) asociado a una extensión concreta
//
TIconoAsociado = class(TObject)
private
FHandle: HICON;
FExtension: ShortString;
public
constructor Create(filename: ShortString); overload;
constructor Create(ico: TIconoAsociado); overload; // copy-constructor
destructor Destroy; override;
// Retorna un HICON asociado a un archivo (del proyecto JEDI)
class function GetFileTypeIcon(const Filename: string; UsarAtributos: Boolean): HICON;
property Handle: HICON read FHandle;
property Extension: ShortString read FExtension;
end;
//
// Esta clase representa una lista de iconos asociados a sus extensiones
// (objetos de tipo TIconoAsociado)
//
TListaIconosAsociados = class(TStringList)
public
destructor Destroy; override;
function AddIcon(ico: TIconoAsociado): integer;
end;
//
// Esta clase es un descendiente de TImageList que gestiona la recuperación de iconos
// asociados de archivos.
// Sigue el patrón "pool"
//
TIconosAsociados = class(TImageList)
private
FAsociados: TListaIconosAsociados;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function AddIconoAsociado(const Filename: ShortString): TImageIndex;
end;
implementation
uses ShellAPI, SysUtils;
// Proc/Fun : TIconoAsociado.Create
//
// Parametros : filename: string
//
// Comentarios: Crea un nuevo icono asociado, obteniendo el handle del icono
//
constructor TIconoAsociado.Create(filename: ShortString);
var
ext: ShortString;
begin
inherited Create;
ext := ExtractFileExt(filename);
System.Delete(ext, 1, 1);
self.FExtension := ext;
self.FHandle := GetFileTypeIcon(filename, true);
end;
// Proc/Fun : TIconoAsociado.Create
//
// Parametros : ico: TIconoAsociado
//
// Comentarios: Crea un icono a partir de los datos de otro.
// Sigue el patrón "copy-constructor"
//
constructor TIconoAsociado.Create(ico: TIconoAsociado); // copy-constructor
begin
inherited Create;
self.FExtension := ico.FExtension;
self.FHandle := ico.FHandle;
end;
// Proc/Fun: TIconoAsociado.Destroy
//
// Comentarios: Libera el objeto TIconoAsociado y el descriptor HICON
//
destructor TIconoAsociado.Destroy;
begin
if FHandle <> 0 then
DestroyIcon(FHandle);
inherited;
end;
// Proc/Fun : class function TIconoAsociado.GetFileTypeIcon()
//
// Valor retorno: HICON
// Parametros : const Filename: string; UsarAtributos: Boolean
//
// Comentarios : Crea un descriptor de tipo HICON que representa el icono (16x16)asociado a
// una extensión. Este descriptor debe destruírse con DestroyIcon.
//
class function TIconoAsociado.GetFileTypeIcon(const Filename: string; UsarAtributos: Boolean): HICON;
var
FileInfo: TSHFileInfo;
flags: Cardinal;
begin
FillChar(FileInfo, sizeof(TSHFileInfo), 0);
flags := SHGFI_ICON or SHGFI_SMALLICON;
if UsarAtributos then
flags := flags or SHGFI_USEFILEATTRIBUTES;
SHGetFileInfo(PChar(Filename), 0, FileInfo, sizeof(TShFileInfo), flags);
result := FileInfo.hIcon;
end;
// Proc/Fun : destructor TListaIconosAsociados.Destroy
//
// Comentarios : Destruye la lista y los objetos contenidos en la lista
//
destructor TListaIconosAsociados.Destroy;
var
icoAs: TIconoAsociado;
i: integer;
begin
for i := Pred(self.Count) downto 0 do
begin
icoAs := TIconoAsociado(self.Objects[i]);
icoAs.Free;
end;
self.Clear;
inherited;
end;
// Proc/Fun : function TListaIconosAsociados.AddIcon
//
// Valor retorno: integer
// Parametros : ico: TIconoAsociado
//
// Comentarios : Añade un nuevo icono a la lista
//
function TListaIconosAsociados.AddIcon(ico: TIconoAsociado): integer;
begin
result := self.AddObject(ico.Extension, ico);
end;
// Proc/Fun : constructor TIconosAsociados.Create
//
// Parametros : AOwner: TComponent
//
// Comentarios : Crea el ImageList y da valores iniciales
//
constructor TIconosAsociados.Create(AOwner: TComponent);
begin
inherited;
self.Width := 16;
self.Height := 16;
self.ShareImages := true;
FAsociados := TListaIconosAsociados.Create;
end;
destructor TIconosAsociados.Destroy;
begin
FAsociados.Free;
inherited;
end;
// Proc/Fun : function TIconosAsociados.AddIconoAsociado()
//
// Valor retorno: TImageIndex
// Parametros : const Filename: ShortString
//
// Comentarios : Busca si el icono asociado a "Filename" ya existe, retornándolo o
// creando uno nuevo en caso de que no exista.
//
function TIconosAsociados.AddIconoAsociado(const Filename: ShortString): TImageIndex;
var
ind: integer;
ico: TIcon;
icoAso: TIconoAsociado;
ext: ShortString;
begin
ext := AnsiLowercase(ExtractFileExt(filename));
System.Delete(ext, 1, 1);
// comprobar si este ya ha sido insertado
// Se excluyen aquellos tipos que tienen que mostrar un icono distinto por
// cada archivo, es decir: los programas y los iconos.
if (ext = 'exe') or (ext = 'ico') then
ind := -1
else
ind := FAsociados.IndexOf(ext);
if ind = -1 then
begin
icoAso := TIconoAsociado.Create(filename);
ico := TIcon.Create;
try
ico.Handle := icoAso.Handle;
ind := self.AddIcon(ico);
finally
ico.Free;
end;
// añadir a la lista de asociados.
FAsociados.AddIcon(icoAso);
end;
result := ind;
end;
end.
|
unit uModVoucher;
interface
uses
uModApp, uModUnit, uModAgreementVoucher, System.Generics.Collections,
uModOrganization, uModTransaksi;
type
TmodVoucherDetil = class;
TModVoucher = class(TModApp)
private
FAUTUNIT: TModUnit;
FMODORGANIZATION: TModOrganization;
FVCR_EXPIRE_DATE: TDateTime;
FVCR_ISSUED_DATE: TDateTime;
FVCR_NO: string;
FVCR_NOMINAL: Double;
FVCR_NOMINALBAYAR: Double;
FVCR_QTY: Double;
FVCR_START_DATE: TDateTime;
FVCR_STATUS: string;
FVoucherDetils: TobjectList<TModVoucherDetil>;
function GetVoucherDetils: TobjectList<TModVoucherDetil>;
public
property VoucherDetils: TobjectList<TModVoucherDetil> read GetVoucherDetils
write FVoucherDetils;
published
[AttributeOfForeign('AUT$UNIT_ID')]
property AUTUNIT: TModUnit read FAUTUNIT write FAUTUNIT;
property MODORGANIZATION: TModOrganization read FMODORGANIZATION write
FMODORGANIZATION;
property VCR_EXPIRE_DATE: TDateTime read FVCR_EXPIRE_DATE write
FVCR_EXPIRE_DATE;
property VCR_ISSUED_DATE: TDateTime read FVCR_ISSUED_DATE write
FVCR_ISSUED_DATE;
property VCR_NO: string read FVCR_NO write FVCR_NO;
property VCR_NOMINAL: Double read FVCR_NOMINAL write FVCR_NOMINAL;
property VCR_NOMINALBAYAR: Double read FVCR_NOMINALBAYAR write
FVCR_NOMINALBAYAR;
property VCR_QTY: Double read FVCR_QTY write FVCR_QTY;
property VCR_START_DATE: TDateTime read FVCR_START_DATE write FVCR_START_DATE;
property VCR_STATUS: string read FVCR_STATUS write FVCR_STATUS;
end;
TModVoucherDetil = class(TModApp)
private
FAUTUNIT: TModUnit;
FMODORGANIZATION: TModOrganization;
FMODTRANSAKSI: TModTransaksi;
FVCRD_NO: string;
FVCRD_NOMINAL: Double;
FVCRD_POS_TRANS_NO: string;
FVCRD_STATUS: string;
FVOUCHER: TModVoucher;
public
class function GetTableName: String; override;
published
[AttributeOfForeign('AUT$UNIT_ID')]
property AUTUNIT: TModUnit read FAUTUNIT write FAUTUNIT;
property MODORGANIZATION: TModOrganization read FMODORGANIZATION write
FMODORGANIZATION;
property MODTRANSAKSI: TModTransaksi read FMODTRANSAKSI write FMODTRANSAKSI;
property VCRD_NO: string read FVCRD_NO write FVCRD_NO;
property VCRD_NOMINAL: Double read FVCRD_NOMINAL write FVCRD_NOMINAL;
property VCRD_POS_TRANS_NO: string read FVCRD_POS_TRANS_NO write
FVCRD_POS_TRANS_NO;
property VCRD_STATUS: string read FVCRD_STATUS write FVCRD_STATUS;
[AttributeOfHeader]
property VOUCHER: TModVoucher read FVOUCHER write FVOUCHER;
end;
implementation
class function TModVoucherDetil.GetTableName: String;
begin
Result := 'VOUCHER_DETIL';
end;
function TModVoucher.GetVoucherDetils: TobjectList<TModVoucherDetil>;
begin
if FVoucherDetils = nil then
FVoucherDetils := TObjectList<TModVoucherDetil>.Create();
Result := FVoucherDetils;
end;
initialization
TModVoucher.RegisterRTTI;
TModVoucherDetil.RegisterRTTI;
end.
|
unit DragOut;
interface
uses files, OLE2, classes, clipbrd, fileoperations;
Type
TGiveFiles=class
data:IDataObject;
copied:boolean;
FContainer:TContainerFile;
Files:TStringList;
extracted:boolean;
Constructor Create(Container:TContainerFile);
Destructor Destroy;override;
Procedure Clear;
Procedure AddFile(Name:String;fi:TFileInfo);
Procedure CopyIt; {Copies to clipboard}
Procedure DragIt; {Drag&drops}
Procedure ExtractFiles;
end;
implementation
uses Windows, OleAuto {for OleCheck}, SysUtils, ShlObj;
var TempDir:String;
type
TMyDataObject = class(IDataObject)
private
RefCount: integer;
Data: TStringList;
public
function QueryInterface(const iid: TIID; var obj): HResult; override; stdcall;
function AddRef: Longint; override; stdcall;
function Release: Longint; override; stdcall;
function GetData(var formatetcIn: TFormatEtc; var medium: TStgMedium):
HResult; override; stdcall;
function GetDataHere(var formatetc: TFormatEtc; var medium: TStgMedium):
HResult; override; stdcall;
function QueryGetData(var formatetc: TFormatEtc): HResult;
override; stdcall;
function GetCanonicalFormatEtc(var formatetc: TFormatEtc;
var formatetcOut: TFormatEtc): HResult; override; stdcall;
function SetData(var formatetc: TFormatEtc; var medium: TStgMedium;
fRelease: BOOL): HResult; override; stdcall;
function EnumFormatEtc(dwDirection: Longint; var enumFormatEtc:
IEnumFormatEtc): HResult; override; stdcall;
function DAdvise(var formatetc: TFormatEtc; advf: Longint;
advSink: IAdviseSink; var dwConnection: Longint): HResult; override; stdcall;
function DUnadvise(dwConnection: Longint): HResult; override; stdcall;
function EnumDAdvise(var enumAdvise: IEnumStatData): HResult;
override; stdcall;
constructor Create(sl: TStringList);
end;
TMyEnum = class(IEnumFormatEtc)
private
RefCount: integer;
Index: integer;
public
function QueryInterface(const iid: TIID; var obj): HResult; override; stdcall;
function AddRef: Longint; override; stdcall;
function Release: Longint; override; stdcall;
function Next(celt: Longint; var elt;
pceltFetched: PLongint): HResult; override; stdcall;
function Skip(celt: Longint): HResult; override; stdcall;
function Reset: HResult; override; stdcall;
function Clone(var enum: IEnumFormatEtc): HResult; override; stdcall;
end;
TMyDropSource = class(IDropSource)
private
RefCount: integer;
dobj:TMyDataObject;
public
Constructor Create(obj:TMyDataObject);
function QueryInterface(const iid: TIID; var obj): HResult; override; stdcall;
function AddRef: Longint; override; stdcall;
function Release: Longint; override; stdcall;
function QueryContinueDrag(fEscapePressed: BOOL;
grfKeyState: Longint): HResult; override; stdcall;
function GiveFeedback(dwEffect: Longint): HResult; override; stdcall;
end;
Function Slist2Hdrop(sl:TStringList):HGlobal;
var
pdf: PDropFiles;
ps, ps1: PChar;
lentdir,len:Integer;
i:integer;
begin
len:=0;
lentdir:=Length(TempDir);
For i:=0 to sl.Count-1 do
inc(len,Length(sl[i])+1+Lentdir);
Result := GlobalAlloc(GMEM_SHARE, Sizeof(pdf^)+len+2);
if Result = 0 then exit;
pdf:=GlobalLock(Result);
with pdf^ do
begin
pFiles:=sizeof(pdf^);
pt.X:=0;
pt.Y:=0;
fNC:=true;
fWide:=false;
end;
ps:=pchar(pdf)+sizeof(pdf^);
ps1:=ps;
ps^:=#0;
for i:=0 to sl.Count-1 do
begin
ps:=StrEcopy(ps,pchar(TempDir));
ps:=StrECopy(ps,Pchar(sl[i]))+1;
end;
ps^:=#0;
if ps1=nil then;
GlobalUnlock(Result);
end;
{ TMyDataObject }
constructor TMyDataObject.Create(sl: TStringList);
begin
inherited Create;
Data := sl;
end;
function TMyDataObject.QueryInterface(const iid: TIID; var obj): HResult; stdcall;
begin
if IsEqualIID(iid, IID_IUnknown) or IsEqualIID(iid, IID_IDataObject) then begin
Pointer(obj) := self;
AddRef;
Result := S_OK;
end else begin
Pointer(obj) := nil;
Result := E_NOINTERFACE;
end;
end;
function TMyDataObject.AddRef: Longint; stdcall;
begin
Inc(RefCount);
Result := RefCount;
end;
function TMyDataObject.Release: Longint; stdcall;
begin
Dec(RefCount);
Result := RefCount;
if RefCount = 0 then
Free;
end;
function TMyDataObject.GetData(var formatetcIn: TFormatEtc; var medium: TStgMedium):
HResult; stdcall;
var
hdf: HGlobal;
begin
if Failed(QueryGetData(formatetcIn)) then
Result := DV_E_FORMATETC
else begin
hdf:=sList2HDrop(data);
if hdf=0 then
begin
Result := E_OUTOFMEMORY;
Exit;
end;
with medium do begin
tymed := TYMED_HGLOBAL;
hGlobal:=hdf;
unkForRelease := nil;
end;
Result := S_OK;
end;
end;
function TMyDataObject.GetDataHere(var formatetc: TFormatEtc; var medium: TStgMedium):
HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TMyDataObject.QueryGetData(var formatetc: TFormatEtc): HResult; stdcall;
begin
with formatetc do begin
if cfFormat <> CF_HDROP then
Result := DV_E_FORMATETC
else if (tymed and TYMED_HGLOBAL) = 0 then
Result := DV_E_TYMED
else
Result := S_OK;
end;
end;
function TMyDataObject.GetCanonicalFormatEtc(var formatetc: TFormatEtc;
var formatetcOut: TFormatEtc): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TMyDataObject.SetData(var formatetc: TFormatEtc; var medium: TStgMedium;
fRelease: BOOL): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TMyDataObject.EnumFormatEtc(dwDirection: Longint; var enumFormatEtc:
IEnumFormatEtc): HResult; stdcall;
begin
if dwDirection = DATADIR_GET then begin
enumFormatEtc := TMyEnum.Create;
enumFormatEtc.AddRef;
Result := S_OK;
end else begin
enumFormatEtc := nil;
Result := E_NOTIMPL;
end;
end;
function TMyDataObject.DAdvise(var formatetc: TFormatEtc; advf: Longint;
advSink: IAdviseSink; var dwConnection: Longint): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TMyDataObject.DUnadvise(dwConnection: Longint): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TMyDataObject.EnumDAdvise(var enumAdvise: IEnumStatData): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
{ TMyEnum }
function TMyEnum.QueryInterface(const iid: TIID; var obj): HResult; stdcall;
begin
if IsEqualIID(iid, IID_IUnknown) or IsEqualIID(iid, IID_IEnumFormatEtc) then begin
Pointer(obj) := self;
AddRef;
Result := S_OK;
end else begin
Pointer(obj) := nil;
Result := E_NOINTERFACE;
end;
end;
function TMyEnum.AddRef: Longint; stdcall;
begin
Inc(RefCount);
Result := RefCount;
end;
function TMyEnum.Release: Longint; stdcall;
begin
Dec(RefCount);
Result := RefCount;
if RefCount = 0 then
Free;
end;
function TMyEnum.Next(celt: Longint; var elt;
pceltFetched: PLongint): HResult; stdcall;
begin
Result := S_FALSE;
if (Index = 0) and (celt > 0) then begin
Inc(Index);
with TFormatEtc(elt) do begin
cfFormat := CF_HDROP;
ptd := nil; // not sure I should do this!
dwAspect := DVASPECT_ICON;
lindex := -1;
tymed := TYMED_HGLOBAL;
end;
if pceltFetched <> nil then pceltFetched^ := 1;
if celt = 1 then Result := S_OK;
end else begin
if pceltFetched <> nil then pceltFetched^ := 0;
end;
end;
function TMyEnum.Skip(celt: Longint): HResult; stdcall;
begin
Inc(Index, celt);
if Index > 1 then Result := S_FALSE else Result := S_OK;
end;
function TMyEnum.Reset: HResult; stdcall;
begin
Index := 0;
Result := S_OK;
end;
function TMyEnum.Clone(var enum: IEnumFormatEtc): HResult; stdcall;
begin
enum := TMyEnum.Create;
enum.AddRef;
TMyEnum(enum).Index := Index;
Result := S_OK;
end;
{ TMyDropDSource }
Constructor TMyDropSource.Create(obj:TMyDataObject);
begin
dobj:=obj;
end;
function TMyDropSource.QueryInterface(const iid: TIID; var obj): HResult; stdcall;
begin
if IsEqualIID(iid, IID_IUnknown) or IsEqualIID(iid, IID_IDropSource) then begin
Pointer(obj) := self;
AddRef;
Result := S_OK;
end else begin
Pointer(obj) := nil;
Result := E_NOINTERFACE;
end;
end;
function TMyDropSource.AddRef: Longint; stdcall;
begin
Inc(RefCount);
Result := RefCount;
end;
function TMyDropSource.Release: Longint; stdcall;
begin
Dec(RefCount);
Result := RefCount;
if RefCount = 0 then
Free;
end;
function TMyDropSource.QueryContinueDrag(fEscapePressed: BOOL;
grfKeyState: Longint): HResult; stdcall;
begin
if fEscapePressed then
Result := DRAGDROP_S_CANCEL
else if (grfKeyState and MK_LBUTTON) = 0 then
Result := DRAGDROP_S_DROP
else
Result := NOERROR;
end;
function TMyDropSource.GiveFeedback(dwEffect: Longint): HResult; stdcall;
begin
Result := DRAGDROP_S_USEDEFAULTCURSORS;
end;
{ Global Function }
Constructor TGiveFiles.Create(Container:TContainerFile);
begin
FContainer:=Container;
files:=TStringList.Create;
end;
Destructor TGiveFiles.Destroy;
begin
Clear;
files.free;
end;
Procedure TGiveFiles.AddFile(Name:String;fi:TFileInfo);
begin
Files.AddObject(Name,Fi);
end;
Procedure TGiveFiles.Clear;
var clp:TClipBoard;
i:integer;
begin
clp:=Clipboard;
if clp.HasFormat(CF_HDROP) then Clp.Clear;
if extracted then
for i:=0 to files.count-1 do
DeleteFile(TempDir+files[i]);
extracted:=false;
Files.Clear;
end;
Procedure TGiveFiles.CopyIt; {Copies to clipboard}
var hdf:Hglobal;
clp:TClipBoard;
begin
ExtractFiles;
hdf:=sList2HDrop(files);
clp:=Clipboard;
clp.SetAsHandle(CF_HDROP,hdf);
end;
Procedure TGiveFiles.ExtractFiles;
var i:integer;
f,fout:TFile;
begin
if extracted then exit;
for i:=0 to Files.Count-1 do
begin
f:=FContainer.OpenFileByFI(TFileInfo(Files.Objects[i]));
fout:=OpenFileWrite(TempDir+files[i],0);
CopyFileData(f,fout,f.fsize);
f.Fclose;
fout.Fclose;
end;
extracted:=true;
end;
Procedure TGiveFiles.DragIt; {Drag&drops}
var
MyData: TMyDataObject;
MyDrop: TMyDropSource;
Effect: LongInt;
begin
ExtractFiles;
try
MyData := TMyDataObject.Create(files);
MyData.AddRef;
{ OleSetClipBoard(MyData);
exit;}
try
MyDrop := TMyDropSource.Create(MyData);
MyDrop.AddRef;
try
DoDragDrop(IDataObject(MyData), IDropSource(MyDrop),
DROPEFFECT_COPY, Effect);
finally
MyData.Release;
end;
finally
MyDrop.Release;
end;
except
end;
end;
{ Startup/Shutdown }
var s:array[0..255] of char;
initialization
begin
OleCheck(OleInitialize(nil));
GetTempPath(256,s);
TempDir:=s;
end;
finalization
OleUninitialize;
end.
|
procedure TGLine.initialize;
begin
dx:=p2.getX-p1.getX;
dy:=p2.getY-p1.getY;
d:=sqrt(dx*dx+dy*dy);
// m:=dy/dx;
ex:=dx/d;
ey:=dy/d;
end;
//------------------------------------------------------------------
constructor TGLine.Create(p1_,p2_:TGPoint;s:TGLineState;L:TList;C:TCanvas);
begin
p1:=p1_;
p2:=p2_;
bisectorOf[1]:=-1;
bisectorOf[2]:=-1;
state:=s;
inherited Create(L,C);
Color.Color:=$00FFFFFF;
initialize;
end;
//------------------------------------------------------------------
function TGLine.Clone:TGraphObject;
begin
result:=TGLine.Create(p1,p2,state,nil,getCanvas);
result.orig_index:=getOrigIndex;
TGLine(result).BisectorOf[1]:=BisectorOf[1];
TGLine(result).BisectorOf[2]:=BisectorOf[2];
end;
//------------------------------------------------------------------
procedure TGLine.draw;
var maxl:extended; //maximal line length possible in canvas, let canvas clip.
p:TPoint; //needed to set locations in canvas
begin
maxl:=sqrt(sqr(getcanvas.ClipRect.Right)+sqr(getcanvas.ClipRect.Bottom));
getcanvas.Pen.Color:=Color.Color;
case state of
TwoPoint:begin
p.x:=round(p1.getX);
p.y:=round(p1.getY);
getcanvas.PenPos:=p;
getcanvas.LineTo(round(p2.getX),round(p2.getY));
end;
OnePoint:begin
p.x:=round(p1.getX);
p.y:=round(p1.getY);
getcanvas.PenPos:=p;
getcanvas.LineTo(round(p1.getx+maxl*2*ex),round(p1.gety+maxl*2*ey));
end;
Vector :begin
p.x:=round(p1.getX-maxl*ex);
p.y:=round(p1.getY-maxl*ey);
getcanvas.PenPos:=p;
getcanvas.LineTo(round(p1.getx+maxl*2*ex),round(p1.gety+maxl*2*ey));
end;
end;
end;
//------------------------------------------------------------------
procedure TGLine.clear;
begin
end;
//------------------------------------------------------------------
function TGLine.GetState:TGLineState;
begin
result:=state;
end;
//------------------------------------------------------------------
function TGLine.Intersect(ln:TGLine):boolean;
var ax,ay,divider:extended;
begin
result:=false;
divider:=ex*ln.ey-ey*ln.ex;
if divider=0 then exit; //paralell
r:=-(p1.getX*ey-p1.getY*ex+ex*ln.p1.getY-ey*ln.p1.getX)/divider;
t:=-(p1.getX*ln.ey-p1.getY*ln.ex-ln.p1.getX*ln.ey+ln.p1.getY*ln.ex)/divider;
ax:=p1.getX+t*ex;
ay:=p1.getY+t*ey;
if (state=Vector) and (ln.state=vector) then
result:=true;
if (state=Vector) and (ln.state=OnePoint) then
if r>=0 then result:=true;
if (state=Vector) and (ln.state=TwoPoint) then
if (r>=0) and (r<=ln.d) then result:=true;
if (state=OnePoint) and (ln.state=vector) then
if (t>=0) then result:=true;
if (state=OnePoint) and (ln.state=OnePoint) then
if (t>=0) and (r>=0) then result:=true;
if (state=OnePoint) and (ln.state=TwoPoint) then
if (t>=0) and (r>=0) and (r<=ln.d) then result:=true;
if (state=TwoPoint) and (ln.state=vector) then
if (t>=0) and (t<=d) then result:=true;
if (state=TwoPoint) and (ln.state=OnePoint) then
if (t>=0) and (t<=d) and (r>=0) then result:=true;
if (state=TwoPoint) and (ln.state=TwoPoint) then
if (t>=0) and (t<=d) and (r>=0) and (r<=ln.d) then result:=true;
if result then begin
ix:=ax;
iy:=ay;
end;
end;
//------------------------------------------------------------------
procedure TGLine.GetCurrentIPoint(var x,y:extended); // copies ix and iy. only valid after intersect() call !
begin
x:=ix;
y:=iy;
end;
//------------------------------------------------------------------
procedure TGLine.GetCurrentIPoint(var P:TGPoint); // copies ix and iy. only valid after intersect() call !
begin
if assigned(p) then p.free;
p:=TGPoint.create(ix,iy,nil,getcanvas);
end;
//------------------------------------------------------------------
procedure TGLine.CutRight(ln:TGLine);
begin
if intersect(ln) then begin
if state=vector then begin
state:=OnePoint;
p1.MoveTo(ix,iy);
if ex>0 then begin
ex:=-ex;
ey:=-ey;
end;
p2.MoveTo(ix+ex,iy+ey);
end else
if state=OnePoint then begin
if ex>0 then begin
state:=TwoPoint;
p2.MoveTo(ix,iy);
end else begin
//state unchanged ! stais OnePoint !!!
p1.MoveTo(ix,iy);
p2.MoveTo(ix+ex,iy+ey);
end;
end else
if state=TwoPoint then begin
state:=TwoPoint;
if ex>0 then begin
p2.MoveTo(ix,iy);
end else begin
p1.MoveTo(ix,iy);
end;
end;
initialize;
end;
end;
//------------------------------------------------------------------
procedure TGLine.CutLeft(ln:TGLine);
begin
if intersect(ln) then begin
if state=vector then begin
state:=OnePoint;
p1.MoveTo(ix,iy);
if ex<=0 then begin
ex:=-ex;
ey:=-ey;
end;
p2.MoveTo(ix+ex,iy+ey);
end else
if state=OnePoint then begin
if ex<=0 then begin
state:=TwoPoint;
p2.MoveTo(ix,iy);
end else begin
//state unchanged ! stais OnePoint !!!
p1.MoveTo(ix,iy);
p2.MoveTo(ix+ex,iy+ey);
end;
end else
if state=TwoPoint then begin
if ex<=0 then begin
p2.MoveTo(ix,iy);
end else begin
p1.MoveTo(ix,iy);
end;
end;
initialize;
end;
end;
//------------------------------------------------------------------
procedure TGLine.CutBoth(ln:TGLine); // caller line must be the one on top
var a,b:TGline;
begin
a:=(clone as TGLine);
b:=(ln.clone as TGLine);
if a.ey>0 then begin
a.ex:=-a.ex;
a.ey:=-a.ey;
end;
if b.ey>0 then begin
b.ex:=-b.ex;
b.ey:=-b.ey;
end;
if a.ex>=b.ex then begin
if a.ex>0 then CutRight(ln) else CutLeft(ln);
if b.ex<0 then ln.CutRight(a) else ln.CutLeft(a);
end else begin
if a.ex>0 then CutRight(ln) else CutLeft(ln);
if b.ex>0 then ln.CutLeft(a) else ln.CutRight(a);
end;
a.free;
b.free;
end;
|
unit UContaCorrenteVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO,
UCondominioVO;
type
[TEntity]
[TTable('ContaCorrente')]
TContaCorrenteVO = class(TGenericVO)
private
FidContaCorrente : Integer;
FidContasReceber : Integer;
FidLcto : Integer;
FdtComp : TDateTime;
public
[TId('idContaCorrente')]
[TGeneratedValue(sAuto)]
property FdContaCorrente : Integer read FidContaCorrente write FidContaCorrente;
[TColumn('idContasReceber','CR',0,[ldGrid,ldLookup,ldComboBox], False)]
property idContasReceber: integer read FidContasReceber write FidContasReceber;
[TColumn('idLcto','IdLcto',0,[ldLookup,ldComboBox], False)]
property idLcto: integer read FidLcto write FidLcto;
[TColumn('DTCOMPETENCIA','DATA',0,[], True, 'contasReceber', 'idcontasReceber', 'idcontasReceber')]
property dtComp: TDateTime read FdtComp write FdtComp;
procedure ValidarCamposObrigatorios;
end;
implementation
procedure TContaCorrenteVO.ValidarCamposObrigatorios;
begin
end;
end.
|
unit mrSearchEdit;
interface
uses
Windows, SysUtils, Classes, Graphics, Messages, cxButtonEdit, mrBoundLabel,
ExtCtrls, Controls, Types, Menus, StdCtrls, cxEdit;
type
TmrSearchEdit = class(TcxButtonEdit)
private
FEditLabel: TmrBoundLabel;
FLabelPosition: TLabelPosition;
FLabelSpacing: Integer;
FRequiredLabel: TmrBoundLabel;
FPopupMenuButton: TPopupMenu;
FRequired: Boolean;
FLocked: Boolean;
procedure SetLabelPosition(const Value: TLabelPosition);
procedure SetLabelSpacing(const Value: Integer);
procedure SetInternalButton;
procedure SetInternalPopup;
procedure SetupInternalLabel;
procedure SetCommandButtons;
procedure MyOnButtonClick(Sender: TObject; AbsoluteIndex: Integer);
procedure SetRequired(const Value: Boolean);
procedure PopupClick(Sender: TObject);
procedure SearchRecord;
procedure OpenRecord;
procedure ClearValue;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetName(const Value: TComponentName); override;
procedure CMVisiblechanged(var Message: TMessage); message CM_VISIBLECHANGED;
procedure CMEnabledchanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure CMBidimodechanged(var Message: TMessage); message CM_BIDIMODECHANGED;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CMExit(var Message: TCMExit);
procedure SetParent(AParent: TWinControl); override;
procedure DoButtonUp(Index: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetBounds(ALeft: Integer; ATop: Integer; AWidth: Integer;
AHeight: Integer); override;
property Required: Boolean read FRequired write SetRequired;
property Locked: Boolean read FLocked write FLocked;
published
property EditLabel: TmrBoundLabel read FEditLabel;
property LabelPosition: TLabelPosition read FLabelPosition write SetLabelPosition;
property LabelSpacing: Integer read FLabelSpacing write SetLabelSpacing;
end;
TmrDBSearchEdit = class(TmrSearchEdit)
end;
procedure Register;
implementation
uses mrSearchEditFrm;
procedure Register;
begin
RegisterComponents('MultiTierDataControls', [TmrSearchEdit]);
RegisterComponents('MultiTierDataControls', [TmrDBSearchEdit]);
end;
{ TmrSearchEdit }
procedure TmrSearchEdit.ClearValue;
begin
end;
procedure TmrSearchEdit.CMTextChanged(var Message: TMessage);
begin
inherited;
// TODO
//FKeyFieldValue := DataSource.DataSet.FieldByName(FKeyField).AsString;
end;
procedure TmrSearchEdit.CMBidimodechanged(var Message: TMessage);
begin
FEditLabel.BiDiMode := BiDiMode;
FRequiredLabel.BiDiMode := BiDiMode;
end;
procedure TmrSearchEdit.CMExit(var Message: TCMExit);
begin
// TODO
//SetKeyField;
end;
procedure TmrSearchEdit.CMEnabledchanged(var Message: TMessage);
begin
inherited;
FEditLabel.Enabled := Enabled;
FRequiredLabel.Enabled := Enabled;
end;
procedure TmrSearchEdit.CMVisiblechanged(var Message: TMessage);
begin
FEditLabel.Visible := Visible;
FRequiredLabel.Visible := Visible;
if Visible and Required then
FRequiredLabel.Parent := Self.Parent
else
FRequiredLabel.Parent := nil;
end;
constructor TmrSearchEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
SetInternalButton;
SetInternalPopup;
Properties.ReadOnly := True;
FLabelPosition := lpLeft;
FLabelSpacing := 6;
SetupInternalLabel;
Properties.OnButtonClick := MyOnButtonClick;
end;
destructor TmrSearchEdit.Destroy;
begin
FPopupMenuButton.Free;
inherited Destroy;
end;
procedure TmrSearchEdit.MyOnButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
begin
DoButtonUp(AbsoluteIndex);
end;
procedure TmrSearchEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
begin
if AComponent = FEditLabel then
FEditLabel := nil;
if AComponent = FRequiredLabel then
FRequiredLabel := nil;
end;
end;
procedure TmrSearchEdit.OpenRecord;
begin
end;
procedure TmrSearchEdit.PopupClick(Sender: TObject);
begin
case TMenuItem(Sender).MenuIndex of
0: OpenRecord;
2: ClearValue;
end;
end;
procedure TmrSearchEdit.SetInternalPopup;
procedure CreateMenuItem(Caption: String);
var
MenuItem: TMenuItem;
begin
MenuItem := TMenuItem.Create(FPopupMenuButton);
FPopupMenuButton.Items.Add(MenuItem);
MenuItem.Caption := Caption;
MenuItem.OnClick := PopupClick;
end;
begin
if not Assigned(FPopupMenuButton) then
begin
FPopupMenuButton := TPopupMenu.Create(Self);
FPopupMenuButton.Name := 'SubPopupMenu';
FPopupMenuButton.SetSubComponent(True);
FPopupMenuButton.FreeNotification(Self);
CreateMenuItem('&Open...');
CreateMenuItem('-');
CreateMenuItem('Clear');
end;
end;
procedure TmrSearchEdit.SetLabelPosition(const Value: TLabelPosition);
var
P: TPoint;
begin
if Assigned(FEditLabel) then
begin
FLabelPosition := Value;
case Value of
lpAbove: P := Point(Left, Top - FEditLabel.Height - FLabelSpacing);
lpBelow: P := Point(Left, Top + Height + FLabelSpacing);
lpLeft : P := Point(Left - FEditLabel.Width - FLabelSpacing,
Top + ((Height - FEditLabel.Height) div 2));
lpRight: P := Point(Left + Width + FLabelSpacing,
Top + ((Height - FEditLabel.Height) div 2));
end;
FEditLabel.SetBounds(P.x, P.y, FEditLabel.Width, FEditLabel.Height);
end;
if Assigned(FRequiredLabel) then
FRequiredLabel.SetBounds(Left + Width + 3, Top + 1, FRequiredLabel.Width, FRequiredLabel.Height);
end;
procedure TmrSearchEdit.SetLabelSpacing(const Value: Integer);
begin
FLabelSpacing := Value;
SetLabelPosition(FLabelPosition);
end;
procedure TmrSearchEdit.SetName(const Value: TComponentName);
begin
if (csDesigning in ComponentState) and ((FEditlabel.GetTextLen = 0) or
(CompareText(FEditLabel.Caption, Name) = 0)) then
FEditLabel.Caption := Value;
inherited SetName(Value);
if csDesigning in ComponentState then
Text := '';
end;
procedure TmrSearchEdit.SetParent(AParent: TWinControl);
begin
inherited SetParent(AParent);
if Assigned(FEditLabel) then
begin
FEditLabel.Parent := AParent;
FEditLabel.Visible := True;
end;
end;
procedure TmrSearchEdit.SetRequired(const Value: Boolean);
begin
FRequired := Value;
if Value then
FRequiredLabel.Parent := Self.Parent
else
FRequiredLabel.Parent := nil;
end;
procedure TmrSearchEdit.SetupInternalLabel;
begin
if not Assigned(FEditLabel) then
begin
FEditLabel := TmrBoundLabel.Create(Self);
FEditLabel.Name := 'SubEditLabel';
FEditLabel.SetSubComponent(True);
FEditLabel.FreeNotification(Self);
TLabel(FEditLabel).FocusControl := Self;
end;
if not Assigned(FRequiredLabel) then
begin
FRequiredLabel := TmrBoundLabel.Create(Self);
with FRequiredLabel do
begin
Name := 'SubRequiredLabel';
SetSubComponent(True);
FreeNotification(Self);
Caption := '*';
Font.Color := $00804000;
Font.Style := [fsBold];
Font.Size := 15;
Font.Name := 'Verdana';
Transparent := True;
end;
end;
end;
procedure TmrSearchEdit.DoButtonUp(Index: Integer);
var
CursorPos: TPoint;
begin
case Index of
0:
if not FLocked then
SearchRecord;
1:
begin
SetCommandButtons;
GetCursorPos(CursorPos);
FPopupMenuButton.Popup(CursorPos.X, CursorPos.Y);
end;
end;
// TODO
//EditButtonClick;
end;
procedure TmrSearchEdit.SetInternalButton;
begin
with Properties.Buttons do
begin
Add;
Items[0].Kind := bkGlyph;
Items[1].Kind := bkEllipsis;
end;
end;
procedure TmrSearchEdit.SearchRecord;
begin
with TSearchEditFrm.Create(Self) do
try
Init;
ShowSearch;
finally
Free;
end;
end;
procedure TmrSearchEdit.SetCommandButtons;
begin
FPopupMenuButton.Items[0].Visible := True;
FPopupMenuButton.Items[1].Visible := True;
FPopupMenuButton.Items[2].Visible := True;
FPopupMenuButton.Items[1].Enabled := True;
FPopupMenuButton.Items[2].Enabled := not FLocked;
end;
procedure TmrSearchEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
SetLabelPosition(FLabelPosition);
end;
end.
|
unit pkcs11_token;
interface
uses
Controls,
pkcs11t,
pkcs11_api,
pkcs11_mechanism,
pkcs11_session;
const
NULL_TIME = 0;
type
TPKCS11Token = class(TPKCS11API)
private
protected
FSlotID: integer;
FCacheTokenInfo: boolean;
FCachedTokenInfoPresent: boolean;
FCachedTokenInfo: CK_TOKEN_INFO;
// xxx - change these and all like them to TList
FCachedMechanismsArray: TPKCS11MechanismArray;
procedure SetCacheTokenInfo(flag: boolean);
function GetXLabel(): string;
function GetManufacturerID(): string;
function GetModel(): string;
function GetSerialNumber(): string;
function GetFlags(): CK_FLAGS;
function GetMaxSessionCount(): cardinal;
function GetSessionCount(): cardinal;
function GetMaxRwSessionCount(): cardinal;
function GetRwSessionCount(): cardinal;
function GetMaxPinLen(): cardinal;
function GetMinPinLen(): cardinal;
function GetTotalPublicMemory(): cardinal;
function GetFreePublicMemory(): cardinal;
function GetTotalPrivateMemory(): cardinal;
function GetFreePrivateMemory(): cardinal;
function GetHardwareVersion(): CK_VERSION;
function GetFirmwareVersion(): CK_VERSION;
function GetUTCTime(): TDateTime;
function _GetCountMechanisms(): integer;
function InitToken(usePINPad: boolean; SOPIN: string; tokenLabel: string): boolean; overload;
public
constructor Create();
destructor Destroy(); override;
property SlotID: integer read FSlotID write FSlotID;
function GetTokenInfo(var info: CK_TOKEN_INFO): boolean;
function InitToken(tokenLabel: string): boolean; overload;
function InitToken(SOPIN: string; tokenLabel: string): boolean; overload;
function GetCountMechanisms(): integer;
function GetMechanismList(var mechsArray: TPKCS11MechanismArray): boolean;
function GetMechanismByIdx(idx: integer): TPKCS11Mechanism; overload;
function GetMechanismByType(mechType: CK_MECHANISM_TYPE): TPKCS11Mechanism; overload;
function OpenSession(readOnly: boolean): TPKCS11Session; overload;
function OpenSession(flags: cardinal; callbackData: CK_VOID_PTR; callback: CK_NOTIFY): TPKCS11Session; overload;
procedure CloseSession(session: TPKCS11Session);
procedure CloseAllSessions();
// If this flag is set, GetTokenInfo will return cached information
property CacheTokenInfo: boolean read FCacheTokenInfo write SetCacheTokenInfo;
procedure FlushCache();
property XLabel: string read GetXLabel;
property ManufacturerID: string read GetManufacturerID;
property Model: string read GetModel;
property SerialNumber: string read GetSerialNumber;
property Flags: CK_FLAGS read GetFlags;
property MaxSessionCount : cardinal read GetMaxSessionCount;
property SessionCount : cardinal read GetSessionCount;
property MaxRwSessionCount : cardinal read GetMaxRwSessionCount;
property RwSessionCount : cardinal read GetRwSessionCount;
property MaxPinLen : cardinal read GetMaxPinLen;
property MinPinLen : cardinal read GetMinPinLen;
property TotalPublicMemory : cardinal read GetTotalPublicMemory;
property FreePublicMemory : cardinal read GetFreePublicMemory;
property TotalPrivateMemory: cardinal read GetTotalPrivateMemory;
property FreePrivateMemory : cardinal read GetFreePrivateMemory;
property HardwareVersion : CK_VERSION read GetHardwareVersion;
property FirmwareVersion : CK_VERSION read GetFirmwareVersion;
property UTCTime: TDateTime read GetUTCTime;
property CountMechanisms: integer read GetCountMechanisms;
// Note: Mechanism(...) indexes from zero
property Mechanism[idx: integer]: TPKCS11Mechanism read GetMechanismByIdx;
end;
implementation
uses
SysUtils,
DateUtils;
constructor TPKCS11Token.Create();
begin
inherited Create();
FCachedMechanismsArray := nil;
FCacheTokenInfo := TRUE;
end;
destructor TPKCS11Token.Destroy();
begin
inherited;
end;
function TPKCS11Token.GetTokenInfo(var info: CK_TOKEN_INFO): boolean;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_GetTokenInfo, FN_NAME_C_GetTokenInfo);
if (FCacheTokenInfo and FCachedTokenInfoPresent) then
begin
info := FCachedTokenInfo;
Result := TRUE;
end
else
begin
LastRV := LibraryFunctionList.CK_C_GetTokenInfo(SlotID, @info);
Result := RVSuccess(LastRV);
if (Result and CacheTokenInfo) then
begin
FCachedTokenInfo := info;
FCachedTokenInfoPresent := TRUE;
end;
end;
end;
function TPKCS11Token.OpenSession(readOnly: boolean): TPKCS11Session;
var
flags: cardinal;
begin
flags := CKF_SERIAL_SESSION;
if not(readOnly) then
begin
flags := (flags + CKF_RW_SESSION);
end;
Result := OpenSession(
flags,
//(CKF_SERIAL_SESSION),
nil,
nil
);
end;
// Note: It's the CALLERS responsibility to free off the returned object
// Returns new session, or nil on failure
function TPKCS11Token.OpenSession(flags: cardinal; callbackData: CK_VOID_PTR; callback: CK_NOTIFY): TPKCS11Session;
var
newSession: TPKCS11Session;
tmpHandle: CK_SESSION_HANDLE;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_OpenSession, FN_NAME_C_OpenSession);
newSession := nil;
LastRV := LibraryFunctionList.CK_C_OpenSession(
slotID,
flags,
callbackData,
callback,
@tmpHandle
);
if RVSuccess(LastRV) then
begin
newSession := TPKCS11Session.Create();
newSession.FhSession := tmpHandle;
newSession.SlotID := SlotID;
newSession.LibraryFunctionList := LibraryFunctionList;
end;
Result := newSession;
end;
// Important: Keep implementation of:
//
// TPKCS11Token.CloseSession(...);
// TPKCS11Session.CloseSession();
//
// in sync
procedure TPKCS11Token.CloseSession(session: TPKCS11Session);
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_CloseSession, FN_NAME_C_CloseSession);
LastRV := LibraryFunctionList.CK_C_CloseSession(session.FhSession);
end;
procedure TPKCS11Token.CloseAllSessions();
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_CloseAllSessions, FN_NAME_C_CloseAllSessions);
LastRV := LibraryFunctionList.CK_C_CloseAllSessions(slotID);
end;
function TPKCS11Token.GetXLabel(): string;
var
info: CK_TOKEN_INFO;
begin
Result := '';
if (GetTokenInfo(info)) then
begin
Result := UTF8CHARArrayToString(TCK_UTF8CHARArray_32(info.Xlabel));
end;
end;
function TPKCS11Token.GetManufacturerID(): string;
var
info: CK_TOKEN_INFO;
begin
Result := '';
if (GetTokenInfo(info)) then
begin
Result := UTF8CHARArrayToString(TCK_UTF8CHARArray_32(info.manufacturerID));
end;
end;
function TPKCS11Token.GetModel(): string;
var
info: CK_TOKEN_INFO;
begin
Result := '';
if (GetTokenInfo(info)) then
begin
Result := UTF8CHARArrayToString(TCK_UTF8CHARArray_16(info.model));
end;
end;
function TPKCS11Token.GetSerialNumber(): string;
var
info: CK_TOKEN_INFO;
begin
Result := '';
if (GetTokenInfo(info)) then
begin
Result := UTF8CHARArrayToString(TCK_UTF8CHARArray_16(info.serialNumber));
end;
end;
function TPKCS11Token.GetFlags(): CK_FLAGS;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.Flags;
end;
end;
function TPKCS11Token.GetMaxSessionCount(): cardinal;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.ulMaxSessionCount;
end;
end;
function TPKCS11Token.GetSessionCount(): cardinal;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.ulSessionCount;
end;
end;
function TPKCS11Token.GetMaxRwSessionCount(): cardinal;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.ulMaxRwSessionCount;
end;
end;
function TPKCS11Token.GetRwSessionCount(): cardinal;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.ulRwSessionCount;
end;
end;
function TPKCS11Token.GetMaxPinLen(): cardinal;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.ulMaxPinLen;
end;
end;
function TPKCS11Token.GetMinPinLen(): cardinal;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.ulMinPinLen;
end;
end;
function TPKCS11Token.GetTotalPublicMemory(): cardinal;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.ulTotalPublicMemory;
end;
end;
function TPKCS11Token.GetFreePublicMemory(): cardinal;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.ulFreePublicMemory;
end;
end;
function TPKCS11Token.GetTotalPrivateMemory(): cardinal;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.ulTotalPrivateMemory;
end;
end;
function TPKCS11Token.GetFreePrivateMemory(): cardinal;
var
info: CK_TOKEN_INFO;
begin
Result := 0;
if (GetTokenInfo(info)) then
begin
Result := info.ulFreePrivateMemory;
end;
end;
function TPKCS11Token.GetHardwareVersion(): CK_VERSION;
var
info: CK_TOKEN_INFO;
begin
Result := NULL_VERSION;
if (GetTokenInfo(info)) then
begin
Result := info.hardwareVersion;
end;
end;
function TPKCS11Token.GetFirmwareVersion(): CK_VERSION;
var
info: CK_TOKEN_INFO;
begin
Result := NULL_VERSION;
if (GetTokenInfo(info)) then
begin
Result := info.firmwareVersion;
end;
end;
function TPKCS11Token.GetUTCTime(): TDateTime;
var
info: CK_TOKEN_INFO;
strDate: string;
tmpChar: char;
yyyy: integer;
mo: integer;
dd: integer;
hh: integer;
mi: integer;
ss: integer;
i: integer;
begin
Result := NULL_TIME;
if (GetTokenInfo(info)) then
begin
strDate:= '';
for i:=low(info.utcTime) to high(info.utcTime) do
begin
tmpChar := char(info.utcTime[i]);
// This code only so it's easier to see what the value is when debugging
//if (
// (tmpChar < #32) or
// (tmpChar > #127)
// ) then
//begin
// tmpChar := '0';
//end;
strDate := strDate + tmpChar;
end;
// Testing date; should give 2nd Jan 2007 03:04:05
// strDate := '2007010203040500';
if (
TryStrToInt(Copy(strDate, 1, 4), yyyy) and
TryStrToInt(Copy(strDate, 5, 2), mo) and
TryStrToInt(Copy(strDate, 7, 2), dd) and
TryStrToInt(Copy(strDate, 9, 2), hh) and
TryStrToInt(Copy(strDate, 11, 2), mi) and
TryStrToInt(Copy(strDate, 13, 2), ss)
) then
begin
Result := EncodeDateTime(yyyy, mo, dd, hh, mi, ss, 00);
end;
end;
end;
function TPKCS11Token.GetCountMechanisms(): integer;
begin
Result := _GetCountMechanisms();
end;
function TPKCS11Token._GetCountMechanisms(): integer;
var
mechanismsArray: TPKCS11MechanismArray;
begin
Result := 0;
if GetMechanismList(mechanismsArray) then
begin
Result := length(mechanismsArray);
end;
end;
function TPKCS11Token.GetMechanismList(var mechsArray: TPKCS11MechanismArray): boolean;
var
ulCount: CK_ULONG;
mechType: CK_MECHANISM_TYPE;
ptrBuffer: CK_MECHANISM_TYPE_PTR;
ptrBufferOffset: CK_MECHANISM_TYPE_PTR;
bufferSize: integer;
i: integer;
mechObj: TPKCS11Mechanism;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_GetMechanismList, FN_NAME_C_GetMechanismList);
if (FCachedMechanismsArray <> nil) then
begin
mechsArray := FCachedMechanismsArray;
Result := TRUE;
exit;
end;
// Get count...
ulCount := 0;
LastRV := LibraryFunctionList.CK_C_GetMechanismList(FSlotID, nil, @ulCount);
if RVSuccess(LastRV) then
begin
// Get...
bufferSize := (sizeof(FSlotID) * ulCount);
ptrBuffer := allocmem(bufferSize);
try
LastRV := LibraryFunctionList.CK_C_GetMechanismList(FSlotID, ptrBuffer, @ulCount);
if RVSuccess(LastRV) then
begin
SetLength(mechsArray, ulCount);
ptrBufferOffset := ptrBuffer;
for i:=1 to ulCount do
begin
mechObj:= TPKCS11Mechanism.Create();
mechType := ptrBufferOffset^;
mechObj.LibraryFunctionList := LibraryFunctionList;
mechObj.SlotID := FSlotID;
mechObj.MechanismType := mechType;
mechsArray[i-1] := mechObj;
ptrBufferOffset := Pointer(PChar(ptrBufferOffset) + sizeof(ptrBufferOffset^));
end;
FCachedMechanismsArray := mechsArray;
end;
finally
FreeMem(ptrBuffer);
end;
end;
Result := RVSuccess(LastRV);
end;
function TPKCS11Token.GetMechanismByIdx(idx: integer): TPKCS11Mechanism;
var
mechanismsArray: TPKCS11MechanismArray;
begin
Result := nil;
if GetMechanismList(mechanismsArray) then
begin
// Sanity check
if ((low(mechanismsArray) + idx) > high(mechanismsArray)) then
begin
raise EPKCS11ListIndexOutOFBounds.Create(E_EPKCS11_LISTINDEXOUTOFBOUNDS);
end;
Result := mechanismsArray[(low(mechanismsArray) + idx)];
end;
end;
function TPKCS11Token.GetMechanismByType(mechType: CK_MECHANISM_TYPE): TPKCS11Mechanism;
var
mechanismsArray: TPKCS11MechanismArray;
i: integer;
begin
Result := nil;
if GetMechanismList(mechanismsArray) then
begin
for i:=low(mechanismsArray) to high(mechanismsArray) do
begin
if (mechanismsArray[i].MechanismType = mechType) then
begin
Result := mechanismsArray[i];
break;
end;
end;
end;
end;
procedure TPKCS11Token.SetCacheTokenInfo(flag: boolean);
begin
FCacheTokenInfo := flag;
// Flush any cached information
if not(FCacheTokenInfo) then
begin
FlushCache();
end;
end;
procedure TPKCS11Token.FlushCache();
begin
FCachedTokenInfoPresent := FALSE;
FillChar(FCachedTokenInfo, 0, sizeof(FCachedTokenInfo));
end;
function TPKCS11Token.InitToken(usePINPad: boolean; SOPIN: string; tokenLabel: string): boolean;
var
useTokenLabel: string;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_InitToken, FN_NAME_C_InitToken);
// Pad label out to 32 chars
useTokenLabel := tokenLabel + StringOfChar(' ', (32 - length(tokenLabel)));
if usePINPad then
begin
LastRV := LibraryFunctionList.CK_C_InitToken(
FSlotID,
NULL_PTR,
0,
CK_UTF8CHAR_PTR(PChar(useTokenLabel))
);
end
else
begin
LastRV := LibraryFunctionList.CK_C_InitToken(
FSlotID,
CK_UTF8CHAR_PTR(PChar(SOPIN)),
length(SOPIN),
CK_UTF8CHAR_PTR(PChar(useTokenLabel))
);
end;
Result := RVSuccess(LastRV);
end;
function TPKCS11Token.InitToken(tokenLabel: string): boolean;
begin
Result := InitToken(TRUE, '', tokenLabel);
end;
function TPKCS11Token.InitToken(SOPIN: string; tokenLabel: string): boolean;
begin
Result := InitToken(FALSE, SOPIN, tokenLabel);
end;
END.
|
unit uFormSelectLocation;
interface
uses
Winapi.Windows,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Dmitry.Controls.PathEditor,
Dmitry.PathProviders,
Dmitry.PathProviders.MyComputer,
VirtualTrees,
uMemory,
uThreadForm,
uFormInterfaces,
uPathProvideTreeView;
type
TFormSelectLocation = class(TThreadForm, ISelectLocationForm)
PePath: TPathEditor;
PnExplorer: TPanel;
BtnCancel: TButton;
BtnOk: TButton;
procedure BtnCancelClick(Sender: TObject);
procedure BtnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure PePathChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
FShellTreeView: TPathProvideTreeView;
procedure PathTreeViewChange(Sender: TCustomVirtualDrawTree; PathItem: TPathItem);
procedure PathTreeViewDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo);
protected
procedure InterfaceDestroyed; override;
function GetFormID: string; override;
public
{ Public declarations }
function Execute(Title, StartPath: string; out PathItem: TPathItem; AllowVirtualItems: Boolean): Boolean;
end;
implementation
{$R *.dfm}
{ TFormSelectLocation }
procedure TFormSelectLocation.BtnCancelClick(Sender: TObject);
begin
Close;
ModalResult := mrCancel;
end;
procedure TFormSelectLocation.BtnOkClick(Sender: TObject);
begin
Close;
ModalResult := mrOk;
end;
function TFormSelectLocation.Execute(Title, StartPath: string;
out PathItem: TPathItem; AllowVirtualItems: Boolean): Boolean;
var
StartItem: TPathItem;
begin
PathItem := nil;
FShellTreeView := TPathProvideTreeView.Create(Self);
FShellTreeView.Parent := PnExplorer;
FShellTreeView.LoadColorScheme;
FShellTreeView.Align := AlClient;
FShellTreeView.OnlyFileSystem := not AllowVirtualItems;
FShellTreeView.LoadHomeDirectory(Self);
FShellTreeView.OnSelectPathItem := PathTreeViewChange;
FShellTreeView.OnNodeDblClick := PathTreeViewDblClick;
PePath.OnlyFileSystem := True;
StartItem := PathProviderManager.CreatePathItem(StartPath);
try
if StartItem <> nil then
PePath.SetPathEx(Self, StartItem, True)
else
PePath.SetPathEx(THomeItem, '');
finally
F(StartItem);
end;
if Title <> '' then
Caption := Title;
ShowModal;
Result := ModalResult = mrOk;
if Result then
PathItem := PePath.PathEx.Copy;
F(FShellTreeView);
end;
procedure TFormSelectLocation.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TFormSelectLocation.FormCreate(Sender: TObject);
begin
BtnCancel.Caption := L('Cancel');
BtnOk.Caption := L('Ok');
end;
procedure TFormSelectLocation.FormDestroy(Sender: TObject);
begin
F(FShellTreeView);
end;
procedure TFormSelectLocation.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
function TFormSelectLocation.GetFormID: string;
begin
Result := 'SelectLocation';
end;
procedure TFormSelectLocation.InterfaceDestroyed;
begin
inherited;
Release;
end;
procedure TFormSelectLocation.PathTreeViewChange(Sender: TCustomVirtualDrawTree;
PathItem: TPathItem);
begin
PePath.SetPathEx(Sender, PathItem, False);
end;
procedure TFormSelectLocation.PathTreeViewDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo);
begin
if (HitInfo.HitNode <> nil) and (PePath.PathEx <> nil) then
BtnOkClick(Sender);
end;
procedure TFormSelectLocation.PePathChange(Sender: TObject);
begin
FShellTreeView.SelectPathItem(PePath.PathEx);
end;
initialization
FormInterfaces.RegisterFormInterface(ISelectLocationForm, TFormSelectLocation);
end.
|
//
// Title: SFDBGridInplaceCheckBox
//
// Description: A CheckBox that serves as InplaceEditor within a DBGrid
//
// Created by: Frank Huber
//
// Copyright: Frank Huber - The SoftwareFactory -
// Alberweilerstr. 1
// D-88433 Schemmerhofen
//
// http://www.thesoftwarefactory.de
//
unit SFDBGridInplaceCheckBox;
interface
uses
System.SysUtils, System.Classes, Vcl.DBCtrls, Vcl.Controls, Vcl.Grids,
Vcl.DBGrids, System.Types;
type
TSFDBGridInplaceCheckBox = class(TDBCheckBox)
private
mDBGrid: TDBGrid;
mColumnIdx: Integer;
mGrdDrawColCellSave: TDrawColumnCellEvent;
private
procedure setDBGrid(pVal: TDBGrid);
procedure setColumnIdx(pVal: Integer);
function findAssignedGrid(pParent: TWinControl; pName: String): TControl;
private
procedure grdDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer;
Column: TColumn; State: TGridDrawState);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoExit; override;
public
procedure Assign(Source: TPersistent); override;
public
constructor Create(pOwner: TComponent); override;
destructor Destroy; override;
published
property DBGrid: TDBGrid read mDBGrid write setDBGrid;
property ColIdx: Integer read mColumnIdx write setColumnIdx;
end;
implementation
uses Winapi.Windows, Data.DB;
constructor TSFDBGridInplaceCheckBox.Create(pOwner: TComponent);
begin
inherited;
mDBGrid := nil;
mColumnIdx := -1;
mGrdDrawColCellSave := nil;
end;
destructor TSFDBGridInplaceCheckBox.Destroy;
begin
inherited;
if (Assigned(mDBGrid)) then
begin
mDBGrid.OnDrawColumnCell := mGrdDrawColCellSave;
mDBGrid := nil;
end;
end;
procedure TSFDBGridInplaceCheckBox.Assign(Source: TPersistent);
var lNewGrd: TControl;
begin
inherited;
if (Source is TSFDBGridInplaceCheckBox) then
begin
if (Assigned(TSFDBGridInplaceCheckBox(Source).DBGrid)) then
begin
lNewGrd := findAssignedGrid(Parent, TSFDBGridInplaceCheckBox(Source).DBGrid.Name);
if (Assigned(lNewGrd)) and (lNewGrd is TDBGrid) then
DBGrid := TDBGrid(lNewGrd);
end;
ColIdx := TSFDBGridInplaceCheckBox(Source).ColIdx;
end;
end;
procedure TSFDBGridInplaceCheckBox.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (Assigned(mDBGrid)) and (AComponent = mDBGrid) then
mDBGrid := nil;
end;
procedure TSFDBGridInplaceCheckBox.DoExit;
begin
inherited;
if (Assigned(mDBGrid)) then
Visible := False;
end;
procedure TSFDBGridInplaceCheckBox.grdDrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
const
LC_CHECKSIZE = 15;
var
lInplaceRect, lCellRect: TRect;
lHandled: Boolean;
begin
inherited;
lHandled := False;
if (Assigned(mGrdDrawColCellSave)) then
begin
mGrdDrawColCellSave(Sender, Rect, DataCol, Column, State);
lHandled := True;
end;
if (Assigned(mDBGrid)) and (Assigned(DataSource)) and (DataSource = mDBGrid.DataSource)
and (Assigned(DataSource.DataSet)) and (DataCol = mColumnIdx) then
begin
if (mDBGrid.Focused) and (gdSelected in State) and
((DataSource.AutoEdit) or (DataSource.DataSet.State in [dsEdit, dsInsert]))
and (DataSource.DataSet.RecNo >= 1) then
begin
lInplaceRect := Rect;
lInplaceRect.Left := mDBGrid.Left + lInplaceRect.Left;
lInplaceRect.Top := mDBGrid.Top + lInplaceRect.Top;
lInplaceRect.Right := mDBGrid.Left + lInplaceRect.Right;
lInplaceRect.Bottom := mDBGrid.Top + lInplaceRect.Bottom;
Width := LC_CHECKSIZE;
Height := LC_CHECKSIZE;
Left := lInplaceRect.Left + ((lInplaceRect.Right - lInplaceRect.Left - LC_CHECKSIZE) div 2) + 2;
Top := lInplaceRect.Top + ((lInplaceRect.Bottom - lInplaceRect.Top - LC_CHECKSIZE) div 2) + 2;
Checked := (DataSource.DataSet.FieldByName(Column.FieldName).AsString = ValueChecked);
Visible := True;
BringToFront;
SetFocus;
end else
begin
lCellRect := Rect;
lCellRect.Top := lCellRect.Top + ((lCellRect.Bottom - lCellRect.Top - LC_CHECKSIZE) div 2);
lCellRect.Bottom := lCellRect.Top + LC_CHECKSIZE;
lCellRect.Left := lCellRect.Left + ((lCellRect.Right - lCellRect.Left - LC_CHECKSIZE) div 2);
lCellRect.Right := lCellRect.Left + LC_CHECKSIZE;
if (DataSource.DataSet.FieldByName(Column.FieldName).AsString = ValueChecked) then
DrawFrameControl(mDBGrid.Canvas.Handle, lCellRect, DFC_BUTTON, DFCS_CHECKED)
else
DrawFrameControl(mDBGrid.Canvas.Handle, lCellRect, DFC_BUTTON, DFCS_BUTTONCHECK);
end;
end else
if not(lHandled) then
mDBGrid.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
procedure TSFDBGridInplaceCheckBox.setDBGrid(pVal: TDBGrid);
begin
if (pVal <> mDBGrid) then
begin
if (Assigned(mDBGrid)) then
begin
mDBGrid.OnDrawColumnCell := mGrdDrawColCellSave;
mDBGrid.RemoveFreeNotification(Self);
end;
mDBGrid := pVal;
mGrdDrawColCellSave := mDBGrid.OnDrawColumnCell;
mDBGrid.OnDrawColumnCell := grdDrawColumnCell;
mDBGrid.FreeNotification(Self);
Visible := False;
if (mColumnIdx > -1) then
mDBGrid.Invalidate;
end;
end;
procedure TSFDBGridInplaceCheckBox.setColumnIdx(pVal: Integer);
begin
if (pVal <> mColumnIdx) then
begin
mColumnIdx := pVal;
Visible := False;
if (Assigned(mDBGrid)) then
mDBGrid.Invalidate;
end;
end;
function TSFDBGridInplaceCheckBox.findAssignedGrid(pParent: TWinControl; pName: String): TControl;
begin
Result := nil;
if not(Assigned(pParent)) then
Exit;
Result := pParent.FindChildControl(pName);
if not(Assigned(Result)) and (Assigned(pParent.Parent)) then
Result := findAssignedGrid(pParent.Parent, pName);
end;
end.
|
unit ServUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ScktComp, common, StdCtrls, FileCtrl, Buttons;
const
Version = ' 2.1';
type
TForm1 = class( TForm )
ServSock: TServerSocket;
Memo1: TMemo;
edtDir: TEdit;
StaticText1: TStaticText;
lbFiles: TListBox;
StaticText2: TStaticText;
sbSetDir: TSpeedButton;
procedure ServSockClientConnect( Sender: TObject;
Socket: TCustomWinSocket );
procedure ServSockClientDisconnect( Sender: TObject;
Socket: TCustomWinSocket );
procedure ServSockClientError( Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer );
procedure ServSockClientRead( Sender: TObject;
Socket: TCustomWinSocket );
procedure sbSetDirClick( Sender: TObject );
procedure ServSockListen( Sender: TObject; Socket: TCustomWinSocket );
procedure FormCreate( Sender: TObject );
private
{ Private declarations }
FServerDir: string;
public
{ Public declarations }
end;
var
Form1 : TForm1;
implementation
{$R *.DFM}
//*****************************************************************************
procedure TForm1.FormCreate( Sender: TObject );
begin
Caption := Caption + Version;
// set default directory;
FServerDir := ExtractFileDir( Application.ExeName );
EdtDir.Text := FServerDir;
EnumFiles( FServerDir + '\*.*', lbFiles.Items, false );
ServSock.Open;
end;
//*****************************************************************************
procedure TForm1.ServSockListen( Sender: TObject; Socket: TCustomWinSocket );
begin
Log( Memo1.Lines, ' server listening on port ' + IntTostr( ServSock.Port ) +
'...' );
end;
//*****************************************************************************
procedure TForm1.ServSockClientConnect( Sender: TObject;
Socket: TCustomWinSocket );
begin
Log( memo1.lines, 'client connect : ' + Socket.RemoteHost );
end;
//*****************************************************************************
procedure TForm1.ServSockClientDisconnect( Sender: TObject;
Socket: TCustomWinSocket );
begin
Log( memo1.lines, 'client disconnect : ' + Socket.RemoteHost );
end;
//*****************************************************************************
procedure TForm1.ServSockClientError( Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer );
begin
Log( memo1.lines, 'socketerror ' + IntToStr( ErrorCode ) );
Socket.Close;
ErrorCode := 0; // avoid exceptions !
end;
//*****************************************************************************
procedure TForm1.ServSockClientRead( Sender: TObject;
Socket: TCustomWinSocket );
var
Buf : string;
MsgLen,
LenReceived : integer;
Header : TMsgHeader;
begin
// get approximate message length
MsgLen := Socket.ReceiveLength;
// prepare a buffer and get message
SetLength( Buf, MsgLen );
LenReceived := Socket.ReceiveBuf( Buf[1], MsgLen );
// **always** adjust for actually received # of bytes!
Buf := Copy( Buf, 1, LenReceived );
if Length( Buf ) >= SizeOf( Header ) then
begin
// extract header
move( Buf[1], Header, SizeOf( Header ) );
// delete header from message
Delete( Buf, 1, SizeOf( Header ) );
//
case Header.OpCode of
MSG_REQUEST_FILE: begin
Log( memo1.Lines, 'sending ' + Buf
+ ' to ' + Socket.RemoteHost );
if SendFile( Socket, Buf ) then
Log( memo1.Lines, ' file sent.' )
else begin
Log( memo1.Lines, ' error while sending file.' );
Socket.Close;
end
end;
MSG_REQUEST_LIST: begin
Log( memo1.Lines, 'sending filelist'
+ ' to ' + Socket.RemoteHost );
SendFileList( Socket, FServerDir, '*.*' );
end;
else
SendError( Socket, MSG_ERR_ILLEGAL_CODE );
end;
end
else begin
Log( memo1.lines, 'message corrupt ! closing connection' );
Socket.Close;
end;
end;
//*****************************************************************************
procedure TForm1.sbSetDirClick( Sender: TObject );
begin
if SelectDirectory( FServerDir, [], 0 ) then
begin
edtDir.Text := FServerDir;
EnumFiles( FServerDir + '\*.*', lbFiles.Items, false );
end;
end;
end.
|
unit docs.unity;
interface
uses
Horse,
Horse.GBSwagger;
procedure registry();
implementation
uses schemas.classes;
procedure registry();
begin
Swagger
.Path('unidades/{id_unidade}')
.Tag('Unidades Medidas')
.GET('listar uma unidade medida', 'listar unidade de medida especifica')
.AddParamPath('id_unidade', 'id_unidade')
.Schema(SWAG_INTEGER)
.Required(true)
.&End
.AddParamHeader('Authorization', 'bearer token jwt')
.Schema(SWAG_STRING)
.&End
.AddResponse(200)
.Schema(TUnityPagination)
.&End
.AddResponse(404, 'unidade não encontrada')
.Schema(TMessage)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('unidades')
.Tag('Unidades Medidas')
.GET('listar unidade medidades com paginação', 'listagem de unidade medidas com paginação e filtros')
.Description('o query param find representa o nome de uma coluna do banco e value o valor que sera colocado no criterio de filtro exemplo: find=id&value=10')
.AddParamQuery('page', 'page')
.Schema(SWAG_INTEGER)
.&End
.AddParamQuery('limit', 'limit')
.Schema(SWAG_INTEGER)
.&End
.AddParamQuery('find', 'find')
.Schema(SWAG_STRING)
.&End
.AddParamQuery('value', 'value')
.Schema(SWAG_STRING)
.&End
.AddParamHeader('Authorization', 'bearer token jwt')
.Schema(SWAG_STRING)
.&End
.AddResponse(200)
.Schema(TUnity)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('unidades')
.Tag('Unidades Medidas')
.Post('criar unidade', 'criar uma nova unidade medidads')
.AddParamBody
.Schema(TUnity)
.&End
.AddParamHeader('Authorization', 'bearer token jwt')
.Schema(SWAG_STRING)
.&End
.AddResponse(201)
.Schema(TUnity)
.&End
.AddResponse(404, 'unidade medida não encontrada')
.Schema(TMessage)
.&End
.AddResponse(401, 'token não encontrado ou invalido')
.Schema(SWAG_STRING)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('unidades/{id_unidade}')
.Tag('Unidades Medidas')
.Put('alterar unidade medida ', 'alteração de uma unidades medida')
.AddParamPath('id_unidade', 'id_unidade')
.Schema(SWAG_INTEGER)
.&end
.AddParamBody
.Schema(TUnity)
.&End
.AddParamHeader('Authorization', 'bearer token jwt')
.Schema(SWAG_STRING)
.&End
.AddResponse(200)
.Schema(TRegion)
.&End
.AddResponse(404, 'unidade de medida não encontrada')
.Schema(TMessage)
.&End
.AddResponse(401, 'token não encontrado ou invalido')
.Schema(SWAG_STRING)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('unidades/{id_unidade}')
.Tag('Unidades Medidas')
.Delete('deletar unidade medida ', 'deletar uma unidade medida')
.AddParamPath('id_unidade', 'id_unidade')
.Schema(SWAG_INTEGER)
.&end
.AddParamHeader('Authorization', 'bearer token jwt')
.Schema(SWAG_STRING)
.&End
.AddResponse(200, 'unidade medida deletada com sucesso')
.Schema(TMessage)
.&End
.AddResponse(404, 'unidade não encontrada')
.Schema(TMessage)
.&End
.AddResponse(401, 'token não encontrado ou invalido, não foi possivel deletar a comunidade')
.Schema(SWAG_STRING)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
end;
end.
|
unit UDSQLExpressions;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeSQLExpressionsDlg = class(TForm)
pnlExpressions: TPanel;
lblExpression: TLabel;
lblExpressionName: TLabel;
lbNames: TListBox;
memoExpression: TMemo;
btnCheck: TButton;
btnCheckAll: TButton;
btnOk: TButton;
btnClear: TButton;
lblCount: TLabel;
editCount: TEdit;
gbFormat: TGroupBox;
lblFieldName: TLabel;
lblFieldType: TLabel;
lblFieldLength: TLabel;
lblTop: TLabel;
lblLeft: TLabel;
lblSection: TLabel;
lblWidth: TLabel;
lblHeight: TLabel;
editFieldName: TEdit;
editFieldType: TEdit;
editFieldLength: TEdit;
btnBorder: TButton;
btnFont: TButton;
btnFormat: TButton;
editTop: TEdit;
editLeft: TEdit;
editWidth: TEdit;
editHeight: TEdit;
cbSection: TComboBox;
rgUnits: TRadioGroup;
FontDialog1: TFontDialog;
btnHiliteConditions: TButton;
cbObjectPropertiesActive: TCheckBox;
procedure lbNamesClick(Sender: TObject);
procedure memoExpressionChange(Sender: TObject);
procedure btnCheckClick(Sender: TObject);
procedure btnCheckAllClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure UpdateSQLExpressions;
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure rgUnitsClick(Sender: TObject);
procedure editSizeEnter(Sender: TObject);
procedure editSizeExit(Sender: TObject);
procedure cbSectionChange(Sender: TObject);
procedure btnBorderClick(Sender: TObject);
procedure btnFontClick(Sender: TObject);
procedure btnFormatClick(Sender: TObject);
procedure btnHiliteConditionsClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure InitializeFormatControls(OnOff: boolean);
procedure cbObjectPropertiesActiveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
ExIndex : smallint;
PrevSize : string;
end;
var
CrpeSQLExpressionsDlg: TCrpeSQLExpressionsDlg;
bSQLExpressions : boolean;
implementation
{$R *.DFM}
uses TypInfo, UCrpeUtl, UDBorder, UDFormat, UDHiliteConditions,
UDFont, UCrpeClasses;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.FormCreate(Sender: TObject);
begin
bSQLExpressions := True;
LoadFormPos(Self);
btnOk.Tag := 1;
ExIndex := -1;
cbObjectPropertiesActive.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.FormShow(Sender: TObject);
begin
UpdateSQLExpressions;
end;
{------------------------------------------------------------------------------}
{ UpdateSQLExpressions }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.UpdateSQLExpressions;
var
OnOff : boolean;
i : integer;
begin
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
begin
OnOff := False;
ExIndex := -1;
end
else
begin
OnOff := (Cr.SQLExpressions.Count > 0);
{Get SQLExpressions Index}
if OnOff then
begin
if Cr.SQLExpressions.ItemIndex > -1 then
ExIndex := Cr.SQLExpressions.ItemIndex
else
ExIndex := 0;
end;
end;
cbObjectPropertiesActive.Checked := Cr.SQLExpressions.ObjectPropertiesActive;
InitializeControls(OnOff);
{Update list box}
if OnOff = True then
begin
for i := 0 to (Cr.SQLExpressions.Count - 1) do
lbNames.Items.Add(Cr.SQLExpressions[i].Name);
editCount.Text := IntToStr(Cr.SQLExpressions.Count);
lbNames.ItemIndex := ExIndex;
lbNamesClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TMemo then
begin
TMemo(Components[i]).Clear;
TMemo(Components[i]).Color := ColorState(OnOff);
TMemo(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ InitializeFormatControls }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.InitializeFormatControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
{Check Tag}
if TComponent(Components[i]).Tag <> 0 then
Continue;
{Make sure these components are owned by the Format groupbox}
if Components[i] is TButton then
begin
if TButton(Components[i]).Parent <> gbFormat then Continue;
TButton(Components[i]).Enabled := OnOff;
end;
if Components[i] is TRadioGroup then
begin
if TRadioGroup(Components[i]).Parent <> gbFormat then Continue;
TRadioGroup(Components[i]).Enabled := OnOff;
end;
if Components[i] is TComboBox then
begin
if TComboBox(Components[i]).Parent <> gbFormat then Continue;
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
if TEdit(Components[i]).Parent <> gbFormat then Continue;
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNamesClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.lbNamesClick(Sender: TObject);
var
OnOff : Boolean;
begin
ExIndex := lbNames.ItemIndex;
memoExpression.OnChange := nil;
memoExpression.Lines.Assign(Cr.SQLExpressions[ExIndex].Expression);
memoExpression.OnChange := memoExpressionChange;
{Activate Format options}
OnOff := (Cr.SQLExpressions.Item.Handle <> 0);
InitializeFormatControls(OnOff);
if OnOff then
begin
{Field Info}
editFieldName.Text := Cr.SQLExpressions.Item.FieldName;
editFieldType.Text := GetEnumName(TypeInfo(TCrFieldValueType),
Ord(Cr.SQLExpressions.Item.FieldType));
editFieldLength.Text := IntToStr(Cr.SQLExpressions.Item.FieldLength);
{Size and Position}
cbSection.ItemIndex := Cr.SectionFormat.IndexOf(Cr.SQLExpressions.Item.Section);
rgUnitsClick(Self);
end;
{Set HiliteConditions button}
btnHiliteConditions.Enabled := (Cr.SQLExpressions.Item.FieldType in [fvInt8s..fvCurrency])
and OnOff;
end;
{------------------------------------------------------------------------------}
{ memoExpressionChange }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.memoExpressionChange(Sender: TObject);
begin
Cr.SQLExpressions.Item.Expression.Assign(memoExpression.Lines);
end;
{------------------------------------------------------------------------------}
{ btnCheckClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.btnCheckClick(Sender: TObject);
begin
if Cr.SQLExpressions.Item.Check then
MessageDlg('SQLExpression is Good!', mtInformation, [mbOk], 0)
else
MessageDlg('SQLExpression has an Error.' + Chr(10) +
Cr.LastErrorString, mtError, [mbOk], 0);
end;
{------------------------------------------------------------------------------}
{ btnCheckAllClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.btnCheckAllClick(Sender: TObject);
var
i : integer;
s : string;
begin
Screen.Cursor := crHourglass;
lbNames.ItemIndex := 0;
for i := 0 to (lbNames.Items.Count - 1) do
begin
lbNames.ItemIndex:= i;
Cr.SQLExpressions[lbNames.ItemIndex];
memoExpression.OnChange := nil;
memoExpression.Lines.Assign(Cr.SQLExpressions.Item.Expression);
memoExpression.OnChange := memoExpressionChange;
Cr.SQLExpressions.Item.Expression.Assign(memoExpression.Lines);
if not Cr.SQLExpressions.Item.Check then
begin
MessageBeep(0);
s := 'The SQLExpression "' + Cr.SQLExpressions[i].Name + '" has an error!' +
Chr(10) + 'Continue checking?';
if Application.MessageBox(PChar(s), 'Formula Error', MB_OKCANCEL + MB_DEFBUTTON1) = IDOK then
Continue
else
Break;
end;
end;
if i = (lbNames.Items.Count) then
begin
MessageBeep(0);
MessageDlg('Finished verifying formulas!', mtInformation, [mbOk], 0)
end;
Screen.Cursor := crDefault;
end;
{------------------------------------------------------------------------------}
{ cbObjectPropertiesActiveClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.cbObjectPropertiesActiveClick(Sender: TObject);
begin
Cr.SQLExpressions.ObjectPropertiesActive := cbObjectPropertiesActive.Checked;
UpdateSQLExpressions;
end;
{------------------------------------------------------------------------------}
{ rgUnitsClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.rgUnitsClick(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
editTop.Text := TwipsToInchesStr(Cr.SQLExpressions.Item.Top);
editLeft.Text := TwipsToInchesStr(Cr.SQLExpressions.Item.Left);
editWidth.Text := TwipsToInchesStr(Cr.SQLExpressions.Item.Width);
editHeight.Text := TwipsToInchesStr(Cr.SQLExpressions.Item.Height);
end
else {twips}
begin
editTop.Text := IntToStr(Cr.SQLExpressions.Item.Top);
editLeft.Text := IntToStr(Cr.SQLExpressions.Item.Left);
editWidth.Text := IntToStr(Cr.SQLExpressions.Item.Width);
editHeight.Text := IntToStr(Cr.SQLExpressions.Item.Height);
end;
end;
{------------------------------------------------------------------------------}
{ editSizeEnter }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.editSizeEnter(Sender: TObject);
begin
if Sender is TEdit then
PrevSize := TEdit(Sender).Text;
end;
{------------------------------------------------------------------------------}
{ editSizeExit }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.editSizeExit(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
if not IsFloating(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.SQLExpressions.Item.Top := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.SQLExpressions.Item.Left := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editWidth' then
Cr.SQLExpressions.Item.Width := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editHeight' then
Cr.SQLExpressions.Item.Height := InchesStrToTwips(TEdit(Sender).Text);
UpdateSQLExpressions; {this will truncate any decimals beyond 3 places}
end;
end
else {twips}
begin
if not IsNumeric(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.SQLExpressions.Item.Top := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.SQLExpressions.Item.Left := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editWidth' then
Cr.SQLExpressions.Item.Width := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editHeight' then
Cr.SQLExpressions.Item.Height := StrToInt(TEdit(Sender).Text);
end;
end;
end;
{------------------------------------------------------------------------------}
{ cbSectionChange }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.cbSectionChange(Sender: TObject);
begin
Cr.SQLExpressions.Item.Section := cbSection.Items[cbSection.ItemIndex];
end;
{------------------------------------------------------------------------------}
{ btnBorderClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.btnBorderClick(Sender: TObject);
begin
CrpeBorderDlg := TCrpeBorderDlg.Create(Application);
CrpeBorderDlg.Border := Cr.SQLExpressions.Item.Border;
CrpeBorderDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnFontClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.btnFontClick(Sender: TObject);
begin
if Cr.Version.Crpe.Major > 7 then
begin
CrpeFontDlg := TCrpeFontDlg.Create(Application);
CrpeFontDlg.Crf := Cr.SQLExpressions.Item.Font;
CrpeFontDlg.ShowModal;
end
else
begin
FontDialog1.Font.Assign(Cr.SQLExpressions.Item.Font);
if FontDialog1.Execute then
Cr.SQLExpressions.Item.Font.Assign(FontDialog1.Font);
end;
end;
{------------------------------------------------------------------------------}
{ btnFormatClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.btnFormatClick(Sender: TObject);
begin
CrpeFormatDlg := TCrpeFormatDlg.Create(Application);
CrpeFormatDlg.Format := Cr.SQLExpressions.Item.Format;
CrpeFormatDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnHiliteConditionsClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.btnHiliteConditionsClick(Sender: TObject);
begin
CrpeHiliteConditionsDlg := TCrpeHiliteConditionsDlg.Create(Application);
CrpeHiliteConditionsDlg.Crh := Cr.SQLExpressions.Item.HiliteConditions;
CrpeHiliteConditionsDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.btnClearClick(Sender: TObject);
begin
Cr.SQLExpressions.Clear;
UpdateSQLExpressions;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.btnOkClick(Sender: TObject);
begin
rgUnits.ItemIndex := 1; {change to twips to avoid the Update call}
if (not IsStrEmpty(Cr.ReportName)) and (ExIndex > -1) then
begin
editSizeExit(editTop);
editSizeExit(editLeft);
editSizeExit(editWidth);
editSizeExit(editHeight);
end;
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeSQLExpressionsDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bSQLExpressions := False;
Release;
end;
end.
|
Unit Itimer ;
{ * Itimer : *
* *
* Esta unidad se encarga de los timers y el despertador de usuario *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* *
* 03 / 04 / 05 : Son redefinidas las syscalls *
* *
* 22 / 04 / 04 : Creacion de las llamadas al sistema *
* *
* 21 / 12 / 03 : Creo Alarmas que no duermen al proc *
* *
* 05 / 12 / 03 : Primera version *
* *
**********************************************************************
}
{DEFINE DEBUG}
interface
{$I ../include/toro/procesos.inc}
{$I ../include/toro/signal.inc}
{$I ../include/head/gdt.h}
{$I ../include/head/mm.h}
{$I ../include/head/asm.h}
{$I ../include/head/procesos.h }
{$I ../include/head/relog.h}
{$I ../include/head/scheduler.h}
{$I ../include/head/signal.h}
{$I ../include/head/printk_.h}
{ Simbolos utilizados para la cola ligada de timers }
{$DEFINE Use_Tail }
{$DEFINE nodo_struct := p_timer_user }
{$DEFINE next_nodo := next_timer }
{$DEFINE prev_nodo := prev_timer }
{$DEFINE nodo_tail := Tq_Alarmas }
{ Macros creados solo para comodidad }
{$DEFINE Push_Timer := Push_Node }
{$DEFINE Pop_Timer := Pop_Node }
const tq_Alarmas: p_timer_user = nil;
tq_Dormidas : p_tarea_Struc = nil;
var Contador : dword ;
implementation
{$I ../include/head/list.h}
{ * Sys_Setitimer : *
* *
* entry : Puntero donde se devera ir luego de la alarm *
* miliseg : Numero de mileseg de la alarma *
* *
* implementacion de la llamada al sistema para colocar una alarma *
* en el proceso actual , si hubiese otra alarma esta es quitada *
* *
*******************************************************************
}
procedure sys_setitimer(miliseg:dword);cdecl;[public , alias :'SYS_SETITIMER'];
begin
if (tarea_actual^.timer.estado) then
begin
tarea_actual^.timer.timer.interval := miliseg;
tarea_actual^.timer.timer.time_action := contador + miliseg;
end
else
begin
tarea_actual^.timer.estado := true ;
tarea_actual^.timer.timer.interval := miliseg;
tarea_actual^.timer.timer.time_action := contador + miliseg;
Push_Timer (@tarea_actual^.timer);
end;
{$IFDEF DEBUG}
printk('/nAlarma --> Pid : %d en : %d miliseg\n',[tarea_actual^.pid , miliseg],[]);
{$ENDIF}
end;
{ * Sys_getitimer : *
* *
* Esta funcion devuelve de cuanto se ha colocado el intervalo del timer *
* *
*************************************************************************
}
function sys_getitimer:dword;cdecl;[public , alias : 'SYS_GETITIMER'];
begin
exit(Tarea_Actual^.timer.timer.interval);
end;
{ * Sys_Sleep :
* *
* miliseg : Numero de milisegundos que el proceso permanecera *
* dormido *
* *
* Llamada el sistema que duerme un proceso , dado en miliseg *
* si tuviera alguna alarma esta es eliminada *
* *
*****************************************************************
}
function sys_sleep(miliseg:dword):dword;cdecl;[public , alias :'SYS_SLEEP'];
var ret:word;
tarea:p_tarea_struc;
begin
{ Los timers puestos son eliminados }
If (Tarea_Actual^.timer.estado) then
begin
Pop_Timer(@Tarea_Actual^.timer);
Tarea_Actual^.timer.estado := false;
end;
{ Calculo segun el relog del sistema }
tarea_Actual^.Despertador.interval := miliseg;
tarea_Actual^.Despertador.time_action := contador + miliseg;
{ la tarea se duerme }
Proceso_Interrumpir (Tarea_Actual , tq_dormidas);
end;
{ * Timer_Inc : *
* *
* Este procedimiento es llamado en cada irq de relog y mantiene el *
* contador del sistema y los timers *
* *
***********************************************************************
}
procedure timer_Inc;[public , alias :'TIMER_INC'];
var tarea_d,Tarea_p : p_tarea_struc;
timer_tmp , timer_t : p_timer_user;
begin
{ Incremento el contador del Sistema }
contador += 1;
tarea_d := tq_dormidas;
If (tq_dormidas <> nil) then
begin
repeat
{ Esta Tarea cumplio su tiempo ? , entonces la despierto }
if (tarea_d^.Despertador.time_action <= contador) then
begin
Tarea_p := Tarea_d^.prev_tarea;
Proceso_Reanudar (tarea_d , tq_dormidas);
Tarea_d := Tarea_p;
end;
{ Se continua la busqueda }
Tarea_d := Tarea_d^.next_tarea;
until (Tarea_D=tq_dormidas) or (tq_dormidas=nil) ;
end;
{ Ahora busco tareas con alarmas }
if (tq_alarmas = nil) then exit;
timer_tmp := tq_alarmas;
repeat
{ el timer vencio!!! }
if (Timer_tmp^.timer.time_action <= contador) then
begin
timer_tmp^.estado := false;
timer_t := timer_tmp^.prev_timer ;
{ se quita el timer y se envia la se¤al }
Pop_Timer(timer_tmp);
Signal_Send(Timer_tmp^.tarea,SIG_ALARM);
timer_tmp := timer_t ;
end;
{ Continuo con la ejecucion }
timer_tmp := timer_tmp^.next_timer;
until (Timer_tmp = tq_alarmas);
end;
end.
|
unit uRDMLookupInventory;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Windows, Messages, SysUtils, Classes, ComServ, ComObj, VCLCom, DataBkr,
DBClient, MRAppServer_TLB, StdVcl, ADODB, DB, Provider, mrConfigLookupSvr,
mrConfigLookupCli;
type
TRDMLookupInventory = class(TRemoteDataModule, IRDMLookupInventory)
dspLuManufacturer: TDataSetProvider;
quLuManufacturer: TADOQuery;
quLuModel: TADOQuery;
dspLuModel: TDataSetProvider;
quLuColor: TADOQuery;
quLuSize: TADOQuery;
dspLuColor: TDataSetProvider;
dspLuSize: TDataSetProvider;
quLuCategory: TADOQuery;
dspLuCategory: TDataSetProvider;
dspLuGroup: TDataSetProvider;
dspLuSubCategory: TDataSetProvider;
quLuGroup: TADOQuery;
quLuSubCategory: TADOQuery;
clCaterory: TmrConfigLookupSvr;
quLuDefectType: TADOQuery;
dspLuDefectType: TDataSetProvider;
clLuDefectType: TmrConfigLookupSvr;
private
FIRDMApplicationHub: IRDMApplicationHub;
FSQLConnection: TADOConnection;
procedure SetConnection;
protected
class procedure UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); override;
function Get_RDMApplicationHub: IRDMApplicationHub; safecall;
procedure Set_RDMApplicationHub(const Value: IRDMApplicationHub); safecall;
end;
var
RDMLookupInventory: TRDMLookupInventory;
RDMLookupInventoryFactory: TComponentFactory;
implementation
{$R *.DFM}
class procedure TRDMLookupInventory.UpdateRegistry(Register: Boolean; const ClassID, ProgID: string);
begin
if Register then
begin
inherited UpdateRegistry(Register, ClassID, ProgID);
EnableSocketTransport(ClassID);
EnableWebTransport(ClassID);
end else
begin
DisableSocketTransport(ClassID);
DisableWebTransport(ClassID);
inherited UpdateRegistry(Register, ClassID, ProgID);
end;
end;
function TRDMLookupInventory.Get_RDMApplicationHub: IRDMApplicationHub;
begin
Result := FIRDMApplicationHub;
end;
procedure TRDMLookupInventory.Set_RDMApplicationHub(
const Value: IRDMApplicationHub);
begin
FIRDMApplicationHub := Value;
FSQLConnection := TADOConnection(FIRDMApplicationHub.SQLConnection);
SetConnection;
end;
procedure TRDMLookupInventory.SetConnection;
var
i: Integer;
begin
for i := 0 to Pred(ComponentCount) do
if Components[i] is TADOQuery then
TADOQuery(Components[i]).Connection := FSQLConnection;
end;
initialization
RDMLookupInventoryFactory := TComponentFactory.Create(ComServer, TRDMLookupInventory,
Class_RDMLookupInventory, ciInternal, tmApartment);
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvMemo, Vcl.StdCtrls;
const
DEMO_TITLE = 'FNC Core Utils - MIME demo';
DEMO_BUTTON = 'Execute';
type
TFrmMain = class(TForm)
btnExecute: TButton;
txtLog: TAdvMemo;
procedure btnExecuteClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure DoExecute;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses TMSFNCUtils;
procedure TFrmMain.btnExecuteClick(Sender: TObject);
begin
DoExecute;
end;
procedure TFrmMain.DoExecute;
var
LFilename : String;
begin
LFilename := 'test.pdf';
var LMIMEType := TTMSFNCUtils.GetMimeType(LFilename);
txtLog.Lines.Add( LMIMEType );
txtLog.Lines.Add( TTMSFNCUtils.GetFileExtension(LMIMEType));
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
btnExecute.Caption := DEMO_BUTTON;
self.Caption := DEMO_TITLE;
txtLog.Lines.Clear;
end;
end.
|
unit fos_mos_monitoringapp;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
Licence conditions
(§LIC_END)
}
{$codepage UTF8}
{$mode objfpc}{$H+}
{$modeswitch nestedprocvars}
interface
uses
Classes, SysUtils,
FOS_TOOL_INTERFACES,
FRE_DB_INTERFACE,
FRE_DB_COMMON,
fos_mos_monitoring_mod,
fre_hal_disk_enclosure_pool_mangement,
fre_zfs,
fre_scsi,
fre_hal_schemes,
fre_monitoring,
fre_hal_mos;
type
{ TFOS_CITYCOM_MONITORING_APP }
TFOS_CITYCOM_MONITORING_APP=class(TFRE_DB_APPLICATION)
private
procedure _UpdateSitemap (const session: TFRE_DB_UserSession);
protected
procedure SetupApplicationStructure ; override;
procedure MySessionInitialize (const session: TFRE_DB_UserSession);override;
procedure MySessionPromotion (const session: TFRE_DB_UserSession); override;
public
class procedure RegisterSystemScheme (const scheme:IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class procedure InstallDBObjects4Domain (const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID); override;
class procedure InstallDBObjects4SysDomain (const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID); override;
class procedure InstallUserDBObjects (const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType); override;
published
function WEB_MOS_DATA_FEED (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
end;
procedure Register_DB_Extensions;
implementation
procedure Register_DB_Extensions;
begin
fos_mos_monitoring_mod.Register_DB_Extensions;
GFRE_DBI.RegisterObjectClassEx(TFOS_CITYCOM_MONITORING_APP);
//GFRE_DBI.Initialize_Extension_Objects;
end;
{ TFOS_CITYCOM_MONITORING_APP }
procedure TFOS_CITYCOM_MONITORING_APP.SetupApplicationStructure;
begin
inherited SetupApplicationStructure;
InitApp('description');
AddApplicationModule(TFOS_CITYCOM_MOS_PHYSICAL_MOD.create);
AddApplicationModule(TFOS_CITYCOM_MOS_LOGICAL_MOD.create);
end;
procedure TFOS_CITYCOM_MONITORING_APP._UpdateSitemap(const session: TFRE_DB_UserSession);
var
SiteMapData : IFRE_DB_Object;
conn : IFRE_DB_CONNECTION;
begin
conn:=session.GetDBConnection;
SiteMapData := GFRE_DBI.NewObject;
FREDB_SiteMap_AddRadialEntry(SiteMapData,'MOS',FetchAppTextShort(session,'sitemap_main'),'images_apps/citycom_monitoring/main_white.svg','',0,conn.sys.CheckClassRight4MyDomain(sr_FETCH,TFOS_CITYCOM_MONITORING_APP));
FREDB_SiteMap_AddRadialEntry(SiteMapData,'MOS/Physical',FetchAppTextShort(session,'sitemap_physical'),'images_apps/citycom_monitoring/physical_white.svg',TFOS_CITYCOM_MOS_PHYSICAL_MOD.Classname,0,conn.sys.CheckClassRight4MyDomain(sr_FETCH,TFOS_CITYCOM_MOS_PHYSICAL_MOD));
FREDB_SiteMap_AddRadialEntry(SiteMapData,'MOS/Logical',FetchAppTextShort(session,'sitemap_logical'),'images_apps/citycom_monitoring/logical_white.svg',TFOS_CITYCOM_MOS_LOGICAL_MOD.Classname,0,conn.sys.CheckClassRight4MyDomain(sr_FETCH,TFOS_CITYCOM_MOS_LOGICAL_MOD));
FREDB_SiteMap_RadialAutoposition(SiteMapData);
session.GetSessionAppData(Classname).Field('SITEMAP').AsObject := SiteMapData;
end;
procedure TFOS_CITYCOM_MONITORING_APP.MySessionInitialize(const session: TFRE_DB_UserSession);
begin
inherited MySessionInitialize(session);
if session.IsInteractiveSession then begin
_UpdateSitemap(session);
end;
end;
procedure TFOS_CITYCOM_MONITORING_APP.MySessionPromotion(const session: TFRE_DB_UserSession);
begin
inherited MySessionPromotion(session);
if session.IsInteractiveSession then
_UpdateSitemap(session);
end;
class procedure TFOS_CITYCOM_MONITORING_APP.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName('TFRE_DB_APPLICATION');
end;
class procedure TFOS_CITYCOM_MONITORING_APP.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
CreateAppText(conn,'caption','Monitoring','Monitoring','Monitoring');
CreateAppText(conn,'sitemap_main','Main','','Main');
CreateAppText(conn,'sitemap_logical','Logical','','Logical');
CreateAppText(conn,'sitemap_physical','Physical','','Physical');
end;
end;
class procedure TFOS_CITYCOM_MONITORING_APP.InstallDBObjects4Domain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
inherited InstallDBObjects4Domain(conn, currentVersionId, domainUID);
if currentVersionId='' then begin
//ADMINS
CheckDbResult(conn.AddGroup('MOSADMINS','Admins of Citycom Monitoring','Monitoring Admins',domainUID),'could not create admins group');
CheckDbResult(conn.AddRolesToGroup('MOSADMINS',domainUID,TFRE_DB_StringArray.Create(
TFOS_CITYCOM_MONITORING_APP.GetClassRoleNameFetch,
TFOS_CITYCOM_MOS_PHYSICAL_MOD.GetClassRoleNameFetch,
TFOS_CITYCOM_MOS_LOGICAL_MOD.GetClassRoleNameFetch
)),'could not add roles for group Admins');
CheckDbResult(conn.AddRolesToGroup('MOSADMINS',domainUID, TFRE_DB_VIRTUALMOSOBJECT.GetClassStdRoles),'could not add roles TFRE_DB_VIRTUALSERVICE for group Admins');
CheckDbResult(conn.AddRolesToGroup('MOSADMINS',domainUID, TFRE_DB_ZFS_POOL.GetClassStdRoles(false,false,false,true)),'could not add roles TFRE_DB_ZFS_POOL for group Admins');
CheckDbResult(conn.AddRolesToGroup('MOSADMINS',domainUID, TFRE_DB_ZFS_DATASTORAGE.GetClassStdRoles(false,false,false,true)),'could not add roles TFRE_DB_ZFS_POOL for group Admins');
//MANAGERS
CheckDbResult(conn.AddGroup('MOSMANAGERS','Managers of Citycom Monitoring','Monitoring Managers',domainUID),'could not create managers group');
CheckDbResult(conn.AddRolesToGroup('MOSMANAGERS',domainUID,TFRE_DB_StringArray.Create(
TFOS_CITYCOM_MONITORING_APP.GetClassRoleNameFetch,
TFOS_CITYCOM_MOS_PHYSICAL_MOD.GetClassRoleNameFetch,
TFOS_CITYCOM_MOS_LOGICAL_MOD.GetClassRoleNameFetch
)),'could not add roles for group Managers');
CheckDbResult(conn.AddRolesToGroup('MOSMANAGERS',domainUID, TFRE_DB_VIRTUALMOSOBJECT.GetClassStdRoles(true,true,false,true)),'could not add roles TFRE_DB_VIRTUALSERVICE for group Managers');
//VIEWERS
CheckDbResult(conn.AddGroup('MOSVIEWERS','Viewers of Citycom Monitoring','Monitoring Viewers',domainUID),'could not create viewers group');
CheckDbResult(conn.AddRolesToGroup('MOSVIEWERS',domainUID,TFRE_DB_StringArray.Create(
TFOS_CITYCOM_MONITORING_APP.GetClassRoleNameFetch,
TFOS_CITYCOM_MOS_PHYSICAL_MOD.GetClassRoleNameFetch,
TFOS_CITYCOM_MOS_LOGICAL_MOD.GetClassRoleNameFetch
)),'could not add roles for group Viewers');
CheckDbResult(conn.AddRolesToGroup('MOSVIEWERS',domainUID, TFRE_DB_VIRTUALMOSOBJECT.GetClassStdRoles(false,false,false,true)),'could not add roles TFRE_DB_VIRTUALSERVICE for group Viewers');
end;
end;
class procedure TFOS_CITYCOM_MONITORING_APP.InstallDBObjects4SysDomain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
inherited InstallDBObjects4Domain(conn, currentVersionId, domainUID);
if currentVersionId='' then begin
//FEEDER
CheckDbResult(conn.AddGroup('MONITORFEEDER','Group for Storage Data Feeder','Storage Feeder',domainUID),'could not create Storage feeder group');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID,TFRE_DB_StringArray.Create(
TFOS_CITYCOM_MONITORING_APP.GetClassRoleNameFetch
)),'could not add roles for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_VIRTUALMOSOBJECT.GetClassStdRoles),'could not add roles TFRE_DB_VIRTUALMOSOBJECT for group MONITOREFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_MOS_SNMP.GetClassStdRoles),'could not add roles TFRE_DB_MOS_SNMP for group MONITOREFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_MACHINE.GetClassStdRoles),'could not add roles TFRE_DB_MACHINE for group MONITOREFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_ZFS_POOL.GetClassStdRoles),'could not add roles TFRE_DB_ZFS_POOL for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_ZFS_BLOCKDEVICE.GetClassStdRoles),'could not add roles TFRE_DB_ZFS_BLOCKDEVICE for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_ZFS_CONTAINER.GetClassStdRoles),'could not add roles TFRE_DB_ZFS_CONTAINER for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_ZFS_REPLACEDISK.GetClassStdRoles),'could not add roles TFRE_DB_ZFS_REPLACEDISK for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_ZFS_VDEV_RAIDMIRROR.GetClassStdRoles),'could not add roles TFRE_DB_ZFS_VDEV_RAIDMIRROR for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_ZFS_DATASTORAGE.GetClassStdRoles),'could not add roles TFRE_DB_ZFS_DATASTORAGE for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_ZFS_LOG.GetClassStdRoles),'could not add roles TFRE_DB_ZFS_LOG for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_ZFS_CACHE.GetClassStdRoles),'could not add roles TFRE_DB_ZFS_CACHE for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_ZFS_SPARE.GetClassStdRoles),'could not add roles TFRE_DB_ZFS_SPARE for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_PHYS_DISK.GetClassStdRoles),'could not add roles TFRE_DB_PHYS_DISK for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_SAS_DISK.GetClassStdRoles),'could not add roles TFRE_DB_SAS_DISK for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_SATA_DISK.GetClassStdRoles),'could not add roles TFRE_DB_SATA_DISK for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_ENCLOSURE.GetClassStdRoles),'could not add roles TFRE_DB_ENCLOSURE for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_SAS_EXPANDER.GetClassStdRoles),'could not add roles TFRE_DB_SAS_EXPANDER for group MONITORFEEDER');
CheckDbResult(conn.AddRolesToGroup('MONITORFEEDER',domainUID, TFRE_DB_DRIVESLOT.GetClassStdRoles),'could not add roles TFRE_DB_DRIVESLOT for group MONITORFEEDER');
end;
end;
class procedure TFOS_CITYCOM_MONITORING_APP.InstallUserDBObjects(const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType);
begin
CreateMonitoringCollections(conn);
CreateDiskDataCollections(conn);
if currentVersionId='' then begin
currentVersionId := '1.0';
end;
end;
function TFOS_CITYCOM_MONITORING_APP.WEB_MOS_DATA_FEED(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
//var
// i : NativeInt;
// moscollection : IFRE_DB_COLLECTION;
// mos_parent_id : TFRE_DB_GUID;
//
// procedure _processUpdates(const updatestep:TFRE_DB_UPDATE_TRANSPORT);
// var update_type : TFRE_DB_ObjCompareEventType;
// obj_id : TFRE_DB_GUID;
// target_obj : IFRE_DB_Object;
// res : TFRE_DB_Errortype;
//
//
// procedure _setStatus(const db_mos:TFRE_DB_VIRTUALMOSOBJECT);
// begin
// if db_mos.Field('res_boolean').AsBoolean then
// db_mos.SetMOSStatus(fdbstat_ok,nil,nil,nil,conn)
// else
// db_mos.SetMOSStatus(fdbstat_error,nil,nil,nil,conn);
// end;
//
// procedure _updateAddVirtualMos(const mosobj:TFRE_DB_VIRTUALMOSOBJECT);
// var key_mos : TFRE_DB_NameType;
// db_mos : TFRE_DB_VIRTUALMOSOBJECT;
// dbo : IFRE_DB_Object;
//
//
//
// procedure __insertmos;
// begin
// dbo := mosobj.CloneToNewObject();
// db_mos := dbo.Implementor_HC as TFRE_DB_VIRTUALMOSOBJECT;
// db_mos.Field('mosparentIds').AsObjectLink := mos_parent_id;
//// db_machine.Field('caption_mos').AsString:=machinename;
// CheckDbResult(moscollection.Store(db_mos),'store mos in moscollection');
// conn.Fetch(mosobj.UID,dbo);
// db_mos := dbo.Implementor_HC as TFRE_DB_VIRTUALMOSOBJECT;
// _setStatus(db_mos);
// GFRE_DBI.LogInfo(dblc_APPLICATION,'Added Mos Object [%s] uid [%s] to db', [key_mos,mosobj.UID_String]);
// end;
//
// procedure __deletemos;
// begin
// CheckDbResult(conn.Delete(dbo.UID),'could not delete mos uid ['+dbo.UID_String+']');
// end;
//
// procedure __updatemos;
// begin
// db_mos := dbo.Implementor_HC as TFRE_DB_VIRTUALMOSOBJECT;
// db_mos.SetAllSimpleObjectFieldsFromObject(mosobj);
// _setStatus(db_mos);
//// CheckDbResult(moscollection.update(db_mos),'update mos in moscollection');
// end;
//
// begin
// key_mos := mosobj.GetMOSKey;
// if moscollection.GetIndexedObj(key_mos,dbo) then
// begin
// if dbo.UID<>mosobj.UID then // delete if UID is not matching
// begin
// __deletemos;
// __insertmos;
// end
// else
// begin
// __updatemos;
// end;
// end
// else
// begin
// __insertmos;
// end;
// end;
//
//
// begin
// writeln('SWL: UPDATESTEP ',updatestep.DumpToString);
// update_type := updatestep.GetType;
// if updatestep.GetIsChild=false then // root object with machines
// begin
// case update_type of
// cev_FieldDeleted:
// begin
// raise EFRE_DB_Exception.Create(edb_ERROR,'Unsupported field delete for subobjects in root object [%s] ',[updatestep.DumpToString()]);
// end;
// cev_FieldAdded:
// begin
// if updatestep.GetNewField.FieldType<>fdbft_Object then
// begin
// raise EFRE_DB_Exception.Create(edb_ERROR,'Unsupported field add for simple fields in root object [%s] ',[updatestep.DumpToString()]);
// end
// else
// begin
// if (updatestep.GetNewField.AsObject.Implementor_HC is TFRE_DB_VIRTUALMOSOBJECT) then
// begin
// _updateAddVirtualMos ((updatestep.GetNewField.AsObject.Implementor_HC as TFRE_DB_VIRTUALMOSOBJECT));
// end
// else
// raise EFRE_DB_Exception.Create(edb_ERROR,'Unsupported field add for other subobjects than TFRE_DB_VIRTUALMOSOBJECT [%s] ',[updatestep.DumpToString()]);
// end;
// end;
// cev_FieldChanged:
// begin
// raise EFRE_DB_Exception.Create(edb_ERROR,'Unsupported field change for subobjects in root class [%s] ',[updatestep.DumpToString()]);
// end;
// else
// raise EFRE_DB_Exception.Create(edb_ERROR,'Invalid Update Type [%s] for id [%s]',[Inttostr(Ord(updatestep.GetType)),FREDB_G2H(updatestep.UID)]);
// end;
// end
// else
// begin
// obj_id := updatestep.UID;
// CheckDbResult(conn.Fetch(obj_id,target_obj),'could not fetch object for update');
// case update_type of
// cev_FieldDeleted:
// begin
// if updatestep.GetOldField.FieldType<>fdbft_Object then
// begin
// writeln('SWL GENERIC DELETE SIMPLE FIELD:',updatestep.GetUpdateScheme,' ',updatestep.GetOldFieldName);
// target_obj.DeleteField(updatestep.GetOldFieldName);
// CheckDBResult(conn.Update(target_obj),'could not update generic object after field delete');
// end
// else
// begin
// writeln('SWL GENERIC DELETE OBJECT:',updatestep.DumpToString);
// end;
// end;
// cev_FieldAdded:
// begin
// writeln('SWL GENERIC ADD:',updatestep.DumpToString);
// if updatestep.GetNewField.FieldType<>fdbft_Object then
// begin
// writeln('SWL GENERIC ADD SIMPLE FIELD:',updatestep.GetUpdateScheme,' ',updatestep.GetNewFieldName);
// target_obj.Field(updatestep.GetNewFieldName).CloneFromField(updatestep.GetNewField);
// CheckDBResult(conn.Update(target_obj),'could not update generic object after field add');
// end
// else
// begin
// writeln('SWL GENERIC ADD OBJECT:',updatestep.DumpToString);
// end;
// end;
// cev_FieldChanged:
// begin
// if updatestep.GetNewField.FieldType<>fdbft_Object then
// begin
// res := conn.Fetch(updatestep.UID,target_obj);
// if res=edb_NOT_FOUND then
// begin
// GFRE_DBI.LogWarning(dblc_APPLICATION,'could not fetch object for field update',[FREDB_G2H(updatestep.UID)]);
// exit;
// end;
// writeln('SWL GENERIC UPDATE:',target_obj.SchemeClass,' ',updatestep.GetNewFieldName);
//
// target_obj.Field(updatestep.GetNewFieldName).CloneFromField(updatestep.GetNewField);
// if (target_obj.Implementor_HC is TFRE_DB_VIRTUALMOSOBJECT) then
// _setStatus((target_obj.Implementor_HC as TFRE_DB_VIRTUALMOSOBJECT));
// CheckDBResult(conn.Update(target_obj),'could not update generic object');
// end;
// end
// else
// raise EFRE_DB_Exception.Create(edb_ERROR,'Invalid Update Type [%s] for id [%s]',[Inttostr(Ord(updatestep.GetType)),FREDB_G2H(obj_id)]);
// end;
// end;
// end;
begin
abort;
//moscollection:= conn.GetCollection(CFRE_DB_MOS_COLLECTION);
//if moscollection.GetIndexedUID('RZNORD',mos_parent_id)=false then
// raise EFRE_DB_Exception.Create(edb_ERROR,'Could not find RZNORD mos object');
//if input.FieldExists('UPDATE') then
// begin
// for i := 0 to input.Field('UPDATE').ValueCount-1 do
// begin
// _processUpdates((input.Field('UPDATE').AsObjectItem[i].Implementor_HC as TFRE_DB_UPDATE_TRANSPORT));
// end;
// end;
//result := GFRE_DB_NIL_DESC;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uGeolocation;
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
uCEFChromium, uCEFWindowParent, uCEFInterfaces, uCEFApplication, uCEFTypes, uCEFConstants;
const
MINIBROWSER_NEWLOCATION = WM_APP + $100;
type
TGeolocationFrm = class(TForm)
CEFWindowParent1: TCEFWindowParent;
Chromium1: TChromium;
NavControlPnl: TPanel;
Edit1: TEdit;
GoBtn: TButton;
StatusBar1: TStatusBar;
Timer1: TTimer;
procedure Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser);
procedure GoBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
protected
procedure BrowserCreatedMsg(var aMessage : TMessage); message CEF_AFTERCREATED;
procedure NewLocationMsg(var aMessage : TMessage); message MINIBROWSER_NEWLOCATION;
procedure WMMove(var aMessage : TWMMove); message WM_MOVE;
procedure WMMoving(var aMessage : TMessage); message WM_MOVING;
procedure WMEnterMenuLoop(var aMessage: TMessage); message WM_ENTERMENULOOP;
procedure WMExitMenuLoop(var aMessage: TMessage); message WM_EXITMENULOOP;
end;
var
GeolocationFrm : TGeolocationFrm;
GlobalPosition : TCefGeoposition;
implementation
{$R *.dfm}
uses
uCEFMiscFunctions;
procedure GeoLocationUpdate(const position: PCefGeoposition);
begin
GlobalPosition.latitude := position.latitude;
GlobalPosition.longitude := position.longitude;
GlobalPosition.altitude := position.altitude;
GlobalPosition.accuracy := position.accuracy;
GlobalPosition.altitude_accuracy := position.altitude_accuracy;
GlobalPosition.heading := position.heading;
GlobalPosition.speed := position.speed;
GlobalPosition.timestamp := position.timestamp;
GlobalPosition.error_code := position.error_code;
GlobalPosition.error_message := position.error_message;
PostMessage(GeolocationFrm.Handle, MINIBROWSER_NEWLOCATION, 0, 0);
end;
procedure TGeolocationFrm.Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser);
begin
PostMessage(Handle, CEF_AFTERCREATED, 0, 0);
end;
procedure TGeolocationFrm.FormCreate(Sender: TObject);
begin
CefGetGeolocation(GeoLocationUpdate);
end;
procedure TGeolocationFrm.FormShow(Sender: TObject);
begin
// GlobalCEFApp.GlobalContextInitialized has to be TRUE before creating any browser
// If it's not initialized yet, we use a simple timer to create the browser later.
if not(Chromium1.CreateBrowser(CEFWindowParent1, '')) then Timer1.Enabled := True;
end;
procedure TGeolocationFrm.GoBtnClick(Sender: TObject);
begin
Chromium1.LoadURL(Edit1.Text);
end;
procedure TGeolocationFrm.BrowserCreatedMsg(var aMessage : TMessage);
begin
CEFWindowParent1.UpdateSize;
NavControlPnl.Enabled := True;
GoBtn.Click;
end;
procedure TGeolocationFrm.NewLocationMsg(var aMessage : TMessage);
begin
StatusBar1.Panels[0].Text := 'lat : ' + floattostr(GlobalPosition.latitude);
StatusBar1.Panels[1].Text := 'lon : ' + floattostr(GlobalPosition.longitude);
StatusBar1.Panels[2].Text := 'alt : ' + floattostr(GlobalPosition.altitude);
end;
procedure TGeolocationFrm.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled := False;
if not(Chromium1.CreateBrowser(CEFWindowParent1, '')) and not(Chromium1.Initialized) then
Timer1.Enabled := True;
end;
procedure TGeolocationFrm.WMMove(var aMessage : TWMMove);
begin
inherited;
if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted;
end;
procedure TGeolocationFrm.WMMoving(var aMessage : TMessage);
begin
inherited;
if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted;
end;
procedure TGeolocationFrm.WMEnterMenuLoop(var aMessage: TMessage);
begin
inherited;
if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := True;
end;
procedure TGeolocationFrm.WMExitMenuLoop(var aMessage: TMessage);
begin
inherited;
if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := False;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls;
type
TForm1 = class(TForm)
OpenButton1: TButton;
OpenLabel1: TLabel;
OpenButton2: TButton;
OpenLabel2: TLabel;
OpenButton3: TButton;
OpenLabel3: TLabel;
OpenButton4: TButton;
OpenLabel4: TLabel;
SaveButton1: TButton;
SaveLabel1: TLabel;
SaveButton2: TButton;
SaveLabel2: TLabel;
procedure OpenButton1Click(Sender: TObject);
procedure OpenButton2Click(Sender: TObject);
procedure OpenButton3Click(Sender: TObject);
procedure OpenButton4Click(Sender: TObject);
procedure SaveButton1Click(Sender: TObject);
procedure SaveButton2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
NtDialog;
resourcestring
SOpenTitle = 'Open File';
SSaveTitle = 'Save File';
SSaveFile = 'SampleFile.xml';
SAllFiles = 'All files'; // loc Part of file dialog filter: All files (*.*)
SAllSupportedFiles = 'All supported files'; // loc Part of file dialog filter: All supported files (...)
SXmlFiles = 'XML files'; // loc Part of file dialog filter: XML files (*.xml)
SIniFiles = 'Ini files'; // loc Part of file dialog filter: Ini files (*.ini)
procedure TForm1.OpenButton1Click(Sender: TObject);
resourcestring
// This string is hard to translate and very error prone for syntax mistakes
SOpenFilter = 'All supported files (*.xml;*.ini)|*.xml;*.ini|XML files (*.xml)|*.xml|Ini files (*.ini)|*.ini|All files (*.*)|*.*';
var
dialog: TOpenDialog;
begin
dialog := TOpenDialog.Create(nil);
try
dialog.Title := SOpenTitle;
dialog.Filter := SOpenFilter;
if dialog.Execute then
ShowMessage(dialog.FileName);
finally
dialog.Free;
end;
end;
procedure TForm1.OpenButton2Click(Sender: TObject);
var
dialog: TOpenDialog;
filter: TNtDialogFilter;
begin
// The result of this is the same as above but instead of having one difficult and error prone string, SOpenFilter, we will have
// four simple and easy to translate strings: SAllFiles, SAllSupportedFiles, SXmlFiles and SIniFiles
dialog := TOpenDialog.Create(nil);
try
dialog.Title := SOpenTitle;
filter := TNtDialogFilter.Create;
try
filter.Supported(SAllSupportedFiles); // All supported files is first
filter.Add(SXmlFiles, 'xml'); // XML files
filter.Add(SIniFiles, 'ini'); // Ini files
filter.All(SAllFiles); // All files is last
dialog.Filter := filter.Value;
finally
filter.Free;
end;
if dialog.Execute then
ShowMessage(dialog.FileName);
finally
dialog.Free;
end;
end;
procedure TForm1.OpenButton3Click(Sender: TObject);
var
dialog: TOpenDialog;
filter: TNtDialogFilter;
begin
// As above but without All supported files and All files.
dialog := TOpenDialog.Create(nil);
try
dialog.Title := SOpenTitle;
filter := TNtDialogFilter.Create;
try
filter.Add(SXmlFiles, 'xml'); // XML files
filter.Add(SIniFiles, 'ini'); // Ini files
dialog.Filter := filter.Value;
finally
filter.Free;
end;
if dialog.Execute then
ShowMessage(dialog.FileName);
finally
dialog.Free;
end;
end;
procedure TForm1.OpenButton4Click(Sender: TObject);
var
dialog: TOpenDialog;
filter: TNtDialogFilter;
begin
dialog := TOpenDialog.Create(nil);
try
dialog.Title := SOpenTitle;
filter := TNtDialogFilter.Create;
try
filter.Add(SXmlFiles, 'xml'); // XML files
filter.Supported(SAllSupportedFiles); // All supported files is second
filter.Add(SIniFiles, 'ini'); // Ini files
filter.All(SAllFiles); // All files is last
dialog.Filter := filter.Value;
finally
filter.Free;
end;
if dialog.Execute then
ShowMessage(dialog.FileName);
finally
dialog.Free;
end;
end;
procedure TForm1.SaveButton1Click(Sender: TObject);
resourcestring
// This string is hard to translate and very error prone for syntax mistakes
SSaveFilter = 'XML files (*.xml)|*.xml|Ini files (*.ini)|*.ini';
var
dialog: TSaveDialog;
begin
dialog := TSaveDialog.Create(nil);
try
dialog.Title := SSaveTitle;
dialog.FileName := SSaveFile;
dialog.Filter := SSaveFilter;
if dialog.Execute then
ShowMessage(dialog.FileName);
finally
dialog.Free;
end;
end;
procedure TForm1.SaveButton2Click(Sender: TObject);
var
dialog: TSaveDialog;
filter: TNtDialogFilter;
begin
// The result of this is the same as above but instead of having one difficult and error prone string, SSaveFilter, we will have
// two simple and easy to translate strings: SXmlFiles and SIniFiles
dialog := TSaveDialog.Create(nil);
try
dialog.Title := SSaveTitle;
dialog.FileName := SSaveFile;
filter := TNtDialogFilter.Create;
try
filter.Add(SXmlFiles, 'xml'); // XML files
filter.Add(SIniFiles, 'ini'); // Ini files
dialog.Filter := filter.Value;
finally
filter.Free;
end;
if dialog.Execute then
ShowMessage(dialog.FileName);
finally
dialog.Free;
end;
end;
end.
|
unit LanguageSetLoaderJsonUnit;
interface
uses
Classes,
jsonparser, fpjson,
LanguageStringMapUnit,
LanguageUnit, LanguageSetUnit, LanguageSetLoaderUnit;
type
{ TLanguageSetLoaderJson }
TLanguageSetLoaderJson = class(TLanguageSetLoader)
protected
procedure LoadFromData(const aData: TJSONData);
procedure LoadLanguage(const aKey: string; const aData: TJsonData);
function LoadTexts(const aData: TJsonObject): TStringMap;
function LoadLanguageFromObject(const aData: TJsonObject): TLanguage;
procedure RaiseException(const aMessage: string);
public
constructor Create(const aStream: TStream); override;
procedure Load; override;
end;
TLanguageSetLoaderJsonException = class(TLanguageSetLoaderException);
implementation
{ TLanguageSetLoaderJson }
procedure TLanguageSetLoaderJson.LoadFromData(const aData: TJSONData);
var
i: Integer;
begin
if aData.JSONType <> jtObject then
RaiseException('Root element is not an object');
for i := 0 to aData.Count - 1 do
LoadLanguage(TJsonObject(aData).Names[i], aData.Items[i]);
end;
procedure TLanguageSetLoaderJson.LoadLanguage(const aKey: string; const aData: TJsonData);
begin
if aData.JSONType <> jtObject then
RaiseException('Language is not an object: "' + aKey + '"');
FLanguageSet.LanguageIds.Add(aKey);
FLanguageSet.Languages.Add(LoadLanguageFromObject(TJsonObject(aData)));
end;
function TLanguageSetLoaderJson.LoadTexts(const aData: TJsonObject): TStringMap;
var
o: TJsonObject;
currentKey: string;
currentValue: TJsonData;
i: Integer;
begin
result := TStringMap.Create;
o := TJsonObject(aData);
for i := 0 to o.Count - 1 do
begin
currentKey := o.Names[i];
currentValue := o.Items[i];
if
currentValue.JSONType <> jtString
then
RaiseException('Item is not a string: "' + currentKey + '"');
result.Insert(currentKey, currentValue.AsString);
end;
end;
function TLanguageSetLoaderJson.LoadLanguageFromObject(const aData: TJsonObject): TLanguage;
begin
result := TLanguage.Create(LoadTexts(aData));
end;
procedure TLanguageSetLoaderJson.RaiseException(const aMessage: string);
begin
raise TLanguageSetLoaderJsonException.Create(aMessage);
end;
constructor TLanguageSetLoaderJson.Create(const aStream: TStream);
begin
inherited Create(aStream);
end;
procedure TLanguageSetLoaderJson.Load;
var
parser: TJSONParser;
data: TJSONData;
begin
FLanguageSet := TLanguageSet.Create;
parser := TJSONParser.Create(Stream);
data := parser.Parse;
LoadFromData(data);
data.Free;
parser.Free;
end;
end.
|
unit GLDRotationForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ComCtrls, GL, GLDTypes, GLDClasses;
type
TGLDRotationForm = class(TForm)
L_XAngle: TLabel;
L_YAngle: TLabel;
L_ZAngle: TLabel;
TB_XAngle: TTrackBar;
TB_YAngle: TTrackBar;
TB_ZAngle: TTrackBar;
E_XAngle: TEdit;
E_YAngle: TEdit;
E_ZAngle: TEdit;
BB_Ok: TBitBtn;
BB_Cancel: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TrackBarChange(Sender: TObject);
procedure EditChange(Sender: TObject);
procedure BitBtnClick(Sender: TObject);
private
FAllowChange: GLboolean;
FCloseMode: GLubyte;
FRotation3D: TGLDRotation3D;
FOldRotation3D: TGLDRotation3D;
FEditedRotationClass: TGLDRotation3DClass;
FOnChange: TNotifyEvent;
procedure SetRotation3D(Value: TGLDRotation3D);
procedure SetEditedRotationClass(Value: TGLDRotation3DClass);
procedure Modified;
procedure Change;
public
property Rotation: TGLDRotation3D read FRotation3D write SetRotation3D;
property EditedRotation: TGLDRotation3DClass read FEditedRotationClass write SetEditedRotationClass;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
function GLDGetRotationForm: TGLDRotationForm;
procedure GLDReleaseRotationForm;
implementation
{$R *.dfm}
uses
GLDConst, GLDX;
var
vRotationForm: TGLDRotationForm = nil;
function GLDGetRotationForm: TGLDRotationForm;
begin
if not Assigned(vRotationForm) then
vRotationForm := TGLDRotationForm.Create(nil);
Result := vRotationForm;
end;
procedure GLDReleaseRotationForm;
begin
if Assigned(vRotationForm) then
vRotationForm.Free;
vRotationForm := nil;
end;
procedure TGLDRotationForm.FormCreate(Sender: TObject);
begin
FAllowChange := True;
FCloseMode := GLD_CLOSEMODE_CANCEL;
FEditedRotationClass := nil;
FOnChange := nil;
end;
procedure TGLDRotationForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if (FCloseMode = GLD_CLOSEMODE_CANCEL) and
(FEditedRotationClass <> nil) then
begin
FEditedRotationClass.Params := FOldRotation3D;
Modified;
end;
end;
procedure TGLDRotationForm.TrackBarChange(Sender: TObject);
begin
if (not FAllowChange) or
(not (Sender is TTrackBar)) or
(FEditedRotationClass = nil) then Exit;
FRotation3D.Angles[TTrackBar(Sender).Tag] :=
TTrackBar(Sender).Position;
Change;
end;
procedure TGLDRotationForm.EditChange(Sender: TObject);
begin
if (not FAllowChange) or
(not (Sender is TEdit)) or
(FEditedRotationClass = nil) then Exit;
FRotation3D.Angles[TEdit(Sender).Tag] :=
GLDXStrToFloat(TEdit(Sender).Text);
Change;
end;
procedure TGLDRotationForm.BitBtnClick(Sender: TObject);
begin
FCloseMode := TBitBtn(Sender).Tag;
Close;
end;
procedure TGLDRotationForm.SetRotation3D(Value: TGLDRotation3D);
begin
if GLDXRotation3DEqual(FRotation3D, Value) then Exit;
FRotation3D := Value;
Change;
end;
procedure TGLDRotationForm.SetEditedRotationClass(Value: TGLDRotation3DClass);
begin
FEditedRotationClass := Value;
if FEditedRotationClass <> nil then
begin
FOldRotation3D := FEditedRotationClass.Params;
SetRotation3D(FEditedRotationClass.Params);
end;
end;
procedure TGLDRotationForm.Modified;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TGLDRotationForm.Change;
begin
FAllowChange := False;
TB_XAngle.Position := Round(FRotation3D.XAngle);
TB_YAngle.Position := Round(FRotation3D.YAngle);
TB_ZAngle.Position := Round(FRotation3D.ZAngle);
E_XAngle.Text := FloatToStrF(FRotation3D.XAngle, ffGeneral, 4, 4);
E_YAngle.Text := FloatToStrF(FRotation3D.YAngle, ffGeneral, 4, 4);
E_ZAngle.Text := FloatToStrF(FRotation3D.ZAngle, ffGeneral, 4, 4);
if FEditedRotationClass <> nil then
FEditedRotationClass.Params := FRotation3D;
FAllowChange := True;
Modified;
end;
initialization
finalization
GLDReleaseRotationForm;
end.
|
unit TestUContadorVO;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, SysUtils, Atributos, UContadorVO, UCondominioVO, Generics.Collections,
UGenericVO, Classes, Constantes, UPessoasVO;
type
// Test methods for class TContadorVO
TestTContadorVO = class(TTestCase)
strict private
FContadorVO: TContadorVO;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestValidarCamposObrigatorios;
procedure TestValidarCamposObrigatoriosNaoEncontrado;
end;
implementation
procedure TestTContadorVO.SetUp;
begin
FContadorVO := TContadorVO.Create;
end;
procedure TestTContadorVO.TearDown;
begin
FContadorVO.Free;
FContadorVO := nil;
end;
procedure TestTContadorVO.TestValidarCamposObrigatorios;
var
Contador : TContadorVO;
begin
Contador := TContadorVO.Create;
Contador.idPessoa := 35;
Contador.Crc :='Teste';
Contador.dtEntrada := StrToDate('01/01/2012');
try
Contador.ValidarCamposObrigatorios;
Check(true,'Sucesso!')
except on E: Exception do
Check(false,'Erro!');
end;
end;
procedure TestTContadorVO.TestValidarCamposObrigatoriosNaoEncontrado;
var
Contador : TContadorVO;
begin
Contador := TContadorVO.Create;
Contador.idPessoa := 0;
Contador.Crc :='';
Contador.dtEntrada := StrToDate('01/01/2000');
try
Contador.ValidarCamposObrigatorios;
Check(false,'Erro!')
except on E: Exception do
Check(true,'Sucesso!');
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTContadorVO.Suite);
end.
|
{**************************************************************************************}
{ }
{ CCR Exif - Delphi class library for reading and writing image metadata }
{ Version 1.5.1 }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 }
{ (the "License"); you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. See the License for the specific }
{ language governing rights and limitations under the License. }
{ }
{ The Original Code is CCR.Exif.BaseUtils.pas. }
{ }
{ The Initial Developer of the Original Code is Chris Rolliston. Portions created by }
{ Chris Rolliston are Copyright (C) 2009-2012 Chris Rolliston. All Rights Reserved. }
{ }
{**************************************************************************************}
{$I CCR.Exif.inc}
unit CCR.Exif.BaseUtils;
interface
uses
Types, SysUtils, Classes,
{$IFNDEF UNICODE}WideStrings,{$ENDIF} CCR.Exif.StreamHelper;
{ backfill basic types and routines for D2006-7 }
type
{$IF not Declared(EProgrammerNotFound)}
EProgrammerNotFound = class(Exception);
{$IFEND}
{$IFDEF UNICODE}
TUnicodeStrings = TStrings;
TUnicodeStringList = TStringList;
{$ELSE}
TUnicodeStrings = TWideStrings;
TUnicodeStringList = TWideStringList;
RawByteString = AnsiString; //added in D2009
UnicodeString = WideString; //added in D2009
{$IF not Declared(TBytes)}
TBytes = array of Byte; //added in D2007
{$IFEND}
function CharInSet(Ch: AnsiChar; const CharSet: TSysCharSet): Boolean; inline; overload;
function CharInSet(Ch: WideChar; const CharSet: TSysCharSet): Boolean; inline; overload;
function UpCase(const Ch: AnsiChar): AnsiChar; overload;
function UpCase(const Ch: WideChar): WideChar; overload;
function UTF8ToString(const UTF8: RawByteString): string; inline; overload;
{$ENDIF}
function UTF8ToString(UTF8Buffer: Pointer; ByteLen: Integer): string; overload;
function BinToHexStr(Data: Pointer; Size: Integer): string; overload;
function BinToHexStr(const Buffer; Size: Integer): string; overload; inline;
function GetExecutableName: string; inline;
{ non-specific }
type
ECCRExifException = class(Exception);
EUnsupportedGraphicFormat = class(ECCRExifException);
TMetadataLoadError = (leBadOffset, leBadTagCount, leBadTagHeader);
TMetadataLoadErrors = set of TMetadataLoadError;
TNoRefCountInterfacedObject = class(TObject, IInterface)
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
IStreamPersistEx = interface(IStreamPersist)
['{2E9F3433-E5A9-4FBA-9C89-68B97DADA33C}']
function GetEmpty: Boolean;
property Empty: Boolean read GetEmpty;
end;
IMetadataBlock = interface
['{F77F5203-C526-4457-81A7-13941FE461CB}']
function GetData: TCustomMemoryStream;
function IsExifBlock(CheckID: Boolean = True): Boolean;
function IsIPTCBlock(CheckID: Boolean = True): Boolean;
function IsXMPBlock(CheckID: Boolean = True): Boolean;
property Data: TCustomMemoryStream read GetData; //this is not guaranteed to be writeable
end;
TMetadataBlockDynArray = array of IMetadataBlock;
TMetadataBlock = class(TInterfacedObject, IMetadataBlock)
protected type
TDataStream = class(TMemoryStream)
strict private
FDisableChanges: Boolean;
protected
function Realloc(var NewCapacity: Longint): Pointer; override;
procedure SetSize(const NewSize: Int64); override;
public
destructor Destroy; override;
procedure SetSize(NewSize: Longint); override;
function Write(const Buffer; Count: Longint): Longint; override;
property DisableChanges: Boolean read FDisableChanges write FDisableChanges;
end;
strict private
FData: TDataStream;
protected
function GetData: TCustomMemoryStream;
function HasExifBlockID: Boolean; virtual;
function HasIPTCBlockID: Boolean; virtual;
function HasXMPBlockID: Boolean; virtual;
public
constructor Create(const DataSource: IStreamPersist = nil); overload;
constructor Create(DataSource: TStream; BytesToRead: Integer); overload;
destructor Destroy; override;
function IsExifBlock(CheckID: Boolean = True): Boolean;
function IsIPTCBlock(CheckID: Boolean = True): Boolean;
function IsXMPBlock(CheckID: Boolean = True): Boolean;
property Data: TDataStream read FData;
end;
TDateTimeTagValue = record
strict private const
FirstValidDateTime: TDateTime = -693593; //1st Jan, 1 AD
MissingOrInvalidValue: TDateTime = -700000;
strict private
FValue: TDateTime;
function GetAsString: string;
public
constructor CreateFromString(const AString: string);
class function CreateMissingOrInvalid: TDateTimeTagValue; static;
class operator Equal(const A, B: TDateTimeTagValue): Boolean;
class operator NotEqual(const A, B: TDateTimeTagValue): Boolean;
class operator Implicit(const Source: TDateTimeTagValue): TDateTime;
class operator Implicit(const Source: TDateTime): TDateTimeTagValue;
class operator LessThan(const A, B: TDateTimeTagValue): Boolean;
class operator LessThanOrEqual(const A, B: TDateTimeTagValue): Boolean;
class operator GreaterThan(const A, B: TDateTimeTagValue): Boolean;
class operator GreaterThanOrEqual(const A, B: TDateTimeTagValue): Boolean;
property AsString: string read GetAsString;
function MissingOrInvalid: Boolean; inline;
property Value: TDateTime read FValue;
end;
TLongIntTagValue = record
strict private
FValue: LongInt;
FMissingOrInvalid: Boolean;
function GetAsString: string;
public
constructor CreateFromString(const AString: string);
class function CreateMissingOrInvalid: TLongIntTagValue; static;
class operator Equal(const A, B: TLongIntTagValue): Boolean;
class operator NotEqual(const A, B: TLongIntTagValue): Boolean;
class operator Implicit(const Source: TLongIntTagValue): Int64;
class operator Implicit(const Source: TLongIntTagValue): LongInt;
class operator Implicit(const Source: LongInt): TLongIntTagValue;
class operator LessThan(const A, B: TLongIntTagValue): Boolean;
class operator LessThanOrEqual(const A, B: TLongIntTagValue): Boolean;
class operator GreaterThan(const A, B: TLongIntTagValue): Boolean;
class operator GreaterThanOrEqual(const A, B: TLongIntTagValue): Boolean;
class operator Negative(const Source: TLongIntTagValue): TLongIntTagValue;
property AsString: string read GetAsString;
property MissingOrInvalid: Boolean read FMissingOrInvalid;
property Value: LongInt read FValue;
end;
TLongWordTagValue = record
strict private
FValue: LongWord;
FMissingOrInvalid: Boolean;
function GetAsString: string;
public
constructor CreateFromString(const AString: string);
class function CreateMissingOrInvalid: TLongWordTagValue; static;
class operator Equal(const A, B: TLongWordTagValue): Boolean;
class operator NotEqual(const A, B: TLongWordTagValue): Boolean;
class operator Implicit(const Source: TLongWordTagValue): Int64;
class operator Implicit(const Source: TLongWordTagValue): UInt64;
class operator Implicit(const Source: TLongWordTagValue): LongWord;
class operator Implicit(const Source: LongWord): TLongWordTagValue;
class operator LessThan(const A, B: TLongWordTagValue): Boolean;
class operator LessThanOrEqual(const A, B: TLongWordTagValue): Boolean;
class operator GreaterThan(const A, B: TLongWordTagValue): Boolean;
class operator GreaterThanOrEqual(const A, B: TLongWordTagValue): Boolean;
property AsString: string read GetAsString;
property MissingOrInvalid: Boolean read FMissingOrInvalid;
property Value: LongWord read FValue;
end;
TWordTagValue = record
strict private
FValue: Word;
FMissingOrInvalid: Boolean;
function GetAsString: string;
public
constructor CreateFromString(const AString: string);
class function CreateMissingOrInvalid: TWordTagValue; static;
class operator Equal(const A, B: TWordTagValue): Boolean;
class operator NotEqual(const A, B: TWordTagValue): Boolean;
class operator Implicit(const Source: TWordTagValue): Int64;
class operator Implicit(const Source: TWordTagValue): UInt64;
class operator Implicit(const Source: TWordTagValue): Integer;
class operator Implicit(const Source: TWordTagValue): Word;
class operator Implicit(const Source: TWordTagValue): TLongIntTagValue;
class operator Implicit(const Source: TWordTagValue): TLongWordTagValue;
class operator Implicit(const Source: Word): TWordTagValue;
class operator LessThan(const A, B: TWordTagValue): Boolean;
class operator LessThanOrEqual(const A, B: TWordTagValue): Boolean;
class operator GreaterThan(const A, B: TWordTagValue): Boolean;
class operator GreaterThanOrEqual(const A, B: TWordTagValue): Boolean;
property AsString: string read GetAsString;
property MissingOrInvalid: Boolean read FMissingOrInvalid;
property Value: Word read FValue;
end;
TUserMemoryStream = class(TCustomMemoryStream) //read-only stream access on an existing buffer;
protected
procedure SetSize(NewSize: Longint); override;
procedure SetSize(const NewSize: Int64); override;
public
constructor Create(Memory: Pointer; Size: Integer);
procedure ChangeMemory(NewMemory: Pointer; NewSize: Integer);
function Write(const Buffer; Count: Integer): Integer; override;
end;
TGraphicSaveMethod = procedure (InStream, OutStream: TStream) of object;
TGetGraphicSaveMethod = procedure (InStream: TStream; var AMethod: TGraphicSaveMethod) of object;
procedure DoSaveToGraphic(const FileName: string;
const DetectTypeFunc: TGetGraphicSaveMethod); overload;
procedure DoSaveToGraphic(const Graphic: IStreamPersist; //!!!changed from TGraphic
const DetectTypeFunc: TGetGraphicSaveMethod); overload;
procedure DoSaveToGraphic(GraphicStream: TStream;
const DetectTypeFunc: TGetGraphicSaveMethod); overload; // WHY THE HELL NOT DEFINED BEFORE???
{ PSD file parsing and writing; note that Adobe resource blocks may be found in other types of file too }
type
EInvalidPSDHeader = class(ECCRExifException);
TIPTCSectionID = 1..9;
TIPTCTagID = type Byte;
TIPTCTagInfo = record
SectionID: TIPTCSectionID;
TagID: TIPTCTagID;
DataSize: Integer;
end;
TAdobeResBlock = record public const
ExifTypeID = $0422;
IPTCTypeID = $0404;
XMPTypeID = $0424;
NewIPTCTagMarker: Byte = 28;
class function TryReadIPTCHeader(Stream: TStream; var TagInfo: TIPTCTagInfo;
AlwaysResetStreamPos: Boolean = False): Boolean; static;
end;
IAdobeResBlock = interface(IMetadataBlock)//also IStreamPersist...
['{D7F88330-C1DF-4261-A3B2-1701AFAB8873}']
function GetSignature: AnsiString;
procedure SetSignature(const Value: AnsiString);
function GetTypeID: Word;
procedure SetTypeID(Value: Word);
function GetName: AnsiString;
procedure SetName(const Value: AnsiString);
function GetTotalSize: Integer;
function GetLoadedCleanly: Boolean;
function HasIPTCData: Boolean; deprecated {$IFDEF DepCom}'Renamed IsIPTCBlock'{$ENDIF};
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
property LoadedCleanly: Boolean read GetLoadedCleanly;
property Signature: AnsiString read GetSignature write SetSignature;
property TypeID: Word read GetTypeID write SetTypeID;
property Name: AnsiString read GetName write SetName;
property TotalSize: Integer read GetTotalSize;
end;
IAdobeBlock = IAdobeResBlock deprecated {$IFDEF DepCom}'Renamed IAdobeResBlock'{$ENDIF};
IAdobeResBlockEnumerator = interface
function GetCurrent: IAdobeResBlock;
function MoveNext: Boolean;
property Current: IAdobeResBlock read GetCurrent;
end;
{$Z2}
TAdobeColorMode = (cmMonochrome, cmGrayscale, cmIndexed, cmRGB, cmCMYK,
cmMultichannel, cmHalftone, cmLAB);
{$Z1}
TPSDHeaderInfo = record
Width, Height: Integer;
Channels, Depth: Word;
ColorMode: TAdobeColorMode;
PaletteData: TBytes;
end;
TPSDInfo = record
Header: TPSDHeaderInfo;
ResourceSectionSize, LayersSectionSize: Integer; //includes size of section length field
function ResourceSectionOffset: Integer;
function LayersSectionOffset: Integer;
end;
IAdobeResBlockParser = interface
function GetEnumerator: IAdobeResBlockEnumerator;
end;
function CreateAdobeBlock: IAdobeResBlock; overload;
function CreateAdobeBlock(ATypeID: Word; const ADataSource: IStreamPersist = nil): IAdobeResBlock; overload;
function CreateAdobeBlock(ATypeID: Word; ADataSource: TStream; ADataSize: Integer = 0): IAdobeResBlock; overload;
function CreateAdobeBlock(ATypeID: Word; const AName: AnsiString;
const ADataSource: IStreamPersist = nil): IAdobeResBlock; overload;
function CreateAdobeBlock(const ASignature: AnsiString; ATypeID: Word;
const AName: AnsiString; const ADataSource: IStreamPersist = nil): IAdobeResBlock; overload;
function HasPSDHeader(Stream: TStream): Boolean; overload;
function HasPSDHeader(const FileName: string): Boolean; overload;
function ParsePSDHeader(Stream: TStream; var Info: TPSDInfo;
StreamOwnership: TStreamOwnership = soReference): IAdobeResBlockParser; overload;
function ParsePSDHeader(const FileName: string; var Info: TPSDInfo): IAdobeResBlockParser; overload; inline;
procedure WritePSDHeader(Stream: TStream; const Info: TPSDHeaderInfo);
procedure WritePSDResourceSection(Stream: TStream; const Blocks: array of IAdobeResBlock); overload;
procedure WritePSDResourceSection(Stream: TStream; const Blocks: IInterfaceList); overload;
{ JPEG file parsing and writing }
type
EInvalidJPEGHeader = class(ECCRExifException);
PJPEGSegmentHeader = ^TJPEGSegmentHeader;
TJPEGSegmentHeader = packed record
strict private
function GetDataSize: Word;
procedure SetDataSize(const Value: Word);
public
property DataSize: Word read GetDataSize write SetDataSize;
public
NewMarkerByte: Byte; //$FF
MarkerNum: Byte;
case Integer of
0: (DataSizeHi, DataSizeLo: Byte;
Data: record end);
1: (DataSizeBigEndian: Word);
end;
TJFIFDensityUnits = (duNone, duPixelsPerInch, duPixelsPerCentimetre);
TJFIFData = packed record
strict private
function GetHorzDensity: Word;
procedure SetHorzDensity(const Value: Word);
function GetVertDensity: Word;
procedure SetVertDensity(const Value: Word);
public
property HorzDensity: Word read GetHorzDensity write SetHorzDensity;
property VertDensity: Word read GetVertDensity write SetVertDensity;
public
Ident: array[0..4] of AnsiChar; //should be 'JFIF', including null terminator
MajorVersion, MinorVersion: Byte;
DensityUnits: TJFIFDensityUnits;
case Integer of
0: (HorzDensityHi, HorzDensityLo: Byte;
VertDensityHi, VertDensityLo: Byte;
ThumbnailWidth, ThumbnailHeight: Byte;
ThumbnailPixels: record end);
1: (HorzDensityBigEndian: Word;
VertDensityBigEndian: Word);
end;
PJPEGStartOfFrameData = ^TJPEGStartOfFrameData;
TJPEGStartOfFrameData = packed record
strict private
function GetImageWidth: Word;
function GetImageHeight: Word;
procedure SetImageHeight(const Value: Word);
procedure SetImageWidth(const Value: Word);
public
property ImageWidth: Word read GetImageWidth write SetImageWidth;
property ImageHeight: Word read GetImageHeight write SetImageHeight;
public
SamplePrecision: Byte; //8
ImageHeightHi, ImageHeightLo: Byte;
ImageWidthHi, ImageWidthLo: Byte;
ComponentCount: Byte; //1 = gray scaled, 3 = color YCbCr or YIQ, 4 = color CMYK
ComponentData: record end;
end;
TJPEGMarker = Byte;
TJPEGMarkers = set of TJPEGMarker;
IJPEGSegment = interface(IMetadataBlock) //also IStreamPersistEx...
['{5F41F0BA-C43F-4671-8B66-4B6D5B2BF90F}']
function GetEnumerator: IAdobeResBlockEnumerator;
function GetMarkerNum: TJPEGMarker;
function IsAdobeApp13: Boolean;
property MarkerNum: TJPEGMarker read GetMarkerNum;
end;
TUserJPEGSegment = class(TMetadataBlock, IMetadataBlock, IJPEGSegment,
IStreamPersist, IStreamPersistEx)
strict private
FAdobeHeaderSize: Integer;
FMarkerNum: TJPEGMarker;
protected
function HasExifBlockID: Boolean; override;
function HasIPTCBlockID: Boolean; override;
function HasXMPBlockID: Boolean; override;
{ IStreamPersist }
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
{ IStreamPersistEx}
function GetEmpty: Boolean;
{ IJPEGSegment }
function GetMarkerNum: TJPEGMarker;
function IsAdobeApp13: Boolean;
public const
AdobeHeader: array[0..13] of AnsiChar = 'Photoshop 3.0'#0;
OldAdobeHeader: array[0..18] of AnsiChar = 'Adobe_Photoshop2.5:';
public
constructor Create(AMarkerNum: TJPEGMarker = 0; const ASource: IStreamPersist = nil); overload;
function GetEnumerator: IAdobeResBlockEnumerator;
function IsIPTCBlock(CheckID: Boolean = True): Boolean; //override inherited implementation
property MarkerNum: TJPEGMarker read FMarkerNum write FMarkerNum;
end;
IFoundJPEGSegment = interface(IJPEGSegment)
['{C236AF21-5577-439A-BD44-8C0673347F44}']
function GetOffset: Int64;
function GetOffsetOfData: Int64;
function GetTotalSize: Integer;
property Offset: Int64 read GetOffset;
property OffsetOfData: Int64 read GetOffsetOfData;
property TotalSize: Integer read GetTotalSize;
end;
IJPEGHeaderParser = interface
function GetCurrent: IFoundJPEGSegment;
function GetEnumerator: IJPEGHeaderParser;
function MoveNext: Boolean;
property Current: IFoundJPEGSegment read GetCurrent;
end;
const
jmNewOrPadding = TJPEGMarker($FF);
jmStartOfImage = TJPEGMarker($D8);
jmEndOfImage = TJPEGMarker($D9);
jmQuantizationTable = TJPEGMarker($DB);
jmStartOfFrame0 = TJPEGMarker($C0);
jmStartOfFrame1 = TJPEGMarker($C1);
jmStartOfFrame2 = TJPEGMarker($C2);
jmStartOfFrame3 = TJPEGMarker($C3);
jmStartOfFrame5 = TJPEGMarker($C5);
jmStartOfFrame6 = TJPEGMarker($C6);
jmStartOfFrame7 = TJPEGMarker($C7);
jmJPEGExtension = TJPEGMarker($C8);
jmHuffmanTable = TJPEGMarker($C4);
jmRestartInternal = TJPEGMarker($DD);
jmComment = TJPEGMarker($FE);
jmAppSpecificFirst = TJPEGMarker($E0);
jmAppSpecificLast = TJPEGMarker($EF);
jmJFIF = TJPEGMarker($E0);
jmApp1 = TJPEGMarker($E1);
jmApp13 = TJPEGMarker($ED);
jmStartOfScan = TJPEGMarker($DA);
JPEGFileHeader: Word = jmNewOrPadding or jmStartOfImage shl 8;
type
TJPEGSegment = record const
HeaderSize = 4;
AllMarkers = [Low(TJPEGMarker)..High(TJPEGMarker)];
AnyMarker = AllMarkers;
MarkersWithNoData = [$00, $01, $D0..$D9];
StartOfFrameMarkers = [jmStartOfFrame0..jmStartOfFrame3,
jmStartOfFrame5..jmStartOfFrame7]; //there's no jmStartOfFrame4
ExifHeader: array[0..5] of AnsiChar = 'Exif'#0#0;
XMPHeader: array[0..28] of AnsiChar = 'http://ns.adobe.com/xap/1.0/'#0;
end;
const
AllJPEGMarkers = TJPEGSegment.AllMarkers deprecated;
AnyJPEGMarker = TJPEGSegment.AnyMarker;
StartOfFrameMarkers = TJPEGSegment.StartOfFrameMarkers deprecated;
MarkersWithNoData = TJPEGSegment.MarkersWithNoData deprecated;
{
var
Segment: IFoundJPEGSegment;
begin
for Segment in JPEGHeader(JPEGStream) do
...
for Segment in JPEGHeader('myimage.jpg') do
...
for Segment in JPEGHeader(JPEGImage) do
...
}
function JPEGHeader(JPEGStream: TStream; const MarkersToLookFor: TJPEGMarkers = TJPEGSegment.AnyMarker;
StreamOwnership: TStreamOwnership = soReference): IJPEGHeaderParser; overload;
function JPEGHeader(const JPEGFile: string;
const MarkersToLookFor: TJPEGMarkers = TJPEGSegment.AnyMarker): IJPEGHeaderParser; overload; inline;
function JPEGHeader(const JPEGImage: IStreamPersist; //!!!changed from TGraphic
const MarkersToLookFor: TJPEGMarkers = TJPEGSegment.AnyMarker): IJPEGHeaderParser; overload;
function HasJPEGHeader(Stream: TStream): Boolean; overload;
function HasJPEGHeader(const FileName: string): Boolean; overload;
function GetJPEGDataSize(Data: TStream; ReturnZeroIfFindNoEOI: Boolean = False): Int64; overload;
function GetJPEGDataSize(const JPEGImage: IStreamPersist): Int64; overload;
function RemoveJPEGSegments(const JPEGFile: string; Markers: TJPEGMarkers): TJPEGMarkers; overload;
function RemoveJPEGSegments(const JPEGImage: IStreamPersist; Markers: TJPEGMarkers): TJPEGMarkers; overload;
function CreateAdobeApp13Segment(const Blocks: array of IAdobeResBlock): IJPEGSegment; overload;
function CreateAdobeApp13Segment(const Blocks: IInterfaceList = nil): IJPEGSegment; overload;
procedure UpdateApp1JPEGSegments(InStream, OutStream: TStream;
NewExifSource, NewXMPSource: IStreamPersistEx); //used by the SaveToStream methods of TExifData and TXMPPacket; if NewXXXSource is nil, the data in InStream is copied over
procedure WriteJPEGFileHeader(Stream: TStream); inline;
procedure WriteJPEGSegment(Stream: TStream; MarkerNum: TJPEGMarker;
const Data; DataSize: Word); overload;
procedure WriteJPEGSegment(Stream: TStream; MarkerNum: TJPEGMarker;
Data: TStream; DataSize: Word = 0); overload;
procedure WriteJPEGSegment(Stream: TStream; Segment: IJPEGSegment); overload;
{ TIFF bits - the rest is in CCR.Exif.TiffUtils.pas }
const
TiffSmallEndianCode = Word($4949);
TiffBigEndianCode = Word($4D4D);
TiffMagicNum = Word($002A);
TiffMagicNumBigEndian = Word($2A00);
implementation
uses
{$IFDEF MSWINDOWS}Windows,{$ENDIF}{$IFDEF POSIX}Posix.Unistd,{$ENDIF}
{$IFDEF HasIOUtils}IOUtils,{$ENDIF}Math, RTLConsts, Contnrs,
CCR.Exif.Consts, CCR.Exif.TagIDs;
type
TAdobeBlock = class(TMetadataBlock, IStreamPersist, IAdobeResBlock)
strict private
FLoadedCleanly: Boolean;
FSignature: AnsiString;
FTypeID: Word;
FName: AnsiString;
class function GetValidSignature(const S: AnsiString): AnsiString; static;
protected
procedure Clear;
function HasExifBlockID: Boolean; override;
function HasIPTCBlockID: Boolean; override;
function HasXMPBlockID: Boolean; override;
{ IStreamPersist}
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
{ IAdobeResBlock}
function GetSignature: AnsiString;
procedure SetSignature(const Value: AnsiString);
function GetTypeID: Word;
procedure SetTypeID(Value: Word);
function GetName: AnsiString;
procedure SetName(const Value: AnsiString);
function GetTotalSize: Integer;
function GetLoadedCleanly: Boolean;
function HasIPTCData: Boolean;
public
constructor Create; overload;
constructor Create(AStream: TStream); overload;
constructor Create(const ASignature: AnsiString; ATypeID: Word;
const AName: AnsiString; const ADataSource: IStreamPersist); overload;
end;
TAdobeResBlockEnumerator = class(TInterfacedObject, IAdobeResBlockEnumerator)
strict private
FCurrent: IAdobeResBlock;
FNextPos, FPosTooFar: Int64;
FStream: TStream;
FStreamOwnership: TStreamOwnership;
protected
function GetCurrent: IAdobeResBlock;
property NextPos: Int64 read FNextPos write FNextPos;
property PosTooFar: Int64 read FPosTooFar write FPosTooFar;
public
constructor Create(AStream: TStream; AStreamOwnership: TStreamOwnership = soReference);
destructor Destroy; override;
function MoveNext: Boolean;
property Current: IAdobeResBlock read FCurrent;
property Stream: TStream read FStream;
end;
TFoundJPEGSegment = class(TUserJPEGSegment, IFoundJPEGSegment)
strict private
FOffset: Int64;
protected
{ IFoundJPEGSegment }
function GetOffset: Int64;
function GetOffsetOfData: Int64;
function GetTotalSize: Integer;
public
constructor Create(AMakerNum: TJPEGMarker; ASource: TStream; ADataSize: Integer); overload;
end;
TJPEGHeaderParser = class(TInterfacedObject, IJPEGHeaderParser)
strict private
FCurrent: IFoundJPEGSegment;
FLastMarker: TJPEGMarker;
FMarkersToLookFor: TJPEGMarkers;
FSavedPos, FStartPos: Int64;
FStream: TStream;
FStreamOwnership: TStreamOwnership;
protected
function GetEnumerator: IJPEGHeaderParser;
function GetCurrent: IFoundJPEGSegment;
function MoveNext: Boolean;
public
constructor Create(JPEGStream: TStream; const MarkersToLookFor: TJPEGMarkers;
StreamOwnership: TStreamOwnership);
destructor Destroy; override;
end;
{$IFNDEF UNICODE}
function CharInSet(Ch: AnsiChar; const CharSet: TSysCharSet): Boolean;
begin
Result := Ch in CharSet;
end;
function CharInSet(Ch: WideChar; const CharSet: TSysCharSet): Boolean;
begin
Result := (Ch <= High(AnsiChar)) and (AnsiChar(Ch) in CharSet);
end;
function UpCase(const Ch: AnsiChar): AnsiChar;
begin
Result := Ch;
case Result of
'a'..'z': Dec(Result, Ord('a') - Ord('A'));
end;
end;
function UpCase(const Ch: WideChar): WideChar;
begin
Result := Ch;
case Result of
'a'..'z': Dec(Result, Ord('a') - Ord('A'));
end;
end;
function UTF8ToString(const UTF8: RawByteString): string;
begin
Result := Utf8ToAnsi(UTF8);
end;
{$ENDIF}
function UTF8ToString(UTF8Buffer: Pointer; ByteLen: Integer): string;
var
S: UTF8String;
begin
SetString(S, PAnsiChar(UTF8Buffer), ByteLen);
Result := UTF8ToString(S);
end;
function BinToHexStr(Data: Pointer; Size: Integer): string;
begin
SetString(Result, nil, 0);
if Size = 0 then Exit;
SetString(Result, nil, Size * 2);
BinToHex(PAnsiChar(Data), PChar(Result), Size);
end;
function BinToHexStr(const Buffer; Size: Integer): string;
begin
Result := BinToHexStr(@Buffer, Size);
end;
{$IF Declared(TPath)}
function GetTempFileName: string; inline;
begin
Result := TPath.GetTempFileName;
end;
{$ELSE}
function GetTempFileName: string;
var
Buffer: array[0..MAX_PATH] of Char;
begin
if (Windows.GetTempPath(MAX_PATH, Buffer) = 0) or (Windows.GetTempFileName(Buffer,
'tmp', 0, Buffer) = 0) then
RaiseLastOSError
else
Result := Buffer;
end;
{$IFEND}
procedure DoSaveToGraphic(GraphicStream: TStream;
const DetectTypeFunc: TGetGraphicSaveMethod); overload;
var
SaveMethod: TGraphicSaveMethod;
TempFileName: string;
TempStream: TStream;
begin
GraphicStream.Seek(0, soBeginning);
TempFileName := '';
TempStream := nil;
try
SaveMethod := nil;
DetectTypeFunc(GraphicStream, SaveMethod);
if not Assigned(SaveMethod) then
raise EUnsupportedGraphicFormat.CreateRes(@SUnsupportedGraphicFormat);
if GraphicStream.Size < $FFFFFF then //If the source data is under 16MB, buffer to
TempStream := TMemoryStream.Create //memory, else buffer to a temporary file.
else
begin
TempFileName := GetTempFileName;
TempStream := TFileStream.Create(TempFileName, fmCreate);
end;
SaveMethod(GraphicStream, TempStream);
GraphicStream.Seek(0, soBeginning);
if TempStream is TMemoryStream then
GraphicStream.WriteBuffer(TMemoryStream(TempStream).Memory^, TempStream.Size)
else
GraphicStream.CopyFrom(TempStream, 0);
GraphicStream.Size := TempStream.Size;
finally
TempStream.Free;
if TempFileName <> '' then SysUtils.DeleteFile(TempFileName);
end;
end;
procedure DoSaveToGraphic(const FileName: string;
const DetectTypeFunc: TGetGraphicSaveMethod);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmOpenReadWrite);
try
DoSaveToGraphic(Stream, DetectTypeFunc);
finally
Stream.Free;
end;
end;
procedure DoSaveToGraphic(const Graphic: IStreamPersist;
const DetectTypeFunc: TGetGraphicSaveMethod);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
Graphic.SaveToStream(Stream);
DoSaveToGraphic(Stream, DetectTypeFunc);
Stream.Seek(0, soBeginning);
Graphic.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
{ TNoRefCountInterfacedObject }
function TNoRefCountInterfacedObject.QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function TNoRefCountInterfacedObject._AddRef: Integer; stdcall;
begin
Result := -1;
end;
function TNoRefCountInterfacedObject._Release: Integer; stdcall;
begin
Result := -1;
end;
{ TMetadataBlock.TDataStream }
destructor TMetadataBlock.TDataStream.Destroy;
begin
FDisableChanges := False;
inherited;
end;
procedure TMetadataBlock.TDataStream.SetSize(NewSize: Longint);
begin
if DisableChanges then
raise EStreamError.CreateRes(@SStreamIsReadOnly);
inherited SetSize(NewSize);
end;
function TMetadataBlock.TDataStream.Realloc(var NewCapacity: Longint): Pointer;
begin
if DisableChanges then
raise EStreamError.CreateRes(@SStreamIsReadOnly)
else
Result := inherited Realloc(NewCapacity);
end;
procedure TMetadataBlock.TDataStream.SetSize(const NewSize: Int64);
begin
if DisableChanges then
raise EStreamError.CreateRes(@SStreamIsReadOnly);
inherited SetSize(NewSize);
end;
function TMetadataBlock.TDataStream.Write(const Buffer; Count: Longint): Longint;
begin
if DisableChanges then
raise EStreamError.CreateRes(@SStreamIsReadOnly);
Result := inherited Write(Buffer, Count);
end;
{ TMetadataBlock }
constructor TMetadataBlock.Create(const DataSource: IStreamPersist = nil);
begin
inherited Create;
FData := TDataStream.Create;
if DataSource <> nil then DataSource.SaveToStream(FData);
end;
constructor TMetadataBlock.Create(DataSource: TStream; BytesToRead: Integer);
begin
Create;
if BytesToRead > 0 then FData.CopyFrom(DataSource, BytesToRead);
end;
destructor TMetadataBlock.Destroy;
begin
FData.Free;
inherited;
end;
function TMetadataBlock.GetData: TCustomMemoryStream;
begin
Result := FData;
end;
function TMetadataBlock.HasExifBlockID: Boolean;
begin
Result := False;
end;
function TMetadataBlock.HasIPTCBlockID: Boolean;
begin
Result := False;
end;
function TMetadataBlock.HasXMPBlockID: Boolean;
begin
Result := False;
end;
function TMetadataBlock.IsExifBlock(CheckID: Boolean = True): Boolean;
var
Words: PWordArray;
begin
Result := False;
if (CheckID and not HasExifBlockID) or (FData.Size < 8) then Exit;
Words := FData.Memory;
if CompareMem(Words, @TJPEGSegment.ExifHeader, SizeOf(TJPEGSegment.ExifHeader)) then //TExifData will just skip any Exif segment header
Inc(PByte(Words), SizeOf(TJPEGSegment.ExifHeader));
if (Words[0] = TiffSmallEndianCode) or (Words[0] = TiffBigEndianCode) then
case Words[1] of
TiffMagicNum, TiffMagicNumBigEndian: Result := True; //ParseTiff doesn't mind if these are confused
end;
end;
function TMetadataBlock.IsIPTCBlock(CheckID: Boolean = True): Boolean;
var
Header: TIPTCTagInfo;
begin
FData.Seek(0, soFromBeginning);
Result := (not CheckID or HasIPTCBlockID) and
TAdobeResBlock.TryReadIPTCHeader(FData, Header, True);
end;
function TMetadataBlock.IsXMPBlock(CheckID: Boolean = True): Boolean;
const
XMPStart: PAnsiChar = '<?xpacket ';
XMPStartLen = 10;
var
SeekPtr: PAnsiChar;
begin
Result := False;
if (CheckID and not HasXMPBlockID) or (FData.Size < 20) then Exit;
SeekPtr := FData.Memory;
if CompareMem(SeekPtr, @TJPEGSegment.XMPHeader, SizeOf(TJPEGSegment.XMPHeader)) then
Inc(SeekPtr, SizeOf(TJPEGSegment.XMPHeader));
Result := CompareMem(SeekPtr, XMPStart, XMPStartLen);
end;
{ TDateTimeTagValue }
constructor TDateTimeTagValue.CreateFromString(const AString: string);
begin
if not TryStrToDateTime(AString, FValue) then
FValue := MissingOrInvalidValue;
end;
class function TDateTimeTagValue.CreateMissingOrInvalid: TDateTimeTagValue;
begin
Result.FValue := MissingOrInvalidValue;
end;
function TDateTimeTagValue.MissingOrInvalid: Boolean;
begin
Result := (Value < FirstValidDateTime);
end;
function TDateTimeTagValue.GetAsString: string;
begin
if MissingOrInvalid then
Result := ''
else
Result := DateTimeToStr(Value);
end;
class operator TDateTimeTagValue.Equal(const A, B: TDateTimeTagValue): Boolean;
begin
if A.MissingOrInvalid then
Result := B.MissingOrInvalid
else
Result := (A.Value = B.Value);
end;
class operator TDateTimeTagValue.NotEqual(const A, B: TDateTimeTagValue): Boolean;
begin
Result := not (A = B);
end;
class operator TDateTimeTagValue.Implicit(const Source: TDateTimeTagValue): TDateTime;
begin
Result := Source.Value;
end;
class operator TDateTimeTagValue.Implicit(const Source: TDateTime): TDateTimeTagValue;
begin
Result.FValue := Source;
end;
class operator TDateTimeTagValue.LessThan(const A, B: TDateTimeTagValue): Boolean;
begin
Result := (A.Value < B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid;
end;
class operator TDateTimeTagValue.LessThanOrEqual(const A, B: TDateTimeTagValue): Boolean;
begin
Result := (A.MissingOrInvalid and B.MissingOrInvalid) or
((A.Value <= B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid);
end;
class operator TDateTimeTagValue.GreaterThan(const A, B: TDateTimeTagValue): Boolean;
begin
Result := (A.Value > B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid;
end;
class operator TDateTimeTagValue.GreaterThanOrEqual(const A, B: TDateTimeTagValue): Boolean;
begin
Result := (A.MissingOrInvalid and B.MissingOrInvalid) or
((A.Value >= B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid);
end;
{ TLongIntTagValue }
constructor TLongIntTagValue.CreateFromString(const AString: string);
begin
if TryStrToInt(AString, FValue) then
FMissingOrInvalid := False
else
Self := CreateMissingOrInvalid;
end;
class function TLongIntTagValue.CreateMissingOrInvalid;
begin
Result.FMissingOrInvalid := True;
Result.FValue := 0;
end;
function TLongIntTagValue.GetAsString: string;
begin
if FMissingOrInvalid then
Result := ''
else
Result := IntToStr(FValue);
end;
class operator TLongIntTagValue.Equal(const A, B: TLongIntTagValue): Boolean;
begin
Result := (A.Value = B.Value) and (A.MissingOrInvalid = B.MissingOrInvalid);
end;
class operator TLongIntTagValue.Implicit(const Source: TLongIntTagValue): Int64;
begin
Result := Source.Value;
end;
class operator TLongIntTagValue.Implicit(const Source: TLongIntTagValue): LongInt;
begin
Result := Source.Value;
end;
class operator TLongIntTagValue.Implicit(const Source: LongInt): TLongIntTagValue;
begin
Result.FValue := Source;
Result.FMissingOrInvalid := False;
end;
class operator TLongIntTagValue.LessThan(const A, B: TLongIntTagValue): Boolean;
begin
Result := (A.Value < B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid;
end;
class operator TLongIntTagValue.LessThanOrEqual(const A, B: TLongIntTagValue): Boolean;
begin
Result := (A.MissingOrInvalid and B.MissingOrInvalid) or
((A.Value <= B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid);
end;
class operator TLongIntTagValue.NotEqual(const A, B: TLongIntTagValue): Boolean;
begin
Result := not (A = B);
end;
class operator TLongIntTagValue.GreaterThan(const A, B: TLongIntTagValue): Boolean;
begin
Result := (A.Value > B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid;
end;
class operator TLongIntTagValue.GreaterThanOrEqual(const A, B: TLongIntTagValue): Boolean;
begin
Result := (A.MissingOrInvalid and B.MissingOrInvalid) or
((A.Value >= B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid);
end;
class operator TLongIntTagValue.Negative(const Source: TLongIntTagValue): TLongIntTagValue;
begin
if Source.MissingOrInvalid then
Result := Source
else
Result := -Source.Value;
end;
{ TLongWordTagValue }
constructor TLongWordTagValue.CreateFromString(const AString: string);
var
Int64Val: Int64;
begin
if TryStrToInt64(AString, Int64Val) and (Int64Val >= 0) and (Int64Val <= High(LongWord)) then
begin
FValue := Int64Val;
FMissingOrInvalid := False;
end
else
Self := CreateMissingOrInvalid;
end;
class function TLongWordTagValue.CreateMissingOrInvalid;
begin
Result.FMissingOrInvalid := True;
Result.FValue := 0;
end;
class operator TLongWordTagValue.Equal(const A, B: TLongWordTagValue): Boolean;
begin
Result := (A.Value = B.Value) and (A.MissingOrInvalid = B.MissingOrInvalid);
end;
function TLongWordTagValue.GetAsString: string;
begin
if FMissingOrInvalid then
Result := ''
else
Result := IntToStr(FValue);
end;
class operator TLongWordTagValue.GreaterThan(const A, B: TLongWordTagValue): Boolean;
begin
Result := (A.Value > B.Value) and not B.MissingOrInvalid; //don't need check for A.MissingOrInvalid
end;
class operator TLongWordTagValue.GreaterThanOrEqual(const A, B: TLongWordTagValue): Boolean;
begin
Result := (A.MissingOrInvalid and B.MissingOrInvalid) or
((A.Value >= B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid);
end;
class operator TLongWordTagValue.Implicit(const Source: TLongWordTagValue): Int64;
begin
Result := Source.Value;
end;
class operator TLongWordTagValue.Implicit(const Source: TLongWordTagValue): UInt64;
begin
Result := Source.Value;
end;
class operator TLongWordTagValue.Implicit(const Source: TLongWordTagValue): LongWord;
begin
Result := Source.Value;
end;
class operator TLongWordTagValue.Implicit(const Source: LongWord): TLongWordTagValue;
begin
Result.FValue := Source;
Result.FMissingOrInvalid := False;
end;
class operator TLongWordTagValue.LessThan(const A, B: TLongWordTagValue): Boolean;
begin
Result := (A.Value < B.Value) and not A.MissingOrInvalid;
end;
class operator TLongWordTagValue.LessThanOrEqual(const A, B: TLongWordTagValue): Boolean;
begin
Result := (A.MissingOrInvalid and B.MissingOrInvalid) or
((A.Value <= B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid);
end;
class operator TLongWordTagValue.NotEqual(const A, B: TLongWordTagValue): Boolean;
begin
Result := not (A = B);
end;
{ TWordTagValue }
constructor TWordTagValue.CreateFromString(const AString: string);
var
IntVal: Integer;
begin
if TryStrToInt(AString, IntVal) and (IntVal >= 0) and (IntVal <= High(Word)) then
begin
FValue := IntVal;
FMissingOrInvalid := False;
end
else
Self := CreateMissingOrInvalid;
end;
class function TWordTagValue.CreateMissingOrInvalid;
begin
Result.FMissingOrInvalid := True;
Result.FValue := 0;
end;
class operator TWordTagValue.Equal(const A, B: TWordTagValue): Boolean;
begin
Result := (A.Value = B.Value) and (A.MissingOrInvalid = B.MissingOrInvalid);
end;
function TWordTagValue.GetAsString: string;
begin
if FMissingOrInvalid then
Result := ''
else
Result := IntToStr(FValue);
end;
class operator TWordTagValue.GreaterThan(const A, B: TWordTagValue): Boolean;
begin
Result := (A.Value > B.Value) and not B.MissingOrInvalid; //don't need check for A.MissingOrInvalid
end;
class operator TWordTagValue.GreaterThanOrEqual(const A, B: TWordTagValue): Boolean;
begin
Result := (A.MissingOrInvalid and B.MissingOrInvalid) or
((A.Value >= B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid);
end;
class operator TWordTagValue.Implicit(const Source: TWordTagValue): TLongIntTagValue;
begin
if Source.MissingOrInvalid then
Result := TLongIntTagValue.CreateMissingOrInvalid
else
Result := Source.Value;
end;
class operator TWordTagValue.Implicit(const Source: TWordTagValue): TLongWordTagValue;
begin
if Source.MissingOrInvalid then
Result := TLongWordTagValue.CreateMissingOrInvalid
else
Result := Source.Value;
end;
class operator TWordTagValue.Implicit(const Source: TWordTagValue): Int64;
begin
Result := Source.Value;
end;
class operator TWordTagValue.Implicit(const Source: TWordTagValue): UInt64;
begin
Result := Source.Value;
end;
class operator TWordTagValue.Implicit(const Source: TWordTagValue): Integer;
begin
Result := Source.Value;
end;
class operator TWordTagValue.Implicit(const Source: TWordTagValue): Word;
begin
Result := Source.Value;
end;
class operator TWordTagValue.Implicit(const Source: Word): TWordTagValue;
begin
Result.FValue := Source;
Result.FMissingOrInvalid := False;
end;
class operator TWordTagValue.LessThan(const A, B: TWordTagValue): Boolean;
begin
Result := (A.Value < B.Value) and not A.MissingOrInvalid;
end;
class operator TWordTagValue.LessThanOrEqual(const A, B: TWordTagValue): Boolean;
begin
Result := (A.MissingOrInvalid and B.MissingOrInvalid) or
((A.Value <= B.Value) and not A.MissingOrInvalid and not B.MissingOrInvalid);
end;
class operator TWordTagValue.NotEqual(const A, B: TWordTagValue): Boolean;
begin
Result := not (A = B);
end;
{ TUserMemoryStream }
constructor TUserMemoryStream.Create(Memory: Pointer; Size: Integer);
begin
inherited Create;
SetPointer(Memory, Size);
end;
procedure TUserMemoryStream.ChangeMemory(NewMemory: Pointer; NewSize: Integer);
begin
SetPointer(NewMemory, NewSize);
Position := 0;
end;
procedure TUserMemoryStream.SetSize(NewSize: Longint);
begin
raise EStreamError.CreateRes(@SStreamIsReadOnly);
end;
procedure TUserMemoryStream.SetSize(const NewSize: Int64);
begin
raise EStreamError.CreateRes(@SStreamIsReadOnly);
end;
function TUserMemoryStream.Write(const Buffer; Count: Integer): Integer;
begin
raise EStreamError.CreateRes(@SStreamIsReadOnly);
end;
{ TAdobeResBlock }
class function TAdobeResBlock.TryReadIPTCHeader(Stream: TStream;
var TagInfo: TIPTCTagInfo; AlwaysResetStreamPos: Boolean = False): Boolean;
var //IPTC data is made up of a continuous stream of tags that just begin.
Header: packed record
StartMarker: Byte;
RecID: Byte;
TagID: Byte;
DataSize: SmallInt;
end;
ByteVal: Byte;
WordVal: Word;
LongIntVal: LongInt;
begin
Result := False;
if not Stream.TryReadBuffer(Header, SizeOf(Header)) then Exit;
if (Header.StartMarker = NewIPTCTagMarker) and (Header.RecID in [Low(TIPTCSectionID)..High(TIPTCSectionID)]) then
begin
Result := True;
Header.DataSize := Swap(Header.DataSize); //big endian
if Header.DataSize >= 0 then
TagInfo.DataSize := Header.DataSize
else
case Header.DataSize of
-1: if Stream.ReadByte(ByteVal) then
TagInfo.DataSize := ByteVal
else
Result := False;
-2: if Stream.ReadWord(BigEndian, WordVal) then
TagInfo.DataSize := WordVal
else
Result := False;
-4: if Stream.ReadLongInt(BigEndian, LongIntVal) then
TagInfo.DataSize := LongIntVal
else
Result := False;
else Result := False;
end;
end;
if Result then
begin
TagInfo.SectionID := Header.RecID;
TagInfo.TagID := Header.TagID;
end;
if AlwaysResetStreamPos or not Result then
Stream.Seek(-SizeOf(Header), soCurrent);
end;
{ TAdobeBlock }
class function TAdobeBlock.GetValidSignature(const S: AnsiString): AnsiString;
begin
Result := StringOfChar(AnsiChar(' '), 4);
StrPLCopy(PAnsiChar(Result), S, 4);
end;
constructor TAdobeBlock.Create;
begin
inherited Create;
Clear;
end;
constructor TAdobeBlock.Create(AStream: TStream);
begin
inherited Create;
LoadFromStream(AStream)
end;
constructor TAdobeBlock.Create(const ASignature: AnsiString; ATypeID: Word;
const AName: AnsiString; const ADataSource: IStreamPersist);
begin
inherited Create;
FLoadedCleanly := True;
FSignature := GetValidSignature(ASignature);
FTypeID := ATypeID;
FName := AName;
if ADataSource <> nil then ADataSource.SaveToStream(Data);
end;
procedure TAdobeBlock.Clear;
begin
Data.Clear;
FSignature := GetValidSignature('');
FTypeID := 0;
FName := '';
FLoadedCleanly := True;
end;
function TAdobeBlock.GetLoadedCleanly: Boolean;
begin
Result := FLoadedCleanly;
end;
function TAdobeBlock.GetName: AnsiString;
begin
Result := FName;
end;
function TAdobeBlock.GetSignature: AnsiString;
begin
Result := FSignature;
end;
function TAdobeBlock.GetTotalSize: Integer; //!!!test
begin
Result := 11 + Length(FName) + Data.Size;
if not Odd(Length(FName)) then Inc(Result);
if Odd(Result) then Inc(Result);
end;
function TAdobeBlock.GetTypeID: Word;
begin
Result := FTypeID;
end;
function TAdobeBlock.HasExifBlockID: Boolean;
begin
Result := (FTypeID = TAdobeResBlock.ExifTypeID);
end;
function TAdobeBlock.HasIPTCBlockID: Boolean;
begin
Result := (FTypeID = TAdobeResBlock.IPTCTypeID);
end;
function TAdobeBlock.HasIPTCData: Boolean;
begin
Result := IsIPTCBlock;
end;
function TAdobeBlock.HasXMPBlockID: Boolean;
begin
Result := (FTypeID = TAdobeResBlock.XMPTypeID);
end;
procedure TAdobeBlock.LoadFromStream(Stream: TStream);
var //Method amended in trunk r.14 to avoid exceptions on some malformed
Len: Integer; //data, implementing LoadedCleanly property at the same time.
Header: packed record
Signature: array[0..3] of AnsiChar;
BigEndianTypeID: Word;
NameLen: Byte;
end;
begin
Clear;
FLoadedCleanly := False;
if not Stream.TryReadBuffer(Header, SizeOf(Header)) then Exit;
SetString(FSignature, Header.Signature, 4);
FTypeID := Swap(Header.BigEndianTypeID);
SetString(FName, nil, Header.NameLen);
if Header.NameLen <> 0 then
if not Stream.TryReadBuffer(Pointer(FName)^, Header.NameLen) then Exit;
if not Odd(Header.NameLen) then
if Stream.Read(Len, 1) <> 1 then Exit;
if not Stream.ReadLongInt(BigEndian, Len) or (Len < 0) then Exit;
if Len <> 0 then
begin
Data.SetSize(Len);
if not Stream.TryReadBuffer(Data.Memory^, Len) then Exit;
if Odd(Len) then
if Stream.Read(Len, 1) <> 1 then Exit;
end;
FLoadedCleanly := True;
end;
procedure TAdobeBlock.SaveToStream(Stream: TStream);
var
Buffer: array[0..4] of AnsiChar;
Len: Integer;
begin
Stream.WriteBuffer(StrPLCopy(Buffer, FSignature, 4)^, 4);
Stream.WriteWord(FTypeID, BigEndian);
Len := Length(FName);
if Len > High(Byte) then Len := High(Byte);
Stream.WriteByte(Len);
if Len <> 0 then Stream.WriteBuffer(Pointer(FName)^, Len);
if not Odd(Len) then Stream.WriteByte(0);
Len := Data.Size;
Stream.WriteLongInt(Len, BigEndian);
if Len <> 0 then Stream.WriteBuffer(Data.Memory^, Len);
if Odd(Len) then Stream.WriteByte(0);
end;
procedure TAdobeBlock.SetName(const Value: AnsiString);
begin
FName := Value;
end;
procedure TAdobeBlock.SetSignature(const Value: AnsiString);
begin
FSignature := GetValidSignature(Value);
end;
procedure TAdobeBlock.SetTypeID(Value: Word);
begin
FTypeID := Value;
end;
{ TAdobeResBlockEnumerator }
constructor TAdobeResBlockEnumerator.Create(AStream: TStream;
AStreamOwnership: TStreamOwnership);
begin
inherited Create;
FStream := AStream;
FStreamOwnership := AStreamOwnership;
if AStream = nil then Exit;
FNextPos := AStream.Position;
FPosTooFar := AStream.Size;
end;
destructor TAdobeResBlockEnumerator.Destroy;
begin
if FStreamOwnership = soOwned then //If loop didn't complete, MoveNext
FreeAndNil(FStream); //wouldn't have had the chance to
inherited; //free the stream.
end;
function TAdobeResBlockEnumerator.GetCurrent: IAdobeResBlock;
begin
Result := FCurrent;
end;
function TAdobeResBlockEnumerator.MoveNext: Boolean;
begin
FCurrent := nil;
Result := (FStream <> nil) and (FNextPos < FPosTooFar - 12);
if not Result then
begin
if FStreamOwnership = soOwned then
FreeAndNil(FStream);
Exit;
end;
FStream.Position := FNextPos;
FCurrent := TAdobeBlock.Create(FStream);
if FCurrent.LoadedCleanly then
FNextPos := FStream.Position
else
FNextPos := FPosTooFar;
end;
{ TJPEGSegmentHeader }
function TJPEGSegmentHeader.GetDataSize: Word;
begin
Result := DataSizeLo or (DataSizeHi shl 8);
end;
procedure TJPEGSegmentHeader.SetDataSize(const Value: Word);
begin
with WordRec(Value) do
begin
DataSizeHi := Hi;
DataSizeLo := Lo;
end;
end;
{ TJFIFData }
function TJFIFData.GetHorzDensity: Word;
begin
Result := HorzDensityLo or (HorzDensityHi shl 8);
end;
function TJFIFData.GetVertDensity: Word;
begin
Result := VertDensityLo or (VertDensityHi shl 8);
end;
procedure TJFIFData.SetHorzDensity(const Value: Word);
begin
with WordRec(Value) do
begin
HorzDensityHi := Hi;
HorzDensityLo := Lo;
end;
end;
procedure TJFIFData.SetVertDensity(const Value: Word);
begin
with WordRec(Value) do
begin
VertDensityHi := Hi;
VertDensityLo := Lo;
end;
end;
{ TJPEGStartOfFrameData }
function TJPEGStartOfFrameData.GetImageWidth: Word;
begin
Result := ImageWidthLo or (ImageWidthHi shl 8);
end;
function TJPEGStartOfFrameData.GetImageHeight: Word;
begin
Result := ImageHeightLo or (ImageHeightHi shl 8);
end;
procedure TJPEGStartOfFrameData.SetImageHeight(const Value: Word);
begin
with WordRec(Value) do
begin
ImageHeightHi := Hi;
ImageHeightLo := Lo;
end;
end;
procedure TJPEGStartOfFrameData.SetImageWidth(const Value: Word);
begin
with WordRec(Value) do
begin
ImageWidthHi := Hi;
ImageWidthLo := Lo;
end;
end;
{ TUserJPEGSegment }
constructor TUserJPEGSegment.Create(AMarkerNum: TJPEGMarker = 0;
const ASource: IStreamPersist = nil);
begin
inherited Create;
FMarkerNum := AMarkerNum;
if ASource <> nil then
begin
ASource.SaveToStream(Data);
Data.Position := 0;
end;
end;
function TUserJPEGSegment.GetEmpty: Boolean;
begin
Result := (Data.Size = 0);
end;
function TUserJPEGSegment.GetEnumerator: IAdobeResBlockEnumerator;
begin
if not IsAdobeApp13 then
Result := TAdobeResBlockEnumerator.Create(nil)
else
begin
Data.Position := FAdobeHeaderSize;
Result := TAdobeResBlockEnumerator.Create(Data)
end;
end;
function TUserJPEGSegment.GetMarkerNum: TJPEGMarker;
begin
Result := FMarkerNum;
end;
function TUserJPEGSegment.HasExifBlockID: Boolean;
begin
Result := (FMarkerNum = jmApp1);
end;
function TUserJPEGSegment.HasIPTCBlockID: Boolean;
begin
Result := (FMarkerNum = jmApp13);
end;
function TUserJPEGSegment.HasXMPBlockID: Boolean;
begin
Result := (FMarkerNum = jmApp1);
end;
function TUserJPEGSegment.IsAdobeApp13: Boolean;
begin
Result := False;
FAdobeHeaderSize := 0;
if (MarkerNum <> jmApp13) or (Data.Size < 20) then Exit;
if CompareMem(@AdobeHeader, Data.Memory, SizeOf(AdobeHeader)) then
FAdobeHeaderSize := SizeOf(AdobeHeader)
else if CompareMem(@OldAdobeHeader, Data.Memory, SizeOf(OldAdobeHeader)) then
FAdobeHeaderSize := SizeOf(OldAdobeHeader)
else
Exit;
Result := True;
end;
function TUserJPEGSegment.IsIPTCBlock(CheckID: Boolean = True): Boolean;
var
ResBlock: IAdobeResBlock;
begin
Result := True;
for ResBlock in Self do
if ResBlock.IsIPTCBlock(CheckID) then Exit;
Result := False;
end;
procedure TUserJPEGSegment.LoadFromStream(Stream: TStream);
begin
Data.Clear;
repeat
FMarkerNum := Stream.ReadByte;
until (FMarkerNum <> jmNewOrPadding); //extra $FF bytes are legal as padding
if not (FMarkerNum in TJPEGSegment.MarkersWithNoData) then
begin
Data.SetSize(Stream.ReadWord(BigEndian) - 2);
if Stream.Read(Data.Memory^, Data.Size) <> Data.Size then
begin
Data.Clear;
raise EReadError.CreateRes(@SReadError);
end;
end;
end;
procedure TUserJPEGSegment.SaveToStream(Stream: TStream);
begin
WriteJPEGSegment(Stream, MarkerNum, Data);
end;
{ TFoundJPEGSegment }
constructor TFoundJPEGSegment.Create(AMakerNum: TJPEGMarker; ASource: TStream;
ADataSize: Integer);
begin
inherited Create(AMakerNum);
FOffset := ASource.Position - SizeOf(TJPEGSegmentHeader);
if AMakerNum in TJPEGSegment.MarkersWithNoData then
Inc(FOffset, 2)
else if ADataSize > 0 then
begin
Data.SetSize(ADataSize);
ASource.ReadBuffer(Data.Memory^, ADataSize);
end;
end;
{ TFoundJPEGSegment.IFoundJPEGSegment }
function TFoundJPEGSegment.GetOffset: Int64;
begin
Result := FOffset;
end;
function TFoundJPEGSegment.GetOffsetOfData: Int64;
begin
Result := FOffset + SizeOf(TJPEGSegmentHeader);
end;
function TFoundJPEGSegment.GetTotalSize: Integer;
begin
Result := Data.Size + SizeOf(TJPEGSegmentHeader);
if MarkerNum in TJPEGSegment.MarkersWithNoData then Dec(Result, 2);
end;
{ TJPEGHeaderParser }
constructor TJPEGHeaderParser.Create(JPEGStream: TStream;
const MarkersToLookFor: TJPEGMarkers; StreamOwnership: TStreamOwnership);
begin
inherited Create;
FMarkersToLookFor := MarkersToLookFor;
FStartPos := JPEGStream.Position;
FStream := JPEGStream;
FStreamOwnership := StreamOwnership;
if JPEGStream.ReadWord(SmallEndian) <> JPEGFileHeader then
raise EInvalidJPEGHeader.CreateRes(@SInvalidJPEGHeader);
FSavedPos := FStartPos + 2;
end;
destructor TJPEGHeaderParser.Destroy;
begin
if FStreamOwnership = soOwned then //If loop didn't complete, MoveNext
FreeAndNil(FStream); //wouldn't have had the chance to
inherited; //free the stream.
end;
function TJPEGHeaderParser.GetCurrent: IFoundJPEGSegment;
begin
Result := FCurrent;
end;
function TJPEGHeaderParser.GetEnumerator: IJPEGHeaderParser;
begin
Result := Self;
end;
function TJPEGHeaderParser.MoveNext: Boolean;
var
AllocatedBuffer: Boolean;
Buffer: PAnsiChar;
BufferSize: Integer;
DataSize: Word;
MaxPos, SeekPtr: PAnsiChar;
begin
FCurrent := nil;
Result := False;
if (FStream = nil) or (FLastMarker = jmEndOfImage) then Exit;
FStream.Position := FSavedPos;
while FStream.ReadByte = jmNewOrPadding do
begin
repeat
FLastMarker := FStream.ReadByte;
until (FLastMarker <> jmNewOrPadding); //extra $FF bytes are legal as padding
if FLastMarker in TJPEGSegment.MarkersWithNoData then
DataSize := 0
else
DataSize := FStream.ReadWord(BigEndian) - 2;
if not (FLastMarker in FMarkersToLookFor) then
if FLastMarker = jmEndOfImage then
Break
else
FStream.Seek(DataSize, soCurrent)
else
begin
FCurrent := TFoundJPEGSegment.Create(FLastMarker, FStream, DataSize);
FSavedPos := FStream.Position;
Result := True;
Exit;
end;
end;
if (FLastMarker = jmStartOfScan) and (jmEndOfImage in FMarkersToLookFor) then
begin
FSavedPos := FStream.Position;
BufferSize := FStream.Size - FSavedPos;
AllocatedBuffer := not (FStream is TCustomMemoryStream);
if AllocatedBuffer then
GetMem(Buffer, BufferSize)
else
begin
Buffer := TCustomMemoryStream(FStream).Memory;
Inc(Buffer, FSavedPos);
end;
try
if AllocatedBuffer then FStream.ReadBuffer(Buffer^, BufferSize);
MaxPos := @Buffer[BufferSize - 1];
SeekPtr := Buffer;
while SeekPtr < MaxPos do
begin
Inc(SeekPtr);
if Byte(SeekPtr^) <> jmNewOrPadding then Continue;
Inc(SeekPtr);
if Byte(SeekPtr^) <> jmEndOfImage then Continue;
Inc(SeekPtr);
FStream.Position := FSavedPos + (SeekPtr - Buffer);
FCurrent := TFoundJPEGSegment.Create(jmEndOfImage, FStream, 0);
FLastMarker := jmEndOfImage;
Result := True;
Exit;
end;
finally
if AllocatedBuffer then FreeMem(Buffer);
end;
FStream.Seek(0, soEnd);
end;
if FStreamOwnership = soOwned then
FreeAndNil(FStream);
end;
function JPEGHeader(JPEGStream: TStream; const MarkersToLookFor: TJPEGMarkers;
StreamOwnership: TStreamOwnership): IJPEGHeaderParser; overload;
begin
Result := TJPEGHeaderParser.Create(JPEGStream, MarkersToLookFor, StreamOwnership);
end;
function JPEGHeader(const JPEGFile: string;
const MarkersToLookFor: TJPEGMarkers): IJPEGHeaderParser;
begin
Result := JPEGHeader(TFileStream.Create(JPEGFile, fmOpenRead or fmShareDenyWrite), MarkersToLookFor,
soOwned);
end;
function JPEGHeader(const JPEGImage: IStreamPersist;
const MarkersToLookFor: TJPEGMarkers): IJPEGHeaderParser;
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
JPEGImage.SaveToStream(Stream);
Stream.Position := 0;
Result := JPEGHeader(Stream, MarkersToLookFor, soOwned);
end;
function HasJPEGHeader(Stream: TStream): Boolean; overload;
begin
Result := Stream.TryReadHeader(JPEGFileHeader, SizeOf(JPEGFileHeader), True);
end;
function HasJPEGHeader(const FileName: string): Boolean; overload;
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Result := HasJPEGHeader(Stream);
finally
Stream.Free;
end;
end;
function GetJPEGDataSize(Data: TStream; ReturnZeroIfFindNoEOI: Boolean = False): Int64; overload;
var
OrigPos: Int64;
Segment: IFoundJPEGSegment;
begin
OrigPos := Data.Position;
if ReturnZeroIfFindNoEOI then
Result := 0
else
Result := Data.Size - OrigPos;
for Segment in JPEGHeader(Data, [jmEndOfImage]) do
Result := Data.Position - OrigPos;
Data.Position := OrigPos;
end;
function GetJPEGDataSize(const JPEGImage: IStreamPersist): Int64; overload;
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
JPEGImage.SaveToStream(Stream); //TJPEGImage.LoadFromStream keeps everything from the starting pos
Stream.Position := 0;
Result := GetJPEGDataSize(Stream);
finally
Stream.Free;
end;
end;
{ UpdateApp1JPEGSegments notes:
- Used internally by TExifData and TXMPPacket.
- Enforces the proper segment order of JFIF -> Exif -> XMP -> everything else.
- TExifData will pass in itself as NewExifSource and its child TXMPPacket instance as
NewXMPSource.
- A standalone TXMPPacket will pass nil as NewExifSource and itself as NewXMPSource. }
procedure UpdateApp1JPEGSegments(InStream, OutStream: TStream;
NewExifSource, NewXMPSource: IStreamPersistEx);
var
BytesToSegment, InStreamStartPos: Int64;
FoundExif, FoundXMP: Boolean;
I: Integer;
Segment: IFoundJPEGSegment;
SegmentsToSkip: IInterfaceList;
begin
if not HasJPEGHeader(InStream) then
raise EInvalidJPEGHeader.CreateRes(@SInvalidJPEGHeader);
FoundExif := False;
FoundXMP := False;
InStreamStartPos := InStream.Position;
SegmentsToSkip := TInterfaceList.Create;
WriteJPEGFileHeader(OutStream);
for Segment in JPEGHeader(InStream, [jmJFIF, jmApp1]) do
begin
if Segment.MarkerNum = jmJFIF then
WriteJPEGSegment(OutStream, Segment)
else
begin
if not FoundExif and Segment.IsExifBlock then
begin
FoundExif := True;
if NewExifSource = nil then NewExifSource := IStreamPersistEx(Segment);
end
else if not FoundXMP and Segment.IsXMPBlock then
begin
FoundXMP := True;
if NewXMPSource = nil then NewXMPSource := IStreamPersistEx(Segment);
end
else
Continue;
end;
SegmentsToSkip.Add(Segment);
end;
Segment := nil;
if (NewExifSource <> nil) and not NewExifSource.Empty then
if Supports(NewExifSource, IJPEGSegment, Segment) then
WriteJPEGSegment(OutStream, Segment)
else
begin
Segment := TFoundJPEGSegment.Create(jmApp1);
Segment.Data.WriteBuffer(TJPEGSegment.ExifHeader, SizeOf(TJPEGSegment.ExifHeader));
NewExifSource.SaveToStream(Segment.Data);
WriteJPEGSegment(OutStream, Segment);
end;
Segment := nil;
if (NewXMPSource <> nil) and not NewXMPSource.Empty then
if Supports(NewXMPSource, IJPEGSegment, Segment) then
WriteJPEGSegment(OutStream, Segment)
else
begin
Segment := TFoundJPEGSegment.Create(jmApp1);
Segment.Data.WriteBuffer(TJPEGSegment.XMPHeader, SizeOf(TJPEGSegment.XMPHeader));
NewXMPSource.SaveToStream(Segment.Data);
WriteJPEGSegment(OutStream, Segment);
end;
InStream.Position := InStreamStartPos + SizeOf(JPEGFileHeader);
for I := 0 to SegmentsToSkip.Count - 1 do
begin
Segment := IFoundJPEGSegment(SegmentsToSkip[I]);
BytesToSegment := Segment.Offset - InStream.Position;
if BytesToSegment > 0 then
OutStream.CopyFrom(InStream, BytesToSegment);
InStream.Seek(Segment.TotalSize, soCurrent)
end;
OutStream.CopyFrom(InStream, InStream.Size - InStream.Position);
OutStream.Size := OutStream.Position;
end;
procedure WriteJPEGFileHeader(Stream: TStream); inline;
begin
Stream.WriteBuffer(JPEGFileHeader, SizeOf(JPEGFileHeader));
end;
procedure WriteJPEGSegment(Stream: TStream; MarkerNum: TJPEGMarker;
const Data; DataSize: Word); overload;
var
Header: TJPEGSegmentHeader;
begin
Header.NewMarkerByte := jmNewOrPadding;
Header.MarkerNum := MarkerNum;
Inc(DataSize, 2);
Header.DataSizeHi := Hi(DataSize);
Header.DataSizeLo := Lo(DataSize);
Dec(DataSize, 2);
Stream.WriteBuffer(Header, SizeOf(Header));
if (DataSize > 0) and (@Data <> nil) then Stream.WriteBuffer(Data, DataSize);
end;
procedure WriteJPEGSegment(Stream: TStream; MarkerNum: TJPEGMarker;
Data: TStream; DataSize: Word); overload;
var
Buffer: Pointer;
BufferAllocated: Boolean;
begin
if DataSize = 0 then
begin
Data.Position := 0;
DataSize := Word(Data.Size);
if DataSize = 0 then
begin
WriteJPEGSegment(Stream, MarkerNum, MarkerNum, 0);
Exit;
end;
end;
BufferAllocated := not (Data is TCustomMemoryStream);
if BufferAllocated then
GetMem(Buffer, DataSize)
else
begin
Buffer := @PByteArray(TCustomMemoryStream(Data).Memory)[Data.Position];
Data.Seek(DataSize, soCurrent);
end;
try
if BufferAllocated then Data.ReadBuffer(Buffer^, DataSize);
WriteJPEGSegment(Stream, MarkerNum, Buffer^, DataSize);
finally
if BufferAllocated then FreeMem(Buffer);
end;
end;
procedure WriteJPEGSegment(Stream: TStream; Segment: IJPEGSegment); overload;
begin
WriteJPEGSegment(Stream, Segment.MarkerNum, Segment.Data);
end;
function CreateAdobeBlock: IAdobeResBlock; overload;
begin
Result := TAdobeBlock.Create;
end;
function CreateAdobeBlock(ATypeID: Word; const ADataSource: IStreamPersist = nil): IAdobeResBlock; overload;
begin
Result := TAdobeBlock.Create('8BIM', ATypeID, '', ADataSource);
end;
function CreateAdobeBlock(ATypeID: Word; ADataSource: TStream; ADataSize: Integer): IAdobeResBlock;
begin
Result := TAdobeBlock.Create('8BIM', ATypeID, '', nil);
if ADataSize < 0 then Exit;
if ADataSize = 0 then
begin
ADataSource.Position := 0;
ADataSize := Max(ADataSource.Size, MaxLongint);
end;
Result.Data.Size := ADataSize;
ADataSource.WriteBuffer(Result.Data.Memory^, ADataSize);
end;
function CreateAdobeBlock(ATypeID: Word; const AName: AnsiString;
const ADataSource: IStreamPersist): IAdobeResBlock; overload;
begin
Result := TAdobeBlock.Create('8BIM', ATypeID, AName, ADataSource);
end;
function CreateAdobeBlock(const ASignature: AnsiString; ATypeID: Word;
const AName: AnsiString; const ADataSource: IStreamPersist): IAdobeResBlock; overload;
begin
Result := TAdobeBlock.Create(ASignature, ATypeID, AName, ADataSource);
end;
function CreateAdobeApp13Segment(const Blocks: array of IAdobeResBlock): IJPEGSegment;
var
Item: IAdobeResBlock;
Stream: TStream;
begin
Result := TUserJPEGSegment.Create(jmApp13);
Stream := Result.Data;
Stream.WriteBuffer(TUserJPEGSegment.AdobeHeader, SizeOf(TUserJPEGSegment.AdobeHeader));
for Item in Blocks do
Item.SaveToStream(Stream);
end;
function CreateAdobeApp13Segment(const Blocks: IInterfaceList): IJPEGSegment;
var
I: Integer;
Stream: TStream;
begin
Result := TUserJPEGSegment.Create(jmApp13);
Stream := Result.Data;
Stream.WriteBuffer(TUserJPEGSegment.AdobeHeader, SizeOf(TUserJPEGSegment.AdobeHeader));
if Blocks <> nil then
for I := 0 to Blocks.Count - 1 do
(Blocks[I] as IAdobeResBlock).SaveToStream(Stream);
end;
function DoRemoveJPEGSegments(InStream, OutStream: TStream; Markers: TJPEGMarkers): TJPEGMarkers;
var
Segment: IFoundJPEGSegment;
StartPos: Int64;
begin
Result := [];
StartPos := InStream.Position;
for Segment in JPEGHeader(InStream, Markers - [jmEndOfImage]) do
begin
Include(Result, Segment.MarkerNum);
if Segment.Offset <> StartPos then
begin
InStream.Position := StartPos;
OutStream.CopyFrom(InStream, Segment.Offset - StartPos);
end;
StartPos := Segment.Offset + Segment.TotalSize;
end;
InStream.Position := StartPos;
OutStream.CopyFrom(InStream, InStream.Size - StartPos);
end;
function RemoveJPEGSegments(const JPEGFile: string; Markers: TJPEGMarkers): TJPEGMarkers;
var
InStream: TMemoryStream;
OutStream: TFileStream;
begin
if Markers = [] then Exit;
OutStream := nil;
InStream := TMemoryStream.Create;
try
InStream.LoadFromFile(JPEGFile);
OutStream := TFileStream.Create(JPEGFile, fmCreate);
Result := DoRemoveJPEGSegments(InStream, OutStream, Markers);
finally
OutStream.Free;
InStream.Free;
end;
end;
function RemoveJPEGSegments(const JPEGImage: IStreamPersist; Markers: TJPEGMarkers): TJPEGMarkers;
var
InStream, OutStream: TMemoryStream;
begin
if Markers = [] then Exit;
OutStream := nil;
InStream := TMemoryStream.Create;
try
JPEGImage.SaveToStream(InStream);
InStream.Position := 0;
OutStream := TMemoryStream.Create;
Result := DoRemoveJPEGSegments(InStream, OutStream, Markers);
if Result <> [] then
begin
OutStream.Position := 0;
JPEGImage.LoadFromStream(OutStream);
end;
finally
OutStream.Free;
InStream.Free;
end;
end;
{ TPSDInfo }
const
FixedPSDHeaderSize = 12;
FixedPSDHeader: array[1..FixedPSDHeaderSize] of AnsiChar = '8BPS'#0#1#0#0#0#0#0#0;
function TPSDInfo.ResourceSectionOffset: Integer;
begin
Result := FixedPSDHeaderSize + 18 + Length(Header.PaletteData);
end;
function TPSDInfo.LayersSectionOffset: Integer;
begin
Result := ResourceSectionOffset + ResourceSectionSize;
end;
{ PSD file parsing }
type
TAdobeResBlockParser = class(TAdobeResBlockEnumerator, IAdobeResBlockParser)
protected
function GetEnumerator: IAdobeResBlockEnumerator;
public
constructor Create(AStream: TStream; AStreamOwnership: TStreamOwnership; var Info: TPSDInfo);
end;
constructor TAdobeResBlockParser.Create(AStream: TStream;
AStreamOwnership: TStreamOwnership; var Info: TPSDInfo);
function ReadLen: LongInt;
begin
if not Stream.ReadLongInt(BigEndian, Result) or (Result < 0) then
raise EInvalidPSDHeader.CreateRes(@SInvalidPSDHeader);
end;
begin
inherited Create(AStream, AStreamOwnership);
if not Stream.TryReadHeader(FixedPSDHeader, SizeOf(FixedPSDHeader)) then
raise EInvalidPSDHeader.CreateRes(@SInvalidPSDHeader);
Info.Header.Channels := Stream.ReadWord(BigEndian);
Info.Header.Height := Stream.ReadLongInt(BigEndian);
Info.Header.Width := Stream.ReadLongInt(BigEndian);
Info.Header.Depth := Stream.ReadWord(BigEndian);
Word(Info.Header.ColorMode) := Stream.ReadWord(BigEndian);
SetLength(Info.Header.PaletteData, ReadLen);
if Info.Header.PaletteData <> nil then
Stream.ReadBuffer(Info.Header.PaletteData[0], Length(Info.Header.PaletteData));
Info.ResourceSectionSize := ReadLen + 4;
NextPos := AStream.Position;
PosTooFar := Min(PosTooFar, NextPos + Info.ResourceSectionSize - 4);
Stream.Seek(Info.ResourceSectionSize - 4, soCurrent);
Info.LayersSectionSize := ReadLen + 4;
end;
function TAdobeResBlockParser.GetEnumerator: IAdobeResBlockEnumerator;
begin
Result := Self;
end;
function HasPSDHeader(Stream: TStream): Boolean; overload;
var
Buffer: array[1..FixedPSDHeaderSize] of AnsiChar;
BytesRead: Integer;
begin
BytesRead := Stream.Read(Buffer, FixedPSDHeaderSize);
Result := (BytesRead = FixedPSDHeaderSize) and
CompareMem(@Buffer, @FixedPSDHeader, FixedPSDHeaderSize);
Stream.Seek(-BytesRead, soCurrent);
end;
function HasPSDHeader(const FileName: string): Boolean; overload;
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Result := HasPSDHeader(Stream);
finally
Stream.Free;
end;
end;
function ParsePSDHeader(Stream: TStream; var Info: TPSDInfo;
StreamOwnership: TStreamOwnership): IAdobeResBlockParser;
begin
Result := TAdobeResBlockParser.Create(Stream, StreamOwnership, Info);
end;
function ParsePSDHeader(const FileName: string; var Info: TPSDInfo): IAdobeResBlockParser; overload; inline;
begin
Result := ParsePSDHeader(TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite), Info, soOwned);
end;
procedure WritePSDHeader(Stream: TStream; const Info: TPSDHeaderInfo);
begin
Stream.WriteBuffer(FixedPSDHeader, FixedPSDHeaderSize);
Stream.WriteWord(Info.Channels, BigEndian);
Stream.WriteLongInt(Info.Height, BigEndian);
Stream.WriteLongInt(Info.Width, BigEndian);
Stream.WriteWord(Info.Depth, BigEndian);
Stream.WriteWord(Word(Info.ColorMode), BigEndian);
Stream.WriteLongInt(Length(Info.PaletteData), BigEndian);
if Info.PaletteData <> nil then
Stream.WriteBuffer(Info.PaletteData[0], Length(Info.PaletteData));
end;
procedure WritePSDResourceSection(Stream: TStream; const Blocks: array of IAdobeResBlock); overload;
var
Block: IAdobeResBlock;
TotalSize: Integer;
begin
TotalSize := 0;
for Block in Blocks do
if Block <> nil then Inc(TotalSize, Block.TotalSize);
Stream.WriteLongInt(TotalSize, BigEndian);
if TotalSize <> 0 then
for Block in Blocks do
if Block <> nil then Block.SaveToStream(Stream);
end;
procedure WritePSDResourceSection(Stream: TStream; const Blocks: IInterfaceList);
var
DynArray: array of IAdobeResBlock;
I: Integer;
begin
if Blocks <> nil then
begin
SetLength(DynArray, Blocks.Count);
for I := 0 to Blocks.Count - 1 do
Supports(Blocks[I], IAdobeResBlock, DynArray[I]);
end;
WritePSDResourceSection(Stream, DynArray);
end;
function GetExecutableName: string;
var
MatchedCase: TFilenameCaseMatch;
begin
Result := ExpandFileNameCase(GetModuleName(0), MatchedCase);
end;
end.
|
unit uFrameUserTable;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxSplitter, cxPC, cxControls, uFrameGrid;
type
TFrameUserTable = class(TFrame)
pcChild: TcxPageControl;
Splitter: TcxSplitter;
private
FChildVisible: boolean;
procedure SetChildVisible(const Value: boolean);
{ Private declarations }
public
function AddChildSheet: TcxTabSheet; virtual;
property ChildVisible: boolean read FChildVisible write SetChildVisible;
end;
implementation
{$R *.dfm}
{ TFrameUserBook }
function TFrameUserTable.AddChildSheet: TcxTabSheet;
begin
result:=TcxTabSheet.Create(self);
result.PageControl:=pcChild;
end;
procedure TFrameUserTable.SetChildVisible(const Value: boolean);
begin
FChildVisible:=Value;
pcChild.Visible:=Value;
Splitter.Visible:=Value;
end;
end.
|
{$DEFINE Delphi3orHigher}
unit Dmitry.Controls.ShellNotification;
interface
uses Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs,
{$IFNDEF Delphi3orHigher} OLE2, {$ELSE} ActiveX, ComObj, {$ENDIF}
ShlObj;
type
NOTIFYREGISTER = record
pidlPath : PItemIDList;
bWatchSubtree : boolean;
end;
PNOTIFYREGISTER = ^NOTIFYREGISTER;
const
SNM_SHELLNOTIFICATION = WM_USER +1;
SHCNF_ACCEPT_INTERRUPTS = $0001;
SHCNF_ACCEPT_NON_INTERRUPTS = $0002;
SHCNF_NO_PROXY = $8000;
type
TNotificationEvent = (neAssociationChange, neAttributesChange,
neFileChange, neFileCreate, neFileDelete, neFileRename,
neDriveAdd, neDriveRemove, neShellDriveAdd, neDriveSpaceChange,
neMediaInsert, neMediaRemove, neFolderCreate, neFolderDelete,
neFolderRename, neFolderUpdate, neNetShare, neNetUnShare,
neServerDisconnect, neImageListChange);
TNotificationEvents = set of TNotificationEvent;
TShellNotificationEvent1 = procedure(Sender: TObject;
Path: String)of Object;
TShellNotificationEvent2 = procedure(Sender: TObject;
path1, path2: String) of Object;
TShellNotification = class(TComponent)
private
fWatchEvents: TNotificationEvents;
fPath: String;
fActive, fWatch: Boolean;
prevPath1, prevPath2: String;
PrevEvent: Integer;
Handle, NotifyHandle: HWND;
fOnAssociationChange: TNotifyEvent;
fOnAttribChange: TShellNotificationEvent2;
FOnCreate: TShellNotificationEvent1;
FOnDelete: TShellNotificationEvent1;
FOnDriveAdd: TShellNotificationEvent1;
FOnDriveAddGui: TShellNotificationEvent1;
FOnDriveRemove: TShellNotificationEvent1;
FOnMediaInsert: TShellNotificationEvent1;
FOnMediaRemove: TShellNotificationEvent1;
FOnDirCreate: TShellNotificationEvent1;
FOnNetShare: TShellNotificationEvent1;
FOnNetUnShare: TShellNotificationEvent1;
FOnRenameFolder: TShellNotificationEvent2;
FOnItemRename: TShellNotificationEvent2;
FOnFolderRemove: TShellNotificationEvent1;
FOnServerDisconnect: TShellNotificationEvent1;
FOnFolderUpdate: TShellNotificationEvent1;
function PathFromPidl(Pidl: PItemIDList): String;
procedure SetWatchEvents(const Value: TNotificationEvents);
function GetActive: Boolean;
procedure SetActive(const Value: Boolean);
procedure SetPath(const Value: String);
procedure SetWatch(const Value: Boolean);
protected
procedure ShellNotifyRegister;
procedure ShellNotifyUnregister;
procedure WndProc(var Message: TMessage);
procedure DoAssociationChange; dynamic;
procedure DoAttributesChange(Path1, Path2: String); dynamic;
procedure DoCreateFile(Path: String); dynamic;
procedure DoDeleteFile(Path: String); dynamic;
procedure DoDriveAdd(Path:String); dynamic;
procedure DoDriveAddGui(Path: String); dynamic;
procedure DoDriveRemove(Path: String); dynamic;
procedure DoMediaInsert(Path: String); dynamic;
procedure DoMediaRemove(Path: String); dynamic;
procedure DoDirCreate(Path: String); dynamic;
procedure DoNetShare(Path: String); dynamic;
procedure DoNetUnShare(Path: String); dynamic;
procedure DoRenameFolder(Path1, Path2: String); dynamic;
procedure DoRenameItem(Path1, Path2: String); dynamic;
procedure DoFolderRemove(Path: String); dynamic;
procedure DoServerDisconnect(Path: String); dynamic;
procedure DoDirUpdate(Path: String); dynamic;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Path: String read fPath write SetPath;
property Active: Boolean read GetActive write SetActive;
property WatchSubTree: Boolean read fWatch write SetWatch;
property WatchEvents: TNotificationEvents
read fWatchEvents write SetWatchEvents;
property OnAssociationChange: TNotifyEvent
read fOnAssociationChange write FOnAssociationChange;
property OnAttributesChange: TShellNotificationEvent2
read fOnAttribChange write fOnAttribChange;
property OnFileCreate: TShellNotificationEvent1
read FOnCreate write FOnCreate;
property OnFolderRename: TShellNotificationEvent2
read FOnRenameFolder write FOnRenameFolder;
property OnFolderUpdate: TShellNotificationEvent1
read FOnFolderUpdate write FOnFolderUpdate;
property OnFileDelete: TShellNotificationEvent1
read FOnDelete write FOnDelete;
property OnDriveAdd: TShellNotificationEvent1
read FOnDriveAdd write FOnDriveAdd;
property OnFolderRemove: TShellNotificationEvent1
read FOnFolderRemove write FOnFolderRemove;
property OnItemRename: TShellNotificationEvent2
read FOnItemRename write FOnItemRename;
property OnDriveAddGui: TShellNotificationEvent1
read FOnDriveAddGui write FOnDriveAddGui;
property OnDriveRemove: TShellNotificationEvent1
read FOnDriveRemove write FOnDriveRemove;
property OnMediaInserted: TShellNotificationEvent1
read FOnMediaInsert write FOnMediaInsert;
property OnMediaRemove: TShellNotificationEvent1
read FOnMediaRemove write FOnMediaRemove;
property OnDirCreate: TShellNotificationEvent1
read FOnDirCreate write FOnDirCreate;
property OnNetShare: TShellNotificationEvent1
read FOnNetShare write FOnNetShare;
property OnNetUnShare: TShellNotificationEvent1
read FOnNetUnShare write FOnNetUnShare;
property OnServerDisconnect: TShellNotificationEvent1
read FOnServerDisconnect write FOnServerDisconnect;
end;
function SHChangeNotifyRegister( hWnd: HWND; dwFlags: integer;
wEventMask : cardinal; uMsg: UINT; cItems : integer;
lpItems : PNOTIFYREGISTER) : HWND; stdcall;
function SHChangeNotifyDeregister(hWnd: HWND) : boolean; stdcall;
function SHILCreateFromPath(Path: Pointer; PIDL: PItemIDList;
var Attributes: ULONG):HResult; stdcall;
procedure Register;
implementation
const Shell32DLL = 'shell32.dll';
function SHChangeNotifyRegister; external Shell32DLL index 2 delayed;
function SHChangeNotifyDeregister; external Shell32DLL index 4 delayed;
function SHILCreateFromPath; external Shell32DLL index 28 delayed;
{ TShellNotification }
constructor TShellNotification.Create(AOwner: TComponent);
begin
inherited Create( AOwner );
if not (csDesigning in ComponentState) then
Handle := AllocateHWnd(WndProc);
PrevEvent := 0;
fWatchEvents := [neAssociationChange, neAttributesChange,
neFileChange, neFileCreate, neFileDelete, neFileRename,
neDriveAdd, neDriveRemove, neShellDriveAdd, neDriveSpaceChange,
neMediaInsert, neMediaRemove, neFolderCreate, neFolderDelete,
neFolderRename, neFolderUpdate, neNetShare, neNetUnShare,
neServerDisconnect, neImageListChange];
end;
destructor TShellNotification.Destroy;
begin
if not (csDesigning in ComponentState) then
Active := False;
if Handle <> 0 then DeallocateHWnd( Handle );
inherited Destroy;
end;
procedure TShellNotification.DoAssociationChange;
begin
if Assigned( fOnAssociationChange ) and (neAssociationChange in fWatchEvents) then
fOnAssociationChange( Self );
end;
procedure TShellNotification.DoAttributesChange;
begin
if Assigned( fOnAttribChange ) then
fOnAttribChange( Self, Path1, Path2 );
end;
procedure TShellNotification.DoCreateFile(Path: String);
begin
if Assigned( fOnCreate ) then
FOnCreate(Self, Path)
end;
procedure TShellNotification.DoDeleteFile(Path: String);
begin
if Assigned( FOnDelete ) then
FOnDelete(Self, Path);
end;
procedure TShellNotification.DoDirCreate(Path: String);
begin
if Assigned( FOnDirCreate ) then
FOnDirCreate( Self, Path );
end;
procedure TShellNotification.DoDirUpdate(Path: String);
begin
if Assigned( FOnFolderUpdate ) then
FOnFolderUpdate(Self, Path);
end;
procedure TShellNotification.DoDriveAdd(Path: String);
begin
if Assigned( FOnDriveAdd ) then
FOnDriveAdd(Self, Path);
end;
procedure TShellNotification.DoDriveAddGui(Path: String);
begin
if Assigned( FOnDriveAddGui ) then
FOnDriveAdd(Self, Path);
end;
procedure TShellNotification.DoDriveRemove(Path: String);
begin
if Assigned( FOnDriveRemove ) then
FOnDriveRemove(Self, Path);
end;
procedure TShellNotification.DoFolderRemove(Path: String);
begin
if Assigned(FOnFolderRemove) then
FOnFolderRemove( Self, Path );
end;
procedure TShellNotification.DoMediaInsert(Path: String);
begin
if Assigned( FOnMediaInsert ) then
FOnMediaInsert(Self, Path);
end;
procedure TShellNotification.DoMediaRemove(Path: String);
begin
if Assigned(FOnMediaRemove) then
FOnMediaRemove(Self, Path);
end;
procedure TShellNotification.DoNetShare(Path: String);
begin
if Assigned(FOnNetShare) then
FOnNetShare(Self, Path);
end;
procedure TShellNotification.DoNetUnShare(Path: String);
begin
if Assigned(FOnNetUnShare) then
FOnNetUnShare(Self, Path);
end;
procedure TShellNotification.DoRenameFolder(Path1, Path2: String);
begin
if Assigned( FOnRenameFolder ) then
FOnRenameFolder(Self, Path1, Path2);
end;
procedure TShellNotification.DoRenameItem(Path1, Path2: String);
begin
if Assigned( FOnItemRename ) then
FonItemRename(Self, Path1, Path2);
end;
procedure TShellNotification.DoServerDisconnect(Path: String);
begin
if Assigned( FOnServerDisconnect ) then
FOnServerDisconnect(Self, Path);
end;
function TShellNotification.GetActive: Boolean;
begin
Result := (NotifyHandle <> 0) and (fActive);
end;
function TShellNotification.PathFromPidl(Pidl: PItemIDList): String;
begin
SetLength(Result, Max_Path);
if not SHGetPathFromIDList(Pidl, PChar(Result)) then Result := '';
if pos(#0, Result) > 0 then
SetLength(Result, pos(#0, Result));
end;
procedure TShellNotification.SetActive(const Value: Boolean);
begin
if (Value <> fActive) then
begin
fActive := Value;
if fActive then ShellNotifyRegister else ShellNotifyUnregister;
end;
end;
procedure TShellNotification.SetPath(const Value: String);
begin
if fPath <> Value then
begin
fPath := Value;
ShellNotifyRegister;
end;
end;
procedure TShellNotification.SetWatch(const Value: Boolean);
begin
if fWatch <> Value then
begin
fWatch := Value;
ShellNotifyRegister;
end;
end;
procedure TShellNotification.SetWatchEvents(
const Value: TNotificationEvents);
begin
if fWatchEvents <> Value then
begin
fWatchEvents := Value;
ShellNotifyRegister;
end;
end;
procedure TShellNotification.ShellNotifyRegister;
var
Option: TNotificationEvent;
NotifyRecord: NOTIFYREGISTER;
Flags: DWORD;
Pidl: PItemIDList;
Attributes: ULONG;
const
NotifyFlags: array[TNotificationEvent] of DWORD = (
SHCNE_ASSOCCHANGED, SHCNE_ATTRIBUTES, SHCNE_UPDATEITEM,
SHCNE_CREATE, SHCNE_DELETE, SHCNE_RENAMEITEM, SHCNE_DRIVEADD,
SHCNE_DRIVEREMOVED, SHCNE_DRIVEADDGUI, SHCNE_FREESPACE,
SHCNE_MEDIAINSERTED, SHCNE_MEDIAREMOVED, SHCNE_MKDIR,
SHCNE_RMDIR, SHCNE_RENAMEFOLDER, SHCNE_UPDATEDIR,
SHCNE_NETSHARE, SHCNE_NETUNSHARE, SHCNE_SERVERDISCONNECT,
SHCNE_UPDATEIMAGE);
begin
ShellNotifyUnregister;
if not (csDesigning in ComponentState) and
not (csLoading in ComponentState) then
begin
SHILCreatefromPath( PChar(fPath), @Pidl, Attributes);
NotifyRecord.pidlPath := Pidl;
NotifyRecord.bWatchSubtree := fWatch;
Flags := 0;
for Option := Low(Option) to High(Option) do
if (Option in FWatchEvents) then
Flags := Flags or NotifyFlags[Option];
NotifyHandle := SHChangeNotifyRegister(Handle,
SHCNF_ACCEPT_INTERRUPTS or SHCNF_ACCEPT_NON_INTERRUPTS,
Flags, SNM_SHELLNOTIFICATION, 1, @NotifyRecord);
end;
end;
procedure TShellNotification.ShellNotifyUnregister;
begin
if NotifyHandle <> 0 then
SHChangeNotifyDeregister(NotifyHandle);
end;
procedure TShellNotification.WndProc(var Message: TMessage);
type
TPIDLLIST = record
pidlist : array[1..2] of PITEMIDLIST;
end;
PIDARRAY = ^TPIDLLIST;
var
Path1 : string;
Path2 : string;
ptr : PIDARRAY;
repeated : boolean;
event : longint;
begin
case Message.Msg of
SNM_SHELLNOTIFICATION:
begin
event := Message.LParam and ($7FFFFFFF);
Ptr := PIDARRAY(Message.WParam);
Path1 := PathFromPidl( Ptr^.pidlist[1] );
Path2 := PathFromPidl( Ptr^.pidList[2] );
repeated := (PrevEvent = event)
and (uppercase(prevpath1) = uppercase(Path1))
and (uppercase(prevpath2) = uppercase(Path2));
if Repeated then exit;
PrevEvent := Message.Msg;
prevPath1 := Path1;
prevPath2 := Path2;
case event of
SHCNE_ASSOCCHANGED : DoAssociationChange;
SHCNE_ATTRIBUTES : DoAttributesChange( Path1, Path2);
SHCNE_CREATE : DoCreateFile(Path1);
SHCNE_DELETE : DoDeleteFile(Path1);
SHCNE_DRIVEADD : DoDriveAdd(Path1);
SHCNE_DRIVEADDGUI : DoDriveAddGui(path1);
SHCNE_DRIVEREMOVED : DoDriveRemove(Path1);
SHCNE_MEDIAINSERTED : DoMediaInsert(Path1);
SHCNE_MEDIAREMOVED : DoMediaRemove(Path1);
SHCNE_MKDIR : DoDirCreate(Path1);
SHCNE_NETSHARE : DoNetShare(Path1);
SHCNE_NETUNSHARE : DoNetUnShare(Path1);
SHCNE_RENAMEFOLDER : DoRenameFolder(Path1, Path2);
SHCNE_RENAMEITEM : DoRenameItem(Path1, Path2);
SHCNE_RMDIR : DoFolderRemove(Path1);
SHCNE_SERVERDISCONNECT : DoServerDisconnect(Path);
SHCNE_UPDATEDIR : DoDirUpdate(Path);
SHCNE_UPDATEIMAGE : ;
SHCNE_UPDATEITEM : ;
end;//Case event of
end;//SNM_SHELLNOTIFICATION
end; //case
end;
procedure Register;
begin
RegisterComponents('Shell', [TShellNotification]);
end;
end.
|
PROGRAM wildcard;
(* Matching Going from the left to right
recursive *)
FUNCTION Matching(p, s : STRING):Boolean;
VAR
i,j:Integer;
BEGIN
i := 1;
j := 1;
WHILE (p[j] <> '*') AND (j <= length(p)) AND ((s[i] = p[j]) OR
(p[j] = '?')) DO BEGIN
i := i + 1;
j := j + 1;
END;
IF (p[j] <> '*') AND (i <= length(s)) THEN BEGIN
Matching := Matching(p,Copy(s,2,length(s)))
END
ELSE IF (j <= length(p)) AND (i <= length(s)) THEN BEGIN
Matching := Matching(Copy(p, j + 1, Length(p)),Copy(s, 2, length(s)));
END
ELSE IF ((j >= length(p)) AND (i >= length(s))) OR
((j = length(p)) AND (p[j] = '*')) THEN BEGIN
Matching := True;
END
ELSE Begin
Matching := False;
END;
END;
VAR
s,p : STRING;
BEGIN
s := '?c?$';
p := 'aca$';
IF Matching(s, p) THEN WriteLn(s, ' and ', p, #9#9, ' True')
ELSE WriteLn(s, ' and ', p, #9, ' False');
s := '?c?$';
p := 'acasdfa$';
IF Matching(s, p) THEN WriteLn(s, ' and ', p, #9, ' True')
ELSE WriteLn(s, ' and ', p, #9, ' False');
s := '*c?$';
p := 'asssssca$';
IF Matching(s, p) THEN WriteLn(s, ' and ', p, #9, ' True')
ELSE WriteLn(s, ' and ', p, #9, ' False');
s := '?c*$';
p := 'acaaaaaaaaaa$';
IF Matching(s, p) THEN WriteLn(s, ' and ', p, #9, ' True')
ELSE WriteLn(s, ' and ', p, #9,' False');
s := '?*c*?$';
p := 'aabbacaba$';
IF Matching(s, p) THEN WriteLn(s, ' and ', p, #9, ' True')
ELSE WriteLn(s, ' and ', p, #9,' False');
END. |
unit uClasses;
interface
type
TCarros = class
private
FCodigo: Integer;
FModelo: string;
FDataLancamento: TDateTime;
procedure SetCodigo(const Value: Integer);
procedure SetModelo(const Value: string);
procedure SetDataLancamento(const Value: TDateTime);
published
property Codigo : Integer read FCodigo write SetCodigo;
property Modelo : string read FModelo write SetModelo;
property DataLancamento : TDateTime read FDataLancamento write SetDataLancamento;
class function Inserir(pModelo: string; pDataLancamento:TDateTime): TCarros;
class function Buscar(pCodigo: Integer):TCarros;
end;
TCliente = class
private
FCodigo: Integer;
FCPF: String;
procedure SetCodigo(const Value: Integer);
procedure SetCPF(const Value: String);
published
property Codigo : Integer read FCodigo write SetCodigo;
property CPF : String read FCPF write SetCPF;
class function Inserir(pCPF: string): TCliente;
class function Buscar(pCodigo: Integer):TCliente;
end;
TVendas = class
private
FCodigo: Integer;
FCliente: TCliente;
FCarro: TCarros;
procedure SetCodigo(const Value: Integer);
procedure SetCliente(const Value: TCliente);
procedure SetCarro(const Value: TCarros);
published
property Codigo : Integer read FCodigo write SetCodigo;
property Cliente : TCliente read FCliente write SetCliente;
property Carro : TCarros read FCarro write SetCarro;
class function Inserir(pCliente: TCliente; pCarros: TCarros):TVendas;
end;
TRotina = class
public
procedure Executar;
end;
implementation
uses uClasses;
{ Carros }
class function TCarros.Buscar(pCodigo: Integer): TCarros;
begin
Result := TCarros.Create;
//Utilizei o ExecutarSql para retornar campo a campo
Result.Codigo := pCodigo;
Result.Modelo := ExecutarSql('Select Modelo from Carros where codigo = ' + IntToStr(pCodigo));
Result.DataLancamento := ExecutarSql('Select DataLancamento from Carros where codigo = ' + IntToStr(pCodigo));
end;
class function TCarros.Inserir(pModelo: string; pDataLancamento:TDateTime): TCarros;
begin
Result := TCarros.Create;
Result.Codigo := ExecutarSql('Select max(cod) + 1 as Codigo from Carros ');
Result.Modelo := pModelo;
Result.DataLancamento := pDataLancamento;
InserirDadosBD('insert into Carros (Codigo, Modelo, DataLancamento) values ('+IntToStr(Result.Codigo)+','+Result.Modelo+','+DateTimeToStr(pDataLancamento)+')');
end;
procedure TCarros.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TCarros.SetDataLancamento(const Value: TDateTime);
begin
FDataLancamento := Value;
end;
procedure TCarros.SetModelo(const Value: string);
begin
FModelo := Value;
end;
{ Cliente }
class function TCliente.Buscar(pCodigo: Integer): TCliente;
begin
Result := TCliente.Create;
//Utilizei o ExecutarSql para retornar campo a campo
Result.Codigo := pCodigo;
Result.CPF := ExecutarSql('Select CPF from Cliente where codigo = ' + IntToStr(pCodigo));
end;
class function TCliente.Inserir(pCPF: string): TCliente;
begin
if ExecutarSql('Select count(1) as CPF from Cliente where CPF = '''+pCPF+'''') = 0 then
begin
Result := TCliente.Create;
Result.Codigo := ExecutarSql('Select max(cod) + 1 as Codigo from Cliente ');
Result.CPF := pCPF;
InserirDadosBD('insert into Cliente (Codigo, CPF) values ('+IntToStr(Result.Codigo)+','+Result.CPF+')');
end;
end;
procedure TCliente.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TCliente.SetCPF(const Value: String);
begin
FCPF := Value;
end;
{ Vendas }
class function TVendas.Inserir(pCliente: TCliente;
pCarros: TCarros): TVendas;
begin
Result := TVendas.Create;
Result.Codigo := ExecutarSql('Select max(cod) + 1 as Codigo from Vendas ');
Result.Cliente := pCliente;
Result.Carros := pCarros;
InserirDadosBD('insert into Carros (Codigo, Modelo, DataLancamento) values ('+IntToStr(Result.Codigo)+','+Result.Modelo+','+DateTimeToStr(pDataLancamento)+')');v
end;
procedure TVendas.SetCarro(const Value: TCarros);
begin
FCarro := Value;
end;
procedure TVendas.SetCliente(const Value: TCliente);
begin
FCliente := Value;
end;
procedure TVendas.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
{ TRotina }
procedure TRotina.Executar;
begin
TCliente.Inserir('000.000.000-00');
TCliente.Inserir('111.111.111-11');
TCliente.Inserir('222.222.222-22');
TCliente.Inserir('333.333.333-33');
TCliente.Inserir('444.444.444-44');
TCarros.Inserir('Marea', Now);
TCarros.Inserir('Uno', Now);
TCarros.Inserir('Palio', Now);
TCarros.Inserir('Gol', Now);
TCarros.Inserir('Vectra', Now);
TVendas.Inserir(TCliente.Buscar(1), TCarro.Buscar(5));
TVendas.Inserir(TCliente.Buscar(2), TCarro.Buscar(4));
TVendas.Inserir(TCliente.Buscar(3), TCarro.Buscar(3));
TVendas.Inserir(TCliente.Buscar(4), TCarro.Buscar(2));
TVendas.Inserir(TCliente.Buscar(5), TCarro.Buscar(1));
end;
end.
|
unit SHDefaultDataSaver;
interface
uses
Classes,DB,
DBGridEh, DBGridEhImpExp,
// SQLHammer
SHDesignIntf;
type
TBTDataSaver = class(TSHComponent, ISHDataSaver, ISHDemon)
private
FSupportsExtentions: TStringList;
FExtentionDescriptions: TStringList;
protected
function SupportsExtentions: TStrings;
function ExtentionDescriptions: TStrings;
procedure SaveToFile(AComponent, ADataset, AGrid: TComponent; AFileName: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
procedure Register();
implementation
uses SysUtils;
var
CXlsBof: array[0..5] of Word = ($809, 8, 0, $10, 0, 0);
CXlsEof: array[0..1] of Word = ($0A, 00);
CXlsLabel: array[0..5] of Word = ($FF, 0, 0, 0, 0, 0);
CXlsNumber: array[0..4] of Word = ($203, 14, 0, 0, 0);
CXlsRk: array[0..4] of Word = ($27E, 10, 0, 0, 0);
CXlsBlank: array[0..4] of Word = ($201, 6, 0, 0, $17);
type THackXLSExporter=class(TDBGridEhExport)
private
FCol, FRow: Word;
end;
TBTGridToXLSFile=class(TDBGridEhExportAsXLS)
private
procedure WriteWideStringCell(const AValue: WideString);
procedure IncColRow;
protected
procedure WriteDataCell(Column: TColumnEh; FColCellParamsEh: TColCellParamsEh); override;
end;
procedure StreamWriteWordArray(Stream: TStream; wr: array of Word);
var
i: Integer;
begin
for i := 0 to Length(wr)-1 do
{$IFDEF CIL}
Stream.Write(wr[i]);
{$ELSE}
Stream.Write(wr[i], SizeOf(wr[i]));
{$ENDIF}
end;
procedure StreamWriteWideString(Stream: TStream; S: WideString);
begin
Stream.Write(PWideChar(S)^, (Length(s)) * SizeOf(WideChar));
end;
procedure StreamWriteString(Stream: TStream; S: String);
begin
Stream.Write(PChar(S)^, (Length(s)));
end;
procedure TBTGridToXLSFile.WriteWideStringCell(const AValue: WideString);
var
L: Word;
begin
L := Length(aValue);
CXlsLabel[1] := 8 + L*SizeOf(WideChar);
CXlsLabel[2] := THackXLSExporter(Self).FRow;
CXlsLabel[3] := THackXLSExporter(Self).FCol;
CXlsLabel[5] := L*SizeOf(WideChar);
StreamWriteWordArray(Stream, CXlsLabel);
// Stream.WriteBuffer(CXlsLabel, SizeOf(CXlsLabel));
StreamWriteWideString(Stream, AValue);
// StreamWriteString(Stream, S);
// Stream.WriteBuffer(Pointer(AValue)^, L);
IncColRow;
end;
procedure TBTGridToXLSFile.WriteDataCell(Column: TColumnEh; FColCellParamsEh: TColCellParamsEh);
begin
if True or(Column.Field = nil) or not(Column.Field is TWideStringField) then
inherited
else
WriteWideStringCell(TWideStringField(Column.Field).Value)
// Не получилось. Там формат какой-то другой.
end;
procedure TBTGridToXLSFile.IncColRow;
begin
with THackXLSExporter(Self) do
begin
if FCol = ExpCols.Count - 1 then
begin
Inc(FRow);
FCol := 0;
end else
Inc(FCol);
end
end;
procedure Register();
begin
SHRegisterComponents([TBTDataSaver]);
end;
{ TBTDataSaver }
function TBTDataSaver.SupportsExtentions: TStrings;
begin
Result := FSupportsExtentions;
end;
function TBTDataSaver.ExtentionDescriptions: TStrings;
begin
Result := FExtentionDescriptions;
end;
procedure TBTDataSaver.SaveToFile(AComponent, ADataset, AGrid: TComponent;
AFileName: string);
var
vExpClass: TDBGridEhExportClass;
vExt: string;
begin
if AGrid.InheritsFrom(TDBGridEh) then
begin
vExt := ExtractFileExt(AFileName);
case FSupportsExtentions.IndexOf(vExt) of
0: vExpClass := TDBGridEhExportAsText;
1: vExpClass := TDBGridEhExportAsCSV;
2: vExpClass := TDBGridEhExportAsHTML;
3: vExpClass := TDBGridEhExportAsRTF;
// 4: vExpClass := TDBGridEhExportAsXLS;
4: vExpClass := TBTGridToXLSFile;
else
vExpClass := nil;
end;
if vExpClass <> nil then
begin
if TDBGridEh(AGrid).Selection.SelectionType = gstNon then
SaveDBGridEhToExportFile(vExpClass, TDBGridEh(AGrid), AFileName, True)
else
SaveDBGridEhToExportFile(vExpClass, TDBGridEh(AGrid), AFileName, False);
end;
end;
end;
constructor TBTDataSaver.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSupportsExtentions := TStringList.Create;
FExtentionDescriptions := TStringList.Create;
FSupportsExtentions.Add('.txt');
FSupportsExtentions.Add('.csv');
FSupportsExtentions.Add('.htm');
FSupportsExtentions.Add('.rtf');
FSupportsExtentions.Add('.xls');
FExtentionDescriptions.Add('Text files');
FExtentionDescriptions.Add('Comma separated values');
FExtentionDescriptions.Add('HTML file');
FExtentionDescriptions.Add('Rich Text Format');
FExtentionDescriptions.Add('Microsoft Excel Workbook');
end;
destructor TBTDataSaver.Destroy;
begin
FSupportsExtentions.Free;
FExtentionDescriptions.Free;
inherited;
end;
initialization
Register();
end.
|
//Delphi版雪花算法
//作者:不得闲
//https://github.com/suiyunonghen/DelphiSnowflake
//QQ: 75492895
unit DxSnowflake;
interface
uses System.SysUtils,System.SyncObjs,System.Generics.Collections,System.DateUtils;
type
TWorkerID = 0..1023;
TDxSnowflake = class
private
FWorkerID: TWorkerID;
FLocker: TCriticalSection;
fTime: Int64;
fstep: int64;
FStartEpoch: Int64;
public
constructor Create(StartTime: TDateTime);
destructor Destroy;override;
property WorkerID: TWorkerID read FWorkerID write FWorkerID;
function Generate: Int64;
end;
implementation
const
Epoch: int64 = 1539615188000; //北京时间2018-10-15号
//工作站的节点位数
WorkerNodeBits:Byte = 10;
//序列号的节点数
StepBits: Byte = 12;
timeShift: Byte = 22;
nodeShift: Byte = 12;
var
WorkerNodeMax: int64;
nodeMask:int64;
stepMask:int64;
procedure InitNodeInfo;
begin
WorkerNodeMax := -1 xor (-1 shl WorkerNodeBits);
nodeMask := WorkerNodeMax shl StepBits;
stepMask := -1 xor (-1 shl StepBits);
end;
{ TDxSnowflake }
constructor TDxSnowflake.Create(StartTime: TDateTime);
begin
FLocker := TCriticalSection.Create;
if StartTime >= Now then
FStartEpoch := DateTimeToUnix(IncMinute(Now,-2))
else if YearOf(StartTime) < 1984 then
FStartEpoch := Epoch
else FStartEpoch := DateTimeToUnix(StartTime);
FStartEpoch := FStartEpoch * 1000;//ms
end;
destructor TDxSnowflake.Destroy;
begin
FLocker.Free;
inherited;
end;
function TDxSnowflake.Generate: Int64;
var
curtime: Int64;
begin
FLocker.Acquire;
try
curtime := DateTimeToUnix(Now) * 1000;
if curtime = fTime then
begin
fstep := (fstep + 1) and stepMask;
if fstep = 0 then
begin
while curtime <= fTime do
curtime := DateTimeToUnix(Now) * 1000;
end;
end
else fstep := 0;
fTime := curtime;
Result := (curtime - FStartEpoch) shl timeShift or FWorkerID shl nodeShift or fstep;
finally
FLocker.Release;
end;
end;
initialization
InitNodeInfo;
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit uRtfdDiagram;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, contnrs, Math, Types,
Controls, Graphics, LCLIntf, LCLType, IniFiles, Dialogs,
uViewIntegrator, essConnectPanel, uModelEntity, uModel, uListeners, EssLayout,
uDiagramFrame, uRtfdComponents, uIterators, uFeedback, uError, uConfig,
uPathLayout, uLayoutConcepts;
type
TRtfdDiagram = class(TDiagramIntegrator,
IBeforeObjectModelListener, IAfterObjectModelListener,
IAfterUnitPackageListener)
private
Panel: TessConnectPanel;
Frame: TDiagramFrame;
//Map Entity.fullName -> TRtfdCustomPanel
BoxNames: TStringList;
FHasHidden : boolean;
FHasChanged : boolean;
IsAllClasses : boolean;
ZoomFocusW,ZoomFocusH : integer;
procedure ClearDiagram;
procedure AddBox(E: TModelEntity);
function GetBox(const S : string) : TRtfdBox;
procedure ResolveAssociations;
//Model listeners
procedure ModelBeforeChange(Sender: TModelEntity);
procedure ModelAfterChange(Sender: TModelEntity);
procedure IBeforeObjectModelListener.Change = ModelBeforeChange;
procedure IAfterObjectModelListener.Change = ModelAfterChange;
//Unitpackage listeners
procedure UnitPackageAfterChange(Sender: TModelEntity);
procedure UnitPackageAfterAddChild(Sender: TModelEntity; NewChild: TModelEntity);
procedure UnitPackageAfterRemove(Sender: TModelEntity);
procedure UnitPackageAfterEntityChange(Sender: TModelEntity);
procedure IAfterUnitPackageListener.Change = UnitPackageAfterChange;
procedure IAfterUnitPackageListener.AddChild = UnitPackageAfterAddChild;
procedure IAfterUnitPackageListener.Remove = UnitPackageAfterRemove;
procedure IAfterUnitPackageListener.EntityChange = UnitPackageAfterEntityChange;
procedure OnNeedZoomUpdate(Sender : TObject);
protected
procedure StoreDiagram; override;
function FetchDiagram : integer; override;
function HasChanged : boolean;
procedure SetVisibilityFilter(const Value: TVisibility); override;
procedure CurrentEntityChanged; override;
procedure SetShowAssoc(const Value: boolean); override;
procedure SetPathStyle(const Value: TPathLayoutStyle); override;
public
constructor Create(om: TObjectModel; AParent: TWinControl; AFeedback : IEldeanFeedback = nil); override;
destructor Destroy; override;
procedure InitFromModel; override;
procedure PaintTo(Canvas: TCanvas; X, Y: integer; SelectedOnly : boolean); override;
procedure GetDiagramSize(var W,H : integer); override;
procedure SetPackage(const Value: TAbstractPackage); override;
procedure DoLayout; override;
function GetClickAreas : TStringList; override;
procedure OpenSelectedPackage;
procedure DrawZoom(Canvas : TCanvas; W,H : integer); override;
procedure SetZoomedScroll(ScrollX,ScrollY,W,H : integer); override;
procedure HideSelectedDiagramElements; override;
function HasHiddenElements : boolean; override;
procedure UnHideAllElements; override;
function GetSelectedRect : TRect; override;
procedure ScreenCenterEntity(E : TModelEntity); override;
end;
implementation
uses
uRtfdDiagramFrame;
constructor TRtfdDiagram.Create(om: TObjectModel; AParent: TWinControl; AFeedback : IEldeanFeedback = nil);
begin
inherited Create(Om, AParent, AFeedback);
Frame := TRtfdDiagramFrame.Create(AParent, Self);
Frame.Parent := AParent;
Panel := TessConnectPanel.Create(AParent);
if not Config.IsLimitedColors then
Panel.BackBitmap := TRtfdDiagramFrame(Frame).DiaBackImage.Picture.Bitmap;
Panel.Parent := Frame.ScrollBox;
//Both these events triggers refresh of zoomimage
Panel.OnContentChanged := @OnNeedZoomUpdate;
Frame.ScrollBox.OnResize := @OnNeedZoomUpdate;
BoxNames := TStringList.Create;
BoxNames.CaseSensitive := True;
BoxNames.Sorted := True;
BoxNames.Duplicates := dupIgnore;
Model.AddListener(IBeforeObjectModelListener(Self));
ClearDiagram;
end;
destructor TRtfdDiagram.Destroy;
begin
//Force listeners to release, and diagram to persist.
Panel.Hide;
Package := nil;
ClearDiagram;
Model.RemoveListener(IBeforeObjectModelListener(Self));
FreeAndNil(BoxNames);
inherited;
end;
procedure TRtfdDiagram.InitFromModel;
var
Mi : IModelIterator;
FetchCount : integer;
procedure InAddUnit(Up: TUnitPackage);
var
Mi : IModelIterator;
begin
Mi := Up.GetClassifiers;
while Mi.HasNext do
AddBox( Mi.Next );
end;
begin
IsAllClasses := Package=AllClassesPackage;
Panel.Hide;
if not Assigned(FPackage) then
begin
Package := Model.ModelRoot;
//If there is only one package (except unknown) then show it.
//Assign with Package-property to trigger listeners
Mi := (FPackage as TLogicPackage).GetPackages;
if Mi.Count=2 then
begin
Mi.Next;
Package := Mi.Next as TAbstractPackage;
end;
end;
//Clean old
ClearDiagram;
//Create boxes
if FPackage is TUnitPackage then
begin
InAddUnit(FPackage as TUnitPackage);
{ FPCTODO This should draw the unit name on the diagram.
As coded this causes a memory leak. It does not show anyway
in current implinentation. It should not leak by design as it
is a control which is added to the panel, and ClearDiagram
has a call to DestroyComponents on the panel, but it does.
Perhaps it would be better to code this is as a descendant of Box
with paint override so it is added to the managed components and
can also be repositioned via the box dragging mechanism.
}
// TRtfdUnitPackageDiagram.Create(Panel, FPackage, 50);
end
else
begin
//Logic package
//Exclude unknown-package, otherwise all temp-classes will be included on showallclasses.
//Also, unkown-package will be shown on package-overview (including docgen)
if IsAllClasses then
begin
//These lines show all members of a package on one diagram
Mi := TModelIterator.Create( (Model.ModelRoot as TLogicPackage).GetPackages, TEntitySkipFilter.Create(Model.UnknownPackage) );
while Mi.HasNext do
InAddUnit( Mi.Next as TUnitPackage )
end
else
begin
Mi := TModelIterator.Create( (FPackage as TLogicPackage).GetPackages, TEntitySkipFilter.Create(Model.UnknownPackage) );
while Mi.HasNext do
AddBox( Mi.Next );
end;
end;
//Fetch layout for this diagram
FetchCount := FetchDiagram;
//Create arrow between boxes
//This must be done after fetchdiagram because Connection-setting might be stored
ResolveAssociations;
//Make auto-layout
if FetchCount=0 then
DoLayout
else if FetchCount<BoxNames.Count-2 then
//if MessageDlg('Model has changed since diagram was saved.'#13'Re-layout?',mtConfirmation,mbOKCancel,0) = mrOk then
DoLayout
else
begin
with GetStorage(False) do
begin
Feedback.Message('Diagram layout and settings was read from file: ' + FileName);
Free;
end;
end;
Panel.RecalcSize;
Panel.IsModified := False;
DoOnUpdateToolbar;
DoOnUpdateZoom;
Panel.Show;
Panel.SetFocus;
FHasChanged := False;
end;
procedure TRtfdDiagram.ModelBeforeChange(Sender: TModelEntity);
begin
ErrorHandler.Trace(Format('%s : %s', ['ModelBeforeChange', ClassName]));
Package := nil;
IsAllClasses := False;
ClearDiagram;
end;
procedure TRtfdDiagram.ModelAfterChange(Sender: TModelEntity);
begin
ErrorHandler.Trace(Format('%s : %s', ['ModelAfterChange', ClassName]));
InitFromModel;
end;
procedure TRtfdDiagram.PaintTo(Canvas: TCanvas; X, Y: integer; SelectedOnly : boolean);
var
OldBit : Graphics.TBitmap;
begin
OldBit := Panel.BackBitmap;
Panel.BackBitmap := nil;
if SelectedOnly then
begin
if (Panel.GetFirstSelected<>nil) then
Panel.SelectedOnly := True;
end
else
//Selection-markers should not be visible in the saved picture
Panel.ClearSelection;
Panel.PaintTo(Canvas.Handle, X, Y);
Panel.SelectedOnly := False;
Panel.BackBitmap := OldBit;
end;
procedure TRtfdDiagram.ClearDiagram;
begin
if not (csDestroying in Panel.ComponentState) then
begin
Panel.ClearManagedObjects;
Panel.DestroyComponents;
end;
BoxNames.Clear;
FHasHidden := False;
FHasChanged := False;
end;
procedure TRtfdDiagram.AddBox(E: TModelEntity);
var
Mi : IModelIterator;
Int : TInterface;
C : TClass;
A : TAttribute;
function InCreateBox(E: TModelEntity; BoxT: TRtfdBoxClass): TRtfdBox;
begin
Result := BoxT.Create(Panel, E, Frame, VisibilityFilter);
BoxNames.AddObject(E.FullName, Result);
end;
begin
if E is TUnitPackage then
Panel.AddManagedObject( InCreateBox(E,TRtfdUnitPackage) )
else if E is TClass then
//Class
begin
//Insert related boxes from other packages
//This should not be done if IsAllClasses, because then all boxes are inserted anyway
if not IsAllClasses then
begin
//Ancestor that is in another package and that is not already inserted
//is added to the diagram.
C := (E as TClass);
if Assigned(C.Ancestor) and
(C.Ancestor.Owner<>E.Owner) and
( GetBox(C.Ancestor.FullName)=nil ) then
Panel.AddManagedObject( InCreateBox(C.Ancestor,TRtfdClass) );
//Implementing interface that is in another package and is not already inserted
//is added to the diagram.
Mi := C.GetImplements;
while Mi.HasNext do
begin
Int := Mi.Next as TInterface;
if (Int.Owner<>E.Owner) and
( GetBox( Int.FullName )=nil ) then
Panel.AddManagedObject( InCreateBox(Int,TRtfdInterface) );
end;
//Attribute associations that are in other packages are added
if ShowAssoc then
begin
Mi := C.GetAttributes;
while Mi.HasNext do
begin
A := TAttribute(Mi.Next);
if Assigned(A.TypeClassifier) and (GetBox(A.TypeClassifier.FullName)=nil) and
(A.TypeClassifier<>C) and (A.TypeClassifier<>C.Ancestor) and
(A.TypeClassifier.Owner<>Model.UnknownPackage) then //Avoid getting temp-types from unknown (java 'int' for example)
begin
if A.TypeClassifier is TClass then
Panel.AddManagedObject( InCreateBox(A.TypeClassifier,TRtfdClass) );
if A.TypeClassifier is TInterface then
Panel.AddManagedObject( InCreateBox(A.TypeClassifier,TRtfdInterface) );
if A.TypeClassifier is TEnumeration then
Panel.AddManagedObject( InCreateBox(A.TypeClassifier,TRtfdEnumeration) );
end;
end;
end;
end;
if GetBox(E.FullName)=nil then
Panel.AddManagedObject( InCreateBox(E,TRtfdClass) );
end
else if E is TInterface then
//Interface
begin
//Ancestor that is in another package and that is not already inserted
//is added to the diagram.
if (not IsAllClasses) and
Assigned((E as TInterface).Ancestor) and
(TInterface(E).Ancestor.Owner<>E.Owner) and
( GetBox(TInterface(E).Ancestor.FullName)=nil ) then
Panel.AddManagedObject( InCreateBox((E as TInterface).Ancestor,TRtfdInterface) );
if GetBox(E.FullName)=nil then
Panel.AddManagedObject( InCreateBox(E,TRtfdInterface) );
end
else if E is TEnumeration then
begin
if GetBox(E.FullName)=nil then
Panel.AddManagedObject( InCreateBox(E,TRtfdEnumeration) );
end;
end;
procedure TRtfdDiagram.ResolveAssociations;
var
I : integer;
CBox: TRtfdClass;
IBox : TRtfdInterface;
A : TAttribute;
UBox : TRtfdUnitPackage;
U : TUnitPackage;
Dep : TUnitDependency;
Mi : IModelIterator;
DestBox: TRtfdBox;
begin
for I := 0 to BoxNames.Count - 1 do
if (BoxNames.Objects[I] is TRtfdClass) then
begin //Class
CBox := (BoxNames.Objects[I] as TRtfdClass);
//Ancestor
if Assigned((CBox.Entity as TClass).Ancestor) then
begin
DestBox := GetBox( (CBox.Entity as TClass).Ancestor.FullName );
if Assigned(DestBox) then
Panel.ConnectObjects(CBox,DestBox);
end;
//Implements
Mi := (CBox.Entity as TClass).GetImplements;
while Mi.HasNext do
begin
DestBox := GetBox( Mi.Next.FullName );
if Assigned(DestBox) then
Panel.ConnectObjects(CBox,DestBox,csThinDash);
end;
//Attributes associations
if ShowAssoc then
begin
Mi := (CBox.Entity as TClass).GetAttributes;
while Mi.HasNext do
begin
A := TAttribute(Mi.Next);
//Avoid arrows that points to themselves, also associations to ancestor (double arrows)
if Assigned(A.TypeClassifier) and
(A.TypeClassifier<>CBox.Entity) and
(A.TypeClassifier<>(CBox.Entity as TClass).Ancestor) then
begin
DestBox := GetBox( A.TypeClassifier.FullName );
//Test for same entity, this will filter out TDatatype that can have same name as a class
if Assigned(DestBox) and (DestBox.Entity=A.TypeClassifier) then
Panel.ConnectObjects(CBox,DestBox,csThin,asEmptyOpen);
end;
end;
end;
end else if (BoxNames.Objects[I] is TRtfdInterface) then
begin //Interface
IBox := (BoxNames.Objects[I] as TRtfdInterface);
//Ancestor
if Assigned((IBox.Entity as TInterface).Ancestor) then
begin
DestBox := GetBox( (IBox.Entity as TInterface).Ancestor.FullName );
if Assigned(DestBox) then
Panel.ConnectObjects(IBox,DestBox);
end;
end else if (BoxNames.Objects[I] is TRtfdUnitPackage) then
begin //Unit
UBox := (BoxNames.Objects[I] as TRtfdUnitPackage);
U := UBox.Entity as TUnitPackage;
Mi := U.GetUnitDependencies;
while Mi.HasNext do
begin
Dep := Mi.Next as TUnitDependency;
if Dep.Visibility=viPublic then
begin
DestBox := GetBox( Dep.Package.FullName );
if Assigned(DestBox) then
Panel.ConnectObjects(UBox,DestBox,csThinDash,asEmptyOpen);
end;
end;
end;
end;
procedure TRtfdDiagram.SetPackage(const Value: TAbstractPackage);
begin
if Assigned(FPackage) and HasChanged then
StoreDiagram;
if Assigned(FPackage) and (FPackage is TUnitPackage) then
FPackage.RemoveListener(IAfterUnitPackageListener(Self));
inherited SetPackage(Value);
if Assigned(FPackage) and (FPackage is TUnitPackage) then
FPackage.AddListener(IAfterUnitPackageListener(Self));
if Assigned(Frame.ScrollBox) and (not Config.IsTerminating) then
begin
Frame.ScrollBox.HorzScrollBar.Position := 0;
Frame.ScrollBox.VertScrollBar.Position := 0;
end;
end;
procedure TRtfdDiagram.UnitPackageAfterAddChild(Sender: TModelEntity;
NewChild: TModelEntity);
begin
ErrorHandler.Trace(Format('%s : %s : %s', ['UnitPackageAfterAddChild', ClassName, Sender.Name]));
if (NewChild is TClass) or (NewChild is TInterface) then
begin
AddBox(NewChild);
ResolveAssociations;
end;
end;
procedure TRtfdDiagram.UnitPackageAfterChange(Sender: TModelEntity);
begin
ErrorHandler.Trace(Format('%s : %s : %s', ['UnitPackageAfterChange', ClassName, Sender.Name]));
end;
procedure TRtfdDiagram.UnitPackageAfterEntityChange(Sender: TModelEntity);
begin
ErrorHandler.Trace(Format('%s : %s : %s', ['UnitPackageAfterEntityChange', ClassName, Sender.Name]));
end;
procedure TRtfdDiagram.UnitPackageAfterRemove(Sender: TModelEntity);
begin
ErrorHandler.Trace(Format('%s : %s : %s', ['UnitPackageAfterRemove', ClassName, Sender.Name]));
end;
procedure TRtfdDiagram.OpenSelectedPackage;
var
C: TControl;
begin
//Anropas av frame action
C := Panel.GetFirstSelected;
if Assigned(C) and (C is TRtfdUnitPackage) then
begin
Package := (C as TRtfdUnitPackage).P;
InitFromModel;
CurrentEntity := Package;
end;
end;
function TRtfdDiagram.HasChanged: boolean;
begin
Result := FHasChanged or Panel.IsModified;
end;
procedure TRtfdDiagram.StoreDiagram;
var
Ini : TCustomIniFile;
I : integer;
Box : TRtfdBox;
S : string;
DoSave : boolean;
begin
DoSave:=False;
case Config.DiSave of
dsAsk : DoSave := MessageDlg('Save changed layout?',mtConfirmation, [mbYes,mbNo] , 0)=mrYes;
dsNever : ;
dsAlways : DoSave := True;
end;
if DoSave then
begin
Ini := GetStorage(True);
if Assigned(Ini) then
try
//Boxes
for I := 0 to BoxNames.Count - 1 do
begin
Box := BoxNames.Objects[I] as TRtfdBox;
S := 'Box: ' + Package.FullName + ' - ' + Box.Entity.FullName;
Ini.EraseSection(S);
Ini.WriteInteger(S,'X', Box.Left);
Ini.WriteInteger(S,'Y', Box.Top);
if not Box.Visible then
Ini.WriteBool(S,'Visible', Box.Visible);
//Ini.WriteInteger(S,'W', Box.Width);
//Ini.WriteInteger(S,'H', Box.Height);
end;
//Diagram stuff
S := 'Diagram: ' + Package.FullName;
Ini.EraseSection(S);
Ini.WriteInteger(S,'OffsetX',Frame.ScrollBox.VertScrollBar.Position);
Ini.WriteInteger(S,'OffsetY',Frame.ScrollBox.HorzScrollBar.Position);
Ini.WriteInteger(S,'Visibility', Integer(VisibilityFilter) );
Ini.WriteBool(S,'ShowAssoc', ShowAssoc);
Ini.WriteInteger(S,'PathStyle', Integer(PathStyle));
//Commit
try
try
Ini.UpdateFile;
except
ErrorHandler.Trace('Could not write layout to disk');
end;
finally
end;
finally
Ini.Free;
end;
end;
end;
function TRtfdDiagram.FetchDiagram : integer;
var
Ini : TCustomIniFile;
I,NextX,NextY : integer;
Box : TRtfdBox;
S : string;
begin
Result := 0;
NextX := 50;
NextY := 50;
Ini := GetStorage(False);
if Assigned(Ini) then
try
//Boxar
for I := 0 to BoxNames.Count - 1 do
begin
Box := BoxNames.Objects[I] as TRtfdBox;
S := 'Box: ' + Package.FullName + ' - ' + Box.Entity.FullName;
if Ini.SectionExists(S) then
begin
Inc(Result);
Box.Left := Ini.ReadInteger(S,'X',Box.Left);
Box.Top := Ini.ReadInteger(S,'Y',Box.Top);
Box.Visible := Ini.ReadBool(S,'Visible', True);
if (not Box.Visible) and (not FHasHidden) then
FHasHidden := True;
end
else
begin
//Boxes not in file will get a default postion in upper left corner
Box.BoundsRect := Rect(NextX, NextY, NextX + Box.Width, NextY + Box.Height);
Inc(NextX,25);
Inc(NextY,25);
end;
end;
//Diagram stuff
S := 'Diagram: ' + Package.FullName;
if Ini.SectionExists(S) then
begin
Frame.ScrollBox.VertScrollBar.Position := Ini.ReadInteger(S,'OffsetX',Frame.ScrollBox.VertScrollBar.Position);
Frame.ScrollBox.HorzScrollBar.Position := Ini.ReadInteger(S,'OffsetY',Frame.ScrollBox.HorzScrollBar.Position);;
VisibilityFilter := TVisibility(Ini.ReadInteger(S,'Visibility', Integer( Low(TVisibility) ) ));
ShowAssoc := Ini.ReadBool(S,'ShowAssoc', ShowAssoc);
PathStyle := TPathLayoutStyle(Ini.ReadInteger(S,'PathStyle', Integer( Low(TPathLayoutStyle) ) ));;
end;
finally
Ini.Free;
end;
end;
procedure TRtfdDiagram.DoLayout;
var
Layout : TEssLayout;
begin
if BoxNames.Count>0 then
begin
Panel.Hide;
Layout := TEssLayout.CreateLayout( Panel );
try
Layout.Execute;
finally
Panel.Show;
Layout.Free
end;
Panel.IsModified := True;
Panel.RecalcSize;
Panel.Refresh;
end;
end;
function TRtfdDiagram.GetBox(const S: string): TRtfdBox;
var
I : integer;
begin
I := BoxNames.IndexOf( S );
if I=-1 then
Result := nil
else
Result := BoxNames.Objects[I] as TRtfdBox;
end;
procedure TRtfdDiagram.SetVisibilityFilter(const Value: TVisibility);
var
I : integer;
begin
if Value<>VisibilityFilter then
begin
Panel.Hide;
for I := 0 to BoxNames.Count - 1 do
(BoxNames.Objects[I] as TRtfdBox).MinVisibility := Value;
Panel.RecalcSize;
Panel.Show;
FHasChanged := True;
inherited;
end;
end;
procedure TRtfdDiagram.GetDiagramSize(var W, H: integer);
begin
W := Panel.Width;
H := Panel.Height;
end;
function TRtfdDiagram.GetClickAreas: TStringList;
var
I : integer;
Box : TRtfdBox;
S : string;
begin
Result := TStringList.Create;
for I := 0 to BoxNames.Count-1 do
begin
Box := BoxNames.Objects[I] as TRtfdBox;
S := IntToStr(Box.Left) + ',' + IntToStr(Box.Top) + ',' +
IntToStr(Box.Left + Box.Width) + ',' + IntToStr(Box.Top + Box.Height);
Result.AddObject(S,Box.Entity);
end;
end;
procedure TRtfdDiagram.HideSelectedDiagramElements;
var
C: TControl;
L : TObjectList;
I : integer;
begin
//Called from frame action
L := Panel.GetSelectedControls;
try
if L.Count>0 then
begin
for I := 0 to L.Count-1 do
begin
C := L[I] as TControl;
if (C is TRtfdBox) and Assigned(GetBox( (C as TRtfdBox).Entity.FullName )) then
begin
C.Visible := False;
FHasHidden := True;
FHasChanged := True;
end;
end;
Panel.ClearSelection;
Panel.RecalcSize;
Panel.Refresh;
end;
finally
L.Free;
end;
end;
function TRtfdDiagram.HasHiddenElements: boolean;
begin
Result := FHasHidden;
end;
procedure TRtfdDiagram.UnHideAllElements;
var
I : integer;
Box : TRtfdBox;
begin
for I := 0 to BoxNames.Count - 1 do
begin
Box := BoxNames.Objects[I] as TRtfdBox;
if not Box.Visible then
Box.Visible := True;
end;
Panel.RecalcSize;
Panel.Refresh;
FHasHidden := False;
FHasChanged := True;
end;
procedure TRtfdDiagram.DrawZoom(Canvas: TCanvas; W,H : integer);
var
I,ZoomW,ZoomH : integer;
Box : TRtfdBox;
ScaleX,ScaleY,Scale : double;
R : TRect;
begin
if Panel.Width=0 then
Exit;
ScaleX := W / Panel.Width;
ScaleY := H / Panel.Height;
Scale := Min(ScaleX,ScaleY);
//Clear whole area
Canvas.Brush.Color := clBtnFace;
Canvas.FillRect( Rect(0,0,W,H) );
//Fill area for zoomcanvas
Canvas.Brush.Color := clWhite;
Canvas.Pen.Color := clBlack;
ZoomW := Round(Panel.Width * Scale);
ZoomH := Round(Panel.Height * Scale);
Canvas.Rectangle( Rect(0,0, ZoomW,ZoomH ) );
if not Config.IsLimitedColors then
Canvas.Brush.Color := $EAF4F8
else
Canvas.Brush.Color := clWhite;
//Draw boxes
for I := 0 to BoxNames.Count-1 do
begin
Box := TRtfdBox(BoxNames.Objects[I]);
if not Box.Visible then
Continue;
R := Box.BoundsRect;
R.Left := Round(R.Left * Scale);
R.Top := Round(R.Top * Scale);
R.Right := Round(R.Right * Scale);
R.Bottom := Round(R.Bottom * Scale);
Canvas.Rectangle(R);
end;
//Draw zoomfocus-box
ZoomFocusW := Round(Frame.ScrollBox.Width * Scale);
ZoomFocusH := Round(Frame.ScrollBox.Height * Scale);
R.Left := Round(Frame.ScrollBox.HorzScrollBar.Position * Scale);
R.Top := Round(Frame.ScrollBox.VertScrollBar.Position * Scale);
R.Right := R.Left + ZoomFocusW;
R.Bottom := R.Top + ZoomFocusH;
if not ((R.Left=0) and (R.Right>=ZoomW) and (R.Top=0) and (R.Bottom>=ZoomH)) then
begin
Canvas.Pen.Mode := pmXor;
Canvas.Rectangle(R);
Canvas.Pen.Mode := pmCopy;
end;
end;
procedure TRtfdDiagram.SetZoomedScroll(ScrollX, ScrollY, W, H: integer);
var
ScaleX,ScaleY,Scale : double;
begin
ScaleX := Panel.Width / W;
ScaleY := Panel.Height / H ;
Scale := Max(ScaleX,ScaleY);
//Modify coords to put mousearrow in center of zoomfocus-box
Dec(ScrollX,ZoomFocusW div 2);
Dec(ScrollY,ZoomFocusH div 2);
Frame.ScrollBox.HorzScrollBar.Position := Min(Frame.ScrollBox.HorzScrollBar.Range-Frame.ScrollBox.Width,Round(ScrollX * Scale));
Frame.ScrollBox.VertScrollBar.Position := Min(Frame.ScrollBox.VertScrollBar.Range-Frame.ScrollBox.Height,Round(ScrollY * Scale));
end;
procedure TRtfdDiagram.OnNeedZoomUpdate(Sender: TObject);
begin
DoOnUpdateZoom;
end;
procedure TRtfdDiagram.CurrentEntityChanged;
var
P : TModelEntity;
begin
inherited;
P := CurrentEntity;
while Assigned(P) and (not (P is TAbstractPackage)) do
P := P.Owner;
if Assigned(P) and (P<>Package) then
begin
Package := P as TAbstractPackage;
InitFromModel
end;
if (CurrentEntity is TClass) or (CurrentEntity is TInterface) then
ScreenCenterEntity(CurrentEntity);
end;
function TRtfdDiagram.GetSelectedRect: TRect;
var
C: TControl;
L : TObjectList;
I : integer;
R : TRect;
begin
L := Panel.GetSelectedControls;
if L.Count=0 then
Result := Rect(0,0,0,0)
else
begin
Result := Rect(MaxInt,MaxInt,0,0);
for I := 0 to L.Count-1 do
begin
C := TControl(L[I]);
R := C.BoundsRect;
if R.Top<Result.Top then
Result.Top := R.Top;
if R.Left<Result.Left then
Result.Left := R.Left;
if R.Bottom>Result.Bottom then
Result.Bottom := R.Bottom;
if R.Right>Result.Right then
Result.Right := R.Right;
end;
end;
L.Free;
end;
procedure TRtfdDiagram.ScreenCenterEntity(E: TModelEntity);
var
I : integer;
Box : TRtfdBox;
begin
for I := 0 to BoxNames.Count-1 do
if TRtfdBox(BoxNames.Objects[I]).Entity=E then
begin
Box := TRtfdBox(BoxNames.Objects[I]);
Frame.ScrollBox.ScrollInView(Box);
Break;
end;
end;
procedure TRtfdDiagram.SetShowAssoc(const Value: boolean);
begin
if Value<>ShowAssoc then
FHasChanged := True;
inherited;
end;
procedure TRtfdDiagram.SetPathStyle(const Value: TPathLayoutStyle);
begin
Panel.PathStyle := Value;
inherited SetPathStyle(Value);
end;
end.
|
unit UDFormulaEdit;
interface
uses
Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons;
type
TCrpeFormulaEditDlg = class(TForm)
memoFormula: TMemo;
btnOk: TButton;
btnCancel: TButton;
btnClear: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
SenderList : TStrings;
end;
var
CrpeFormulaEditDlg: TCrpeFormulaEditDlg;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpeFormulaEditDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpeFormulaEditDlg.FormShow(Sender: TObject);
begin
memoFormula.Lines.Assign(SenderList);
end;
{------------------------------------------------------------------------------}
{ btnClearClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeFormulaEditDlg.btnClearClick(Sender: TObject);
begin
memoFormula.Clear;
end;
{------------------------------------------------------------------------------}
{ btnOkClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeFormulaEditDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ btnCancelClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeFormulaEditDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpeFormulaEditDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ModalResult = mrOk then
SenderList.Assign(memoFormula.Lines);
Release;
end;
end.
|
unit GLDTorus;
interface
uses
Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDObjects;
type
TGLDTorus = class(TGLDEditableObject)
private
FRadius1: GLfloat;
FRadius2: GLfloat;
FSegments: GLushort;
FSides: GLushort;
FStartAngle1: GLfloat;
FSweepAngle1: GLfloat;
FStartAngle2: GLfloat;
FSweepAngle2: GLfloat;
FNormals: PGLDVector3fArray;
FPoints: PGLDVector3fArray;
function GetMode: GLubyte;
function GetPoint(i, j: GLushort): PGLDVector3f;
procedure SetRadius1(Value: GLfloat);
procedure SetRadius2(Value: GLfloat);
procedure SetSegments(Value: GLushort);
procedure SetSides(Value: GLushort);
procedure SetStartAngle1(Value: GLfloat);
procedure SetSweepAngle1(Value: GLfloat);
procedure SetStartAngle2(Value: GLfloat);
procedure SetSweepAngle2(Value: GLfloat);
function GetParams: TGLDTorusParams;
procedure SetParams(Value: TGLDTorusParams);
protected
procedure CalcBoundingBox; override;
procedure CreateGeometry; override;
procedure DestroyGeometry; override;
procedure DoRender; override;
procedure SimpleRender; override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function RealName: string; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function CanConvertTo(_ClassType: TClass): GLboolean; override;
function ConvertTo(Dest: TPersistent): GLboolean; override;
function ConvertToTriMesh(Dest: TPersistent): GLboolean;
function ConvertToQuadMesh(Dest: TPersistent): GLboolean;
function ConvertToPolyMesh(Dest: TPersistent): GLboolean;
property Params: TGLDTorusParams read GetParams write SetParams;
published
property Radius1: GLfloat read FRadius1 write SetRadius1;
property Radius2: GLfloat read FRadius2 write SetRadius2;
property Segments: GLushort read FSegments write SetSegments default GLD_TORUS_SEGMENTS_DEFAULT;
property Sides: GLushort read FSides write SetSides default GLD_TORUS_SIDES_DEFAULT;
property StartAngle1: GLfloat read FStartAngle1 write SetStartAngle1;
property SweepAngle1: GLfloat read FSweepAngle1 write SetSweepAngle1;
property StartAngle2: GLfloat read FStartAngle2 write SetStartAngle2;
property SweepAngle2: GLfloat read FSweepAngle2 write SetSweepAngle2;
end;
implementation
uses
SysUtils, GLDGizmos, GLDX, GLDMesh, GLDUtils;
var
vTorusCounter: GLuint = 0;
constructor TGLDTorus.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
Inc(vTorusCounter);
FName := GLD_TORUS_STR + IntToStr(vTorusCounter);
FRadius1 := GLD_STD_TORUSPARAMS.Radius1;
FRadius2 := GLD_STD_TORUSPARAMS.Radius2;
FSegments := GLD_STD_TORUSPARAMS.Segments;
FSides := GLD_STD_TORUSPARAMS.Sides;
FStartAngle1 := GLD_STD_TORUSPARAMS.StartAngle1;
FSweepAngle1 := GLD_STD_TORUSPARAMS.SweepAngle1;
FStartAngle2 := GLD_STD_TORUSPARAMS.StartAngle2;
FSweepAngle2 := GLD_STD_TORUSPARAMS.SweepAngle2;
FPosition.Vector3f := GLD_STD_TORUSPARAMS.Position;
FRotation.Params := GLD_STD_TORUSPARAMS.Rotation;
CreateGeometry;
end;
destructor TGLDTorus.Destroy;
begin
inherited Destroy;
end;
procedure TGLDTorus.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if (Source is TGLDTorus) then Exit;
inherited Assign(Source);
SetParams(TGLDTorus(Source).GetParams);
end;
procedure TGLDTorus.DoRender;
var
iSegs, iSides: GLushort;
begin
for iSegs := 1 to FSegments do
begin
glBegin(GL_QUAD_STRIP);
for iSides := 2 to FSides + 2 do
begin
glNormal3fv(@FNormals^[(iSegs + 1) * (FSides + 3) + iSides]);
glVertex3fv(@FPoints^[(iSegs + 1) * (FSides + 3) + iSides]);
glNormal3fv(@FNormals^[iSegs * (FSides + 3) + iSides]);
glVertex3fv(@FPoints^[iSegs * (FSides + 3) + iSides]);
end;
glEnd;
end;
end;
procedure TGLDTorus.SimpleRender;
var
iSegs, iSides: GLushort;
begin
for iSegs := 0 to FSegments do
begin
glBegin(GL_QUAD_STRIP);
for iSides := 2 to FSides + 2 do
begin
glVertex3fv(@FPoints^[(iSegs + 1) * (FSides + 3) + iSides]);
glVertex3fv(@FPoints^[iSegs * (FSides + 3) + iSides]);
end;
glEnd;
end;
end;
procedure TGLDTorus.CalcBoundingBox;
begin
FBoundingBox := GLDXCalcBoundingBox(FPoints, (FSegments + 3) * (FSides + 3));
end;
procedure TGLDTorus.CreateGeometry;
var
iSegs, iP: GLushort;
A1, A2: GLfloat;
begin
if FSegments < 1 then FSegments := 1 else
if FSegments > 1000 then FSegments := 1000;
if FSides < 1 then FSides := 1 else
if FSides > 1000 then FSides := 1000;
ReallocMem(FNormals, (FSegments + 3) * (FSides + 3) * SizeOf(TGLDVector3f));
ReallocMem(FPoints, (FSegments + 3) * (FSides + 3) * SizeOf(TGLDVector3f));
A1 := GLDXGetAngleStep(FStartAngle1, FSweepAngle1, FSides);
A2 := GLDXGetAngleStep(FStartAngle2, FSweepAngle2, FSegments);
for iSegs := 1 to FSegments + 3 do
begin
for iP := 1 to FSides + 3 do
begin
FPoints^[(iSegs - 1) * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(FStartAngle1 + (iP - 2) * A1) * (FRadius1 +
(GLDXCoSinus(FStartAngle2 + (iSegs - 2) * A2) * FRadius2)),
GLDXSinus(FStartAngle2 + (iSegs - 2) * A2) * FRadius2,
-(GLDXSinus(FStartAngle1 + (iP - 2) * A1) * (FRadius1 +
GLDXCoSinus(FStartAngle2 + (iSegs - 2) * A2) * FRadius2)));
end;
end;
FModifyList.ModifyPoints(
[GLDXVector3fArrayData(FPoints, (FSegments + 3) * (FSides + 3))]);
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FPoints, (FSegments + 3) * (FSides + 3)),
GLDXVector3fArrayData(FNormals, (FSegments + 3) * (FSides + 3)),
FSegments + 2, FSides + 2));
for iP := 1 to (FSegments + 3) * (FSides + 3) do
FNormals^[iP] := GLDXVectorNeg(FNormals^[iP]);
CalcBoundingBox;
end;
procedure TGLDTorus.DestroyGeometry;
begin
ReallocMem(FNormals, 0);
ReallocMem(FPoints, 0);
FNormals := nil; FPoints := nil;
end;
class function TGLDTorus.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_TORUS;
end;
class function TGLDTorus.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDTorus;
end;
class function TGLDTorus.RealName: string;
begin
Result := GLD_TORUS_STR;
end;
procedure TGLDTorus.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
Stream.Read(FRadius1, SizeOf(GLfloat));
Stream.Read(FRadius2, SizeOf(GLfloat));
Stream.Read(FSegments, SizeOf(GLushort));
Stream.Read(FSides, SizeOf(GLushort));
Stream.Read(FStartAngle1, SizeOf(GLfloat));
Stream.Read(FSweepAngle1, SizeOf(GLfloat));
Stream.Read(FStartAngle2, SizeOf(GLfloat));
Stream.Read(FSweepAngle2, SizeOf(GLfloat));
CreateGeometry;
end;
procedure TGLDTorus.SaveToStream(Stream: TStream);
begin
inherited SaveToStream(Stream);
Stream.Write(FRadius1, SizeOf(GLfloat));
Stream.Write(FRadius2, SizeOf(GLfloat));
Stream.Write(FSegments, SizeOf(GLushort));
Stream.Write(FSides, SizeOf(GLushort));
Stream.Write(FStartAngle1, SizeOf(GLfloat));
Stream.Write(FSweepAngle1, SizeOf(GLfloat));
Stream.Write(FStartAngle2, SizeOf(GLfloat));
Stream.Write(FSweepAngle2, SizeOf(GLfloat));
end;
function TGLDTorus.CanConvertTo(_ClassType: TClass): GLboolean;
begin
Result := (_ClassType = TGLDTorus) or
(_ClassType = TGLDTriMesh) or
(_ClassType = TGLDQuadMesh) or
(_ClassType = TGLDPolyMesh);
end;
function TGLDTorus.ConvertTo(Dest: TPersistent): GLboolean;
begin
Result := False;
if not Assigned(Dest) then Exit;
if Dest.ClassType = Self.ClassType then
begin
Dest.Assign(Self);
Result := True;
end else
if Dest is TGLDTriMesh then
Result := ConvertToTriMesh(Dest) else
if Dest is TGLDQuadMesh then
Result := ConvertToQuadMesh(Dest) else
if Dest is TGLDPolyMesh then
Result := ConvertToPolyMesh(Dest);
end;
{$WARNINGS OFF}
function TGLDTorus.ConvertToTriMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
i, j: GLushort;
F: TGLDTriFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDTriMesh) then Exit;
M := GetMode;
with TGLDTriMesh(Dest) do
begin
DeleteVertices;
F.Smoothing := GLD_SMOOTH_ALL;
if M = 0 then
begin
VertexCapacity := FSegments * FSides;
for i := 1 to FSegments do
for j := 1 to FSides do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * FSides + j;
if i = FSegments then
F.Point3 := j
else F.Point3 := i * FSides + j;
if j = FSides then
F.Point2 := (i - 1) * FSides + 1
else F.Point2 := (i - 1) * FSides + j + 1;
AddFace(F);
F.Point1 := (i - 1) * FSides + 1;
if j <> FSides then Inc(F.Point1, j);
if i = FSegments then
F.Point3 := j
else F.Point3 := i * FSides + j;
if i = FSegments then
F.Point2 := 1
else F.Point2 := i * FSides + 1;
if j <> FSides then Inc(F.Point2, j);
AddFace(F);
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := (FSegments + 1) * FSides;
for i := 1 to FSegments + 1 do
for j := 1 to FSides do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point3 := (i - 1) * FSides + j;
F.Point2 := i * FSides + j;
if j = FSides then
F.Point1 := (i - 1) * FSides + 1
else F.Point1 := (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := i * FSides + j;
if j = FSides then
begin
F.Point3 := (i - 1) * FSides + 1;
F.Point1 := i * FSides + 1;
end else
begin
F.Point3 := (i - 1) * FSides + j + 1;
F.Point1 := i * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := FSegments * (FSides + 1);
for i := 1 to FSegments do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point3 := (i - 1) * (FSides + 1) + j;
if i = FSegments then
F.Point2 := j
else F.Point2 := i * (FSides + 1) + j;
F.Point1 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := (i - 1) * (FSides + 1) + j + 1;
if i = FSegments then
begin
F.Point3 := j;
F.Point2 := j + 1;
end else
begin
F.Point3 := i * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j + 1;
end;
AddFace(F);
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := (FSegments + 1) * (FSides + 1);
for i := 1 to FSegments + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * (FSides + 1) + j;
F.Point3 := i * (FSides + 1) + j;
F.Point2 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := (i - 1) * (FSides + 1) + j + 1;
F.Point3 := i * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j + 1;
AddFace(F);
end;
end; // M = 3
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDTriMesh(Dest).Selected := Self.Selected;
TGLDTriMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
function TGLDTorus.ConvertToQuadMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
i, j: GLushort;
F: TGLDQuadFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDQuadMesh) then Exit;
M := GetMode;
with TGLDQuadMesh(Dest) do
begin
DeleteVertices;
F.Smoothing := GLD_SMOOTH_ALL;
if M = 0 then
begin
VertexCapacity := FSegments * FSides;
for i := 1 to FSegments do
for j := 1 to FSides do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * FSides + j;
if i = FSegments then
F.Point4 := j
else F.Point4 := i * FSides + j;
if j = FSides then
F.Point2 := (i - 1) * FSides + 1
else F.Point2 := (i - 1) * FSides + j + 1;
if i = FSegments then
F.Point3 := 1
else F.Point3 := i * FSides + 1;
if j <> FSides then Inc(F.Point3, j);
AddFace(F);
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := (FSegments + 1) * FSides;
for i := 1 to FSegments + 1 do
for j := 1 to FSides do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point2 := (i - 1) * FSides + j;
F.Point1 := i * FSides + j;
if j = FSides then
begin
F.Point4 := i * FSides + 1;
F.Point3 := (i - 1) * FSides + 1;
end else
begin
F.Point4 := i * FSides + j + 1;
F.Point3 := (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := FSegments * (FSides + 1);
for i := 1 to FSegments do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point4 := (i - 1) * (FSides + 1) + j;
F.Point1 := (i - 1) * (FSides + 1) + j + 1;
if i = FSegments then
begin
F.Point3 := j;
F.Point2 := j + 1;
end else
begin
F.Point3 := i * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j + 1;
end;
AddFace(F);
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := (FSegments + 1) * (FSides + 1);
for i := 1 to FSegments + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := i * (FSides + 1) + j + 1;
F.Point4 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
end; // M = 3
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDQuadMesh(Dest).Selected := Self.Selected;
TGLDQuadMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
function TGLDTorus.ConvertToPolyMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
i, j: GLushort;
P: TGLDPolygon;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDPolyMesh) then Exit;
M := GetMode;
with TGLDPolyMesh(Dest) do
begin
DeleteVertices;
//F.Smoothing := GLD_SMOOTH_ALL;
if M = 0 then
begin
VertexCapacity := FSegments * FSides;
for i := 1 to FSegments do
for j := 1 to FSides do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := (i - 1) * FSides + j;
if i = FSegments then
P.Data^[4] := j
else P.Data^[4] := i * FSides + j;
if j = FSides then
P.Data^[2] := (i - 1) * FSides + 1
else P.Data^[2] := (i - 1) * FSides + j + 1;
if i = FSegments then
P.Data^[3] := 1
else P.Data^[3] := i * FSides + 1;
if j <> FSides then Inc(P.Data^[3], j);
AddFace(P);
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := (FSegments + 1) * FSides;
for i := 1 to FSegments + 1 do
for j := 1 to FSides do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[2] := (i - 1) * FSides + j;
P.Data^[1] := i * FSides + j;
if j = FSides then
begin
P.Data^[4] := i * FSides + 1;
P.Data^[3] := (i - 1) * FSides + 1;
end else
begin
P.Data^[4] := i * FSides + j + 1;
P.Data^[3] := (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := FSegments * (FSides + 1);
for i := 1 to FSegments do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[4] := (i - 1) * (FSides + 1) + j;
P.Data^[1] := (i - 1) * (FSides + 1) + j + 1;
if i = FSegments then
begin
P.Data^[3] := j;
P.Data^[2] := j + 1;
end else
begin
P.Data^[3] := i * (FSides + 1) + j;
P.Data^[2] := i * (FSides + 1) + j + 1;
end;
AddFace(P);
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := (FSegments + 1) * (FSides + 1);
for i := 1 to FSegments + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := (i - 1) * (FSides + 1) + j;
P.Data^[2] := i * (FSides + 1) + j;
P.Data^[3] := i * (FSides + 1) + j + 1;
P.Data^[4] := (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
end; // M = 3
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDPolyMesh(Dest).Selected := Self.Selected;
TGLDPolyMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
{$WARNINGS ON}
function TGLDTorus.GetMode: GLubyte;
var
A1, A2: GLfloat;
begin
A1 := GLDXGetAngle(FStartAngle1, FSweepAngle1);
A2 := GLDXGetAngle(FStartAngle2, FSweepAngle2);
if A1 = 360 then
begin
if A2 = 360 then Result := 0
else Result := 1;
end else
begin
if A2 = 360 then Result := 2
else Result := 3;
end;
end;
function TGLDTorus.GetPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FPoints^[i * (FSides + 3) + j + 1];
end;
procedure TGLDTorus.SetRadius1(Value: GLfloat);
begin
if FRadius1 = Value then Exit;
FRadius1 := Value;
CreateGeometry;
Change;
end;
procedure TGLDTorus.SetRadius2(Value: GLfloat);
begin
if FRadius2 = Value then Exit;
FRadius2 := Value;
CreateGeometry;
Change;
end;
procedure TGLDTorus.SetSegments(Value: GLushort);
begin
if FSegments = Value then Exit;
FSegments := Value;
CreateGeometry;
Change;
end;
procedure TGLDTorus.SetSides(Value: GLushort);
begin
if FSides = Value then Exit;
FSides := Value;
CreateGeometry;
Change;
end;
procedure TGLDTorus.SetStartAngle1(Value: GLfloat);
begin
if FStartAngle1 = Value then Exit;
FStartAngle1 := Value;
CreateGeometry;
Change;
end;
procedure TGLDTorus.SetSweepAngle1(Value: GLfloat);
begin
if FSweepAngle1 = Value then Exit;
FSweepAngle1 := Value;
CreateGeometry;
Change;
end;
procedure TGLDTorus.SetStartAngle2(Value: GLfloat);
begin
if FStartAngle2 = Value then Exit;
FStartAngle2 := Value;
CreateGeometry;
Change;
end;
procedure TGLDTorus.SetSweepAngle2(Value: GLfloat);
begin
if FSweepAngle2 = Value then Exit;
FSweepAngle2 := Value;
CreateGeometry;
Change;
end;
function TGLDTorus.GetParams: TGLDTorusParams;
begin
Result := GLDXTorusParams(FColor.Color3ub, FRadius1, FRadius2,
FSegments, FSides, FStartAngle1, FSweepAngle1, FStartAngle1, FSweepAngle2,
FPosition.Vector3f, FRotation.Params);
end;
procedure TGLDTorus.SetParams(Value: TGLDTorusParams);
begin
if GLDXTorusParamsEqual(GetParams, Value) then Exit;
PGLDColor3f(FColor.GetPointer)^ := GLDXColor3f(Value.Color);
FRadius1 := Value.Radius1;
FRadius2 := Value.Radius2;
FSegments := Value.Segments;
FSides := Value.Sides;
FStartAngle1 := Value.StartAngle1;
FSweepAngle1 := Value.SweepAngle1;
FStartAngle2 := Value.StartAngle2;
FSweepAngle2 := Value.SweepAngle2;
PGLDVector3f(FPosition.GetPointer)^ := Value.Position;
PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation;
CreateGeometry;
Change;
end;
end.
|
unit TestUMain;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, System.SysUtils, Vcl.Graphics, Winapi.Windows, System.Variants,
Vcl.Dialogs, Vcl.Controls, Vcl.Forms, Winapi.Messages, System.Classes,
umain;
type
// Test methods for class TForm2
TestTForm2 = class(TTestCase)
strict private
fform2 : Tform2;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestaIva();
end;
implementation
procedure TestTForm2.SetUp;
begin
FForm2 := TForm2.Create(nil);
end;
procedure TestTForm2.TearDown;
begin
FForm2.Free;
FForm2 := nil;
end;
procedure TestTForm2.TestaIva();
var
AValorMerc: double;
APercentualIva: double;
AValorIva: double;
begin
AValorMerc := 1000;
APercentualIva := 11;
AValorIva := round(AValorMerc / APercentualIva);
Check(AValorIva <> 91, 'O valor do iva esta incorreto');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTForm2.Suite);
end.
|
{*------------------------------------------------------------------------------
GestionDesErreurs
Gestion Des Erreurs du moteur de Sarrah
@Author CIRAD
@Version v_3.0
-------------------------------------------------------------------------------}
unit GestionDesErreurs;
interface
uses Dialogs,Main;
type
/// Enumération des unités du moteur
TUnite = (UModelsManage, UClasseSimule, UClasseScenario,
UGestionDesTables, UBilEau, UPalmier, UMilBilanCarbone, UBhyTypeFAO,
UBiomasse, UMeteo, UEcopalm2, UMathStats, UMain, ULectDonnee, UEcopalm2_2,
URiz, {VN contraintes} UContrainte, USorghum, UPhenologie,
UBilanCarbonSarra, UUImportExport,
UDataModuleRecherche, UDeriveClimato, URisocas);
{*--------------------------------------------------------------------------
Procédure permettant d'afficher un message d'erreur ainsi que l'unité dans
laquelle l'erreur s'est produite.
@Author CIRAD
@Version v_3.0
@param LeMessage Le message a afficher
@param LUnite L'unité d'où provient l'erreur
---------------------------------------------------------------------------}
procedure AfficheMessageErreur(LeMessage: string; LUnite: TUnite);
implementation
{uses Main;}
var
ErreurAffichee: Boolean; /// Vrai si une erreur a été affichée
{--------------------------------------------------------------------------
Procédure permettant d'afficher un message d'erreur ainsi que l'unité dans
laquelle l'erreur s'est produite.
@Author CIRAD
@Version v_3.0
@param LeMessage Le message a afficher
@param LUnite L'unité d'où provient l'erreur
---------------------------------------------------------------------------}
procedure AfficheMessageErreur(LeMessage: string; LUnite: TUnite);
var
NomUnite: string; /// Nom de l'unité
begin
try
//main.erreur := true;
if not ErreurAffichee then
begin
case LUnite of
UModelsManage: NomUnite := 'ModelsManage.pas';
UClasseSimule: NomUnite := 'ClasseSimule.pas';
UClasseScenario: NomUnite := 'ClasseScenario.pas';
UGestionDesTables: NomUnite := 'GestionDesTables.pas';
UBilEau: NomUnite := 'BilEau.pas';
UPalmier: NomUnite := 'Palmier.pas';
UMilBilanCarbone: NomUnite := 'MilBilanCarbone.pas';
UBhyTypeFAO: NomUnite := 'BhyTypeFAO.pas';
UBiomasse: NomUnite := 'Biomasse.pas';
UMeteo: NomUnite := 'Meteo.pas';
UEcopalm2: NomUnite := 'Ecopalm2.pas';
UMathStats: NomUnite := 'MathStats.pas';
UMain: NomUnite := 'Main.pas';
ULectDonnee: NomUnite := 'LectDonnee.pas';
UEcopalm2_2: NomUnite := 'Ecopalm2_2.pas';
URiz: NomUnite := 'Riz.pas';
USorghum: NomUnite := 'Sorghum.pas';
UPhenologie: NomUnite := 'Phenologie.pas';
UBilanCarbonSarra: NomUnite := 'BilanCarbonSarra.pas';
UUImportExport: NomUnite := 'UImportExport.pas';
UDeriveClimato: NomUnite := 'DeriveClimato.pas';
{VN contraintes}UContrainte: NomUnite := 'Contrainte.pas';
UDataModuleRecherche: NomUnite := 'DataModuleRecherche.pas';
URisocas: NomUnite := 'risocas.pas';
else
NomUnite := '-- non renseigné--';
end;
ShowMessage('Unité ' + NomUnite + ' | Erreur: ' + LeMessage);
ErreurAffichee := True;
end;
except
ShowMessage('Erreur générale grave... Affichage des erreurs impossible');
ErreurAffichee := True;
end;
end;
initialization
ErreurAffichee := False;
end.
|
unit Pospolite.View.CSS.Selector;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
...
}
{$mode objfpc}{$H+}
{$modeswitch advancedrecords}
interface
uses
Classes, SysUtils, math, Pospolite.View.Basics, Pospolite.View.CSS.Declaration;
type
{ TPLCSSSelectorContext }
TPLCSSSelectorContext = packed record
strict private
FFinish: SizeInt;
FSelector: TPLString;
FStart: SizeInt;
FValue: TPLString;
public
constructor Create(const ASelector, AValue: TPLString; const AStart, AFinish: SizeInt);
property Selector: TPLString read FSelector write FSelector;
property Value: TPLString read FValue write FValue;
property Start: SizeInt read FStart write FStart;
property Finish: SizeInt read FFinish write FFinish;
end;
{ TPLCSSSelectorContextable }
TPLCSSSelectorContextable = packed class
protected
FContext: TPLCSSSelectorContext;
public
constructor Create(const AContext: TPLCSSSelectorContext); virtual;
property Context: TPLCSSSelectorContext read FContext write FContext;
end;
{ TPLCSSSimpleSelector }
TPLCSSSimpleSelector = packed class(TPLCSSSelectorContextable);
TPLCSSSimpleSelectors = packed class(specialize TPLObjectList<TPLCSSSimpleSelector>);
{ TPLCSSSimpleSelectorPattern }
TPLCSSSimpleSelectorPattern = packed class(TPLCSSSelectorContextable)
private
FSimpleSelectors: TPLCSSSimpleSelectors;
public
constructor Create(const AContext: TPLCSSSelectorContext); override;
destructor Destroy; override;
function AppliesTo(AObject: TPLHTMLObject; out AApplied: TPLHTMLObject): TPLBool;
property SimpleSelectors: TPLCSSSimpleSelectors read FSimpleSelectors;
end;
TPLCSSSimpleSelectorPatterns = packed class(specialize TPLObjectList<TPLCSSSimpleSelectorPattern>);
TPLCSSSelectorExpressionSignal = (sesPlus = '+', sesMinus = '-');
TPLCSSSelectorExpressionKind = (sekIdentifier, sekNumber, sekString, sekSignal);
TPLCSSSelectorExpressionItem = specialize TPLParameter<TPLCSSSelectorExpressionKind, TPLString>;
TPLCSSSelectorExpressionItems = class(specialize TPLList<TPLCSSSelectorExpressionItem>);
{ TPLCSSSelectorExpression }
TPLCSSSelectorExpression = packed record
strict private
FFirst, FSecond: TPLInt;
FText: TPLString;
public
constructor Create(const AFirst, ASecond: TPLInt; const AText: TPLString);
class function Null: TPLCSSSelectorExpression; static;
class operator =(a, b: TPLCSSSelectorExpression) r: TPLBool;
property First: TPLInt read FFirst;
property Second: TPLInt read FSecond;
property Text: TPLString read FText;
end;
{ TPLCSSSelectorPseudoExpression }
TPLCSSSelectorPseudoExpression = packed class(TPLCSSSelectorContextable)
private
FEvaluation: TPLCSSSelectorExpression;
FItems: TPLCSSSelectorExpressionItems;
FText: TPLString;
public
constructor Create(const AContext: TPLCSSSelectorContext; const AText: TPLString;
const AEvaluation: TPLCSSSelectorExpression); reintroduce;
destructor Destroy; override;
function IsValidAsGroup: TPLBool; inline;
property Text: TPLString read FText write FText;
property Evaluation: TPLCSSSelectorExpression read FEvaluation write FEvaluation;
property Items: TPLCSSSelectorExpressionItems read FItems;
end;
{ TPLCSSSelectorPseudoEvaluator }
TPLCSSSelectorPseudoEvaluator = packed class sealed
public
class function Evaluate(AList: TPLCSSSelectorExpressionItems): TPLCSSSelectorExpression;
end;
TPLCSSSelectorPseudoKind = (pskClass, pskElement);
TPLCSSSelectorPseudo = packed class(TPLCSSSimpleSelector)
private
FExpression: TPLCSSSelectorPseudoExpression;
FKind: TPLCSSSelectorPseudoKind;
FName: TPLString;
FNamespaced: TPLBool;
public
constructor Create(const AContext: TPLCSSSelectorContext; const AName: TPLString;
const AExpression: TPLCSSSelectorPseudoExpression; const AKind: TPLCSSSelectorPseudoKind;
const ANamespaced: TPLBool); reintroduce;
destructor Destroy; override;
property Name: TPLString read FName;
property Expression: TPLCSSSelectorPseudoExpression read FExpression;
property Kind: TPLCSSSelectorPseudoKind read FKind;
property Namespaced: TPLBool read FNamespaced;
end;
{ TPLCSSSelectorString }
TPLCSSSelectorString = packed class(TPLCSSSelectorContextable)
private
FValue: TPLString;
public
constructor Create(const AContext: TPLCSSSelectorContext; const AValue: TPLString); reintroduce;
property Value: TPLString read FValue write FValue;
end;
{ TPLCSSSelectorAttribute }
TPLCSSSelectorAttribute = packed class(TPLCSSSimpleSelector)
private
FCaseSensitive: TPLBool;
FComparator: TPLString;
FName: TPLString;
FValue: TPLCSSSelectorString;
public
constructor Create(const AContext: TPLCSSSelectorContext; const AName,
AComparator: TPLString; const AValue: TPLCSSSelectorString;
const ACaseSensitive: TPLBool = false); reintroduce;
destructor Destroy; override;
property Name: TPLString read FName;
property Comparator: TPLString read FComparator;
property Value: TPLCSSSelectorString read FValue;
property CaseSensitive: TPLBool read FCaseSensitive;
end;
{ TPLCSSSelectorClass }
TPLCSSSelectorClass = packed class(TPLCSSSimpleSelector)
private
FName: TPLString;
public
constructor Create(const AContext: TPLCSSSelectorContext; const AName: TPLString); reintroduce;
property Name: TPLString read FName;
end;
{ TPLCSSSelectorType }
TPLCSSSelectorType = packed class(TPLCSSSelectorClass)
public
function IsUniversal: TPLBool; inline;
end;
{ TPLCSSSelectorHash }
TPLCSSSelectorHash = packed class(TPLCSSSelectorClass);
{ TPLCSSSelectorNegation }
TPLCSSSelectorNegation = packed class(TPLCSSSelectorClass);
TPLCSSSelectorCombinator = (scUndefined = 0, scDescendant = ' ', scChild = '>',
scGeneralSibling = '~', scAdjascentSibling = '+');
TPLCSSSelectorCombinatorItem = specialize TPLParameter<SizeInt, TPLCSSSelectorCombinator>;
TPLCSSSelectorCombinators = packed class(specialize TPLList<TPLCSSSelectorCombinatorItem>);
{ TPLCSSSelector }
TPLCSSSelector = packed class(TPLCSSSelectorContextable)
private
FCombinators: TPLCSSSelectorCombinators;
FSimpleSelectors: TPLCSSSimpleSelectorPatterns;
public
constructor Create(const AContext: TPLCSSSelectorContext); override;
destructor Destroy; override;
property SimpleSelectors: TPLCSSSimpleSelectorPatterns read FSimpleSelectors;
property Combinators: TPLCSSSelectorCombinators read FCombinators;
end;
IPLCSSSelectors = specialize IPLObjectList<TPLCSSSelector>;
TPLCSSSelectors = packed class(specialize TPLObjectList<TPLCSSSelector>, IPLCSSSelectors);
{ TPLCSSSelectorParser }
TPLCSSSelectorParser = packed class sealed
public
class function ParseSelector(ASelector: TPLString): TPLCSSSelectors;
end;
implementation
uses character, strutils, LazUTF8, Pospolite.View.HTML.Basics;
function BelongsToLinearFunction(a, b, v: SizeInt): TPLBool;
var
i: SizeInt = 0;
begin
if a = 0 then exit(v = b);
while v <> a*i + b do Inc(i); // poprawić!
Result := v = a*i + b;
end;
{ TPLCSSSelectorContext }
constructor TPLCSSSelectorContext.Create(const ASelector, AValue: TPLString;
const AStart, AFinish: SizeInt);
begin
FSelector := ASelector;
FValue := AValue;
FStart := AStart;
FFinish := AFinish;
end;
{ TPLCSSSelectorContextable }
constructor TPLCSSSelectorContextable.Create(
const AContext: TPLCSSSelectorContext);
begin
inherited Create;
FContext := AContext;
end;
{ TPLCSSSimpleSelectorPattern }
constructor TPLCSSSimpleSelectorPattern.Create(
const AContext: TPLCSSSelectorContext);
begin
inherited Create(AContext);
FSimpleSelectors := TPLCSSSimpleSelectors.Create();
end;
destructor TPLCSSSimpleSelectorPattern.Destroy;
begin
FSimpleSelectors.Free;
inherited Destroy;
end;
function TPLCSSSimpleSelectorPattern.AppliesTo(AObject: TPLHTMLObject;
out AApplied: TPLHTMLObject): TPLBool;
var
i: SizeInt = 0;
attr: TPLHTMLObjectAttribute;
p1, p2: TPLString;
ps: TPLCSSSelectorPseudo;
obj: TPLHTMLObject;
j: SizeInt;
r: TPLBool;
v: TPLInt;
begin
Result := false;
AApplied := AObject;
if FSimpleSelectors.Empty then exit;
if (FSimpleSelectors.First is TPLCSSSelectorType and
TPLCSSSelectorType(FSimpleSelectors.First).IsUniversal) then Inc(i);
while i < FSimpleSelectors.Count do begin
if FSimpleSelectors[i] is TPLCSSSelectorType then begin
if AObject.Name.ToLower <> TPLCSSSelectorType(FSimpleSelectors[i]).Name.ToLower then exit;
end else if FSimpleSelectors[i] is TPLCSSSelectorHash then begin
if AObject.Attributes.Id = Default(TPLHTMLObjectAttribute) then exit;
if AObject.Attributes.Id.Value.ToLower <> TPLCSSSelectorHash(FSimpleSelectors[i]).Name.ToLower then exit;
end else if FSimpleSelectors[i] is TPLCSSSelectorAttribute then begin
if AObject.Attributes.Empty then exit;
attr := AObject.Attributes.Get(TPLCSSSelectorAttribute(FSimpleSelectors[i]).Name);
if (attr = Default(TPLHTMLObjectAttribute)) or TPLCSSSelectorAttribute(FSimpleSelectors[i]).Name.IsEmpty then exit;
if TPLCSSSelectorAttribute(FSimpleSelectors[i]).Comparator.IsEmpty
or not Assigned(TPLCSSSelectorAttribute(FSimpleSelectors[i]).Value) then begin
Inc(i);
continue;
end;
p1 := TPLCSSSelectorAttribute(FSimpleSelectors[i]).Value.Value;
p2 := attr.Value;
if not TPLCSSSelectorAttribute(FSimpleSelectors[i]).CaseSensitive then begin
p1 := p1.ToLower;
p2 := p2.ToLower;
end;
case TPLCSSSelectorAttribute(FSimpleSelectors[i]).Comparator of
'=': if p1 <> p2 then exit;
'~=': if (p2 <> p1) and not (p1 in p2.Split(' ')) then exit;
'|=': if not ((p2 = p1) or (p2.StartsWith(p1+'-'))) then exit;
'^=': if not p2.StartsWith(p1) then exit;
'$=': if not p2.EndsWith(p1) then exit;
'*=': if not p2.Exists(p1) then exit;
end;
end else if FSimpleSelectors[i] is TPLCSSSelectorPseudo then begin
//... zrobić pseudo-elementy typu ::-webkit-scrollbar...
if not (AObject is TPLHTMLNormalObject) then exit;
ps := TPLCSSSelectorPseudo(FSimpleSelectors[i]);
case ps.Name.ToLower of
'hover': if AObject.State <> esHover then exit;
'active': if AObject.State <> esActive then exit;
'focus': if AObject.State <> esFocus then exit;
'focus-visible': if AObject.State <> esFocusVisible then exit;
'focus-within': if AObject.State <> esFocusWithin then exit;
'any-link': if not (AObject.IsLink and (AObject.State in [esNormal, esVisited])) then exit;
'link': if not AObject.IsLink or (AObject.State <> esNormal) then exit;
'visited': if not AObject.IsLink or (AObject.State <> esVisited) then exit;
'local-link': if not AObject.IsLink or not AObject.Attributes.Href.Value.Trim.StartsWith('#') then exit;
'root': if AObject.Name <> 'html' then exit;
'empty': if not AObject.Children.Empty or (TPLHTMLObjectFactory.GetTextFromTextNodes(AObject).Trim <> '') then exit;
'first-child': begin
if not Assigned(AObject.Parent) then obj := AObject else obj := AObject.Parent;
r := false;
for j := 0 to obj.Children.Count-1 do begin
if (obj.Children[j].Name = AObject.Name) and (obj.Children[j] = AObject) then begin
r := true;
AApplied := obj.Children[j];
break;
end;
if obj.Children[j].Name = AObject.Name then break;
end;
if not r then exit;
end;
'last-child': begin
if not Assigned(AObject.Parent) then obj := AObject else obj := AObject.Parent;
r := false;
for j := obj.Children.Count-1 downto 0 do begin
if (obj.Children[j].Name = AObject.Name) and (obj.Children[j] = AObject) then begin
r := true;
AApplied := obj.Children[j];
break;
end;
if obj.Children[j].Name = AObject.Name then break;
end;
if not r then exit;
end;
'only-child': if AObject.Children.Count - TPLHTMLObjectFactory.GetTextNodesCount(AObject) > 0 then exit;
// to co niżej naprawić dla <> *, tzn. np. p:nth-child(...)
'nth-child':
if not BelongsToLinearFunction(ps.Expression.Evaluation.First, ps.Expression.Evaluation.Second, AObject.PositionInParent+1) then exit;
'nth-last-child': begin
v := 0;
if Assigned(AObject.Parent) then v := AObject.Parent.Children.Count;
if not BelongsToLinearFunction(ps.Expression.Evaluation.First, ps.Expression.Evaluation.Second, v-AObject.PositionInParent) then exit;
end;
'nth-of-type': ;
'nth-last-of-type': ;
//...
end;
end else if FSimpleSelectors[i] is TPLCSSSelectorClass then begin
if AObject.Attributes.&Class = Default(TPLHTMLObjectAttribute) then exit;
if not (TPLCSSSelectorClass(FSimpleSelectors[i]).Name.ToLower in AObject.Attributes.&Class.Value.ToLower.Split(' ')) then exit;
end;
AObject := AApplied;
Inc(i);
end;
Result := true;
end;
{ TPLCSSSelectorExpression }
constructor TPLCSSSelectorExpression.Create(const AFirst, ASecond: TPLInt;
const AText: TPLString);
begin
FFirst := AFirst;
FSecond := ASecond;
FText := AText;
end;
class function TPLCSSSelectorExpression.Null: TPLCSSSelectorExpression;
begin
Result := Default(TPLCSSSelectorExpression);
end;
class operator TPLCSSSelectorExpression.=(a, b: TPLCSSSelectorExpression)
r: TPLBool;
begin
r := (a.First = b.First) and (a.Second = b.Second) and (a.Text = b.Text);
end;
{ TPLCSSSelectorPseudoExpression }
constructor TPLCSSSelectorPseudoExpression.Create(
const AContext: TPLCSSSelectorContext; const AText: TPLString;
const AEvaluation: TPLCSSSelectorExpression);
begin
inherited Create(AContext);
FText := AText;
FEvaluation := AEvaluation;
FItems := TPLCSSSelectorExpressionItems.Create;
end;
destructor TPLCSSSelectorPseudoExpression.Destroy;
begin
FItems.Free;
inherited Destroy;
end;
function TPLCSSSelectorPseudoExpression.IsValidAsGroup: TPLBool;
begin
Result := FEvaluation <> TPLCSSSelectorExpression.Null;
end;
{ TPLCSSSelectorPseudoEvaluator }
class function TPLCSSSelectorPseudoEvaluator.Evaluate(
AList: TPLCSSSelectorExpressionItems): TPLCSSSelectorExpression;
var
i: SizeInt = 0;
s: TPLCSSSelectorExpressionSignal = sesPlus;
c: TPLBool = false;
a: TPLInt = 0;
b: TPLInt = 0;
function Current: TPLCSSSelectorExpressionItem;
begin
Result := AList[i];
end;
function IsEOF: TPLBool;
begin
Result := i >= AList.Count;
end;
begin
Result := TPLCSSSelectorExpression.Null;
if not Assigned(AList) or AList.Empty then exit;
if Current.Value in TPLStringFuncs.NewArray(['odd', 'even']) then exit(TPLCSSSelectorExpression.Create(2, ifthen(Current.Value = 'odd', 1, 0), ''));
if (Current.Key = sekIdentifier) and (Current.Value <> 'n') then exit;
if Current.Key = sekSignal then begin
if Current.Value = '+' then s := sesPlus else s := sesMinus;
Inc(i);
if IsEOF then exit;
end;
if Current.Key = sekNumber then begin
TryStrToInt64(Current.Value, a);
c := true;
Inc(i);
end;
if s = sesMinus then a := -a;
if IsEOF then exit(TPLCSSSelectorExpression.Create(0, a, ''));
if (Current.Key = sekIdentifier) and (Current.Value = 'n') then begin
c := true;
Inc(i);
end;
if not c then exit;
if IsEOF then exit(TPLCSSSelectorExpression.Create(a, 0, ''));
s := sesPlus;
if Current.Key = sekSignal then begin
if Current.Value = '+' then s := sesPlus else s := sesMinus;
Inc(i);
if IsEOF then exit;
end;
if Current.Key = sekNumber then begin
TryStrToInt64(Current.Value, b);
if s = sesMinus then b := -b;
Inc(i);
end;
if IsEOF then exit(TPLCSSSelectorExpression.Create(a, b, ''));
end;
constructor TPLCSSSelectorPseudo.Create(const AContext: TPLCSSSelectorContext;
const AName: TPLString; const AExpression: TPLCSSSelectorPseudoExpression;
const AKind: TPLCSSSelectorPseudoKind; const ANamespaced: TPLBool);
begin
inherited Create(AContext);
FName := AName;
FExpression := AExpression;
FKind := AKind;
FNamespaced := ANamespaced;
end;
destructor TPLCSSSelectorPseudo.Destroy;
begin
if Assigned(FExpression) then FExpression.Free;
inherited Destroy;
end;
{ TPLCSSSelectorString }
constructor TPLCSSSelectorString.Create(const AContext: TPLCSSSelectorContext;
const AValue: TPLString);
begin
inherited Create(AContext);
FValue := AValue;
end;
{ TPLCSSSelectorAttribute }
constructor TPLCSSSelectorAttribute.Create(
const AContext: TPLCSSSelectorContext; const AName, AComparator: TPLString;
const AValue: TPLCSSSelectorString; const ACaseSensitive: TPLBool);
begin
inherited Create(Context);
FName := AName;
FComparator := AComparator;
FValue := AValue;
FCaseSensitive := ACaseSensitive;
end;
destructor TPLCSSSelectorAttribute.Destroy;
begin
if Assigned(FValue) then FValue.Free;
inherited Destroy;
end;
{ TPLCSSSelectorClass }
constructor TPLCSSSelectorClass.Create(const AContext: TPLCSSSelectorContext;
const AName: TPLString);
begin
inherited Create(AContext);
FName := AName;
end;
{ TPLCSSSelectorType }
function TPLCSSSelectorType.IsUniversal: TPLBool;
begin
Result := Name = '*';
end;
{ TPLCSSSelector }
constructor TPLCSSSelector.Create(const AContext: TPLCSSSelectorContext);
begin
inherited Create(AContext);
FCombinators := TPLCSSSelectorCombinators.Create;
FSimpleSelectors := TPLCSSSimpleSelectorPatterns.Create(true);
end;
destructor TPLCSSSelector.Destroy;
begin
FCombinators.Free;
FSimpleSelectors.Free;
inherited Destroy;
end;
{ TPLCSSSelectorParser }
class function TPLCSSSelectorParser.ParseSelector(ASelector: TPLString
): TPLCSSSelectors;
var
pos: SizeInt = 1;
function IsEOF: TPLBool; inline;
begin
Result := pos > Length(ASelector);
end;
function Current: TPLChar;
begin
if not IsEOF then Result := ASelector[pos] else Result := #0;
end;
procedure ConsumeWhitespace;
begin
while not IsEOF and Current.IsWhiteSpace do Inc(pos);
end;
function IsSpecialPseudo(const APseudo: TPLString): TPLBool; inline;
begin
Result := APseudo.ToLower in TPLStringFuncs.NewArray(['after', 'before',
'first-letter', 'first-line', 'marker', 'placeholder', 'selection']);
end;
function NewIdentifier: TPLString;
begin
Result := '';
if not IsEOF and (Current <> '_') and not TCharacter.IsLetter(Current) then exit;
while not IsEOF and (TCharacter.IsLetterOrDigit(Current) or (Current in ['_', '-'])) do begin
Result += Current;
Inc(pos);
end;
end;
function NewNumber: TPLString;
begin
Result := Current;
Inc(pos);
while not IsEOF and TCharacter.IsNumber(Current) do begin
Result += Current;
Inc(pos);
end;
end;
function NewString: TPLCSSSelectorString;
var
q: TPLChar;
esc: TPLBool = false;
v, pom, pom2: TPLString;
i, p: SizeInt;
begin
q := Current;
v := '';
pom := '';
p := pos;
Inc(pos);
while not IsEOF do begin
if esc then begin
if Current in ['0'..'9', 'A'..'F', 'a'..'f'] then begin
pom2 := '';
for i := 0 to 5 do begin
if not (Current in ['0'..'9', 'A'..'F', 'a'..'f']) then break;
pom2 += Current;
Inc(pos);
end;
pom2 := UnicodeToUTF8(pom2.FromHex);
v += pom2;
pom += pom2;
end else begin
v += Current;
pom += Current;
end;
esc := false;
end else begin
if Current = q then begin
Inc(pos);
break;
end;
pom += Current;
if Current = '\' then esc := true else v += Current;
end;
Inc(pos);
end;
Result := TPLCSSSelectorString.Create(TPLCSSSelectorContext.Create(ASelector, pom, p, pos), v);
end;
function NewAttribute: TPLCSSSelectorAttribute;
var
sub: TPLString = '[';
pom, pom2, op: TPLString;
cs: TPLBool = false;
p, pp: SizeInt;
v: TPLCSSSelectorString = nil;
q: TPLChar;
begin
op := '';
p := pos;
ConsumeWhitespace;
pom := '';
if not IsEOF then pom := NewIdentifier;
if pom.IsEmpty then pom := 'attr';
sub += pom;
ConsumeWhitespace;
if not isEOF then begin
if Current in ['~', '*', '$', '|', '^'] then begin
op := Current + '=';
Inc(pos);
if IsEOF or (Current <> '=') then begin
if not IsEOF and not (Current in ['''', '"']) then Inc(pos);
end else Inc(pos);
end else if Current <> ']' then begin
if Current = '=' then op := '=';
Inc(pos);
end;
ConsumeWhitespace;
if not IsEOF then begin
if op <> '' then begin
sub += op;
if Current in ['''', '"'] then begin
q := Current;
v := NewString;
sub += q + v.Context.Value + q;
end else begin
pp := pos;
pom2 := NewIdentifier;
sub += pom2;
v := TPLCSSSelectorString.Create(TPLCSSSelectorContext.Create(ASelector, pom2, pp, pos), pom2);
end;
end;
ConsumeWhitespace;
if LowerCase(Current) in ['i', 's'] then begin
cs := LowerCase(Current) = 's';
Inc(pos);
end;
ConsumeWhitespace;
if not IsEOF then Inc(pos);
end;
end;
Result := TPLCSSSelectorAttribute.Create(TPLCSSSelectorContext.Create(ASelector, sub + ']', p, pos), pom, op, v, cs);
end;
function NewPseudoExpression: TPLCSSSelectorPseudoExpression;
var
p: SizeInt;
sb: TPLString = '';
c: TPLChar;
list: TPLCSSSelectorExpressionItems;
expr: TPLCSSSelectorExpression;
s: TPLCSSSelectorString;
pom: TPLString;
begin
p := pos;
list := TPLCSSSelectorExpressionItems.Create;
if Current in ['''', '"'] then begin
c := Current;
s := NewString;
sb += c + s.Value + c;
expr := TPLCSSSelectorExpression.Create(0, 0, s.Value);
s.Free;
exit(TPLCSSSelectorPseudoExpression.Create(TPLCSSSelectorContext.Create(ASelector, sb, p, pos), expr.Text, expr));
end else begin
while not IsEOF do begin
if Current in ['+', '-'] then begin
list.Add(TPLCSSSelectorExpressionItem.Create(sekSignal, Current));
Inc(pos);
end else if TCharacter.IsLetter(Current) then begin
pom := NewIdentifier;
sb += pom;
list.Add(TPLCSSSelectorExpressionItem.Create(sekIdentifier, pom));
end else if TCharacter.IsDigit(Current) then begin
pom := NewNumber;
sb += pom;
list.Add(TPLCSSSelectorExpressionItem.Create(sekNumber, pom));
end else break;
ConsumeWhitespace;
end;
end;
Result := TPLCSSSelectorPseudoExpression.Create(TPLCSSSelectorContext.Create(ASelector, sb, p, pos), sb, TPLCSSSelectorPseudoEvaluator.Evaluate(list));
list.Free;
end;
function NewPseudo(AName: TPLString; ANamespaced: TPLBool; AKind: TPLCSSSelectorPseudoKind): TPLCSSSelectorPseudo;
var
expr: TPLCSSSelectorPseudoExpression = nil;
sub: TPLString = '';
p: SizeInt;
begin
p := pos;
sub += AName;
ConsumeWhitespace;
if not IsEOF and (Current = '(') then begin
sub += Current;
Inc(pos);
ConsumeWhitespace;
expr := NewPseudoExpression;
sub += expr.Context.Value + ')';
ConsumeWhitespace;
if not IsEOF then Inc(pos);
end;
Result := TPLCSSSelectorPseudo.Create(TPLCSSSelectorContext.Create(ASelector, sub, p, pos), AName, expr, AKind, ANamespaced);
end;
function NewPattern: TPLCSSSimpleSelectorPattern;
var
p, pp, sc: SizeInt;
sub: TPLString = '';
ss: TPLBool = false;
pom: TPLString;
ps, dc: TPLBool;
begin
p := pos;
Result := TPLCSSSimpleSelectorPattern.Create(TPLCSSSelectorContext.Create(ASelector, '', p, pos));
if Current = '*' then begin
ss := true;
sub += Current;
Result.SimpleSelectors.Add(TPLCSSSelectorType.Create(TPLCSSSelectorContext.Create(ASelector, '*', p, pos), '*'));
Inc(pos);
end else if TCharacter.IsLetter(Current) then begin
ss := true;
pom := NewIdentifier;
sub += pom;
Result.SimpleSelectors.Add(TPLCSSSelectorType.Create(TPLCSSSelectorContext.Create(ASelector, pom, p, pos), pom));
end;
sc := 0;
ps := false;
while not IsEOF do begin
pp := pos;
case Current of
'.': begin
Inc(pos);
if not IsEOF then pom := NewIdentifier else pom := '';
if not pom.IsEmpty then begin
sub += '.' + pom;
Result.SimpleSelectors.Add(TPLCSSSelectorClass.Create(TPLCSSSelectorContext.Create(ASelector, '.' + pom, pp, pos), pom));
end;
end;
'#': begin
Inc(pos);
if not IsEOF then pom := NewIdentifier else pom := '';
if not pom.IsEmpty then begin
sub += '#' + pom;
Result.SimpleSelectors.Add(TPLCSSSelectorHash.Create(TPLCSSSelectorContext.Create(ASelector, '#' + pom, pp, pos), pom));
end;
end;
'[': begin
pp := pos;
Inc(pos);
Result.SimpleSelectors.Add(NewAttribute);
sub += ASelector.SubStr(pp, pos - pp + 1);
end;
':': begin
dc := false;
Inc(pos);
sub += ':';
if IsEOF then break;
if Current = ':' then begin
dc := true;
sub += ':';
Inc(pos);
end;
if not IsEOF then pom := NewIdentifier.ToLower else pom := '';
if not pom.IsEmpty then begin
if IsSpecialPseudo(pom) or dc then begin
sub += pom;
Result.SimpleSelectors.Add(NewPseudo(pom, dc, pskElement));
end else begin
case pom of
'not': begin
//...
end;
// zrobić :is, :where, :nth-...
else begin
sub += pom;
Result.SimpleSelectors.Add(NewPseudo(pom, dc, pskClass));
end;
end;
end;
Inc(sc);
end;
end;
else break;
end;
end;
with Result.Context do begin
Value := sub;
Finish := pos;
end;
end;
function NewSelector: TPLCSSSelector;
var
sub: TPLString = '';
c: TPLCSSSelectorCombinator;
wsp: TPLBool;
p: TPLCSSSimpleSelectorPattern;
begin
Result := TPLCSSSelector.Create(TPLCSSSelectorContext.Create(ASelector, '', pos, pos));
while not IsEOF do begin
c := scUndefined;
if not Result.SimpleSelectors.Empty then begin
wsp := false;
if not IsEOF and Current.IsWhiteSpace then begin
wsp := true;
ConsumeWhitespace;
end;
if not IsEOF then begin
case Current of
'>': c := scChild;
'~': c := scGeneralSibling;
'+': c := scAdjascentSibling;
else if wsp then c := scDescendant else c := scChild;
end;
if (c = scUndefined) or (Current = ',') then break;
if c = scDescendant then sub += ' ' else begin
sub += Current;
Inc(pos);
end;
ConsumeWhitespace;
if IsEOF then break;
end else break;
//if c = scUndefined then begin
// Inc(pos);
// continue;
//end;
Result.Combinators.Add(TPLCSSSelectorCombinatorItem.Create(Result.SimpleSelectors.Count-1, c));
end;
p := NewPattern;
sub += p.Context.Value;
Result.SimpleSelectors.Add(p);
end;
with Result.Context do begin
Value := sub;
Finish := pos;
end;
end;
begin
ASelector := ASelector.Trim;
Result := TPLCSSSelectors.Create(true);
while not IsEOF do begin
ConsumeWhitespace;
Result.Add(NewSelector);
ConsumeWhitespace;
if not IsEOF and (Current <> ',') then break;
Inc(pos);
end;
end;
end.
|
unit cxGridPlacement;
interface
uses stdctrls, windows, classes, Sysutils, Controls, comctrls, Forms, cxGridDBTableView;
type
TAvcxGridPlacement = class(TComponent)
private
FActive: Boolean;
FRestored: Boolean;
FSaved: Boolean;
FDestroying: Boolean;
FcxGridDBTableView: TcxGridDBTableView;
FTag: Integer;
FSaveFormShow: TNotifyEvent;
FSaveFormDestroy: TNotifyEvent;
FSaveFormCloseQuery: TCloseQueryEvent;
procedure SetEvents;
procedure RestoreEvents;
procedure FormShow(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormDestroy(Sender: TObject);
function GetForm: TForm;
protected
procedure Loaded; override;
property Form: TForm read GetForm;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SaveGridPlacement;
procedure RestoreGridPlacement;
published
property Active: Boolean read FActive write FActive default True;
property GridDBTableView: TcxGridDBTableView read FcxGridDBTableView write FcxGridDBTableView;
property Tag: Integer read FTag write FTag default 0;
end;
procedure Register;
implementation
uses FIBQuery, pFIBQuery, FIBDataset, db, cxGridCustomView, cxGrid;
procedure Register;
begin
RegisterComponents('Data Controls', [TAvcxGridPlacement]);
end;
constructor TAvcxGridPlacement.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FActive := True;
end;
destructor TAvcxGridPlacement.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
RestoreEvents;
end;
inherited Destroy;
end;
procedure TAvcxGridPlacement.Loaded;
var
Loading: Boolean;
begin
Loading := csLoading in ComponentState;
inherited Loaded;
if not (csDesigning in ComponentState) then
begin
if Loading then SetEvents;
end;
end;
function TAvcxGridPlacement.GetForm: TForm;
begin
if Owner is TCustomForm then Result := TForm(Owner as TCustomForm)
else Result := nil;
end;
procedure TAvcxGridPlacement.SetEvents;
begin
if Owner is TCustomForm then
begin
with TForm(Form) do
begin
FSaveFormShow := OnShow;
OnShow := FormShow;
FSaveFormCloseQuery := OnCloseQuery;
OnCloseQuery := FormCloseQuery;
FSaveFormDestroy := OnDestroy;
OnDestroy := FormDestroy;
end;
end;
end;
procedure TAvcxGridPlacement.RestoreEvents;
begin
if (Owner <> nil) and (Owner is TCustomForm) then
with TForm(Form) do
begin
OnShow := FSaveFormShow;
OnCloseQuery := FSaveFormCloseQuery;
OnDestroy := FSaveFormDestroy;
end;
end;
procedure TAvcxGridPlacement.FormShow(Sender: TObject);
begin
if Active then
try
RestoreGridPlacement;
except
Application.HandleException(Self);
end;
if Assigned(FSaveFormShow) then FSaveFormShow(Sender);
end;
procedure TAvcxGridPlacement.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if Assigned(FSaveFormCloseQuery) then
FSaveFormCloseQuery(Sender, CanClose);
if CanClose and Active and (Owner is TCustomForm) and (Form.Handle <> 0) then
try
SaveGridPlacement;
except
Application.HandleException(Self);
end;
end;
procedure TAvcxGridPlacement.FormDestroy(Sender: TObject);
begin
if Active and not FSaved then begin
FDestroying := True;
try
SaveGridPlacement;
except
Application.HandleException(Self);
end;
FDestroying := False;
end;
if Assigned(FSaveFormDestroy) then FSaveFormDestroy(Sender);
end;
procedure TAvcxGridPlacement.SaveGridPlacement;
var
FQuery: TpFIBQuery;
Write_Str: TMemoryStream;
Size: Integer;
F: Array [0..4] of Integer;
begin
if FRestored or not Active then
begin
Write_Str := TMemoryStream.Create;
FQuery := TpFIBQuery.Create(Self);
FQuery.Database := (FcxGridDBTableView.DataController.DataSource.DataSet as TFIBDataset).Database;
FQuery.Transaction := (FcxGridDBTableView.DataController.DataSource.DataSet as TFIBDataset).UpdateTransaction;
if not FQuery.Transaction.InTransaction then FQuery.Transaction.StartTransaction;
try
FQuery.SQL.Text := 'execute procedure PMTWP101BLOBSUPD(:concept, :user_id, :val)';
FQuery.ParamByName('concept').AsInteger := 20000000+Tag*100000+1000;
FQuery.ParamByName('user_id').AsInteger := FQuery.Database.Tag;
FcxGridDBTableView.StoreToStream(Write_Str,[gsoUseFilter]);
FQuery.ParamByName('VAL').LoadFromStream(Write_Str);
FQuery.ExecProc;
Write_Str.Clear;
FQuery.ParamByName('concept').AsInteger := 20000000+Tag*100000+1000+1;
Size := (FcxGridDBTableView.Control as TcxCustomGrid).Font.Size;
Write_Str.Write(Size, sizeof(Size));
FQuery.ParamByName('VAL').LoadFromStream(Write_Str);
FQuery.ExecProc;
Write_Str.Clear;
FQuery.ParamByName('concept').AsInteger := 20000000+Tag*100000;
F[0] := Form.Left;
F[1] := Form.Top;
F[2] := Form.Width;
F[3] := Form.Height;
Case Form.WindowState of
wsNormal: F[4] := 0;
wsMinimized: F[4] := 1;
wsMaximized: F[4] := 2;
end;
Write_Str.Write(F[0], SizeOf(F));
FQuery.ParamByName('VAL').LoadFromStream(Write_Str);
FQuery.ExecProc;
Write_Str.Clear;
FQuery.Transaction.CommitRetaining;
FSaved := True;
finally
Write_Str.Free;
end;
end;
end;
procedure TAvcxGridPlacement.RestoreGridPlacement;
var
Read_Str: TMemoryStream;
FQuery: TpFIBQuery;
Size: Integer;
F: array [0..4] of Integer;
begin
FSaved := False;
Read_Str := TMemoryStream.Create;
FQuery := TpFIBQuery.Create(Self);
FQuery.Database := (FcxGridDBTableView.DataController.DataSource.DataSet as TFIBDataset).Database;
FQuery.Transaction := (FcxGridDBTableView.DataController.DataSource.DataSet as TFIBDataset).UpdateTransaction;
if not FQuery.Transaction.InTransaction then FQuery.Transaction.StartTransaction;
try
FQuery.SQL.Text := 'select * from p101_blobs where concept = :concept and link = :user_id';
FQuery.ParamByName('concept').AsInteger := 20000000+Tag*100000+1000;
FQuery.ParamByName('user_id').AsInteger := FQuery.Database.Tag;
FQuery.Close;
FQuery.ExecQuery;
if not FQuery.Eof then
begin
FQuery.FieldByName('VAL').SaveToStream(Read_Str);
Read_Str.Seek(0, soFromBeginning);
FcxGridDBTableView.RestoreFromStream(Read_Str, False, False, [gsoUseFilter]);
Read_Str.Clear;
end;
FQuery.ParamByName('concept').AsInteger := 20000000+Tag*100000+1000+1;
FQuery.Close;
FQuery.ExecQuery;
if not FQuery.Eof then
begin
FQuery.FieldByName('VAL').SaveToStream(Read_Str);
Read_Str.Seek(0, soFromBeginning);
Read_Str.Read(Size, sizeof(Size));
(FcxGridDBTableView.Control as TcxCustomGrid).Font.Size := Size;
Read_Str.Clear;
end;
FQuery.ParamByName('concept').AsInteger := 20000000+Tag*100000;
FQuery.Close;
FQuery.ExecQuery;
if not FQuery.Eof then
begin
FQuery.FieldByName('VAL').SaveToStream(Read_Str);
Read_Str.Seek(0, soFromBeginning);
Read_Str.Read(F[0],sizeof(F));
Form.WindowState := wsNormal;
Form.Left := F[0];
Form.Top := F[1];
Form.Width := F[2];
Form.Height := F[3];
Case F[4] of
0: Form.WindowState := wsNormal;
1: Form.WindowState := wsMinimized;
2: Form.WindowState := wsMaximized;
end;
end;
FQuery.Close;
FRestored := True;
finally
FQuery.Free;
Read_Str.Free;
end;
end;
end.
|
unit TestApp;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
(*
** pagamento menor do que conta.
moeda: array [1..4 ] of integer(
50, 10, 5, 1)
cedulas: array [ 1..5 ] of integer (
100,50,10,5,1 )
*)
interface
uses
TestFramework, App, System.SysUtils;
type
// Test methods for class TTroco
TestTTroco = class(TTestCase)
strict private
FTroco: TTroco;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestVerificaValorPgtoMenor;
procedure TestVerificaValorPgtoMaior;
procedure TestVerificaValorTroco;
end;
implementation
procedure TestTTroco.SetUp;
begin
FTroco := TTroco.Create;
end;
procedure TestTTroco.TearDown;
begin
FreeAndNil(FTroco);
end;
procedure TestTTroco.TestVerificaValorPgtoMaior;
begin
FTroco.VlrConta := 1000;
FTroco.VlrPago := 900;
Check(FTroco.VerificaValorPgtoMaior, 'erro');
end;
procedure TestTTroco.TestVerificaValorPgtoMenor;
begin
FTroco.VlrConta := 1;
FTroco.VlrPago := 900;
Check(FTroco.VerificaValorPgtoMenor, 'erro');
end;
procedure TestTTroco.TestVerificaValorTroco;
var
vValorTrocoPago: Double;
vValorExatoTroco: Double;
begin
// FTroco.VerificaValorExatoTroco()
vValorExatoTroco := 50;
vValorTrocoPago := 50;
CheckTrue((vValorExatoTroco - vValorTrocoPago) = 0);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTTroco.Suite);
end.
|
namespace Maps;
interface
uses
MapKit,
UIKit;
type
[IBObject]
MainViewController = public class(UIViewController, IUIPopoverControllerDelegate, IFlipsideViewControllerDelegate, IUISearchBarDelegate, IUITableViewDataSource, IUITableViewDelegate)
private
{$REGION IUIPopoverControllerDelegate}
method popoverControllerShouldDismissPopover(aPopoverController: UIPopoverController): Boolean;
method popoverControllerDidDismissPopover(aPopoverController: UIPopoverController);
{$ENDREGION}
{$REGION IFlipsideViewControllerDelegate}
method flipsideViewControllerDidFinish(aController: FlipsideViewController);
{$ENDREGION}
method doSearch(aGoToFirst: Boolean);
method goToMapItem(aMapItem: MKMapItem);
var fResults: NSArray;
public
method viewDidLoad; override;
method didReceiveMemoryWarning; override;
property prefersStatusBarHidden: Boolean read true; override;
method prepareForSegue(aSegue: not nullable UIStoryboardSegue) sender(aSender: id); override;
[IBAction] method togglePopover(aSender: id);
{$REGION IUISearchBarDelegate}
method searchBarShouldBeginEditing(aSearchBar: UISearchBar): Boolean;
method searchBarTextDidBeginEditing(aSearchBar: UISearchBar);
method searchBarShouldEndEditing(aSearchBar: UISearchBar): Boolean;
method searchBarTextDidEndEditing(aSearchBar: UISearchBar);
method searchBar(aSearchBar: UISearchBar) textDidChange(searchText: NSString);
method searchBar(aSearchBar: UISearchBar) shouldChangeTextInRange(range: NSRange) replacementText(text: NSString): Boolean;
method searchBarSearchButtonClicked(aSearchBar: UISearchBar);
method searchBarBookmarkButtonClicked(aSearchBar: UISearchBar);
method searchBarCancelButtonClicked(aSearchBar: UISearchBar);
method searchBarResultsListButtonClicked(aSearchBar: UISearchBar);
method searchBar(aSearchBar: UISearchBar) selectedScopeButtonIndexDidChange(selectedScope: NSInteger);
{$REGION IUITableViewDataSource}
method numberOfSectionsInTableView(aTableView: not nullable UITableView): NSInteger;
method tableView(aTableView: not nullable UITableView) numberOfRowsInSection(section: NSInteger): NSInteger;
method tableView(aTableView: not nullable UITableView) cellForRowAtIndexPath(indexPath: not nullable NSIndexPath): not nullable UITableViewCell;
method tableView(aTableView: not nullable UITableView) didSelectRowAtIndexPath(indexPath: NSIndexPath);
{$ENDREGION}
[IBOutlet] property flipsidePopoverController: UIPopoverController;
[IBOutlet] property map: weak MKMapView;
[IBOutlet] property searchBar: weak UISearchBar;
[IBOutlet] property tableView: weak UITableView;
end;
implementation
method MainViewController.viewDidLoad;
begin
inherited viewDidLoad;
end;
method MainViewController.didReceiveMemoryWarning;
begin
inherited didReceiveMemoryWarning;
end;
{$REGION IUIPopoverControllerDelegate}
method MainViewController.popoverControllerShouldDismissPopover(aPopoverController: UIPopoverController):Boolean;
begin
end;
method MainViewController.popoverControllerDidDismissPopover(aPopoverController: UIPopoverController);
begin
flipsidePopoverController := nil;
end;
{$ENDREGION}
{$REGION IFlipsideViewControllerDelegate}
method MainViewController.flipsideViewControllerDidFinish(aController: FlipsideViewController);
begin
dismissViewControllerAnimated(true) completion(nil);
end;
{$ENDREGION}
method MainViewController.prepareForSegue(aSegue: not nullable UIStoryboardSegue) sender(aSender: id);
begin
if aSegue.identifier.isEqualToString('showAlternate') then begin
aSegue.destinationViewController.delegate := self;
if UIDevice.currentDevice.userInterfaceIdiom = UIUserInterfaceIdiom.UIUserInterfaceIdiomPad then begin
var lPopoverController := (aSegue as UIStoryboardPopoverSegue).popoverController;
flipsidePopoverController := lPopoverController;
lPopoverController.delegate := self;
end;
end;
end;
method MainViewController.togglePopover(aSender: id);
begin
if assigned(flipsidePopoverController) then begin
flipsidePopoverController.dismissPopoverAnimated(true);
flipsidePopoverController := nil;
end
else begin
performSegueWithIdentifier('showAlternate') sender(aSender);
end;
end;
{$REGION IUISearchBarDelegate}
method MainViewController.searchBarShouldBeginEditing(aSearchBar: UISearchBar): Boolean;
begin
result := true;
end;
method MainViewController.searchBarTextDidBeginEditing(aSearchBar: UISearchBar);
begin
end;
method MainViewController.searchBarShouldEndEditing(aSearchBar: UISearchBar): Boolean;
begin
result := true;
end;
method MainViewController.searchBarTextDidEndEditing(aSearchBar: UISearchBar);
begin
end;
method MainViewController.searchBar(aSearchBar: UISearchBar) textDidChange(searchText: NSString);
begin
if length(searchBar.text) = 0 then begin
tableView.hidden := true;
end
else begin
doSearch(false);
end;
end;
method MainViewController.searchBar(aSearchBar: UISearchBar) shouldChangeTextInRange(range: NSRange) replacementText(text: NSString): Boolean;
begin
result := true;
end;
method MainViewController.searchBarSearchButtonClicked(aSearchBar: UISearchBar);
begin
doSearch(true);
searchBar.resignFirstResponder();
end;
method MainViewController.searchBarBookmarkButtonClicked(aSearchBar: UISearchBar);
begin
end;
method MainViewController.searchBarCancelButtonClicked(aSearchBar: UISearchBar);
begin
tableView.hidden := true;
end;
method MainViewController.searchBarResultsListButtonClicked(aSearchBar: UISearchBar);
begin
end;
method MainViewController.searchBar(aSearchBar: UISearchBar) selectedScopeButtonIndexDidChange(selectedScope: NSInteger);
begin
end;
{$ENDREGION}
{$REGION IUITableViewDataSource}
method MainViewController.numberOfSectionsInTableView(aTableView: not nullable UITableView): NSInteger;
begin
result := 1;
end;
method MainViewController.tableView(aTableView: not nullable UITableView) numberOfRowsInSection(section: NSInteger): NSInteger;
begin
result := if assigned(fResults) then fResults.count else 0; // todo: use colon
end;
method MainViewController.tableView(aTableView: not nullable UITableView) cellForRowAtIndexPath(indexPath: not nullable NSIndexPath): not nullable UITableViewCell;
begin
result := new UITableViewCell withStyle(UITableViewCellStyle.UITableViewCellStyleSubtitle) reuseIdentifier('CELL');
var m := fResults[indexPath.row] as MKMapItem;
result.textLabel.text := m.name;
end;
method MainViewController.tableView(aTableView: not nullable UITableView) didSelectRowAtIndexPath(indexPath: NSIndexPath);
begin
tableView.deselectRowAtIndexPath(indexPath) animated(true);
goToMapItem( fResults[indexPath.row]);
searchBar.resignFirstResponder();
end;
{$ENDREGION}
method MainViewController.doSearch(aGoToFirst: Boolean);
begin
var lRequest := new MKLocalSearchRequest;
lRequest.naturalLanguageQuery := searchBar.text;
var lSearch := new MKLocalSearch withRequest(lRequest);
lSearch.startWithCompletionHandler(method (aResponse: MKLocalSearchResponse; aError: NSError) begin
fResults := aResponse:mapItems;
tableView.hidden := not assigned(fResults);
tableView.reloadData();
if aGoToFirst and assigned(fResults) and (fResults.count > 0) then
goToMapItem(fResults[0]);
end);
end;
method MainViewController.goToMapItem(aMapItem: MKMapItem);
begin
var lRegion := new MKCoordinateRegion;
lRegion.center := aMapItem.placemark.location.coordinate;
lRegion.span := MKCoordinateSpanMake(0.005, 0.005);
map.setRegion(lRegion) animated(true);
tableView.hidden := true;
end;
end.
|
(*
* Copyright (c) 2004
* HouSisong@gmail.com
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*)
//------------------------------------------------------------------------------
// 具现化的Pointer类型的声明
// Create by HouSisong, 2004.09.04
//------------------------------------------------------------------------------
unit DGL_Pointer;
interface
uses
SysUtils;
{$I DGLCfg.inc_h}
type
_ValueType = Pointer;
const
_NULL_Value:pointer=nil;
{$define _DGL_NotHashFunction}
{$define _DGL_Compare} //是否需要比较函数,可选
function _IsEqual(const a,b :_ValueType):boolean; {$ifdef _DGL_Inline} inline; {$endif}//result:=(a=b);
function _IsLess(const a,b :_ValueType):boolean; {$ifdef _DGL_Inline} inline; {$endif} //result:=(a<b); 默认排序准则
{$I DGL.inc_h}
type
TPointerAlgorithms = _TAlgorithms;
IPointerIterator = _IIterator;
IPointerContainer = _IContainer;
IPointerSerialContainer = _ISerialContainer;
IPointerVector = _IVector;
IPointerList = _IList;
IPointerDeque = _IDeque;
IPointerStack = _IStack;
IPointerQueue = _IQueue;
IPointerPriorityQueue = _IPriorityQueue;
IPointerSet = _ISet;
IPointerMultiSet = _IMultiSet;
TPointerVector = _TVector;
TPointerDeque = _TDeque;
TPointerList = _TList;
IPointerVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:)
IPointerDequeIterator = _IDequeIterator; //速度比_IIterator稍快一点:)
IPointerListIterator = _IListIterator; //速度比_IIterator稍快一点:)
TPointerStack = _TStack;
TPointerQueue = _TQueue;
TPointerPriorityQueue = _TPriorityQueue;
//
IPointerMapIterator = _IMapIterator;
IPointerMap = _IMap;
IPointerMultiMap = _IMultiMap;
TPointerSet = _TSet;
TPointerMultiSet = _TMultiSet;
TPointerMap = _TMap;
TPointerMultiMap = _TMultiMap;
TPointerHashSet = _THashSet;
TPointerHashMultiSet = _THashMultiSet;
TPointerHashMap = _THashMap;
TPointerHashMultiMap = _THashMultiMap;
implementation
function _IsEqual(const a,b :_ValueType):boolean;
begin
result:=(a=b);
end;
function _IsLess(const a,b :_ValueType):boolean;
begin
result:=(Cardinal(a)<Cardinal(b));
end;
{$I DGL.inc_pas}
end.
|
unit uFrameBaseProps;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cxGraphics, cxCurrencyEdit, cxMaskEdit,
cxDropDownEdit, cxControls, cxContainer, cxEdit, cxTextEdit, uAttributes,
cxMemo, cxPC, DB, ADODB, cxDBEdit, cxLookupEdit, cxDBLookupEdit,
cxDBLookupComboBox, Menus, cxButtonEdit, cxLookAndFeelPainters, cxButtons,
cxCheckBox;
type
TTypeInfoRec = record
L1: string;
L2: string;
end;
TPropsFor = (pfBooks, pfObjects);
TFrameBaseProps = class(TFrame)
pcList: TcxPageControl;
tsList: TcxTabSheet;
memList: TcxMemo;
pcProps: TcxPageControl;
tsProps: TcxTabSheet;
lbName: TLabel;
lbType: TLabel;
lbL1: TLabel;
lbL2: TLabel;
teName: TcxTextEdit;
cbType: TcxComboBox;
ceL1: TcxCurrencyEdit;
ceL2: TcxCurrencyEdit;
qryObjects: TADOQuery;
dsObjects: TDataSource;
lcbObjects: TcxLookupComboBox;
lcbField: TcxLookupComboBox;
dsField: TDataSource;
qryField: TADOQuery;
lblOKOF: TLabel;
beOKOF: TcxButtonEdit;
beObjectSelect: TcxButtonEdit;
lblCanAddRecord: TLabel;
cbCanAddRecord: TcxCheckBox;
lblBuh: TLabel;
beBuh: TcxButtonEdit;
teBuhKod: TcxTextEdit;
private
FAttribute: TCustomAttribute;
FPropsFor: TPropsFor;
procedure SetAttribute(const Value: TCustomAttribute);
{ Private declarations }
protected
public
property Attribute: TCustomAttribute read FAttribute write SetAttribute;
property PropsFor: TPropsFor read FPropsFor write FPropsFor;
procedure SetEditStyle(at: TAttributeType); virtual;
procedure UpdateObjectList; virtual;
procedure OKOFPropertiesButtonClick(AButtonIndex: Integer); virtual;
procedure BuhPropertiesButtonClick(AButtonIndex: Integer); virtual;
procedure ObjectSelectPropertiesButtonClick(AButtonIndex: Integer); virtual;
procedure CanAddRecordClick(Sender: TObject); virtual;
procedure ObjectsPropertiesChange;
constructor Create(AOwner: TComponent); override;
end;
implementation
uses uMain, uAccess, uParams, uFrmOKOF, uException, uDlgObject_selector;
const
TypeInfoRec: array[TAttributeType] of TTypeInfoRec = (
{1} (l1:''; l2:''), //<нет данных>
{2} (l1:''; l2:''), //Адрес
{3} (l1:''; l2:''), //Документ
{4} (l1:''; l2:''), //Целое
{5} (l1:'Длина:'; l2:''), //Строка
{6} (l1:'Значащих цифр:'; l2:'После запятой:'), //Дробное
{7} (l1:''; l2:''), //Логическое
{8} (l1:''; l2:''), //Дата
{9} (l1:''; l2:''), //Время
{10} (l1:''; l2:''), //ДатаВремя
{11} (l1:''; l2:''), //Изображение
{12} (l1:''; l2:''), //Список
{13} (l1:''; l2:''), //Подчиненный список - не поддерживается
{14} (l1:''; l2:''), //Категория (только для GUI)
{15} (l1:'Справочник:'; l2:'Ссылка на поле:'), //Справочник
{16} (l1:''; l2:''), //Пользовательская таблица (только для GUI)
{17} (l1:''; l2:''), //Дочерний объект
{18} (l1:'Объект:'; l2:'') //Ссылка на объект
);
{$R *.dfm}
{ TFrameBaseProps }
procedure TFrameBaseProps.SetAttribute(const Value: TCustomAttribute);
var
cbCanAddRecordOnClick_old: TNotifyEvent;
begin
FAttribute:=Value;
SetEditStyle(Value.AttrType);
teName.Text:=Value.Name;
beObjectSelect.Text:=Value.ObjectLinkName;
cbType.ItemIndex:=byte(Value.AttrType);
ceL1.Value:=Value.L1;
ceL2.Value:=Value.L2;
if Value.AttrType=atList then begin
Value.LoadListItems;
memList.Lines.Assign(Value.ListItems);
end
else
memList.Text:=Value.OkofName;
if Value.AttrType=atBook then begin
self.lcbObjects.EditValue:=Value.L1;
self.lcbField.EditValue:=Value.L2;
end;
if Value.IsChilded and (Value.AttrType in [atCategory, atSubList, atObjectLink]) then begin
teName.Enabled:=false;
cbType.Enabled:=false;
end else begin
teName.Enabled:=true;
cbType.Enabled:=true;
end;
beOKOF.Text:=Value.OkofKOD;
cbCanAddRecordOnClick_old:=cbCanAddRecord.OnClick;
try
cbCanAddRecord.OnClick:=nil;
cbCanAddRecord.Checked:=Value.CanAddRecord;
finally
cbCanAddRecord.OnClick:=cbCanAddRecordOnClick_old;
end;
beBuh.Text:=Value.BuhName;
teBuhKod.Text:=Value.BuhKod;
end;
procedure TFrameBaseProps.SetEditStyle(at: TAttributeType);
var
l1, l2: string;
begin
l1:=TypeInfoRec[at].L1;
l2:=TypeInfoRec[at].L2;
lbL1.Caption:=l1;
lbL2.Caption:=l2;
lbL1.Visible:=l1<>'';
lbL2.Visible:=l2<>'';
ceL1.Visible:=(l1<>'') and (not (at=atBook));
ceL2.Visible:=l2<>'';
if at=atList then begin
pcList.Visible:=true;
tsList.Caption:='Список';
memList.Properties.ReadOnly:=false;
memList.Properties.WordWrap:=false;
end
else
if (at in [atTable, atChildObject, atObjectLink]) and (PropsFor=pfObjects) then begin
pcList.Visible:=true;
tsList.Caption:='Значение ОКОФ';
memList.Properties.ReadOnly:=true;
memList.Properties.WordWrap:=true;
lblCanAddRecord.Visible:=true;
cbCanAddRecord.Visible:=true;
lblBuh.Visible:=true;
beBuh.Visible:=true;
teBuhKod.Visible:=true;
end
else begin
pcList.Visible:=false;
lblCanAddRecord.Visible:=false;
cbCanAddRecord.Visible:=false;
lblBuh.Visible:=false;
beBuh.Visible:=false;
teBuhKod.Visible:=false;
end;
self.lcbObjects.Visible:=at=atBook;
self.lcbField.Visible:=at=atBook;
if (at in [atTable, atChildObject]) and (PropsFor=pfObjects) then begin
lblOKOF.Visible:=true;
beOKOF.Visible:=true;
end
else begin
lblOKOF.Visible:=false;
beOKOF.Visible:=false;
end;
if at=atObjectLink then begin
beObjectSelect.Visible:=true;
// teName.Properties.ReadOnly:=true;
end else begin
beObjectSelect.Visible:=false;
// teName.Properties.ReadOnly:=false;
end
end;
procedure TFrameBaseProps.UpdateObjectList;
begin
qryObjects.Close;
qryObjects.Open;
end;
constructor TFrameBaseProps.Create(AOwner: TComponent);
begin
inherited;
qryObjects.Connection:=frmMain.ADOConnection;
qryField.Connection:=frmMain.ADOConnection;
// (self.lcbObjects.Properties as TcxLookupComboBoxProperties).OnChange:=lcbObjectsPropertiesChange;
UpdateObjectList;
end;
procedure TFrameBaseProps.OKOFPropertiesButtonClick(
AButtonIndex: Integer);
var
a: TAccessSelectorForm;
p: TParamCollection;
begin
if AButtonIndex = 0 then begin
Attribute.OkofID:=0;
Attribute.OkofKOD:='';
Attribute.OkofName:='';
beOKOF.Text:='';
memList.Text:='';
end;
if AButtonIndex = 1 then begin
if Assigned(Attribute.ParentAttribute) and (Attribute.ParentAttribute.OkofID=0) then
raise EOKOFNotAssignedToParentException.Create('Нельзя привязывать объект к разделу ОКОФ пока не будет привязан его родитель');
a:=TAccessSelectorForm.Create;
a.ObjectID:=9;
a.FormClass:=TfrmOKOF;
p:=TParamCollection.Create(TParamItem);
try
p.Add('код_ОКОФ').Value:=Attribute.OkofID;
p.Add('Код');
p.Add('Наименование');
if Assigned(Attribute.ParentAttribute) then
p['код_ОКОФ_Родитель'].Value:=Attribute.ParentAttribute.OkofID;
if a.ShowModal(p, null)<>mrOK then exit;
Attribute.OkofID:=p['код_ОКОФ'].Value;
Attribute.OkofKOD:=p['Код'].Value;
Attribute.OkofName:=p['Наименование'].Value;
beOKOF.Text:=p['Код'].Value;
memList.Text:=p['Наименование'].Value;
Attribute.Updated:=true;
finally
p.Free;
end;
end;
end;
procedure TFrameBaseProps.ObjectSelectPropertiesButtonClick(
AButtonIndex: Integer);
var
dlg: TdlgObject_selector;
begin
dlg:=TdlgObject_selector.Create(nil);
try
dlg.FrameObjects.CreateTree(-1, 'объект', true);
if dlg.ShowModal<>mrOK then exit;
if teName.Text = 'Без имени' then
teName.Text:=dlg.SelectedObjectName;
beObjectSelect.Text:=dlg.SelectedObjectName;
Attribute.L1:=dlg.SelectedObjectID;
Attribute.ObjectLinkName:=beObjectSelect.Text;
finally
dlg.Free;
end
end;
procedure TFrameBaseProps.ObjectsPropertiesChange;
begin
qryField.Close;
if qryObjects.Active and (qryObjects.RecordCount>0) then begin
qryField.SQL.Text:='sp_ОбъектыАтрибутыДляВыбора_получить @код_Объект = '+IntToStr(lcbObjects.EditValue);
qryField.Open;
end
end;
procedure TFrameBaseProps.CanAddRecordClick(Sender: TObject);
begin
Attribute.CanAddRecord:=cbCanAddRecord.Checked;
Attribute.Updated:=true;
end;
procedure TFrameBaseProps.BuhPropertiesButtonClick(AButtonIndex: Integer);
var
a: TAccessSelectorForm;
begin
if AButtonIndex = 0 then begin
Attribute.BuhID:=0;
Attribute.BuhName:='';
beBuh.Text:='';
teBuhKod.Text:='';
end;
if AButtonIndex = 1 then begin
a:=TAccessSelectorForm.Create;
a.ObjectID:=512;
if a.ShowModal(nil, Attribute.BuhID)<>mrOK then exit;
Attribute.BuhID:=a.CurRecordValues['Бухгалтерские счета имущества казны.код_Бухгалтерские счета имущества казны'].Value;
Attribute.BuhName:=a.CurRecordValues['Бухгалтерские счета имущества казны.Название счета'].Value;
Attribute.BuhKod:=a.CurRecordValues['Бухгалтерские счета имущества казны.Счет'].Value;
beBuh.Text:=Attribute.BuhName;
teBuhKod.Text:=Attribute.BuhKod;
Attribute.Updated:=true;
end;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.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. }
{ }
{***************************************************************************}
unit DPM.Core.Packaging;
interface
uses
System.SysUtils,
System.Classes,
Spring.Container.Common,
Spring.Collections,
VSoft.CancellationToken,
DPM.Core.Options.Pack,
DPM.Core.Types,
DPM.Core.TargetPlatform,
DPM.Core.Packaging.Archive;
type
{$M+}
IPackageWriter = interface
['{10944B58-5766-4B73-9C7F-C8488151E42B}']
function WritePackageFromSpec(const cancellationToken : ICancellationToken; const options : TPackOptions) : boolean;
end;
implementation
end.
|
object fmFileList: TfmFileList
Left = 453
Top = 213
ActiveControl = eName
BorderStyle = bsDialog
Caption = 'File List'
ClientHeight = 285
ClientWidth = 306
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object lb: TListBox
Left = 8
Top = 36
Width = 213
Height = 245
ItemHeight = 13
Sorted = True
TabOrder = 1
OnClick = lbClick
OnDblClick = btnOKClick
end
object btnOK: TButton
Left = 228
Top = 12
Width = 75
Height = 23
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 2
OnClick = btnOKClick
end
object btnCancel: TButton
Left = 228
Top = 40
Width = 75
Height = 23
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 3
end
object eName: TEdit
Left = 8
Top = 12
Width = 213
Height = 21
TabOrder = 0
OnChange = eNameChange
OnKeyDown = eNameKeyDown
end
end
|
{*************************************************************
Author: Stéphane Vander Clock (SVanderClock@Arkadia.com)
www: http://www.arkadia.com
EMail: SVanderClock@Arkadia.com
product: Alcinoe ALCommon Unit
Version: 3.05
Description: Misc definition type or const for Alcinoe component
Legal issues: Copyright (C) 1999-2005 by Arkadia Software Engineering
This software is provided 'as-is', without any express
or implied warranty. In no event will the author be
held liable for any damages arising from the use of
this software.
Permission is granted to anyone to use this software
for any purpose, including commercial applications,
and to alter it and redistribute it freely, subject
to the following restrictions:
1. The origin of this software must not be
misrepresented, you must not claim that you wrote
the original software. If you use this software in
a product, an acknowledgment in the product
documentation would be appreciated but is not
required.
2. Altered source versions must be plainly marked as
such, and must not be misrepresented as being the
original software.
3. This notice may not be removed or altered from any
source distribution.
4. You must register this software by sending a picture
postcard to the author. Use a nice stamp and mention
your name, street address, EMail address and any
comment you like to say.
Know bug :
History :
Link :
Please send all your feedback to SVanderClock@Arkadia.com
**************************************************************}
unit ALCommon;
interface
type
{---------------------------------------------------------------------------}
TAlPaintEvent = procedure (Sender: TObject; var continue: boolean) of object;
implementation
end.
|
(******************************************************************************
Autor : José Fábio Nascimento de Almeida
e-mail : fabio@interativasoft.com.br ; fabiorecife@yahoo.com.br
data criação: 21/12/2005
Responsabilidade : Testar as classes de uJSON
Arquivo : uJSON.pas
*******************************************************************************)
unit uTestJSON;
interface
uses TestFramework;
Type
TTestJSONObject = class (TTestCase)
published
procedure testCreateString;
procedure testCreate;
procedure testCreateTStringList;
procedure testCreateJSONObject_ArrayOfString;
procedure testAccumulate;
procedure testAssignTo;
procedure testClean;
procedure testNames ;
procedure testOptInt ;
procedure testUnicodCaracters;
end;
implementation
uses uJSON, SysUtils, Classes;
{ TTestJSONObject }
procedure TTestJSONObject.testAccumulate;
var
json : TJSONObject;
jarray : TJSONArray;
i : integer;
begin
try
json := TJSONObject.create ();
try
// primeiro valor
json.accumulate('array',_Integer.create(0));
Check(json.opt('array')<> nil,'accumulate não funcionou');
CheckEquals(0,json.optInt('array'),'valor errado');
//segundo valor
json.accumulate('array',_Integer.create(1));
CheckEquals(2,json.optJSONArray ('array').length,'quantidade errado');
jarray := json.optJSONArray ('array');
i := jarray.getInt(0);
CheckEquals(0,i,'quantidade errado');
CheckEquals(1,json.optJSONArray ('array').getInt(1),'valor errado');
finally
json.free;
end;
except
on e: exception do begin
Fail('Create '#10#13+e.Message);
end;
end;
end;
procedure TTestJSONObject.testAssignTo;
var
json, jo : TJSONObject;
begin
try
try
jo := TJSONObject.create ('{exemplo:"valor", inteiro:1}');
json := TJSONObject.create;
jo.assignTo(json);
CheckEquals(1,json.getInt('inteiro'));
except
on e: exception do begin
Fail('assignTo '#10#13+e.Message);
end;
end;
finally
if (Assigned (json)) then json.free;
if (Assigned(jo)) then jo.free
end;
end;
procedure TTestJSONObject.testClean;
var
json : TJSONObject;
begin
try
try
json := TJSONObject.create ('{exemplo:[1,2,3]}');
checkTrue (json.opt('exemplo') <> nil);
checkEquals (3,json.getJSONArray('exemplo').length);
json.clean;
checkTrue (json.opt('exemplo') = nil);
except
on e: exception do begin
Fail('testClean '#10#13+e.Message);
end;
end;
finally
if Assigned(json) then json.free;
end;
end;
procedure TTestJSONObject.testCreate;
var
json : TJSONObject;
begin
try
try
json := TJSONObject.create ();
CheckTrue(json<>nil);
except
on e: exception do begin
Fail('Create '#10#13+e.Message);
end;
end;
finally
if Assigned(json) then json.free;
end;
end;
procedure TTestJSONObject.testCreateJSONObject_ArrayOfString;
var
json, jo : TJSONObject;
begin
try
jo := TJSONObject.create ('{exemplo:"valor", inteiro:1}');
json := TJSONObject.create (jo,['exemplo']);
try
CheckTrue(json.opt('exemplo')<>nil);
CheckTrue(json.opt('inteiro')=nil);
finally
json.free;
jo.free;
end;
except
on e: exception do begin
fail ('Create ( TJSONObject, Array of String ...'+#10#13+e.Message);
end;
end;
end;
procedure TTestJSONObject.testCreateString;
var
json : TJSONObject;
begin
try
json := TJSONObject.create ('{exemplo:"valor", inteiro:1}');
try
CheckTrue(json.opt('exemplo')<>nil);
finally
json.free;
end;
except
on e: exception do begin
fail ('Create ( String ...'+#10#13+e.Message);
end;
end;
end;
procedure TTestJSONObject.testCreateTStringList;
var
json : TJSONObject;
s : TStringList;
begin
try
s := TStringlist.create;
s.AddObject('exemplo',_String.create('valor'));
s.AddObject('inteiro',_Integer.create(1));
json := TJSONObject.create (s);
try
CheckEquals('valor',json.getString('exemplo'));
CheckEquals(1,json.getInt('inteiro'));
finally
json.free;
s.free;
end;
except
on e: exception do begin
fail ('Create (map...'+#10#13+e.Message);
end;
end;
end;
procedure TTestJSONObject.testNames;
var
json : TJSONObject;
a : TJSONArray;
begin
try
try
json := TJSONObject.create ('{exemplo:"valor", inteiro:1}');
a := json.names;
checkEquals (2, a.length);
except
on e: exception do begin
Fail('Create '#10#13+e.Message);
end;
end;
finally
if Assigned(json) then json.free;
if Assigned (a) then a.free;
end;
end;
procedure TTestJSONObject.testOptInt;
var
json : TJSONObject;
begin
try
try
json := TJSONObject.create ('{exemplo:"valor", inteiro:"1"}');
CheckEquals(1,json.optInt ('inteiro'));
except
on e: exception do begin
Fail('Create '#10#13+e.Message);
end;
end;
finally
if Assigned(json) then json.free;
end;
end;
procedure TTestJSONObject.testUnicodCaracters;
var
json : TJSONObject;
begin
json := TJSONObject.create ('{exemplo:"\u0046\u0041\u0042\u0049\u004F"}');
checkEquals('FABIO',json.getString('exemplo'));
end;
initialization
RegisterTest('JSON', TTestJSONObject.Suite);
end.
|
unit o_MailLesen;
interface
uses
SysUtils, Classes,
IdMessage, IdPOP3, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase,
IdMessageClient, IdSMTPBase, IdSMTP, Vcl.StdCtrls, IdIOHandler,
IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdGlobal;
type
TMailLesen = class(TObject)
private
FPop3: TIdPOP3;
FSmtp: TIdSMTP;
FMsg: TIdMessage;
FIOHandler: TIdSSLIOHandlerSocketOpenSSL;
//FIOHandler: TIdSSLIOHandlerSocketBase;
FMeineEmail: string;
FMeinPasswort: string;
FBetreff: string;
FNachricht: string;
FEMailAdresse: string;
procedure LeseEMail;
public
constructor Create;
destructor Destroy; override;
property MeineEMail: string read FMeineEmail write FMeineEMail;
property MeinPasswort: string read FMeinPasswort write FMeinPasswort;
property Betreff: string read FBetreff write FBetreff;
property Nachricht: string read FNachricht write FNachricht;
property EMailAdresse: string read FEMailAdresse write FEMailAdresse;
procedure UeberWebDe;
procedure UeberGMail;
end;
implementation
{ TMailLesen }
uses
Dialogs;
constructor TMailLesen.Create;
begin
inherited;
FSmtp := TIdSMTP.Create(nil);
FMsg := TIdMessage.Create(nil);
FIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
FPop3 := TIdPOP3.Create(nil);
//FSmtp.IOHandler := FIOHandler;
FPop3.IOHandler := FIOHandler;
FMeineEmail := '';
FMeinPasswort := '';
FBetreff := '';
FNachricht := '';
FEMailAdresse := '';
end;
destructor TMailLesen.Destroy;
begin
FreeAndNil(FPop3);
FreeAndNil(FSmtp);
FreeAndNil(FMsg);
FreeAndNil(FIOHandler);
inherited;
end;
procedure TMailLesen.LeseEMail;
var
MailCount: Integer;
begin
FPop3.Connect;
MailCount := FPop3.CheckMessages;
ShowMessage(IntToStr(MailCount));
end;
procedure TMailLesen.UeberGMail;
begin
//FPop3.Host := 'imap.gmail.com';
FPop3.Host := 'pop.gmail.com';
FPop3.Port := 995;
FPop3.Username := FMeineEMail;
FPop3.Password := FMeinPasswort;
FPOP3.UseTLS := utUseExplicitTLS;
FIOHandler.Host := FPop3.Host;
FIOHandler.Destination := FPop3.Host + ':995';
FIOHandler.DefaultPort := 0;
FIOHandler.SSLOptions.Method := sslvSSLv3;
FIOHandler.SSLOptions.Mode := sslmUnassigned;
FIOHandler.SSLOptions.VerifyMode := [];
FIOHandler.SSLOptions.VerifyDepth := 0;
LeseEMail;
end;
procedure TMailLesen.UeberWebDe;
begin
end;
end.
|
unit uDemoViewFrameTipo1;
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.Controls.Presentation, FMX.ScrollBox, FMX.Memo,
uInterfaces,
uAtributos,
uDemoInterfaces,
uDemoViewModels,
uTypes,
uView;
type
[ViewForVM(IMyViewModel1, TMyViewModel1)]
TFrame1 = class(TFrameView<IMyViewModel1, TMyViewModel1>)
Memo1: TMemo;
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function GetVM_AsInterface: IMyViewModel1; override;
function GetVM_AsObject: TMyViewModel1; override;
end;
implementation
{$R *.fmx}
{ TFrame1 }
procedure TFrame1.Button1Click(Sender: TObject);
begin
Memo1.Lines.Add(GetVM_AsInterface.Hello1);
end;
function TFrame1.GetVM_AsInterface: IMyViewModel1;
begin
Result := FViewModel as IMyViewModel1
end;
function TFrame1.GetVM_AsObject: TMyViewModel1;
begin
Result := FViewModel as TMyViewModel1;
end;
end.
|
unit ibSHRegisterFrm;
interface
uses
SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHComponentFrm,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Grids, TypInfo, AppEvnts, ELPropInsp;
type
TRegisterType = (rtUnknown, rtServer, rtDatabase, rtCreate, rtInfo);
TibBTRegisterForm = class(TibBTComponentForm)
Panel1: TPanel;
Panel2: TPanel;
CheckBox1: TCheckBox;
PropInspector: TELPropertyInspector;
Bevel1: TBevel;
Button1: TButton;
ApplicationEvents1: TApplicationEvents;
procedure PropInspectorFilterProp(Sender: TObject;
AInstance: TPersistent; APropInfo: PPropInfo;
var AIncludeProp: Boolean);
procedure PropInspectorGetEditorClass(Sender: TObject;
AInstance: TPersistent; APropInfo: PPropInfo;
var AEditorClass: TELPropEditorClass);
procedure Panel2Resize(Sender: TObject);
procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FPropSavedList: TStrings;
FRegisterType: TRegisterType;
FTestConnection: ISHTestConnection;
procedure DoShowProps(AInspector: TELPropertyInspector; APersistent: TPersistent);
protected
procedure DoOnIdle; override;
procedure DoOnBeforeModalClose(Sender: TObject; var ModalResult: TModalResult;
var Action: TCloseAction); override;
procedure DoOnAfterModalClose(Sender: TObject; ModalResult: TModalResult); override;
public
{ Public declarations }
constructor Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string); override;
destructor Destroy; override;
function ReceiveEvent(AEvent: TSHEvent): Boolean; override;
end;
var
ibBTRegisterForm: TibBTRegisterForm;
implementation
uses
ibSHConsts;
{$R *.dfm}
{ TibBTRegisterForm }
constructor TibBTRegisterForm.Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string);
begin
inherited Create(AOwner, AParent, AComponent, ACallString);
FPropSavedList := TStringList.Create;
FRegisterType := TRegisterType(Component.Tag);
Supports(Component, ISHTestConnection, FTestConnection);
DoShowProps(PropInspector, Component);
Designer.GetPropValues(Component, Component.ClassName, FPropSavedList);
if Assigned(ModalForm) then
begin
// ModalForm.EnabledOK := False;
SetFormSize(380, 440);
if Assigned(Parent) and (Parent is TPanel) then TPanel(Parent).BevelInner := bvNone;
case FRegisterType of
rtServer: ModalForm.CaptionOK := Format('%s', [SBtnRegister]);
rtDatabase: ModalForm.CaptionOK := Format('%s', [SBtnRegister]);
rtCreate: ModalForm.CaptionOK := Format('%s', [SBtnCreate]);
rtInfo: ModalForm.CaptionOK := Format('%s', [SBtnSave]);
end;
end;
case FRegisterType of
rtServer:
begin
Caption := Format('%s', [SCallRegisterServer]);
CheckBox1.Caption := Format('%s', [SBtnRegisterAfterRegister]);
end;
rtDatabase:
begin
Caption := Format('%s', [SCallRegisterDatabase]);
CheckBox1.Caption := Format('%s', [SBtnConnectAfterRegister]);
CheckBox1.Checked := False;
end;
rtCreate:
begin
Caption := Format('%s', [SCallCreateDatabase]);
CheckBox1.Caption := Format('%s', [SBtnRegisterAfterCreate]);
end;
rtInfo:
begin
Caption := Format('%s', [SCallRegisterInfo]);
CheckBox1.Visible := False;
end;
end;
if FRegisterType = rtInfo then
begin
if Supports(Component, ISHServer) then PropInspector.ReadOnly := Designer.CurrentServerInUse;
if Supports(Component, ISHDatabase) then PropInspector.ReadOnly := Designer.CurrentDatabaseInUse;
Panel2.Visible := not PropInspector.ReadOnly;
end;
end;
destructor TibBTRegisterForm.Destroy;
begin
FPropSavedList.Free;
inherited Destroy;
end;
procedure TibBTRegisterForm.DoShowProps(AInspector: TELPropertyInspector;
APersistent: TPersistent);
var
AList: TList;
begin
AList := TList.Create;
try
if Assigned(AInspector) then
with AInspector do
begin
BeginUpdate;
if Assigned(APersistent) then
begin
AList.Add(APersistent);
Objects.SetObjects(AList);
end else
Objects.Clear;
EndUpdate;
end;
finally
AList.Free;
end;
end;
function TibBTRegisterForm.ReceiveEvent(AEvent: TSHEvent): Boolean;
begin
case AEvent.Event of
SHE_REFRESH_OBJECT_INSPECTOR: PropInspector.UpdateItems;
end;
Result := True;
end;
procedure TibBTRegisterForm.DoOnIdle;
begin
if not (csDestroying in Self.ComponentState) then
begin
Button1.Enabled := FTestConnection.CanTestConnection;
if Assigned(ModalForm) then
begin
case FRegisterType of
rtServer, rtDatabase: ModalForm.EnabledOK := True;
rtCreate: ModalForm.EnabledOK := True;
rtInfo: ModalForm.EnabledOK := True;
end;
end;
end;
end;
procedure TibBTRegisterForm.DoOnBeforeModalClose(Sender: TObject; var ModalResult: TModalResult;
var Action: TCloseAction);
begin
if ModalResult = mrOK then
begin
PropInspector.Perform(CM_EXIT, 0, 0);
if CheckBox1.Checked then Component.Tag := 5;
end else
Designer.SetPropValues(Component, Component.ClassName, FPropSavedList);
end;
procedure TibBTRegisterForm.DoOnAfterModalClose(Sender: TObject; ModalResult: TModalResult);
begin
inherited DoOnAfterModalClose(Sender, ModalResult);
end;
procedure TibBTRegisterForm.PropInspectorFilterProp(Sender: TObject;
AInstance: TPersistent; APropInfo: PPropInfo; var AIncludeProp: Boolean);
begin
AIncludeProp := Assigned(Component) and Component.CanShowProperty(APropInfo.Name);
end;
procedure TibBTRegisterForm.PropInspectorGetEditorClass(
Sender: TObject; AInstance: TPersistent; APropInfo: PPropInfo;
var AEditorClass: TELPropEditorClass);
begin
AEditorClass := TELPropEditorClass(Designer._GetProxiEditorClass(
TELPropertyInspector(Sender), AInstance, APropInfo));
end;
procedure TibBTRegisterForm.Panel2Resize(Sender: TObject);
begin
CheckBox1.Width := CheckBox1.Parent.ClientWidth;
end;
procedure TibBTRegisterForm.ApplicationEvents1Idle(Sender: TObject;
var Done: Boolean);
begin
DoOnIdle;
end;
procedure TibBTRegisterForm.Button1Click(Sender: TObject);
begin
if Assigned(FTestConnection) and FTestConnection.CanTestConnection then
FTestConnection.TestConnection;
end;
end.
|
unit XLSHashTrie;
{
Delphi implementation of HashTrie dynamic hashing method
Full description available on www.softlab.od.ua
Delphi 2,3,4,5
Freware with source.
Copyright (c) 2000-2001, SoftLab MIL-TEC Ltd
Web: http://www.softcomplete.com
Email: support@softcomplete.com
THIS SOFTWARE AND THE ACCOMPANYING FILES ARE DISTRIBUTED
"AS IS" AND WITHOUT WARRANTIES AS TO PERFORMANCE OF MERCHANTABILITY OR
ANY OTHER WARRANTIES WHETHER EXPRESSED OR IMPLIED.
NO WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE IS OFFERED.
THE USER MUST ASSUME THE ENTIRE RISK OF USING THE ACCOMPANYING CODE.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented, you must
not claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. Original copyright may not be removed or altered from any source
distribution.
4. All copyright of HashTrie dynamic hashing method belongs to Andre N Belokon,
SoftLab MIL-TEC Ltd.
Changes to original HashTrie Copyright (c) 2004, Axolot Data.
}
interface
uses Windows, SysUtils;
const
// DON'T CHANGE LeafSize VALUE !!! MUST BE EQ 256
// because some code optimization used
LeafSize = 256;
// determines max length of the list
// very big|small values decrease performance
// optimum value in range 4..16
BucketSize = 8;
type PXLSString = ^TXLSString;
TXLSString = record
Index: integer;
RefCount: integer;
Len: word;
Options: byte;
Data: record end;
end;
type
TLinkedItem = class
private
Value: DWORD;
Next: TLinkedItem;
public
constructor Create(FValue: DWORD; FNext: TLinkedItem);
destructor Destroy; override;
end;
THashTrie = class; // forward
TTraverseProc = procedure (UserData,UserProc: Pointer;
Value: DWORD; var Done: Boolean) of object;
TTreeItem = class
private
Owner: THashTrie;
Level: integer;
Filled: integer;
Items: array[0..LeafSize-1] of TObject;
function ROR(Value: DWORD): DWORD;
function RORN(Value: DWORD; Level: integer): DWORD;
procedure AddDown(Value,Hash: DWORD);
procedure Delete(Value,Hash: DWORD);
function Find(Value,Hash: DWORD): Boolean;
function FindVal(Value,Hash: DWORD): Pointer;
function Traverse(UserData,UserProc: Pointer; TraverseProc: TTraverseProc): Boolean;
function GetCount(var Count: integer): Boolean;
procedure Clear;
public
constructor Create(AOwner: THashTrie);
destructor Destroy; override;
end;
THashTrie = class(TObject)
private
Root: TTreeItem;
protected
function HashValue(Value: DWORD): DWORD; virtual; abstract;
procedure DestroyItem(var Value: DWORD); virtual; abstract;
function CompareValue(Value1,Value2: DWORD): Boolean; virtual; abstract;
procedure AddDown(Value,Hash: DWORD);
procedure Delete(Value,Hash: DWORD);
function Find(Value,Hash: DWORD): Boolean;
function FindVal(Value,Hash: DWORD): Pointer;
procedure Traverse(UserData,UserProc: Pointer; TraverseProc: TTraverseProc);
public
constructor Create;
destructor Destroy; override;
procedure ClearTree;
function Count: integer;
end;
TSSTHashTraverseProc = procedure (UserData: Pointer; const Value: PXLSString; var Done: Boolean);
TSSTHashTraverseMeth = procedure (UserData: Pointer; const Value: PXLSString; var Done: Boolean) of object;
TSSTHashTrie = class(THashTrie)
private
protected
function HashValue(Value: DWORD): DWORD; override;
procedure DestroyItem(var Value: DWORD); override;
function CompareValue(Value1,Value2: DWORD): Boolean; override;
function HashStr(P: PXLSString): DWORD;
procedure TraverseProc(UserData,UserProc: Pointer; Value: DWORD; var Done: Boolean);
procedure TraverseMeth(UserData,UserProc: Pointer; Value: DWORD; var Done: Boolean);
function GetSize(Value: PXLSString): integer; virtual; abstract;
function GetDataPointer(Value: PXLSString): PByteArray; virtual; abstract;
public
function Add(P: PXLSString): PXLSString;
procedure Delete(P: PXLSString);
function FindVal(P: PXLSString; Hash: DWORD): PXLSString;
procedure Traverse(UserData: Pointer; UserProc: TSSTHashTraverseProc); overload;
procedure Traverse(UserData: Pointer; UserProc: TSSTHashTraverseMeth); overload;
end;
function CalcStrCRC32(const S: string): DWORD;
implementation
{ TTreeItem }
procedure TTreeItem.AddDown(Value, Hash: DWORD);
var i,j: integer;
TreeItem: TTreeItem;
LinkedItem: TLinkedItem;
begin
i:=Hash and $FF;
if Items[i] = nil then begin
Items[i]:=TLinkedItem.Create(Value,nil);
Inc(Filled);
end else if Items[i] is TTreeItem then begin
TTreeItem(Items[i]).AddDown(Value,ROR(Hash));
end else begin
j:=0;
LinkedItem:=TLinkedItem(Items[i]);
while LinkedItem <> nil do begin
if Owner.CompareValue(LinkedItem.Value,Value) then begin
// found
Exit;
end;
LinkedItem:=LinkedItem.Next;
Inc(j)
end;
if j >= BucketSize then begin
// full
TreeItem:=TTreeItem.Create(Owner);
TreeItem.Level:=Level+1;
LinkedItem:=TLinkedItem(Items[i]);
while LinkedItem <> nil do begin
TreeItem.AddDown(LinkedItem.Value,
RORN(Owner.HashValue(LinkedItem.Value), Level+1));
LinkedItem:=LinkedItem.Next;
end;
TreeItem.AddDown(Value,ROR(Hash));
TLinkedItem(Items[i]).Free;
Items[i]:=TreeItem;
end else
Items[i]:=TLinkedItem.Create(Value,TLinkedItem(Items[i]));
end;
end;
procedure TTreeItem.Clear;
var
j: integer;
LinkedItem: TLinkedItem;
begin
for j:=0 to LeafSize-1 do begin
if Items[j] <> nil then begin
if Items[j] is TTreeItem then begin
TTreeItem(Items[j]).Free;
Items[j] := Nil;
end
else begin
LinkedItem:=TLinkedItem(Items[j]);
while LinkedItem <> nil do begin
Owner.DestroyItem(LinkedItem.Value);
LinkedItem:=LinkedItem.Next;
end;
TLinkedItem(Items[j]).Free;
Items[j] := Nil;
end;
end;
end;
end;
constructor TTreeItem.Create(AOwner: THashTrie);
var j: integer;
begin
Owner:=AOwner;
Level:=0;
Filled:=0;
for j:=0 to LeafSize-1 do Items[j]:=nil;
end;
procedure TTreeItem.Delete(Value, Hash: DWORD);
var i: integer;
PrevLinkedItem,LinkedItem: TLinkedItem;
begin
i:=Hash and $FF;
if Items[i] = nil then begin
Exit;
end else if Items[i] is TTreeItem then begin
TTreeItem(Items[i]).Delete(Value,ROR(Hash));
if TTreeItem(Items[i]).Filled = 0 then begin
TTreeItem(Items[i]).Free;
Items[i]:=nil;
end;
end else begin
PrevLinkedItem:=nil;
LinkedItem:=TLinkedItem(Items[i]);
while LinkedItem <> nil do begin
if Owner.CompareValue(LinkedItem.Value,Value) then begin
// found
if PrevLinkedItem = nil then begin
Items[i]:=LinkedItem.Next;
if Items[i] = nil then
Dec(Filled);
end else
PrevLinkedItem.Next:=LinkedItem.Next;
LinkedItem.Next:=nil;
Owner.DestroyItem(LinkedItem.Value);
LinkedItem.Free;
Exit;
end;
PrevLinkedItem:=LinkedItem;
LinkedItem:=LinkedItem.Next;
end;
end;
end;
destructor TTreeItem.Destroy;
begin
Clear;
inherited;
end;
function TTreeItem.Find(Value, Hash: DWORD): Boolean;
var i: integer;
LinkedItem: TLinkedItem;
begin
Result:=False;
i:=Hash and $FF;
if Items[i] = nil then begin
Exit;
end else if Items[i] is TTreeItem then begin
Result:=TTreeItem(Items[i]).Find(Value,ROR(Hash));
end else begin
LinkedItem:=TLinkedItem(Items[i]);
while LinkedItem <> nil do begin
if Owner.CompareValue(LinkedItem.Value,Value) then begin
// found
Result:=True;
Exit;
end;
LinkedItem:=LinkedItem.Next;
end;
end;
end;
function TTreeItem.FindVal(Value, Hash: DWORD): Pointer;
var i: integer;
LinkedItem: TLinkedItem;
begin
Result:=Nil;
i:=Hash and $FF;
if Items[i] = nil then begin
Exit;
end else if Items[i] is TTreeItem then begin
Result:=TTreeItem(Items[i]).FindVal(Value,ROR(Hash));
end else begin
LinkedItem:=TLinkedItem(Items[i]);
while LinkedItem <> nil do begin
if Owner.CompareValue(LinkedItem.Value,Value) then begin
// found
Result:=Pointer(LinkedItem.Value);
Exit;
end;
LinkedItem:=LinkedItem.Next;
end;
end;
end;
function TTreeItem.GetCount(var Count: integer): Boolean;
var j: integer;
LinkedItem: TLinkedItem;
begin
Result := False;
for j:=0 to LeafSize-1 do
if Items[j] <> nil then begin
if Items[j] is TTreeItem then begin
Result := TTreeItem(Items[j]).GetCount(Count);
end else begin
LinkedItem := TLinkedItem(Items[j]);
while LinkedItem <> nil do begin
Inc(Count);
LinkedItem:=LinkedItem.Next;
end;
end;
if Result then
Exit;
end;
end;
function TTreeItem.ROR(Value: DWORD): DWORD;
begin
Result:=((Value and $FF) shl 24) or ((Value shr 8) and $FFFFFF);
end;
function TTreeItem.RORN(Value: DWORD; Level: integer): DWORD;
begin
Result:=Value;
while Level > 0 do begin
Result:=ROR(Result);
Dec(Level);
end;
end;
function TTreeItem.Traverse(UserData,UserProc: Pointer;
TraverseProc: TTraverseProc): Boolean;
var j: integer;
LinkedItem: TLinkedItem;
begin
Result:=False;
for j:=0 to LeafSize-1 do
if Items[j] <> nil then begin
if Items[j] is TTreeItem then begin
Result:=TTreeItem(Items[j]).Traverse(UserData,UserProc,TraverseProc);
end else begin
LinkedItem:=TLinkedItem(Items[j]);
while LinkedItem <> nil do begin
TraverseProc(UserData,UserProc,LinkedItem.Value,Result);
LinkedItem:=LinkedItem.Next;
end;
end;
if Result then Exit;
end;
end;
{ TLinkedItem }
constructor TLinkedItem.Create(FValue: DWORD; FNext: TLinkedItem);
begin
Value:=FValue;
Next:=FNext;
end;
destructor TLinkedItem.Destroy;
begin
if Next <> nil then
Next.Free;
end;
{ THashTrie }
procedure THashTrie.AddDown(Value,Hash: DWORD);
begin
if Root = nil then
Root:=TTreeItem.Create(Self);
Root.AddDown(Value,Hash);
end;
procedure THashTrie.Delete(Value,Hash: DWORD);
begin
if Root <> nil then
Root.Delete(Value,Hash);
end;
function THashTrie.Find(Value,Hash: DWORD): Boolean;
begin
if Root <> nil then
Result:=Root.Find(Value,Hash)
else
Result:=False;
end;
constructor THashTrie.Create;
begin
inherited;
Root:=nil;
end;
destructor THashTrie.Destroy;
begin
if Root <> nil then Root.Free;
inherited;
end;
procedure THashTrie.Traverse(UserData, UserProc: Pointer;
TraverseProc: TTraverseProc);
begin
if Root <> nil then
Root.Traverse(UserData, UserProc, TraverseProc);
end;
function THashTrie.FindVal(Value, Hash: DWORD): Pointer;
begin
if Root <> nil then
Result:=Root.FindVal(Value,Hash)
else
Result:=Nil;
end;
procedure THashTrie.ClearTree;
begin
if Root <> Nil then
Root.Clear;
end;
{ dynamic crc32 table }
const
CRC32_POLYNOMIAL = $EDB88320;
var
Ccitt32Table: array[0..255] of DWORD;
function CalcStrCRC32(const S: string): DWORD;
var j: integer;
begin
Result:=$FFFFFFFF;
for j:=1 to Length(S) do
Result:= (((Result shr 8) and $00FFFFFF) xor (Ccitt32Table[(Result xor byte(S[j])) and $FF]));
end;
function CalcStrCRC32P(const P: Pointer; Len: integer): DWORD;
var j: integer;
begin
Result:=$FFFFFFFF;
for j:=0 to Len - 1 do
Result:= (((Result shr 8) and $00FFFFFF) xor (Ccitt32Table[(Result xor PByteArray(P)[j]) and $FF]));
end;
procedure BuildCRCTable;
var i, j: longint;
value: DWORD;
begin
for i := 0 to 255 do begin
value := i;
for j := 8 downto 1 do
if ((value and 1) <> 0) then
value := (value shr 1) xor CRC32_POLYNOMIAL
else
value := value shr 1;
Ccitt32Table[i] := value;
end
end;
function THashTrie.Count: integer;
begin
Result := 0;
if Root <> nil then
Root.GetCount(Result);
end;
{ TSSTHashTrie }
function TSSTHashTrie.Add(P: PXLSString): PXLSString;
var
Hash: DWORD;
begin
Hash := HashStr(P);
Result := FindVal(P,Hash);
if Result <> Nil then begin
Inc(Result.RefCount);
FreeMem(P);
end
else begin
AddDown(DWORD(P),Hash);
Result := P;
end;
end;
function TSSTHashTrie.CompareValue(Value1, Value2: DWORD): Boolean;
var
Sz1,Sz2: integer;
begin
Sz1 := GetSize(PXLSString(Value1));
Sz2 := GetSize(PXLSString(Value2));
if Sz1 = Sz2 then
Result := CompareMem(GetDataPointer(Pointer(Value1)),GetDataPointer(Pointer(Value2)),Sz1)
else
Result := False;
end;
procedure TSSTHashTrie.Delete(P: PXLSString);
var
FoundStr: PXLSString;
begin
FoundStr := FindVal(P,HashStr(P));
if FoundStr <> Nil then begin
Dec(FoundStr.RefCount);
if FoundStr.RefCount <= 0 then
inherited Delete(DWORD(P),HashStr(P));
end;
end;
procedure TSSTHashTrie.DestroyItem(var Value: DWORD);
begin
FreeMem(Pointer(Value));
end;
function TSSTHashTrie.FindVal(P: PXLSString; Hash: DWord): PXLSString;
begin
Result := inherited FindVal(DWORD(P),Hash);
end;
function TSSTHashTrie.HashStr(P: PXLSString): DWORD;
begin
Result:=CalcStrCRC32P(GetDataPointer(P),GetSize(P));
end;
function TSSTHashTrie.HashValue(Value: DWORD): DWORD;
begin
Result:=CalcStrCRC32P(Pointer(Value),GetSize(Pointer(Value)));
end;
procedure TSSTHashTrie.Traverse(UserData: Pointer; UserProc: TSSTHashTraverseProc);
begin
inherited Traverse(UserData,@UserProc,TraverseProc);
end;
procedure TSSTHashTrie.Traverse(UserData: Pointer; UserProc: TSSTHashTraverseMeth);
begin
inherited Traverse(UserData,@TMethod(UserProc),TraverseMeth);
end;
procedure TSSTHashTrie.TraverseMeth(UserData, UserProc: Pointer; Value: DWORD; var Done: Boolean);
type
PTSSTHashTraverseMeth = ^TSSTHashTraverseMeth;
begin
PTSSTHashTraverseMeth(UserProc)^(UserData,PXLSString(Value),Done);
end;
procedure TSSTHashTrie.TraverseProc(UserData, UserProc: Pointer; Value: DWORD; var Done: Boolean);
begin
TSSTHashTraverseProc(UserProc)(UserData,PXLSString(Value),Done);
end;
initialization
BuildCRCTable;
end.
|
{*******************************************************************************
* uCrUtils *
* *
* Вспомогательные утилиты для шифрования *
* Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uCrUtils;
interface
const Hex = '-A;?()BWXQ8$wa+!';
function IntToHex(i: LongWord): String;
function GetIntFromString(var s: String): LongWord;
function GetIntFromHex(var s: String; var Error: Boolean): LongWord;
function IntToString(i: LongWord): String;
function Scramble(i: LongWord): LongWord;
function UnScramble(i: LongWord): LongWord;
function ScrStr(s: String): String;
function UnScrStr(s: String): String;
function RandomHex: Char;
implementation
uses StrUtils;
function RandomHex: Char;
begin
Result := Hex[1+Random(Length(Hex))];
end;
function ScrStr(s: String): String;
var
i: Integer;
c: Char;
begin
Result := '';
for i:=1 to Length(s) do
begin
c := chr((ord(s[i]) + 7*i) mod 256);
Result := Result + c;
end;
end;
function UnScrStr(s: String): String;
var
i: Integer;
c: Char;
begin
Result := '';
for i:=1 to Length(s) do
begin
c := chr((ord(s[i]) - 7*i) mod 256);
Result := Result + c;
end;
end;
function Scramble(i: LongWord): LongWord;
begin
Result := i xor $17061983;
end;
function UnScramble(i: LongWord): LongWord;
begin
Result := i xor $17061983;
end;
function IntToHex(i: LongWord): String;
var
ii, len: LongWord;
begin
Result := '';
while ( i > 0 ) do
begin
Result := Result + Hex[1+i mod 16];
i := i div 16;
end;
len := Length(Result);
for ii:=len to 7 do
Result := Hex[1] + Result;
end;
function GetIntFromString(var s: String): LongWord;
var
i, len: LongWord;
begin
Result := 0;
len := Length(s);
if len > 4 then len := 4;
for i:=1 to len do
begin
Result := Result shl 8;
Result := Result + Ord(s[i]);
end;
s := Copy(s, len+1, Length(s));
end;
function GetIntFromHex(var s: String; var Error: Boolean): LongWord;
var
i, p: LongWord;
begin
Error := False;
if ( Length(s) mod 2 = 1 ) or ( Length(s) < 8 )then
begin
Error := True;
s := '';
Result := 0;
Exit;
end;
Result := 0;
for i:=1 to 8 do
begin
Result := Result shl 4;
p := Pos(s[i], Hex);
if p = 0 then
begin
Error := True;
s := '';
Exit;
end
else Result := Result + p-1;
end;
s := Copy(s, 9, Length(s));
end;
function IntToString(i: LongWord): String;
var
t: LongWord;
begin
Result := '';
while i > 0 do
begin
t := i mod 256;
if t > 0 then
Result := Result + Chr(t);
i := i div 256;
end;
end;
initialization
Randomize;
end.
|
Unit Procesos;
{ * Procesos : *
* *
* Esta unidad se encarga de la creacion y eliminacion de procesos *
* aqui no estan implementadas las llamadas al sistema , *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* *
* 05 / 07 / 04 : Se aplica el modelo de memoria paginada *
* *
* 20 / 03 / 04 : Depuracion *
* *
* 20 / 12 / 03 : Primera Version *
* *
************************************************************************
}
interface
{DEFINE DEBUG}
{DEFINE STAT}
{$I ../include/toro/procesos.inc}
{$I ../include/toro/signal.inc}
{$I ../include/head/asm.h}
{$I ../include/head/gdt.h}
{$I ../include/head/signal.h}
{$I ../include/head/scheduler.h}
{$I ../include/head/open.h}
{$I ../include/head/printk_.h}
{$I ../include/head/paging.h}
{$I ../include/head/vmalloc.h}
{$I ../include/head/inodes.h}
{$I ../include/head/itimer.h}
{$I ../include/head/dcache.h}
{$DEFINE Use_Hash}
{$DEFINE Use_Tail}
{$DEFINE nodo_struct := p_tarea_struc }
{$DEFINE next_nodo := next_tarea }
{$DEFINE prev_nodo := prev_tarea }
{ colas que aqui son manipuladas }
const Tq_WaitPid : p_tarea_struc = nil ;
Tq_Zombies : p_tarea_struc = nil ;
var Pid_T:dword;
Tq_Interrumpidas : p_tarea_struc ;
Hash_Pid : array[1..Max_HashPid] of p_tarea_struc;
procedure proceso_eliminar(Tarea:p_tarea_struc);
procedure proceso_interrumpir(Tarea:p_tarea_struc ; var Cola : p_tarea_struc);
procedure proceso_reanudar(Tarea:p_tarea_struc;var Cola : p_tarea_struc );
implementation
{$I ../include/head/list.h}
{$I ../include/head/lock.h}
function nuevo_pid:dword;
begin
pid_t += 1;
exit (pid_t);
end;
{ * Thread_Crear : *
* *
* Kernel_Ip : Puntero a codigo del kernel *
* Retorno : puntero al thread o nil se falla *
* *
* Funcion que crea un thread de kernel , por ahora no estan implemen *
* tados dentro del sistema *
* *
***********************************************************************
}
function thread_crear(Kernel_IP:pointer):p_tarea_struc;[public , alias : 'THREAD_CREAR'];
var stack,stack0:pointer;
nuevo_tss,cont:word;
tmp:^struc_descriptor;
begin
{ son protegidos los recursos }
Gdt_Lock;
Mem_Lock;
If ( Gdt_Huecos_Libres = 0 ) then
begin
Gdt_Unlock;
Mem_Unlock;
exit(nil);
end;
If (nr_free_page < 3) then
begin
Gdt_Unlock;
Mem_Unlock;
exit(nil);
end;
{ Se pide memoria para la imagen de thread y el stack }
Thread_Crear := get_free_kpage;
stack := get_free_kpage;
nuevo_tss := Gdt_Set_Tss(@Thread_Crear^.reg);
{ son liberados los recursos }
Mem_Unlock;
Gdt_Unlock;
with Thread_Crear^ do
begin
Politica := Sched_RR;
pid := Nuevo_Pid;
Padre_Pid := 0;
quantum_a := 0;
tss_Descp := nuevo_tss;
tss_p := pointer(GDT_NUEVA +(nuevo_tss -1 )*8);
dir_page:= Kernel_Pdt;
reg.cr3 := Kernel_Pdt;
reg.cs := KERNEL_CODE_SEL;
reg.ds := KERNEL_DATA_SEL;
reg.es := KERNEL_DATA_SEL;
reg.gs := KERNEL_DATA_SEL;
reg.ss := KERNEL_DATA_SEL;
reg.fs := KERNEL_DATA_SEL;
reg.esp := stack + Page_Size - 1;
reg.eip := Kernel_IP;
reg.eflags := $202;
flags_de_signal := 0;
virtual_time := 0 ;
real_time := contador ;
nice := 0 ;
for cont:= 0 to NR_OPEN do Archivos[cont].f_op := nil;
end;
{$IFDEF DEBUG}
printk('/nThread Nuevo ---> Pid /V %d \n',[Thread_Crear^.pid],[]);
{$ENDIF}
add_task(Thread_Crear);
exit(Thread_Crear);
end;
{ * Proceso_Crear : *
* *
* Ppid : Pid del Padre *
* Politica : Politica para la planif el proceso *
* *
* Esta funcion devuelve un puntero a una nueva tarea , esta es creada *
* pero no agregada a la cola de listas , tampoco el PDT de usuario *
* El proceso es creado "limpio" *
* Trabaja sobre la zona alta *
* *
************************************************************************
}
function proceso_crear (ppid:dword;sched:word):p_tarea_struc;[public , alias : 'PROCESO_CREAR' ];
var nuevo_tss , ret : word;
stack0 , pdt : pointer;
begin
{ Es protegido el acceso a los recursos }
Gdt_Lock;
Mem_Lock;
{ ahora se vera si hay recursos para la operacion }
If (Gdt_Huecos_Libres = 1) then
begin
Mem_Unlock;
Gdt_Unlock;
exit(nil);
end;
If nr_free_page < 3 then
begin
Mem_Unlock;
Gdt_Unlock;
exit(nil);
end;
{ estas llamadas no pueden devolver nil }
Proceso_Crear := get_free_kpage;
stack0 := get_free_kpage;
pdt := get_free_kpage;
nuevo_tss := Gdt_Set_Tss(@Proceso_Crear^.reg);
{ son liberados }
Mem_Unlock;
Gdt_Unlock;
{ Es copiada la zona baja donde se encuentra el codigo y datos del kernel }
{ en maquinas en que la memoria supere 1GB , el kernel no puede acceder con }
{ el pdt del usuario a mas alla de el primer GB , por lo tanto devera abrir }
{ el Kernel_PDT y luego restaurarlo }
memcopy(Kernel_Pdt , pdt , Page_Size);
With Proceso_Crear^ do
begin
Politica := Sched ;
pid := Nuevo_Pid;
Padre_pid := PPid;
quantum_a := 0;
Tss_Descp := nuevo_tss;
Tss_P := pointer(GDT_NUEVA +(nuevo_tss -1 )*8);
stack0_page := stack0;
dir_page := pdt;
reg.cr3 := pdt;
reg.eip :=nil;
reg.esp :=nil;
reg.cs :=USER_CODE_SEL;
reg.ds :=USER_DATA_SEL;
reg.ss :=USER_DATA_SEL;
reg.es :=USER_DATA_SEL;
reg.fs :=USER_DATA_SEL;
reg.gs :=USER_DATA_SEL;
reg.ss0 :=KERNEL_DATA_SEL;
reg.esp0:= stack0 + Page_Size -1;
{ Punteros de retorno del proceso del modo nucleo }
ret_esp := reg.esp0 - 8 ;
ret_eip := reg.esp0 - 20;
reg.eflags:=$202;
flags_de_signal:=0;
{ Directorio de inicio }
cwd := nil ;
for ret:= 0 to NR_OPEN do
begin
Archivos[ret].f_op := nil;
Archivos[ret].inodo := nil;
end;
for ret:= 0 to 31 do signals[ret] := nil ;
timer.estado := false ;
timer.tarea := Proceso_Crear;
nice := 0 ;
real_time := contador ;
virtual_time := 0 ;
end;
{ Cola ordenada por nacimiento }
Hash_Push(Proceso_Crear);
end;
{ * Proceso_Clonar *
* *
* Tarea_Padre : Tarea que sera clonada *
* Retorno : Puntero a la nueva tarea o nil si falla *
* *
* Esta funcion se encarga de crear un copia exacta del proceso dado *
* y de todas las area de memoria , estas son recreadas y no comparti *
* das *
* *
***********************************************************************
}
function proceso_clonar(Tarea_Padre:p_tarea_struc):p_tarea_struc;[ Public , Alias : 'PROCESO_CLONAR'];
var size,tmp:dword;
tarea_hijo:p_tarea_struc;
ret:dword;
ori,dest:pointer;
begin
tarea_hijo := Proceso_Crear(Tarea_Padre^.pid,Tarea_Padre^.Politica);
If tarea_hijo=nil then exit(nil);
{ Tama¤o del proceso padre }
size := Tarea_Padre^.text_area.size + Tarea_Padre^.data_area.size + Tarea_Padre^.stack_area.size;
Mem_Lock;
{ Hay memoria para clonar el proceso? }
If nr_free_page < (size div Page_Size) then
begin
Mem_Unlock;
Proceso_Eliminar (Tarea_Hijo);
exit(nil);
end;
Save_Cr3;
Load_Kernel_Pdt;
{ Son creadas las areas vmm }
With Tarea_Hijo^ do
begin
text_area.size := 0;
text_area.flags := VMM_WRITE;
text_area.add_l_comienzo := pointer(HIGH_MEMORY);
text_area.add_l_fin := pointer(HIGH_MEMORY - 1) ;
stack_area.size :=0;
stack_area.flags := VMM_WRITE;
stack_area.add_l_comienzo := pointer(STACK_PAGE);
stack_area.add_l_fin := pointer(STACK_PAGE);
end;
{ La zona de codigo es duplicada }
vmm_alloc(Tarea_Hijo,@Tarea_Hijo^.text_area,Tarea_Padre^.text_area.size);
vmm_copy(Tarea_Padre,Tarea_Hijo,@Tarea_Padre^.text_area,@Tarea_Hijo^.text_area);
{ El area de pila es alocada y copiada tal cual }
vmm_alloc(Tarea_hijo,@Tarea_Hijo^.stack_area,Tarea_Padre^.stack_area.size);
vmm_copy(Tarea_Padre,Tarea_Hijo,@Tarea_Padre^.stack_area,@Tarea_Hijo^.stack_area);
Mem_Unlock;
{ Se heredan los desc de archivos }
for ret:= 0 to NR_OPEN do Clone_Filedesc(@Tarea_Padre^.Archivos[ret],@Tarea_Hijo^.Archivos[ret]);
{ es heredado el inodo de trabajo }
Tarea_hijo^.cwd := Tarea_Padre^.cwd ;
Tarea_hijo^.cwd^.count += 1;
Restore_Cr3;
exit(Tarea_Hijo);
end;
{ * Proceso_Interrumpir: *
* *
* Tarea:Tarea que sera interrumpida *
* Cola : Cola donde se encuentra interrumpida *
* *
* Este procedimiento detiene la ejecucion de un procedimiento *
* que no estuviese ya interrumpido . Luego de detenerlo llama al *
* planificador para que cambie de tarea *
* *
*************************************************************************
}
procedure proceso_interrumpir(Tarea:p_tarea_struc ; var Cola : p_tarea_struc);[public , alias :'PROCESO_INTERRUMPIR'];
begin
{ Zona critica }
cerrar;
{ Esto nunca puede ocurrir }
If Tarea^.estado = Tarea_Interrumpida Then exit;
{ Pasa a estado interrumpida }
Tarea^.estado := Tarea_Interrumpida;
{ Es agregada a la cola de interrumpidas }
Push_Node(tarea,Cola);
{ Re planificar }
Scheduling;
{ Aqui vuelve y son manejadas las se¤ales }
Signaling;
end;
{ * Proceso_Reanudar *
* *
* Tarea : Puntero a la tarea interrumpida *
* Cola : Cola ligada donde se encuentra la tarea *
* *
* Este procedimiento Reanuda una tarea que estubiese interrumpiada *
* por IO o por un despertador *
* *
*************************************************************************
}
procedure proceso_reanudar(Tarea:p_tarea_struc;var Cola : p_tarea_struc ); [public , alias :'PROCESO_REANUDAR'];
begin
if (Tarea = nil ) or (Cola = nil ) then exit ;
Tarea^.estado := Tarea_Lista ;
{ Se quita la tarea de la cola interrumpida }
Pop_Node (tarea,Cola);
{ la tarea pasa a la cola para ser planificado rapidamente }
add_interrupt_task (tarea);
{ se llamara al planificador en la proxima irq de relog }
if Tarea_Actual <> tarea then need_sched := true
end;
{ * Proceso_Eliminar : *
* *
* Tarea : Puntero a la tarea eliminada *
* *
* Procedimiento usado pocas veces para eliminar un proceso totalmente *
* de la memoria *
* *
***********************************************************************
}
procedure proceso_eliminar(Tarea:p_tarea_struc);[public , alias :'PROCESO_ELIMINAR'];
begin
Hash_Pop(Tarea);
free_page(Tarea^.stack0_page);
Gdt_Quitar(Tarea^.tss_descp);
free_page(Tarea^.dir_page);
free_page(Tarea);
end;
{ * Proceso_Destruir : *
* *
* Tarea : Tarea q sera destruida *
* *
* llamada para destruir un proceso , que puede ser provocada por una *
* execpcion o una se¤al , si es un proceso padre es eliminada tota *
* talmente del sistema pero si posee padre , se vuelve un zombie , y *
* sera destruida cuando el padre realice un WAITPID *
* *
**********************************************************************
}
procedure proceso_destruir(Tarea:p_tarea_struc);[public , alias :'PROCESO_DESTRUIR'];
var padre,hijos:p_tarea_struc;
tmp:word;
begin
{$IFDEF DEBUG}
printk('/VProcesos/n : Tiempo de vida de Pid %d : /V%d \n',[tarea^.pid , contador - tarea^.real_time],[]);
{$ENDIF}
{ es devuelto el inodo de trabajo }
put_dentry (Tarea_actual^.cwd^.i_dentry);
Load_Kernel_Pdt;
{ las areas de codigo son liberadas }
vmm_free(Tarea,@Tarea^.text_area);
vmm_free(Tarea,@Tarea^.stack_area);
{ Son cerrados todos los archivos }
for tmp := 0 to Nr_Open do If Tarea^.Archivos[tmp].f_op <> nil then Sys_Close(tmp);
{ Si el proceso padre tuviera hijos al morir este todos los hijos }
{se volverian hijos directos de INIT }
hijos := Tq_Zombies;
If hijos = nil then
else
{ se rastrea la cola en busca de hijos }
repeat
If hijos^.padre_pid=Tarea^.padre_pid then hijos^.padre_pid:=1;
hijos := hijos^.next_tarea;
until (Hijos = Tq_Zombies);
{ La tarea ahora sera zombie }
Tarea^.estado := Tarea_Zombie;
{ Se agrega a la cola de zombies }
Push_Node (Tarea,Tq_Zombies);
{ Si el padre estubiese esperando en la cola WaitPid , se reanuda }
{para que mate al proceso hijo }
padre := Tq_WaitPid;
If padre = nil then
else
begin
{ Se rastrea todo la cola en busca del padre }
repeat
If padre^.pid = Tarea^.padre_pid then
begin
Proceso_Reanudar( Padre , Tq_WaitPid );
exit;
end;
padre := Padre^.next_tarea;
until (Padre = Tq_WaitPid);
end;
{ el padre esta interrumpido o en la cola listos }
padre := Hash_Get (Tarea^.padre_pid);
{ se le avisa al padre que devera hacer Wait_Pid }
Signal_Send (padre , Sig_Hijo);
end;
{ * Esperar_Hijo : *
* *
* Tarea_Padre : Puntero a la tarea en busca de hijos *
* Pidh : Devuelve el Pid del hijo muerto *
* Err_code : devuelve el numero de error del proceso hijo *
* *
* Se encarga de devolver la causa de terminacion de un proceso hijo *
* y si no hubiese ninguno se interrumpe en espera de un proceso hijo *
* *
***********************************************************************
}
procedure esperar_hijo(Tarea_Padre:p_tarea_struc;var PidH:dword;var err_code:word);[public , alias :'ESPERAR_HIJO'];
var tmp:p_tarea_struc;
label 1,2;
begin
1 : tmp := Tq_Zombies ;
If (tmp = nil) then goto 2;
repeat
{ la tarea busca a sus hijos }
{ se encontro un hijo }
If (tmp^.padre_pid = Tarea_Padre^.pid) then
begin
PidH := tmp^.pid;
err_code := tmp^.terminacion;
{ se quita de la cola zombie }
Pop_Node(tmp,Tq_Zombies);
{ Es eliminada todo la memoria que queda del proceso }
Proceso_Eliminar (tmp);
exit;
end;
tmp := tmp^.next_tarea;
until (tmp=nil) or (tmp=Tq_Zombies);
{ Parece que no hay hijos la tarea es interrumpida }
2 : Proceso_Interrumpir (Tarea_Padre , Tq_WaitPid);
goto 1;
end;
{ * Proceso_Init : *
* *
* Aqui se inicializan las variables de la unidad procesos *
* *
***********************************************************************
}
procedure proceso_init ; [public,alias:'PROCESO_INIT'];
var ret : dword ;
begin
Pid_t := 0 ;
Tq_Interrumpidas := nil ;
Tarea_Actual := nil ;
contador := 0 ;
{ Son inicializadas todas las colas }
for ret := 1 to Max_HashPid do Hash_Pid[ret] := nil ;
end;
end.
|
unit SDUWindows64;
interface
function SDUIsWow64Process(const hProcess: THandle): boolean;
function SDUWow64EnableWow64FsRedirection(Enable: boolean): boolean;
function SDUWow64RevertWow64FsRedirection(const OldValue: Pointer): boolean;
function SDUWow64DisableWow64FsRedirection(out OldValue: Pointer): boolean;
function SDULoadLibKernel32(): boolean;
procedure SDUFreeLibKernel32();
implementation
uses
Windows;
const
KERNEL32_DLL = 'Kernel32.dll';
type
PPointer = ^Pointer;
TIsWow64PRocess = function (
hProcess: THandle;
Wow64Process: PBoolean
): boolean; stdcall;
TWow64EnableWow64FsRedirection = function (
Enable: boolean
): boolean; stdcall;
TWow64RevertWow64FsRedirection = function (
OldValue: Pointer
): boolean; stdcall;
TWow64DisableWow64FsRedirection = function (
OldValue: PPointer
): boolean; stdcall;
var
hLibKernel32: THandle;
fnIsWow64Process: TIsWow64PRocess;
fnWow64EnableWow64FsRedirection: TWow64EnableWow64FsRedirection;
fnWow64RevertWow64FsRedirection: TWow64RevertWow64FsRedirection;
fnWow64DisableWow64FsRedirection: TWow64DisableWow64FsRedirection;
function SDULoadLibKernel32(): boolean;
begin
hLibKernel32 := LoadLibrary(KERNEL32_DLL);
Result := (hLibKernel32 <> 0);
if not Result then begin
SDUFreeLibKernel32();
end else begin
@fnIsWow64Process := GetProcAddress(hLibKernel32, 'IsWow64Process');
@fnWow64EnableWow64FsRedirection := GetProcAddress(hLibKernel32, 'Wow64EnableWow64FsRedirection');
@fnWow64RevertWow64FsRedirection := GetProcAddress(hLibKernel32, 'Wow64RevertWow64FsRedirection');
@fnWow64DisableWow64FsRedirection := GetProcAddress(hLibKernel32, 'Wow64DisableWow64FsRedirection');
end;
end;
procedure SDUFreeLibKernel32();
begin
if (hLibKernel32 <> 0) then
begin
FreeLibrary(hLibKernel32);
hLibKernel32 := 0;
end;
@fnIsWow64Process := nil;
@fnWow64EnableWow64FsRedirection := nil;
@fnWow64RevertWow64FsRedirection := nil;
@fnWow64DisableWow64FsRedirection := nil;
end;
function SDUIsWow64Process(const hProcess: THandle): boolean;
var
wow64Retval: boolean;
begin
Result := FALSE;
if (@fnIsWow64Process <> nil) then begin
Result := fnIsWow64Process(hProcess, @wow64Retval);
// if no result assume false
if Result then Result := wow64Retval;
end;
end;
function SDUWow64EnableWow64FsRedirection(Enable: boolean): boolean;
begin
Result := FALSE;
if (@fnWow64EnableWow64FsRedirection <> nil) then
begin
Result := fnWow64EnableWow64FsRedirection(Enable);
end;
end;
function SDUWow64RevertWow64FsRedirection(const OldValue: Pointer): boolean;
begin
Result := FALSE;
if (@fnWow64RevertWow64FsRedirection <> nil) then
begin
Result := fnWow64RevertWow64FsRedirection(OldValue);
end;
end;
function SDUWow64DisableWow64FsRedirection(out OldValue: Pointer): boolean;
begin
Result := FALSE;
if (@fnWow64DisableWow64FsRedirection <> nil) then
begin
Result := fnWow64DisableWow64FsRedirection(@OldValue);
end;
end;
initialization
SDULoadLibKernel32();
finalization
SDUFreeLibKernel32();
END.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFGeolocationHandler;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefGeolocationHandlerOwn = class(TCefBaseRefCountedOwn, ICefGeolocationHandler)
protected
function OnRequestGeolocationPermission(const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback): Boolean; virtual;
procedure OnCancelGeolocationPermission(const browser: ICefBrowser; requestId: Integer); virtual;
public
constructor Create; virtual;
end;
TCustomGeolocationHandler = class(TCefGeolocationHandlerOwn)
protected
FEvent: IChromiumEvents;
function OnRequestGeolocationPermission(const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback): Boolean; override;
procedure OnCancelGeolocationPermission(const browser: ICefBrowser; requestId: Integer); override;
public
constructor Create(const events: IChromiumEvents); reintroduce; virtual;
destructor Destroy; override;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFBrowser, uCEFGeolocationCallback;
function cef_geolocation_handler_on_request_geolocation_permission(self: PCefGeolocationHandler;
browser: PCefBrowser; const requesting_url: PCefString; request_id: Integer;
callback: PCefGeolocationCallback): Integer; stdcall;
begin
with TCefGeolocationHandlerOwn(CefGetObject(self)) do
Result := Ord(OnRequestGeolocationPermission(TCefBrowserRef.UnWrap(browser), CefString(requesting_url),
request_id, TCefGeolocationCallbackRef.UnWrap(callback)));
end;
procedure cef_geolocation_handler_on_cancel_geolocation_permission(self: PCefGeolocationHandler;
browser: PCefBrowser; request_id: Integer); stdcall;
begin
with TCefGeolocationHandlerOwn(CefGetObject(self)) do
OnCancelGeolocationPermission(TCefBrowserRef.UnWrap(browser), request_id);
end;
// TCefGeolocationHandlerOwn
constructor TCefGeolocationHandlerOwn.Create;
begin
inherited CreateData(SizeOf(TCefGeolocationHandler));
with PCefGeolocationHandler(FData)^ do
begin
on_request_geolocation_permission := cef_geolocation_handler_on_request_geolocation_permission;
on_cancel_geolocation_permission := cef_geolocation_handler_on_cancel_geolocation_permission;
end;
end;
function TCefGeolocationHandlerOwn.OnRequestGeolocationPermission(
const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer;
const callback: ICefGeolocationCallback): Boolean;
begin
Result := False;
end;
procedure TCefGeolocationHandlerOwn.OnCancelGeolocationPermission(const browser: ICefBrowser; requestId: Integer);
begin
end;
// TCustomGeolocationHandler
constructor TCustomGeolocationHandler.Create(const events: IChromiumEvents);
begin
inherited Create;
FEvent := events;
end;
destructor TCustomGeolocationHandler.Destroy;
begin
FEvent := nil;
inherited Destroy;
end;
procedure TCustomGeolocationHandler.OnCancelGeolocationPermission(const browser: ICefBrowser; requestId: Integer);
begin
if (FEvent <> nil) then
FEvent.doOnCancelGeolocationPermission(browser, requestId);
end;
function TCustomGeolocationHandler.OnRequestGeolocationPermission(const browser : ICefBrowser;
const requestingUrl : ustring;
requestId : Integer;
const callback : ICefGeolocationCallback): Boolean;
begin
if (FEvent <> nil) then
Result := FEvent.doOnRequestGeolocationPermission(browser, requestingUrl, requestId, callback)
else
Result := inherited OnRequestGeolocationPermission(browser, requestingUrl, requestId, callback);
end;
end.
|
unit uFrmDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmParent, ActnList, Menus, cxLookAndFeelPainters, StdCtrls,
cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, cxLabel, uDefCom;
type
TfrmDialog = class(TfrmParent)
pnlBottom: TPanel;
btnOK: TcxButton;
btnCannel: TcxButton;
actOK: TAction;
actCancel: TAction;
pnlTop: TPanel;
lblTitle: TcxLabel;
pnlClient: TPanel;
procedure actCancelExecute(Sender: TObject);
private
{ Private declarations }
procedure SetTitle(const Value: string); override;
function FrmShowStyle: TShowStyle; override;
public
{ Public declarations }
end;
var
frmDialog: TfrmDialog;
implementation
{$R *.dfm}
{ TfrmDialog }
procedure TfrmDialog.SetTitle(const Value: string);
begin
inherited;
lblTitle.Caption := Value;
Caption := Value;
end;
procedure TfrmDialog.actCancelExecute(Sender: TObject);
begin
inherited;
ModalResult := mrCancel;
end;
function TfrmDialog.FrmShowStyle: TShowStyle;
begin
Result := fssShowModal;
end;
end.
|
Unit AddEditSymServerForm;
Interface
Uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls;
Type
TAddEditSymServerFrm = Class(TForm)
MainPanel: TPanel;
StornoButton: TButton;
OkButton: TButton;
LocalEdit: TEdit;
BrowseButton: TButton;
Label1: TLabel;
ServerEdit: TEdit;
Label2: TLabel;
LocalOpenDialog: TFileOpenDialog;
procedure StornoButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BrowseButtonClick(Sender: TObject);
Private
FCancelled : Boolean;
FSymPath : WideString;
Public
Constructor Create(AOwner:TComponent; APath:WideString = ''); Reintroduce;
Property Cancelled : Boolean Read FCancelled;
Property OneSymPath : WideString Read FSymPath;
end;
Implementation
Constructor TAddEditSymServerFrm.Create(AOwner:TComponent; APath:WideString = '');
begin
FSymPath := APath;
FCancelled := True;
Inherited Create(AOwner);
end;
{$R *.DFM}
Procedure TAddEditSymServerFrm.BrowseButtonClick(Sender: TObject);
begin
If LocalOpenDialog.Execute Then
LocalEdit.Text := LocalOpenDialog.FileName;
end;
Procedure TAddEditSymServerFrm.FormCreate(Sender: TObject);
Var
starIndex : Integer;
begin
If Pos(WideString('srv*'), FSymPath) = 1 Then
Delete(FSymPath, 1, Length('srv*'));
starIndex := Pos(WideString('*'), FSymPath);
If starIndex > 0 Then
begin
LocalEdit.Text := Copy(FSymPath, 1, starIndex - 1);
ServerEdit.Text := Copy(FSymPath, starIndex + 1, Length(FSymPath) - starIndex - 1);
end
Else LocalEdit.Text := FSymPath;
end;
procedure TAddEditSymServerFrm.OkButtonClick(Sender: TObject);
begin
FSymPath := '';
If ServerEdit.Text <> '' Then
FSymPath := 'srv*';
If LocalEdit.Text <> '' Then
FSymPath := FSymPath + LocalEdit.Text;
If ServerEdit.Text <> '' Then
FSymPath := FSymPath + '*' + ServerEdit.Text;
FCancelled := False;
Close;
end;
Procedure TAddEditSymServerFrm.StornoButtonClick(Sender: TObject);
begin
Close;
end;
End.
|
unit Duktape.Api;
interface
const
{$IF Defined(WIN32)}
LIB_DUKTAPE = 'duktape32.dll';
PREFIX = '';
{$ELSEIF Defined(WIN64)}
LIB_DUKTAPE = 'duktape64.dll';
PREFIX = '';
{$ELSEIF Defined(ANDROID)}
LIB_DUKTAPE = 'libduktape_android.a';
PREFIX = '';
{$ELSEIF Defined(IOS)}
LIB_DUKTAPE = 'libduktape_ios.a';
PREFIX = '';
{$ELSEIF Defined(MACOS32)}
LIB_DUKTAPE = 'libduktape_osx32.dylib';
PREFIX = '_';
{$ELSEIF Defined(MACOS64)}
LIB_DUKTAPE = 'libduktape_osx64.a';
PREFIX = '';
{$ELSEIF Defined(LINUX)}
LIB_DUKTAPE = 'libduktape_linux64.so';
PREFIX = '';
{$ELSE}
{$MESSAGE Error 'Unsupported platform'}
{$ENDIF}
(*
* duk_config.h configuration header generated by genconfig.py.
*
* Git commit d7fdb67f18561a50e06bafd196c6b423af9ad6fe (v2.3.0).
* Git branch: master
*
* Supported platforms:
* - Mac OSX, iPhone, Darwin
* - Orbis
* - OpenBSD
* - Generic BSD
* - Atari ST TOS
* - AmigaOS
* - Durango (XboxOne)
* - Windows
* - Flashplayer (Crossbridge)
* - QNX
* - TI-Nspire
* - Emscripten
* - Linux
* - Solaris
* - AIX
* - HPUX
* - Generic POSIX
* - Cygwin
* - Generic UNIX
* - Generic fallback
*
* Supported architectures:
* - x86
* - x64
* - x32
* - ARM 32-bit
* - ARM 64-bit
* - MIPS 32-bit
* - MIPS 64-bit
* - PowerPC 32-bit
* - PowerPC 64-bit
* - SPARC 32-bit
* - SPARC 64-bit
* - SuperH
* - Motorola 68k
* - Emscripten
* - Generic
*
* Supported compilers:
* - Clang
* - GCC
* - MSVC
* - Emscripten
* - TinyC
* - VBCC
* - Bruce's C compiler
* - Generic
*
*)
type
TDukUInt8 = UInt8;
TDukInt8 = Int8;
TDukUInt16 = UInt16;
TDukInt16 = Int16;
TDukUInt32 = UInt32;
TDukInt32 = Int32;
TDukUInt64 = UInt32;
TDukInt64 = Int32;
TDukUInt = Cardinal;
TDukInt = Integer;
TDukSize = NativeUInt;
TDukPtrDiff = NativeInt;
TDukSmallUInt = Cardinal;
TDukSmallInt = Integer;
TDukBool = TDukSmallUInt;
TDukIdx = TDukInt;
TDukUIdx = TDukUInt;
TDukUArrIdx = TDukUInt;
TDukRet = TDukSmallInt;
TDukErrCode = TDukInt;
TDukCodepoint = TDukInt;
TDukUCodepoint = TDukUInt;
TDukFloat = Single;
TDukDouble = Double;
type
PDukUInt8 = ^TDukUInt8;
PDukInt8 = ^TDukInt8;
PDukUInt16 = ^TDukUInt16;
PDukInt16 = ^TDukInt16;
PDukUInt32 = ^TDukUInt32;
PDukInt32 = ^TDukInt32;
PDukUInt64 = ^TDukUInt64;
PDukInt64 = ^TDukInt64;
PDukUInt = ^TDukUInt;
PDukInt = ^TDukInt;
PDukSize = ^TDukSize;
PDukPtrDiff = ^TDukPtrDiff;
PDukSmallUInt = ^TDukSmallUInt;
PDukSmallInt = ^TDukSmallInt;
PDukBool = ^TDukBool;
PDukIdx = ^TDukIdx;
PDukUIdx = ^TDukUIdx;
PDukUArrIdx = ^TDukUArrIdx;
PDukRet = ^TDukRet;
PDukErrCode = ^TDukErrCode;
PDukCodepoint = ^TDukCodepoint;
PDukUCodepoint = ^TDukUCodepoint;
PDukFloat = ^TDukFloat;
PDukDouble = ^TDukDouble;
type
TDukUIntLeast8 = TDukUInt8;
TDukIntLeast8 = TDukInt8;
TDukUIntLeast16 = TDukUInt16;
TDukIntLeast16 = TDukInt16;
TDukUIntLeast32 = TDukUInt32;
TDukIntLeast32 = TDukInt32;
TDukUIntLeast64 = TDukUInt64;
TDukIntLeast64 = TDukInt64;
type
TDukUIntFast8 = TDukUInt8;
TDukIntFast8 = TDukInt8;
TDukUIntFast16 = TDukUInt16;
TDukIntFast16 = TDukInt16;
TDukUIntFast32 = TDukUInt32;
TDukIntFast32 = TDukInt32;
TDukUIntFast64 = TDukUInt64;
TDukIntFast64 = TDukInt64;
TDukUIntFast = TDukUIntFast32;
TDukIntFast = TDukIntFast32;
TDukSmallUIntFast = TDukUIntFast16;
TDukSmallIntFast = TDukIntFast16;
type
TDukUIntMax = TDukUInt64;
TDukIntMax = TDukInt64;
const
DUK_UINT8_MIN = $00;
DUK_UINT8_MAX = $FF;
DUK_INT8_MIN = -$80;
DUK_INT8_MAX = $7F;
DUK_UINT_LEAST8_MIN = $00;
DUK_UINT_LEAST8_MAX = $FF;
DUK_INT_LEAST8_MIN = -$80;
DUK_INT_LEAST8_MAX = $7F;
DUK_UINT_FAST8_MIN = $00;
DUK_UINT_FAST8_MAX = $FF;
DUK_INT_FAST8_MIN = -$80;
DUK_INT_FAST8_MAX = $7F;
DUK_UINT16_MIN = $0000;
DUK_UINT16_MAX = $FFFF;
DUK_INT16_MIN = -$8000;
DUK_INT16_MAX = $7FFF;
DUK_UINT_LEAST16_MIN = $0000;
DUK_UINT_LEAST16_MAX = $FFFF;
DUK_INT_LEAST16_MIN = -$8000;
DUK_INT_LEAST16_MAX = $7FFF;
DUK_UINT_FAST16_MIN = $0000;
DUK_UINT_FAST16_MAX = $FFFF;
DUK_INT_FAST16_MIN = -$8000;
DUK_INT_FAST16_MAX = $7FFF;
DUK_UINT32_MIN = $00000000;
DUK_UINT32_MAX = $FFFFFFFF;
DUK_INT32_MIN = -$80000000;
DUK_INT32_MAX = $7FFFFFFF;
DUK_UINT_LEAST32_MIN = $00000000;
DUK_UINT_LEAST32_MAX = $FFFFFFFF;
DUK_INT_LEAST32_MIN = -$80000000;
DUK_INT_LEAST32_MAX = $7FFFFFFF;
DUK_UINT_FAST32_MIN = $00000000;
DUK_UINT_FAST32_MAX = $FFFFFFFF;
DUK_INT_FAST32_MIN = -$80000000;
DUK_INT_FAST32_MAX = $7FFFFFFF;
DUK_UINT64_MIN = $0000000000000000;
DUK_UINT64_MAX = $FFFFFFFFFFFFFFFF;
DUK_INT64_MIN = -$8000000000000000;
DUK_INT64_MAX = $7FFFFFFFFFFFFFFF;
DUK_UINT_LEAST64_MIN = $0000000000000000;
DUK_UINT_LEAST64_MAX = $FFFFFFFFFFFFFFFF;
DUK_INT_LEAST64_MIN = -$8000000000000000;
DUK_INT_LEAST64_MAX = $7FFFFFFFFFFFFFFF;
DUK_UINT_FAST64_MIN = $0000000000000000;
DUK_UINT_FAST64_MAX = $FFFFFFFFFFFFFFFF;
DUK_INT_FAST64_MIN = -$8000000000000000;
DUK_INT_FAST64_MAX = $7FFFFFFFFFFFFFFF;
const
DUK_UINTMAX_MIN = DUK_UINT64_MIN;
DUK_UINTMAX_MAX = DUK_UINT64_MAX;
DUK_INTMAX_MIN = DUK_INT64_MIN;
DUK_INTMAX_MAX = DUK_INT64_MAX;
const
DUK_UINT_MIN = DUK_UINT32_MIN;
DUK_UINT_MAX = DUK_UINT32_MAX;
DUK_INT_MIN = DUK_INT32_MIN;
DUK_INT_MAX = DUK_INT32_MAX;
DUK_UINT_FAST_MIN = DUK_UINT_FAST32_MIN;
DUK_UINT_FAST_MAX = DUK_UINT_FAST32_MAX;
DUK_INT_FAST_MIN = DUK_INT_FAST32_MIN;
DUK_INT_FAST_MAX = DUK_INT_FAST32_MAX;
DUK_SMALL_UINT_MIN = DUK_UINT32_MIN;
DUK_SMALL_UINT_MAX = DUK_UINT32_MAX;
DUK_SMALL_INT_MIN = DUK_INT32_MIN;
DUK_SMALL_INT_MAX = DUK_INT32_MAX;
DUK_SMALL_UINT_FAST_MIN = DUK_UINT16_MIN;
DUK_SMALL_UINT_FAST_MAX = DUK_UINT16_MAX;
DUK_SMALL_INT_FAST_MIN = DUK_INT16_MIN;
DUK_SMALL_INT_FAST_MAX = DUK_INT16_MAX;
DUK_BOOL_MIN = DUK_SMALL_INT_MIN;
DUK_BOOL_MAX = DUK_SMALL_INT_MAX;
DUK_IDX_MIN = DUK_INT_MIN;
DUK_IDX_MAX = DUK_INT_MAX;
DUK_UIDX_MIN = DUK_UINT_MIN;
DUK_UIDX_MAX = DUK_UINT_MAX;
DUK_UARRIDX_MIN = DUK_UINT_MIN;
DUK_UARRIDX_MAX = DUK_UINT_MAX;
DUK_ERRCODE_MIN = DUK_INT_MIN;
DUK_ERRCODE_MAX = DUK_INT_MAX;
DUK_CODEPOINT_MIN = DUK_INT_MIN;
DUK_CODEPOINT_MAX = DUK_INT_MAX;
DUK_UCODEPOINT_MIN = DUK_UINT_MIN;
DUK_UCODEPOINT_MAX = DUK_UINT_MAX;
DUK_RET_MIN = DUK_SMALL_INT_MIN;
DUK_RET_MAX = DUK_SMALL_INT_MAX;
(*
* Duktape public API for Duktape 2.1.0.
*
* See the API reference for documentation on call semantics. The exposed,
* supported API is between the "BEGIN PUBLIC API" and "END PUBLIC API"
* comments. Other parts of the header are Duktape internal and related to
* e.g. platform/compiler/feature detection.
*
* Git commit a459cf3c9bd1779fc01b435d69302b742675a08f (v2.2.0).
* Git branch master.
*
* See Duktape AUTHORS.rst and LICENSE.txt for copyright and
* licensing information.
*)
(*
* ===============
* Duktape license
* ===============
*
* (http://opensource.org/licenses/MIT)
*
* Copyright (c) 2013-2018 by Duktape authors (see AUTHORS.rst)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*)
(*
* ===============
* Duktape authors
* ===============
*
* Copyright
* =========
*
* Duktape copyrights are held by its authors. Each author has a copyright
* to their contribution, and agrees to irrevocably license the contribution
* under the Duktape ``LICENSE.txt``.
*
* Authors
* =======
*
* Please include an e-mail address, a link to your GitHub profile, or something
* similar to allow your contribution to be identified accurately.
*
* The following people have contributed code, website contents, or Wiki contents,
* and agreed to irrevocably license their contributions under the Duktape
* ``LICENSE.txt`` (in order of appearance):
*
* * Sami Vaarala <sami.vaarala@iki.fi>
* * Niki Dobrev
* * Andreas \u00d6man <andreas@lonelycoder.com>
* * L\u00e1szl\u00f3 Lang\u00f3 <llango.u-szeged@partner.samsung.com>
* * Legimet <legimet.calc@gmail.com>
* * Karl Skomski <karl@skomski.com>
* * Bruce Pascoe <fatcerberus1@gmail.com>
* * Ren\u00e9 Hollander <rene@rene8888.at>
* * Julien Hamaide (https://github.com/crazyjul)
* * Sebastian G\u00f6tte (https://github.com/jaseg)
* * Tomasz Magulski (https://github.com/magul)
* * \D. Bohdan (https://github.com/dbohdan)
* * Ond\u0159ej Jirman (https://github.com/megous)
* * Sa\u00fal Ibarra Corretg\u00e9 <saghul@gmail.com>
* * Jeremy HU <huxingyi@msn.com>
* * Ole Andr\u00e9 Vadla Ravn\u00e5s (https://github.com/oleavr)
* * Harold Brenes (https://github.com/harold-b)
* * Oliver Crow (https://github.com/ocrow)
* * Jakub Ch\u0142api\u0144ski (https://github.com/jchlapinski)
* * Brett Vickers (https://github.com/beevik)
* * Dominik Okwieka (https://github.com/okitec)
* * Remko Tron\u00e7on (https://el-tramo.be)
* * Romero Malaquias (rbsm@ic.ufal.br)
* * Michael Drake <michael.drake@codethink.co.uk>
* * Steven Don (https://github.com/shdon)
* * Simon Stone (https://github.com/sstone1)
* * \J. McC. (https://github.com/jmhmccr)
* * Jakub Nowakowski (https://github.com/jimvonmoon)
* * Tommy Nguyen (https://github.com/tn0502)
* * Fabrice Fontaine (https://github.com/ffontaine)
* * Christopher Hiller (https://github.com/boneskull)
* * Gonzalo Diethelm (https://github.com/gonzus)
* * Michal Kasperek (https://github.com/michalkas)
* * Andrew Janke (https://github.com/apjanke)
* * Steve Fan (https://github.com/stevefan1999)
*
* Other contributions
* ===================
*
* The following people have contributed something other than code (e.g. reported
* bugs, provided ideas, etc; roughly in order of appearance):
*
* * Greg Burns
* * Anthony Rabine
* * Carlos Costa
* * Aur\u00e9lien Bouilland
* * Preet Desai (Pris Matic)
* * judofyr (http://www.reddit.com/user/judofyr)
* * Jason Woofenden
* * Micha\u0142 Przyby\u015b
* * Anthony Howe
* * Conrad Pankoff
* * Jim Schimpf
* * Rajaran Gaunker (https://github.com/zimbabao)
* * Andreas \u00d6man
* * Doug Sanden
* * Josh Engebretson (https://github.com/JoshEngebretson)
* * Remo Eichenberger (https://github.com/remoe)
* * Mamod Mehyar (https://github.com/mamod)
* * David Demelier (https://github.com/markand)
* * Tim Caswell (https://github.com/creationix)
* * Mitchell Blank Jr (https://github.com/mitchblank)
* * https://github.com/yushli
* * Seo Sanghyeon (https://github.com/sanxiyn)
* * Han ChoongWoo (https://github.com/tunz)
* * Joshua Peek (https://github.com/josh)
* * Bruce E. Pascoe (https://github.com/fatcerberus)
* * https://github.com/Kelledin
* * https://github.com/sstruchtrup
* * Michael Drake (https://github.com/tlsa)
* * https://github.com/chris-y
* * Laurent Zubiaur (https://github.com/lzubiaur)
* * Neil Kolban (https://github.com/nkolban)
* * Wilhelm Wanecek (https://github.com/wanecek)
* * Andrew Janke (https://github.com/apjanke)
*
* If you are accidentally missing from this list, send me an e-mail
* (``sami.vaarala@iki.fi``) and I'll fix the omission.
*)
(*
* BEGIN PUBLIC API
*)
(*
* Version and Git commit identification
*)
(* Duktape version, (major * 10000) + (minor * 100) + patch. Allows C code
* to #if (DUK_VERSION >= NNN) against Duktape API version. The same value
* is also available to ECMAscript code in Duktape.version. Unofficial
* development snapshots have 99 for patch level (e.g. 0.10.99 would be a
* development version after 0.10.0 but before the next official release).
*)
const
DUK_VERSION = 20300;
(* Git commit, describe, and branch for Duktape build. Useful for
* non-official snapshot builds so that application code can easily log
* which Duktape snapshot was used. Not available in the ECMAscript
* environment.
*)
const
DUK_GIT_COMMIT = 'd7fdb67f18561a50e06bafd196c6b423af9ad6fe';
DUK_GIT_DESCRIBE = 'v2.3.0';
DUK_GIT_BRANCH = 'master';
(*
* Public API specific typedefs
*
* Many types are wrapped by Duktape for portability to rare platforms
* where e.g. 'int' is a 16-bit type. See practical typing discussion
* in Duktape web documentation.
*)
type
PDukContext = Pointer;
type
TDukAllocFunction = function(udata: Pointer; size: TDukSize): Pointer; cdecl;
TDukReallocFunction = function(udata: Pointer; ptr: Pointer; size: TDukSize): Pointer; cdecl;
TDukFreeFunction = procedure(udata: Pointer; ptr: Pointer); cdecl;
TDukCFunction = function(ctx: PDukContext): TDukRet; cdecl;
TDukFatalFunction = procedure(udata: Pointer; const msg: MarshaledAString); cdecl;
TDukDecodeCharFunction = procedure(udata: Pointer; codepoint: TDukCodepoint); cdecl;
TDukMapCharFunction = function(udata: Pointer; codepoint: TDukCodepoint): TDukCodepoint; cdecl;
TDukSafeCallFunction = function(ctx: PDukContext; udata: Pointer): TDukRet; cdecl;
TDukDebugReadFunction = function(udata: Pointer; buffer: MarshaledAString; length: TDukSize): TDukSize; cdecl;
TDukDebugWriteFunction = function(udata: Pointer; const buffer: MarshaledAString; length: TDukSize): TDukSize; cdecl;
TDukDebugPeekFunction = function(udata: Pointer): TDukSize; cdecl;
TDukDebugReadFlushFunction = procedure(udata: Pointer); cdecl;
TDukDebugWriteFlushFunction = procedure(udata: Pointer); cdecl;
TDukDebugRequestFunction = function(ctx: PDukContext; udata: Pointer; nvalues: TDukIdx): TDukIdx; cdecl;
TDukDebugDetachedFunction = procedure(ctx: PDukContext; udata: Pointer); cdecl;
type
PDukThreadState = ^TDukThreadState;
TDukThreadState = record
{ Enough space to hold internal suspend/resume structure.
This is rather awkward and to be fixed when the internal
structure is visible for the public API header. }
Data: array [0..127] of Byte;
end;
type
PDukMemoryFunctions = ^TDukMemoryFunctions;
TDukMemoryFunctions = record
AllocFunc: TDukAllocFunction;
ReallocFunc: TDukReallocFunction;
FreeFunc: TDukFreeFunction;
UserData: Pointer;
end;
type
PDukFunctionListEntry = ^TDukFunctionListEntry;
TDukFunctionListEntry = record
Key: MarshaledAString;
Value: TDukCFunction;
NumArgs: TDukIdx;
end;
type
PDukNumberListEntry = ^TDukNumberListEntry;
TDukNumberListEntry = record
Key: MarshaledAString;
Value: TDukDouble;
end;
type
PDukTimeComponents = ^TDukTimeComponents;
TDukTimeComponents = record
Year: TDukDouble;
Month: TDukDouble;
Day: TDukDouble;
Hours: TDukDouble;
Minutes: TDukDouble;
Seconds: TDukDouble;
Milliseconds: TDukDouble;
Weekday: TDukDouble;
end;
(*
* Constants
*)
(* Duktape debug protocol version used by this build. *)
const
DUK_DEBUG_PROTOCOL_VERSION = 2;
(* Used to represent invalid index; if caller uses this without checking,
* this index will map to a non-existent stack entry. Also used in some
* API calls as a marker to denote "no value".
*)
const
DUK_INVALID_INDEX = DUK_IDX_MIN;
(* Indicates that a native function does not have a fixed number of args,
* and the argument stack should not be capped/extended at all.
*)
const
DUK_VARARGS = -1;
(* Number of value stack entries (in addition to actual call arguments)
* guaranteed to be allocated on entry to a Duktape/C function.
*)
const
DUK_API_ENTRY_STACK = 64;
(* Value types, used by e.g. duk_get_type() *)
const
DUK_TYPE_MIN = 0;
DUK_TYPE_NONE = 0; (* no value, e.g. invalid index *)
DUK_TYPE_UNDEFINED = 1; (* ECMAScript undefined *)
DUK_TYPE_NULL = 2; (* ECMAScript null *)
DUK_TYPE_BOOLEAN = 3; (* ECMAScript boolean: 0 or 1 *)
DUK_TYPE_NUMBER = 4; (* ECMAScript number: double *)
DUK_TYPE_STRING = 5; (* ECMAScript string: CESU-8 / extended UTF-8 encoded *)
DUK_TYPE_OBJECT = 6; (* ECMAScript object: includes objects, arrays, functions, threads *)
DUK_TYPE_BUFFER = 7; (* fixed or dynamic, garbage collected byte buffer *)
DUK_TYPE_POINTER = 8; (* raw void pointer *)
DUK_TYPE_LIGHTFUNC = 9; (* lightweight function pointer *)
DUK_TYPE_MAX = 9;
(* Value mask types, used by e.g. duk_get_type_mask() *)
const
DUK_TYPE_MASK_NONE = 1 shl DUK_TYPE_NONE;
DUK_TYPE_MASK_UNDEFINED = 1 shl DUK_TYPE_UNDEFINED;
DUK_TYPE_MASK_NULL = 1 shl DUK_TYPE_NULL;
DUK_TYPE_MASK_BOOLEAN = 1 shl DUK_TYPE_BOOLEAN;
DUK_TYPE_MASK_NUMBER = 1 shl DUK_TYPE_NUMBER;
DUK_TYPE_MASK_STRING = 1 shl DUK_TYPE_STRING;
DUK_TYPE_MASK_OBJECT = 1 shl DUK_TYPE_OBJECT;
DUK_TYPE_MASK_BUFFER = 1 shl DUK_TYPE_BUFFER;
DUK_TYPE_MASK_POINTER = 1 shl DUK_TYPE_POINTER;
DUK_TYPE_MASK_LIGHTFUNC = 1 shl DUK_TYPE_LIGHTFUNC;
DUK_TYPE_MASK_THROW = 1 shl 10; (* internal flag value: throw if mask doesn't match *)
DUK_TYPE_MASK_PROMOTE = 1 shl 11; (* internal flag value: promote to object if mask matches *)
(* Coercion hints *)
const
DUK_HINT_NONE = 0; (* prefer number, unless input is a Date, in which
* case prefer string (E5 Section 8.12.8) *)
DUK_HINT_STRING = 1; (* prefer string *)
DUK_HINT_NUMBER = 2; (* prefer number *)
(* Enumeration flags for duk_enum() *)
const
DUK_ENUM_INCLUDE_NONENUMERABLE = 1 shl 0; (* enumerate non-numerable properties in addition to enumerable *)
DUK_ENUM_INCLUDE_HIDDEN = 1 shl 1; (* enumerate hidden symbols too (in Duktape 1.x called internal properties) *)
DUK_ENUM_INCLUDE_SYMBOLS = 1 shl 2; (* enumerate symbols *)
DUK_ENUM_EXCLUDE_STRINGS = 1 shl 3; (* exclude strings *)
DUK_ENUM_OWN_PROPERTIES_ONLY = 1 shl 4; (* don't walk prototype chain, only check own properties *)
DUK_ENUM_ARRAY_INDICES_ONLY = 1 shl 5; (* only enumerate array indices *)
DUK_ENUM_SORT_ARRAY_INDICES = 1 shl 6; (* sort array indices (applied to full enumeration result, including inherited array indices) *)
DUK_ENUM_NO_PROXY_BEHAVIOR = 1 shl 7; (* enumerate a proxy object itself without invoking proxy behavior *)
(* Compilation flags for duk_compile() and duk_eval() *)
(* DUK_COMPILE_xxx bits 0-2 are reserved for an internal 'nargs' argument.
*)
const
DUK_COMPILE_EVAL = 1 shl 3; (* compile eval code (instead of global code) *)
DUK_COMPILE_FUNCTION = 1 shl 4; (* compile function code (instead of global code) *)
DUK_COMPILE_STRICT = 1 shl 5; (* use strict (outer) context for global, eval, or function code *)
DUK_COMPILE_SHEBANG = 1 shl 6; (* allow shebang ('#! ...') comment on first line of source *)
DUK_COMPILE_SAFE = 1 shl 7; (* (internal) catch compilation errors *)
DUK_COMPILE_NORESULT = 1 shl 8; (* (internal) omit eval result *)
DUK_COMPILE_NOSOURCE = 1 shl 9; (* (internal) no source string on stack *)
DUK_COMPILE_STRLEN = 1 shl 10; (* (internal) take strlen() of src_buffer (avoids double evaluation in macro) *)
DUK_COMPILE_NOFILENAME = 1 shl 11; (* (internal) no filename on stack *)
DUK_COMPILE_FUNCEXPR = 1 shl 12; (* (internal) source is a function expression (used for Function constructor) *)
(* Flags for duk_def_prop() and its variants *)
const
DUK_DEFPROP_WRITABLE = 1 shl 0; (* set writable (effective if DUK_DEFPROP_HAVE_WRITABLE set) *)
DUK_DEFPROP_ENUMERABLE = 1 shl 1; (* set enumerable (effective if DUK_DEFPROP_HAVE_ENUMERABLE set) *)
DUK_DEFPROP_CONFIGURABLE = 1 shl 2; (* set configurable (effective if DUK_DEFPROP_HAVE_CONFIGURABLE set) *)
DUK_DEFPROP_HAVE_WRITABLE = 1 shl 3; (* set/clear writable *)
DUK_DEFPROP_HAVE_ENUMERABLE = 1 shl 4; (* set/clear enumerable *)
DUK_DEFPROP_HAVE_CONFIGURABLE = 1 shl 5; (* set/clear configurable *)
DUK_DEFPROP_HAVE_VALUE = 1 shl 6; (* set value (given on value stack) *)
DUK_DEFPROP_HAVE_GETTER = 1 shl 7; (* set getter (given on value stack) *)
DUK_DEFPROP_HAVE_SETTER = 1 shl 8; (* set setter (given on value stack) *)
DUK_DEFPROP_FORCE = 1 shl 9; (* force change if possible, may still fail for e.g. virtual properties *)
DUK_DEFPROP_SET_WRITABLE = DUK_DEFPROP_HAVE_WRITABLE or DUK_DEFPROP_WRITABLE;
DUK_DEFPROP_CLEAR_WRITABLE = DUK_DEFPROP_HAVE_WRITABLE;
DUK_DEFPROP_SET_ENUMERABLE = DUK_DEFPROP_HAVE_ENUMERABLE or DUK_DEFPROP_ENUMERABLE;
DUK_DEFPROP_CLEAR_ENUMERABLE = DUK_DEFPROP_HAVE_ENUMERABLE;
DUK_DEFPROP_SET_CONFIGURABLE = DUK_DEFPROP_HAVE_CONFIGURABLE or DUK_DEFPROP_CONFIGURABLE;
DUK_DEFPROP_CLEAR_CONFIGURABLE = DUK_DEFPROP_HAVE_CONFIGURABLE;
DUK_DEFPROP_W = DUK_DEFPROP_WRITABLE;
DUK_DEFPROP_E = DUK_DEFPROP_ENUMERABLE;
DUK_DEFPROP_C = DUK_DEFPROP_CONFIGURABLE;
DUK_DEFPROP_WE = DUK_DEFPROP_WRITABLE or DUK_DEFPROP_ENUMERABLE;
DUK_DEFPROP_WC = DUK_DEFPROP_WRITABLE or DUK_DEFPROP_CONFIGURABLE;
DUK_DEFPROP_WEC = DUK_DEFPROP_WRITABLE or DUK_DEFPROP_ENUMERABLE or DUK_DEFPROP_CONFIGURABLE;
DUK_DEFPROP_HAVE_W = DUK_DEFPROP_HAVE_WRITABLE;
DUK_DEFPROP_HAVE_E = DUK_DEFPROP_HAVE_ENUMERABLE;
DUK_DEFPROP_HAVE_C = DUK_DEFPROP_HAVE_CONFIGURABLE;
DUK_DEFPROP_HAVE_WE = DUK_DEFPROP_HAVE_WRITABLE or DUK_DEFPROP_HAVE_ENUMERABLE;
DUK_DEFPROP_HAVE_WC = DUK_DEFPROP_HAVE_WRITABLE or DUK_DEFPROP_HAVE_CONFIGURABLE;
DUK_DEFPROP_HAVE_WEC = DUK_DEFPROP_HAVE_WRITABLE or DUK_DEFPROP_HAVE_ENUMERABLE or DUK_DEFPROP_HAVE_CONFIGURABLE;
DUK_DEFPROP_SET_W = DUK_DEFPROP_SET_WRITABLE;
DUK_DEFPROP_SET_E = DUK_DEFPROP_SET_ENUMERABLE;
DUK_DEFPROP_SET_C = DUK_DEFPROP_SET_CONFIGURABLE;
DUK_DEFPROP_SET_WE = DUK_DEFPROP_SET_WRITABLE or DUK_DEFPROP_SET_ENUMERABLE;
DUK_DEFPROP_SET_WC = DUK_DEFPROP_SET_WRITABLE or DUK_DEFPROP_SET_CONFIGURABLE;
DUK_DEFPROP_SET_WEC = DUK_DEFPROP_SET_WRITABLE or DUK_DEFPROP_SET_ENUMERABLE or DUK_DEFPROP_SET_CONFIGURABLE;
DUK_DEFPROP_CLEAR_W = DUK_DEFPROP_CLEAR_WRITABLE;
DUK_DEFPROP_CLEAR_E = DUK_DEFPROP_CLEAR_ENUMERABLE;
DUK_DEFPROP_CLEAR_C = DUK_DEFPROP_CLEAR_CONFIGURABLE;
DUK_DEFPROP_CLEAR_WE = DUK_DEFPROP_CLEAR_WRITABLE or DUK_DEFPROP_CLEAR_ENUMERABLE;
DUK_DEFPROP_CLEAR_WC = DUK_DEFPROP_CLEAR_WRITABLE or DUK_DEFPROP_CLEAR_CONFIGURABLE;
DUK_DEFPROP_CLEAR_WEC = DUK_DEFPROP_CLEAR_WRITABLE or DUK_DEFPROP_CLEAR_ENUMERABLE or DUK_DEFPROP_CLEAR_CONFIGURABLE;
DUK_DEFPROP_ATTR_W = DUK_DEFPROP_HAVE_WEC or DUK_DEFPROP_W;
DUK_DEFPROP_ATTR_E = DUK_DEFPROP_HAVE_WEC or DUK_DEFPROP_E;
DUK_DEFPROP_ATTR_C = DUK_DEFPROP_HAVE_WEC or DUK_DEFPROP_C;
DUK_DEFPROP_ATTR_WE = DUK_DEFPROP_HAVE_WEC or DUK_DEFPROP_WE;
DUK_DEFPROP_ATTR_WC = DUK_DEFPROP_HAVE_WEC or DUK_DEFPROP_WC;
DUK_DEFPROP_ATTR_WEC = DUK_DEFPROP_HAVE_WEC or DUK_DEFPROP_WEC;
(* Flags for duk_push_thread_raw() *)
const
DUK_THREAD_NEW_GLOBAL_ENV = 1 shl 0; (* create a new global environment *)
(* Flags for duk_gc() *)
const
DUK_GC_COMPACT = 1 shl 0; (* compact heap objects *)
(* Error codes (must be 8 bits at most, see duk_error.h) *)
const
DUK_ERR_NONE = 0; (* no error (e.g. from duk_get_error_code()) *)
DUK_ERR_ERROR = 1; (* Error *)
DUK_ERR_EVAL_ERROR = 2; (* EvalError *)
DUK_ERR_RANGE_ERROR = 3; (* RangeError *)
DUK_ERR_REFERENCE_ERROR = 4; (* ReferenceError *)
DUK_ERR_SYNTAX_ERROR = 5; (* SyntaxError *)
DUK_ERR_TYPE_ERROR = 6; (* TypeError *)
DUK_ERR_URI_ERROR = 7; (* URIError *)
(* Return codes for C functions (shortcut for throwing an error) *)
const
DUK_RET_ERROR = -DUK_ERR_ERROR;
DUK_RET_EVAL_ERROR = -DUK_ERR_EVAL_ERROR;
DUK_RET_RANGE_ERROR = -DUK_ERR_RANGE_ERROR;
DUK_RET_REFERENCE_ERROR = -DUK_ERR_REFERENCE_ERROR;
DUK_RET_SYNTAX_ERROR = -DUK_ERR_SYNTAX_ERROR;
DUK_RET_TYPE_ERROR = -DUK_ERR_TYPE_ERROR;
DUK_RET_URI_ERROR = -DUK_ERR_URI_ERROR;
(* Return codes for protected calls (duk_safe_call(), duk_pcall()) *)
const
DUK_EXEC_SUCCESS = 0;
DUK_EXEC_ERROR = 1;
(* Debug levels for DUK_USE_DEBUG_WRITE(). *)
const
DUK_LEVEL_DEBUG = 0;
DUK_LEVEL_DDEBUG = 1;
DUK_LEVEL_DDDEBUG = 2;
(*
* Macros to create Symbols as C statically constructed strings.
*
* Call e.g. as DUK_HIDDEN_SYMBOL("myProperty") <=> ("\xFF" "myProperty").
* Local symbols have a unique suffix, caller should take care to avoid
* conflicting with the Duktape internal representation by e.g. prepending
* a '!' character: DUK_LOCAL_SYMBOL("myLocal", "!123").
*
* Note that these can only be used for string constants, not dynamically
* created strings.
*)
function DUK_HIDDEN_SYMBOL(const AX: UTF8String): UTF8String; inline;
function DUK_GLOBAL_SYMBOL(const AX: UTF8String): UTF8String; inline;
function DUK_LOCAL_SYMBOL(const AX, AUniq: UTF8String): UTF8String; inline;
function DUK_WELLKNOWN_SYMBOL(const AX: UTF8String): UTF8String; inline;
(*
* Context management
*)
function duk_create_heap(alloc_func: TDukAllocFunction; realloc_func: TDukReallocFunction; free_func: TDukFreeFunction; heap_udata: Pointer; fatal_handler: TDukFatalFunction): PDukContext; cdecl external LIB_DUKTAPE name PREFIX + 'duk_create_heap';
procedure duk_destroy_heap(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_destroy_heap';
procedure duk_suspend(ctx: PDukContext; state: PDukThreadState); cdecl external LIB_DUKTAPE name PREFIX + 'duk_suspend';
procedure duk_resume(ctx: PDukContext; const state: PDukThreadState); cdecl external LIB_DUKTAPE name PREFIX + 'duk_resume';
function duk_create_heap_default: PDukContext; inline;
(*
* Memory management
*
* Raw functions have no side effects (cannot trigger GC).
*)
function duk_alloc_raw(ctx: PDukContext; size: TDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_alloc_raw';
procedure duk_free_raw(ctx: PDukContext; ptr: Pointer); cdecl external LIB_DUKTAPE name PREFIX + 'duk_free_raw';
function duk_realloc_raw(ctx: PDukContext; ptr: Pointer; size: TDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_realloc_raw';
function duk_alloc(ctx: PDukContext; size: TDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_alloc';
procedure duk_free(ctx: PDukContext; ptr: Pointer); cdecl external LIB_DUKTAPE name PREFIX + 'duk_free';
function duk_realloc(ctx: PDukContext; ptr: Pointer; size: TDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_realloc';
procedure duk_get_memory_functions(ctx: PDukContext; out_funcs: PDukMemoryFunctions); cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_memory_functions';
procedure duk_gc(ctx: PDukContext; flags: TDukUInt); cdecl external LIB_DUKTAPE name PREFIX + 'duk_gc';
(*
* Error handling
*)
procedure duk_throw_raw(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_throw_raw';
procedure duk_throw(ctx: PDukContext); inline;
procedure duk_fatal_raw(ctx: PDukContext; const err_msg: MarshaledAString); cdecl external LIB_DUKTAPE name PREFIX + 'duk_fatal_raw';
procedure duk_fatal(ctx: PDukContext; const err_msg: MarshaledAString); inline;
procedure duk_error_raw(ctx: PDukContext; err_code: TDukErrCode; const filename: MarshaledAString; const line: TDukInt; const fmt: MarshaledAString); varargs; cdecl external LIB_DUKTAPE name PREFIX + 'duk_error_raw';
procedure duk_error(ctx: PDukContext; err_code: TDukErrCode; const fmt: MarshaledAString); inline;
procedure duk_generic_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
procedure duk_eval_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
procedure duk_range_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
procedure duk_reference_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
procedure duk_syntax_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
procedure duk_type_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
procedure duk_uri_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
(*
* Other state related functions
*)
function duk_is_strict_call(ctx: PDukContext): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_strict_call';
function duk_is_constructor_call(ctx: PDukContext): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_constructor_call';
(*
* Stack management
*)
function duk_normalize_index(ctx: PDukContext; idx: TDukIdx): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_normalize_index';
function duk_require_normalize_index(ctx: PDukContext; idx: TDukIdx): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_normalize_index';
function duk_is_valid_index(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_valid_index';
procedure duk_require_valid_index(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_valid_index';
function duk_get_top(ctx: PDukContext): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_top';
procedure duk_set_top(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_set_top';
function duk_get_top_index(ctx: PDukContext): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_top_index';
function duk_require_top_index(ctx: PDukContext): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_top_index';
(* Although extra/top could be an unsigned type here, using a signed type
* makes the API more robust to calling code calculation errors or corner
* cases (where caller might occasionally come up with negative values).
* Negative values are treated as zero, which is better than casting them
* to a large unsigned number. (This principle is used elsewhere in the
* API too.)
*)
function duk_check_stack(ctx: PDukContext; extra: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_check_stack';
procedure duk_require_stack(ctx: PDukContext; extra: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_stack';
function duk_check_stack_top(ctx: PDukContext; top: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_check_stack_top';
procedure duk_require_stack_top(ctx: PDukContext; top: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_stack_top';
(*
* Stack manipulation (other than push/pop)
*)
procedure duk_swap(ctx: PDukContext; idx1: TDukIdx; idx2: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_swap';
procedure duk_swap_top(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_swap_top';
procedure duk_dup(ctx: PDukContext; from_idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_dup';
procedure duk_dup_top(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_dup_top';
procedure duk_insert(ctx: PDukContext; to_idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_insert';
procedure duk_replace(ctx: PDukContext; to_idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_replace';
procedure duk_copy(ctx: PDukContext; from_idx: TDukIdx; to_idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_copy';
procedure duk_remove(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_remove';
procedure duk_xcopymove_raw(to_ctx: PDukContext; from_ctx: PDukContext; count: TDukIdx; is_copy: TDukBool); cdecl external LIB_DUKTAPE name PREFIX + 'duk_xcopymove_raw';
procedure duk_xmove_top(to_ctx: PDukContext; from_ctx: PDukContext; count: TDukIdx); inline;
procedure duk_xcopy_top(to_ctx: PDukContext; from_ctx: PDukContext; count: TDukIdx); inline;
(*
* Push operations
*
* Push functions return the absolute (relative to bottom of frame)
* position of the pushed value for convenience.
*
* Note: duk_dup() is technically a push.
*)
procedure duk_push_undefined(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_undefined';
procedure duk_push_null(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_null';
procedure duk_push_boolean(ctx: PDukContext; val: TDukBool); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_boolean';
procedure duk_push_true(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_true';
procedure duk_push_false(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_false';
procedure duk_push_number(ctx: PDukContext; val: TDukDouble); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_number';
procedure duk_push_nan(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_nan';
procedure duk_push_int(ctx: PDukContext; val: TDukInt); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_int';
procedure duk_push_uint(ctx: PDukContext; val: TDukUInt); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_uint';
function duk_push_string(ctx: PDukContext; const str: MarshaledAString): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_string';
function duk_push_lstring(ctx: PDukContext; const str: MarshaledAString; len: TDukSize): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_lstring';
procedure duk_push_pointer(ctx: PDukContext; p: Pointer); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_pointer';
function duk_push_sprintf(ctx: PDukContext; const fmt: MarshaledAString): MarshaledAString; cdecl; varargs external LIB_DUKTAPE name PREFIX + 'duk_push_sprintf';
function duk_push_literal(ctx: PDukContext; const str: MarshaledAString): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_string';
procedure duk_push_this(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_this';
procedure duk_push_new_target(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_new_target';
procedure duk_push_current_function(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_current_function';
procedure duk_push_current_thread(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_current_thread';
procedure duk_push_global_object(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_global_object';
procedure duk_push_heap_stash(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_heap_stash';
procedure duk_push_global_stash(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_global_stash';
procedure duk_push_thread_stash(ctx: PDukContext; target_ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_thread_stash';
function duk_push_object(ctx: PDukContext): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_object';
function duk_push_bare_object(ctx: PDukContext): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_bare_object';
function duk_push_array(ctx: PDukContext): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_array';
function duk_push_c_function(ctx: PDukContext; func: TDukCFunction; nargs: TDukIdx): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_c_function';
function duk_push_c_lightfunc(ctx: PDukContext; func: TDukCFunction; nargs: TDukIdx; length: TDukIdx; magic: TDukInt): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_c_lightfunc';
function duk_push_thread_raw(ctx: PDukContext; flags: TDukUInt): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_thread_raw';
function duk_push_proxy(ctx: PDukContext; proxy_flags: TDukUInt): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_proxy';
function duk_push_thread(ctx: PDukContext): TDukIdx; inline;
function duk_push_thread_new_globalenv(ctx: PDukContext): TDukIdx; inline;
function duk_push_error_object_raw(ctx: PDukContext; err_code: TDukErrcode; const filename: MarshaledAString; line: TDukInt; const fmt: MarshaledAString): TDukIdx; cdecl; varargs external LIB_DUKTAPE name PREFIX + 'duk_push_error_object_raw';
function duk_push_error_object(ctx: PDukContext; err_code: TDukErrcode; const fmt: MarshaledAString): TDukIdx; inline;
const
DUK_BUF_FLAG_DYNAMIC = 1 shl 0; (* internal flag: dynamic buffer *)
DUK_BUF_FLAG_EXTERNAL = 1 shl 1; (* internal flag: external buffer *)
DUK_BUF_FLAG_NOZERO = 1 shl 2; (* internal flag: don't zero allocated buffer *)
function duk_push_buffer_raw(ctx: PDukContext; size: TDukSize; flags: TDukSmallUInt): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_buffer_raw';
function duk_push_buffer(ctx: PDukContext; size: TDukSize; dynamic: Boolean): Pointer; inline;
function duk_push_fixed_buffer(ctx: PDukContext; size: TDukSize): Pointer; inline;
function duk_push_dynamic_buffer(ctx: PDukContext; size: TDukSize): Pointer; inline;
function duk_push_external_buffer(ctx: PDukContext): Pointer; inline;
const
DUK_BUFOBJ_ARRAYBUFFER = 0;
DUK_BUFOBJ_NODEJS_BUFFER = 1;
DUK_BUFOBJ_DATAVIEW = 2;
DUK_BUFOBJ_INT8ARRAY = 3;
DUK_BUFOBJ_UINT8ARRAY = 4;
DUK_BUFOBJ_UINT8CLAMPEDARRAY = 5;
DUK_BUFOBJ_INT16ARRAY = 6;
DUK_BUFOBJ_UINT16ARRAY = 7;
DUK_BUFOBJ_INT32ARRAY = 8;
DUK_BUFOBJ_UINT32ARRAY = 9;
DUK_BUFOBJ_FLOAT32ARRAY = 10;
DUK_BUFOBJ_FLOAT64ARRAY = 11;
procedure duk_push_buffer_object(ctx: PDukContext; idx_buffer: TDukIdx; byte_offset: TDukSize; byte_length: TDukSize; flags: TDukUInt); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_buffer_object';
function duk_push_heapptr(ctx: PDukContext; ptr: Pointer): TDukIdx; cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_heapptr';
(*
* Pop operations
*)
procedure duk_pop(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_pop';
procedure duk_pop_n(ctx: PDukContext; count: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_pop_n';
procedure duk_pop_2(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_pop_2';
procedure duk_pop_3(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_pop_3';
(*
* Type checks
*
* duk_is_none(), which would indicate whether index it outside of stack,
* is not needed; duk_is_valid_index() gives the same information.
*)
function duk_get_type(ctx: PDukContext; idx: TDukIdx): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_type';
function duk_check_type(ctx: PDukContext; idx: TDukIdx; _type: TDukInt): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_check_type';
function duk_get_type_mask(ctx: PDukContext; idx: TDukIdx): TDukUInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_type_mask';
function duk_check_type_mask(ctx: PDukContext; idx: TDukIdx; mask: TDukUInt): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_check_type_mask';
function duk_is_undefined(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_undefined';
function duk_is_null(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_null';
function duk_is_null_or_undefined(ctx: PDukContext; idx: TDukIdx): TDukBool; inline;
function duk_is_boolean(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_boolean';
function duk_is_number(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_number';
function duk_is_nan(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_nan';
function duk_is_string(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_string';
function duk_is_object(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_object';
function duk_is_buffer(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_buffer';
function duk_is_buffer_data(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_buffer_data';
function duk_is_pointer(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_pointer';
function duk_is_lightfunc(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_lightfunc';
function duk_is_symbol(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_symbol';
function duk_is_array(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_array';
function duk_is_function(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_function';
function duk_is_c_function(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_c_function';
function duk_is_ecmascript_function(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_ecmascript_function';
function duk_is_bound_function(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_bound_function';
function duk_is_thread(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_thread';
function duk_is_callable(ctx: PDukContext; idx: TDukIdx): TDukBool; inline;
function duk_is_constructable(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_constructable';
function duk_is_dynamic_buffer(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_dynamic_buffer';
function duk_is_fixed_buffer(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_fixed_buffer';
function duk_is_external_buffer(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_is_external_buffer';
(* Buffers and lightfuncs are not considered primitive because they mimic
* objects and e.g. duk_to_primitive() will coerce them instead of returning
* them as is. Symbols are represented as strings internally.
*)
function duk_is_primitive(ctx: PDukContext; idx: TDukIdx): TDukBool; inline;
(* Symbols are object coercible, covered by DUK_TYPE_MASK_STRING. *)
function duk_is_object_coercible(ctx: PDukContext; idx: TDukIdx): TDukBool; inline;
function duk_get_error_code(ctx: PDukContext; idx: TDukIdx): TDukErrcode; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_error_code';
function duk_is_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
function duk_is_eval_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
function duk_is_range_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
function duk_is_reference_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
function duk_is_syntax_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
function duk_is_type_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
function duk_is_uri_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
(*
* Get operations: no coercion, returns default value for invalid
* indices and invalid value types.
*
* duk_get_undefined() and duk_get_null() would be pointless and
* are not included.
*)
function duk_get_boolean(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_boolean';
function duk_get_number(ctx: PDukContext; idx: TDukIdx): TDukDouble; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_number';
function duk_get_int(ctx: PDukContext; idx: TDukIdx): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_int';
function duk_get_uint(ctx: PDukContext; idx: TDukIdx): TDukUInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_uint';
function duk_get_string(ctx: PDukContext; idx: TDukIdx): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_string';
function duk_get_lstring(ctx: PDukContext; idx: TDukIdx; out_len: PDukSize): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_lstring';
function duk_get_buffer(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_buffer';
function duk_get_buffer_data(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_buffer_data';
function duk_get_pointer(ctx: PDukContext; idx: TDukIdx): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_pointer';
function duk_get_c_function(ctx: PDukContext; idx: TDukIdx): TDukCFunction; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_c_function';
function duk_get_context(ctx: PDukContext; idx: TDukIdx): PDukContext; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_context';
function duk_get_heapptr(ctx: PDukContext; idx: TDukIdx): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_heapptr';
(*
* Get-with-explicit default operations: like get operations but with an
* explicit default value.
*)
function duk_get_boolean_default(ctx: PDukContext; idx: TDukIdx; def_value: TDukBool): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_boolean_default';
function duk_get_number_default(ctx: PDukContext; idx: TDukIdx; def_value: TDukDouble): TDukDouble; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_number_default';
function duk_get_int_default(ctx: PDukContext; idx: TDukIdx; def_value: TDukInt): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_int_default';
function duk_get_uint_default(ctx: PDukContext; idx: TDukIdx; def_value: TDukUInt): TDukUInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_uint_default';
function duk_get_string_default(ctx: PDukContext; idx: TDukIdx; const def_value: MarshaledAString): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_string_default';
function duk_get_lstring_default(ctx: PDukContext; idx: TDukIdx; out_len: PDukSize; const def_ptr: MarshaledAString; def_len: TDukSize): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_lstring_default';
function duk_get_buffer_default(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize; def_ptr: Pointer; def_len: TDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_buffer_default';
function duk_get_buffer_data_default(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize; def_ptr: Pointer; def_len: TDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_buffer_data_default';
function duk_get_pointer_default(ctx: PDukContext; idx: TDukIdx; def_value: Pointer): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_pointer_default';
function duk_get_c_function_default(ctx: PDukContext; idx: TDukIdx; def_value: TDukCFunction): TDukCFunction; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_c_function_default';
function duk_get_context_default(ctx: PDukContext; idx: TDukIdx; def_value: PDukContext): PDukContext; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_context_default';
function duk_get_heapptr_default(ctx: PDukContext; idx: TDukIdx; def_value: Pointer): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_heapptr_default';
(*
* Opt operations: like require operations but with an explicit default value
* when value is undefined or index is invalid, null and non-matching types
* cause a TypeError.
*)
function duk_opt_boolean(ctx: PDukContext; idx: TDukIdx; def_value: TDukBool): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_boolean';
function duk_opt_number(ctx: PDukContext; idx: TDukIdx; def_value: TDukDouble): TDukDouble; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_number';
function duk_opt_int(ctx: PDukContext; idx: TDukIdx; def_value: TDukInt): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_int';
function duk_opt_uint(ctx: PDukContext; idx: TDukIdx; def_value: TDukUInt): TDukUInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_uint';
function duk_opt_string(ctx: PDukContext; idx: TDukIdx; const def_ptr: MarshaledAString): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_string';
function duk_opt_lstring(ctx: PDukContext; idx: TDukIdx; out_len: PDukSize; const def_ptr: MarshaledAString; def_len: TDukSize): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_lstring';
function duk_opt_buffer(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize; def_ptr: Pointer; def_size: TDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_buffer';
function duk_opt_buffer_data(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize; def_ptr: Pointer; def_size: TDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_buffer_data';
function duk_opt_pointer(ctx: PDukContext; idx: TDukIdx; def_value: Pointer): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_pointer';
function duk_opt_c_function(ctx: PDukContext; idx: TDukIdx; def_value: TDukCFunction): TDukCFunction; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_c_function';
function duk_opt_context(ctx: PDukContext; idx: TDukIdx; def_value: PDukContext): PDukContext; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_context';
function duk_opt_heapptr(ctx: PDukContext; idx: TDukIdx; def_value: Pointer): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_opt_heapptr';
(*
* Require operations: no coercion, throw error if index or type
* is incorrect. No defaulting.
*)
procedure duk_require_type_mask(ctx: PDukContext; idx: TDukIdx; mask: TDukUInt); inline;
procedure duk_require_undefined(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_undefined';
procedure duk_require_null(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_null';
function duk_require_boolean(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_boolean';
function duk_require_number(ctx: PDukContext; idx: TDukIdx): TDukDouble; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_number';
function duk_require_int(ctx: PDukContext; idx: TDukIdx): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_int';
function duk_require_uint(ctx: PDukContext; idx: TDukIdx): TDukUInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_uint';
function duk_require_string(ctx: PDukContext; idx: TDukIdx): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_string';
function duk_require_lstring(ctx: PDukContext; idx: TDukIdx; out_len: PDukSize): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_lstring';
procedure duk_require_object(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_object';
function duk_require_buffer(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_buffer';
function duk_require_buffer_data(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_buffer_data';
function duk_require_pointer(ctx: PDukContext; idx: TDukIdx): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_pointer';
function duk_require_c_function(ctx: PDukContext; idx: TDukIdx): TDukCFunction; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_c_function';
function duk_require_context(ctx: PDukContext; idx: TDukIdx): PDukContext; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_context';
procedure duk_require_function(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_function';
procedure duk_require_callable(ctx: PDukContext; idx: TDukIdx); inline;
function duk_require_heapptr(ctx: PDukContext; idx: TDukIdx): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_require_heapptr';
(* Symbols are object coercible and covered by DUK_TYPE_MASK_STRING. *)
procedure duk_require_object_coercible(ctx: PDukContext; idx: TDukIdx); inline;
(*
* Coercion operations: in-place coercion, return coerced value where
* applicable. If index is invalid, throw error. Some coercions may
* throw an expected error (e.g. from a toString() or valueOf() call)
* or an internal error (e.g. from out of memory).
*)
procedure duk_to_undefined(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_undefined';
procedure duk_to_null(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_null';
function duk_to_boolean(ctx: PDukContext; idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_boolean';
function duk_to_number(ctx: PDukContext; idx: TDukIdx): TDukDouble; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_number';
function duk_to_int(ctx: PDukContext; idx: TDukIdx): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_int';
function duk_to_uint(ctx: PDukContext; idx: TDukIdx): TDukUInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_uint';
function duk_to_int32(ctx: PDukContext; idx: TDukIdx): TDukInt32; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_int32';
function duk_to_uint32(ctx: PDukContext; idx: TDukIdx): TDukUInt32; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_uint32';
function duk_to_uint16(ctx: PDukContext; idx: TDukIdx): TDukUInt16; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_uint16';
function duk_to_string(ctx: PDukContext; idx: TDukIdx): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_string';
function duk_to_lstring(ctx: PDukContext; idx: TDukIdx; out_len: PDukSize): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_lstring';
function duk_to_buffer_raw(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize; flags: TDukUInt): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_buffer_raw';
function duk_to_pointer(ctx: PDukContext; idx: TDukIdx): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_pointer';
procedure duk_to_object(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_object';
procedure duk_to_primitive(ctx: PDukContext; idx: TDukIdx; hint: TDukInt); cdecl external LIB_DUKTAPE name PREFIX + 'duk_to_primitive';
const
DUK_BUF_MODE_FIXED = 0; (* internal: request fixed buffer result *)
DUK_BUF_MODE_DYNAMIC = 1; (* internal: request dynamic buffer result *)
DUK_BUF_MODE_DONTCARE = 2; (* internal: don't care about fixed/dynamic nature *)
function duk_to_buffer(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; inline;
function duk_to_fixed_buffer(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; inline;
function duk_to_dynamic_buffer(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; inline;
(* safe variants of a few coercion operations *)
function duk_safe_to_lstring(ctx: PDukContext; idx: TDukIdx; out_len: PDukSize): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_safe_to_lstring';
function duk_safe_to_string(ctx: PDukContext; idx: TDukIdx): MarshaledAString; inline;
(*
* Value length
*)
function duk_get_length(ctx: PDukContext; idx: TDukIdx): TDukSize; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_length';
procedure duk_set_length(ctx: PDukContext; idx: TDukIdx; len: TDukSize); cdecl external LIB_DUKTAPE name PREFIX + 'duk_set_length';
(*
* Misc conversion
*)
function duk_base64_encode(ctx: PDukContext; idx: TDukIdx): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_base64_encode';
procedure duk_base64_decode(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_base64_decode';
function duk_hex_encode(ctx: PDukContext; idx: TDukIdx): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_hex_encode';
procedure duk_hex_decode(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_hex_decode';
function duk_json_encode(ctx: PDukContext; idx: TDukIdx): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_json_encode';
procedure duk_json_decode(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_json_decode';
function duk_buffer_to_string(ctx: PDukContext; idx: TDukIdx): MarshaledAString; cdecl external LIB_DUKTAPE name PREFIX + 'duk_buffer_to_string';
(*
* Buffer
*)
function duk_resize_buffer(ctx: PDukContext; idx: TDukIdx; new_size: TDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_resize_buffer';
function duk_steal_buffer(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; cdecl external LIB_DUKTAPE name PREFIX + 'duk_steal_buffer';
procedure duk_config_buffer(ctx: PDukContext; idx: TDukIdx; ptr: Pointer; len: TDukSize); cdecl external LIB_DUKTAPE name PREFIX + 'duk_config_buffer';
(*
* Property access
*
* The basic function assumes key is on stack. The _(l)string variant takes
* a C string as a property name; the _literal variant takes a C literal.
* The _index variant takes an array index as a property name (e.g. 123 is
* equivalent to the key "123"). The _heapptr variant takes a raw, borrowed
* heap pointer.
*)
function duk_get_prop(ctx: PDukContext; obj_idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_prop';
function duk_get_prop_string(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_prop_string';
function duk_get_prop_literal(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_prop_string';
function duk_get_prop_lstring(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString; key_len: TDukSize): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_prop_lstring';
function duk_get_prop_index(ctx: PDukContext; obj_idx: TDukIdx; arr_idx: TDukUArrIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_prop_index';
function duk_get_prop_heapptr(ctx: PDukContext; obj_idx: TDukIdx; ptr: Pointer): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_prop_heapptr';
function duk_put_prop(ctx: PDukContext; obj_idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_prop';
function duk_put_prop_string(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_prop_string';
function duk_put_prop_literal(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_prop_string';
function duk_put_prop_lstring(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString; key_len: TDukSize): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_prop_lstring';
function duk_put_prop_index(ctx: PDukContext; obj_idx: TDukIdx; arr_idx: TDukUArrIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_prop_index';
function duk_put_prop_heapptr(ctx: PDukContext; obj_idx: TDukIdx; ptr: Pointer): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_prop_heapptr';
function duk_del_prop(ctx: PDukContext; obj_idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_del_prop';
function duk_del_prop_string(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_del_prop_string';
function duk_del_prop_literal(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_del_prop_string';
function duk_del_prop_lstring(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString; key_len: TDukSize): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_del_prop_lstring';
function duk_del_prop_index(ctx: PDukContext; obj_idx: TDukIdx; arr_idx: TDukUArrIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_del_prop_index';
function duk_del_prop_heapptr(ctx: PDukContext; obj_idx: TDukIdx; ptr: Pointer): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_del_prop_heapptr';
function duk_has_prop(ctx: PDukContext; obj_idx: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_has_prop';
function duk_has_prop_string(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_has_prop_string';
function duk_has_prop_literal(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_has_prop_string';
function duk_has_prop_lstring(ctx: PDukContext; obj_idx: TDukIdx; const key: MarshaledAString; key_len: TDukSize): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_has_prop_lstring';
function duk_has_prop_index(ctx: PDukContext; obj_idx: TDukIdx; arr_idx: TDukUArrIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_has_prop_index';
function duk_has_prop_heapptr(ctx: PDukContext; obj_idx: TDukIdx; ptr: Pointer): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_has_prop_heapptr';
procedure duk_get_prop_desc(ctx: PDukContext; obj_idx: TDukIdx; flags: TDukUInt); cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_prop_desc';
procedure duk_def_prop(ctx: PDukContext; obj_idx: TDukIdx; flags: TDukUInt); cdecl external LIB_DUKTAPE name PREFIX + 'duk_def_prop';
function duk_get_global_string(ctx: PDukContext; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_global_string';
function duk_get_global_literal(ctx: PDukContext; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_global_string';
function duk_get_global_heapptr(ctx: PDukContext; const ptr: Pointer): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_global_heapptr';
function duk_get_global_lstring(ctx: PDukContext; const key: MarshaledAString; key_len: TDukSize): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_global_lstring';
function duk_put_global_string(ctx: PDukContext; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_global_string';
function duk_put_global_literal(ctx: PDukContext; const key: MarshaledAString): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_global_string';
function duk_put_global_lstring(ctx: PDukContext; const key: MarshaledAString; key_len: TDukSize): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_global_lstring';
function duk_put_global_heapptr(ctx: PDukContext; const ptr: Pointer): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_global_heapptr';
(*
* Inspection
*)
procedure duk_inspect_value(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_inspect_value';
procedure duk_inspect_callstack_entry(ctx: PDukContext; level: TDukInt); cdecl external LIB_DUKTAPE name PREFIX + 'duk_inspect_callstack_entry';
(*
* Object prototype
*)
procedure duk_get_prototype(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_prototype';
procedure duk_set_prototype(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_set_prototype';
(*
* Object finalizer
*)
procedure duk_get_finalizer(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_finalizer';
procedure duk_set_finalizer(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_set_finalizer';
(*
* Global object
*)
procedure duk_set_global_object(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_set_global_object';
(*
* Duktape/C function magic value
*)
function duk_get_magic(ctx: PDukContext; idx: TDukIdx): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_magic';
procedure duk_set_magic(ctx: PDukContext; idx: TDukIdx; magic: TDukInt); cdecl external LIB_DUKTAPE name PREFIX + 'duk_set_magic';
function duk_get_current_magic(ctx: PDukContext): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_current_magic';
(*
* Module helpers: put multiple function or constant properties
*)
procedure duk_put_function_list(ctx: PDukContext; obj_idx: TDukIdx; const funcs: PDukFunctionListEntry); cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_function_list';
procedure duk_put_number_list(ctx: PDukContext; obj_idx: TDukIdx; const numbers: PDukNumberListEntry); cdecl external LIB_DUKTAPE name PREFIX + 'duk_put_number_list';
(*
* Object operations
*)
procedure duk_compact(ctx: PDukContext; obj_idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_compact';
procedure duk_enum(ctx: PDukContext; obj_idx: TDukIdx; enum_flags: TDukUInt); cdecl external LIB_DUKTAPE name PREFIX + 'duk_enum';
function duk_next(ctx: PDukContext; enum_idx: TDukIdx; get_value: TDukBool): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_next';
procedure duk_seal(ctx: PDukContext; obj_idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_seal';
procedure duk_freeze(ctx: PDukContext; obj_idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_freeze';
(*
* String manipulation
*)
procedure duk_concat(ctx: PDukContext; count: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_concat';
procedure duk_join(ctx: PDukContext; count: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_join';
procedure duk_decode_string(ctx: PDukContext; idx: TDukIdx; callback: TDukDecodeCharFunction; udata: Pointer); cdecl external LIB_DUKTAPE name PREFIX + 'duk_decode_string';
procedure duk_map_string(ctx: PDukContext; idx: TDukIdx; callback: TDukMapCharFunction; udata: Pointer); cdecl external LIB_DUKTAPE name PREFIX + 'duk_map_string';
procedure duk_substring(ctx: PDukContext; idx: TDukIdx; start_char_offset: TDukSize; end_char_offset: TDukSize); cdecl external LIB_DUKTAPE name PREFIX + 'duk_substring';
procedure duk_trim(ctx: PDukContext; idx: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_trim';
function duk_char_code_at(ctx: PDukContext; idx: TDukIdx; char_offset: TDukSize): TDukCodepoint; cdecl external LIB_DUKTAPE name PREFIX + 'duk_char_code_at';
(*
* ECMAScript operators
*)
function duk_equals(ctx: PDukContext; idx1: TDukIdx; idx2: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_equals';
function duk_strict_equals(ctx: PDukContext; idx1: TDukIdx; idx2: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_strict_equals';
function duk_samevalue(ctx: PDukContext; idx1: TDukIdx; idx2: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_samevalue';
function duk_instanceof(ctx: PDukContext; idx1: TDukIdx; idx2: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_instanceof';
(*
* Random
*)
function duk_random(ctx: PDukContext): TDukDouble; cdecl external LIB_DUKTAPE name PREFIX + 'duk_random';
(*
* Function (method) calls
*)
procedure duk_call(ctx: PDukContext; nargs: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_call';
procedure duk_call_method(ctx: PDukContext; nargs: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_call_method';
procedure duk_call_prop(ctx: PDukContext; obj_idx: TDukIdx; nargs: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_call_prop';
function duk_pcall(ctx: PDukContext; nargs: TDukIdx): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_pcall';
function duk_pcall_method(ctx: PDukContext; nargs: TDukIdx): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_pcall_method';
function duk_pcall_prop(ctx: PDukContext; obj_idx: TDukIdx; nargs: TDukIdx): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_pcall_prop';
procedure duk_new(ctx: PDukContext; nargs: TDukIdx); cdecl external LIB_DUKTAPE name PREFIX + 'duk_new';
function duk_pnew(ctx: PDukContext; nargs: TDukIdx): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_pnew';
function duk_safe_call(ctx: PDukContext; func: TDukSafeCallFunction; udata: Pointer; nargs: TDukIdx; nrets: TDukIdx): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_safe_call';
(*
* Thread management
*)
(* There are currently no native functions to yield/resume, due to the internal
* limitations on coroutine handling. These will be added later.
*)
(*
* Compilation and evaluation
*)
function duk_eval_raw(ctx: PDukContext; const src_buffer: MarshaledAString; src_length: TDukSize; flags: TDukUInt): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_eval_raw';
function duk_compile_raw(ctx: PDukContext; const src_buffer: MarshaledAString; src_length: TDukSize; flags: TDukUInt): TDukInt; cdecl external LIB_DUKTAPE name PREFIX + 'duk_compile_raw';
(* plain *)
function duk_eval(ctx: PDukContext): TDukInt; inline;
function duk_eval_noresult(ctx: PDukContext): TDukInt; inline;
function duk_peval(ctx: PDukContext): TDukInt; inline;
function duk_peval_noresult(ctx: PDukContext): TDukInt; inline;
function duk_compile(ctx: PDukContext; flags: TDukUInt): TDukInt; inline;
function duk_pcompile(ctx: PDukContext; flags: TDukUInt): TDukInt; inline;
(* string *)
function duk_eval_string(ctx: PDukContext; const src: MarshaledAString): TDukInt; inline;
function duk_eval_string_noresult(ctx: PDukContext; const src: MarshaledAString): TDukInt; inline;
function duk_peval_string(ctx: PDukContext; const src: MarshaledAString): TDukInt; inline;
function duk_peval_string_noresult(ctx: PDukContext; const src: MarshaledAString): TDukInt; inline;
function duk_compile_string(ctx: PDukContext; flags: TDukUInt; const src: MarshaledAString): TDukInt; inline;
function duk_compile_string_filename(ctx: PDukContext; flags: TDukUInt; const src: MarshaledAString): TDukInt; inline;
function duk_pcompile_string(ctx: PDukContext; flags: TDukUInt; const src: MarshaledAString): TDukInt; inline;
function duk_pcompile_string_filename(ctx: PDukContext; flags: TDukUInt; const src: MarshaledAString): TDukInt; inline;
(* lstring *)
function duk_eval_lstring(ctx: PDukContext; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
function duk_eval_lstring_noresult(ctx: PDukContext; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
function duk_peval_lstring(ctx: PDukContext; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
function duk_peval_lstring_noresult(ctx: PDukContext; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
function duk_compile_lstring(ctx: PDukContext; flags: TDukUInt; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
function duk_compile_lstring_filename(ctx: PDukContext; flags: TDukUInt; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
function duk_pcompile_lstring(ctx: PDukContext; flags: TDukUInt; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
function duk_pcompile_lstring_filename(ctx: PDukContext; flags: TDukUInt; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
(*
* Bytecode load/dump
*)
procedure duk_dump_function(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_dump_function';
procedure duk_load_function(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_load_function';
(*
* Debugging
*)
procedure duk_push_context_dump(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_push_context_dump';
(*
* Debugger (debug protocol)
*)
procedure duk_debugger_attach(ctx: PDukContext; read_cb: TDukDebugReadFunction; write_cb: TDukDebugWriteFunction; peek_cb: TDukDebugPeekFunction; read_flush_cb: TDukDebugReadFlushFunction; write_flush_cb: TDukDebugWriteFlushFunction; request_cb: TDukDebugRequestFunction; detached_cb: TDukDebugDetachedFunction; udata: Pointer); cdecl external LIB_DUKTAPE name PREFIX + 'duk_debugger_attach';
procedure duk_debugger_detach(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_debugger_detach';
procedure duk_debugger_cooperate(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_debugger_cooperate';
function duk_debugger_notify(ctx: PDukContext; nvalues: TDukIdx): TDukBool; cdecl external LIB_DUKTAPE name PREFIX + 'duk_debugger_notify';
procedure duk_debugger_pause(ctx: PDukContext); cdecl external LIB_DUKTAPE name PREFIX + 'duk_debugger_pause';
(*
* Time handling
*)
function duk_get_now(ctx: PDukContext): TDukDouble; cdecl external LIB_DUKTAPE name PREFIX + 'duk_get_now';
procedure duk_time_to_components(ctx: PDukContext; timeval: TDukDouble; comp: PDukTimeComponents); cdecl external LIB_DUKTAPE name PREFIX + 'duk_time_to_components';
function duk_components_to_time(ctx: PDukContext; comp: PDukTimeComponents): TDukDouble; cdecl external LIB_DUKTAPE name PREFIX + 'duk_components_to_time';
(*
* Date provider related constants
*
* NOTE: These are "semi public" - you should only use these if you write
* your own platform specific Date provider, see doc/datetime.rst.
*)
(* Millisecond count constants. *)
const
DUK_DATE_MSEC_SECOND = 1000;
DUK_DATE_MSEC_MINUTE = 60 * 1000;
DUK_DATE_MSEC_HOUR = 60 * 60 * 1000;
DUK_DATE_MSEC_DAY = 24 * 60 * 60 * 1000;
(* ECMAScript date range is 100 million days from Epoch:
* > 100e6 * 24 * 60 * 60 * 1000 // 100M days in millisecs
* 8640000000000000
* (= 8.64e15)
*)
const
DUK_DATE_MSEC_100M_DAYS = 8.64e15;
DUK_DATE_MSEC_100M_DAYS_LEEWAY = 8.64e15 + 24 * 3600e3;
(* ECMAScript year range:
* > new Date(100e6 * 24 * 3600e3).toISOString()
* '+275760-09-13T00:00:00.000Z'
* > new Date(-100e6 * 24 * 3600e3).toISOString()
* '-271821-04-20T00:00:00.000Z'
*)
const
DUK_DATE_MIN_ECMA_YEAR = -271821;
DUK_DATE_MAX_ECMA_YEAR = 275760;
(* Part indices for internal breakdowns. Part order from DUK_DATE_IDX_YEAR
* to DUK_DATE_IDX_MILLISECOND matches argument ordering of ECMAScript API
* calls (like Date constructor call). Some functions in duk_bi_date.c
* depend on the specific ordering, so change with care. 16 bits are not
* enough for all parts (year, specifically).
*
* Must be in-sync with genbuiltins.py.
*)
const
DUK_DATE_IDX_YEAR = 0; (* year *)
DUK_DATE_IDX_MONTH = 1; (* month: 0 to 11 *)
DUK_DATE_IDX_DAY = 2; (* day within month: 0 to 30 *)
DUK_DATE_IDX_HOUR = 3;
DUK_DATE_IDX_MINUTE = 4;
DUK_DATE_IDX_SECOND = 5;
DUK_DATE_IDX_MILLISECOND = 6;
DUK_DATE_IDX_WEEKDAY = 7; (* weekday: 0 to 6, 0=sunday, 1=monday, etc *)
DUK_DATE_IDX_NUM_PARTS = 8;
(* Internal API call flags, used for various functions in duk_bi_date.c.
* Certain flags are used by only certain functions, but since the flags
* don't overlap, a single flags value can be passed around to multiple
* functions.
*
* The unused top bits of the flags field are also used to pass values
* to helpers (duk__get_part_helper() and duk__set_part_helper()).
*
* Must be in-sync with genbuiltins.py.
*)
(* NOTE: when writing a Date provider you only need a few specific
* flags from here, the rest are internal. Avoid using anything you
* don't need.
*)
const
DUK_DATE_FLAG_NAN_TO_ZERO = 1 shl 0; (* timeval breakdown: internal time value NaN -> zero *)
DUK_DATE_FLAG_NAN_TO_RANGE_ERROR = 1 shl 1; (* timeval breakdown: internal time value NaN -> RangeError (toISOString) *)
DUK_DATE_FLAG_ONEBASED = 1 shl 2; (* timeval breakdown: convert month and day-of-month parts to one-based (default is zero-based) *)
DUK_DATE_FLAG_EQUIVYEAR = 1 shl 3; (* timeval breakdown: replace year with equivalent year in the [1971,2037] range for DST calculations *)
DUK_DATE_FLAG_LOCALTIME = 1 shl 4; (* convert time value to local time *)
DUK_DATE_FLAG_SUB1900 = 1 shl 5; (* getter: subtract 1900 from year when getting year part *)
DUK_DATE_FLAG_TOSTRING_DATE = 1 shl 6; (* include date part in string conversion result *)
DUK_DATE_FLAG_TOSTRING_TIME = 1 shl 7; (* include time part in string conversion result *)
DUK_DATE_FLAG_TOSTRING_LOCALE = 1 shl 8; (* use locale specific formatting if available *)
DUK_DATE_FLAG_TIMESETTER = 1 shl 9; (* setter: call is a time setter (affects hour, min, sec, ms); otherwise date setter (affects year, month, day-in-month) *)
DUK_DATE_FLAG_YEAR_FIXUP = 1 shl 10; (* setter: perform 2-digit year fixup (00...99 -> 1900...1999) *)
DUK_DATE_FLAG_SEP_T = 1 shl 11; (* string conversion: use 'T' instead of ' ' as a separator *)
DUK_DATE_FLAG_VALUE_SHIFT = 12; (* additional values begin at bit 12 *)
(*
* END PUBLIC API
*)
implementation
function DUK_HIDDEN_SYMBOL(const AX: UTF8String): UTF8String; inline;
begin
Result := #$FF + AX;
end;
function DUK_GLOBAL_SYMBOL(const AX: UTF8String): UTF8String; inline;
begin
Result := #$80 + AX;
end;
function DUK_LOCAL_SYMBOL(const AX, AUniq: UTF8String): UTF8String; inline;
begin
Result := #$81 + AX + #$FF + AUniq;
end;
function DUK_WELLKNOWN_SYMBOL(const AX: UTF8String): UTF8String; inline;
begin
Result := #$81 + AX + #$FF;
end;
function duk_create_heap_default: PDukContext; inline;
begin
Result := duk_create_heap(nil, nil, nil, nil, nil);
end;
procedure duk_throw(ctx: PDukContext); inline;
begin
duk_throw_raw(ctx);
end;
procedure duk_fatal(ctx: PDukContext; const err_msg: MarshaledAString); inline;
begin
duk_fatal_raw(ctx, err_msg);
end;
procedure duk_error(ctx: PDukContext; err_code: TDukErrCode; const fmt: MarshaledAString); inline;
begin
duk_error_raw(ctx, err_code, nil, 0, fmt);
end;
procedure duk_generic_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
begin
duk_error_raw(ctx, DUK_ERR_ERROR, nil, 0, fmt);
end;
procedure duk_eval_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
begin
duk_error_raw(ctx, DUK_ERR_EVAL_ERROR, nil, 0, fmt);
end;
procedure duk_range_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
begin
duk_error_raw(ctx, DUK_ERR_RANGE_ERROR, nil, 0, fmt);
end;
procedure duk_reference_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
begin
duk_error_raw(ctx, DUK_ERR_REFERENCE_ERROR, nil, 0, fmt);
end;
procedure duk_syntax_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
begin
duk_error_raw(ctx, DUK_ERR_SYNTAX_ERROR, nil, 0, fmt);
end;
procedure duk_type_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
begin
duk_error_raw(ctx, DUK_ERR_TYPE_ERROR, nil, 0, fmt);
end;
procedure duk_uri_error(ctx: PDukContext; const fmt: MarshaledAString); inline;
begin
duk_error_raw(ctx, DUK_ERR_URI_ERROR, nil, 0, fmt);
end;
procedure duk_xmove_top(to_ctx: PDukContext; from_ctx: PDukContext; count: TDukIdx); inline;
begin
duk_xcopymove_raw(to_ctx, from_ctx, count, 0);
end;
procedure duk_xcopy_top(to_ctx: PDukContext; from_ctx: PDukContext; count: TDukIdx); inline;
begin
duk_xcopymove_raw(to_ctx, from_ctx, count, 1);
end;
function duk_push_thread(ctx: PDukContext): TDukIdx; inline;
begin
Result := duk_push_thread_raw(ctx, 0);
end;
function duk_push_thread_new_globalenv(ctx: PDukContext): TDukIdx; inline;
begin
Result := duk_push_thread_raw(ctx, DUK_THREAD_NEW_GLOBAL_ENV);
end;
function duk_push_error_object(ctx: PDukContext; err_code: TDukErrcode; const fmt: MarshaledAString): TDukIdx; inline;
begin
Result := duk_push_error_object_raw(ctx, err_code, nil, 0, fmt);
end;
function duk_push_buffer(ctx: PDukContext; size: TDukSize; dynamic: Boolean): Pointer; inline;
begin
if (dynamic) then
Result := duk_push_buffer_raw(ctx, size, DUK_BUF_FLAG_DYNAMIC)
else
Result := duk_push_buffer_raw(ctx, size, 0);
end;
function duk_push_fixed_buffer(ctx: PDukContext; size: TDukSize): Pointer; inline;
begin
Result := duk_push_buffer_raw(ctx, size, 0);
end;
function duk_push_dynamic_buffer(ctx: PDukContext; size: TDukSize): Pointer; inline;
begin
Result := duk_push_buffer_raw(ctx, size, DUK_BUF_FLAG_DYNAMIC);
end;
function duk_push_external_buffer(ctx: PDukContext): Pointer; inline;
begin
Result := duk_push_buffer_raw(ctx, 0, DUK_BUF_FLAG_DYNAMIC or DUK_BUF_FLAG_EXTERNAL);
end;
function duk_is_null_or_undefined(ctx: PDukContext; idx: TDukIdx): TDukBool; inline;
begin
Result := Ord((duk_get_type_mask(ctx, idx) and (DUK_TYPE_MASK_NULL or DUK_TYPE_MASK_UNDEFINED)) <> 0);
end;
function duk_is_callable(ctx: PDukContext; idx: TDukIdx): TDukBool; inline;
begin
Result := duk_is_function(ctx, idx);
end;
function duk_is_primitive(ctx: PDukContext; idx: TDukIdx): TDukBool; inline;
begin
Result := duk_check_type_mask(ctx, idx, DUK_TYPE_MASK_UNDEFINED or
DUK_TYPE_MASK_NULL or DUK_TYPE_MASK_BOOLEAN or DUK_TYPE_MASK_NUMBER or
DUK_TYPE_MASK_STRING or DUK_TYPE_MASK_POINTER);
end;
function duk_is_object_coercible(ctx: PDukContext; idx: TDukIdx): TDukBool; inline;
begin
Result := duk_check_type_mask(ctx, idx, DUK_TYPE_MASK_BOOLEAN or
DUK_TYPE_MASK_NUMBER or DUK_TYPE_MASK_STRING or DUK_TYPE_MASK_OBJECT or
DUK_TYPE_MASK_BUFFER or DUK_TYPE_MASK_POINTER or DUK_TYPE_MASK_LIGHTFUNC);
end;
function duk_is_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
begin
Result := (duk_get_error_code(ctx, idx) <> 0);
end;
function duk_is_eval_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
begin
Result := (duk_get_error_code(ctx, idx) = DUK_ERR_EVAL_ERROR);
end;
function duk_is_range_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
begin
Result := (duk_get_error_code(ctx, idx) = DUK_ERR_RANGE_ERROR);
end;
function duk_is_reference_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
begin
Result := (duk_get_error_code(ctx, idx) = DUK_ERR_REFERENCE_ERROR);
end;
function duk_is_syntax_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
begin
Result := (duk_get_error_code(ctx, idx) = DUK_ERR_SYNTAX_ERROR);
end;
function duk_is_type_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
begin
Result := (duk_get_error_code(ctx, idx) = DUK_ERR_TYPE_ERROR);
end;
function duk_is_uri_error(ctx: PDukContext; idx: TDukIdx): Boolean; inline;
begin
Result := (duk_get_error_code(ctx, idx) = DUK_ERR_URI_ERROR);
end;
procedure duk_require_type_mask(ctx: PDukContext; idx: TDukIdx; mask: TDukUInt); inline;
begin
duk_check_type_mask(ctx, idx, mask or DUK_TYPE_MASK_THROW);
end;
procedure duk_require_callable(ctx: PDukContext; idx: TDukIdx); inline;
begin
duk_require_function(ctx, idx);
end;
procedure duk_require_object_coercible(ctx: PDukContext; idx: TDukIdx); inline;
begin
duk_check_type_mask(ctx, idx, DUK_TYPE_MASK_BOOLEAN or DUK_TYPE_MASK_NUMBER or
DUK_TYPE_MASK_STRING or DUK_TYPE_MASK_OBJECT or DUK_TYPE_MASK_BUFFER or
DUK_TYPE_MASK_POINTER or DUK_TYPE_MASK_LIGHTFUNC or DUK_TYPE_MASK_THROW);
end;
function duk_to_buffer(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; inline;
begin
Result := duk_to_buffer_raw(ctx, idx, out_size, DUK_BUF_MODE_DONTCARE);
end;
function duk_to_fixed_buffer(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; inline;
begin
Result := duk_to_buffer_raw(ctx, idx, out_size, DUK_BUF_MODE_FIXED);
end;
function duk_to_dynamic_buffer(ctx: PDukContext; idx: TDukIdx; out_size: PDukSize): Pointer; inline;
begin
Result := duk_to_buffer_raw(ctx, idx, out_size, DUK_BUF_MODE_DYNAMIC);
end;
function duk_safe_to_string(ctx: PDukContext; idx: TDukIdx): MarshaledAString; inline;
begin
Result := duk_safe_to_lstring(ctx, idx, nil);
end;
function duk_eval(ctx: PDukContext): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, nil, 0, 1 or DUK_COMPILE_EVAL
or DUK_COMPILE_NOFILENAME);
end;
function duk_eval_noresult(ctx: PDukContext): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, nil, 0, 1 or DUK_COMPILE_EVAL
or DUK_COMPILE_NOFILENAME or DUK_COMPILE_NORESULT);
end;
function duk_peval(ctx: PDukContext): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, nil, 0, 1 or DUK_COMPILE_EVAL
or DUK_COMPILE_NOFILENAME or DUK_COMPILE_SAFE);
end;
function duk_peval_noresult(ctx: PDukContext): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, nil, 0, 1 or DUK_COMPILE_EVAL
or DUK_COMPILE_NOFILENAME or DUK_COMPILE_SAFE or DUK_COMPILE_NORESULT);
end;
function duk_compile(ctx: PDukContext; flags: TDukUInt): TDukInt; inline;
begin
Result := duk_compile_raw(ctx, nil, 0, 2 or flags);
end;
function duk_pcompile(ctx: PDukContext; flags: TDukUInt): TDukInt; inline;
begin
Result := duk_compile_raw(ctx, nil, 0, 2 or flags or DUK_COMPILE_SAFE);
end;
function duk_eval_string(ctx: PDukContext; const src: MarshaledAString): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, src, 0, DUK_COMPILE_EVAL or DUK_COMPILE_NOSOURCE
or DUK_COMPILE_STRLEN or DUK_COMPILE_NOFILENAME);
end;
function duk_eval_string_noresult(ctx: PDukContext; const src: MarshaledAString): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, src, 0, DUK_COMPILE_EVAL or DUK_COMPILE_NOSOURCE
or DUK_COMPILE_STRLEN or DUK_COMPILE_NOFILENAME or DUK_COMPILE_NORESULT);
end;
function duk_peval_string(ctx: PDukContext; const src: MarshaledAString): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, src, 0, DUK_COMPILE_EVAL or DUK_COMPILE_NOSOURCE
or DUK_COMPILE_STRLEN or DUK_COMPILE_NOFILENAME or DUK_COMPILE_SAFE);
end;
function duk_peval_string_noresult(ctx: PDukContext; const src: MarshaledAString): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, src, 0, DUK_COMPILE_EVAL or DUK_COMPILE_NOSOURCE
or DUK_COMPILE_STRLEN or DUK_COMPILE_NOFILENAME or DUK_COMPILE_SAFE
or DUK_COMPILE_NORESULT);
end;
function duk_compile_string(ctx: PDukContext; flags: TDukUInt; const src: MarshaledAString): TDukInt; inline;
begin
Result := duk_compile_raw(ctx, nil, 0, flags or DUK_COMPILE_NOSOURCE or
DUK_COMPILE_STRLEN or DUK_COMPILE_NOFILENAME);
end;
function duk_compile_string_filename(ctx: PDukContext; flags: TDukUInt; const src: MarshaledAString): TDukInt; inline;
begin
Result := duk_compile_raw(ctx, nil, 0, 1 or flags or DUK_COMPILE_NOSOURCE or
DUK_COMPILE_STRLEN);
end;
function duk_pcompile_string(ctx: PDukContext; flags: TDukUInt; const src: MarshaledAString): TDukInt; inline;
begin
Result := duk_compile_raw(ctx, nil, 0, flags or DUK_COMPILE_NOSOURCE or
DUK_COMPILE_STRLEN or DUK_COMPILE_NOFILENAME or DUK_COMPILE_SAFE);
end;
function duk_pcompile_string_filename(ctx: PDukContext; flags: TDukUInt; const src: MarshaledAString): TDukInt; inline;
begin
Result := duk_compile_raw(ctx, nil, 0, 1 or flags or DUK_COMPILE_NOSOURCE or
DUK_COMPILE_STRLEN or DUK_COMPILE_SAFE);
end;
function duk_eval_lstring(ctx: PDukContext; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, buf, len, DUK_COMPILE_EVAL or DUK_COMPILE_NOSOURCE
or DUK_COMPILE_NOFILENAME);
end;
function duk_eval_lstring_noresult(ctx: PDukContext; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, buf, len, DUK_COMPILE_EVAL or DUK_COMPILE_NOSOURCE
or DUK_COMPILE_NOFILENAME or DUK_COMPILE_NORESULT);
end;
function duk_peval_lstring(ctx: PDukContext; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, buf, len, DUK_COMPILE_EVAL or DUK_COMPILE_NOSOURCE
or DUK_COMPILE_NOFILENAME or DUK_COMPILE_SAFE);
end;
function duk_peval_lstring_noresult(ctx: PDukContext; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
begin
Result := duk_eval_raw(ctx, buf, len, DUK_COMPILE_EVAL or DUK_COMPILE_NOSOURCE
or DUK_COMPILE_NOFILENAME or DUK_COMPILE_SAFE or DUK_COMPILE_NORESULT);
end;
function duk_compile_lstring(ctx: PDukContext; flags: TDukUInt; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
begin
Result := duk_compile_raw(ctx, buf, len, flags or DUK_COMPILE_NOSOURCE or
DUK_COMPILE_NOFILENAME);
end;
function duk_compile_lstring_filename(ctx: PDukContext; flags: TDukUInt; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
begin
Result := duk_compile_raw(ctx, buf, len, 1 or flags or DUK_COMPILE_NOSOURCE);
end;
function duk_pcompile_lstring(ctx: PDukContext; flags: TDukUInt; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
begin
Result := duk_compile_raw(ctx, buf, len, flags or DUK_COMPILE_NOSOURCE or
DUK_COMPILE_NOFILENAME or DUK_COMPILE_SAFE);
end;
function duk_pcompile_lstring_filename(ctx: PDukContext; flags: TDukUInt; const buf: MarshaledAString; len: TDukSize): TDukInt; inline;
begin
Result := duk_compile_raw(ctx, buf, len, 1 or flags or DUK_COMPILE_NOSOURCE
or DUK_COMPILE_SAFE);
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: dlgToolProperties
Author: Kiriakos Vlahos
Date: 04-Jun-2005
Purpose: Dialog for specifying command-line tool properties
History:
-----------------------------------------------------------------------------}
unit dlgToolProperties;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cTools, ExtCtrls, StdCtrls, JvExStdCtrls, JvCheckBox, SynEdit,
JvGroupBox, ComCtrls, JvExComCtrls, JvHotKey, Mask, JvExMask,
JvSpin, Menus, ActnList, TBXDkPanels;
type
TToolProperties = class(TForm)
Panel1: TPanel;
btnOK: TButton;
btnCancel: TButton;
FormatsPopup: TPopupMenu;
Filename1: TMenuItem;
Linenumber1: TMenuItem;
Columnnumber1: TMenuItem;
PageControl: TPageControl;
tsProperties: TTabSheet;
tsEnvironment: TTabSheet;
JvGroupBox1: TJvGroupBox;
Label1: TLabel;
Label5: TLabel;
Label14: TLabel;
edDescription: TEdit;
edName: TEdit;
JvGroupBox2: TJvGroupBox;
Label2: TLabel;
Label6: TLabel;
Label7: TLabel;
Label3: TLabel;
SynApplication: TSynEdit;
SynParameters: TSynEdit;
SynWorkDir: TSynEdit;
btnAppDir: TButton;
btnWorkDir: TButton;
JvGroupBox4: TJvGroupBox;
Label4: TLabel;
Label8: TLabel;
Label13: TLabel;
hkShortCut: TJvHotKey;
JvGroupBox3: TJvGroupBox;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
cbCaptureOutput: TJvCheckBox;
cbParseMessages: TJvCheckBox;
edMessagesFormat: TEdit;
btnStdFormats: TButton;
JvGroupBox5: TJvGroupBox;
Label9: TLabel;
cbHideConsole: TJvCheckBox;
cbWaitForTermination: TJvCheckBox;
seTimeout: TJvSpinEdit;
cbParseTraceback: TJvCheckBox;
lvItems: TListView;
JvGroupBox6: TJvGroupBox;
Label15: TLabel;
Label16: TLabel;
edEnvName: TEdit;
ActionList: TActionList;
actAddItem: TAction;
actDeleteItem: TAction;
actMoveUp: TAction;
actMoveDown: TAction;
actUpdateItem: TAction;
edEnvValue: TEdit;
cbUseCustomEnv: TJvCheckBox;
btnHelp: TButton;
TBXButton1: TTBXButton;
TBXButton3: TTBXButton;
TBXButton4: TTBXButton;
TBXButton5: TTBXButton;
TBXButton2: TTBXButton;
cbStandardInput: TComboBox;
cbStandardOutput: TComboBox;
cbContext: TComboBox;
cbSaveFiles: TComboBox;
procedure FormShow(Sender: TObject);
procedure btnStdFormatsClick(Sender: TObject);
procedure Filename1Click(Sender: TObject);
procedure SynApplicationEnter(Sender: TObject);
procedure SynParametersEnter(Sender: TObject);
procedure SynWorkDirEnter(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnWorkDirClick(Sender: TObject);
procedure btnAppDirClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actAddItemExecute(Sender: TObject);
procedure actDeleteItemExecute(Sender: TObject);
procedure actMoveUpExecute(Sender: TObject);
procedure actMoveDownExecute(Sender: TObject);
procedure actUpdateItemExecute(Sender: TObject);
procedure lvItemsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
procedure btnHelpClick(Sender: TObject);
private
{ Private declarations }
fEnvStrings : TStrings;
public
{ Public declarations }
end;
function EditTool(Tool : TExternalTool) : Boolean;
implementation
uses dmCommands, JvBrowseFolder, JclSysInfo;
{$R *.dfm}
function EditTool(Tool : TExternalTool) : Boolean;
Var
i : integer;
begin
Result := False;
if not Assigned(Tool) then Exit;
with TToolProperties.Create(Application) do
try
with Tool do begin
edName.Text := Caption;
edDescription.Text := Description;
SynApplication.Text := ApplicationName;
SynParameters.Text := Parameters;
SynWorkDir.Text := WorkingDirectory;
cbContext.ItemIndex := Integer(Context);
hkShortCut.HotKey := ShortCut;
cbSaveFiles.ItemIndex := Integer(SaveFiles);
cbStandardInput.ItemIndex := Integer(ProcessInput);
cbStandardOutput.ItemIndex := Integer(ProcessOutput);
cbCaptureOutput.Checked := CaptureOutput;
seTimeOut.Value := TimeOut;
cbWaitForTermination.Checked := WaitForTerminate;
cbHideConsole.Checked := ConsoleHidden;
cbParseMessages.Checked := ParseMessages;
cbParseTraceback.Checked := ParseTraceback;
edMessagesFormat.Text := MessagesFormat;
cbUseCustomEnv.Checked := UseCustomEnvironment;
if UseCustomEnvironment then
fEnvStrings.Assign(Environment)
else
GetEnvironmentVars(fEnvStrings);
end;
Result := (ShowModal = mrOK) and (edName.Text <> '');
if Result then with Tool do begin
Caption := edName.Text;
Description := edDescription.Text;
ApplicationName := SynApplication.Text;
Parameters := SynParameters.Text;
WorkingDirectory := SynWorkDir.Text;
Context := TToolContext(cbContext.ItemIndex);
ShortCut := hkShortCut.HotKey;
SaveFiles := TSaveFiles(cbSaveFiles.ItemIndex);
ProcessInput := TProcessStdInputOption(cbStandardInput.ItemIndex);
ProcessOutput := TProcessStdOutputOption(cbStandardOutput.ItemIndex);
CaptureOutput := cbCaptureOutput.Checked;
TimeOut := Trunc(seTimeOut.Value);
WaitForTerminate := cbWaitForTermination.Checked;
ConsoleHidden := cbHideConsole.Checked;
ParseMessages := cbParseMessages.Checked;
ParseTraceback := cbParseTraceback.Checked;
MessagesFormat := edMessagesFormat.Text;
UseCustomEnvironment := cbUseCustomEnv.Checked;
Environment.Clear;
if UseCustomEnvironment then begin
for i := 0 to lvItems.Items.Count - 1 do
Environment.Add(lvItems.Items[i].Caption + '=' + lvItems.Items[i].SubItems[0]);
end;
end;
cbParseMessages.LinkedControls.Clear; // workaround to JVCL bug in JvCheckBox
finally
Release;
end;
end;
procedure TToolProperties.btnStdFormatsClick(Sender: TObject);
var
p: TPoint;
begin
p:= btnStdFormats.ClientToScreen(Point(btnStdFormats.Width, 0));
FormatsPopup.Popup(p.x, p.y);
end;
procedure TToolProperties.Filename1Click(Sender: TObject);
begin
case (Sender as TMenuItem).Tag of
0: edMessagesFormat.SelText := GrepFileNameParam;
1: edMessagesFormat.SelText := GrepLineNumberParam;
2: edMessagesFormat.SelText := GrepColumnNumberParam;
end;
edMessagesFormat.SetFocus;
end;
procedure TToolProperties.SynApplicationEnter(Sender: TObject);
begin
CommandsDataModule.ParameterCompletion.Editor := SynApplication;
CommandsDataModule.ModifierCompletion.Editor := SynApplication;
end;
procedure TToolProperties.SynParametersEnter(Sender: TObject);
begin
CommandsDataModule.ParameterCompletion.Editor := SynParameters;
CommandsDataModule.ModifierCompletion.Editor := SynParameters;
end;
procedure TToolProperties.SynWorkDirEnter(Sender: TObject);
begin
CommandsDataModule.ParameterCompletion.Editor := SynWorkDir;
CommandsDataModule.ModifierCompletion.Editor := SynWorkDir;
end;
procedure TToolProperties.FormCreate(Sender: TObject);
begin
fEnvStrings := TStringList.Create;
end;
procedure TToolProperties.FormDestroy(Sender: TObject);
begin
fEnvStrings.Free;
CommandsDataModule.ParameterCompletion.Editor := nil;
CommandsDataModule.ModifierCompletion.Editor := nil;
end;
procedure TToolProperties.btnWorkDirClick(Sender: TObject);
var
S: string;
begin
S := '';
if BrowseDirectory(S, 'Select working directory:', 0) then begin
SynWorkDir.SelText := S;
SynWorkDir.SetFocus;
end;
end;
procedure TToolProperties.btnAppDirClick(Sender: TObject);
begin
with CommandsDataModule.dlgFileOpen do begin
Title := 'Select application or file to execute';
Filter := 'Executable Files (*.exe;*.bat;*.cmd)|*.exe;*.bat;*.cmd|All files|*.*|';
if Execute then begin
SynApplication.SelText := FileName;
SynApplication.SetFocus;
end;
end;
end;
procedure TToolProperties.actAddItemExecute(Sender: TObject);
Var
Item : TListItem;
i : Integer;
begin
if edEnvName.Text <> '' then begin
for i := 0 to lvItems.Items.Count - 1 do
if CompareText(lvItems.Items[i].Caption, EdEnvName.Text) = 0 then begin
Item := lvItems.Items[i];
Item.Caption := EdEnvName.Text;
Item.SubItems[0] := EdEnvValue.Text;
Item.Selected := True;
Exit;
end;
with lvItems.Items.Add() do begin
Caption := edEnvName.Text;
SubItems.Add(edEnvValue.Text);
end;
end;end;
procedure TToolProperties.actDeleteItemExecute(Sender: TObject);
begin
if lvItems.ItemIndex >= 0 then
lvItems.Items.Delete(lvItems.ItemIndex);
end;
procedure TToolProperties.actMoveUpExecute(Sender: TObject);
Var
Name, Value : string;
Index : integer;
begin
if lvItems.ItemIndex > 0 then begin
Index := lvItems.ItemIndex;
Name := lvItems.Items[Index].Caption;
Value := lvItems.Items[Index].SubItems[0];
lvItems.Items.Delete(Index);
with lvItems.Items.Insert(Index - 1) do begin
Caption := Name;
SubItems.Add(Value);
Selected := True;
end;
end;
end;
procedure TToolProperties.actMoveDownExecute(Sender: TObject);
Var
Name, Value : string;
Index : integer;
begin
if lvItems.ItemIndex < lvItems.Items.Count - 1 then begin
Index := lvItems.ItemIndex;
Name := lvItems.Items[Index].Caption;
Value := lvItems.Items[Index].SubItems[0];
lvItems.Items.Delete(Index);
with lvItems.Items.Insert(Index + 1) do begin
Caption := Name;
SubItems.Add(Value);
Selected := True;
end;
end;
end;
procedure TToolProperties.actUpdateItemExecute(Sender: TObject);
Var
i : integer;
begin
if (edEnvName.Text <> '') and (lvItems.ItemIndex >= 0) then begin
for i := 0 to lvItems.Items.Count - 1 do
if (CompareText(lvItems.Items[i].Caption, edEnvName.Text) = 0) and
(i <> lvItems.ItemIndex) then
begin
MessageDlg('Another item has the same name', mtError, [mbOK], 0);
Exit;
end;
with lvItems.Items[lvItems.ItemIndex] do begin
Caption := EdEnvName.Text;
SubItems[0] := EdEnvValue.Text;
end;
end;
end;
procedure TToolProperties.lvItemsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
if Item.Selected then begin
edEnvName.Text := Item.Caption;
edEnvValue.Text := Item.SubItems[0];
end;
end;
procedure TToolProperties.ActionListUpdate(Action: TBasicAction;
var Handled: Boolean);
begin
actDeleteItem.Enabled := lvItems.ItemIndex >= 0;
actMoveUp.Enabled := lvItems.ItemIndex >= 1;
actMoveDown.Enabled := (lvItems.ItemIndex >= 0) and
(lvItems.ItemIndex < lvItems.Items.Count - 1);
actAddItem.Enabled := edName.Text <> '';
actUpdateItem.Enabled := (edName.Text <> '') and (lvItems.ItemIndex >= 0);
Handled := True;
end;
procedure TToolProperties.btnHelpClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TToolProperties.FormShow(Sender: TObject);
Var
i : integer;
begin
lvItems.Clear;
for i := 0 to fEnvStrings.Count - 1 do
if fEnvStrings.Names[i] <> '' then
with lvItems.Items.Add() do begin
Caption := fEnvStrings.Names[i];
SubItems.Add(fEnvStrings.Values[Caption]);
end;
end;
end.
|
unit FlowTestView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls,
pngimage,
Node, Box;
type
TFlowTestForm = class(TForm)
BoxMemo: TMemo;
Panel: TPanel;
PaintBox: TPaintBox;
Splitter1: TSplitter;
DOMMemo: TMemo;
Splitter3: TSplitter;
Image1: TImage;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure PaintBoxPaint(Sender: TObject);
private
{ Private declarations }
procedure DoDumpNodes(inNodes: TNodeList; inDent: string);
procedure DumpBoxes(inBoxes: TBoxList; inDent: string);
procedure DumpBoxStructure;
procedure DumpDOMStructure;
public
{ Public declarations }
end;
var
FlowTestForm: TFlowTestForm;
implementation
uses
FlowTest, Render3;
var
N: TNode;
B: TBox;
{$R *.dfm}
procedure TFlowTestForm.FormCreate(Sender: TObject);
begin
N := BuildNode;
DumpDOMStructure;
end;
procedure TFlowTestForm.FormResize(Sender: TObject);
begin
//R.Width := ClientWidth - 32;
B.Free;
B := BuildBox(PaintBox.Canvas, N);
DumpBoxStructure;
PaintBox.Invalidate;
end;
procedure TFlowTestForm.PaintBoxPaint(Sender: TObject);
begin
RenderBox(B, PaintBox.Canvas, PaintBox.ClientRect);
end;
procedure TFlowTestForm.DoDumpNodes(inNodes: TNodeList; inDent: string);
var
i: Integer;
node: TNode;
s: string;
begin
for i := 0 to Pred(inNodes.Count) do
begin
node := inNodes[i];
if (node <> nil) then
begin
s := Format('%s| (%d) [%s: %s] => [%s] ',
[ inDent, i, {node.Element}'', node.ClassName, node.Text ]);
DOMMemo.Lines.Add(s);
if node.Nodes <> nil then
DoDumpNodes(node.Nodes, inDent + '--');
end;
end;
end;
procedure TFlowTestForm.DumpDOMStructure;
begin
DOMMemo.Lines.BeginUpdate;
try
DOMMemo.Lines.Clear;
DOMMemo.Lines.Add('DOM Structure:');
DoDumpNodes(N.Nodes, '');
finally
DOMMemo.Lines.EndUpdate;
end;
end;
procedure TFlowTestForm.DumpBoxes(inBoxes: TBoxList; inDent: string);
var
i: Integer;
box: TBox;
s, t: string;
begin
if inBoxes <> nil then
for i := 0 to Pred(inBoxes.Count) do
begin
box := inBoxes[i];
if (box <> nil) then
begin
t := '';
if box.Node <> nil then
t := box.Node.Text;
s := Format('%s| (%d) [%s] [%d, %d => %d, %d] [%d, %d] => [%s] ',
[ inDent, i, {box.Name}'', box.Left, box.Top, box.Width, box.Height,
box.Offset.X, box.Offset.Y, t ]);
//if (box.Node <> nil) then
// s := s + '(' + box.className + ')';
BoxMemo.Lines.Add(s);
DumpBoxes(box.Boxes, inDent + '--');
end;
end;
end;
procedure TFlowTestForm.DumpBoxStructure;
begin
try
BoxMemo.Lines.BeginUpdate;
BoxMemo.Lines.Clear;
BoxMemo.Lines.Add('Box Structure:');
DumpBoxes(B.Boxes, '');
finally
BoxMemo.Lines.EndUpdate;
end;
end;
end.
|
unit Utilities;
interface
uses
Windows, Winspool, SysUtils, StdCtrls, ExtCtrls, Forms, Graphics, IniFiles, Grids, DBGrids, Dialogs;
type
TDoc_Info_1 = record
pDocName: pChar;
pOutputFile: pChar;
pDataType: pChar;
end;
function StringToCaseSelect (Selector: string; CaseList: array of string): Integer;
procedure GridDeleteRow(RowNumber: Integer; Grid: TstringGrid);
procedure ResizeStringGrid(strg: TStringGrid; pW: integer);
procedure PrintLabel(PrinterName, Line1, Line2, Line3, Count, SampNr: string; DoBarcode: boolean);
procedure PrintLabelVar(PrinterName, Line1, Line2, Line3, Line4, Count, SampNr, L1L1, L1L2, L1L3, L1L4, L1bc,
L2L1, L2L2, L2L3, L2L4, L2bc: string; DoBarcode: boolean; ReturnSample, CNIsotopA: string);
procedure SaveFileIniStr(const FName, Section, Key, strValue: string);
procedure SaveIniPath(const Path, Section, Key, strValue: string);
function ReadFileIniStrPath(const FName, Section, Key, sDefault: string): string;
function ReadIniPath(const Path, Section, Key, sDefault: string): string;
function ReplaceUmlaute(s: string): string;
{procedure ColourLabel(const lab: TLabel; const valid: boolean); //DigitChecker
function CheckIsInteger(const edit: TLabeledEdit; const lab: TLabel; //DigitChecker
const min: integer = -maxint; const max: integer = maxint): boolean;
}
implementation
const
//Linie 1 - 4
yAddressLine1: string = '0046'; // inch; Abstand in Y-Richtung (Linie 1) '0046'
yAddressLine2: string = '0026'; // inch; Abstand in Y-Richtung (Linie 2) '0032'
yAddressLine3: string = '0015'; // inch; Abstand in Y-Richtung (Linie 3) '0021'
yAddressLine4: string = '0004'; // inch; Abstand in Y-Richtung (Linie 4) '0010'
Label1xAddressLine1: string = '0008'; // inch; Abstand in X-Richtung (Label 1, Linie 1)
Label1xAddressLine2: string = '0008'; // inch; Abstand in X-Richtung (Label 1, Linie 2,3)
Label2xAddressLine1: string = '0140'; // inch; Abstand in X-Richtung (Label 2, Linie 1)
Label2xAddressLine2: string = '0140'; // inch; Abstand in X-Richtung (Label 2, Linie 2,3)
//Barcode
//bcyAddress: string = '0006'; //inch, Abstand in Y-Richtung (barcode), barcode at the bottom
bcyAddress: string = '0039'; //inch, Abstand in Y-Richtung (barcode), barcode at the top
bcLabel1xAddress: string = '0015'; //inch
bcLabel2xAddress: string = '0148'; //inch
ReturnSampleyAddress: string = '0048';
procedure PrintRAW(PrinterName, PrintText: String);
// Printtext must be 8bit ascii and not simple 'string'
// maybe use AnsiString instead of UTF8String
// maybe also WritePrinter(Handle, @PrintText[1], Length(PrintText), N);
var
DocInfo: TDoc_Info_1;
Handle: THandle;
//DocInfo: TDocInfo1;
PrintTextAnsi: AnsiString;
N: DWORD;
begin
if not OpenPrinter(PChar(PrinterName), Handle, nil) then
begin
ShowMessage('Problem printing on: ' + PrinterName + ' (Handle: ' + Handle.ToString + ', Error: ' + SysErrorMessage(GetLastError()) + ')');
Exit;
end;
with DocInfo do
begin
pDocName := PChar('test doc');
pOutputFile := nil;
pDataType := 'RAW';
end;
StartDocPrinter(Handle, 1, @DocInfo);
StartPagePrinter(Handle);
PrintTextAnsi:=PrintText; // change type from string to AnsiString
//WritePrinter(Handle, PChar(PrintText), Length(PrintText), N); //write to printer, change this
WritePrinter(Handle, @PrintTextAnsi[1], Length(PrintTextAnsi), N);
EndPagePrinter(Handle);
EndDocPrinter(Handle);
ClosePrinter(Handle);
end;
procedure PrintLabel(PrinterName, Line1, Line2, Line3, Count, SampNr: string; DoBarcode: boolean);
var
s: AnsiString; // String has to be 8bit AnsiString and not 'string'
function PrinterStart: string;
begin
Result := #$02 + #$1B + 'G1' + #$0D + #$0A + //Selects proper command set for your application (48)
#$02 + 'XD' + #$0D + #$0A + //Selects default module. If default is set with other command moduleparameter, the module selected with this command is used.(45)
#$02 + 'qC' + #$0D + #$0A + //Clears default module.
#$02 + 'Q' + #$0D + #$0A + //Clearing all memory module contents
#$02 + 'n' + #$0D + #$0A + //inch system
#$02 + 'c0000' + #$0D + #$0A + //paper length for continuous paper
#$02 + 'e' + #$0D + #$0A + //edge sensor selection
#$02 + 'M0548' + #$0D + #$0A + //Maximum label length
#$02 + 'S3' + #$0D + #$0A + //Paper feed speed (40)
#$02 + 'L' + #$0D + #$0A + //specifying printing contents setting start
'D11' + #$0D + #$0A + //setting pixel size (57)
'A2' + #$0D + #$0A + //Specifies development method for character and bar code.(54)|
'C0000' + #$0D + #$0A +
'ySWE'; //Selection of a TrueType font symbol set (47)
end;
function LineHeader: string;
begin
Result := #$0D + #$0A + #$1B + 'P00' + #$0D + #$0A; //P00:Specifying space between characters
end;
function BarcodeHeader: string;
begin
Result := #$0D + #$0A + '1o22016'; //Barcode
end;
function TextHeader: string;
begin
Result := '1911A08'; //1: no rotation; 9: Font Number; 11: Horizontal/Vertikal expansion; A08: Font size
end;
function TextEnd: string;
begin
Result := #$0D + #$0A +
'sALABEL' + #$0D + #$0A + //Stores label format into memory module and ends label format.(67)
#$02 + 'V0' + #$0D + #$0A + //With this command, memory switch contents can be changed temporarily.(43)
#$02 + 'O0218' + #$0D + #$0A + //Setting printing position (35)
#$02 + 'f294' + #$0D + #$0A + //peeling (cutting) position (23)
#$02 + 'L' + #$0D + #$0A + //specifying printing contents setting start
'rLABEL' + #$0D + #$0A + //Vielleicht: Detects label position automatically by reflective paper sensor(?)(39)
'D11' + #$0D + #$0A + //setting pixel size (57)
'H15' + #$0D + #$0A + //Sets print density (heat energy is applied to print head).(58)
'P3' + #$0D + #$0A + //Setting printable area speed (60)
'S3' + #$0D + #$0A + //Sets unprintable area speed. (66)
'p3' + #$0D + #$0A; //Setting backfeed speed (61)
end;
function PrinterEnd: string;
begin
Result := #$0D + #$0A + 'E' + #$0D + #$0A; //Ends label format mode and prints
end;
begin
if DoBarcode = false then //CheckBox deaktiviert
begin
s := PrinterStart +
LineHeader + TextHeader + yAddressLine1 + Label1xAddressLine1 + Line1 +
LineHeader + TextHeader + yAddressLine3 + Label1xAddressLine2 + Line3 +
LineHeader + TextHeader + yAddressLine2 + Label1xAddressLine2 + Line2 + //Labelwechsel
LineHeader + TextHeader + yAddressLine1 + Label2xAddressLine1 + Line1 +
LineHeader + TextHeader + yAddressLine3 + Label2xAddressLine2 + Line3 +
LineHeader + TextHeader + yAddressLine2 + Label2xAddressLine2 + Line2 +
TextEnd + Count + PrinterEnd; //Count: "Q000X" Setting number of prints (63)
end
else begin
s := PrinterStart +
LineHeader + TextHeader + yAddressLine1 + Label1xAddressLine1 + Line1 +
BarcodeHeader + bcyAddress + bcLabel1xAddress + SampNr +
LineHeader + TextHeader + yAddressLine3 + Label1xAddressLine2 + Line3 +
LineHeader + TextHeader + yAddressLine2 + Label1xAddressLine2 + Line2 + //Labelwechsel
LineHeader + TextHeader + yAddressLine1 + Label2xAddressLine1 + Line1 +
BarcodeHeader + bcyAddress + bcLabel2xAddress + SampNr +
LineHeader + TextHeader + yAddressLine3 + Label2xAddressLine2 + Line3 +
LineHeader + TextHeader + yAddressLine2 + Label2xAddressLine2 + Line2 +
TextEnd + Count + PrinterEnd;
end;
PrintRAW(PrinterName, s);
end;
// #############################################################
// Prozedur für pLabelDruckTabPages
// #$0D + #$0A = CR LF aka Windows Linebreak
// #############################################################
procedure PrintLabelVar(PrinterName, Line1, Line2, Line3, Line4, Count, SampNr, L1L1, L1L2, L1L3, L1L4, L1bc,
L2L1, L2L2, L2L3, L2L4, L2bc: string; DoBarcode: boolean; ReturnSample, CNIsotopA: string);
var
//t: string;
t: AnsiString; //use UTF8String that is UTF8 (8bit)
function PrinterVarStart: string;
begin
Result := #$02 + #$1B + 'G1' + #$0D + #$0A + //Selects proper command set for your application (48)
#$02 + 'XD' + #$0D + #$0A + //Selects default module. If default is set with other command moduleparameter, the module selected with this command is used.(45)
#$02 + 'qC' + #$0D + #$0A + //Clears default module.
#$02 + 'Q' + #$0D + #$0A + //Clearing all memory module contents
#$02 + 'n' + #$0D + #$0A + //inch system
#$02 + 'c0000' + #$0D + #$0A + //paper length for continuous paper
#$02 + 'e' + #$0D + #$0A + //edge sensor selection
#$02 + 'M0548' + #$0D + #$0A + //Maximum label length
#$02 + 'S3' + #$0D + #$0A + //Paper feed speed (40)
#$02 + 'L' + #$0D + #$0A + //specifying printing contents setting start
'D11' + #$0D + #$0A + //setting pixel size (57)
'A2' + #$0D + #$0A + //Specifies development method for character and bar code.(54)|
'C0000' + #$0D + #$0A +
'ySWE'; //Selection of a TrueType font symbol set (47)
end;
function LineVarHeader: string;
begin
Result := #$0D + #$0A + #$1B + 'P00' + #$0D + #$0A; //P00:Specifying space between characters
end;
function FixedLineVarHeader1: string;
// command to draw a line
// 1X11,000,row(xxxx), column(xxxx)
begin
// Result := #$0D + #$0A + '1X1100000450013l01030001' + #$0D + #$0A; //dicke Linie
Result := #$0D + #$0A + '1X1100000450013l00750001' + #$0D + #$0A; //dicke kurze Linie
end;
function FixedLineVarHeader2: string;
begin
// Result := #$0D + #$0A + '1X1100000450145l01030001' + #$0D + #$0A; //dicke Linie; 1X11000: fixed for Lines, 0045:X, 0145:Y, l01:size, 030:horiz. ausdehn., 001:vertikale ausd
// Result := #$0D + #$0A + '1X1100000450145l01030001' + #$0D + #$0A; //dicke Linie; 1X11000: fixed for Lines, 0045:X, 0145:Y, l01:size, 025:horiz. ausdehn., 001:vertikale ausd
Result := #$0D + #$0A + '1X1100000450145l0750001' + #$0D + #$0A; // dicke kurze Linie
end;
function BarcodeVarHeader: string;
// general layout of code: rotate(1), font(W1c), thick(5), narrow(5), height (000)
begin
//Result := #$0D + #$0A + '1W1c33000'; //DataMatrix: Modulbreite 3 -> also set L1bc = 0109 and L2bc = 0242
Result := #$0D + #$0A + '1W1c66000'; //DataMatrix-Font: W1c, thick: 6, Narrow: 6, height: 000, also set L1bc = 0099 and L2bc = 0232
//Result := #$0D + #$0A + '1W1c99000'; //DataMatrix: Modulbreite 9 -> also set L1bc = 0089 and L2bc = 0222
//Result := #$0D + #$0A + '1o22016'; //Barcode 93
end;
function BarcodeVarEnd: string;
begin
Result := '2000000000';
end;
function ReturnSampleVarHeader: string;
begin
Result := '1911A04'; //1: no rotation; 9: Font Number; 11: Horizontal/Vertikal expansion; A04: Font size
end;
function ReturnSampleText(ReturnSample: string): string;
begin
// showmessage(ReturnSample);
if ReturnSample = '1' then
Begin
Result := 'Ret';
end
else
begin
Result := '';
end;
end;
function CNIsotopAVarEnd: string;
begin
//Result := '2000000000';
end;
function CNIsotopAVarHeader: string;
begin
Result := '1911A05'; //1: no rotation; 9: Font Number; 11: Horizontal/Vertikal expansion; A04: Font size (smallest)
end;
function CNIsotopAText(CNIsotopA: string): string;
begin
if CNIsotopA = '1' then
Begin
Result := 'CN'; //1: no rotation; 9: Font Number; 11: Horizontal/Vertikal expansion; A08: Font size
if ReturnSample = '1' then Result:= ' | ' + Result; // add a ',' between this and ReturnSample Flag
end
else
begin
Result := '';
end;
end;
function ReturnSampleVarEnd: string;
begin
//Result := '2000000000';
end;
function TextVarHeader: string;
// character field defintion (page 1-76) that defines how to print the text
begin
Result := '1911A08'; //1: no rotation; 9: Font Number; 1: Horizontal Expansion; 1:Vertikal Expansion expansion; A08: Font size in pt (only valid if font is set to 9)
end;
function TextVarEnd: string;
begin
Result := #$0D + #$0A +
'sALABEL' + #$0D + #$0A + //Stores label format into memory module and ends label format.(67)
#$02 + 'V0' + #$0D + #$0A + //With this command, memory switch contents can be changed temporarily.(43)
#$02 + 'O0218' + #$0D + #$0A + //Setting printing position (35)
#$02 + 'f294' + #$0D + #$0A + //peeling (cutting) position (23)
#$02 + 'L' + #$0D + #$0A + //specifying printing contents setting start
'rLABEL' + #$0D + #$0A + //Vielleicht: Detects label position automatically by reflective paper sensor(?)(39)
'D11' + #$0D + #$0A + //setting pixel size (57)
'H15' + #$0D + #$0A + //Sets print density (heat energy is applied to print head).(58)
'P3' + #$0D + #$0A + //Setting printable area speed (60)
'S3' + #$0D + #$0A + //Sets unprintable area speed. (66)
'p3' + #$0D + #$0A; //Setting backfeed speed (61)
end;
function PrinterVarEnd: string;
begin
Result := #$0D + #$0A + 'E' + #$0D + #$0A; //Ends label format mode and prints
end;
// generte the string of commands that will be send to the printer
// PrinterVarStart: general printer setup
// LineVarHeader: Specify general setting for this line
// TextVarHeader: specify how exactly the text is being printed (font, size)
// yAddress: y-Position (row number on label)
// xAdress: x-Position (column number on label) e.g. L1L1
// Linex: actual Text to be printed
begin
if DoBarcode = false then //CheckBox deaktiviert, don't print barcode
begin
t := PrinterVarStart +
LineVarHeader + TextVarHeader + yAddressLine1 + L1L1 + Line1 +
LineVarHeader + ReturnSampleVarHeader + ReturnSampleyAddress + '0070' + ReturnSampleText(ReturnSample) + CNIsotopAText(CNIsotopA) +
LineVarHeader + TextVarHeader + yAddressLine4 + L1L4 + Line4 +
LineVarHeader + TextVarHeader + yAddressLine3 + L1L3 + Line3 +
LineVarHeader + TextVarHeader + yAddressLine2 + L1L2 + Line2 +
FixedLineVarHeader1 + //Labelwechsel
LineVarHeader + TextVarHeader + yAddressLine1 + L2L1 + Line1 +
LineVarHeader + ReturnSampleVarHeader + ReturnSampleyAddress + '0205' + ReturnSampleText(ReturnSample) + CNIsotopAText(CNIsotopA) +
LineVarHeader + TextVarHeader + yAddressLine4 + L2L4 + Line4 +
LineVarHeader + TextVarHeader + yAddressLine3 + L2L3 + Line3 +
LineVarHeader + TextVarHeader + yAddressLine2 + L2L2 + Line2 +
FixedLineVarHeader2 +
TextVarEnd + Count + PrinterVarEnd; //Count: "Q000X" Setting number of prints (63)
end
else
begin
t := PrinterVarStart +
LineVarHeader + TextVarHeader + yAddressLine1 + L1L1 + Line1 +
LineVarHeader + ReturnSampleVarHeader + ReturnSampleyAddress + '0070' + ReturnSampleText(ReturnSample) + CNIsotopAText(CNIsotopA) +
BarcodeVarHeader + bcyAddress + L1bc + BarcodeVarEnd + SampNr +
LineVarHeader + TextVarHeader + yAddressLine4 + L1L4 + Line4 +
LineVarHeader + TextVarHeader + yAddressLine3 + L1L3 + Line3 +
LineVarHeader + TextVarHeader + yAddressLine2 + L1L2 + Line2 +
FixedLineVarHeader1 + //Labelwechsel
LineVarHeader + TextVarHeader + yAddressLine1 + L2L1 + Line1 +
LineVarHeader + ReturnSampleVarHeader + ReturnSampleyAddress + '0205' + ReturnSampleText(ReturnSample) + CNIsotopAText(CNIsotopA) +
BarcodeVarHeader + bcyAddress + L2bc + BarcodeVarEnd + SampNr +
LineVarHeader + TextVarHeader + yAddressLine4 + L2L4 + Line4 +
LineVarHeader + TextVarHeader + yAddressLine3 + L2L3 + Line3 +
LineVarHeader + TextVarHeader + yAddressLine2 + L2L2 + Line2 +
FixedLineVarHeader2 +
TextVarEnd + Count + PrinterVarEnd;
end;
// ShowMessage(t);
// send commands to printer
PrintRAW(PrinterName, t);
end;
{procedure ColourLabel(const lab: TLabel; const valid: boolean);
const
colours: array[boolean] of TColor = (clRed, clWindowText);
begin
if Assigned(lab) then
lab.Font.Color := colours[valid];
end;
function CheckIsInteger(const edit: TLabeledEdit; const lab: TLabel; const min: integer = -MaxInt; const max: integer = maxint): boolean;
var
v: integer;
begin
try
v := StrToInt(edit.Text);
result := (min <= v) and (v <= max);
except
result := false;
end;
ColourLabel(lab, result);
end; }
procedure ResizeStringGrid(strg: TStringGrid; pW: integer); //grid, parent
var
i, w: integer;
begin
with strg do begin
w := 0;
for I := 0 to ColCount - 1 do w := w + ColWidths[i] + 1; // 1 = gridline
w := w + 7;
ColWidths[ColCount - 1] := ColWidths[ColCount - 1] + pW - w;
end;
end;
procedure GridDeleteRow(RowNumber: Integer; Grid: TstringGrid);
var
i: Integer;
begin
Grid.Row := RowNumber;
if (Grid.Row = Grid.RowCount - 1) then
{ On the last row}
Grid.RowCount := Grid.RowCount - 1
else
begin
{ Not the last row}
for i := RowNumber to Grid.RowCount - 1 do
Grid.Rows[i] := Grid.Rows[i + 1];
Grid.RowCount := Grid.RowCount - 1;
end;
end;
function StringToCaseSelect (Selector: string; CaseList: array of string): Integer;
var cnt: integer;
begin
Result := -1;
for cnt := 0 to Length(CaseList) - 1 do
begin
if CompareText(Selector, CaseList[cnt]) = 0 then
begin
Result := cnt;
Break;
end;
end;
end;
procedure SaveFileIniStr(const FName, Section, Key, strValue: string);
var
IniF: TIniFile;
begin
IniF := TIniFile.Create(FName);
IniF.WriteString(Section, Key, strValue);
IniF.Free;
end;
procedure SaveIniPath(const Path, Section, Key, strValue: string);
var
FName: string;
begin
FName := ChangeFileExt(Path, '.INI');
SaveFileIniStr(FName, Section, Key, strValue);
end;
function ReadIniPath(const Path, Section, Key, sDefault: string): string;
var
FName: string;
begin
FName := ChangeFileExt(Path, '.INI');
result := ReadFileIniStrPath(FName, Section, Key, sDefault);
end;
function ReadFileIniStrPath(const FName, Section, Key, sDefault: string): string;
var
IniF: TIniFile;
begin
IniF := TIniFile.Create(FName);
result := IniF.ReadString(Section, Key, sDefault);
IniF.Free;
end;
function ReplaceUmlaute(s: string): string;
var i: integer;
begin
result := '';
for i := 1 to length(s) do
begin
Case s[i] of
'ä': result := result+'ae';
'ü': result := result+'ue';
'ö': result := result+'oe';
'ß': result := result+'ss';
else result := result+s[i];
end;
end;
end;
end.
|
unit CollectionEditor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ToolWin, Menus, ImgList,
dcedit, dcfdes, dcsystem, dcdsgnstuff;
type
TCollectionEditorForm = class(TForm)
ItemsView: TListView;
ToolBar1: TToolBar;
AddItemButton: TToolButton;
DeleteButton: TToolButton;
ToolButton1: TToolButton;
LoadButton: TToolButton;
SaveButton: TToolButton;
DropMenu: TPopupMenu;
ToolImages: TImageList;
DisabledImages: TImageList;
procedure ItemsViewData(Sender: TObject; Item: TListItem);
procedure ItemsViewSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure AddItemClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FCollectionName: string;
FCollection: TCollection;
protected
function GetItemName(inItem: TCollectionItem): string;
procedure SetCollection(const Value: TCollection);
procedure SetCollectionName(const Value: string);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure RefreshList;
procedure UpdateDeleteButton;
procedure UpdateDesigner;
public
{ Public declarations }
Designer: IDesigner;
property Collection: TCollection read FCollection
write SetCollection;
property CollectionName: string read FCollectionName
write SetCollectionName;
end;
implementation
uses
InspectorView;
{$R *.dfm}
{ CollectionEditorForm }
procedure TCollectionEditorForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
// if Collection <> nil then
// Collection.Editor := nil;
Action := caFree;
end;
procedure TCollectionEditorForm.SetCollection(
const Value: TCollection);
function GoodOwner: Boolean;
begin
Result := (FCollection <> nil) and (FCollection.Owner <> nil)
and (FCollection.Owner is TComponent);
end;
begin
if GoodOwner then
TComponent(FCollection.Owner).RemoveFreeNotification(Self);
FCollection := Value;
if GoodOwner then
TComponent(FCollection.Owner).FreeNotification(Self);
CollectionName := Collection.GetNamePath;
// Collection.Editor := Self;
RefreshList;
end;
procedure TCollectionEditorForm.SetCollectionName(const Value: string);
begin
FCollectionName := Value;
Caption := 'Editing ' + FCollectionName;
end;
procedure TCollectionEditorForm.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
// if (Operation = opRemove) and (AComponent = Collection) then
if (Operation = opRemove) then
if (FCollection <> nil) and (FCollection.Owner = AComponent) then
begin
FCollection := nil;
Close;
end;
end;
procedure TCollectionEditorForm.UpdateDeleteButton;
begin
DeleteButton.Enabled := ItemsView.Selected <> nil;
end;
procedure TCollectionEditorForm.UpdateDesigner;
var
item: TCollectionItem;
begin
if (ItemsView.Selected <> nil) then
begin
item := Collection.Items[ItemsView.Selected.Index];
InspectorForm.InspectPersistent(item);
end;
end;
procedure TCollectionEditorForm.RefreshList;
var
i: Integer;
begin
if (ItemsView.Selected <> nil) then
i := ItemsView.Selected.Index
else
i := 0;
ItemsView.Items.Count := Collection.Count;
if (i > ItemsView.Items.Count) then
i := ItemsView.Items.Count - 1;
if (i >= 0) then
ItemsView.Selected := ItemsView.Items[i];
ItemsView.Invalidate;
UpdateDeleteButton;
UpdateDesigner;
end;
function TCollectionEditorForm.GetItemName(inItem: TCollectionItem): string;
begin
if inItem.DisplayName <> '' then
Result := inItem.DisplayName
else
Result := '(no name)';
end;
procedure TCollectionEditorForm.ItemsViewData(Sender: TObject;
Item: TListItem);
begin
if Item.Index >= Collection.Count then
Item.Caption := 'Bad Index'
else
Item.Caption := Format('%d - %s',
[ Item.Index, GetItemName(Collection.Items[Item.Index]) ]);
end;
procedure TCollectionEditorForm.AddItemClick(Sender: TObject);
begin
//AddItemButton.Tag := TComponent(Sender).Tag;
Collection.Add;
RefreshList;
end;
procedure TCollectionEditorForm.DeleteButtonClick(Sender: TObject);
begin
Collection.Items[ItemsView.Selected.Index].Free;
RefreshList;
end;
procedure TCollectionEditorForm.ItemsViewSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
UpdateDeleteButton;
UpdateDesigner;
// if (Item <> nil) and Selected then
// Designer.SelectComponent(Collection.Components[Item.Index]);
end;
end.
|
unit fos_infrastructure_mod;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
Licence conditions
(§LIC_END)
}
{$codepage UTF8}
{$mode objfpc}{$H+}
{$modeswitch nestedprocvars}
{$DEFINE ZONE_DEBUGING}
interface
uses
Classes, SysUtils,
FOS_TOOL_INTERFACES,
FRE_DB_INTERFACE,
FRE_DB_COMMON,fre_system,
//fre_dbbusiness,
//fre_hal_disk_enclosure_pool_mangement,
fre_zfs,
fre_scsi,
fre_hal_schemes,
//fos_citycom_voip_mod,
fos_infrastructure_if_mod,
fos_firmbox_pool_mod,
fos_firmbox_vm_machines_mod,
fos_firmbox_firewall_mod,
fos_firmbox_dhcp_mod,
fos_firmbox_fileserver_mod,
fos_firmbox_webserver_mod,
fos_firmbox_groupware_mod,
fos_firmbox_vpn_mod,
fos_firmbox_dns_mod;
//fre_diff_transport;
type
{ TFOS_INFRASTRUCTURE_MOD }
TFOS_INFRASTRUCTURE_MOD = class (TFRE_DB_APPLICATION_MODULE)
private
finfrastructureIFMod : TFOS_INFRASTRUCTURE_IF_MOD;
fStoragePoolsMod : TFOS_FIRMBOX_POOL_MOD;
fVMMod : TFRE_FIRMBOX_VM_MACHINES_SERVICE_IF_MOD;
fFirewallMod : TFRE_FIRMBOX_FIREWALL_SERVICE_IF_MOD;
fDHCPMod : TFRE_FIRMBOX_DHCP_SERVICE_IF_MOD;
fFSMod : TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD;
fVPNMod : TFRE_FIRMBOX_VPN_SERVICE_IF_MOD;
fWebserverMod : TFOS_FIRMBOX_WEBSERVER_SERVICE_IF_MOD;
fGroupwareMod : TFOS_FIRMBOX_GROUPWARE_SERVICE_IF_MOD;
fDNSMod : TFOS_FIRMBOX_DNS_SERVICE_IF_MOD;
function _canAddDC (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
function _canAddDC (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
function _canDeleteDC (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
function _canDeleteDC (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
function _canAddMachine (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
function _canAddMachine (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
function _canDeleteMachine (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
function _canDeleteMachine (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
function _canAddPDataset (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
function _canAddPDataset (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
function _canDeletePDataset (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
function _canDeletePDataset (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
function _canDeleteZone (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
function _canDeleteZone (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
function _canDelete (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const id: String): Boolean;
function _storeDC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function _storeMachine (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function _storeParentDataset (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function _storeZone (const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
function _deleteDC (const dbo:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):Boolean;
function _deleteMachine (const dbo:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):Boolean;
function _deleteDataset (const dbo:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):Boolean;
function _deleteZone (const dbo:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):Boolean;
function _getDetails (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):TFRE_DB_CONTENT_DESC;
function _getZoneDetails (const dbo:IFRE_DB_Object; const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):TFRE_DB_CONTENT_DESC;
function _getZoneContainerDSDetails (const dbo:IFRE_DB_Object; const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):TFRE_DB_CONTENT_DESC;
function _getPoolDetails (const dbo:IFRE_DB_Object; const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):TFRE_DB_CONTENT_DESC;
function _canModifyService (const dbo:IFRE_DB_Object; const conn: IFRE_DB_CONNECTION):Boolean;
function _canDeleteService (const dbo:IFRE_DB_Object; const conn: IFRE_DB_CONNECTION):Boolean;
function _canApplyService (const dbo:IFRE_DB_Object; const conn: IFRE_DB_CONNECTION):Boolean;
function _canEnableService (const dbo:IFRE_DB_Object; const conn: IFRE_DB_CONNECTION):Boolean;
function _canDisableService (const dbo:IFRE_DB_Object; const conn: IFRE_DB_CONNECTION):Boolean;
function _canModifyService (const serviceClass: TFRE_DB_NameType; const conn: IFRE_DB_CONNECTION):Boolean;
function _canDeleteService (const serviceClass: TFRE_DB_NameType; const conn: IFRE_DB_CONNECTION):Boolean;
function _canApplyService (const serviceClass: TFRE_DB_NameType; const conn: IFRE_DB_CONNECTION):Boolean;
function _canEnableService (const serviceClass: TFRE_DB_NameType; const conn: IFRE_DB_CONNECTION):Boolean;
function _canDisableService (const serviceClass: TFRE_DB_NameType; const conn: IFRE_DB_CONNECTION):Boolean;
procedure _getZoneButtonStates (const status: TFRE_DB_ZONESTATUS_PLUGIN; var installDis,uninstallDis,bootDis,shutdownDis,haltDis: Boolean);
function _updateZoneServiceToolbar (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function _CreateOpaqueCommandData (const hint_text,cmd_type : string):IFRE_DB_Object;
procedure _GetOpaqueComandData (const opd:IFRE_DB_Object ; out hint_text,cmd_type : string); { finalizes the object }
protected
procedure SetupAppModuleStructure ; override;
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class procedure InstallUserDBObjects (const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType); override;
procedure MySessionInitializeModule (const session : TFRE_DB_UserSession);override;
published
function WEB_Content (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;override;
function WEB_Add (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_Store (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_GridMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_GridSC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_Delete (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_DeleteConfirmed (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_IPoolsObjChanged (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_PoolContentSnapshots (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZoneContentConfiguration (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZoneContentServices (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZoneContentSMFs (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_StoreZoneConfiguration (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZoneObjChanged (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_DSObjChanged (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_DSContentConfiguration (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_DSContentSnapshots (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ServicesGridMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ServicesGridSC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_SMFsGridMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_SMFShowLog (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_SMFLoadLog (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ServiceObjChanged (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_AddService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ModifyService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_DeleteService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_DeleteServiceConfirmed (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_StoreService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ApplyServiceConfig (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ApplyServiceConfigConfirmed (const input:IFRE_DB_Object; const ses: IFRE_DB_UserSession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_EnableService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_DisableService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZoneInstall (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZoneUninstall (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZoneUninstallConfirmed (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZoneBoot (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZoneShutdown (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZoneHalt (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
procedure CCB_ZoneReply (const ses: IFRE_DB_UserSession; const rifstatus: TFRE_DB_RIF_RESULT ; const ocid: Qword; const opaquedata: IFRE_DB_Object);
end;
procedure Register_DB_Extensions;
implementation
procedure Register_DB_Extensions;
begin
fre_hal_schemes.Register_DB_Extensions;
fre_zfs.Register_DB_Extensions;
//fre_scsi.Register_DB_Extensions;
fos_infrastructure_if_mod.Register_DB_Extensions;
fos_firmbox_pool_mod.Register_DB_Extensions;
fos_firmbox_vm_machines_mod.Register_DB_Extensions;
fos_firmbox_dhcp_mod.Register_DB_Extensions;
fos_firmbox_vpn_mod.Register_DB_Extensions;
fos_firmbox_firewall_mod.Register_DB_Extensions;
fos_firmbox_fileserver_mod.Register_DB_Extensions;
fos_firmbox_webserver_mod.Register_DB_Extensions;
fos_firmbox_groupware_mod.Register_DB_Extensions;
fos_firmbox_dns_mod.Register_DB_Extensions;
fos_firmbox_pool_mod.Register_DB_Extensions;
GFRE_DBI.RegisterObjectClassEx(TFOS_INFRASTRUCTURE_MOD);
end;
{ TFOS_INFRASTRUCTURE_MOD }
class procedure TFOS_INFRASTRUCTURE_MOD.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName('TFRE_DB_APPLICATION_MODULE');
end;
function TFOS_INFRASTRUCTURE_MOD._canAddDC(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=ses.SysConfig.IsSystemManaged and conn.sys.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_DATACENTER);
end;
function TFOS_INFRASTRUCTURE_MOD._canAddDC(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
begin
Result:=ses.SysConfig.IsSystemManaged and conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_DATACENTER,dId);
end;
function TFOS_INFRASTRUCTURE_MOD._canDeleteDC(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=ses.SysConfig.IsSystemManaged and conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_DATACENTER);
end;
function TFOS_INFRASTRUCTURE_MOD._canDeleteDC(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION;const dId: TFRE_DB_GUID): Boolean;
begin
Result:=ses.SysConfig.IsSystemManaged and conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_DATACENTER,dId);
end;
function TFOS_INFRASTRUCTURE_MOD._canAddMachine(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=ses.SysConfig.IsSystemManaged and conn.sys.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_MACHINE) and conn.sys.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_ZONE);
end;
function TFOS_INFRASTRUCTURE_MOD._canAddMachine(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
begin
Result:=ses.SysConfig.IsSystemManaged and conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_MACHINE,dId) and conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_ZONE,dId);
end;
function TFOS_INFRASTRUCTURE_MOD._canDeleteMachine(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=ses.SysConfig.IsSystemManaged and conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_MACHINE) and conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_ZONE);
end;
function TFOS_INFRASTRUCTURE_MOD._canDeleteMachine(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
begin
Result:=ses.SysConfig.IsSystemManaged and conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_MACHINE,dId) and conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_ZONE,dId);
end;
function TFOS_INFRASTRUCTURE_MOD._canAddPDataset(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=conn.sys.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_ZFS_ZONE_CONTAINER_DATASET);
end;
function TFOS_INFRASTRUCTURE_MOD._canAddPDataset(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
begin
Result:=conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_ZFS_ZONE_CONTAINER_DATASET,dId);
end;
function TFOS_INFRASTRUCTURE_MOD._canDeletePDataset(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_ZFS_ZONE_CONTAINER_DATASET);
end;
function TFOS_INFRASTRUCTURE_MOD._canDeletePDataset(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION;const dId: TFRE_DB_GUID): Boolean;
begin
Result:=conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_ZFS_ZONE_CONTAINER_DATASET,dId);
end;
function TFOS_INFRASTRUCTURE_MOD._canDeleteZone(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_ZONE) and conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_ZFS_DATASET_FILESYSTEM) and
//services
conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_VROOTSERVER) and
conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_VMACHINE) and
conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_VMACHINE_NIC) and
conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_VMACHINE_DISK) and
conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_HDD) and
conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_VIRTUAL_FILESERVER) and
conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_DHCP) and
conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_VPN) and
conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_FIREWALL_SERVICE);
end;
function TFOS_INFRASTRUCTURE_MOD._canDeleteZone(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dId: TFRE_DB_GUID): Boolean;
begin
Result:=conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_ZONE,dId) and conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_ZFS_DATASET_FILESYSTEM,dId) and
//services
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VROOTSERVER,dId) and
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VMACHINE,dId) and
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VMACHINE_NIC,dId) and
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VMACHINE_DISK,dId) and
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_HDD,dId) and
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VIRTUAL_FILESERVER,dId) and
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_DHCP,dId) and
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VPN,dId) and
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_FIREWALL_SERVICE,dId);
end;
function TFOS_INFRASTRUCTURE_MOD._canDelete(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const id: String): Boolean;
var
dbo : IFRE_DB_Object;
hcObj : TObject;
dsObj : IFRE_DB_Object;
pstatus : TFRE_DB_POOLSTATUS_PLUGIN;
zstatus : TFRE_DB_ZONESTATUS_PLUGIN;
begin
Result:=false;
CheckDbResult(conn.Fetch(FREDB_H2G(id),dbo));
hcObj:=dbo.Implementor_HC;
if hcObj is TFRE_DB_DATACENTER then begin
if _canDeleteDC(ses,conn,dbo.DomainID) then begin
if conn.GetReferencesCount(dbo.UID,false)=0 then begin
Result:=true;
end;
end;
end else
if hcObj is TFRE_DB_MACHINE then begin
if _canDeleteDC(ses,conn,dbo.DomainID) then begin
if conn.GetReferencesCount(dbo.UID,false,TFRE_DB_ZFS_POOL.ClassName,'serviceParent')=0 then begin
Result:=true;
end;
end;
end else
if hcObj is TFRE_DB_ZFS_POOL then begin
if fStoragePoolsMod.canDeletePool(ses,conn,dbo.DomainID) then begin
dbo.GetPlugin(TFRE_DB_POOLSTATUS_PLUGIN,pstatus);
if pstatus.isPlanned then begin
dsObj:=TFRE_DB_ZFS_POOL(hcObj).getRootDataset(conn);
if conn.GetReferencesCount(dsObj.UID,false)=0 then begin
Result:=true;
end;
end;
end;
end else
if hcObj is TFRE_DB_ZFS_ZONE_CONTAINER_DATASET then begin
if _canDeletePDataset(ses,conn,dbo.DomainID) then begin
if conn.GetReferencesCount(dbo.UID,false)=0 then begin
Result:=true;
end;
end;
end else
if hcObj is TFRE_DB_ZONE then begin
if not (hcObj is TFRE_DB_GLOBAL_ZONE) then begin //global zone
if _canDeleteZone(ses,conn,dbo.DomainID) then begin
dbo.GetPlugin(TFRE_DB_ZONESTATUS_PLUGIN,zstatus);
if zstatus.isDeleted or (conn.GetReferencesCount(dbo.UID,false)=0) then begin
Result:=true;
end;
end;
end;
end;
end;
function TFOS_INFRASTRUCTURE_MOD._storeDC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
schemeObject: IFRE_DB_SchemeObject;
coll : IFRE_DB_COLLECTION;
dc : TFRE_DB_DATACENTER;
begin
if not _canAddDC(ses,conn,ses.GetDomainUID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
coll:=conn.GetCollection(CFRE_DB_DATACENTER_COLLECTION);
if coll.ExistsIndexedText(input.Field('objname').AsString)<>0 then begin
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'add_infrastructure_error_exists_cap'),FetchModuleTextShort(ses,'add_infrastructure_error_exists_message_dc'),fdbmt_error);
exit;
end;
if not GFRE_DBI.GetSystemScheme(TFRE_DB_DATACENTER,schemeObject) then
raise EFRE_DB_Exception.Create(edb_ERROR,'the scheme [%s] is unknown!',[TFRE_DB_DATACENTER]);
dc:=TFRE_DB_DATACENTER.CreateForDB;
schemeObject.SetObjectFieldsWithScheme(input,dc,true,conn);
CheckDbResult(coll.Store(dc));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.Create.Describe();
end;
function TFOS_INFRASTRUCTURE_MOD._storeMachine(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
schemeObject: IFRE_DB_SchemeObject;
coll : IFRE_DB_COLLECTION;
machine : TFRE_DB_MACHINE;
dcId : TFRE_DB_GUID;
zone : TFRE_DB_ZONE;
zcoll : IFRE_DB_COLLECTION;
gtemplate : TFRE_DB_FBZ_TEMPLATE;
begin
if not _canAddMachine(ses,conn,ses.GetDomainUID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
coll:=conn.GetMachinesCollection;
if coll.ExistsIndexedText(input.Field('objname').AsString)<>0 then begin
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'add_infrastructure_error_exists_cap'),FetchModuleTextShort(ses,'add_infrastructure_error_exists_message_machine'),fdbmt_error);
exit;
end;
if not GFRE_DBI.GetSystemScheme(TFRE_DB_MACHINE,schemeObject) then
raise EFRE_DB_Exception.Create(edb_ERROR,'the scheme [%s] is unknown!',[TFRE_DB_MACHINE]);
gtemplate:=finfrastructureIFMod.getGlobalTemplate(conn);
machine:=TFRE_DB_MACHINE.CreateForDB;
dcId:=FREDB_H2G(input.Field('dc').AsString);
input.DeleteField('dc');
machine.Field('datacenterid').AsObjectLink:=dcId;
machine.Field('serviceParent').AsObjectLink:=dcId;
schemeObject.SetObjectFieldsWithScheme(input,machine,true,conn);
CheckDbResult(coll.Store(machine.CloneToNewObject()));
//create global zone
zcoll:=conn.GetCollection(CFOS_DB_ZONES_COLLECTION);
zone:=TFRE_DB_GLOBAL_ZONE.CreateForDB;
zone.ObjectName:='global';
zone.ZNAME :='global';
zone.Field('templateid').AsObjectLink:=gtemplate.UID;
zone.Field('hostid').AsObjectLink:=machine.UID;
zone.Field('serviceParent').AsObjectLink:=machine.UID;
zone.Setup_UCT_Zone;
CheckDBResult(zcoll.Store(zone));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.Create.Describe();
end;
function TFOS_INFRASTRUCTURE_MOD._storeParentDataset(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
coll : IFRE_DB_COLLECTION;
schemeObject: IFRE_DB_SchemeObject;
pool : TFRE_DB_ZFS_POOL;
ds : TFRE_DB_ZFS_DATASET_FILESYSTEM;
rootDS : IFRE_DB_Object;
begin
if not _canAddPDataset(ses,conn,ses.GetDomainUID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
coll:=conn.GetCollection(CFRE_DB_ZFS_DATASET_COLLECTION);
if not GFRE_DBI.GetSystemScheme(TFRE_DB_ZFS_ZONE_CONTAINER_DATASET,schemeObject) then
raise EFRE_DB_Exception.Create(edb_ERROR,'the scheme [%s] is unknown!',[TFRE_DB_ZFS_ZONE_CONTAINER_DATASET]);
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('pool').AsString),TFRE_DB_ZFS_POOL,pool));
input.DeleteField('pool');
rootDS:=pool.getRootDataset(conn);
ds:=TFRE_DB_ZFS_ZONE_CONTAINER_DATASET.CreateForDB;
schemeObject.SetObjectFieldsWithScheme(input,ds,true,conn);
if not finfrastructureIFMod.fillDataSetObj(conn,ds,rootDS,coll) then begin
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'add_infrastructure_error_exists_cap'),FetchModuleTextShort(ses,'add_infrastructure_error_exists_message_dataset'),fdbmt_error);
exit;
end;
CheckDBResult(coll.Store(ds));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.Create.Describe();
end;
function TFOS_INFRASTRUCTURE_MOD._storeZone(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
domain_id : TFRE_DB_GUID;
template : TFRE_DB_FBZ_TEMPLATE;
rzInput : IFRE_DB_Object;
dsId : TFRE_DB_GUID;
begin
if input.FieldExistsAndNotMarkedClear('domain') then begin
domain_id:=FREDB_H2G(input.Field('domain').AsString);
end else begin
domain_id:=ses.GetDomainUID;
end;
input.DeleteField('domain');
dsId:=FREDB_H2G(input.Field('ds').AsString);
input.DeleteField('ds');
if not finfrastructureIFMod.createZoneAndImplicitDatasets(ses,conn,dsId,domain_id,input,zone,template) then begin
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'add_infrastructure_error_exists_cap'),FetchModuleTextShort(ses,'add_infrastructure_error_exists_message_zone'),fdbmt_error);
exit;
end;
if template.root then begin
rzInput:=GFRE_DBI.NewObject;
rzInput.Field('zoneId').AsString:=zone.UID_String;
rzInput.Field('serviceClass').AsString:=TFRE_DB_VROOTSERVER.ClassName;
rzInput.FieldPathCreate('data.objname').AsString:=zone.ObjectName;
WEB_StoreService(rzInput,ses,app,conn);
end;
template.Finalize;
zone.Finalize;
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFOS_INFRASTRUCTURE_MOD._deleteDC(const dbo: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): Boolean;
begin
CheckDbResult(conn.Delete(dbo.UID));
end;
function TFOS_INFRASTRUCTURE_MOD._deleteMachine(const dbo: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): Boolean;
var
zcoll: IFRE_DB_COLLECTION;
zObj : IFRE_DB_Object;
begin
Result:=true;
//delete global zone
zcoll:=conn.GetCollection(CFOS_DB_ZONES_COLLECTION);
if zcoll.GetIndexedObjText('global@' + dbo.UID_String,zObj,false,'upid')>0 then begin
CheckDbResult(conn.Delete(zObj.UID));
end;
//delete machine
CheckDbResult(conn.Delete(dbo.UID));
end;
function TFOS_INFRASTRUCTURE_MOD._deleteDataset(const dbo: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=true;
CheckDbResult(conn.Delete(dbo.UID));
end;
function TFOS_INFRASTRUCTURE_MOD._deleteZone(const dbo: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): Boolean;
var
dsObj : IFRE_DB_Object;
domainObj : IFRE_DB_Object;
domainsObj : IFRE_DB_Object;
refCount : NativeInt;
refCountDomains: NativeInt;
serviceDBO : IFRE_DB_Object;
refs : TFRE_DB_GUIDArray;
i : Integer;
procedure _delChildDS(const ds: IFRE_DB_Object);
var
i : Integer;
childDs : TFRE_DB_GUIDArray;
cdsObj : IFRE_DB_Object;
begin
childDs:=conn.GetReferences(ds.UID,false,TFRE_DB_ZFS_DATASET_FILESYSTEM.ClassName,'serviceParent');
for i := 0 to Length(childDs)-1 do begin
CheckDbResult(conn.Fetch(childDs[i],cdsObj));
_delChildDS(cdsObj);
CheckDbResult(conn.Delete(cdsObj.UID));
end;
end;
begin
Result:=true;
//delete services
refs:=conn.GetReferences(dbo.UID,false);
for i := 0 to Length(refs) - 1 do begin
conn.Fetch(refs[i],serviceDBO);
if serviceDBO.IsA(TFRE_DB_VMACHINE) then begin
fVMMod.deleteServiceConfiguration(conn,ses,serviceDBO);
end else
if serviceDBO.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
fFirewallMod.deleteServiceConfiguration(conn,ses,serviceDBO);
end else
if serviceDBO.IsA(TFRE_DB_DHCP) then begin
fDHCPMod.deleteServiceConfiguration(conn,ses,serviceDBO);
end else
if serviceDBO.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
fFSMod.deleteServiceConfiguration(conn,ses,serviceDBO);
end else
if serviceDBO.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
fFSMod.deleteServiceConfiguration(conn,ses,serviceDBO);
end else
if serviceDBO.IsA(TFRE_DB_VPN) then begin
fVPNMod.deleteServiceConfiguration(conn,ses,serviceDBO);
end else
if serviceDBO.IsA(TFRE_DB_HTTP_SERVICE) then begin
fWebserverMod.deleteServiceConfiguration(conn,ses,serviceDBO);
end else
if serviceDBO.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
fGroupwareMod.deleteServiceConfiguration(conn,ses,serviceDBO);
end else
if serviceDBO.IsA(TFRE_DB_DNS) then begin
fDNSMod.deleteServiceConfiguration(conn,ses,serviceDBO);
end else begin
raise EFRE_DB_Exception.Create(edb_ERROR,'Referenced object is not a known service.');
end;
end;
//delete zone
CheckDbResult(conn.Fetch(dbo.Field('serviceParent').AsObjectLink,dsObj));
CheckDbResult(conn.Delete(dbo.UID));
//delete zone dataset
CheckDbResult(conn.Fetch(dsObj.Field('serviceParent').AsObjectLink,domainObj));
//delete child datasets e.g.: zonedata
_delChildDS(dsObj);
writeln('SEAS ' + dsObj.DumpToString());
CheckDbResult(conn.Delete(dsObj.UID));
//delete domain if empty
refCount:=conn.GetReferencesCount(domainObj.UID,false,TFRE_DB_ZFS_DATASET_FILESYSTEM.ClassName,'serviceParent');
if refCount=0 then begin;
CheckDbResult(conn.Fetch(domainObj.Field('serviceParent').AsObjectLink,domainsObj));
CheckDbResult(conn.Delete(domainObj.UID));
//delete domains if empty
refCountDomains:=conn.GetReferencesCount(domainsObj.UID,false,TFRE_DB_ZFS_DATASET_FILESYSTEM.ClassName,'serviceParent');
if refCountDomains=0 then begin
CheckDbResult(conn.Delete(domainsObj.UID));
end;
end;
end;
function TFOS_INFRASTRUCTURE_MOD._getDetails(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): TFRE_DB_CONTENT_DESC;
var
res : TFRE_DB_CONTENT_DESC;
dbo : IFRE_DB_Object;
scheme: IFRE_DB_SchemeObject;
form : TFRE_DB_FORM_PANEL_DESC;
hcObj : TObject;
begin
if ses.GetSessionModuleData(ClassName).FieldExists('selectedDS') then begin
ses.UnregisterDBOChangeCB('infrastructureDSO');
ses.GetSessionModuleData(ClassName).DeleteField('selectedDS');
end;
if ses.GetSessionModuleData(ClassName).FieldExists('selectedZone') then begin
ses.UnregisterDBOChangeCB('infrastructureZO');
ses.GetSessionModuleData(ClassName).DeleteField('selectedZone');
end;
if not input.FieldExists('selected') or (input.Field('selected').ValueCount<>1) then begin
res:=TFRE_DB_HTML_DESC.create.Describe(FetchModuleTextShort(ses,'info_details_select_one'));
end else begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
hcObj:=dbo.Implementor_HC;
if hcObj is TFRE_DB_ZFS_POOL then begin
res:=_getPoolDetails(dbo,input,ses,app,conn);
end else
if hcObj is TFRE_DB_ZONE then begin
res:=_getZoneDetails(dbo,input,ses,app,conn);
end else
if hcObj is TFRE_DB_ZFS_ZONE_CONTAINER_DATASET then begin
res:=_getZoneContainerDSDetails(dbo,input,ses,app,conn);
end else begin
GFRE_DBI.GetSystemSchemeByName(dbo.Implementor_HC.ClassName,scheme);
if hcObj is TFRE_DB_MACHINE then begin
form:=TFRE_DB_FORM_PANEL_DESC.create.Describe('',true);
form.AddSchemeFormGroup(scheme.GetInputGroup('main_config'),ses);
form.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),CSFT('saveOperation',dbo),fdbbt_submit);
end else begin
form:=TFRE_DB_FORM_PANEL_DESC.create.Describe('',true,false);
form.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses);
end;
form.FillWithObjectValues(dbo,ses);
res:=form;
end;
end;
res.contentId:='infrastructureDetails';
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD._getZoneDetails(const dbo: IFRE_DB_Object; const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): TFRE_DB_CONTENT_DESC;
var
res : TFRE_DB_SUBSECTIONS_DESC;
sf : TFRE_DB_SERVER_FUNC_DESC;
template: TFRE_DB_FBZ_TEMPLATE;
begin
ses.GetSessionModuleData(ClassName).Field('selectedZone').AsGUID:=dbo.UID;
ses.RegisterDBOChangeCB(dbo.UID,CWSF(@WEB_ZoneObjChanged),'infrastructureZO');
CheckDbResult(conn.FetchAs(dbo.field('templateid').AsObjectLink,TFRE_DB_FBZ_TEMPLATE,template));
res:=TFRE_DB_SUBSECTIONS_DESC.create.Describe();
sf:=CWSF(@WEB_ZoneContentConfiguration);
sf.AddParam.Describe('selected',dbo.UID_String);
res.AddSection.Describe(sf,FetchModuleTextShort(ses,'zone_config_tab'),1);
if not (template.root or template.unknown) then begin;
sf:=CWSF(@WEB_ZoneContentServices);
sf.AddParam.Describe('selected',dbo.UID_String);
res.AddSection.Describe(sf,FetchModuleTextShort(ses,'zone_services_tab'),2);
end;
if conn.SYS.CheckClassRight4DomainId(sr_FETCH,TFRE_DB_SMF,dbo.DomainID) then begin
sf:=CWSF(@WEB_ZoneContentSMFs);
sf.AddParam.Describe('selected',dbo.UID_String);
res.AddSection.Describe(sf,FetchModuleTextShort(ses,'zone_smf_tab'),2);
end;
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD._getZoneContainerDSDetails(const dbo: IFRE_DB_Object; const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): TFRE_DB_CONTENT_DESC;
var
res : TFRE_DB_SUBSECTIONS_DESC;
sf : TFRE_DB_SERVER_FUNC_DESC;
begin
ses.GetSessionModuleData(ClassName).Field('selectedDS').AsGUID:=dbo.UID;
ses.RegisterDBOChangeCB(dbo.UID,CWSF(@WEB_DSObjChanged),'infrastructureDSO');
res:=TFRE_DB_SUBSECTIONS_DESC.Create.Describe();
sf:=CWSF(@WEB_DSContentConfiguration);
sf.AddParam.Describe('selected',dbo.UID_String);
res.AddSection.Describe(sf,FetchModuleTextShort(ses,'dataset_config_tab'),1);
res.AddSection.Describe(CWSF(@WEB_DSContentSnapshots),FetchModuleTextShort(ses,'dataset_snapshots_tab'),2);
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD._getPoolDetails(const dbo: IFRE_DB_Object; const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): TFRE_DB_CONTENT_DESC;
var
res : TFRE_DB_SUBSECTIONS_DESC;
sf : TFRE_DB_SERVER_FUNC_DESC;
begin
res:=TFRE_DB_SUBSECTIONS_DESC.Create.Describe();
sf:=CWSF(@fStoragePoolsMod.WEB_Content);
sf.AddParam.Describe('selected',dbo.UID_String);
res.AddSection.Describe(sf,FetchModuleTextShort(ses,'pool_config_tab'),1);
sf:=CWSF(@WEB_PoolContentSnapshots);
sf.AddParam.Describe('selected',dbo.UID_String);
res.AddSection.Describe(sf,FetchModuleTextShort(ses,'pool_snapshots_tab'),2);
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD._canModifyService(const dbo: IFRE_DB_Object; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if dbo.IsA(TFRE_DB_VMACHINE) then begin
Result:=fVMMod.canModifyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
Result:=fFirewallMod.canModifyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_DHCP) then begin
Result:=fDHCPMod.canModifyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
Result:=fFSMod.canModifyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
Result:=fFSMod.canModifyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_VPN) then begin
Result:=fVPNMod.canModifyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_HTTP_SERVICE) then begin
Result:=fWebserverMod.canModifyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
Result:=fGroupwareMod.canModifyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_DNS) then begin
Result:=fDNSMod.canModifyService(conn,dbo);
end else begin
Result:=conn.sys.CheckClassRight4DomainId(sr_UPDATE,dbo.Implementor_HC.ClassType,dbo.DomainID);
end;
end;
function TFOS_INFRASTRUCTURE_MOD._canDeleteService(const dbo: IFRE_DB_Object; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if dbo.IsA(TFRE_DB_VMACHINE) then begin
Result:=fVMMod.canDeleteService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
Result:=fFirewallMod.canDeleteService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_DHCP) then begin
Result:=fDHCPMod.canDeleteService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
Result:=fFSMod.canDeleteService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
Result:=fFSMod.canDeleteService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_VPN) then begin
Result:=fVPNMod.canDeleteService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_HTTP_SERVICE) then begin
Result:=fWebserverMod.canDeleteService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
Result:=fGroupwareMod.canDeleteService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_DNS) then begin
Result:=fDNSMod.canDeleteService(conn,dbo);
end else begin
Result:=conn.sys.CheckClassRight4DomainId(sr_DELETE,dbo.Implementor_HC.ClassType,dbo.DomainID) and (conn.GetReferencesCount(dbo.UID,false)=0);
end;
end;
function TFOS_INFRASTRUCTURE_MOD._canApplyService(const dbo: IFRE_DB_Object; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if dbo.IsA(TFRE_DB_VMACHINE) then begin
Result:=fVMMod.canApplyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
Result:=fFirewallMod.canApplyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_DHCP) then begin
Result:=fDHCPMod.canApplyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
Result:=fFSMod.canApplyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
Result:=fFSMod.canApplyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_VPN) then begin
Result:=fVPNMod.canApplyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_HTTP_SERVICE) then begin
Result:=fWebserverMod.canApplyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
Result:=fGroupwareMod.canApplyService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_DNS) then begin
Result:=fDNSMod.canApplyService(conn,dbo);
end else begin
Result:=conn.sys.CheckClassRight4DomainId(sr_UPDATE,dbo.Implementor_HC.ClassType,dbo.DomainID);
end;
end;
function TFOS_INFRASTRUCTURE_MOD._canEnableService(const dbo: IFRE_DB_Object; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if dbo.IsA(TFRE_DB_VMACHINE) then begin
Result:=fVMMod.canEnableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
Result:=fFirewallMod.canEnableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_DHCP) then begin
Result:=fDHCPMod.canEnableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
Result:=fFSMod.canEnableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
Result:=fFSMod.canEnableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_VPN) then begin
Result:=fVPNMod.canEnableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_HTTP_SERVICE) then begin
Result:=fWebserverMod.canEnableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
Result:=fGroupwareMod.canEnableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_DNS) then begin
Result:=fDNSMod.canEnableService(conn,dbo);
end else begin
Result:=conn.sys.CheckClassRight4DomainId(sr_UPDATE,dbo.Implementor_HC.ClassType,dbo.DomainID);
end;
end;
function TFOS_INFRASTRUCTURE_MOD._canDisableService(const dbo: IFRE_DB_Object; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if dbo.IsA(TFRE_DB_VMACHINE) then begin
Result:=fVMMod.canDisableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
Result:=fFirewallMod.canDisableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_DHCP) then begin
Result:=fDHCPMod.canDisableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
Result:=fFSMod.canDisableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
Result:=fFSMod.canDisableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_VPN) then begin
Result:=fVPNMod.canDisableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_HTTP_SERVICE) then begin
Result:=fWebserverMod.canDisableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
Result:=fGroupwareMod.canDisableService(conn,dbo);
end else
if dbo.IsA(TFRE_DB_DNS) then begin
Result:=fDNSMod.canDisableService(conn,dbo);
end else begin
Result:=conn.sys.CheckClassRight4DomainId(sr_UPDATE,dbo.Implementor_HC.ClassType,dbo.DomainID);
end;
end;
function TFOS_INFRASTRUCTURE_MOD._canModifyService(const serviceClass: TFRE_DB_NameType; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if serviceClass=TFRE_DB_VMACHINE.ClassName then begin
Result:=fVMMod.canModifyService(conn);
end else
if serviceClass=TFRE_DB_FIREWALL_SERVICE.ClassName then begin
Result:=fFirewallMod.canModifyService(conn);
end else
if serviceClass=TFRE_DB_DHCP.ClassName then begin
Result:=fDHCPMod.canModifyService(conn);
end else
if serviceClass=TFRE_DB_VIRTUAL_FILESERVER.ClassName then begin
Result:=fFSMod.canModifyService(conn);
end else
if serviceClass=TFRE_DB_GLOBAL_FILESERVER.ClassName then begin
Result:=fFSMod.canModifyService(conn);
end else
if serviceClass=TFRE_DB_VPN.ClassName then begin
Result:=fVPNMod.canModifyService(conn);
end else
if serviceClass=TFRE_DB_HTTP_SERVICE.ClassName then begin
Result:=fWebserverMod.canModifyService(conn);
end else
if serviceClass=TFRE_DB_GROUPWARE_SERVICE.ClassName then begin
Result:=fGroupwareMod.canModifyService(conn);
end else
if serviceClass=TFRE_DB_DNS.ClassName then begin
Result:=fDNSMod.canModifyService(conn)
end else begin
Result:=conn.sys.CheckClassRight4AnyDomain(sr_UPDATE,serviceClass);
end;
end;
function TFOS_INFRASTRUCTURE_MOD._canDeleteService(const serviceClass: TFRE_DB_NameType; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if serviceClass=TFRE_DB_VMACHINE.ClassName then begin
Result:=fVMMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_FIREWALL_SERVICE.ClassName then begin
Result:=fFirewallMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_DHCP.ClassName then begin
Result:=fDHCPMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_VIRTUAL_FILESERVER.ClassName then begin
Result:=fFSMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_GLOBAL_FILESERVER.ClassName then begin
Result:=fFSMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_VPN.ClassName then begin
Result:=fVPNMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_HTTP_SERVICE.ClassName then begin
Result:=fWebserverMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_GROUPWARE_SERVICE.ClassName then begin
Result:=fGroupwareMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_DNS.ClassName then begin
Result:=fDNSMod.canDeleteService(conn);
end else begin
Result:=conn.sys.CheckClassRight4AnyDomain(sr_DELETE,serviceClass);
end;
end;
function TFOS_INFRASTRUCTURE_MOD._canApplyService(const serviceClass: TFRE_DB_NameType; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if serviceClass=TFRE_DB_VMACHINE.ClassName then begin
Result:=fVMMod.canApplyService(conn);
end else
if serviceClass=TFRE_DB_FIREWALL_SERVICE.ClassName then begin
Result:=fFirewallMod.canApplyService(conn);
end else
if serviceClass=TFRE_DB_DHCP.ClassName then begin
Result:=fDHCPMod.canApplyService(conn);
end else
if serviceClass=TFRE_DB_VIRTUAL_FILESERVER.ClassName then begin
Result:=fFSMod.canApplyService(conn);
end else
if serviceClass=TFRE_DB_GLOBAL_FILESERVER.ClassName then begin
Result:=fFSMod.canApplyService(conn);
end else
if serviceClass=TFRE_DB_VPN.ClassName then begin
Result:=fVPNMod.canApplyService(conn);
end else
if serviceClass=TFRE_DB_HTTP_SERVICE.ClassName then begin
Result:=fWebserverMod.canApplyService(conn);
end else
if serviceClass=TFRE_DB_GROUPWARE_SERVICE.ClassName then begin
Result:=fGroupwareMod.canApplyService(conn);
end else
if serviceClass=TFRE_DB_DNS.ClassName then begin
Result:=fDNSMod.canApplyService(conn);
end else begin
Result:=conn.sys.CheckClassRight4AnyDomain(sr_UPDATE,serviceClass);
end;
end;
function TFOS_INFRASTRUCTURE_MOD._canEnableService(const serviceClass: TFRE_DB_NameType; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if serviceClass=TFRE_DB_VMACHINE.ClassName then begin
Result:=fVMMod.canEnableService(conn);
end else
if serviceClass=TFRE_DB_FIREWALL_SERVICE.ClassName then begin
Result:=fFirewallMod.canEnableService(conn);
end else
if serviceClass=TFRE_DB_DHCP.ClassName then begin
Result:=fDHCPMod.canEnableService(conn);
end else
if serviceClass=TFRE_DB_VIRTUAL_FILESERVER.ClassName then begin
Result:=fFSMod.canEnableService(conn);
end else
if serviceClass=TFRE_DB_GLOBAL_FILESERVER.ClassName then begin
Result:=fFSMod.canEnableService(conn);
end else
if serviceClass=TFRE_DB_VPN.ClassName then begin
Result:=fVPNMod.canEnableService(conn);
end else
if serviceClass=TFRE_DB_HTTP_SERVICE.ClassName then begin
Result:=fWebserverMod.canEnableService(conn);
end else
if serviceClass=TFRE_DB_GROUPWARE_SERVICE.ClassName then begin
Result:=fGroupwareMod.canEnableService(conn);
end else
if serviceClass=TFRE_DB_DNS.ClassName then begin
Result:=fDNSMod.canEnableService(conn);
end else begin
Result:=conn.sys.CheckClassRight4AnyDomain(sr_UPDATE,serviceClass);
end;
end;
function TFOS_INFRASTRUCTURE_MOD._canDisableService(const serviceClass: TFRE_DB_NameType; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if serviceClass=TFRE_DB_VMACHINE.ClassName then begin
Result:=fVMMod.canDisableService(conn);
end else
if serviceClass=TFRE_DB_FIREWALL_SERVICE.ClassName then begin
Result:=fFirewallMod.canDisableService(conn);
end else
if serviceClass=TFRE_DB_DHCP.ClassName then begin
Result:=fDHCPMod.canDisableService(conn);
end else
if serviceClass=TFRE_DB_VIRTUAL_FILESERVER.ClassName then begin
Result:=fFSMod.canDisableService(conn);
end else
if serviceClass=TFRE_DB_GLOBAL_FILESERVER.ClassName then begin
Result:=fFSMod.canDisableService(conn);
end else
if serviceClass=TFRE_DB_VPN.ClassName then begin
Result:=fVPNMod.canDisableService(conn);
end else
if serviceClass=TFRE_DB_HTTP_SERVICE.ClassName then begin
Result:=fWebserverMod.canDisableService(conn);
end else
if serviceClass=TFRE_DB_GROUPWARE_SERVICE.ClassName then begin
Result:=fGroupwareMod.canDisableService(conn);
end else
if serviceClass=TFRE_DB_DNS.ClassName then begin
Result:=fDNSMod.canDisableService(conn);
end else begin
Result:=conn.sys.CheckClassRight4AnyDomain(sr_UPDATE,serviceClass);
end;
end;
procedure TFOS_INFRASTRUCTURE_MOD._getZoneButtonStates(const status: TFRE_DB_ZONESTATUS_PLUGIN; var installDis, uninstallDis, bootDis, shutdownDis, haltDis: Boolean);
begin //FIXXME
installDis:=true; uninstallDis:=true; bootDis:=true; haltDis:=true; shutdownDis:=true;
if status.isLocked then exit;
if status.isDeleted then begin
installDis:=false;
exit;
end;
case status.field('zstate_num').AsInt32 of
-1: installDis:=false;
0: ;
1: uninstallDis:=false;
2: begin uninstallDis:=false; bootDis:=false; end;
3: ;
4: begin uninstallDis:=false; haltDis:=false; shutdownDis:=false; end;
5: ;
6: uninstallDis:=false;
7: begin uninstallDis:=false; haltDis:=false; shutdownDis:=false; end;
end;
end;
function TFOS_INFRASTRUCTURE_MOD._CreateOpaqueCommandData(const hint_text, cmd_type: string): IFRE_DB_Object;
begin
result := GFRE_DBI.NewObject;
result.Field('HT').AsString:=hint_text;
result.Field('CT').AsString:=cmd_type;
end;
procedure TFOS_INFRASTRUCTURE_MOD._GetOpaqueComandData(const opd: IFRE_DB_Object; out hint_text, cmd_type: string);
begin
hint_text := opd.Field('HT').AsString;
cmd_type := opd.Field('CT').AsString;
opd.Finalize;
end;
procedure TFOS_INFRASTRUCTURE_MOD.SetupAppModuleStructure;
begin
inherited SetupAppModuleStructure;
finfrastructureIFMod:=TFOS_INFRASTRUCTURE_IF_MOD.create;
AddApplicationModule(finfrastructureIFMod);
fStoragePoolsMod:=TFOS_FIRMBOX_POOL_MOD.create;
AddApplicationModule(fStoragePoolsMod);
//fVoIPMod:=TFOS_CITYCOM_VOIP_SERVICE_MOD.create;
//AddApplicationModule(fVoIPMod);
fVMMod:=TFRE_FIRMBOX_VM_MACHINES_SERVICE_IF_MOD.create;
AddApplicationModule(fVMMod);
fFirewallMod:=TFRE_FIRMBOX_FIREWALL_SERVICE_IF_MOD.create;
AddApplicationModule(fFirewallMod);
fDHCPMod:=TFRE_FIRMBOX_DHCP_SERVICE_IF_MOD.create;
AddApplicationModule(fDHCPMod);
fFSMod:=TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.create;
AddApplicationModule(fFSMod);
fVPNMod:=TFRE_FIRMBOX_VPN_SERVICE_IF_MOD.create;
AddApplicationModule(fVPNMod);
fWebserverMod:=TFOS_FIRMBOX_WEBSERVER_SERVICE_IF_MOD.create;
AddApplicationModule(fWebserverMod);
fGroupwareMod:=TFOS_FIRMBOX_GROUPWARE_SERVICE_IF_MOD.create;
AddApplicationModule(fGroupwareMod);
fDNSMod:=TFOS_FIRMBOX_DNS_SERVICE_IF_MOD.create;
AddApplicationModule(fDNSMod);
InitModuleDesc('infrastructure_description');
end;
class procedure TFOS_INFRASTRUCTURE_MOD.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
CreateModuleText(conn,'infrastructure_description','Infrastructure','Infrastructure','Infrastructure');
CreateModuleText(conn,'grid_name','Name');
CreateModuleText(conn,'grid_status','Status');
CreateModuleText(conn,'tb_add','Add');
CreateModuleText(conn,'tb_delete','Delete');
CreateModuleText(conn,'cm_delete','Delete');
CreateModuleText(conn,'add_infrastructure_diag_cap','Add infrastructure');
CreateModuleText(conn,'add_infrastructure_type','Type');
CreateModuleText(conn,'add_infrastructure_type_datacenter','Datacenter');
CreateModuleText(conn,'add_infrastructure_type_machine','Machine');
CreateModuleText(conn,'add_infrastructure_type_pool','Pool');
CreateModuleText(conn,'add_infrastructure_type_dataset','Dataset');
CreateModuleText(conn,'add_infrastructure_type_zone','Zone');
CreateModuleText(conn,'add_infrastructure_parent_datacenter','Datacenter');
CreateModuleText(conn,'add_infrastructure_parent_machine','Machine');
CreateModuleText(conn,'add_infrastructure_parent_pool','Pool');
CreateModuleText(conn,'add_infrastructure_parent_dataset','Dataset');
CreateModuleText(conn,'add_infrastructure_zone_template','Template');
CreateModuleText(conn,'add_infrastructure_parent_pool_value','%pool_str% (%datacenter_str%: %machine_str%)');
CreateModuleText(conn,'add_infrastructure_error_exists_cap','Error');
CreateModuleText(conn,'add_infrastructure_error_exists_message_dc','A datacenter with the given name already exists. Please choose another name.');
CreateModuleText(conn,'add_infrastructure_error_exists_message_machine','A machine with the given name already exists. Please choose another name.');
CreateModuleText(conn,'add_infrastructure_error_exists_message_dataset','A dataset with the given name already exists on the chosen pool. Please choose another name.');
CreateModuleText(conn,'add_infrastructure_error_exists_message_zone','A zone with the given name already exists for the given domain. Please choose another name.');
CreateModuleText(conn,'modify_infrastructure_error_exists_cap','Error');
CreateModuleText(conn,'modify_infrastructure_error_exists_message_zone','A zone with the given name already exists for the given domain. Please choose another name.');
CreateModuleText(conn,'delete_diag_cap','Remove Infrastructure');
CreateModuleText(conn,'delete_diag_msg','Remove infrastructure object "%object_str%"?');
CreateModuleText(conn,'error_delete_single_select','Exactly one object has to be selected for deletion.');
CreateModuleText(conn,'uninstall_zone_diag_cap','Uninstall Zone');
CreateModuleText(conn,'uninstall_zone_diag_msg','Uninstall zone "%zone_str%"?');
CreateModuleText(conn,'info_details_select_one','Please select an object to get detailed information about it.');
CreateModuleText(conn,'zone_services_tab','Services');
CreateModuleText(conn,'zone_smf_tab','SMF');
CreateModuleText(conn,'zone_config_tab','Zone');
CreateModuleText(conn,'zone_config_save_error_cap','Error');
CreateModuleText(conn,'zone_config_save_error_msg','Error saving zone configuration. Following service(s) are already in use and cannot be disabled: %services_str%');
CreateModuleText(conn,'zone_config_form_avail_services_group','Available Services');
CreateModuleText(conn,'zone_config_form_status','Zone Status');
CreateModuleText(conn,'grid_service_name','Name');
CreateModuleText(conn,'tb_add_service','Add');
CreateModuleText(conn,'tb_delete_service','Delete');
CreateModuleText(conn,'tb_enable_service','Enable');
CreateModuleText(conn,'tb_disable_service','Disable');
CreateModuleText(conn,'cm_delete_service','Delete');
CreateModuleText(conn,'add_service_diag_cap','Add %service_str%');
CreateModuleText(conn,'delete_service_diag_cap','Remove Service');
CreateModuleText(conn,'delete_service_diag_msg','Remove service "%service_str%"?');
CreateModuleText(conn,'service_create_error_exists_cap','Error: Add service');
CreateModuleText(conn,'service_create_error_exists_msg','A %service_str% service with the given name already exists!');
CreateModuleText(conn,'tb_zone_install','Install');
CreateModuleText(conn,'tb_zone_uninstall','Uninstall');
CreateModuleText(conn,'tb_zone_boot','Boot');
CreateModuleText(conn,'tb_zone_shutdown','Shutdown');
CreateModuleText(conn,'tb_zone_halt','Halt');
CreateModuleText(conn,'add_infrastructure_domain','Domain');
DeleteModuleText(conn,'zone_config_form_status');
CreateModuleText(conn,'zone_config_form_status','Zone Status');
CreateModuleText(conn,'zone_config_form_status_group','Status Information');
CreateModuleText(conn,'grid_service_status','Status');
CreateModuleText(conn,'add_standalone_infrastructure_parent_pool_value','%pool_str%');
CreateModuleText(conn,'cm_enable_service','Enable');
CreateModuleText(conn,'cm_disable_service','Disable');
CreateModuleText(conn,'tb_apply_service_config','Apply Configuration');
CreateModuleText(conn,'cm_apply_service_config','Apply Configuration');
CreateModuleText(conn,'apply_service_diag_cap','Apply Configuration');
CreateModuleText(conn,'apply_service_diag_msg','This will apply the Service configuration and restart it! Are you sure?');
CreateModuleText(conn,'tb_modify_service','Modify');
CreateModuleText(conn,'cm_modify_service','Modify');
CreateModuleText(conn,'modify_service_diag_cap','Modify %service_str%');
CreateModuleText(conn,'infrastructure_grid_pool_scrubbing_postfix','- Scrub in progress');
CreateModuleText(conn,'tb_import_pool','Import Pool');
CreateModuleText(conn,'pool_snapshots_tab','Snapshots');
CreateModuleText(conn,'pool_config_tab','Pool');
CreateModuleText(conn,'dataset_snapshots_tab','Snapshots');
CreateModuleText(conn,'dataset_config_tab','Dataset');
CreateModuleText(conn,'add_infrastructure_type_error_cap','Error');
CreateModuleText(conn,'add_infrastructure_type_error_msg_machine','No datacenter available to add a machine.');
CreateModuleText(conn,'add_infrastructure_type_error_msg_pool','No machine available to add a pool.');
CreateModuleText(conn,'add_infrastructure_type_error_msg_dataset','No pool available to add a dataset.');
CreateModuleText(conn,'add_infrastructure_type_error_msg_zone','No dataset available to add a zone.');
CreateModuleText(conn,'add_infrastructure_type_error_msg_zone_template','No template available to create a zone.');
CreateModuleText(conn,'grid_smf_name','Name');
CreateModuleText(conn,'tb_smf_show_log','Show Log');
CreateModuleText(conn,'cm_smf_show_log','Show Log');
CreateModuleText(conn,'smf_show_log_diag_cap','SMF Log');
CreateModuleText(conn,'smf_show_log_diag_close','Close');
CreateModuleText(conn,'smf_show_log_diag_no_log','No log available');
end;
end;
class procedure TFOS_INFRASTRUCTURE_MOD.InstallUserDBObjects(const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType);
var
coll: IFRE_DB_COLLECTION;
tmpl: TFRE_DB_FBZ_TEMPLATE;
begin
CreateDiskDataCollections(conn);
CreateZFSDataCollections(conn);
CreateServicesCollections(conn);
if currentVersionId='' then begin
currentVersionId := '1.0';
coll:=conn.GetCollection(CFRE_DB_TEMPLATE_COLLECTION);
{ moved to boxconsole / install }
//tmpl := TFRE_DB_FBZ_TEMPLATE.CreateForDB;
//tmpl.ObjectName:='GLOBAL';
//tmpl.global:=true;
//tmpl.Field('serviceclasses').AddString(TFRE_DB_GLOBAL_FILESERVER.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_Routing.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_AGGR.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_IPMP.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_IPTUN.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_STUB.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_BRIDGE.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_SIMNET.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_VNIC.ClassName);
//tmpl.SetDomainID(conn.GetDefaultDomainUID);
//CheckDBResult(coll.Store(tmpl));
//
//tmpl := TFRE_DB_FBZ_TEMPLATE.CreateForDB;
//tmpl.ObjectName:='SYSTEM';
//tmpl.system:=true;
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_AGGR.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_IPMP.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_IPTUN.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_STUB.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_BRIDGE.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_SIMNET.ClassName);
//tmpl.Field('serviceclasses').AddString(TFRE_DB_DATALINK_VNIC.ClassName);
//tmpl.SetDomainID(conn.GetDefaultDomainUID);
//CheckDBResult(coll.Store(tmpl));
end;
end;
procedure TFOS_INFRASTRUCTURE_MOD.MySessionInitializeModule(const session: TFRE_DB_UserSession);
var
app : TFRE_DB_APPLICATION;
conn : IFRE_DB_CONNECTION;
transform : IFRE_DB_SIMPLE_TRANSFORM;
dc : IFRE_DB_DERIVED_COLLECTION;
langres : TFRE_DB_StringArray;
procedure _calcPoolChooserLabel(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
var
str: String;
begin
str:=StringReplace(langres[0],'%datacenter_str%',transformed_object.Field('dc').AsString,[rfReplaceAll]);
str:=StringReplace(str,'%machine_str%',transformed_object.Field('machine').AsString,[rfReplaceAll]);
str:=StringReplace(str,'%pool_str%',transformed_object.Field('objname').AsString,[rfReplaceAll]);
transformed_object.Field('label').AsString:=str;
end;
procedure _setIcon(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
begin
transformed_object.Field('icon').AsString:=FREDB_getThemedResource('images_apps/classicons/'+LowerCase(input.SchemeClass)+'.svg');
end;
procedure _setInfrastructureObjFields(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
var
pplugin : TFRE_DB_POOLSTATUS_PLUGIN;
zplugin : TFRE_DB_ZONESTATUS_PLUGIN;
begin
if input.IsA(TFRE_DB_ZFS_POOL) then begin
input.GetPlugin(TFRE_DB_POOLSTATUS_PLUGIN,pplugin);
if pplugin.isScrubInProgress then begin
transformed_object.Field('objname').AsString:=transformed_object.Field('objname').AsString + ' ' + langres[Length(langres)-1];
end;
end else begin
if input.IsA(TFRE_DB_ZONE) then begin
input.GetPlugin(TFRE_DB_ZONESTATUS_PLUGIN,zplugin);
transformed_object.Field('status_icon').AsString:=zplugin.getZoneStatusIcon;
transformed_object.Field('status_icon_tooltip').AsString:=langres[zplugin.getZoneStatusLangNum];
end;
end;
_setIcon(input,transformed_object,langres);
end;
procedure _setServiceObjFields(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
begin
G_setServiceStatusAndConfigFields(input,transformed_object,langres);
_setIcon(input,transformed_object,langres);
end;
begin
inherited MySessionInitializeModule(session);
app := GetEmbeddingApp;
conn := session.GetDBConnection;
if session.IsInteractiveSession then begin
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname','',FetchModuleTextShort(session,'grid_name'),dt_string,true,false,false,true,1,'icon');
AddOneToOnescheme('status_icon','',FetchModuleTextShort(session,'grid_status'),dt_icon,true,false,false,true,1,'','','',nil,'status_icon_tooltip');
AddMatchingReferencedField(['<SERVICEDOMAIN'],'objname','serviceObj','',true,dt_description,true,true,1,'','',nil,'',false,'domainid');
AddOneToOnescheme('icon','','',dt_string,false);
AddOneToOnescheme('status_icon_tooltip','','',dt_string,false);
langres:=TFRE_DB_ZONESTATUS_PLUGIN.getZoneStatusLangRes(conn);
SetLength(langres,Length(langres)+1);
langres[Length(langres)-1]:=FetchModuleTextShort(session,'infrastructure_grid_pool_scrubbing_postfix');
SetSimpleFuncTransformNested(@_setInfrastructureObjFields,langres);
end;
dc := session.NewDerivedCollection('INFRASTRUCTURE_GRID');
with dc do begin
SetDeriveParent(conn.GetCollection(CFRE_DB_DATACENTER_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Listview,[cdgf_Children],'',CWSF(@WEB_GridMenu),nil,CWSF(@WEB_GridSC));
if session.SysConfig.IsSystemManaged then begin
SetParentToChildLinkField ('<SERVICEPARENT',[TFRE_DB_ZFS_DATASET_FILESYSTEM.ClassName]);
end else begin
SetParentToChildLinkField ('<SERVICEPARENT',[TFRE_DB_ZFS_DATASET_FILESYSTEM.ClassName,TFRE_DB_DATACENTER.ClassName]);
end;
Filters.AddSchemeObjectFilter('schemes',[TFRE_DB_DATACENTER.ClassName,TFRE_DB_MACHINE.ClassName,TFRE_DB_ZFS_POOL.ClassName,TFRE_DB_GLOBAL_ZONE.ClassName,TFRE_DB_ZONE.ClassName,TFRE_DB_ZFS_ZONE_CONTAINER_DATASET.ClassName,TFRE_DB_ZFS_DATASET_FILESYSTEM.ClassName]);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname');
AddOneToOnescheme('uid');
end;
dc := session.NewDerivedCollection('ZONE_DOMAIN_CHOOSER');
with dc do begin
SetDeriveParent(conn.AdmGetDomainCollection);
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('objname',true);
Filters.AddStdClassRightFilter('rights','uid','','','TFRE_DB_ZONE',[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname');
end;
dc := session.NewDerivedCollection('DC_CHOOSER');
with dc do begin
SetDeriveParent(conn.GetCollection(CFRE_DB_DATACENTER_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('objname',true);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname');
AddMatchingReferencedField(['SERVICEPARENT>TFRE_DB_MACHINE','SERVICEPARENT>TFRE_DB_DATACENTER'],'objname','dc');
AddMatchingReferencedField(['SERVICEPARENT>TFRE_DB_MACHINE'],'objname','machine');
AddOneToOnescheme('label','label');
if session.SysConfig.IsSystemManaged then begin
SetSimpleFuncTransformNested(@_calcPoolChooserLabel,[FetchModuleTextShort(session,'add_infrastructure_parent_pool_value')]);
end else begin
SetSimpleFuncTransformNested(@_calcPoolChooserLabel,[FetchModuleTextShort(session,'add_standalone_infrastructure_parent_pool_value')]);
end;
end;
dc := session.NewDerivedCollection('POOL_CHOOSER');
with dc do begin
SetDeriveParent(conn.GetCollection(CFRE_DB_ZFS_POOL_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('label',true);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname','',FetchModuleTextShort(session,'grid_service_name'),dt_string,true,false,false,true,1,'icon');
AddOneToOnescheme('icon','','',dt_string,false);
AddOneToOnescheme('status_icons','',FetchModuleTextShort(session,'grid_service_status'),dt_icon,true,false,false,true,1,'','','',nil,'status_icon_tooltips');
AddMatchingReferencedField(['SERVICEPARENT>'],'uid','zuid','',false);
AddMatchingReferencedObjPlugin(['SERVICEPARENT>'],TFRE_DB_ZONESTATUS_PLUGIN,'zplugin');
SetSimpleFuncTransformNested(@_setServiceObjFields,TFRE_DB_SERVICE_STATUS_PLUGIN.getStatusLangres(conn));
end;
dc := session.NewDerivedCollection('ZONE_SERVICES_GRID');
with dc do begin
SetDeriveParent(conn.GetCollection(CFOS_DB_SERVICES_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Listview,[],'',CWSF(@WEB_ServicesGridMenu),nil,CWSF(@WEB_ServicesGridSC));
SetDefaultOrderField('objname',true);
Filters.AddSchemeObjectFilter('schemes',TFRE_DB_DATALINK.getAllDataLinkClasses,false);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname','',FetchModuleTextShort(session,'grid_smf_name'));
AddMatchingReferencedField(['ZONE>'],'uid','zuid','',false);
end;
dc := session.NewDerivedCollection('ZONE_SMFS_GRID');
with dc do begin
SetDeriveParent(conn.GetCollection(CFOS_DB_SMFS_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Listview,[],'',CWSF(@WEB_SMFsGridMenu));
SetDefaultOrderField('objname',true);
end;
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_Content(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
dc : IFRE_DB_DERIVED_COLLECTION;
grid : TFRE_DB_VIEW_LIST_DESC;
layout : TFRE_DB_LAYOUT_DESC;
importDisabled : Boolean;
machine : IFRE_DB_Object;
ipools : IFRE_DB_Object;
begin
CheckClassVisibility4AnyDomain(ses);
dc:=ses.FetchDerivedCollection('INFRASTRUCTURE_GRID');
grid:=dc.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC;
if _canAddDC(ses,conn) or _canAddMachine(ses,conn) or _canAddPDataset(ses,conn) or fStoragePoolsMod.canAddPool(ses,conn) or finfrastructureIFMod.canAddZone(ses,conn) then begin
grid.AddButton.Describe(CWSF(@WEB_Add),'',FetchModuleTextShort(ses,'tb_add'));
end;
if _canDeleteDC(ses,conn) or _canDeleteMachine(ses,conn) or _canDeletePDataset(ses,conn) or fStoragePoolsMod.canDeletePool(ses,conn) or _canDeleteZone(ses,conn) then begin
grid.AddButton.DescribeManualType('tb_delete',CWSF(@WEB_Delete),'',FetchModuleTextShort(ses,'tb_delete'),'',true);
end;
if fStoragePoolsMod.canAddPool(ses,conn) then begin
if ses.SysConfig.IsSystemManaged then begin
importDisabled:=false;
end else begin
machine:=conn.GetMachinesCollection.First;
if not Assigned(machine) then
raise EFRE_DB_Exception.Create(edb_ERROR,'No machine found');
ipools:=fStoragePoolsMod.getImportablePools(ses,conn,machine.UID_String,true);
if Assigned(ipools) then begin
ses.RegisterDBOChangeCB(ipools.UID,CWSF(@WEB_IPoolsObjChanged),'infrastructureMod');
end;
importDisabled:=not fStoragePoolsMod.hasImportablePools(ipools);
end;
grid.AddButton.DescribeManualType('tb_import_pool',CWSF(@fStoragePoolsMod.WEB_ImportPool),'',FetchModuleTextShort(ses,'tb_import_pool'),'',importDisabled);
end;
layout:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(grid,_getDetails(input,ses,app,conn));
layout.contentId:='infrastructureMod';
Result:=layout;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_Add(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
res : TFRE_DB_FORM_DIALOG_DESC;
store : TFRE_DB_STORE_DESC;
scheme : IFRE_DB_SchemeObject;
chooser: TFRE_DB_INPUT_CHOOSER_DESC;
group : TFRE_DB_INPUT_GROUP_DESC;
dc : IFRE_DB_DERIVED_COLLECTION;
begin
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'add_infrastructure_diag_cap'),600,true,true,false);
store:=TFRE_DB_STORE_DESC.create.Describe('id');
chooser:=res.AddChooser.Describe(FetchModuleTextShort(ses,'add_infrastructure_type'),'type',store,dh_chooser_radio,true,true,true,false);
if _canAddDC(ses,conn) then begin
store.AddEntry.Describe(FetchModuleTextShort(ses,'add_infrastructure_type_datacenter'),'DC');
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_DATACENTER.ClassName,scheme);
group:=res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses,false,false,'dc',true,true);
chooser.addDependentInputGroup(group,'DC');
end;
if _canAddMachine(ses,conn) then begin
store.AddEntry.Describe(FetchModuleTextShort(ses,'add_infrastructure_type_machine'),'M');
if (ses.FetchDerivedCollection('DC_CHOOSER').ItemCount=0) then begin
res.AddDescription.Describe(FetchModuleTextShort(ses,'add_infrastructure_type_error_cap'),FetchModuleTextShort(ses,'add_infrastructure_type_error_msg_machine'),'m.error');
chooser.addDependentInput('m.error','M',fdv_visible);
chooser.addDependentInput('addInfrastructureSave','M',fdv_none,fdes_disabled);
end else begin
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_MACHINE.ClassName,scheme);
res.AddChooser.Describe(FetchModuleTextShort(ses,'add_infrastructure_parent_datacenter'),'m.dc',ses.FetchDerivedCollection('DC_CHOOSER').GetStoreDescription as TFRE_DB_STORE_DESC,dh_chooser_combo,true,true,true);
group:=res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses,false,false,'m',true,true);
chooser.addDependentInputGroup(group,'M');
chooser.addDependentInput('m.dc','M',fdv_visible);
end;
end;
if fStoragePoolsMod.canAddPool(ses,conn) then begin
store.AddEntry.Describe(FetchModuleTextShort(ses,'add_infrastructure_type_pool'),'P');
if (ses.FetchDerivedCollection('MACHINE_CHOOSER').ItemCount=0) then begin
res.AddDescription.Describe(FetchModuleTextShort(ses,'add_infrastructure_type_error_cap'),FetchModuleTextShort(ses,'add_infrastructure_type_error_msg_pool'),'p.error');
chooser.addDependentInput('p.error','P',fdv_visible);
chooser.addDependentInput('addInfrastructureSave','P',fdv_none,fdes_disabled);
end else begin
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_ZFS_POOL.ClassName,scheme);
if ses.SysConfig.IsSystemManaged then begin
dc:=ses.FetchDerivedCollection('MACHINE_CHOOSER');
res.AddChooser.Describe(FetchModuleTextShort(ses,'add_infrastructure_parent_machine'),'p.machine',dc.GetStoreDescription as TFRE_DB_STORE_DESC,dh_chooser_combo,true,true,dc.ItemCount>1);
end;
group:=res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses,false,false,'p',true,true);
chooser.addDependentInputGroup(group,'P');
chooser.addDependentInput('p.machine','P',fdv_visible);
end;
end;
if _canAddPDataset(ses,conn) then begin
store.AddEntry.Describe(FetchModuleTextShort(ses,'add_infrastructure_type_dataset'),'DS');
if (ses.FetchDerivedCollection('POOL_CHOOSER').ItemCount=0) then begin
res.AddDescription.Describe(FetchModuleTextShort(ses,'add_infrastructure_type_error_cap'),FetchModuleTextShort(ses,'add_infrastructure_type_error_msg_dataset'),'d.error');
chooser.addDependentInput('d.error','DS',fdv_visible);
chooser.addDependentInput('addInfrastructureSave','DS',fdv_none,fdes_disabled);
end else begin
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_ZFS_ZONE_CONTAINER_DATASET.ClassName,scheme);
dc:=ses.FetchDerivedCollection('POOL_CHOOSER');
res.AddChooser.Describe(FetchModuleTextShort(ses,'add_infrastructure_parent_pool'),'ds.pool',dc.GetStoreDescription as TFRE_DB_STORE_DESC,dh_chooser_combo,true,true,dc.ItemCount>1);
group:=res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses,false,false,'ds',true,true);
chooser.addDependentInputGroup(group,'DS');
chooser.addDependentInput('ds.pool','DS',fdv_visible);
end;
end;
if finfrastructureIFMod.canAddZone(ses,conn) then begin
store.AddEntry.Describe(FetchModuleTextShort(ses,'add_infrastructure_type_zone'),'Z');
if (ses.FetchDerivedCollection('DATASET_CHOOSER').ItemCount=0) or (ses.FetchDerivedCollection('TEMPLATE_CHOOSER').ItemCount=0) then begin
if (ses.FetchDerivedCollection('DATASET_CHOOSER').ItemCount=0) then begin
res.AddDescription.Describe(FetchModuleTextShort(ses,'add_infrastructure_type_error_cap'),FetchModuleTextShort(ses,'add_infrastructure_type_error_msg_zone'),'z.error');
chooser.addDependentInput('z.error','Z',fdv_visible);
end;
if (ses.FetchDerivedCollection('TEMPLATE_CHOOSER').ItemCount=0) then begin
res.AddDescription.Describe(FetchModuleTextShort(ses,'add_infrastructure_type_error_cap'),FetchModuleTextShort(ses,'add_infrastructure_type_error_msg_zone_template'),'z.error_t');
chooser.addDependentInput('z.error_t','Z',fdv_visible);
end;
chooser.addDependentInput('addInfrastructureSave','Z',fdv_none,fdes_disabled);
end else begin
chooser.setDefaultValue('Z');
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_ZONE.ClassName,scheme);
dc:=ses.FetchDerivedCollection('ZONE_DOMAIN_CHOOSER');
if dc.ItemCount>1 then begin
res.AddChooser.Describe(FetchModuleTextShort(ses,'add_infrastructure_domain'),'z.domain',dc.GetStoreDescription.Implementor_HC as TFRE_DB_STORE_DESC,dh_chooser_combo,true,true,true,false,ses.GetDomainUID_String);
end;
dc:=ses.FetchDerivedCollection('DATASET_CHOOSER');
res.AddChooser.Describe(FetchModuleTextShort(ses,'add_infrastructure_parent_dataset'),'z.ds',dc.GetStoreDescription as TFRE_DB_STORE_DESC,dh_chooser_combo,true,true,dc.ItemCount>1);
group:=res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses,false,false,'z',true,true);
dc:=ses.FetchDerivedCollection('TEMPLATE_CHOOSER');
res.AddChooser.Describe(FetchModuleTextShort(ses,'add_infrastructure_zone_template'),'z.templateid',dc.GetStoreDescription as TFRE_DB_STORE_DESC,dh_chooser_combo,true,true,dc.ItemCount>1);
chooser.addDependentInputGroup(group,'Z');
chooser.addDependentInput('z.domain','Z',fdv_visible);
chooser.addDependentInput('z.templateid','Z',fdv_visible);
chooser.addDependentInput('z.ds','Z',fdv_visible);
end;
end;
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),CWSF(@WEB_Store),fdbbt_submit,'addInfrastructureSave');
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_Store(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
if not input.FieldPathExists('data.type') then raise EFRE_DB_Exception.Create(edb_ERROR,'Missing required parameter "type"');
case input.FieldPath('data.type').AsString of
'DC': begin
if not input.FieldPathExists('data.dc') then raise EFRE_DB_Exception.Create(edb_ERROR,'Missing required data');
Result:=_storeDC(input.FieldPath('data.dc').AsObject,ses,app,conn);
end;
'M' : begin
if not input.FieldPathExists('data.m') then raise EFRE_DB_Exception.Create(edb_ERROR,'Missing required data');
Result:=_storeMachine(input.FieldPath('data.m').AsObject,ses,app,conn);
end;
'P' : begin
if not input.FieldPathExists('data.p') then raise EFRE_DB_Exception.Create(edb_ERROR,'Missing required data');
Result:=fStoragePoolsMod.storePool(input.FieldPath('data.p').AsObject,ses,app,conn);
end;
'DS': begin
if not input.FieldPathExists('data.ds') then raise EFRE_DB_Exception.Create(edb_ERROR,'Missing required data');
Result:=_storeParentDataset(input.FieldPath('data.ds').AsObject,ses,app,conn);
end;
'Z' : begin
if not input.FieldPathExists('data.z') then raise EFRE_DB_Exception.Create(edb_ERROR,'Missing required data');
Result:=_storeZone(input.FieldPath('data.z').AsObject,ses,app,conn);
end;
else begin
raise EFRE_DB_Exception.Create(edb_ERROR,'Unknown infrastructure type');
end;
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_GridMenu(const input: IFRE_DB_Object;const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION;const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
res : TFRE_DB_MENU_DESC;
sf : TFRE_DB_SERVER_FUNC_DESC;
begin
res:=TFRE_DB_MENU_DESC.create.Describe;
if _canDelete(ses,conn,input.Field('selected').AsString) then begin
sf:=CWSF(@WEB_Delete);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_delete'),'',sf);
end;
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_GridSC(const input: IFRE_DB_Object;const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
deleteDisabled : Boolean;
begin
deleteDisabled:=not (input.FieldExists('selected') and _canDelete(ses,conn,input.Field('selected').AsString));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('tb_delete',deleteDisabled));
Result:=_getDetails(input,ses,app,conn);
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_Delete(const input: IFRE_DB_Object;const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION;const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
sf : TFRE_DB_SERVER_FUNC_DESC;
cap,msg : String;
dbo : IFRE_DB_Object;
begin
if not _canDelete(ses,conn,input.Field('selected').AsString) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if input.Field('selected').ValueCount<>1 then raise EFRE_DB_Exception.Create(FetchModuleTextShort(ses,'error_delete_single_select'));
sf:=CWSF(@WEB_DeleteConfirmed);
sf.AddParam.Describe('selected',input.Field('selected').AsStringArr);
cap:=FetchModuleTextShort(ses,'delete_diag_cap');
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsStringArr[0]),dbo));
msg:=StringReplace(FetchModuleTextShort(ses,'delete_diag_msg'),'%object_str%',dbo.Field('objname').AsString,[rfReplaceAll]);
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(cap,msg,fdbmt_confirm,sf);
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_DeleteConfirmed(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
i : NativeInt;
dbo : IFRE_DB_Object;
hcObj: TObject;
begin
if not _canDelete(ses,conn,input.Field('selected').AsString) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if input.field('confirmed').AsBoolean then begin
for i:= 0 to input.Field('selected').ValueCount-1 do begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsStringArr[i]),dbo));
hcObj:=dbo.Implementor_HC;
if hcObj is TFRE_DB_DATACENTER then begin
_deleteDC(dbo,ses,app,conn);
end else
if hcObj is TFRE_DB_MACHINE then begin
_deleteMachine(dbo,ses,app,conn);
end else
if hcObj is TFRE_DB_ZFS_POOL then begin
fStoragePoolsMod.deletePool(dbo,ses,app,conn);
end else
if hcObj is TFRE_DB_ZFS_ZONE_CONTAINER_DATASET then begin
_deleteDataset(dbo,ses,app,conn);
end else
if hcObj is TFRE_DB_ZONE then begin
_deleteZone(dbo,ses,app,conn);
end;
end;
end;
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_IPoolsObjChanged(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
machine: IFRE_DB_Object;
begin
Result:=GFRE_DB_NIL_DESC;
if input.Field('type').AsString='UPD' then begin
machine:=conn.GetMachinesCollection.First;
if not Assigned(machine) then
raise EFRE_DB_Exception.Create(edb_ERROR,'No machine found');
fStoragePoolsMod.setImportablePools(ses,conn,machine.UID_String,input.Field('obj').AsObject);
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_PoolContentSnapshots(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
pool : TFRE_DB_ZFS_POOL;
begin
CheckClassVisibility4AnyDomain(ses);
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_ZFS_POOL,pool));
Result:=finfrastructureIFMod.getHierarchicalSnapshotsGrid(pool.getRootDataset(conn).Name,input,ses,app,conn);
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ZoneContentConfiguration(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
template : TFRE_DB_FBZ_TEMPLATE;
res : TFRE_DB_FORM_PANEL_DESC;
i : Integer;
exClass : TFRE_DB_ObjectClassEx;
conf : IFRE_DB_Object;
sf : TFRE_DB_SERVER_FUNC_DESC;
defaultValue: Boolean;
disabled : Boolean;
serviceClass: String;
menu : TFRE_DB_MENU_DESC;
scheme : IFRE_DB_SchemeObject;
group : TFRE_DB_INPUT_GROUP_DESC;
plugin : TFRE_DB_ZONESTATUS_PLUGIN;
installDis : Boolean;
uninstallDis: Boolean;
bootDis : Boolean;
haltDis : Boolean;
shutdownDis : Boolean;
begin
CheckClassVisibility4AnyDomain(ses);
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_ZONE,zone));
res:=TFRE_DB_FORM_PANEL_DESC.create.Describe('');
res.contentId:='configureZone';
GFRE_DBI.GetSystemSchemeByName(zone.ClassName,scheme);
res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses,false,false,'zone');
res.FillWithObjectValues(zone,ses,'zone');
CheckDbResult(conn.FetchAs(zone.Field('templateid').AsObjectLink,TFRE_DB_FBZ_TEMPLATE,template));
group:=res.AddGroup.Describe(FetchModuleTextShort(ses,'zone_config_form_avail_services_group'),true,false);
if not (template.root or template.unknown) then begin //don't add services for root/unknown zone since there are none
for i := 0 to template.Field('serviceclasses').ValueCount -1 do begin
serviceClass:=template.Field('serviceclasses').AsStringArr[i];
exClass:=GFRE_DBI.GetObjectClassEx(serviceClass);
if Assigned(exClass) then begin //ignore not found serviceClasses
if not ((serviceClass=TFRE_DB_VMACHINE.ClassName) or
(serviceClass=TFRE_DB_FIREWALL_SERVICE.ClassName) or
(serviceClass=TFRE_DB_DHCP.ClassName) or
(serviceClass=TFRE_DB_VIRTUAL_FILESERVER.ClassName) or
(serviceClass=TFRE_DB_GLOBAL_FILESERVER.ClassName) or
(serviceClass=TFRE_DB_VPN.ClassName) or
(serviceClass=TFRE_DB_HTTP_SERVICE.ClassName) or
(serviceClass=TFRE_DB_GROUPWARE_SERVICE.ClassName) or
(serviceClass=TFRE_DB_DNS.ClassName)) then begin
continue; //skip not managed services
end;
conf:=exClass.Invoke_DBIMC_Method('GetConfig',input,ses,app,conn);
if conf.Field('type').AsString='service' then begin
defaultValue:=FREDB_StringInArrayIdx(serviceClass,zone.Field('disabledSCs').AsStringArr)=-1;
if not defaultValue then begin
disabled:=false;
end else begin
disabled:=conn.GetReferencesCount(zone.UID,false,serviceClass,'serviceParent')>0;
end;
group.AddBool.Describe(conf.Field('caption').AsString,'config.'+serviceClass,false,false,disabled,defaultValue);
end;
end;
end;
end;
zone.GetPlugin(TFRE_DB_ZONESTATUS_PLUGIN,plugin);
group:=res.AddGroup.Describe(FetchModuleTextShort(ses,'zone_config_form_status_group'),false,false);
group.AddDescription.Describe(FetchModuleTextShort(ses,'zone_config_form_status'),plugin.getZoneStatus(conn),'status');
if conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_ZONE,zone.DomainID) then begin
sf:=CWSF(@WEB_StoreZoneConfiguration);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit);
if not (zone is TFRE_DB_GLOBAL_ZONE) then begin
sf.AddParam.Describe('zoneId',zone.UID_String);
_getZoneButtonStates(plugin,installDis,uninstallDis,bootDis,shutdownDis,haltDis);
menu:=TFRE_DB_MENU_DESC.create.Describe();
if not template.unknown then begin
sf:=CWSF(@WEB_ZoneInstall);
sf.AddParam.Describe('zoneId',zone.UID_String);
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_zone_install'),'',sf,installDis,'zone_install');
sf:=CWSF(@WEB_ZoneUninstall);
sf.AddParam.Describe('zoneId',zone.UID_String);
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_zone_uninstall'),'',sf,uninstallDis,'zone_uninstall');
end;
sf:=CWSF(@WEB_ZoneBoot);
sf.AddParam.Describe('zoneId',zone.UID_String);
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_zone_boot'),'',sf,bootDis,'zone_boot');
sf:=CWSF(@WEB_ZoneShutdown);
sf.AddParam.Describe('zoneId',zone.UID_String);
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_zone_shutdown'),'',sf,shutdownDis,'zone_shutdown');
sf:=CWSF(@WEB_ZoneHalt);
sf.AddParam.Describe('zoneId',zone.UID_String);
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_zone_halt'),'',sf,haltDis,'zone_halt');
res.SetMenu(menu);
end;
end;
res.contentId:='ZONE_CONFIG';
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ZoneContentServices(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
res : TFRE_DB_VIEW_LIST_DESC;
dc : IFRE_DB_DERIVED_COLLECTION;
menu : TFRE_DB_MENU_DESC;
canAdd : Boolean;
canAddService : Boolean;
template : TFRE_DB_FBZ_TEMPLATE;
i : Integer;
serviceClass : String;
exClass : TFRE_DB_ObjectClassEx;
conf : IFRE_DB_Object;
sf : TFRE_DB_SERVER_FUNC_DESC;
submenu : TFRE_DB_SUBMENU_DESC;
canApply : Boolean;
canDelete : Boolean;
canEnable : Boolean;
canDisable : Boolean;
disabledSCs : TFRE_DB_StringArray;
canModify : Boolean;
begin
CheckClassVisibility4AnyDomain(ses);
ses.GetSessionModuleData(ClassName).DeleteField('selectedService');
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_ZONE,zone));
dc:=ses.FetchDerivedCollection('ZONE_SERVICES_GRID');
dc.Filters.RemoveFilter('zone');
dc.Filters.AddUIDFieldFilter('zone','zuid',[zone.UID],dbnf_OneValueFromFilter);
res:=dc.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC;
canAdd:=false;
canModify:=false;
canDelete:=false;
canEnable:=false;
canDisable:=false;
canApply:=false;
menu:=TFRE_DB_MENU_DESC.create.Describe;
submenu:=menu.AddMenu.Describe(FetchModuleTextShort(ses,'tb_add_service'),'',false,'add_menu');
disabledSCs:=zone.Field('disabledSCs').AsStringArr;
CheckDbResult(conn.FetchAs(zone.Field('templateid').AsObjectLink,TFRE_DB_FBZ_TEMPLATE,template));
for i := 0 to template.Field('serviceclasses').ValueCount -1 do begin
serviceClass:=template.Field('serviceclasses').AsStringArr[i];
if FREDB_StringInArrayIdx(serviceClass,disabledSCs)<>-1 then continue; //skip disabled services
exClass:=GFRE_DBI.GetObjectClassEx(serviceClass);
if Assigned(exClass) then begin //ignore not found serviceClasses
conf:=exClass.Invoke_DBIMC_Method('GetConfig',input,ses,app,conn);
if conf.Field('type').AsString='service' then begin
if serviceClass=TFRE_DB_VMACHINE.ClassName then begin
canAddService:=fVMMod.canAddService(ses,conn,false);
canModify:=canModify or fVMMod.canModifyService(conn);
canApply:=canApply or fVMMod.canApplyService(conn);
canEnable:=canEnable or fVMMod.canEnableService(conn);
canDisable:=canDisable or fVMMod.canDisableService(conn);
canDelete:=canDelete or fVMMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_FIREWALL_SERVICE.ClassName then begin
canAddService:=fFirewallMod.canAddService(conn);
canModify:=canModify or fFirewallMod.canModifyService(conn);
canApply:=canApply or fFirewallMod.canApplyService(conn);
canEnable:=canEnable or fFirewallMod.canEnableService(conn);
canDisable:=canDisable or fFirewallMod.canDisableService(conn);
canDelete:=canDelete or fFirewallMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_DHCP.ClassName then begin
canAddService:=fDHCPMod.canAddService(conn);
canModify:=canModify or fDHCPMod.canModifyService(conn);
canApply:=canApply or fDHCPMod.canApplyService(conn);
canEnable:=canEnable or fDHCPMod.canEnableService(conn);
canDisable:=canDisable or fDHCPMod.canDisableService(conn);
canDelete:=canDelete or fDHCPMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_VIRTUAL_FILESERVER.ClassName then begin
canAddService:=fFSMod.canAddService(conn,false);
canModify:=canModify or fFSMod.canModifyService(conn);
canApply:=canApply or fFSMod.canApplyService(conn);
canEnable:=canEnable or fFSMod.canEnableService(conn);
canDisable:=canDisable or fFSMod.canDisableService(conn);
canDelete:=canDelete or fFSMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_GLOBAL_FILESERVER.ClassName then begin
canAddService:=fFSMod.canAddService(conn,true);
//canModify:=canModify or fFSMod.canModifyService(conn);
//canApply:=canApply or fFSMod.canApplyService(conn);
//canEnable:=canEnable or fFSMod.canEnableService(conn);
//canDisable:=canDisable or fFSMod.canDisableService(conn);
//canDelete:=canDelete or fFSMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_VPN.ClassName then begin
canAddService:=fVPNMod.canAddService(conn);
canModify:=canModify or fVPNMod.canModifyService(conn);
canApply:=canApply or fVPNMod.canApplyService(conn);
canEnable:=canEnable or fVPNMod.canEnableService(conn);
canDisable:=canDisable or fVPNMod.canDisableService(conn);
canDelete:=canDelete or fVPNMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_HTTP_SERVICE.ClassName then begin
canAddService:=fWebserverMod.canAddService(conn);
canModify:=canModify or fWebserverMod.canModifyService(conn);
canApply:=canApply or fWebserverMod.canApplyService(conn);
canEnable:=canEnable or fWebserverMod.canEnableService(conn);
canDisable:=canDisable or fWebserverMod.canDisableService(conn);
canDelete:=canDelete or fWebserverMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_GROUPWARE_SERVICE.ClassName then begin
canAddService:=fGroupwareMod.canAddService(conn);
canModify:=canModify or fGroupwareMod.canModifyService(conn);
canApply:=canApply or fGroupwareMod.canApplyService(conn);
canEnable:=canEnable or fGroupwareMod.canEnableService(conn);
canDisable:=canDisable or fGroupwareMod.canDisableService(conn);
canDelete:=canDelete or fGroupwareMod.canDeleteService(conn);
end else
if serviceClass=TFRE_DB_DNS.ClassName then begin
canAddService:=fDNSMod.canAddService(conn);
canModify:=canModify or fDNSMod.canModifyService(conn);
canApply:=canApply or fDNSMod.canApplyService(conn);
canEnable:=canEnable or fDNSMod.canEnableService(conn);
canDisable:=canDisable or fDNSMod.canDisableService(conn);
canDelete:=canDelete or fDNSMod.canDeleteService(conn);
end else begin //ignore not managed services
canAddService:=false;
//canAddService:=conn.SYS.CheckClassRight4AnyDomain(sr_STORE,serviceClass);
//canModify:=canModify or conn.SYS.CheckClassRight4AnyDomain(sr_UPDATE,serviceClass);
//canApply:=canApply or conn.SYS.CheckClassRight4AnyDomain(sr_UPDATE,serviceClass);
//canEnable:=canEnable or conn.SYS.CheckClassRight4AnyDomain(sr_UPDATE,serviceClass);
//canDisable:=canDisable or conn.SYS.CheckClassRight4AnyDomain(sr_UPDATE,serviceClass);
//canDelete:=canDelete or conn.SYS.CheckClassRight4AnyDomain(sr_DELETE,serviceClass);
end;
if canAddService then begin
canAdd:=true;
sf:=CWSF(@WEB_AddService);
sf.AddParam.Describe('serviceClass',serviceClass);
sf.AddParam.Describe('zoneId',zone.UID_String);
submenu.AddEntry.Describe(conf.Field('caption').AsString,'',sf,conf.Field('OnlyOneServicePerZone').AsBoolean and (conn.GetReferencesCount(zone.UID,false,serviceClass,'serviceParent')>0));
end;
end;
end;
end;
if canAdd or canDelete or canApply or canEnable or canDisable then begin
if not canAdd then begin
menu:=TFRE_DB_MENU_DESC.create.Describe;
end;
if canModify then begin
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_modify_service'),'',CWSF(@WEB_ModifyService),true,'service_modify');
end;
if canApply then begin
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_apply_service_config'),'',CWSF(@WEB_ApplyServiceConfig),true,'service_apply_config');
end;
if canEnable then begin
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_enable_service'),'',CWSF(@WEB_EnableService),true,'service_enable');
end;
if canDisable then begin
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_disable_service'),'',CWSF(@WEB_DisableService),true,'service_disable');
end;
if canDelete then begin
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_delete_service'),'',CWSF(@WEB_DeleteService),true,'service_delete');
end;
res.SetMenu(menu);
end;
res.contentId:='ZONE_SERVICES';
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ZoneContentSMFs(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
dc : IFRE_DB_DERIVED_COLLECTION;
res : TFRE_DB_VIEW_LIST_DESC;
zone : TFRE_DB_ZONE;
begin
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_ZONE,zone));
if not conn.SYS.CheckClassRight4DomainId(sr_FETCH,TFRE_DB_SMF,zone.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
dc:=ses.FetchDerivedCollection('ZONE_SMFS_GRID');
dc.Filters.RemoveFilter('zone');
dc.Filters.AddUIDFieldFilter('zone','zuid',[zone.UID],dbnf_OneValueFromFilter);
res:=dc.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC;
res.AddButton.Describe(CWSF(@WEB_SMFShowLog),'',FetchModuleTextShort(ses,'tb_smf_show_log'),'',fdgbd_single);
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD._updateZoneServiceToolbar(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
disabledSCs : TFRE_DB_StringArray;
template : TFRE_DB_FBZ_TEMPLATE;
i : Integer;
serviceClass : String;
exClass : TFRE_DB_ObjectClassEx;
conf : IFRE_DB_Object;
canAddService: Boolean;
sf : TFRE_DB_SERVER_FUNC_DESC;
submenu : TFRE_DB_MENU_DESC;
begin
CheckClassVisibility4AnyDomain(ses);
CheckDbResult(conn.FetchAs(ses.GetSessionModuleData(ClassName).Field('selectedZone').AsGUID,TFRE_DB_ZONE,zone));
disabledSCs:=zone.Field('disabledSCs').AsStringArr;
CheckDbResult(conn.FetchAs(zone.Field('templateid').AsObjectLink,TFRE_DB_FBZ_TEMPLATE,template));
submenu:=TFRE_DB_MENU_DESC.create.Describe;
for i := 0 to template.Field('serviceclasses').ValueCount -1 do begin
serviceClass:=template.Field('serviceclasses').AsStringArr[i];
if FREDB_StringInArrayIdx(serviceClass,disabledSCs)<>-1 then continue; //skip disabled services
exClass:=GFRE_DBI.GetObjectClassEx(serviceClass);
if Assigned(exClass) then begin //ignore not found serviceClasses
conf:=exClass.Invoke_DBIMC_Method('GetConfig',input,ses,app,conn);
if conf.Field('type').AsString='service' then begin
if serviceClass=TFRE_DB_VMACHINE.ClassName then begin
canAddService:=fVMMod.canAddService(ses,conn,false);
end else
if serviceClass=TFRE_DB_FIREWALL_SERVICE.ClassName then begin
canAddService:=fFirewallMod.canAddService(conn);
end else
if serviceClass=TFRE_DB_DHCP.ClassName then begin
canAddService:=fDHCPMod.canAddService(conn);
end else
if serviceClass=TFRE_DB_VIRTUAL_FILESERVER.ClassName then begin
canAddService:=fFSMod.canAddService(conn,false);
end else
if serviceClass=TFRE_DB_GLOBAL_FILESERVER.ClassName then begin
canAddService:=fFSMod.canAddService(conn,true);
end else
if serviceClass=TFRE_DB_VPN.ClassName then begin
canAddService:=fVPNMod.canAddService(conn);
end else
if serviceClass=TFRE_DB_HTTP_SERVICE.ClassName then begin
canAddService:=fWebserverMod.canAddService(conn);
end else
if serviceClass=TFRE_DB_GROUPWARE_SERVICE.ClassName then begin
canAddService:=fGroupwareMod.canAddService(conn);
end else
if serviceClass=TFRE_DB_DNS.ClassName then begin
canAddService:=fDNSMod.canAddService(conn);
end else begin //ignore not managed services
canAddService:=false;
end;
if canAddService then begin
sf:=CWSF(@WEB_AddService);
sf.AddParam.Describe('serviceClass',serviceClass);
sf.AddParam.Describe('zoneId',zone.UID_String);
submenu.AddEntry.Describe(conf.Field('caption').AsString,'',sf,conf.Field('OnlyOneServicePerZone').AsBoolean and (conn.GetReferencesCount(zone.UID,false,serviceClass,'serviceParent')>0));
end;
end;
end;
end;
Result:=TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeSubmenu('add_menu',submenu);
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_StoreZoneConfiguration(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
errorClasses : TFRE_DB_StringArray;
sf : TFRE_DB_SERVER_FUNC_DESC;
servicesStr : String;
exClass : TFRE_DB_ObjectClassEx;
i : Integer;
conf : IFRE_DB_Object;
schemeObject : IFRE_DB_SchemeObject;
coll : IFRE_DB_COLLECTION;
template : TFRE_DB_FBZ_TEMPLATE;
rootServers : TFRE_DB_GUIDArray;
rootServer : IFRE_DB_Object;
modified : Boolean;
procedure _handleService(const field: IFRE_DB_Field);
var
idx : NativeInt;
refCount: NativeInt;
begin
idx:=FREDB_StringInArrayIdx(field.FieldName,zone.Field('disabledSCs').AsStringArr);
if field.AsBoolean then begin
if idx<>-1 then begin
zone.Field('disabledSCs').RemoveString(idx);
end;
end else begin
if idx=-1 then begin
refCount:=conn.GetReferencesCount(zone.UID,false,field.FieldName,'serviceParent');
if refCount>0 then begin
SetLength(errorClasses,Length(errorClasses)+1);
errorClasses[Length(errorClasses)-1]:=field.FieldName;
end;
zone.Field('disabledSCs').AddString(field.FieldName);
end;
end;
end;
begin
Result:=GFRE_DB_NIL_DESC;
modified:=false;
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_ZONE,zone));
if not conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_ZONE,zone.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if input.FieldPathExists('data.zone') then begin //update the zone
if not GFRE_DBI.GetSystemScheme(zone.ClassType,schemeObject) then
raise EFRE_DB_Exception.Create(edb_ERROR,'the scheme [%s] is unknown!',[zone.ClassName]);
if input.FieldPathExists('data.zone.objname') and (input.FieldPath('data.zone.objname').AsString<>zone.ObjectName) then begin
zone.ObjectName:=input.FieldPath('data.zone.objname').AsString;
coll:=conn.GetCollection(CFOS_DB_ZONES_COLLECTION);
if coll.ExistsIndexedText(zone.ObjectName,false,'displayname')<>0 then begin
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'modify_infrastructure_error_exists_cap'),FetchModuleTextShort(ses,'modify_infrastructure_error_exists_message_zone'),fdbmt_error);
exit;
end;
CheckDbResult(conn.FetchAs(zone.field('templateid').AsObjectLink,TFRE_DB_FBZ_TEMPLATE,template));
if template.root then begin //update root server service obj
rootServers:=conn.GetReferences(zone.UID,false,TFRE_DB_VROOTSERVER.ClassName,'serviceParent');
for i := 0 to High(rootServers) do begin //should always be only one
CheckDbResult(conn.Fetch(rootServers[i],rootServer));
rootServer.field('UCT').AsString:=TFRE_DB_VROOTSERVER.ClassName + '_' + zone.ObjectName + '@' + zone.UID_String;
rootServer.Field('objname').AsString:=zone.ObjectName;
CheckDbResult(conn.Update(rootServer));
end;
end;
end;
schemeObject.SetObjectFieldsWithScheme(input.FieldPath('data.zone').AsObject,zone,false,conn);
CheckDBResult(conn.Update(zone.CloneToNewObject()));
modified:=true;
end;
if input.FieldPathExists('data.config') then begin
SetLength(errorClasses,0);
input.FieldPath('data.config').AsObject.ForAllFields(@_handleService,true);
if Length(errorClasses)=0 then begin
CheckDbResult(conn.Update(zone.CloneToNewObject()));
modified:=true;
end else begin
sf:=CWSF(@WEB_ZoneContentConfiguration);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
servicesStr:='';
for i := 0 to high(errorClasses) do begin
exClass:=GFRE_DBI.GetObjectClassEx(errorClasses[i]);
if i>0 then servicesStr:=servicesStr + ', ';
if Assigned(exClass) then begin
conf:=exClass.Invoke_DBIMC_Method('GetConfig',input,ses,app,conn);
servicesStr:=servicesStr + conf.Field('caption').AsString;
end else begin
servicesStr:=servicesStr + errorClasses[i];
end;
end;
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'zone_config_save_error_cap'),StringReplace(FetchModuleTextShort(ses,'zone_config_save_error_msg'),'%services_str%',servicesStr,[rfReplaceAll]),fdbmt_error,sf);
end;
end;
if modified then begin
zone.UpdateEmbedded(conn,ses);
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_DSObjChanged(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
Result:=GFRE_DB_NIL_DESC;
if input.Field('type').AsString='UPD' then begin
if ses.isUpdatableContentVisible('DS_CONFIG') then begin
input.Field('selected').AsString:=FREDB_G2H(ses.GetSessionModuleData(ClassName).Field('selectedDS').AsGUID);
Result:=WEB_DSContentConfiguration(input,ses,app,conn);
end;
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_DSContentConfiguration(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
form : TFRE_DB_FORM_PANEL_DESC;
scheme: IFRE_DB_SchemeObject;
dbo : TFRE_DB_ZFS_ZONE_CONTAINER_DATASET;
begin
CheckClassVisibility4AnyDomain(ses);
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_ZFS_ZONE_CONTAINER_DATASET,dbo));
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_ZFS_ZONE_CONTAINER_DATASET.ClassName,scheme);
form:=TFRE_DB_FORM_PANEL_DESC.create.Describe('',true,false);
form.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses);
form.AddSchemeFormGroup(scheme.GetInputGroup('properties'),ses);
form.FillWithObjectValues(dbo,ses);
finfrastructureIFMod.addSnapshotJobsToForm(dbo,form,ses,conn);
finfrastructureIFMod.addSnapshotMenuToForm(dbo,form,ses,conn);
form.contentId:='DS_CONFIG';
Result:=form;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_DSContentSnapshots(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
ds : TFRE_DB_ZFS_DATASET;
begin
CheckClassVisibility4AnyDomain(ses);
CheckDbResult(conn.FetchAs(ses.GetSessionModuleData(ClassName).Field('selectedDS').AsGUID,TFRE_DB_ZFS_DATASET,ds));
Result:=finfrastructureIFMod.getHierarchicalSnapshotsGrid(ds.Name,input,ses,app,conn);
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ServicesGridMenu(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
res: TFRE_DB_MENU_DESC;
sf : TFRE_DB_SERVER_FUNC_DESC;
dbo: IFRE_DB_Object;
begin
res:=TFRE_DB_MENU_DESC.create.Describe;
if input.FieldExists('selected') and (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if _canModifyService(dbo.SchemeClass,conn) then begin
sf:=CWSF(@WEB_ModifyService);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_modify_service'),'',sf,not _canModifyService(dbo,conn));
end;
if _canApplyService(dbo.SchemeClass,conn) then begin
sf:=CWSF(@WEB_ApplyServiceConfig);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_apply_service_config'),'',sf,not _canApplyService(dbo,conn));
end;
if _canEnableService(dbo.SchemeClass,conn) then begin
sf:=CWSF(@WEB_EnableService);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_enable_service'),'',sf,not _canEnableService(dbo,conn));
end;
if _canDisableService(dbo.SchemeClass,conn) then begin
sf:=CWSF(@WEB_DisableService);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_disable_service'),'',sf, not _canDisableService(dbo,conn));
end;
if _canDeleteService(dbo.SchemeClass,conn) then begin
sf:=CWSF(@WEB_DeleteService);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_delete_service'),'',sf,not _canDeleteService(dbo,conn));
end;
end;
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ServicesGridSC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
deleteDisabled : Boolean;
applyDisabled : Boolean;
enableDisabled : Boolean;
disableDisabled : Boolean;
dbo : IFRE_DB_Object;
modfiyDisabled : Boolean;
begin
deleteDisabled:=true;
modfiyDisabled:=true;
applyDisabled:=true;
enableDisabled:=true;
disableDisabled:=true;
if ses.GetSessionModuleData(ClassName).FieldExists('selectedService') then begin
ses.UnregisterDBOChangeCB('infrastructureModSO');
end;
if input.FieldExists('selected') and (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
ses.RegisterDBOChangeCB(dbo.UID,CWSF(@WEB_ServiceObjChanged),'infrastructureModSO');
deleteDisabled:=not _canDeleteService(dbo,conn);
modfiyDisabled:=not _canModifyService(dbo,conn);
applyDisabled:=not _canApplyService(dbo,conn);
enableDisabled:=not _canEnableService(dbo,conn);
disableDisabled:=not _canDisableService(dbo,conn);
ses.GetSessionModuleData(ClassName).Field('selectedService').AsStringArr:=input.Field('selected').AsStringArr;
end else begin
ses.GetSessionModuleData(ClassName).DeleteField('selectedService');
end;
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('service_delete',deleteDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('service_modify',modfiyDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('service_apply_config',applyDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('service_enable',enableDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('service_disable',disableDisabled));
Result:=GFRE_DB_NIL_DESC;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_SMFsGridMenu(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
res : TFRE_DB_MENU_DESC;
sf : TFRE_DB_SERVER_FUNC_DESC;
begin
res:=TFRE_DB_MENU_DESC.create.Describe;
sf:=CWSF(@WEB_SMFShowLog);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_smf_show_log'),'',sf);
Result:=res;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_SMFShowLog(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
diag : TFRE_DB_DIALOG_DESC;
sf : TFRE_DB_SERVER_FUNC_DESC;
begin
CheckClassVisibility4AnyDomain(ses);
sf:=CWSF(@WEB_SMFLoadLog);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
diag:=TFRE_DB_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'smf_show_log_diag_cap'),TFRE_DB_EDITOR_DESC.create.Describe(sf,nil,nil,nil,ct_log,false));
diag.AddButton.Describe(FetchModuleTextShort(ses,'smf_show_log_diag_close'),nil,fdbbt_close);
Result:=diag;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_SMFLoadLog(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
smfDbo : IFRE_DB_Object;
log : String;
begin
CheckClassVisibility4AnyDomain(ses);
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),smfDbo));
log:=FetchModuleTextShort(ses,'smf_show_log_diag_no_log');
Result:=TFRE_DB_EDITOR_DATA_DESC.create.Describe(log);
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ServiceObjChanged(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
dbo : IFRE_DB_Object;
begin
if input.Field('type').AsString='DEL' then begin
ses.GetSessionModuleData(ClassName).DeleteField('selectedService');
end else begin
if ses.GetSessionModuleData(ClassName).FieldExists('selectedService') then begin
dbo:=input.Field('obj').AsObject;
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('service_delete',not _canDeleteService(dbo,conn)));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('service_apply_config',not _canApplyService(dbo,conn)));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('service_enable',not _canEnableService(dbo,conn)));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('service_disable',not _canDisableService(dbo,conn)));
end;
end;
Result:=GFRE_DB_NIL_DESC;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_AddService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
scheme : IFRE_DB_SchemeObject;
res : TFRE_DB_FORM_DIALOG_DESC;
sf : TFRE_DB_SERVER_FUNC_DESC;
serviceClass: shortstring;
exClass : TFRE_DB_ObjectClassEx;
conf : IFRE_DB_Object;
begin
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('zoneId').AsString),TFRE_DB_ZONE,zone));
serviceClass:=input.Field('serviceClass').AsString;
if serviceClass=TFRE_DB_VMACHINE.ClassName then begin
Result:=fVMMod.addService(input,ses,app,conn);
end else
if serviceClass=TFRE_DB_FIREWALL_SERVICE.ClassName then begin
Result:=fFirewallMod.addService(input,ses,app,conn);
end else
if serviceClass=TFRE_DB_DHCP.ClassName then begin
Result:=fDHCPMod.addService(input,ses,app,conn);
end else
if serviceClass=TFRE_DB_VIRTUAL_FILESERVER.ClassName then begin
Result:=fFSMod.addService(input,ses,app,conn,false);
end else
if serviceClass=TFRE_DB_GLOBAL_FILESERVER.ClassName then begin
Result:=fFSMod.addService(input,ses,app,conn,true);
end else
if serviceClass=TFRE_DB_VPN.ClassName then begin
Result:=fVPNMod.addService(input,ses,app,conn);
end else
if serviceClass=TFRE_DB_HTTP_SERVICE.ClassName then begin
Result:=fWebserverMod.addService(input,ses,app,conn);
end else
if serviceClass=TFRE_DB_GROUPWARE_SERVICE.ClassName then begin
Result:=fGroupwareMod.addService(input,ses,app,conn);
end else
if serviceClass=TFRE_DB_DNS.ClassName then begin
Result:=fDNSMod.addService(input,ses,app,conn);
end else begin
if not conn.SYS.CheckClassRight4DomainId(sr_STORE,serviceClass,zone.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
exClass:=GFRE_DBI.GetObjectClassEx(serviceClass);
if not Assigned(exClass) then
raise EFRE_DB_Exception.Create('ObjectClass ' + serviceClass + ' not found');
conf:=exClass.Invoke_DBIMC_Method('GetConfig',input,ses,app,conn);
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(StringReplace(FetchModuleTextShort(ses,'add_service_diag_cap'),'%service_str%',conf.Field('caption').AsString,[rfReplaceAll]),600);
GFRE_DBI.GetSystemSchemeByName(serviceClass,scheme);
res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses);
sf:=CWSF(@WEB_StoreService);
sf.AddParam.Describe('zoneId',zone.UID_String);
sf.AddParam.Describe('serviceClass',serviceClass);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit);
Result:=res;
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ModifyService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
scheme : IFRE_DB_SchemeObject;
res : TFRE_DB_FORM_DIALOG_DESC;
service : TFRE_DB_SERVICE;
conf : IFRE_DB_Object;
begin
if not input.FieldExists('selected') or (input.Field('selected').AsString='') then begin
input.Field('selected').AsString:=ses.GetSessionModuleData(ClassName).Field('selectedService').AsString;
end;
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_SERVICE,service));
if service.IsA(TFRE_DB_VMACHINE) then begin
Result:=fVMMod.modifyService(input,ses,app,conn,service,'');
end else
if service.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
Result:=fFirewallMod.modifyService(input,ses,app,conn,service,'');
end else
if service.IsA(TFRE_DB_DHCP) then begin
Result:=fDHCPMod.modifyService(input,ses,app,conn,service,'');
end else
if service.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
Result:=fFSMod.modifyService(input,ses,app,conn,service,'');
end else
if service.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
Result:=fFSMod.modifyService(input,ses,app,conn,service,'');
end else
if service.IsA(TFRE_DB_VPN) then begin
Result:=fVPNMod.modifyService(input,ses,app,conn,service,'');
end else
if service.IsA(TFRE_DB_HTTP_SERVICE) then begin
Result:=fWebserverMod.modifyService(input,ses,app,conn,service,'');
end else
if service.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
Result:=fGroupwareMod.modifyService(input,ses,app,conn,service,'');
end else
if service.IsA(TFRE_DB_DNS) then begin
Result:=fDNSMod.modifyService(input,ses,app,conn,service,'');
end else begin //FIXXME - default code
if not _canModifyService(service,conn) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
conf:=service.WBC_GetConfig(input,ses,app,conn);
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(StringReplace(FetchModuleTextShort(ses,'modify_service_diag_cap'),'%service_str%',conf.Field('caption').AsString,[rfReplaceAll]),600);
GFRE_DBI.GetSystemSchemeByName(service.SchemeClass,scheme);
res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),CSFT('saveOperation',service),fdbbt_submit);
Result:=res;
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_DeleteService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
sf : TFRE_DB_SERVER_FUNC_DESC;
cap,msg : String;
service : TFRE_DB_SERVICE;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsString:=ses.GetSessionModuleData(ClassName).Field('selectedService').AsString;
end;
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_SERVICE,service));
if service.IsA(TFRE_DB_VMACHINE) then begin
Result:=fVMMod.deleteService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
Result:=fFirewallMod.deleteService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_DHCP) then begin
Result:=fDHCPMod.deleteService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
Result:=fFSMod.deleteService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
Result:=fFSMod.deleteService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_VPN) then begin
Result:=fVPNMod.deleteService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_HTTP_SERVICE) then begin
Result:=fWebserverMod.deleteService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
Result:=fGroupwareMod.deleteService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_DNS) then begin
Result:=fDNSMod.deleteService(input,ses,app,conn,service);
end else begin //FIXXME - default code
if not _canDeleteService(service,conn) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
sf:=CWSF(@WEB_DeleteServiceConfirmed);
sf.AddParam.Describe('selected',service.UID_String);
cap:=FetchModuleTextShort(ses,'delete_service_diag_cap');
msg:=StringReplace(FetchModuleTextShort(ses,'delete_service_diag_msg'),'%service_str%',service.Field('objname').AsString,[rfReplaceAll]);
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(cap,msg,fdbmt_confirm,sf);
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_DeleteServiceConfirmed(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
i : NativeInt;
service : TFRE_DB_SERVICE;
begin
if input.field('confirmed').AsBoolean then begin
for i:= 0 to input.Field('selected').ValueCount-1 do begin
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsStringArr[i]),TFRE_DB_SERVICE,service));
if not _canDeleteService(service,conn) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
CheckDbResult(conn.Delete(service.UID));
end;
end;
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_StoreService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
scheme : IFRE_DB_SchemeObject;
zone : TFRE_DB_ZONE;
dbo : IFRE_DB_Object;
coll : IFRE_DB_COLLECTION;
exClass : TFRE_DB_ObjectClassEx;
conf : IFRE_DB_Object;
serviceClass : TFRE_DB_String;
idx : String;
servicePlugin: TFRE_DB_SERVICE_STATUS_PLUGIN;
begin
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('zoneId').AsString),TFRE_DB_ZONE,zone));
if not conn.SYS.CheckClassRight4DomainId(sr_STORE,input.Field('serviceClass').AsString,zone.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if not input.FieldPathExists('data.objname') then
raise EFRE_DB_Exception.Create('Missing input parameter objname!');
serviceClass:=input.Field('serviceClass').AsString;
exClass:=GFRE_DBI.GetObjectClassEx(serviceClass);
if not Assigned(exClass) then
raise EFRE_DB_Exception.Create('ObjectClass ' + serviceClass + ' not found');
conf:=exClass.Invoke_DBIMC_Method('GetConfig',input,ses,app,conn);
idx:=serviceClass + '_' + input.FieldPath('data.objname').AsString + '@' + zone.UID_String;
coll:=conn.GetCollection(CFOS_DB_SERVICES_COLLECTION);
if coll.ExistsIndexedText(idx)<>0 then begin
Result:=TFRE_DB_MESSAGE_DESC.Create.Describe(FetchModuleTextShort(ses,'service_create_error_exists_cap'),StringReplace(FetchModuleTextShort(ses,'service_create_error_exists_msg'),'%service_str%',conf.Field('caption').AsString,[rfReplaceAll]),fdbmt_error);
exit;
end;
GFRE_DBI.GetSystemSchemeByName(serviceClass,scheme);
dbo:=GFRE_DBI.NewObjectSchemeByName(serviceClass);
dbo.Field('serviceParent').AsObjectLink:=zone.UID;
dbo.field('UCT').AsString:=idx;
dbo.SetDomainID(zone.DomainID);
scheme.SetObjectFieldsWithScheme(input.Field('data').AsObject,dbo,true,conn);
CheckDbResult(coll.Store(dbo));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ApplyServiceConfig(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
service : TFRE_DB_SERVICE;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsString:=ses.GetSessionModuleData(ClassName).Field('selectedService').AsString;
end;
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_SERVICE,service));
if service.IsA(TFRE_DB_VMACHINE) then begin
Result:=fVMMod.applyConfig(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
Result:=fFirewallMod.applyConfig(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_DHCP) then begin
Result:=fDHCPMod.applyConfig(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
Result:=fFSMod.applyConfig(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
Result:=fFSMod.applyConfig(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_VPN) then begin
Result:=fVPNMod.applyConfig(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_HTTP_SERVICE) then begin
Result:=fWebserverMod.applyConfig(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
Result:=fGroupwareMod.applyConfig(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_DNS) then begin
Result:=fDNSMod.applyConfig(input,ses,app,conn,service);
end else begin
if not conn.SYS.CheckClassRight4DomainId(sr_UPDATE,service.ClassType,service.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'apply_service_diag_cap'),FetchModuleTextShort(ses,'apply_service_diag_msg'),fdbmt_confirm,CWSF(@WEB_ApplyServiceConfigConfirmed));
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ApplyServiceConfigConfirmed(const input: IFRE_DB_Object; const ses: IFRE_DB_UserSession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
service : TFRE_DB_SERVICE;
servicePlugin : TFRE_DB_SERVICE_STATUS_PLUGIN;
begin //FIXXME default code
CheckDbResult(conn.FetchAs(FREDB_H2G(ses.GetSessionModuleData(ClassName).Field('selectedService').AsString),TFRE_DB_SERVICE,service));
if not conn.SYS.CheckClassRight4DomainId(sr_UPDATE,service.ClassType,service.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
service.GetPlugin(TFRE_DB_SERVICE_STATUS_PLUGIN,servicePlugin);
service.Embed(conn);
servicePlugin.setConfigApplied;
CheckDbResult(conn.Update(service));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_EnableService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
service : TFRE_DB_SERVICE;
zone : TFRE_DB_ZONE;
machine_uid : TFRE_DB_GUID;
procedure GotAnswer(const ses: IFRE_DB_UserSession; const new_input: IFRE_DB_Object; const status: TFRE_DB_COMMAND_STATUS; const ocid: Qword; const opaquedata: IFRE_DB_Object);
var stat : string;
begin
case status of
cdcs_OK: stat := 'CMD_OK';
cdcs_TIMEOUT: stat := 'CMD_TIMEOUT';
cdcs_ERROR: stat := 'CMD_ERROR';
end;
writeln('GOT ANSWER ENABLE SERVICE ',status,' ',new_input.DumpToString());
if status<>cdcs_OK then
begin
ses.SendServerClientRequest(TFRE_DB_MESSAGE_DESC.create.Describe('Result',stat+' '+new_input.GetAsJSONString(),fdbmt_info));
end;
end;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsString:=ses.GetSessionModuleData(ClassName).Field('selectedService').AsString;
end;
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_SERVICE,service));
if service.IsA(TFRE_DB_VMACHINE) then begin { high level service }
Result:=fVMMod.enableService(input,ses,app,conn,service); { }
end else
if service.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
Result:=fFirewallMod.enableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_DHCP) then begin
Result:=fDHCPMod.enableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
Result:=fFSMod.enableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
Result:=fFSMod.enableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_VPN) then begin
Result:=fVPNMod.enableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_HTTP_SERVICE) then begin
Result:=fWebserverMod.enableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
Result:=fGroupwareMod.enableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_DNS) then begin
Result:=fDNSMod.enableService(input,ses,app,conn,service);
end else begin //FIXXME - default code
Result:=TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','No application interfacemodule found for enable service class '+service.SchemeClass,fdbmt_error);
//CheckDbResult(conn.FetchAs(service.Field('serviceparent').asGUID,TFRE_DB_ZONE,zone));
//machine_uid := zone.MachineID;
//service.Field('zonename').AsString:=zone.UID_String;
//service.Embed(conn);
//writeln('SWL EMBEDDED SERVICE:',service.DumpToString);
//if ses.InvokeRemoteInterface(machine_uid,@service.RIF_EnableService,@GotAnswer,nil)=edb_OK then begin
// Result:=GFRE_DB_SUPPRESS_SYNC_ANSWER;
//end else begin
//Result:=TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','No feeder connected that implements the service enable for '+service.UID_String+' '+machine_uid.AsHexString,fdbmt_error);
//end;
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_DisableService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
service : TFRE_DB_SERVICE;
zone : TFRE_DB_ZONE;
machine_uid : TFRE_DB_GUID;
i : integer;
procedure GotAnswer(const ses: IFRE_DB_UserSession; const new_input: IFRE_DB_Object; const status: TFRE_DB_COMMAND_STATUS; const ocid: Qword; const opaquedata: IFRE_DB_Object);
var stat : string;
begin
case status of
cdcs_OK: stat := 'CMD_OK';
cdcs_TIMEOUT: stat := 'CMD_TIMEOUT';
cdcs_ERROR: stat := 'CMD_ERROR';
end;
writeln('GOT ANSWER DISABLE SERVICE ',status,' ',new_input.DumpToString());
if status<>cdcs_OK then
begin
ses.SendServerClientRequest(TFRE_DB_MESSAGE_DESC.create.Describe('Result',stat+' '+new_input.GetAsJSONString(),fdbmt_info));
end;
end;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsString:=ses.GetSessionModuleData(ClassName).Field('selectedService').AsString;
end;
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_SERVICE,service));
if service.IsA(TFRE_DB_VMACHINE) then begin
Result:=fVMMod.disableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_FIREWALL_SERVICE) then begin
Result:=fFirewallMod.disableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_DHCP) then begin
Result:=fDHCPMod.disableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_VIRTUAL_FILESERVER) then begin
Result:=fFSMod.disableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_GLOBAL_FILESERVER) then begin
Result:=fFSMod.disableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_VPN) then begin
Result:=fVPNMod.disableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_HTTP_SERVICE) then begin
Result:=fWebserverMod.disableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_GROUPWARE_SERVICE) then begin
Result:=fGroupwareMod.disableService(input,ses,app,conn,service);
end else
if service.IsA(TFRE_DB_DNS) then begin
Result:=fDNSMod.disableService(input,ses,app,conn,service);
end else begin //FIXXME - default code
Result:=TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','No application interfacemodule found for disable service class '+service.SchemeClass,fdbmt_error);
//CheckDbResult(conn.FetchAs(service.Field('serviceparent').asGUID,TFRE_DB_ZONE,zone));
//machine_uid := zone.MachineID;
//service.Field('zonename').AsString:=zone.UID_String;
//service.Embed(conn);
//if ses.InvokeRemoteInterface(machine_uid,@service.RIF_DisableService,@GotAnswer,nil)=edb_OK then begin
// Result:=GFRE_DB_SUPPRESS_SYNC_ANSWER;
//end else begin
// Result:=TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','No feeder connected that implements the service disable for '+service.UID_String+' '+machine_uid.AsHexString,fdbmt_error);
//end;
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ZoneUninstall(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
sf : TFRE_DB_SERVER_FUNC_DESC;
zone : TFRE_DB_ZONE;
begin
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('zoneId').AsString),TFRE_DB_ZONE,zone));
if not conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_ZONE,zone.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
sf:=CWSF(@WEB_ZoneUninstallConfirmed);
sf.AddParam.Describe('zoneId',zone.UID_String);
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'uninstall_zone_diag_cap'),StringReplace(FetchModuleTextShort(ses,'uninstall_zone_diag_msg'),'%zone_str%',zone.ObjectName,[rfReplaceAll]),fdbmt_confirm,sf);
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ZoneUninstallConfirmed(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
machine_uid : TFRE_DB_GUID;
job : TFRE_DB_ZONEDESTROY_JOB;
embedded : IFRE_DB_Object;
coll : IFRE_DB_COLLECTION;
begin
if input.field('confirmed').AsBoolean then begin
//FIXXME : Plugin Lock !
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('zoneId').AsString),TFRE_DB_ZONE,zone));
if not conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_ZONE,zone.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
machine_uid := zone.MachineID;
coll:=conn.GetCollection(CFOS_DB_ZONES_EMBEDDED_COLLECTION);
if coll.GetIndexedObjText(zone.UCT,embedded,false,'upid')=0 then
raise EFRE_DB_Exception.Create('Embedded zone object not found');
job := TFRE_DB_ZONEDESTROY_JOB.create;
job.SetDomainID(embedded.DomainID);
job.SetZoneObject(embedded);
//job.DontStartImmediateJob := true; { debug zone uninstall }
if ses.InvokeRemoteInterface(machine_uid,@job.RIF_Start,@CCB_ZoneReply,_CreateOpaqueCommandData('ZONEUNINSTALL','ZU'))=edb_OK then begin
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();;
exit;
end else begin
result := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','No feeder connected that implements the zone uninstall for '+zone.UID_String+' '+machine_uid.AsHexString,fdbmt_error);
end;
end else begin
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
end;
procedure TFOS_INFRASTRUCTURE_MOD.CCB_ZoneReply(const ses: IFRE_DB_UserSession; const rifstatus: TFRE_DB_RIF_RESULT; const ocid: Qword; const opaquedata: IFRE_DB_Object);
var hint,cmd_type : string;
begin
_GetOpaqueComandData(opaquedata,hint,cmd_type);
writeln('ZONE CMD ANSWER : ',hint,' ',cmd_type,' ',rifstatus.GetAsJSONString());
case rifstatus.Transferstatus of
cdcs_OK:
begin
if rifstatus.ErrorCode<>0 then
begin
ses.SendServerClientRequest(TFRE_DB_MESSAGE_DESC.create.Describe('ZONECOMMAND '+cmd_type,'Error:'+hint+LineEnding+rifstatus.ErrorText,fdbmt_error));
end
else
;{ it's ok }
end;
cdcs_TIMEOUT:
begin
//FIXXME - send message with solution suggestion
ses.SendServerClientRequest(TFRE_DB_MESSAGE_DESC.create.Describe('ZONECOMMAND '+cmd_type,'Failed Timeout:'+hint,fdbmt_error));
end;
cdcs_ERROR:
begin
ses.SendServerClientRequest(TFRE_DB_MESSAGE_DESC.create.Describe('ZONECOMMAND '+cmd_type,'Error:'+hint+LineEnding+rifstatus.ErrorText,fdbmt_error));
end;
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ZoneBoot(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
machine_uid : TFRE_DB_GUID;
begin
//FIXXME : Plugin Lock !
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('zoneId').AsString),TFRE_DB_ZONE,zone));
machine_uid := zone.MachineID;
if ses.InvokeRemoteInterface(machine_uid,@zone.RIF_Boot,@CCB_ZoneReply,_CreateOpaqueCommandData('ZONEBOOT','ZB'))=edb_OK then
begin
result := GFRE_DB_NIL_DESC;
exit;
end
else
begin
result := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','No feeder connected that implements the zone boot for '+zone.UID_String+' '+machine_uid.AsHexString,fdbmt_error);
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ZoneShutdown(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
machine_uid : TFRE_DB_GUID;
begin
//FIXXME : Plugin Lock !
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('zoneId').AsString),TFRE_DB_ZONE,zone));
machine_uid := zone.MachineID;
if ses.InvokeRemoteInterface(machine_uid,@zone.RIF_Shutdown,@CCB_ZoneReply,_CreateOpaqueCommandData('ZONESHUTDOWN','ZS'))=edb_OK then
begin
result := GFRE_DB_NIL_DESC;
exit;
end
else
begin
result := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','No feeder connected that implements the zone boot for '+zone.UID_String+' '+machine_uid.AsHexString,fdbmt_error);
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ZoneHalt(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
machine_uid : TFRE_DB_GUID;
begin
//FIXXME : Plugin Lock !
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('zoneId').AsString),TFRE_DB_ZONE,zone));
machine_uid := zone.MachineID;
if ses.InvokeRemoteInterface(machine_uid,@zone.RIF_Halt,@CCB_ZoneReply,_CreateOpaqueCommandData('ZONEHALT','ZH'))=edb_OK then
begin
result := GFRE_DB_NIL_DESC;
exit;
end
else
begin
result := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','No feeder connected that implements the zone boot for '+zone.UID_String+' '+machine_uid.AsHexString,fdbmt_error);
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ZoneObjChanged(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
Result:=GFRE_DB_NIL_DESC;
if input.Field('type').AsString<>'DEL' then begin
if ses.isUpdatableContentVisible('ZONE_CONFIG') then begin
input.Field('selected').AsString:=FREDB_G2H(ses.GetSessionModuleData(ClassName).Field('selectedZone').AsGUID);
Result:=WEB_ZoneContentConfiguration(input,ses,app,conn);
end;
if ses.isUpdatableContentVisible('ZONE_SERVICES') then begin
Result:=_updateZoneServiceToolbar(input,ses,app,conn);
end;
end;
end;
function TFOS_INFRASTRUCTURE_MOD.WEB_ZoneInstall(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
zone : TFRE_DB_ZONE;
embedded : IFRE_DB_Object;
machine_uid : TFRE_DB_GUID;
job : TFRE_DB_ZONECREATION_JOB;
coll : IFRE_DB_COLLECTION;
begin
//FIXXME : Plugin Lock !
CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('zoneId').AsString),TFRE_DB_ZONE,zone));
if not conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_ZONE,zone.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
machine_uid := zone.MachineID;
coll:=conn.GetCollection(CFOS_DB_ZONES_EMBEDDED_COLLECTION);
if coll.GetIndexedObjText(zone.UCT,embedded,false,'upid')=0 then
raise EFRE_DB_Exception.Create('Embedded zone object not found');
job := TFRE_DB_ZONECREATION_JOB.create;
job.SetDomainID(embedded.DomainID);
job.SetZoneObject(embedded);
//job.DontStartImmediateJob := true; { debug zone install }
if ses.InvokeRemoteInterface(machine_uid,@job.RIF_Start,@CCB_ZoneReply,_CreateOpaqueCommandData('ZONEINSTALL','ZI'))=edb_OK then
begin
result := GFRE_DB_NIL_DESC;
exit;
end
else
begin
result := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','No feeder connected that implements the zone installation for '+zone.UID_String+' '+machine_uid.AsHexString,fdbmt_error);
end;
end;
end.
|
unit FMX.LoadingIndicator;
interface
uses
System.Classes,
System.Types,
System.UITypes,
System.Math,
FMX.Types,
FMX.Controls,
FMX.Graphics,
FMX.Objects,
FMX.Layouts,
FMX.Ani,
FMX.Utils,
FMX.ComponentsCommon;
type
TLoadingIndicatorKind = (LoadingArcs, LoadingDoubleBounce, LoadingFlipPlane,
LoadingPulse, LoadingArcsRing, LoadingRing, LoadingThreeDots, LoadingWave);
[ComponentPlatformsAttribute(TFMXPlatforms)]
TFMXLoadingIndicator = class(TLayout)
private type
TCell = record
Col: Integer;
Row: Integer;
ColSpan: Integer;
RowSpan: Integer;
end;
private const
INDICATOR_DURING: array [TLoadingIndicatorKind] of Single = (
3, 1, 1.6, 1.5, 0.8, 0.8, 1.9, 1
);
INDICATOR_AUTOREVERSE: array [TLoadingIndicatorKind] of Boolean = (
False, True, False, True, False, False, False, False
);
INDICATOR_MINSIZE: array [TLoadingIndicatorKind] of TSizeF = (
(cx: 45; cy: 45),
(cx: 45; cy: 45),
(cx: 45; cy: 45),
(cx: 45; cy: 45),
(cx: 45; cy: 45),
(cx: 45; cy: 45),
(cx: 70; cy: 20),
(cx: 50; cy: 40)
);
RING_CELLS: array [0 .. 7] of TCell = (
(Col: 2; Row: 0; ColSpan: 1; RowSpan: 1),
(Col: 3; Row: 0; ColSpan: 2; RowSpan: 2),
(Col: 4; Row: 2; ColSpan: 1; RowSpan: 1),
(Col: 3; Row: 3; ColSpan: 2; RowSpan: 2),
(Col: 2; Row: 4; ColSpan: 1; RowSpan: 1),
(Col: 0; Row: 3; ColSpan: 2; RowSpan: 2),
(Col: 0; Row: 2; ColSpan: 1; RowSpan: 1),
(Col: 0; Row: 0; ColSpan: 2; RowSpan: 2)
);
RING_CIRCLE_SIZE = 7;
procedure ConfirmSize;
private
FKind: TLoadingIndicatorKind;
FBrush: TBrush;
FAnimation: TAnimation;
FDrawProc: procedure of object;
function GetCellRect(CellWidth, CellHeight: Single; const Cell: TCell): TRectF;
function GetColor: TAlphaColor;
procedure OnAnimation(Sender: TObject);
procedure SetKind(const Value: TLoadingIndicatorKind);
procedure SetColor(const Value: TAlphaColor);
procedure CreateAnimation;
procedure DrawLoadingArcs;
procedure DrawLoadingArcsRing;
procedure DrawLoadingDoubleBounce;
procedure DrawLoadingFlipPlane;
procedure DrawLoadingPulse;
procedure DrawLoadingRing;
procedure DrawLodingThreeDots;
procedure DrawLoadingWave;
protected
procedure Resize; override;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
procedure Start;
published
property Color: TAlphaColor read GetColor write SetColor;
property Kind: TLoadingIndicatorKind read FKind write SetKind
default TLoadingIndicatorKind.LoadingPulse;
property Align;
property Anchors;
property ClipChildren default False;
property ClipParent default False;
property Cursor default crDefault;
property DragMode default TDragMode.dmManual;
property EnableDragHighlight default True;
property Enabled default True;
property Locked default False;
property Height;
property HitTest default True;
property Padding;
property Opacity;
property Margins;
property PopupMenu;
property Position;
property RotationAngle;
property RotationCenter;
property Scale;
property Size;
property Visible default True;
property Width;
{ Drag and Drop events }
property OnDragEnter;
property OnDragLeave;
property OnDragOver;
property OnDragDrop;
property OnDragEnd;
{ Mouse events }
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseEnter;
property OnMouseLeave;
property OnPainting;
property OnPaint;
property OnResize;
{$IF (RTLVersion >= 32)} // Tokyo
property OnResized;
{$ENDIF}
end;
implementation
type
TMyAnimation = class(TAnimation)
protected
procedure ProcessAnimation; override;
end;
{ TFMXLoadingIndicator }
procedure TFMXLoadingIndicator.OnAnimation(Sender: TObject);
begin
Repaint;
end;
procedure TFMXLoadingIndicator.Paint;
begin
inherited;
FDrawProc;
end;
procedure TFMXLoadingIndicator.Resize;
begin
inherited;
if not (csLoading in ComponentState) then
begin
ConfirmSize;
Repaint;
end;
end;
constructor TFMXLoadingIndicator.Create(AOwner: TComponent);
begin
inherited;
FBrush := TBrush.Create(TBrushKind.Solid, $FF1282B2);
FKind := TLoadingIndicatorKind.LoadingPulse;
Width := 45;
Height := 45;
CreateAnimation;
FAnimation.Duration := INDICATOR_DURING[FKind];
FAnimation.AutoReverse := INDICATOR_AUTOREVERSE[FKind];
FDrawProc := DrawLoadingPulse;
end;
procedure TFMXLoadingIndicator.Loaded;
begin
inherited;
Start;
end;
procedure TFMXLoadingIndicator.SetColor(const Value: TAlphaColor);
begin
if FBrush.Color <> Value then
begin
FBrush.Color := Value;
end;
end;
procedure TFMXLoadingIndicator.SetKind(const Value: TLoadingIndicatorKind);
begin
if FKind <> Value then
begin
FKind := Value;
case Kind of
LoadingArcs:
FDrawProc := DrawLoadingArcs;
LoadingDoubleBounce:
FDrawProc := DrawLoadingDoubleBounce;
LoadingFlipPlane:
FDrawProc := DrawLoadingFlipPlane;
LoadingPulse:
FDrawProc := DrawLoadingPulse;
LoadingArcsRing:
FDrawProc := DrawLoadingArcsRing;
LoadingRing:
FDrawProc := DrawLoadingRing;
LoadingThreeDots:
FDrawProc := DrawLodingThreeDots;
LoadingWave:
FDrawProc := DrawLoadingWave;
end;
FAnimation.Duration := INDICATOR_DURING[Kind];
FAnimation.AutoReverse := INDICATOR_AUTOREVERSE[Kind];
if not (csLoading in ComponentState) then
begin
ConfirmSize;
Repaint;
end;
end;
end;
procedure TFMXLoadingIndicator.Start;
begin
CreateAnimation;
FAnimation.Start;
end;
procedure TFMXLoadingIndicator.ConfirmSize;
var
MinSize: TSizeF;
begin
MinSize := INDICATOR_MINSIZE[Kind];
if Width < MinSize.Width then
Width := MinSize.Width;
if Height < MinSize.Height then
Height := MinSize.Height;
end;
procedure TFMXLoadingIndicator.CreateAnimation;
begin
if not Assigned(FAnimation) then
begin
FAnimation := TMyAnimation.Create(Self);
FAnimation.Stored := False;
FAnimation.Loop := True;
FAnimation.OnProcess := OnAnimation;
AddObject(FAnimation);
end;
end;
destructor TFMXLoadingIndicator.Destroy;
begin
FBrush.Free;
inherited;
end;
procedure TFMXLoadingIndicator.DrawLoadingArcs;
var
Arc: TPathData;
P: TPointF;
R: Single;
T, A: Single;
begin
T := FAnimation.NormalizedTime;
A := InterpolateSingle(0, 360, T);
P := PointF(Width / 2, Height / 2);
R := Min(P.X, P.Y);
Arc := TPathData.Create;
try
Arc.AddArc(P, PointF(R, R), A, 270);
Arc.AddArc(P, PointF(R - 5, R - 5), A + 270, -270);
Arc.ClosePath;
Canvas.FillPath(Arc, 1, FBrush);
R := R - 5;
A := 360 - A;
Arc.Clear;
Arc.AddArc(P, PointF(R, R), A + 45, -210);
Arc.AddArc(P, PointF(R - 5, R - 5), A + 45 - 210, 210);
Arc.ClosePath;
Canvas.FillPath(Arc, 0.3, FBrush);
finally
Arc.Free;
end;
end;
procedure TFMXLoadingIndicator.DrawLoadingArcsRing;
var
P: TPointF;
R: Single;
StartAngle: Single;
path: TPathData;
I: Integer;
T: Single;
O: Single;
begin
T := FAnimation.NormalizedTime;
P := PointF(Width / 2, Height / 2);
R := Min(P.X, P.Y);
StartAngle := -15;
path := TPathData.Create;
try
for I := 0 to 7 do
begin
if T < 0.125 then
O := InterpolateSingle(1, 0.3, T * 8)
else
O := 0.3;
T := T - 0.125;
if T < 0 then
T := T + 1;
path.Clear;
path.AddArc(P, PointF(R, R), StartAngle, 30);
path.AddArc(P, PointF(R - 5, R - 5), StartAngle + 30, -30);
path.ClosePath;
Canvas.FillPath(path, O, FBrush);
StartAngle := StartAngle + 45;
end;
finally
path.Free;
end;
end;
procedure TFMXLoadingIndicator.DrawLoadingDoubleBounce;
var
T, S: Single;
P: TPointF;
R, R1, R2: Single;
DR: TRectF;
begin
T := FAnimation.NormalizedTime;
S := InterpolateSingle(1, 0, T);
P := PointF(Width / 2, Height / 2);
R := Min(P.X, P.Y);
R1 := R * S;
R2 := R * (1 - S);
DR := RectF(P.X - R1, P.Y - R1, P.X + R1, P.Y + R1);
Canvas.FillEllipse(DR, 0.3, FBrush);
DR := RectF(P.X - R2, P.Y - R2, P.X + R2, P.Y + R2);
Canvas.FillEllipse(DR, 0.3, FBrush);
end;
procedure TFMXLoadingIndicator.DrawLoadingFlipPlane;
function CalcScale(T: Single): Single;
begin
if T < 0.25 then
Result := InterpolateSingle(1, 0, T / 0.25)
else if T < 0.5 then
Result := InterpolateSingle(0, 1, (T - 0.25) / 0.25)
else
Result := 1;
end;
var
R: TRectF;
SX, SY: Single;
T: Single;
begin
T := FAnimation.NormalizedTime;
SY := CalcScale(T);
T := T - 0.5;
if T < 0 then
T := T + 1;
SX := CalcScale(T);
R := RectF(0, 0, Width * SX, Height * SY);
R := R.CenterAt(RectF(0, 0, Width, Height));
Canvas.FillRect(R, 0, 0, AllCorners, 1, FBrush);
end;
procedure TFMXLoadingIndicator.DrawLoadingPulse;
var
T, S: Single;
P: TPointF;
R: Single;
DR: TRectF;
begin
T := FAnimation.NormalizedTime;
S := InterpolateSingle(0, 1, T);
P := PointF(Width / 2, Height / 2);
R := Min(P.X, P.Y) * S;
DR := RectF(P.X - R, P.Y - R, P.X + R, P.Y + R);
Canvas.FillEllipse(DR, 1 - S, FBrush);
end;
procedure TFMXLoadingIndicator.DrawLoadingRing;
var
T: Single;
I: Integer;
S: Single;
R, DR: TRectF;
begin
T := FAnimation.NormalizedTime;
for I := 0 to 7 do
begin
if T < 0.4 then
S := InterpolateSingle(0, 1, T / 0.4)
else if T < 0.8 then
S := InterpolateSingle(1, 0, (T - 0.4) / 0.4)
else
S := 0;
R := GetCellRect(Width / 5, Height / 5, RING_CELLS[I]);
DR := RectF(0, 0, RING_CIRCLE_SIZE * S, RING_CIRCLE_SIZE * S);
DR := DR.CenterAt(R);
Canvas.FillEllipse(DR, 1, FBrush);
T := T - 0.125;
if T < 0 then
T := T + 1;
end;
end;
procedure TFMXLoadingIndicator.DrawLoadingWave;
var
T: Single;
I: Integer;
S: Single;
R: TRectF;
W, H, Space: Single;
begin
T := FAnimation.NormalizedTime;
W := (Width - 20) / 5;
H := Height;
Space := 0;
for I := 0 to 4 do
begin
if T < 0.1 then
S := InterpolateSingle(1/1.6, 1, T / 0.1)
else if (T < 0.15) then
S := 1.6
else if T < 0.35 then
S := InterpolateSingle(1, 1/1.6, (T - 0.15) / 0.2)
else
S := 1/1.6;
T := T - 0.05;
if T < 0 then
T := T + 1;
R := RectF(0, 0, W, H * S);
R.Offset(I * W + Space, (Height - R.Height) / 2);
Space := Space + 5;
Canvas.FillRect(R, 0, 0, AllCorners, 1, FBrush);
end;
end;
procedure TFMXLoadingIndicator.DrawLodingThreeDots;
var
T, S: Single;
I: Integer;
R, DR: TRectF;
W, H, Space, CR: Single;
begin
T := FAnimation.CurrentTime;
W := (Width - 10) / 3;
H := Height;
Space := 0;
for I := 0 to 2 do
begin
if T < 0.5 then
S := InterpolateSingle(0, 1, T / 0.5)
else if T < 0.6 then
S := 1
else if T < 1.1 then
S := InterpolateSingle(1, 0, (T - 0.6) / 0.5)
else
S := 0;
T := T - 0.25;
if T < 0 then
T := T + 1.9;
R := RectF(0, 0, W, H);
R.Offset(I * W + Space, 0);
Space := Space + 5;
CR := Min(W, H) * S;
DR := RectF(0, 0, CR, CR);
DR := DR.CenterAt(R);
Canvas.FillEllipse(DR, 1, FBrush);
end;
end;
function TFMXLoadingIndicator.GetCellRect(CellWidth, CellHeight: Single;
const Cell: TCell): TRectF;
var
R: TRectF;
begin
R.Left := CellWidth * Cell.Col;
R.Top := CellHeight * Cell.Row;
R.Right := CellWidth * (Cell.Col + Cell.ColSpan);
R.Bottom := CellHeight * (Cell.Row + Cell.RowSpan);
Result := RectF(0, 0, CellWidth, CellHeight);
RectCenter(Result, R);
end;
function TFMXLoadingIndicator.GetColor: TAlphaColor;
begin
Result := FBrush.Color
end;
{ TMyAnimation }
procedure TMyAnimation.ProcessAnimation;
begin
end;
end.
|
unit uRelatAlteracoesAssinante;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, JvExStdCtrls, JvButton,
JvCtrls, JvComponentBase, JvEnterTab, Vcl.Mask, JvExMask, JvToolEdit;
type
TfrmRelatAlteracoesAssinante = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
edtDataFim: TJvDateEdit;
edtDataIni: TJvDateEdit;
JvEnterAsTab: TJvEnterAsTab;
btnOk: TJvImgBtn;
btnCancelar: TJvImgBtn;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
function GetDataInicial: TDate;
function GetDataFinal: TDate;
public
{ Public declarations }
property DataInicial: TDate read GetDataInicial;
property DataFinal: TDate read GetDataFinal;
end;
var
frmRelatAlteracoesAssinante: TfrmRelatAlteracoesAssinante;
implementation
{$R *.dfm}
uses uPrincipal, uDadosGlobal;
procedure TfrmRelatAlteracoesAssinante.FormCreate(Sender: TObject);
begin
edtDataFim.Date := dmDadosGlobal.GetDataHoraBanco;
edtDataIni.Date := IncMonth(dmDadosGlobal.GetDataHoraBanco, -12);
end;
function TfrmRelatAlteracoesAssinante.GetDataFinal: TDate;
begin
Result := edtDataFim.Date;
end;
function TfrmRelatAlteracoesAssinante.GetDataInicial: TDate;
begin
Result := edtDataIni.Date;
end;
end.
|
unit UnitZarplataConsts;
interface
resourcestring
//Dpr-source
Ini_FileName = 'Config.ini';
OpenConfigError_Text = 'Не знайдено файл з настрйками';
OpenDBError_Text = 'Неможливо встановити'+#13+'підключення до бази';
Application_Caption = 'Зарплата';
DB_Connection_Text = 'Підключення до бази даних: ';
WriteParameters_Text = 'Читання параметрів';
//Сплеш форма
TZSplash_Form_Label_Firm_Caption = 'Підприємство';
TZSplash_Form_Label_System_Caption = 'Автоматизована'+#13+'підсистема розрахунка'+#13+'заробітної плати';
TZSplash_Form_Label_Rights_Caption = 'Права на даний продукт захищені українським та міжнародним законодавством. Усі права належать ДонНУ.';
TZSplash_Form_Label_Version_Caption = 'Версія: ';
//Общее
InsertBtn_Caption = 'Додати';
UpdateBtn_Caption = 'Редагувати';
DeleteBtn_Caption = 'Вилучити';
SelectBtn_Caption = 'Обрати';
SelectAllBtn_Caption = 'Обрати з підлеглими';
RefreshBtn_Caption = 'Поновити';
ExitBtn_Caption = 'Вийти';
SpravBtn_Caption = 'Довідник';
UpdateAllBtn_Caption = 'Редагувати';
LocateBtn_Caption = 'Шукати';
LocateNextBtn_Caption = ' Шукати далі';
YesBtn_Caption = 'Прийняти';
CancelBtn_Caption = 'Відмінити';
Error_Caption = 'Помилка';
ButtonsControlBar_caption = 'Дії';
//Главное меню программы
FZMainMenu_Caption = 'Підсистема розрахунку заробітної плати';
//----------------------------------------------------------------------------------------------------------
FZMainMenu_AboutSubMainMenu_Caption = 'Довідка';
//----------------------------------------------------------------------------------------------------------
FZMainMenu_ServiceSubMainMenu_Caption = 'Сервіс';
FZMainMenu_SystemPreverencesPunktMainMenu_Caption = 'Властивості';
FZMainMenu_TaxesNetsPunktMainMenu_Caption = 'Податки';
FZMainMenu_ReturnPrevPeriodPunktMainMenu_Caption = 'Відкат на попередній період';
//----------------------------------------------------------------------------------------------------------
FZMainMenu_SpSubMainMenu_Caption = 'Довідники';
FZMainMenu_CalendarSpPunktMainMenu_Caption = 'Календар';
FZMainMenu_WorkerCategorySpPunktMainMenu_Caption = 'Категорії працівників';
FZMainMenu_SmetaSpPunktMainMenu_Caption = 'Смети';
FZMainMenu_VoSpPunktMainMenu_Caption = 'Види оплати';
FZMainMenu_DivisionSpPunktMainMenu_Caption = 'Підрозділи';
FZMainMenu_PrivilegeSpPunktMainMenu_Caption = 'Льготи';
FZMainMenu_VOutSpPunktMainMenu_Caption = 'Види виплат';
FZMainMenu_VoplSpravPunktMainMenu_Caption = 'Види операцій';
FZMainMenu_ViewVoPunktMainMenu_Caption = 'Відображення';
FZMainMenu_PeoplePunktMainMenu_Caption = 'Фізичні особи';
//----------------------------------------------------------------------------------------------------------
FZMainMenu_DataSubMainMenu_Caption = 'Данні';
FZMainMenu_WorkerDtPunktMainMenu_Caption = 'Співробітників';
FZMainMenu_PeoplePropPunktMainMenu_Caption = 'Властивості осіб';
FZMainMenu_StudentDtPunktMainMenu_Caption = 'Студентів';
FZMainMenu_CurrentDtPunktMainMenu_Caption = 'Поточні операції';
FZMainMenu_PeoplePrivPunktMainMenu_Caption = 'Що користуються льготами';
FZMainMenu_RemontPunktMainMenu_Caption = 'Ремонтні роботи';
FZMainMenu_DopMoneyPunktMainMenu_Caption = 'Додаткових нарахувань';
FZMAinMenu_AlimentPunktMainMenu_Caption = 'Що сплачують аліменти';
FZMAinMenu_InvalidPunktMainMenu_Caption = 'Перелік інвалідів';
FZMainMenu_AlwaysUderzhPunktMainMenu_Caption = 'Постійних утримань';
FZMainMenu_SsudaPunktMainMenu_Caption = 'Що брали ссуду';
FZMainMenu_NonSpisokPunktMainMenu_Caption = 'Склад поза списком';
//----------------------------------------------------------------------------------------------------------
FZMainMenu_InformationSubMainMenu_Caption = 'Інформація';
FZMainMenu_PrevPeriodDataPunktMainMenu_Caption = 'Данні минулих періодів';
FZMainMenu_LostDataPunktMainMenu_Caption = 'Данні звільнень';
FZMainMenu_UchetVedSubInformSubMainMenu_Caption = 'Дані відомостей';
FZMainMenu_VedCurrentMonthPunktMainMenu_Caption = 'Відомості періода';
FZMainMenu_ReestrVedPunktMainMenu_Caption = 'Реєстри';
FZMainMenu_FilterVedPunktMainMenu_Caption = 'Пошук';
//----------------------------------------------------------------------------------------------------------
FZMainMenu_WorkSubMainMenu_Caption = 'Робота';
FZMainMenu_AvansPunktMainMenu_Caption = 'Розрахунок авансу';
FZMainMenu_PromViplatiPunktMainMenu_Caption = 'Поточні операції';
FZMainMenu_RaschetPunktMainMenu_Caption = 'Терміновий розрахунок';
FZMainMenu_ZarplataPunktMainMenu_Caption = 'Розрахунок заробітної плати';
FZMainMenu_StipPunktMainMenu_Caption = 'Розрахунок стипендіальних виплат';
FZMainMenu_VedRaschetPunktMainMenu_Caption = 'Відомості розрахунку';
FZMainMenu_DataRaschetPunktMainMenu_Caption = 'Данні розрахунку';
FZMainMenu_ReCountPunktMainMenu_Caption = 'Перерахунок';
FZMainMenu_ReCountDataPunktMainMenu_Caption = 'Перегляд перерахунка';
FZMainMenu_OperationEndPunktMainMenu_Caption = 'Завершення операції';
//----------------------------------------------------------------------------------------------------------
FZMainMenu_PrintSubMainMenu_Caption = 'Друк';
//----------------------------------------------------------------------------------------------------------
FZMainMenu_SpravSubMainMenu_Caption = 'Довідки';
FZMainMenu_SvodPunktMainMenu_Caption = 'Звіти';
FZMainMenu_SprSubsPunktMainMenu_Caption = 'Про доходи(субсидія)';
//----------------------------------------------------------------------------------------------------------
FZMainMenu_WindowSubMainMenu_Caption = 'Вікна';
FZMainMenu_CascadePunktMainMenu_Caption = 'Каскадом';
FZMainMenu_TileVerPunktMainMenu_Caption = 'Вертикально';
FZMainMenu_TileGorPunktMainMenu_Caption = 'Горизонтально';
FZMainMenu_MinAllPunktMainMenu_Caption = 'Мінімізувати';
FZMainMenu_NormAllPunktMainMenu_Caption = 'Нормалізувати';
FZMainMenu_CloseWindAllPunktMainMenu_Caption = 'Закрити';
//----------------------------------------------------------------------------------------------------------
FZMainMenu_ExitPunktMainMenu_Caption = 'Вихід';
FZMainMenu_ExitAnswer_Caption = 'Вихід';
FZMainMenu_ExitAnswer_Text = 'Ви дійсно бажаєте'+#13+'покинути систему?';
//SotrListView
Form_SotrList_Caption ='Працівниіки(інформація)';
TnColumnCaption ='Таб. номер';
FamiliaColumnCaption ='Фамілія';
ImyaColumnCaption ='Імя';
OtchestvoColumnCaption ='По батькові';
SotrDetailsBtnCaption ='Інформація';
//SotrFilterForm
Form_SotrFilterCaption ='Параметри відбіра';
Tn_Label_Caption ='Табельний номер:';
Familia_Label_Caption ='Фамілія:';
Ink_Label_Caption ='Індетифікаційний номер:';
Department_Label_Caption ='Підрозділ';
//FSp_People_Prop_Control
FSp_People_Prop_Control_Caption_Insert = 'Додавання признака';
FSp_People_Prop_Control_Caption_Update = 'Редагування признака';
FSp_People_Prop_Control_Caption_Delete = 'Вилучення признака';
FSp_People_Prop_Control_IdentificationBox_Caption = 'Головні данні';
FSp_People_Prop_Control_PeriodBox_Caption = 'Період дії';
FSp_People_Prop_Control_LabelPeople_Caption = 'Фізична особа:';
FSp_People_Prop_Control_PropLabel_Caption = 'Признак:';
FSp_People_Prop_Control_DateBegLabel_Caption = 'Початок';
FSp_People_Prop_Control_DateEndLabel_Caption = 'Закінчення';
//******************************************************************************
//******************************************************************************
//******************************************************************************
//******************************************************************************
//******************************************************************************
//******************************************************************************
//******************************************************************************
ZAccess_UserLabel_Caption = 'Користувач';
ZAccess_UserLogin_Caption = 'Пароль';
ZAccess_Caption = 'Вхід';
ZAccess_YesBtn_Caption = 'Далі';
ZAccess_CancelBtn_Caption = 'Вийти';
ZAccess_ErrorInSystemAccess_Caption = 'Помилка у системі безпеки!';
//******************************************************************************
//******************************************************************************
//******************************************************************************
//******************************************************************************
//******************************************************************************
//******************************************************************************
//******************************************************************************
//SotrDetailsForm
SotrDetailsFormCaption ='Детальна інформація по співробітнику';
PeriodBegColumnCaption ='З';
PeriodEndColumnCaption ='По';
PostColumnCaption ='Посада';
PaymentColumnCaption ='Тариф/Оклад';
GeneralPageCaption ='Загальна інформація';
DepartmentLabelCaption ='Підрозділ:';
OrderNumCaption ='Наказ номер:';
ManMovingGridHeaderCaption ='Посадові переміщення';
ManBonusGridHeaderCaption ='Надбавки та доплати';
BonusNameCaption ='Назва';
BonusPaymentCaption ='Сумма/Процент';
BonusBegCaption ='З';
BonusEndCaption ='По';
BonusOrderNumCaption ='Наказ №';
ManBonusPageCaption ='Надбавки';
FilterButtonCaption ='Відбір';
//Грид с больничными
ManHospitalPageCaption ='Листи непрацездатності';
HospDateBegCaption ='З';
HospDateEndCaption ='По';
HospSeriaCaption ='Серія';
HospNumCaption ='Номер';
HospPercentCaption ='Процент';
//Грид с отпусками
ManHolidayPageCaption ='Відпустки';
ManHolNameCaption ='Назва';
ManHolPeriodBegCaption ='Період з';
ManHolPeriodEndCaption ='Період по';
ManHolDateBegCaption ='З';
ManHolDateEndCaption ='По';
implementation
end.
|
//Algorithme Le garage automobile
//But:Algorithme qui affiche des garages et leurs véhicules, véhicule le plus vieux etc.
//Entree: Nom garage, adresse ,modele...
//Sortie: affiche des garages et leurs véhicules, véhicule le plus vieux etc.
Programme Garage
Type
adre=Enregistrement
coordonnee:chaîne
numTel:entier
email:chaîne
FinEnregistrement
Type
garage=Enregistrement
nom:chaîne
adresse:adre
nbrVoi:entier
FinEnregistrement
Type
voiture=Enregistrement
marque:chaîne
modèle:chaîne
energie:chaîne
PuiFis:entier
PuiDYN:entier
couleur:chaîne
option:chaîne
anneeMod:entier
prixMod:entier
coteArgus:entier
dateCircu:entier
age:entier
immatri:chaîne
FinEnregistrement
Type
TGa=Tableau[1..2] de garage
//BUT:entrer le nom et toutes les coordonnées des garages.
//ENTREE:Des chaîne de charactère et un entier dans un tableau de garage
//SORTIE:un tableau de garage, un entier qui donne le nombre de voiture au total.
Procedure CreerGarage(var TabGarage:TGa ; var nbrVoiMax:entier)
var
i:entier
debut
nbrVoiMax<--0
Pour i De 1 à 2 Faire
Ecrire("Veuillez entrer le nom du garage n°"&i&" :")
Lire(TabGarage[i].nom)
Ecrire("Veuillez entrer le numero de la rue, nom de la rue, code postal, ville et pays:")
Lire(TabGarage[i].adresse.coordonnee)
Ecrire("Veuillez entrer le numero de téléphone du garage:")
Lire(TabGarage[i].adresse.numTel)
Ecrire("Veuillez entrer votre adresse email:")
Lire(TabGarage[i].adressse.email)
Ecrire("Veuillez entrer le nombre de voiture que possède le garage:")
Lire(TabGarage[i].nbrVoi)
//Variable qui récupère le nombre de voiture au totale dans les deux garages:
nbrVoiMax<--nbrVoiMax+TabGarage[i].nbrVoi
FinPour
fin;
Procedure CreerVoiture(var nbrVoiMax:entier ; var TabVoi:Tableau[1..nbrVoiMax] de voiture)
var
i:entier
debut
Pour i De 1 A nbrVoiMax Faire
Ecrire("Veuillez entrer la marque de la voiture n°"&i&":")
Lire(TabVoi[i].marque)
Ecrire("Veuillez entrer le modèle de la voiture n°"&i&":")*
Lire(TabVoi[i].modèle)
var
TabVoi:Tableau[1..nbrVoiMax] de voiture
TabGarage:TGa
nbrVoiMax:entier
//Programme Principal:
DEBUT
CreerGarage(TabGarage,nbrVoiMax)
FIN.
CE QUI EST FAIT:
-tout les types nécessaire
-procedure de création des garages
A FAIRE:
-Procedure de création des voitures
-Procedure de répartition des voitures
-Procedure d'affichage des garages et de leurs voitures
-Procedure d'affichage de la voiture la plus ancienne
-Procedure d'affichage de la moyenne des valeurs des voitures de chaque garage
|
unit frmEditCarNoByFNCard;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, Buttons, ExtCtrls, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, DBClient, StdCtrls, StrUtils, frmBase,
Grids, DBGrids;
type
TEditCarNoByFNCardForm = class(TBaseForm)
cxGEditCarNO: TcxGrid;
cxTVEditCarNO: TcxGridDBTableView;
cxLEditCarNO: TcxGridLevel;
PnlBottom: TPanel;
Panel2: TPanel;
SBtnExit: TSpeedButton;
EdtNewCarNo: TEdit;
Label2: TLabel;
CDSEditCarNO: TClientDataSet;
DSEditCarNOData: TDataSource;
Label1: TLabel;
EdtFNCard: TEdit;
ButQuery: TButton;
BtnEdit: TButton;
BtnSave: TButton;
lbl1: TLabel;
edt1: TEdit;
procedure SBtnExitClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ButQueryClick(Sender: TObject);
procedure BtnEditClick(Sender: TObject);
procedure BtnSaveClick(Sender: TObject);
procedure cxTVEditCarNODataControllerFilterBeforeChange(
Sender: TcxDBDataFilterCriteria; ADataSet: TDataSet;
const AFilterText: String);
procedure EdtFNCardChange(Sender: TObject);
private
{ Private declarations }
procedure MyFormKeyPress(Sender: TObject; var Key: Char);
procedure init; //初始化
procedure Query; //查询方法
function GetEditCarNoDataByFnCard(aFNCard : String) : Boolean; //根据后整卡号查询数据
procedure ControlButton(isAction : Boolean);
function EditNewLocation(aCDS : TClientDataSet; aNewCarNo, aLocateField : String) : Boolean;
function EditNewCarNO(aCDS : TClientDataSet; aNewCarNo, aLocateField : String) : Boolean; // Added by WuDev 2016/9/8 16:06:21 增加车牌号修改
function GetSaveString(aCDS : TClientDataSet) : String;
procedure save;
public
{ Public declarations }
end;
var
EditCarNoByFNCardForm: TEditCarNoByFNCardForm;
implementation
uses uFNMResource, ServerDllPub, uShowMessage, uGridDecorator, uLogin;
{$R *.dfm}
{ TEditCarNoByFNCardForm }
procedure TEditCarNoByFNCardForm.init;
begin
{SButQuery.Glyph.LoadFromResourceName(HInstance, RES_REFRESH);
SBtnSave.Glyph.LoadFromResourceName(HInstance, RES_SAVE);
SBtnExit.Glyph.LoadFromResourceName(HInstance, RES_EXIT);
SBtnEdit.Glyph.LoadFromResourceName(HInstance, RES_EDIT);}
ControlButton(False);
Self.OnKeyPress := MyFormKeyPress;
EdtFNCard.OnKeyPress := MyFormKeyPress;
EdtNewCarNo.OnKeyPress := MyFormKeyPress;
EdtFNCard.SetFocus;
end;
procedure TEditCarNoByFNCardForm.SBtnExitClick(Sender: TObject);
begin
Close;
end;
procedure TEditCarNoByFNCardForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TEditCarNoByFNCardForm.FormDestroy(Sender: TObject);
begin
EditCarNoByFNCardForm := nil;
end;
procedure TEditCarNoByFNCardForm.FormShow(Sender: TObject);
begin
init;
end;
procedure TEditCarNoByFNCardForm.Query;
var
i : Integer;
begin
if EdtFNCard.Text = '' then
Exit;
if not GetEditCarNoDataByFnCard(EdtFNCard.Text) then
begin
ControlButton(False);
TMsgDialog.ShowMsgDialog('没有待修改车位的坯布数据', 2);
Exit;
end;
//绑定cxGrid
GridDecorator.BindCxViewWithDataSource(cxTVEditCarNO, DSEditCarNOData);
for i := 0 to cxTVEditCarNO.ColumnCount - 1 do
cxTVEditCarNO.Columns[i].Options.Editing := False;
ControlButton(True);
CDSEditCarNO.IndexFieldNames := 'Car_No;FN_Card';
end;
function TEditCarNoByFNCardForm.GetEditCarNoDataByFnCard(aFNCard: String): Boolean;
var
sql, sErrorMsg : WideString;
vData : OleVariant;
begin
Result := False;
try
ShowMsg('正在获取数据稍等!', crHourGlass);
sql := QuotedStr('GetEditCarNODataByFnCard') + ',' + QuotedStr(aFNCard); // + '|' + Login.CurrentDepartment
FNMServerObj.GetQueryData(vData,'GiFullCarFabricsData', sql, sErrorMsg);
if Trim(sErrorMsg) <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;//if
CDSEditCarNO.Data := vData;
Result := ((CDSEditCarNO.Active) and (CDSEditCarNO.RecordCount > 0));
finally
ShowMsg('', crDefault);
end;//finally
end;
procedure TEditCarNoByFNCardForm.ControlButton(isAction : Boolean);
begin
BtnEdit.Enabled := isAction;
BtnSave.Enabled := isAction;
end;
function TEditCarNoByFNCardForm.EditNewLocation(aCDS : TClientDataSet; aNewCarNo, aLocateField : String) : Boolean;
var
locateValue : string;
begin
Result := False;
if (aCDS.Active) and (aCDS.RecordCount > 0) and (aNewCarNo <> '') then
begin
locateValue := aCDS.FieldByName(aLocateField).AsString;
try
aCDS.DisableControls;
aCDS.First;
while not aCDS.Eof do
begin
aCDS.Edit;
aCDS.FieldByName('NewLocation').AsString := aNewCarNo;
aCDS.Post;
aCDS.Next;
end;//while
finally
aCDS.EnableControls;
aCDS.Locate(aLocateField, locateValue, []);
end;//finally
end;//if
end;
// Added by WuDev 2016/9/8 16:05:24 增加车牌号修改
function TEditCarNoByFNCardForm.EditNewCarNO(aCDS : TClientDataSet; aNewCarNo, aLocateField : String) : Boolean;
var
locateValue,IndexFieldNames : string;
begin
Result := False;
IndexFieldNames:= aCDS.IndexFieldNames;
aCDS.IndexFieldNames:= '';
if (aCDS.Active) and (aCDS.RecordCount > 0) and (aNewCarNo <> '') then
begin
locateValue := aCDS.FieldByName(aLocateField).AsString;
try
aCDS.DisableControls;
aCDS.First;
while not aCDS.Eof do
begin
aCDS.Edit;
aCDS.FieldByName('Car_No').AsString := aNewCarNo;
aCDS.Post;
aCDS.Next;
end;//while
finally
aCDS.IndexFieldNames:= IndexFieldNames;
aCDS.EnableControls;
aCDS.Locate(aLocateField, locateValue, []);
end;//finally
end;//if
end;
procedure TEditCarNoByFNCardForm.MyFormKeyPress(Sender: TObject; var Key: Char);
begin
if Key <> #13 then
begin
if TWinControl(Sender).Name = 'EdtNewCarNo' then
TEdit(Sender).CharCase := ecUpperCase;
end
else
begin
if TWinControl(Sender).Name = 'EdtFNCard' then
begin
if trim(EdtFNCard.Text) <> '' then
begin
ButQuery.OnClick(Sender);
EdtNewCarNo.SetFocus;
EdtNewCarNo.SelectAll;
end;//if
end
else if TWinControl(Sender).Name = 'EdtNewCarNo' then
begin
if (trim(TEdit(Sender).Text) <> '') and (BtnSave.Enabled) then //(BtnEdit.Enabled) and
if (CDSEditCarNO.Active) then
begin
//BtnEdit.OnClick(Sender);
//BtnSave.SetFocus;
BtnSave.OnClick(Sender);
end;//if
end;//else if
end;//else
end;
function TEditCarNoByFNCardForm.GetSaveString(aCDS: TClientDataSet): String;
var
fnCard, newLocation , newCarNo: string; // Added by WuDev 2016/9/8 16:01:53 增加车牌号修改
begin
Result := '';
try
if(aCDS.Active) and (aCDS.RecordCount > 0) then
begin
aCDS.DisableControls;
aCDS.First;
while not aCDS.Eof do
begin
if fnCard <> aCDS.FieldByName('FN_Card').AsString then
begin
fnCard := '';
newLocation := '';
newCarNo := ''; // Added by WuDev 2016/9/8 16:01:53 增加车牌号修改
fnCard := aCDS.FieldByName('FN_Card').AsString;
newLocation := aCDS.FieldByName('NewLocation').AsString;
newCarNo := aCDS.FieldByName('Car_No').AsString;
if newLocation = '' then
newLocation := aCDS.FieldByName('Car_No').AsString;
end;//if
aCDS.Next;
end;//while
Result := fnCard + '|' + newLocation + '|' + login.LoginID + '|' +newCarNo;
end;//if
finally
aCDS.EnableControls;
end;//finally
end;
procedure TEditCarNoByFNCardForm.save;
var
updateList : string;
sql, sErrorMsg : WideString;
vData : OleVariant;
cds : TClientDataSet;
begin
if Trim(EdtNewCarNo.Text) = '' then
Exit;
{if MessageDlg('是否执行保存操作?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then
Exit;
}
EditNewCarNO(CDSEditCarNO,edt1.text,'Fabric_NO');
EditNewLocation(CDSEditCarNO, EdtNewCarNo.Text, 'Fabric_NO');
if CDSEditCarNO.State in [dsEdit, dsInsert] then
CDSEditCarNO.Post;
if CDSEditCarNO.ChangeCount > 0 then
begin
cds := TClientDataSet.Create(nil);
try
ShowMsg('正在保存数据稍等!', crHourGlass);
updateList := GetSaveString(CDSEditCarNO);
sql := QuotedStr('UpdateEditCarNODataByFnCard') + ',' + QuotedStr(updateList);
FNMServerObj.GetQueryData(vData, 'GiFullCarFabricsData', sql, sErrorMsg);
if Trim(sErrorMsg) <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;//if
CDSEditCarNO.MergeChangeLog;
cds.Data := vData;
if cds.Active then
begin
if cds.FieldByName('IsUpdateJobTrace').AsBoolean then
TMsgDialog.ShowMsgDialog('数据保存成功', mtInformation)
else
TMsgDialog.ShowMsgDialog('数据保存成功, 但该卡未出布, 未能执行下机操作', mtWarning);
EdtNewCarNo.Text := '';
end;//if
EdtFNCard.SetFocus;
EdtFNCard.SelectAll;
finally
if Assigned(cds) then
FreeAndNil(cds);
ShowMsg('', crDefault);
end;//finally
end;//if
end;
procedure TEditCarNoByFNCardForm.ButQueryClick(Sender: TObject);
begin
inherited;
Query;
end;
procedure TEditCarNoByFNCardForm.BtnEditClick(Sender: TObject);
begin
inherited;
EditNewLocation(CDSEditCarNO, EdtNewCarNo.Text, 'Fabric_NO');
end;
procedure TEditCarNoByFNCardForm.BtnSaveClick(Sender: TObject);
begin
inherited;
save;
end;
procedure TEditCarNoByFNCardForm.cxTVEditCarNODataControllerFilterBeforeChange(
Sender: TcxDBDataFilterCriteria; ADataSet: TDataSet;
const AFilterText: String);
begin
inherited;
if AFilterText <> '' then
begin
if Pos('= TRUE', UpperCase(AFilterText)) > 0 then
ADataSet.Filter := Stringreplace(UpperCase(AFilterText), '= TRUE', '<> FALSE', [rfReplaceAll])
else
ADataSet.Filter := AFilterText;
ADataSet.Filtered := True;
ADataSet.First;
end
else
begin
ADataSet.Filtered := False;
ADataSet.Filter := '';
end;//else}
end;
procedure TEditCarNoByFNCardForm.EdtFNCardChange(Sender: TObject);
var
key : Char;
begin
inherited;
if Length(Trim(TEdit(Sender).Text)) >= 9 then
begin
key := #13;
MyFormKeyPress(Sender, key);
end;//if
end;
end.
|
unit SetCCDReadoutUnit;
// ---------------------------------------
// Enter coordinates of CCD readout region
// ---------------------------------------
// 20.02.07 Limits of range now set correctly
// 22.05.13 Cancel now closes form rather than hides (avoiding form error)
// 16.09.15 .. JD Form position/size saved by MainFrm.SaveFormPosition() when form closed
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, RangeEdit;
type
TSetCCDReadoutFrm = class(TForm)
AreaGrp: TGroupBox;
edXRange: TRangeEdit;
Label1: TLabel;
Label2: TLabel;
edYRange: TRangeEdit;
bOK: TButton;
bCancel: TButton;
procedure FormShow(Sender: TObject);
procedure bOKClick(Sender: TObject);
procedure bCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
ImagingRestartRequired : Boolean ;
public
{ Public declarations }
end;
var
SetCCDReadoutFrm: TSetCCDReadoutFrm;
implementation
{$R *.dfm}
uses MainUnit;
procedure TSetCCDReadoutFrm.FormShow(Sender: TObject);
// --------------------------------------
// Initialisations when form is displayed
// --------------------------------------
begin
edXRange.LoValue := MainFrm.CCDRegion.Left ;
edXRange.HiValue := MainFrm.CCDRegion.Right ;
edYRange.LoValue := MainFrm.CCDRegion.Top ;
edYRange.HiValue := MainFrm.CCDRegion.Bottom ;
ClientWidth := AreaGrp.Left + AreaGrp.Width + 5 ;
ClientHeight := bOK.Top + bOK.Height + 5 ;
if not MainFrm.bLiveImage.Enabled then begin
MainFrm.bStopImage.Click ;
ImagingRestartRequired := True ;
end
else ImagingRestartRequired := False ;
end;
procedure TSetCCDReadoutFrm.bOKClick(Sender: TObject);
// -----------------
// OK button pressed
// -----------------
begin
if not MainFrm.bLiveImage.Enabled then MainFrm.StopCamera ;
MainFrm.CCDRegion.Left := edXRange.LoValue ;
MainFrm.CCDRegion.Right := edXRange.HiValue ;
MainFrm.CCDRegion.Top := edYRange.LoValue ;
if MainFrm.LiveImagingInProgress then MainFrm.CCDRegion.Top := 0.0 ;
MainFrm.CCDRegion.Bottom := edYRange.HiValue ;
if ImagingRestartRequired then MainFrm.bLiveImage.Click ;
close ;
end;
procedure TSetCCDReadoutFrm.bCancelClick(Sender: TObject);
// ---------------------
// Cancel button pressed
// ---------------------
begin
Close ;
end;
procedure TSetCCDReadoutFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
// ---------------------------
// Tidy up when form is closed
// ---------------------------
begin
Action := caFree ;
MainFrm.bEnterCCDArea.Enabled := True ;
end;
end.
|
unit fos_stats_control_interface;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(§LIC_END)
}
{$mode objfpc}{$H+}
{$modeswitch nestedprocvars}
{$interfaces corba}
//{$codepage UTF8}
interface
uses
Classes, SysUtils,FRE_DB_INTERFACE,FOS_TOOL_INTERFACES,FRE_PROCESS,FRE_SYSTEM,fre_base_parser;
const cDEBUG_ZPOOL_NAME = 'zones';
var c_GET_ZFS_DATA_ONCE : string = 'zfs list -Hp -o name,referenced,available,used '+cDEBUG_ZPOOL_NAME;
const
cIOSTATFILEONCE = 'sh -c /zones/firmos/onceiostat.sh';
c_GET_CPU_DATA = 'mpstat -q 1';
c_GET_CPU_DATA_LOC = 'mpstat -q 1';
c_GET_RAM_DATA = 'vmstat 1';
c_GET_RAM_DATA_LOC = 'vmstat 1';
c_GET_NETWORK_DATA = 'dlstat show-phys -o link,type,pkts,bytes -p -i 1';
c_GET_NETWORK_DATA_LOC = 'dlstat show-phys -o link,type,pkts,bytes -p -i 1';
c_GET_CACHE_DATA = 'kstat -p zfs:0:arcstats:size zfs:0:arcstats:misses zfs:0:arcstats:hits zfs:0:arcstats:c zfs:0:arcstats:c_min zfs:0:arcstats:c_max 1';
c_GET_CACHE_DATA_LOC = 'kstat -p zfs:0:arcstats:size zfs:0:arcstats:misses zfs:0:arcstats:hits zfs:0:arcstats:c zfs:0:arcstats:c_min zfs:0:arcstats:c_max 1';
type
{ IFOS_STATS_CONTROL }
IFOS_STATS_CONTROL=interface
procedure StartCPUParser (const enable:boolean);
procedure StartRAMParser (const enable:boolean);
procedure StartNetworkParser (const enable:boolean);
procedure StartCacheParser (const enable:boolean);
procedure StartZFSParser (const enable:boolean);
function Get_CPU_Data : IFRE_DB_Object;
function Get_CacheData : IFRE_DB_Object;
function Get_Ram_Data : IFRE_DB_Object;
function Get_ZFS_Data_Once : IFRE_DB_Object;
function Get_Network_Data : IFRE_DB_Object;
procedure Finalize;
end;
function Get_Stats_Control(const user,host:string): IFOS_STATS_CONTROL;
implementation
type
{ TFOS_CPU_PARSER }
TFOS_CPU_PARSER=class(TFOS_PARSER_PROC)
protected
procedure MySetup ; override;
procedure MyOutStreamCallBack (const stream:TStream); override;
public
end;
{ TFOS_RAM_PARSER }
TFOS_RAM_PARSER=class(TFOS_PARSER_PROC)
protected
procedure MySetup ; override;
procedure MyOutStreamCallBack (const stream:TStream); override;
public
end;
{ TFOS_NETWORK_PARSER }
TFOS_NETWORK_PARSER=class(TFOS_PARSER_PROC)
protected
procedure MySetup ; override;
procedure MyOutStreamCallBack (const stream:TStream); override;
public
end;
{ TFOS_CACHE_PARSER }
TFOS_CACHE_PARSER=class(TFOS_PARSER_PROC)
protected
procedure MySetup ; override;
procedure MyOutStreamCallBack (const stream:TStream); override;
public
end;
{ TFOS_ZFS_PARSER }
TFOS_ZFS_PARSER=class(TFOS_PARSER_PROC)
private
protected
procedure MySetup ; override;
procedure MyOutStreamCallBack (const stream:TStream); override;
public
end;
{ TFOS_STATS_CONTROL }
TFOS_STATS_CONTROL=class(TObject,IFOS_STATS_CONTROL)
private
cremoteuser : string;
cremotehost : string;
cremotekeyfilename : string;
FCPUMon : TFOS_CPU_PARSER;
FRAMMon : TFOS_RAM_PARSER;
FNetworkMon : TFOS_NETWORK_PARSER;
FCacheMon : TFOS_CACHE_PARSER;
FZFSMon : TFOS_ZFS_PARSER;
procedure Finalize;
public
constructor Create (const user,host,dir : string);
destructor Destroy ; override ;
procedure StartCPUParser (const enable:boolean);
procedure StartRAMParser (const enable:boolean);
procedure StartNetworkParser (const enable:boolean);
procedure StartCacheParser (const enable:boolean);
procedure StartZFSParser (const enable:boolean);
function Get_CPU_Data : IFRE_DB_Object;
function Get_CacheData : IFRE_DB_Object;
function Get_Ram_Data : IFRE_DB_Object;
function Get_ZFS_Data_Once : IFRE_DB_Object;
function Get_Network_Data : IFRE_DB_Object;
end;
function Get_Stats_Control(const user, host: string): IFOS_STATS_CONTROL;
var res : TFOS_STATS_CONTROL;
dir : string;
begin
dir := SetDirSeparators(cFRE_SERVER_DEFAULT_DIR+'/ssl/user/id_rsa');
res := TFOS_STATS_CONTROL.Create(user,host,dir);
Result := res;
end;
procedure TFOS_ZFS_PARSER.MySetup;
begin
FLine.Delimiter:=' ';
end;
procedure TFOS_ZFS_PARSER.MyOutStreamCallBack(const stream: TStream);
var
st: TStringStream;
lc: Integer;
i: Integer;
s: String;
SA: TFOSStringArray;
j: Integer;
procedure _UpdateZFS;
var
poolid : string;
begin
poolid := Fline[0];
FData.Field(poolid).AsObject.Field('referenced').AsInt64 := StrToInt64(Fline[1]);
FData.Field(poolid).AsObject.Field('available').AsInt64 := StrToInt64(Fline[2]);
FData.Field(poolid).AsObject.Field('used').AsInt64 := StrToInt64(Fline[3]);
end;
begin
stream.Position:=0;
st := TStringStream.Create('');
try
st.CopyFrom(stream,stream.Size);
stream.Size:=0;
FLines.DelimitedText := st.DataString;
if Flines.count>0 then begin
lc := FLines.Count;
for i := 0 to lc-1 do begin
s := FLines[i];
if s='' then
continue;
GFRE_BT.SeperateString(s,#9,SA);
fline.Clear;
for j := 0 to high(sa) do
begin
if sa[j]<>'' then
FLine.Add(sa[j]);
end;
if FLine.count<>4 then
raise EFRE_Exception.Create('zfs parser error, unexpected val count ' + IntToStr(fline.Count));
FLock.Acquire;
try
try
_UpdateZFS;
except on E:Exception do begin
writeln(ClassName,'>>>Mickey Parser Error---');
s:= Fline.DelimitedText;
writeln(s);
writeln(Classname,'<<<Mickey Parser Error---');
end;end;
finally
FLock.Release;
end;
end;
end else begin
writeln(ClassName,'*IGNORING JUNK : ',st.Size,': [',st.DataString,']');
end;
finally
st.Free;
end;
end;
procedure TFOS_CACHE_PARSER.MySetup;
begin
FLine.Delimiter:=' ';
end;
procedure TFOS_CACHE_PARSER.MyOutStreamCallBack(const stream: TStream);
var
st: TStringStream;
lc: Integer;
i: Integer;
s: String;
SA: TFOSStringArray;
j: Integer;
procedure _UpdateCache;
var
s : string;
TA: TFOSStringArray;
begin
//s := FLine.CommaText;
//writeln(Fline.Count,' ',s);
GFRE_BT.SeperateString(Fline[0],':',TA);
case TA[3] of
'hits': begin
if FData.FieldExists('hits') then begin
FData.Field('relHits').AsInt16:=StrToInt64(Fline[1]) - FData.Field('hits').AsInt64;
end else begin
FData.Field('relHits').AsInt16:=0;
end;
end;
'misses': begin
if FData.FieldExists('misses') then begin
FData.Field('relMisses').AsInt16:=StrToInt64(Fline[1]) - FData.Field('misses').AsInt64;
end else begin
FData.Field('relMisses').AsInt16:=0;
end;
end;
end;
FData.Field(TA[3]).AsInt64 := StrToInt64(Fline[1]);
end;
begin
stream.Position:=0;
st := TStringStream.Create('');
try
st.CopyFrom(stream,stream.Size);
stream.Size:=0;
FLines.DelimitedText := st.DataString;
if Flines.count>0 then begin
lc := FLines.Count;
for i:= 0 to lc-1 do
begin
s := FLines[i];
if s='' then continue;
GFRE_BT.SeperateString(s,#9,SA);
fline.Clear;
for j := 0 to high(sa) do
begin
if sa[j]<>'' then
FLine.Add(sa[j]);
end;
if FLine.count<>2 then
raise EFRE_Exception.Create('cache parser error, unexpected val count');
FLock.Acquire;
try
try
_UpdateCache;
except on E:Exception do begin
writeln(ClassName,'>>>Mickey Parser Error---');
s:= Fline.DelimitedText;
writeln(s);
writeln(Classname,'<<<Mickey Parser Error---');
end;end;
finally
FLock.Release;
end;
end;
end else begin
writeln(ClassName,'*IGNORING JUNK : ',st.Size,': [',st.DataString,']');
end;
finally
st.Free;
end;
end;
procedure TFOS_NETWORK_PARSER.MySetup;
begin
FLine.Delimiter:=' ';
end;
procedure TFOS_NETWORK_PARSER.MyOutStreamCallBack(const stream: TStream);
var
st: TStringStream;
lc: Integer;
i: Integer;
s: String;
SA: TFOSStringArray;
j: Integer;
// link,type,pkts,bytes
procedure _UpdateNetwork;
var
s : string;
netId,netType : String;
pkts,bytes : string;
begin
//s := FLine.CommaText;
//writeln(Fline.Count,' ',s);
netId := Fline[0];
netType := FLine[1];
pkts := Fline[2];
bytes := Fline[3];
FData.Field(netId).AsObject.Field(netType).AsObject.Field('pkts').AsInt64 := StrToInt64(pkts);
FData.Field(netId).AsObject.Field(netType).AsObject.Field('bytes').AsInt64 := StrToInt64(bytes);
end;
begin
stream.Position:=0;
st := TStringStream.Create('');
try
st.CopyFrom(stream,stream.Size);
stream.Size:=0;
FLines.DelimitedText := st.DataString;
if Flines.count>0 then begin
lc := FLines.Count;
for i:= 0 to lc-1 do
begin
s := FLines[i];
if s='' then continue;
GFRE_BT.SeperateString(s,':',SA);
fline.Clear;
for j := 0 to high(sa) do
begin
if sa[j]<>'' then
FLine.Add(sa[j]);
end;
if FLine.count<>4 then
raise EFRE_Exception.Create('network parser error, unexpected val count');
FLock.Acquire;
try
try
_UpdateNetwork;
except on E:Exception do begin
writeln(ClassName,'>>>Mickey Parser Error---');
s:= Fline.DelimitedText;
writeln(s);
writeln(Classname,'<<<Mickey Parser Error---');
end;end;
finally
FLock.Release;
end;
end;
end else begin
writeln(ClassName,'*IGNORING JUNK : ',st.Size,': [',st.DataString,']');
end;
finally
st.Free;
end;
end;
procedure TFOS_RAM_PARSER.MySetup;
begin
FLine.Delimiter:=' ';
end;
procedure TFOS_RAM_PARSER.MyOutStreamCallBack(const stream: TStream);
var
st: TStringStream;
lc: Integer;
i: Integer;
s: String;
SA: TFOSStringArray;
j: Integer;
// r b w swap free re mf pi po fr de sr lf rm s0 s1 in sy cs us sy id
procedure _UpdateRAM;
var
s : string;
begin
//s := FLine.CommaText;
//writeln(Fline.Count,' ',s);
FData.Field('kthr_r').AsInt64 := StrToInt64(Fline[0]);
FData.Field('kthr_b').AsInt64 := StrToInt64(Fline[1]);
FData.Field('kthr_w').AsInt64 := StrToInt64(Fline[2]);
FData.Field('memory_swap').AsInt64 := StrToInt64(Fline[3]);
FData.Field('memory_free').AsInt64 := StrToInt64(Fline[4]);
FData.Field('page_re').AsInt64 := StrToInt64(Fline[5]);
FData.Field('page_mf').AsInt64 := StrToInt64(Fline[6]);
FData.Field('page_pi').AsInt64 := StrToInt64(Fline[7]);
FData.Field('page_po').AsInt64 := StrToInt64(Fline[8]);
FData.Field('page_fr').AsInt64 := StrToInt64(Fline[9]);
FData.Field('page_de').AsInt64 := StrToInt64(Fline[10]);
FData.Field('page_sr').AsInt64 := StrToInt64(Fline[10]);
//ignore disks (4)
//FData.Field('').AsInt64 := StrToInt64(Fline[12]);
//FData.Field('').AsInt64 := StrToInt64(Fline[13]);
//FData.Field('').AsInt64 := StrToInt64(Fline[14]);
//FData.Field('').AsInt64 := StrToInt64(Fline[15]);
FData.Field('faults_in').AsInt64 := StrToInt64(Fline[16]);
FData.Field('faults_sy').AsInt64 := StrToInt64(Fline[17]);
FData.Field('faults_cs').AsInt64 := StrToInt64(Fline[18]);
FData.Field('cpu_us').AsInt64 := StrToInt64(Fline[19]);
FData.Field('cpu_sy').AsInt64 := StrToInt64(Fline[20]);
FData.Field('cpu_id').AsInt64 := StrToInt64(Fline[21]);
end;
begin
stream.Position:=0;
st := TStringStream.Create('');
try
st.CopyFrom(stream,stream.Size);
stream.Size:=0;
FLines.DelimitedText := st.DataString;
if Flines.count>0 then begin
lc := FLines.Count;
for i:= 0 to lc-1 do
begin
if pos('kthr',Flines[i])>1 then continue;
if pos('r b w',Flines[i])>1 then continue;
s := FLines[i];
if s='' then continue;
GFRE_BT.SeperateString(s,' ',SA);
fline.Clear;
for j := 0 to high(sa) do
begin
if sa[j]<>'' then
FLine.Add(sa[j]);
end;
if FLine.count<>22 then
raise EFRE_Exception.Create('ram parser error, unexpected val count');
FLock.Acquire;
try
try
_UpdateRAM;
except on E:Exception do begin
writeln(ClassName,'>>>Mickey Parser Error---');
s:= Fline.DelimitedText;
writeln(s);
writeln(Classname,'<<<Mickey Parser Error---');
end;end;
finally
FLock.Release;
end;
end;
end else begin
writeln(ClassName,'*IGNORING JUNK : ',st.Size,': [',st.DataString,']');
end;
finally
st.Free;
end;
end;
{ TFOS_DISK_PARSER }
{ TFOS_CPU_PARSER }
procedure TFOS_CPU_PARSER.MySetup;
begin
FLine.Delimiter:=' ';
end;
procedure TFOS_CPU_PARSER.MyOutStreamCallBack(const stream: TStream);
var st : TStringStream;
i,j : integer;
s : string;
lc : integer;
// CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl
procedure _UpdateCPU;
var CPUID : string[30];
s : string;
begin
CPUID := 'CPU'+Fline[0];
//s := FLine.CommaText;
//writeln(Fline.Count,' ',s);
FData.Field(CPUID).AsObject.Field('minf').AsInt64 := StrToInt64(Fline[1]);
FData.Field(CPUID).AsObject.Field('mjf').AsInt64 := StrToInt64(Fline[2]);
FData.Field(CPUID).AsObject.Field('xcal').AsInt64 := StrToInt64(Fline[3]);
FData.Field(CPUID).AsObject.Field('intr').AsInt64 := StrToInt64(Fline[4]);
FData.Field(CPUID).AsObject.Field('ithr').AsInt64 := StrToInt64(Fline[5]);
FData.Field(CPUID).AsObject.Field('csw').AsInt64 := StrToInt64(Fline[6]);
FData.Field(CPUID).AsObject.Field('icsw').AsInt64 := StrToInt64(Fline[7]);
FData.Field(CPUID).AsObject.Field('migr').AsInt64 := StrToInt64(Fline[8]);
FData.Field(CPUID).AsObject.Field('smtx').AsInt64 := StrToInt64(Fline[9]);
FData.Field(CPUID).AsObject.Field('srw').AsInt64 := StrToInt64(Fline[10]);
FData.Field(CPUID).AsObject.Field('syscl').AsInt64 := StrToInt64(Fline[11]);
FData.Field(CPUID).AsObject.Field('usr').AsInt64 := StrToInt64(Fline[12]);
FData.Field(CPUID).AsObject.Field('sys').AsInt64 := StrToInt64(Fline[13]);
//FData.Field(CPUID).AsObject.Field('wt').AsInt64 := StrToInt64(Fline[14]); // always zero
FData.Field(CPUID).AsObject.Field('idl').AsInt64 := StrToInt64(Fline[15]);
end;
var sa:TFOSStringArray;
begin
stream.Position:=0;
st := TStringStream.Create('');
try
st.CopyFrom(stream,stream.Size);
stream.Size:=0;
FLines.DelimitedText := st.DataString;
if Flines.count>0 then begin
lc := FLines.Count;
for i:= 0 to lc-1 do
begin
if pos('CPU',Flines[i])=1 then
continue;
s := FLines[i];
if s='' then
continue;
GFRE_BT.SeperateString(s,' ',SA);
fline.Clear;
for j := 0 to high(sa) do
begin
if sa[j]<>'' then
FLine.Add(sa[j]);
end;
if FLine.count<>16 then
raise EFRE_Exception.Create('cpu parser error, unexpected val count');
FLock.Acquire;
try
try
_UpdateCPU;
except on E:Exception do begin
writeln(ClassName,'>>>Mickey Parser Error---');
s:= Fline.DelimitedText;
writeln(s);
writeln(Classname,'<<<Mickey Parser Error---');
end;end;
finally
FLock.Release;
end;
end;
end else begin
writeln(ClassName,'*IGNORING JUNK : ',st.Size,': [',st.DataString,']');
end;
finally
st.Free;
end;
end;
{ TFOS_DISK_CONTROL }
procedure TFOS_STATS_CONTROL.Finalize;
begin
Free;
end;
constructor TFOS_STATS_CONTROL.Create(const user, host, dir: string);
begin
abort;
//if user<>'' then
// begin
// FCPUMon := TFOS_CPU_PARSER.Create(user,dir,host,c_GET_CPU_DATA);
// FRAMMon := TFOS_RAM_PARSER.Create(user,dir,host,c_GET_RAM_DATA);
// FNetworkMon := TFOS_NETWORK_PARSER.Create(user,dir,host,c_GET_NETWORK_DATA);
// FCacheMon := TFOS_CACHE_PARSER.Create(user,dir,host,c_GET_CACHE_DATA);
// end
//else
// begin
// FCPUMon := TFOS_CPU_PARSER.Create(user,dir,host,c_GET_CPU_DATA_LOC);
// FRAMMon := TFOS_RAM_PARSER.Create(user,dir,host,c_GET_RAM_DATA_LOC);
// FNetworkMon := TFOS_NETWORK_PARSER.Create(user,dir,host,c_GET_NETWORK_DATA_LOC);
// FCacheMon := TFOS_CACHE_PARSER.Create(user,dir,host,c_GET_CACHE_DATA_LOC);
// end;
//cremoteuser := user;
//cremotehost := host;
//cremotekeyfilename := dir;
end;
destructor TFOS_STATS_CONTROL.Destroy;
begin
FNetworkMon.Disable;
FNetworkMon.Free;
FCacheMon.Disable;
FCacheMon.Free;
FRAMMon.Disable;
FRAMMon.FRee;
FCPUMon.Disable;
FCPUMon.Free;
inherited Destroy;
end;
procedure TFOS_STATS_CONTROL.StartCPUParser(const enable: boolean);
begin
if enable then
FCPUMon.Enable
else
FCPUMon.Disable;
end;
procedure TFOS_STATS_CONTROL.StartRAMParser(const enable: boolean);
begin
if enable then
FRAMMon.Enable
else
FRAMMon.Disable;
end;
procedure TFOS_STATS_CONTROL.StartNetworkParser(const enable: boolean);
begin
if enable then
FNetworkMon.Enable
else
FNetworkMon.Disable;
end;
procedure TFOS_STATS_CONTROL.StartCacheParser(const enable: boolean);
begin
if enable then
FCacheMon.Enable
else
FCacheMon.Disable;
end;
procedure TFOS_STATS_CONTROL.StartZFSParser(const enable: boolean);
begin
if enable then
FCPUMon.Enable
else
FCPUMon.Disable;
end;
function TFOS_STATS_CONTROL.Get_CPU_Data: IFRE_DB_Object;
var
CPUAGGR : IFRE_DB_Object;
count : Integer;
procedure _addCpu(const field: IFRE_DB_Field);
procedure _addValue(const field: IFRE_DB_Field);
begin
if field.FieldType=fdbft_GUID then exit;
CPUAGGR.Field(field.FieldName).AsReal32:=CPUAGGR.Field(field.FieldName).AsReal32+field.AsInt64;
end;
procedure _setValue(const field: IFRE_DB_Field);
begin
if field.FieldType=fdbft_GUID then exit;
CPUAGGR.Field(field.FieldName).AsReal32:=field.AsInt64;
end;
begin
if field.FieldType=fdbft_GUID then exit;
if count=0 then begin
field.AsObject.ForAllFields(@_setValue);
end else begin
field.AsObject.ForAllFields(@_addValue);
end;
count:=count+1;
end;
procedure _divideValue(const field: IFRE_DB_Field);
begin
if field.FieldType=fdbft_GUID then exit;
field.AsReal32:=field.AsReal32 / count;
end;
begin
result := FCPUMon.Get_Data_Object;
count := 0;
CPUAGGR:=GFRE_DBI.NewObject;
result.ForAllFields(@_addCpu);
CPUAGGR.ForAllFields(@_divideValue);
result.Field('CPU_AGGR').AsObject := CPUAGGR;
end;
function TFOS_STATS_CONTROL.Get_CacheData: IFRE_DB_Object;
begin
result := FCacheMon.Get_Data_Object;
end;
function TFOS_STATS_CONTROL.Get_Ram_Data: IFRE_DB_Object;
begin
result := FRAMMon.Get_Data_Object;
end;
function TFOS_STATS_CONTROL.Get_ZFS_Data_Once: IFRE_DB_Object;
var
dimon : TFOS_ZFS_PARSER;
begin
abort;
//dimon := TFOS_ZFS_PARSER.Create(cremoteuser,cremotekeyfilename,cremotehost,c_GET_ZFS_DATA_ONCE);
try
//dimon.Once;
result := dimon.Get_Data_Object;
finally
dimon.Free;
end;
end;
function TFOS_STATS_CONTROL.Get_Network_Data: IFRE_DB_Object;
var
NETAGGR : IFRE_DB_Object;
count : Integer;
procedure _addNet(const field: IFRE_DB_Field);
procedure _setObjs(const field: IFRE_DB_Field);
begin
if field.FieldType=fdbft_GUID then exit;
NETAGGR.Field(field.FieldName).AsObject:=field.AsObject.CloneToNewObject();
end;
procedure _addObjs(const field: IFRE_DB_Field);
var
objId: String;
procedure _addValues(const field: IFRE_DB_Field);
begin
if field.FieldType=fdbft_GUID then exit;
NETAGGR.Field(objId).AsObject.Field(field.FieldName).AsInt64:=NETAGGR.Field(objId).AsObject.Field(field.FieldName).AsInt64+field.AsInt64;
end;
begin
if field.FieldType=fdbft_GUID then exit;
objId:=field.FieldName;
field.AsObject.ForAllFields(@_addValues);
end;
begin
if field.FieldType=fdbft_GUID then exit;
if count=0 then begin
field.AsObject.ForAllFields(@_setObjs);
end else begin
field.AsObject.ForAllFields(@_addObjs);
end;
count:=count+1;
end;
begin
result := FNetworkMon.Get_Data_Object;
NETAGGR:=GFRE_DBI.NewObject;
count:=0;
result.ForAllFields(@_addNet);
result.Field('NET_AGGR').AsObject := NETAGGR;
end;
end.
|
unit ItemPedidoVenda;
interface
uses
Produto, DBXJSONReflect, RTTI, DBXPlatform;
type
TDoubleInterceptor = class(TJSONInterceptor)
public
function StringConverter(Data: TObject; Field: string): string; override;
procedure StringReverter(Data: TObject; Field: string; Arg: string); override;
end;
TItemPedidoVenda = class
private
FProduto: TProduto;
FQuantidade: Integer;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FDescontoValor: Currency;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FDescontoPercentual: Currency;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FValor: Currency;
public
property Produto: TProduto read FProduto write FProduto;
property Quantidade: Integer read FQuantidade write FQuantidade;
property DescontoValor: Currency read FDescontoValor write FDescontoValor;
property DescontoPercentual: Currency read FDescontoPercentual write FDescontoPercentual;
property Valor: Currency read FValor write FValor;
end;
implementation
{ TDoubleInterceptor }
function TDoubleInterceptor.StringConverter(Data: TObject; Field: string): string;
var
LRttiContext: TRttiContext;
LValue: Double;
begin
LValue := LRttiContext.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<Double>;
Result := TDBXPlatform.JsonFloat(LValue);
end;
procedure TDoubleInterceptor.StringReverter(Data: TObject; Field, Arg: string);
var
LRttiContext: TRttiContext;
LValue: Double;
begin
LValue := TDBXPlatform.JsonToFloat(Arg);
LRttiContext.GetType(Data.ClassType).GetField(Field).SetValue(Data, TValue.From<Double>(LValue));
end;
end.
|
unit RunOptions;
{$ALIGN ON}
{$MINENUMSIZE 4}
interface
uses
Windows,
SysUtils, Classes, IniFiles;
//{$define RedirectStdOut}
const
CAllOpt = 'All';
CInfoNam = 'Info';
CInfos: array[0..2] of string = ('0', '1', '2');
CBuildNam = 'Build';
CBuilds: array[0..2] of string = (CAllOpt, 'debug', 'release');
COSNam = 'OS';
COSs: array[0..5] of string = (CAllOpt, 'freebsd', 'linux', 'openbsd', 'osx', 'windows');
CX86Nam = 'X86';
CX86s: array[0..2] of string = (CAllOpt, '32', '64');
CDMDNam = 'DMD';
CRunNam = 'Run';
COptSec = 'Options';
CFilSec = 'Files';
type
TOptions = record
Build: string;
OS: string;
X86: string;
ProjectIniFileName: string;
Info: Integer;
end;
// Valid section names
// [Options]
// [Options Build_Debug] [Options Build_Release]
// [Options OS_Windows] [Options OS_...]
// [Options X86_32] [Options X86_64]
// [Files]
// [Files Build_Debug] [Files Build_Release]
// [Files OS_Windows] [Files OS_...]
// [Files X86_32] [Files X86_64]
TDMDOptions = class(TObject)
private
CheckFiles: TStringList;
CheckOptions: TStringList;
public
Options: TOptions;
RunFiles: TStringList;
RunOptions: TStringList;
constructor Create(const AOptions: TOptions);
destructor Destroy; override;
function AddFile(const AFile: string): Boolean;
function AddOption(const AOption: string): Boolean;
function BuildIt(const ADMD: string): Integer;
function BuildInfo: string;
function GetDMDArguments: string;
procedure ReadFiles(const AProjectIniFile: TMemIniFile; const ASectionName: string);
procedure ReadOptions(const AProjectIniFile: TMemIniFile; const ASectionName: string);
function RunIt(const ARun: string): Integer;
end;
TDMDOptionsArray = array of TDMDOptions;
TRunOptions = class(TObject)
public
// Build=default Debug
// OS=default Windows
// X86=default 32
// Info=default 1
Options: TOptions;
DMD: string; // default dmd.exe
Run: string;
constructor Create;
function GetDMDOptions: TDMDOptionsArray;
function ReadOptions(var Errors: string): Boolean;
function SetOption(const AName, AValue: string): Boolean;
class function RunOptions: string;
end;
function AddLine(var Lines: string; const ALine: string): string;
function AddStr(var Strs: string; const AStr: string; const ADelim: Char = ' '): string;
function BreakOption(const AStr: string; var Name, Value: string): Integer;
function IndexOf(const AStrs: array of string; const AStr: string): Integer;
function Quote(const AStr: string; const AQuote: Char = '"'): string;
function Run(const AExe, AArguments: string): Integer;
function StripQuote(const AStr: string): string;
function ToCSV(const AStrs: array of string; const ADelim: Char = ','): string;
function WriteStdOut(AStr: AnsiString): BOOL;
function WriteLnStdOut(AStr: AnsiString): BOOL;
implementation
function AddLine(var Lines: string; const ALine: string): string;
begin
if Length(Lines) = 0 then
Lines := ALine
else
Lines := Lines + sLineBreak + ALine;
Result := Lines;
end;
function AddStr(var Strs: string; const AStr: string; const ADelim: Char = ' '): string;
begin
if Length(Strs) = 0 then
Strs := AStr
else
Strs := Strs + ADelim + AStr;
Result := Strs;
end;
function BreakOption(const AStr: string; var Name, Value: string): Integer;
var
I: Integer;
begin
I := Pos('=', AStr);
if I > 0 then
begin
Name := Trim(Copy(AStr, 1, I - 1));
Value := Trim(Copy(AStr, I + 1, Length(AStr) - I));
if Length(Name) > 0 then
begin
if Length(Value) > 0 then
Result := 2
else
Result := 1;
end
else
Result := -1;
end
else
begin
Result := 0;
end;
end;
function IndexOf(const AStrs: array of string; const AStr: string): Integer;
var
I: Integer;
begin
for I := 0 to High(AStrs) do
begin
if AStrs[I] = AStr then
begin
Result := I;
Exit;
end;
end;
Result := -1;
end;
function Quote(const AStr: string; const AQuote: Char = '"'): string;
begin
Result := AQuote + AStr + AQuote;
end;
procedure CloseHandleAndNil(var H: THandle);
begin
if H <> INVALID_HANDLE_VALUE then
begin
Windows.CloseHandle(H);
H := INVALID_HANDLE_VALUE;
end;
end;
type
_STARTUPINFOW = record
cb: DWORD;
lpReserved: LPWSTR;
lpDesktop: LPWSTR;
lpTitle: LPWSTR;
dwX: DWORD;
dwY: DWORD;
dwXSize: DWORD;
dwYSize: DWORD;
dwXCountChars: DWORD;
dwYCountChars: DWORD;
dwFillAttribute: DWORD;
dwFlags: DWORD;
wShowWindow: Word;
cbReserved2: Word;
lpReserved2: PByte;
hStdInput: THandle;
hStdOutput: THandle;
hStdError: THandle;
end;
TStartupInfoW = _STARTUPINFOW;
function CreateProcessW(lpApplicationName: PWideChar; lpCommandLine: PWideChar;
lpProcessAttributes, lpThreadAttributes: PSecurityAttributes;
bInheritHandles: BOOL; dwCreationFlags: DWORD; lpEnvironment: Pointer;
lpCurrentDirectory: PWideChar; const lpStartupInfo: TStartupInfoW;
var lpProcessInformation: TProcessInformation): BOOL; stdcall; external kernel32 name 'CreateProcessW';
(*
BOOL PeekNamedPipe(
[in] HANDLE hNamedPipe,
[out, optional] LPVOID lpBuffer,
[in] DWORD nBufferSize,
[out, optional] LPDWORD lpBytesRead,
[out, optional] LPDWORD lpTotalBytesAvail,
[out, optional] LPDWORD lpBytesLeftThisMessage
);
*)
{$ifdef RedirectStdOut}
function RedirectStd(const AReadHandle, AWriteHandle: THandle): Boolean;
const
CBufferSize = 1000;
var
Buffer: array[0..CBufferSize] of Byte;
BytesAvail, BytesRead, ByteWrites: DWORD;
begin
BytesAvail := 0;
BytesRead := 0;
if not Windows.PeekNamedPipe(AReadHandle, nil, 0, @BytesRead, @BytesAvail, nil) then
begin
Result := False;
Exit;
end;
if BytesAvail = 0 then
begin
Result := False;
Exit;
end;
BytesRead := 0;
if BytesAvail > CBufferSize then
BytesAvail := CBufferSize;
Result := Windows.ReadFile(AReadHandle, Buffer, BytesAvail, BytesRead, nil);
if Result and (BytesRead > 0) then
begin
ByteWrites := 0;
Windows.WriteFile(AWriteHandle, Buffer, BytesRead, ByteWrites, nil);
end;
end;
{$endif}
function Run(const AExe, AArguments: string): Integer;
var
ApplicationName, CommandLine, CurrentDirectory: WideString;
ApplicationNameP, CommandLineP, CurrentDirectoryP: PWideChar;
PI: TProcessInformation;
SA: TSecurityAttributes;
SI: TStartupInfoW;
{$ifdef RedirectStdOut}
StdErrPipeRead, StdErrPipeWrite,
StdOutPipeRead, StdOutPipeWrite: THandle;
ReadOK: Boolean;
{$endif}
begin
Result := 0;
FillChar(SA, SizeOf(SA), 0);
SA.nLength := SizeOf(SA);
SA.bInheritHandle := True;
{$ifdef RedirectStdOut}
StdOutPipeRead := INVALID_HANDLE_VALUE;
StdOutPipeWrite := INVALID_HANDLE_VALUE;
Windows.CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
Windows.SetHandleInformation(StdOutPipeRead, HANDLE_FLAG_INHERIT, 0);
StdErrPipeRead := INVALID_HANDLE_VALUE;
StdErrPipeWrite := INVALID_HANDLE_VALUE;
Windows.CreatePipe(StdErrPipeRead, StdErrPipeWrite, @SA, 0);
Windows.SetHandleInformation(StdErrPipeRead, HANDLE_FLAG_INHERIT, 0);
{$endif}
FillChar(SI, SizeOf(SI), 0);
SI.cb := SizeOf(SI);
SI.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
SI.wShowWindow := SW_HIDE;
SI.hStdInput := Windows.GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
{$ifdef RedirectStdOut}
SI.hStdOutput := StdOutPipeWrite;
SI.hStdError := StdErrPipeWrite;
{$else}
SI.hStdOutput := Windows.GetStdHandle(STD_OUTPUT_HANDLE);
SI.hStdError := Windows.GetStdHandle(STD_ERROR_HANDLE);
{$endif}
if Length(AExe) > 0 then
begin
ApplicationName := AExe + #0;
ApplicationNameP := PWideChar(ApplicationName);
end
else
ApplicationNameP := nil;
if Length(AArguments) > 0 then
begin
CommandLine := AArguments + #0;
CommandLineP := PWideChar(CommandLine);
end
else
CommandLineP := nil;
//CurrentDirectory := ExtractFileDir(ParamStr(0)) + #0;
//CurrentDirectoryP := PWideChar(CurrentDirectory);
CurrentDirectoryP := nil;
{$ifdef RedirectStdOut}
try
if not CreateProcessW(ApplicationNameP, CommandLineP, nil, nil, True, 0, nil, CurrentDirectoryP, SI, PI) then
begin
Result := GetLastError;
Exit;
end;
CloseHandleAndNil(StdErrPipeWrite);
CloseHandleAndNil(StdOutPipeWrite);
try
ReadOK := True; // Make Delphi 7 happy
repeat
case Windows.WaitForSingleObject(PI.hProcess, 1000) of
WAIT_FAILED, WAIT_ABANDONED:
Break;
end;
ReadOK := RedirectStd(StdErrPipeRead, Windows.GetStdHandle(STD_ERROR_HANDLE));
if RedirectStd(StdOutPipeRead, Windows.GetStdHandle(STD_OUTPUT_HANDLE)) then
ReadOK := True;
until not ReadOK;
// Last read after DMD closed
RedirectStd(StdErrPipeRead, Windows.GetStdHandle(STD_ERROR_HANDLE));
RedirectStd(StdOutPipeRead, Windows.GetStdHandle(STD_OUTPUT_HANDLE));
finally
Windows.CloseHandle(PI.hThread);
Windows.CloseHandle(PI.hProcess);
end;
finally
CloseHandleAndNil(StdErrPipeRead);
CloseHandleAndNil(StdErrPipeWrite);
CloseHandleAndNil(StdOutPipeRead);
CloseHandleAndNil(StdOutPipeWrite);
end;
{$else}
if not CreateProcessW(ApplicationNameP, CommandLineP, nil, nil, True, 0, nil, CurrentDirectoryP, SI, PI) then
begin
Result := Windows.GetLastError;
Exit;
end;
Windows.WaitForSingleObject(PI.hProcess, INFINITE);
Windows.CloseHandle(PI.hThread);
Windows.CloseHandle(PI.hProcess);
Sleep(1000);
{$endif}
end;
function StripQuote(const AStr: string): string;
var
C: Char;
begin
if Length(AStr) > 1 then
begin
C := AStr[1];
if ((C = '"') or (C = '''')) and (C = AStr[Length(AStr)]) then
Result := Trim(Copy(AStr, 2, Length(AStr) - 2))
else
Result := Trim(AStr);
end
else
Result := Trim(AStr);
end;
function ToCSV(const AStrs: array of string; const ADelim: Char = ','): string;
var
I: Integer;
begin
Result := AStrs[0];
for I := 1 to High(AStrs) do
Result := Result + ADelim + AStrs[I];
end;
function WriteStdOut(AStr: AnsiString): BOOL;
var
OutHandle: THandle;
BytesRead, ByteWrites: DWORD;
begin
OutHandle := Windows.GetStdHandle(STD_OUTPUT_HANDLE);
BytesRead := Length(AStr);
ByteWrites := 0;
if BytesRead > 0 then
Result := Windows.WriteFile(OutHandle, AStr[1], BytesRead, ByteWrites, nil)
else
Result := True;
end;
function WriteLnStdOut(AStr: AnsiString): BOOL;
begin
Result := WriteStdOut(AStr);
if Result then
Result := WriteStdOut(sLineBreak);
end;
{ TDMDOptions }
function TDMDOptions.AddFile(const AFile: string): Boolean;
begin
Result := (Length(AFile) > 0) and (AFile[1] <> '#') and (CheckFiles.IndexOf(AFile) < 0);
if Result then
begin
CheckFiles.Add(AFile);
RunFiles.Add(AFile);
end;
end;
function TDMDOptions.AddOption(const AOption: string): Boolean;
begin
Result := (Length(AOption) > 1) and (AOption[1] <> '#') and (CheckOptions.IndexOf(AOption) < 0);
if Result then
begin
CheckOptions.Add(AOption);
RunOptions.Add(AOption);
end;
end;
function TDMDOptions.BuildInfo: string;
begin
Result := CBuildNam + '=' + Options.Build
+ ' ' + COSNam + '=' + Options.OS
+ ' ' + CX86Nam + '=' + Options.X86
+ ' ' + Options.ProjectIniFileName;
end;
function TDMDOptions.BuildIt(const ADMD: string): Integer;
var
DMDArguments: string;
begin
DMDArguments := GetDMDArguments;
if Options.Info >= 1 then
begin
WriteStdOut(BuildInfo);
WriteLnStdOut(' ...');
end;
if Options.Info >= 2 then
begin
WriteStdOut(ADMD);
WriteStdOut(' ');
WriteLnStdOut(DMDArguments);
end;
Result := Run(ADMD, DMDArguments);
if Result <> 0 then
WriteLnStdOut('BuildIt failed with error code: ' + IntToStr(Result));
end;
constructor TDMDOptions.Create(const AOptions: TOptions);
const
CFilesCapacity = 1000;
COptionsCapacity = 100;
var
ProjectIniFile: TMemIniFile;
begin
Options := AOptions;
CheckFiles := TStringList.Create;
CheckFiles.Capacity := CFilesCapacity;
CheckFiles.Sorted := True;
CheckOptions := TStringList.Create;
CheckOptions.Capacity := COptionsCapacity;
CheckOptions.Sorted := True;
RunFiles := TStringList.Create;
RunFiles.Capacity := CFilesCapacity;
RunOptions := TStringList.Create;
RunOptions.Capacity := COptionsCapacity;
ProjectIniFile := TMemIniFile.Create(AOptions.ProjectIniFileName);
try
ReadOptions(ProjectIniFile, COptSec);
ReadOptions(ProjectIniFile, COptSec + ' ' + CBuildNam + '_' + AOptions.Build);
ReadOptions(ProjectIniFile, COptSec + ' ' + COSNam + '_' + AOptions.OS);
ReadOptions(ProjectIniFile, COptSec + ' ' + CX86Nam + '_' + AOptions.X86);
ReadFiles(ProjectIniFile, CFilSec);
ReadFiles(ProjectIniFile, CFilSec + ' ' + CBuildNam + '_' + AOptions.Build);
ReadFiles(ProjectIniFile, CFilSec + ' ' + COSNam + '_' + AOptions.OS);
ReadFiles(ProjectIniFile, CFilSec + ' ' + CX86Nam + '_' + AOptions.X86);
finally
ProjectIniFile.Free;
end;
CheckFiles.Clear;
CheckOptions.Clear;
if AOptions.X86 = '32' then
AddOption('-m32')
else if AOptions.X86 = '64' then
AddOption('-m64');
if Length(AOptions.OS) > 0 then
AddOption('-os=' + AOptions.OS);
end;
destructor TDMDOptions.Destroy;
begin
FreeAndNil(CheckFiles);
FreeAndNil(CheckOptions);
FreeAndNil(RunFiles);
FreeAndNil(RunOptions);
inherited Destroy;
end;
function TDMDOptions.GetDMDArguments: string;
var
I: Integer;
begin
Result := '';
for I := 0 to RunOptions.Count - 1 do
AddStr(Result, RunOptions[I]);
for I := 0 to RunFiles.Count - 1 do
AddStr(Result, Quote(RunFiles[I]));
end;
procedure TDMDOptions.ReadFiles(const AProjectIniFile: TMemIniFile; const ASectionName: string);
var
Values: TStringList;
I: Integer;
begin
Values := TStringList.Create;
try
AProjectIniFile.ReadSectionValues(ASectionName, Values);
for I := 0 to Values.Count - 1 do
AddFile(Trim(Values[I]));
finally
Values.Free;
end;
end;
procedure TDMDOptions.ReadOptions(const AProjectIniFile: TMemIniFile; const ASectionName: string);
var
Values: TStringList;
I: Integer;
begin
Values := TStringList.Create;
try
AProjectIniFile.ReadSectionValues(ASectionName, Values);
for I := 0 to Values.Count - 1 do
AddOption(Trim(Values[I]));
finally
Values.Free;
end;
end;
function TDMDOptions.RunIt(const ARun: string): Integer;
begin
if Options.Info >= 1 then
begin
WriteStdOut(ARun);
WriteLnStdOut(' ...');
end;
Result := Run('', ARun);
if Result <> 0 then
WriteLnStdOut('RunIt failed with error code: ' + IntToStr(Result));
end;
{ TRunOptions }
constructor TRunOptions.Create;
begin
Options.Build := 'debug';
Options.OS := 'windows';
Options.X86 := '32';
Options.Info := 1;
DMD := 'dmd.exe';
end;
function TRunOptions.GetDMDOptions: TDMDOptionsArray;
var
Builds, OSs, X86s: array of string;
DMDOptions: TOptions;
I, B, O, X: Integer;
begin
if Options.Build = CAllOpt then
begin
SetLength(Builds, Length(CBuilds) - 1);
for I := 1 to High(CBuilds) do
Builds[I - 1] := CBuilds[I];
end
else
begin
SetLength(Builds, 1);
Builds[0] := Options.Build;
end;
if Options.OS = CAllOpt then
begin
SetLength(OSs, Length(COSs) - 1);
for I := 1 to High(COSs) do
OSs[I - 1] := COSs[I];
end
else
begin
SetLength(OSs, 1);
OSs[0] := Options.OS;
end;
if Options.X86 = CAllOpt then
begin
SetLength(X86s, Length(CX86s) - 1);
for I := 1 to High(CX86s) do
X86s[I - 1] := CX86s[I];
end
else
begin
SetLength(X86s, 1);
X86s[0] := Options.X86;
end;
I := 0;
DMDOptions := Options;
SetLength(Result, Length(Builds) * Length(OSs) * Length(X86s));
for B := 0 to High(Builds) do
begin
for O := 0 to High(OSs) do
begin
for X := 0 to High(X86s) do
begin
DMDOptions.Build := Builds[B];
DMDOptions.OS := OSs[O];
DMDOptions.X86 := X86s[X];
Result[I] := TDMDOptions.Create(DMDOptions);
Inc(I);
end;
end;
end;
end;
function TRunOptions.ReadOptions(var Errors: string): Boolean;
// ParamStr(0)=program file name
var
S, N, V: string;
I, ErrorCount: Integer;
procedure AddError(const AError: string);
begin
AddLine(Errors, AError);
Inc(ErrorCount);
end;
begin
ErrorCount := 0;
for I := 1 to ParamCount do
begin
S := ParamStr(I);
case BreakOption(S, N, V) of
0:
Options.ProjectIniFileName := StripQuote(S);
1:
AddError('Invalid option: ' + S);
2:
begin
if not SetOption(N, V) then
AddError('Invalid option: ' + S);
end;
else
AddError('Invalid option: ' + S);
end;
end;
if Length(Options.ProjectIniFileName) = 0 then
AddError('Missing project file-name')
else if not FileExists(Options.ProjectIniFileName) then
AddError('Invalid project file-name: ' + Options.ProjectIniFileName);
Result := ErrorCount = 0;
end;
class function TRunOptions.RunOptions: string;
begin
Result := 'ProjectFileName.ini';
AddLine(Result, CBuildNam + '=debug [' + ToCSV(CBuilds) + ']');
AddLine(Result, COSNam + '=windows [' + ToCSV(COSs) + ']');
AddLine(Result, CX86Nam + '=32 [' + ToCSV(CX86s) + ']');
AddLine(Result, CInfoNam + '=1 [' + ToCSV(CInfos) + ']');
AddLine(Result, CDMDNam + '=dmd.exe');
AddLine(Result, CRunNam + '=???.exe arguments...');
end;
function TRunOptions.SetOption(const AName, AValue: string): Boolean;
begin
if AName = CBuildNam then
begin
if IndexOf(CBuilds, AValue) >= 0 then
begin
Options.Build := AValue;
Result := True;
Exit;
end;
end
else if AName = COSNam then
begin
if IndexOf(COSs, AValue) >= 0 then
begin
Options.OS := AValue;
Result := True;
Exit;
end;
end
else if AName = CX86Nam then
begin
if IndexOf(CX86s, AValue) >= 0 then
begin
Options.X86 := AValue;
Result := True;
Exit;
end;
end
else if AName = CInfoNam then
begin
if IndexOf(CInfos, AValue) >= 0 then
begin
Options.Info := StrToInt(AValue);
Result := True;
Exit;
end;
end
else if AName = CDMDNam then
begin
DMD := StripQuote(AValue);
Result := True;
Exit;
end
else if AName = CRunNam then
begin
Run := StripQuote(AValue);
Result := True;
Exit;
end;
Result := False;
end;
end.
|
unit InflatablesList_ItemShopTemplate_Base;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
InflatablesList_Types,
InflatablesList_ItemShop,
InflatablesList_ItemShopParsingSettings;
type
TILItemShopTemplate_Base = class(TObject)
protected
// internals
fStaticSettings: TILStaticManagerSettings;
// data
fName: String;
fShopName: String;
fUntracked: Boolean;
fAltDownMethod: Boolean;
fShopURL: String;
fParsingSettings: TILItemShopParsingSettings;
procedure SetStaticSettings(Value: TILStaticManagerSettings); virtual;
// data setters
procedure SetName(const Value: String); virtual;
procedure SetShopName(const Value: String); virtual;
procedure SetUntracked(const Value: Boolean); virtual;
procedure SetAltDownMethod(const Value: Boolean); virtual;
procedure SetShopURL(const Value: String); virtual;
procedure InitializeData; virtual;
procedure FinalizeData; virtual;
procedure Initialize; virtual;
procedure Finalize; virtual;
public
constructor Create; overload;
constructor Create(BaseOn: TILItemShop; UniqueCopy: Boolean); overload;
constructor CreateAsCopy(Source: TILItemShopTemplate_Base; UniqueCopy: Boolean);
destructor Destroy; override;
procedure CopyTo(Shop: TILItemShop); virtual;
property StaticSettings: TILStaticManagerSettings read fStaticSettings write SetStaticSettings;
property Name: String read fName write SetName;
property ShopName: String read fShopName write SetShopName;
property Untracked: Boolean read fUntracked write SetUntracked;
property AltDownMethod: Boolean read fAltDownMethod write SetAltDownMethod;
property ShopURL: String read fShopURL write SetShopURL;
property ParsingSettings: TILItemShopParsingSettings read fParsingSettings;
end;
implementation
uses
SysUtils,
InflatablesList_Utils;
procedure TILItemShopTemplate_Base.SetStaticSettings(Value: TILStaticManagerSettings);
begin
fStaticSettings := IL_ThreadSafeCopy(Value);
fParsingSettings.StaticSettings := fStaticSettings;
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_Base.SetName(const Value: String);
begin
If not IL_SameStr(fName,Value) then
begin
fName := Value;
UniqueString(fName);
fParsingSettings.TemplateReference := fName;
end;
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_Base.SetShopName(const Value: String);
begin
If not IL_SameStr(fShopName,Value) then
begin
fShopName := Value;
UniqueString(fShopName);
end;
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_Base.SetUntracked(const Value: Boolean);
begin
If fUntracked <> Value then
begin
fUntracked := Value;
end;
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_Base.SetAltDownMethod(const Value: Boolean);
begin
If fAltDownMethod <> Value then
begin
fAltDownMethod := Value;
end;
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_Base.SetShopURL(const Value: String);
begin
If not IL_SameStr(fShopURL,Value) then
begin
fShopURL := Value;
UniqueString(fShopURL);
end;
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_Base.InitializeData;
begin
fName := '';
fShopName := '';
fUntracked := False;
fAltDownMethod := False;
fShopURL := '';
fParsingSettings := TILItemShopParsingSettings.Create;
fParsingSettings.StaticSettings := fStaticSettings;
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_Base.FinalizeData;
begin
FreeAndNil(fParsingSettings);
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_Base.Initialize;
begin
FillChar(fStaticSettings,SizeOf(TILStaticManagerSettings),0);
InitializeData;
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_Base.Finalize;
begin
FinalizeData;
end;
//==============================================================================
constructor TILItemShopTemplate_Base.Create;
begin
inherited Create;
Initialize;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
constructor TILItemShopTemplate_Base.Create(BaseOn: TILItemShop; UniqueCopy: Boolean);
begin
inherited Create;
// do not call initialize
fStaticSettings := IL_ThreadSafeCopy(BaseOn.StaticSettings);
fName := BaseOn.Name;
UniqueString(fName);
fShopName := BaseOn.Name;
UniqueString(fShopName);
fUntracked := BaseOn.Untracked;
fAltDownMethod := BaseOn.AltDownMethod;
fShopURL := BaseOn.ShopURL;
UniqueString(fShopURL);
fParsingSettings := TILItemShopParsingSettings.CreateAsCopy(BaseOn.ParsingSettings,UniqueCopy);
fParsingSettings.TemplateReference := fName; // reference self
end;
//------------------------------------------------------------------------------
constructor TILItemShopTemplate_Base.CreateAsCopy(Source: TILItemShopTemplate_Base; UniqueCopy: Boolean);
begin
inherited Create;
// do not call initialize
fStaticSettings := IL_ThreadSafeCopy(Source.StaticSettings);
fName := Source.Name;
UniqueString(fName);
fShopName := Source.ShopName;
UniqueString(fShopName);
fUntracked := Source.Untracked;
fAltDownMethod := Source.AltDownMethod;
fShopURL := Source.ShopURL;
UniqueString(fShopURL);
fParsingSettings := TILItemShopParsingSettings.CreateAsCopy(Source.ParsingSettings,UniqueCopy);
// do not change anything else in parsing settings, leave it as direct copy
end;
//------------------------------------------------------------------------------
destructor TILItemShopTemplate_Base.Destroy;
begin
Finalize;
inherited;
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_Base.CopyTo(Shop: TILItemShop);
var
i: Integer;
begin
Shop.BeginUpdate;
try
Shop.Name := fShopName;
Shop.Untracked := fUntracked;
Shop.AltDownMethod := fAltDownMethod;
Shop.ShopURL := fShopURL;
// variables (copy only when destination is empty)
For i := 0 to Pred(Shop.ParsingSettings.VariableCount) do
If Length(Shop.ParsingSettings.Variables[i]) <= 0 then
Shop.ParsingSettings.Variables[i] := fParsingSettings.Variables[i];
// copy only reference to self, not actual parsing settings (objects)
Shop.ParsingSettings.TemplateReference := fName;
Shop.ParsingSettings.DisableParsingErrors := fParsingSettings.DisableParsingErrors;
finally
Shop.EndUpdate;
end;
end;
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics,
VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser,
VCL.TMSFNCMaps, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TFrmMain = class(TForm)
Map: TTMSFNCMaps;
Panel1: TPanel;
btnCloseBridge: TButton;
btnCloseAll: TButton;
btnAdd: TButton;
procedure FormCreate(Sender: TObject);
procedure btnCloseAllClick(Sender: TObject);
procedure btnCloseBridgeClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
private
{ Private declarations }
FBridgeID: String;
procedure AddPopups;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses Flix.Utils.Maps, IOUtils;
procedure TFrmMain.AddPopups;
var
LText: String;
begin
LText := '<center><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/GoldenGateBridge-001.jpg/320px-GoldenGateBridge-001.jpg" />' +
'<h1>Golden Gate Bridge</h1><p>Text about the bridge</p></center>';
FBridgeID := Map.ShowPopup(37.819722, -122.478611, LText );
LText := '<center><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Alcatraz_Island_as_seen_from_the_East.jpg/320px-Alcatraz_Island_as_seen_from_the_East.jpg" />' +
'<h1>Alcatraz Island</h1><p>Text about the island</p></center>';
Map.ShowPopup(37.826667, -122.422778, LText );
end;
procedure TFrmMain.btnAddClick(Sender: TObject);
begin
AddPopups;
end;
procedure TFrmMain.btnCloseAllClick(Sender: TObject);
begin
Map.CloseAllPopups;
end;
procedure TFrmMain.btnCloseBridgeClick(Sender: TObject);
begin
Map.ClosePopup(FBridgeID);
end;
procedure TFrmMain.FormCreate(Sender: TObject);
var
LKeys: TServiceAPIKeys;
begin
LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) );
try
Map.APIKey := LKeys.GetKey( msGoogleMaps );
finally
LKeys.Free;
end;
end;
end.
|
unit GLGizmoArv;
// Arvydas Juskevicius aka adirex
// arvydas@adirex.com
// original Still used by me.. ilh there is a component for D6 and up...
interface
uses
Winapi.OpenGL,
Winapi.OpenGLext,
System.SysUtils,
System.Classes,
GLVectorGeometry,
GLScene,
GLTexture,
OpenGLTokens,
GLVectorLists,
GLCrossPlatform,
GLContext,
GLSilhouette,
GLObjects,
GLColor,
GLRenderContextInfo,
GLState;
type
TGizmoArrowType = (gtAxisX, gtAxisY, gtAxisZ);
TGizmoCornerType = (gtPlaneXY, gtPlaneXZ, gtPlaneYZ);
TGLGizmoArrow = class(TGLQuadricObject)
private
FGizmoType: TGizmoArrowType;
FBottomRadius: Single;
FHeight: Single;
FArrowHeadHeight: Single;
FSelected: Boolean;
FSelectedColor: TGLColor;
procedure SetGizmoType(const Value: TGizmoArrowType);
procedure SetBottomRadius(const Value: Single);
procedure SetHeight(const Value: Single);
procedure SetArrowHeadHeight(const Value: Single);
procedure SetSelected(const Value: Boolean);
procedure SetSelectedColor(const Value: TGLColor);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure BuildList(var rci: TGLRenderContextInfo); override;
published
property GizmoType: TGizmoArrowType read FGizmoType write SetGizmoType;
property BottomRadius: Single read FBottomRadius write SetBottomRadius;
property Height: Single read FHeight write SetHeight;
property ArrowHeadHeight: Single read FArrowHeadHeight
write SetArrowHeadHeight;
property Selected: Boolean read FSelected write SetSelected;
property SelectedColor: TGLColor read FSelectedColor write SetSelectedColor;
end;
TGLGizmoCorner = class(TGLQuadricObject)
private
FGizmoType: TGizmoCornerType;
FHeight: Single;
FDistance: Single;
FSelected: Boolean;
FSelectedColor: TGLColor;
procedure SetGizmoType(const Value: TGizmoCornerType);
procedure SetHeight(const Value: Single);
procedure SetDistance(const Value: Single);
procedure SetSelected(const Value: Boolean);
procedure SetSelectedColor(const Value: TGLColor);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure BuildList(var rci: TGLRenderContextInfo); override;
published
property GizmoType: TGizmoCornerType read FGizmoType write SetGizmoType;
property Height: Single read FHeight write SetHeight;
property Distance: Single read FDistance write SetDistance;
property Selected: Boolean read FSelected write SetSelected;
property SelectedColor: TGLColor read FSelectedColor write SetSelectedColor;
end;
implementation
{ TGLGizmoArrow }
procedure TGLGizmoArrow.Assign(Source: TPersistent);
begin
inherited;
end;
procedure TGLGizmoArrow.BuildList(var rci: TGLRenderContextInfo);
var
color: TColorVector;
quadric: GLUquadricObj;
MultiplierX, MultiplierY, MultiplierZ: Byte;
begin // Shut up compuiler
MultiplierX := 1;
MultiplierY := 0;
MultiplierZ := 0;
case FGizmoType of
gtAxisX:
begin
color := clrRed;
MultiplierX := 1;
MultiplierY := 0;
MultiplierZ := 0;
end;
gtAxisY:
begin
color := clrGreen;
MultiplierX := 0;
MultiplierY := 1;
MultiplierZ := 0;
end;
gtAxisZ:
begin
color := clrBlue;
MultiplierX := 0;
MultiplierY := 0;
MultiplierZ := 1;
end;
end;
glDisable(GL_DEPTH_TEST);
glPushAttrib(GL_ENABLE_BIT or GL_CURRENT_BIT or GL_LIGHTING_BIT or
GL_LINE_BIT or GL_COLOR_BUFFER_BIT);
glDisable(GL_LIGHTING);
glEnable(GL_LINE_SMOOTH);
glLineWidth(1);
// ResetGLMaterialColors;
glColorMaterial(GL_FRONT, GL_EMISSION);
glEnable(GL_COLOR_MATERIAL);
if Selected then
begin
GL.Color4fv(SelectedColor.AsAddress);
end
else
begin
glColor4fv(@color);
end;
glBegin(GL_LINES);
glVertex3f(0, 0, 0);
glVertex3f((FHeight - FArrowHeadHeight) * MultiplierX,
(FHeight - FArrowHeadHeight) * MultiplierY, (FHeight - FArrowHeadHeight)*MultiplierZ);
glEnd;
glPushMatrix;
glColor4fv(@color);
quadric := gluNewQuadric();
SetupQuadricParams(PGLUQuadric(quadric));
case FGizmoType of
gtAxisX:
begin
glRotated(90, 0, 1, 0);
glTranslatef(0, 0, FHeight - FArrowHeadHeight); // {FHeight}0.2*0.5
end;
gtAxisY:
begin
glRotated(-90, 1, 0, 0);
glTranslatef(0, 0, FHeight - FArrowHeadHeight); // {FHeight}0.2*0.5
end;
gtAxisZ:
begin
glRotated(-90, 0, 0, 1);
glTranslatef(0, 0, FHeight - FArrowHeadHeight); // {FHeight}0.2*0.5
end;
end;
gluCylinder(quadric, BottomRadius, 0, FArrowHeadHeight, { Slices } 8, { Stacks } 2);
SetInvertedQuadricOrientation(PGLUQuadric(quadric));
// color := clrBlack;
glColor4fv(@color);
gluDisk(quadric, 0, BottomRadius, { Slices } 8, { FLoops } 1);
gluDeleteQuadric(quadric);
glPopMatrix;
glPopAttrib;
{ Switch back to the normal rendering mode }
glEnable(GL_DEPTH_TEST);
end;
constructor TGLGizmoArrow.Create(AOwner: TComponent);
begin
inherited;
FBottomRadius := 0.05;
FHeight := 1;
FArrowHeadHeight := 0.2;
ObjectStyle := ObjectStyle + [osDirectDraw];
FSelected := False;
FSelectedColor := TGLColor.Create(Self);
FSelectedColor.color := clrYellow;
end;
destructor TGLGizmoArrow.Destroy;
begin
FSelectedColor.Free;
inherited;
end;
procedure TGLGizmoArrow.SetArrowHeadHeight(const Value: TGLFloat);
begin
if FArrowHeadHeight <> Value then
begin
FArrowHeadHeight := Value;
StructureChanged;
end;
end;
procedure TGLGizmoArrow.SetBottomRadius(const Value: TGLFloat);
begin
if FBottomRadius <> Value then
begin
FBottomRadius := Value;
StructureChanged;
end;
end;
procedure TGLGizmoArrow.SetGizmoType(const Value: TGizmoArrowType);
begin
if FGizmoType <> Value then
begin
FGizmoType := Value;
StructureChanged;
end;
end;
procedure TGLGizmoArrow.SetHeight(const Value: TGLFloat);
begin
if FHeight <> Value then
begin
FHeight := Value;
StructureChanged;
end;
end;
procedure TGLGizmoArrow.SetSelected(const Value: Boolean);
begin
if FSelected <> Value then
begin
FSelected := Value;
NotifyChange(Self);
end;
end;
procedure TGLGizmoArrow.SetSelectedColor(const Value: TGLColor);
begin
FSelectedColor.color := Value.color;
NotifyChange(Self);
end;
{ TGLGizmoCorner }
procedure TGLGizmoCorner.Assign(Source: TPersistent);
begin
inherited;
end;
procedure TGLGizmoCorner.BuildList(var rci: TGLRenderContextInfo);
var
color: TColorVector;
MultiplierX, MultiplierY, MultiplierZ: Byte;
begin
glDisable(GL_DEPTH_TEST);
// Shut up compiler
MultiplierX := 1;
MultiplierY := 1;
MultiplierZ := 0;
case FGizmoType of
gtPlaneXY:
begin
MultiplierX := 1;
MultiplierY := 1;
MultiplierZ := 0;
end;
gtPlaneXZ:
begin
MultiplierX := 1;
MultiplierY := 0;
MultiplierZ := 1;
end;
gtPlaneYZ:
begin
MultiplierX := 0;
MultiplierY := 1;
MultiplierZ := 1;
end;
end;
glPushAttrib(GL_ENABLE_BIT or GL_CURRENT_BIT or GL_LIGHTING_BIT or
GL_LINE_BIT or GL_COLOR_BUFFER_BIT);
glDisable(GL_LIGHTING);
glEnable(GL_LINE_SMOOTH);
glLineWidth(1);
glColorMaterial(GL_FRONT, GL_EMISSION);
glEnable(GL_COLOR_MATERIAL);
if Selected then
begin
GL.Color4fv(SelectedColor.AsAddress);
end
else
begin
if MultiplierY = 1 then
begin
color := clrGreen;
glColor4fv(@color);
end
else
begin
color := clrBlue;
glColor4fv(@color);
end;
end;
glBegin(GL_LINES);
// x part of the corner
glVertex3f(FDistance * MultiplierX, FDistance * MultiplierY,
FDistance * MultiplierZ);
glVertex3f((FDistance - FHeight) * MultiplierX, FDistance * MultiplierY,
FDistance * MultiplierZ);
glEnd;
if Selected then
begin
GL.Color4fv(SelectedColor.AsAddress);
end
else
begin
if MultiplierX = 1 then
begin
color := clrRed;
glColor4fv(@color);
end
else
begin
color := clrBlue;
glColor4fv(@color);
end;
end;
glBegin(GL_LINES);
// y part of the corner
glVertex3f(FDistance * MultiplierX, FDistance * MultiplierY,
FDistance * MultiplierZ);
glVertex3f(FDistance * MultiplierX, (FDistance - FHeight) * MultiplierY,
FDistance * MultiplierZ);
glEnd;
if Selected then
begin
GL.Color4fv(SelectedColor.AsAddress);
end
else
begin
if MultiplierX = 1 then
begin
color := clrRed;
glColor4fv(@color);
end
else
begin
color := clrGreen;
glColor4fv(@color);
end;
end;
glBegin(GL_LINES);
// z part of the corner
glVertex3f(FDistance * MultiplierX, FDistance * MultiplierY,
FDistance * MultiplierZ);
glVertex3f(FDistance * MultiplierX, FDistance * MultiplierY,
(FDistance - FHeight) * MultiplierZ);
glEnd;
glPopAttrib;
{ Switch back to the normal rendering mode }
glEnable(GL_DEPTH_TEST);
end;
constructor TGLGizmoCorner.Create(AOwner: TComponent);
begin
inherited;
FHeight := 0.2;
FDistance := 1;
ObjectStyle := ObjectStyle + [osDirectDraw];
FSelectedColor := TGLColor.Create(Self);
FSelectedColor.color := clrYellow;
end;
destructor TGLGizmoCorner.Destroy;
begin
FSelectedColor.Free;
inherited;
end;
procedure TGLGizmoCorner.SetDistance(const Value: TGLFloat);
begin
if FDistance <> Value then
begin
FDistance := Value;
StructureChanged;
end;
end;
procedure TGLGizmoCorner.SetGizmoType(const Value: TGizmoCornerType);
begin
if FGizmoType <> Value then
begin
FGizmoType := Value;
StructureChanged;
end;
end;
procedure TGLGizmoCorner.SetHeight(const Value: TGLFloat);
begin
if FHeight <> Value then
begin
FHeight := Value;
StructureChanged;
end;
end;
procedure TGLGizmoCorner.SetSelected(const Value: Boolean);
begin
if FSelected <> Value then
begin
FSelected := Value;
NotifyChange(Self);
end;
end;
procedure TGLGizmoCorner.SetSelectedColor(const Value: TGLColor);
begin
FSelectedColor.color := Value.color;
NotifyChange(Self);
end;
end.
|
UNIT Parse;
{$H+}
INTERFACE
USES Scanner,
crt,
gsub,
param,
ar,
video,
estructura;
FUNCTION Parse_Ini_Interprete(VAR MyCollection: CollectionObject):boolean;
IMPLEMENTATION
PROCEDURE ERRORES(TL : TTipoToken ; TC : String);
BEGIN
IF TL = TOKEN_ID THEN BEGIN
writeln('Se esperaba "ID" y se encontro "',TC,'"');
END;
IF TL = TOKEN_FIGURAS THEN BEGIN
writeln('Se esperaba "FIGURAS" y se encontro "',TC,'"');
END;
IF TL = TOKEN_CORCHETE_A THEN BEGIN
writeln('Se esperaba "{" y se encontro "',TC,'"');
END;
IF TL = TOKEN_CORCHETE_C THEN BEGIN
writeln('Se esperaba "}" y se encontro "',TC,'"');
END;
IF TL = TOKEN_MARCADORES THEN BEGIN
writeln('Se esperaba "MARCADORES" y se encontro "',TC,'"');
END;
IF TL = TOKEN_ENTERO THEN BEGIN
writeln('Se esperaba "ENTERO" y se encontro "',TC,'"');
END;
END;
FUNCTION ExisteTabla(tb : CollectionObject;n:String):boolean;
VAR
I:INTEGER;
RESPUESTA:BOOLEAN;
BEGIN
I:=0;
RESPUESTA:=FALSE;
WHILE I< 10 DO BEGIN
IF n = Tb[I].name THEN BEGIN
RESPUESTA:= TRUE;
I:=11;
END
ELSE BEGIN
I:=I+1;
END;
END;
ExisteTabla:=RESPUESTA;
END;
FUNCTION Parse_Seccion_Marcadores(VAR A : CollectionObject): boolean;
var
ID : integer;
i : integer;
r, respuesta :boolean;
aux:String;
m:integer;
Table : CollectionObject;
BEGIN
i:=0;
Table:=A;
respuesta := ExisteTabla(Table,T.Cadena);
WHILE (T.Tipo = TOKEN_ID) and (not respuesta) DO BEGIN
m:=0;
ID := arLoadPatt(pchar('Data/patt.'+T.Cadena));
if ID < 0 THEN BEGIN
clrscr;
writeln('No Existe el Patron !!!');
halt(0);
END;
aux:=T.Cadena;
T:=Scannea;
IF T.Tipo = TOKEN_CORCHETE_A THEN BEGIN
T := Scannea;
CASE T.Tipo OF
TOKEN_CUBO : BEGIN
WHILE m< 10 DO BEGIN
IF Table[m].name_figure = 'cubo' THEN BEGIN
Table[m].id:=ID;
Table[m].name:=aux;
m:=11;
END
ELSE BEGIN
m:=m+1;
END;
END;
T := Scannea;
END;
TOKEN_TETERA : BEGIN
WHILE m< 10 DO BEGIN
IF Table[m].name_figure = 'tetera' THEN BEGIN
Table[m].id:=ID;
Table[m].name:=aux;
write(Table[m].name);
m:=11;
END
ELSE BEGIN
m:=m+1;
END;
END;
T := Scannea;
END;
TOKEN_ESFERA : BEGIN
WHILE m< 10 DO BEGIN
IF Table[m].name_figure = 'esfera' THEN BEGIN
Table[m].id:=ID;
Table[m].name:=aux;
write(Table[m].name);
m:=11;
END
ELSE BEGIN
m:=m+1;
END;
END;
T := Scannea;
END;
END;
IF T.Tipo = TOKEN_ENTERO THEN BEGIN
Table[i].marker_width:=80.0;
T:=Scannea;
IF T.Tipo = TOKEN_ENTERO THEN BEGIN Table[i].Marker_center[0]:=0.0;
T:=Scannea;
IF T.Tipo = TOKEN_ENTERO THEN BEGIN
Table[i].Marker_center[1]:=0.0;
T:=Scannea;
IF T.Tipo = TOKEN_CORCHETE_C THEN BEGIN
T:=Scannea;
write(T.Tipo);
write(T.Cadena);
END
ELSE BEGIN
r := false;
ERRORES(TOKEN_CORCHETE_C,T.Cadena);
END;
END
ELSE BEGIN
r := false;
ERRORES(TOKEN_ENTERO,T.Cadena);
END;
END
ELSE BEGIN
r := false;
ERRORES(TOKEN_ENTERO,T.Cadena);
END;
END
ELSE BEGIN
r := false;
ERRORES(TOKEN_ENTERO,T.Cadena);
END;
END
ELSE BEGIN
r:= false;
ERRORES(TOKEN_CORCHETE_A,T.Cadena);
END;
i:=i+1;
respuesta := ExisteTabla(Table,T.Cadena);
END;
A:=Table;
Parse_Seccion_Marcadores := r;
END;
FUNCTION Parse_Seccion_Figuras(VAR A : CollectionObject): boolean;
VAR
i : integer;
AF : CollectionObject;
r: boolean;
BEGIN
r:= true;
i:=0;
WHILE T.Tipo in [TOKEN_CUBO,TOKEN_TETERA,TOKEN_ESFERA] DO BEGIN
CASE T.Tipo OF
TOKEN_CUBO : BEGIN
AF[i].name_figure := T.Cadena;
AF[i].id_figure := i;
T := Scannea;
IF T.Tipo = TOKEN_ENTERO THEN BEGIN
AF[i].size_figure:=T.Valor;
T := Scannea;
END
ELSE BEGIN
r:= false;
ERRORES(T.Tipo, T.Cadena);
END;
END;
TOKEN_ESFERA : BEGIN
AF[i].name_figure := T.Cadena;
AF[i].id_figure := i;
T := Scannea;
IF T.Tipo = TOKEN_ENTERO THEN BEGIN
AF[i].size_figure := T.Valor;
T := Scannea;
IF T.Tipo = TOKEN_ENTERO THEN BEGIN
T := Scannea;
IF T.Tipo = TOKEN_ENTERO THEN BEGIN
T := Scannea;
END
ELSE BEGIN
r:= false;
ERRORES(T.Tipo, T.Cadena);
END;
END
ELSE BEGIN
r:= false;
ERRORES(T.Tipo, T.Cadena);
END;
END
ELSE BEGIN
r:= false;
ERRORES(T.Tipo, T.Cadena);
END;
END;
TOKEN_TETERA : BEGIN
AF[i].name_figure := T.Cadena;
AF[i].id_figure := i;
T := Scannea;
IF T.Tipo = TOKEN_ENTERO THEN BEGIN
AF[i].size_figure := T.Valor;
T := Scannea;
END
ELSE BEGIN
r:= false;
ERRORES(T.Tipo, T.Cadena);
END;
END;
END;
i:=i+1;
END;
A:=AF;
Parse_Seccion_Figuras := r;
END;
FUNCTION Parse_Ini_Interprete(VAR MyCollection : CollectionObject): boolean;
VAR
A : CollectionObject;
r : boolean;
BEGIN
avance := True;
T := Scannea;
IF T.Tipo = TOKEN_FIGURAS THEN BEGIN
T := Scannea;
IF T.Tipo = TOKEN_CORCHETE_A THEN BEGIN
T := Scannea;
IF Parse_Seccion_Figuras(A) THEN BEGIN
IF T.Tipo = TOKEN_CORCHETE_C THEN BEGIN
T := Scannea;
END
ELSE BEGIN
r := False;
ERRORES(TOKEN_CORCHETE_C,T.Cadena);
END;
END;
END
ELSE BEGIN
r := False;
ERRORES(TOKEN_CORCHETE_A,T.Cadena);
END;
IF T.Tipo = TOKEN_MARCADORES THEN BEGIN
T := Scannea;
IF T.Tipo = TOKEN_CORCHETE_A THEN BEGIN
T:=Scannea;
IF Parse_Seccion_Marcadores(A) THEN BEGIN
IF T.Tipo = TOKEN_CORCHETE_C THEN BEGIN
T := Scannea;
END
ELSE BEGIN
r:=False;
ERRORES(TOKEN_CORCHETE_C,T.Cadena);
END;
END;
END
ELSE BEGIN
r:= False;
ERRORES(TOKEN_CORCHETE_A,T.Cadena);
END;
END
ELSE BEGIN
r:= False;
ERRORES(TOKEN_MARCADORES,T.Cadena);
END;
END
ELSE BEGIN
r:= False;
ERRORES(TOKEN_FIGURAS,T.Cadena);
END;
MyCollection := A;
Parse_Ini_Interprete := r;
END;
END.
|
unit St_Services_Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxCheckBox, FIBQuery, pFIBQuery,
pFIBStoredProc, ActnList, FIBDataSet, pFIBDataSet, cxContainer, cxLabel,
ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid,
ImgList, ComCtrls, ToolWin, cxCalendar, cxTextEdit, Menus,
StdCtrls, cxCurrencyEdit, RxMenus, dxBar, dxStatusBar, AccMGMT,
St_Common_Types, St_Common_Funcs, st_ConstUnit, FIBDatabase, pFIBDatabase,
st_Common_Messages, st_consts_messages;
type
TfrmService_Main = class(TForm)
cxGrid1: TcxGrid;
cxGrid1DBTableView1: TcxGridDBTableView;
SERVICE_TITLE: TcxGridDBColumn;
SERVICE_SHIFR: TcxGridDBColumn;
cxGrid1Level1: TcxGridLevel;
WriteProc: TpFIBStoredProc;
ToolBar1: TToolBar;
AddButton: TToolButton;
EditButton: TToolButton;
DeleteButton: TToolButton;
RefreshButton: TToolButton;
ExitButton: TToolButton;
ImageListOfCategory: TImageList;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
ActionList1: TActionList;
AddAction: TAction;
EditAction: TAction;
DeleteAction: TAction;
RefreshAction: TAction;
ExitAction: TAction;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
SelectButton: TToolButton;
ImageList1: TImageList;
dxBarManager1: TdxBarManager;
PopupMenu1: TdxBarPopupMenu;
N1: TdxBarButton;
N2: TdxBarButton;
DeleteAction1: TdxBarButton;
RefreshAction1: TdxBarButton;
N3: TdxBarButton;
PopupImageList: TImageList;
PopupMenu2: TPopupMenu;
MenuItem1: TMenuItem;
MenuItem2: TMenuItem;
MenuItem3: TMenuItem;
MenuItem4: TMenuItem;
HotKey_StatusBar: TdxStatusBar;
Cash_Style: TcxStyle;
SelectAction: TAction;
WorkDatabase: TpFIBDatabase;
ServiceDataSet: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
ServiceDataSource: TDataSource;
StoredProc: TpFIBStoredProc;
Panel1: TPanel;
ToolBar2: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
cxGrid2: TcxGrid;
cxGridDBTableView1: TcxGridDBTableView;
cxGridDBColumn2: TcxGridDBColumn;
cxGridLevel1: TcxGridLevel;
cxGridDBTableView1DBColumn1: TcxGridDBColumn;
cxGridDBTableView1DBColumn2: TcxGridDBColumn;
ServiceDetailDataSet: TpFIBDataSet;
ServiceDetailDataSource: TDataSource;
act_name: TAction;
cxGridDBTableView1DBColumn3: TcxGridDBColumn;
Panel2: TPanel;
Label_razdel_title: TcxLabel;
Label_stat_title: TcxLabel;
SERVICE_SUMMA: TcxGridDBColumn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ExitButtonClick(Sender: TObject);
procedure DataSetAfterOpen(DataSet: TDataSet);
procedure cxGrid1DBTableView1DblClick(Sender: TObject);
procedure SelectButtonClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure ToolButton1Click(Sender: TObject);
procedure ToolButton2Click(Sender: TObject);
procedure ToolButton3Click(Sender: TObject);
procedure act_nameExecute(Sender: TObject);
procedure ServiceDetailDataSetAfterScroll(DataSet: TDataSet);
private
PLanguageIndex: byte;
procedure FormIniLanguage();
public
Res : Variant;
constructor Create(AParameter : TstSimpleParams);reintroduce;
end;
var
frmService_Main: TfrmService_Main;
implementation
uses St_Services_Edit, St_Services_Details;
{$R *.dfm}
constructor TfrmService_Main.Create(AParameter : TstSimpleParams);
begin
Inherited Create(AParameter.Owner);
self.FormStyle:=AParameter.FormStyle;
if self.FormStyle = fsNormal
then SelectButton.Visible := true;
WorkDatabase.Handle:=AParameter.Db_Handle;
ReadTransaction.StartTransaction;
RefreshButtonClick(self);
ServiceDetailDataSet.SelectSQL.Text:='select * from ST_SERVICE_DETAIL_SEL(:ID_SERVICE)';
end;
procedure TfrmService_Main.FormIniLanguage();
begin
// индекс языка (1-укр, 2 - рус)
PLanguageIndex:= stLanguageIndex;
//названия кнопок
ExitButton.Caption := st_ConstUnit.st_ExitBtn_Caption[PLanguageIndex];
ExitButton.Hint := st_ConstUnit.st_ExitBtn_Caption[PLanguageIndex];
AddButton.Caption := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
AddButton.Hint := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
ToolButton1.Caption := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
ToolButton1.Hint := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
EditButton.Caption := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
EditButton.Hint := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
ToolButton2.Caption := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
ToolButton2.Hint := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
DeleteButton.Caption := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
DeleteButton.Hint := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
ToolButton3.Caption := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
ToolButton3.Hint := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
RefreshButton.Caption := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex];
RefreshButton.Hint := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex];
SelectButton.Caption := st_ConstUnit.st_Select_Caption[PLanguageIndex];
SelectButton.Hint := st_ConstUnit.st_Select_Caption[PLanguageIndex];
HotKey_StatusBar.Panels[0].Text:= st_ConstUnit.st_InsertBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
HotKey_StatusBar.Panels[1].Text:= st_ConstUnit.st_EditBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
HotKey_StatusBar.Panels[2].Text:= st_ConstUnit.st_DeleteBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
HotKey_StatusBar.Panels[3].Text:= st_ConstUnit.st_RefreshBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex];
HotKey_StatusBar.Panels[4].Text:= st_ConstUnit.st_Select_Caption[PLanguageIndex] + st_ConstUnit.st_EnterBtn_ShortCut[PLanguageIndex];
HotKey_StatusBar.Panels[5].Text:= st_ConstUnit.st_ExitBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_ExitBtn_Caption[PLanguageIndex];
HotKey_StatusBar.Hint := st_ConstUnit.st_HotKeys[PLanguageIndex];
// пошел грид
SERVICE_TITLE.Caption := st_ConstUnit.st_NameLable[PLanguageIndex];
MenuItem1.Caption := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
MenuItem2.Caption := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
MenuItem3.Caption := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
MenuItem4.Caption := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex];
MenuItem1.Hint := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
MenuItem2.Hint := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
MenuItem3.Hint := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
MenuItem4.Hint := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex];
Label_razdel_title.Caption := st_ConstUnit.st_razdel[PLanguageIndex];
Label_stat_title.Caption := st_ConstUnit.st_stat[PLanguageIndex];
end;
procedure TfrmService_Main.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TfrmService_Main.FormShow(Sender: TObject);
begin
cxGrid1.SetFocus;
end;
procedure TfrmService_Main.FormCreate(Sender: TObject);
begin
FormIniLanguage();
end;
procedure TfrmService_Main.ExitButtonClick(Sender: TObject);
begin
Close;
end;
procedure TfrmService_Main.DataSetAfterOpen(DataSet: TDataSet);
begin
if (DataSet.RecordCount=0)
then begin
EditButton.Enabled := false;
DeleteButton.Enabled := false;
end
else begin
EditButton.Enabled := true;
DeleteButton.Enabled := true;
end;
end;
procedure TfrmService_Main.cxGrid1DBTableView1DblClick(Sender: TObject);
begin
SelectButtonClick(self)
end;
procedure TfrmService_Main.SelectButtonClick(Sender: TObject);
begin
If ServiceDataSet.RecordCount = 0 then Exit;
Res := VarArrayOf([ServiceDataSet.FieldByName('ID_SERVICE').value,
ServiceDataSet.FieldByName('SERVICE_TITLE').value,
ServiceDataSet.FieldByName('SERVICE_SHIFR').value,
// ServiceDataSet.FieldByName('ID_SERVICE_TYPE').value,
ServiceDetailDataSet.FieldByName('ST_OPTIONS').Value]);
ModalResult := mrOk;
end;
procedure TfrmService_Main.RefreshButtonClick(Sender: TObject);
var
id : integer;
begin
if ServiceDataSet.RecordCount > 0 then id := ServiceDataSet.FieldByName('ID_SERVICE').Value;
ServiceDataSet.Close;
ServiceDataSet.SelectSQL.Text:='select * from ST_SP_SERVICE_SEL';
ServiceDataSet.Open;
ServiceDataSet.Locate('ID_SERVICE',id,[]);
end;
procedure TfrmService_Main.AddButtonClick(Sender: TObject);
var T: TfrmServiceEdit;
id:Integer;
begin
T:=TfrmServiceEdit.Create(self);
T.ComboBox_type.ItemIndex:=0;
if T.ShowModal = mrOk then
begin
StoredProc.StoredProcName:='ST_SP_SERVICE_INS';
StoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('SERVICE_TITLE').Value:=T.cxTextEdit1.Text;
StoredProc.ParamByName('SERVICE_SHIFR').Value:=T.cxTextEdit2.Text;
StoredProc.ParamByName('ID_SERVICE_TYPE').Value:=T.ComboBox_type.ItemIndex + 1;
StoredProc.ExecProc;
ID:=StoredProc.ParamByName('ID_SERVICE').Value;
WriteTransaction.Commit;
RefreshButtonClick(self);
ServiceDataSet.Locate('ID_SERVICE',id,[]);
end;
T.Free;
end;
procedure TfrmService_Main.EditButtonClick(Sender: TObject);
var T: TfrmServiceEdit;
id:integer;
begin
if (ServiceDataSet.RecordCount = 0) then Exit;
T:=TfrmServiceEdit.Create(self);
t.cxTextEdit1.Text:=ServiceDataSet.FieldByName('SERVICE_TITLE').Value;
t.cxTextEdit2.Text:=ServiceDataSet.FieldByName('SERVICE_SHIFR').Value;
T.ComboBox_type.ItemIndex:= ServiceDataSet.FieldByName('ID_SERVICE_TYPE').Value-1;
ID:=ServiceDataSet.FieldByName('ID_SERVICE').Value;
if T.ShowModal = mrOk then
begin
StoredProc.StoredProcName:='ST_SP_SERVICE_UPD';
StoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('ID_SERVICE').Value :=id;
StoredProc.ParamByName('SERVICE_TITLE').Value:=T.cxTextEdit1.Text;
StoredProc.ParamByName('SERVICE_SHIFR').Value:=T.cxTextEdit2.Text;
StoredProc.ParamByName('ID_SERVICE_TYPE').Value:=T.ComboBox_type.ItemIndex + 1;
StoredProc.ExecProc;
WriteTransaction.Commit;
RefreshButtonClick(self);
ServiceDataSet.Locate('ID_SERVICE',id,[]);
end;
T.Free;
end;
procedure TfrmService_Main.DeleteButtonClick(Sender: TObject);
var
ID : Integer;
i : Integer;
begin
if ServiceDataSet.RecordCount=0 then Exit;
i:= st_Common_Messages.stShowMessage(st_Confirmation_Caption[PLanguageIndex], st_warning_Delete[PLanguageIndex], mtConfirmation, [mbYes, mbNo]);
if ((i = 7) or (i= 2)) then exit;
ID:=ServiceDataSet.FieldByName('ID_SERVICE').Value;
StoredProc.StoredProcName:='ST_SP_SERVICE_DEL';
StoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('ID_SERVICE').Value := id;
StoredProc.ExecProc;
WriteTransaction.Commit;
ServiceDataSet.CacheDelete;
end;
procedure TfrmService_Main.ToolButton1Click(Sender: TObject);
var
T, T2 : TfrmServiceDetail;
id : Integer;
begin
if ServiceDataSet.RecordCount = 0 then Exit;
T:=TfrmServiceDetail.Create(self, date,date, WorkDatabase.Handle);
if T.ShowModal = mrOk then
begin
try
StoredProc.StoredProcName:='ST_SERVICE_DETAIL_INS';
StoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('ID_SERVICE').Value := ServiceDataSet.FieldByName('ID_SERVICE').Value;
StoredProc.ParamByName('DATE_BEG').Value := T.DateBeg;
StoredProc.ParamByName('DATE_END').Value := T.DateEnd;
StoredProc.ParamByName('ID_RAZD_ST').Value := T.ID_RAZD_ST;
if T.without_pdv.Checked
then StoredProc.ParamByName('ST_OPTIONS').Value := 0;
if T.with_pdv.Checked
then StoredProc.ParamByName('ST_OPTIONS').Value := 1;
StoredProc.ExecProc;
id := StoredProc.ParamByName('ID_SERVICE_DETAIL').Value;
if ((T.with_pdv.Checked) or (T.pdv.Checked)) then
Begin
If T.with_pdv.Checked then ShowMessage('Необхідно додати статтю для ПДВ');
T2 := TfrmServiceDetail.Create(self, date,date, WorkDatabase.Handle);
T2.without_pdv.Enabled := False;
If T.with_pdv.Checked then
Begin
T2.with_pdv.Enabled := False;
T2.pdv.Checked := True;
End
else
begin
T2.pdv.Enabled := False;
T2.with_pdv.Checked := True;
end;
If T2.ShowModal = mrOk then
Begin
StoredProc.StoredProcName:='ST_SERVICE_DETAIL_INS';
StoredProc.Transaction := WriteTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('ID_SERVICE').Value := ServiceDataSet.FieldByName('ID_SERVICE').Value;
StoredProc.ParamByName('DATE_BEG').Value := T2.DateBeg;
StoredProc.ParamByName('DATE_END').Value := T2.DateEnd;
StoredProc.ParamByName('ID_RAZD_ST').Value := T2.ID_RAZD_ST;
StoredProc.ParamByName('ST_OPTIONS').Value := 2;
StoredProc.ExecProc;
id := StoredProc.ParamByName('ID_SERVICE_DETAIL').Value;
End
else
begin
WriteTransaction.Rollback;
T2.Free;
T.Free;
Exit;
end;
T2.free;
End;
WriteTransaction.Commit;
cxGrid2.BeginUpdate;
ServiceDetailDataSet.CloseOpen(true);
ServiceDetailDataSet.Locate('ID_SERVICE_DETAIL',id,[]);
cxGrid2.EndUpdate;
except on E:Exception do
begin
WriteTransaction.Rollback;
ShowMessage(E.Message);
ServiceDetailDataSet.CloseOpen(true);
end;
end;
end;
T.Free;
end;
procedure TfrmService_Main.ToolButton2Click(Sender: TObject);
var T:TfrmServiceDetail;
id:Integer;
begin
if ServiceDataSet.RecordCount > 0 then
begin
T := TfrmServiceDetail.Create(self, ServiceDetailDataSet.FieldByName('DATE_BEG').Value ,
ServiceDetailDataSet.FieldByName('DATE_END').Value,
WorkDatabase.Handle);
if ServiceDetailDataSet.FieldByName('ST_OPTIONS').Value = 0
then T.without_pdv.Checked := True;
if ServiceDetailDataSet.FieldByName('ST_OPTIONS').Value = 1
then T.with_pdv.Checked := True;
if ServiceDetailDataSet.FieldByName('ST_OPTIONS').Value = 2 then
Begin
T.pdv.Checked := True;
T.pdv.Enabled := True;
End;
T.cxButtonEdit1.Text:=ServiceDetailDataSet.FieldByName('RZ_NUM').AsString+'/'+ServiceDetailDataSet.FieldByName('ST_NUM').AsString;
T.id_razd_st:=ServiceDetailDataSet.FieldByName('ID_RAZD_ST').Value;
if T.ShowModal = mrOk then
begin
try
StoredProc.StoredProcName:='ST_SERVICE_DETAIL_UPD';
StoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('ID_SERVICE').Value :=ServiceDataSet.FieldByName('ID_SERVICE').Value;
id:=ServiceDetailDataSet.FieldByName('ID_SERVICE_DETAIL').Value;
StoredProc.ParamByName('ID_SERVICE_DETAIL').Value :=id;
StoredProc.ParamByName('DATE_BEG').Value :=T.DateBeg;
StoredProc.ParamByName('DATE_END').Value :=T.DateEnd;
StoredProc.ParamByName('ID_RAZD_ST').Value :=T.ID_RAZD_ST;
if T.without_pdv.Checked
then StoredProc.ParamByName('ST_OPTIONS').Value := 0;
if T.with_pdv.Checked
then StoredProc.ParamByName('ST_OPTIONS').Value := 1;
if T.pdv.Checked
then StoredProc.ParamByName('ST_OPTIONS').Value := 2;
StoredProc.ExecProc;
WriteTransaction.Commit;
cxGrid2.BeginUpdate;
ServiceDetailDataSet.CloseOpen(true);
ServiceDetailDataSet.Locate('ID_SERVICE_DETAIL',id,[]);
cxGrid2.EndUpdate;
except on E:Exception do
begin
ShowMessage(E.Message);
ServiceDetailDataSet.CloseOpen(true);
end;
end;
end;
T.Free;
end;
end;
procedure TfrmService_Main.ToolButton3Click(Sender: TObject);
var ID:Integer;
begin
if (ServiceDetailDataSet.RecordCount>0)
then begin
if Application.MessageBox('Ви дійсно бажаете видалити запис?',
'Увага!', MB_YESNO + MB_ICONQUESTION) = IDYES
then begin
ID:=ServiceDetailDataSet.FieldByName('ID_SERVICE_DETAIL').Value;
StoredProc.StoredProcName:='ST_SERVICE_DETAIL_DEL';
StoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('ID_SERVICE_DETAIL').Value :=id;
StoredProc.ExecProc;
WriteTransaction.Commit;
ServiceDetailDataSet.CacheDelete;
end;
end;
end;
procedure TfrmService_Main.act_nameExecute(Sender: TObject);
begin
Load_Help(self, WorkDatabase.Handle, 'sp_services');
end;
procedure TfrmService_Main.ServiceDetailDataSetAfterScroll(
DataSet: TDataSet);
begin
if not(VarIsNull(ServiceDetailDataSet['RZ_TITLE'])) then
Label_razdel_title.Caption := st_ConstUnit.st_razdel[PLanguageIndex] + ': ' + ServiceDetailDataSet['RZ_TITLE'];
if not(VarIsNull( ServiceDetailDataSet['ST_TITLE'])) then
Label_stat_title.Caption := st_ConstUnit.st_stat[PLanguageIndex] + ': ' + ServiceDetailDataSet['ST_TITLE'];
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.