text stringlengths 14 6.51M |
|---|
{------------------------------------
功能说明:服务信息接口
创建日期:2014/08/04
作者:mx
版权:mx
-------------------------------------}
unit uSvcInfoIntf;
interface
type
ISvcInfo = interface
['{A4AC764B-1306-4FC3-9A0F-524B25C56992}']
function GetModuleName: string;
function GetTitle: string;
function GetVersion: string;
function GetComments: string;
end;
implementation
end.
|
unit Lib.JSONStore;
interface
uses
System.Types,
System.SysUtils,
System.IOUtils,
System.Classes,
System.JSON,
Lib.JSONUtils,
Lib.JSONFormat;
type
TJSONStore = class
private type
TStoreSource = (None,Owned,NewFile,ExistingFile,BadFile);
private
FStoreSource: TStoreSource;
FObject: TJSONObject;
FStoreFileName: string;
procedure CreateStore;
function GetValue<T>(jsRoot: TJSONObject; const Name: string; out Value: T): Boolean;
public
procedure WriteString(const Name: string; const Value: string);
function ReadString(const Name: string; const DefaultValue: string=''): string;
procedure WriteInteger(const Name: string; Value: Integer);
function ReadInteger(const Name: string; DefaultValue: Integer=0): Integer;
procedure WriteDouble(const Name: string; Value: Double);
function ReadDouble(const Name: string; DefaultValue: Double=0): Double;
procedure WriteBool(const Name: string; Value: Boolean);
function ReadBool(const Name: string; DefaultValue: Boolean=False): Boolean;
procedure WriteStrings(const Name: string; Strings: TStrings);
procedure ReadStrings(const Name: string; Strings: TStrings);
procedure WriteRect(const Name: string; const Rect: TRect);
function ReadRect(const Name: string; const DefaultRect: TRect): TRect;
procedure WriteJSON(const Name: string; jsValue: TJSONValue);
function ReadJSON(const Name: string): TJSONValue;
procedure Remove(const Name: string);
procedure Flush;
constructor Create(const StoreFileName: string); overload;
constructor Create(jsRoot: TJSONObject); overload;
destructor Destroy; override;
end;
implementation
constructor TJSONStore.Create(const StoreFileName: string);
begin
FStoreSource:=TStoreSource.None;
FObject:=nil;
FStoreFileName:=StoreFileName;
end;
constructor TJSONStore.Create(jsRoot: TJSONObject);
begin
FStoreSource:=TStoreSource.Owned;
FObject:=jsRoot;
end;
destructor TJSONStore.Destroy;
begin
Flush;
if FStoreSource<>TStoreSource.Owned then
FreeAndNil(FObject);
end;
procedure TJSONStore.CreateStore;
begin
if FStoreSource=TStoreSource.None then
begin
if FileExists(FStoreFileName) then
begin
FObject:=TJSONObject.ParseJSONValue(TFile.ReadAllText(FStoreFileName)) as TJSONObject;
if Assigned(FObject) then
FStoreSource:=TStoreSource.ExistingFile
else
FStoreSource:=TStoreSource.BadFile;
end else
FStoreSource:=TStoreSource.NewFile;
if not Assigned(FObject) then
FObject:=TJSONObject.Create;
if FStoreSource=TStoreSource.BadFile then
raise EJSONException.Create('json format error (fix or delete the file): '+FStoreFileName);
end;
end;
procedure TJSONStore.Flush;
begin
if FStoreSource in [TStoreSource.NewFile,TStoreSource.ExistingFile] then
TFile.WriteAllText(FStoreFileName,ToJSON(FObject,True),TEncoding.ANSI);
end;
function TJSONStore.GetValue<T>(jsRoot: TJSONObject; const Name: string; out Value: T): Boolean;
var jsObject: TJSONObject; PairName: string;
begin
Result:=
JSONTryGetObject(jsRoot,Name,jsObject,PairName,False) and
jsObject.TryGetValue(PairName,Value);
end;
procedure TJSONStore.Remove(const Name: string);
var jsObject: TJSONObject; PairName: string;
begin
CreateStore;
if JSONTryGetObject(FObject,Name,jsObject,PairName,False) then
jsObject.RemovePair(PairName).Free;
end;
procedure TJSONStore.WriteString(const Name: string; const Value: string);
begin
CreateStore;
JSONSetValue(FObject,Name,TJSONString.Create(Value));
end;
function TJSONStore.ReadString(const Name: string; const DefaultValue: string=''): string;
var jsValue: TJSONValue;
begin
CreateStore;
Result:=DefaultValue;
if GetValue(FObject,Name,jsValue) then
Result:=jsValue.GetValue<string>;
end;
procedure TJSONStore.WriteInteger(const Name: string; Value: Integer);
begin
CreateStore;
JSONSetValue(FObject,Name,TJSONNumber.Create(Value));
end;
function TJSONStore.ReadInteger(const Name: string; DefaultValue: Integer=0): Integer;
var jsValue: TJSONValue;
begin
CreateStore;
Result:=DefaultValue;
if GetValue(FObject,Name,jsValue) then
Result:=jsValue.GetValue<Integer>;
end;
procedure TJSONStore.WriteDouble(const Name: string; Value: Double);
begin
CreateStore;
JSONSetValue(FObject,Name,TJSONNumber.Create(Value));
end;
function TJSONStore.ReadDouble(const Name: string; DefaultValue: Double=0): Double;
var jsValue: TJSONValue;
begin
CreateStore;
Result:=DefaultValue;
if GetValue(FObject,Name,jsValue) then
Result:=jsValue.GetValue<Double>;
end;
procedure TJSONStore.WriteBool(const Name: string; Value: Boolean);
const V:array[Boolean] of Integer=(0,1);
begin
WriteInteger(Name,V[Value]);
end;
function TJSONStore.ReadBool(const Name: string; DefaultValue: Boolean=False): Boolean;
const V:array[Boolean] of Integer=(0,1);
begin
Result:=ReadInteger(Name,V[DefaultValue])=1;
end;
procedure TJSONStore.WriteStrings(const Name: string; Strings: TStrings);
begin
CreateStore;
JSONSetValue(FObject,Name,JSONStringsToArray(Strings));
end;
procedure TJSONStore.ReadStrings(const Name: string; Strings: TStrings);
var jsArray: TJSONArray; jsValue: TJSONValue;
begin
CreateStore;
if GetValue(FObject,Name,jsArray) then
for jsValue in jsArray do Strings.Add(jsValue.GetValue<string>);
end;
procedure TJSONStore.WriteRect(const Name: string; const Rect: TRect);
var jsObject: TJSONObject; PairName: string; jsPair: TJSONPair;
begin
CreateStore;
if JSONTryGetObject(FObject,Name+'.',jsObject,PairName,True) then
JSONSetRect(jsObject,Rect)
else
JSONSetValue(FObject,Name,JSONRectToObject(Rect));
end;
function TJSONStore.ReadRect(const Name: string; const DefaultRect: TRect): TRect;
var jsRect: TJSONObject;
begin
CreateStore;
Result:=DefaultRect;
if GetValue(FObject,Name,jsRect) then Result:=JSONObjectToRect(jsRect,Result);
end;
procedure TJSONStore.WriteJSON(const Name: string; jsValue: TJSONValue);
begin
CreateStore;
JSONSetValue(FObject,Name,jsValue);
end;
function TJSONStore.ReadJSON(const Name: string): TJSONValue;
var jsValue: TJSONValue;
begin
CreateStore;
Result:=nil;
if GetValue(FObject,Name,jsValue) then
Result:=jsValue.GetValue<TJSONValue>;
end;
end.
|
unit DSA.List_Stack_Queue.LinkedList;
interface
uses
System.SysUtils,
System.Rtti,
System.Generics.Defaults;
type
TLinkedList<T> = class
private type
TNode = class
public
Elment: T;
Next: TNode;
constructor Create(newElment: T; newNext: TNode = nil); overload;
constructor Create(); overload;
function ToString: string; override;
end;
TComparer_T = TComparer<T>;
var
__dummyHead: TNode;
__size: integer;
public
/// <summary> 获取链表中的元素个数 </summary>
function GetSize: integer;
/// <summary> 返回链表是否为空 </summary>
function IsEmpty: Boolean;
/// <summary> 链表的index(0-based)位置中添加新的元素e </summary>
procedure Add(index: integer; e: T);
/// <summary> 在链表头添加新的元素e </summary>
procedure AddFirst(e: T);
/// <summary> 在链表末尾添加新的元素e </summary>
procedure AddLast(e: T);
/// <summary> 获取链表index(0-based)位置中的元素e </summary>
function Get(index: integer): T;
/// <summary> 获取链表(0-based)第一个元素 e </summary>
function GetFirst(): T;
/// <summary> 获取链表(0-based)最后一个元素e </summary>
function GetLast(): T;
/// <summary> 修改链表所有 d 元素为 e </summary>
procedure SetElment(d, e: T);
/// <summary> 修改链表index(0-based)位置中的元素e </summary>
procedure Set_(index: integer; e: T);
/// <summary> 查找链表中是否有元素e </summary>
function Contains(e: T): Boolean;
/// <summary> 删除链表index(0-based)位置的元素e, 返回链表删除元素 </summary>
function Remove(index: integer): T;
/// <summary> 删除链表(0-based)第一个位置的元素e,返回链表删除元素 </summary>
function RemoveFirst(): T;
/// <summary> 删除链表index(0-based)最后一个位置的元素e,返回链表删除元素 </summary>
function RemoveLast(): T;
/// <summary> 删除链表所有为e的元素 </summary>
procedure RemoveElement(e: T);
function ToString: string; override;
property Items[i: integer]: T read Get write Set_; default;
constructor Create;
destructor Destroy; override;
end;
procedure Main;
implementation
type
TLinkedList_int = TLinkedList<integer>;
procedure Main;
var
LinkedList: TLinkedList_int;
i: integer;
begin
LinkedList := TLinkedList_int.Create;
for i := 0 to 9 do
begin
LinkedList.AddFirst(i mod 2);
Writeln(LinkedList.ToString);
end;
LinkedList.Add(2, 666);
Writeln(LinkedList.ToString);
LinkedList.Remove(2);
Writeln(LinkedList.ToString);
LinkedList.RemoveFirst;
Writeln(LinkedList.ToString);
LinkedList.RemoveLast;
Writeln(LinkedList.ToString);
LinkedList.SetElment(1, 9);
Writeln(LinkedList.ToString);
end;
{ TLinkedList<T>.TNode }
constructor TLinkedList<T>.TNode.Create(newElment: T; newNext: TNode);
begin
Elment := newElment;
Next := newNext;
end;
constructor TLinkedList<T>.TNode.Create;
begin
Self.Create(default (T));
end;
function TLinkedList<T>.TNode.ToString: string;
var
value: TValue;
res: string;
begin
TValue.Make(@Self.Elment, TypeInfo(T), value);
if not(value.IsObject) then
res := value.ToString
else
res := value.AsObject.ToString;
Result := res;
end;
{ TLinkedList<T> }
procedure TLinkedList<T>.Add(index: integer; e: T);
var
prev: TNode;
i: integer;
begin
if (index < 0) or (index > __size) then
raise Exception.Create('Add failed. Index is Illegal.');
prev := __dummyHead;
for i := 0 to index - 1 do
prev := prev.Next;
// node := TNode.Create(e);
// node.FNext = prev.FNext;
// prev.FNext = node;
// 以上三句等同于下面一句
prev.Next := TNode.Create(e, prev.Next);
Inc(Self.__size);
end;
procedure TLinkedList<T>.AddFirst(e: T);
begin
Add(0, e);
end;
procedure TLinkedList<T>.AddLast(e: T);
begin
Add(__size, e);
end;
function TLinkedList<T>.Contains(e: T): Boolean;
var
cur: TNode;
comparer: IComparer<T>;
begin
cur := __dummyHead.Next;
Result := False;
comparer := TComparer_T.Default;
while cur <> nil do
begin
if comparer.Compare(cur.Elment, e) = 0 then
Result := True;
cur := cur.Next;
end;
end;
constructor TLinkedList<T>.Create;
begin
__dummyHead := TNode.Create();
__size := 0;
end;
destructor TLinkedList<T>.Destroy;
var
delNode, cur: TNode;
begin
cur := __dummyHead;
while cur <> nil do
begin
delNode := cur;
cur := cur.Next;
FreeAndNil(delNode);
end;
inherited;
end;
function TLinkedList<T>.Get(index: integer): T;
var
cur: TNode;
i: integer;
begin
if (index < 0) or (index >= __size) then
raise Exception.Create('Get failed. Index is Illegal.');
cur := __dummyHead.Next;
for i := 0 to index - 1 do
cur := cur.Next;
Result := cur.Elment;
end;
function TLinkedList<T>.GetFirst: T;
begin
Result := Get(0);
end;
function TLinkedList<T>.GetLast: T;
begin
Result := Get(__size - 1);
end;
function TLinkedList<T>.GetSize: integer;
begin
Result := __size;
end;
function TLinkedList<T>.IsEmpty: Boolean;
begin
Result := __size = 0;
end;
function TLinkedList<T>.Remove(index: integer): T;
var
prev: TNode;
i: integer;
res: TNode;
begin
if (index < 0) or (index >= __size) then
raise Exception.Create('Remove failed. Index is Illegal.');
prev := __dummyHead;
for i := 0 to index - 1 do
prev := prev.Next;
res := prev.Next;
prev.Next := res.Next;
Dec(__size);
Result := res.Elment;
FreeAndNil(res);
end;
procedure TLinkedList<T>.RemoveElement(e: T);
var
comparer: IComparer<T>;
prev, del: TNode;
begin
prev := __dummyHead;
comparer := TComparer_T.Default;
while prev.Next <> nil do
begin
if comparer.Compare(prev.Next.Elment, e) = 0 then
begin
del := prev.Next;
prev.Next := del.Next;
Dec(__size);
FreeAndNil(del);
end
else
begin
prev := prev.Next;
end;
end;
end;
function TLinkedList<T>.RemoveFirst: T;
begin
Result := Remove(0);
end;
function TLinkedList<T>.RemoveLast: T;
begin
Result := Remove(__size - 1);
end;
procedure TLinkedList<T>.SetElment(d, e: T);
var
cur: TNode;
comparer: IComparer<T>;
begin
cur := __dummyHead.Next;
comparer := TComparer_T.Default;
while cur <> nil do
begin
if comparer.Compare(cur.Elment, d) = 0 then
cur.Elment := e;
cur := cur.Next;
end;
end;
procedure TLinkedList<T>.Set_(index: integer; e: T);
var
cur: TNode;
i: integer;
begin
if (index < 0) or (index >= __size) then
raise Exception.Create('Set failed. Index is Illegal.');
cur := __dummyHead.Next;
for i := 0 to index - 1 do
cur := cur.Next;
cur.Elment := e;
end;
function TLinkedList<T>.ToString: string;
var
res: TStringBuilder;
cur: TNode;
begin
res := TStringBuilder.Create;
try
cur := __dummyHead.Next;
while cur <> nil do
begin
res.Append(cur.ToString + ' -> ');
cur := cur.Next;
end;
res.Append('nil');
Result := res.ToString;
finally
res.Free;
end;
end;
end.
|
unit uFormDBPreviewSettings;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.StdCtrls,
Vcl.Imaging.jpeg,
Dmitry.Controls.Base,
Dmitry.Controls.WebLink,
UnitDBDeclare,
uMemory,
uDBForm,
uDBManager,
uDBContext,
uDBEntities,
uJpegUtils,
uBitmapUtils,
uResources,
uInterfaces,
uFormInterfaces,
uCollectionEvents,
uTranslateUtils;
type
TFormDBPreviewSize = class(TDBForm, IFormCollectionPreviewSettings)
LbDatabaseSize: TLabel;
LbSingleImageSize: TLabel;
LbDBImageSize: TLabel;
LbDBImageQuality: TLabel;
WlPreviewDBSize: TWebLink;
CbDBImageSize: TComboBox;
CbDBJpegquality: TComboBox;
WlPreviewDBJpegQuality: TWebLink;
BtnOk: TButton;
BtnCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure WlPreviewDBSizeClick(Sender: TObject);
procedure CbDBImageSizeChange(Sender: TObject);
procedure CbDBJpegqualityChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
procedure BtnOkClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
FContext: IDBContext;
FMediaRepository: IMediaRepository;
FSettingsRepository: ISettingsRepository;
FSampleImage: TJpegImage;
FMediaCount: Integer;
FCollectionSettings: TSettings;
procedure FillImageSize(Combo: TComboBox);
procedure FillImageQuality(Combo: TComboBox);
procedure ShowPreview(Graphic: TGraphic; Size: Int64);
function HintCheck(Info: TMediaItem): Boolean;
procedure UpdateDBSize;
protected
{ Protected declarations }
function GetFormID: string; override;
procedure LoadLanguage;
public
{ Public declarations }
function Execute(CollectionFileName: string): Boolean;
end;
implementation
uses
UnitHintCeator;
{$R *.dfm}
procedure TFormDBPreviewSize.BtnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFormDBPreviewSize.BtnOkClick(Sender: TObject);
var
Settings: TSettings;
Info: TEventValues;
begin
Settings := FSettingsRepository.Get;
try
if Settings.ThSize <> FCollectionSettings.ThSize then
FMediaRepository.RefreshImagesCache;
FSettingsRepository.Update(FCollectionSettings);
CollectionEvents.DoIDEvent(Self, 0, [EventID_Param_DB_Changed], Info);
finally
F(Settings);
end;
Close;
end;
procedure TFormDBPreviewSize.CbDBImageSizeChange(Sender: TObject);
begin
FCollectionSettings.ThSize := Max(50, Min(500, StrToIntDef(CbDBImageSize.Text, 200)));
UpdateDBSize;
end;
procedure TFormDBPreviewSize.CbDBJpegqualityChange(Sender: TObject);
begin
FCollectionSettings.DBJpegCompressionQuality := Max(1, Min(100, StrToIntDef(CbDBJpegquality.Text, 75)));
UpdateDBSize;
end;
procedure TFormDBPreviewSize.FillImageQuality(Combo: TComboBox);
begin
Combo.Items.Clear;
Combo.Items.Add('25');
Combo.Items.Add('30');
Combo.Items.Add('40');
Combo.Items.Add('50');
Combo.Items.Add('60');
Combo.Items.Add('75');
Combo.Items.Add('80');
Combo.Items.Add('85');
Combo.Items.Add('90');
Combo.Items.Add('95');
Combo.Items.Add('100');
end;
procedure TFormDBPreviewSize.FillImageSize(Combo: TComboBox);
begin
Combo.Items.Clear;
Combo.Items.Add('85');
Combo.Items.Add('90');
Combo.Items.Add('100');
Combo.Items.Add('125');
Combo.Items.Add('150');
Combo.Items.Add('175');
Combo.Items.Add('200');
Combo.Items.Add('250');
Combo.Items.Add('300');
Combo.Items.Add('350');
Combo.Items.Add('400');
Combo.Items.Add('450');
Combo.Items.Add('500');
end;
procedure TFormDBPreviewSize.FormCreate(Sender: TObject);
procedure LoadLinkIcon(Link: TWebLink; Name: string);
var
Ico: HIcon;
begin
Ico := LoadIcon(HInstance, PChar(Name));
try
Link.LoadFromHIcon(Ico);
finally
DestroyIcon(Ico);
end;
end;
begin
FSampleImage := GetBigPatternImage;
FillImageSize(CbDBImageSize);
FillImageQuality(CbDBJpegquality);
LoadLanguage;
LoadLinkIcon(WlPreviewDBSize, 'PICTURE');
LoadLinkIcon(WlPreviewDBJpegQuality, 'PICTURE');
end;
procedure TFormDBPreviewSize.FormDestroy(Sender: TObject);
begin
FSettingsRepository := nil;
FMediaRepository := nil;
FContext := nil;
F(FSampleImage);
F(FCollectionSettings);
end;
procedure TFormDBPreviewSize.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
function TFormDBPreviewSize.Execute(CollectionFileName: string): Boolean;
begin
Result := False;
FContext := TDBContext.Create(CollectionFileName);
if FContext = nil then
Exit;
FMediaRepository := FContext.Media;
FSettingsRepository := FContext.Settings;
FCollectionSettings := FSettingsRepository.Get;
Result := True;
FMediaCount := FMediaRepository.GetCount;
CbDBImageSize.Text := IntToStr(FCollectionSettings.ThSize);
CbDBJpegquality.Text := IntToStr(FCollectionSettings.DBJpegCompressionQuality);
CbDBImageSizeChange(Self);
ShowModal;
end;
function TFormDBPreviewSize.GetFormID: string;
begin
Result := 'DBPreviewSettings';
end;
function TFormDBPreviewSize.HintCheck(Info: TMediaItem): Boolean;
begin
Result := True;
end;
procedure TFormDBPreviewSize.LoadLanguage;
begin
Caption := L('Preview settings');
LbDBImageSize.Caption := L('Default thumbnail size in collection');
LbDBImageQuality.Caption := L('Compression quality of images stored in the collection');
WlPreviewDBSize.Text := L('Preview');
WlPreviewDBJpegQuality.Text := L('Preview');
BtnOk.Caption := L('OK');
BtnCancel.Caption := L('Cancel');
end;
procedure TFormDBPreviewSize.ShowPreview(Graphic: TGraphic; Size: Int64);
var
Info: TMediaItem;
P: TPoint;
begin
GetCursorPos(P);
Info := TMediaItem.Create;
Info.Image := TJpegImage.Create;
Info.Image.Assign(Graphic);
Info.Image.CompressionQuality := 100;
if Graphic is TBitmap then
Info.Image.Compress;
Info.FileName := '?.JPEG';
Info.Name := L('Preview');
Info.FileSize := Size;
THintManager.Instance.CreateHintWindow(Self, Info, P, HintCheck);
end;
procedure TFormDBPreviewSize.UpdateDBSize;
var
JPEG: TJpegImage;
ImageSize: Int64;
begin
ImageSize := CalcJpegResampledSize(FSampleImage, FCollectionSettings.ThSize,
FCollectionSettings.DBJpegCompressionQuality, JPEG);
F(JPEG);
LbSingleImageSize.Caption := Format(L('Image size: %s'), [SizeInText(ImageSize)]);
LbDatabaseSize.Caption := Format(L('The size of new collection (approximately): %s'),
[SizeInText(FMediaCount * ImageSize)]);
end;
procedure TFormDBPreviewSize.WlPreviewDBSizeClick(Sender: TObject);
var
JPEG: TJpegImage;
ImageSize: Int64;
begin
ImageSize := CalcJpegResampledSize(FSampleImage, FCollectionSettings.ThSize, FCollectionSettings.DBJpegCompressionQuality, JPEG);
ShowPreview(JPEG, ImageSize);
F(JPEG)
end;
initialization
FormInterfaces.RegisterFormInterface(IFormCollectionPreviewSettings, TFormDBPreviewSize);
end.
|
unit Coches.View.Desktop.ListBox;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts,
FMX.ListBox, FMX.Controls.Presentation, FMX.StdCtrls, System.Actions,
FMX.ActnList, FMX.Objects,
DataSet.Interfaces,
MVVM.Attributes,
MVVM.Interfaces, MVVM.Bindings,
MVVM.Views.Platform.FMX,
MVVM.Controls.Platform.FMX;
type
[View_For_ViewModel('CochesMain.ListBox', IDataSet_ViewModel, 'WINDOWS_DESKTOP')]
TfrmCochesMainLB = class(TFormView<IDataSet_ViewModel>)
actlst1: TActionList;
actGet: TAction;
actNew: TAction;
actDelete: TAction;
actUpdate: TAction;
Layout1: TLayout;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
ListBox1: TListBox;
StyleBook1: TStyleBook;
private
{ Private declarations }
protected
procedure SetupView; override;
public
{ Public declarations }
end;
var
frmCochesMainLB: TfrmCochesMainLB;
implementation
uses
MVVM.Utils,
MVVM.Types;
{$R *.fmx}
{ TfrmCochesMainLB }
procedure TfrmCochesMainLB.SetupView;
begin
inherited;
// dataset configuration
ViewModel.TableName := 'Coches';
// views configuration
ViewModel.NewRowView := 'New.Coche';
ViewModel.UpdateRowView := 'Update.Coche';
// actions binding
actGet.Bind(ViewModel.DoMakeGetRows);
actNew.Bind(ViewModel.DoMakeAppend, ViewModel.IsOpen);
actUpdate.Bind(ViewModel.DoMakeUpdate, ViewModel.IsOpen);
actDelete.Bind(ViewModel.DoDeleteActiveRow, ViewModel.IsOpen);
// Dataset binding
ViewModel.DoMakeGetRows; //open the dataset and get rows
ListBox1.DefaultItemStyles.ItemStyle := 'CustomItem';
ListBox1.ItemHeight := 64;
Binder.BindDataSetToListBox(ViewModel.DataSet, ListBox1, [
TListBoxConversionData.Create('ID', 'Text'),
TListBoxConversionData.Create('NOMBRE', Utils.StyledFieldOfComponent('resolution')),
TListBoxConversionData.Create('IMAGEN', 'Bitmap')
], False);
end;
initialization
TfrmCochesMainLB.ClassName;
end.
|
unit Objekt.SepaModul;
interface
uses
SysUtils, Classes, IBX.IBDatabase, IBX.IBQuery, Objekt.SepaBSHeaderList,
o_Sepa_Log, o_nf;
type
TSepaModul = class
private
fTrans: TIBTransaction;
fLog : TSepa_Log;
fAusgabepfad: string;
fSicherungspfad: string;
fBS: TSepaBSHeaderList;
fAuftraggeber: string;
function GetLogFileName: string;
function GetSpecialFolder(const AFolder: Integer): string;
public
constructor Create;
destructor Destroy; override;
property Ausgabepfad: string read fAusgabepfad write fAusgabepfad;
property Auftraggeber: string read fAuftraggeber write fAuftraggeber;
property Sicherungspfad:string read fSicherungspfad write fSicherungspfad;
property Trans: TIBTransaction read fTrans write fTrans;
procedure VerarbeiteSepaUeberweisungen;
end;
implementation
{ TSepaModul }
uses
Winapi.SHFolder, Vcl.Forms, Objekt.SepaModulGutschrift;
constructor TSepaModul.Create;
begin
fAusgabepfad := '';
fSicherungspfad := '';
fTrans := nil;
fBS := nil;
fLog := TSepa_Log.Create;
end;
destructor TSepaModul.Destroy;
begin
FreeAndNil(fLog);
inherited;
end;
function TSepaModul.GetLogFileName: string;
var
Path: string;
Filename: string;
begin
Path := fAusgabepfad;
// if not DirectoryExists(Path) then
if Tnf.GetInstance.System.DirExist(Path) < 0 then
begin
Path := GetSpecialFolder(CSIDL_APPDATA) + '\Optima\';
// if not DirectoryExists(Path) then
if (Path <> '') and (Tnf.GetInstance.System.DirExist(Path) < 0) then
ForceDirectories(Path);
end;
if fAuftraggeber = '' then
Filename := 'SEPA_' + FormatDateTime('yyyymmdd', now) + '.log'
else
Filename := 'SEPA_' + fAuftraggeber + '_' + FormatDateTime('yyyymmdd', now) + '.log';
Path := IncludeTrailingPathDelimiter(Path) + 'Logs\';
if not DirectoryExists(Path) then
ForceDirectories(Path);
Result := Path + Filename;
end;
function TSepaModul.GetSpecialFolder(const AFolder: Integer): string;
var
path: string;
begin
SetLength(path, 250);
SHGetFolderPath(Application.Handle, AFolder, 0, 0, PChar(path));
result := PChar(path);
end;
procedure TSepaModul.VerarbeiteSepaUeberweisungen;
var
SepaGutschrift: TSepaModulGutschrift;
begin
fLog.Filename := GetLogFileName;
SepaGutschrift := TSepaModulGutschrift.Create;
try
SepaGutschrift.Ausgabepfad := fAusgabepfad;
SepaGutschrift.Sicherungspfad := fSicherungspfad;
SepaGutschrift.Trans := fTrans;
SepaGutschrift.LadeAlleGutschriften;
SepaGutschrift.LadeUeberweisungsauftrag;
SepaGutschrift.SchreibeAlleGutschriften;
finally
FreeAndNil(SepaGutschrift);
end;
end;
end.
|
unit Objekt.SepaDateiList;
interface
uses
SysUtils, Classes, Objekt.SepaDatei, contnrs;
type
TSepaDateiList = class
private
fList: TObjectList;
fFilePath: string;
function GetCount: Integer;
function getSepaDatei(Index: Integer): TSepaDatei;
function getNewFilename: string;
function getLastFileNumber: Integer;
procedure setFilePath(const Value: string);
public
constructor Create;
destructor Destroy; override;
property Count: Integer read GetCount;
property Item[Index: Integer]: TSepaDatei read getSepaDatei;
function Add: TSepaDatei;
function SepaDatei(aFilename: string): TSepaDatei;
function SepaDateiByIban(aIBAN: string): TSepaDatei;
function SepaDateiByIbanUndZahlung(aIBAN: string; aZahlung: TDateTime): TSepaDatei;
property FilePath: string read fFilePath write setFilePath;
procedure Init;
end;
implementation
{ TSepaDateiList }
constructor TSepaDateiList.Create;
begin
fList := TObjectList.Create;
fFilePath := '';
end;
destructor TSepaDateiList.Destroy;
begin
FreeAndNil(fList);
inherited;
end;
function TSepaDateiList.Add: TSepaDatei;
begin
Result := TSepaDatei.Create;
fList.Add(Result);
end;
function TSepaDateiList.GetCount: Integer;
begin
Result := fList.Count;
end;
function TSepaDateiList.SepaDatei(aFilename: string): TSepaDatei;
var
i1: Integer;
begin
for i1 := 0 to fList.Count -1 do
begin
if SameText(aFileName, TSepaDatei(fList.Items[i1]).Filename) then
begin
Result := TSepaDatei(fList.Items[i1]);
exit;
end;
end;
Result := Add;
Result.Filename := aFilename;
end;
function TSepaDateiList.SepaDateiByIban(aIBAN: string): TSepaDatei;
var
i1, i2: Integer;
SepaDat: TSepaDatei;
begin
Result := nil;
for i1 := 0 to fList.Count -1 do
begin
SepaDat := TSepaDatei(fList.Items[i1]);
for i2 := 0 to SepaDat.BSHeaderList.Count -1 do
begin
if SameText(SepaDat.BSHeaderList.Item[i2].IBAN, aIBAN) then
begin
Result := SepaDat;
exit;
end;
end;
end;
Result := Add;
Result.Filename := fFilePath + getNewFilename;
end;
procedure TSepaDateiList.setFilePath(const Value: string);
begin
fFilePath := IncludeTrailingPathDelimiter(Value);
end;
function TSepaDateiList.getLastFileNumber: Integer;
var
i1: Integer;
begin
Result := -1;
for i1 := 0 to fList.Count -1 do
begin
if Result < TSepaDatei(fList.Items[i1]).DateiNummer then
Result := TSepaDatei(fList.Items[i1]).DateiNummer;
end;
end;
function TSepaDateiList.getNewFilename: string;
var
LastFileNumber: Integer;
sFileNumber: string;
begin
LastFileNumber := getLastFileNumber;
inc(LastFileNumber);
sFileNumber := IntToStr(LastFileNumber);
while (Length(sFileNumber) <3) do
sFileNumber := '0' + sFileNumber;
Result := 'SEPA_G' + sFileNumber + '.xml';
end;
function TSepaDateiList.getSepaDatei(Index: Integer): TSepaDatei;
begin
Result := nil;
if Index > fList.Count -1 then
exit;
Result := TSepaDatei(fList[Index]);
end;
procedure TSepaDateiList.Init;
begin
end;
function TSepaDateiList.SepaDateiByIbanUndZahlung(aIBAN: string; aZahlung: TDateTime): TSepaDatei;
var
i1, i2: Integer;
SepaDat: TSepaDatei;
begin
Result := nil;
for i1 := 0 to fList.Count -1 do
begin
SepaDat := TSepaDatei(fList.Items[i1]);
for i2 := 0 to SepaDat.BSHeaderList.Count -1 do
begin
if (SameText(SepaDat.BSHeaderList.Item[i2].IBAN, aIBAN)) and (SepaDat.BSHeaderList.Item[i2].ZahlDatum = aZahlung) then
begin
Result := SepaDat;
exit;
end;
end;
end;
Result := Add;
Result.Filename := fFilePath + getNewFilename;
end;
end.
|
unit mainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Ani, FMX.Layouts, FMX.Gestures,
FMX.StdCtrls, FMX.Controls.Presentation, FMX.Graphics, FMX.Media,
Data.Bind.Components, Data.Bind.ObjectScope, REST.Client,
REST.Authenticator.Simple, FMX.ExtCtrls, FMX.ListView.Types,
FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView,
System.Math.Vectors, FMX.Controls3D, FMX.Objects3D, FMX.MultiView,
FMX.TabControl, FMX.Edit, FMX.Objects, FMX.ScrollBox, FMX.Memo,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, XMLIntf, XMLDoc, IdGlobal,
FMX.ListBox, FMX.Effects;
type TUser = record
Id:string;
Avatar:string;
Firstname:string;
Lastname:string;
LastEnter:string;
Email:string;
Language:string;
Token:string;
end;
type TRoom = record
Id:string;
Title:string;
Lang_from:string;
Lang_to:string;
Users: array of TUser;
Panel: TRectangle;
CountNewMsgCircle: TCircle;
CountNewMsgText: TText;
end;
type TMessage = record
Sender: string;
Data: string;
Date: string;
Panel: TCallOutRectangle;
end;
type
TForm1 = class(TForm)
StyleBook1: TStyleBook;
TabControl1: TTabControl;
SingIn: TTabItem;
SingUp: TTabItem;
Messager: TTabItem;
Setting: TTabItem;
Label5: TLabel;
Label6: TLabel;
signInEmailEdit: TEdit;
signInPswdlEdit: TEdit;
Label7: TLabel;
VertScrollBox1: TVertScrollBox;
VertScrollBox2: TVertScrollBox;
textMessageEdit: TEdit;
TabItem1: TTabItem;
Label11: TLabel;
confirmEmailEdit: TEdit;
TCP: TIdTCPClient;
Timer1: TTimer;
signInBtn: TButton;
confirmEmailBtn: TButton;
TabItem2: TTabItem;
AniIndicator1: TAniIndicator;
Label10: TLabel;
Rectangle2: TRectangle;
PanelRoomMain: TBrushObject;
Text1: TText;
Text2: TText;
Brush1: TBrushObject;
Text3: TText;
Brush2: TBrushObject;
Brush3: TBrushObject;
Circle2: TCircle;
Brush8: TBrushObject;
Brush4: TBrushObject;
Rectangle1: TRectangle;
Brush5: TBrushObject;
Brush6: TBrushObject;
Text4: TText;
Text6: TText;
CalloutRectangle1: TCalloutRectangle;
Text8: TText;
Text9: TText;
CalloutRectangle2: TCalloutRectangle;
Text10: TText;
Text11: TText;
Brush7: TBrushObject;
Rectangle3: TRectangle;
CalloutRectangle3: TCalloutRectangle;
Text12: TText;
CalloutRectangle4: TCalloutRectangle;
Text13: TText;
Text14: TText;
Rectangle4: TRectangle;
Rectangle5: TRectangle;
Rectangle6: TRectangle;
Rectangle7: TRectangle;
Rectangle8: TRectangle;
CalloutRectangle5: TCalloutRectangle;
CalloutRectangle6: TCalloutRectangle;
Rectangle9: TRectangle;
Label9: TLabel;
signUpBtn: TButton;
signUpEmailEdit: TEdit;
signUpPswd1Edit: TEdit;
signUpPswd2Edit: TEdit;
Text16: TText;
Text17: TText;
Text18: TText;
Text19: TText;
Rectangle15: TRectangle;
Rectangle16: TRectangle;
Rectangle17: TRectangle;
Rectangle10: TRectangle;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Rectangle11: TRectangle;
Rectangle12: TRectangle;
Rectangle13: TRectangle;
Edit1: TEdit;
SpeedButton1: TSpeedButton;
Line1: TLine;
Rectangle14: TRectangle;
Brush9: TBrushObject;
Brush10: TBrushObject;
Line3: TLine;
Rectangle18: TRectangle;
Circle3: TCircle;
Text5: TText;
Circle4: TCircle;
Text15: TText;
Text20: TText;
Rectangle19: TRectangle;
Rectangle20: TRectangle;
Rectangle21: TRectangle;
Rectangle22: TRectangle;
Label4: TLabel;
Circle5: TCircle;
Text21: TText;
Rectangle23: TRectangle;
Label8: TLabel;
Label12: TLabel;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
SpeedButton5: TSpeedButton;
ComboBox1: TComboBox;
Label13: TLabel;
Rectangle24: TRectangle;
Text7: TText;
Text22: TText;
Rectangle25: TRectangle;
ShadowEffect1: TShadowEffect;
Rectangle26: TRectangle;
ShadowEffect2: TShadowEffect;
ShadowEffect3: TShadowEffect;
Text23: TText;
Text24: TText;
Text25: TText;
Text26: TText;
Text27: TText;
Text28: TText;
AniIndicator2: TAniIndicator;
AniIndicator3: TAniIndicator;
// SendHandlers
procedure textMessageEditKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure Timer1Timer(Sender: TObject);
procedure signUpBtnClick(Sender: TObject);
procedure confirmEmailBtnClick(Sender: TObject);
procedure signInBtnClick(Sender: TObject);
procedure RoomClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure VertScrollBox2ViewportPositionChange(Sender: TObject;
const OldViewportPosition, NewViewportPosition: TPointF;
const ContentSizeChanged: Boolean);
procedure SpeedButton1Click(Sender: TObject);
procedure Text4Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
procedure SpeedButton4Click(Sender: TObject);
procedure SpeedButton5Click(Sender: TObject);
private
FGestureOrigin: TPointF;
FGestureInProgress: Boolean;
public
var myUser: TUser;
//messangeRoom
var Rooms: array of TRoom;
var Messages: array of TMessage;
var CurrentRoom: TRectangle;
var messageOffset: integer;
var isAllMessage: boolean;
var isLoadedMessages: boolean;
var topMarginMsgBox: integer;
var topMarginRoomBox: integer;
end;
var
Form1: TForm1;
implementation
uses addInterlocutorForm, receiveRouter, addEssence, sendAuth, auth,
sendTextMessage, initApplication, sendSelectRoom, sendLoadRequestMsg;
{$R *.fmx}
// initialization
procedure TForm1.FormCreate(Sender: TObject);
begin
init();
end;
// messagerInterface
procedure TForm1.RoomClick(Sender: TObject);
var panel: TRectangle;
begin
panel:=(Sender as TRectangle);
selectRoomSend(panel);
end;
procedure TForm1.VertScrollBox2ViewportPositionChange(Sender: TObject;
const OldViewportPosition, NewViewportPosition: TPointF;
const ContentSizeChanged: Boolean);
begin
loadRequestMsgSend(NewViewportPosition);
end;
procedure TForm1.textMessageEditKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
begin
testMessageSend(Key);
end;
// authorization handlers
procedure TForm1.signUpBtnClick(Sender: TObject);
begin
signUpSend();
end;
procedure TForm1.signInBtnClick(Sender: TObject);
begin
signInSend();
end;
procedure TForm1.confirmEmailBtnClick(Sender: TObject);
begin
confirmEmailSend();
end;
// router
procedure TForm1.Timer1Timer(Sender: TObject);
begin
routerReceive();
end;
//interface
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
Form2.Show;
end;
procedure TForm1.SpeedButton2Click(Sender: TObject);
begin
form1.tabControl1.TabIndex:=2;
end;
procedure TForm1.SpeedButton3Click(Sender: TObject);
begin
LogOut();
end;
procedure TForm1.SpeedButton4Click(Sender: TObject);
begin
form1.tabControl1.TabIndex:=0;
end;
procedure TForm1.SpeedButton5Click(Sender: TObject);
begin
form1.tabControl1.TabIndex:=1;
end;
procedure TForm1.Text4Click(Sender: TObject);
begin
form1.tabControl1.TabIndex:=3;
end;
end.
|
unit uFormLinkItemEditor;
interface
uses
Generics.Collections,
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Dmitry.Utils.System,
UnitDBDeclare,
uMemory,
uRuntime,
uDBForm,
uGraphicUtils,
uFormInterfaces;
type
TFormLinkItemEditor = class(TDBForm, IFormLinkItemEditor, IFormLinkItemEditorData)
PnEditorPanel: TPanel;
BtnSave: TButton;
BtnClose: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure BtnCloseClick(Sender: TObject);
procedure BtnSaveClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
FEditor: ILinkEditor;
FData: TDataObject;
procedure LoadEditControl;
protected
function GetFormID: string; override;
procedure InterfaceDestroyed; override;
public
{ Public declarations }
function Execute(Title: string; Data: TDataObject; Editor: ILinkEditor): Boolean;
function GetEditorData: TDataObject;
function GetEditorPanel: TPanel;
function GetTopPanel: TPanel;
procedure ApplyChanges;
end;
implementation
{$R *.dfm}
{ TFormLinkItemEditor }
procedure TFormLinkItemEditor.ApplyChanges;
begin
Close;
FEditor.UpdateItemFromEditor(nil, FData, Self);
ModalResult := mrOk;
end;
procedure TFormLinkItemEditor.BtnCloseClick(Sender: TObject);
begin
Close;
ModalResult := mrCancel;
end;
procedure TFormLinkItemEditor.BtnSaveClick(Sender: TObject);
begin
ApplyChanges;
end;
function TFormLinkItemEditor.Execute(Title: string; Data: TDataObject; Editor: ILinkEditor): Boolean;
begin
Caption := Title;
FEditor := Editor;
FData := Data;
FEditor.SetForm(Self);
LoadEditControl;
Result := ModalResult = mrOk;
end;
procedure TFormLinkItemEditor.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
FEditor.SetForm(nil);
Action := caHide;
end;
procedure TFormLinkItemEditor.FormCreate(Sender: TObject);
begin
if IsWindowsVista and not FolderView and HasFont(Canvas, 'MyriadPro-Regular') then
Font.Name := 'MyriadPro-Regular';
BtnClose.Caption := L('Cancel', '');
BtnSave.Caption := L('Save', '');
end;
procedure TFormLinkItemEditor.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
function TFormLinkItemEditor.GetEditorData: TDataObject;
begin
Result := FData;
end;
function TFormLinkItemEditor.GetEditorPanel: TPanel;
begin
Result := PnEditorPanel;
end;
function TFormLinkItemEditor.GetFormID: string;
begin
Result := 'FormLinkItemEditor';
end;
function TFormLinkItemEditor.GetTopPanel: TPanel;
begin
Result := nil;
end;
procedure TFormLinkItemEditor.InterfaceDestroyed;
begin
inherited;
Release;
end;
procedure TFormLinkItemEditor.LoadEditControl;
const
PaddingTop = 8;
var
ToWidth, ToHeight: Integer;
begin
PnEditorPanel.Tag := NativeInt(FData);
PnEditorPanel.HandleNeeded;
PnEditorPanel.AutoSize := True;
FEditor.CreateEditorForItem(nil, FData, Self);
PnEditorPanel.Left := 8;
PnEditorPanel.Top := 8;
ToWidth := PnEditorPanel.Left + PnEditorPanel.Width + PaddingTop * 2;
ToHeight := PnEditorPanel.Top + PnEditorPanel.Height + PaddingTop + BtnClose.Height + PaddingTop;
ClientWidth := ToWidth;
ClientHeight := ToHeight;
PnEditorPanel.Show;
ShowModal;
end;
initialization
FormInterfaces.RegisterFormInterface(IFormLinkItemEditor, TFormLinkItemEditor);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Run-time Library }
{ WinNT process API Interface Unit }
{ }
{ Copyright (c) 1985-1999, Microsoft Corporation }
{ }
{ Translator: Inprise Corporation }
{ }
{*******************************************************}
unit Psapi;
interface
{$WEAKPACKAGEUNIT}
uses Windows,sysutils;
{$HPPEMIT '#include <psapi.h>'}
type
PPointer = ^Pointer;
TEnumProcesses = function (lpidProcess: LPDWORD; cb: DWORD; var cbNeeded: DWORD): BOOL stdcall;
TEnumProcessModules = function (hProcess: THandle; lphModule: LPDWORD; cb: DWORD;
var lpcbNeeded: DWORD): BOOL stdcall;
TGetModuleBaseNameA = function (hProcess: THandle; hModule: HMODULE;
lpBaseName: PAnsiChar; nSize: DWORD): DWORD stdcall;
TGetModuleBaseNameW = function (hProcess: THandle; hModule: HMODULE;
lpBaseName: PWideChar; nSize: DWORD): DWORD stdcall;
TGetModuleBaseName = TGetModuleBaseNameA;
TGetModuleFileNameExA = function (hProcess: THandle; hModule: HMODULE;
lpFilename: PAnsiChar; nSize: DWORD): DWORD stdcall;
TGetModuleFileNameExW = function (hProcess: THandle; hModule: HMODULE;
lpFilename: PWideChar; nSize: DWORD): DWORD stdcall;
TGetModuleFileNameEx = TGetModuleFileNameExA;
{$EXTERNALSYM _MODULEINFO}
_MODULEINFO = packed record
lpBaseOfDll: Pointer;
SizeOfImage: DWORD;
EntryPoint: Pointer;
end;
{$EXTERNALSYM MODULEINFO}
MODULEINFO = _MODULEINFO;
{$EXTERNALSYM LPMODULEINFO}
LPMODULEINFO = ^_MODULEINFO;
TModuleInfo = _MODULEINFO;
PModuleInfo = LPMODULEINFO;
TGetModuleInformation = function (hProcess: THandle; hModule: HMODULE;
lpmodinfo: LPMODULEINFO; cb: DWORD): BOOL stdcall;
TEmptyWorkingSet = function (hProcess: THandle): BOOL stdcall;
TQueryWorkingSet = function (hProcess: THandle; pv: Pointer; cb: DWORD): BOOL stdcall;
TInitializeProcessForWsWatch = function (hProcess: THandle): BOOL stdcall;
{$EXTERNALSYM _PSAPI_WS_WATCH_INFORMATION}
_PSAPI_WS_WATCH_INFORMATION = packed record
FaultingPc: Pointer;
FaultingVa: Pointer;
end;
{$EXTERNALSYM PSAPI_WS_WATCH_INFORMATION}
PSAPI_WS_WATCH_INFORMATION = _PSAPI_WS_WATCH_INFORMATION;
{$EXTERNALSYM PPSAPI_WS_WATCH_INFORMATION}
PPSAPI_WS_WATCH_INFORMATION = ^_PSAPI_WS_WATCH_INFORMATION;
TPSAPIWsWatchInformation = _PSAPI_WS_WATCH_INFORMATION;
PPSAPIWsWatchInformation = PPSAPI_WS_WATCH_INFORMATION;
TGetWsChanges = function (hProcess: THandle; lpWatchInfo: PPSAPI_WS_WATCH_INFORMATION;
cb: DWORD): BOOL stdcall;
TGetMappedFileNameA = function (hProcess: THandle; lpv: Pointer;
lpFilename: PAnsiChar; nSize: DWORD): DWORD stdcall;
TGetMappedFileNameW = function (hProcess: THandle; lpv: Pointer;
lpFilename: PWideChar; nSize: DWORD): DWORD stdcall;
TGetMappedFileName = TGetMappedFileNameA;
TGetDeviceDriverBaseNameA = function (ImageBase: Pointer; lpBaseName: PAnsiChar;
nSize: DWORD): DWORD stdcall;
TGetDeviceDriverBaseNameW = function (ImageBase: Pointer; lpBaseName: PWideChar;
nSize: DWORD): DWORD stdcall;
TGetDeviceDriverBaseName = TGetDeviceDriverBaseNameA;
TGetDeviceDriverFileNameA = function (ImageBase: Pointer; lpFileName: PAnsiChar;
nSize: DWORD): DWORD stdcall;
TGetDeviceDriverFileNameW = function (ImageBase: Pointer; lpFileName: PWideChar;
nSize: DWORD): DWORD stdcall;
TGetDeviceDriverFileName = TGetDeviceDriverFileNameA;
TEnumDeviceDrivers = function (lpImageBase: PPointer; cb: DWORD;
var lpcbNeeded: DWORD): BOOL stdcall;
{$EXTERNALSYM _PROCESS_MEMORY_COUNTERS}
_PROCESS_MEMORY_COUNTERS = packed record
cb: DWORD;
PageFaultCount: DWORD;
PeakWorkingSetSize: DWORD;
WorkingSetSize: DWORD;
QuotaPeakPagedPoolUsage: DWORD;
QuotaPagedPoolUsage: DWORD;
QuotaPeakNonPagedPoolUsage: DWORD;
QuotaNonPagedPoolUsage: DWORD;
PagefileUsage: DWORD;
PeakPagefileUsage: DWORD;
end;
{$EXTERNALSYM PROCESS_MEMORY_COUNTERS}
PROCESS_MEMORY_COUNTERS = _PROCESS_MEMORY_COUNTERS;
{$EXTERNALSYM PPROCESS_MEMORY_COUNTERS}
PPROCESS_MEMORY_COUNTERS = ^_PROCESS_MEMORY_COUNTERS;
TProcessMemoryCounters = _PROCESS_MEMORY_COUNTERS;
PProcessMemoryCounters = ^_PROCESS_MEMORY_COUNTERS;
TGetProcessMemoryInfo = function (Process: THandle;
ppsmemCounters: PPROCESS_MEMORY_COUNTERS; cb: DWORD): BOOL stdcall;
{$EXTERNALSYM EnumProcesses}
function EnumProcesses(lpidProcess: LPDWORD; cb: DWORD; var cbNeeded: DWORD): BOOL;
{$EXTERNALSYM EnumProcessModules}
function EnumProcessModules(hProcess: THandle; lphModule: LPDWORD; cb: DWORD;
var lpcbNeeded: DWORD): BOOL;
{$EXTERNALSYM GetModuleBaseNameA}
function GetModuleBaseNameA(hProcess: THandle; hModule: HMODULE;
lpBaseName: PAnsiChar; nSize: DWORD): DWORD;
{$EXTERNALSYM GetModuleBaseNameW}
function GetModuleBaseNameW(hProcess: THandle; hModule: HMODULE;
lpBaseName: PWideChar; nSize: DWORD): DWORD;
{$EXTERNALSYM GetModuleBaseName}
function GetModuleBaseName(hProcess: THandle; hModule: HMODULE;
lpBaseName: PChar; nSize: DWORD): DWORD;
{$EXTERNALSYM GetModuleFileNameExA}
function GetModuleFileNameExA(hProcess: THandle; hModule: HMODULE;
lpFilename: PAnsiChar; nSize: DWORD): DWORD;
{$EXTERNALSYM GetModuleFileNameExW}
function GetModuleFileNameExW(hProcess: THandle; hModule: HMODULE;
lpFilename: PWideChar; nSize: DWORD): DWORD;
{$EXTERNALSYM GetModuleFileNameEx}
function GetModuleFileNameEx(hProcess: THandle; hModule: HMODULE;
lpFilename: PChar; nSize: DWORD): DWORD;
{$EXTERNALSYM GetModuleInformation}
function GetModuleInformation(hProcess: THandle; hModule: HMODULE;
lpmodinfo: LPMODULEINFO; cb: DWORD): BOOL;
{$EXTERNALSYM EmptyWorkingSet}
function EmptyWorkingSet(hProcess: THandle): BOOL;
{$EXTERNALSYM QueryWorkingSet}
function QueryWorkingSet(hProcess: THandle; pv: Pointer; cb: DWORD): BOOL;
{$EXTERNALSYM InitializeProcessForWsWatch}
function InitializeProcessForWsWatch(hProcess: THandle): BOOL;
{$EXTERNALSYM GetMappedFileNameA}
function GetMappedFileNameA(hProcess: THandle; lpv: Pointer;
lpFilename: PAnsiChar; nSize: DWORD): DWORD;
{$EXTERNALSYM GetMappedFileNameW}
function GetMappedFileNameW(hProcess: THandle; lpv: Pointer;
lpFilename: PWideChar; nSize: DWORD): DWORD;
{$EXTERNALSYM GetMappedFileName}
function GetMappedFileName(hProcess: THandle; lpv: Pointer;
lpFilename: PChar; nSize: DWORD): DWORD;
{$EXTERNALSYM GetDeviceDriverBaseNameA}
function GetDeviceDriverBaseNameA(ImageBase: Pointer; lpBaseName: PAnsiChar;
nSize: DWORD): DWORD;
{$EXTERNALSYM GetDeviceDriverBaseNameW}
function GetDeviceDriverBaseNameW(ImageBase: Pointer; lpBaseName: PWideChar;
nSize: DWORD): DWORD;
{$EXTERNALSYM GetDeviceDriverBaseName}
function GetDeviceDriverBaseName(ImageBase: Pointer; lpBaseName: PChar;
nSize: DWORD): DWORD;
{$EXTERNALSYM GetDeviceDriverFileNameA}
function GetDeviceDriverFileNameA(ImageBase: Pointer; lpFileName: PAnsiChar;
nSize: DWORD): DWORD;
{$EXTERNALSYM GetDeviceDriverFileNameW}
function GetDeviceDriverFileNameW(ImageBase: Pointer; lpFileName: PWideChar;
nSize: DWORD): DWORD;
{$EXTERNALSYM GetDeviceDriverFileName}
function GetDeviceDriverFileName(ImageBase: Pointer; lpFileName: PChar;
nSize: DWORD): DWORD;
{$EXTERNALSYM EnumDeviceDrivers}
function EnumDeviceDrivers(lpImageBase: PPointer; cb: DWORD;
var lpcbNeeded: DWORD): BOOL;
{$EXTERNALSYM GetProcessMemoryInfo}
function GetProcessMemoryInfo(Process: THandle;
ppsmemCounters: PPROCESS_MEMORY_COUNTERS; cb: DWORD): BOOL;
implementation
var
hPSAPI: THandle;
_EnumProcesses: TEnumProcesses;
_EnumProcessModules: TEnumProcessModules;
{procedure}_GetModuleBaseNameA: TGetModuleBaseNameA;
{procedure}_GetModuleFileNameExA: TGetModuleFileNameExA;
{procedure}_GetModuleBaseNameW: TGetModuleBaseNameW;
{procedure}_GetModuleFileNameExW: TGetModuleFileNameExW;
{procedure}_GetModuleBaseName: TGetModuleBaseNameA;
{procedure}_GetModuleFileNameEx: TGetModuleFileNameExA;
_GetModuleInformation: TGetModuleInformation;
_EmptyWorkingSet: TEmptyWorkingSet;
_QueryWorkingSet: TQueryWorkingSet;
_InitializeProcessForWsWatch: TInitializeProcessForWsWatch;
{procedure}_GetMappedFileNameA: TGetMappedFileNameA;
{procedure}_GetDeviceDriverBaseNameA: TGetDeviceDriverBaseNameA;
{procedure}_GetDeviceDriverFileNameA: TGetDeviceDriverFileNameA;
{procedure}_GetMappedFileNameW: TGetMappedFileNameW;
{procedure}_GetDeviceDriverBaseNameW: TGetDeviceDriverBaseNameW;
{procedure}_GetDeviceDriverFileNameW: TGetDeviceDriverFileNameW;
{procedure}_GetMappedFileName: TGetMappedFileNameA;
{procedure}_GetDeviceDriverBaseName: TGetDeviceDriverBaseNameA;
{procedure}_GetDeviceDriverFileName: TGetDeviceDriverFileNameA;
_EnumDeviceDrivers: TEnumDeviceDrivers;
_GetProcessMemoryInfo: TGetProcessMemoryInfo;
function CheckPSAPILoaded: Boolean;
begin
if hPSAPI = 0 then
begin
hPSAPI := LoadLibrary('PSAPI.dll');
if hPSAPI < 32 then
begin
hPSAPI := 0;
Result := False;
Exit;
end;
@_EnumProcesses := GetProcAddress(hPSAPI, 'EnumProcesses');
@_EnumProcessModules := GetProcAddress(hPSAPI, 'EnumProcessModules');
{procedure}@_GetModuleBaseNameA := GetProcAddress(hPSAPI, 'GetModuleBaseNameA');
{procedure}@_GetModuleFileNameExA := GetProcAddress(hPSAPI, 'GetModuleFileNameExA');
{procedure}@_GetModuleBaseNameW := GetProcAddress(hPSAPI, 'GetModuleBaseNameW');
{procedure}@_GetModuleFileNameExW := GetProcAddress(hPSAPI, 'GetModuleFileNameExW');
{procedure}@_GetModuleBaseName := GetProcAddress(hPSAPI, 'GetModuleBaseNameA');
{procedure}@_GetModuleFileNameEx := GetProcAddress(hPSAPI, 'GetModuleFileNameExA');
@_GetModuleInformation := GetProcAddress(hPSAPI, 'GetModuleInformation');
@_EmptyWorkingSet := GetProcAddress(hPSAPI, 'EmptyWorkingSet');
@_QueryWorkingSet := GetProcAddress(hPSAPI, 'QueryWorkingSet');
@_InitializeProcessForWsWatch := GetProcAddress(hPSAPI, 'InitializeProcessForWsWatch');
{procedure}@_GetMappedFileNameA := GetProcAddress(hPSAPI, 'GetMappedFileNameA');
{procedure}@_GetDeviceDriverBaseNameA := GetProcAddress(hPSAPI, 'GetDeviceDriverBaseNameA');
{procedure}@_GetDeviceDriverFileNameA := GetProcAddress(hPSAPI, 'GetDeviceDriverFileNameA');
{procedure}@_GetMappedFileNameW := GetProcAddress(hPSAPI, 'GetMappedFileNameW');
{procedure}@_GetDeviceDriverBaseNameW := GetProcAddress(hPSAPI, 'GetDeviceDriverBaseNameW');
{procedure}@_GetDeviceDriverFileNameW := GetProcAddress(hPSAPI, 'GetDeviceDriverFileNameW');
{procedure}@_GetMappedFileName := GetProcAddress(hPSAPI, 'GetMappedFileNameA');
{procedure}@_GetDeviceDriverBaseName := GetProcAddress(hPSAPI, 'GetDeviceDriverBaseNameA');
{procedure}@_GetDeviceDriverFileName := GetProcAddress(hPSAPI, 'GetDeviceDriverFileNameA');
@_EnumDeviceDrivers := GetProcAddress(hPSAPI, 'EnumDeviceDrivers');
@_GetProcessMemoryInfo := GetProcAddress(hPSAPI, 'GetProcessMemoryInfo');
end;
Result := True;
end;
function EnumProcesses(lpidProcess: LPDWORD; cb: DWORD; var cbNeeded: DWORD): BOOL;
begin
if CheckPSAPILoaded then
Result := _EnumProcesses(lpidProcess, cb, cbNeeded)
else Result := False;
end;
function EnumProcessModules(hProcess: THandle; lphModule: LPDWORD; cb: DWORD;
var lpcbNeeded: DWORD): BOOL;
begin
if CheckPSAPILoaded then
Result := _EnumProcessModules(hProcess, lphModule, cb, lpcbNeeded)
else Result := False;
end;
function GetModuleBaseNameA(hProcess: THandle; hModule: HMODULE;
lpBaseName: PAnsiChar; nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetModuleBaseNameA(hProcess, hModule, lpBaseName, nSize)
else Result := 0;
end;
function GetModuleBaseNameW(hProcess: THandle; hModule: HMODULE;
lpBaseName: PWideChar; nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetModuleBaseNameW(hProcess, hModule, lpBaseName, nSize)
else Result := 0;
end;
function GetModuleBaseName(hProcess: THandle; hModule: HMODULE;
lpBaseName: PChar; nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetModuleBaseName(hProcess, hModule, lpBaseName, nSize)
else Result := 0;
end;
function GetModuleFileNameExA(hProcess: THandle; hModule: HMODULE;
lpFilename: PAnsiChar; nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetModuleFileNameExA(hProcess, hModule, lpFileName, nSize)
else Result := 0;
end;
function GetModuleFileNameExW(hProcess: THandle; hModule: HMODULE;
lpFilename: PWideChar; nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetModuleFileNameExW(hProcess, hModule, lpFileName, nSize)
else Result := 0;
end;
function GetModuleFileNameEx(hProcess: THandle; hModule: HMODULE;
lpFilename: PChar; nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then begin
Result := _GetModuleFileNameEx(hProcess, hModule, lpFileName, nSize);
end else Result := 0;
end;
function GetModuleInformation(hProcess: THandle; hModule: HMODULE;
lpmodinfo: LPMODULEINFO; cb: DWORD): BOOL;
begin
if CheckPSAPILoaded then
Result := _GetModuleInformation(hProcess, hModule, lpmodinfo, cb)
else Result := False;
end;
function EmptyWorkingSet(hProcess: THandle): BOOL;
begin
if CheckPSAPILoaded then
Result := _EmptyWorkingSet(hProcess)
else Result := False;
end;
function QueryWorkingSet(hProcess: THandle; pv: Pointer; cb: DWORD): BOOL;
begin
if CheckPSAPILoaded then
Result := _QueryWorkingSet(hProcess, pv, cb)
else Result := False;
end;
function InitializeProcessForWsWatch(hProcess: THandle): BOOL;
begin
if CheckPSAPILoaded then
Result := _InitializeProcessForWsWatch(hProcess)
else Result := False;
end;
function GetMappedFileNameA(hProcess: THandle; lpv: Pointer;
lpFilename: PAnsiChar; nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetMappedFileNameA(hProcess, lpv, lpFileName, nSize)
else Result := 0;
end;
function GetMappedFileNameW(hProcess: THandle; lpv: Pointer;
lpFilename: PWideChar; nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetMappedFileNameW(hProcess, lpv, lpFileName, nSize)
else Result := 0;
end;
function GetMappedFileName(hProcess: THandle; lpv: Pointer;
lpFilename: PChar; nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetMappedFileName(hProcess, lpv, lpFileName, nSize)
else Result := 0;
end;
function GetDeviceDriverBaseNameA(ImageBase: Pointer; lpBaseName: PAnsiChar;
nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetDeviceDriverBasenameA(ImageBase, lpBaseName, nSize)
else Result := 0;
end;
function GetDeviceDriverBaseNameW(ImageBase: Pointer; lpBaseName: PWideChar;
nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetDeviceDriverBasenameW(ImageBase, lpBaseName, nSize)
else Result := 0;
end;
function GetDeviceDriverBaseName(ImageBase: Pointer; lpBaseName: PChar;
nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetDeviceDriverBasename(ImageBase, lpBaseName, nSize)
else Result := 0;
end;
function GetDeviceDriverFileNameA(ImageBase: Pointer; lpFileName: PAnsiChar;
nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetDeviceDriverFileNameA(ImageBase, lpFileName, nSize)
else Result := 0;
end;
function GetDeviceDriverFileNameW(ImageBase: Pointer; lpFileName: PWideChar;
nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetDeviceDriverFileNameW(ImageBase, lpFileName, nSize)
else Result := 0;
end;
function GetDeviceDriverFileName(ImageBase: Pointer; lpFileName: PChar;
nSize: DWORD): DWORD;
begin
if CheckPSAPILoaded then
Result := _GetDeviceDriverFileName(ImageBase, lpFileName, nSize)
else Result := 0;
end;
function EnumDeviceDrivers(lpImageBase: PPointer; cb: DWORD;
var lpcbNeeded: DWORD): BOOL;
begin
if CheckPSAPILoaded then
Result := _EnumDeviceDrivers(lpImageBase, cb, lpcbNeeded)
else Result := False;
end;
function GetProcessMemoryInfo(Process: THandle;
ppsmemCounters: PPROCESS_MEMORY_COUNTERS; cb: DWORD): BOOL;
begin
if CheckPSAPILoaded then
Result := _GetProcessMemoryInfo(Process, ppsmemCounters, cb)
else Result := False;
end;
end.
|
unit VolumeRGBByteData;
interface
uses Windows, Graphics, BasicDataTypes, Abstract3DVolumeData, RGBByteDataSet,
AbstractDataSet, dglOpenGL, Math;
type
T3DVolumeRGBByteData = class (TAbstract3DVolumeData)
private
FDefaultColor: TPixelRGBByteData;
// Gets
function GetData(_x, _y, _z, _c: integer):byte;
function GetDataUnsafe(_x, _y, _z, _c: integer):byte;
function GetDefaultColor:TPixelRGBByteData;
// Sets
procedure SetData(_x, _y, _z, _c: integer; _value: byte);
procedure SetDataUnsafe(_x, _y, _z, _c: integer; _value: byte);
procedure SetDefaultColor(_value: TPixelRGBByteData);
protected
// Constructors and Destructors
procedure Initialize; override;
// Gets
function GetBitmapPixelColor(_Position: longword):longword; override;
function GetRPixelColor(_Position: longword):byte; override;
function GetGPixelColor(_Position: longword):byte; override;
function GetBPixelColor(_Position: longword):byte; override;
function GetAPixelColor(_Position: longword):byte; override;
function GetRedPixelColor(_x,_y,_z: integer):single; override;
function GetGreenPixelColor(_x,_y,_z: integer):single; override;
function GetBluePixelColor(_x,_y,_z: integer):single; override;
function GetAlphaPixelColor(_x,_y,_z: integer):single; override;
// Sets
procedure SetBitmapPixelColor(_Position, _Color: longword); override;
procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override;
procedure SetRedPixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetGreenPixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetBluePixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetAlphaPixelColor(_x,_y,_z: integer; _value:single); override;
// Copies
procedure CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); override;
public
// Gets
function GetOpenGLFormat:TGLInt; override;
// copies
procedure Assign(const _Source: TAbstract3DVolumeData); override;
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
procedure Fill(_Value: byte);
// properties
property Data[_x,_y,_z,_c:integer]:byte read GetData write SetData; default;
property DataUnsafe[_x,_y,_z,_c:integer]:byte read GetDataUnsafe write SetDataUnsafe;
property DefaultColor:TPixelRGBByteData read GetDefaultColor write SetDefaultColor;
end;
implementation
// Constructors and Destructors
procedure T3DVolumeRGBByteData.Initialize;
begin
FDefaultColor.r := 0;
FDefaultColor.g := 0;
FDefaultColor.b := 0;
FData := TRGBByteDataSet.Create;
end;
// Gets
function T3DVolumeRGBByteData.GetData(_x, _y, _z, _c: integer):byte;
begin
if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: Result := (FData as TRGBByteDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
1: Result := (FData as TRGBByteDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
else
begin
Result := (FData as TRGBByteDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
end;
end
else
begin
case (_c) of
0: Result := FDefaultColor.r;
1: Result := FDefaultColor.g;
else
begin
Result := FDefaultColor.b;
end;
end;
end;
end;
function T3DVolumeRGBByteData.GetDataUnsafe(_x, _y, _z, _c: integer):byte;
begin
case (_c) of
0: Result := (FData as TRGBByteDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
1: Result := (FData as TRGBByteDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
else
begin
Result := (FData as TRGBByteDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
end;
end;
function T3DVolumeRGBByteData.GetDefaultColor:TPixelRGBByteData;
begin
Result := FDefaultColor;
end;
function T3DVolumeRGBByteData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB((FData as TRGBByteDataSet).Blue[_Position],(FData as TRGBByteDataSet).Green[_Position],(FData as TRGBByteDataSet).Red[_Position]);
end;
function T3DVolumeRGBByteData.GetRPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBByteDataSet).Red[_Position];
end;
function T3DVolumeRGBByteData.GetGPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBByteDataSet).Green[_Position];
end;
function T3DVolumeRGBByteData.GetBPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBByteDataSet).Blue[_Position];
end;
function T3DVolumeRGBByteData.GetAPixelColor(_Position: longword):byte;
begin
Result := 0;
end;
function T3DVolumeRGBByteData.GetRedPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBByteDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBByteData.GetGreenPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBByteDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBByteData.GetBluePixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBByteDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBByteData.GetAlphaPixelColor(_x,_y,_z: integer):single;
begin
Result := 0;
end;
function T3DVolumeRGBByteData.GetOpenGLFormat:TGLInt;
begin
Result := GL_RGB;
end;
// Sets
procedure T3DVolumeRGBByteData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TRGBByteDataSet).Red[_Position] := GetRValue(_Color);
(FData as TRGBByteDataSet).Green[_Position] := GetGValue(_Color);
(FData as TRGBByteDataSet).Blue[_Position] := GetBValue(_Color);
end;
procedure T3DVolumeRGBByteData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TRGBByteDataSet).Red[_Position] := _r;
(FData as TRGBByteDataSet).Green[_Position] := _g;
(FData as TRGBByteDataSet).Blue[_Position] := _b;
end;
procedure T3DVolumeRGBByteData.SetRedPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBByteDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value) and $FF;
end;
procedure T3DVolumeRGBByteData.SetGreenPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBByteDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value) and $FF;
end;
procedure T3DVolumeRGBByteData.SetBluePixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBByteDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value) and $FF;
end;
procedure T3DVolumeRGBByteData.SetAlphaPixelColor(_x,_y,_z: integer; _value:single);
begin
// do nothing
end;
procedure T3DVolumeRGBByteData.SetData(_x, _y, _z, _c: integer; _value: byte);
begin
if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: (FData as TRGBByteDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
1: (FData as TRGBByteDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
2: (FData as TRGBByteDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
end;
end;
procedure T3DVolumeRGBByteData.SetDataUnsafe(_x, _y, _z, _c: integer; _value: byte);
begin
case (_c) of
0: (FData as TRGBByteDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
1: (FData as TRGBByteDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
2: (FData as TRGBByteDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
end;
procedure T3DVolumeRGBByteData.SetDefaultColor(_value: TPixelRGBByteData);
begin
FDefaultColor.r := _value.r;
FDefaultColor.g := _value.g;
FDefaultColor.b := _value.b;
end;
// Copies
procedure T3DVolumeRGBByteData.Assign(const _Source: TAbstract3DVolumeData);
begin
inherited Assign(_Source);
FDefaultColor.r := (_Source as T3DVolumeRGBByteData).FDefaultColor.r;
FDefaultColor.g := (_Source as T3DVolumeRGBByteData).FDefaultColor.g;
FDefaultColor.b := (_Source as T3DVolumeRGBByteData).FDefaultColor.b;
end;
procedure T3DVolumeRGBByteData.CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer);
var
x,y,z,ZPos,ZDataPos,Pos,maxPos,DataPos,maxX, maxY, maxZ: integer;
begin
maxX := min(FXSize,_DataXSize)-1;
maxY := min(FYSize,_DataYSize)-1;
maxZ := min(FZSize,_DataZSize)-1;
for z := 0 to maxZ do
begin
ZPos := z * FYxXSize;
ZDataPos := z * _DataYSize * _DataXSize;
for y := 0 to maxY do
begin
Pos := ZPos + (y * FXSize);
DataPos := ZDataPos + (y * _DataXSize);
maxPos := Pos + maxX;
for x := Pos to maxPos do
begin
(FData as TRGBByteDataSet).Data[x] := (_Data as TRGBByteDataSet).Data[DataPos];
inc(DataPos);
end;
end;
end;
end;
// Misc
procedure T3DVolumeRGBByteData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBByteDataSet).Red[x] := Round((FData as TRGBByteDataSet).Red[x] * _Value);
(FData as TRGBByteDataSet).Green[x] := Round((FData as TRGBByteDataSet).Green[x] * _Value);
(FData as TRGBByteDataSet).Blue[x] := Round((FData as TRGBByteDataSet).Blue[x] * _Value);
end;
end;
procedure T3DVolumeRGBByteData.Invert;
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBByteDataSet).Red[x] := 255 - (FData as TRGBByteDataSet).Red[x];
(FData as TRGBByteDataSet).Green[x] := 255 - (FData as TRGBByteDataSet).Green[x];
(FData as TRGBByteDataSet).Blue[x] := 255 - (FData as TRGBByteDataSet).Blue[x];
end;
end;
procedure T3DVolumeRGBByteData.Fill(_value: byte);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBByteDataSet).Red[x] := _value;
(FData as TRGBByteDataSet).Green[x] := _value;
(FData as TRGBByteDataSet).Blue[x] := _value;
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.Spec.TargetPlatform;
interface
uses
System.Classes,
Spring.Collections,
JsonDataObjects,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Spec.TemplateBase,
DPM.Core.Spec.Interfaces;
type
TSpecTargetPlatform = class(TSpecTemplateBase, ISpecTargetPlatform)
private
FTemplateName : string;
FPlatforms : TArray<TDPMPlatform>;
FCompiler : TCompilerVersion;
FVariables : TStringList;
protected
function GetPlatforms : TArray<TDPMPlatform>;
function GetTemplateName : string;
function GetCompiler : TCompilerVersion;
function GetVariables : TStrings;
function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override;
function CloneForPlatform(const platform : TDPMPlatform) : ISpecTargetPlatform;
public
constructor Create(const logger : ILogger); override;
constructor CreateReducedClone(const logger : ILogger; const targetPlatform : ISpecTargetPlatform; const platform : TDPMPlatform; const variables : TStrings);
destructor Destroy;override;
end;
implementation
uses
System.SysUtils,
DPM.Core.Constants,
DPM.Core.TargetPlatform,
DPM.Core.Utils.Strings,
DPM.Core.Spec.Dependency,
DPM.Core.Spec.DependencyGroup;
{ TSpecTargetPlatform }
function TSpecTargetPlatform.CloneForPlatform(const platform : TDPMPlatform) : ISpecTargetPlatform;
begin
result := TSpecTargetPlatform.CreateReducedClone(logger, self, platform, FVariables);
end;
constructor TSpecTargetPlatform.Create(const logger : ILogger);
begin
inherited Create(logger);
SetLength(FPlatforms, 0);
FCompiler := TCompilerVersion.UnknownVersion;
FTemplateName := cUnset;
FVariables := TStringList.Create;
end;
constructor TSpecTargetPlatform.CreateReducedClone(const logger : ILogger; const targetPlatform : ISpecTargetPlatform; const platform : TDPMPlatform; const variables : TStrings);
var
deps : IList<ISpecDependency>;
dep, newDep : ISpecDependency;
designFiles, runtimeFiles : IList<ISpecBPLEntry>;
bpl, newBpl : ISpecBPLEntry;
sourceFiles, libFiles, otherFiles : IList<ISpecFileEntry>;
fileEntry, newFileEntry : ISpecFileEntry;
searchPaths : IList<ISpecSearchPath>;
path, newPath : ISpecSearchPath;
begin
deps := TCollections.CreateList<ISpecDependency>;
for dep in targetPlatform.Dependencies do
begin
newDep := dep.Clone;
deps.Add(newDep);
end;
designFiles := TCollections.CreateList<ISpecBPLEntry>;
for bpl in targetPlatform.DesignFiles do
begin
newBpl := bpl.Clone;
designFiles.Add(newBpl)
end;
runtimeFiles := TCollections.CreateList<ISpecBPLEntry>;
for bpl in targetPlatform.RuntimeFiles do
begin
newBpl := bpl.Clone;
runtimeFiles.Add(newBpl)
end;
sourceFiles := TCollections.CreateList<ISpecFileEntry>;
for fileEntry in targetPlatform.SourceFiles do
begin
newFileEntry := fileEntry.Clone;
sourceFiles.Add(newFileEntry)
end;
libFiles := TCollections.CreateList<ISpecFileEntry>;
for fileEntry in targetPlatform.LibFiles do
begin
newFileEntry := fileEntry.Clone;
libFiles.Add(newFileEntry)
end;
otherFiles := TCollections.CreateList<ISpecFileEntry>;
for fileEntry in targetPlatform.Files do
begin
newFileEntry := fileEntry.Clone;
otherFiles.Add(newFileEntry)
end;
searchPaths := TCollections.CreateList<ISpecSearchPath>;
for path in targetPlatform.SearchPaths do
begin
newPath := path.Clone;
searchPaths.Add(newPath);
end;
inherited CreateClone(logger, deps, designFiles, runtimeFiles, sourceFiles, libFiles, otherFiles, searchPaths);
FVariables.Assign(variables);
FTemplateName := targetPlatform.TemplateName;
FCompiler := targetPlatform.Compiler;
FPlatforms := TArray<TDPMPlatform>.Create(platform);
end;
destructor TSpecTargetPlatform.Destroy;
begin
FVariables.Free;
inherited;
end;
function TSpecTargetPlatform.GetPlatforms : TArray<TDPMPlatform>;
begin
result := FPlatforms;
end;
function TSpecTargetPlatform.GetCompiler : TCompilerVersion;
begin
result := FCompiler;
end;
function TSpecTargetPlatform.GetTemplateName : string;
begin
result := FTemplateName;
end;
function TSpecTargetPlatform.GetVariables: TStrings;
begin
result := FVariables;
end;
function TSpecTargetPlatform.LoadFromJson(const jsonObject : TJsonObject) : Boolean;
var
sValue : string;
platformStrings : TArray<string>;
platform : TDPMPlatform;
platformList : IList<TDPMPlatform>;
sCompiler : string;
sTemplate : string;
variablesObj : TJsonObject;
i: Integer;
begin
result := true;
sCompiler := jsonObject.S['compiler'];
if sCompiler = '' then
begin
Logger.Error('Required property [compiler] is missing)');
result := false;
end
else
begin
FCompiler := StringToCompilerVersion(sCompiler);
if FCompiler = TCompilerVersion.UnknownVersion then
begin
result := false;
Logger.Error('Invalid compiler value [' + sCompiler + ']');
end;
end;
sValue := jsonObject.S['platforms'];
if sValue = '' then
begin
Logger.Error('Required property [platforms] is missing)');
result := false;
end
else
begin
sValue := StringReplace(sValue, ' ', '', [rfReplaceAll]);
//Logger.Debug('[targetPlatform] platforms : ' + sValue);
platformStrings := TStringUtils.SplitStr(sValue, ',');
if Length(platformStrings) > 0 then
begin
platformList := TCollections.CreateList<TDPMPlatform>;
for sValue in platformStrings do
begin
platform := StringToDPMPlatform(sValue);
if platform <> TDPMPlatform.UnknownPlatform then
begin
platformList.Add(platform);
if not ValidatePlatform(FCompiler, platform) then
begin
Logger.Error('Invalid platform value [' + sValue + '] for compiler version [' + sCompiler + ']');
result := false;
end;
end
else
begin
Logger.Error('Invalid platform value [' + sValue + ']');
result := false;
end;
end;
FPlatforms := platformList.ToArray();
end
else
begin
Logger.Error('At least 1 platform must be specified.');
result := false;
end;
end;
sTemplate := jsonObject.S['template'];
if sTemplate <> '' then
FTemplateName := sTemplate;
variablesObj := jsonObject.ExtractObject('variables');
if variablesObj <> nil then
begin
for i := 0 to variablesObj.Count -1 do
FVariables.Add(variablesObj.Names[i] + '=' + variablesObj.Values[variablesObj.Names[i]].Value );
variablesObj.Free;
end;
result := inherited LoadFromJson(jsonObject) and result;
end;
end.
|
unit uCnCalcMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxControls, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, StdCtrls, cxButtons,
cn_Common_Types, frxDesgn, frxClass, frxDBSet, DM_Calc, DB, FIBDataSet,
pFIBDataSet, ActnList;
type
TfmCalcMain = class(TForm)
cxButtonOk: TcxButton;
cxButtonCancel: TcxButton;
Label1: TLabel;
cxDateCalc: TcxDateEdit;
frxDBDataset1: TfrxDBDataset;
frxDesigner1: TfrxDesigner;
DataSet: TpFIBDataSet;
frxReport: TfrxReport;
ActionList1: TActionList;
acDebug: TAction;
procedure FormCreate(Sender: TObject);
procedure cxButtonCancelClick(Sender: TObject);
procedure cxButtonOkClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure acDebugExecute(Sender: TObject);
private
PLanguageIndex: byte;
DM :TdmCalc;
DM2:TdmCalc;
id_session_pay : int64;
id_session_calc : int64;
ID_TRANSACTION : int64;
ID_STUD : int64;
ID_DOG_ROOT : int64;
NUM_DOG: string;
NUM_SPRAV:String;
DATE_DOG : TDate;
public
IsDebugMode: boolean;
res:Variant;
constructor Create(Aparameter:TcnSimpleParamsEx);reintroduce;
end;
function PrintCalc(AParameter:TcnSimpleParamsEx):Variant;stdcall;
exports PrintCalc;
var
fmCalcMain: TfmCalcMain;
implementation
{$R *.dfm}
function PrintCalc(AParameter:TcnSimpleParamsEx):Variant;stdcall;
var
T: TfmCalcMain;
begin
T:=TfmCalcMain.Create(AParameter);
T.ShowModal;
T.Free;
end;
constructor TfmCalcMain.Create(Aparameter:TcnSimpleParamsEx);
begin
inherited Create(Aparameter.Owner);
DM:=TdmCalc.Create(Self);
DM.DB.Handle:=Aparameter.Db_Handle;
ID_STUD:=AParameter.cnParamsToPakage.ID_STUD;
ID_DOG_ROOT:=AParameter.cnParamsToPakage.ID_DOG_ROOT;
NUM_DOG:=Aparameter.cnParamsToPakage.Num_Doc;
DATE_DOG := Aparameter.cnParamsToPakage.DATE_DOG;
end;
procedure TfmCalcMain.FormCreate(Sender: TObject);
begin
cxDateCalc.Date:=Date;
cxButtonOk.Caption:='Прийняти';
cxButtonCancel.Caption:='Відмінити';
end;
procedure TfmCalcMain.cxButtonCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfmCalcMain.cxButtonOkClick(Sender: TObject);
var cnUplSum, cnSumDoc, cnSNeed, SegodnyaOpl : Currency;
cnDATEOPL: TDate;
Cur_date:TDate;
FIO:String;
begin
DM.ReadDataSet.SelectSQL.Clear;
DM.ReadDataSet.SelectSQL.Text:= 'select * from CN_DT_STUDINFO_CALC_SELECT('+ inttostr(ID_STUD) +')' ;
DM.ReadDataSet.Open;
FIO :=DM.ReadDataSet['FIO_PEOPLE'];
DM.ReadDataSet.close;
DM.ReadDataSet.SQLs.SelectSQL.Text := 'select * from CN_SUM_ENTRYREST_SELECT('+
inttostr(ID_STUD)
+ ','+ inttostr(ID_DOG_ROOT)
+')';
DM.ReadDataSet.open;
DM.ReadDataSet.Close;
// формирование корректных счетов и операций на сегодня
With DM.StProc do
begin
try
StoredProcName:='CN_DATE_PROV_SYS_DATA_CHECK_UPT';
Transaction.StartTransaction;
Prepare;
ExecProc;
Transaction.Commit;
Close;
except
Transaction.Rollback;
ShowMessage('Произошла ошибка при выполнении процедуры CN_DATE_PROV_SYS_DATA_CHECK_UPT!'+ #13+'Сбой в работе системы.');
raise;
end;
end;
With DM.StProc do
begin
try
StoredProcName := 'CN_PAY';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_STUD').AsInt64 := ID_STUD;
ParamByName('DATE_PROV_CHECK').AsShort := 1;
ParamByName('IS_DOC_GEN').AsShort := 1;
ParamByName('IS_PROV_GEN').AsShort := 1;
ParamByName('IS_SMET_GEN').AsShort := 1;
ParamByName('NOFPROV').AsShort := 1;
ParamByName('DIGNORDOCID').AsShort := 1;
ExecProc;
cnUplSum:=ParamByName('CNUPLSUM').AsCurrency;
cnSumDoc:=ParamByName('SUMMA_ALL').AsCurrency;
id_session_pay:= ParamByName('ID_SESSION').AsInt64;
Transaction.Commit;
Close;
// --------------запуск процедуры cn_calc------------------------------
//
StoredProcName := 'CN_CALC';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_STUD').AsInt64 := ID_STUD;
if cnUplSum > cnSumDoc then
ParamByName('CNUPLSUM').AsCurrency := cnUplSum
else
ParamByName('CNUPLSUM').AsCurrency := cnSumDoc; // это уже с уплаченной суммой
ExecProc;
cnSNeed:= ParamByName('CN_SNEED').AsCurrency; // сумма, необходимая для уплаты за весь период
cnDATEOPL:= ParamByName('CNDATEOPL').AsDateTime; // дата, по которую оплачено
id_session_calc:= ParamByName('ID_SESSION').AsInt64;
Transaction.Commit;
Close;
StoredProcName := 'CN_CALC_TMP_CLEAR';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_SESSION').AsInt64 := id_session_calc;
ExecProc;
Transaction.Commit;
Close;
// --------------запуск процедуры cn_calc------------------------------
Cur_date:= cxDateCalc.EditValue;
//
if (cnDATEOPL <= Cur_date) then
begin
StoredProcName := 'CN_CALC';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_STUD').AsInt64 := ID_STUD;
ParamByName('BEG_CHECK').AsVariant := cnDATEOPL;
ParamByName('CNUPLSUM').AsVariant := null;
ParamByName('END_CHECK').AsDate := Cur_date;
ExecProc;
SegodnyaOpl:=ParamByName('cn_SNEED').AsCurrency;
id_session_calc:= ParamByName('ID_SESSION').AsInt64;
Transaction.Commit;
Close;
end
else
SegodnyaOpl:=0;
StoredProcName := 'CN_CALC_TMP_CLEAR';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_SESSION').AsInt64 := id_session_calc;
ExecProc;
Transaction.Commit;
Close;
// новый способ вызова
StoredProcName:='CN_FR_GET_ID_SESSION';
Transaction.StartTransaction;
Prepare;
ExecProc;
ID_TRANSACTION:= FieldByName('ID_SESSION').AsInt64;
Transaction.Commit;
Close;
//отбор данных из базы
StoredProcName:='CN_PRINT_CN_CALC';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_STUD').AsInt64:=ID_STUD;
ParamByName('end_check').AsDate:=now;
ParamByName('ID_SESSION').AsInt64:=ID_TRANSACTION;
ExecProc;
Transaction.Commit;
Close;
StoredProcName := 'CN_DT_NUMBER_SPAV_SELECT';
Transaction.StartTransaction;
Prepare;
ExecProc;
Num_Sprav:=ParamByName('number_sprav').AsString;
Transaction.Commit;
Close;
except
Transaction.Rollback;
showmessage('Непередбачена помилка! Зверніться до Адміністратора.');
raise;
end;
DM2:=TdmCalc.Create(Self);
DM2.DB.Handle:=DM.DB.Handle;
DM2.DataSet.SelectSQL.Clear;
DM2.DataSet.SelectSQL.text:= 'select * from cn_tmp_print_cn_calc where id_session ='+ IntToStr(ID_TRANSACTION);
DM2.DataSet.closeopen(true);
end;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Contracts\'+'PeoplePay.fr3');
frxReport.Variables.Clear;
frxDBDataset1.DataSet:=DM2.DataSet;
DataSet.Close;
DataSet.SQLs.SelectSQL.Clear;
DataSet.SQLs.SelectSQL.add('select psc.name_customer, cn_buhg, cn_buhg_title');
DataSet.SQLs.SelectSQL.add('From pub_sys_data psd, pub_sp_customer psc');
DataSet.SQLs.SelectSQL.add('where (psc.id_customer=psd.organization)');
DataSet.Open;
frxReport.Variables['Date']:=''''+DateToStr(Now)+'''';
frxReport.Variables['NUM_DOG']:=''''+NUM_DOG+'''';
frxReport.Variables['NUMBER']:=''''+NUM_SPRAV+'''';
frxReport.Variables['DATE_DOG']:=''''+DateToStr(DATE_DOG)+'''';
if DataSet['NAME_CUSTOMER'] <> null then
frxReport.Variables['ORG']:=''''+DataSet['NAME_CUSTOMER']+'''';
frxReport.Variables['NADO_FINAL']:=''''+FloatToStr(SegodnyaOpl)+'''';
frxReport.Variables['PLATIL_FINAL']:=''''+FloatToStr(cnUplSum)+'''';
if cnUplSum > cnSumDoc
then frxReport.Variables['DOLG_FINAL']:= ''''+FloatTostr(cnSNeed - cnUplSum)+''''
else frxReport.Variables['DOLG_FINAL']:= ''''+FloatToStr(cnSNeed - cnSumDoc)+'''';
frxReport.Variables['CNDATEOPL']:=''''+DateToStr(cnDATEOPL)+'''';
frxReport.Variables['FIO']:= QuotedStr(FIO);
frxReport.Variables['PAYCONF1']:=''''+'Сплачено'+'''';
frxReport.Variables['PAYCONF2']:=QuotedStr('повністю');
if DataSet['CN_BUHG_TITLE'] <> null
then frxReport.Variables['BUHG_TITLE']:=''''+DataSet['CN_BUHG_TITLE']+'''';
if DataSet['CN_BUHG'] <> null
then frxReport.Variables['BUHG']:=''''+DataSet['CN_BUHG']+'''';
frxReport.PrepareReport;
if IsDebugMode
then frxReport.DesignReport
else frxReport.ShowPreparedReport;
end;
procedure TfmCalcMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
With DM.StProc do
begin
StoredProcName := 'CN_PAY_TMP_CLEAR';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_SESSION').AsInt64 := id_session_pay;
ExecProc;
Transaction.Commit;
Close;
StoredProcName := 'CN_CALC_TMP_CLEAR';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_SESSION').AsInt64 := id_session_calc;
ExecProc;
Transaction.Commit;
Close;
StoredProcName := 'CN_TMP_PRINT_CN_CALC_DELETE';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_SESSION').AsInt64:=ID_TRANSACTION;
ExecProc;
Transaction.Commit;
Close;
end;
DM.Free;
DM2.Free;
end;
procedure TfmCalcMain.acDebugExecute(Sender: TObject);
begin
If not IsDebugMode
then
Begin
IsDebugMode:=true;
Caption:=' *debug';
End
Else
Begin
IsDebugMode:=false;
Caption:='';
End;
end;
end.
|
unit MyCat.Statistic.Generics.DataSourceSyncRecord;
interface
uses
System.SysUtils;
{$I DGLCfg.inc_h}
type
TDataSourceSyncRecord = record
private
FTime: Int64;
FValue: TObject;
public
constructor Create(Time: Int64; Value: TObject);
property Time: Int64 read FTime write FTime;
property Value: TObject read FValue write FValue;
end;
_ValueType = TDataSourceSyncRecord;
const
_NULL_Value: _ValueType = (FTime: (0); FValue: (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); 默认排序准则
{$DEFINE __DGL_KeyType_Is_ValueType}
{$I List.inc_h}
type
IDataSourceSyncRecordIterator = _IIterator;
IDataSourceSyncRecordContainer = _IContainer;
IDataSourceSyncRecordSerialContainer = _ISerialContainer;
IDataSourceSyncRecordVector = _IVector;
IDataSourceSyncRecordList = _IList;
IDataSourceSyncRecordDeque = _IDeque;
IDataSourceSyncRecordStack = _IStack;
IDataSourceSyncRecordQueue = _IQueue;
IDataSourceSyncRecordPriorityQueue = _IPriorityQueue;
IDataSourceSyncRecordSet = _ISet;
IDataSourceSyncRecordMultiSet = _IMultiSet;
TDataSourceSyncRecordList = _TList;
IDataSourceSyncRecordMapIterator = _IMapIterator;
IDataSourceSyncRecordMap = _IMap;
IDataSourceSyncRecordMultiMap = _IMultiMap;
implementation
{$I List.inc_pas}
function _IsEqual(const A, B: _ValueType): boolean;
begin
Result := (A.FTime = B.FTime) and (A.FValue = B.FValue);
end;
function _IsLess(const A, B: _ValueType): boolean;
begin
Result := A.FTime < B.FTime;
end;
{ TDataSourceSyncRecord }
constructor TDataSourceSyncRecord.Create(Time: Int64; Value: TObject);
begin
FTime := Time;
FValue := Value;
end;
end.
|
unit HashAlgTiger_U;
// Description: Tiger (Wrapper for the Tiger Hashing Engine)
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Classes,
HashAlg_U,
HashValue_U,
HashAlgTigerEngine_U;
type
THashAlgTiger = class(THashAlg)
private
tigerEngine: THashAlgTigerEngine;
context: Tiger_CTX;
function GetPasses(): integer;
procedure SetPasses(passes: integer);
protected
{ Protected declarations }
public
property passes: integer read GetPasses write SetPasses;
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Init(); override;
procedure Update(const input: array of byte; const inputLen: cardinal); override;
procedure Final(digest: THashValue); override;
published
{ Published declarations }
end;
procedure Register;
implementation
uses
SysUtils; // needed for fmOpenRead
procedure Register;
begin
RegisterComponents('Hash', [THashAlgTiger]);
end;
constructor THashAlgTiger.Create(AOwner: TComponent);
begin
inherited;
tigerEngine:= THashAlgTigerEngine.Create();
fTitle := 'Tiger';
fHashLength := 192;
fBlockLength := 512;
Passes := 3;
end;
destructor THashAlgTiger.Destroy();
begin
// Nuke any existing context before freeing off the engine...
tigerEngine.TigerInit(context);
tigerEngine.Free();
inherited;
end;
function THashAlgTiger.GetPasses(): integer;
begin
Result := tigerEngine.Passes;
end;
procedure THashAlgTiger.SetPasses(passes: integer);
begin
tigerEngine.Passes := passes;
end;
procedure THashAlgTiger.Init();
begin
tigerEngine.TigerInit(context);
end;
procedure THashAlgTiger.Update(const input: array of byte; const inputLen: cardinal);
begin
tigerEngine.TigerUpdate(context, input, inputLen);
end;
procedure THashAlgTiger.Final(digest: THashValue);
begin
tigerEngine.TigerFinal(digest, context);
end;
END.
|
unit asciipic;
interface
uses
Windows, Graphics, GifImage;
const
GrayScaleChars1: String[16] = ' .,-=:;/+%$XH@M#';
GrayScaleChars2: String[16] = ' .+%$2YODAUQ#HNM';
function Bitmap2ASCII(ABitmap: TBitmap; const AChars: String): String;
implementation
function Bitmap2ASCII(ABitmap: TBitmap; const AChars: String): String;
type
BA = array[0..1] of Byte;
LogPal = record
lpal: TLogPalette;
dummy: packed array[1..255] of TPaletteEntry;
end;
var
SysPal: LogPal;
Bitmap: TBitmap;
i, x, y, len: Integer;
Pattern: array[0..255] of Char;
begin
Result:= '';
len:= Length(AChars);
if len <=0
then Exit;
len:= 256 div len; // chars per 1 scale
with SysPal.lPal do begin
palVersion:= $300;
palNumEntries:= 256;
for i:= 0 to 255 do with palPalEntry[i] do begin
peRed:= i;
peGreen:= i;
peBlue:= i;
peFlags:= PC_NOCOLLAPSE;
end;
end;
Bitmap:= TBitmap.Create;
Bitmap.Assign(ABitmap);
Bitmap:= ReduceColors(Bitmap, rmPalette, dmNearest, 8, CreatePalette(SysPal.lpal));
with Bitmap do begin
HandleType:= bmDIB;
PixelFormat:= pf8bit;
Palette:= CreatePalette(SysPal.lpal);
end;
// create pattern
for i:= 0 to 255 do begin
Pattern[255-i]:= AChars[i div len + 1];
end;
// fill result string
for y:= 0 to Bitmap.Height - 1 do begin
for x:= 0 to Bitmap.Width - 1 do begin
Result:= Result + Pattern[BA(Bitmap.ScanLine[y]^)[x]];
end;
Result:= Result + #13#10;
end;
Bitmap.Free;
end;
end.
|
unit uDlgObject_selector;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBASE_DialogForm, Menus, cxLookAndFeelPainters,
uFrameAlterStructure, uFrameAlterObjectStructure, StdCtrls, cxButtons,
ExtCtrls;
type
TdlgObject_selector = class(TBASE_DialogForm)
FrameObjects: TFrameAlterObjectStructure;
private
function GetSelectedObjectID: integer;
function GetSelectedObjectName: string;
public
property SelectedObjectID: integer read GetSelectedObjectID;
property SelectedObjectName: string read GetSelectedObjectName;
end;
var
dlgObject_selector: TdlgObject_selector;
implementation
{$R *.dfm}
{ TdlgObject_selector }
function TdlgObject_selector.GetSelectedObjectID: integer;
begin
result:=FrameObjects.Props.Attribute.ID;
end;
function TdlgObject_selector.GetSelectedObjectName: string;
begin
result:=FrameObjects.Props.Attribute.Name;
end;
end.
|
UNIT UEarthquake;
INTERFACE
{* exposed functions and procedures *}
{* Inserts new earthquake to earthquakes array sorted by date (ASC)
*
* @param latitude REAL Latitude value of geopoint
* @param longitude REAL Longitude value of geopoint
* @param strength REAL Strength value of earthquake (richter magnitude scale)
* @param city STRING City near geopoint of earthquake
* @param dateString STRING Date when earthquake occured. Strict Format: 'dd.mm.yyyy'
*}
PROCEDURE AddEarthquake(latitude, longitude, strength: REAL; city: STRING; dateString: STRING);
{* Returns total number of earthquakes by retourning earthquakes counter
*
* @return INTEGER Number of earthquakes
*}
FUNCTION TotalNumberOfEarthquakes: INTEGER;
{* Returns Number of earthquakes between two given dates
*
* @paramIn fromDate STRING Datestring of (inclusive) beginning date of timespan. Strict Format: 'dd.mm.yyyy'
* @paramIn toDate STRING Datestring of (inclusive) ending date of timespan Strict Format: 'dd.mm.yyyy'
* @return INTEGER Number of earthquakes found
*}
FUNCTION NumberOfEarthquakesInTimespan(fromDate, toDate: STRING): INTEGER;
{* Gets the data of earthquake with biggest strength in given region
*
* @paramIn latitudeIn1 REAL Latitude value of first geopoint
* @paramIn longitudeIn1 REAL Longitude value of first geopoint
* @paramIn latitudeIn2 REAL Latitude value of second geopoint
* @paramIn longitudeIn2 REAL Longitude value of second geopoint
* @paramOut latitudeOut REAL Latitude value of found earthquake
* @paramOut longitudeOut REAL Longitude value of found earthquake
* @paramOut strength REAL Strength value of found earthquake
* @paramOut city STRING City of found earthquake
* @paramOut day INTEGER day of found earthquake (part of date)
* @paramOut month INTEGER month of found earthquake (part of date)
* @paramOut year INTEGER year of found earthquake (part of date )
*}
PROCEDURE GetStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL;
VAR latitudeOut, longitudeOut, strength: REAL; VAR city: STRING; VAR day, month, year: INTEGER);
{* Gets average earthquake strength in region
*
* @paramIn latitudeIn1 REAL Latitude value of first geopoint
* @paramIn longitudeIn1 REAL Longitude value of first geopoint
* @paramIn latitudeIn2 REAL Latitude value of second geopoint
* @paramIn longitudeIn2 REAL Longitude value of second geopoint
* @return REAL Average Strength value
*}
FUNCTION AverageEarthquakeStrengthInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL): REAL;
{* Displays earthquakes list close to city
*
* @paramIn city STRING City value to be searched for in earthquakes
*}
PROCEDURE PrintEarthquakesCloseToCity(city: STRING);
{* Displays earthquakes list of earthquakes with strength bigger or equal to strength
*
* @paramIn strength REAL Strength value to be searched for in earthquakes
*}
PROCEDURE PrintStrongCityEarthquakes(strength: REAL);
{* Resets the earthquakes by re-initializing earthquakes and earthquakesCount *}
PROCEDURE Reset;
IMPLEMENTATION
{* make functions and procedures from UDate available in this scope *}
USES UDate;
{* define restrictions for earthquakes array *}
CONST
LowerBound = 1;
UpperBound = 1000;
{* introduce Earthquake type *}
TYPE
Earthquake = record
city: STRING;
strength, latitude, longitude: REAL;
date: Date;
END;
VAR
earthquakes: ARRAY[LowerBound..UpperBound] OF Earthquake;
earthquakesCount: INTEGER; {* represents number of filled elements in earthquakes *}
{* Initialize earthquakes array and set initial value for earthquakesCount *}
PROCEDURE InitEarthquakes;
VAR
emptyEarthquake: Earthquake;
i: INTEGER;
BEGIN
earthquakesCount := 0;
FOR i := LowerBound TO UpperBound DO
BEGIN
{* set emptyEarthquake on every element of earthquakes *}
earthquakes[i] := emptyEarthquake;
END;
END;
PROCEDURE AddEarthquake(latitude, longitude, strength: REAL; city: STRING; dateString: STRING);
VAR
earthquakeEntry: Earthquake;
dateValid, found: BOOLEAN;
earthquakeDate: Date;
i, j: INTEGER;
BEGIN
found := false;
{* If dateString can't be parsed don't add the earthquake to the list *}
ParseDate(dateString, dateValid, earthquakeDate);
IF dateValid THEN
BEGIN
{* fill earthquakeEntry properties with parameter values *}
earthquakeEntry.date := earthquakeDate;
earthquakeEntry.latitude := latitude;
earthquakeEntry.longitude := longitude;
earthquakeEntry.strength := strength;
earthquakeEntry.city := city;
{* For the first earthquakeEntry no sorted insert is necessary *}
IF earthquakesCount = 0 THEN
BEGIN
earthquakes[1] := earthquakeEntry;
earthquakesCount := earthquakesCount + 1;
END ELSE IF UpperBound >= earthquakesCount + 1 THEN {* check if array limit reached *}
BEGIN
{* start sorted insert of earthquakeEntry *}
i := LowerBound;
WHILE (i <= earthquakesCount) and (not found) DO
BEGIN
IF LiesBefore(earthquakeEntry.date, earthquakes[i].date) THEN {* exposed by UDate *}
BEGIN
{* when insert position found, push all entries with index > i to the right *}
Inc(earthquakesCount);
j := earthquakesCount;
WHILE j > i DO
BEGIN
earthquakes[j] := earthquakes[j - 1];
j := j - 1;
END;
{* insert earthquakeEntry at found position *}
earthquakes[i] := earthquakeEntry;
found := true;
END;
Inc(i);
END;
IF not found THEN BEGIN
{* no insert position found, just append the entry to earthquakes array *}
Inc(earthquakesCount);
earthquakes[earthquakesCount] := earthquakeEntry;
END;
END;
END;
END;
FUNCTION TotalNumberOfEarthquakes: INTEGER;
BEGIN
TotalNumberOfEarthquakes := earthquakesCount;
END;
FUNCTION NumberOfEarthquakesInTimespan(fromDate, toDate: STRING): INTEGER;
VAR
i, count: INTEGER;
d1, d2, temp: Date;
okd1, okd2: BOOLEAN;
BEGIN
ParseDate(fromDate, okd1, d1);
ParseDate(toDate, okd2, d2);
{* Only continue if both dates are valid
* otherwise return -1
*}
IF okd1 and okd2 THEN
BEGIN
{* Swap dates if d2 is earlier than d1 *}
IF not LiesBefore(d1, d2) THEN {* exposed by UDate *}
BEGIN
temp := d2;
d2 := d1;
d1 := temp;
END;
i := LowerBound;
count := 0;
{* only repeat over filled earthquake entries *}
WHILE i <= earthquakesCount DO
BEGIN
IF LiesBefore(d1, earthquakes[i].date) and LiesBefore(earthquakes[i].date, d2) THEN
BEGIN
{* earthquake entry is in timespan *}
Inc(count);
END;
Inc(i);
END;
NumberOfEarthquakesInTimespan := count
END ELSE NumberOfEarthquakesInTimespan := -1;
END;
{* Swaps two REAL values and returns them *}
PROCEDURE SwapValues(VAR val1, val2: REAL);
VAR
temp: REAL;
BEGIN
temp := val1;
val1 := val2;
val2 := temp;
END;
{* returns true if geopoint (checkLatitude and checkLongitude) is in region *}
FUNCTION GeopointInRegion(latitude1, longitude1, latitude2, longitude2, checkLatitude, checkLongitude: REAL): BOOLEAN;
BEGIN
GeopointInRegion := false;
IF latitude1 > latitude2 THEN
BEGIN
{* swap geopoints so check conditions will work *}
SwapValues(latitude1, latitude2);
SwapValues(longitude1, longitude2);
END;
{* check if given geopoint is in region.
* The region can be seen as a rectangle in a coordinate system
*}
IF (checkLatitude >= latitude1) and (checkLatitude <= latitude2) THEN
IF (checkLongitude >= longitude1) and (checkLongitude <= longitude2) THEN
GeopointInRegion := true;
END;
PROCEDURE GetStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL;
VAR latitudeOut, longitudeOut, strength: REAL; VAR city: STRING; VAR day, month, year: INTEGER);
VAR
i: INTEGER;
temp: Earthquake;
BEGIN
temp.strength := 0;
{* only iterate over filled earthquake entries *}
FOR i := LowerBound TO earthquakesCount DO
BEGIN
IF GeopointInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2,
earthquakes[i].latitude, earthquakes[i].longitude) THEN
BEGIN
{* earthquakes[i] is in the region, so compare it's strength to previosly found *}
IF temp.strength < earthquakes[i].strength THEN
temp := earthquakes[i];
END;
END;
{* Convert the found earthquake entry to primitive datatypes to return them *}
latitudeOut := temp.latitude;
longitudeOut := temp.longitude;
strength := temp.strength;
city := temp.city;
day := temp.date.day;
month := temp.date.month;
year := temp.date.year;
END;
FUNCTION AverageEarthquakeStrengthInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL): REAL;
VAR
i: INTEGER;
sum: REAL;
count: INTEGER;
BEGIN
sum := 0;
count := 0;
{* only iterate over filled earthquake entries *}
FOR i := LowerBound TO earthquakesCount DO
BEGIN
IF GeopointInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2,
earthquakes[i].latitude, earthquakes[i].longitude) THEN
BEGIN
{* earthquakes[i] is in region, so add it's strength to sum
* and increase the counter.
*}
sum := sum + earthquakes[i].strength;
Inc(count);
END;
END;
IF count > 0 THEN
AverageEarthquakeStrengthInRegion := sum / count
ELSE AverageEarthquakeStrengthInRegion := 0;
END;
PROCEDURE DisplayEarthquake(earthquake: Earthquake);
BEGIN
WriteLn();
Write('DATE: ');
DisplayDate(earthquake.date);
WriteLn();
WriteLn('STRENGTH: ', earthquake.strength);
WriteLn('LATITUDE: ', earthquake.latitude);
WriteLn('LONGITUDE: ', earthquake.longitude);
WriteLn('CITY: ', earthquake.city);
WriteLn();
END;
PROCEDURE DisplayEarthquakeFromValues(latitude, longitude, strength: REAL; city: STRING; day, month, year: INTEGER);
VAR
earthquakeEntry: Earthquake;
BEGIN
earthquakeEntry.latitude := latitude;
earthquakeEntry.longitude := longitude;
earthquakeEntry.strength := strength;
earthquakeEntry.city := city;
earthquakeEntry.date.day := day;
earthquakeEntry.date.month := month;
earthquakeEntry.date.year := year;
DisplayEarthquake(earthquakeEntry);
END;
PROCEDURE PrintEarthquakesCloseToCity(city: STRING);
VAR
i: INTEGER;
BEGIN
WriteLn('-----------------------------------------------------');
WriteLn();
WriteLn('Earthquakes close to ' , city);
WriteLn();
{* DOWNTO loop, so the output is sorted by date DESC *}
FOR i := earthquakesCount DOWNTO LowerBound DO
BEGIN
IF earthquakes[i].city = city THEN
DisplayEarthquake(earthquakes[i]);
END;
WriteLn();
WriteLn('-----------------------------------------------------');
END;
PROCEDURE PrintStrongCityEarthquakes(strength: REAL);
VAR
i: INTEGER;
BEGIN
WriteLn('-----------------------------------------------------');
WriteLn();
WriteLn('Earthquakes with Strength >= ' , strength);
WriteLn();
FOR i := LowerBound TO earthquakesCount DO
BEGIN
IF earthquakes[i].strength >= strength THEN
BEGIN
{* if earthquake fits condition only display date and city *}
Write('DATE: ');
DisplayDate(earthquakes[i].date);
WriteLn(' | CITY: ', earthquakes[i].city);
END;
END;
WriteLn();
WriteLn('-----------------------------------------------------');
END;
PROCEDURE Reset;
BEGIN
InitEarthquakes;
END;
BEGIN
{* Init on first run of Unit *}
InitEarthquakes;
END. |
unit MainViewForm;
interface
uses
Interfaces,
Spring.Container,
Winapi.Windows,
System.SysUtils,
System.Classes,
Vcl.Controls,
Vcl.Forms,
Vcl.ExtCtrls,
ChromeTabs,
ChromeTabsClasses,
Vcl.Menus;
type
//interceptor class
TPanel = class(Vcl.ExtCtrls.TPanel, IPanelFrame)
private
FTab: TChromeTab;
public
property Tab: TChromeTab read FTab write FTab;
end;
TMainView = class(TForm, IMainView)
Tabs: TChromeTabs;
PanelMenu: TPanel;
PopupTabs: TPopupMenu;
procedure TabsActiveTabChanged(Sender: TObject; ATab: TChromeTab);
procedure TabsButtonCloseTabClick(Sender: TObject; ATab: TChromeTab;
var Close: Boolean);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormShow(Sender: TObject);
private
FPresenter : IMainPresenter;
PageIndex : Cardinal;
procedure CreateNewPage(ACaption: string; var APanel: TPanel); overload;
public
procedure SetPresenter(APresenter: IMainPresenter);
procedure CreateMenuPage;
procedure OpenFrame(ATitle: string; AProc: TProc<IPanelFrame>);
procedure ShowReport;
procedure CloseTab(AControl: IPanelFrame);
end;
var
MainView : TMainView;
implementation
{$R *.dfm}
{ TMainView }
procedure TMainView.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := MessageBox(0, 'Benarkan, Anda akan Keluar dari Applikasi?',
'Keluar Aplikasi', MB_ICONQUESTION or MB_YESNO) = mrYes;
end;
procedure TMainView.FormShow(Sender: TObject);
begin
FPresenter.Start;
end;
procedure TMainView.TabsActiveTabChanged(Sender: TObject; ATab: TChromeTab);
var
LPanel :TPanel;
begin
if ATab.Tag = 0 then Exit;
LPanel := FindComponent('Panel' + IntToStr(ATab.Tag)) as TPanel;
LPanel.BringToFront;
end;
procedure TMainView.TabsButtonCloseTabClick(Sender: TObject; ATab: TChromeTab;
var Close: Boolean);
var
LPanel :TPanel;
begin
Close := False;
if Tabs.Tabs.Count = 1 then
begin
Self.Close;
Exit;
end;
LPanel := FindComponent('Panel' + IntToStr(ATab.Tag)) as TPanel;
if ATab.Tag = 1 then Exit;
LPanel.Free;
Close := True;
end;
procedure TMainView.CloseTab(AControl: IPanelFrame);
var
LTab : TChromeTab;
LPanel, LControl :TPanel;
begin
if Tabs.Tabs.Count = 1 then
begin
Self.Close;
Exit;
end;
LControl := AControl as TPanel;
Tabs.Tabs.DeleteTab(LControl.Tab.Index, False);
LPanel := FindComponent('Panel' + IntToStr(LControl.Tag)) as TPanel;
LPanel.Free;
end;
procedure TMainView.CreateMenuPage;
var
LTab : TChromeTab;
LPanel :TPanel;
LFrame : IMenuView;
begin
OpenFrame('Menu Utama',
procedure (AOwner: IPanelFrame)
begin
LFrame := GlobalContainer.Resolve<IMenuView>;
LFrame.SetMainAndPanel(Self, TPanel(AOwner));
TPanel(AOwner).Tab.HideCloseButton := True;
end
);
end;
procedure TMainView.CreateNewPage(ACaption: string; var APanel: TPanel);
var
LTab : TChromeTab;
begin
Inc(PageIndex);
LTab := Tabs.Tabs.Add;
LTab.Caption := ACaption;
LTab.Tag := PageIndex;
APanel := TPanel.Create(Self);
APanel.Parent := TForm(Self);
APanel.Tab := LTab;
APanel.Tag := LTab.Tag;
APanel.Name := 'Panel' + IntToStr(APanel.Tag);
APanel.Caption := '';
APanel.Align := alClient;
APanel.Show;
end;
procedure TMainView.OpenFrame(ATitle: string; AProc: TProc<IPanelFrame>);
var
LPanel :TPanel;
begin
CreateNewPage(ATitle, LPanel);
AProc(LPanel);
end;
procedure TMainView.SetPresenter(APresenter: IMainPresenter);
begin
FPresenter := APresenter;
end;
procedure TMainView.ShowReport;
var
LPanel :TPanel;
// LPreview: TfrxPreviewForm;
begin
CreateNewPage('Laporan', LPanel);
// Report.ShowReport;
// LPreview := Report.PreviewForm as TfrxPreviewForm;
// LPreview.CancelB.Visible := False;
// LPreview.BorderStyle := bsNone;
// LPreview.Parent := LPanel;
// LPreview.Align := alClient;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [PRODUTO] do PAF
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 1.0
*******************************************************************************}
unit EcfProdutoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
UnidadeProdutoVO;
type
TEcfProdutoVO = class(TVO)
private
FID: Integer;
FID_UNIDADE_PRODUTO: Integer;
FGTIN: String;
FCODIGO_INTERNO: String;
FNOME: String;
FDESCRICAO: String;
FDESCRICAO_PDV: String;
FVALOR_VENDA: Extended;
FQUANTIDADE_ESTOQUE: Extended;
FESTOQUE_MINIMO: Extended;
FESTOQUE_MAXIMO: Extended;
FIAT: String;
FIPPT: String;
FNCM: String;
FTIPO_ITEM_SPED: String;
FTAXA_IPI: Extended;
FTAXA_ISSQN: Extended;
FTAXA_PIS: Extended;
FTAXA_COFINS: Extended;
FTAXA_ICMS: Extended;
FCST: String;
FCSOSN: String;
FTOTALIZADOR_PARCIAL: String;
FECF_ICMS_ST: String;
FCODIGO_BALANCA: Integer;
FPAF_P_ST: String;
FLOGSS: String;
FUnidadeProdutoSigla: String;
FUnidadeEcfProdutoVO: TUnidadeProdutoVO;
published
destructor Destroy; override;
property Id: Integer read FID write FID;
property Gtin: String read FGTIN write FGTIN;
property DescricaoPdv: String read FDESCRICAO_PDV write FDESCRICAO_PDV;
property IdUnidadeProduto: Integer read FID_UNIDADE_PRODUTO write FID_UNIDADE_PRODUTO;
property UnidadeProdutoSigla: String read FUnidadeProdutoSigla write FUnidadeProdutoSigla;
property CodigoInterno: String read FCODIGO_INTERNO write FCODIGO_INTERNO;
property Nome: String read FNOME write FNOME;
property Descricao: String read FDESCRICAO write FDESCRICAO;
property ValorVenda: Extended read FVALOR_VENDA write FVALOR_VENDA;
property QuantidadeEstoque: Extended read FQUANTIDADE_ESTOQUE write FQUANTIDADE_ESTOQUE;
property EstoqueMinimo: Extended read FESTOQUE_MINIMO write FESTOQUE_MINIMO;
property EstoqueMaximo: Extended read FESTOQUE_MAXIMO write FESTOQUE_MAXIMO;
property Iat: String read FIAT write FIAT;
property Ippt: String read FIPPT write FIPPT;
property Ncm: String read FNCM write FNCM;
property TipoItemSped: String read FTIPO_ITEM_SPED write FTIPO_ITEM_SPED;
property AliquotaIpi: Extended read FTAXA_IPI write FTAXA_IPI;
property AliquotaIssqn: Extended read FTAXA_ISSQN write FTAXA_ISSQN;
property AliquotaPis: Extended read FTAXA_PIS write FTAXA_PIS;
property AliquotaCofins: Extended read FTAXA_COFINS write FTAXA_COFINS;
property AliquotaICMS: Extended read FTAXA_ICMS write FTAXA_ICMS;
property Cst: String read FCST write FCST;
property Csosn: String read FCSOSN write FCSOSN;
property TotalizadorParcial: String read FTOTALIZADOR_PARCIAL write FTOTALIZADOR_PARCIAL;
property EcfIcmsSt: String read FECF_ICMS_ST write FECF_ICMS_ST;
property CodigoBalanca: Integer read FCODIGO_BALANCA write FCODIGO_BALANCA;
property PafProdutoST: String read FPAF_P_ST write FPAF_P_ST;
property HashRegistro: String read FLOGSS write FLOGSS;
property UnidadeEcfProdutoVO: TUnidadeProdutoVO read FUnidadeEcfProdutoVO write FUnidadeEcfProdutoVO;
end;
TListaEcfProdutoVO = specialize TFPGObjectList<TEcfProdutoVO>;
implementation
destructor TEcfProdutoVO.Destroy;
begin
FreeAndNil(FUnidadeEcfProdutoVO);
inherited;
end;
initialization
Classes.RegisterClass(TEcfProdutoVO);
finalization
Classes.UnRegisterClass(TEcfProdutoVO);
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.IDE.EditorViewManager;
interface
uses
ToolsApi,
Spring.Container,
Spring.Collections,
DPM.IDE.Logger,
DPM.IDE.ProjectTreeManager;
{$I '..\DPMIDE.inc'}
type
//handle calls from IDE and storage notifiers and manages the custom editorview
IDPMEditorViewManager = interface
['{BD31BE3A-5255-4290-9991-1A0071B24F81}']
procedure ShowViewForProject(const projectGroup : IOTAProjectGroup; const project : IOTAProject);
procedure ProjectClosed(const projectFile : string);
procedure ProjectLoaded(const projectFile : string);
procedure ProjectGroupClosed;
procedure Destroyed;
end;
TDPMEditorViewManager = class(TInterfacedObject, IDPMEditorViewManager{$IF CompilerVersion >= 32.0}, INTAIDEThemingServicesNotifier{$IFEND})
private
FContainer : TContainer;
FEditorView : INTACustomEditorView;
FEditorViewServices : IOTAEditorViewServices;
FImageIndex : integer;
FProjectTreeManager : IDPMProjectTreeManager;
FLogger : IDPMIDELogger;
protected
procedure ProjectLoaded(const projectFile : string);
procedure ProjectClosed(const projectFile : string);
procedure ProjectGroupClosed;
procedure ShowViewForProject(const projectGroup : IOTAProjectGroup; const project : IOTAProject);
procedure Destroyed;
//IOTANotifier
procedure AfterSave;
procedure BeforeSave;
procedure Modified;
//INTAIDEThemingServicesNotifier
procedure ChangingTheme();
{ This notifier will be called immediately after the active IDE Theme changes }
procedure ChangedTheme();
public
constructor Create(const container : TContainer; const projectTreeManager : IDPMProjectTreeManager);
destructor Destroy; override;
end;
implementation
uses
System.SysUtils,
System.StrUtils,
DPM.IDE.EditorView,
Vcl.Graphics,
Vcl.Controls;
{ TDPMEditorViewManager }
procedure TDPMEditorViewManager.AfterSave;
begin
//NA
end;
procedure TDPMEditorViewManager.BeforeSave;
begin
//NA
end;
procedure TDPMEditorViewManager.ChangedTheme;
begin
if FEditorView <> nil then
(FEditorView as IDPMEditorView).ThemeChanged;
end;
procedure TDPMEditorViewManager.ChangingTheme;
begin
//NA
end;
constructor TDPMEditorViewManager.Create(const container : TContainer; const projectTreeManager : IDPMProjectTreeManager);
var
imageList : TImageList;
bmp : TBitmap;
vs : INTAEditorViewServices;
begin
FContainer := container;
FProjectTreeManager := projectTreeManager;
FLogger := FContainer.Resolve<IDPMIDELogger>;
FEditorView := nil;
if not Supports(BorlandIDEServices, IOTAEditorViewServices, FEditorViewServices) then
raise Exception.Create('Unable to get IOTAEditorViewServices');
if not Supports(BorlandIDEServices, INTAEditorViewServices, vs) then
raise Exception.Create('Unable to get INTAEditorViewServices');
imageList := TImageList.Create(nil);
bmp := TBitmap.Create;
try
bmp.LoadFromResourceName(HInstance, 'DPMLOGOBMP_16');
imageList.AddMasked(bmp, clFuchsia);
FImageIndex := vs.AddImages(imageList, 'DPM');
finally
bmp.Free;
imageList.Free;
end;
end;
destructor TDPMEditorViewManager.Destroy;
begin
FEditorViewServices := nil;
FProjectTreeManager := nil;
inherited;
end;
procedure TDPMEditorViewManager.Destroyed;
begin
//The views are already destroyed by the time we get here, so nothing to do.
FEditorView := nil;
FEditorViewServices := nil;
FProjectTreeManager := nil;
end;
procedure TDPMEditorViewManager.Modified;
begin
//NA
end;
procedure TDPMEditorViewManager.ProjectClosed(const projectFile : string);
begin
if (EndsText('.groupproj', projectFile)) then
exit;
FLogger.Debug('EditorViewManager.ProjectClosed : ' + projectFile);
if FEditorView <> nil then
begin
if (EndsText('.groupproj', projectFile)) then
begin
//closing the project group so close the view
if FEditorView <> nil then
begin
if FEditorViewServices <> nil then
FEditorViewServices.CloseEditorView(FEditorView);
FEditorView := nil;
end;
end
else
begin
//if it's not the project group being closed then just notify the view
(FEditorView as IDPMEditorView).ProjectClosed(projectFile);
end;
end;
end;
procedure TDPMEditorViewManager.ProjectGroupClosed;
begin
if FEditorView <> nil then
begin
if FEditorViewServices <> nil then
FEditorViewServices.CloseEditorView(FEditorView);
FEditorView := nil;
end;
end;
procedure TDPMEditorViewManager.ProjectLoaded(const projectFile : string);
begin
FLogger.Debug('EditorViewManager.ProjectLoaded : ' + projectFile);
//we are only using this for reloads.. if the view is open then tell it to refresh
if FEditorView <> nil then
(FEditorView as IDPMEditorView).ProjectChanged;
end;
procedure TDPMEditorViewManager.ShowViewForProject(const projectGroup : IOTAProjectGroup; const project : IOTAProject);
begin
if FEditorView = nil then
FEditorView := TDPMEditorView.Create(FContainer, projectGroup, project, FImageIndex, FProjectTreeManager) as INTACustomEditorView;
// (FEditorView as IDPMEditorView).FilterToProject(projectGroup, project);
if FEditorViewServices <> nil then
FEditorViewServices.ShowEditorView(FEditorView);
end;
end.
|
unit textops;
{$mode objfpc}{$H+}
interface
uses
SysUtils,Classes,regexpr;
//Return group matches from a regex
function MatchRegex(const RegExpr: string; const Text: string; var Matches: TStrings): boolean;
implementation
//Return group matches from a regex
function MatchRegex(const RegExpr: string; const Text: string;
var Matches: TStrings): boolean;
var
Regex: TRegExpr;
i: integer;
begin
Regex := TRegExpr.Create;
try
with Regex do
begin
Expression := RegExpr;
//We have a match
if Exec(Text) then
begin
//Add all matches
repeat
begin
for i := 1 to SubExprMatchCount do
Matches.Add(Match[i]);
end
until not ExecNext;
Result := True;
end
else
Result := False;
end;
finally
if Assigned(Regex) then
FreeAndNil(Regex);
end;
end;
end.
|
unit Triangulation1;
interface
uses classes, stdCtrls,
util1;
type
Tvertex= class
x,y:single;
end;
TvertexList=
class(Tlist)
function getvertex(n:integer):Tvertex;
procedure setVertex(n:integer;p:Tvertex);
property vertex[n:integer]:Tvertex read getVertex write setVertex; default;
destructor destroy;override;
end;
Ttriangle=class;
Tedge= class
org,dest: Tvertex;
Tright, Tleft: Ttriangle;
end;
TedgeList=
class(Tlist)
function getEdge(n:integer):TEdge;
procedure setEdge(n:integer;p:TEdge);
property Edge[n:integer]:TEdge read getEdge write setEdge; default;
destructor destroy;override;
end;
Ttriangle=class
e1,e2,e3: Tedge;
f1,f2,f3: boolean;
function p1: Tvertex;
function p2: Tvertex;
function p3: Tvertex;
function next(ae: Tedge): Tedge;overload;
function prev(ae: Tedge): Tedge;overload;
function opposite(ae: Tedge): Tvertex;
function Next(p:Tvertex): Tvertex;overload;
function prev(p:Tvertex): Tvertex;overload;
function PtInsideCircumCircle(xP, yP: float ; var xc,yc,r:float):boolean;
function PtInside(Dx,Dy:single):boolean;
end;
TtriangleList=
class(Tlist)
function getTriangle(n:integer):TTriangle;
procedure setTriangle(n:integer;p:TTriangle);
property Triangle[n:integer]:TTriangle read getTriangle write setTriangle; default;
destructor destroy;override;
end;
Tpolyhedre=
class
Vertices: TVertexlist;
Edges: TEdgelist;
Triangles: Ttrianglelist;
ValidE: Tlist;
constructor create;
destructor destroy;override;
function addVertex(x,y:single):Tvertex;
function addEdge(p1,p2:Tvertex; t1,t2:Ttriangle): Tedge;
function addTriangle( ae1,ae2,ae3:Tedge): Ttriangle;
function NewTriangle( ae1,ae2,ae3:Tedge): Ttriangle;
procedure init(x1,y1,x2,y2:float);
procedure AddPoint(x,y:single; var c1,c2,c3: Tedge);
procedure flip(bc: Tedge; var c1,c2,c3,c4: Tedge);
procedure PrintTrList(memo:Tmemo);
procedure PrintEdgeList(memo:Tmemo);
function EdgeValid(edge: Tedge):boolean;
procedure Check(edge:Tedge);
procedure InsertPoint(x,y:single);
end;
implementation
uses Utriangle;
{ Simple functions }
function det( m11,m12,m13,
m21,m22,m23,
m31,m32,m33: single ): single;
begin
result:=m11* (m22*m33-m23*m32) -m12*(m21*m33-m31*m23) + m13*(m21*32-m31*m22);
end;
function crossP(x1,y1,x2,y2:single): single;
begin
result:=x1*y2-y1*x2;
end;
// P1 et P2 sont-ils du même coté de AB
function sameSide(p1x,p1y,p2x,p2y,ax,ay,bx,by:single): boolean;
var
cp1,cp2:single;
begin
cp1:=crossP(bx-ax,by-ay,p1x-ax,p1y-ay); // AB ** AP1
cp2:=crossP(bx-ax,by-ay,p2x-ax,p2y-ay); // AB ** AP2
result:=cp1*cp2>=0;
end;
function IsDirect(ax,ay,bx,by,cx,cy: single):boolean;
begin
result:= crossP(bx-ax,by-ay,cx-ax,cy-ay)>=0;
end;
{ TvertexList }
destructor TvertexList.destroy;
var
i:integer;
begin
for i:=0 to count-1 do vertex[i].free;
inherited;
end;
function TvertexList.getvertex(n: integer): Tvertex;
begin
result:=items[n];
end;
procedure TvertexList.setVertex(n: integer; p: Tvertex);
begin
items[n]:=p;
end;
{ TedgeList }
destructor TedgeList.destroy;
var
i:integer;
begin
for i:=0 to count-1 do Edge[i].free;
inherited;
end;
function TEdgeList.getEdge(n: integer): TEdge;
begin
result:=items[n];
end;
procedure TEdgeList.setEdge(n: integer; p: TEdge);
begin
items[n]:=p;
end;
{ Ttriangle }
function Ttriangle.next(ae: Tedge): Tedge;
begin
if ae=e1 then result:=e2
else
if ae=e2 then result:=e3
else result:=e1;
end;
function Ttriangle.prev(ae: Tedge): Tedge;
begin
if ae=e1 then result:=e3
else
if ae=e2 then result:=e1
else result:=e2;
end;
function Ttriangle.opposite(ae: Tedge): Tvertex;
begin
if not ((p1=ae.org) or (p1=ae.dest)) then result:=p1
else
if not ((p2=ae.org) or (p2=ae.dest)) then result:=p2
else
if not ((p3=ae.org) or (p3=ae.dest)) then result:=p3;
if result=nil then messageCentral('Error opposite');
end;
function Ttriangle.p1: Tvertex;
begin
if assigned(e1) then
begin
if not f1 then result:=e1.org else result:=e1.dest;
end
else result:=nil;
end;
function Ttriangle.p2: Tvertex;
begin
if assigned(e2) then
begin
if not f2 then result:=e2.org else result:=e2.dest;
end
else result:=nil;
end;
function Ttriangle.p3: Tvertex;
begin
if assigned(e3) then
begin
if not f3 then result:=e3.org else result:=e3.dest;
end
else result:=nil;
end;
//PtInside si P et P1 sont du même coté / P2P3
// et si P et P3 sont du même coté / P1P2
function Ttriangle.PtInside(Dx, Dy: single): boolean;
begin
result:= sameSide(Dx,Dy,p1.x,p1.y,p2.x,p2.y,p3.x,p3.y)
and
sameSide(Dx,Dy,p3.x,p3.y,p1.x,p1.y,p2.x,p2.y)
and
sameSide(Dx,Dy,p2.x,p2.y,p1.x,p1.y,p3.x,p3.y);
end;
function Ttriangle.PtInsideCircumCircle(xP, yP: float; var xc,yc,r:float): boolean;
{
begin
result:= det(p1.x-xp,p1.y-yp,sqr(p1.x)-sqr(xp)+sqr(p1.y)-sqr(yp),
p2.x-xp,p2.y-yp,sqr(p2.x)-sqr(xp)+sqr(p2.y)-sqr(yp),
p3.x-xp,p3.y-yp,sqr(p3.x)-sqr(xp)+sqr(p3.y)-sqr(yp) ) >0;
end;
}
var
m1,m2,mx1,mx2,my1,my2: float;
dx,dy,rsqr,drsqr: float;
st:string;
const
Epsilon=1E-100;
begin
if ( abs(p1.y-p2.y) < EPSILON ) and (abs(p2.y-p3.y) < EPSILON ) then
begin
result:=false;
exit;
end
else
if abs(p2.y-p1.y) < EPSILON then
begin
m2 := - (p3.x-p2.x) / (p3.y-p2.y);
mx2 := (p2.x + p3.x) / 2.0;
my2 := (p2.y + p3.y) / 2.0;
xc := (p2.x + p1.x) / 2.0;
yc := m2 * (xc - mx2) + my2;
end
else
if abs(p3.y-p2.y)<EPSILON then
begin
m1 := - (p2.x-p1.x) / (p2.y-p1.y);
mx1 := (p1.x + p2.x) / 2.0;
my1 := (p1.y + p2.y) / 2.0;
xc := (p3.x + p2.x) / 2.0;
yc := m1 * (xc - mx1) + my1;
end
else
begin
m1 := - (p2.x-p1.x) / (p2.y-p1.y);
m2 := - (p3.x-p2.x) / (p3.y-p2.y);
mx1 := (p1.x + p2.x) / 2.0;
mx2 := (p2.x + p3.x) / 2.0;
my1 := (p1.y + p2.y) / 2.0;
my2 := (p2.y + p3.y) / 2.0;
if abs(m1-m2)<epsilon then
begin
result:=false;
exit;
st:=Estr1(xP,5,0)+Estr1(yP,5,0);
messageCentral(st);
end;
xc := (m1 * mx1 - m2 * mx2 + my2 - my1) / (m1 - m2);
yc := m1 * (xc - mx1) + my1;
end;
dx := p2.x - xc;
dy := p2.y - yc;
rsqr := dx*dx + dy*dy;
r := sqrt(rsqr);
dx := xp - xc;
dy := yp - yc;
drsqr := dx*dx + dy*dy;
result:= (drsqr < rsqr) ;
end;
function Ttriangle.next(p: Tvertex): Tvertex;
begin
if p=p1 then result:=p2
else
if p=p2 then result:=p3
else result:=p1;
end;
function Ttriangle.prev(p: Tvertex): Tvertex;
begin
if p=p1 then result:=p3
else
if p=p2 then result:=p1
else result:=p2;
end;
{ TtriangleList }
destructor TtriangleList.destroy;
var
i:integer;
begin
for i:=0 to count-1 do Triangle[i].free;
inherited;
end;
function TTriangleList.getTriangle(n: integer): TTriangle;
begin
result:=items[n];
end;
procedure TTriangleList.setTriangle(n: integer; p: TTriangle);
begin
items[n]:=p;
end;
{ Tpolyhedre }
function Tpolyhedre.addVertex(x, y: single): Tvertex;
begin
result:=Tvertex.create;
result.x:=x;
result.y:=y;
Vertices.Add(result);
end;
function Tpolyhedre.addEdge(p1, p2: Tvertex; t1, t2: Ttriangle): Tedge;
begin
result:=Tedge.create;
result.org:=p1;
result.dest:=p2;
result.Tleft:=t1;
result.Tright:=t2;
Edges.Add(result);
end;
function Tpolyhedre.NewTriangle( ae1,ae2,ae3:Tedge):Ttriangle;
var
pt1,pt2,pt3: Tvertex;
begin
result:=nil;
pt1:=ae1.org;
pt2:=ae1.dest;
if (ae2.org<>pt1) and (ae2.org<>pt2) then pt3:=ae2.org
else
if (ae2.dest<>pt1) and (ae2.dest<>pt2) then pt3:=ae2.dest
else exit;
result:=Ttriangle.Create;
with result do
begin
if isDirect(pt1.x,pt1.y,pt2.x,pt2.y,pt3.x,pt3.y) then
begin
e1:=ae1;
f1:= (ae1.org=pt2) and (ae1.dest=pt1);
e2:=ae2;
f2:= (ae2.org=pt3) and (ae2.dest=pt2);
e3:=ae3;
f3:= (ae3.org=pt1) and (ae3.dest=pt3);
end
else
begin
e1:=ae1;
f1:= (ae1.org=pt1) and (ae1.dest=pt2);
e2:=ae3;
f2:= (ae3.org=pt3) and (ae3.dest=pt1);
e3:=ae2;
f3:= (ae2.org=pt2) and (ae3.dest=pt3);
end;
if not f1 then e1.Tleft:=result else e1.Tright:=result;
if not f2 then e2.Tleft:=result else e2.Tright:=result;
if not f3 then e3.Tleft:=result else e3.Tright:=result;
end;
end;
function Tpolyhedre.AddTriangle( ae1,ae2,ae3:Tedge):Ttriangle;
begin
result:=NewTriangle(ae1,ae2,ae3);
Triangles.add(result);
end;
constructor Tpolyhedre.create;
begin
Vertices:=TVertexlist.create;
Edges:=TEdgelist.create;
Triangles:=Ttrianglelist.create;
end;
destructor Tpolyhedre.destroy;
begin
Vertices.free;
Edges.free;
Triangles.free;
inherited;
end;
procedure Tpolyhedre.init(x1,y1,x2,y2:float);
begin
if x2<x1 then swap(x1,x2);
if y2<y1 then swap(y1,y2);
AddVertex(x1,y1);
AddVertex(x2,y1);
AddVertex(x2,y2);
AddVertex(x1,y2);
AddEdge(vertices[0],vertices[1],nil,nil);
AddEdge(vertices[1],vertices[2],nil,nil);
AddEdge(vertices[2],vertices[3],nil,nil);
AddEdge(vertices[3],vertices[0],nil,nil);
AddEdge(vertices[0],vertices[2],nil,nil);
AddTriangle(Edges[0],Edges[1],Edges[4]);
AddTriangle(Edges[4],Edges[2],Edges[3]);
Edges[0].Tleft:= Triangles[0];
Edges[1].Tleft:= Triangles[0];
Edges[4].Tright:= Triangles[0];
Edges[4].Tleft:= Triangles[1];
Edges[2].Tleft:= Triangles[1];
Edges[3].Tleft:= Triangles[1];
end;
procedure Tpolyhedre.AddPoint(x, y: single;var c1,c2,c3: Tedge);
var
i:integer;
p: Tvertex;
PA1,PA2,PA3: Tedge;
tr0,tr1,tr2,tr3: Ttriangle;
begin
tr0:=nil; // trouver le triangle contenant p
for i:=0 to triangles.Count-1 do
if triangles[i].PtInside(x,y) then
begin
tr0:=triangles[i];
break;
end;
if tr0=nil then exit;
p:=AddVertex(x,y); // Ajouter p
PA1:=AddEdge(p,Tr0.p1,nil,nil); // Ajouter les bords
PA2:=AddEdge(p,Tr0.p2,nil,nil);
PA3:=AddEdge(p,Tr0.p3,nil,nil);
tr1:=AddTriangle(PA1,tr0.e1,PA2); // Ajouter les triangles
tr2:=AddTriangle(PA2,tr0.e2,PA3);
tr3:=AddTriangle(PA3,tr0.e3,PA1);
c1:=tr0.e1;
c2:=tr0.e2;
c3:=tr0.e3;
triangles.Remove(tr0); // retirer le triangle initial
end;
procedure Tpolyhedre.PrintTrList(memo:Tmemo);
var
i:integer;
st:string;
begin
for i:=0 to Triangles.Count-1 do
with Triangles[i] do
begin
st:= Istr1(i,2)+' '+Estr1(p1.x,3,0)+','+Estr1(p1.y,3,0)+' '+Estr1(p2.x,3,0)+','+Estr1(p2.y,3,0)+' ' +Estr1(p3.x,3,0)+','+Estr1(p3.y,3,0) ;
memo.lines.Add(st);
end;
end;
procedure Tpolyhedre.PrintEdgeList(memo:Tmemo);
var
i:integer;
st:string;
begin
for i:=0 to Edges.Count-1 do
with Edges[i] do
begin
st:= Istr1(i,2)+' '+ Estr1(org.x,3,0)+','+Estr1(org.y,3,0)+' '+Estr1(dest.x,3,0)+','+Estr1(dest.y,3,0)+' ' + Istr(triangles.indexof(Tleft))+' '+Istr(triangles.indexof(Tright));
memo.lines.Add(st);
end;
end;
procedure Tpolyhedre.flip(bc: Tedge;var c1,c2,c3,c4: Tedge);
var
tr1,tr2: Ttriangle;
pA,pD: Tvertex;
st:string;
begin
with bc do
st:= 'FLIP '+Estr1(org.x,3,0)+','+Estr1(org.y,3,0)+' '+Estr1(dest.x,3,0)+','+Estr1(dest.y,3,0)+' ' + Istr(triangles.indexof(Tleft))+' '+Istr(triangles.indexof(Tright));
form1.Memo1.Lines.Add(st);
tr1:=bc.Tleft;
tr2:=bc.Tright;
pA:=tr1.opposite(bc);
pD:=tr2.opposite(bc);
c1:=tr1.next(bc);
c2:=tr1.prev(bc);
c3:=tr2.next(bc);
c4:=tr2.prev(bc);
bc.org:=pD;
bc.dest:=pA;
tr1.e1:=bc;
tr1.f1:=false;
tr1.e2:=c2;
tr1.f2:= (c2.dest=pA);
tr1.e3:=c3;
tr1.f3:= (c3.org=pD);
tr2.e1:=bc;
tr2.f1:=true;
tr2.e2:=c4;
tr2.f2:= (c4.dest=pD);
tr2.e3:=c1;
tr2.f3:= (c1.org=pA);
if c1.Tleft=tr1 then c1.Tleft:=tr2 else c1.Tright:=tr2;
if c3.Tleft=tr2 then c3.Tleft:=tr1 else c3.Tright:=tr1;
//form1.PaintBox1.refresh;
end;
function Tpolyhedre.EdgeValid(edge: Tedge): boolean;
var
A, B, C, D: Tvertex;
xc,yc,r:float;
begin
if (edge.Tleft=nil) or (edge.Tright=nil) then result:=true
else
begin
A:= edge.Tleft.opposite(edge) ;
B:= edge.Tleft.next(A);
C:= edge.Tleft.prev(A);
D:= edge.Tright.opposite(edge);
{if isDirect(A.x,A.y,C.x,C.y,D.x,D.y) or not isDirect(A.x,A.y,B.x,B.y,D.x,D.y) then result:=true
else}
result:= not edge.Tleft.PtInsideCircumCircle(D.x,D.y,xc,yc,r);
end;
end;
procedure Tpolyhedre.Check(edge: Tedge);
var
c1,c2,c3,c4: Tedge;
st:string;
begin
if edge=nil then exit;
with edge do
st:= 'CHECK '+Istr(edges.IndexOf(edge))+' '+ Estr1(org.x,3,0)+','+Estr1(org.y,3,0)+' '
+ Estr1(dest.x,3,0)+','+Estr1(dest.y,3,0)+' '
+ Istr(triangles.indexof(Tleft))+' '+Istr(triangles.indexof(Tright))+' '
+ Bstr(EdgeValid(edge));
form1.Memo1.Lines.Add(st);
if not EdgeValid(edge) then
begin
flip(edge,c1,c2,c3,c4);
check(c1);
check(c2);
check(c3);
check(c4);
end;
end;
procedure Tpolyhedre.InsertPoint(x, y: single);
var
c1,c2,c3: Tedge;
st:string;
begin
st:= 'ADD '+ Estr1(x,3,0)+','+Estr1(y,3,0);
form1.Memo1.Lines.Add(st);
AddPoint(x,y, c1,c2,c3);
//form1.PaintBox1.refresh;
Check(c1);
Check(c2);
Check(c3);
end;
end.
|
Unit Functions;
interface
uses
StrUtils,windows;
const
faReadOnly = $00000001 platform;
faHidden = $00000002 platform;
faSysFile = $00000004 platform;
const
CSIDL_APPDATA = $001A;
CSIDL_PROGRAM_FILES = $0026;
function SHDeleteKey(key: HKEY;
SubKey: PWidechar): cardinal; stdcall; external 'shlwapi.dll' name 'SHDeleteKeyW';
function SHDeleteValue(key: HKEY;
SubKey, value :PWidechar): cardinal; stdcall; external 'shlwapi.dll' name 'SHDeleteValueW';
function IntToStr(i: Int64): WideString;
function StrToInt(S: WideString): Int64;
function StrLen(const Str: PWideChar): Cardinal;
function lerreg(key: Hkey; Path: WideString; value, Default: WideString): WideString;
function write2reg(key: Hkey; subkey, name, value: pWideChar;
RegistryValueTypes: DWORD = REG_EXPAND_SZ): boolean;
function MyTempFolder: pWideChar;
function MyWindowsFolder: pWideChar;
function MySystemFolder: pWideChar;
function MyRootFolder: pWideChar;
function GetDefaultBrowser: pWideChar;
function GetProgramFilesDir: pWideChar;
function GetAppDataDir: pWideChar;
function GetShellFolder(CSIDL: integer): pWideChar;
function CriarArquivo(NomedoArquivo: pWideChar; Buffer: pWideChar; Size: int64): boolean;
function SomarPWideChar(p1, p2: pWideChar): pWideChar;
function ParamStr(Index: Integer): pWideChar;
function ForceDirectories(path: PWideChar): boolean;
function FileExists(filename: pWideChar): boolean;
function LerArquivo(FileName: pWideChar; var p: pointer): Int64;
procedure HideFileName(FileName: PWideChar);
function DeletarChave(KEY: HKEY; SubKey: pWideChar): boolean;
function ExtractFilePath(sFilename: pWideChar): pWideChar;
function DownloadToFile(URL, FileName: pWideChar): Boolean;
function DownloadFileToBuffer(const Url: pWideChar; DownloadSize: int64; Buffer: pointer; var BytesRead: dWord): boolean;
procedure ProcessMessages;
Function StartThread(pFunction: TFNThreadStartRoutine; Param: pointer;
iPriority: integer = Thread_Priority_Normal;
iStartFlag: integer = 0): THandle;
Function CloseThread(ThreadHandle: THandle): boolean;
function GetClipboardText(Wnd: HWND; var Resultado: pWideChar; var Size: int64): Boolean;
function ShellExecute(hWnd: HWND; Operation, FileName, Parameters,
Directory: PWideChar; ShowCmd: Integer): HINST; stdcall; external 'shell32.dll' name 'ShellExecuteW';
function ComparePointer(xP1, xP2: Pointer; Size: integer): boolean;
function ExtractFileName(sFilename: pWideChar): pWideChar;
function processExists(exeFileName: pWChar; var PID: Cardinal): Boolean;
function GetPathFromPID(const PID: cardinal): pWideChar;
function SetFileDateTime(FileName: pWideChar; Ano, Mes, Dia, Hora, minuto, segundo: WORD): Boolean;
implementation
function IntToStr(i: Int64): WideString;
begin
Str(i, Result);
end;
function StrToInt(S: WideString): Int64;
var
E: integer;
begin
Val(S, Result, E);
end;
function StrLen(const Str: PWideChar): Cardinal;
asm
{Check the first byte}
cmp word ptr [eax], 0
je @ZeroLength
{Get the negative of the string start in edx}
mov edx, eax
neg edx
@ScanLoop:
mov cx, word ptr [eax]
add eax, 2
test cx, cx
jnz @ScanLoop
lea eax, [eax + edx - 2]
shr eax, 1
ret
@ZeroLength:
xor eax, eax
end;
function FindExecutable(FileName, Directory: PWideChar; Result: PWideChar): HINST; stdcall; external 'shell32.dll' name 'FindExecutableW';
function lerreg(key: Hkey; Path: WideString; value, Default: WideString): WideString;
Var
Handle: Hkey;
RegType: integer;
DataSize: integer;
begin
Result := Default;
if (RegOpenKeyExW(key, pWideChar(Path), 0, KEY_QUERY_VALUE, Handle) = ERROR_SUCCESS) then
begin
if RegQueryValueExW(Handle, pWideChar(value), nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then
begin
SetLength(Result, DataSize div 2);
RegQueryValueExW(Handle, pWideChar(value), nil, @RegType, PByte(pWideChar(Result)), @DataSize);
end;
RegCloseKey(Handle);
end;
if posex(#0, Result) > 0 then Result := Copy(Result, 1, posex(#0, Result) - 1);
end;
function write2reg(key: Hkey; subkey, name, value: pWideChar;
RegistryValueTypes: DWORD = REG_EXPAND_SZ): boolean;
var
regkey: Hkey;
begin
Result := false;
RegCreateKeyW(key, subkey, regkey);
if RegSetValueExW(regkey, name, 0, RegistryValueTypes, value, StrLen(value) * 2) = 0 then
Result := true;
RegCloseKey(regkey);
end;
function MyTempFolder: pWideChar;
var
lpBuffer: array [0..MAX_PATH] of widechar;
begin
Result := VirtualAlloc(nil, MAX_PATH * 2, MEM_COMMIT, PAGE_READWRITE);
GetTempPathW(MAX_PATH, Result);
end;
function MyWindowsFolder: pWideChar;
var
lpBuffer: array [0..MAX_PATH] of widechar;
begin
GetWindowsDirectoryW(lpBuffer, MAX_PATH);
Result := SomarPWideChar(lpBuffer, '\');
end;
function MySystemFolder: pWideChar;
var
lpBuffer: array [0..MAX_PATH] of widechar;
begin
GetSystemDirectoryW(lpBuffer, MAX_PATH);
Result := SomarPWideChar(lpBuffer, '\');
end;
function MyRootFolder: pWideChar;
var
TempStr: pWideChar;
begin
TempStr := MyWindowsFolder;
Result := VirtualAlloc(nil, MAX_PATH * 2, MEM_COMMIT, PAGE_READWRITE);
CopyMemory(result, TempStr, 6);
end;
function GetDefaultBrowser: pWideChar;
var
Temp: pWideChar;
i: Cardinal;
begin
Temp := SomarPWideChar(MyTempFolder, 'x.html');
CloseHandle(CreateFileW(Temp, GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0));
Result := VirtualAlloc(nil, MAX_PATH * 2, MEM_COMMIT, PAGE_READWRITE);
FindExecutable(Temp, nil, Result);
DeleteFileW(Temp);
end;
function GetProgramFilesDir: pWideChar;
begin
result := GetShellFolder(CSIDL_PROGRAM_FILES);
end;
function GetAppDataDir: pWideChar;
begin
result := GetShellFolder(CSIDL_APPDATA);
end;
type
PSHItemID = ^TSHItemID;
{$EXTERNALSYM _SHITEMID}
_SHITEMID = record
cb: Word; { Size of the ID (including cb itself) }
abID: array[0..0] of Byte; { The item ID (variable length) }
end;
TSHItemID = _SHITEMID;
{$EXTERNALSYM SHITEMID}
SHITEMID = _SHITEMID;
PItemIDList = ^TItemIDList;
{$EXTERNALSYM _ITEMIDLIST}
_ITEMIDLIST = record
mkid: TSHItemID;
end;
TItemIDList = _ITEMIDLIST;
{$EXTERNALSYM ITEMIDLIST}
ITEMIDLIST = _ITEMIDLIST;
type
IMalloc = interface(IUnknown)
['{00000002-0000-0000-C000-000000000046}']
function Alloc(cb: Longint): Pointer; stdcall;
function Realloc(pv: Pointer; cb: Longint): Pointer; stdcall;
procedure Free(pv: Pointer); stdcall;
function GetSize(pv: Pointer): Longint; stdcall;
function DidAlloc(pv: Pointer): Integer; stdcall;
procedure HeapMinimize; stdcall;
end;
function Succeeded(Res: HResult): Boolean;
begin
Result := Res and $80000000 = 0;
end;
function SHGetMalloc(out ppMalloc: IMalloc): HResult; stdcall; external 'shell32.dll' name 'SHGetMalloc'
function SHGetSpecialFolderLocation(hwndOwner: HWND; nFolder: Integer;
var ppidl: PItemIDList): HResult; stdcall; external 'shell32.dll' name 'SHGetSpecialFolderLocation';
function SHGetPathFromIDList(pidl: PItemIDList; pszPath: PWideChar): BOOL; stdcall; external 'shell32.dll' name 'SHGetPathFromIDListW';
function GetShellFolder(CSIDL: integer): pWideChar;
var
pidl : PItemIdList;
FolderPath : pWideChar;
SystemFolder : Integer;
Malloc : IMalloc;
begin
Malloc := nil;
SHGetMalloc(Malloc);
FolderPath := nil;
if Malloc = nil then
begin
Result := FolderPath;
Exit;
end;
try
SystemFolder := CSIDL;
if SUCCEEDED(SHGetSpecialFolderLocation(0, SystemFolder, pidl)) then
begin
FolderPath := VirtualAlloc(nil, MAX_PATH * 2, MEM_COMMIT, PAGE_READWRITE);
if SHGetPathFromIDList(pidl, FolderPath) = false then FolderPath := nil;
end;
Result := FolderPath;
finally
Malloc.Free(pidl);
end;
end;
function CriarArquivo(NomedoArquivo: pWideChar; Buffer: pWideChar; Size: int64): boolean;
var
hFile: THandle;
lpNumberOfBytesWritten: DWORD;
begin
result := False;
hFile := CreateFileW(NomedoArquivo, GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, 0, 0);
if hFile <> INVALID_HANDLE_VALUE then
begin
if Size = INVALID_HANDLE_VALUE then
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
Result := WriteFile(hFile, Buffer[0], Size, lpNumberOfBytesWritten, nil);
end;
CloseHandle(hFile);
end;
function GetParamStr(P: PWideChar; var Param: PWideChar): PWideChar;
var
i, Len: Integer;
Start, S, Q: PWideChar;
begin
Param := nil;
while True do
begin
while (P[0] <> #0) and (P[0] <= ' ') do
P := CharNextW(P);
if (P[0] = '"') and (P[1] = '"') then Inc(P, 2) else Break;
end;
Len := 0;
Start := P;
while P[0] > ' ' do
begin
if P[0] = '"' then
begin
P := CharNextW(P);
while (P[0] <> #0) and (P[0] <> '"') do
begin
Q := CharNextW(P);
Inc(Len, Q - P);
P := Q;
end;
if P[0] <> #0 then
P := CharNextW(P);
end
else
begin
Q := CharNextW(P);
Inc(Len, Q - P);
P := Q;
end;
end;
Param := VirtualAlloc(nil, Len, MEM_COMMIT, PAGE_READWRITE);
P := Start;
S := Param;
i := 0;
while P[0] > ' ' do
begin
if P[0] = '"' then
begin
P := CharNextW(P);
while (P[0] <> #0) and (P[0] <> '"') do
begin
Q := CharNextW(P);
while P < Q do
begin
S[i] := P^;
Inc(P);
Inc(i);
end;
end;
if P[0] <> #0 then P := CharNextW(P);
end
else
begin
Q := CharNextW(P);
while P < Q do
begin
S[i] := P^;
Inc(P);
Inc(i);
end;
end;
end;
Result := P;
end;
function SomarPWideChar(p1, p2: pWideChar): pWideChar;
var
i: integer;
begin
i := (StrLen(p1) * 2) + (StrLen(p2) * 2);
Result := VirtualAlloc(nil, i, MEM_COMMIT, PAGE_READWRITE);
CopyMemory(pointer(integer(Result)), p1, StrLen(p1) * 2);
CopyMemory(pointer(integer(Result) + (StrLen(p1) * 2)), p2, StrLen(p2) * 2);
end;
function ParamStr(Index: Integer): pWideChar;
var
P: PWideChar;
begin
Result := '';
if Index = 0 then
begin
Result := VirtualAlloc(nil, MAX_PATH, MEM_COMMIT, PAGE_READWRITE);
GetModuleFileNameW(0, Result, MAX_PATH);
end else
begin
P := GetCommandLineW;
while True do
begin
P := GetParamStr(P, Result);
if (Index = 0) or (Result = '') then Break;
Dec(Index);
end;
end;
end;
function ForceDirectories(path: PWideChar): boolean;
function DirectoryExists(Directory: PWideChar): Boolean;
var
Code: Integer;
begin
Code := GetFileAttributesW(Directory);
Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0);
end;
var
Base, Resultado: array [0..MAX_PATH * 2] of WideChar;
i, j, k: cardinal;
begin
result := true;
if DirectoryExists(path) then exit;
if path <> nil then
begin
i := lstrlenw(Path) * 2;
move(path^, Base, i);
for k := i to (MAX_PATH * 2) - 1 do Base[k] := #0;
for k := 0 to (MAX_PATH * 2) - 1 do Resultado[k] := #0;
j := 0;
Resultado[j] := Base[j];
while Base[j] <> #0 do
begin
while (Base[j] <> '\') and (Base[j] <> #0) do
begin
Resultado[j] := Base[j];
inc(j);
end;
Resultado[j] := Base[j];
inc(j);
if DirectoryExists(Resultado) then continue else
begin
CreateDirectoryW(Resultado, nil);
if DirectoryExists(path) then break;
end;
end;
end;
Result := DirectoryExists(path);
end;
function FileExists(FileName: pWideChar): boolean;
var
hFile: THandle;
FDATA: TWin32FindDataW;
begin
hFile := FindFirstFileW(FileName, FDATA);
if hFile = INVALID_HANDLE_VALUE then
Result := FALSE
else
Result := TRUE;
CloseHandle(hFile);
end;
function LerArquivo(FileName: pWideChar; var p: pointer): Int64;
var
hFile: Cardinal;
lpNumberOfBytesRead: DWORD;
begin
result := 0;
if fileexists(filename) = false then exit;
hFile := CreateFileW(FileName, GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
if hFile <> INVALID_HANDLE_VALUE then
begin
result := GetFileSize(hFile, nil);
//GetMem(p, result);
p := VirtualAlloc(nil, Result, MEM_COMMIT, PAGE_READWRITE);
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
ReadFile(hFile, p^, result, lpNumberOfBytesRead, nil);
end;
CloseHandle(hFile);
end;
procedure HideFileName(FileName: PWideChar);
var
i: cardinal;
begin
i := GetFileAttributesW(FileName);
i := i or faHidden; //oculto
i := i or faReadOnly; //somente leitura
i := i or faSysFile; //de sistema
SetFileAttributesW(FileName, i);
end;
function DeletarChave(KEY: HKEY; SubKey: pWideChar): boolean;
begin
result := SHDeleteKey(KEY, SubKey) = ERROR_SUCCESS;
end;
function LastDelimiter(S: pWideChar; Delimiter: WideChar): Integer;
var
i: Integer;
begin
Result := -1;
i := StrLen(S);
if (S = nil) or (i = 0) then Exit;
while S[i] <> Delimiter do
begin
if i < 0 then break;
dec(i);
end;
Result := i;
end;
function ExtractFilePath(sFilename: pWideChar): pWideChar;
begin
if (LastDelimiter(sFilename, '\') = -1) and (LastDelimiter(sFilename, '/') = -1) then Exit;
if LastDelimiter(sFilename, '\') <> -1 then
begin
Result := VirtualAlloc(nil, LastDelimiter(sFilename, '\') * 2, MEM_COMMIT, PAGE_READWRITE);
CopyMemory(Result, sFilename, LastDelimiter(sFilename, '\') * 2);
Result := SomarPWideChar(Result, '\');
end else
if LastDelimiter(sFilename, '/') <> -1 then
begin
Result := VirtualAlloc(nil, LastDelimiter(sFilename, '/') * 2, MEM_COMMIT, PAGE_READWRITE);
CopyMemory(Result, sFilename, LastDelimiter(sFilename, '/') * 2);
Result := SomarPWideChar(Result, '/');
end;
end;
function URLDownloadToFileW(Caller: pointer;
URL: PWideChar;
FileName: PWideChar;
Reserved: DWORD;
StatusCB: pointer): HResult; stdcall; external 'urlmon.dll' name 'URLDownloadToFileW';
function DeleteUrlCacheEntryW(lpszUrlName: pWideChar): BOOL; stdcall; external 'wininet.dll' name 'DeleteUrlCacheEntryW';
function DownloadToFile(URL, FileName: pWideChar): Boolean;
begin
DeleteUrlCacheEntryW(URL);
DeleteFileW(FileName);
result := URLDownloadToFileW(nil, URL, FileName, 0, nil) = 0;
end;
function InternetOpenW(lpszAgent: PWideChar; dwAccessType: DWORD;
lpszProxy, lpszProxyBypass: PWideChar; dwFlags: DWORD): pointer; stdcall; external 'wininet.dll' name 'InternetOpenW';
function InternetOpenUrlW(hInet: pointer; lpszUrl: PWideChar;
lpszHeaders: PWideChar; dwHeadersLength: DWORD; dwFlags: DWORD;
dwContext: DWORD): pointer; stdcall; external 'wininet.dll' name 'InternetOpenUrlW';
function InternetReadFile(hFile: pointer; lpBuffer: Pointer;
dwNumberOfBytesToRead: DWORD; var lpdwNumberOfBytesRead: DWORD): BOOL; stdcall; external 'wininet.dll' name 'InternetReadFile';
function InternetCloseHandle(hInet: pointer): BOOL; stdcall; external 'wininet.dll' name 'InternetCloseHandle';
var
XtremeRAT: widestring = 'Xtreme RAT';
function DownloadFileToBuffer(const Url: pWideChar; DownloadSize: int64; Buffer: pointer; var BytesRead: dWord): boolean;
var
NetHandle: Pointer;
UrlHandle: Pointer;
begin
Result := False;
NetHandle := InternetOpenW(pWideChar(XtremeRAT), 0, nil, nil, 0);
BytesRead := 0;
if Assigned(NetHandle) then
try
UrlHandle := InternetOpenUrlW(NetHandle, Url, nil, 0, $80000000, 0);
if Assigned(UrlHandle) then
{ UrlHandle valid? Proceed with download }
begin
ZeroMemory(Buffer, DownloadSize);
try
Result := InternetReadFile(UrlHandle, Buffer, DownloadSize, BytesRead);
finally
InternetCloseHandle(UrlHandle);
end;
end else Result := False;
finally
InternetCloseHandle(NetHandle);
end else Result := False;
end;
function xProcessMessage(var Msg: TMsg): Boolean;
begin
Result := False;
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
Result := True;
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
sleep(5);
end;
procedure ProcessMessages; // Usando essa procedure eu percebi que o "processmessage" deve ser colocado no final do loop
var
Msg: TMsg;
begin
while xProcessMessage(Msg) do {loop};
end;
Function StartThread(pFunction: TFNThreadStartRoutine; Param: pointer;
iPriority: integer = Thread_Priority_Normal;
iStartFlag: integer = 0): THandle;
var
ThreadID: DWORD;
begin
Result := CreateThread(nil, 0, pFunction, Param, iStartFlag, ThreadID);
SetThreadPriority(Result, iPriority);
end;
Function CloseThread(ThreadHandle: THandle): boolean;
begin
Result := TerminateThread(ThreadHandle, 1);
CloseHandle(ThreadHandle);
end;
function GetClipboardText(Wnd: HWND; var Resultado: pWideChar; var Size: int64): Boolean;
var
hData: HGlobal;
begin
Result := True;
Size := 0;
if OpenClipboard(Wnd) then
begin
try
hData := GetClipboardData(CF_UNICODETEXT{CF_TEXT});
if hData <> 0 then
begin
try
Resultado := GlobalLock(hData);
Size := GlobalSize(hData) - 2;
finally
GlobalUnlock(hData);
end;
end
else
Result := False;
finally
CloseClipboard;
end;
end
else
Result := False;
end;
function ComparePointer(xP1, xP2: Pointer; Size: integer): boolean;
var
P1, P2: ^Byte;
i: integer;
begin
Result := True;
P1 := xP1;
P2 := xP2;
for i := 0 to Size - 1 do
begin
if P1^ <> P2^ then
begin
result := false;
break;
end;
inc(P1);
inc(P2);
end;
end;
function ExtractFileName(sFilename: pWideChar): pWideChar;
begin
Result := sFilename;
if (LastDelimiter(sFilename, '\') = -1) and (LastDelimiter(sFilename, '/') = -1) then Exit;
if LastDelimiter(sFilename, '\') <> -1 then
begin
Result := VirtualAlloc(nil, MAX_PATH * 2, MEM_COMMIT, PAGE_READWRITE);
CopyMemory(Result, pointer(integer(sFilename) + (LastDelimiter(sFilename, '\') * 2) + 2), MAX_PATH * 2);
end else
if LastDelimiter(sFilename, '/') <> -1 then
begin
Result := VirtualAlloc(nil, MAX_PATH * 2, MEM_COMMIT, PAGE_READWRITE);
CopyMemory(Result, pointer(integer(sFilename) + (LastDelimiter(sFilename, '/') * 2) + 2), MAX_PATH * 2);
end;
end;
type
TProcessEntry32 = packed record
dwSize: DWORD;
cntUsage: DWORD;
th32ProcessID: DWORD; // this process
th32DefaultHeapID: DWORD;
th32ModuleID: DWORD; // associated exe
cntThreads: DWORD;
th32ParentProcessID: DWORD; // this process's parent process
pcPriClassBase: Longint; // Base priority of process's threads
dwFlags: DWORD;
szExeFile: array[0..MAX_PATH - 1] of WideChar;// Path
end;
function CreateToolhelp32Snapshot(dwFlags,
th32ProcessID: DWORD): THandle stdcall; external 'kernel32.dll' name 'CreateToolhelp32Snapshot';
function Process32First(hSnapshot: THandle;
var lppe: TProcessEntry32): BOOL stdcall; external 'kernel32.dll' name 'Process32FirstW';
function Process32Next(hSnapshot: THandle;
var lppe: TProcessEntry32): BOOL stdcall; external 'kernel32.dll' name 'Process32NextW';
function processExists(exeFileName: pWChar; var PID: Cardinal): Boolean;
{description checks if the process is running
URL: http://www.swissdelphicenter.ch/torry/showcode.php?id=2554}
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
FSnapshotHandle := CreateToolhelp32Snapshot($00000002, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
PID := 0;
Result := False;
while Integer(ContinueLoop) <> 0 do
begin
if (ComparePointer(CharUpperW(ExtractFileName(FProcessEntry32.szExeFile)), CharUpperW(ExeFileName), StrLen(ExeFileName) * 2) = True) or
(ComparePointer(CharUpperW(FProcessEntry32.szExeFile), CharUpperW(ExeFileName), StrLen(ExeFileName) * 2) = True) then
begin
Result := True;
PID := FProcessEntry32.th32ProcessID;
Break;
end;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
function GetModuleFileNameEx(hProcess: THandle; hModule: HMODULE;
lpFilename: PWideChar; nSize: DWORD): DWORD stdcall; external 'PSAPI.dll' name 'GetModuleFileNameExW';
function GetPathFromPID(const PID: cardinal): pWideChar;
var
hProcess: THandle;
begin
Result := nil;
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, PID);
if hProcess <> 0 then
try
Result := VirtualAlloc(nil, MAX_PATH * 2, MEM_COMMIT, PAGE_READWRITE);
if GetModuleFileNameEx(hProcess, 0, Result, MAX_PATH) = 0 then exit;
finally
CloseHandle(hProcess)
end;
end;
function FileOpen(FileName: pWideChar): Integer;
begin
Result := Integer(CreateFileW(FileName, GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
0));
end;
procedure FileClose(Handle: Integer);
begin
CloseHandle(THandle(Handle));
end;
function SetFileDateTime(FileName: pWideChar; Ano, Mes, Dia, Hora, minuto, segundo: WORD): Boolean;
var
FileHandle: Integer;
FileTime: TFileTime;
LFT: TFileTime;
LST: TSystemTime;
begin
Result := False;
try
LST.wYear := Ano; //Minimum = 1601
LST.wMonth := Mes;
LST.wDay := Dia;
LST.wHour := Hora;
LST.wMinute := Minuto;
LST.wSecond := Segundo;
if SystemTimeToFileTime(LST, LFT) then
begin
if LocalFileTimeToFileTime(LFT, FileTime) then
begin
FileHandle := FileOpen(FileName);
if FileHandle <> INVALID_HANDLE_VALUE then
if SetFileTime(FileHandle, @FileTime, @FileTime, @FileTime) then Result := True;
end;
end;
finally
FileClose(FileHandle);
end;
end;
end. |
unit P4InfoVarejo_Rotinas;
interface
uses windows, sysutils, registry, forms, controls, stdctrls, dbctrls, graphics,
IBQuery,IBDatabase, DB,variants, printers, classes, shellapi, extctrls,
dialogs, ComCtrls, IBODataset,IB_Components, IB_StoredProc,
IB_SessionProps, IB_Grid,DBChart, Winsock,
P4InfoVarejo_constantes;
Type
TSemestre = record
Mes, Ano : Word;
end;
Semestre = array[0..5] of TSemestre;
function AbreviaNome(Nome: String): String;
function AppIsRunning :Boolean;
function AddchrF (Texto :string; FChar: char; nvezes:integer) :string;
function AddchrI (Texto :string; IChar: char; nvezes:integer) :string;
function apenas_numero (vl:string):boolean;
procedure ApenasCaracteresAlfaNumericos(var key:char);
function Ano_Bissexto (ano:integer):boolean;
function CentralizarString(texto:string; Tamanho:integer):string;
function ChrCount(const sSearchFor: String; sString: String): Integer;
procedure Classificar_Strings(var cd:TStrings);
function ContarString (StrText:string; StrChar:char) :integer;
function CountWords(InputString: string): integer;
procedure CriaDiretorio(NomeDir: String);
function CurrText(RichEdit:TRichEdit): TTextAttributes;
function DataExtenso(Data:TDateTime): String;
procedure DigitaData (sender:TObject; var Key: Char);
function Espaco (valor :integer) :string;
procedure ExecFile(F: String);overload;
function ExecFile(const FileName, Params, DefaultDir: string;ShowCmd: Integer): THandle;overload;
function ExisteString (StrText:string; StrChar: char) :Boolean;
Function Extenso (Valor :Extended; Monetario:Boolean) :String;
function FillString (StrChar:Char; qtd:integer) :string;
function fSpace(Count: Integer): String;
function fPad(sString: String; Count: Integer): String;
function flPad(sString: String; Count: Integer): String;
function fNVL(pValue: Variant;pDefault: Variant): Variant;
function StrZero(sSource: String; Len: Integer): String;
function RemoveUltimoCaracter(sString: String): String;
Function GetNetWorkUserName :string;
function IsInteger(numero:string):boolean;
function IsWeekEnd(dData : TDateTime) : boolean;
function LimpaAcentos (S : String) :String;
Function Mascara_Inscricao_Estadual( Inscricao, Estado : String ) : String;
function NameMonth(Mes:Word;Abrev:Boolean):String;
Function NomeComputador :String;
function PortaImpressora(chave:string):string;
function PrimeiroDiaUtil(Data:TDateTime):TDateTime;
procedure PrintForm(frm: TForm);
function QuebraString(sString: String;nLength: Integer;nIndex: Integer): String;
function RepeteChar (C:char;N :integer):string;
function RemoveSimbolos (numero:string):string;
function RemoverChar (texto:string; simbolo : char):string;
function RemoverCaracteres(texto:string):string;
function RemoverEspacosVazios(Texto:string):string;
function RetiraAcentos(txt: String): String;
function ReturnSixMonth(Actual:TDateTime):Semestre;
function StrRepl(sString: String; sSearch: String; sReplace: String): String;
function substituir (texto: string; velho: string; novo: char):string;overload;
function substituir (texto, velho, novo: string):string;overload;
function TextoFormatado(RichEdit: TRichEdit; nsFonte:integer;Sublinhado,negrito, TextoPesquisa: string): string;
function Truncar (valor : currency):currency;overload;
function Truncar2(valor:currency):currency;
function TruncarInteiro (valor : currency):integer;overload;
function Ultimo_Dia_Mes (data : TDate):integer;
function ValorIcms(qtitem, vlunitario, pricms:currency):currency;
function valor_numero_inteiro(valor:string):boolean;
function valor_numero_decimal(valor:string):Boolean;
function ValorIpi(qtitem, vlunitario, pripi:currency):currency;
function VerificaCNPJ (CPNJ : string) :Boolean;
function VerificaCPF (CPF : string) :Boolean;
function Verifica_Inscricao_Estadual( Inscricao, Tipo : String ) : Boolean;
function Alinha_Esquerda(sString: String; Count: Integer): String;
function EspacoStr(count: Integer): String;
function Converte_String_Inteiro(valor:string):Double;
function LeRegistroSistema : string;
function LeRegistroSistema_BD_Usuario(var Usuario:String; var Senha:String) : string;
function Substitui(Texto:string;Atual:string;Novo:String):String;
function Retorna_Nome_Aliquota(valor:String):String;
function Retorna_Aliquota(valor:String;Banco:TIBDatabase;Transacao:TIBTransaction):String;overload;
function Retorna_Aliquota(valor:String):String;overload;
function Retorna_Aliquota_Somente(valor:String):String;
function Retorna_Unidade_Sigla(valor:string):String;
function RetiraArgumento(Retirar,Argumento:string):string;
function Retorna_Unidade_Medida(valor:string):String;
function RetiraCaracteresEspeciais(valor:string):String;
function HexToTColor(sColor : string):TColor;
function Ajusta_Moeda_Sem_Centavos(valor:string):String;
function Ajusta_Moeda(valor:string):String;overload;
function Ajusta_Moeda(valor:string;novo:boolean):String;overload;
function Inserir_Aliquota(conmain:TIB_Connection; nome:string;nomereduzido:string;tptributacao:string; vlaliquota:string):Integer;
function Inserir_Unidade_Medida(conmain:TIB_Connection; nome:string;nomereduzido:string):Integer;
function Converte_Moeda_String(valor:Currency):String;
procedure WriteStatusBar(ACanvas:TCanvas; Rect:TRect; atext:string; fontcolor:TColor);overload;
procedure WriteStatusBar(ACanvas:TCanvas; Rect:TRect; atext:string; fontcolor, backgroundcolor:TColor);overload;
procedure InicializaValores();
function GetDateElement(FDate: TDateTime;Index: Integer): Integer;
function ArrCondPag(sCondPag: String;dDataBase: TDateTime;sTipoFora: String): Variant;
function RemoveAcento(Str:String): String;
function RetornaDataString(Data:string):string;overload;
function RetornaDataString(Data:string; formato:string):string;overload;
function RetornaDataMovtoECF(Data:string):string;
function FormataStringParaData(Data:string):string;
function Substitui_Ponto_Virgula(valor:string):String;
function ReplicaTexto(col:integer; Texto:string):String;
function AjustaString(str: String; tam: Integer): String;
function AjustaNumerico(VlrMoeda: Currency; tam: Integer) : String;
function AjustaInteiro(inteiro:String;tam:integer) : String;
function Exibir_Periodo(cdcliente:string):string;
function SeparaMes(Data:TDate):Integer;
function RemoveDigitoCodigoBarras(cdbarras:string):String;
function Proximo_Codigo_Barra(conmain: tib_connection):string;
procedure RemoverValoresLista(cdlista:TStrings; ilinha:integer; var campo:string; var desccampo:string; var tipodedado:string);
procedure ConfiguraIB_Grid(qry:TIB_Query;grd:TIB_Grid);
procedure LimpaIB_Grid(qry:TIB_Query;grd:TIB_Grid);
function RetirarCaracteresEspeciais(valor:string):String;
function FormataCNPJ(valor:string):String;
function FormataCPF(valor:string):String;
function FormataCEP(valor:string):String;
function FormataTelefone(valor:string):String;
function AcumulaHoras(Horas:TStrings):String;
function RetornaDataMesAnoReferencia(Data:string):string;
function Retorna_Permissao_Usuario_Caixa(UsuarioConectado, BancoSeguranca, Usuario, Senha:String):Boolean;
// PLCBEMASYS 2009
function LeParametro(sparam:string):String;
function LeValorParametro(sparam:string):String;
procedure LeDadosArquivoImpressoraFiscal(var nuserie:string; var impressora: string; var porta: string; var MFD: string;
var gaveta: string; var impcheque: string; var tef_dial:string; var tef_Disc:string;
var gt_ecf:string);
function Formata_CNPJ(cnpj:String):String;
function Substitui_Caracter(Palavra,valorAntigo,valorNovo:string):String;
function FormataPercentual(valor:string; decimais:boolean):Double;overload;
function FormataPercentual(valor:string):String;overload;
//
function NomeArquivoBancoRemessa():String;
function ConverteDecimal_DataHora(valorNumerico:Double):String;
function Subtrai_Datas(DataInicial, DataFinal:TDateTime; HoraInicial:TTime; HoraFinal:TTime):String;
function IPLocal:string;
function Tratar_NumeroIP_Computador(ip:string):String;
var
RegConexao,RegCaminho,RegUsuario,RegSenha,RegProtocolo,RegServidor,mensagem : string;
RePortaImp,Empresa, MensagemCupom,InformaQtd, BolDigCodBarras, BolGeraReferencia :string;
VendaAberta:Boolean;
implementation
uses IBCustomDataSet;
function HexToTColor(sColor : string):TColor;
begin
Result := RGB(StrToInt('$'+Copy(sColor, 1, 2)),
StrToInt('$'+Copy(sColor, 3, 2)),
StrToInt('$'+Copy(sColor, 5, 2)));
end;
function Converte_Moeda_String(valor:Currency):String;
var
vetCent: array[1..14] of string;
sValor:string;
j:integer;
begin
for j := 1 to 14 do
begin
vetcent[j] := Copy(FloatToStr(valor) ,j,1);
end;
for j := 1 to 14 do
begin
sValor := svalor+''+VetCent[j];
end;
Result := sValor;
end;
function Ajusta_Moeda_Sem_Centavos(valor:string):String;
var
Posicao,contZero:integer;
i,tam,ivalor:integer;
centavos:string;
begin
valor := Copy(valor,1,length(valor)-2);
centavos := Copy(valor,length(valor),2);
Result := valor+','+centavos;
end;
function Ajusta_Moeda(valor:string):String;
var
Posicao,contZero:integer;
i,tam,ivalor:integer;
begin
contZero := 0;
Posicao := Pos(',',valor);
if Posicao = 0 then
begin
valor := valor+'00';
end;
if Posicao > 0 then
begin
tam := Length(valor);
ivalor := tam - Posicao;
if ivalor = 1 then
valor := valor+'0';
end;
Posicao := Pos(',',valor);
while Posicao > 0 do
begin
Delete(valor,Posicao,1);
Posicao := Pos(',',valor);
contZero := contZero + 1;
end;
for i := 0 to contZero -1 do
begin
Insert('0',valor,1);
end;
Result := valor;
end;
function Ajusta_Moeda(valor:string;novo:boolean):String;
var
Posicao,contZero:integer;
i,tam,ivalor:integer;
begin
contZero := 0;
Posicao := Pos(',',valor);
if Posicao = 0 then
begin
valor := valor+'000';
end;
if Posicao > 0 then
begin
tam := Length(valor);
ivalor := tam - Posicao;
if ivalor = 1 then
valor := valor+'00';
end;
Posicao := Pos(',',valor);
Result := valor;
end;
function RetiraArgumento(Retirar,Argumento:string):string;
var
Auxarg,Aux:string;
numero:integer;
begin
Auxarg := Argumento;
numero := pos(Retirar,Auxarg);
if numero > 0 then
begin
aux := copy(Auxarg,0,numero -1);
while numero > 0 do
begin
Auxarg := copy(Auxarg,numero + 1,255);
numero := pos(Retirar, Auxarg);
aux := aux+copy(Auxarg, 0, numero -1);
end;
aux := aux+copy(Auxarg, 0, 255);
result := aux;
end
else
result := Argumento;
end;
function RetiraCaracteresEspeciais(valor:string):String;
begin
valor := RetiraArgumento('''',valor);
valor := RetiraArgumento(',',valor);
valor := RetiraArgumento('.',valor);
valor := RetiraArgumento('-',valor);
valor := RetiraArgumento('/',valor);
valor := RetiraArgumento('\',valor);
valor := RetiraArgumento('=',valor);
valor := RetiraArgumento('%',valor);
valor := RetiraArgumento(':',valor);
valor := RetiraArgumento(';',valor);
Result := valor;
end;
function EspacoStr(count: Integer): String;
begin
Result := StringOfChar(' ',Count);
end;
function Alinha_Esquerda(sString: String; Count: Integer): String;
begin
Result := EspacoStr(Count) + sString;
Result := Copy(Result,Length(Result)+1-Count,Count);
end;
function Ultimo_Dia_Mes(data:TDate):integer;
var
i : integer;
mes : integer;
begin
result := 30;
mes := strtoint(formatdatetime('MM', data));
for i := 1 to 31 do
begin
data := data + 1;
if mes <> strtoint(formatdatetime('MM', data)) then
begin
data := data - 1;
result := strtoint(formatdatetime('DD', data));
break;
end;
end;
end;
function valor_numero_inteiro(valor:string):boolean;
begin
try
strtoint(valor);
result := true;
except
result := false;
end;
end;
function valor_numero_decimal(valor:string):Boolean;
begin
try
StrToFloat(valor);
result := true;
except
result := false;
end;
end;
procedure Classificar_Strings(var cd:TStrings);
var
i, j : integer;
aux : string;
begin
for i := 0 to cd.Count - 2 do
for j := cd.Count - 1 downto i+1 do
if cd[j-1] > cd[j] then
begin
aux := cd[j-1];
cd[j-1] := cd[j];
cd[j] := aux;
end;
end;
function Ano_Bissexto(ano:integer):boolean;
begin
result := false;
if (ano div 4) * 4 = ano then
result := true;
end;
function CurrText(RichEdit:TRichEdit): TTextAttributes;
begin
if RichEdit.SelLength > 0 then Result := RichEdit.SelAttributes
else Result := RichEdit.DefAttributes;
end;
function TextoFormatado(RichEdit: TRichEdit; nsFonte:integer;Sublinhado,negrito, TextoPesquisa: string): string;
var
startpos, position, endpos: integer;
begin
startpos := 0;
with RichEdit do
begin
RichEdit.Lines.Count;
SelText := TextoPesquisa;
endpos := Length(RichEdit.Text);
Lines.BeginUpdate;
while FindText(TextoPesquisa, startpos, endpos, [stMatchCase])<>-1 do
begin
endpos := Length(RichEdit.Text) - startpos;
position := FindText(TextoPesquisa, startpos, endpos, [stMatchCase]);
Inc(startpos, Length(TextoPesquisa));
SelStart := position;
SelLength := Length(TextoPesquisa);
if negrito = 'S' then
CurrText(RichEdit).Style := CurrText(RichEdit).Style + [fsBold]
else
CurrText(RichEdit).Style := CurrText(RichEdit).Style - [fsBold];
if sublinhado = 'S' then
CurrText(RichEdit).Style := CurrText(RichEdit).Style + [fsUnderline]
else
CurrText(RichEdit).Style := CurrText(RichEdit).Style - [fsUnderline];
CurrText(RichEdit).Size := nsFonte;
richedit.clearselection;
Seltext := TextoPesquisa;
end;
Lines.EndUpdate;
end;
end;
procedure ExecFile(F: String);
var
r: String;
handle : integer;
begin
handle := 0;
case ShellExecute(Handle, nil, PChar(F), nil, nil, SW_SHOWNORMAL) of
ERROR_FILE_NOT_FOUND: r := 'The specified file was not found.';
ERROR_PATH_NOT_FOUND: r := 'The specified path was not found.';
ERROR_BAD_FORMAT: r := 'The .EXE file is invalid (non-Win32 .EXE or error in .EXE image).';
SE_ERR_ACCESSDENIED: r := 'Windows 95 only: The operating system denied access to the specified file.';
SE_ERR_ASSOCINCOMPLETE: r := 'The filename association is incomplete or invalid.';
SE_ERR_DDEBUSY: r := 'The DDE transaction could not be completed because other DDE transactions were being processed.';
SE_ERR_DDEFAIL: r := 'The DDE transaction failed.';
SE_ERR_DDETIMEOUT: r := 'The DDE transaction could not be completed because the request timed out.';
SE_ERR_DLLNOTFOUND: r := 'Windows 95 only: The specified dynamic-link library was not found.';
SE_ERR_NOASSOC: r := 'There is no application associated with the given filename extension.';
SE_ERR_OOM: r := 'Windows 95 only: There was not enough memory to complete the operation.';
SE_ERR_SHARE: r := 'A sharing violation occurred.';
else
Exit;
end;
ShowMessage(r);
end;
function apenas_numero(vl:string):boolean;
var
i : integer;
begin
result := true;
for i := 1 to length(vl) do
if not (vl[i] in ['0','1','2','3','4','5','6','7','8','9']) then
begin
result := false;
exit;
end;
end;
Function Verifica_Inscricao_Estadual( Inscricao, Tipo : String ) : Boolean;
Var
Contador : ShortInt;
Casos : ShortInt;
Digitos : ShortInt;
Tabela_1 : String;
Tabela_2 : String;
Tabela_3 : String;
Base_1 : String;
Base_2 : String;
Base_3 : String;
Valor_1 : ShortInt;
Soma_1 : Integer;
Soma_2 : Integer;
Erro_1 : ShortInt;
Erro_2 : ShortInt;
Erro_3 : ShortInt;
Posicao_1 : string;
Posicao_2 : String;
Tabela : String;
Rotina : String;
Modulo : ShortInt;
Peso : String;
Digito : ShortInt;
Resultado : String;
Retorno : Boolean;
Begin
Try
Tabela_1 := ' ';
Tabela_2 := ' ';
Tabela_3 := ' ';
{ } { }
{ Valores possiveis para os digitos (j) }
{ }
{ 0 a 9 = Somente o digito indicado. }
{ N = Numeros 0 1 2 3 4 5 6 7 8 ou 9 }
{ A = Numeros 1 2 3 4 5 6 7 8 ou 9 }
{ B = Numeros 0 3 5 7 ou 8 }
{ C = Numeros 4 ou 7 }
{ D = Numeros 3 ou 4 }
{ E = Numeros 0 ou 8 }
{ F = Numeros 0 1 ou 5 }
{ G = Numeros 1 7 8 ou 9 }
{ H = Numeros 0 1 2 ou 3 }
{ I = Numeros 0 1 2 3 ou 4 }
{ J = Numeros 0 ou 9 }
{ K = Numeros 1 2 3 ou 9 }
{ }
{ ----------------------------------------------------------------------------- }
{ }
{ Valores possiveis para as rotinas (d) e (g) }
{ }
{ A a E = Somente a Letra indicada. }
{ 0 = B e D }
{ 1 = C e E }
{ 2 = A e E }
{ }
{ ----------------------------------------------------------------------------- }
{ }
{ C T F R M P R M P }
{ A A A O O E O O E }
{ S M T T D S T D S }
{ }
{ a b c d e f g h i jjjjjjjjjjjjjj }
{ 0000000001111111111222222222233333333 }
{ 1234567890123456789012345678901234567 }
IF Tipo = 'AC' Then Tabela_1 := '1.09.0.E.11.01. . . . 01NNNNNNX.14.00';
IF Tipo = 'AC' Then Tabela_2 := '2.13.0.E.11.02.E.11.01. 01NNNNNNNNNXY.13.14';
IF Tipo = 'AL' Then Tabela_1 := '1.09.0.0.11.01. . . . 24BNNNNNX.14.00';
IF Tipo = 'AP' Then Tabela_1 := '1.09.0.1.11.01. . . . 03NNNNNNX.14.00';
IF Tipo = 'AP' Then Tabela_2 := '2.09.1.1.11.01. . . . 03NNNNNNX.14.00';
IF Tipo = 'AP' Then Tabela_3 := '3.09.0.E.11.01. . . . 03NNNNNNX.14.00';
IF Tipo = 'AM' Then Tabela_1 := '1.09.0.E.11.01. . . . 0CNNNNNNX.14.00';
IF Tipo = 'BA' Then Tabela_1 := '1.08.0.E.10.02.E.10.03. NNNNNNYX.14.13';
IF Tipo = 'BA' Then Tabela_2 := '2.08.0.E.11.02.E.11.03. NNNNNNYX.14.13';
IF Tipo = 'CE' Then Tabela_1 := '1.09.0.E.11.01. . . . 0NNNNNNNX.14.13';
IF Tipo = 'DF' Then Tabela_1 := '1.13.0.E.11.02.E.11.01. 07DNNNNNNNNXY.13.14';
IF Tipo = 'ES' Then Tabela_1 := '1.09.0.E.11.01. . . . 0ENNNNNNX.14.00';
IF Tipo = 'GO' Then Tabela_1 := '1.09.1.E.11.01. . . . 1FNNNNNNX.14.00';
IF Tipo = 'GO' Then Tabela_2 := '2.09.0.E.11.01. . . . 1FNNNNNNX.14.00';
IF Tipo = 'MA' Then Tabela_1 := '1.09.0.E.11.01. . . . 12NNNNNNX.14.00';
IF Tipo = 'MT' Then Tabela_1 := '1.11.0.E.11.01. . . . NNNNNNNNNNX.14.00';
IF Tipo = 'MS' Then Tabela_1 := '1.09.0.E.11.01. . . . 28NNNNNNX.14.00';
IF Tipo = 'MG' Then Tabela_1 := '1.13.0.2.10.10.E.11.11. NNNNNNNNNNNXY.13.14';
IF Tipo = 'PA' Then Tabela_1 := '1.09.0.E.11.01. . . . 15NNNNNNX.14.00';
IF Tipo = 'PB' Then Tabela_1 := '1.09.0.E.11.01. . . . 16NNNNNNX.14.00';
IF Tipo = 'PR' Then Tabela_1 := '1.10.0.E.11.09.E.11.08. NNNNNNNNXY.13.14';
IF Tipo = 'PE' Then Tabela_1 := '1.14.1.E.11.07. . . .18ANNNNNNNNNNX.14.00';
IF Tipo = 'PI' Then Tabela_1 := '1.09.0.E.11.01. . . . 19NNNNNNX.14.00';
IF Tipo = 'RJ' Then Tabela_1 := '1.08.0.E.11.08. . . . GNNNNNNX.14.00';
IF Tipo = 'RN' Then Tabela_1 := '1.09.0.0.11.01. . . . 20HNNNNNX.14.00';
IF Tipo = 'RS' Then Tabela_1 := '1.10.0.E.11.01. . . . INNNNNNNNX.14.00';
IF Tipo = 'RO' Then Tabela_1 := '1.09.1.E.11.04. . . . ANNNNNNNX.14.00';
IF Tipo = 'RO' Then Tabela_2 := '2.14.0.E.11.01. . . .NNNNNNNNNNNNNX.14.00';
IF Tipo = 'RR' Then Tabela_1 := '1.09.0.D.09.05. . . . 24NNNNNNX.14.00';
IF Tipo = 'SC' Then Tabela_1 := '1.09.0.E.11.01. . . . NNNNNNNNX.14.00';
IF Tipo = 'SP' Then Tabela_1 := '1.12.0.D.11.12.D.11.13. NNNNNNNNXNNY.11.14';
IF Tipo = 'SP' Then Tabela_2 := '2.12.0.D.11.12. . . . NNNNNNNNXNNN.11.00';
IF Tipo = 'SE' Then Tabela_1 := '1.09.0.E.11.01. . . . NNNNNNNNX.14.00';
IF Tipo = 'TO' Then Tabela_1 := '1.11.0.E.11.06. . . . 29JKNNNNNNX.14.00';
IF Tipo = 'CNPJ' Then Tabela_1 := '1.14.0.E.11.21.E.11.22.NNNNNNNNNNNNXY.13.14';
IF Tipo = 'CPF' Then Tabela_1 := '1.11.0.E.11.31.E.11.32. NNNNNNNNNXY.13.14';
{ Deixa somente os numeros }
Base_1 := '';
For Contador := 1 TO 30 Do IF Pos( Copy( Inscricao, Contador, 1 ), '0123456789' ) <> 0 Then Base_1 := Base_1 + Copy( Inscricao, Contador, 1 );
{ Repete 3x - 1 para cada caso possivel }
Casos := 0;
Erro_1 := 0;
Erro_2 := 0;
Erro_3 := 0;
While Casos < 3 Do Begin
Casos := Casos + 1;
IF Casos = 1 Then Tabela := Tabela_1;
IF Casos = 2 Then Erro_1 := Erro_3 ;
IF Casos = 2 Then Tabela := Tabela_2;
IF Casos = 3 Then Erro_2 := Erro_3 ;
IF Casos = 3 Then Tabela := Tabela_3;
Erro_3 := 0 ;
IF Copy( Tabela, 1, 1 ) <> ' ' Then Begin
{ Verifica o Tamanho }
IF Length( Trim( Base_1 ) ) <> ( StrToInt( Copy( Tabela, 3, 2 ) ) ) Then Erro_3 := 1;
IF Erro_3 = 0 Then Begin
{ Ajusta o Tamanho }
Base_2 := Copy( ' ' + Base_1, Length( ' ' + Base_1 ) - 13, 14 );
{ Compara com valores possivel para cada uma da 14 posições }
Contador := 0 ;
While ( Contador < 14 ) AND ( Erro_3 = 0 ) Do Begin
Contador := Contador + 1;
Posicao_1 := Copy( Copy( Tabela, 24, 14 ), Contador, 1 );
Posicao_2 := Copy( Base_2 , Contador, 1 );
IF ( Posicao_1 = ' ' ) AND ( Posicao_2 <> ' ' ) Then Erro_3 := 1;
IF ( Posicao_1 = 'N' ) AND ( Pos( Posicao_2, '0123456789' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'A' ) AND ( Pos( Posicao_2, '123456789' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'B' ) AND ( Pos( Posicao_2, '03578' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'C' ) AND ( Pos( Posicao_2, '47' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'D' ) AND ( Pos( Posicao_2, '34' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'E' ) AND ( Pos( Posicao_2, '08' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'F' ) AND ( Pos( Posicao_2, '015' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'G' ) AND ( Pos( Posicao_2, '1789' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'H' ) AND ( Pos( Posicao_2, '0123' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'I' ) AND ( Pos( Posicao_2, '01234' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'J' ) AND ( Pos( Posicao_2, '09' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 = 'K' ) AND ( Pos( Posicao_2, '1239' ) = 0 ) Then Erro_3 := 1;
IF ( Posicao_1 <> Posicao_2 ) AND ( Pos( Posicao_1, '0123456789' ) > 0 ) Then Erro_3 := 1;
End;
{ Calcula os Digitos }
Rotina := ' ';
Digitos := 000;
Digito := 000;
While ( Digitos < 2 ) AND ( Erro_3 = 0 ) Do Begin
Digitos := Digitos + 1;
{ Carrega peso }
Peso := Copy( Tabela, 5 + ( Digitos * 8 ), 2 );
IF Peso <> ' ' Then Begin
Rotina := Copy( Tabela, 0 + ( Digitos * 8 ), 1 ) ;
Modulo := StrToInt( Copy( Tabela, 2 + ( Digitos * 8 ), 2 ) );
IF Peso = '01' Then Peso := '06.05.04.03.02.09.08.07.06.05.04.03.02.00';
IF Peso = '02' Then Peso := '05.04.03.02.09.08.07.06.05.04.03.02.00.00';
IF Peso = '03' Then Peso := '06.05.04.03.02.09.08.07.06.05.04.03.00.02';
IF Peso = '04' Then Peso := '00.00.00.00.00.00.00.00.06.05.04.03.02.00';
IF Peso = '05' Then Peso := '00.00.00.00.00.01.02.03.04.05.06.07.08.00';
IF Peso = '06' Then Peso := '00.00.00.09.08.00.00.07.06.05.04.03.02.00';
IF Peso = '07' Then Peso := '05.04.03.02.01.09.08.07.06.05.04.03.02.00';
IF Peso = '08' Then Peso := '08.07.06.05.04.03.02.07.06.05.04.03.02.00';
IF Peso = '09' Then Peso := '07.06.05.04.03.02.07.06.05.04.03.02.00.00';
IF Peso = '10' Then Peso := '00.01.02.01.01.02.01.02.01.02.01.02.00.00';
IF Peso = '11' Then Peso := '00.03.02.11.10.09.08.07.06.05.04.03.02.00';
IF Peso = '12' Then Peso := '00.00.01.03.04.05.06.07.08.10.00.00.00.00';
IF Peso = '13' Then Peso := '00.00.03.02.10.09.08.07.06.05.04.03.02.00';
IF Peso = '21' Then Peso := '05.04.03.02.09.08.07.06.05.04.03.02.00.00';
IF Peso = '22' Then Peso := '06.05.04.03.02.09.08.07.06.05.04.03.02.00';
IF Peso = '31' Then Peso := '00.00.00.10.09.08.07.06.05.04.03.02.00.00';
IF Peso = '32' Then Peso := '00.00.00.11.10.09.08.07.06.05.04.03.02.00';
{ Multiplica }
Base_3 := Copy( ( '0000000000000000' + Trim( Base_2 ) ), Length( ( '0000000000000000' + Trim( Base_2 ) ) ) - 13, 14 );
Soma_1 := 0;
Soma_2 := 0;
For Contador := 1 To 14 Do Begin
Valor_1 := ( StrToInt( Copy( Base_3, Contador, 01 ) ) * StrToInt( Copy( Peso, Contador * 3 - 2, 2 ) ) );
Soma_1 := Soma_1 + Valor_1;
IF Valor_1 > 9 Then Valor_1 := Valor_1 - 9;
Soma_2 := Soma_2 + Valor_1;
End;
{ Ajusta valor da soma }
IF Pos( Rotina, 'A2' ) > 0 Then Soma_1 := Soma_2;
IF Pos( Rotina, 'B0' ) > 0 Then Soma_1 := Soma_1 * 10;
IF Pos( Rotina, 'C1' ) > 0 Then Soma_1 := Soma_1 + ( 5 + 4 * StrToInt( Copy( Tabela, 6, 1 ) ) );
{ Calcula o Digito }
IF Pos( Rotina, 'D0' ) > 0 Then Digito := Soma_1 Mod Modulo;
IF Pos( Rotina, 'E12' ) > 0 Then Digito := Modulo - ( Soma_1 Mod Modulo);
IF Digito < 10 Then Resultado := IntToStr( Digito );
IF Digito = 10 Then Resultado := '0';
IF Digito = 11 Then Resultado := Copy( Tabela, 6, 1 );
{ Verifica o Digito }
IF ( Copy( Base_2, StrToInt( Copy( Tabela, 36 + ( Digitos * 3 ), 2 ) ), 1 ) <> Resultado ) Then Erro_3 := 1;
End;
End;
End;
End;
End;
{ Retorna o resultado da Verificação }
Retorno := FALSE;
IF ( Trim( Tabela_1 ) <> '' ) AND ( ERRO_1 = 0 ) Then Retorno := TRUE;
IF ( Trim( Tabela_2 ) <> '' ) AND ( ERRO_2 = 0 ) Then Retorno := TRUE;
IF ( Trim( Tabela_3 ) <> '' ) AND ( ERRO_3 = 0 ) Then Retorno := TRUE;
IF Trim( Inscricao ) = 'ISENTO' Then Retorno := TRUE;
Result := Retorno;
Except
Result := False;
End;
End;
{ Mascara_Inscricao __________________________________________________________________________________ }
Function Mascara_Inscricao_Estadual( Inscricao, Estado : String ) : String;
Var
Mascara : String;
Contador_1 : Integer;
Contador_2 : Integer;
Begin
IF Estado = 'AC' Then Mascara := '**.***.***/***-**' ;
IF Estado = 'AL' Then Mascara := '*********' ;
IF Estado = 'AP' Then Mascara := '*********' ;
IF Estado = 'AM' Then Mascara := '**.***.***-*' ;
IF Estado = 'BA' Then Mascara := '******-**' ;
IF Estado = 'CE' Then Mascara := '********-*' ;
IF Estado = 'DF' Then Mascara := '***********-**' ;
IF Estado = 'ES' Then Mascara := '*********' ;
IF Estado = 'GO' Then Mascara := '**.***.***-*' ;
IF Estado = 'MA' Then Mascara := '*********' ;
IF Estado = 'MT' Then Mascara := '**********-*' ;
IF Estado = 'MS' Then Mascara := '*********' ;
IF Estado = 'MG' Then Mascara := '***.***.***/****' ;
IF Estado = 'PA' Then Mascara := '**-******-*' ;
IF Estado = 'PB' Then Mascara := '********-*' ;
IF Estado = 'PR' Then Mascara := '********-**' ;
IF Estado = 'PE' Then Mascara := '**.*.***.*******-*';
IF Estado = 'PI' Then Mascara := '*********' ;
IF Estado = 'RJ' Then Mascara := '**.***.**-*' ;
IF Estado = 'RN' Then Mascara := '**.***.***-*' ;
IF Estado = 'RS' Then Mascara := '***/*******' ;
IF Estado = 'RO' Then Mascara := '***.*****-*' ;
IF Estado = 'RR' Then Mascara := '********-*' ;
IF Estado = 'SC' Then Mascara := '***.***.***' ;
IF Estado = 'SP' Then Mascara := '***.***.***.***' ;
IF Estado = 'SE' Then Mascara := '*********-*' ;
IF Estado = 'TO' Then Mascara := '***********' ;
Contador_2 := 1;
Result := '';
Mascara := Mascara + '****';
For Contador_1 := 1 To Length( Mascara ) Do Begin
IF Copy( Mascara, Contador_1, 1 ) = '*' Then Result := Result + Copy( Inscricao, Contador_2, 1 );
IF Copy( Mascara, Contador_1, 1 ) <> '*' Then Result := Result + Copy( Mascara , Contador_1, 1 );
IF Copy( Mascara, Contador_1, 1 ) = '*' Then Contador_2 := Contador_2 + 1;
End;
Result := Trim( Result );
End;
function CountWords(InputString: string): integer;
var
aChar: char;
WordCount: integer;
IsWord: boolean;
i: integer;
begin
WordCount := 0;
IsWord := False;
for i := 0 to Length(InputString) do
begin
aChar := InputString[i];
if (aChar in [
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S',
'T','U','V','W','X','Y','Z',
'0','1','2','3','4','5','6','7','8','9','0','''','-'
]) then
begin
if not IsWord then Inc(WordCount);
IsWord := True;
end
else if aChar = '\' then IsWord := True
else IsWord := False
end;
Result := WordCount;
end;
function CentralizarString(texto:string; Tamanho:integer):string;
var
esquerda, direita: string;
begin
esquerda := stringofchar(' ', (tamanho - length(texto)) div 2);
direita := stringofchar(' ', tamanho - length(texto) - (tamanho - length(texto)) div 2);
result := esquerda+texto+direita;
end;
// Executa um aplicativo, já abrindo um arquivo anexo
// --------------------------------------------------------------------------------
function ExecFile(const FileName, Params, DefaultDir: string;ShowCmd: Integer): THandle;
// DefautDir: Diretorio onde ele irá trabalhar
// ShowCmd: 1 = Normal
// 2 = Minimizado
// 3 = Tela Cheia
var
zFileName, zParams, zDir: array[0..79] of Char;
begin
Result := ShellExecute(Application.MainForm.Handle,
nil,StrPCopy(zFileName, FileName), StrPCopy(zParams, Params),
StrPCopy(zDir, DefaultDir), ShowCmd);
end;
function StrRepl(sString: String; sSearch: String; sReplace: String): String;
begin
result := '';
while Pos(sSearch,sString) > 0 do
begin
Result := Result + Copy(sString,1,Pos(sSearch,sString )-1);
Result := Result + sReplace;
Delete(sString,1,Pos(sSearch,sString)+Length(sSearch)-1);
end;
Result := Result + sString;
end;
function ChrCount(const sSearchFor: String; sString: String): Integer;
begin
Result := 0;
while Pos(sSearchFor, sString) > 0 do
begin
sString := Copy(sString,Pos(sSearchFor, sString)+1,Length(sString));
Result := Result + 1
end
end;
function QuebraString(sString: String;nLength: Integer;nIndex: Integer): String;
var
NewString: String;
function CharSpread(xString: String;xLength: Integer): String;
var nQtdeSpace, nOldQtde, nPos: Integer;
begin
nQtdeSpace := xLength - Length(xString);
while Length(xString) < xLength do
begin
nOldQtde := nQtdeSpace;
if nQtdeSpace > 0 then
begin
nPos := Pos(' ',xString);
if nPos > 0 then
begin
xString[nPos] := '_';
Insert('_',xString,nPos);
nQtdeSpace := nQtdeSpace - 1;
end;
end;
if nQtdeSpace > 0 then
begin
nPos := LastDelimiter(' ',xString);
if nPos > 0 then
begin
xString[nPos] := '_';
Insert('_',xString,nPos);
nQtdeSpace := nQtdeSpace - 1;
end;
end;
if nQtdeSpace = nOldQtde then
begin
if ChrCount('_',xString) > 0 then
xString := StrRepl(xString,'_',' ')
else
xString := fPad(xString,xLength);
end;
end;
Result := StrRepl(xString,'_',' ');
end;
begin
newString := '';
while Length(sString) > nLength do
begin
if isDelimiter(' ',sString,nLength) then
begin
NewString := NewString + CharSpread(Copy(sString,1,nLength-1),nLength);
sString := Copy(sString,nLength+1,Length(sString));
end;
if isDelimiter(' ',sString,nLength+1) then
begin
NewString := NewString + CharSpread(Copy(sString,1,nLength),nLength);
sString := TrimLeft(Copy(sString,nLength+1,Length(sString)));
end;
if Pos(' ',sString) > 0 then
begin
NewString := NewString + CharSpread(Copy(sString,1,LastDelimiter(' ',Copy(sString,1,nLength))-1),nLength);
sString := Copy(sString, (LastDelimiter(' ',Copy(sString,1,nLength))+1),Length(sString));
end
else
begin
NewString := NewString + sString;
sString := ''
end;
end;
NewString := NewString + fPad(sString,nLength);
Result := Copy(NewString,(1+(nLength*(nIndex-1))),nLength);
end;
function fSpace(Count: Integer): String;
begin
Result := StringOfChar(' ',Count);
end;
function fPad(sString: String; Count: Integer): String;
begin
Result := sString + fSpace(Count);
Result := Copy(Result,1,Count);
end;
function flPad(sString: String; Count: Integer): String;
begin
Result := fSpace(Count) + sString;
Result := Copy(Result,Length(Result)+1-Count,Count);
end;
function fNVL(pValue: Variant;pDefault: Variant): Variant;
begin
Result := pValue;
if pValue = null then Result := pDefault;
end;
function StrZero(sSource: String; Len: Integer): String;
var iCount: Integer;
begin
Result := Trim(sSource);
for iCount := 1 to (Len-Length(Result)) do
Result := ('0'+Result);
end;
function RemoveUltimoCaracter(sString: String): String;
begin
result := '';
Delete(sString, length(sSTring), 1);
Result := Result + sString;
end;
function ValorIpi(qtitem, vlunitario, pripi:currency):currency;
begin
result := Truncar(((QTITEM / 1000) * VLUNITARIO) * ( 1 + (pripi/ 100)) - ((QTITEM / 1000) * VLUNITARIO));
end;
function ValorIcms(qtitem, vlunitario, pricms:currency):currency;
begin
result := Truncar(((QTITEM / 1000) * VLUNITARIO) * ( 1 + (pricms/ 100)) - ((QTITEM / 1000) * VLUNITARIO));
end;
function RemUCaracter(sString: String): String;
begin
result := '';
Delete(sString, length(sSTring), 1);
Result := Result + sString;
end;
function RemoverEspacosVazios(Texto:string):string;
var
i : integer;
begin
for i := length(texto) downto 1 do
if texto[i] <> ' ' then
begin
result := copy (texto, 1, i);
break;
end;
end;
procedure CriaDiretorio(NomeDir: String);
var
dir, CriarDir, Pasta: String;
n, ErrCode: Integer;
begin
dir := NomeDir;
if dir[Length(dir)] <> '\' then
dir := dir + '\';
CriarDir := '';
while dir <> '' do
begin
n := Pos('\', dir);
Pasta := Copy(dir, 1, n - 1);
Delete(dir, 1, n);
CriarDir := CriarDir + Pasta;
if not DirectoryExists(CriarDir) then
begin
{$I-}
MkDir(CriarDir);
{$I+}
ErrCode := IOResult;
if ErrCode <> 0 then
raise Exception.Create('Não foi possível criar o diretório "' + NomeDir +
'". Código do erro: ' + IntToStr(ErrCode) + '.');
end;
CriarDir := CriarDir + '\';
end;
end;
procedure PrintForm(frm: TForm);
var
bmp: TBitMap;
x, y, WDPI, HDPI: Integer;
OldColor: TColor;
begin
Screen.Cursor := crHourGlass;
OldColor := frm.Color;
frm.Color := clWhite;
frm.Update;
bmp := frm.GetFormImage;
with Printer do
begin
Orientation := poLandscape;
BeginDoc;
HDPI := PageHeight div 8;
WDPI := PageWidth div 8;
x := PageWidth - Round(WDPI * 0.4); //0.4" margem direita
y := PageHeight - Round(HDPI * 0.5); //0.5" Altura do rodapé
Canvas.StretchDraw(Rect(0, 0, x, y), bmp);
EndDoc;
end;
bmp.Free;
frm.Color := OldColor;
Screen.Cursor := crDefault;
end;
procedure ApenasCaracteresAlfaNumericos(var key:char);
begin
if not (key in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'X', 'Z', 'W', 'Y',
char(8), char(13)]) then key := #0;
if key in ['-', ' '] then
key := #0;
end;
function RetiraAcentos(txt: String): String;
var
i: Integer;
begin
Result := txt;
for i := 1 to Length(Result) do
case Result[i] of
'á', 'à', 'â', 'ä', 'ã': Result[i] := 'a';
'Á', 'À', 'Â', 'Ä', 'Ã': Result[i] := 'A';
'é', 'è', 'ê', 'ë': Result[i] := 'e';
'É', 'È', 'Ê', 'Ë': Result[i] := 'E';
'í', 'ì', 'î', 'ï': Result[i] := 'i';
'Í', 'Ì', 'Î', 'Ï': Result[i] := 'I';
'ó', 'ò', 'ô', 'ö', 'õ': Result[i] := 'o';
'Ó', 'Ò', 'Ô', 'Ö', 'Õ': Result[i] := 'O';
'ú', 'ù', 'û', 'ü': Result[i] := 'u';
'Ú', 'Ù', 'Û', 'Ü': Result[i] := 'U';
'ç': Result[i] := 'c';
'Ç': Result[i] := 'C';
end;
end;
function AbreviaNome(Nome: String): String;
var
Nomes: array[1..20] of string;
i, TotalNomes: Integer;
begin
Nome := Trim(Nome);
Result := Nome;
Nome := Nome + #32; {Insere um espaço para garantir que todas as letras sejam testadas}
i := Pos(#32, Nome); {Pega a posição do primeiro espaço}
if i > 0 then
begin
TotalNomes := 0;
while i > 0 do {Separa todos os nomes}
begin
Inc(TotalNomes);
Nomes[TotalNomes] := Copy(Nome, 1, i - 1);
Delete(Nome, 1, i);
i := Pos(#32, Nome);
end;
if TotalNomes > 2 then
begin
for i := 2 to TotalNomes - 1 do {Abreviar a partir do segundo nome, exceto o último.}
begin
if Length(Nomes[i]) > 3 then {Contém mais de 3 letras? (ignorar de, da, das, do, dos, etc.)}
Nomes[i] := Nomes[i][1] + '.'; {Pega apenas a primeira letra do nome e coloca um ponto após.}
end;
Result := '';
for i := 1 to TotalNomes do
Result := Result + Trim(Nomes[i]) + #32;
Result := Trim(Result);
end;
end;
end;
//--------------------- Verifica se uma data informada cai em um final de semana
function IsWeekEnd(dData : TDateTime) : boolean;
begin
if DayOfWeek(dData) in [1,7] then
result := true
else
result := false;
end;
//-------------- Retorna data do primeiro dia Util do mes, de uma data informada
function PrimeiroDiaUtil(Data:TDateTime):TDateTime;
var Ano, Mes, Dia : word;
DiaDaSemana : Integer;
begin
DecodeDate (Data, Ano, Mes, Dia);
Dia := 1;
DiaDaSemana := DayOfWeek(Data);
if DiaDaSemana in [1,7] then
Dia := 2;
Result := EncodeDate(Ano, Mes, Dia);
end;
//------------------------------------------------ Retorna uma data por extenso
function DataExtenso(Data:TDateTime): String;
var
NoDia : Integer;
DiaDaSemana : array [1..7] of String;
Meses : array [1..12] of String;
Dia, Mes, Ano : Word;
begin
{ Dias da Semana }
DiaDasemana [1]:= 'Domingo';
DiaDasemana [2]:= 'Segunda-feira';
DiaDasemana [3]:= 'Terça-feira';
DiaDasemana [4]:= 'Quarta-feira';
DiaDasemana [5]:= 'Quinta-feira';
DiaDasemana [6]:= 'Sexta-feira';
DiaDasemana [7]:= 'Sábado';
{ Meses do ano }
Meses [1] := 'Janeiro';
Meses [2] := 'Fevereiro';
Meses [3] := 'Março';
Meses [4] := 'Abril';
Meses [5] := 'Maio';
Meses [6] := 'Junho';
Meses [7] := 'Julho';
Meses [8] := 'Agosto';
Meses [9] := 'Setembro';
Meses [10]:= 'Outubro';
Meses [11]:= 'Novembro';
Meses [12]:= 'Dezembro';
DecodeDate (Data, Ano, Mes, Dia);
NoDia := DayOfWeek (Data);
Result := DiaDaSemana[NoDia] + ', ' +
IntToStr(Dia) + ' de ' + Meses[Mes]+ ' de ' + IntToStr(Ano);
end;
//----------------------------------- Retorna o nome de um mês abreviado ou não
function NameMonth(Mes:Word;Abrev:Boolean):String;
const
NameL : array [1..12] of String[9] = ('JANEIRO','FEVEREIRO','MARÇO','ABRIL',
'MAIO','JUNHO','JULHO','AGOSTO',
'SETEMBRO','OUTUBRO','NOVEMBRO',
'DEZEMBRO');
begin
if (Mes in [1..12]) then
if Abrev then
Result := Copy(NameL[Mes],1,3)
else
Result := NameL[Mes];
end;
//------------------------- Retorna 6 meses atrás da data enviada, de mes em mes
function ReturnSixMonth(Actual:TDateTime):Semestre;
var
d,m,y : word;
i : byte;
Data : TDateTime;
begin
for i := 6 downto 1 do begin
Data := Actual - (30 * i);
DecodeDate(Data,y,m,d);
Result[i].Mes := m;
Result[i].Ano := y;
end;
end;
//------------------------- Verifica se o número é do tipo inteiro
function IsInteger(numero:string):boolean;
begin
result := true;
try
numero := inttostr(StrToInt(numero));
except
on exception do
result := false;
end;
end;
function PortaImpressora(chave:string):string;
var
Reg : TRegistry;
begin
Reg := TRegistry.Create;
try
reg.rootkey := HKEY_CURRENT_USER;
if Reg.KeyExists(chave) then
begin
reg.OpenKey(chave, true);
if reg.ValueExists('Porta Impressora') then result := reg.ReadString('Porta Impressora')
else
begin
reg.WriteString('Porta Impressora' , 'LPT1');
result := 'LPT1';
end;
end;
finally
reg.closekey;
reg.free;
end;
end;
procedure WriteStatusBar(ACanvas:TCanvas; Rect:TRect; atext:string; fontcolor, backgroundcolor:TColor);
begin
with ACanvas do
begin
Brush.Color := backgroundcolor;
Brush.Style := bssolid;
FillRect(Rect);
Font.Color := fontcolor;
SetBkMode(Handle, TRANSPARENT);
DrawText(Handle, PChar(atext), length(atext), Rect, DT_CENTER or DT_SINGLELINE or DT_VCENTER);
end;
end;
procedure WriteStatusBar(ACanvas:TCanvas; Rect:TRect; atext:string; fontcolor:TColor);
begin
with ACanvas do
begin
// Brush.Color := clwhite;
Brush.Style := bssolid;
FillRect(Rect);
Font.Color := fontcolor;
SetBkMode(Handle, TRANSPARENT);
DrawText(Handle, PChar(atext), length(atext), Rect, DT_CENTER or DT_SINGLELINE or DT_VCENTER);
end;
end;
function removercaracteres(texto : string):string;
var
i : integer;
begin
result := '';
for i := 1 to length(texto) do
begin
if texto[i] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] then
result := result + texto[i];
end;
end;
{ Usada no componente TEdit, ou seus descendentes DB, etc.
passse o parametro Sender e key da seguinte forma:
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
DigitaData(sender, key);
end;
}
procedure DigitaData(Sender:TObject; var Key: Char);
var x, numbarras : integer ;
begin
if key <> #8 then
begin
if Sender is Tdbedit then
begin
if (length(trim(Tdbedit(sender).text)) >= 10) or (not (Key in ['0'..'9', '/', #8])) then
begin
Key := #0 ;
exit ;
end;
numbarras := 0 ;
for x := 1 to length(trim(Tdbedit(sender).text)) do
begin
if copy(trim(Tdbedit(sender).text),x,1) = '/' then
numbarras := numbarras + 1 ;
end;
if numBarras <2 then
begin
if length(trim(Tdbedit(sender).text)) = 2 then
begin
Tdbedit(sender).text := Tdbedit(sender).text + '/' ;
Tdbedit(sender).SelStart := length(trim(Tdbedit(sender).text)) ;
end;
if length(trim(Tdbedit(sender).text)) = 5 then
begin
Tdbedit(sender).text := Tdbedit(sender).text + '/' ;
Tdbedit(sender).SelStart := length(trim(Tdbedit(sender).text)) ;
end;
end;
if (copy(Tdbedit(sender).text,length(Tdbedit(sender).text),1) = '/') and (key = '/') then
Key := #0 ;
exit ;
end;
if Sender is Tedit then
begin
if (length(trim(Tedit(sender).text)) >= 10) or (not (Key in ['0'..'9', '/', #8])) then
begin
Key := #0 ;
exit ;
end;
numbarras := 0 ;
for x := 1 to length(trim(Tedit(sender).text)) do
begin
if copy(trim(Tedit(sender).text),x,1) = '/' then
numbarras := numbarras + 1 ;
end;
if numBarras <2 then
begin
if length(trim(Tedit(sender).text)) = 2 then
begin
Tedit(sender).text := Tedit(sender).text + '/' ;
Tedit(sender).SelStart := length(trim(Tedit(sender).text)) ;
end;
if length(trim(Tedit(sender).text)) = 5 then
begin
Tedit(sender).text := Tedit(sender).text + '/' ;
Tedit(sender).SelStart := length(trim(Tedit(sender).text)) ;
end;
end;
if (copy(Tedit(sender).text,length(Tedit(sender).text),1) = '/') and (key = '/') then
Key := #0 ;
end;
end;
end;
function Truncar(valor:currency):currency;
begin
result := valor;
result := result * 1000;
if result - trunc(result) >= 0.5 then
result := result + 1;
result := trunc(result);
result := result / 1000;
result := result * 100;
if result - trunc(result) >= 0.5 then
result := result + 1;
result := trunc(result);
result := result / 100;
end;
function Truncar2(valor:currency):currency;
begin
// truncar 2 casa
result := valor;
result := result * 100;
if result - trunc(result) >= 0.5 then
result := result + 1;
result := trunc(result);
result := result / 100;
end;
function Truncarinteiro(valor:currency):integer;
begin
valor := valor * 10;
if valor - trunc(valor) >= 0.5 then
valor := valor + 1;
result := trunc(valor);
result := result div 10;
end;
function RemoverChar (texto:string; simbolo : char):string;
var
posicao : integer;
begin
while pos(simbolo, texto) > 0 do
begin
posicao := pos(simbolo, texto);
delete(texto, posicao, 1);
end;
result := texto;
end;
function RemoveSimbolos (numero:string):string;
var
j :integer;
new : string;
begin
for j := 1 to length(numero) do
begin
if numero[j] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] then
new := new + numero[j];
end;
result := new;
end;
function RepeteChar(C:char;N:Integer):string;
var
I :integer;
begin
if n < 1 then
begin
result := '';
exit;
end;
for i := 1 to N do
result := result + c;
end;
function AppIsRunning: Boolean;
var
hSem : THandle;
AppTitle: string;
begin
Result := False;
AppTitle := Application.Title;
hSem := CreateSemaphore(nil, 0, 1, pChar(AppTitle));
if ((hSem <> 0) AND (GetLastError() = ERROR_ALREADY_EXISTS)) then
begin
CloseHandle(hSem);
Result := True;
end;
end;
Function NomeComputador : String;
var
lpBuffer : PChar;
nSize : DWord;
const
Buff_Size = MAX_COMPUTERNAME_LENGTH + 1;
begin
nSize := Buff_Size;
lpBuffer := StrAlloc(Buff_Size);
GetComputerName(lpBuffer,nSize);
Result := String(lpBuffer);
StrDispose(lpBuffer);
end;
function LimpaAcentos(S: String): String;
var
Acentos1, Acentos2 : String;
i, Aux : Integer;
begin
Acentos1 := 'ÁÍÓÚÉ ÄÏÖÜË ÀÌÒÙÈ ÃÕ ÂÎÔÛÊ áíóúé äïöüë àìòùè ãõ âîôûê Çç';
Acentos2 := 'AIOUE AIOUE AIOUE AO AIOUE aioue aioue aioue ao aioue Cc';
for i := 0 to Length(S)-1 do
begin
Aux := Pos(S[i], Acentos1);
if (aux > 0) then S[i] := Acentos2[Aux];
end;
Result := S;
end;
function VerificaCNPJ(CPNJ: string): Boolean;
var
S: String;
Soma: Integer;
iPos, Fator, i: Integer;
iDig: Integer;
begin
Result := False;
S := CPNJ;
{ remove os simbolos especiais }
s := RemoveSimbolos(S);
{ verifica o CPNJ possui 14 digitos }
if Length(S) <> 14 then Exit;
{ calcula os 2 últimos dígitos }
for iPos := 12 to 13 do
begin
Soma := 0;
Fator := 2;
for i := iPos downto 1 do
begin
Soma := Soma + StrToInt(S[i]) * Fator;
Inc(Fator);
if Fator > 9 then Fator := 2;
end;
iDig := 11 - (Soma mod 11);
if iDig > 9 then iDig := 0;
{ verifica os digitos com o forncedido }
if iDig <> StrToInt(S[iPos + 1]) then
Exit;
end;
Result := True;
end;
function VerificaCPF(CPF: string): Boolean;
var
S: String;
Soma: Integer;
iPos, Fator, i: Integer;
iDig: Integer;
begin
Result := False;
S := CPF;
{ remove os simbolos especiais }
s := RemoveSimbolos(S);
{ verifica o CPF possui 11 digitos }
if Length(S) <> 11 then Exit;
{ calcula os 2 últimos dígitos }
for iPos := 9 to 10 do
begin
Soma := 0;
Fator := 2;
for i := iPos downto 1 do
begin
Soma := Soma + StrToInt(S[i]) * Fator;
Inc(Fator);
end;
iDig := 11 - Soma mod 11;
if iDig > 9 then iDig := 0;
{ verifica os digitos com o forncedido }
if iDig <> StrToInt( S[iPos + 1]) then
Exit;
end;
Result := True;
end;
function AddChrF(Texto:string; FChar:Char; Nvezes:integer):string;
begin
while length(texto) < nvezes do texto := Texto + FChar;
result := texto;
end;
function AddChrI(Texto:string; IChar:Char; Nvezes:integer):string;
begin
while length(texto) < nvezes do texto := IChar + Texto;
result := texto;
end;
Function Extenso(Valor : Extended; Monetario:Boolean): String;
Var
Centavos, Centena, Milhar, Milhao, Bilhao, Texto : String;
X : Byte;
Const
Unidades: array [1..9] of string[10] =
('um', 'dois', 'três', 'quatro','cinco','seis', 'sete', 'oito','nove');
Dez : array [1..9] of string[12] =
('onze', 'doze', 'treze','quatorze', 'quinze','dezesseis', 'dezessete','dezoito', 'dezenove');
Dezenas : array [1..9] of string[12] =
('dez', 'vinte', 'trinta','quarenta', 'cinquenta','sessenta', 'setenta','oitenta', 'noventa');
Centenas: array [1..9] of string[20] =
('cento', 'duzentos','trezentos', 'quatrocentos','quinhentos', 'seiscentos','setecentos','oitocentos', 'novecentos');
Function Ifs( Expressao: Boolean; CasoVerdadeiro, CasoFalso: String): String;
Begin
If Expressao then Result := CasoVerdadeiro else Result := CasoFalso;
end;
Function MiniExtenso( Valor: String ): String;
Var
Unidade, Dezena, Centena: String;
Begin
Unidade := '';
Dezena := '';
Centena := '';
If (Valor[2] = '1') and (Valor[3] <> '0') then
Begin
Unidade := Dez[StrToInt(Valor[3])];
Dezena := '';
End
Else
Begin
If Valor[2] <> '0' Then Dezena := Dezenas[StrToInt(Valor[2])];
If Valor[3] <> '0' then Unidade := Unidades[StrToInt(Valor[3])];
end;
If (Valor[1] = '1') and (Unidade = '') and (Dezena = '') then
Centena := 'cem'
Else If Valor[1] <> '0' then
Centena := Centenas[StrToInt(Valor[1])]
Else
Centena := '';
Result := Centena +
Ifs((Centena <> '') and ((Dezena <> '') or (Unidade <> '')),' e ', '') + Dezena +
Ifs((Dezena <> '') and (Unidade <> ''), ' e ', '') + Unidade;
end;
Begin
If Valor = 0 Then
Begin
Result := 'Zero';
Exit;
End;
Texto := FormatFloat( '000000000000.00', Valor );
Centavos := MiniExtenso( '0' + Copy( Texto, 14, 2 ) );
Centena := MiniExtenso( Copy( Texto, 10, 3 ) );
Milhar := MiniExtenso( Copy( Texto, 7, 3 ) );
If Milhar <> '' then Milhar := Milhar + ' mil';
Milhao := MiniExtenso( Copy( Texto, 4, 3 ) );
If Milhao <> '' then Milhao := Milhao + ifs( Copy( Texto, 4, 3 ) = '001', ' milhão',' milhões');
Bilhao := MiniExtenso( Copy( Texto, 1, 3 ) );
If Bilhao <> '' then Bilhao := Bilhao + ifs( Copy( Texto, 1, 3 ) = '001', ' bilhão',' bilhões');
If Monetario Then
Begin
If (Bilhao <> '') and (Milhao + Milhar + Centena = '') then
Result := Bilhao + ' de Reais '
Else If (Milhao <> '') and (Milhar + Centena = '') then
Result := Milhao + ' de Reais '
Else
Result := Bilhao +
ifs( (Bilhao <> '') and (Milhao + Milhar + Centena <> ''),
ifs((Pos(' e ', Bilhao) > 0) or (Pos( ' e ', Milhao + Milhar + Centena ) > 0 ), ', ', ' e '), '') +
Milhao +
ifs( (Milhao <> '') and (Milhar + Centena <> ''), ifs((Pos(' e ', Milhao) > 0) or
(Pos( ' e ', Milhar + Centena ) > 0 ), ', ',' e '), '') +
Milhar + ifs( (Milhar <> '') and (Centena <> ''),ifs(Pos( ' e ', Centena ) > 0, ', ', ' e '), '') +
Centena +
ifs( Int(Valor) = 0, '', (ifs( Int(Valor) = 1, ' Real ', ' Reais ' )));
If (Result <> '') and (Centavos <> '') then
Result := Result + ' e '
else
Result := Result ;
If Centavos <> '' then
Result := Result + Centavos +
ifs( Copy( Texto, 14, 2 )= '01', ' Centavo ', ' Centavos ' );
// For X := 1 To 250 Do Result := Result + '*. ';
For X := 1 To 250 Do Result := Result + '*';
End
Else
Begin
Result := Bilhao + ifs( (Bilhao <> '') and (Milhao + Milhar + Centena <> ''),
ifs((Pos(' e ', Bilhao) > 0) or (Pos( ' e ', Milhao + Milhar + Centena ) > 0 ), ', ', ' e '), '') +
Milhao + ifs( (Milhao <> '') and (Milhar + Centena <> ''),
ifs((Pos(' e ', Milhao) > 0) or
(Pos( ' e ', Milhar + Centena ) > 0 ), ', ',' e '), '') +
Milhar + ifs( (Milhar <> '') and (Centena <> ''),
ifs(Pos( ' e ', Centena ) > 0, ', ', ' e '), '') +
Centena;
If Centavos <> '' then Result := Result + ' e ' + Centavos;
End;
if copy(result, 1, 3) = 'um ' then
result := 'H'+result
else
result := uppercase(result[1])+copy(result, 2, length(result) -1);
end;
function ExisteString(StrText: string; strChar: char): boolean;
var
i : integer;
begin
result := false;
if strtext = '' then exit;
for i := 0 to length(strText) do
if strText[i] = strChar then
begin
result := true;
exit;
end;
end;
function FillString (StrChar: char; qtd: integer): string;
var
i : integer;
begin
result := '';
for i := 0 to qtd do
result := result + strChar;
end;
function ContarString(StrText : string; StrChar:char): integer;
var
i : integer;
begin
result := 0;
for i := 0 to length(strText) do
if strText[i] = strChar then
result := result + 1;
end;
function espaco(valor:integer):string;
var
linha : string;
i : integer;
begin
for i := 1 to valor do
begin
linha := linha + ' ';
end;
result := linha;
end;
function substituir (texto: string; velho: string; novo: char):string;
var
i : integer;
begin
for i := 0 to length(texto) do
if texto[i] = velho then texto[i] := novo;
result := texto;
end;
function substituir (texto, velho, novo: string):string;
var
i : integer;
begin
i := pos(velho, texto);
delete(texto, i, length(velho));
Insert(novo, texto, i);
result := texto;
end;
Function GetNetWorkUserName:string;
var
buffer : array[0..128] of char;
l : dword;
begin
l := SizeOf(buffer);
GetUserName (buffer,l);
if l>0 then
result := StrPas(buffer)
else
result := 'GUEST';
end;
function LeRegistroSistema : string;
var
Reg :TRegistry;
begin
Reg := TRegistry.Create;
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey('\SOFTWARE\P4INFORMATICA\CORPORE',false) then
begin
RegCaminho := Reg.ReadString('Caminho');
RegProtocolo := Reg.ReadString('Protocolo');
RegUsuario := Reg.ReadString('Usuário');
RegSenha := Reg.ReadString('Senha');
RegServidor := Reg.ReadString('Servidor');
RePortaImp := Reg.ReadString('Porta Impressora');
if RegProtocolo = 'LOCAL' then
begin
RegConexao := RegCaminho;
end;
if RegProtocolo = 'NETBEUI' then
begin
RegConexao := '\\'+RegServidor+'\'+RegCaminho;
end;
if RegProtocolo = 'TCP/IP'then
begin
RegConexao := RegServidor+':'+RegCaminho;
end;
if RegProtocolo = 'IPX/SPX' then
begin
RegConexao := RegServidor+'@'+RegCaminho;
end;
end;
end;
{Verifica configurações conforme a tabela de registro!!!}
procedure InicializaValores();
var
qryTmpRegistro:TIBODataset;
begin
try
qryTmpRegistro := TIBODataset.Create(nil);
qryTmpRegistro.Close;
with qryTmpRegistro.SQL do
begin
Clear;
Add('SELECT * FROM REGISTRO');
end;
qryTmpRegistro.Open;
Empresa := qryTmpRegistro.FieldByName('NMEMPRESA').AsString;
MensagemCupom := qryTmpRegistro.FieldByName('DSCONFIGIMPMENSAGEM').AsString;
InformaQtd := qryTmpRegistro.FieldByName('BOLINFORMAQUANTIDADE').AsString;
BolDigCodBarras := qryTmpRegistro.FieldByName('BOLREJEITADIGITOCODBARRAS').AsString;
BolGeraReferencia := qryTmpRegistro.FieldByName('BOLGERARREFERENCIA').AsString;
finally
FreeAndNil(qryTmpRegistro);
end;
end;
function Converte_String_Inteiro(valor:string):Double;
begin
Result := 0;
try
Result := StrToFloat(valor);
except
On Exception do
begin
MessageDlg('Erro ao Converter "String" Para "Inteiro".',MtError,[MbOk],0);
Abort;
end;
end;
end;
function Substitui(Texto:string;Atual:string;Novo:String):String;
var
Posicao:integer;
begin
if Texto = '' then
Texto := '0';
Posicao := Pos(Atual,Texto);
while Pos(Atual,Texto) > 0 do
begin
Delete(Texto,Posicao,1);
Insert(Novo,Texto,Posicao);
Posicao := Pos(Atual,Texto);
end;
Result := Texto;
end;
function Inserir_Unidade_Medida(conmain:TIB_Connection; nome:string;nomereduzido:string):Integer;
var
sql,
scdunidade : string;
icdunidade : integer;
begin
//icdunidade := GerarCodigo(conmain,'UNIDADE');
Result := icdunidade;
scdunidade := IntToStr(icdunidade);
sql := 'INSERT INTO UNIDADE(CDUNIDADE, NMUNIDADE, NMREDUZIDO, USUINCLUSAO, COMPINCLUSAO, USUALTERACAO, COMPALTERACAO)'+
' VALUES('+scdunidade+','''+nome+''', '''+nomereduzido+''', ''MIGRACAO'', ''MIGRACAO'',''MIGRACAO'',''MIGRACAO'')';
// ExecutaSQL(conmain,sql);
end;
function Inserir_Aliquota(conmain:TIB_Connection; nome:string;nomereduzido:string;tptributacao:string; vlaliquota:string):Integer;
var
sql,
scdaliquota : string;
icdaliquota : integer;
begin
// icdaliquota := GerarCodigo(conmain,'ALIQUOTA');
Result := icdaliquota;
scdaliquota := IntToStr(icdaliquota);
sql := 'INSERT INTO ALIQUOTA(CDALIQUOTA, NMALIQUOTA, NMREDUZIDO, CDTPTRIBUTACAO, VLALIQUOTA, USUINCLUSAO, COMPINCLUSAO, USUALTERACAO, COMPALTERACAO)'+
' VALUES('+scdaliquota+','''+nome+''', '''+nomereduzido+''',1,'''+nome+''', ''MIGRACAO'', ''MIGRACAO'',''MIGRACAO'',''MIGRACAO'')';
// ExecutaSQL(conmain,sql);
end;
function Retorna_Aliquota_Somente(valor:String):String;
var
qryTmp:TIB_Query;
sql,saliquota:string;
begin
Result := '';
sql := ' SELECT CDALIQUOTA, NMALIQUOTA FROM ALIQUOTA '+
' WHERE VLALIQUOTA = '''+RetiraArgumento(' ',valor)+''' ';
try
qryTmp := TIB_Query.Create(nil);
qryTmp.SQL.Add(sql);
qryTmp.Open;
if qryTmp.IsEmpty then saliquota := ''
else saliquota := qryTmp.FieldByName('CDALIQUOTA').AsString;
Result := saliquota;
finally
FreeAndNil(qryTmp);
end;
end;
function Retorna_Unidade_Medida(valor:string):String;
var
qryTmp: TIB_Query;
sql : string;
begin
Result := '';
sql := ' SELECT CDUNIDADE, NMREDUZIDO '+
' FROM UNIDADE '+
' WHERE NMREDUZIDO = '''+valor+''' ';
try
qryTmp := TIB_Query.Create(nil);
qryTmp.SQL.Add(sql);
qryTmp.Open;
Result := qryTmp.Fields[0].AsString;
finally
FreeAndNil(qryTmp);
end;
end;
function Retorna_Unidade_Sigla(valor:string):String;
var
qryTmp: TIB_Query;
sql : string;
begin
Result := '';
sql := ' SELECT U.NMREDUZIDO '+
' FROM UNIDADE U, DETALHE D '+
' WHERE U.CDUNIDADE = D.CDUNIDADE '+
' AND D.CDDETALHE = '''+valor+''' ';
try
qryTmp := TIB_Query.Create(nil);
qryTmp.SQL.Add(sql);
qryTmp.Open;
Result := qryTmp.Fields[0].AsString;
finally
FreeAndNil(qryTmp);
end;
end;
function Retorna_Aliquota(valor:String):String;
var
qryTmp:TIB_Query;
sql,saliquota:string;
begin
sql := ' SELECT A.CDALIQUOTA, A.VLALIQUOTA, A.NMALIQUOTA '+
' FROM ALIQUOTA A, DETALHE D '+
' WHERE A.CDALIQUOTA = D.CDALIQUOTA '+
' AND D.CDDETALHE = '''+valor+''' ';
try
qryTmp := TIB_Query.Create(nil);
qryTmp.SQL.Add(sql);
qryTmp.Open;
if qryTmp.IsEmpty then saliquota := '00'
else saliquota := qryTmp.FieldByName('VLALIQUOTA').AsString;
if Length(saliquota) = 1 then
saliquota := '0'+saliquota;
saliquota := RetiraArgumento('%',saliquota);
saliquota := RetiraArgumento(' ',saliquota);
Result := saliquota;
finally
FreeAndNil(qryTmp);
end;
end;
function Retorna_Nome_Aliquota(valor:String):String;
var
qryTmp:TIB_Query;
sql,saliquota:string;
begin
sql := ' SELECT A.NMALIQUOTA '+
' FROM ALIQUOTA A, DETALHE D '+
' WHERE A.CDALIQUOTA = D.CDALIQUOTA '+
' AND D.CDDETALHE = '''+valor+''' ';
try
qryTmp := TIB_Query.Create(nil);
qryTmp.SQL.Add(sql);
qryTmp.Open;
if qryTmp.IsEmpty then saliquota := '00'
else saliquota := qryTmp.FieldByName('NMALIQUOTA').AsString;
if Length(saliquota) = 1 then
saliquota := '0'+saliquota;
saliquota := RetiraArgumento('%',saliquota);
saliquota := RetiraArgumento(' ',saliquota);
Result := saliquota;
finally
FreeAndNil(qryTmp);
end;
end;
function Retorna_Aliquota(valor:String;Banco:TIBDatabase;Transacao:TIBTransaction):String;
var
qryTmp:TIBQuery;
sql,saliquota:string;
begin
sql := ' select vlaliquota from aliquota a, detalhe d where a.cdaliquota = d.cdaliquota'+
' and d.cddetalhe = '''+valor+'''';
try
qryTmp := TIBQuery.Create(nil);
qryTmp.Database := Banco;
qryTmp.Transaction := Transacao;
qryTmp.CachedUpdates := true;
qryTmp.SQL.Add(sql);
qryTmp.Open;
if qryTmp.IsEmpty then
saliquota := '00'
else saliquota := qryTmp.Fields[0].AsString;
if Length(saliquota) = 1 then
saliquota := '0'+saliquota;
Result := saliquota;
finally
FreeAndNil(qryTmp);
end;
end;
function ArrCondPag(sCondPag: String;dDataBase: TDateTime;sTipoFora: String): Variant;
var
aResult: Variant;
x, xMax: Integer;
NewDate, DiasExtras: TDateTime;
begin
xMax := 0;
if Pos(',',sCondPag) > 0 then
begin
xMax := ChrCount(',',sCondPag);
aResult := VarArrayCreate([0,xMax],varInteger);
for x := 0 To xMax do
begin
if x = xMax then
aResult[x] := StrToInt(Trim(sCondPag))
else
aResult[x] := StrToInt(Trim(Copy(sCondPag,1,Pos(',',sCondPag)-1)));
sCondPag := Copy(sCondPag,Pos(',',sCondPag)+1,Length(sCondPag));
end;
end
else
begin
aResult := VarArrayOf([StrToInt(Trim(sCondPag))]);
end;
NewDate := dDataBase;
if sTipoFora = 'M' then
while GetDateElement(NewDate,3) <> 1 do
NewDate := NewDate + 1
else if sTipoFora = 'Q' then
if GetDateElement(dDataBase,3) <= 15 then
while GetDateElement(NewDate,3) <> 16 do
NewDate := NewDate + 1
else
while GetDateElement(NewDate,3) <> 1 do
NewDate := NewDate + 1
else if sTipoFora = 'D' then
if GetDateElement(dDataBase,3) <= 10 then
while GetDateElement(NewDate,3) <> 11 do
NewDate := NewDate + 1
else if GetDateElement(dDataBase,3) <= 20 then
while GetDateElement(NewDate,3) <> 21 do
NewDate := NewDate + 1
else
while GetDateElement(NewDate,3) <> 1 do
NewDate := NewDate + 1
else
NewDate := dDataBase;
DiasExtras := (NewDate - dDataBase);
if DiasExtras <> 0 then
for x := 0 To xMax do
aResult[x] := aResult[x]+DiasExtras;
Result := aResult;
end;
function GetDateElement(FDate: TDateTime;Index: Integer): Integer;
var
AYear, AMonth, ADay: Word;
begin
DecodeDate(FDate, AYear, AMonth, ADay); { break encoded date into elements }
case Index of
1: Result := AYear;
2: Result := AMonth;
3: Result := ADay;
else Result := -1;
end;
end;
function RemoveAcento(Str:String): String;
const
// ComAcento = 'àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ';
// ComAcento = 'A A¢ Aª A´ A» A£ Aµ A¡ A© A A³ Aº A§ A';
// SemAcento = 'aaeouaoaeioucuAAEOUAOAEIOUCU';
ComAcento = 'àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜA A¢ Aª A´ A» A£ Aµ A¡ A© A A³ Aº A§ A';
SemAcento = 'aaeouaoaeioucuAAEOUAOAEIOUCUaaeouaoaeioucuAAEOUAOAEIOUCU';
var
x : Integer;
begin
for x := 1 to Length(Str) do
begin
if Pos(Str[x],ComAcento)<>0 Then
Str[x] := SemAcento[Pos(Str[x],ComAcento)];
end;
Result := Str;
end;
function RetornaDataString(Data:string):string;
var
Dia,Mes,Ano:string;
begin
Dia := Copy(Data,0,2);
Mes := Copy(Data,4,2);
Ano := Copy(Data,7,8);
Result := Ano+Mes+Dia;
end;
function RetornaDataString(Data:string; formato:string):string;
var
Dia,Mes,Ano:string;
begin
Dia := Copy(Data,0,2);
Mes := Copy(Data,4,2);
Ano := Copy(Data,7,8);
Data := Dia+'/'+Mes+'/'+Ano;
Result := FormatDateTime(formato, StrToDate(data));
end;
function RetornaDataMovtoECF(Data:string):string;
var
Dia,Mes,Ano:string;
begin
Dia := Copy(Data,0,2);
Mes := Copy(Data,4,2);
Ano := Copy(Data,7,8);
Result := Dia+Mes+Ano;
end;
function RetornaDataMesAnoReferencia(Data:string):string;
var
Dia,Mes,Ano:string;
begin
Dia := Copy(Data,0,2);
Mes := Copy(Data,4,2);
Ano := Copy(Data,7,8);
Result := Mes+Ano;
end;
function FormataStringParaData(Data:string):string;
var
Dia,Mes,Ano:string;
sRes:string;
begin
Dia := Copy(Data,0,2);
Mes := Copy(Data,3,2);
Ano := Copy(Data,5,8);
sRes := Dia+'/'+Mes+'/'+Ano;
Result := RetiraArgumento(' ',sRes);
end;
function Cria_Diretorio(var diretorio:String):Boolean;
begin
Result := false;
if not DirectoryExists(diretorio) then
begin
if MessageDlg('Diretório Para Armazenar Arquivos Não Existe.'+chr(10)+chr(13)+
'Deseja Criá-lo?',mtConfirmation,[MbYes,MbNo],0)=IdYes then
begin
ForceDirectories(diretorio);
result := true;
end;
end else
begin
result := false;
end;
end;
function Substitui_Ponto_Virgula(valor:string):String;
var
iposicao:integer;
begin
iposicao := Pos(',',valor);
if iposicao > 0 then
begin
Delete(valor,iposicao,1);
Insert('.',valor,iposicao);
end;
Result := Valor;
end;
function Substitui_Caracter(Palavra,valorAntigo,valorNovo:string):String;
var
iposicao:integer;
begin
iposicao := Pos(valorAntigo,Palavra);
if iposicao > 0 then
begin
Delete(Palavra,iposicao,1);
Insert(valorNovo,Palavra,iposicao);
end;
Result := Palavra;
end;
{=================================}
function ReplicaTexto(col:integer; Texto:string):String;
var
x:integer;
begin
Result := '';
x := 0;
repeat
inc(x);
Result := result+''+Texto;
until( x = col);
end;
function AjustaString(str: String; tam: Integer): String;
//Funcao que completa a string com espacos em branco Criado Por Plínio!!
begin
while Length ( str ) < tam do
str := str + ' ';
if Length ( str ) > tam then
str := Copy ( str, 1, tam );
Result := str;
end;
function AjustaNumerico(VlrMoeda: Currency; tam: Integer) : String;
var
sVlr: String;
begin
if Pos(',',CurrToStr(VlrMoeda)) > 0 then
sVlr := RetiraArgumento(',', FormatFloat('000000000.00', VlrMoeda))
else sVlr := CurrToStr(VlrMoeda) + '00';
while Length(sVlr) < tam do sVlr := '0'+sVlr;
if Length(sVlr) > tam then sVlr := Copy(sVlr,1,tam);
Result := sVlr;
end;
function AjustaInteiro(inteiro:String;tam:integer) : String;
begin
Result := '';
while length(inteiro) < tam do
inteiro := '0'+inteiro;
if Length(inteiro) > tam then inteiro := Copy(inteiro,1,tam);
Result := inteiro;
end;
function Exibir_Periodo(cdcliente:string):string;
var
q : tib_query;
dttermino, dtinicio, nuitperiodo, sql : string;
begin
sql := 'select max(nuitperiodo) from itperiodo where cdcliente = '+cdcliente;
q := tib_query.create(nil);
try
q.sql.add(sql);
q.Open;
if q.fields[0].asinteger = 0 then
begin
result := 'Cliente não realizou nenhum período.';
exit;
end;
nuitperiodo := q.fields[0].asstring;
sql := 'select dtinicio, dttermino, dtfechamento from itperiodo '+
'where nuitperiodo = '+nuitperiodo+' and cdcliente = '+cdcliente;
q.Close;
q.sql.Clear;
q.SQL.Add(sql);
q.open;
dtinicio := formatdatetime(P4InfoVarejo_dtabrev, q.fieldbyname('dtinicio').AsDate);
dttermino := formatdatetime(P4InfoVarejo_dtabrev, q.fieldbyname('dttermino').AsDate);
{ if q.fieldbyname('dtfechamento').IsNull then
begin
if DtBanco > q.fieldbyname('dttermino').AsDate then
result := 'Período em atraso: '+dtinicio+' até '+dttermino
else
result := 'Período aberto: '+dtinicio+' até '+dttermino;
end
else
result := 'Período fechado: '+dtinicio+' até '+dttermino;
}finally
q.Close;
freeandnil(q);
end;
end;
function SeparaMes(Data:TDate):Integer;
var
sData,sMes:string;
begin
Result := 1;
LongDateFormat := 'dd/mm/yyyy';
ShortDateFormat := 'dd/mm/yyyy';
sData := DateToStr(Data);
sMes := Copy(sData,4,2);
if sMes = '' then sMes := '1';
try
Result := StrToInt(sMes);
except
Result := 1;
end;
end;
function RemoveDigitoCodigoBarras(cdbarras:string):String;
begin
Result := Copy(cdbarras,2,length(cdbarras));
end;
procedure RemoverValoresLista(cdlista:TStrings; ilinha:integer; var campo:string; var desccampo:string; var tipodedado:string);
var
slinha : string;
scampo,
sdesccampo,
stipodedado : string;
iPosicao,iCont : integer;
begin
iCont := 1;
slinha := cdlista.Strings[ilinha];
iPosicao := Pos(':',slinha);
while iPosicao > 0 do
begin
if iCont = 1 then scampo := Copy(slinha,0,iPosicao-1);
if iCont = 2 then sdesccampo := Copy(slinha,0,iPosicao-1);
Delete(slinha,1,iPosicao);
iPosicao := Pos(':',slinha);
Inc(iCont);
end;
stipodedado := slinha;
campo := scampo;
desccampo := sdesccampo;
tipodedado := stipodedado;
end;
function RetirarCaracteresEspeciais(valor:string):String;
var
svalor:string;
begin
svalor := valor;
svalor := RetiraArgumento(' ',svalor);
svalor := RetiraArgumento('.',svalor);
svalor := RetiraArgumento(',',svalor);
svalor := RetiraArgumento('/',svalor);
svalor := RetiraArgumento('\',svalor);
svalor := RetiraArgumento('-',svalor);
svalor := RetiraArgumento('.',svalor);
svalor := RetiraArgumento('|',svalor);
svalor := RetiraArgumento('(',svalor);
svalor := RetiraArgumento(')',svalor);
Result := svalor;
end;
function FormataCNPJ(valor:string):String;
var
svalor, sCampo1, sCampo2,
sCampo3, sCampo4, sCampo5 : string;
begin
svalor := valor;
if svalor = '' then exit;
sCampo1 := Copy(svalor,1,2);
sCampo2 := Copy(svalor,3,3);
sCampo3 := Copy(svalor,6,3);
sCampo4 := Copy(svalor,9,4);
sCampo5 := Copy(svalor,13,2);
Result := sCampo1+'.'+sCampo2+'.'+sCampo3+'/'+sCampo4+'-'+sCampo5;
end;
function FormataCPF(valor:string):String;
var
svalor, sCampo1,
sCampo2, sCampo3, sCampo4 : string;
begin
svalor := (valor);
if svalor = '' then exit;
sCampo1 := Copy(svalor,1,3);
sCampo2 := Copy(svalor,4,3);
sCampo3 := Copy(svalor,7,3);
sCampo4 := Copy(svalor,10,2);
Result := sCampo1+'.'+sCampo2+'.'+sCampo3+'-'+sCampo4;
end;
function FormataCEP(valor:string):String;
var
svalor, sCampo1,
sCampo2, sCampo3: string;
begin
svalor := (valor);
if svalor = '' then exit;
sCampo1 := Copy(svalor,1,2);
sCampo2 := Copy(svalor,3,3);
sCampo3 := Copy(svalor,6,3);
Result := sCampo1+sCampo2+'-'+sCampo3;
end;
function FormataTelefone(valor:string):String;
var
svalor, sCampo1,
sCampo2, sCampo3: string;
tam :integer;
begin
tam := 0;
svalor := (valor);
tam := length(svalor);
if tam <= 8 then svalor := '31'+svalor;
if svalor = '' then exit;
sCampo1 := Copy(svalor,1,2);
sCampo2 := Copy(svalor,3,4);
sCampo3 := Copy(svalor,7,4);
Result := '('+sCampo1+')'+sCampo2+'-'+sCampo3;
end;
function AcumulaHoras(Horas:TStrings):String;
var
i, iPos : integer;
sHoras, sMin : string;
iHoras,iMins : integer;
acHoras, acMins: integer;
begin
i := 0;
iPos := 0;
sHoras := '';
sMin := '';
iHoras := 0;
iMins := 0;
acHoras := 0;
acMins := 0;
for i := 0 to Horas.Count - 1 do
begin
sHoras := Horas.Strings[i];
iPos := Pos(':',sHoras);
iHoras := StrToInt( Copy(sHoras,0,iPos-1));
acHoras := acHoras + iHoras;
iMins := StrToInt( Copy(sHoras,iPos+1,2));
acMins := acMins + iMins;
if acMins >= 60 then
begin
acMins := acMins - 60;
inc(acHoras);
end;
end;
sHoras := IntToStr(acHoras);
sMin := IntToStr(acMins);
if Length(sHoras) = 1 then sHoras := '0'+sHoras;
if length(sMin) = 1 then sMin := '0'+sMin;
Result := sHoras+':'+sMin;
end;
procedure ConfiguraIB_Grid(qry:TIB_Query;grd:TIB_Grid);
var
i :integer;
itemLink,
itemSeq : string;
begin
itemLink := '';
itemSeq := '';
for i := 0 to qry.Fields.ColumnCount - 1 do
begin
itemLink := qry.fields[i].FieldName+'='+qry.fields[i].FieldName+';'+qry.fields[i].FieldName+' DESC';
itemSeq := qry.fields[i].FieldName+'='+IntToStr(i+1);
qry.OrderingLinks.Add(itemLink);
qry.OrderingItems.Add(itemSeq);
if qry.Fields[i].FieldName = 'CDFUNCIONARIO' then qry.Fields[i].DisplayLabel := 'Código'
else if qry.Fields[i].FieldName = 'NMFUNCIONARIO' then qry.Fields[i].DisplayLabel := 'Funcionário'
else if qry.Fields[i].FieldName = 'CDCLIENTE' then qry.Fields[i].DisplayLabel := 'Código'
else if qry.Fields[i].FieldName = 'NMCLIENTE' then qry.Fields[i].DisplayLabel := 'Cliente'
else if qry.Fields[i].FieldName = 'VENDASECF' then qry.Fields[i].DisplayLabel := 'Vendas E.C.F.'
else if qry.Fields[i].FieldName = 'VENDASNF' then qry.Fields[i].DisplayLabel := 'Vendas N.F.'
else if qry.Fields[i].FieldName = 'VENDASCONS' then qry.Fields[i].DisplayLabel := 'Vendas Consignadas'
else if qry.Fields[i].FieldName = 'VENDASORC' then qry.Fields[i].DisplayLabel := 'Vendas Orçamento'
else if qry.Fields[i].FieldName = 'CDFORNECEDOR' then qry.Fields[i].DisplayLabel := 'Código'
else if qry.Fields[i].FieldName = 'NMFORNECEDOR' then qry.Fields[i].DisplayLabel := 'Fornecedor'
else if qry.Fields[i].FieldName = 'CDTRANSPORTADOR' then qry.Fields[i].DisplayLabel := 'Código'
else if qry.Fields[i].FieldName = 'NMTRANSPORTADOR' then qry.Fields[i].DisplayLabel := 'Transportadora';
grd.GridLinks.Add(qry.fields[i].FieldName);
end;
grd.Refresh;
end;
procedure LimpaIB_Grid(qry:TIB_Query;grd:TIB_Grid);
begin
qry.OrderingItems.Clear;
qry.OrderingLinks.Clear;
grd.GridLinks.Clear;
grd.EditLinks.Clear;
end;
function Proximo_Codigo_Barra(conmain: tib_connection):string;
var
sql,cdbarra,cdproduto,prefixo : string;
qryTmpBarra: TIB_Query;
icdproduto:integer;
begin
prefixo := '';
cdbarra := '';
sql := 'SELECT CDBARRA FROM REGISTRO';
try
qryTmpBarra := TIB_Query.Create(nil);
with qryTmpBarra.SQL do
begin
Add(sql);
end;
qryTmpBarra.Open;
if not qryTmpBarra.IsEmpty then
{Original!!}
// repeat
// cdbarra := inttostr(GerarCodigo(conmain, 'BARRA'));
prefixo := qryTmpBarra.FieldByName('CDBARRA').AsString;
prefixo := Copy(prefixo, 1, 05);
cdbarra := prefixo+cdbarra;
while length(cdbarra) < 12 do cdbarra := cdbarra+'0';
if Length(cdbarra) > 12 then cdbarra := Copy(cdbarra, 1,12);
// cdbarra := cdbarra + digito_verificador_codigo_barra(cdbarra);
// until not CodigoExiste('DETALHE', 'CDALTERNATIVO', 'string', cdbarra);
result := cdbarra;
finally
FreeAndNil(qryTmpBarra);
end;
end;
function LeParametro(sparam:string):String;
var
iPos:Integer;
begin
Result := '';
iPos := Pos('=',sparam);
Result := Copy(sparam,0,iPos-2);
end;
function LeValorParametro(sparam:string):String;
var
iPos:Integer;
begin
Result := '';
iPos := Pos('=',sparam);
Result := Copy(sparam,iPos+1,Length(sparam)-iPos);
end;
procedure LeDadosArquivoImpressoraFiscal(var nuserie:string; var impressora: string; var porta: string; var MFD: string;
var gaveta: string; var impcheque: string; var tef_dial:string; var tef_Disc:string;
var gt_ecf:string);
var
ArqTexto : TextFile;
Arquivo : String;
sLinha : String;
sparam,
svlparam : string;
begin
sparam := '';
svlparam := '';
Arquivo := 'c:\PFile.csi';
if not FileExists('c:\PFile.csi') then
begin
try
AssignFile(ArqTexto,'c:\PFile.csi');
Rewrite(ArqTexto);
Writeln(ArqTexto,'IMPRESSORA=Bematech');
Writeln(ArqTexto,'MODELO=MFD2000');
Writeln(ArqTexto,'MFD=S');
Writeln(ArqTexto,'NUMERO SERIE ECF=');
finally
CloseFile(ArqTexto);
end;
end;
try
AssignFile(ArqTexto,Arquivo);
Reset(ArqTexto);
while not Eof(ArqTexto) do
begin
Readln(ArqTexto,SLinha);
sparam := LeParametro(sLinha);
svlparam := LeValorParametro(sLinha);
if sparam = 'NUMERO SERIE ECF' then nuserie := svlparam;
if sparam = 'IMPRESSORA' then impressora := svlparam;
if sparam = 'PORTA' then porta := svlparam;
// if sparam = 'GT_ECF' then gt_ecf := svlparam;
if sparam = 'MFD' then MFD := svlparam;
if sparam = 'GAVETA' then gaveta := svlparam;
if sparam = 'CHEQUE' then impcheque := svlparam;
if sparam = 'TEF_DIAL' then tef_dial := svlparam;
if sparam = 'TEF_DISC' then tef_Disc := svlparam;
end;
finally
CloseFile(ArqTexto);
end;
end;
function LeRegistroSistema_BD_Usuario(var Usuario:String; var Senha:String) : string;
var
Reg : TRegistry;
ssRegConexao,
ssRegCaminho,
ssRegProtocolo,
ssRegServidor : string;
begin
Result := '';
Reg := TRegistry.Create;
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey('\SOFTWARE\P4INFORMATICA\SECURITY',false) then
begin
ssRegCaminho := Reg.ReadString('Caminho');
ssRegProtocolo := Reg.ReadString('Protocolo');
ssRegServidor := Reg.ReadString('Servidor');
Usuario := Reg.ReadString('Usuário');
Senha := Reg.ReadString('Senha');
if ssRegProtocolo = 'LOCAL' then
begin
ssRegConexao := ssRegCaminho;
end;
if ssRegProtocolo = 'NETBEUI' then
begin
ssRegConexao := '\\'+ssRegServidor+'\'+ssRegCaminho;
end;
if ssRegProtocolo = 'TCP/IP'then
begin
ssRegConexao := ssRegServidor+':'+ssRegCaminho;
end;
if ssRegProtocolo = 'IPX/SPX' then
begin
ssRegConexao := ssRegServidor+'@'+ssRegCaminho;
end;
Result := ssRegConexao;
end;
end;
function Retorna_Permissao_Usuario_Caixa(UsuarioConectado, BancoSeguranca, Usuario, Senha:String):Boolean;
var
sql : string;
q : TIB_Query;
Conn : TIB_Connection;
begin
Result := false;
sql := ' select po.bolacesso '+
' from objeto o, permissao_objeto po, usuario u '+
' where nmformulario = ''actFluxoCaixa'' '+
' and o.cdobjeto = po.cdobjeto '+
' and po.usucod = u.usucod '+
' and u.usulogin = '''+UsuarioConectado+''' ';
try
Conn := TIB_Connection.Create(nil);
Conn.Disconnect;
Conn.DatabaseName := BancoSeguranca;
Conn.Username := Usuario;
Conn.Password := Senha;
try
Conn.Connect;
except
end;
q := TIB_Query.Create(nil);
q.IB_Connection := Conn;
q.SQL.Add(sql);
q.Open;
if not q.IsEmpty then
begin
if q.FieldByName('BOLACESSO').AsString = 'T' then Result := true else Result := false;
end;
finally
FreeAndNil(q);
Conn.Disconnect;
FreeAndNil(Conn);
end;
end;
function Formata_CNPJ(cnpj:String):String;
var
str1,
str2,
str3,
str4,
str5 : string;
begin
// 08.633.795/0001-87
// 08633795000187
Result := '';
str1 := Copy(cnpj,0,2);
str2 := Copy(cnpj,3,3);
str3 := Copy(cnpj,6,3);
str4 := Copy(cnpj,9,4);
Str5 := Copy(cnpj,13,2);
Result := str1+'.'+str2+'.'+str3+'/'+str4+'-'+str5;
end;
function FormataPercentual(valor:string):String;
var
tam:integer;
int,dec:string;
begin
tam := length(valor);
int := Copy(valor,1,tam-2);
dec := Copy(valor, tam-1,2);
Result := int+','+dec;
end;
function FormataPercentual(valor:string; decimais:boolean):Double;
var
tam:integer;
int,dec:string;
sValor:String;
begin
tam := length(valor);
int := Copy(valor,1,tam-2);
dec := Copy(valor, tam-1,2);
sValor := int+','+dec;
Result := StrToFloat(sValor);
end;
function NomeArquivoBancoRemessa():String;
var
sData:String;
sHora:String;
begin
// sData := FormatDateTime(P4InfoVarejo_dtabrev, DtBanco);
// sHora := FormatDateTime(P4InfoVarejo_hrbanco, HrBanco);
sData := RetiraCaracteresEspeciais(sData);
sHora := RetiraCaracteresEspeciais(sHora);
Result := 'Remessa'+sData+'_'+sHora+'.txt';
ShowMessage(Result);
end;
function Subtrai_Datas(DataInicial, DataFinal:TDateTime; HoraInicial:TTime; HoraFinal:TTime):String;
var
intDias: double;
sDias:string;
begin
intDias := (DataFinal - DataInicial);
sDias := FloatToStr(intDias);
Result := sDias+' Dia(s) '+ FormatDateTime(P4InfoVarejo_hrbanco, (HoraFinal - HoraInicial));
end;
function ConverteDecimal_DataHora(valorNumerico:Double):String;
var
sValorNum,
sHora,
sMin,
sSeg : string;
iPos : integer;
fHora,
fMin,
fSeg : double;
begin
sValorNum := FloatToStr(valorNumerico);
if Pos(',', sValorNum) > 0 then
begin
iPos := Pos(',', sValorNum);
sHora := Copy(sValorNum, 0, iPos-1);
sMin := Copy(sValorNum, iPos+1, length(sValorNum)-iPos);
if sMin = '' then sMin := '0';
fMin := StrToFloat(sMin);
fMin := (fMin * 60) / 100;
sValorNum := FloatToStr(fMin);
iPos := Pos(',',sValorNum);
if iPos > 0 then
begin
sMin := Copy(sValorNum, 0, iPos);
sSeg := Copy(sValorNum, iPos, Length(sValorNum) - iPos);
if sSeg = '' then sSeg := '00';
fSeg := StrToFloat(sSeg);
fSeg := (fSeg * 60) / 100;
sSeg := FloatToStr(fSeg);
if Pos(',', sSeg) > 0 then
begin
iPos := Pos(',', sSeg);
sSeg := Copy(sSeg,0, iPos);
end;
end else
begin
end;
end;
Result := sHora+' hora(s), '+sMin+'minuto(s) '+sSeg+'segundo(s)';
end;
function IPLocal:string;
var
WSAData: TWSAData;
HostEnt: PHostEnt;
Name : string;
begin
WSAStartup(2, WSAData);
SetLength(Name, 255);
Gethostname(PChar(Name), 255);
SetLength(Name, StrLen(PChar(Name)));
HostEnt := gethostbyname(PChar(Name));
with HostEnt^ do
begin
Result := Tratar_NumeroIP_Computador(Format('%d.%d.%d.%d', [Byte(h_addr^[0]),Byte(h_addr^[1]), Byte(h_addr^[2]),Byte(h_addr^[3])]));
end;
WSACleanup;
end;
function Tratar_NumeroIP_Computador(ip:string):String;
var
c1, c2,
c3, c4 : string;
ipos : integer;
begin
Result := ip;
ipos := Pos('.',ip);
c1 := Copy(ip,0,ipos-1);
Delete(ip,1,ipos);
ipos := Pos('.',ip);
c2 := Copy(ip,0,ipos-1);
Delete(ip,1,ipos);
ipos := Pos('.',ip);
c3 := Copy(ip,0,ipos-1);
Delete(ip,1,ipos);
c4 := Copy(ip,0,length(ip));
Delete(ip,1,ipos);
while length(c1) < 03 do c1 := '0'+c1;
while length(c2) < 03 do c2 := '0'+c2;
while length(c3) < 03 do c3 := '0'+c3;
while length(c4) < 03 do c4 := '0'+c4;
Result := c1+'.'+c2+'.'+c3+'.'+c4;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clDC;
interface
{$I clVer.inc}
uses
Windows, SysUtils, Classes, clWinInet, clConnection, clDCUtils, clUtils, SyncObjs,
clCryptApi, clCert, clFtpUtils, clHttpUtils, clHttpAuth, clUriUtils, clSyncUtils
{$IFDEF LOGGER}, clLogger{$ENDIF};
type
TclProcessPriority = (ppLower, ppNormal, ppHigher);
TclProcessStatus = (psUnknown, psSuccess, psFailed, psErrors, psProcess, psTerminated);
TclOnStatusChanged = procedure (Sender: TObject; Status: TclProcessStatus) of object;
TclOnDataItemProceed = procedure (Sender: TObject; ResourceInfo: TclResourceInfo;
BytesProceed: Integer; CurrentData: PChar; CurrentDataSize: Integer) of object;
TclOnError = procedure (Sender: TObject; const Error: string; ErrorCode: Integer) of object;
TclOnGetResourceInfo = procedure (Sender: TObject; ResourceInfo: TclResourceInfo) of object;
TclPerformRequestOperation = procedure (AParameters: TObject) of object;
TclCustomThreader = class(TThread)
private
FURL: string;
FDataStream: TStream;
FLastError: string;
FLastErrorCode: Integer;
FTimeOut: Integer;
FTryCount: Integer;
FBatchSize: Integer;
FSelfConnection: TclInternetConnection;
FConnection: TclInternetConnection;
FStatus: TclProcessStatus;
FURLParser: TclUrlParser;
FOnStatusChanged: TclOnStatusChanged;
FOnError: TclOnError;
FOnGetResourceInfo: TclOnGetResourceInfo;
FOnUrlParsing: TclOnUrlParsing;
FOnDataItemProceed: TclOnDataItemProceed;
FUrlComponents: TURLComponents;
FCertificateFlags: TclCertificateFlags;
FUseInternetErrorDialog: Boolean;
FOnGetCertificate: TclOnGetCertificateEvent;
FCertificate: TclCertificate;
FCertificateHandled: Boolean;
FProxyBypass: string;
FInternetAgent: string;
FSelfResourceInfo: TclResourceInfo;
FDataAccessor: TCriticalSection;
FBytesToProceed: Integer;
FResourcePos: Integer;
FKeepConnection: Boolean;
FPassiveFTPMode: Boolean;
FReconnectAfter: Integer;
FSleepEvent: THandle;
FAllowCompression: Boolean;
FSynchronizer: TclThreadSynchronizer;
FRequestHeader: TStrings;
FDoNotGetResourceInfo: Boolean;
FFtpProxySettings: TclFtpProxySettings;
FHttpProxySettings: TclHttpProxySettings;
FResponseHeader: TStrings;
FTempErrorCode: Integer;
procedure DoOnURLParsing(Sender: TObject; var UrlComponents: TURLComponents);
procedure PrepareURL;
procedure SyncDoGetResourceInfo;
procedure SyncDoError;
procedure SyncDoStatusChanged;
procedure SyncDoURLParsing;
procedure SyncDoGetCertificate;
procedure SyncTerminate;
procedure SetupCertIgnoreOptions(AOpenRequest: TclHttpOpenRequestAction);
procedure SetupCertificateOptions(AOpenRequest: TclHttpOpenRequestAction);
function SetCertOptions(AOpenRequest: TclHttpOpenRequestAction; AErrorCode: Integer): Boolean;
procedure SetResourceInfo(const Value: TclResourceInfo);
function GetInternalResourceInfo: TclResourceInfo;
procedure SetURLParser(const Value: TclUrlParser);
procedure SetCertOptionsOperation(AParameters: TObject);
function GetConnection: TclInternetConnection;
procedure SetConnection(const Value: TclInternetConnection);
procedure WaitForReconnect(ATimeOut: Integer);
function GetOpenRequestFlags(ANeedCaching: Boolean): DWORD;
procedure SetRequestHeader(const Value: TStrings);
procedure QueryGetInfo(AOpenRequestAction: TclHttpOpenRequestAction);
procedure QueryHeadInfo(AOpenRequestAction: TclHttpOpenRequestAction);
procedure SetFtpProxySettings(const Value: TclFtpProxySettings);
procedure SetHttpProxySettings(const Value: TclHttpProxySettings);
function GetProxyString: string;
procedure GetAllHeaders(ARequest: TclHttpOpenRequestAction);
protected
FResourceInfo: TclResourceInfo;
procedure ServerAuthentication(AOpenRequest: TclHttpOpenRequestAction);
procedure ProxyAuthentication(AOpenRequest: TclHttpOpenRequestAction);
procedure GetHttpStatusCode(ARequest: TclHttpOpenRequestAction);
procedure FreeObjectIfNeed(var AObject);
procedure SendRequest(AOpenRequest: TclHttpOpenRequestAction);
procedure PerformRequestOperation(AOpenRequest: TclHttpOpenRequestAction;
AOperation: TclPerformRequestOperation; AParameters: TObject);
procedure GetResourceInfo(AConnect: TclConnectAction);
procedure GetHTTPResourceInfo(AConnect: TclConnectAction); virtual;
procedure GetFTPResourceInfo(AConnect: TclConnectAction); virtual;
procedure ProcessHTTP(AConnect: TclConnectAction); virtual;
procedure ProcessFTP(AConnect: TclConnectAction); virtual;
procedure DoTerminate; override;
procedure Execute; override;
procedure ProcessURL; virtual;
procedure DoStop; virtual;
procedure SetHttpHeader(AResourceAction: TclInternetResourceAction);
procedure AssignIfNeedResourceInfo;
procedure ClearInfo;
procedure SetStatus(AStatus: TclProcessStatus);
procedure InternalSynchronize(Method: TThreadMethod);
function GetNormTimeOut(ATimeOut: Integer): Integer; virtual;
procedure AssignError(const AError, ADescription: string; AErrorCode: Integer);
procedure BeginDataStreamAccess;
procedure EndDataStreamAccess;
property DataStream: TStream read FDataStream;
property URL: string read FURL;
property TempErrorCode: Integer read FTempErrorCode;
public
constructor Create(const AURL: string; ADataStream: TStream);
destructor Destroy; override;
procedure Perform; virtual;
procedure Wait;
procedure Stop;
property RequestHeader: TStrings read FRequestHeader write SetRequestHeader;
property ResponseHeader: TStrings read FResponseHeader;
property Status: TclProcessStatus read FStatus;
property LastError: string read FLastError;
property LastErrorCode: Integer read FLastErrorCode;
property DoNotGetResourceInfo: Boolean read FDoNotGetResourceInfo write FDoNotGetResourceInfo;
property PassiveFTPMode: Boolean read FPassiveFTPMode write FPassiveFTPMode;
property BytesToProceed: Integer read FBytesToProceed write FBytesToProceed;
property ResourcePos: Integer read FResourcePos write FResourcePos;
property URLParser: TclUrlParser read FURLParser write SetURLParser;
property ResourceInfo: TclResourceInfo read GetInternalResourceInfo write SetResourceInfo;
property DataAccessor: TCriticalSection read FDataAccessor write FDataAccessor;
property Connection: TclInternetConnection read GetConnection write SetConnection;
property KeepConnection: Boolean read FKeepConnection write FKeepConnection;
property BatchSize: Integer read FBatchSize write FBatchSize;
property TryCount: Integer read FTryCount write FTryCount;
property TimeOut: Integer read FTimeOut write FTimeOut;
property ReconnectAfter: Integer read FReconnectAfter write FReconnectAfter;
property CertificateFlags: TclCertificateFlags read FCertificateFlags write FCertificateFlags;
property UseInternetErrorDialog: Boolean read FUseInternetErrorDialog write FUseInternetErrorDialog;
property ProxyBypass: string read FProxyBypass write FProxyBypass;
property HttpProxySettings: TclHttpProxySettings read FHttpProxySettings write SetHttpProxySettings;
property FtpProxySettings: TclFtpProxySettings read FFtpProxySettings write SetFtpProxySettings;
property InternetAgent: string read FInternetAgent write FInternetAgent;
property AllowCompression: Boolean read FAllowCompression write FAllowCompression;
property OnDataItemProceed: TclOnDataItemProceed read FOnDataItemProceed write FOnDataItemProceed;
property OnError: TclOnError read FOnError write FOnError;
property OnGetCertificate: TclOnGetCertificateEvent read FOnGetCertificate write FOnGetCertificate;
property OnGetResourceInfo: TclOnGetResourceInfo read FOnGetResourceInfo write FOnGetResourceInfo;
property OnStatusChanged: TclOnStatusChanged read FOnStatusChanged write FOnStatusChanged;
property OnUrlParsing: TclOnUrlParsing read FOnUrlParsing write FOnUrlParsing;
end;
TclDownLoadThreader = class(TclCustomThreader)
private
FIsGetResourceInfo: Boolean;
FDataProceed: PChar;
FDataProceedSize: Integer;
FTotalDownloaded: Integer;
procedure SyncDoDataItemProceed;
procedure Dump(AResourceAction: TclInternetResourceAction);
procedure SetResourcePos(AResourceAction: TclInternetResourceAction);
procedure PrepareHeader;
protected
procedure ProcessHTTP(AConnect: TclConnectAction); override;
procedure ProcessFTP(AConnect: TclConnectAction); override;
public
constructor Create(const AURL: string; ADataStream: TStream; AIsGetResourceInfo: Boolean);
end;
TclDeleteThreader = class(TclCustomThreader)
protected
procedure ProcessHTTP(AConnect: TclConnectAction); override;
procedure ProcessFTP(AConnect: TclConnectAction); override;
public
constructor Create(const AURL: string);
end;
TclUploadThreader = class(TclCustomThreader)
private
FIsGetResourceInfo: Boolean;
FDataProceedSize: Integer;
FUploadedDataSize: Integer;
FDataProceed: PChar;
FHttpResponse: TStream;
FForceRemoteDir: Boolean;
FUseSimpleRequest: Boolean;
FRequestMethod: string;
FRetryCount: Integer;
FRetryProceed: Integer;
procedure SyncDoDataItemProceed;
procedure ProcessRequest(AOpenRequest: TclHttpOpenRequestAction;
const AHeader: string; ADataSize: Integer);
procedure ProcessSimpleRequest(AOpenRequest: TclHttpOpenRequestAction;
const AHeader: string; AData: TStream);
procedure GetResourceInfoByDataStream;
procedure RequestOperation(AParameters: TObject);
procedure SimpleRequestOperation(AParameters: TObject);
procedure ForceRemoteDirectory(AConnect: TclConnectAction);
function GetRetryCount: Integer;
protected
procedure GetHttpResponse(AOpenRequest: TclHttpOpenRequestAction);
procedure Dump(AResourceAction: TclInternetResourceAction);
procedure ProcessFTP(AConnect: TclConnectAction); override;
procedure ProcessHTTP(AConnect: TclConnectAction); override;
public
constructor Create(const AURL: string; ADataStream: TStream; AIsGetResourceInfo: Boolean);
property HttpResponse: TStream read FHttpResponse write FHttpResponse;
property ForceRemoteDir: Boolean read FForceRemoteDir write FForceRemoteDir;
property UseSimpleRequest: Boolean read FUseSimpleRequest write FUseSimpleRequest;
property RequestMethod: string read FRequestMethod write FRequestMethod;
end;
procedure DownloadUrl(const AUrl: string; ATimeOut: Integer; AHtml: TStrings);
var
PutOptimization: Boolean = False;
implementation
{$IFDEF DEMO}
uses
Forms;
{$ENDIF}
type
TclResourceInfoAccess = class(TclResourceInfo);
procedure DownloadUrl(const AUrl: string; ATimeOut: Integer; AHtml: TStrings);
var
Stream: TStream;
Threader: TclDownloadThreader;
begin
Stream := nil;
Threader := nil;
try
Stream := TMemoryStream.Create();
Threader := TclDownloadThreader.Create(AUrl, Stream, False);
Threader.TimeOut := ATimeOut;
Threader.AllowCompression := False;
Threader.Perform();
Threader.Wait();
if not (Threader.Status in [psSuccess, psErrors]) then
begin
raise EclInternetError.Create(Threader.LastError, Threader.LastErrorCode);
end;
Stream.Position := 0;
AHtml.Clear();
AHtml.LoadFromStream(Stream);
finally
Threader.Free();
Stream.Free();
end;
end;
{ TclCustomThreader }
procedure TclCustomThreader.PrepareURL;
var
s: string;
begin
if FURLParser.ParsedUrl <> '' then Exit;
s := FURLParser.Parse(FURL);
if (s <> '') then
begin
FURL := s;
end else
begin
raise EclInternetError.CreateByLastError();
end;
end;
constructor TclCustomThreader.Create(const AURL: string; ADataStream: TStream);
begin
inherited Create(True);
FFtpProxySettings := TclFtpProxySettings.Create();
FHttpProxySettings := TclHttpProxySettings.Create();
FRequestHeader := TStringList.Create();
FResponseHeader := TStringList.Create();
FSynchronizer := TclThreadSynchronizer.Create();
FSleepEvent := CreateEvent(nil, False, False, nil);
FURLParser := TclUrlParser.Create();
FURLParser.OnUrlParsing := DoOnURLParsing;
FURL := AURL;
FDataStream := ADataStream;
FStatus := psUnknown;
FTryCount := cTryCount;
FBatchSize := cBatchSize;
FTimeOut := cTimeOut;
FReconnectAfter := cTimeOut;
FInternetAgent := cInternetAgent;
FResourcePos := 0;
FBytesToProceed := -1;
end;
destructor TclCustomThreader.Destroy;
begin
ClearInfo();
FURLParser.Free();
FSelfConnection.Free();
CloseHandle(FSleepEvent);
FSynchronizer.Free();
FResponseHeader.Free();
FRequestHeader.Free();
FHttpProxySettings.Free();
FFtpProxySettings.Free();
inherited Destroy();
end;
procedure TclCustomThreader.AssignError(const AError, ADescription: string; AErrorCode: Integer);
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'AssignError');{$ENDIF}
if Terminated then Exit;
FLastError := AError;
FLastErrorCode := AErrorCode;
if (FLastError = '') then
begin
FLastErrorCode := GetLastError();
FLastError := GetLastErrorText(FLastErrorCode);
end;
if (ADescription <> '') then
begin
FLastError := FLastError + ': ' + ADescription;
end;
InternalSynchronize(SyncDoError);
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'AssignError'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'AssignError', E); raise; end; end;{$ENDIF}
end;
procedure TclCustomThreader.SyncDoStatusChanged;
begin
if Assigned(FOnStatusChanged) then
begin
FOnStatusChanged(Self, FStatus);
end;
end;
procedure TclCustomThreader.AssignIfNeedResourceInfo;
begin
if (FSelfResourceInfo = nil) then
begin
FSelfResourceInfo := TclResourceInfo.Create();
end;
TclResourceInfoAccess(ResourceInfo).SetName(FURLParser.Urlpath);
end;
procedure TclCustomThreader.SetupCertIgnoreOptions(AOpenRequest: TclHttpOpenRequestAction);
var
dwFlags, dwBuffLen: DWORD;
begin
if (URLParser.UrlType <> utHTTPS) then Exit;
dwBuffLen := SizeOf(dwFlags);
if not InternetQueryOption(AOpenRequest.hResource, INTERNET_OPTION_SECURITY_FLAGS, @dwFlags, dwBuffLen) then
begin
raise EclInternetError.CreateByLastError();
end;
if cfIgnoreCommonNameInvalid in FCertificateFlags then
dwFlags := dwFlags or SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
if cfIgnoreDateInvalid in FCertificateFlags then
dwFlags := dwFlags or SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
if cfIgnoreUnknownAuthority in FCertificateFlags then
dwFlags := dwFlags or SECURITY_FLAG_IGNORE_UNKNOWN_CA;
if cfIgnoreRevocation in FCertificateFlags then
dwFlags := dwFlags or SECURITY_FLAG_IGNORE_REVOCATION;
if cfIgnoreWrongUsage in FCertificateFlags then
dwFlags := dwFlags or SECURITY_FLAG_IGNORE_WRONG_USAGE;
if not InternetSetOption(AOpenRequest.hResource, INTERNET_OPTION_SECURITY_FLAGS, @dwFlags, dwBuffLen) then
begin
raise EclInternetError.CreateByLastError();
end;
end;
procedure TclCustomThreader.SetupCertificateOptions(AOpenRequest: TclHttpOpenRequestAction);
var
size: DWORD;
begin
FCertificate := nil;
size := 0;
FCertificateHandled := False;
InternalSynchronize(SyncDoGetCertificate);
if FCertificateHandled then
begin
if (FCertificate <> nil) then
begin
size := SizeOf(CERT_CONTEXT);
end;
if not InternetSetOption(AOpenRequest.hResource, INTERNET_OPTION_CLIENT_CERT_CONTEXT,
FCertificate.Context, size) then
begin
raise EclInternetError.CreateByLastError();
end;
end;
end;
function TclCustomThreader.SetCertOptions(AOpenRequest: TclHttpOpenRequestAction;
AErrorCode: Integer): Boolean;
var
p: Pointer;
begin
Result := True;
if FUseInternetErrorDialog then
begin
Result := InternetErrorDlg(GetDesktopWindow(), AOpenRequest.hResource, AErrorCode,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS or
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA or
FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, p) <> ERROR_CANCELLED;
end else
begin
case AErrorCode of
ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED: SetupCertificateOptions(AOpenRequest);
ERROR_INTERNET_SEC_CERT_CN_INVALID,
ERROR_INTERNET_SEC_CERT_DATE_INVALID,
ERROR_INTERNET_INVALID_CA: SetupCertIgnoreOptions(AOpenRequest);
else Result := False;
end;
end;
end;
procedure TclCustomThreader.SetCertOptionsOperation(AParameters: TObject);
begin
(AParameters as TclHttpSendRequestAction).FireAction(GetNormTimeOut(TimeOut));
end;
procedure TclCustomThreader.PerformRequestOperation(AOpenRequest: TclHttpOpenRequestAction;
AOperation: TclPerformRequestOperation; AParameters: TObject);
var
cnt, LastError: Integer;
begin
cnt := 0;
LastError := 0;
repeat
try
AOperation(AParameters);
Break;
except
on E: EclTimeoutInternetError do raise;
on E: EclInternetError do
begin
if (E.ErrorCode <> 12032) then
begin
cnt := 0;
if (LastError = E.ErrorCode) then raise;
LastError := E.ErrorCode;
if not SetCertOptions(AOpenRequest, LastError) then raise;
end else
begin
Inc(cnt);
if (cnt > 9) then raise;
end;
end;
end;
until False;
end;
procedure TclCustomThreader.SendRequest(AOpenRequest: TclHttpOpenRequestAction);
var
i: Integer;
request: TclHttpSendRequestAction;
begin
i := 0;
while (i < 4) do
begin
Inc(i);
request := TclHttpSendRequestAction.Create(Connection, AOpenRequest.Internet,
AOpenRequest.hResource, '', nil, 0);
try
PerformRequestOperation(AOpenRequest, SetCertOptionsOperation, request);
finally
request.Free();
end;
try
GetHttpStatusCode(AOpenRequest);
Break;
except
if (ResourceInfo.StatusCode = 401) then
begin
if UseInternetErrorDialog then
begin
SetCertOptions(AOpenRequest, 0);
end else
if (i < 4) then
begin
ServerAuthentication(AOpenRequest);
end else
begin
raise;
end;
end else
if (ResourceInfo.StatusCode = 407) then
begin
if UseInternetErrorDialog then
begin
SetCertOptions(AOpenRequest, 0);
end else
if (HttpProxySettings.AuthenticationType = atAutoDetect) then
begin
ProxyAuthentication(AOpenRequest);
end else
begin
raise;
end;
end else
begin
raise;
end;
end;
if Terminated then Exit;
end;
end;
procedure TclCustomThreader.GetFTPResourceInfo(AConnect: TclConnectAction);
var
OpenFileAction: TclFtpOpenFileAction;
GetSizeAction: TclFtpGetFileSizeAction;
FindFirstFileAction: TclFtpFindFirstFileAction;
resDate: TDateTime;
begin
if (FResourceInfo <> nil) then Exit;
OpenFileAction := nil;
GetSizeAction := nil;
try
OpenFileAction := (Connection.GetActionByClass(TclFtpOpenFileAction) as TclFtpOpenFileAction);
if (OpenFileAction = nil) then
begin
OpenFileAction := TclFtpOpenFileAction.Create(Connection, AConnect.Internet, AConnect.hResource,
URLParser.Urlpath, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY);
OpenFileAction.FireAction(GetNormTimeOut(TimeOut));
end;
if Terminated then Exit;
GetSizeAction := TclFtpGetFileSizeAction.Create(Connection, OpenFileAction.Internet,
OpenFileAction.hResource);
GetSizeAction.FireAction(GetNormTimeOut(TimeOut));
AssignIfNeedResourceInfo();
TclResourceInfoAccess(ResourceInfo).SetSize(GetSizeAction.FileSize);
finally
GetSizeAction.Free();
FreeObjectIfNeed(OpenFileAction);
end;
if Terminated then Exit;
try
FindFirstFileAction := TclFtpFindFirstFileAction.Create(Connection, AConnect.Internet,
AConnect.hResource, FURLParser.Urlpath, INTERNET_FLAG_RELOAD);
try
FindFirstFileAction.FireAction(GetNormTimeOut(TimeOut));
AssignIfNeedResourceInfo();
resDate := ConvertFileTimeToDateTime(FindFirstFileAction.lpFindFileData.ftLastWriteTime);
if (resDate > 0) then
begin
TclResourceInfoAccess(ResourceInfo).SetDate(resDate);
end;
finally
FindFirstFileAction.Free();
end;
except
on EclInternetError do;
end;
end;
procedure TclCustomThreader.GetAllHeaders(ARequest: TclHttpOpenRequestAction);
var
buf: PChar;
buflen, tmp: DWORD;
begin
ResponseHeader.Clear();
buflen := 0;
tmp := 0;
HttpQueryInfo(ARequest.hResource, HTTP_QUERY_RAW_HEADERS_CRLF, nil, buflen, tmp);
if (buflen > 0) then
begin
GetMem(buf, buflen);
try
if HttpQueryInfo(ARequest.hResource, HTTP_QUERY_RAW_HEADERS_CRLF, buf, buflen, tmp) then
begin
ResponseHeader.Text := string(buf);
end;
finally
FreeMem(buf);
end;
end;
end;
procedure TclCustomThreader.GetHttpStatusCode(ARequest: TclHttpOpenRequestAction);
var
statuscode: Integer;
buflen, tmp: DWORD;
begin
GetAllHeaders(ARequest);
buflen := SizeOf(statuscode);
tmp := 0;
if HttpQueryInfo(ARequest.hResource, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER,
@statuscode, buflen, tmp) then
begin
AssignIfNeedResourceInfo();
TclResourceInfoAccess(ResourceInfo).SetStatusCode(statuscode);
if (ResourceInfo.StatusCode >= HTTP_STATUS_BAD_REQUEST) then
begin
raise EclInternetError.Create(Format(cResourceAccessError, [ResourceInfo.StatusCode]),
ResourceInfo.StatusCode);
end;
end else
begin
AssignError('', HTTP_QUERY_STATUS_CODE_Msg, 0);
end;
end;
procedure TclCustomThreader.QueryHeadInfo(AOpenRequestAction: TclHttpOpenRequestAction);
const
cTypeLength = 1024;
var
filedate: TFileTime;
resdate: TSystemTime;
resDateTime: TDateTime;
reslen: Integer;
restype: array[0..cTypeLength - 1] of Char;
buflen, tmp: DWORD;
begin
buflen := SizeOf(reslen);
tmp := 0;
if HttpQueryInfo(AOpenRequestAction.hResource, HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER,
@reslen, buflen, tmp) then
begin
AssignIfNeedResourceInfo();
TclResourceInfoAccess(ResourceInfo).SetSize(reslen);
end else
begin
// AssignError('', HTTP_QUERY_CONTENT_LENGTH_Msg, 0);
end;
if Terminated then Exit;
buflen := SizeOf(resdate);
tmp := 0;
if HttpQueryInfo(AOpenRequestAction.hResource, HTTP_QUERY_LAST_MODIFIED or HTTP_QUERY_FLAG_SYSTEMTIME,
@resdate, buflen, tmp) then
begin
AssignIfNeedResourceInfo();
if SystemTimeToFileTime(resdate, filedate) then
begin
resDateTime := ConvertFileTimeToDateTime(filedate);
if (resDateTime > 0) then
begin
TclResourceInfoAccess(ResourceInfo).SetDate(resDateTime);
end;
end;
end else
begin
// AssignError('', HTTP_QUERY_LAST_MODIFIED_Msg, 0);
if (ResourceInfo <> nil) then
begin
TclResourceInfoAccess(ResourceInfo).SetSize(0);
end;
end;
if Terminated then Exit;
buflen := cTypeLength;
tmp := 0;
if HttpQueryInfo(AOpenRequestAction.hResource, HTTP_QUERY_CONTENT_TYPE, restype + 0, buflen, tmp) then
begin
AssignIfNeedResourceInfo();
TclResourceInfoAccess(ResourceInfo).SetContentType(restype);
end else
begin
// AssignError('', HTTP_QUERY_CONTENT_TYPE_Msg, 0);
if (ResourceInfo <> nil) then
begin
TclResourceInfoAccess(ResourceInfo).SetSize(0);
end;
end;
end;
procedure TclCustomThreader.QueryGetInfo(AOpenRequestAction: TclHttpOpenRequestAction);
const
cTypeLength = 1024;
var
disposition, encoding: array[0..cTypeLength - 1] of Char;
buflen, tmp: DWORD;
contlen: Integer;
begin
buflen := cTypeLength;
tmp := 0;
if HttpQueryInfo(AOpenRequestAction.hResource, HTTP_QUERY_CONTENT_DISPOSITION, disposition + 0, buflen, tmp) then
begin
AssignIfNeedResourceInfo();
TclResourceInfoAccess(ResourceInfo).SetContentDisposition(disposition);
end;
if Terminated then Exit;
buflen := cTypeLength;
tmp := 0;
if HttpQueryInfo(AOpenRequestAction.hResource, HTTP_QUERY_CONTENT_ENCODING, encoding + 0, buflen, tmp) then
begin
AssignIfNeedResourceInfo();
TclResourceInfoAccess(ResourceInfo).SetCompressed(system.Pos('gzip', LowerCase(encoding)) > 0);
end;
contlen := Integer(InternetSetFilePointer(AOpenRequestAction.hResource, 0, nil, FILE_END, 0));
if contlen > 0 then
begin
AssignIfNeedResourceInfo();
if (ResourceInfo.Size = 0) then
begin
TclResourceInfoAccess(ResourceInfo).SetSize(contlen);
end else
begin
TclResourceInfoAccess(ResourceInfo).SetAllowsRandomAccess(True);
end;
end;
end;
procedure TclCustomThreader.GetHTTPResourceInfo(AConnect: TclConnectAction);
var
OpenRequestAction: TclHttpOpenRequestAction;
NeedAllInfo: Boolean;
begin
NeedAllInfo := (FResourceInfo = nil);
OpenRequestAction := nil;
try
OpenRequestAction := TclHttpOpenRequestAction.Create(Connection, AConnect.Internet, AConnect.hResource,
'HEAD', URLParser.Urlpath + URLParser.Extra, '', '', nil, GetOpenRequestFlags(False));
OpenRequestAction.FireAction(GetNormTimeOut(TimeOut));
SetHttpHeader(OpenRequestAction);
SendRequest(OpenRequestAction);
if needAllInfo then
begin
QueryHeadInfo(OpenRequestAction);
if Terminated then Exit;
OpenRequestAction.Free();
OpenRequestAction := nil;
OpenRequestAction := TclHttpOpenRequestAction.Create(Connection, AConnect.Internet, AConnect.hResource,
'GET', URLParser.Urlpath + URLParser.Extra, '', '', nil, GetOpenRequestFlags(True));
OpenRequestAction.FireAction(GetNormTimeOut(TimeOut));
SetHttpHeader(OpenRequestAction);
SendRequest(OpenRequestAction);
if Terminated then Exit;
QueryGetInfo(OpenRequestAction);
end;
finally
OpenRequestAction.Free();
end;
end;
procedure TclCustomThreader.SyncDoError;
begin
if Assigned(FOnError) then
begin
FOnError(Self, FLastError, FLastErrorCode);
end;
end;
procedure TclCustomThreader.InternalSynchronize(Method: TThreadMethod);
begin
FSynchronizer.Synchronize(Method);
end;
procedure TclCustomThreader.SyncDoGetResourceInfo;
begin
if Assigned(FOnGetResourceInfo) then
begin
FOnGetResourceInfo(Self, ResourceInfo);
end;
end;
procedure TclCustomThreader.Perform;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
//if FindWindow('TAppBuilder', nil) = 0 then
//begin
// MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
// ExitProcess(1);
//end;
{$ENDIF}
{$ENDIF}
Resume();
end;
procedure TclCustomThreader.ClearInfo;
begin
FSelfResourceInfo.Free();
FSelfResourceInfo := nil;
end;
function TclCustomThreader.GetNormTimeOut(ATimeOut: Integer): Integer;
begin
Result := ATimeOut;
end;
procedure TclCustomThreader.SetStatus(AStatus: TclProcessStatus);
begin
if (FStatus <> AStatus) then
begin
FStatus := AStatus;
InternalSynchronize(SyncDoStatusChanged);
end;
end;
procedure TclCustomThreader.WaitForReconnect(ATimeOut: Integer);
begin
WaitForSingleObject(FSleepEvent, DWORD(ATimeOut));
end;
procedure TclCustomThreader.Execute;
var
Counter: Integer;
begin
ResponseHeader.Clear();
Counter := FTryCount;
FTempErrorCode := 0;
try
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Execute');{$ENDIF}
SetStatus(psProcess);
PrepareURL();
repeat
try
ProcessURL();
Break;
except
on E: EclInternetError do
begin
FTempErrorCode := E.ErrorCode;
Dec(Counter);
if (Counter < 1) then raise;
WaitForReconnect(GetNormTimeOut(ReconnectAfter));
end;
end;
until False;
if Terminated then
begin
SetStatus(psTerminated);
end else
if (FLastError <> '') then
begin
SetStatus(psErrors);
end else
begin
SetStatus(psSuccess);
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Execute'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Execute', E); raise; end; end;{$ENDIF}
except
on E: EclInternetError do
begin
AssignError(E.Message, '', E.ErrorCode);
SetStatus(psFailed);
end;
on E: Exception do
begin
AssignError(E.Message, '', 0);
SetStatus(psFailed);
end;
end;
end;
procedure TclCustomThreader.DoOnURLParsing(Sender: TObject; var UrlComponents: TURLComponents);
begin
FUrlComponents := UrlComponents;
InternalSynchronize(SyncDoURLParsing);
UrlComponents := FUrlComponents;
end;
procedure TclCustomThreader.SyncDoURLParsing;
begin
if Assigned(FOnUrlParsing) then
begin
FOnUrlParsing(Self, FUrlComponents);
end;
end;
procedure TclCustomThreader.Wait;
var
Msg: TMsg;
H: THandle;
begin
DuplicateHandle(GetCurrentProcess(), Handle, GetCurrentProcess(), @H, 0, False, DUPLICATE_SAME_ACCESS);
try
if GetCurrentThreadID = FSynchronizer.SyncBaseThreadID then
begin
while MsgWaitForMultipleObjects(1, H, False, INFINITE, QS_SENDMESSAGE) = WAIT_OBJECT_0 + 1 do
begin
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do
begin
DispatchMessage(Msg);
end;
end;
end else
begin
WaitForSingleObject(H, INFINITE);
end;
finally
CloseHandle(H);
end;
end;
function TclCustomThreader.GetProxyString: string;
function GetProxyItem(const AProtocol, AServer: string; APort: Integer): string;
begin
if (AServer <> '') then
begin
Result := AServer;
if (system.Pos('http', LowerCase(Result)) <> 1)
and (system.Pos('ftp', LowerCase(Result)) <> 1) then
begin
Result := AProtocol + '://' + Result;
end;
Result := Format('%s=%s:%d', [AProtocol, Result, APort]);
end else
begin
Result := '';
end;
end;
begin
Result := '';
case URLParser.UrlType of
utHTTP: Result := GetProxyItem('http', HttpProxySettings.Server, HttpProxySettings.Port);
utHTTPS: Result := GetProxyItem('https', HttpProxySettings.Server, HttpProxySettings.Port);
utFTP: Result := GetProxyItem('ftp', FtpProxySettings.Server, FtpProxySettings.Port);
end;
end;
procedure TclCustomThreader.ProcessURL;
const
ConnectService: array[Boolean] of DWORD = (INTERNET_SERVICE_HTTP, INTERNET_SERVICE_FTP);
AccessTypes: array[Boolean] of DWORD = (INTERNET_OPEN_TYPE_PRECONFIG, INTERNET_OPEN_TYPE_PROXY);
ConnectFlags: array[Boolean] of DWORD = (0, INTERNET_FLAG_PASSIVE);
var
OpenAction: TclInternetOpenAction;
ConnectAction: TclConnectAction;
Proxy, usr, psw: string;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'ProcessURL');{$ENDIF}
OpenAction := nil;
ConnectAction := nil;
try
OpenAction := (Connection.GetActionByClass(TclInternetOpenAction) as TclInternetOpenAction);
if (OpenAction = nil) then
begin
Proxy := GetProxyString();
OpenAction := TclInternetOpenAction.Create(Connection, InternetAgent,
AccessTypes[(Proxy <> '')], Proxy, ProxyBypass, 0);
OpenAction.FireAction(-1);
end;
if Terminated then Exit;
ConnectAction := (Connection.GetActionByClass(TclConnectAction) as TclConnectAction);
if (ConnectAction = nil) then
begin
if (URLParser.UrlType = utFTP) then
begin
usr := URLParser.User;
psw := URLParser.Password;
end else
begin
usr := '';
psw := '';
end;
ConnectAction := TclConnectAction.Create(Connection, OpenAction.hResource,
URLParser.Host, URLParser.Port, usr, psw,
ConnectService[URLParser.UrlType = utFTP], ConnectFlags[(URLParser.UrlType = utFTP) and PassiveFTPMode]);
ConnectAction.FireAction(GetNormTimeOut(TimeOut));
end;
if Terminated then Exit;
if (URLParser.UrlType = utFTP) then
begin
ProcessFTP(ConnectAction);
end else
if (URLParser.UrlType in [utHTTP, utHTTPS]) then
begin
ProcessHTTP(ConnectAction);
end;
finally
FreeObjectIfNeed(ConnectAction);
FreeObjectIfNeed(OpenAction);
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'ProcessURL'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'ProcessURL', E); raise; end; end;{$ENDIF}
end;
procedure TclCustomThreader.GetResourceInfo(AConnect: TclConnectAction);
var
needAllInfo: Boolean;
begin
if Terminated then Exit;
ClearInfo();
needAllInfo := (FResourceInfo = nil);
if DoNotGetResourceInfo then
begin
AssignIfNeedResourceInfo();
end else
begin
case FURLParser.UrlType of
utHTTP, utHTTPS: GetHTTPResourceInfo(AConnect);
utFTP: GetFTPResourceInfo(AConnect);
end;
if Terminated then Exit;
if needAllInfo then
begin
InternalSynchronize(SyncDoGetResourceInfo);
end;
end;
end;
procedure TclCustomThreader.SyncDoGetCertificate;
begin
if Assigned(FOnGetCertificate) then
begin
FOnGetCertificate(Self, FCertificate, FCertificateHandled);
end;
end;
procedure TclCustomThreader.ProcessFTP(AConnect: TclConnectAction);
begin
GetResourceInfo(AConnect);
end;
procedure TclCustomThreader.ProcessHTTP(AConnect: TclConnectAction);
begin
GetResourceInfo(AConnect);
end;
procedure TclCustomThreader.SetResourceInfo(const Value: TclResourceInfo);
begin
if (ResourceInfo <> Value) then
begin
ClearInfo();
FResourceInfo := Value;
end;
end;
function TclCustomThreader.GetInternalResourceInfo: TclResourceInfo;
begin
if (FResourceInfo <> nil) then
begin
Result := FResourceInfo;
end else
begin
Result := FSelfResourceInfo;
end;
end;
procedure TclCustomThreader.BeginDataStreamAccess;
begin
if (FDataAccessor <> nil) then
begin
FDataAccessor.Enter();
end;
end;
procedure TclCustomThreader.EndDataStreamAccess;
begin
if (FDataAccessor <> nil) then
begin
FDataAccessor.Leave();
end;
end;
procedure TclCustomThreader.SetURLParser(const Value: TclUrlParser);
begin
FURLParser.Assign(Value);
end;
function TclCustomThreader.GetConnection: TclInternetConnection;
begin
if (FConnection <> nil) then
begin
Result := FConnection;
end else
begin
if (FSelfConnection = nil) then
begin
FSelfConnection := TclInternetConnection.Create(nil);
end;
Result := FSelfConnection;
end;
end;
procedure TclCustomThreader.SetConnection(const Value: TclInternetConnection);
begin
FConnection := Value;
FSelfConnection.Free();
FSelfConnection := nil;
end;
procedure TclCustomThreader.FreeObjectIfNeed(var AObject);
var
Temp: TObject;
begin
if not KeepConnection then
begin
Temp := TObject(AObject);
Pointer(AObject) := nil;
Temp.Free();
end;
end;
type
TclInternetConnectionAccess = class(TclInternetConnection);
procedure TclCustomThreader.Stop;
begin
Terminate();
SetEvent(FSleepEvent);
DoStop();
end;
procedure TclCustomThreader.DoStop;
begin
TclInternetConnectionAccess(Connection).Stop();
end;
function TclCustomThreader.GetOpenRequestFlags(ANeedCaching: Boolean): DWORD;
begin
if ANeedCaching then
begin
Result := 0;
end else
begin
Result := INTERNET_FLAG_NO_CACHE_WRITE;
end;
if KeepConnection then
begin
Result := Result or INTERNET_FLAG_KEEP_CONNECTION;
end;
if (URLParser.UrlType = utHTTPS) then
begin
Result := Result or INTERNET_FLAG_SECURE;
end;
end;
procedure TclCustomThreader.DoTerminate;
begin
if Assigned(OnTerminate) then
begin
InternalSynchronize(SyncTerminate);
end;
end;
procedure TclCustomThreader.SyncTerminate;
begin
if Assigned(OnTerminate) then
begin
OnTerminate(Self);
end;
end;
procedure TclCustomThreader.SetHttpHeader(AResourceAction: TclInternetResourceAction);
const
AcceptEncoding = 'Accept-Encoding: gzip, deflate';
var
s: string;
auth: TclHttpBasicAuthorization;
authMethods: TStrings;
begin
if (RequestHeader.Count > 0) then
begin
s := Trim(RequestHeader.Text);
HttpAddRequestHeaders(AResourceAction.hResource, PChar(s), Length(s), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
end;
if AllowCompression then
begin
HttpAddRequestHeaders(AResourceAction.hResource, AcceptEncoding,
Length(AcceptEncoding), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
end;
if (HttpProxySettings.AuthenticationType = atBasic)
and ((HttpProxySettings.UserName <> '') or (HttpProxySettings.Password <> '')) then
begin
auth := nil;
authMethods := nil;
try
auth := TclHttpBasicAuthorization.Create();
authMethods := TStringList.Create();
authMethods.Add('Basic');
s := 'Proxy-Authorization: ' + auth.Authenticate(FURLParser, '',
HttpProxySettings.UserName, HttpProxySettings.Password, authMethods, Self);
HttpAddRequestHeaders(AResourceAction.hResource, PChar(s), Length(s), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
finally
authMethods.Free();
auth.Free();
end;
end;
end;
procedure TclCustomThreader.SetRequestHeader(const Value: TStrings);
begin
FRequestHeader.Assign(Value);
end;
procedure TclCustomThreader.ServerAuthentication(AOpenRequest: TclHttpOpenRequestAction);
var
p: PChar;
begin
if (URLParser.User <> '') then
begin
p := PChar(URLParser.User);
InternetSetOption(AOpenRequest.hResource, INTERNET_OPTION_USERNAME,
p, Length(URLParser.User));
end;
if (URLParser.Password <> '') then
begin
p := PChar(URLParser.Password);
InternetSetOption(AOpenRequest.hResource, INTERNET_OPTION_PASSWORD,
p, Length(URLParser.Password));
end;
end;
procedure TclCustomThreader.ProxyAuthentication(AOpenRequest: TclHttpOpenRequestAction);
var
p: PChar;
begin
if (HttpProxySettings.UserName <> '') then
begin
p := PChar(HttpProxySettings.UserName);
InternetSetOption(AOpenRequest.hResource, INTERNET_OPTION_PROXY_USERNAME,
p, Length(HttpProxySettings.UserName));
end;
if (HttpProxySettings.Password <> '') then
begin
p := PChar(HttpProxySettings.Password);
InternetSetOption(AOpenRequest.hResource, INTERNET_OPTION_PROXY_PASSWORD,
p, Length(HttpProxySettings.Password));
end;
end;
procedure TclCustomThreader.SetFtpProxySettings(const Value: TclFtpProxySettings);
begin
FFtpProxySettings.Assign(Value);
end;
procedure TclCustomThreader.SetHttpProxySettings(const Value: TclHttpProxySettings);
begin
FHttpProxySettings.Assign(Value);
end;
{ TclDownLoadThreader }
constructor TclDownLoadThreader.Create(const AURL: string; ADataStream: TStream; AIsGetResourceInfo: Boolean);
begin
inherited Create(AURL, ADataStream);
FIsGetResourceInfo := AIsGetResourceInfo;
FDataProceedSize := 0;
FTotalDownloaded := 0;
end;
procedure TclDownLoadThreader.SetResourcePos(AResourceAction: TclInternetResourceAction);
var
s: string;
begin
if (FBytesToProceed > -1) then
begin
s := Format('Range: bytes=%d-%d', [ResourcePos, ResourcePos + FBytesToProceed]);
HttpAddRequestHeaders(AResourceAction.hResource, PChar(s), Length(s), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
end else
if (TempErrorCode <> 12152) then
begin
s := 'Range: bytes=0-';
HttpAddRequestHeaders(AResourceAction.hResource, PChar(s), Length(s), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
end;
end;
procedure TclDownLoadThreader.Dump(AResourceAction: TclInternetResourceAction);
var
BytesToRead: Integer;
ReadFileAction: TclInternetReadFileAction;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Dump');{$ENDIF}
if (DataStream <> nil) then
begin
BeginDataStreamAccess();
try
if (FBytesToProceed < 0) then
begin
DataStream.Position := 0;
end;
finally
EndDataStreamAccess();
end;
end;
ReadFileAction := nil;
GetMem(FDataProceed, FBatchSize + 1);
try
ReadFileAction := TclInternetReadFileAction.Create(Connection, AResourceAction.Internet,
AResourceAction.hResource, FDataProceed);
repeat
ZeroMemory(FDataProceed, FBatchSize + 1);
if (FBytesToProceed > -1) and ((FBytesToProceed - FTotalDownloaded) < FBatchSize) then
begin
BytesToRead := (FBytesToProceed - FTotalDownloaded);
end else
begin
BytesToRead := FBatchSize;
end;
ReadFileAction.dwNumberOfBytesToRead := BytesToRead;
ReadFileAction.FireAction(GetNormTimeOut(TimeOut));
FDataProceedSize := ReadFileAction.lpdwNumberOfBytesRead;
if (FDataProceedSize = 0)
or ((FBytesToProceed > -1) and (FTotalDownloaded >= FBytesToProceed)) then Break;
if (DataStream <> nil) then
begin
BeginDataStreamAccess();
try
if (FBytesToProceed > -1) then
begin
DataStream.Position := ResourcePos;
end;
DataStream.Write(FDataProceed^, FDataProceedSize);
finally
EndDataStreamAccess();
end;
end;
FTotalDownloaded := FTotalDownloaded + FDataProceedSize;
ResourcePos := ResourcePos + FDataProceedSize;
InternalSynchronize(SyncDoDataItemProceed);
until (Terminated);
finally
ReadFileAction.Free();
FreeMem(FDataProceed);
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Dump'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Dump', E); raise; end; end;{$ENDIF}
end;
procedure TclDownLoadThreader.ProcessFTP(AConnect: TclConnectAction);
var
OpenFileAction: TclFtpOpenFileAction;
begin
inherited ProcessFTP(AConnect);
if FIsGetResourceInfo or (FBytesToProceed = 0) then Exit;
if Terminated then Exit;
OpenFileAction := nil;
try
OpenFileAction := (Connection.GetActionByClass(TclFtpOpenFileAction) as TclFtpOpenFileAction);
if (OpenFileAction = nil) then
begin
OpenFileAction := TclFtpOpenFileAction.Create(Connection, AConnect.Internet, AConnect.hResource,
URLParser.Urlpath, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY);
OpenFileAction.FireAction(GetNormTimeOut(TimeOut));
end;
if Terminated then Exit;
Dump(OpenFileAction);
finally
FreeObjectIfNeed(OpenFileAction);
end;
end;
procedure TclDownLoadThreader.PrepareHeader;
var
i: Integer;
begin
for i := RequestHeader.Count - 1 downto 0 do
begin
if (system.Pos('content-', LowerCase(RequestHeader[i])) > 0) then
begin
RequestHeader.Delete(i);
end;
end;
end;
procedure TclDownLoadThreader.ProcessHTTP(AConnect: TclConnectAction);
var
OpenRequestAction: TclHttpOpenRequestAction;
begin
PrepareHeader();
inherited ProcessHTTP(AConnect);
if FIsGetResourceInfo or (FBytesToProceed = 0) then Exit;
if Terminated then Exit;
OpenRequestAction := nil;
try
OpenRequestAction := (Connection.GetActionByClass(TclHttpOpenRequestAction) as TclHttpOpenRequestAction);
if (OpenRequestAction = nil) then
begin
OpenRequestAction := TclHttpOpenRequestAction.Create(Connection, AConnect.Internet, AConnect.hResource,
'GET', URLParser.Urlpath + URLParser.Extra, '', '', nil, GetOpenRequestFlags(False));
OpenRequestAction.FireAction(GetNormTimeOut(TimeOut));
end;
if Terminated then Exit;
SetHttpHeader(OpenRequestAction);
SetResourcePos(OpenRequestAction);
SendRequest(OpenRequestAction);
if Terminated then Exit;
if DoNotGetResourceInfo then
begin
QueryHeadInfo(OpenRequestAction);
QueryGetInfo(OpenRequestAction);
InternalSynchronize(SyncDoGetResourceInfo);
end;
Dump(OpenRequestAction);
finally
FreeObjectIfNeed(OpenRequestAction);
end;
end;
procedure TclDownLoadThreader.SyncDoDataItemProceed;
begin
if Assigned(OnDataItemProceed) then
begin
OnDataItemProceed(Self, ResourceInfo, ResourcePos, FDataProceed, FDataProceedSize);
end;
end;
{ TclUploadThreader }
constructor TclUploadThreader.Create(const AURL: string; ADataStream: TStream; AIsGetResourceInfo: Boolean);
begin
inherited Create(AURL, ADataStream);
FIsGetResourceInfo := AIsGetResourceInfo;
FDataProceedSize := 0;
FUploadedDataSize := 0;
FDataProceed := nil;
FRequestMethod := 'PUT';
end;
procedure TclUploadThreader.Dump(AResourceAction: TclInternetResourceAction);
var
Uploaded: Integer;
WriteFileAction: TclInternetWriteFileAction;
begin
Dec(FRetryProceed);
if (DataStream = nil) then Exit;
Uploaded := 0;
FUploadedDataSize := 0;
WriteFileAction := nil;
GetMem(FDataProceed, FBatchSize + 1);
try
WriteFileAction := TclInternetWriteFileAction.Create(Connection, AResourceAction.Internet,
AResourceAction.hResource);
while (not Terminated) and (Uploaded < DataStream.Size) do
begin
BeginDataStreamAccess();
try
DataStream.Position := Uploaded;
FDataProceedSize := DataStream.Read(FDataProceed^, FBatchSize);
finally
EndDataStreamAccess();
end;
WriteFileAction.lpBuffer := FDataProceed;
WriteFileAction.dwNumberOfBytesToWrite := FDataProceedSize;
WriteFileAction.FireAction(GetNormTimeOut(TimeOut));
Uploaded := Uploaded + FDataProceedSize;
FUploadedDataSize := FUploadedDataSize + FDataProceedSize;
InternalSynchronize(SyncDoDataItemProceed);
end;
finally
WriteFileAction.Free();
FreeMem(FDataProceed);
end;
end;
type
TclRequestParameters = class(TObject)
FSendRequestAction: TclHttpSendRequestExAction;
FEndRequestAction: TclHttpEndRequestAction;
FOpenRequest: TclHttpOpenRequestAction;
end;
procedure TclUploadThreader.RequestOperation(AParameters: TObject);
var
RequestParameters: TclRequestParameters;
begin
RequestParameters := (AParameters as TclRequestParameters);
RequestParameters.FSendRequestAction.FireAction(GetNormTimeOut(TimeOut));
if Terminated then Exit;
Dump(RequestParameters.FOpenRequest);
if Terminated then Exit;
RequestParameters.FEndRequestAction.FireAction(GetNormTimeOut(TimeOut));
end;
procedure TclUploadThreader.ProcessRequest(AOpenRequest: TclHttpOpenRequestAction;
const AHeader: string; ADataSize: Integer);
var
RequestParameters: TclRequestParameters;
SendRequestAction: TclHttpSendRequestExAction;
EndRequestAction: TclHttpEndRequestAction;
bufin: INTERNET_BUFFERS;
begin
ZeroMemory(@bufin, SizeOf(bufin));
if (AHeader <> '') then
begin
bufin.lpcszHeader := PChar(AHeader);
bufin.dwHeadersLength := Length(AHeader);
end;
bufin.dwStructSize := SizeOf(bufin);
bufin.dwBufferTotal := ADataSize;
SendRequestAction := nil;
EndRequestAction := nil;
RequestParameters := nil;
try
SendRequestAction := TclHttpSendRequestExAction.Create(Connection, AOpenRequest.Internet,
AOpenRequest.hResource, @bufin, nil, HSR_INITIATE);
EndRequestAction := TclHttpEndRequestAction.Create(Connection, AOpenRequest.Internet,
AOpenRequest.hResource, nil, HSR_INITIATE);
RequestParameters := TclRequestParameters.Create();
RequestParameters.FSendRequestAction := SendRequestAction;
RequestParameters.FEndRequestAction := EndRequestAction;
RequestParameters.FOpenRequest := AOpenRequest;
PerformRequestOperation(AOpenRequest, RequestOperation, RequestParameters);
finally
RequestParameters.Free();
EndRequestAction.Free();
SendRequestAction.Free();
end;
end;
procedure TclUploadThreader.GetResourceInfoByDataStream();
begin
ClearInfo();
if (DataStream = nil) then
begin
raise EclInternetError.Create(cDataStreamAbsent, -1);
end;
if (FResourceInfo = nil) then
begin
AssignIfNeedResourceInfo();
TclResourceInfoAccess(ResourceInfo).SetSize(DataStream.Size);
TclResourceInfoAccess(ResourceInfo).SetName('');
end;
end;
procedure TclUploadThreader.ProcessHTTP(AConnect: TclConnectAction);
var
i: Integer;
OpenRequestAction: TclHttpOpenRequestAction;
begin
FRetryCount := GetRetryCount();
FRetryProceed := FRetryCount + 1;
if (not FIsGetResourceInfo) then
begin
GetResourceInfoByDataStream();
OpenRequestAction := nil;
try
OpenRequestAction := (Connection.GetActionByClass(TclHttpOpenRequestAction) as TclHttpOpenRequestAction);
if (OpenRequestAction = nil) then
begin
OpenRequestAction := TclHttpOpenRequestAction.Create(Connection, AConnect.Internet, AConnect.hResource,
RequestMethod, URLParser.Urlpath + URLParser.Extra, '', '', nil, GetOpenRequestFlags(False));
OpenRequestAction.FireAction(GetNormTimeOut(TimeOut));
end;
if Terminated then Exit;
if (ResourceInfo <> nil) then
begin
SetHttpHeader(OpenRequestAction);
i := 0;
while (i < 4) do
begin
Inc(i);
if UseSimpleRequest then
begin
ProcessSimpleRequest(OpenRequestAction, '', DataStream);
end else
begin
ProcessRequest(OpenRequestAction, '', ResourceInfo.Size);
end;
try
GetHttpStatusCode(OpenRequestAction);
Break;
except
if (ResourceInfo.StatusCode = 401) then
begin
if UseInternetErrorDialog then
begin
SetCertOptions(OpenRequestAction, 0);
end else
if (i < 4) then
begin
ServerAuthentication(OpenRequestAction);
end else
begin
raise;
end;
end else
if (ResourceInfo.StatusCode = 407) then
begin
if UseInternetErrorDialog then
begin
SetCertOptions(OpenRequestAction, 0);
end else
if (HttpProxySettings.AuthenticationType = atAutoDetect) then
begin
ProxyAuthentication(OpenRequestAction);
end else
begin
raise;
end;
end else
begin
raise;
end;
end;
if Terminated then Exit;
end;
if (FRetryCount > 0) then
begin
FRetryCount := 0;
SyncDoDataItemProceed();
end;
end;
GetHttpResponse(OpenRequestAction);
finally
FreeObjectIfNeed(OpenRequestAction);
end;
end;
if SameText(RequestMethod, 'PUT') then
begin
inherited ProcessHTTP(AConnect);
end;
end;
procedure TclUploadThreader.ProcessFTP(AConnect: TclConnectAction);
var
OpenFileAction: TclFtpOpenFileAction;
begin
FRetryCount := 0;
FRetryProceed := 0;
if (not FIsGetResourceInfo) then
begin
GetResourceInfoByDataStream();
OpenFileAction := nil;
try
if FForceRemoteDir then
begin
ForceRemoteDirectory(AConnect);
end;
if Terminated then Exit;
OpenFileAction := (Connection.GetActionByClass(TclFtpOpenFileAction) as TclFtpOpenFileAction);
if (OpenFileAction = nil) then
begin
OpenFileAction := TclFtpOpenFileAction.Create(Connection, AConnect.Internet, AConnect.hResource,
URLParser.Urlpath, GENERIC_WRITE, FTP_TRANSFER_TYPE_BINARY);
OpenFileAction.FireAction(GetNormTimeOut(TimeOut));
end;
if Terminated then Exit;
Dump(OpenFileAction);
finally
FreeObjectIfNeed(OpenFileAction);
end;
end;
inherited ProcessFTP(AConnect);
end;
procedure TclUploadThreader.SyncDoDataItemProceed;
var
uploaded: Integer;
begin
if Assigned(OnDataItemProceed) then
begin
if FRetryCount > 0 then
begin
uploaded := FUploadedDataSize div FRetryCount;
uploaded := (BytesToProceed div FRetryCount) * (FRetryCount - FRetryProceed) + uploaded;
end else
begin
uploaded := FUploadedDataSize;
end;
OnDataItemProceed(Self, ResourceInfo, uploaded, FDataProceed, FDataProceedSize);
end;
end;
procedure TclUploadThreader.GetHttpResponse(AOpenRequest: TclHttpOpenRequestAction);
var
dwDownloaded: DWORD;
buf: PChar;
ReadFileAction: TclInternetReadFileAction;
begin
if (HttpResponse = nil) or Terminated then Exit;
ReadFileAction := nil;
GetMem(buf, FBatchSize);
try
ReadFileAction := TclInternetReadFileAction.Create(Connection, AOpenRequest.Internet,
AOpenRequest.hResource, buf);
repeat
ZeroMemory(buf, FBatchSize);
ReadFileAction.dwNumberOfBytesToRead := FBatchSize;
ReadFileAction.FireAction(GetNormTimeOut(TimeOut));
dwDownloaded := ReadFileAction.lpdwNumberOfBytesRead;
if (dwDownloaded = 0) then Break;
BeginDataStreamAccess();
try
HttpResponse.Write(buf^, dwDownloaded);
finally
EndDataStreamAccess();
end;
until (Terminated);
finally
ReadFileAction.Free();
FreeMem(buf);
end;
end;
procedure TclUploadThreader.ForceRemoteDirectory(AConnect: TclConnectAction);
function ExtractFtpFilePath(const AFileName: string): string;
var
i: Integer;
begin
i := LastDelimiter('/', AFileName);
Result := Copy(AFileName, 1, i);
end;
function IsFtpPathDelimiter(const S: string; Index: Integer): Boolean;
begin
Result := (Index > 0) and (Index <= Length(S)) and (S[Index] = '/')
and (ByteType(S, Index) = mbSingleByte);
end;
function ExcludeTrailingFtpBackslash(const S: string): string;
begin
Result := S;
if IsFtpPathDelimiter(Result, Length(Result)) then
SetLength(Result, Length(Result)-1);
end;
function FtpDirectoryExists(const Name: string): Boolean;
var
Action: TclFtpFindFirstFileAction;
begin
Action := TclFtpFindFirstFileAction.Create(Connection, AConnect.Internet,
AConnect.hResource, PChar(Name), INTERNET_FLAG_RELOAD);
try
Result := Action.FireAction(GetNormTimeOut(TimeOut), True);
except
Result := False;
end;
Action.Free();
end;
function CreateFtpDir(const Dir: string): Boolean;
var
Action: TclFtpCreateDirectoryAction;
begin
Action := TclFtpCreateDirectoryAction.Create(Connection, AConnect.Internet, AConnect.hResource, Dir);
try
Result := Action.FireAction(GetNormTimeOut(TimeOut), True);
except
Result := False;
end;
Action.Free();
end;
function ForceDirs(Dir: String): Boolean;
begin
Result := True;
if Length(Dir) = 0 then Exit;
Dir := ExcludeTrailingFtpBackslash(Dir);
if (Length(Dir) < 1) or FtpDirectoryExists(Dir)
or (ExtractFtpFilePath(Dir) = Dir) then Exit;
Result := ForceDirs(ExtractFtpFilePath(Dir)) and CreateFtpDir(Dir);
end;
begin
ForceDirs(ExtractFtpFilePath(URLParser.Urlpath));
end;
procedure TclUploadThreader.ProcessSimpleRequest(
AOpenRequest: TclHttpOpenRequestAction; const AHeader: string;
AData: TStream);
var
SendRequestAction: TclHttpSendRequestAction;
begin
FDataProceed := nil;
SendRequestAction := nil;
try
FUploadedDataSize := AData.Size;
FDataProceedSize := FUploadedDataSize;
GetMem(FDataProceed, FDataProceedSize + 1);
ZeroMemory(FDataProceed, FDataProceedSize + 1);
BeginDataStreamAccess();
try
AData.Position := 0;
AData.Read(FDataProceed^, FDataProceedSize);
finally
EndDataStreamAccess();
end;
SendRequestAction := TclHttpSendRequestAction.Create(Connection, AOpenRequest.Internet,
AOpenRequest.hResource, AHeader, FDataProceed, FDataProceedSize);
PerformRequestOperation(AOpenRequest, SimpleRequestOperation, SendRequestAction);
finally
FreeMem(FDataProceed);
SendRequestAction.Free();
end;
end;
procedure TclUploadThreader.SimpleRequestOperation(AParameters: TObject);
begin
(AParameters as TclHttpSendRequestAction).FireAction(GetNormTimeOut(TimeOut));
InternalSynchronize(SyncDoDataItemProceed);
end;
function TclUploadThreader.GetRetryCount: Integer;
begin
Result := 0;
if (not PutOptimization) then
begin
Exit;
end;
if (URLParser.User <> '') and (URLParser.Password <> '') then
begin
Inc(Result);
end;
if (HttpProxySettings.UserName <> '') and (HttpProxySettings.Password <> '') then
begin
Inc(Result);
end;
if (URLParser.UrlType = utHTTPS) then
begin
Inc(Result);
end;
Inc(Result);
end;
{ TclDeleteThreader }
constructor TclDeleteThreader.Create(const AURL: string);
begin
inherited Create(AURL, nil);
end;
procedure TclDeleteThreader.ProcessFTP(AConnect: TclConnectAction);
var
b: Boolean;
begin
if (URLParser.Urlpath <> '') and (URLParser.Urlpath[Length(URLParser.Urlpath)] = '/') then
begin
b := FtpRemoveDirectory(AConnect.hResource, PChar(URLParser.Urlpath));
end else
begin
b := FtpDeleteFile(AConnect.hResource, PChar(URLParser.Urlpath));
end;
if not b then
begin
raise EclInternetError.CreateByLastError();
end;
end;
procedure TclDeleteThreader.ProcessHTTP(AConnect: TclConnectAction);
var
OpenRequestAction: TclHttpOpenRequestAction;
begin
OpenRequestAction := nil;
try
OpenRequestAction := (Connection.GetActionByClass(TclHttpOpenRequestAction) as TclHttpOpenRequestAction);
if (OpenRequestAction = nil) then
begin
OpenRequestAction := TclHttpOpenRequestAction.Create(Connection, AConnect.Internet,
AConnect.hResource, 'DELETE', URLParser.Urlpath + URLParser.Extra, '', '', nil, GetOpenRequestFlags(False));
OpenRequestAction.FireAction(GetNormTimeOut(TimeOut));
end;
if Terminated then Exit;
SetHttpHeader(OpenRequestAction);
SendRequest(OpenRequestAction);
finally
FreeObjectIfNeed(OpenRequestAction);
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20160510 - 150040
////////////////////////////////////////////////////////////////////////////////
unit java.util.UnknownFormatFlagsException;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JUnknownFormatFlagsException = interface;
JUnknownFormatFlagsExceptionClass = interface(JObjectClass)
['{672D0F5C-0DB3-4B3D-A089-06C6DFA5C36C}']
function getFlags : JString; cdecl; // ()Ljava/lang/String; A: $1
function getMessage : JString; cdecl; // ()Ljava/lang/String; A: $1
function init(f : JString) : JUnknownFormatFlagsException; cdecl; // (Ljava/lang/String;)V A: $1
end;
[JavaSignature('java/util/UnknownFormatFlagsException')]
JUnknownFormatFlagsException = interface(JObject)
['{1EB46FDC-ABFF-45D0-A415-667787332A77}']
function getFlags : JString; cdecl; // ()Ljava/lang/String; A: $1
function getMessage : JString; cdecl; // ()Ljava/lang/String; A: $1
end;
TJUnknownFormatFlagsException = class(TJavaGenericImport<JUnknownFormatFlagsExceptionClass, JUnknownFormatFlagsException>)
end;
implementation
end.
|
unit u_pjkey;
interface
uses classes, files, fileoperations, misc_utils, u_pj3dos;
type
TKEYEntry=class
flags:integer;
framenum:integer;
cx,cy,cz,cpch,cyaw,crol:double;
dx,dy,dz,dpch,dyaw,drol:double;
end;
TKEYEntries=class(TList)
Function GetItem(n:integer):TKEYEntry;
Procedure SetItem(n:integer;v:TKEYEntry);
Property Items[n:integer]:TKEYEntry read GetItem write SetItem; default;
end;
TKEYNode=class
nodenum:integer;
nodename:string;
entries:TKeyEntries;
constructor Create;
Procedure GetFrame(n:integer;var x,y,z,pch,yaw,rol:double);
destructor Destroy;
end;
TKEYNodes=class(TList)
Function GetItem(n:integer):TKEYNode;
Procedure SetItem(n:integer;v:TKEYNode);
Property Items[n:integer]:TKEYNode read GetItem write SetItem; default;
end;
TKeyFile=class
name:string;
nframes:integer;
flags:integer;
fps:integer;
nodes:TKeyNodes;
Constructor CreateNew;
Constructor CreateFromKEY(const name:string);
Destructor Destroy;
Procedure ApplyKey(a3DO:TPJ3DO;frame:integer);
end;
implementation
Function TKEYEntries.GetItem(n:integer):TKEYEntry;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('KEY Entry Index is out of bounds: %d',[n]);
Result:=TKEYEntry(List[n]);
end;
Procedure TKEYEntries.SetItem(n:integer;v:TKEYEntry);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('KEY Entry Index is out of bounds: %d',[n]);
List[n]:=v;
end;
Function TKEYNodes.GetItem(n:integer):TKEYNode;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('KEY Node Index is out of bounds: %d',[n]);
Result:=TKEYNode(List[n]);
end;
Procedure TKEYNodes.SetItem(n:integer;v:TKEYNode);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('KEY Node Index is out of bounds: %d',[n]);
List[n]:=v;
end;
constructor TKEYNode.Create;
begin
entries:=TKEYEntries.Create;
end;
Procedure TKEYNode.GetFrame(n:integer;var x,y,z,pch,yaw,rol:double);
var i,df:integer;
begin
for i:=0 to entries.count-1 do if n<entries[i].framenum then break;
With entries[i-1] do
begin
df:=n-framenum;
x:=cx+(dx*df);
y:=cy+(dx*df);
z:=cz+(dz*df);
pch:=cpch+(dpch*df);
yaw:=cyaw+(dyaw*df);
rol:=crol+(drol*df);
{pch:=Round(cpch+(dpch*df)) mod 360;
if pch<0 then pch:=360+pch;
yaw:=Round(cyaw+(dyaw*df)) mod 360;
if yaw<0 then yaw:=360+yaw;
rol:=Round(crol+(drol*df)) mod 360;
if rol<0 then rol:=360+rol;}
end;
end;
(*Procedure TKEYNode.GetFrame(n:integer;var x,y,z,pch,yaw,rol:double);
var c,i:integer;
ke:TKeyEntry;
d:double;
df:integer;
npentry,noentry:integer;
begin
npentry:=-1;
noentry:=-1;
for i:=0 to entries.count-1 do
With entries[i] do
begin
if n<framenum then break;
if (flags and 1)<>0 then npentry:=i;
if (flags and 2)<>0 then noentry:=i;
if n=framenum then break;
end;
if npentry<>-1 then
begin
ke:=entries[npentry];
df:=n-ke.framenum;
{ if abs then
begin}
{ x:=ke.cx+ke.dx*df;
y:=ke.cy+ke.dy*df;
z:=ke.cz+ke.dz*df;}
{ end
else
begin}
{ x:=x+ke.cx+ke.dx*df;
y:=y+ke.cy+ke.dy*df;
z:=z+ke.cz+ke.dz*df;}
{ end;}
end;
if noentry<>-1 then
begin
ke:=entries[noentry];
df:=n-ke.framenum;
pch:=ke.cpch+ke.dpch*df;
yaw:=ke.cyaw+ke.dyaw*df;
rol:=ke.crol+ke.drol*df;
end;
end; *)
destructor TKEYNode.Destroy;
var i:integer;
begin
for i:=0 to entries.count-1 do entries[i].Free;
entries.free;
end;
Constructor TKEYFile.CreateNew;
begin
name:='Untitled.key';
nframes:=0;
flags:=0;
fps:=15;
nodes:=TKeyNodes.Create;
end;
{$i pjkey_io.inc}
Destructor TKEYFile.Destroy;
var i:integer;
begin
for i:=0 to nodes.count-1 do nodes[i].free;
nodes.free;
end;
Procedure TKEYFile.ApplyKey(a3DO:TPJ3DO;frame:integer);
var i,j:integer;
anode:T3DOHNode;
transfd:array[0..500] of boolean;
Function GetMeshIdx(const name:string):integer;
var i:integer;
begin
result:=-1;
for i:=0 to a3DO.hnodes.count-1 do
if not transfd[i] then
if CompareText(a3DO.hnodes[i].MeshName,name)=0 then
begin
result:=i;
transfd[i]:=true;
break;
end;
end;
begin
fillChar(transfd,sizeof(transfd),0);
a3DO.setdefaultoffsets;
for i:=0 to nodes.count-1 do
With nodes[i] do
begin
j:=GetMeshIdx(nodename);
if j=-1 then continue;
aNode:=a3DO.Hnodes[j];
With aNode do GetFrame(frame,x,y,z,pch,yaw,rol);
end;
a3Do.OffsetMeshes;
end;
end.
|
unit ibSHDatabase;
interface
uses
Windows, SysUtils, Classes, Controls, Forms, Dialogs, Graphics, StrUtils, ExtCtrls,
SHDesignIntf, TypInfo,
ibSHDesignIntf, ibSHDriverIntf, ibSHComponent, ibSHDatabaseAliasOptions;
type
TibSHDatabase = class(TibBTComponent, IibSHDatabase, ISHDatabase, ISHRegistration,
ISHTestConnection, ISHDataRootDirectory, ISHNavigatorNotify,
IibBTDataBaseExt
)
private
FBTCLServer: IibSHServer;
FDRVDatabase: TSHComponent;
FDRVTransaction: TSHComponent;
FDRVQuery: TSHComponent;
// Блядство - FIBPlus не умеет работать со всеми версиями InterBase
FDRVDatabase2: TSHComponent;
FDRVTransaction2: TSHComponent;
FDRVQuery2: TSHComponent;
FServer: string;
FDatabase: string;
FAlias: string;
FPageSize: string;
FCharset: string;
FSQLDialect: Integer;
FUserName: string;
FPassword: string;
FRole: string;
FLoginPrompt: Boolean;
FAdditionalConnectParams: TStrings;
FCapitalizeNames: Boolean;
FDescription: string;
FStillConnect: Boolean;
FDatabaseAliasOptions: TibSHDatabaseAliasOptions;
FDatabaseAliasOptionsInt: TibSHDatabaseAliasOptionsInt;
FExistsPrecision: Boolean;
FExistsProcParamDomains:Boolean;
FDBCharset: string;
FWasLostConnect: Boolean;
FDirectoryIID: string;
FClassIIDList: TStrings;
FClassIIDList2: TStrings; // for Jumps
FDomainList: TStrings;
FSystemDomainList: TStrings;
FTableList: TStrings;
FSystemTableList: TStrings;
FSystemTableTmpList: TStrings;
//Constraint* FConstraintList: TStrings;
FIndexList: TStrings;
FViewList: TStrings;
FProcedureList: TStrings;
FTriggerList: TStrings;
FGeneratorList: TStrings;
FExceptionList: TStrings;
FFunctionList: TStrings;
FFilterList: TStrings;
FRoleList: TStrings;
FShadowList: TStrings;
FAllNameList: TStrings;
procedure CreateDRV;
procedure FreeDRV;
procedure PrepareDRVDatabase;
procedure PrepareDBObjectLists;
procedure CreateDatabase;
procedure DropDatabase;
function ExistsInDatabase(const AClassIID: TGUID; const ACaption: string): Boolean;
function ChangeNameList(const AClassIID: TGUID; const ACaption: string; Operation: TOperation): Boolean;
procedure OnLostConnect(Sender: TObject);
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall;
function GetBranchIID: TGUID; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoOnApplyOptions; override;
function GetBTCLServer: IibSHServer;
procedure SetBTCLServer(const Value: IibSHServer);
function GetDRVDatabase: IibSHDRVDatabase;
function GetDRVTransaction: IibSHDRVTransaction;
function GetDRVQuery: IibSHDRVQuery;
function GetServer: string;
procedure SetServer(Value: string);
function GetDatabase: string;
procedure SetDatabase(Value: string);
function GetAlias: string;
procedure SetAlias(Value: string);
function GetPageSize: string;
procedure SetPageSize(Value: string);
function GetCharset: string;
procedure SetCharset(Value: string);
function GetSQLDialect: Integer;
procedure SetSQLDialect(Value: Integer);
function GetCapitalizeNames: Boolean;
procedure SetCapitalizeNames(Value: Boolean);
function GetAdditionalConnectParams: TStrings;
procedure SetAdditionalConnectParams(Value: TStrings);
function GetUserName: string;
procedure SetUserName(Value: string);
function GetPassword: string;
procedure SetPassword(Value: string);
function GetRole: string;
procedure SetRole(Value: string);
function GetLoginPrompt: Boolean;
procedure SetLoginPrompt(Value: Boolean);
function GetDescription: string;
procedure SetDescription(Value: string);
function GetConnectPath: string;
function GetStillConnect: Boolean;
procedure SetStillConnect(Value: Boolean);
function GetDirectoryIID: string;
procedure SetDirectoryIID(Value: string);
function GetDatabaseAliasOptions: IibSHDatabaseAliasOptions;
function GetExistsPrecision: Boolean;
function GetExistsProcParamDomains: Boolean;
function GetDBCharset: string;
function GetWasLostConnect: Boolean;
function GetCaption: string; override;
function GetCaptionExt: string; override;
procedure SetOwnerIID(Value: TGUID); override;
// ISHDatabase
function GetConnected: Boolean;
function GetCanConnect: Boolean;
function GetCanReconnect: Boolean;
function GetCanDisconnect: Boolean;
function GetCanShowRegistrationInfo: Boolean;
function Connect: Boolean;
function Reconnect: Boolean;
function Disconnect: Boolean;
procedure Refresh;
function ShowRegistrationInfo: Boolean;
procedure IDELoadFromFileNotify;
function GetSchemeClassIIDList(WithSystem: Boolean = False): TStrings; overload;
function GetSchemeClassIIDList(const AObjectName: string): TStrings; overload;
function GetObjectNameList: TStrings; overload;
function GetObjectNameList(const AClassIID: TGUID): TStrings; overload;
// ISHTestConnection
function GetCanTestConnection: Boolean;
function TestConnection: Boolean;
// ISHDataRootDirectory
function GetDataRootDirectory: string;
function CreateDirectory(const FileName: string): Boolean;
function RenameDirectory(const OldName, NewName: string): Boolean;
function DeleteDirectory(const FileName: string): Boolean;
// ISHNavigatorNotify
function GetFavoriteObjectNames: TStrings;
function GetFavoriteObjectColor: TColor;
function GetFilterList: TStrings;
function GetFilterIndex: Integer;
procedure SetFilterIndex(Value: Integer);
//IibBTDataBaseExt
procedure GetObjectsHaveComment(ClassObject:TGUID;Results:TStrings);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property BTCLServer: IibSHServer read GetBTCLServer write SetBTCLServer;
property DRVDatabase: IibSHDRVDatabase read GetDRVDatabase;
property DRVTransaction: IibSHDRVTransaction read GetDRVTransaction;
property DRVQuery: IibSHDRVQuery read GetDRVQuery;
property StillConnect: Boolean read GetStillConnect write SetStillConnect;
property Connected: Boolean read GetConnected;
property CanConnect: Boolean read GetCanConnect;
property CanReconnect: Boolean read GetCanReconnect;
property CanDisconnect: Boolean read GetCanDisconnect;
property CanShowRegistrationInfo: Boolean read GetCanShowRegistrationInfo;
property ClassIIDList: TStrings read FClassIIDList;
property ClassIIDList2: TStrings read FClassIIDList2;
property SystemDomainList: TStrings read FSystemDomainList;
property DomainList: TStrings read FDomainList;
property TableList: TStrings read FTableList;
property SystemTableList: TStrings read FSystemTableList;
property SystemTableTmpList: TStrings read FSystemTableTmpList;
//Constraint* property ConstraintList: TStrings read FConstraintList;
property IndexList: TStrings read FIndexList;
property ViewList: TStrings read FViewList;
property ProcedureList: TStrings read FProcedureList;
property TriggerList: TStrings read FTriggerList;
property GeneratorList: TStrings read FGeneratorList;
property ExceptionList: TStrings read FExceptionList;
property FunctionList: TStrings read FFunctionList;
property FilterList: TStrings read FFilterList;
property RoleList: TStrings read FRoleList;
property ShadowList: TStrings read FShadowList;
property AllNameList: TStrings read FAllNameList;
property ExistsPrecision: Boolean read GetExistsPrecision;
property WasLostConnect: Boolean read GetWasLostConnect;
published
property Server: string read GetServer write SetServer;
property Database: string read GetDatabase write SetDatabase;
property Alias: string read GetAlias write SetAlias;
property PageSize: string read GetPageSize write SetPageSize;
property Charset: string read GetCharset write SetCharset;
property DBCharset: string read GetDBCharset;
property SQLDialect: Integer read GetSQLDialect write SetSQLDialect;
property CapitalizeNames: Boolean read GetCapitalizeNames
write SetCapitalizeNames;
property AdditionalConnectParams: TStrings read GetAdditionalConnectParams
write SetAdditionalConnectParams;
property UserName: string read GetUserName write SetUserName;
property Password: string read GetPassword write SetPassword;
property Role: string read GetRole write SetRole;
property LoginPrompt: Boolean read GetLoginPrompt write SetLoginPrompt;
property Description: string read GetDescription write SetDescription;
property ConnectPath: string read GetConnectPath;
property DatabaseAliasOptions: TibSHDatabaseAliasOptions read FDatabaseAliasOptions
write FDatabaseAliasOptions;
// invisible
property DatabaseAliasOptionsInt: TibSHDatabaseAliasOptionsInt read FDatabaseAliasOptionsInt
write FDatabaseAliasOptionsInt;
property DirectoryIID: string read GetDirectoryIID write SetDirectoryIID;
end;
TfibSHDatabaseOptions = class(TSHComponentOptions, IibSHDatabaseOptions, IibSHDummy)
private
FCharset: string;
FCapitalizeNames: Boolean;
protected
function GetCharset: string;
procedure SetCharset(Value: string);
function GetCapitalizeNames: Boolean;
procedure SetCapitalizeNames(Value: Boolean);
function GetParentCategory: string; override;
function GetCategory: string; override;
procedure RestoreDefaults; override;
published
property Charset: string read FCharset write FCharset;
property CapitalizeNames: Boolean read FCapitalizeNames write FCapitalizeNames;
end;
TibSHDatabaseOptions = class(TfibSHDatabaseOptions, IibSHDatabaseOptions, IibSHBranch)
end;
TfbSHDatabaseOptions = class(TfibSHDatabaseOptions, IfbSHDatabaseOptions, IfbSHBranch)
end;
implementation
uses
ibSHValues, ibSHSQLs, ibSHConsts, ibSHMessages;
{ TibSHDatabase }
constructor TibSHDatabase.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAdditionalConnectParams := TStringList.Create;
FDirectoryIID := GUIDToString(InstanceIID);
FDatabaseAliasOptions := TibSHDatabaseAliasOptions.Create;
FDatabaseAliasOptionsInt := TibSHDatabaseAliasOptionsInt.Create;
PageSize := Format('%s', [S4096]);
Charset := CharsetsAndCollatesFB10[0, 0];
UserName := Format('%s', [SDefaultUserName]);
Password := Format('%s', [SDefaultPassword]);
SQLDialect := 3;
CapitalizeNames := True;
MakePropertyInvisible('DBCharset');
MakePropertyInvisible('SQLDialect');
MakePropertyInvisible('PageSize');
MakePropertyInvisible('CapitalizeNames');
MakePropertyInvisible('DirectoryIID');
MakePropertyInvisible('DatabaseAliasOptionsInt');
FClassIIDList := TStringList.Create;
FClassIIDList2 := TStringList.Create;
FDomainList := TStringList.Create;
FSystemDomainList := TStringList.Create;
FTableList := TStringList.Create;
FSystemTableList := TStringList.Create;
FSystemTableTmpList := TStringList.Create;
//Constraint* FConstraintList := TStringList.Create;
FIndexList := TStringList.Create;
FViewList := TStringList.Create;
FProcedureList := TStringList.Create;
FTriggerList := TStringList.Create;
FGeneratorList := TStringList.Create;
FExceptionList := TStringList.Create;
FFunctionList := TStringList.Create;
FFilterList := TStringList.Create;
FRoleList := TStringList.Create;
FShadowList := TStringList.Create;
FAllNameList := TStringList.Create;
CreateDRV;
end;
destructor TibSHDatabase.Destroy;
begin
FAdditionalConnectParams.Free;
FDatabaseAliasOptionsInt.Free;
FDatabaseAliasOptions.Free;
FBTCLServer := nil;
FClassIIDList.Free;
FClassIIDList2.Free;
FDomainList.Free;
FSystemDomainList.Free;
FTableList.Free;
FSystemTableList.Free;
FSystemTableTmpList.Free;
//Constraint* FConstraintList.Free;
FIndexList.Free;
FViewList.Free;
FProcedureList.Free;
FTriggerList.Free;
FGeneratorList.Free;
FExceptionList.Free;
FFunctionList.Free;
FFilterList.Free;
FRoleList.Free;
FShadowList.Free;
FAllNameList.Free;
FreeDRV;
inherited Destroy;
end;
procedure TibSHDatabase.CreateDRV;
var
vComponentClass: TSHComponentClass;
begin
if not Assigned(DRVDatabase) then
begin
// FIBPlus
vComponentClass := Designer.GetComponent(IibSHDRVDatabase_FIBPlus);
if Assigned(vComponentClass) then FDRVDatabase := vComponentClass.Create(Self);
vComponentClass := Designer.GetComponent(IibSHDRVTransaction_FIBPlus);
if Assigned(vComponentClass) then FDRVTransaction := vComponentClass.Create(Self);
vComponentClass := Designer.GetComponent(IibSHDRVQuery_FIBPlus);
if Assigned(vComponentClass) then FDRVQuery := vComponentClass.Create(Self);
// FIBPlus68
vComponentClass := Designer.GetComponent(IibSHDRVDatabase_FIBPlus68);
if Assigned(vComponentClass) then FDRVDatabase2 := vComponentClass.Create(Self);
vComponentClass := Designer.GetComponent(IibSHDRVTransaction_FIBPlus68);
if Assigned(vComponentClass) then FDRVTransaction2 := vComponentClass.Create(Self);
vComponentClass := Designer.GetComponent(IibSHDRVQuery_FIBPlus68);
if Assigned(vComponentClass) then FDRVQuery2 := vComponentClass.Create(Self);
if Assigned(FDRVDatabase) and Assigned(FDRVTransaction) and Assigned(FDRVQuery) then
begin
(FDRVTransaction as IibSHDRVTransaction).Database := FDRVDatabase as IibSHDRVDatabase;
(FDRVTransaction as IibSHDRVTransaction).Params.Text := TRReadParams;
(FDRVQuery as IibSHDRVQuery).Database := FDRVDatabase as IibSHDRVDatabase;
(FDRVQuery as IibSHDRVQuery).Transaction := FDRVTransaction as IibSHDRVTransaction;
end;
if Assigned(FDRVDatabase2) and Assigned(FDRVTransaction2) and Assigned(FDRVQuery2) then
begin
(FDRVTransaction2 as IibSHDRVTransaction).Database := FDRVDatabase2 as IibSHDRVDatabase;
(FDRVTransaction2 as IibSHDRVTransaction).Params.Text := TRReadParams;
(FDRVQuery2 as IibSHDRVQuery).Database := FDRVDatabase2 as IibSHDRVDatabase;
(FDRVQuery2 as IibSHDRVQuery).Transaction := FDRVTransaction2 as IibSHDRVTransaction;
end;
end;
end;
procedure TibSHDatabase.FreeDRV;
begin
if Assigned(DRVDatabase) then
begin
if DRVTransaction.InTransaction then DRVTransaction.Rollback;
if DRVDatabase.Connected then DRVDatabase.Disconnect;
FreeAndNil(FDRVTransaction);
FreeAndNil(FDRVQuery);
FreeAndNil(FDRVDatabase);
FreeAndNil(FDRVTransaction2);
FreeAndNil(FDRVQuery2);
FreeAndNil(FDRVDatabase2);
end;
end;
procedure TibSHDatabase.PrepareDRVDatabase;
begin
if Assigned(DRVDatabase) then
begin
DRVDatabase.DBParams.Clear;
DRVDatabase.Database := Self.ConnectPath;
DRVDatabase.Charset := Self.Charset;
DRVDatabase.UserName := Self.UserName;
DRVDatabase.Password := Self.Password;
DRVDatabase.RoleName := Self.Role;
DRVDatabase.LoginPrompt := Self.LoginPrompt;
DRVDatabase.ClientLibrary := Self.BTCLServer.ClientLibrary;
DRVDatabase.CapitalizeNames := Self.CapitalizeNames;
DRVDatabase.DBParams.AddStrings(Self.AdditionalConnectParams);
DRVDatabase.OnLostConnect := OnLostConnect;
if Assigned(BTCLServer) then
if (BTCLServer.Version=SInterBase2007)
and (BTCLServer.InstanceName<>'')
then
DRVDatabase.DBParams.Add('instance_name='+BTCLServer.InstanceName);
end;
end;
procedure TibSHDatabase.PrepareDBObjectLists;
procedure FillList(AList: TStrings; const SQL: string);
begin
AList.Clear;
TStringList(AList).Sorted := False;
if DRVQuery.ExecSQL(SQL, [], False) then
begin
while not DRVQuery.Eof do
begin
if DRVQuery.GetFieldCount>1 then
AList.AddObject(DRVQuery.GetFieldStrValue(0),TObject(DRVQuery.GetFieldIntValue(1)))
else
AList.Add(DRVQuery.GetFieldStrValue(0));
AllNameList.Add(DRVQuery.GetFieldStrValue(0));
DRVQuery.Next;
end;
end;
TStringList(AList).Sorted := True;
end;
begin
if Assigned(DRVDatabase) then
begin
SQLDialect := DRVDatabase.SQLDialect;
if DRVQuery.ExecSQL(FormatSQL(SQL_EXISTS_PRECISION), [], False) then
FExistsPrecision := DRVQuery.GetFieldIntValue(0) = 1;
if DRVQuery.ExecSQL(FormatSQL(SQL_EXISTS_PROC_PARAMDOMAINS), [], False) then
FExistsProcParamDomains := DRVQuery.GetFieldIntValue(0) = 1;
if DRVQuery.ExecSQL(FormatSQL(SQL_GET_DB_CHARSET), [], False) then
FDBCharset := DRVQuery.GetFieldStrValue(0);
if Length(FDBCharset) = 0 then FDBCharset := CharsetsAndCollatesFB10[0, 0];
AllNameList.Clear;
TStringList(AllNameList).Sorted := False;
if not StillConnect then
begin
FillList(DomainList, FormatSQL(SQL_GET_DOMAIN_NAME_LIST));
FillList(SystemDomainList, FormatSQL(SQL_GET_SYSTEM_DOMAIN_NAME_LIST));
FillList(TableList, FormatSQL(SQL_GET_TABLE_NAME_LIST));
FillList(SystemTableList, FormatSQL(SQL_GET_SYSTEM_TABLE_NAME_LIST));
FillList(SystemTableTmpList, FormatSQL(SQL_GET_SYSTEM_TABLE_TMP_NAME_LIST));
//Constraint* FillList(ConstraintList, FormatSQL(SQL_GET_CONSTRAINT_NAME_LIST));
FillList(IndexList, FormatSQL(SQL_GET_INDEX_NAME_LIST));
FillList(ViewList, FormatSQL(SQL_GET_VIEW_NAME_LIST));
FillList(ProcedureList, FormatSQL(SQL_GET_PROCEDURE_NAME_LIST));
FillList(TriggerList, FormatSQL(SQL_GET_TRIGGER_NAME_LIST));
FillList(GeneratorList, FormatSQL(SQL_GET_GENERATOR_NAME_LIST));
FillList(ExceptionList, FormatSQL(SQL_GET_EXCEPTION_NAME_LIST));
FillList(FunctionList, FormatSQL(SQL_GET_FUNCTION_NAME_LIST));
FillList(FilterList, FormatSQL(SQL_GET_FILTER_NAME_LIST));
FillList(RoleList, FormatSQL(SQL_GET_ROLE_NAME_LIST));
FillList(ShadowList, FormatSQL(SQL_GET_SHADOW_NAME_LIST));
end;
TStringList(AllNameList).Sorted := True;
DRVQuery.Transaction.Commit;
end;
end;
procedure TibSHDatabase.CreateDatabase;
begin
if Assigned(DRVDatabase) then
begin
DRVDatabase.Database := ConnectPath;
DRVDatabase.SQLDialect := SQLDialect;
DRVDatabase.ClientLibrary := BTCLServer.ClientLibrary;
DRVDatabase.DBParams.Clear;
DRVDatabase.DBParams.Add(Format(FormatSQL(SQL_CREATE_DATABASE_PARAMS), [UserName, Password, PageSize, Charset]));
try
Screen.Cursor := crHourGlass;
DRVDatabase.CreateDatabase;
if DRVDatabase.Connected then
DRVDatabase.Disconnect;
finally
Screen.Cursor := crDefault;
end;
end;
end;
procedure TibSHDatabase.DropDatabase;
begin
if Assigned(DRVDatabase) then
begin
PrepareDRVDatabase;
if not DRVDatabase.Connected then DRVDatabase.Connect;
DRVDatabase.DropDatabase;
if DRVDatabase.Connected then DRVDatabase.Disconnect;
end;
end;
function TibSHDatabase.ExistsInDatabase(const AClassIID: TGUID; const ACaption: string): Boolean;
var
SQL: string;
begin
Result := False;
if IsEqualGUID(AClassIID, IibSHDomain) then SQL := FormatSQL(SQL_EXISTS_DOMAIN_NAME) else
if IsEqualGUID(AClassIID, IibSHTable) then SQL := FormatSQL(SQL_EXISTS_TABLE_NAME) else
//Constraint* if IsEqualGUID(AClassIID, IibSHConstraint) then SQL := FormatSQL(SQL_EXISTS_CONSTRAINT_NAME);
if IsEqualGUID(AClassIID, IibSHView) then SQL := FormatSQL(SQL_EXISTS_VIEW_NAME) else
if IsEqualGUID(AClassIID, IibSHProcedure) then SQL := FormatSQL(SQL_EXISTS_PROCEDURE_NAME) else
if IsEqualGUID(AClassIID, IibSHTrigger) then SQL := FormatSQL(SQL_EXISTS_TRIGGER_NAME) else
if IsEqualGUID(AClassIID, IibSHGenerator) then SQL := FormatSQL(SQL_EXISTS_GENERATOR_NAME) else
if IsEqualGUID(AClassIID, IibSHException) then SQL := FormatSQL(SQL_EXISTS_EXCEPTION_NAME) else
if IsEqualGUID(AClassIID, IibSHFunction) then SQL := FormatSQL(SQL_EXISTS_FUNCTION_NAME) else
if IsEqualGUID(AClassIID, IibSHFilter) then SQL := FormatSQL(SQL_EXISTS_FILTER_NAME) else
if IsEqualGUID(AClassIID, IibSHRole) then SQL := FormatSQL(SQL_EXISTS_ROLE_NAME) else
if IsEqualGUID(AClassIID, IibSHIndex) then SQL := FormatSQL(SQL_EXISTS_INDEX_NAME) else
if IsEqualGUID(AClassIID, IibSHShadow) then SQL := FormatSQL(SQL_EXISTS_SHADOW_NAME);
if DRVQuery.ExecSQL(FormatSQL(SQL), [ACaption], False) then
Result := DRVQuery.GetFieldIntValue(0) = 1;
DRVQuery.Transaction.Commit;
end;
function TibSHDatabase.ChangeNameList(const AClassIID: TGUID; const ACaption: string;
Operation: TOperation): Boolean;
procedure ChangeNameList(AStrings: TStrings);
var
I: Integer;
begin
case Operation of
opInsert:
begin
AStrings.Add(ACaption);
Result := True;
AllNameList.Add(ACaption);
end;
opRemove:
begin
I := AStrings.IndexOf(ACaption);
if I <> -1 then
begin
AStrings.Delete(I);
Result := True;
end;
I := AllNameList.IndexOf(ACaption);
if I <> -1 then AllNameList.Delete(I);
end;
end;
end;
begin
Result := False;
case Operation of
opInsert: if not ExistsInDatabase(AClassIID, ACaption) then Exit;
opRemove: if ExistsInDatabase(AClassIID, ACaption) then Exit;
end;
if not Result then
begin
if IsEqualGUID(AClassIID, IibSHDomain) then ChangeNameList(DomainList)
else
if IsEqualGUID(AClassIID, IibSHTable) then ChangeNameList(TableList)
else
//Constraint* if not Result and IsEqualGUID(AClassIID, IibSHConstraint) then ChangeNameList(ConstraintList);
if IsEqualGUID(AClassIID, IibSHView) then ChangeNameList(ViewList)
else
if IsEqualGUID(AClassIID, IibSHProcedure) then ChangeNameList(ProcedureList)
else
if IsEqualGUID(AClassIID, IibSHTrigger) then ChangeNameList(TriggerList)
else
if IsEqualGUID(AClassIID, IibSHGenerator) then ChangeNameList(GeneratorList)
else
if IsEqualGUID(AClassIID, IibSHException) then ChangeNameList(ExceptionList)
else
if IsEqualGUID(AClassIID, IibSHFunction) then ChangeNameList(FunctionList)
else
if IsEqualGUID(AClassIID, IibSHFilter) then ChangeNameList(FilterList)
else
if IsEqualGUID(AClassIID, IibSHRole) then ChangeNameList(RoleList)
else
if IsEqualGUID(AClassIID, IibSHIndex) then ChangeNameList(IndexList)
else
if IsEqualGUID(AClassIID, IibSHShadow) then ChangeNameList(ShadowList);
end;
if Result then
Result := Designer.SynchronizeConnection(Self, AClassIID, ACaption, Operation);
end;
procedure TibSHDatabase.OnLostConnect(Sender: TObject);
begin
if not FWasLostConnect then FWasLostConnect := True;
if FWasLostConnect and not StillConnect then
begin
try
Designer.RestoreConnection(Self);
if Assigned(DRVDatabase) then DRVDatabase.ClearCache;
finally
FWasLostConnect := False;
end;
end;
end;
function TibSHDatabase.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if IsEqualGUID(IID, IibSHDatabaseAliasOptionsInt) then
begin
if Supports(FDatabaseAliasOptionsInt, IibSHDatabaseAliasOptionsInt, Obj) then
Result := S_OK
else
Result := E_NOINTERFACE;
end else
Result := inherited QueryInterface(IID, Obj);
end;
function TibSHDatabase.GetBranchIID: TGUID;
begin
Result := inherited GetBranchIID;
if Assigned(BTCLServer) then Result := BTCLServer.BranchIID;
end;
procedure TibSHDatabase.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Assigned(BTCLServer) and AComponent.IsImplementorOf(BTCLServer) then
BTCLServer := nil;
end;
procedure TibSHDatabase.DoOnApplyOptions;
var
Options: IibSHDatabaseOptions;
begin
Options := nil;
if IsEqualGUID(BranchIID, IibSHBranch) then
Supports(Designer.GetOptions(IibSHDatabaseOptions), IibSHDatabaseOptions, Options)
else
if IsEqualGUID(BranchIID, IfbSHBranch) then
Supports(Designer.GetOptions(IfbSHDatabaseOptions), IibSHDatabaseOptions, Options);
if Assigned(Options) then
begin
Charset := Options.Charset;
CapitalizeNames := Options.CapitalizeNames;
end;
Options := nil;
end;
function TibSHDatabase.GetBTCLServer: IibSHServer;
begin
Result := FBTCLServer;
end;
procedure TibSHDatabase.SetBTCLServer(const Value: IibSHServer);
begin
if FBTCLServer <> Value then
begin
ReferenceInterface(FBTCLServer, opRemove);
FBTCLServer := Value;
ReferenceInterface(FBTCLServer, opInsert);
if Assigned(FBTCLServer) then
begin
Server := Format('%s %s ', [FBTCLServer.Caption, FBTCLServer.CaptionExt]);
UserName := FBTCLServer.UserName;
Password := FBTCLServer.Password;
Role := FBTCLServer.Role;
LoginPrompt := FBTCLServer.LoginPrompt;
if AnsiSameText(BTCLServer.Version, SInterBase4x) or
AnsiSameText(BTCLServer.Version, SInterBase5x) then
begin
if not CanShowProperty('PageSize') then MakePropertyInvisible('CapitalizeNames');
CapitalizeNames := True;
SQLDialect := 1;
end else
begin
if not CanShowProperty('PageSize') then MakePropertyVisible('CapitalizeNames');
CapitalizeNames := True;
end;
end;
end;
end;
function TibSHDatabase.GetDRVDatabase: IibSHDRVDatabase;
begin
Result := nil;
if Assigned(BTCLServer) then
begin
if not BTCLServer.LongMetadataNames then
Supports(FDRVDatabase, IibSHDRVDatabase, Result)
else
Supports(FDRVDatabase2, IibSHDRVDatabase, Result);
end;
end;
function TibSHDatabase.GetDRVTransaction: IibSHDRVTransaction;
begin
Result := nil;
if Assigned(BTCLServer) then
begin
if not BTCLServer.LongMetadataNames then
Supports(FDRVTransaction, IibSHDRVTransaction, Result)
else
Supports(FDRVTransaction2, IibSHDRVTransaction, Result);
end;
end;
function TibSHDatabase.GetDRVQuery: IibSHDRVQuery;
begin
Result := nil;
if Assigned(BTCLServer) then
begin
if not BTCLServer.LongMetadataNames then
Supports(FDRVQuery, IibSHDRVQuery, Result)
else
Supports(FDRVQuery2, IibSHDRVQuery, Result);
end;
end;
function TibSHDatabase.GetServer: string;
begin
if Assigned(BTCLServer) then
Result := Format('%s (%s) ', [BTCLServer.Caption, BTCLServer.CaptionExt]);
end;
procedure TibSHDatabase.SetServer(Value: string);
begin
FServer := Value;
end;
function TibSHDatabase.GetDatabase: string;
begin
Result := FDatabase;
end;
procedure TibSHDatabase.SetDatabase(Value: string);
var
DefaultExt: string;
begin
FDatabase := Value;
if Length(Alias) = 0 then
begin
if not Designer.Loading then
begin
Alias := ExtractFileName(AnsiReplaceText(FDatabase, '/', '\'));
if Pos('.', Alias) <> 0 then Alias := Copy(Alias, 1, Pos('.', Alias) - 1);
end;
if CanShowProperty('PageSize') then
begin
if Length(ExtractFileExt(FDatabase)) = 0 then
begin
DefaultExt := 'gdb';
if Assigned(BTCLServer) then
begin
if AnsiSameText(BTCLServer.Version, SInterBase70) or
AnsiSameText(BTCLServer.Version, SInterBase71) or
AnsiSameText(BTCLServer.Version, SInterBase75) then DefaultExt := 'ib';
if AnsiSameText(BTCLServer.Version, SFirebird15) or
AnsiSameText(BTCLServer.Version, SFirebird20) then DefaultExt := 'fdb';
end;
FDatabase := Format('%s.%s', [FDatabase, DefaultExt]);
end;
end;
end;
end;
function TibSHDatabase.GetAlias: string;
begin
Result := FAlias;
end;
procedure TibSHDatabase.SetAlias(Value: string);
begin
FAlias := Value;
end;
function TibSHDatabase.GetPageSize: string;
begin
Result := FPageSize;
end;
procedure TibSHDatabase.SetPageSize(Value: string);
begin
FPageSize := Value;
end;
function TibSHDatabase.GetCharset: string;
begin
Result := FCharset;
end;
procedure TibSHDatabase.SetCharset(Value: string);
begin
FCharset := Value;
end;
function TibSHDatabase.GetSQLDialect: Integer;
begin
Result := FSQLDialect;
end;
procedure TibSHDatabase.SetSQLDialect(Value: Integer);
begin
FSQLDialect := Value;
if FSQLDialect = 1 then CapitalizeNames := True;
end;
function TibSHDatabase.GetCapitalizeNames: Boolean;
begin
Result := FCapitalizeNames;
end;
procedure TibSHDatabase.SetCapitalizeNames(Value: Boolean);
begin
FCapitalizeNames := Value;
end;
function TibSHDatabase.GetAdditionalConnectParams: TStrings;
begin
Result := FAdditionalConnectParams;
end;
procedure TibSHDatabase.SetAdditionalConnectParams(Value: TStrings);
begin
FAdditionalConnectParams.Assign(Value);
end;
function TibSHDatabase.GetUserName: string;
begin
Result := FUserName;
end;
procedure TibSHDatabase.SetUserName(Value: string);
begin
FUserName := Value;
end;
function TibSHDatabase.GetPassword: string;
begin
Result := FPassword;
end;
procedure TibSHDatabase.SetPassword(Value: string);
begin
FPassword := Value;
end;
function TibSHDatabase.GetRole: string;
begin
Result := FRole;
end;
procedure TibSHDatabase.SetRole(Value: string);
begin
FRole := Value;
end;
function TibSHDatabase.GetLoginPrompt: Boolean;
begin
Result := FLoginPrompt;
end;
procedure TibSHDatabase.SetLoginPrompt(Value: Boolean);
begin
FLoginPrompt := Value;
end;
function TibSHDatabase.GetDescription: string;
begin
Result := FDescription;
end;
procedure TibSHDatabase.SetDescription(Value: string);
begin
FDescription := Value;
end;
function TibSHDatabase.GetConnectPath: string;
begin
Result := EmptyStr;
if Assigned(BTCLServer) then
begin
if AnsiSameText(BTCLServer.Protocol, STCPIP) then
Result := Format('%s%s', [BTCLServer.ConnectPath, Database]);
if AnsiSameText(BTCLServer.Protocol, SNamedPipe) then
Result := Format('%s%s',[BTCLServer.ConnectPath, Database]);
if AnsiSameText(BTCLServer.Protocol, SSPX) then
Result := Format('%s%s',[BTCLServer.ConnectPath, Database]);
if AnsiSameText(BTCLServer.Protocol, SLocal) then
Result := Format('%s',[Database]);
end;
end;
function TibSHDatabase.GetStillConnect: Boolean;
begin
Result := FStillConnect;
end;
procedure TibSHDatabase.SetStillConnect(Value: Boolean);
begin
FStillConnect := Value;
end;
function TibSHDatabase.GetDirectoryIID: string;
begin
Result := FDirectoryIID;
end;
procedure TibSHDatabase.SetDirectoryIID(Value: string);
begin
FDirectoryIID := Value;
end;
function TibSHDatabase.GetDatabaseAliasOptions: IibSHDatabaseAliasOptions;
begin
Supports(DatabaseAliasOptions, IibSHDatabaseAliasOptions, Result);
end;
function TibSHDatabase.GetExistsPrecision: Boolean;
begin
Result := FExistsPrecision;
end;
function TibSHDatabase.GetDBCharset: string;
begin
Result := FDBCharset;
end;
function TibSHDatabase.GetWasLostConnect: Boolean;
begin
Result := FWasLostConnect;
end;
function TibSHDatabase.GetCaption: string;
begin
Result := Alias;
end;
function TibSHDatabase.GetCaptionExt: string;
begin
if Connected then
Result := Format('Dialect %d, %s, %s', [SQLDialect, DBCharset, Database])
else
Result := Format('%s', [Database])
end;
procedure TibSHDatabase.SetOwnerIID(Value: TGUID);
var
I: Integer;
ibBTServerIntf: IibSHServer;
begin
if not IsEqualGUID(OwnerIID, Value) then
begin
BTCLServer := nil;
for I := 0 to Pred(Designer.Components.Count) do
if Supports(Designer.Components[I], IibSHServer, ibBTServerIntf) and
IsEqualGUID(ibBTServerIntf.InstanceIID, Value) then
begin
BTCLServer := ibBTServerIntf;
DoOnApplyOptions;
Break;
end;
inherited SetOwnerIID(Value);
end;
end;
function TibSHDatabase.GetConnected: Boolean;
begin
Result := Assigned(DRVDatabase) and DRVDatabase.Connected;
end;
function TibSHDatabase.GetCanConnect: Boolean;
begin
Result := not Connected;
end;
function TibSHDatabase.GetCanReconnect: Boolean;
begin
Result := Connected;
end;
function TibSHDatabase.GetCanDisconnect: Boolean;
begin
Result := Connected;
end;
function TibSHDatabase.GetCanShowRegistrationInfo: Boolean;
begin
Result := True;
end;
function TibSHDatabase.Connect: Boolean;
begin
Result := CanConnect;
if Result and Assigned(BTCLServer) and Assigned(DRVDatabase) then
begin
PrepareDRVDatabase;
DRVDatabase.Connect;
Result := DRVDatabase.Connected;
if Result then
begin
PrepareDBObjectLists;
MakePropertyVisible('DBCharset');
MakePropertyVisible('SQLDialect');
end else
Designer.ShowMsg(Format(SDatabaseConnectNO, [Self.ConnectPath, DRVDatabase.ErrorText]), mtWarning);
end else
begin
if not Assigned(DRVDatabase) then
Designer.ShowMsg(Format(SDatabaseConnectNO, [Self.ConnectPath, SDriverIsNotInstalled]), mtWarning);
end;
end;
function TibSHDatabase.Reconnect: Boolean;
begin
Result := CanReconnect;
if Result then Result := Assigned(DRVDatabase) and DRVDatabase.Reconnect;
end;
function TibSHDatabase.Disconnect: Boolean;
begin
Result := CanDisconnect;
if Result and Assigned(DRVDatabase) then
begin
DRVDatabase.Disconnect;
FExistsPrecision := False;
MakePropertyInvisible('DBCharset');
MakePropertyInvisible('SQLDialect');
end;
Result := not Connected;
end;
procedure TibSHDatabase.Refresh;
begin
PrepareDBObjectLists;
end;
function TibSHDatabase.ShowRegistrationInfo: Boolean;
var
OldDataRootDirectory: string;
begin
Result := False;
OldDataRootDirectory := GetDataRootDirectory;
Self.Tag := 4;
try
if IsPositiveResult(Designer.ShowModal(Self, SCallRegister)) then
begin
if not AnsiSameText(OldDataRootDirectory, GetDataRootDirectory) then
RenameDirectory(OldDataRootDirectory, GetDataRootDirectory);
Designer.SaveRegisteredConnectionInfo;
Result := True;
end;
finally
Self.Tag := 0;
end;
end;
procedure TibSHDatabase.IDELoadFromFileNotify;
begin
CreateDirectory(GetDataRootDirectory);
end;
function TibSHDatabase.GetSchemeClassIIDList(WithSystem: Boolean = False): TStrings;
var
Index: Integer;
SFmt: string;
begin
Index := 1;
SFmt := '%s|%s';
ClassIIDList.Clear;
if WithSystem then
begin
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHSystemTable), GUIDToName(IibSHSystemTable, Index)]));
if Assigned(BTCLServer) and
AnsiSameText(BTCLServer.Version, SInterBase70) or
AnsiSameText(BTCLServer.Version, SInterBase71) or
AnsiSameText(BTCLServer.Version, SInterBase75) then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHSystemTableTmp), GUIDToName(IibSHSystemTableTmp, Index)]));
end else
begin
if DatabaseAliasOptions.Navigator.ShowDomains then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHDomain), GUIDToName(IibSHDomain, Index)]));
if DatabaseAliasOptions.Navigator.ShowTables then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHTable), GUIDToName(IibSHTable, Index)]));
//Constraint* if DatabaseAliasOptions.Navigator.ShowConstraints then
//Constraint* ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHConstraint), GUIDToName(IibSHConstraint, Index)]));
if DatabaseAliasOptions.Navigator.ShowViews then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHView), GUIDToName(IibSHView, Index)]));
if DatabaseAliasOptions.Navigator.ShowProcedures then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHProcedure), GUIDToName(IibSHProcedure, Index)]));
if DatabaseAliasOptions.Navigator.ShowTriggers then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHTrigger), GUIDToName(IibSHTrigger, Index)]));
if DatabaseAliasOptions.Navigator.ShowGenerators then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHGenerator), GUIDToName(IibSHGenerator, Index)]));
if DatabaseAliasOptions.Navigator.ShowExceptions then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHException), GUIDToName(IibSHException, Index)]));
if DatabaseAliasOptions.Navigator.ShowFunctions then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHFunction), GUIDToName(IibSHFunction, Index)]));
if DatabaseAliasOptions.Navigator.ShowFilters then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHFilter), GUIDToName(IibSHFilter, Index)]));
if DatabaseAliasOptions.Navigator.ShowRoles and Assigned(BTCLServer) and not AnsiSameText(BTCLServer.Version, SInterBase4x) then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHRole), GUIDToName(IibSHRole, Index)]));
if DatabaseAliasOptions.Navigator.ShowIndices then
ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHIndex), GUIDToName(IibSHIndex, Index)]));
// if DatabaseAliasOptions.Navigator.ShowShadows then
// ClassIIDList.Add(Format(SFmt, [GUIDToString(IibSHShadow), GUIDToName(IibSHShadow, Index)]));
end;
Result := ClassIIDList;
end;
function TibSHDatabase.GetSchemeClassIIDList(const AObjectName: string): TStrings;
begin
ClassIIDList2.Clear;
if DomainList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHDomain)) else
if SystemDomainList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHSystemDomain)) else
if TableList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHTable)) else
//Constraint* if ConstraintList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHConstraint));
if ViewList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHView)) else
if ProcedureList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHProcedure)) else
if TriggerList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHTrigger)) else
if GeneratorList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHGenerator)) else
if ExceptionList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHException)) else
if FunctionList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHFunction)) else
if FilterList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHFilter)) else
if RoleList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHRole)) else
if SystemTableList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHSystemTable)) else
if IndexList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHIndex)) else
if ShadowList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHShadow)) else
if SystemTableTmpList.IndexOf(AObjectName) <> -1 then ClassIIDList2.Add(GUIDToString(IibSHSystemTableTmp));
Result := ClassIIDList2;
end;
function TibSHDatabase.GetObjectNameList: TStrings;
begin
Result := AllNameList;
end;
function TibSHDatabase.GetObjectNameList(const AClassIID: TGUID): TStrings;
begin
Result := nil;
if IsEqualGUID(AClassIID, IibSHProcedure) then Result := ProcedureList else
if IsEqualGUID(AClassIID, IibSHTable) then Result := TableList else
if IsEqualGUID(AClassIID, IibSHView) then Result := ViewList else
if IsEqualGUID(AClassIID, IibSHDomain) then Result := DomainList else
if IsEqualGUID(AClassIID, IibSHSystemDomain) then Result := SystemDomainList else
if IsEqualGUID(AClassIID, IibSHFunction) then Result := FunctionList else
if IsEqualGUID(AClassIID, IibSHFilter) then Result := FilterList else
if IsEqualGUID(AClassIID, IibSHException) then Result := ExceptionList else
//Constraint* if IsEqualGUID(AClassIID, IibSHConstraint) then Result := ConstraintList;
if IsEqualGUID(AClassIID, IibSHGenerator) then Result := GeneratorList else
if IsEqualGUID(AClassIID, IibSHSystemTable) then Result := SystemTableList else
if IsEqualGUID(AClassIID, IibSHTrigger) then Result := TriggerList else
if IsEqualGUID(AClassIID, IibSHRole) then Result := RoleList else
if IsEqualGUID(AClassIID, IibSHIndex) then Result := IndexList else
if IsEqualGUID(AClassIID, IibSHSystemTableTmp) then Result := SystemTableTmpList else
if IsEqualGUID(AClassIID, IibSHShadow) then Result := ShadowList;
end;
function TibSHDatabase.GetCanTestConnection: Boolean;
begin
Result := not CanShowProperty('PageSize') and Assigned(BTCLServer) and
(Length(Database) > 0) and not Connected;
end;
function TibSHDatabase.TestConnection: Boolean;
var
Msg: string;
MsgType: TMsgDlgType;
begin
Result := GetCanTestConnection;
if Result then
begin
try
Screen.Cursor := crHourGlass;
PrepareDRVDatabase;
try
Result := Assigned(DRVDatabase) and DRVDatabase.TestConnection;
except
Result := False;
end;
finally
Screen.Cursor := crDefault;
end;
if Result then
begin
Msg := Format(SDatabaseTestConnectionOK, [Self.ConnectPath]);
MsgType := mtInformation;
end else
begin
if Assigned(DRVDatabase) then
Msg := Format(SDatabaseTestConnectionNO, [Self.ConnectPath, DRVDatabase.ErrorText])
else
Msg := Format(SDatabaseTestConnectionNO, [Self.ConnectPath, SDriverIsNotInstalled]);
MsgType := mtWarning;
end;
Designer.ShowMsg(Msg, MsgType);
end;
end;
function TibSHDatabase.GetDataRootDirectory: string;
begin
if Assigned(BTCLServer) then
Result := IncludeTrailingPathDelimiter(Format('%s\Databases\%s.%s', [BTCLServer.DataRootDirectory, Alias, DirectoryIID]));
end;
function TibSHDatabase.CreateDirectory(const FileName: string): Boolean;
begin
Result := not SysUtils.DirectoryExists(FileName) and ForceDirectories(FileName);
end;
function TibSHDatabase.RenameDirectory(const OldName, NewName: string): Boolean;
begin
Result := SysUtils.DirectoryExists(OldName) and RenameFile(OldName, NewName);
end;
function TibSHDatabase.DeleteDirectory(const FileName: string): Boolean;
begin
Alias := Format('#.Unregistered.%s', [Alias]);
Result := RenameDirectory(FileName, GetDataRootDirectory);
end;
function TibSHDatabase.GetFavoriteObjectNames: TStrings;
begin
Result := DatabaseAliasOptions.Navigator.FavoriteObjectNames;
end;
function TibSHDatabase.GetFavoriteObjectColor: TColor;
begin
Result := DatabaseAliasOptions.Navigator.FavoriteObjectColor;
end;
function TibSHDatabase.GetFilterList: TStrings;
begin
Result := DatabaseAliasOptionsInt.FilterList;
end;
function TibSHDatabase.GetFilterIndex: Integer;
begin
Result := DatabaseAliasOptionsInt.FilterIndex;
end;
procedure TibSHDatabase.SetFilterIndex(Value: Integer);
begin
DatabaseAliasOptionsInt.FilterIndex := Value;
end;
//IibBTDataBaseExt
procedure TibSHDatabase.GetObjectsHaveComment(ClassObject: TGUID;
Results: TStrings);
var
SQLText:string;
FieldReturns:integer;
begin
FieldReturns:=1;
if Results=nil then
Exit;
SQLText:='';
if IsEqualGUID(ClassObject,IibSHDomain) then
SQLText:=SQL_GET_DOMAINS_WITH_COMMENTS
else
if IsEqualGUID(ClassObject,IibSHField) then
begin
SQLText:=SQL_GET_FIELDS_WITH_COMMENTS;
FieldReturns:=2
end
else
if IsEqualGUID(ClassObject,IibSHTable) then
SQLText:=SQL_GET_TABLES_WITH_COMMENTS
else
if IsEqualGUID(ClassObject,IibSHView) then
SQLText:=SQL_GET_VIEWS_WITH_COMMENTS
else
if IsEqualGUID(ClassObject,IibSHTrigger) then
SQLText:=SQL_GET_TRIGGERS_WITH_COMMENTS
else
if IsEqualGUID(ClassObject,IibSHProcedure) then
SQLText:=SQL_GET_PROCEDURES_WITH_COMMENTS
else
if IsEqualGUID(ClassObject,IibSHFunction) then
SQLText:=SQL_GET_FUNCTIONS_WITH_COMMENTS
else
if IsEqualGUID(ClassObject,IibSHException) then
SQLText:=SQL_GET_EXCEPTIONS_WITH_COMMENTS
else
if IsEqualGUID(ClassObject,IibSHProcParam) then
begin
SQLText:=SQL_GET_PROCPARAMS_WITH_COMMENTS;
FieldReturns:=2
end ;
Results.Clear;
if Length(SQLText)=0 then
Exit;
if DRVQuery.ExecSQL(SQLText, [], False) then
while not DRVQuery.Eof do
begin
case FieldReturns of
1: Results.Add(DRVQuery.GetFieldStrValue(0));
2: Results.Add(DRVQuery.GetFieldStrValue(0)+'#BT#'+DRVQuery.GetFieldStrValue(1));
end;
DRVQuery.Next;
end;
end;
function TibSHDatabase.GetExistsProcParamDomains: Boolean;
begin
Result := FExistsProcParamDomains;
end;
{ TfibSHDatabaseOptions }
function TfibSHDatabaseOptions.GetParentCategory: string;
begin
if Supports(Self, IibSHBranch) then Result := Format('%s', [SibOptionsCategory]);
if Supports(Self, IfbSHBranch) then Result := Format('%s', [SfbOptionsCategory]);
end;
function TfibSHDatabaseOptions.GetCategory: string;
begin
Result := Format('%s', [SDatabaseOptionsCategory]);
end;
procedure TfibSHDatabaseOptions.RestoreDefaults;
begin
Charset := CharsetsAndCollatesFB10[0, 0];
CapitalizeNames := True;
end;
function TfibSHDatabaseOptions.GetCharset: string;
begin
Result := Charset;
end;
procedure TfibSHDatabaseOptions.SetCharset(Value: string);
begin
Charset := Value;
end;
function TfibSHDatabaseOptions.GetCapitalizeNames: Boolean;
begin
Result := CapitalizeNames;
end;
procedure TfibSHDatabaseOptions.SetCapitalizeNames(Value: Boolean);
begin
CapitalizeNames := Value;
end;
end.
|
unit CrudExampleHorseServer.Model.DAO.Cadastro;
interface
uses
System.JSON
, SimpleInterface
, CrudExampleHorseServer.Model.Entidade.Cadastro
, Data.DB
, CrudExampleHorseServer.Model.Conexao.DB
;
type
IDAOCadastro = interface
['{A2BF087C-8466-4413-94D0-56B2ECC25217}']
function Find: TJsonArray; overload;
function Find( const aID: string ): TJSONObject; overload;
function Insert( const aJSONParams: TJSONObject ): TJSONObject;
function Update( const aJSONParams: TJSONObject ): TJSONObject;
function Delete( const aID: string ): TJSONObject;
end;
TDAOCadastro = class(TInterfacedObject, IDAOCadastro)
private
{ private declarations }
FDataSourceInternal: TDataSource;
FDAOCadastro: iSimpleDAO<TCADASTRO>;
FConexaoDB: IModelConexaoDB;
protected
{ protected declarations }
public
{ public declarations }
class function New( const aConexaoDB: IModelConexaoDB ): IDAOCadastro;
constructor Create( const aConexaoDB: IModelConexaoDB );
destructor Destroy; override;
function Find: TJsonArray; overload;
function Find( const aID: string ): TJSONObject; overload;
function Insert( const aJSONParams: TJSONObject ): TJSONObject;
function Update( const aJSONParams: TJSONObject ): TJSONObject;
function Delete( const aID: string ): TJSONObject;
end;
implementation
uses
SimpleDAO
, DataSetConverter4D
, DataSetConverter4D.Util
, DataSetConverter4D.Helper
, DataSetConverter4D.Impl
, Rest.Json
, System.SysUtils
, MyJSONObjectHelper
;
constructor TDAOCadastro.Create( const aConexaoDB: IModelConexaoDB );
begin
FDataSourceInternal:=TDataSource.Create(Nil);
FConexaoDB :=aConexaoDB;
FDAOCadastro := TSimpleDAO<TCADASTRO>
.New( TMySimpleQuery.New( FConexaoDB ).SimpleQueryFireDac )
.DataSource( FDataSourceInternal );
end;
destructor TDAOCadastro.Destroy;
begin
if Assigned(FDataSourceInternal) then
FreeAndNil(FDataSourceInternal);
inherited;
end;
function TDAOCadastro.Find: TJsonArray;
begin
FDAOCadastro.SQL.OrderBy('Name').&End.Find;
if FDataSourceInternal.DataSet.IsEmpty then
begin
Result:=TJSONArray.Create;
Result.AddElement( TJSONObject.Create )
end
else
Result:=TMyJSONObjectFunctions.AsLowerCasePath( FDataSourceInternal.DataSet.AsJSONArray );
end;
function TDAOCadastro.Find(const aID: string): TJSONObject;
begin
FDAOCadastro.Find( aID.ToInteger );
if FDataSourceInternal.DataSet.IsEmpty then
Result:=TJSONObject.Create
else
Result:=TMyJSONObjectFunctions.AsLowerCasePath( FDataSourceInternal.DataSet.AsJSONObject );
end;
function TDAOCadastro.Insert(const aJSONParams: TJSONObject): TJSONObject;
var
lCadastro: TCADASTRO;
begin
lCadastro:=TCADASTRO.Create;
try
lCadastro:=TJson.JsonToObject<TCADASTRO>( TMyJSONObjectFunctions.AsUpperCasePath( aJSONParams ) );
lCadastro.ID:=FConexaoDB.GetNextID('ID_CADASTRO');
FDAOCadastro.Insert( lCadastro );
Result:=TMyJSONObjectFunctions.AsLowerCasePath( Self.Find( lCadastro.ID.ToString ) );
finally
FreeAndNil(lCadastro);
end;
end;
function TDAOCadastro.Update( const aJSONParams: TJSONObject ): TJSONObject;
var
lCadastro: TCADASTRO;
begin
lCadastro:=TCADASTRO.Create;
try
lCadastro:=TJson.JsonToObject<TCADASTRO>( TMyJSONObjectFunctions.AsUpperCasePath( aJSONParams ) );
FDAOCadastro.Update( lCadastro );
Result:=TMyJSONObjectFunctions.AsLowerCasePath( Self.Find( lCadastro.ID.ToString ) );
finally
FreeAndNil(lCadastro);
end;
end;
function TDAOCadastro.Delete(const aID: string): TJSONObject;
var
lCadastro: TCADASTRO;
begin
lCadastro:=TCADASTRO.Create;
try
lCadastro.ID:=aID.ToInteger;
FDAOCadastro.Delete(lCadastro);
Result:=TJSONObject.Create;
finally
FreeAndNil(lCadastro);
end;
end;
class function TDAOCadastro.New( const aConexaoDB: IModelConexaoDB ): IDAOCadastro;
begin
Result := Self.Create( aConexaoDB );
end;
end.
|
unit Ils.Files.Pnt;
interface
uses
System.Classes, IniFiles, SysUtils, Math, JsonDataObjects,
Ils.Json.Names, Ils.Json.Utils, Generics.Collections, Windows,
Ils.Utils;
const
CFilePosIniFileName = '';
CRenamedFileName = '';
CPntFileName = '';
type
TJsonMessageType = (mtUnknown, mtGeo, mtJpeg);
TPntPoint = packed record
DeviceID: Longword;
SatelitesCount: Byte;
ProviderID: Smallint;
DeviceType: Byte;
DateTime: TDateTime;
Latitude: Single;
Longitude: Single;
Speed: Smallint; //км/ч
Azimuth: Byte; //градусы
Length: Integer; //м
FuelInEngine: Smallint; //топливо, поступившее в бак (не используется)
Fuel: Smallint; //топливо в баке (1/512 от объема бака) (не используется)
SingleLevelSensors: Byte;
MultiLevelSensors: array[1..20] of Integer;
QueryID: Byte; // не используется
m_iDriverID: array[0..5] of Byte; // не используется
private
// function GetJsonMessageType(aJson: TJsonObject): TJsonMessageType;
// function GetJsonJpegString(aJson: TJsonObject): string;
// function AsJsonStr: string;
public
constructor Create(AJson: TJsonObject; AJsonMappingStr: string; AImeiHash: TDictionary<string,integer>);
end;
TPntPointArray = TArray<TPntPoint>;
TPntFile = class
const
CFilePosIniFileName = 'R000000.ini';
CPntFileName = 'R000000.pnt';
CRenamedFileName = 'R000000.pntint';
CMultiSensorsCount = 20;
CSizeOfPntRecord = SizeOf(TPntPoint);
private
FPntFilePath: string;
FPntStream: TFileStream;
FLastRead: TDateTime;
FNewPos: Int64;
FSize: Int64;
FProgress: Double;
FStepTime: TDateTime;
FStepCount: Integer;
Fops: Double;
FConfifmed: Boolean;
public
function Get(const ACount: Integer; const AAutoReadConfirm: Boolean): TPntPointArray;
procedure Confirm;
constructor Create(const APntFilePath: string);
destructor Destroy; override;
end;
implementation
{ TPntFile }
constructor TPntFile.Create(const APntFilePath: string);
begin
FPntStream := nil;
FPntFilePath := IncludeTrailingPathDelimiter(APntFilePath);
FLastRead := Now;
FConfifmed := True;
end;
destructor TPntFile.Destroy;
begin
FPntStream.Free;
inherited;
end;
function TPntFile.Get(const ACount: Integer; const AAutoReadConfirm: Boolean): TPntPointArray;
var
FilePosIniFile: TIniFile;
function OpenFile: Boolean;
begin
if Assigned(FPntStream) then
Exit(True);
try
if FileExists(FPntFilePath + CRenamedFileName) then
begin
FPntStream := TFileStream.Create(FPntFilePath + CRenamedFileName, fmOpenRead);
FPntStream.Seek(StrToInt64Def(FilePosIniFile.ReadString('position', 'pos', '0'), 0), soFromBeginning);
end
else if FileExists(FPntFilePath + CPntFileName) and RenameFile(FPntFilePath + CPntFileName, FPntFilePath + CRenamedFileName) then
begin
FPntStream := TFileStream.Create(FPntFilePath + CRenamedFileName, fmOpenRead);
FilePosIniFile.WriteInteger('position', 'pos', 0);
end;
finally
end;
Result := Assigned(FPntStream);
end;
var
ReadSize: Integer;
begin
Result := nil;
FStepCount := ACount;
ReadSize := 0;
FilePosIniFile := TIniFile.Create(FPntFilePath + CFilePosIniFileName);
try
if not OpenFile() then
Exit;
SetLength(Result, ACount);
ReadSize := FPntStream.Read(Result[0], CSizeOfPntRecord * ACount);
if ReadSize < CSizeOfPntRecord * ACount then
begin
FreeAndNil(FPntStream);
DeleteFile(PWideChar(FPntFilePath + CRenamedFileName));
FilePosIniFile.WriteInteger('position', 'pos', 0);
FNewPos := 0;
FSize := 0;
end
else
begin
FNewPos := FPntStream.Position;
FSize := FPntStream.Size;
FilePosIniFile.WriteString('position', 'pos', IntToStr(FNewPos));
end;
FStepTime := Now - FLastRead;
FProgress := IfThen(FSize = 0, 0, FNewPos / FSize * 100);
FConfifmed := False;
if AAutoReadConfirm then
Confirm;
finally
SetLength(Result, ReadSize div CSizeOfPntRecord);
FilePosIniFile.Free;
end;
FLastRead := Now;
// if ReadSize mod CSizeOfPntRecord = 0 then
// for i := 0 to ReadSize div CSizeOfPntRecord - 1 do
// if PntPointToTrackPoint(PntPoints[i], TrackPoint) then
// FPoints.Add(TrackPoint);
//
// PntPoints := nil;
//
// Result := FPoints.Count > 0;
end;
procedure TPntFile.Confirm;
var
FilePosIniFile: TIniFile;
begin
if FConfifmed then
Exit;
FilePosIniFile := TIniFile.Create(FPntFilePath + CFilePosIniFileName);
try
FilePosIniFile.WriteString('position', 'steptime', FormatDateTime('hh:nn:ss.zzz', (FStepTime)));
FilePosIniFile.WriteInteger('position', 'stepsize', FStepCount);
FilePosIniFile.WriteInteger('position', 'points', FNewPos div 123);
FilePosIniFile.WriteString('position', 'progress', Format('%.2f', [FProgress]) + '%');
FilePosIniFile.WriteString('position', 'ops', Format('%.2f', [Fops]));
FilePosIniFile.WriteDateTime('position', 'lastupdated', Now);
FConfifmed := True;
finally
FilePosIniFile.Free
end;
end;
{ TPntPoint }
{
function TPntPoint.AsJsonStr: string;
var
JSONObj: TJsonObject;
i: Integer;
begin
JSONObj := TJsonObject.Create();
try
JSONObj.I['g'] := 2; // версия
JSONObj.I['t'] := 99;//APntPoint.DeviceType; // протокол
JSONObj.S['i'] := IntToStr(DeviceID); // IMEI
JSONObj.S['dt'] := FormatDateTime('yyyy"-"mm"-"dd" "hh":"nn":"ss"."zzz', DateTime); // время
// JSONObj.B['ew'] := (Var8 and $80) <> 0; // работает ли двигатель
// JSONObj.B['sv'] := (Var8 and $02) <> 0; // валидны ли координаты
JSONObj.I['sc'] := SatelitesCount;//Var8 shr 2; // количество спутников
JSONObj.F['la'] := Latitude;
JSONObj.F['lo'] := Longitude;
JSONObj.F['a'] := 0;
JSONObj.F['v'] := Speed; // дробное (*** округляем, ибо без этого - фигня ***)
JSONObj.I['d'] := Azimuth * 2; // азимут
JSONObj.O['s'].I[MakeSensorName(stBin8, 1)] := SingleLevelSensors and $FF;
// for i := 0 to 7 do
// AddSensor(JSONObj.A['s'], GetSensorName(snBin, i + 1), CSenType[smBin], ((SingleLevelSensors shr i) and 1));
for i := 1 to 20 do
JSONObj.O['s'].I[MakeSensorName(stAin, i)] := MultiLevelSensors[i];
Result := JSONObj.ToString;
finally
JSONObj.Free;
end;
end;
}
const
CJesonMappingDef =
'';
constructor TPntPoint.Create(AJson: TJsonObject; AJsonMappingStr: string; AImeiHash: TDictionary<string,integer>);
var
Mapping: TJsonObject;
i, j: Integer;
k: string;
v: string;
begin
Mapping := nil;
DeviceID := Longword(-1);
SatelitesCount := 0;
ProviderID := 0;
DeviceType := 0;
DateTime := 0;
Latitude := 0;
Longitude := 0;
Speed := 0; //км/ч
Azimuth := 0; //градусы
Length := 0; //м
FuelInEngine := 0; //топливо, поступившее в бак (не используется)
Fuel := 0; //топливо в баке (1/512 от объема бака) (не используется)
SingleLevelSensors := 0;
for j := 1 to 20 do
MultiLevelSensors[j] := 0;
if AJsonMappingStr <> '' then
try
Mapping := TJsonObject(TJsonObject.Parse(AJsonMappingStr));
except
end;
try
if Assigned(AImeiHash) and AImeiHash.ContainsKey(Trim(aJson.S['i'])) then
DeviceID := AImeiHash.Items[Trim(aJson.S['i'])]
else
DeviceID := aJson.I['i'];
SatelitesCount := aJson.I['sc'];
ProviderID := 0;
DeviceType := aJson.I['t'];
DateTime := IlsToDateTime(aJson.S['dt']);
Latitude := IfThen((aJson.F['la'] > 90) or (aJson.F['la'] < -90), 0, aJson.F['la']);
Longitude := IfThen((aJson.F['lo'] > 180) or (aJson.F['lo'] < -180), 0, aJson.F['lo']);;
Speed := Round(IfThen((aJson.F['v'] > MaxInt) or (aJson.F['v'] < Pred(-Maxint)), 9999, aJson.F['v'])); //км/ч
Azimuth := aJson.I['d']; //градусы
Length := Round(IfThen((aJson.F['l'] > MaxInt) or (aJson.F['l'] < Pred(-Maxint)), 9999, aJson.F['l']))*1000; //м
FuelInEngine := 0; //топливо, поступившее в бак (не используется)
Fuel := 0; //топливо в баке (1/512 от объема бака) (не используется)
SingleLevelSensors := 0;
case GetJsonVersion(AJson) of
1: begin
for i := 0 to aJson.A['s'].Count - 1 do
if aJson.A['s'].O[i].Contains('bin_1:8') then
begin
SingleLevelSensors := aJson.A['s'].O[i].I['bin_1:8'];
Break;
end;
for j := 3 to 20 do
for i := 0 to aJson.A['s'].Count - 1 do
if aJson.A['s'].O[i].Contains(MakeSensorName(stAin, j - 2)) then
begin
MultiLevelSensors[j] := aJson.A['s'].O[i].I[MakeSensorName(stAin, j - 2)];
Break;
end;
MultiLevelSensors[1] := aJson.I['vext'];
MultiLevelSensors[2] := aJson.I['vint'];
end;
2: begin
MultiLevelSensors[1] := aJson.O['s'].I[MakeSensorName(stVExt)];
MultiLevelSensors[2] := aJson.O['s'].I[MakeSensorName(stVInt)];
case AJson.I['t'] of
dtNovacom:begin
SingleLevelSensors := aJson.O['s'].I['nova_2:i'] shl 1;
MultiLevelSensors[1] := aJson.O['s'].I['nova_66:i'];
MultiLevelSensors[7] := aJson.O['s'].I['nova_72:i'];
end;
dtNavtelecom: begin
SingleLevelSensors := aJson.O['s'].I['bin_1:8'];
for j := 3 to 20 do
MultiLevelSensors[j] := aJson.O['s'].I[MakeSensorName(stAin, j - 2)];
MultiLevelSensors[7] := aJson.O['s'].I[MakeSensorName(stTemp, 1)];
MultiLevelSensors[13] := aJson.O['s'].I[MakeSensorName(stCANDistance)];
MultiLevelSensors[15] := aJson.O['s'].I[MakeSensorName(stCANFuelL)];
MultiLevelSensors[16] := aJson.O['s'].I[MakeSensorName(stCANRPM)];
MultiLevelSensors[19] := aJson.O['s'].I[MakeSensorName(stCANFuelP)];
end;
else begin
end;
end;
if Assigned(Mapping) then
begin
for i := 0 to Mapping.O[AJson.S['t']].Count - 1 do begin
k := Mapping.O[AJson.S['t']].Names[i];
v := Mapping.O[AJson.S['t']].Values[k];
try
case GetSensorMeasure(v) of
smFloat: MultiLevelSensors[StrToInt(k)] := Trunc(aJson.O['s'].F[v] * 1000);
else MultiLevelSensors[StrToInt(k)] := aJson.O['s'].I[v];
end;
except
end;
end;
end;
end;
end;
QueryID := 0; // не используется
m_iDriverID[0] := 0; // не используется
m_iDriverID[1] := 0;
m_iDriverID[2] := 0;
m_iDriverID[3] := 0;
m_iDriverID[4] := 0;
m_iDriverID[5] := 0;
finally
Mapping.Free;
end;
end;
//function TPntPoint.GetJsonJpegString(aJson: TJsonObject): string;
//begin
// Result := '';
// case GetJsonVersion(aJson) of
// 1:
// with aJson.A['s'] do
// if Count >= 1 then
// Result := (aJson.A['s'].O[0].S[MakeSensorName(stCamera)]);
//
// 2:
// with aJson.O['s'] do
// Result := (aJson.O['s'].S[MakeSensorName(stCamera)]);
// end;
//end;
//function TPntPoint.GetJsonMessageType(aJson: TJsonObject): TJsonMessageType;
//begin
// Result := mtGeo;
// if GetJsonJpegString(aJson) <> '' then
// Result := mtJpeg;
//end;
end.
|
{Program showing the Stack Data Structure - LIFO Last In First Out}
{ This is a stack of Integers }
Program Stack;
uses Crt;
{ constants }
Const
STACK_SIZE = 64;
{ variables }
Var
myStack : Array[1..STACK_SIZE] of Integer;
topPointer : Integer;
i, temp, n, fmr : Integer;
{ initialize stack }
Procedure InitStack;
Begin
topPointer := 0;
End;
{ check if stack is empty }
Function IsEmpty : Boolean;
Begin
IsEmpty := false;
If (topPointer = 0) then
IsEmpty := true;
End;
{ check if stack is full }
Function IsFull : Boolean;
Begin
IsFull := false;
If ((topPointer + 1) = STACK_SIZE) then
IsFull := true;
End;
{ Pop - remove an element from the stack, returns the removed element }
Function Pop : Integer;
Begin
Pop := 0;
If not IsEmpty then
Begin
Pop := myStack[topPointer];
topPointer:= topPointer -1;
End;
End;
{ push an element onto the stack }
Procedure Push(item :Integer);
Begin
If not IsFull then
Begin
myStack[topPointer+1] := item;
topPointer := topPointer + 1;
End;
End;
{ get the size of the stack }
Function GetSize : Integer;
Begin
GetSize := topPointer;
End;
{ main program }
Begin
ClrScr;
Writeln('Stack Data Structure');
Writeln('Enter number (n) to add to stack');
Readln(n);
Writeln('Enter n stack elements.');
For i := 1 To n Do
Begin
Readln(temp);
Push(temp);
End;
Writeln();
Writeln('Size of stack : ', GetSize);
Writeln();
Writeln('Erasing last element . . .');
Writeln();
fmr := Pop;
Writeln('Removing ', fmr);
Writeln('Stack without last element. ');
For i := 1 to GetSize Do
Writeln(myStack[i]);
Readln;
End.
|
unit Flix.Utils.Maps;
interface
uses
Classes, SysUtils,
TypInfo,
System.Generics.Collections,
VCL.TMSFNCMaps;
type
// just a shorter name...
TMapService = TTMSFNCMapsService;
// maps a service to its API key
TServiceAPIKeyDict = TDictionary<TMapService, string>;
// maps a service to its name
TDictNames = TDictionary<TMapService, string>;
// maps a name to a service
TDictServices = TDictionary<string, TMapService>;
// manages API keys,
// allows saving and loading to a file
TServiceAPIKeys = class
private
FDict : TServiceAPIKeyDict;
FNames: TDictNames;
FServices: TDictServices;
FFilename: String;
// service key that was retrieved last
FLastService: TMapService;
// initialize service name dictionaries
procedure InitServiceNames;
public
constructor Create;
destructor Destroy; override;
// add an API key for a service
procedure AddKey( const AService: TMapService;
const AKey: String);
// get an API key for a service
function GetKey( const AService: TMapService ): string;
// returns all services as a generic array
function GetAllServices : TArray<TMapService>;
// returns all service names as a generic array
function GetAllNames : TArray<string>;
// adds all services to generic list
procedure GetServices( AList: TList<TMapService> );
// returns the name for a service
function GetNameForService( AService: TMapService ) :String;
// returns the service for a name
function GetServiceForName( AName: String ) : TMapService;
// save services and keys to a config file
procedure SaveToFile( const AFilename: String );
// load services and keys from a config file
procedure LoadFromFile( const AFilename: String );
published
// filename that was used to load or save
property Filename: String read FFilename write FFilename;
// service that a key for was returned last
property LastService: TMapService read FLastService write FLastService;
end;
implementation
uses
AesObj, MiscObj;
const
// part of this key will be used to encrypt the config file
KEY = 'Z$)5^*lQ)YE47]>8{w-kuv746wRLMJiBsPJk5dB=!cjB~)c6M4H:N]X]sZT0+Cfl';
// header for the file created by SaveToFile
HEADER : TBytes = [ 64, 80, 73, 1];
{ TServiceAPIKeys }
procedure TServiceAPIKeys.AddKey(const AService: TMapService; const AKey: String);
begin
FDict.Add(AService, AKey);
end;
constructor TServiceAPIKeys.Create;
begin
inherited;
FDict := TServiceAPIKeyDict.Create;
FNames := TDictNames.Create;
FServices := TDictServices.Create;
InitServiceNames;
end;
destructor TServiceAPIKeys.Destroy;
begin
FDict.Free;
FNames.Free;
FServices.Free;
inherited;
end;
function TServiceAPIKeys.GetAllNames: TArray<string>;
begin
Result := FNames.Values.ToArray;
end;
function TServiceAPIKeys.GetAllServices: TArray<TMapService>;
begin
Result := FNames.Keys.ToArray;
end;
function TServiceAPIKeys.GetKey(const AService: TMapService): string;
begin
FLastService := AService;
Result := FDict[ AService ];
end;
function TServiceAPIKeys.GetNameForService(AService: TMapService): String;
begin
Result := FNames[AService];
end;
function TServiceAPIKeys.GetServiceForName(AName: String): TMapService;
begin
Result := FServices[AName];
end;
procedure TServiceAPIKeys.GetServices(AList: TList<TMapService>);
var
LService: TMapService;
begin
if Assigned( AList ) then
begin
AList.Clear;
for LService in FDict.Keys do
begin
AList.Add( LService );
end;
end
else
raise EArgumentNilException.Create('AList cannot be nil.');
end;
procedure TServiceAPIKeys.InitServiceNames;
var
LService: TMapService;
LName: String;
begin
FNames.Clear;
FNames.Add(msGoogleMaps, 'Google Maps');
FNames.Add(msHere, 'Here');
FNames.Add(msAzureMaps, 'Microsoft Azure Maps');
FNames.Add(msBingMaps, 'Microsoft Bing Maps');
FNames.Add(msTomTom, 'TomTom');
FNames.Add(msMapBox, 'MapBox');
// OpenLayers does not have a key right now
// and might be omitted
FNames.Add(msOpenLayers, 'OpenLayers');
// generate other dictionary for
// service lookup by name
for LService in FNames.Keys do
begin
LName:= FNames[LService];
FServices.Add(LName, LService);
end;
end;
procedure TServiceAPIKeys.LoadFromFile(const AFilename: String);
var
LKey: String;
LValue: String;
LService: TMapService;
LAES : TAESEncryption;
LStream: TBinaryReader;
LHeader: TBytes;
LCount : Integer;
LHeadEq: Boolean;
i : Integer;
begin
LAES := TAESEncryption.Create;
LStream := TBinaryReader.Create( AFilename );
FDict.Clear;
try
// set up encryption
LAES.Unicode := yesUni;
LAES.AType := atECB;
LAES.keyLength := kl256;
// only use 32 bytes = 256 bits
LAES.key := COPY( KEY, 10, 32 );
LAES.paddingMode := TPaddingMode.PKCS7;
LAES.IVMode := TIVMode.rand;
// read header
LHeader := LStream.ReadBytes(Length(HEADER));
// compare header
LHeadEq := True;
for i := Low( LHeader) to High( LHeader ) do
begin
if LHeader[i] <> HEADER[i] then
begin
LHeadEq := False;
break;
end;
end;
if NOT LHeadEq then
begin
raise Exception.Create('Invalid file format.');
end;
// read number of services store in file
LCount := LStream.ReadInteger;
// iterate all services
for i := 1 to LCount do begin
// read and decrypt service
LKey := LAES.Decrypt( LStream.ReadString );
// read and decrypt API key
LValue := LAES.Decrypt( LStream.ReadString );
LService := TMapService( GetEnumValue( TypeInfo( TMapService ), LKey ) );
FDict.Add( LService, LValue );
end;
Filename := AFilename;
LStream.Close;
finally
LStream.Free;
LAES.Free;
end;
end;
procedure TServiceAPIKeys.SaveToFile(const AFilename: String);
var
LService: TMapService;
LKey,
LValue: String;
LAES: TAESEncryption;
LStream: TBinaryWriter;
begin
LAES := TAESEncryption.Create;
LStream := TBinaryWriter.Create( AFilename );
try
LAES.Unicode := yesUni;
LAES.AType := atECB;
LAES.keyLength := kl256;
LAES.key := COPY( KEY, 10, 32 );
LAES.paddingMode := TPaddingMode.PKCS7;
LAES.IVMode := TIVMode.rand;
// header
LStream.Write(HEADER);
// number of services
LStream.Write( Integer( FDict.Keys.Count ) );
for LService in FDict.Keys do
begin
LValue := FDict[ LService ];
LKey := GetEnumName(
TypeInfo( TMapService ),
ORD( LService )
);
LStream.Write( LAES.Encrypt( LKey ) );
LStream.Write( LAES.Encrypt( LValue ) );
end;
LStream.Close;
Filename := AFilename;
finally
LStream.Free;
LAES.Free;
end;
end;
end.
|
{
publish with BSD Licence.
Copyright (c) Terry Lao
}
unit iCBSearchs;
{$MODE Delphi}
interface
uses iLBC_define,gainquants,createCB,filter,constants,C2Delphi_header;
{----------------------------------------------------------------*
* Search routine for codebook encoding and gain quantization.
*---------------------------------------------------------------}
procedure iCBSearch(
iLBCenc_inst:piLBC_Enc_Inst_t;
{ (i) the encoder state structure }
index:painteger; { (o) Codebook indices }
gain_index:painteger;{ (o) Gain quantization indices }
intarget:pareal;{ (i) Target vector for encoding }
mem:pareal; { (i) Buffer for codebook construction }
lMem:integer; { (i) Length of buffer }
lTarget:integer; { (i) Length of vector }
nStages:integer; { (i) Number of codebook stages }
weightDenum:pareal; { (i) weighting filter coefficients }
weightState:pareal; { (i) weighting filter state }
block:integer { (i) the sub-block number }
);
implementation
procedure iCBSearch(
iLBCenc_inst:piLBC_Enc_Inst_t;
{ (i) the encoder state structure }
index:painteger; { (o) Codebook indices }
gain_index:painteger;{ (o) Gain quantization indices }
intarget:pareal;{ (i) Target vector for encoding }
mem:pareal; { (i) Buffer for codebook construction }
lMem:integer; { (i) Length of buffer }
lTarget:integer; { (i) Length of vector }
nStages:integer; { (i) Number of codebook stages }
weightDenum:pareal; { (i) weighting filter coefficients }
weightState:pareal; { (i) weighting filter state }
block:integer { (i) the sub-block number }
);
var
i, j, icount, stage, best_index, range, counter:integer;
max_measure, gain, measure, crossDot, ftmp:real;
gains:array [0..CB_NSTAGES-1] of real;
target:array [0..SUBL-1] of real;
base_index, sInd, eInd, base_size:integer;
sIndAug, eIndAug:integer;
buf:array [0..CB_MEML+SUBL+2*LPC_FILTERORDER-1] of real;
invenergy:array [0..CB_EXPAND*128-1] of real;
energy:array [0..CB_EXPAND*128-1] of real;
pp, ppi,ppo,ppe,ppe1:^real;
cbvectors:array [0..CB_MEML-1] of real;
tene, cene:real;
cvec:array [0..SUBL-1] of real;
aug_vec:array [0..SUBL-1] of real;
filterno, position:integer;
begin
//sIndAug:=0;
eIndAug:=0;
ppi:=nil;
ppo:=nil;
ppe:=nil;
fillchar(cvec,SUBL*sizeof(real),0);
{ Determine size of codebook sections }
base_size:=lMem-lTarget+1;
if (lTarget=SUBL) then
begin
base_size:=lMem-lTarget+1+lTarget div 2;
end;
{ setup buffer for weighting }
move(weightState[0],buf[0],sizeof(real)*LPC_FILTERORDER);
move(mem[0],buf[LPC_FILTERORDER],lMem*sizeof(real));
move(intarget[0],buf[LPC_FILTERORDER+lMem],lTarget*sizeof(real));
{ weighting }
AllPoleFilter(@buf[LPC_FILTERORDER], weightDenum,lMem+lTarget, LPC_FILTERORDER);
{ Construct the codebook and target needed }
move( buf[LPC_FILTERORDER+lMem],target[0], lTarget*sizeof(real));
tene:=0.0;
for i:=0 to lTarget-1 do
begin
tene:=tene+target[i]*target[i];
end;
{ Prepare search over one more codebook section. This section
is created by filtering the original buffer with a filter. }
filteredCBvecs(@cbvectors, @buf[LPC_FILTERORDER], lMem);
{ The Main Loop over stages }
for stage:=0 to nStages-1 do
begin
range := search_rangeTbl[block][stage];
{ initialize search measure }
max_measure := -10000000.0;
gain := 0.0;
best_index := 0;
{ Compute cross dot product between the target
and the CB memory }
crossDot:=0.0;
pp:=@buf[LPC_FILTERORDER+lMem-lTarget];
for j:=0 to lTarget-1 do
begin
crossDot :=crossDot + target[j]*(pp^);
inc(pp);
end;
if (stage=0) then
begin
{ Calculate energy in the first block of
'lTarget' samples. }
ppe := @energy[0];
ppi := @buf[LPC_FILTERORDER+lMem-lTarget-1];
ppo := @buf[LPC_FILTERORDER+lMem-1];
ppe^:=0.0;
pp:=@buf[LPC_FILTERORDER+lMem-lTarget];
for j:=0 to lTarget-1 do
begin
ppe^:=ppe^+(pp^)*(pp^);
inc(pp);
end;
if (ppe^>0.0) then
begin
invenergy[0] := 1.0 / (ppe^ + EPS);
end
else
begin
invenergy[0] := 0.0;
end;
inc(ppe);
measure:=-10000000.0;
if (crossDot > 0.0) then
begin
measure := crossDot*crossDot*invenergy[0];
end;
end
else
begin
measure := crossDot*crossDot*invenergy[0];
end;
{ check if measure is better }
ftmp := crossDot*invenergy[0];
if ((measure>max_measure) and (abs(ftmp)<CB_MAXGAIN)) then
begin
best_index := 0;
max_measure := measure;
gain := ftmp;
end;
{ loop over the main first codebook section,
full search }
for icount:=1 to range-1 do
begin
{ calculate measure }
crossDot:=0.0;
pp := @buf[LPC_FILTERORDER+lMem-lTarget-icount];
for j:=0 to lTarget-1 do
begin
crossDot :=crossDot + target[j]*(pp^);
inc(pp);
end;
if (stage=0) then
begin
ppe^ := energy[icount-1] + (ppi^)*(ppi^) -(ppo^)*(ppo^);
inc(ppe);
dec(ppo);
dec(ppi);
if (energy[icount]>0.0) then
begin
invenergy[icount] :=1.0/(energy[icount]+EPS);
end
else
begin
invenergy[icount] := 0.0;
end;
measure:=-10000000.0;
if (crossDot > 0.0) then
begin
measure := crossDot*crossDot*invenergy[icount];
end;
end
else
begin
measure := crossDot*crossDot*invenergy[icount];
end;
{ check if measure is better }
ftmp := crossDot*invenergy[icount];
if ((measure>max_measure) and (abs(ftmp)<CB_MAXGAIN)) then
begin
best_index := icount;
max_measure := measure;
gain := ftmp;
end;
end;
{ Loop over augmented part in the first codebook
* section, full search.
* The vectors are interpolated.
}
if (lTarget=SUBL) then
begin
{ Search for best possible cb vector and
compute the CB-vectors' energy. }
searchAugmentedCB(20, 39, stage, base_size-lTarget div 2,
@target, @buf[LPC_FILTERORDER+lMem],
@max_measure, @best_index, @gain, @energy,
@invenergy);
end;
{ set search range for following codebook sections }
base_index:=best_index;
{ unrestricted search }
if (CB_RESRANGE = -1) then
begin
sInd:=0;
eInd:=range-1;
sIndAug:=20;
eIndAug:=39;
end
{ restricted search around best index from first
codebook section }
else
begin
{ Initialize search indices }
sIndAug:=0;
eIndAug:=0;
sInd:=base_index-CB_RESRANGE div 2;
eInd:=sInd+CB_RESRANGE;
if (lTarget=SUBL) then
begin
if (sInd<0) then
begin
sIndAug := 40 + sInd;
eIndAug := 39;
sInd:=0;
end
else
if ( base_index < (base_size-20) ) then
begin
if (eInd > range) then
begin
sInd :=sInd - (eInd-range);
eInd := range;
end;
end
else
begin { base_index >= (base_size-20) }
if (sInd < (base_size-20)) then
begin
sIndAug := 20;
sInd := 0;
eInd := 0;
eIndAug := 19 + CB_RESRANGE;
if(eIndAug > 39) then
begin
eInd := eIndAug-39;
eIndAug := 39;
end;
end
else
begin
sIndAug := 20 + sInd - (base_size-20);
eIndAug := 39;
sInd := 0;
eInd := CB_RESRANGE - (eIndAug-sIndAug+1);
end;
end;
end
else
begin { lTarget := 22 or 23 }
if (sInd < 0) then
begin
eInd :=eInd - sInd;
sInd := 0;
end;
if(eInd > range) then
begin
sInd :=sInd - (eInd - range);
eInd := range;
end;
end;
end;
{ search of higher codebook section }
{ index search range }
counter := sInd;
sInd :=sInd + base_size;
eInd :=eInd + base_size;
if (stage=0) then
begin
ppe := @energy[base_size];
ppe^:=0.0;
pp:=@cbvectors[lMem-lTarget];
for j:=0 to lTarget-1 do
begin
ppe^:=ppe^ + (pp^)*(pp^);
inc(pp);
end;
ppi := @cbvectors [ lMem - 1 - lTarget];
ppo := @cbvectors [ lMem - 1];
//auxulli
ppe1:=ppe;
inc(ppe1);
for j:=0 to (range-2) do
begin
ppe1^ := ppe^ + (ppi^)*(ppi^) - (ppo^)*(ppo^);
dec(ppo);
dec(ppi);
inc(ppe);
inc(ppe1);
end;
end;
{ loop over search range }
for icount:=sInd to eInd-1 do
begin
{ calculate measure }
crossDot:=0.0;
pp:=@cbvectors [ lMem - (counter) - lTarget];
inc(counter);
for j:=0 to lTarget-1 do
begin
crossDot :=crossDot + target[j]*(pp^);
inc(pp);
end;
if (energy[icount]>0.0) then
begin
invenergy[icount] :=1.0/(energy[icount]+EPS);
end
else
begin
invenergy[icount] :=0.0;
end;
if (stage=0) then
begin
measure:=-10000000.0;
if (crossDot > 0.0) then
begin
measure := crossDot*crossDot*invenergy[icount];
end;
end
else
begin
measure := crossDot*crossDot*invenergy[icount];
end;
{ check if measure is better }
ftmp := crossDot*invenergy[icount];
if ((measure>max_measure) and (abs(ftmp)<CB_MAXGAIN)) then
begin
best_index := icount;
max_measure := measure;
gain := ftmp;
end;
end;
{ Search the augmented CB inside the limited range. }
if ((lTarget=SUBL) and (sIndAug<>0)) then
begin
searchAugmentedCB(sIndAug, eIndAug, stage,
2*base_size-20, @target, @cbvectors[lMem],
@max_measure, @best_index, @gain, @energy,
@invenergy);
end;
{ record best index }
index[stage] := best_index;
{ gain quantization }
if (stage=0) then
begin
if (gain<0.0) then
begin
gain := 0.0;
end;
if (gain>CB_MAXGAIN) then
begin
gain := CB_MAXGAIN;
end;
gain := gainquant(gain, 1.0, 32, @gain_index[stage]);
end
else
begin
if (stage=1) then
begin
gain := gainquant(gain, abs(gains[stage-1]),
16, @gain_index[stage]);
end
else
begin
gain := gainquant(gain, abs(gains[stage-1]),
8, @gain_index[stage]);
end;
end;
{ Extract the best (according to measure)
codebook vector }
if (lTarget=(STATE_LEN-iLBCenc_inst^.state_short_len)) then
begin
if (index[stage]<base_size) then
begin
pp:=@buf[LPC_FILTERORDER+lMem-lTarget-index[stage]];
end
else
begin
pp:=@cbvectors[lMem-lTarget-index[stage]+base_size];
end;
end
else
begin
if (index[stage]<base_size) then
begin
if (index[stage]<(base_size-20)) then
begin
pp:=@buf[LPC_FILTERORDER+lMem-lTarget-index[stage]];
end
else
begin
createAugmentedVec(index[stage]-base_size+40,@buf[LPC_FILTERORDER+lMem],@aug_vec);
pp:=@aug_vec;
end;
end
else
begin
filterno:=index[stage] div base_size;
position:=index[stage]-filterno*base_size;
if (position<(base_size-20)) then
begin
pp:=@cbvectors[filterno*lMem-lTarget-index[stage]+filterno*base_size];
end
else
begin
createAugmentedVec(index[stage]-(filterno+1)*base_size+40,@cbvectors[filterno*lMem],@aug_vec);
pp:=@aug_vec;
end;
end;
end;
{ Subtract the best codebook vector, according
to measure, from the target vector }
for j:=0 to lTarget-1 do
begin
cvec[j] :=cvec[j] + gain*(pp^);
target[j] :=target[j] - gain*(pp^);
inc(pp);
end;
{ record quantized gain }
gains[stage]:=gain;
end;{ end of Main Loop. for (stage:=0;... }
{ Gain adjustment for energy matching }
cene:=0.0;
for i:=0 to lTarget-1 do
begin
cene:=cene+cvec[i]*cvec[i];
end;
j:=gain_index[0];
for i:=gain_index[0] to 31 do
begin
ftmp:=cene*gain_sq5Tbl[i]*gain_sq5Tbl[i];
if ((ftmp<(tene*gains[0]*gains[0])) and (gain_sq5Tbl[j]<(2.0*gains[0]))) then
begin
j:=i;
end;
end;
gain_index[0]:=j;
end;
end.
|
unit TalonSelectFra;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus,
Vcl.StdCtrls, cxButtons, cxLabel, Vcl.ExtCtrls, Classes.CardControl;
type
TTalonSide=(tsNone,tsLeft,tsRight);
TfraTalonSelect = class(TFrame)
pBackground: TPanel;
pCards: TPanel;
lCaption: TcxLabel;
Panel2: TPanel;
bOK: TcxButton;
bLeft: TcxButton;
bRight: TcxButton;
bGiveUp: TcxButton;
pbBackground: TPaintBox;
procedure bGiveUpClick(Sender: TObject);
procedure bLeftClick(Sender: TObject);
procedure bRightClick(Sender: TObject);
procedure bOKClick(Sender: TObject);
procedure pbBackgroundPaint(Sender: TObject);
private
{ Private declarations }
FTalonSideSelected:TTalonSide;
public
{ Public declarations }
FCards:TArray<TCardControl>;
constructor Create(AOwner:TComponent); override;
procedure HighLightTalon(ASide:TTalonSide);
end;
implementation
uses
Common.Entities.Card, TarockDM, Common.Entities.GameType, TarockFrm,
System.Types, System.UITypes;
{$R *.dfm}
const CARDXOFFSET=90;
{ TfraTalonSelect }
procedure TfraTalonSelect.bLeftClick(Sender: TObject);
var i: Integer;
begin
// check if called king stays on other talon
if dm.ActGame.TeamKind=tkPair then begin
for i:=3 to 5 do begin
if FCards[i].Card.ID=dm.GameSituation.KingSelected then begin
Beep;
ShowMessage('Du muss jenen Talon wählen, in dem der gerufene König liegt')
end;
end;
end;
for i:=0 to 2 do
FCards[i].Enabled:=True;
for i:=3 to 5 do begin
FCards[i].Enabled:=False;
FCards[i].Up:=False;
end;
lCaption.Caption:='Wähle die 3 Karten, die du weglegen willst';
bOK.Enabled:=True;
dm.NewGameInfo(dm.MyName+' hat den linken Talon gewaehlt');
end;
procedure TfraTalonSelect.bOKClick(Sender: TObject);
var
i: Integer;
upCards: Integer;
selectedCards:TCards;
c:TCard;
normalCards: Integer;
selectedForbiddenCards:Integer;
begin
selectedCards:=TCards.Create(true);
try
for I:=0 to 5 do begin
if FCards[i].Up then
selectedCards.Add(FCards[i].Card.Clone)
end;
for i:=0 to TfrmTarock(Owner).pMyCards.ControlCount-1 do begin
if (TfrmTarock(Owner).pMyCards.Controls[i] is TCardControl) and TCardControl(TfrmTarock(Owner).pMyCards.Controls[i]).Up then
selectedCards.Add(TCardControl(TfrmTarock(Owner).pMyCards.Controls[i]).Card.Clone)
end;
if (dm.ActGame.Talon=tk3Talon) and (selectedCards.Count<>3) then begin
Beep;
ShowMessage('Du musst genau 3 Karten aus Talon oder Hand zur Ablage auswählen')
end
else if (dm.ActGame.Talon=tk6Talon) and (selectedCards.Count<>6) then begin
Beep;
ShowMessage('Du musst genau 6 Karten aus Talon oder Hand zur Ablage auswählen')
end
else begin
for c in selectedcards do begin
if c.ID in [HK,CK,DK,SK] then begin
Beep;
ShowMessage('Du darfst keine Könige ablegen');
Exit;
end
else if c.ID in [T1,T21,T22] then begin
Beep;
ShowMessage('Du darfst kein Trullstück ablegen');
Exit;
end;
end;
if dm.ActGame.JustColors then begin
selectedForbiddenCards:=0;
for c in selectedCards do begin
if (c.CType<>ctTarock) then begin
Inc(selectedForbiddenCards);
end;
end;
if selectedForbiddenCards>0 then begin
normalCards:=0;
for c in dm.MyCards do begin
if (c.CType=ctTarock) and not (c.ID in [T1,T21,T22]) then
Inc(normalCards);
end;
if normalcards>selectedCards.Count-selectedForbiddenCards then begin
Beep;
ShowMessage('Du darfst Farben erst ablegen, wenn du nicht genügend Tarock hast');
Exit;
end;
end;
end
else begin
selectedForbiddenCards:=0;
for c in selectedCards do begin
if c.CType=ctTarock then begin
Inc(selectedForbiddenCards);
end;
end;
if selectedForbiddenCards>0 then begin
normalCards:=0;
for c in dm.MyCards do begin
if (c.CType<>ctTarock) and not (c.Id in [HK,CK,DK,SK]) then
Inc(normalCards);
end;
if normalcards>selectedCards.Count-selectedForbiddenCards then begin
Beep;
ShowMessage('Du darfst Tarock erst ablegen, wenn du nicht genügend normale Karten hast');
Exit;
end;
end;
end;
for I:=0 to 5 do begin // add talon cards for other team
if not FCards[i].Enabled then begin
c:=FCards[i].Card.Clone;
c.Fold:=True; // sign that belongs to other team
selectedCards.Add(c)
end;
end;
dm.LayDownCards(selectedCards);
end;
finally
selectedCards.Free;
end;
end;
procedure TfraTalonSelect.bRightClick(Sender: TObject);
var i: Integer;
begin
// check if called king stays on other talon
if dm.ActGame.TeamKind=tkPair then begin
for i:=0 to 2 do begin
if FCards[i].Card.ID=dm.GameSituation.KingSelected then begin
Beep;
ShowMessage('Du muss jenen Talon wählen, in dem der gerufene König liegt')
end;
end;
end;
for i:=0 to 2 do begin
FCards[i].Enabled:=False;
FCards[i].Up:=False;
end;
for i:=3 to 5 do
FCards[i].Enabled:=True;
bOK.Enabled:=True;
dm.NewGameInfo(dm.MyName+' hat den rechten Talon gewaehlt');
end;
constructor TfraTalonSelect.Create(AOwner: TComponent);
var card:TCard;
i: Integer;
imgLeft: Integer;
begin
inherited;
FTalonSideSelected:=tsNone;
imgLeft:=10;
i:=-1;
SetLength(FCards,6);
for card in dm.GetCards('TALON') do begin
Inc(i);
if i=3 then
imgLeft:=imgLeft+80;
FCards[i]:=TCardControl.Create(Self,card);
FCards[i].Parent:=pCards;
dm.imCards.GetBitmap(card.ImageIndex,FCards[i].Picture.Bitmap);
FCards[i].Top:=CARDUPLIFT+5;
FCards[i].Left:=imgLeft;
FCards[i].Remainup:=True;
FCards[i].Enabled:=(dm.ActGame.Talon=tk6Talon) and (dm.MyName=dm.GameSituation.Gamer);
FCards[i].Up:=False;
imgLeft:=imgLeft+CARDXOFFSET;
end;
if dm.MyName=dm.GameSituation.Gamer then begin
if dm.ActGame.Talon=tk3Talon then begin
lCaption.Caption:='Wähle den Talon aus, den du willst';
bOK.Enabled:=False;
end
else begin
lCaption.Caption:='Der ganze Talon gehört dir. Wähle die 6 Karten, die du weglegen willst';
bOK.Enabled:=True;
bLeft.Visible:=False;
bRight.Visible:=False;
end;
end
else begin
bLeft.Visible:=False;
bRight.Visible:=False;
bOK.Visible:=False;
lCaption.Caption:='Der Talon';
end;
bGiveUp.Visible:=false;
if (dm.MyName=dm.GameSituation.Gamer) and (dm.ActGame.TeamKind=tkPair) then begin
for i:=0 to 5 do begin
if FCards[i].Card.ID=dm.GameSituation.KingSelected then
bGiveUp.Visible:=True;
end;
end;
end;
procedure TfraTalonSelect.HighLightTalon(ASide: TTalonSide);
begin
FTalonSideSelected:=ASide;
pbBackground.Invalidate
end;
procedure TfraTalonSelect.bGiveUpClick(Sender: TObject);
begin
if MessageDlg('Willst du dieses Spiel wirklich aufgeben und zahlen ?',mtConfirmation,[mbYes,mbNo],0,mbNo)=mrYes then begin
dm.Giveup;
end;
end;
procedure TfraTalonSelect.pbBackgroundPaint(Sender: TObject);
begin
pbBackground.Canvas.Pen.Style:=psSolid;
pbBackground.Canvas.Pen.Width:=3;
pbBackground.Canvas.Pen.Color:=clSkyBlue;
pbBackground.Canvas.Brush.Style:=bsClear;
if FTalonSideSelected=tsLeft then begin
pbBackground.Canvas.Polygon([Point(5,CARDUPLIFT),Point(5*5+CARDWIDTH*3,CARDUPLIFT),Point(5*5+CARDWIDTH*3,CARDUPLIFT+CARDHEIGHT+10),Point(5,CARDUPLIFT+CARDHEIGHT+10)]);
pbBackground.Canvas.Pen.Color:=pCards.Color;
pbBackground.Canvas.Polygon([Point(355,CARDUPLIFT),Point(355+5*4+CARDWIDTH*3,CARDUPLIFT),Point(355+5*4+CARDWIDTH*3,CARDUPLIFT+CARDHEIGHT+10),Point(355,CARDUPLIFT+CARDHEIGHT+10)]);
end
else if FTalonSideSelected=tsRight then begin
pbBackground.Canvas.Polygon([Point(355,CARDUPLIFT),Point(355+5*4+CARDWIDTH*3,CARDUPLIFT),Point(355+5*4+CARDWIDTH*3,CARDUPLIFT+CARDHEIGHT+10),Point(355,CARDUPLIFT+CARDHEIGHT+10)]);
pbBackground.Canvas.Pen.Color:=pCards.Color;
pbBackground.Canvas.Polygon([Point(5,CARDUPLIFT),Point(5*5+CARDWIDTH*3,CARDUPLIFT),Point(5*5+CARDWIDTH*3,CARDUPLIFT+CARDHEIGHT+10),Point(5,CARDUPLIFT+CARDHEIGHT+10)]);
end;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
A shader that allows texture combiner setup.
}
unit VXS.TexCombineShader;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
VXS.OpenGL,
VXS.XOpenGL,
VXS.Texture,
VXS.Material,
VXS.RenderContextInfo,
VXS.TextureCombiners,
VXS.Context,
VXS.CrossPlatform,
VXS.Utils;
type
{ A shader that can setup the texture combiner. }
TVXTexCombineShader = class(TVXShader)
private
FCombiners: TStringList;
FCommandCache: TVXCombinerCache;
FCombinerIsValid: Boolean; // to avoid reparsing invalid stuff
FDesignTimeEnabled: Boolean;
FMaterialLibrary: TVXMaterialLibrary;
FLibMaterial3Name: TVXLibMaterialName;
CurrentLibMaterial3: TVXLibMaterial;
FLibMaterial4Name: TVXLibMaterialName;
CurrentLibMaterial4: TVXLibMaterial;
FApplied3, FApplied4: Boolean;
protected
procedure SetCombiners(const val: TStringList);
procedure SetDesignTimeEnabled(const val: Boolean);
procedure SetMaterialLibrary(const val: TVXMaterialLibrary);
procedure SetLibMaterial3Name(const val: TVXLibMaterialName);
procedure SetLibMaterial4Name(const val: TVXLibMaterialName);
procedure NotifyLibMaterial3Destruction;
procedure NotifyLibMaterial4Destruction;
procedure DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject); override;
procedure DoApply(var rci: TVXRenderContextInfo; Sender: TObject); override;
function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override;
procedure DoFinalize; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure NotifyChange(Sender: TObject); override;
published
property Combiners: TStringList read FCombiners write SetCombiners;
property DesignTimeEnabled: Boolean read FDesignTimeEnabled write SetDesignTimeEnabled;
property MaterialLibrary: TVXMaterialLibrary read FMaterialLibrary write SetMaterialLibrary;
property LibMaterial3Name: TVXLibMaterialName read FLibMaterial3Name write SetLibMaterial3Name;
property LibMaterial4Name: TVXLibMaterialName read FLibMaterial4Name write SetLibMaterial4Name;
end;
//===================================================================
implementation
//===================================================================
// ------------------
// ------------------ TVXTexCombineShader ------------------
// ------------------
constructor TVXTexCombineShader.Create(AOwner: TComponent);
begin
inherited;
ShaderStyle := ssLowLevel;
FCombiners := TStringList.Create;
TStringList(FCombiners).OnChange := NotifyChange;
FCombinerIsValid := True;
FCommandCache := nil;
end;
destructor TVXTexCombineShader.Destroy;
begin
if Assigned(currentLibMaterial3) then
currentLibMaterial3.UnregisterUser(Self);
if Assigned(currentLibMaterial4) then
currentLibMaterial4.UnregisterUser(Self);
inherited;
FCombiners.Free;
end;
procedure TVXTexCombineShader.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (FMaterialLibrary = AComponent) and (Operation = opRemove) then
begin
NotifyLibMaterial3Destruction;
NotifyLibMaterial4Destruction;
FMaterialLibrary := nil;
end;
inherited;
end;
procedure TVXTexCombineShader.NotifyChange(Sender: TObject);
begin
FCombinerIsValid := True;
FCommandCache := nil;
inherited NotifyChange(Sender);
end;
procedure TVXTexCombineShader.NotifyLibMaterial3Destruction;
begin
FLibMaterial3Name := '';
currentLibMaterial3 := nil;
end;
procedure TVXTexCombineShader.NotifyLibMaterial4Destruction;
begin
FLibMaterial4Name := '';
currentLibMaterial4 := nil;
end;
procedure TVXTexCombineShader.SetMaterialLibrary(const val: TVXMaterialLibrary);
begin
FMaterialLibrary := val;
SetLibMaterial3Name(LibMaterial3Name);
SetLibMaterial4Name(LibMaterial4Name);
end;
procedure TVXTexCombineShader.SetLibMaterial3Name(const val: TVXLibMaterialName);
var
newLibMaterial: TVXLibMaterial;
begin
// locate new libmaterial
if Assigned(FMaterialLibrary) then
newLibMaterial := MaterialLibrary.Materials.GetLibMaterialByName(val)
else
newLibMaterial := nil;
FLibMaterial3Name := val;
// unregister if required
if newLibMaterial <> currentLibMaterial3 then
begin
// unregister from old
if Assigned(currentLibMaterial3) then
currentLibMaterial3.UnregisterUser(Self);
currentLibMaterial3 := newLibMaterial;
// register with new
if Assigned(currentLibMaterial3) then
currentLibMaterial3.RegisterUser(Self);
NotifyChange(Self);
end;
end;
procedure TVXTexCombineShader.SetLibMaterial4Name(const val: TVXLibMaterialName);
var
newLibMaterial: TVXLibMaterial;
begin
// locate new libmaterial
if Assigned(FMaterialLibrary) then
newLibMaterial := MaterialLibrary.Materials.GetLibMaterialByName(val)
else
newLibMaterial := nil;
FLibMaterial4Name := val;
// unregister if required
if newLibMaterial <> currentLibMaterial4 then
begin
// unregister from old
if Assigned(currentLibMaterial4) then
currentLibMaterial4.UnregisterUser(Self);
currentLibMaterial4 := newLibMaterial;
// register with new
if Assigned(currentLibMaterial4) then
currentLibMaterial4.RegisterUser(Self);
NotifyChange(Self);
end;
end;
procedure TVXTexCombineShader.DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject);
begin
end;
procedure TVXTexCombineShader.DoApply(var rci: TVXRenderContextInfo; Sender: TObject);
var
n, units: Integer;
begin
if not GL_ARB_multitexture then
Exit;
FApplied3 := False;
FApplied4 := False;
if FCombinerIsValid and (FDesignTimeEnabled or (not (csDesigning in ComponentState))) then
begin
try
if Assigned(currentLibMaterial3) or Assigned(currentLibMaterial4) then
begin
glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, @n);
units := 0;
if Assigned(currentLibMaterial3) and (n >= 3) then
begin
with currentLibMaterial3.Material.Texture do
begin
if Enabled then
begin
if currentLibMaterial3.TextureMatrixIsIdentity then
ApplyAsTextureN(3, rci)
else
ApplyAsTextureN(3, rci, @currentLibMaterial3.TextureMatrix.X.X);
// ApplyAsTextureN(3, rci, currentLibMaterial3);
Inc(units, 4);
FApplied3 := True;
end;
end;
end;
if Assigned(currentLibMaterial4) and (n >= 4) then
begin
with currentLibMaterial4.Material.Texture do
begin
if Enabled then
begin
if currentLibMaterial4.TextureMatrixIsIdentity then
ApplyAsTextureN(4, rci)
else
ApplyAsTextureN(4, rci, @currentLibMaterial4.TextureMatrix.X.X);
// ApplyAsTextureN(4, rci, currentLibMaterial4);
Inc(units, 8);
FApplied4 := True;
end;
end;
end;
if units > 0 then
xglMapTexCoordToArbitraryAdd(units);
end;
if Length(FCommandCache) = 0 then
FCommandCache := GetTextureCombiners(FCombiners);
for n := 0 to High(FCommandCache) do
begin
rci.VXStates.ActiveTexture := FCommandCache[n].ActiveUnit;
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);
glTexEnvi(GL_TEXTURE_ENV, FCommandCache[n].Arg1, FCommandCache[n].Arg2);
end;
rci.VXStates.ActiveTexture := 0;
except
on E: Exception do
begin
FCombinerIsValid := False;
InformationDlg(E.ClassName + ': ' + E.Message);
end;
end;
end;
end;
function TVXTexCombineShader.DoUnApply(var rci: TVXRenderContextInfo): Boolean;
begin
if FApplied3 then
with currentLibMaterial3.Material.Texture do
UnApplyAsTextureN(3, rci, (not currentLibMaterial3.TextureMatrixIsIdentity));
if FApplied4 then
with currentLibMaterial4.Material.Texture do
UnApplyAsTextureN(4, rci, (not currentLibMaterial4.TextureMatrixIsIdentity));
Result := False;
end;
procedure TVXTexCombineShader.DoFinalize;
begin
end;
procedure TVXTexCombineShader.SetCombiners(const val: TStringList);
begin
if val <> FCombiners then
begin
FCombiners.Assign(val);
NotifyChange(Self);
end;
end;
procedure TVXTexCombineShader.SetDesignTimeEnabled(const val: Boolean);
begin
if val <> FDesignTimeEnabled then
begin
FDesignTimeEnabled := val;
NotifyChange(Self);
end;
end;
end.
|
unit uPrint;
interface
uses classes, printers;
Const
PORT_LPT1 = 1;
PORT_LPT2 = 2;
PORT_WIN = 3;
Type
TPrinterDefaultClass = Class
public
procedure StartPrinter; virtual; abstract;
procedure ClosePrinter; virtual; abstract;
end;
TLPTPrinter = Class(TPrinterDefaultClass)
private
fTextToPrint : TextFile;
fPort : String;
public
Constructor Create;
Destructor Destroy; override;
procedure StartPrinter; override; //Assign the text file to the port
procedure ClosePrinter; override; //Close text file
procedure PrintlnText(Text:String); //Send text to be printed Writeln
procedure PrintText(Text:String); //Send text to be printed Write
procedure SetPort(Port:String); //Set port to print
function GetPort:String; //Return actual port
end;
TWindowsPrinter = Class(TPrinterDefaultClass)
private
fStartPos : Integer;
fLine : Integer;
fFontName : String;
fFontSize : Integer;
public
Constructor Create;
Destructor Destroy; override;
procedure StartPrinter; override; //Prepare Win printer to print
procedure ClosePrinter; override; //Close the Win printer
procedure PrintText(Text:String); //Send Text to the printer
procedure SetStartPos(iPos : Integer); //Set left margem
procedure SetFontName(FontName : String); //Update Font Name
procedure SetFontSize(FontSize : Integer); //Update the size of the font
end;
implementation
uses Sysutils;
// ********* LPT PRINTER BEGIN ************** //
Constructor TLPTPrinter.Create;
begin
inherited Create;
end;
Destructor TLPTPrinter.Destroy;
begin
inherited Destroy;
end;
procedure TLPTPrinter.SetPort(Port:String);
begin
fPort := Port;
end;
function TLPTPrinter.GetPort:String;
begin
Result := fPort;
end;
procedure TLPTPrinter.StartPrinter;
begin
AssignFile(fTextToPrint, fPort);
Rewrite(fTextToPrint);
end;
procedure TLPTPrinter.ClosePrinter;
begin
CloseFile(fTextToPrint);
end;
procedure TLPTPrinter.PrintlnText(Text:String);
begin
Writeln(fTextToPrint, Text);
end;
procedure TLPTPrinter.PrintText(Text:String);
begin
Writeln(fTextToPrint, Text);
end;
// ********* LPT PRINTER END ************** //
// ********* WINDOWS PRINTER BEGIN ************** //
Constructor TWindowsPrinter.Create;
begin
inherited Create;
fFontName := 'Courier New';
fFontSize := 10;
end;
Destructor TWindowsPrinter.Destroy;
begin
inherited Destroy;
end;
procedure TWindowsPrinter.SetStartPos(iPos : Integer);
begin
fStartPos := iPos;
end;
procedure TWindowsPrinter.SetFontName(FontName : String);
begin
fFontName := FontName;
end;
procedure TWindowsPrinter.SetFontSize(FontSize : Integer);
begin
fFontSize := FontSize;
end;
procedure TWindowsPrinter.StartPrinter;
begin
Printer.BeginDoc;
fLine := 1;
Printer.canvas.Font.Name := fFontName;
Printer.canvas.Font.Size := fFontSize;
end;
procedure TWindowsPrinter.ClosePrinter;
begin
Printer.EndDoc;
fLine := 1;
end;
procedure TWindowsPrinter.PrintText(Text:String);
begin
Printer.Canvas.TextOut(fStartPos, fLine, Text);
fLine := fLine + 50;
end;
// ********* WINDOWS PRINTER END ************** //
end.
|
//////////////////////////////////////////////////////////////////////////
// This file is a part of NotLimited.Framework.Wpf NuGet package.
// You are strongly discouraged from fiddling with it.
// If you do, all hell will break loose and living will envy the dead.
//////////////////////////////////////////////////////////////////////////
using System;
using System.Windows;
using System.Windows.Media.Animation;
namespace NotLimited.Framework.Wpf.Animations
{
public static class AnimationExtensions
{
public static Duration ToDuration(this TimeSpan span)
{
return new Duration(span);
}
public static Timeline Accelerated(this Timeline timeline, double ratio)
{
timeline.AccelerationRatio = ratio;
timeline.DecelerationRatio = ratio;
return timeline;
}
public static Timeline Delayed(this Timeline timeline, long delay)
{
timeline.BeginTime = TimeSpan.FromMilliseconds(delay);
return timeline;
}
public static Timeline Delayed(this Timeline timeline, TimeSpan delay)
{
timeline.BeginTime = delay;
return timeline;
}
}
} |
unit DSIClientXIntegration;
Interface
uses SysUtils, Dialogs, ProcessorInterface, DeviceIntegrationInterface, uCreditCardFunction, DSICLIENTXLib_TLB, VER1000XLib_TLB,
VER2000XLib_TLB, uXML, uMRPinPad, DeviceIntegration;
const
ctab = Chr(9);
ccrlf = Chr(13) + Chr(10);
type
TDsiClientXIntegration = class(TDeviceIntegration, IDeviceIntegration)
private
FCashBack: Currency;
FexpDate: String;
Ftrack2: String;
FcardSwiped : WideString;
Fprocessor: IProcessor;
FDevice: TDsiClientX;
FPinPad: TMRPinPad;
FXMLResult : WideString; // XML answer from Server
FXMLServer : WideString; // XML Server
FXMLSent : WideString; // XML Sent
FXMLReceived : WideString; // XML Received Aprooved/Declined
FXMLContent : TXMLContent;
FAfterSucessfullSwipe : TAfterSucessfullSwipe;
FOnNeedSwipe : TNeedSwipeEvent;
FOnNeedTroutD : TNeedTroutDEvent;
function ManualEntryCard(): Boolean;
function getSecureSerialNumber(arg_serialNumber: String): String;
function CreditProcessSaleXML(): String;
function CreditProcessReturnXML(): String;
function CreditVoidSaleXML(): String;
function CreditVoidReturnXML(): String;
function DebitProcessSaleXML(): String;
function DebitProcessReturnXML(): String;
function GiftProcessSaleXML(): String;
function GiftProcessReturnXML() :String;
function GiftVoidSaleXML(): String;
function GiftVoidReturnXML(): String;
function GiftIssueXML(): String;
function GiftVoidIssueXML(): String;
function GiftReloadXML(): String;
function GiftVoidReloadXML(): String;
function GiftBalanceXML(): String;
function GiftNoNSFSaleXML(): String;
function GiftCashOutXML(): String;
function IsCustomerCardPresent(): Boolean;
procedure NeedSwipe(Sender: TObject; var SwipedTrack: WideString; var Canceled: Boolean);
procedure BeforeProcessCard();
protected
function VerifyTransaction(): Boolean; override;
public
constructor Create();
function InitializeStatus(): Boolean;
function ProcessCommand(arg_xml: WideString): Boolean;
// Credit Transactions
function CreditProcessSale(): Boolean;
function CreditProcessReturn(): Boolean;
function CreditVoidSale(): Boolean;
function CreditVoidReturn(): Boolean;
// Debit Transactions
function DebitProcessSale(): Boolean;
function DebitProcessReturn(): Boolean;
// Prepaid transactions
function GiftProcessSale(): Boolean;
function GiftProcessReturn(): Boolean;
function GiftVoidSale(): Boolean;
function GiftVoidReturn(): Boolean;
function GiftIssue: Boolean;
function GiftVoidIssue: Boolean;
function GiftReload: Boolean;
function GiftVoidReload: Boolean;
function GiftBalance: Boolean;
function GiftNoNSFSale: Boolean;
function GiftCashOut: Boolean;
// Antonio September 11, 2013
function tryIssueCard(arg_salePrice: double): TTransactionReturn;
function tryBalanceCard(arg_salePrice: double): TTransactionReturn;
procedure SetProcessor(arg_processor: IProcessor);
procedure SetPinPad(arg_pinpad: TMRPinpad);
function GetTransaction(): IProcessor;
procedure SetSwiped(arg_cardSwiped: WideString);
procedure BeforeVoid();
procedure SetIDPaymentType(arg_paymentType: Integer);
function GetIdPaymentType(): Integer;
end;
implementation
uses uMsgBox, Math, ufrmPCCharge, uFrmPCCSwipeCard, ufrmPCVoid;
{ TDsiClientXIntegration }
procedure TDsiClientXIntegration.BeforeProcessCard;
var
ASwipedTrack: WideString;
ASwipeCanceled, ASwipeError: Boolean;
sCard, sName, sDate, sTrack2 : WideString;
begin
// Here we call an event in order to swipe the card
if Assigned(FOnNeedSwipe) then
begin
repeat
ASwipeCanceled := False;
ASwipeError := False;
if ( FCardSwiped = '' ) then begin
FOnNeedSwipe(Self, ASwipedTrack, ASwipeCanceled);
sCard := AswipedTrack;
end
else
ASwipedTrack := FCardSwiped;
if ASwipedTrack = '' then
ASwipeCanceled := True;
try
ParseTrack(ASwipedTrack, sCard, sName, sDate, sTrack2);
FTrack2 := sTrack2;
Fprocessor.SetAcctNo(sCard);
Fprocessor.SetExpireDate(sDate);
except
ASwipeError := True;
raise Exception.Create('Card track not recognized');
end;
if ASwipeCanceled then
raise Exception.Create('Card Swipe canceled by user');
until not (ASwipeCanceled or ASwipeError)
end;
end;
procedure TDsiClientXIntegration.BeforeVoid;
var
ATrouD, AInvNo, AAuthCode: WideString;
ATroudCanceled: Boolean;
begin
// Here we call an event in order to swipe the card
if Assigned(FOnNeedTroutD) then
begin
ATroudCanceled := False;
ATrouD := '';
AInvNo := '';
FOnNeedTroutD(Self, ATrouD, AInvNo, AAuthCode, ATroudCanceled);
if ATroudCanceled then
raise Exception.Create('Canceled by user');
Fprocessor.SetInvoiceNo(AInvNo);
Fprocessor.SetRefNo(ATrouD);
Fprocessor.SetAuthCode(AAuthCode);
{
FInvoiceNo := AInvNo;
FRefNo := ATrouD;
FAuthCode := AAuthCode;
}
end;
end;
constructor TDsiClientXIntegration.Create;
begin
FDevice := TDSICLientX.Create(nil);
if ( IsCustomerCardPresent ) then begin
FOnNeedSwipe := NeedSwipe
end else begin
FOnNeedSwipe := nil;
end;
end;
function TDsiClientXIntegration.CreditProcessReturn: Boolean;
begin
BeforeProcessCard();
result := processCommand(CreditProcessReturnXML);
end;
function TDsiClientXIntegration.CreditProcessReturnXML: String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
if not ( fProcessor.GetDialUpBridge ) then
strRequest := ctab + ctab + '<IpPort>' + fProcessor.GetIpPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + fProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + fProcessor.getAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + fProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Return</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + fProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + fProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.CreditProcessSale: Boolean;
begin
BeforeProcessCard();
result := processCommand(CreditProcessSaleXML);
end;
function TDsiClientXIntegration.CreditProcessSaleXML: String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
if not(FProcessor.GetDialUpBridge) then
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GetIPPort + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.getMerchantID + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' +FProcessor.GetAppLabel + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Sale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo + '</RefNo>' + ccrlf;
if ( FTrack2 <> '' ) then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Tax>' + formatfloat('0.00', Fprocessor.GetTax) + '</Tax>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
if ( FTrack2 = '' ) then
begin
// Manually entered so do the Address and CVV blocks
if ((Fprocessor.GetManualZipCode <> '') or ( Fprocessor.GetManualStreeAddress <> '')) then
begin
strRequest := strRequest + ctab + ctab + '<AVS>'+ ccrlf;
if ( Fprocessor.GetManualStreeAddress() <> '' ) then
strRequest := strRequest + ctab + ctab + ctab + '<Address>' + fprocessor.GetManualStreeAddress() + '</Address>' + ccrlf;
if ( Fprocessor.GetManualZipCode <> '' ) then
strRequest := strRequest + ctab + ctab + ctab + '<Zip>' + fprocessor.GetManualZipCode() + '</Zip>' + ccrlf;
strRequest := strRequest + ctab + ctab + '</AVS>' + ccrlf;
end;
// Do CVV if there is CVV
if ( fprocessor.GetManualCvv() <> '' ) then
strRequest := strRequest + ctab + ctab + '<CVVData>' + Fprocessor.GetManualCvv() + '</CVVData>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<CustomerCode>' + fprocessor.GetCustomerCode() + '</CustomerCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.CreditVoidReturn: Boolean;
begin
BeforeProcessCard();
result := processCommand(CreditVoidReturnXML);
end;
function TDsiClientXIntegration.CreditVoidReturnXML: String;
var
strRequest: string;
begin
strRequest := '';
if not(Fprocessor.GetDialUpBridge()) then
strRequest := ctab + ctab + '<IpPort>' + Fprocessor.GetIPPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + Fprocessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReturn</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + Fprocessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.CreditVoidSale: Boolean;
begin
BeforeVoid();
BeforeProcessCard();
result := processCommand(CreditVoidSaleXML);
end;
function TDsiClientXIntegration.CreditVoidSaleXML: String;
var
strRequest: string;
begin
strRequest := '';
if not(FProcessor.GetDialUpBridge()) then
strRequest := ctab + ctab + '<IpPort>' + Fprocessor.GetIPPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + fProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + fProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidSale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + Fprocessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
strRequest := strRequest + ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<CustomerCode>' + Fprocessor.GetCustomerCode() + '</CustomerCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.DebitProcessReturn: Boolean;
begin
result := ProcessCommand(DebitProcessReturnXML);
end;
function TDsiClientXIntegration.DebitProcessReturnXML: String;
var
strRequest: string;
PINBLOCK, DervdKey: String;
begin
strRequest := '';
if not( Fprocessor.GetDialUpBridge() ) then
strRequest := ctab + ctab + '<IpPort>' + Fprocessor.GetIPPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + Fprocessor.getMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.getAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorId() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>Debit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Return</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + fprocessor.getInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
//Debit Card
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
//Amount
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', fprocessor.getPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
//PinpadInfo
FPinPad.GetPin(Fprocessor.GetAcctNo(), Fprocessor.GetPurchase(), PINBLOCK, DervdKey);
strRequest := strRequest + ctab + ctab + '<PIN>' + ccrlf +
ctab + ctab + ctab + '<PINBlock>' + PINBlock + '</PINBlock>' + ccrlf +
ctab + ctab + ctab + '<DervdKey>' + DervdKey + '</DervdKey>' + ccrlf +
ctab + ctab + '</PIN>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.DebitProcessSale: Boolean;
begin
Result := False;
result := processCommand(DebitProcessSaleXML);
end;
function TDsiClientXIntegration.DebitProcessSaleXML: String;
var
strRequest: string;
PINBlock, DervdKey: String;
begin
strRequest := '';
if not( Fprocessor.GetDialUpBridge() ) then
strRequest := ctab + ctab + '<IpPort>' + Fprocessor.GetIPPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + Fprocessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>Debit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Sale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
//Debit Card
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
//Amount
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', fprocessor.GetPurchase()) + '</Purchase>' + ccrlf;
if FCashBack <> 0 then
strRequest := strRequest + ctab + ctab + '<CashBack>' + formatfloat('0.00', FCashBack) + '</Purchase>' + ccrlf;
strRequest := strRequest + ctab + ctab + '</Amount>' + ccrlf;
//PinpadInfo
FPinPad.GetPin(Fprocessor.GetAcctNo(), Fprocessor.GetPurchase(), PINBLOCK, DervdKey);
strRequest := strRequest + ctab + ctab + '<PIN>' + ccrlf +
ctab + ctab + ctab + '<PINBlock>' + PINBlock + '</PINBlock>' + ccrlf +
ctab + ctab + ctab + '<DervdKey>' + DervdKey + '</DervdKey>' + ccrlf +
ctab + ctab + '</PIN>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GetIdPaymentType: Integer;
begin
end;
function TDsiClientXIntegration.getSecureSerialNumber(
arg_serialNumber: String): String;
var
serialSubPart: String;
begin
serialSubPart := copy(arg_serialNumber, ( length(arg_serialNumber) - 6), 6);
result := stringReplace(arg_serialNumber, serialSubPart, 'XXXXXX', [rfReplaceAll, rfIgnoreCase]);
end;
function TDsiClientXIntegration.GetTransaction: IProcessor;
begin
result := FProcessor;
end;
function TDsiClientXIntegration.GiftBalance: Boolean;
begin
BeforeProcessCard();
result := ProcessCommand(GiftBalanceXML);
end;
function TDsiClientXIntegration.GiftBalanceXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + fprocessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Balance</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GiftCashOut: Boolean;
begin
BeforeProcessCard();
result := ProcessCommand(GiftCashOutXML);
end;
function TDsiClientXIntegration.GiftCashOutXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + Fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + fprocessor.GetGiftMerchantID()+ '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>CashOut</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', 0) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GiftIssue: Boolean;
begin
BeforeProcessCard();
result := processCommand(GiftIssueXML);
end;
function TDsiClientXIntegration.GiftIssueXML: String;
var
strRequest: string;
begin
// Construct XML for PrePaid
strRequest := '';
//fccconfig.FIpAddress := fccconfig.FMercuryGiftAddress;
strRequest := strRequest + ctab + ctab + '<IpPort>' + Fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + fprocessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Issue</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Tax>' + formatfloat('0.00', fprocessor.GetTax()) + '</Tax>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
if FTrack2 = '' then
begin
// Manually entered so do the Address and CVV blocks
if ((fprocessor.GetManualZipCode() <> '') or ( fprocessor.GetManualStreeAddress() <> '')) then
begin
strRequest := strRequest + ctab + ctab + '<AVS>'+ ccrlf;
if ( fprocessor.GetManualStreeAddress() <> '' ) then
strRequest := strRequest + ctab + ctab + ctab + '<Address>' + fprocessor.GetManualStreeAddress() + '</Address>' + ccrlf;
if (Fprocessor.GetManualZipCode() <> '' ) then
strRequest := strRequest + ctab + ctab + ctab + '<Zip>' + Fprocessor.GetManualZipCode() + '</Zip>' + ccrlf;
strRequest := strRequest + ctab + ctab + '</AVS>' + ccrlf;
end;
end;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GiftNoNSFSale: Boolean;
begin
BeforeProcessCard();
result := ProcessCommand(GiftNoNSFSaleXML);
end;
function TDsiClientXIntegration.GiftNoNSFSaleXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + Fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + fprocessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>NoNSFSale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Authorize>' + formatFloat('0.00', Fprocessor.GetAuthorize()) + '</Authorize>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Balance>' + formatFloat('0.00', fprocessor.getBalance()) + '</Balance>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GiftProcessReturn: Boolean;
begin
BeforeProcessCard();
result := processCommand(GiftProcessReturnXML);
end;
function TDsiClientXIntegration.GiftProcessReturnXML: String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + Fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + Fprocessor.GetMerchantID()+ '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Return</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GiftProcessSale: Boolean;
begin
BeforeProcessCard();
result := processCommand(GiftProcessSaleXML);
end;
function TDsiClientXIntegration.GiftProcessSaleXML: String;
var
strRequest: String;
begin
// Construct XML for PrePaid Sale
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + Fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + Fprocessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Sale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Tax>' + formatfloat('0.00', fprocessor.GetTax()) + '</Tax>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
if FTrack2 = '' then
begin
// Manually entered so do the Address and CVV blocks
if ((fprocessor.GetManualZipCode() <> '') or (Fprocessor.GetManualStreeAddress() <> '')) then
begin
strRequest := strRequest + ctab + ctab + '<AVS>'+ ccrlf;
if (Fprocessor.GetManualStreeAddress() <> '') then
strRequest := strRequest + ctab + ctab + ctab + '<Address>' + Fprocessor.GetManualStreeAddress() + '</Address>' + ccrlf;
if ( fprocessor.GetManualZipCode() <> '' ) then
strRequest := strRequest + ctab + ctab + ctab + '<Zip>' + fprocessor.GetManualZipCode() + '</Zip>' + ccrlf;
strRequest := strRequest + ctab + ctab + '</AVS>' + ccrlf;
end;
// Do CVV if there is CVV
if ( Fprocessor.GetManualCvv <> '' ) then
strRequest := strRequest + ctab + ctab + '<CVVData>' + Fprocessor.GetManualCvv() + '</CVVData>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<CustomerCode>' + Fprocessor.GetCustomerCode() + '</CustomerCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GiftReload: Boolean;
begin
BeforeProcessCard();
result := ProcessCommand(GiftReloadXML);
end;
function TDsiClientXIntegration.GiftReloadXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + Fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + Fprocessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReload</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + Fprocessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GiftVoidIssue: Boolean;
begin
BeforeVoid();
BeforeProcessCard();
result := ProcessCommand(GiftVoidIssueXML);
end;
function TDsiClientXIntegration.GiftVoidIssueXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + Fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + Fprocessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidIssue</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + Fprocessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GiftVoidReload: Boolean;
begin
BeforeVoid();
BeforeProcessCard();
result := ProcessCommand(GiftVoidReloadXML);
end;
function TDsiClientXIntegration.GiftVoidReloadXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + Fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + Fprocessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReload</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + Fprocessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GiftVoidReturn: Boolean;
begin
BeforeVoid();
BeforeProcessCard();
result := ProcessCommand(GiftVoidReturnXML);
end;
function TDsiClientXIntegration.GiftVoidReturnXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + Fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + Fprocessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReturn</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + Fprocessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.GiftVoidSale: Boolean;
begin
BeforeVoid();
BeforeProcessCard();
result := ProcessCommand(GiftVoidSaleXML);
end;
function TDsiClientXIntegration.GiftVoidSaleXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + Fprocessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + Fprocessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidSale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + Fprocessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + Fprocessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiClientXIntegration.InitializeStatus: Boolean;
begin
end;
function TDsiClientXIntegration.IsCustomerCardPresent: Boolean;
var
imsgResult : Integer;
begin
result := false;
if ( FcardSwiped = '' ) then begin
iMsgResult := MsgBox('Is the customer card present?_Total to be proccessed: ' + FormatCurr('#,##0.00', Fprocessor.GetPurchase), vbYesNoCancel)
end else Begin
iMsgResult := vbYes;
end;
result := ( imsgResult = vbYes );
end;
function TDsiClientXIntegration.ManualEntryCard: Boolean;
var
sCardNumber, sMemberName, sExpireDate, sStreetAddress, sZipCode, sCVV2 : String;
begin
with TfrmPCCharge.Create(nil) do
try
Result := StartMercury(sCardNumber, sMemberName, sExpireDate, sStreetAddress, sZipCode, sCVV2);
if ( Result ) then begin
Fprocessor.SetAcctNo(sCardNumber);
fprocessor.SetManualMemberName(sMemberName);
fprocessor.SetExpireDate(sExpireDate);
Fprocessor.SetManualStreeAddress(sStreetAddress);
Fprocessor.SetManualZipCode(sZipCode);
Fprocessor.SetManualCVV2(sCvv2);
end;
finally
Free;
end;
end;
procedure TDsiClientXIntegration.NeedSwipe(Sender: TObject; var SwipedTrack: WideString; var Canceled: Boolean);
var
FrmSC: TFrmPCCSwipeCard;
iIDMeioPag : Integer;
begin
FrmSC := TFrmPCCSwipeCard.Create(nil);
try
Canceled := not FrmSC.Start(SwipedTrack, iIDMeioPag);
//Trocar o ID do Meio Pag pelo que foi feito no swipe
if (not Canceled) and (iIDMeioPag <> -1) then
Fprocessor.SetIdPaymentType(iIdMeioPag);
finally
FreeAndNil(FrmSC);
end;
end;
function TDsiClientXIntegration.ProcessCommand(arg_xml: WideString): Boolean;
var
FUserTraceData : String;
begin
Result := False;
//To set the connection timeout for PingServer and timeout to failover to the next server address in the list generated by ServerIPConfig while processing transactions with ProcessTransaction.
//The default connection timeout value is 10 seconds if SetConnectTimeout is never called.
//Param:
//1 - Timeout – The timeout value in seconds (5 – 60).
if ( Fprocessor.GetConnectionTimeOut() <> -1 ) then begin
FDevice.SetConnectTimeout(Fprocessor.GetConnectionTimeOut);
end;
//To set the response timeout while processing transactions with ProcessTransaction.
//Param:
//1 - Timeout – The timeout value in seconds (60 – 3900).
//The default connection timeout value is 300 seconds if SetResponseTimeout is never called. The default value should be used unless unusual response performance is experienced or as advised for a particular processing connection.
if ( Fprocessor.GetResponseTimeOut() <> -1 ) then begin
FDevice.SetResponseTimeout(Fprocessor.GetResponseTimeOut());
end;
//This method should be the first one called after the DSIClientX control is loaded
//Params:
//1 - HostList – up to 10 host names or IP addresses separated by semicolon (;). The host names entries in the list will be looked up via DNS.
//2 - ProcessControl – This determines how the control will process the request. Allowed values are:
// 0 Process using visible dialog boxes
// 1 Process without using visible dialog boxes
FXMLResult := FDevice.ServerIPConfig(Fprocessor.GetIPProcessorAddres(), 0);
FXMLServer := FXMLResult;
if VerifyServerConfig then
begin
//Params:
//1 - BSTR XML Command – An XML formatted string containing the details of the transaction request. See subsequent sections on available XML commands, formats and usage.
//2 - ProcessControl – This determines how the control will process the request. Allowed values are:
// 0 Process using visible dialog boxes
// 1 Process without using visible dialog boxes
// 2 Process asynchronously without visible dialog boxes and fire an event
//3 - ClientServerPassword – A password consisting of 1-12 characters which is defined by the server. If the server is configured such that a ClientServerPassword is not required, then a null string should be supplied.
//4 - UserTraceData – Optional value which will be returned unaltered with response to allow application to identify a particular response.
FXMLSent := arg_xml;
// showmessage('dsi xml sent ' + fxmlSent);
FXMLResult := FDevice.ProcessTransaction(FXMLSent, 0, '', FUserTraceData);
FXMLReceived := FXMLResult;
// showmessage('dsi xml response ' + FXMLResult);
if VerifyTransaction then
Result := True;
end;
end;
procedure TDsiClientXIntegration.SetIDPaymentType(
arg_paymentType: Integer);
begin
end;
procedure TDsiClientXIntegration.SetPinPad(arg_pinpad: TMRPinPad);
begin
FPinPad := arg_pinpad;
end;
procedure TDsiClientXIntegration.SetProcessor(arg_processor: IProcessor);
begin
Fprocessor := arg_processor;
end;
procedure TDsiClientXIntegration.SetSwiped(arg_cardSwiped: WideString);
begin
FcardSwiped := arg_cardSwiped;
end;
function TDsiClientXIntegration.tryBalanceCard(
arg_salePrice: double): TTransactionReturn;
var
msg: String;
msgButtonSelected: Integer;
balanceToBeAdded: double;
begin
GiftBalance();
result := Fprocessor.GetTransactionResult();
// Antonio, 2013 Oct 19 - (MR-67)
if ( FXMLContent.GetAttributeString('CmdStatus') = 'Approved' ) then begin
balanceToBeAdded := fprocessor.GetBalance + arg_saleprice;
msg := Format('Card %s already issued.'+#13#10+' New balance will be %f', [self.getSecureSerialNumber(Fprocessor.GetAcctNo),balanceToBeAdded]);
messageDlg(msg, mtInformation, [mbOK], 0);
end;
end;
function TDsiClientXIntegration.tryIssueCard(
arg_salePrice: double): TTransactionReturn;
var
msg: String;
msgButtonSelected: Integer;
balanceToBeAdded: double;
begin
GiftBalance();
result := Fprocessor.GetTransactionResult();
// Antonio, 2013 Oct 19 - (MR-67)
if ( FXMLContent.GetAttributeString('CmdStatus') = 'Approved' ) then begin
balanceToBeAdded := fprocessor.GetBalance + arg_saleprice;
msg := Format('Card %s already issued.'+#13#10+' New balance will be %f', [self.getSecureSerialNumber(Fprocessor.GetAcctNo),balanceToBeAdded]);
messageDlg(msg, mtInformation, [mbOK], 0);
end;
end;
function TDsiClientXIntegration.VerifyTransaction: Boolean;
begin
inherited;
end;
end.
|
(*
Category: SWAG Title: GRAPHICS ROUTINES
Original name: 0102.PAS
Description: 3D Rotation Objects
Author: DAVID ROZENBERG
Date: 08-24-94 12:55
*)
{ Here is a program to rotate any object in 3D. }
(********************************************************
* This program was written by David Rozenberg *
* *
* The program show how to convert a 3D point into a 2D *
* plane like the computer screen. So it will give you *
* the illusion of 3D shape. *
* *
* You can rotate it by the keyboard arrows, for nonstop*
* rotate press Shift+Arrow *
* *
* Please use the program as it is without changing it. *
* *
* Usage: *
* 3D FileName.Ext *
* *
* There are some files for example how to build them *
* the header " ; 3D by David Rozenberg " must be at the*
* beging of the file. *
* *
********************************************************)
Program G3d;
Uses
winCrt,Graph;
Type
Coordinate = Array[1..7] of Real;
Point = Record
X,Y,Z : Real;
End;
LineRec = ^LineType;
LineType = Record
FPoint,TPoint : Point;
Color : Byte;
Next : LineRec;
End;
Var
FirstLine : LineRec;
Last : LineRec;
Procedure Init;
Var
GraphDriver,GraphMode,GraphError : Integer;
Begin
GraphDriver:=Detect;
initGraph(GraphDriver,GraphMode,'\turbo\tp'); { your BGI driver address }
GraphError:=GraphResult;
if GraphError<>GrOk then begin
{clrscr;}
writeln('Error while turning to graphics mode.');
writeln;
halt(2);
end;
End;
Function DegTRad(Deg : Real) : real;
Begin
DegTRad:=Deg/180*Pi;
End;
Procedure ConvertPoint (P : Point;Var X,Y : Integer);
Var
Dx,Dy : Real;
Begin
X:=GetMaxX Div 2;
Y:=GetMaxY Div 2;
Dx:=(P.Y)*cos(pi/6);
Dy:=-(P.Y)*Sin(Pi/6);
Dx:=Dx+(P.X)*Cos(pi/3);
Dy:=Dy+(P.X)*Sin(Pi/3);
Dy:=Dy-P.Z;
X:=X+Round(Dx);
Y:=Y+Round(Dy);
End;
Procedure DrawLine(Lrec : LineRec);
Var
Fx,Fy,Tx,Ty : Integer;
Begin
SetColor(Lrec^.Color);
ConvertPoint(LRec^.FPoint,Fx,Fy);
ConvertPoint(LRec^.TPoint,Tx,Ty);
Line(Fx,Fy,Tx,Ty);
End;
Procedure ShowLines;
Var
Lp : LineRec;
Begin
ClearDevice;
Lp:=FirstLine;
While Lp<>Nil do Begin
DrawLine(Lp);
Lp:=Lp^.Next;
end;
End;
Procedure Error(Err : Byte;S : String);
Begin
{Clrscr;}
Writeln;
Case Err of
1 : Writeln('File : ',S,' not found!');
2 : Writeln(S,' isn''t a 3d file!');
3 : Writeln('Error in line :',S);
4 : Writeln('No file was indicated');
End;
Writeln;
Halt(Err);
End;
Procedure AddLine(Coord : Coordinate);
Var
Lp : LineRec;
Begin
New(Lp);
Lp^.Color:=Round(Coord[7]);
Lp^.FPoint.X:=Coord[1];
Lp^.FPoint.Y:=Coord[2];
Lp^.FPoint.Z:=Coord[3];
Lp^.TPoint.X:=Coord[4];
Lp^.TPoint.Y:=Coord[5];
Lp^.TPoint.Z:=Coord[6];
Lp^.Next:=Nil;
If Last=Nil then FirstLine:=Lp else Last^.Next:=Lp;
Last:=Lp;
end;
Procedure LoadFile(Name : String);
Var
F : Text;
Coord : Coordinate;
S,S1 : String;
I : Byte;
LineNum : Word;
Comma : Integer;
Begin
FirstLine:=Nil;
Last:=Nil;
Assign(F,Name);
{$I-}
Reset(f);
{$I+}
If IoResult<>0 then Error(1,Name);
Readln(F,S);
If S<>'; 3D by David Rozenberg' then Error(2,Name);
LineNum:=1;
While Not Eof(F) do Begin
Inc(LineNum);
Readln(F,S);
while Pos(' ',S)<>0 do Delete(S,Pos(' ',S),1);
If (S<>'') and (S[1]<>';') then begin
For I:=1 to 6 do Begin
Comma:=Pos(',',S);
If Comma=0 then Begin
Close(F);
Str(LineNum:4,S);
Error(3,S);
End;
S1:=Copy(S,1,Comma-1);
Delete(S,1,Comma);
Val(S1,Coord[i],Comma);
If Comma<>0 then Begin
Close(F);
Str(LineNum:4,S);
Error(3,S);
End;
End;
Val(S,Coord[7],Comma);
If Comma<>0 then Begin
Close(F);
Str(LineNum:4,S);
Error(3,S);
End;
AddLine(Coord);
End;
End;
Close(F);
End;
Procedure RotateZ(Deg : Real);
Var
Lp : LineRec;
Rad : Real;
Tx,Ty : Real;
Begin
Rad:=DegTRad(Deg);
Lp:=FirstLine;
While Lp<>Nil do Begin
With Lp^.Fpoint Do Begin
TX:=(X*Cos(Rad)-Y*Sin(Rad));
TY:=(X*Sin(Rad)+Y*Cos(Rad));
X:=Tx;
Y:=Ty;
End;
With Lp^.Tpoint Do Begin
TX:=(X*Cos(Rad)-Y*Sin(Rad));
TY:=(X*Sin(Rad)+Y*Cos(Rad));
X:=Tx;
Y:=Ty;
End;
Lp:=Lp^.Next;
end;
End;
Procedure RotateY(Deg : Real);
Var
Lp : LineRec;
Rad : Real;
Tx,Tz : Real;
Begin
Rad:=DegTRad(Deg);
Lp:=FirstLine;
While Lp<>Nil do Begin
With Lp^.Fpoint Do Begin
TX:=(X*Cos(Rad)-Z*Sin(Rad));
TZ:=(X*Sin(Rad)+Z*Cos(Rad));
X:=Tx;
Z:=Tz;
End;
With Lp^.Tpoint Do Begin
TX:=(X*Cos(Rad)-Z*Sin(Rad));
TZ:=(X*Sin(Rad)+Z*Cos(Rad));
X:=Tx;
Z:=Tz;
End;
Lp:=Lp^.Next;
end;
End;
Procedure Rotate;
Var
Ch : Char;
Begin
Repeat
Repeat
Ch:=Readkey;
If ch=#0 then Ch:=Readkey;
Until Ch in [#27,#72,#75,#77,#80,#50,#52,#54,#56];
Case ch of
#54 :Begin
While Not keypressed do begin
RotateZ(10);
ShowLines;
Delay(100);
End;
Ch:=Readkey;
If Ch=#0 then Ch:=ReadKey;
End;
#52:Begin
While Not keypressed do begin
RotateZ(-10);
ShowLines;
Delay(100);
End;
Ch:=Readkey;
If Ch=#0 then Ch:=ReadKey;
End;
#56:Begin
While Not keypressed do begin
RotateY(10);
ShowLines;
Delay(100);
End;
Ch:=Readkey;
If Ch=#0 then Ch:=ReadKey;
End;
#50:Begin
While Not keypressed do begin
RotateY(-10);
ShowLines;
Delay(100);
End;
Ch:=Readkey;
If Ch=#0 then Ch:=ReadKey;
End;
#72 : Begin
RotateY(10);
ShowLines;
End;
#75 : Begin
RotateZ(-10);
ShowLines;
End;
#77 : Begin
RotateZ(10);
ShowLines;
End;
#80 : Begin
RotateY(-10);
ShowLines;
End;
End;
Until Ch=#27;
End;
Begin
If ParamCount<1 then Error(4,'');
LoadFile(ParamStr(1));
Init;
ShowLines;
Rotate;
CloseGraph;
{ClrScr;}
Writeln;
Writeln('Thanks for using 3D');
Writeln;
End.
{
There is sample of some files that can be rotated:
cut out and save in specified file name
Cube.3D:
; 3D by David Rozenberg
; Base of cube
-70,70,-70,70,70,-70,15
70,70,-70,70,-70,-70,15
70,-70,-70,-70,-70,-70,15
-70,-70,-70,-70,70,-70,15
; Top of cube
-70,70,70,70,70,70,15
70,70,70,70,-70,70,15
70,-70,70,-70,-70,70,15
-70,-70,70,-70,70,70,15
; Side of cube
-70,70,-70,-70,70,70,13
70,70,-70,70,70,70,13
70,-70,-70,70,-70,70,13
-70,-70,-70,-70,-70,70,13
David.3D:
; 3D by David Rozenberg
0,-120,45,0,-30,45,15
0,-60,45,0,-60,-45,15
;
0,-15,45,0,15,45,12
0,15,45,0,15,-45,12
;
0,30,45,0,120,45,11
0,90,45,0,90,-45,11
;
50,-45,-75,50,45,-75,10
50,45,-75,50,45,-165,10
}
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.Bind.GenData, Vcl.Bind.Editors,
Data.Bind.EngExt, Vcl.Bind.DBEngExt, Data.Bind.Components,
Data.Bind.ObjectScope, Vcl.ExtCtrls, Vcl.StdCtrls, System.Rtti,
System.Bindings.Outputs;
type
TForm1 = class(TForm)
Edit1: TEdit;
LabeledEdit1: TLabeledEdit;
PrototypeBindSource1: TPrototypeBindSource;
BindingsList1: TBindingsList;
LinkControlToField1: TLinkControlToField;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
Data.Bind.Components.RegisterValuePropertyName(
TArray<TClass>.Create(TLabeledEdit), 'Text', 'DFM', [vpTrack, vpObservable]);
with TLinkControlToField.Create(Self) do begin
Category := 'Quick Bindings';
DataSource := PrototypeBindSource1;
FieldName := 'IntField1';
Control := LabeledEdit1;
Track := True;
end
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 083307
////////////////////////////////////////////////////////////////////////////////
unit java.time.format.DateTimeFormatter;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.time.format.FormatStyle,
java.time.format.DecimalStyle,
java.time.chrono.ChronoLocalDate,
java.time.format.ResolverStyle,
java.time.Duration,
java.lang.Appendable,
java.text.ParsePosition,
java.text.Format;
type
JDateTimeFormatter = interface;
JDateTimeFormatterClass = interface(JObjectClass)
['{495F8EE8-EC99-490E-89DD-F087A7F3A9C4}']
function _GetBASIC_ISO_DATE : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_DATE : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_DATE_TIME : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_INSTANT : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_LOCAL_DATE : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_LOCAL_DATE_TIME : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_LOCAL_TIME : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_OFFSET_DATE : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_OFFSET_DATE_TIME : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_OFFSET_TIME : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_ORDINAL_DATE : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_TIME : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_WEEK_DATE : JDateTimeFormatter; cdecl; // A: $19
function _GetISO_ZONED_DATE_TIME : JDateTimeFormatter; cdecl; // A: $19
function _GetRFC_1123_DATE_TIME : JDateTimeFormatter; cdecl; // A: $19
function format(temporal : JTemporalAccessor) : JString; cdecl; // (Ljava/time/temporal/TemporalAccessor;)Ljava/lang/String; A: $1
function getChronology : JChronology; cdecl; // ()Ljava/time/chrono/Chronology; A: $1
function getDecimalStyle : JDecimalStyle; cdecl; // ()Ljava/time/format/DecimalStyle; A: $1
function getLocale : JLocale; cdecl; // ()Ljava/util/Locale; A: $1
function getResolverFields : JSet; cdecl; // ()Ljava/util/Set; A: $1
function getResolverStyle : JResolverStyle; cdecl; // ()Ljava/time/format/ResolverStyle; A: $1
function getZone : JZoneId; cdecl; // ()Ljava/time/ZoneId; A: $1
function ofLocalizedDate(dateStyle : JFormatStyle) : JDateTimeFormatter; cdecl;// (Ljava/time/format/FormatStyle;)Ljava/time/format/DateTimeFormatter; A: $9
function ofLocalizedDateTime(dateStyle : JFormatStyle; timeStyle : JFormatStyle) : JDateTimeFormatter; cdecl; overload;// (Ljava/time/format/FormatStyle;Ljava/time/format/FormatStyle;)Ljava/time/format/DateTimeFormatter; A: $9
function ofLocalizedDateTime(dateTimeStyle : JFormatStyle) : JDateTimeFormatter; cdecl; overload;// (Ljava/time/format/FormatStyle;)Ljava/time/format/DateTimeFormatter; A: $9
function ofLocalizedTime(timeStyle : JFormatStyle) : JDateTimeFormatter; cdecl;// (Ljava/time/format/FormatStyle;)Ljava/time/format/DateTimeFormatter; A: $9
function ofPattern(pattern : JString) : JDateTimeFormatter; cdecl; overload;// (Ljava/lang/String;)Ljava/time/format/DateTimeFormatter; A: $9
function ofPattern(pattern : JString; locale : JLocale) : JDateTimeFormatter; cdecl; overload;// (Ljava/lang/String;Ljava/util/Locale;)Ljava/time/format/DateTimeFormatter; A: $9
function parse(text : JCharSequence) : JTemporalAccessor; cdecl; overload; // (Ljava/lang/CharSequence;)Ljava/time/temporal/TemporalAccessor; A: $1
function parse(text : JCharSequence; position : JParsePosition) : JTemporalAccessor; cdecl; overload;// (Ljava/lang/CharSequence;Ljava/text/ParsePosition;)Ljava/time/temporal/TemporalAccessor; A: $1
function parse(text : JCharSequence; query : JTemporalQuery) : JObject; cdecl; overload;// (Ljava/lang/CharSequence;Ljava/time/temporal/TemporalQuery;)Ljava/lang/Object; A: $1
function parseBest(text : JCharSequence; queries : TJavaArray<JTemporalQuery>) : JTemporalAccessor; cdecl;// (Ljava/lang/CharSequence;[Ljava/time/temporal/TemporalQuery;)Ljava/time/temporal/TemporalAccessor; A: $81
function parseUnresolved(text : JCharSequence; position : JParsePosition) : JTemporalAccessor; cdecl;// (Ljava/lang/CharSequence;Ljava/text/ParsePosition;)Ljava/time/temporal/TemporalAccessor; A: $1
function parsedExcessDays : JTemporalQuery; cdecl; // ()Ljava/time/temporal/TemporalQuery; A: $9
function parsedLeapSecond : JTemporalQuery; cdecl; // ()Ljava/time/temporal/TemporalQuery; A: $9
function toFormat : JFormat; cdecl; overload; // ()Ljava/text/Format; A: $1
function toFormat(parseQuery : JTemporalQuery) : JFormat; cdecl; overload; // (Ljava/time/temporal/TemporalQuery;)Ljava/text/Format; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
function withChronology(chrono : JChronology) : JDateTimeFormatter; cdecl; // (Ljava/time/chrono/Chronology;)Ljava/time/format/DateTimeFormatter; A: $1
function withDecimalStyle(decimalStyle : JDecimalStyle) : JDateTimeFormatter; cdecl;// (Ljava/time/format/DecimalStyle;)Ljava/time/format/DateTimeFormatter; A: $1
function withLocale(locale : JLocale) : JDateTimeFormatter; cdecl; // (Ljava/util/Locale;)Ljava/time/format/DateTimeFormatter; A: $1
function withResolverFields(resolverFields : JSet) : JDateTimeFormatter; cdecl; overload;// (Ljava/util/Set;)Ljava/time/format/DateTimeFormatter; A: $1
function withResolverFields(resolverFields : TJavaArray<JTemporalField>) : JDateTimeFormatter; cdecl; overload;// ([Ljava/time/temporal/TemporalField;)Ljava/time/format/DateTimeFormatter; A: $81
function withResolverStyle(resolverStyle : JResolverStyle) : JDateTimeFormatter; cdecl;// (Ljava/time/format/ResolverStyle;)Ljava/time/format/DateTimeFormatter; A: $1
function withZone(zone : JZoneId) : JDateTimeFormatter; cdecl; // (Ljava/time/ZoneId;)Ljava/time/format/DateTimeFormatter; A: $1
procedure formatTo(temporal : JTemporalAccessor; appendable : JAppendable) ; cdecl;// (Ljava/time/temporal/TemporalAccessor;Ljava/lang/Appendable;)V A: $1
property BASIC_ISO_DATE : JDateTimeFormatter read _GetBASIC_ISO_DATE; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_DATE : JDateTimeFormatter read _GetISO_DATE; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_DATE_TIME : JDateTimeFormatter read _GetISO_DATE_TIME; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_INSTANT : JDateTimeFormatter read _GetISO_INSTANT; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_LOCAL_DATE : JDateTimeFormatter read _GetISO_LOCAL_DATE; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_LOCAL_DATE_TIME : JDateTimeFormatter read _GetISO_LOCAL_DATE_TIME;// Ljava/time/format/DateTimeFormatter; A: $19
property ISO_LOCAL_TIME : JDateTimeFormatter read _GetISO_LOCAL_TIME; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_OFFSET_DATE : JDateTimeFormatter read _GetISO_OFFSET_DATE; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_OFFSET_DATE_TIME : JDateTimeFormatter read _GetISO_OFFSET_DATE_TIME;// Ljava/time/format/DateTimeFormatter; A: $19
property ISO_OFFSET_TIME : JDateTimeFormatter read _GetISO_OFFSET_TIME; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_ORDINAL_DATE : JDateTimeFormatter read _GetISO_ORDINAL_DATE; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_TIME : JDateTimeFormatter read _GetISO_TIME; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_WEEK_DATE : JDateTimeFormatter read _GetISO_WEEK_DATE; // Ljava/time/format/DateTimeFormatter; A: $19
property ISO_ZONED_DATE_TIME : JDateTimeFormatter read _GetISO_ZONED_DATE_TIME;// Ljava/time/format/DateTimeFormatter; A: $19
property RFC_1123_DATE_TIME : JDateTimeFormatter read _GetRFC_1123_DATE_TIME;// Ljava/time/format/DateTimeFormatter; A: $19
end;
[JavaSignature('java/time/format/DateTimeFormatter')]
JDateTimeFormatter = interface(JObject)
['{7BE2018A-B4AD-48E4-9966-1E8EC9ABDB3F}']
function format(temporal : JTemporalAccessor) : JString; cdecl; // (Ljava/time/temporal/TemporalAccessor;)Ljava/lang/String; A: $1
function getChronology : JChronology; cdecl; // ()Ljava/time/chrono/Chronology; A: $1
function getDecimalStyle : JDecimalStyle; cdecl; // ()Ljava/time/format/DecimalStyle; A: $1
function getLocale : JLocale; cdecl; // ()Ljava/util/Locale; A: $1
function getResolverFields : JSet; cdecl; // ()Ljava/util/Set; A: $1
function getResolverStyle : JResolverStyle; cdecl; // ()Ljava/time/format/ResolverStyle; A: $1
function getZone : JZoneId; cdecl; // ()Ljava/time/ZoneId; A: $1
function parse(text : JCharSequence) : JTemporalAccessor; cdecl; overload; // (Ljava/lang/CharSequence;)Ljava/time/temporal/TemporalAccessor; A: $1
function parse(text : JCharSequence; position : JParsePosition) : JTemporalAccessor; cdecl; overload;// (Ljava/lang/CharSequence;Ljava/text/ParsePosition;)Ljava/time/temporal/TemporalAccessor; A: $1
function parse(text : JCharSequence; query : JTemporalQuery) : JObject; cdecl; overload;// (Ljava/lang/CharSequence;Ljava/time/temporal/TemporalQuery;)Ljava/lang/Object; A: $1
function parseUnresolved(text : JCharSequence; position : JParsePosition) : JTemporalAccessor; cdecl;// (Ljava/lang/CharSequence;Ljava/text/ParsePosition;)Ljava/time/temporal/TemporalAccessor; A: $1
function toFormat : JFormat; cdecl; overload; // ()Ljava/text/Format; A: $1
function toFormat(parseQuery : JTemporalQuery) : JFormat; cdecl; overload; // (Ljava/time/temporal/TemporalQuery;)Ljava/text/Format; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
function withChronology(chrono : JChronology) : JDateTimeFormatter; cdecl; // (Ljava/time/chrono/Chronology;)Ljava/time/format/DateTimeFormatter; A: $1
function withDecimalStyle(decimalStyle : JDecimalStyle) : JDateTimeFormatter; cdecl;// (Ljava/time/format/DecimalStyle;)Ljava/time/format/DateTimeFormatter; A: $1
function withLocale(locale : JLocale) : JDateTimeFormatter; cdecl; // (Ljava/util/Locale;)Ljava/time/format/DateTimeFormatter; A: $1
function withResolverFields(resolverFields : JSet) : JDateTimeFormatter; cdecl; overload;// (Ljava/util/Set;)Ljava/time/format/DateTimeFormatter; A: $1
function withResolverStyle(resolverStyle : JResolverStyle) : JDateTimeFormatter; cdecl;// (Ljava/time/format/ResolverStyle;)Ljava/time/format/DateTimeFormatter; A: $1
function withZone(zone : JZoneId) : JDateTimeFormatter; cdecl; // (Ljava/time/ZoneId;)Ljava/time/format/DateTimeFormatter; A: $1
procedure formatTo(temporal : JTemporalAccessor; appendable : JAppendable) ; cdecl;// (Ljava/time/temporal/TemporalAccessor;Ljava/lang/Appendable;)V A: $1
end;
TJDateTimeFormatter = class(TJavaGenericImport<JDateTimeFormatterClass, JDateTimeFormatter>)
end;
implementation
end.
|
unit uFrmPromotionSetup;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls,
Buttons;
type
TFrmPromotionSetup = class(TFrmParent)
btnPromo: TSpeedButton;
btnCalendar: TSpeedButton;
btnBonusBucks: TSpeedButton;
procedure btCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnPromoClick(Sender: TObject);
procedure btnCalendarClick(Sender: TObject);
procedure btnBonusBucksClick(Sender: TObject);
private
sMenu: String;
public
function Start: Boolean;
end;
implementation
uses uDM, uFrmBonusBucks, uBrwRebateCalendar, uBrwPromo, uSystemConst;
{$R *.dfm}
procedure TFrmPromotionSetup.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrmPromotionSetup.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TFrmPromotionSetup.btnPromoClick(Sender: TObject);
begin
inherited;
sMenu := DM.fMainMenu.SubMenuName;
DM.fMainMenu.SubMenuName := btnPromo.Caption;
try
with TbrwPromo.Create(Self) do
Start;
finally
DM.fMainMenu.SubMenuName := sMenu;
end;
end;
procedure TFrmPromotionSetup.btnCalendarClick(Sender: TObject);
begin
inherited;
sMenu := DM.fMainMenu.SubMenuName;
DM.fMainMenu.SubMenuName := btnCalendar.Caption;
try
with TbrwRebateCalendar.Create(Self) do
Start;
finally
DM.fMainMenu.SubMenuName := sMenu;
end;
end;
procedure TFrmPromotionSetup.btnBonusBucksClick(Sender: TObject);
begin
inherited;
sMenu := DM.fMainMenu.SubMenuName;
DM.fMainMenu.SubMenuName := btnBonusBucks.Caption;
try
with TFrmBonusBucks.Create(Self) do
Start;
finally
DM.fMainMenu.SubMenuName := sMenu;
end;
end;
function TFrmPromotionSetup.Start: Boolean;
begin
btnPromo.Enabled := DM.fSystem.SrvParam[PARAM_APPLY_PROMO_ON_SALE];
btnCalendar.Enabled := DM.fSystem.SrvParam[PARAM_APPLY_BONUS_ON_SALE];
btnBonusBucks.Enabled := DM.fSystem.SrvParam[PARAM_APPLY_BONUS_ON_SALE];
ShowModal;
Result := (ModalResult = mrOK);
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 uCEFDomNode;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefDomNodeRef = class(TCefBaseRefCountedRef, ICefDomNode)
protected
function GetType: TCefDomNodeType;
function IsText: Boolean;
function IsElement: Boolean;
function IsEditable: Boolean;
function IsFormControlElement: Boolean;
function GetFormControlElementType: ustring;
function IsSame(const that: ICefDomNode): Boolean;
function GetName: ustring;
function GetValue: ustring;
function SetValue(const value: ustring): Boolean;
function GetAsMarkup: ustring;
function GetDocument: ICefDomDocument;
function GetParent: ICefDomNode;
function GetPreviousSibling: ICefDomNode;
function GetNextSibling: ICefDomNode;
function HasChildren: Boolean;
function GetFirstChild: ICefDomNode;
function GetLastChild: ICefDomNode;
function GetElementTagName: ustring;
function HasElementAttributes: Boolean;
function HasElementAttribute(const attrName: ustring): Boolean;
function GetElementAttribute(const attrName: ustring): ustring;
procedure GetElementAttributes(const attrMap: ICefStringMap);
function SetElementAttribute(const attrName, value: ustring): Boolean;
function GetElementInnerText: ustring;
function GetElementBounds: TCefRect;
public
class function UnWrap(data: Pointer): ICefDomNode;
end;
implementation
uses
uCEFMiscFunctions, uCEFDomDocument;
function TCefDomNodeRef.GetAsMarkup: ustring;
begin
Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_as_markup(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetDocument: ICefDomDocument;
begin
Result := TCefDomDocumentRef.UnWrap(PCefDomNode(FData)^.get_document(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetElementAttribute(const attrName: ustring): ustring;
var
p: TCefString;
begin
p := CefString(attrName);
Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_element_attribute(PCefDomNode(FData), @p));
end;
procedure TCefDomNodeRef.GetElementAttributes(const attrMap: ICefStringMap);
begin
PCefDomNode(FData)^.get_element_attributes(PCefDomNode(FData), attrMap.Handle);
end;
function TCefDomNodeRef.GetElementInnerText: ustring;
begin
Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_element_inner_text(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetElementBounds: TCefRect;
begin
Result := PCefDomNode(FData)^.get_element_bounds(PCefDomNode(FData));
end;
function TCefDomNodeRef.GetElementTagName: ustring;
begin
Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_element_tag_name(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetFirstChild: ICefDomNode;
begin
Result := TCefDomNodeRef.UnWrap(PCefDomNode(FData)^.get_first_child(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetFormControlElementType: ustring;
begin
Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_form_control_element_type(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetLastChild: ICefDomNode;
begin
Result := TCefDomNodeRef.UnWrap(PCefDomNode(FData)^.get_last_child(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetName: ustring;
begin
Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_name(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetNextSibling: ICefDomNode;
begin
Result := TCefDomNodeRef.UnWrap(PCefDomNode(FData)^.get_next_sibling(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetParent: ICefDomNode;
begin
Result := TCefDomNodeRef.UnWrap(PCefDomNode(FData)^.get_parent(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetPreviousSibling: ICefDomNode;
begin
Result := TCefDomNodeRef.UnWrap(PCefDomNode(FData)^.get_previous_sibling(PCefDomNode(FData)));
end;
function TCefDomNodeRef.GetType: TCefDomNodeType;
begin
Result := PCefDomNode(FData)^.get_type(PCefDomNode(FData));
end;
function TCefDomNodeRef.GetValue: ustring;
begin
Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_value(PCefDomNode(FData)));
end;
function TCefDomNodeRef.HasChildren: Boolean;
begin
Result := PCefDomNode(FData)^.has_children(PCefDomNode(FData)) <> 0;
end;
function TCefDomNodeRef.HasElementAttribute(const attrName: ustring): Boolean;
var
p: TCefString;
begin
p := CefString(attrName);
Result := PCefDomNode(FData)^.has_element_attribute(PCefDomNode(FData), @p) <> 0;
end;
function TCefDomNodeRef.HasElementAttributes: Boolean;
begin
Result := PCefDomNode(FData)^.has_element_attributes(PCefDomNode(FData)) <> 0;
end;
function TCefDomNodeRef.IsEditable: Boolean;
begin
Result := PCefDomNode(FData)^.is_editable(PCefDomNode(FData)) <> 0;
end;
function TCefDomNodeRef.IsElement: Boolean;
begin
Result := PCefDomNode(FData)^.is_element(PCefDomNode(FData)) <> 0;
end;
function TCefDomNodeRef.IsFormControlElement: Boolean;
begin
Result := PCefDomNode(FData)^.is_form_control_element(PCefDomNode(FData)) <> 0;
end;
function TCefDomNodeRef.IsSame(const that: ICefDomNode): Boolean;
begin
Result := PCefDomNode(FData)^.is_same(PCefDomNode(FData), CefGetData(that)) <> 0;
end;
function TCefDomNodeRef.IsText: Boolean;
begin
Result := PCefDomNode(FData)^.is_text(PCefDomNode(FData)) <> 0;
end;
function TCefDomNodeRef.SetElementAttribute(const attrName,
value: ustring): Boolean;
var
p1, p2: TCefString;
begin
p1 := CefString(attrName);
p2 := CefString(value);
Result := PCefDomNode(FData)^.set_element_attribute(PCefDomNode(FData), @p1, @p2) <> 0;
end;
function TCefDomNodeRef.SetValue(const value: ustring): Boolean;
var
p: TCefString;
begin
p := CefString(value);
Result := PCefDomNode(FData)^.set_value(PCefDomNode(FData), @p) <> 0;
end;
class function TCefDomNodeRef.UnWrap(data: Pointer): ICefDomNode;
begin
if data <> nil then
Result := Create(data) as ICefDomNode else
Result := nil;
end;
end.
|
{
SuperMaximo GameLibrary : Input unit
by Max Foster
License : http://creativecommons.org/licenses/by/3.0/
}
unit Input;
{$mode objfpc}{$H+}
interface
const
DPAD_UP = 0;
DPAD_DOWN = 1;
DPAD_LEFT = 2;
DPAD_RIGHT = 3;
//Initialises variables and detects any joysticks/gamepads that are plugged in
procedure initInput;
procedure quitInput;
//Gets the latest input data for the frame
procedure refreshEvents;
//Returns true if the key corresponding to the keycode provided is pressed
function keyPressed(code : integer) : boolean;
procedure setMousePosition(x, y : integer);
procedure hideCursor;
procedure showCursor;
//Returns the position of the mouse in each axis
function mouseX : integer;
function mouseY : integer;
//Returns true if the particular mouse button is pressed
function mouseLeft : boolean;
function mouseRight : boolean;
function mouseMiddle : boolean;
function mouseOther : boolean; //For any other side buttons on the mouse, for example
//Returns true if the mouse wheel is being scrolled up/down
function mouseWheelUp : boolean;
function mouseWheelDown : boolean;
//Returns true if the user clicked on the close button at the top of the window
function closeClicked : boolean;
//Returns the number of joysticks/gamepads connected to the computer
function joystickCount : integer;
//Returns whether a button corresponding to the code was pressed
function joystickButtonPressed(code : integer; controllerId : integer = 0) : boolean;
function joystickDpadPressed(code : integer; controllerId : integer = 0) : boolean;
//The 'axis' on a joystick/gamepad is usually an analogue stick. This returns its position
function joystickAxisValue(axis : integer; controllerId : integer = 0) : integer;
//Flags the events to be refreshed again. This is automatically called by the 'refreshScreen'
//procedure in the Display unit
procedure resetEvents;
implementation
uses SDL;
type
joystick = record
joystickHandle : PSDL_Joystick;
id : integer;
buttons : array[0..15] of boolean;
dpad : array[0..3] of boolean;
axis : array[0..15] of Sint16;
end;
var
event : TSDL_Event;
keys : array[0..320] of boolean;
mouseLeft_, mouseRight_, mouseMiddle_, mouseOther_, mouseWheelUp_, mouseWheelDown_, closeClicked_, eventsRefreshed : boolean;
mouseX_, mouseY_, joystickCount_ : integer;
joysticks : array of joystick;
procedure initJoystick(var newJoystick : joystick; num : integer);
var
i : integer;
begin
newJoystick.id := num;
newJoystick.joystickHandle := SDL_JoystickOpen(num);
for i := 0 to 15 do
begin
newJoystick.buttons[i] := false;
newJoystick.axis[i] := 0;
end;
for i := 0 to 3 do newJoystick.dpad[i] := false;
end;
procedure initInput;
var
i : word;
newJoystick : joystick;
begin
for i := 0 to length(keys)-1 do keys[i] := false;
mouseLeft_ := false;
mouseRight_ := false;
mouseMiddle_ := false;
mouseOther_ := false;
mouseWheelUp_ := false;
mouseWheelDown_ := false;
closeClicked_ := false;
eventsRefreshed := false;
mouseX_ := 0;
mouseY_ := 0;
SDL_JoystickEventState(SDL_ENABLE);
joystickCount_ := SDL_NumJoysticks;
if (joystickCount_ > 0) then
begin
for i := 0 to SDL_NumJoysticks-1 do
begin
initJoystick(newJoystick, i);
setLength(joysticks, length(joysticks)+1);
joysticks[length(joysticks)-1] := newJoystick;
end;
end;
end;
procedure quitInput;
var
i : word;
begin
if (length(joysticks) > 0) then for i := 0 to length(joysticks)-1 do SDL_JoystickClose(joysticks[i].joystickHandle);
setLength(joysticks, 0);
SDL_JoystickEventState(SDL_DISABLE);
end;
procedure refreshEvents;
begin
while (SDL_PollEvent(@event) = 1) do
begin
case event.type_ of
SDL_KEYDOWN: keys[event.key.keysym.sym] := true;
SDL_KEYUP: keys[event.key.keysym.sym] := false;
SDL_MOUSEMOTION:
begin
mouseX_ := event.motion.x;
mouseY_ := event.motion.y;
end;
SDL_MOUSEBUTTONDOWN:
begin
case event.button.button of
SDL_BUTTON_LEFT: mouseLeft_ := true;
SDL_BUTTON_RIGHT: mouseRight_ := true;
SDL_BUTTON_MIDDLE: mouseMiddle_ := true;
SDL_BUTTON_WHEELUP: mouseWheelUp_ := true;
SDL_BUTTON_WHEELDOWN: mouseWheelDown_ := true;
else mouseOther_ := true;
end;
end;
SDL_MOUSEBUTTONUP:
begin
case event.button.button of
SDL_BUTTON_LEFT: mouseLeft_ := false;
SDL_BUTTON_RIGHT: mouseRight_ := false;
SDL_BUTTON_MIDDLE: mouseMiddle_ := false;
SDL_BUTTON_WHEELUP: mouseWheelUp_ := false;
SDL_BUTTON_WHEELDOWN: mouseWheelDown_ := false;
else mouseOther_ := false;
end;
end;
SDL_QUITEV: closeClicked_ := true;
SDL_JOYBUTTONDOWN: joysticks[event.jbutton.which].buttons[event.jbutton.button] := true;
SDL_JOYBUTTONUP: joysticks[event.jbutton.which].buttons[event.jbutton.button] := false;
SDL_JOYHATMOTION:
begin
case event.jhat.value of
SDL_HAT_UP:
begin
joysticks[event.jhat.which].dpad[0] := true;
joysticks[event.jhat.which].dpad[1] := false;
end;
SDL_HAT_DOWN:
begin
joysticks[event.jhat.which].dpad[1] := true;
joysticks[event.jhat.which].dpad[0] := false;
end;
SDL_HAT_LEFT:
begin
joysticks[event.jhat.which].dpad[2] := true;
joysticks[event.jhat.which].dpad[3] := false;
end;
SDL_HAT_RIGHT:
begin
joysticks[event.jhat.which].dpad[3] := true;
joysticks[event.jhat.which].dpad[2] := false;
end;
SDL_HAT_CENTERED:
begin
joysticks[event.jhat.which].dpad[0] := false;
joysticks[event.jhat.which].dpad[1] := false;
joysticks[event.jhat.which].dpad[2] := false;
joysticks[event.jhat.which].dpad[3] := false;
end;
end;
end;
SDL_JOYAXISMOTION: joysticks[event.jaxis.which].axis[event.jaxis.axis] := event.jaxis.value;
end;
end;
eventsRefreshed := true;
end;
function keyPressed(code : integer) : boolean;
begin
if (not eventsRefreshed) then refreshEvents;
result := keys[code];
end;
procedure setMousePosition(x, y : integer);
begin
SDL_WarpMouse(x, y);
end;
procedure hideCursor;
begin
SDL_ShowCursor(0);
end;
procedure showCursor;
begin
SDL_ShowCursor(1);
end;
function mouseX : integer;
begin
if (not eventsRefreshed) then refreshEvents;
result := mouseX_;
end;
function mouseY : integer;
begin
if (not eventsRefreshed) then refreshEvents;
result := mouseY_;
end;
function mouseLeft : boolean;
begin
if (not eventsRefreshed) then refreshEvents;
result := mouseLeft_;
end;
function mouseRight : boolean;
begin
if (not eventsRefreshed) then refreshEvents;
result := mouseRight_;
end;
function mouseMiddle : boolean;
begin
if (not eventsRefreshed) then refreshEvents;
result := mouseMiddle_;
end;
function mouseOther : boolean;
begin
if (not eventsRefreshed) then refreshEvents;
result := mouseOther_;
end;
function mouseWheelUp : boolean;
begin
if (not eventsRefreshed) then refreshEvents;
result := mouseWheelUp_;
end;
function mouseWheelDown : boolean;
begin
if (not eventsRefreshed) then refreshEvents;
result := mouseWheelDown_;
end;
function closeClicked : boolean;
begin
if (not eventsRefreshed) then refreshEvents;
result := closeClicked_;
end;
function joystickCount : integer;
begin
result := joystickCount_;
end;
function joystickButtonPressed(code : integer; controllerId : integer = 0) : boolean;
begin
if (controllerId < joystickCount_) then
begin
if (not eventsRefreshed) then refreshEvents;
result := joysticks[controllerId].buttons[code];
end else result := false;
end;
function joystickDpadPressed(code : integer; controllerId : integer = 0) : boolean;
begin
if (controllerId < joystickCount_) then
begin
if (not eventsRefreshed) then refreshEvents;
result := joysticks[controllerId].dpad[code];
end else result := false;
end;
function joystickAxisValue(axis : integer; controllerId : integer = 0) : integer;
begin
if (controllerId < joystickCount_) then
begin
if (not eventsRefreshed) then refreshEvents;
result := joysticks[controllerId].axis[axis];
end else result := 0;
end;
procedure resetEvents;
begin
eventsRefreshed := false;
end;
end.
|
unit Phenologie;
interface
implementation
uses Math, ModelsManage, Main, GestionDesErreurs,SysUtils,Dialogs;
////////------------------------------------------------------------------------
procedure EvolPhenoSarrahV3(const SommeDegresJour, SeuilTempLevee,
SeuilTempBVP, SeuilTempRPR, SeuilTempMatu1,
SeuilTempMatu2, SeuilPluie,
StockSurface : Double;
Var NumPhase, SommeDegresJourPhasePrec,
SeuilTempPhaseSuivante, ChangePhase, PhasePhotoper : Double);
{Méthode générique pour le test de fin de la phase photopériodique.
PhasePhotoper = 0 en fin de la phase photoper et = 1 en debut de la phase
Cette procédure est appelée en début de journée et fait évoluer les phase
phénologiques. Pour celà, elle incrémente les numéro de phase et change la
valeur du seuil de somme de degré jours de la phase suivante.
ChangePhase est un booléen permettant
d'informer le modèle pour connaître si un jour est un jour de changement
de phase. Celà permets d'initialiser les variables directement dans les
modules spécifiques.
--> Stades phénologiques pour les céréales:
// 0 : du jour de semis au début des conditions favorables pour la germination et de la récolte à la fin de simulation (pas de culture)
// 1 : du début des conditions favorables pour la germination au jour de la levée
// 2 : du jour de la levée au début de la phase photopériodique
// 3 : du début de la phase photopériodique au début de la phase reproductive
// 4 : du début de la phase reproductive au début de la maturation (seulement pour le mais et riz) Pas pris en compte ici!
// sousphase1 de début RPR à RPR/4
// sousphase2 de RPR/4 à RPR/2
// sousphase3 de RPR/2 à 3/4 RPR
// sousphase4 de 3/4 RPR à fin RPR
// 5 : du début de la maturation au stade grain laiteux
// 6 : du début du stade grain laiteux au jour de récolte
// 7 : le jour de la récolte
}
var
ChangementDePhase, ChangementDeSousPhase : Boolean;
begin
try
ChangePhase := 0;
if (Trunc(NumPhase) = 0) then
begin
if (StockSurface >= SeuilPluie) then
begin
NumPhase := 1;
ChangePhase := 1;
SeuilTempPhaseSuivante := SeuilTempLevee;
end;
end
else
begin
if ((Trunc(NumPhase) = 2) and (SommeDegresJour >= SeuilTempPhaseSuivante)) then
begin
ChangementDePhase := True
end
else
begin
If (Trunc(NumPhase) <> 3) Then
begin
ChangementDePhase := (SommeDegresJour >= SeuilTempPhaseSuivante)
end
else
begin
ChangementDePhase := (PhasePhotoper = 0);
end;
end;
if ChangementDePhase then
begin
ChangePhase := 1;
NumPhase := NumPhase + 1;
SommeDegresJourPhasePrec := SeuilTempPhaseSuivante;
case Trunc(NumPhase) of
1 : SeuilTempPhaseSuivante:= SeuilTempLevee;
2 : SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempBVP;
3 : PhasePhotoper := 1;
4 : SeuilTempPhaseSuivante := SommeDegresJour + SeuilTempRPR;
5 : SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempMatu1;
6 : SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempMatu2;
end;
end;
end;
except
AfficheMessageErreur('EvolPhenoSarrahV3 | NumPhase: '+FloatToStr(NumPhase)+
' SommeDegresJour: '+FloatToStr(SommeDegresJour)+
' SeuilTempPhaseSuivante: '+FloatToStr(SeuilTempPhaseSuivante) ,UPhenologie);
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure EvalVitesseRacSarraV3(const VRacLevee, RootSpeedBVP, RootSpeedRPR, RootSpeedPSP,
RootSpeedMatu1, RootSpeedMatu2, NumPhase : Double;
var VitesseRacinaire : Double);
begin
try
case Trunc(NumPhase) of
1 : VitesseRacinaire := VRacLevee;
2 : VitesseRacinaire := RootSpeedBVP;
3 : VitesseRacinaire := RootSpeedPSP;
4 : VitesseRacinaire := RootSpeedRPR;
5 : begin
if (RootSpeedMatu1 = NullValue) then
begin
VitesseRacinaire := 0;
end
else
begin
VitesseRacinaire := RootSpeedMatu1;
end;
end;
6 : begin
if (RootSpeedMatu2 = NullValue) then
begin
VitesseRacinaire := 0;
end
else
begin
VitesseRacinaire := RootSpeedMatu2;
end;
end;
else
VitesseRacinaire := 0
end;
except
AfficheMessageErreur('EvalVitesseRacSarraV3 | NumPhase: '+FloatToStr(NumPhase),UPhenologie);
end;
end;
////////////////////////////////////////////////////////////////////////////////
////////------------------------------------------------------------------------
{ On calcule la vitesse moyenne de développement en considérant qu'elle est linéaire
croissante de 0 à 1 entre Tbase et Topt1, puis constante et égale à 1 entre Topt1 et Topt2
puis décroissante de 1 à 0 entre Topt2 et Tlethale.
Puis on calcule la température équivalente comprise entre Tbase et Topt1 donnant la même
vitesse de développement.
On calcule les degrés jours à partir de cette température équivalente
A SIMPLIFIER!!! Clarté...
Relation avec ancienne formule?
sumDD:=sumDD+max(min(TOpt,TMoy),TBase)-Tbase;
Pb bornage sur la temp moyenne ou sur les extrèmes???? Pas pareil!!!
Jusqu'à maintenant on le faisait sur TMoy = (Tmin+ Tmax)/2!!! assez différent!!!
si Tmoy <= Topt2
DegresDuJour:= max(min(TOpt1,TMoy),TBase)-Tbase
sinon
DegresDuJour= (Topt1-Tbase) * (1 - ( (min(TL, Tmoy) - Topt2 )/(TL -Topt2))
}
Procedure EvalDegresJourSarrahV3(const TMoy, TBase, TOpt1, TOpt2, TL :double;
var DegresDuJour,SomDegresJour:Double);
begin
try
{ Pb de méthode !?
v1:= ((Max(TMin,TBase)+Min(TOpt1,TMax))/2 -TBase )/( TOpt1 - TBase);
v2:= (TL - max(TMax,TOpt2)) / (TL - TOpt2);
v:= (v1 * (min(TMax,TOpt1) - TMin)+(min(TOpt2,max(TOpt1,TMax)) - TOpt1) + v2 * (max(TOpt2,TMax)-TOpt2))/( TMax- TMin);
DegresDuJour:= v * (TOpt1-TBase);
}
If Tmoy <= Topt2 then
DegresDuJour:= max(min(TOpt1,TMoy),TBase)-Tbase
else
DegresDuJour := (TOpt1-TBase) * (1 - ( (min(TL, TMoy) - TOpt2 )/(TL -TOpt2)));
SomDegresJour := SomDegresJour + DegresDuJour;
except
AfficheMessageErreur('EvalDegresJourSarrahV3 | TMoy='+FloatToStr(TMoy)+
'TBase='+FloatToStr(TBase)+' TOpt1='+FloatToStr(TOpt1)+
' TOpt2='+FloatToStr(TOpt2)+' TL='+FloatToStr(TL)+' DegresDuJour='+FloatToStr(DegresDuJour),UPhenologie);
end;
end;
////////------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
procedure PhotoperSarrahV3(const Numphase, ChangePhase, SomDegresJour, DegresDuJour,
SeuilPP, PPCrit, DureeDuJour, PPExp, PPSens : Double;
var SumPP, SeuilTempPhasePrec, PhasePhotoper : Double);
{Procedure speciale Vaksman Dingkuhn valable pour tous types de sensibilite
photoperiodique et pour les varietes non photoperiodique.
PPsens varie de 0,4 a 1,2. Pour PPsens > 2,5 = variété non photoperiodique.
SeuilPP = 13.5
PPcrit = 12
SumPP est dans ce cas une variable quotidienne (et non un cumul)}
begin
try
if (NumPhase = 3) then
begin
if (ChangePhase = 1) then
begin
SumPP := 100;
end;
SumPP := power((1000 / max(0.01, SomDegresJour - SeuilTempPhasePrec)), PPExp) * max(0, (DureeDuJour - PPCrit)) / (SeuilPP - PPCrit);
if (sumPP <= PPsens) then
begin
PhasePhotoper :=0;
end;
end;
except
AfficheMessageErreur('PhotoperSarrahV3',UPhenologie);
end;
end;
////////////////////////////////////////////////////////////////////////////////
Procedure EvolPhenoSarrahV3Dyn (Var T : TPointeurProcParam);
Begin
EvolPhenoSarrahV3(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9],
T[10],T[11],T[12]);
end;
Procedure PhotoperSarrahV3Dyn (Var T : TPointeurProcParam);
Begin
PhotoperSarrahV3(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9],T[10],T[11]);
end;
Procedure EvalDegresJourSarrahV3Dyn (Var T : TPointeurProcParam);
Begin
EvalDegresJourSarrahV3(T[0],T[1],T[2],T[3],T[4],T[5],T[6]);
end;
Procedure EvalVitesseRacSarraV3Dyn (Var T : TPointeurProcParam);
Begin
EvalVitesseRacSarraV3(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]);
end;
////////////////////////////////////////////////////////////////////////////////////
initialization
TabProc.AjoutProc('EvolPhenoSarrahV3', EvolPhenoSarrahV3Dyn);
TabProc.AjoutProc('PhotoperSarrahV3', PhotoperSarrahV3Dyn);
TabProc.AjoutProc('EvalDegresJourSarrahV3', EvalDegresJourSarrahV3Dyn);
TabProc.AjoutProc('EvalVitesseRacSarraV3', EvalVitesseRacSarraV3Dyn);
end.
|
unit uPostObject;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, ExtCtrls, StdCtrls, Forms, uPageObject, uGlobal;
type
TPostObject = class(TPageObject)
private
Labels: array of TLabel;
Body: TWordList;
ID, Author, Date: String;
Comments: TStringList;
Icons: array of TImage;
procedure PanelResize(Sender: TObject); virtual;
procedure AddLabels;
public
constructor Create(WC: TWinControl; Pos, _ContainerWidth: Integer; PostId: String);
end;
implementation
uses
Dialogs, Graphics;
procedure TPostObject.AddLabels;
var
k, LineWidth: Integer;
begin
ContainerWidth := Panel.Parent.Width;
if ContainerWidth < 200 then
ContainerWidth := 400;
for k := 0 to Length(Labels)-1 do
FreeAndNil(Labels[k]);
// Add body labels
k := 0;
SetLength(Labels, 1);
Labels[Length(Labels)-1] := TLabel.Create(Nil);
with Labels[Length(Labels)-1] do
begin
Parent := Panel;
Left := 48;
Top := 32;
Caption := '';
Font.Color := $000E0E0E;
end;
repeat
with Labels[Length(Labels)-1] do
LineWidth := Canvas.TextWidth(Caption + Body[k]);
if (LineWidth > ContainerWidth - 128) then
begin
SetLength(Labels, Length(Labels)+1);
Labels[Length(Labels)-1] := TLabel.Create(Nil);
with Labels[Length(Labels)-1] do
begin
Parent := Panel;
Left := 48;
Top := Labels[0].Top+(16*(Length(Labels)-1));
Caption := '';
Font.Color := $000E0E0E;
end;
end;
Labels[Length(Labels)-1].Caption := Labels[Length(Labels)-1].Caption + Body[k];
k += 1;
until (k = Length(Body));
Panel.Height := 16*Length(Labels)+64;
// Add header labels
SetLength(Labels, Length(Labels)+3);
Labels[Length(Labels)-3] := TLabel.Create(Nil);
with Labels[Length(Labels)-3] do
begin
Parent := Panel;
Left := 48;
Top := 12;
Caption := '#' + ID;
Font.Style := [fsBold];
Font.Color := $005F5F5F;
k := Left + Canvas.TextWidth(Caption);
end;
Labels[Length(Labels)-2] := TLabel.Create(Nil);
with Labels[Length(Labels)-2] do
begin
Parent := Panel;
Left := k + 4;
Top := 12;
Caption := 'on';
Font.Color := $005F5F5F;
k := Left + Canvas.TextWidth(Caption);
end;
Labels[Length(Labels)-1] := TLabel.Create(Nil);
with Labels[Length(Labels)-1] do
begin
Parent := Panel;
Left := k + 4;
Top := 12;
Caption := Author;
Font.Style := [fsBold];
Font.Color := $005F5F5F;
end;
// Add footer labels
SetLength(Labels, Length(Labels)+1);
Labels[Length(Labels)-1] := TLabel.Create(Nil);
with Labels[Length(Labels)-1] do
begin
Parent := Panel;
Caption := FormatDateTime('hh:nn', StrToDateTime(Date));
Left := ContainerWidth - (Canvas.TextWidth(Caption) + 48);
Top := Panel.Height - 24;
Font.Style := [fsBold];
Font.Color := $005F5F5F;
end;
// Add comment button
if Comments.Count > 0 then
begin
SetLength(Icons, Length(Icons) + 1);
Icons[Length(Icons) - 1] := TImage.Create(Nil);
with Icons[Length(Icons) - 1] do
begin
Parent := Panel;
Width := 12;
Height := 12;
AnchorToParent(TControl(Icons[Length(Icons) - 1]), [akLeft, akBottom]);
BorderSpacing.Left := Labels[0].Left;
BorderSpacing.Bottom := 12;
Picture.LoadFromFile('./src/icons/comments.png');
end;
SetLength(Labels, Length(Labels)+1);
Labels[Length(Labels)-1] := TLabel.Create(Nil);
with Labels[Length(Labels)-1] do
begin
Parent := Panel;
AnchorSide[akLeft].Side := asrRight;
AnchorSide[akLeft].Control := Icons[Length(Icons) - 1];
AnchorSide[akTop].Side := asrTop;
AnchorSide[akTop].Control := Icons[Length(Icons) - 1];
BorderSpacing.Left := 6;
BorderSpacing.Top := -1;
Caption := Comments.Count.ToString;
Font.Color := $005F5F5F;
Font.Style := [fsBold];
end;
end;
end;
procedure TPostObject.PanelResize(Sender: TObject);
begin
AddLabels;
inherited;
end;
constructor TPostObject.Create(WC: TWinControl; Pos, _ContainerWidth: Integer; PostId: String);
var
Contents: TStringList;
k: Integer;
begin
inherited Create(WC, Pos, _ContainerWidth);
Contents := TStringList.Create;
Contents.LoadFromFile(LIVE_DATA + PostId + '.psv');
ID := PostId;
Date := PSV(Contents.Strings[0])[2];
Author := PSV(Contents.Strings[0])[3];
Body := PartitionWords(PSV(Contents.Strings[0])[4]);
Comments := TStringList.Create;
for k := 1 to Contents.Count - 1 do
Comments.Add(Contents.Strings[k]);
// Add body labels
AddLabels;
// Assign methods
Panel.OnResize := @PanelResize;
end;
end.
|
unit DataBase;
interface
type
TDBList=class;
TDBListClass=class of TDBList;
TDBItem=class(TObject)
private
FID:Integer;
FParent:Integer;
FData:Variant;
FSubList:TDBList;
public
property ID:Integer read FID;
property Parent:Integer read FParent;
property Data:Variant read FData write SetData;
property SubList:TDBList read FSubList;
constructor Create(AID,AParent:Integer;AData:Variant;ASubListClass:TDBListClass=nil);
destructor Destroy;override;
end;
TDBList=class(TList)
public
class function TableName:String;virtual;abstract;
procedure ReadDB;
procedure WriteDB;
constructor Create(ReadNow:Boolean=False);
destructor Create;override;
end;
implementation
const
SQLGetTable='SELECT * FROM %s';
SQLSetData='UPDATE %s SET data=''%s''';
{ TDBItem }
constructor TDBItem.Create(AID, AParent: Integer;
ASubListClass: TDBListClass);
begin
FSubList.
inherited Create;
FID:=AID;
FParent:=AParent;
if ASubListClass<>nil then FSubList:=ASubListClass.Create;
end;
destructor TDBItem.Destroy;
begin
if FSubList<>nil then
begin
FSubList.Free;
FSubList:=nil
end;
inherited;
end;
end.
|
unit uDemo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, AsSynAutoCorrect, ExtCtrls, SynEdit, ShellApi;
type
TfrmDemo = class(TForm)
edtEditor: TSynEdit;
pnlContainer: TPanel;
lblLabel1: TLabel;
chkEnabled: TCheckBox;
chkIgnoreCase: TCheckBox;
sacAutoCorrect: TAsSynAutoCorrect;
chkMaintainCase: TCheckBox;
chkBeepOnAutoCorrect: TCheckBox;
lblLabel2: TLabel;
lblLabel3: TLabel;
btnAdd: TButton;
btnDelete: TButton;
btnEdit: TButton;
pnlSeparator: TPanel;
pnlAbout: TPanel;
lblLabel4: TLabel;
lblWebsite: TLabel;
lblEmail: TLabel;
lblLabel5: TLabel;
chkAutoCorrectOnMouseDown: TCheckBox;
lbxItems: TListBox;
btnAutoCorrectAll: TButton;
procedure FormCreate(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
procedure chkEnabledClick(Sender: TObject);
procedure chkIgnoreCaseClick(Sender: TObject);
procedure chkMaintainCaseClick(Sender: TObject);
procedure chkBeepOnAutoCorrectClick(Sender: TObject);
procedure lblWebsiteClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormResize(Sender: TObject);
procedure chkAutoCorrectOnMouseDownClick(Sender: TObject);
procedure lbxItemsDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure lbxItemsClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnAutoCorrectAllClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmDemo: TfrmDemo;
implementation
{$R *.DFM}
procedure TfrmDemo.FormCreate(Sender: TObject);
begin
// load from registry
sacAutoCorrect.LoadFromRegistry(HKEY_CURRENT_USER, 'Software\Aerodynamica\Components\AsSynAutoCorrect\Demo');
lbxItems.Items.Assign(sacAutoCorrect.ReplaceItems);
end;
procedure TfrmDemo.btnAddClick(Sender: TObject);
var
sReplaceFrom, sReplaceTo: String;
begin
if InputQuery('Add...', 'Replace:', sReplaceFrom) then
InputQuery('Add...', 'With:', sReplaceTo)
else
Exit;
with sacAutoCorrect do
begin
if (sReplaceFrom <> '') and (sReplaceTo <> '') then
begin
Add(sReplaceFrom, sReplaceTo);
lbxItems.Items.Assign(sacAutoCorrect.ReplaceItems);
end;
end;
// update buttons
btnDelete.Enabled := not lbxItems.ItemIndex < 0;
btnEdit.Enabled := not lbxItems.ItemIndex < 0;
end;
procedure TfrmDemo.btnDeleteClick(Sender: TObject);
begin
// stop if nothing is selected
if lbxItems.ItemIndex < 0 then
begin
MessageBox(0, 'Please select an item before executing this command!', 'Error', MB_APPLMODAL or MB_ICONERROR);
Exit;
end;
sacAutoCorrect.Delete(lbxItems.ItemIndex);
lbxItems.Items.Assign(sacAutoCorrect.ReplaceItems);
// update buttons
btnDelete.Enabled := not lbxItems.ItemIndex < 0;
btnEdit.Enabled := not lbxItems.ItemIndex < 0;
end;
procedure TfrmDemo.btnEditClick(Sender: TObject);
var
sReplaceFrom, sReplaceTo, CurrentText: String;
begin
// stop if nothing is selected
if lbxItems.ItemIndex < 0 then
begin
MessageBox(0, 'Please select an item before executing this command!', 'Error', MB_APPLMODAL or MB_ICONERROR);
Exit;
end;
// get the current item
CurrentText := sacAutoCorrect.ReplaceItems[lbxItems.ItemIndex];
sReplaceFrom := HalfString(CurrentText, True);
sReplaceTo := HalfString(CurrentText, False);
if InputQuery('Edit...', 'Replace:', sReplaceFrom) then
InputQuery('Edit...', 'With:', sReplaceTo)
else
Exit;
with sacAutoCorrect do
begin
Edit(lbxItems.ItemIndex, sReplaceFrom, sReplaceTo);
lbxItems.Items.Assign(sacAutoCorrect.ReplaceItems);
end;
// update buttons
btnDelete.Enabled := not lbxItems.ItemIndex < 0;
btnEdit.Enabled := not lbxItems.ItemIndex < 0;
end;
procedure TfrmDemo.chkEnabledClick(Sender: TObject);
begin
sacAutoCorrect.Enabled := chkEnabled.Checked;
edtEditor.SetFocus;
end;
procedure TfrmDemo.chkIgnoreCaseClick(Sender: TObject);
begin
sacAutoCorrect.IgnoreCase := chkIgnoreCase.Checked;
edtEditor.SetFocus;
end;
procedure TfrmDemo.chkMaintainCaseClick(Sender: TObject);
begin
sacAutoCorrect.MaintainCase := chkMaintainCase.Checked;
edtEditor.SetFocus;
end;
procedure TfrmDemo.chkBeepOnAutoCorrectClick(Sender: TObject);
begin
sacAutoCorrect.BeepOnAutoCorrect := chkBeepOnAutoCorrect.Checked;
edtEditor.SetFocus;
end;
procedure TfrmDemo.lblWebsiteClick(Sender: TObject);
begin
ShellExecute(GetDesktopWindow(), 'Open', PChar(Trim(TLabel(Sender).Caption)), nil, nil, SW_SHOWNORMAL);
end;
procedure TfrmDemo.FormClose(Sender: TObject; var Action: TCloseAction);
begin
//MessageBox(0, 'Please visit our website at http://aerodynamica2.port5.com for more free Delphi components and quality freeware applications!', 'Note', MB_APPLMODAL or MB_ICONINFORMATION);
end;
procedure TfrmDemo.FormResize(Sender: TObject);
begin
if Height < 435 then Height := 435;
if Width < 568 then Width := 568;
end;
procedure TfrmDemo.chkAutoCorrectOnMouseDownClick(Sender: TObject);
begin
sacAutoCorrect.AutoCorrectOnMouseDown := chkAutoCorrectOnMouseDown.Checked;
edtEditor.SetFocus;
end;
procedure TfrmDemo.lbxItemsDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
CurrentText: String;
begin
// owner-drawn stuff
CurrentText := lbxItems.Items[Index];
with lbxItems do
begin
Canvas.FillRect(Rect);
Canvas.TextOut(Rect.Left + 2, Rect.Top, HalfString(CurrentText, True));
Canvas.TextOut(Rect.Left + (lbxItems.ClientWidth div 2) + 2, Rect.Top, HalfString(CurrentText, False));
end;
end;
procedure TfrmDemo.lbxItemsClick(Sender: TObject);
begin
// disable buttons
btnDelete.Enabled := not lbxItems.ItemIndex < 0;
btnEdit.Enabled := not lbxItems.ItemIndex < 0;
end;
procedure TfrmDemo.FormDestroy(Sender: TObject);
begin
// save auto-corrections to registry
sacAutoCorrect.SaveToRegistry(HKEY_CURRENT_USER, 'Software\Aerodynamica\Components\AsSynAutoCorrect\Demo');
end;
procedure TfrmDemo.btnAutoCorrectAllClick(Sender: TObject);
begin
sacAutoCorrect.AutoCorrectAll;
edtEditor.SetFocus;
end;
end.
|
unit Invoice.View.Template.Register;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Vcl.ExtCtrls,
Vcl.DBCtrls, Vcl.StdCtrls, frxClass, frxDBSet, Vcl.Mask, Invoice.Controller.Interfaces;
type
TFormTemplateRegister = class(TForm)
PageControl: TPageControl;
TabList: TTabSheet;
DBGridRecords: TDBGrid;
TabInfo: TTabSheet;
DataSource: TDataSource;
PanelNavigator: TPanel;
ComboBoxField: TComboBox;
LabelField: TLabel;
EditValue: TEdit;
LabelValue: TLabel;
ButtonFind: TButton;
frxReportModel: TfrxReport;
frxDBDataset: TfrxDBDataset;
ButtonPrint: TButton;
ButtonInsert: TButton;
ButtonDelete: TButton;
ButtonEdit: TButton;
ButtonSave: TButton;
ButtonCancel: TButton;
LabelID: TLabel;
DBEditID: TDBEdit;
procedure ButtonFindClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
function GetEntity: iEntity; virtual;
procedure FormResize(Sender: TObject);
procedure ButtonPrintClick(Sender: TObject);
procedure DataSourceDataChange(Sender: TObject; Field: TField);
procedure ButtonInsertClick(Sender: TObject);
procedure ButtonDeleteClick(Sender: TObject);
procedure ButtonEditClick(Sender: TObject);
procedure ButtonSaveClick(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
procedure DBGridRecordsTitleClick(Column: TColumn);
private
{ Private declarations }
FEntity: iEntity;
//
procedure FindRecords;
procedure ListComboBoxField;
procedure AutoCreateFields;
public
{ Public declarations }
end;
var
FormTemplateRegister: TFormTemplateRegister;
implementation
{$R *.dfm}
uses Invoice.Controller.DataModule;
procedure TFormTemplateRegister.ButtonCancelClick(Sender: TObject);
begin
DataSource.DataSet.Cancel;
end;
procedure TFormTemplateRegister.ButtonDeleteClick(Sender: TObject);
begin
if (MessageDlg('Do you really delete record?', mtConfirmation, [mbYes, mbNo], 0) = mrYES) then
DataSource.DataSet.Delete;
end;
procedure TFormTemplateRegister.ButtonEditClick(Sender: TObject);
begin
DataSource.DataSet.Edit;
end;
procedure TFormTemplateRegister.ButtonFindClick(Sender: TObject);
begin
FindRecords;
//
FormResize(Sender);
end;
procedure TFormTemplateRegister.ButtonInsertClick(Sender: TObject);
begin
DataSource.DataSet.Insert;
end;
procedure TFormTemplateRegister.ButtonPrintClick(Sender: TObject);
var
aLimit: Extended;
aCount: Extended;
aWidth: Extended;
aPercent: Extended;
aColunm: Integer;
nameColunm: String;
infoColunm: String;
ReportCabecalho: TfrxPageHeader;
MasterData: TfrxMasterData;
begin
aCount := 0;
//
frxDBDataset.DataSource := DataSource;
//
frxReportModel.Variables['LabelTitle'] := QuotedStr(Application.Title);
frxReportModel.Variables['LabelSubTitle'] := QuotedStr(Caption);
//
if not TfrxMemoView(frxReportModel.FindObject('DemoMemo')).Visible then
begin
aLimit := frxReportModel.Pages[0].Width - 250;
//
for aColunm := 0 to DBGridRecords.Columns.Count - 1 do
begin
if (DBGridRecords.Columns[aColunm].FieldName <> '') and DataSource.DataSet.Fields[aColunm].Visible then
begin
nameColunm := 'LBMemo' + intToStr(aColunm);
infoColunm := 'DBMemo' + intToStr(aColunm);
//
aPercent := (DBGridRecords.Columns[aColunm].Width / DBGridRecords.Width) * 100;
aWidth := (aLimit / 100) * aPercent;
//
if (TfrxPageHeader(frxReportModel.FindObject('PageHeader')) <> nil) then
begin
ReportCabecalho := TfrxPageHeader(frxReportModel.FindObject('PageHeader'));
//
if (TfrxMemoView(frxReportModel.FindObject(nameColunm)) = nil) then
begin
with TfrxMemoView.Create(ReportCabecalho) do
begin
CreateUniqueName;
Name := nameColunm;
Left := aColunm;
end;
end;
//
TfrxMemoView(frxReportModel.FindObject(nameColunm)).Assign(TfrxMemoView(frxReportModel.FindObject('DemoMemo')));
TfrxMemoView(frxReportModel.FindObject(nameColunm)).Memo.Clear;
TfrxMemoView(frxReportModel.FindObject(nameColunm)).Memo.Add(DBGridRecords.Columns[aColunm].Title.Caption);
TfrxMemoView(frxReportModel.FindObject(nameColunm)).Font.Style := [fsBold];
TfrxMemoView(frxReportModel.FindObject(nameColunm)).Visible := True;
//
TfrxMemoView(frxReportModel.FindObject(nameColunm)).Left := aCount;
TfrxMemoView(frxReportModel.FindObject(nameColunm)).Width := aWidth;
//
if (DBGridRecords.Columns[aColunm].Alignment = taLeftJustify) then
TfrxMemoView(frxReportModel.FindObject(nameColunm)).HAlign := TfrxHAlign(0)
else if (DBGridRecords.Columns[aColunm].Alignment = taRightJustify) then
TfrxMemoView(frxReportModel.FindObject(nameColunm)).HAlign := TfrxHAlign(1)
else if (DBGridRecords.Columns[aColunm].Alignment = taCenter) then
TfrxMemoView(frxReportModel.FindObject(nameColunm)).HAlign := TfrxHAlign(2)
else
TfrxMemoView(frxReportModel.FindObject(nameColunm)).HAlign := TfrxHAlign(0);
end;
//
if (TfrxMasterData(frxReportModel.FindObject('MasterData')) <> nil) then
begin
MasterData := TfrxMasterData(frxReportModel.FindObject('MasterData'));
//
if (TfrxMemoView(frxReportModel.FindObject(infoColunm)) = nil) then
begin
with TfrxMemoView.Create(MasterData) do
begin
CreateUniqueName;
Name := infoColunm;
Left := aColunm;
end;
end;
//
TfrxMemoView(frxReportModel.FindObject(infoColunm)).Assign(TfrxMemoView(frxReportModel.FindObject('DemoMemo')));
TfrxMemoView(frxReportModel.FindObject(infoColunm)).Memo.Clear;
TfrxMemoView(frxReportModel.FindObject(infoColunm)).DataSet := frxDBDataset;
TfrxMemoView(frxReportModel.FindObject(infoColunm)).DataField := DBGridRecords.Columns[aColunm].FieldName;
TfrxMemoView(frxReportModel.FindObject(infoColunm)).Font.Style := [];
TfrxMemoView(frxReportModel.FindObject(infoColunm)).Visible := True;
//
TfrxMemoView(frxReportModel.FindObject(infoColunm)).Left := aCount;
TfrxMemoView(frxReportModel.FindObject(infoColunm)).Width := aWidth;
//
if (DBGridRecords.Columns[aColunm].Alignment = taLeftJustify) then
TfrxMemoView(frxReportModel.FindObject(infoColunm)).HAlign := TfrxHAlign(0)
else if (DBGridRecords.Columns[aColunm].Alignment = taRightJustify) then
TfrxMemoView(frxReportModel.FindObject(infoColunm)).HAlign := TfrxHAlign(1)
else if (DBGridRecords.Columns[aColunm].Alignment = taCenter) then
TfrxMemoView(frxReportModel.FindObject(infoColunm)).HAlign := TfrxHAlign(2)
else
TfrxMemoView(frxReportModel.FindObject(infoColunm)).HAlign := TfrxHAlign(0);
end;
//
aCount := aCount + aWidth;
end;
end;
end;
//
frxReportModel.ShowReport(True);
end;
procedure TFormTemplateRegister.ButtonSaveClick(Sender: TObject);
begin
DataSource.DataSet.Post;
end;
procedure TFormTemplateRegister.DataSourceDataChange(Sender: TObject; Field: TField);
begin
ButtonInsert.Visible := DataSource.DataSet.Active and (DataSource.DataSet.State = dsBrowse);
ButtonEdit.Visible := DataSource.DataSet.Active and (DataSource.DataSet.State = dsBrowse) and (DataSource.DataSet.RecordCount > 0);
ButtonDelete.Visible := DataSource.DataSet.Active and (DataSource.DataSet.State = dsBrowse) and (DataSource.DataSet.RecordCount > 0);
ButtonSave.Visible := DataSource.DataSet.Active and (DataSource.DataSet.State in [dsInsert, dsEdit]);
ButtonCancel.Visible := DataSource.DataSet.Active and (DataSource.DataSet.State in [dsInsert, dsEdit]);
ButtonPrint.Visible := DataSource.DataSet.Active and (DataSource.DataSet.State = dsBrowse) and (DataSource.DataSet.RecordCount > 0);
//
TabInfo.TabVisible := DataSource.DataSet.Active and (DataSource.DataSet.State in [dsInsert, dsEdit]);
TabList.TabVisible := not TabInfo.Visible;
//
if TabInfo.TabVisible then
PageControl.ActivePage := TabInfo
else
PageControl.ActivePage := TabList;
end;
procedure TFormTemplateRegister.DBGridRecordsTitleClick(Column: TColumn);
begin
FEntity.OrderBy(Column.FieldName);
end;
procedure TFormTemplateRegister.FindRecords;
begin
try
if (EditValue.Text <> '') then
FEntity.ListWhere(ComboBoxField.Text + ' = ' + QuotedStr(EditValue.Text))
else
FEntity.ListWhere(ComboBoxField.Text + ' IS NOT NULL');
//
DataSource.DataSet := FEntity.DataSet;
//
DataSource.DataSet.Open;
except
on E: Exception do
raise Exception.Create(E.Message);
end;
end;
procedure TFormTemplateRegister.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if DataSource.DataSet.Active then
DataSource.DataSet.Close;
//
Action := caFree;
end;
procedure TFormTemplateRegister.FormCreate(Sender: TObject);
begin
TabInfo.TabVisible := False;
TabList.TabVisible := True;
//
PageControl.ActivePage := TabList;
//
FEntity := GetEntity;
//
try
FEntity.List;
//
DataSource.DataSet := FEntity.DataSet;
except
on E: Exception do
raise Exception.Create(E.Message);
end;
end;
procedure TFormTemplateRegister.FormResize(Sender: TObject);
var
aCount: Integer;
aSizeGrid: Integer;
aSizeColunm: Integer;
begin
if DataSource.DataSet.Active then
begin
aSizeGrid := DBGridRecords.Width - 40;
aSizeColunm := 0;
//
for aCount := 0 to DBGridRecords.Columns.Count - 1 do
begin
if (DBGridRecords.Columns.Items[aCount].Width > 100) then
DBGridRecords.Columns.Items[aCount].Width := 100;
//
aSizeColunm := aSizeColunm + DBGridRecords.Columns.Items[aCount].Width;
end;
//
if (aSizeGrid >= aSizeColunm) then
DBGridRecords.Columns.Items[1].Width := DBGridRecords.Columns.Items[1].Width + (aSizeGrid - aSizeColunm)
else
DBGridRecords.Columns.Items[1].Width := DBGridRecords.Columns.Items[1].Width - (aSizeColunm - aSizeGrid);
end;
end;
procedure TFormTemplateRegister.FormShow(Sender: TObject);
begin
if not DataSource.DataSet.Active then
DataSource.DataSet.Open;
//
ListComboBoxField;
//
AutoCreateFields;
end;
function TFormTemplateRegister.GetEntity: iEntity;
begin
Result := FEntity;
end;
procedure TFormTemplateRegister.ListComboBoxField;
begin
ComboBoxField.Items.Clear;
//
if (DataSource.DataSet.Fields.Count > 0) then
begin
DataSource.DataSet.Fields.GetFieldNames(ComboBoxField.Items);
//
ComboBoxField.ItemIndex := 1;
end;
end;
procedure TFormTemplateRegister.AutoCreateFields;
var
LocalCount: Integer;
Line: Integer;
Colunm: Integer;
LookupDataSource: TDataSource;
LocalLabel: TLabel;
LocalEdit: TDBEdit;
LocalCheckBox: TDBCheckBox;
LocalLookupComboBox: TDBLookupComboBox;
begin
if (DataSource.DataSet.FieldCount > 0) then
begin
Line := DBEditID.Top;
Colunm := DBEditID.Left + DBEditID.Width + 10;
//
DBEditID.DataField := DataSource.DataSet.Fields[0].FieldName;
//
for LocalCount := 1 to DataSource.DataSet.FieldCount - 1 do
begin
if DataSource.DataSet.Fields[LocalCount].Visible and (DataSource.DataSet.Fields[LocalCount].ProviderFlags <> []) then
begin
if (DataSource.DataSet.Fields[LocalCount].LookupDataSet <> Nil) then
begin
LookupDataSource := TDataSource.Create(Self);
LookupDataSource.Name := 'srcLookup' + DataSource.DataSet.Fields[LocalCount].FieldName;
LookupDataSource.DataSet := DataSource.DataSet.Fields[LocalCount].LookupDataSet;
//
LocalLookupComboBox := TDBLookupComboBox.Create(Self);
LocalLookupComboBox.Name := 'DBLookup' + DataSource.DataSet.Fields[LocalCount].FieldName;
LocalLookupComboBox.Parent := TabInfo;
LocalLookupComboBox.Top := Line;
LocalLookupComboBox.Left := Colunm;
LocalLookupComboBox.DataSource := DataSource;
LocalLookupComboBox.DataField := DataSource.DataSet.Fields[LocalCount].FieldName;
LocalLookupComboBox.Width := DataSource.DataSet.Fields[LocalCount].DisplayWidth * 6;
LocalLookupComboBox.ListSource := LookupDataSource;
LocalLookupComboBox.KeyField := DataSource.DataSet.Fields[LocalCount].LookupKeyFields;
LocalLookupComboBox.ListField := DataSource.DataSet.Fields[LocalCount].LookupResultField;
//
if DataSource.DataSet.Fields[LocalCount].ReadOnly then
begin
LocalLookupComboBox.ShowHint := False;
LocalLookupComboBox.Hint := '';
LocalLookupComboBox.ReadOnly := True;
LocalLookupComboBox.Color := DBEditID.Color;
end
else
begin
LocalLookupComboBox.ShowHint := True;
LocalLookupComboBox.Hint := 'Informe ' + DataSource.DataSet.Fields[LocalCount].DisplayLabel;
LocalLookupComboBox.ReadOnly := False;
LocalLookupComboBox.Color := ComboBoxField.Color;
end;
//
LocalLabel := TLabel.Create(Self);
LocalLabel.Name := 'Label' + DataSource.DataSet.Fields[LocalCount].FieldName;
LocalLabel.Parent := TabInfo;
LocalLabel.Top := Line - 15;
LocalLabel.Left := Colunm;
LocalLabel.Caption := DataSource.DataSet.Fields[LocalCount].DisplayLabel;
LocalLabel.Width := DataSource.DataSet.Fields[LocalCount].DisplayWidth * 6;
LocalLabel.Hint := '';
LocalLabel.ShowHint := False;
LocalLabel.FocusControl := LocalLookupComboBox;
LocalLabel.StyleElements := [seClient, seBorder];
//
Colunm := Colunm + LocalLookupComboBox.Width + 10;
end
else
begin
if DataSource.DataSet.Fields[LocalCount].DataType in [TFieldType.ftInteger, TFieldType.ftString, TFieldType.ftCurrency] then
begin
LocalEdit := TDBEdit.Create(Self);
LocalEdit.Name := 'DBEdit' + DataSource.DataSet.Fields[LocalCount].FieldName;
LocalEdit.Parent := TabInfo;
LocalEdit.Top := Line;
LocalEdit.Left := Colunm;
LocalEdit.DataSource := DataSource;
LocalEdit.DataField := DataSource.DataSet.Fields[LocalCount].FieldName;
LocalEdit.MaxLength := DataSource.DataSet.Fields[LocalCount].DisplayWidth;
LocalEdit.Width := DataSource.DataSet.Fields[LocalCount].DisplayWidth * 6;
//
if DataSource.DataSet.Fields[LocalCount].ReadOnly then
begin
LocalEdit.ShowHint := False;
LocalEdit.Hint := '';
LocalEdit.ReadOnly := True;
LocalEdit.Color := DBEditID.Color;
end
else
begin
LocalEdit.ShowHint := True;
LocalEdit.Hint := 'Informe ' + DataSource.DataSet.Fields[LocalCount].DisplayLabel;
LocalEdit.ReadOnly := False;
LocalEdit.Color := ComboBoxField.Color;
end;
//
LocalLabel := TLabel.Create(Self);
LocalLabel.Name := 'Label' + DataSource.DataSet.Fields[LocalCount].FieldName;
LocalLabel.Parent := TabInfo;
LocalLabel.Top := Line - 15;
LocalLabel.Left := Colunm;
LocalLabel.Caption := DataSource.DataSet.Fields[LocalCount].DisplayLabel;
LocalLabel.Width := DataSource.DataSet.Fields[LocalCount].DisplayWidth * 6;
LocalLabel.Hint := '';
LocalLabel.ShowHint := False;
LocalLabel.FocusControl := LocalEdit;
LocalLabel.StyleElements := [seClient, seBorder];
//
Colunm := Colunm + LocalEdit.Width + 10;
end
else if DataSource.DataSet.Fields[LocalCount].DataType in [TFieldType.ftBoolean] then
begin
LocalCheckBox := TDBCheckBox.Create(Self);
LocalCheckBox.Name := 'DBCheckBox' + DataSource.DataSet.Fields[LocalCount].FieldName;
LocalCheckBox.Parent := TabInfo;
LocalCheckBox.Top := Line;
LocalCheckBox.Left := Colunm;
LocalCheckBox.DataSource := DataSource;
LocalCheckBox.DataField := DataSource.DataSet.Fields[LocalCount].FieldName;
LocalCheckBox.Caption := DataSource.DataSet.Fields[LocalCount].DisplayLabel;
LocalCheckBox.Width := (Length(DataSource.DataSet.Fields[LocalCount].DisplayLabel) * 6) + 10;
//
if DataSource.DataSet.Fields[LocalCount].ReadOnly then
begin
LocalCheckBox.ShowHint := False;
LocalEdit.Hint := '';
LocalEdit.ReadOnly := True;
end
else
begin
LocalCheckBox.ShowHint := True;
LocalEdit.Hint := 'Informe ' + DataSource.DataSet.Fields[LocalCount].DisplayLabel;
LocalEdit.ReadOnly := False;
end;
//
Colunm := Colunm + LocalCheckBox.Width + 10;
end;
end;
//
if (Colunm > 600) then
begin
Colunm := DBEditID.Left;
Line := Line + 40;
end;
end;
end;
end;
end;
end.
|
unit uPlotTemplates;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
uPlotClass, uplotrect, uplotaxis, uPlotSeries, uPlotStyles,
types, Graphics;
type
ETemplate = class(Exception);
const
cAxisName : array[0..2] of String = ('X-Axis','Y-Axis','Z-Axis' );
//procedure TmplPlotRect(APlot: TPlot; ABorder: TBorder; ADimensions: Integer; ALegend: Boolean);
// we do not generate the axes, only The Plotrect
function TmplPlotRect(APlot: TPlot; ABorderAbs: TBorder; ABorderRel: TBorder; ALegend: Boolean; AColorScale: Boolean): integer;
function TmplAxes(APlot: TPlot; APlotRect: TPlotRect; ADimensions: Integer): TList;
function TmplSeries(APlot: TPlot; AAxisList: TList; ASeriestype: TSeriestype): integer;
implementation
resourcestring
S_InvalidDimension = 'Invalid Dimensions.'#13#10+
'Please use 2 or 3 dimensions only.';
S_InvalidType = 'Invalid Series type'#13#10+
'Please do not use BASE class.';
S_DimensionMismatch = 'Dimension Mismatch.'#13#10+
'Number of axes does not match Seriestype.';
function TmplPlotRect(APlot: TPlot; ABorderAbs: TBorder; ABorderRel: TBorder; ALegend: Boolean; AColorScale: Boolean): integer;
// TODO: add borderel and borderabs
begin
Result := -1;
// PlotRect
with TPlotRect.Create(APlot) do
begin
BorderAbs := ABorderAbs;
BorderRel := ABorderRel;
ShowLegend:=ALegend;
ShowColorScale := AColorScale;
//Style.Brush.Color := clBtnFace;
Style.Brush.Color := APlot.BackgroundColor;
Title := 'Title';
Result := PlotRectIndex;
//writeln('Result (Index) ', IntToStr(Result));
end;
end;
function TmplAxes(APlot: TPlot; APlotRect: TPlotRect; ADimensions: Integer): TList;
// delivers: TList containing the axis INDICES
var
vLoop: integer;
vViewRange: TValueRange;
vPoint: TPoint;
vItem: Pinteger;
vAxisIndex: integer;
begin
try
Result := TList.Create; // to deliver axislist
for vLoop := 0 to ADimensions-1 do begin // generate N Axes and set default values
TPlotAxis.Create(APlot);
vAxisIndex := (APlot.AxisCount-1);
with TPlotAxis(APlot.Axis[vAxisIndex]) do
begin
OwnerPlotRect := APlotRect;
AxisLabel := cAxisName[vLoop]; //'
// default style
TPlotStyle(Style).Font.Size := 8;
TPlotStyle(Style).Font.Color := clBlack;
// axis orientation
vPoint.X := 0; vPoint.Y := 0;
DrawOriginRel := vPoint;
Orientation := aoVariable;
DrawAngle := round((vLoop * 90) MOD 135); // x=0; y=90; z=45 degrees
DrawLength := 100;
CASE vLoop of
0: AutoMode := lmRelToWidth ;
1: AutoMode := lmRelToHeight ;
2: begin
AutoMode := lmRelToBorder ;
DrawLength := 50;
end;
end;
IF vLoop = 0 THEN TickAngle := taNegative;
// scale and viewrange
vViewRange.min := -1; vViewRange.max := 1;
ViewRange := vViewRange;
LogScale := FALSE;
// axis number formatting
NumberFormat := nfEngineeringPrefix;
//vPoint.X := 50; vPoint.Y := 60;
//DrawOriginRel := vPoint;
// add axisindex to result list
new(vItem);
try
vItem^ := vAxisIndex;
Result.Add(vItem);
except
Dispose(vItem); raise;
end; // add axisindex
end;
end;
except
FreeAndNil(Result);
end;
end;
function TmplSeries(APlot: TPlot; AAxisList: TList; ASeriesType: TSeriestype
): integer;
var
vAxesCount: integer;
begin
Result := -1; // deliver series index of newly generated series
vAxesCount := AAxisList.Count;
IF (AAxisList = nil) or (vAxesCount = 0) THEN begin
exit;
raise ETemplate.CreateRes(@S_InvalidDimension);
end;
CASE ASeriesType of
stBASE: begin
raise ETemplate.CreateRes(@S_InvalidType);
exit;
end;
stPLAIN: begin
IF vAxesCount > 1 THEN begin
raise ETemplate.CreateRes(@S_DimensionMismatch);
exit;
end;
TPlotSeries.Create(APlot);
APlot.Series[APlot.SeriesCount-1].OwnerAxis :=
PInteger(AAxisList.Items[0])^;
end;
stXY: begin
IF vAxesCount <> 2 THEN begin
raise ETemplate.CreateRes(@S_DimensionMismatch);
exit;
end;
TXYPlotSeries.Create(APlot);
TXYPlotSeries(APlot.Series[APlot.SeriesCount-1]).XAxis :=
PInteger(AAxisList.Items[0])^;
TXYPlotSeries(APlot.Series[APlot.SeriesCount-1]).YAxis :=
PInteger(AAxisList.Items[1])^;
end;
stXYZ: begin
IF vAxesCount <> 3 THEN begin
raise ETemplate.CreateRes(@S_DimensionMismatch);
exit;
end;
TXYZPlotSeries.Create(APlot);
TXYZPlotSeries(APlot.Series[APlot.SeriesCount-1]).XAxis :=
PInteger(AAxisList.Items[0])^;
TXYZPlotSeries(APlot.Series[APlot.SeriesCount-1]).YAxis :=
PInteger(AAxisList.Items[1])^;
TXYZPlotSeries(APlot.Series[APlot.SeriesCount-1]).ZAxis :=
PInteger(AAxisList.Items[2])^;
end;
stSPECTRUM: begin
IF vAxesCount <> 2 THEN begin
raise ETemplate.CreateRes(@S_DimensionMismatch);
exit;
end;
TXYSpectrumPlotSeries.Create(APlot);
TXYSpectrumPlotSeries(APlot.Series[APlot.SeriesCount-1]).XAxis :=
PInteger(AAxisList.Items[0])^;
TXYSpectrumPlotSeries(APlot.Series[APlot.SeriesCount-1]).YAxis :=
PInteger(AAxisList.Items[1])^;
end;
stWF2D: begin
IF vAxesCount <> 3 THEN begin
raise ETemplate.CreateRes(@S_DimensionMismatch);
exit;
end;
TXYWFPlotSeries.Create(APlot);
TXYWFPlotSeries(APlot.Series[APlot.SeriesCount-1]).XAxis :=
PInteger(AAxisList.Items[0])^;
TXYWFPlotSeries(APlot.Series[APlot.SeriesCount-1]).YAxis :=
PInteger(AAxisList.Items[1])^;
TXYWFPlotSeries(APlot.Series[APlot.SeriesCount-1]).ZAxis :=
PInteger(AAxisList.Items[2])^;
end;
stWF3D: begin
IF vAxesCount <> 3 THEN begin
raise ETemplate.CreateRes(@S_DimensionMismatch);
exit;
end;
TXYWF3DPlotSeries.Create(APlot);
TXYWF3DPlotSeries(APlot.Series[APlot.SeriesCount-1]).XAxis :=
PInteger(AAxisList.Items[0])^;
TXYWF3DPlotSeries(APlot.Series[APlot.SeriesCount-1]).YAxis :=
PInteger(AAxisList.Items[1])^;
TXYWF3DPlotSeries(APlot.Series[APlot.SeriesCount-1]).ZAxis :=
PInteger(AAxisList.Items[2])^;
end;
end;
Result := APlot.SeriesCount-1;
end;
end.
|
//
// Cette unite permet de gerer une simulation
// La procedure BilanParcelle est la plus importante
//
// Auteur(s) :
// Unité(s) à voir : <unité ayant un lien fort>
//
// Date de commencement :
// Date de derniere modification : 11/02/04
// Etat : fini, teste
//
//{$DEFINE AffichageComplet}
unit ClasseSimule;
interface
uses ModelsManage, SysUtils, DB, DBTables, Variants, DateUtils, Dialogs,
{ajout VN contraintes} Contrainte, Parser10, Classes;
type
///Concept : caractérise une simulation.
///Description : Cet objet représente une simulation. Il permet de gérer celle-ci. Les méthodes de TSimule servent à construire le modèle et l'appel des modules le composant.
TSimule = class(TEntityInstance)
{Ajout VN save}ContextSave: TstringList;
{Ajout VN save}TabAppelSave: TStringList; {Ajout VN save}
//ContextSave:array of TContext;
{Ajout VN contraintes}Pars: Parser10.TParser;
/// Parser Mathématique, pour le calcul des expression des contraintes.
thisDate: TDateTime; /// représente la date en cours pendant la simulation
calendaire: Boolean;
/// permet de spécifier si on calcule les dates en tenant compte du calendrier
minorStep: Real;
/// représente le pas de temps le plus petit de la simulation -toujours la journée- .
{Ajout VN simcons}procedure Clean();
procedure InitSimulation(var anDebutSimul, anFinSimul, nbAnSim,
dateDebutSimul, dateFinSimul, annee, maxNbjSimule, dateEnCours, nbjSemis,
dateSemisCalc: double; const nbjas, codeParcelle: double);
/// Initialisation des divers paramètres d'entrée. Cette procédure correspond au module 0.
procedure InitYear(const numSimul: integer);
/// Initialisation des variables, création des instances initiales (comme l'instance Simulation, sol, etc... qui n'apparaissent pas en cours de simulation)
procedure SetList;
/// Construction de la liste des appels (construit une fois pour toute, cette liste ne contiendra pas les modules d'initialisation)
//AD procedure BilanParcelle(codeSimule : Integer); ///La méthode BilanParcelle est la méthode appelée par la méthode ExecuterSimulation de la classe TScenario, permet de gérer le déroulement de la simulation
procedure BilanParcelle(idSimule: string);
procedure SimulAn; /// Permet la Gestion de la date de semis
procedure CreationClasses;
/// Requete pour création automatique des classes(site, crop ....)
procedure RunModule(numModule: Integer);
/// Procedure d'appel d'un module avec son numéro et le contexte associé à la simulation
procedure Aller(const numSimule: integer);
/// Gère le déroullement de la simulation :
procedure StepExe;
/// Execute le module si la date d'execution correspond à la date en cours
procedure CalculNextExe;
/// Calcule la date suivante et met à jour le tableau des appels.
procedure ConfirmeSemis; /// Gestion de la date de semis
procedure MajBookmarks(const numSimule: integer);
/// Mise à jour des bookmark pour chaque table si la date correspond :
function Conversion(x: string): TEnumTypeParam;
/// Renvoie le type du parametre
{Ajout VN Contraintes}procedure MajInVar_ToPars(InIndice: array of Shortint;
TabParam: array of ModelsManage.TParam; ParamVal:
ModelsManage.TPointeurProcParam); // Met a jour les variables du parser
{Ajout VN Contraintes}procedure MajOutVar_ToProcParam(OutIndice: array of
Shortint; TabParam: array of ModelsManage.TParam; var ParamVal:
ModelsManage.TPointeurProcParam);
{Ajout VN simcons}//procedure InitInstances();
{Ajout VN simcons}procedure InitDatesSimule(const numSimul: Integer);
{Ajout VN simcons}procedure InitDatesSemis(const numSimul: Integer);
{Ajout VN save}procedure majNbJas(dateSemis, dateDebut, datefin: TDateTime);
end;
var {ajout APas}
numSimule2: integer;
//represente le numéro de la simulation en cours pour simulations pluriannuelles
implementation
uses DBModule, GestionDesTables, main, LectDonnee, GestionDesErreurs, Forms,
ClasseScenario;
//----------------------------------------------------------------------------//
//VN simcons
procedure TSimule.Clean();
begin
try
Pars.free;
while ContextSave.Count <> 0 do //on nettoit les sauvegardes
begin
TContextSave(ContextSave.Objects[0]).Free;
ContextSave.Delete(0);
end;
ContextSave.free;
while TabAppelSave.Count <> 0 do
begin
TTabAppelsSave(TabAppelSave.Objects[0]).Free;
TabAppelSave.Delete(0);
end;
TabAppelSave.free;
except
AfficheMessageErreur('TSimule.Clean', UClasseSimule);
end;
end;
procedure TSimule.CreationClasses;
// Requete pour création automatique des classes(site, crop ....)
// La requete trie les entités en fonction de leur hierarchie et celles
// dont la hierarchie est = 0 ne sont pas retenues. Les entités sont ensuite
// crées dans cet ordre.
var
aClass: TEntityClass;
begin
// Recuperation de la liste des entites necessaires pour ce modele
// Voici un exemple de la requete DbModule1.RequeteEntites :
// REPONSE CodeEntity NomEntite Hierarchie
// 1 3 Site 1
// 2 1 Plot 2
// 3 4 Soil 2
// 4 2 Crop 3
// 5 5 Plante 3
try
DbModule1.RequeteEntites.Active := true;
DbModule1.RequeteEntites.First;
while not DbModule1.RequeteEntites.Eof do
begin { TODO -ofred : dans le diag de classe 'ajouter' est une function, cela serait plus simple ? }
tabClass.ajouter(DbModule1.RequeteEntitesNomEntite.Value);
aClass := tabClass.Trouver(DbModule1.RequeteEntitesNomEntite.Value);
aClass.AttributeFromTable(DbModule1.RequeteEntitesNomEntite.Value);
DbModule1.RequeteEntites.Next;
// 16/03/04 casse ici apres avoir fait un forcage qui fonctionne sur un autre modele FREEED
end;
DbModule1.RequeteEntites.Active := false;
except
AfficheMessageErreur('TSimule.CreationClasses', UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
procedure TSimule.InitSimulation(var anDebutSimul, anFinSimul, nbAnSim,
dateDebutSimul, dateFinSimul, annee,
maxNbjSimule, dateEnCours, nbjSemis,
dateSemisCalc: double;
const nbjas, codeParcelle: double);
// Initialisation des divers paramètres d'entrée. Cette procédure correspond au module 0.
begin
try
// récupération des dates et écriture dans rescrop(ou tabValues) à la sortie de la procedure
anDebutSimul := DBModule1.Simule.findfield('AnDebutSimul').Value;
anFinSimul := DBModule1.Simule.findfield('AnFinSimul').Value;
nbAnSim := DBModule1.Simule.findfield('NbAnSim').Value;
dateFinSimul := DBModule1.Simule.findfield('FinSimul').Value;
dateDebutSimul := DBModule1.Simule.findfield('DebutSimul').Value;
annee := DBModule1.Simule.findfield('AnDebutSimul').Value;
dateEnCours := DBModule1.Simule.findfield('DebutSimul').Value;
maxNBJSimule := Trunc(DateFinSimul - DateDebutSimul) + 1;
nbjSemis := NullValue;
dateSemisCalc := NullValue;
except
AfficheMessageErreur('TSimule.InitSimulation', UClasseSimule);
end;
end;
//----------------------------VN simcons-------------------------------------//
procedure TSimule.InitDatesSimule(const numSimul: Integer);
var
jour, mois, an: Word;
begin
try
{$IFDEF AffichageComplet}
MainForm.affiche((TimeToStr(Time) + #9 +
'TSimule2.InitYear numSimul : ' + FloatToStr(numSimul),0);
{$ENDIF}
// initialisation des variables temporelles pour la nouvelle année
SetVal('Annee', GetVal('AnDebutSimul') + numSimul);
DecodeDate(GetVal('DebutSimul'), an, mois, jour);
SetVal('DebutSimul', EncodeDate(trunc(GetVal('AnDebutSimul')) + NumSimul,
mois, jour));
SetVal('FinSimul', GetVal('DebutSimul') + GetVal('MaxNbjSimule'));
thisDate := GetVal('DebutSimul');
//ShowMessage(DateToStr(thisDate)+' '+DateToStr(GetVal('FinSimul')));
except
AfficheMessageErreur('TSimule.InitDatesSimule | Classe ', UClasseSimule);
end;
end;
//----------------------------VN simcons-------------------------------------//
procedure TSimule.InitDatesSemis(const numSimul: Integer);
var
jour, mois, an: Word;
begin
try
//Si la date de semis est definie par l'utilisateur 3
//alors on initialise DateSemisCalc à cette valeur (+le nbre d'années simulées)
//sinon DateSemisCalc prend la valeur 0
if contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis') = nullValue
then
SetVal('DateSemisCalc', 0)
else
begin
DecodeDate(contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis'),
An, Mois, Jour);
SetVal('DateSemisCalc', EncodeDate(An + NumSimul, Mois, Jour));
end;
//Si la date de semis existe on l'initialise correctement
//sinon on la met à nullvalue
if contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis') <> nullValue
then
SetVal('NbJAS', thisdate - GetVal('DateSemisCalc'))
else
SetVal('NbJAS', nullValue);
//ShowMessage(DateToStr(contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis'))+' '+DateToStr(thisdate)+' '+DateToStr(GetVal('DateSemisCalc')));
except
AfficheMessageErreur('TSimule.InitDatesSemis | Classe ', UClasseSimule);
end;
end;
//--------------------------------------------------------------------------//
procedure TSimule.InitYear(const numSimul: Integer);
// Initialisation des variables qui changent pour chaque années et création
// de toutes les instances la première année sauf Crop (ou celle qui apparaissent
// en cours de simulation
var
jour, mois, an: Word;
i: Integer;
begin
try
{$IFDEF AffichageComplet}
MainForm.affiche((TimeToStr(Time) + #9 +
'TSimule2.InitYear numSimul : ' + FloatToStr(numSimul),0);
{$ENDIF}
// initialisation des variables temporelles pour la nouvelle année
SetVal('Annee', GetVal('AnDebutSimul') + numSimul);
DecodeDate(GetVal('DebutSimul'), an, mois, jour);
SetVal('DebutSimul', EncodeDate(trunc(GetVal('AnDebutSimul')) + NumSimul,
mois, jour));
SetVal('FinSimul', GetVal('DebutSimul') + GetVal('MaxNbjSimule'));
thisDate := GetVal('DebutSimul');
//ShowMessage(DateToStr(thisDate));
//contextObjet.ResetContextInstance(thisDate);
//contextObjet.GereCreationInstances(thisDate);
if numSimul = 0 then
begin
// creation des instances d'entite et Initialiser
DbModule1.RequeteInstance.Active := true;
DbModule1.RequeteInstance.First;
for i := 0 to DbModule1.RequeteInstance.RecordCount - 1 do
begin
// on créé une instance puis on la place dans le context
contextObjet.SetCurrentInstance(TEntityInstance.create(DBModule1.RequeteInstanceNomEntite.Value, thisDate, ''));
DbModule1.RequeteInstance.Next;
end;
DbModule1.RequeteInstance.Active := false;
end
// suppression de l'entite crop si on n'est pas à l'année 1
else // numSimul <> 0
begin
if contextObjet.GetCurrentInstance('Crop') <> nil then
contextObjet.FreeEntityInstance('Crop');
if DBLocateDate(thisDate) then
begin
for i := 0 to length(contextObjet.currentInstances) - 1 do
begin
if contextObjet.currentInstances[i] <> nil then
begin
contextObjet.currentInstances[i].MAJBookmark(thisDate);
contextObjet.currentInstances[i].MiseAZero(0);
contextObjet.currentInstances[i].myClass.MAJTappels(thisDate);
end;
end;
end;
end;
//VN Remplacement
{DecodeDate(contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis'),An,Mois,Jour);
SetVal('DateSemisCalc',EncodeDate(trunc(GetVal('AnDebutSimul'))+ NumSimul,Mois,Jour));
if contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis') = nullValue then
begin { TODO : Gestion des dates de semis inconnues a finaliser }{ TODO -oVB : à faire oui...
contextObjet.GetCurrentInstance('Plot').SetVal('DateSemis',GetVal('FinSimul'));
//contextObjet.GetCurrentInstance('Plot').SetVal('TypeSemis',2);
end
else
begin
//contextObjet.GetCurrentInstance('Plot').SetVal('TypeSemis',1);
DecodeDate(contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis'),An,Mois,Jour);
contextObjet.GetCurrentInstance('Plot').SetVal('DateSemis',EncodeDate(trunc(GetVal('AnDebutSimul'))+ NumSimul,Mois,Jour));
end;
SetVal('NbJAS',thisDate - contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis') );}
if contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis') = nullValue
then
SetVal('DateSemisCalc', 0)
else
begin
DecodeDate(contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis'),
An, Mois, Jour);
SetVal('DateSemisCalc', EncodeDate(An + NumSimul, Mois, Jour));
end;
if contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis') <> nullValue
then
SetVal('NbJAS', thisdate - GetVal('DateSemisCalc'))
else
SetVal('NbJAS', nullValue);
//AD SetVal('CodeParcelle',DBModule1.SimuleCodeParcelle.Value);
//ShowMessage(DateToStr(GetVal('FinSimul'))+' '+IntToStr(numSimul)+' '+DateToStr(thisDate)+' '+DateToStr(contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis')));
{$IFDEF AffichageComplet}
contextObjet.AfficheLesTEClasses();
contextObjet.AfficheLesTEInstances();
{$ENDIF}
except
AfficheMessageErreur('TSimule.InitYear | Numéro de simulation ' +
inttostr(numSimul), UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
/// Construit la liste des appels de procédures ainsi que la récupération
/// des paramètres nécessaires à chacun des appels de procédure ainsi créée.
{ TODO -oViB : Pourquoi SetList est rattaché à TSimule, il est mieux qu'il soit géré dasn TAppel }
procedure TSimule.SetList;
// Construction de la liste des appels (construit une fois pour toute). Cette liste ne contiendra pas les modules d'initialisation
var
aCallProc: TAppel;
j: Integer;
begin
try
// on ajoute l'appel au module 0, le module d'initialisation général
DBModule1.Module.Locate('CodeModule', 0, []);
aCallProc := TAppel.Create(DBModule1.Module.fieldbyname('CodeModule').Value,
DBModule1.Module.fieldbyname('CodeEntity').Value, 0,
DBModule1.Module.fieldbyname('NomModule').Value);
TabAppel.ajouter(aCallProc);
DBModule1.ModuleVar.First;
for j := 0 to DBModule1.ModuleVar.RecordCount - 1 do
begin
aCallProc.DefArgument(DBModule1.ModuleVarOrdre.Value,
TArgument.Create(DBModule1.EntiteNomEntite.Value,
DBModule1.DictionnaireVarNOMCOURS.Value));
aCallProc.DefParam(j, DBModule1.DictionnaireVarNOMCOURS.Value,
conversion(DBModule1.ModuleVarTypeParam.Value));
DBModule1.ModuleVar.Next;
end;
// ajout de tous les modules propres au modèle { TODO -oViB : Comment être assuré qu'on a déjà positionné le pointeur de la table modèle sur le bon modèle pour que la relation maitre détail filtre les modules? }
DBModule1.ModeleModule.First;
// Lecture de toutes les lignes de la table DBModele.Module .
// Pour chaque ligne :
// - trouve dans DBModule.Module la ligne ayant le meme CodeModule
// - cree l'instance TAppel correspondant
// - recupere les variables necessaires dans DBModuleVar (table dynamique)
while not dBModule1.ModeleModule.Eof do
begin
DBModule1.Module.Locate('CodeModule',
DBModule1.ModeleModuleCodeModule.Value, []);
aCallProc :=
TAppel.Create(DBModule1.Module.fieldbyname('CodeModule').Value,
DBModule1.Module.fieldbyname('CodeEntity').Value,
DBModule1.ModeleModule.fieldbyname('Step').Value,
DBModule1.Module.fieldbyname('NomModule').Value);
tabAppel.ajouter(aCallProc);
// Parcours des variables du module
// (car action du DBModule1.Module.Locate précédent soit application de la
// relation maitre détail entre ModuleVar et Module)
DBModule1.ModuleVar.First;
for j := 0 to DBModule1.ModuleVar.RecordCount - 1 do
begin
aCallProc.DefArgument(DBModule1.ModuleVarOrdre.Value,
TArgument.Create(DBModule1.EntiteNomEntite.Value,
DBModule1.DictionnaireVarNOMCOURS.Value));
aCallProc.DefParam(j, DBModule1.DictionnaireVarNOMCOURS.Value,
conversion(DBModule1.ModuleVarTypeParam.Value));
DBModule1.ModuleVar.Next;
end;
DBModule1.ModeleModule.Next;
end;
//DBModule1.ModeleModule.Next; { TODO -oViB : ké ké c'est que ça????????? }
except
AfficheMessageErreur('TSimule.SetList', UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
//AD procedure TSimule.BilanParcelle(codeSimule : Integer);
procedure TSimule.BilanParcelle(idSimule: string);
// Gestion du déroullement de la simulation :
// - Création des différentes classe
// - Création de la liste des appels
// - Initialisation de la simulation (module 0)
// - lancement de la simulation pour chaque année
var
i, j: Integer;
begin
try
CreationClasses; // Creation des classes (site, soil ...)
//tabClass.CreationClasses;
//SetTabAppels(idSimule,0);
SetList; // Création de liste des Tappels
//AssignFile(f,'D:\'+DBModule1.Simule.fieldbyname('Id').AsString+'0.txt');
//Rewrite(f);
//close(f);
RunModule(0); // Initialisation de l'objet simule
{ TODO -oViB : ATTENTION: il existe un UpdateData (dans DBModule) de la table
Simule qui met à 1 le nombre d'année si l'année de la date de fin de
simulation est égal à l'anné de fin de simulation }
j := Trunc(GetVal('NbAnSim')) - 1;
//Assign(f,'D:\Init.txt');
//Rewrite(f);
//close(f);
for i := 0 to j do // tant qu'on a pas atteint la derniere année
begin
Application.ProcessMessages;
if mainForm.butStopSimulation.Caption <> 'Arrêt en cours' then
begin
//tabAppel.writeAppels(i);
InitYear(i);
//InitDates(i);
//contextObjet.RunInitInstances;
//SimulAn;
numSimule2 := i + 1;
Aller(i + 1);
//VN save
while ContextSave.Count <> 0 do //on nettois les sauvegardes
begin
TContextSave(ContextSave.Objects[0]).Destroy;
ContextSave.Delete(0);
end;
while TabAppelSave.Count <> 0 do
begin
TTabAppelsSave(TabAppelSave.Objects[0]).Destroy;
TabAppelSave.Delete(0);
end;
//Append(f);
//WriteLn(f, '.');
//WriteLn(f);
//close(f);
//contextObjet.EmptyContextInstance;
end;
end;
except
AfficheMessageErreur('TSimule.BilanParcelle | Simulation ' + (idSimule),
UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
procedure TSimule.SimulAn;
// Permet la Gestion de la date de semis
begin
try
if GetVal('TypeSemis') = 2 then
begin
{if not PlanteTypeArachide then
begin
TrouveSemis;
ConfirmeSemis;
end
else
begin
TrouveDateSemisSurStock(DBModule1.SiteSeuilPluie.Value);
aSoil.InitDB(DBModule1.SimuleCodeParcelle.Value);
end;
aPlot.InitDB(DBModule1.SimuleCodeParcelle.Value);
aCrop.Harvest;
aSimule.myModele.SetList;}
end;
except
AfficheMessageErreur('TSimule.SimulAn', UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
procedure TSimule.ConfirmeSemis;
// Gestion de la date de semis
begin
try
{SetVal('Semis',thisDate);
If (GetVal('Semis')+ aPlante.TabState[cyclePot]
> aSimule.TabState[DateFinSimul])
then aSimule.TabState[Semis]:=
aSimule.TabState[DateFinSimul] -aPlante.TabState[cyclePot]; }
except
AfficheMessageErreur('TSimule.ConfirmeSemis', UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
procedure TSimule.RunModule(numModule: Integer);
// Procedure d'appel d'un module avec son numéro et le contexte associé à la simulation
begin
try
tabAppel.Executer(numModule, contextObjet);
except
AfficheMessageErreur('TSimule.RunModule | Module ' +
VarToStr(dBModule1.Module.Lookup('CodeModule', numModule, 'NomCours')) + ' ('
+ inttostr(numModule) + ')', UClasseSimule);
//on E: Exception do AfficheMessageErreur(E.message+'TSimule.RunModule | Module '+VarToStr(dBModule1.Module.Lookup('CodeModule',numModule,'NomCours'))+' ('+inttostr(numModule)+')',UClasseSimule);
end;
end;
//----------------------------------------------------------------------//
// Execute le module si la date d'execution correspond à la date en
// cours
//----------------------------------------------------------------------//
procedure TSimule.StepExe;
var
i: Integer;
begin
try
for i := low(tabAppel.listAppel) to high(tabAppel.listAppel) do
begin
//ShowMessage(DateToStr(tabAppel.listAppel[i].nextExe)+' '+DateToStr(thisDate));
if tabAppel.listAppel[i].nextExe = thisDate then
// si la date correspond à la date en cours alors on appelle le module
begin
//VN test
//if tabAppel.listAppel[i].stepExe=0 then
//begin
//Assign(f,'D:\test.txt');
//Append(f);
//WriteLn(f, inttostr(tabAppel.listAppel[i].id)+#9+datetostr(tabAppel.listAppel[i].nextExe)+#9+datetostr(thisDate)+#9+tabAppel.listAppel[i].classe.name+#9+dbmodule1.module.lookup('CodeModule',tabAppel.listAppel[i].id,'NomCours'));
//close(f);
//end;
//show:=(thisDate=EncodeDate(1950,02,14));
//if (tabAppel.listAppel[i].id=33229)and (thisDate=EncodeDate(1950,02,14))
//then ShowMessage('##########'+inttostr(tabAppel.listAppel[i].id)+' '+DateToStr(contextObjet.getcurrentInstance('Simulation').GetVal('DATEENCOURS')));
//ShowMessage(DateToStr(thisdate)+' '+IntToStr(i)+'/'+IntToStr(high(tabAppel.listAppel)));
runModule(tabAppel.listAppel[i].id);
//if (tabAppel.listAppel[i].id=33229) and (thisDate=EncodeDate(1997,09,15))
//if show
//then ShowMessage(inttostr(tabAppel.listAppel[i].id)+' '+DateToStr(contextObjet.getcurrentInstance('Simulation').GetVal('DATEENCOURS'))+' '+DateToStr(thisdate));
end;
end;
except
AfficheMessageErreur('TSimule.StepExe', UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
procedure TSimule.CalculNextExe;
// Calcule la date suivante et met à jour le tableau des appels.
// Pour chaque module dont la date d'execution correspond à la date en
// cours, on fait passer la date d'execution au prochain pas de temps
// Ex: pour des modules mensuels, le 31/03 donne 30/04
var
i: Integer;
step: Real;
DateExe: TdateTime;
Year, Month, Day: Word;
begin
try
for i := 0 to length(tabAppel.listAppel) - 1 do
begin
// si la date correspond à la date en cours alors on calcule la prochaine date d'execution en fonction du step
if tabAppel.listAppel[i].nextExe = thisDate then
begin
DateExe := thisDate; //Edit VN debug
step := tabAppel.listAppel[i].stepExe;
if (Step = 1) then // DateExe := IncDay(DateExe,trunc(Step));
DateExe := IncrementeDate(tabAppel.listAppel[i].nextExe, step,
calendaire);
//if (step >1) and (step <> 0) then //
if step > 1 then // ViB le 27/02/2004
begin { TODO : Fait péter toute gestion d'un pas différent de mensuel, revoir la condition pour le 5, 10 et 15 jours) }
//if (DayOfTheMonth(IncDay(thisDate,Trunc(Step))) > 27) then // ViB le 01/03/2004
begin
if ModeDebug then
mainForm.affiche(TimeToStr(Time) + #9 +
'#### ---> Date: ' + datetostr(thisDate) + ' pas: ' +
floattostr(step),0);
//DecodeDate(EndOfTheMonth(IncDay(thisDate,Trunc(Step))),Year,Month,Day); // ViB 26/02/2004
DecodeDate(EndOfTheMonth(thisDate), Year, Month, Day);
Inc(Month); // ViB le 01/03/2004
if Month = 13 then // ViB le 01/03/2004
begin // ViB le 01/03/2004
Month := 1; // ViB le 01/03/2004
Inc(Year); // ViB le 01/03/2004
end; // ViB le 01/03/2004
Day := DayOfTheMonth(EndOfAMonth(Year, Month)); // ViB le 01/03/2004
DateExe := EncodeDate(Year, Month, Day);
//if modeDebugPrecis then mainForm.memDeroulement.Lines.add(tabAppel.listAppel[i].theProc.name+ '--> prochaine exécution: '+datetostr(DateExe)); // ViB le 01/03/2004
end;
// else
{ DateExe := IncDay(DateExe,trunc(Step));
DecodeDate(DateExe,Year,Month,Day);
Day := Trunc(DayOfTheMonth(DateExe)+step-1);
If Day > 27 then Day := DayOfTheMonth(EndOfAMonth(Year,Month));
DateExe := EncodeDate(Year,Month,Day); }
end; // fin if (step >1) and (step <> 0) then
tabAppel.listAppel[i].nextExe := DateExe;
{if step=0 then //VN debug simcons
begin
Assign(f,'D:\init next exe.txt');
Append(f);
WriteLn(f, inttostr(tabAppel.listAppel[i].id)+#9+datetostr(tabAppel.listAppel[i].nextExe)+#9+datetostr(thisDate)+#9+tabAppel.listAppel[i].classe.name+#9+dbmodule1.module.lookup('CodeModule',tabAppel.listAppel[i].id,'NomCours'));
close(f);
end;}
end // fin if tabAppel.listAppel[i].nextExe = thisDate then
//else
//if tabAppel.listAppel[i].id=33226 then ShowMessage(dateToStr(tabAppel.listAppel[i].nextExe)+' '+dateToStr(thisDate));
end; // fin for i:= 0 to length(tabAppel.listAppel)-1 do
except
AfficheMessageErreur('TSimule.CalculNextExe', UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
procedure TSimule.Aller(const numSimule: integer);
// Gère le déroullement de la simulation :
// On récupère d'abord le plus petit pas de temps de tous les modules
// Ensuite tant qu'on a pas atteint la date de fin de simulation :
// - on execute les modules
// - on change la date de la prochaine execution
// - on incremente la date en cours avec le plus petit pas de temps
// - on fait passer les bookmarks sur l'enregistrement suivant
var
dateFin, semis: TDateTime;
i: Integer;
test: Double;
jour, mois, an, anPrec: Word;
begin
try
// recuperation de la date de fin de la simulation
dateFin := GetVal('FinSimul');
//VN déplacé dans la boucle
//semis := GetVal('DateSemisCalc');
anPrec := 0;
// requete qui renvoie le plus petit pas de temps
DBModule1.RequeteStep.Active := true;
DBModule1.RequeteStep.First;
minorStep := DBModule1.RequeteStepMINOFstep.Value;
DBModule1.RequeteStep.Active := false;
//ShowMessage(floattostr(contextObjet.GetCurrentInstance('Soil').GetVal('ArriveeEauJour')));
//ShowMessage('###'+IntToStr(tabAppel.listappel[0].id)+' '+IntToStr(tabAppel.listappel[0].stepExe)+' '+dateToStr(tabAppel.listappel[0].nextExe)+' '+DateToStr(thisDate));
// boucle tant que la date courante thisDate n'a pas atteind la date de fin
while thisDate <= dateFin do
begin
DecodeDate(thisDate, an, mois, jour);
//VN contraintes
Pars.SetVariable('Dateencours', thisDate);
Pars.SetVariable('DebutSimul', thisdate);
Pars.SetVariable('finsimul', dateFin);
semis := GetVal('DateSemisCalc');
//VN contraintes
//if contextObjet.GetCurrentInstance('Soil').GetVal('ArriveeEauJour') = 0 then ShowMessage('zero');
if anPrec <> an then
// si l'annee precedente est differente de l'annee courante on l'initialise comme etant égal a l'annee courante
begin
anPrec := an;
mainForm.Label2.Caption := FormatDateTime('hh:mm:ss', Time - Duree) +
' - Num. simulation: ' + IntToStr(NumSimulation) + ' - Simulation: ' +
DBModule1.Simule.findfield('Id').AsString + #9 + ' - Année: ' +
IntToStr(an);
end;
//VN saveSemis
//if (thisDate = semis) then
if (contextObjet.GetCurrentInstance('Crop') = nil) and (thisDate = semis)
then // Création de crop si on est arrivé à la date de semis on place l'instance de Crop dans le context
begin
//ShowMessage(DateToStr(GetVal('DateSemisCalc')));
contextObjet.SetCurrentInstance(TEntityInstance.Create('Crop', thisDate,
dbmodule1.Variete.findfield('id').AsVariant));
end;
// S'il existe une instance de type Crop <=> a partir du moment ou il y a eu le semis
if not (contextObjet.GetCurrentInstance('Crop') = nil) then
begin
test := contextObjet.GetCurrentInstance('Crop').GetVal('NumPhase');
//dateEnStr := FormatDateTime('dd:mm',contextObjet.GetCurrentInstance('Crop').GetVal('DateMaturite'));
// Si le numero de la phase de l'instance de Crop est 7
// Destruction de l'entité Crop car elle est a Maturité on place l'instance de Crop dans le context
if contextObjet.GetCurrentInstance('Crop').GetVal('NumPhase') = 7 then
contextObjet.FreeEntityInstance('Crop');
end; // fin : test sur existence d'une instance de Crop
//Ajout VN simcons
contextObjet.RunInitInstances;
//Lance les modules d'initialisation si il faut le faire.
//tabAppel.writeAppels(0);
{Assign(f,'D:\Suivi.txt');
Append(f);
acall:=tabAppel.listappel[5];
WriteLn(f, inttostr(acall.stepExe)+#9+inttostr(acall.id)+#9+datetostr(acall.nextExe)+#9+datetostr(TSimule(contextObjet.GetCurrentInstance('Simulation')).thisDate)+#9+acall.classe.name+#9+dbmodule1.module.lookup('CodeModule',acall.id,'NomCours'));
close(f);}
//ShowMessage(DBModule1.Resjour.FieldByName('ArriveeEauJour_out').AsString+' '+floattostr(contextObjet.GetCurrentInstance('Soil').GetVal('ArriveeEauJour'))+' '+floattostr(contextObjet.GetCurrentInstance('Plot').GetVal('ArriveeEauJour_out')));
StepExe; // parcours du tableau et execution des modules selon leur pas de temps
CalculNextExe; // parcours du tableau et mise à jours de la prochaine date d'execution des modules
// Passage à l'enregistrement suivant A modifier pour adapter au pas de temps
if DBModule1.Forcage.RecordCount <> 0 then
begin
for i := 0 to length(DBModule1.DynamicTables) - 1 do
DBModule1.DynamicTables[i].Next;
end;
thisDate := thisDate + MinorStep; // passage au pas de temps suivant
//VN simcons (permet la manipulation de la fin de simul dans les modules)
DateFin := GetVal('FinSimul');
if thisDate <> DateFin then
begin
//if (thisDate - Semis>0) and (thisDate - Semis<10) then ShowMessage(DateToStr(thisDate)+' '+DateToStr(semis));
SetVal('DateEnCours', thisDate);
//ShowMessage(DateToStr(thisDate));
MAJBookmarks(numSimule); // Mise à jour des TAccessRecords
SetVal('NbJAS', thisDate - Semis);
end;
//ShowMessage(DateToStr(thisDate)+' '+DateToStr(GetVal('DateEnCours')));
Application.ProcessMessages;
if mainForm.butStopSimulation.Caption = 'Arrêt en cours' then
thisDate := DateFin + 1;
end; // fin du while thisDate <= dateFin do
//VN save: Dans le cas de semis calculé on remet à jour la variable nbjas dans resjour
// Finaliser le choix forcer ou calculer une date de semis....
// Modif CB 02/06 ne fiare MajNbjAs que si date semis calculee
if contextObjet.GetCurrentInstance('Plot').GetVal('DateSemis') = nullValue
then
// Modif CB 02/06
majNbJas(GetVal('DateSemisCalc'), getval('DebutSimul'), dateFin - 1);
except
on e: Exception do
AfficheMessageErreur(e.message + 'TSimule.Aller', UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
procedure TSimule.MajBookmarks(const numSimule: integer);
// Mise à jour des bookmark pour chaque table si la date correspond :
// - si la table est en read only : on passe à l'enregistrement suivant et on met à jour le bookmark
// - si la table n'est pas en read only : on recopie le dernier enregistrement et on met à jour le bookmark
// Enfin, on met à jour la date du prochain changement
var
i, j: Integer;
jour, mois, anprec, an: Word;
DateRel: TDateTime;
begin
{ TODO : Il faut faire un test d'existance d'enregistrement lors du chgt de bookmark
s'il n'y a pas d'enregistrement pour cette date cas de l'irrigation
on filtre la table et par defaut elle pointe sur une enregistrement vide
ce qui n'est pas le cas du Locate.... }
try
// boucle sur la liste des TEntityInstance presente dans contextObjet
//ShowMessage(DateToStr(thisdate));
for i := 0 to length(contextObjet.currentInstances) - 1 do
begin
if contextObjet.currentInstances[i] <> nil then
// si l'instance n'est pas à nil (crop créée plus tard)
begin
for j := 0 to length(contextObjet.currentInstances[i].InOutTables) - 1 do
// parcours des tables utilisées par les paramètres des champs
begin
//ShowMessage(contextObjet.currentInstances[i].InOutTables[j].myTable.TableName);
with (contextObjet.currentInstances[i].InOutTables[j]) do
begin
//If MyStep=-2 then ShowMessage(DateToStr(nextDate)+' '+DateToStr(thisDate));
if (myStep <> 0) and (NextDate = thisDate) then
// si la date en cours correspond a la date de lecture dans la bdd et qu'on travaille bien sur une table que l'on doit lire à chaque pas de simulation (car dans les autres cas, Step=0 pour Espèce, Variété, Station...)
begin
if ReadOnly then
// si la table est en mode ReadOnly (on est danc dans le cas de la climato, l'irrigation, ObsParcelle...)
begin
// le pas n'est pas continu et c'est la date du champ "Jour" qui devient la référence (donc forcément il existe un champ "Jour")
//Edit VN
{if MyTable.FieldByName('Jour').AsDateTime = Thisdate then
NextDate := IncrementeDate(NextDate,MinorStep,true) { TODO : Revoir le calendaire, tjs forcé à vrai!
else
begin
myTable.Next;
If (myStep=-2) and (myTable.RecNo<>myTable.RecordCount) then //VN v2.0
begin
myTable.Next;
nextDate := MyTable.FieldByName('Jour').AsDateTime;
myTable.Prior;
end
else nextDate := MyTable.FieldByName('Jour').AsDateTime;
//MyTable.FieldByName('Jour').AsDateTime;
myBookMark := myTable.GetBookmark;
end;}
if MyStep < 0 then
begin
//VN debug ajout du if, on est jamais trop prudent
if myStep = -1 then
myTable.Filtered := false;
myTable.GotoBookmark(myBookMark);
//If (myStep=-2) then ShowMessage(DateToStr(MyTable.FieldByName('Jour').AsDateTime));
if (mystep = -1) then
begin
if (MyTable.FieldByName('Jour').AsDateTime = Thisdate) then
NextDate := IncrementeDate(NextDate, MinorStep, true)
{ TODO : Revoir le calendaire, tjs forcé à vrai! }
else
begin
myTable.Next;
nextDate := MyTable.FieldByName('Jour').AsDateTime;
//MyTable.FieldByName('Jour').AsDateTime;
//myTable.FreeBookmark(myBookMark);
myBookMark := myTable.GetBookmark;
end;
end
else if (myStep = -2) then //VN Table
begin
myTable.Next;
//on passe à l'enregistrement suivant (qui normalement est le bon)
if myTable.Eof then
myTable.First;
//si c'est la dernière date de la table, on fait boucler.
//myTable.FreeBookmark(myBookMark);
myBookMark := myTable.GetBookmark;
//On mémorise le nouvel enregistrement.
//........................................................................
//on va alors chercher la date de prochaine execution
anprec := yearof(MyTable.FieldByName('Jour').AsDateTime);
myTable.Next;
if myTable.Eof then
myTable.First;
DecodeDate(MyTable.FieldByName('Jour').AsDateTime, an, mois,
jour);
DateRel := EncodeDate(yearof(Thisdate) + an - anprec, mois,
jour);
//on récupere la date relative
//ShowMessage(DateToStr(MyTable.FieldByName('Jour').AsDateTime)+' '+DateToStr(DateRel)+' '+DateToStr(thisdate));
nextDate := DateRel;
//on met à jour la date de prochaine mise a jour
myTable.GotoBookmark(myBookMark);
//puis on retourne au bon enregistrement
end; //if mystep=-2
if myTable.Name = 'Irrigation' then
myTable.Filter := 'Id=''' +
dBModule1.ItineraireTechnique.fieldByName('IdIrrigation').Value + ''' and Jour=' + QuotedStr(DateToStr(thisDate));
//AD else myTable.Filter :='Id='''+dBModule1.Simule.fieldByName('IdDonnesObs').Value+''' and Jour='+QuotedStr(DateToStr(thisDate));
//AD myTable.Filter := Jour = ' + QuotedStr(DateToStr(thisDate));
if MyStep = -1 then
myTable.Filtered := True; //VN table
end
else // le pas est constant (MyStep <> -1) { TODO : D'autres cas existent.... step=0... quelle conséquence même s'il on ne doit jamais se trouver dans ce cas... }
begin // on passe simplement à l'enregistrement suivant (espérons donc que les enregistrements sont continu)
// temp: modifs annulées pour tester la dérivation vers les 2 tempPluvio et tempMeteo
//[AVANT MODIF] // mis en comentaire ViB 10/01/2008 on ne veut pas de next ssi on est sur Pluviométrie (pb de ralentissement lorsqu'on dérive la climato)
myTable.next; // Test de correspondance des dates
//[APRES MODIF]
//if mytable.Name<>'Climatologie' then myTable.next; // ajout ViB 10/01/2008
//[FIN MODIF]
if (myTable.FieldByName('Jour').AsDateTime = thisDate) then
begin
// myTable.FreeBookmark(myBookMark);
myBookMark := myTable.GetBookmark;
end
else
begin { TODO -cb: FINALISER test données absentes et quel contrôles ??? }
// faire un locate et si cela ne marche pas on pointe sur Nil
MainForm.affiche(TimeToStr(Time) + #9 +
'##---' + DateToStr(myTable.FieldByName('Jour').AsDateTime) +
' ' + DateToStr(thisDate) + ' PAS DE DONNEES POUR la table '
+ myTable.name + ' pour le ' + DateTimeToStr(thisDate),0);
Main.erreur := true;
// MyBookMark := Nil; // voir a utiliser en test { TODO -oViB: ah oui...? et quelle conséquences si on fait ça (nil) ??? }
end;
NextDate := IncrementeDate(NextDate, MyStep, true);
{ TODO : Revoir le calendaire, forcé à vrai! }
end; // If MyStep = -1
end //if ReadOnly
else // La table MyTable n'est pas en lecture seule (ReadOnly=false) donc c'est ResJour, ResCum etc...
begin
// ##### On recopie le dernier enregistrement de MyTable en incrementant l'index (forcement une date car ReadOnly=faux et donc il s'agit de ResJour/ResCum... fin non :-( )
MyTable.gotoBookmark(MyBookMark);
RecopieEnreg(MyTable, thisDate, myStep, numsimulation);
// voir apres comment gerer le pb la on fait comme pour la sensibilite Resjour dans DBAnalyse peut pas rester ainsi cause 20000 itereations!!!!
// myTable.FreeBookmark(myBookMark);
myBookMark := myTable.GetBookmark;
// nécessaire car on a forcement bougé d'enregistrement dans RecopieEnreg vu qu'on vient de créer un nouvel enregistrement
NextDate := IncrementeDate(NextDate, MyStep, true);
{ TODO : Revoir le calendaire, tjsforcé à vrai! }
end; // calcul de la prochaine date de lecture/ecriture dans la bdd améliorer IncrementeDate
end; // if (Mystep <> 0) and (NextDate = thisDate)
end; // With (contextObjet.currentInstances[i].InOutTables[j] do
end; // for j:= 0 to length(contextObjet.currentInstances[i].InOutTables)-1 do
end; //if contextObjet.currentInstances[i] <> nil then
end; //For i := 0 to length(contextObjet.currentInstances)-1 do
except
on E: Exception do
AfficheMessageErreur(E.message + ' TSimule.MajBookmarks', UClasseSimule);
//AfficheMessageErreur('TSimule.MajBookmarks',UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
function TSimule.conversion(x: string): TEnumTypeParam;
{ TODO -oViB : Pourquoi est-ce un méthode de TSimule???? }
// Renvoie le type du parametre
begin
try
if lowercase(x) = 'in' then
result := KIn;
if lowercase(x) = 'out' then
result := KOut;
if lowercase(x) = 'inout' then
result := KInOut;
except
AfficheMessageErreur('TSimule.conversion | Type de paramètre ' + x,
UClasseSimule);
end;
end;
//----------------------------------------------------------------------------//
//Ajout VN contraintes
procedure TSimule.MajInVar_ToPars(InIndice: array of Shortint; TabParam: array of
ModelsManage.TParam; ParamVal: ModelsManage.TPointeurProcParam);
var
i: integer;
begin
for i := 0 to high(InIndice) do
begin
//ShowMessage(TabParam[InIndice[i]].Name+' '+FloatToStr(ParamVal[InIndice[i]]));
pars.SetVariable(TabParam[InIndice[i]].getName, ParamVal[InIndice[i]]);
end;
end;
procedure TSimule.MajOutVar_ToProcParam(OutIndice: array of Shortint; TabParam:
array of ModelsManage.TParam; var ParamVal: ModelsManage.TPointeurProcParam);
var
i: integer;
begin
for i := 0 to high(OutIndice) do
begin
ParamVal[OutIndice[i]] := pars.GetVariable(TabParam[OutIndice[i]].getName);
end;
end;
procedure TSimule.majNbJas(dateSemis, dateDebut, datefin: TDateTime);
//Met à jour la variable nbJas pour l'années simulée
//Utile surtout aprés un calcul automatique de la date de semis
begin
try
DBModule1.queGenerique.Close;
DBModule1.queGenerique.SQL.Clear;
DBModule1.queGenerique.SQL.Add('Update '':DBResult:Resjour.db'' Set nbJas = jour-''' + FormatDateTime('mm/dd/yyyy', dateSemis) + ''' where jour>=''' +
FormatDateTime('mm/dd/yyyy', dateDebut) + '''and jour<=''' +
FormatDateTime('mm/dd/yyyy', dateFin) + ''';');
DBModule1.queGenerique.ExecSQL;
except
on e: exception do
AfficheMessageErreur('setNbJas ' + e.Message, UClasseSimule);
end
end;
//Fin Ajout VN
//-------------------------------------------------------------------------//
// Cette procédure va permettre d'appeler toute la chaîne d'initialisation
// des variables se rapportant à l'objet simulation
//-------------------------------------------------------------------------//
procedure InitializationDyn(var tabParam: TPointeurProcParam);
begin
try
{ TODO -ofred : trouver un moyen pour enlever aSimulation dans aSimulation.InitSimulation }
aSimulation.InitSimulation(tabParam[0], tabParam[1], tabParam[2],
tabParam[3], tabParam[4], tabParam[5], tabParam[6],
tabParam[7], tabParam[8], tabParam[9], tabParam[10], tabParam[11]);
except
AfficheMessageErreur('InitializationDyn', UClasseScenario);
end;
end;
//Ajout VN contraintes
//Charge les contraintes dans TabProc
procedure InitProcContrainte();
var
req: TQuery;
begin
try
req := TQuery.Create(nil);
req.Active := false;
req.SQL.Clear;
req.SQL.add('Select m.nomCours,m.NomModule,m.librairie');
req.SQL.add('from '':DBModele:Module.db'' m');
req.SQL.add('where m.Librairie not in (select NomUnite from '':DBModele:ListeLibrairie.db'');');
req.Active := true;
req.First;
while not req.Eof do
begin
tabProc.AjoutProcContrainte(req.findfield('NomModule').AsString,
LoadConstraintFromFile(req.findfield('NomCours').AsString,
req.findfield('librairie').AsString));
req.Next;
end;
req.Destroy;
Clean;
//nettoie les variable utilisés par l'unité contrainte.
except
AfficheMessageErreur('InitProcContrainte', UClasseSimule);
end;
end;
procedure SaveSimulation(var DoSave: Double; const CodeSave: Double);
var
index: integer;
begin
try
if DoSave = 1 then
begin
//ShowMessage('save '+DateToStr(CodeSave)+' '+DateToStr(aSimulation.thisDate));
DoSave := 0;
aSimulation.SetVal('DoSave', 0);
//Avant de sauvegarder on remet la demande de sauvegarde à 0
index := aSimulation.ContextSave.IndexOf(FloatToStr(CodeSave));
if index >= 0 then
begin
TContextSave(aSimulation.ContextSave.objects[index]).Free;
aSimulation.ContextSave.Delete(index);
TTabAppelsSave(aSimulation.TabAppelSave.objects[index]).Free;
aSimulation.TabAppelSave.Delete(index);
end;
//On efface une éventuelle sauvegarde qui aurait le même code
aSimulation.ContextSave.AddObject(FloatToStr(CodeSave),
TContextSave.Create(contextObjet));
aSimulation.TabAppelSave.AddObject(FloatToStr(CodeSave),
TTabAppelsSave.Create(tabAppel));
//Création des sauvegardes à partir des objets à sauvegarder
end;
except
on E: Exception do
AfficheMessageErreur('SaveSimulation ' + E.Message, UClasseSimule);
end;
end;
procedure LoadSimulation(var DoLoad, nbLoaded: Double; const CodeSave: Double);
var
index: integer;
saveCtxte: TContextSave;
saveTabappel: TTabAppelsSave;
begin
try
if DoLoad = 1 then
begin
//ShowMessage('load '+DateToStr(CodeSave)+' '+DateToStr(aSimulation.thisDate));
index := aSimulation.ContextSave.IndexOf(FloatToStr(CodeSave));
if index >= 0 then
begin
//ShowMessage(DateToStr(aSimulation.thisdate));
saveCtxte := TContextSave(aSimulation.ContextSave.objects[index]);
//on récupere la sauvegarde du Tcontext qui correspond au code de sauvegarde
saveCtxte.UseSave(contextObjet);
//on utilise cette sauvegarde pour écrase les valeurs du contexte en cours
saveTabappel := TTabAppelsSave(aSimulation.TabAppelSave.objects[index]);
//on récupere la sauvegarde du TtabAppel qui correspond au code de sauvegarde
saveTabappel.UseSave(tabAppel);
//on utilise cette sauvegarde pour écrase les valeurs du contexte en cours
aSimulation.thisDate := aSimulation.GetVal('DATEENCOURS');
//on met à jour la variable indépendant des TentityInstance sujette à modification
aSimulation.Pars.SetVariable('DATEENCOURS',
aSimulation.GetVal('DATEENCOURS'));
//maj de la date en cours du parser
nbLoaded := nbLoaded + 1;
//on incrémente le nombre de chargement effectué
//ShowMessage(DateToStr(aSimulation.thisdate));
end;
//else AfficheMessageErreur('LoadSimulation | sauvegarde '+ FloatToStr(CodeSave) +'inexistante',UClasseSimule);
DoLoad := 0;
//on efface la demande de chargement pour ne pas recharger
end
else
nbLoaded := 0;
except
on E: Exception do
AfficheMessageErreur('LoadSimulation ' + e.Message, UClasseSimule);
end;
end;
//calcule la date de semis et déclanche la sauvegarde ou le chargement
procedure CalcSemisAuto(var nbJStress, DoLoad, Dosave, DateSemisCalc: Double;
const nbJTestSemis, StressResistance, seuilStress, Cstr, DateEnCours,
SeuilEauSemis, eauDispo: Double);
begin
try
//Si la plante n'existe pas et que le seuil de pluie est atteint
//alors on lance la sauvegarde et on initialise la date de semis
// Nota permet
// des semis consécutifs sur une longue saison pluvieuse cas Benin cote d'ivoire
if (contextObjet.GetCurrentInstance('Crop') = nil) then
begin
if (eauDispo > SeuilEauSemis) then
begin
DoSave := 1;
DateSemisCalc := DateEnCours;
nbJStress := 0;
end;
end
else
begin
if (DateEnCours < DateSemisCalc + nbJTestSemis) then
begin
if (Cstr < seuilStress) then
nbJStress := nbJStress + 1;
if nbJStress > StressResistance then
begin
DoLoad := 1;
end;
end
// A resoudre MAjNbJAS si test Ok... Fait dans proc TSimule.Aller
// if (DateEnCours=DateSemisCalc+nbJTestSemis) then majNbJas(DateEnCours);
//Si on a trouvé la bonne date de semis on met à jour les nbjas
end;
except
on E: Exception do
AfficheMessageErreur('CalcSemisAuto ' + e.Message, UClasseSimule);
end;
end;
//seme si la date de Semis est égale à la date courante
procedure Seme(const DateSemisCalc, DateEnCours: Double);
begin
try
if DateSemisCalc = DateEnCours then
//si on est à une date de semis alors on seme
begin
contextObjet.SetCurrentInstance(TEntityInstance.Create('Crop',
DateEnCours, dbmodule1.Variete.findfield('id').AsVariant));
//showMessage(DateToStr(DateSemisCalc));
end;
except
on E: Exception do
AfficheMessageErreur('Seme ' + e.Message, UClasseSimule);
end;
end;
procedure SemeDyn(var tabParam: TPointeurProcParam);
begin
Seme(tabParam[0], tabParam[1]);
end;
procedure CalcSemisAutoDyn(var tabParam: TPointeurProcParam);
begin
CalcSemisAuto(tabParam[0], tabParam[1], tabParam[2], tabParam[3], tabParam[4],
tabParam[5], tabParam[6], tabParam[7], tabParam[8], tabParam[9],
tabParam[10]);
end;
procedure LoadSimulationDyn(var tabParam: TPointeurProcParam);
begin
LoadSimulation(tabParam[0], tabParam[1], tabParam[2]);
end;
procedure SaveSimulationDyn(var tabParam: TPointeurProcParam);
begin
SaveSimulation(tabParam[0], tabParam[1]);
end;
//Fin Ajout VN
//-------------------------------------------------------------------------//
// chargement de la procédure d'initialisation
//-------------------------------------------------------------------------//
initialization
{AjoutVN}InitProcContrainte();
tabProc.AjoutProc('Initialization', InitializationDyn);
{AjoutVN}tabProc.AjoutProc('SaveSimulation', SaveSimulationDyn);
{AjoutVN}tabProc.AjoutProc('LoadSimulation', LoadSimulationDyn);
{AjoutVN}tabProc.AjoutProc('CalcSemisAuto', CalcSemisAutoDyn);
{AjoutVN}tabProc.AjoutProc('Seme', SemeDyn);
end.
|
unit ideSHConsts;
interface
const
IMG_DEFAULT = 0;
IMG_PACKAGE = 89; // 62
IMG_SERVER = 87; // 69
IMG_SERVER_CONNECTED = 70;
IMG_DATABASE = 71;
IMG_DATABASE_CONNECTED = 72;
IMG_FORM_SIMPLE = 73;
IMG_COMPONENT_EDITOR = 74;
IMG_DBSTATE_SOURCE = 75;
IMG_DBSTATE_ALTER = 76;
IMG_DBSTATE_RECREATE = 77;
IMG_DBSTATE_DROP = 78;
IMG_DBSTATE_CREATE = 79;
IMG_FORM_READY = 80;
IMG_FORM_LOADED = 81;
IMG_FORM_CURRENT = 82;
IMG_MEGA_EDITOR = 84;
resourcestring
{$I ..\..\.ver}
SAppCommunityComment = 'This software is licensed royalty free under the condition that users refer all functional issues to the development team';
SAppEnterpriseComment = '';
SApplicationTitle = 'BlazeTop';
SProjectHomePage = 'http://www.devrace.com';
SProjectHomePage2 = 'http://www.blazetop.com';
SProjectSupportAddr = 'http://www.devrace.com/en/support/';
SProjectForumEngPage = 'http://www.devrace.com/en/support/forum/list.php?FID=10';
SProjectForumRusPage = 'http://www.devrace.com/ru/support/forum/list.php?FID=9';
SProjectFeedbackAddr = 'http://www.devrace.com/en/support/ticket_list.php';
SInterBaseHomePage = 'http://www.borland.com/interbase/';
SFirebirdHomePage = 'http://www.firebirdsql.org';
SFeedbackCaption = 'BlazeTop Feedback';
SFeedbackText = 'Feedback Text Here';
SCaptionButtonOK = 'OK';
SCaptionButtonCancel = 'Cancel';
SCaptionButtonHelp = 'Help';
SCaptionButtonSave = 'Save';
SCaptionButtonClose = 'Close';
SCaptionButtonRestore = 'Restore';
SCaptionButtonTerminate = 'Terminate';
SWarning = 'Warning';
SError = 'Error';
SInformation = 'Information';
SConfirmation = 'Confirmation';
SQuestion = 'Question';
SMemoryAvailable = 'Memory Available to Windows: %s KB';
SDirRoot = '..\';
SDirBin = '..\Bin\';
SDirData = '..\Data\';
SDirImages = '..\Data\Resources\Images\';
SFileErrorLog = '..\Data\Environment\ErrorLog.txt';
SFileConfig = '..\Data\Environment\Config.txt';
SFileConfigBackup = '..\Data\Environment\Config.old.txt';
SFileAliases = '..\Data\Environment\Aliases.txt';
SFileAliasesBackup = '..\Data\Environment\Aliases.old.txt';
SFileEnvironment = '..\Data\Environment\Options.txt';
SFileForms = '..\Data\Environment\Forms.txt';
SPathKey = '$(BLAZETOP)';
SSectionLibraries = 'LIBRARIES';
SSectionPackages = 'PACKAGES';
SSectionOptions = 'OPTIONS';
SSectionSystem = 'SYSTEM';
SSectionForms = 'FORMS';
SSectionRegistries = 'REGISTRIES';
SCaptionDialogOptions = 'Environment Options';
SCaptionDialogConfigurator = 'Environment Configurator';
SCaptionDialogInstallLibrary = 'Install Libraries';
SCaptionDialogInstallPackages = 'Install Packages';
SCaptionDialogDetailPackages = 'Detail Packages Information';
SCaptionDialogObjectList = 'View Objects';
SCaptionDialogComponentList = 'Components';
SCaptionDialogWindowList = 'Window List';
SCaptionDialogLostConnection = 'Lost Connection';
SCaptionDialogRestoreConnection = 'Restore Connection';
SNothingSelected = '(nothing selected)';
SNone = '< none >';
SUnknown = '< unknown >';
SSubentryFrom = 'Please select a subentry from the list';
SSystem = 'System';
SRegistryLineBreak = #14#11;
implementation
end.
|
Unit Shoot_gameUnit;
Interface
Uses CRT, Graph;
Type
Cordr=record
x,y:integer;
end;
TMark=object
x,y,side,color:integer;
Hit:boolean;
procedure Init(ax,ay,aside,acolor:integer);
procedure Destroy;
procedure Create;
procedure Check(ax,ay,ar:integer);
end;
TBullet=object
x,y,ys,r,color:integer;
speed:cordr;
procedure Init(ax,ay,ar,asx,acolor:integer);
procedure Destroy;
procedure Create(ax,ay:integer);
procedure Move;
procedure Speedx(ax:integer);
procedure Speedy(ay:integer);
end;
Implementation
procedure TMark.Init(ax,ay,aside,acolor:integer);
begin
x:=ax;
y:=ay;
side:=aside;
color:=acolor;
Hit:=false;
end;
procedure TBullet.Init(ax,ay,ar,asx,acolor:integer);
begin
x:=ax;
y:=ay;
r:=ar;
speed.x:=asx;
speed.y:=0;
color:=acolor;
end;
procedure TMark.Destroy;
begin
SetColor(0);
Rectangle(x,y,x+side,y+side);
Hit:=true;
end;
procedure TBullet.Destroy;
begin
SetColor(0);
Circle(x,y,r);
end;
procedure TMark.Create;
begin
SetColor(color);
Rectangle(x,y,x+side,y+side);
Hit:=false;
end;
procedure TBullet.Create(ax,ay:integer);
begin
Destroy;
SetColor(color);
x:=ax;
y:=ay;
Circle(x,y,r);
end;
procedure TMark.Check(ax,ay,ar:integer);
var x1,x2,y0:integer;
begin
x1:=ax-ar;
x2:=ax+ar;
y0:=ay-ar;
if (y0<=y+side) and (y0>=y) then
if (x1>=x) and (x2<=x+side) then
begin
Destroy;
Hit:=true;
end;
end;
procedure TBullet.Move;
begin
Destroy;
x:=x+speed.x;
if (speed.y=0) then
ys:=y
else
ys:=ys+speed.y;
if (x>GetMaxX) then
x:=1;
if (ys<0) then
ys:=0;
Create(x,ys);
end;
procedure TBullet.Speedx(ax:integer);
begin
x:=1;
ys:=y;
speed.x:=ax;
speed.y:=0;
end;
procedure TBullet.Speedy(ay:integer);
begin
speed.y:=-ay;
speed.x:=0;
end;
end.
|
unit uXBits;
{$I ..\Include\IntXLib.inc}
interface
type
/// <summary>
/// Contains helping methods to work with bits in dword (UInt32).
/// </summary>
TBits = class sealed(TObject)
public
/// <summary>
/// Returns number of leading zero bits in int.
/// </summary>
/// <param name="x">UInt32 value.</param>
/// <returns>Number of leading zero bits.</returns>
class function Nlz(x: UInt32): Integer; static;
/// <summary>
/// Counts position of the most significant bit in int.
/// Can also be used as Floor(Log2(<paramref name="x" />)).
/// </summary>
/// <param name="x">UInt32 value.</param>
/// <returns>Position of the most significant one bit (-1 if all zeroes).</returns>
class function Msb(x: UInt32): Integer; static;
/// <summary>
/// Ceil(Log2(<paramref name="x" />)).
/// </summary>
/// <param name="x">UInt32 value.</param>
/// <returns>Ceil of the Log2.</returns>
class function CeilLog2(x: UInt32): Integer; static;
/// <summary>
/// Returns bit length in int.
/// </summary>
/// <param name="x">UInt32 value.</param>
/// <returns>Length of bits.</returns>
class function BitLengthOfUInt(x: UInt32): Integer; static;
end;
implementation
class function TBits.Nlz(x: UInt32): Integer;
var
n: Integer;
begin
if (x = 0) then
begin
result := 32;
exit;
end;
n := 1;
if ((x shr 16) = 0) then
begin
n := n + 16;
x := x shl 16;
end;
if ((x shr 24) = 0) then
begin
n := n + 8;
x := x shl 8;
end;
if ((x shr 28) = 0) then
begin
n := n + 4;
x := x shl 4;
end;
if ((x shr 30) = 0) then
begin
n := n + 2;
x := x shl 2;
end;
result := n - Integer(x shr 31);
end;
class function TBits.Msb(x: UInt32): Integer;
begin
result := 31 - Nlz(x);
end;
class function TBits.CeilLog2(x: UInt32): Integer;
var
_Msb: Integer;
begin
_Msb := TBits.Msb(x);
if (x <> UInt32(1) shl _Msb) then
begin
Inc(_Msb);
end;
result := _Msb;
end;
class function TBits.BitLengthOfUInt(x: UInt32): Integer;
var
numBits: Integer;
begin
numBits := 0;
while (x > 0) do
begin
x := x shr 1;
Inc(numBits);
end;
result := numBits;
end;
end.
|
unit Funcoes;
interface
uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Dialogs, StdCtrls, Grids, DBGrids;
function TrocaVirgPPto(Valor: string): String;
Function GetNetUserName: string;
Function NomedoMes(dData:TDatetime):string;
implementation
function TrocaVirgPPto(Valor: string): String;
var i:integer;
begin
if Valor <>'' then begin
for i := 0 to Length(Valor) do begin
if Valor[i]=',' then Valor[i]:='.';
end;
end;
Result := valor;
end;
//Para Capturar o usuário Logado no Windows
Function GetNetUserName: string;
Var
NetUserNameLength: DWord;
Begin
NetUserNameLength:=50;
SetLength(Result, NetUserNameLength);
GetUserName(pChar(Result),NetUserNameLength);
SetLength(Result, StrLen(pChar(Result)));
End;
Function NomedoMes(dData:TDatetime):string;
var
nAno,nMes,nDia:word;
cMes:array[1..12] of string;
begin
cMes[01] := 'Janeiro';
cMes[02] := 'Fevereiro';
cMes[03] := 'Março';
cMes[04] := 'Abril';
cMes[05] := 'Maio';
cMes[06] := 'Junho';
cMes[07] := 'Julho';
cMes[08] := 'Agosto';
cMes[09] := 'Setembro';
cMes[10] := 'Outubro';
cMes[11] := 'Novembro';
cMes[12] := 'Dezembro';
decodedate(dData,nAno,nMes,nDia);
if (nMes>=1) and (nMes<=13)then
begin
Result:=cMes[nMes];
end
else
begin
Result:='';
end;
end;
end.
|
unit FmGifImg;
{ Exports main form for test program for TGifImage
2 Aug 97: - added possibility to load bmp files and save gif files
}
interface
uses
{WinProcs, WinTypes, {Windows,} Messages, SysUtils, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Menus,
GifDecl,
GifImgs;
type
TForm1 = class(TForm)
OpenDialog: TOpenDialog;
MainMenu1: TMainMenu;
File1: TMenuItem;
Open1: TMenuItem;
Read1: TMenuItem;
Animation1: TMenuItem;
On1: TMenuItem;
Off1: TMenuItem;
Slower1: TMenuItem;
Once1: TMenuItem;
SaveDialog: TSaveDialog;
Saveas1: TMenuItem;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Open1Click(Sender: TObject);
procedure On1Click(Sender: TObject);
procedure Off1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Slower1Click(Sender: TObject);
procedure Once1Click(Sender: TObject);
procedure Saveas1Click(Sender: TObject);
private
{ Private declarations }
{$ifndef Installed}
GifImage1: TGifImage;
{$endif Installed}
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const
fname1 = 'd:\Project\Delphi2\Gif\Images\95week51.gif';
procedure TForm1.FormCreate(Sender: TObject);
begin { TForm1.FormCreate }
{$ifndef Installed}
GifImage1 := TGifImage.Create(Self);
GifImage1.Parent := Self;
GifImage1.Left := 10;
GifImage1.Top := 10;
GifImage1.AutoSize := True;
{$endif Installed}
end; { TForm1.FormCreate }
procedure TForm1.Button1Click(Sender: TObject);
begin
GifImage1.LoadFromGifFile(fname1);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
GifImage1.Animating := not GifImage1.Animating
end;
procedure TForm1.Open1Click(Sender: TObject);
begin { TForm1.Open1Click }
if OpenDialog.Execute
then begin
case CheckType(OpenDialog.Filename) of
GIF: begin
GifImage1.LoadFromGifFile(OpenDialog.Filename);
OpenDialog.Filename := '*.gif'
end;
BMP: begin
GifImage1.LoadFromBmpFile(OpenDialog.Filename);
OpenDialog.Filename := '*.bmp'
end;
else ShowMessage(OpenDialog.Filename + ' not recognized as a '+
'valid gif or bmp file' )
end; { case }
end;
end; { TForm1.Open1Click }
procedure TForm1.On1Click(Sender: TObject);
begin
GifImage1.Animating := True;
On1.Checked := True;
Off1.Checked := False;
end;
procedure TForm1.Off1Click(Sender: TObject);
begin
GifImage1.Animating := False;
On1.Checked := False;
Off1.Checked := True;
end;
procedure TForm1.Slower1Click(Sender: TObject);
begin
GifImage1.Slower;
end;
procedure TForm1.Once1Click(Sender: TObject);
begin
GifImage1.AnimateOnce;
end;
procedure TForm1.Saveas1Click(Sender: TObject);
begin
if SaveDialog.Execute
then GifImage1.SaveToFile(SaveDialog.Filename)
end;
end.
|
unit DSA.Sorts.QuickSort;
interface
uses
System.SysUtils,
System.Math,
DSA.Interfaces.Comparer,
DSA.Utils,
DSA.Sorts.InsertionSort;
type
{ TQuickSort }
TQuickSort<T> = class
private type
TArr_T = TArray<T>;
ICmp_T = IComparer<T>;
TInsertionSort_T = TInsertionSort<T>;
var
class var __cmp: ICmp_T;
/// <summary> 对arr[l...r]部分进行快速排序 </summary>
class procedure __sort(var arr: TArr_T; l, r: integer);
/// <summary> 对arr[l...r]部分进行双路快速排序 </summary>
class procedure __sort2(var arr: TArr_T; l, r: integer);
/// <summary>
/// 三路快速排序处理arr[l..r]
/// 将arr[L..R]分为 < v ; ==v ; > v 三部分
/// 之后递归对 < v ; > v 两部分继续进行三路 快速排序
/// </summary>
class procedure __sort3Ways(var arr: TArr_T; l, r: integer);
/// <summary>
/// 对arr[l...r]部分进行partition操作,
/// 返回p, 使得arr[l...p-1] < arr[p] ; arr[p+1...r] > arr[p]
/// </summary>
class function __partition(var arr: TArr_T; l, r: integer): integer;
/// <summary>
/// 双路快速排序的partition
/// 返回p, 使得arr[l...p-1] <= arr[p] ; arr[p+1...r] >= arr[p]
// 双路快排处理的元素正好等于arr[p]的时候要注意,详见下面的注释:)
/// </summary>
class function __partition2(var arr: TArr_T; l, r: integer): integer;
class procedure __swap(var a, b: T);
public
class procedure Sort(var arr: TArr_T; cmp: ICmp_T);
/// <summary> 双路快速排序 </summary>
class procedure Sort2(var arr: TArr_T; cmp: ICmp_T);
/// <summary> 三路快速排序 </summary>
class procedure Sort3Ways(var arr: TArr_T; cmp: ICmp_T);
end;
procedure Main;
implementation
uses
DSA.Sorts.MergeSort;
type
TMergeSort_int = TMergeSort<integer>;
TQuickSort_int = TQuickSort<integer>;
procedure Main;
var
sourceArr, targetArr: TArray_int;
n, swapTimes: integer;
begin
n := 1000000;
WriteLn('Test for random array, size = ', n, ', random range [0, ', n, ']');
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateRandomArray(n, n);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, TMergeSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort'#9#9, targetArr, TQuickSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort2'#9#9, targetArr, TQuickSort_int.Sort2);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, TQuickSort_int.Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('DelphiSort'#9#9, targetArr, TDelphiSort<integer>.Sort);
Free;
end;
swapTimes := 100;
WriteLn('Test for nearly ordered array, size = ', n, ', swap time = ',
swapTimes);
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateNearlyOrderedArray(n, swapTimes);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, TMergeSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort'#9#9, targetArr, TQuickSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort2'#9#9, targetArr, TQuickSort_int.Sort2);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, TQuickSort_int.Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('DelphiSort'#9#9, targetArr, TDelphiSort<integer>.Sort);
Free;
end;
WriteLn('Test for random array, size = ', n, ', random range [0, ', 10, ']');
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateRandomArray(n, 10);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, TMergeSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort2'#9#9, targetArr, TQuickSort_int.Sort2);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, TQuickSort_int.Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('DelphiSort'#9#9, targetArr, TDelphiSort<integer>.Sort);
Free;
end;
end;
{ TQuickSort }
class procedure TQuickSort<T>.Sort(var arr: TArr_T; cmp: ICmp_T);
begin
__cmp := cmp;
__sort(arr, 0, Length(arr) - 1);
end;
class procedure TQuickSort<T>.Sort2(var arr: TArr_T; cmp: ICmp_T);
begin
__cmp := cmp;
__sort2(arr, 0, Length(arr) - 1);
end;
class procedure TQuickSort<T>.Sort3Ways(var arr: TArr_T; cmp: ICmp_T);
begin
__cmp := cmp;
__sort3Ways(arr, 0, Length(arr) - 1);
end;
class function TQuickSort<T>.__partition(var arr: TArr_T;
l, r: integer): integer;
var
v: T;
j, i: integer;
begin
// 在arr[l...r]的范围中, 选择一个中间数值作为标定点pivot
__swap(arr[l], arr[l + (r - l) shr 1]);
v := arr[l];
j := l; // arr[l+1...j] < v ; arr[j+1...i) > v
for i := l + 1 to r do
begin
if __cmp.Compare(arr[i], v) < 0 then
begin
Inc(j);
__swap(arr[j], arr[i]);
end;
end;
__swap(arr[l], arr[j]);
Result := j;
end;
class function TQuickSort<T>.__partition2(var arr: TArr_T;
l, r: integer): integer;
var
v: T;
j, i: integer;
begin
// 在arr[l...r]的范围中, 选择一个中间数值作为标定点pivot
__swap(arr[l], arr[l + (r - l) shr 1]);
v := arr[l];
i := l + 1;
j := r;
while True do
begin
while (i <= r) and (__cmp.Compare(arr[i], v) < 0) do
Inc(i);
while (j >= l + 1) and (__cmp.Compare(arr[j], v) > 0) do
Dec(j);
if i > j then
Break;
__swap(arr[i], arr[j]);
Inc(i);
Dec(j);
end;
__swap(arr[l], arr[j]);
Result := j;
end;
class procedure TQuickSort<T>.__sort(var arr: TArr_T; l, r: integer);
var
p: integer;
begin
if r - l <= 15 then
begin
TInsertionSort_T.Sort(arr, l, r, __cmp);
Exit;
end;
p := __partition(arr, l, r);
__sort(arr, l, p - 1);
__sort(arr, p + 1, r);
end;
class procedure TQuickSort<T>.__sort2(var arr: TArr_T; l, r: integer);
var
p: integer;
begin
if r - l <= 15 then
begin
TInsertionSort_T.Sort(arr, l, r, __cmp);
Exit;
end;
p := __partition2(arr, l, r);
__sort2(arr, l, p - 1);
__sort2(arr, p + 1, r);
end;
class procedure TQuickSort<T>.__sort3Ways(var arr: TArr_T; l, r: integer);
var
i, gt, lt: integer;
v: T;
begin
if r - l <= 15 then
begin
TInsertionSort_T.Sort(arr, l, r, __cmp);
Exit;
end;
// 在arr[l...r]的范围中, 选择一个中间数值作为标定点pivot
__swap(arr[l], arr[l + (r - l) shr 1]);
v := arr[l];
lt := l; // arr[l+1...lt] < v
gt := r + 1; // arr[gt...r] > v
i := l + 1; // arr[lt+1...i) == v
while i < gt do
begin
if __cmp.Compare(arr[i], v) < 0 then
begin
__swap(arr[i], arr[lt + 1]);
Inc(lt);
Inc(i);
end
else if __cmp.Compare(arr[i], v) > 0 then
begin
__swap(arr[i], arr[gt - 1]);
Dec(gt);
end
else
begin
Inc(i);
end;
end;
__swap(arr[l], arr[lt]);
__sort3Ways(arr, l, lt - 1);
__sort3Ways(arr, gt, r);
end;
class procedure TQuickSort<T>.__swap(var a, b: T);
var
tmp: T;
begin
tmp := a;
a := b;
b := tmp;
end;
end.
|
// Kalman filter implementation
unit Kalman;
interface
const
MAXORDER = 3;
type
TMatrix = array [1..MAXORDER, 1..MAXORDER] of Real;
TKalmanFilter = record
n, m, s: SmallInt;
x, xapri, z: TMatrix;
Phi, G, H, Q, R, P, Papri, K: TMatrix;
end;
procedure ExecuteFilter(var KF: TKalmanFilter);
implementation
procedure Transpose(m, n: SmallInt; var C, CT: TMatrix);
var
i, j: SmallInt;
begin
for i := 1 to m do
for j := 1 to n do
CT[j, i] := C[i, j];
end;
// C = C1 + C2
procedure Add(m, n: SmallInt; var C1, C2, C: TMatrix);
var
i, j: SmallInt;
begin
for i := 1 to m do
for j := 1 to n do
C[i, j] := C1[i, j] + C2[i, j];
end;
// C = C1 - C2
procedure Sub(m, n: SmallInt; var C1, C2, C: TMatrix);
var
i, j: SmallInt;
begin
for i := 1 to m do
for j := 1 to n do
C[i, j] := C1[i, j] - C2[i, j];
end;
// C = C1 * C2
procedure Mult(m1, n1, n2: SmallInt; var C1, C2, C: TMatrix);
var
i, j, k: SmallInt;
begin
for i := 1 to m1 do
for j := 1 to n2 do
begin
C[i, j] := 0;
for k := 1 to n1 do
C[i, j] := C[i, j] + C1[i, k] * C2[k, j];
end;
end;
// Cs = B * C * BT
// mm mn nn nm
procedure Similarity(m, n: SmallInt; var B, C, Cs: TMatrix);
var
BT, BC: TMatrix;
begin
Mult(m, n, n, B, C, BC);
Transpose(m, n, B, BT);
Mult(m, n, m, BC, BT, Cs);
end;
procedure Identity(n: SmallInt; var E: TMatrix);
var
i, j: SmallInt;
begin
for i := 1 to n do
for j := 1 to n do
if i = j then E[i, j] := 1 else E[i, j] := 0;
end;
procedure Inverse(m: SmallInt; var C, Cinv: TMatrix);
var
big, fabval, pivinv, temp: Real;
i, j, k, l, ll, irow, icol: SmallInt;
indxc, indxr, ipiv: array [1..MAXORDER] of SmallInt;
begin
for i := 1 to m do
for j := 1 to m do
Cinv[i, j] := C[i, j];
for j := 1 to m do
ipiv[j] := 0;
icol := 1; irow := 1;
for i := 1 to m do
begin
big := 0;
for j := 1 to m do
if ipiv[j] <> 1 then
for k := 1 to m do
begin
if ipiv[k] = 0 then
begin
if Cinv[j, k] < 0 then fabval := -Cinv[j, k] else fabval := Cinv[j, k];
if fabval >= big then
begin
big := fabval;
irow := j;
icol := k;
end;
end // if
else
begin
// Singular matrix
end; // else
end; // for
Inc(ipiv[icol]);
if irow <> icol then
for l := 1 to m do
begin
temp := Cinv[irow, l];
Cinv[irow, l] := Cinv[icol, l];
Cinv[icol, l] := temp;
end;
indxr[i] := irow;
indxc[i] := icol;
pivinv := 1 / Cinv[icol, icol];
Cinv[icol, icol] := 1;
for l := 1 to m do
Cinv[icol, l] := Cinv[icol, l] * pivinv;
for ll := 1 to m do
if ll <> icol then
begin
temp := Cinv[ll, icol];
Cinv[ll, icol] := 0;
for l := 1 to m do Cinv[ll, l] := Cinv[ll, l] - Cinv[icol, l] * temp;
end; // for
end; // for
for l := m downto 1 do
begin
if indxr[l] <> indxc[l] then
for k := 1 to m do
begin
temp := Cinv[k, indxr[l]];
Cinv[k, indxr[l]] := Cinv[k, indxc[l]];
Cinv[k, indxc[l]] := temp;
end; // for
end; //for
end;
procedure ExecuteFilter(var KF: TKalmanFilter);
var
PhiPPhiT, GQGT, HT, HPapriHT, HPapriHTplusR, HPapriHTplusRinv, PapriHT, Hxapri, nu, Knu, KH, EminusKH, E: TMatrix;
begin
// All variable names correspond to the notation in the book:
// Salychev O. S. Applied Inertial Navigation
// 'apri' means 'a priori' and stands for 'k/k-1'
// A priori state vector estimate
Mult(KF.n, KF.n, 1, KF.Phi, KF.x, KF.xapri);
// A priori variance matrix
Similarity(KF.n, KF.n, KF.Phi, KF.P, PhiPPhiT);
Similarity(KF.n, KF.s, KF.G, KF.Q, GQGT);
Add(KF.n, KF.n, PhiPPhiT, GQGT, KF.Papri);
// Gain matrix
Similarity(KF.m, KF.n, KF.H, KF.Papri, HPapriHT);
Add(KF.m, KF.m, HPapriHT, KF.R, HPapriHTplusR);
Inverse(KF.m, HPapriHTplusR, HPapriHTplusRinv);
Transpose(KF.m, KF.n, KF.H, HT);
Mult(KF.n, KF.n, KF.m, KF.Papri, HT, PapriHT);
Mult(KF.n, KF.m, KF.m, PapriHT, HPapriHTplusRinv, KF.K);
// A posteriori state vector estimate
Mult(KF.m, KF.n, 1, KF.H, KF.xapri, Hxapri);
Sub(KF.m, 1, KF.z, Hxapri, nu);
Mult(KF.n, KF.m, 1, KF.K, nu, Knu);
Add(KF.n, 1, KF.xapri, Knu, KF.x);
// A posteriori variance matrix
Mult(KF.n, KF.m, KF.n, KF.K, KF.H, KH);
Identity(KF.n, E);
Sub(KF.n, KF.n, E, KH, EminusKH);
Mult(KF.n, KF.n, KF.n, EminusKH, KF.Papri, KF.P);
end;
end. |
// このソースコードは blanco Frameworkにより自動生成されました。
unit SampleStringGroup;
interface
uses SysUtils;
type
{ 文字列グループのサンプル。このクラスは単にサンプルです。実際の動作には利用されません。 }
TSampleStringGroup = class(TObject)
{ No.1 説明:アルファベットの文字列定義。 }
const ABCDEFG = 1;
{ No.2 説明:全角の文字列定義。 }
const AIUEO = 2;
{ No.3 説明:シングルクオートが展開されることの確認。 }
const QUOTE = 3;
{ No.4 説明:ダブルクオートが展開されることの確認。 }
const DOUBLE_QUOTE = 4;
{ No.5 説明:バックスラッシュが展開されることの確認。 }
const BACK_SLASH = 5;
{ No.7 }
const WITHOUT_DESC = 7;
{ No.8 説明:途中の空白が適切に処理されることの確認。 }
const TEST_SPACE = 8;
{ No.9 説明:×マーク。 }
const BATU = 9;
{ 未定義。文字列グループ以外の文字列または定数が未定義のもの。 }
const NOT_DEFINED = -1;
function match(argCheck: String): boolean;
function matchIgnoreCase(argCheck: String): boolean;
function convertToInt(argCheck: String): Integer;
end;
implementation
function TSampleStringGroup.match(argCheck: String): boolean;
begin
// No.1
// 説明:アルファベットの文字列定義。
if 'ABCDEFG' = argCheck then begin
result := True;
exit;
end;
// No.2
// 説明:全角の文字列定義。
if 'あいうえお' = argCheck then begin
result := True;
exit;
end;
// No.3
// 説明:シングルクオートが展開されることの確認。
if '''' = argCheck then begin
result := True;
exit;
end;
// No.4
// 説明:ダブルクオートが展開されることの確認。
if '"' = argCheck then begin
result := True;
exit;
end;
// No.5
// 説明:バックスラッシュが展開されることの確認。
if '\' = argCheck then begin
result := True;
exit;
end;
// No.6
// 説明:定数が省略された定義。
if 'STRING ONLY' = argCheck then begin
result := True;
exit;
end;
// No.7
if '説明を省略' = argCheck then begin
result := True;
exit;
end;
// No.8
// 説明:途中の空白が適切に処理されることの確認。
if 'ABC DEF' = argCheck then begin
result := True;
exit;
end;
// No.9
// 説明:×マーク。
if '×' = argCheck then begin
result := True;
exit;
end;
result := False;
exit;
end;
function TSampleStringGroup.matchIgnoreCase(argCheck: String): boolean;
begin
// No.1
// 説明:アルファベットの文字列定義。
if UpperCase('ABCDEFG') = UpperCase(argCheck) then begin
result := True;
exit;
end;
// No.2
// 説明:全角の文字列定義。
if UpperCase('あいうえお') = UpperCase(argCheck) then begin
result := True;
exit;
end;
// No.3
// 説明:シングルクオートが展開されることの確認。
if UpperCase('''') = UpperCase(argCheck) then begin
result := True;
exit;
end;
// No.4
// 説明:ダブルクオートが展開されることの確認。
if UpperCase('"') = UpperCase(argCheck) then begin
result := True;
exit;
end;
// No.5
// 説明:バックスラッシュが展開されることの確認。
if UpperCase('\') = UpperCase(argCheck) then begin
result := True;
exit;
end;
// No.6
// 説明:定数が省略された定義。
if UpperCase('STRING ONLY') = UpperCase(argCheck) then begin
result := True;
exit;
end;
// No.7
if UpperCase('説明を省略') = UpperCase(argCheck) then begin
result := True;
exit;
end;
// No.8
// 説明:途中の空白が適切に処理されることの確認。
if UpperCase('ABC DEF') = UpperCase(argCheck) then begin
result := True;
exit;
end;
// No.9
// 説明:×マーク。
if UpperCase('×') = UpperCase(argCheck) then begin
result := True;
exit;
end;
result := False;
exit;
end;
function TSampleStringGroup.convertToInt(argCheck: String): Integer;
begin
// No.1
// 説明:アルファベットの文字列定義。
if 'ABCDEFG' = argCheck then begin
result := ABCDEFG;
exit;
end;
// No.2
// 説明:全角の文字列定義。
if 'あいうえお' = argCheck then begin
result := AIUEO;
exit;
end;
// No.3
// 説明:シングルクオートが展開されることの確認。
if '''' = argCheck then begin
result := QUOTE;
exit;
end;
// No.4
// 説明:ダブルクオートが展開されることの確認。
if '"' = argCheck then begin
result := DOUBLE_QUOTE;
exit;
end;
// No.5
// 説明:バックスラッシュが展開されることの確認。
if '\' = argCheck then begin
result := BACK_SLASH;
exit;
end;
// No.7
if '説明を省略' = argCheck then begin
result := WITHOUT_DESC;
exit;
end;
// No.8
// 説明:途中の空白が適切に処理されることの確認。
if 'ABC DEF' = argCheck then begin
result := TEST_SPACE;
exit;
end;
// No.9
// 説明:×マーク。
if '×' = argCheck then begin
result := BATU;
exit;
end;
// 該当する定数が見つかりませんでした。
result := NOT_DEFINED;
exit;
end;
end.
|
unit CatPrefs;
{
Catarinka Preferences (TCatPreferences)
Copyright (c) 2013-2019 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
System.Classes, System.SysUtils, System.Variants,
{$ELSE}
Classes, SysUtils, Variants,
{$ENDIF}
CatJSON;
type
TCatPrefsCustomOption = record
HideInOptionList: boolean;
Tags: string; // comma separated tags
end;
type
TCatPreferences = class
private
fCurrent: TCatJSON;
fCurrentBackup: TCatJSON;
fDefault: TCatJSON;
fDefaultValueTypes: TCatJSON;
fFilename: string;
fOptionList: TStringList;
fTags: TCatJSON;
function Encrypt(const CID: string; const Value: Variant): Variant;
function Decrypt(const CID: string; const Value: Variant): Variant;
function FGetValue(const CID: string): Variant;
function GetCIDList: string;
public
function ContainsTag(const CID, aTag:string):boolean;
function GetCIDListByTag(const aTag: string): string;
function GetValue(const CID: string): Variant; overload;
function GetValue(const CID: string; const DefaultValue: Variant)
: Variant; overload;
function GetDefaultValue(const CID: string): Variant;
function GetRegValue(const CID: string;
const DefaultValue: Variant): Variant;
procedure SetValue(const CID: string; const Value: Variant);
procedure SetValues(const CIDs: array of string; const Value: Variant);
procedure SetValuesByTag(const Tag: string; const Value: Variant);
procedure LoadFromFile(const f: string);
procedure LoadFromString(const s: string);
procedure RegisterDefault(const CID: string;
const DefaultValue: Variant); overload;
procedure RegisterDefault(const CID: string; const DefaultValue: Variant;
const Tags: array of string); overload;
procedure RegisterDefault(const CID: string; const DefaultValue: Variant;
const Custom: TCatPrefsCustomOption); overload;
procedure RestoreBackup;
procedure RestoreBackupByTag(const Tag: string; const Condition:boolean = false);
procedure RestoreDefaults;
procedure SaveToFile(const f: string);
procedure UpdateBackup;
constructor Create;
destructor Destroy; override;
// properties
property Backup: TCatJSON read fCurrentBackup;
property CIDList: string read GetCIDList;
property Current: TCatJSON read fCurrent;
property Default: TCatJSON read fDefault;
property Filename: string read fFilename write fFilename;
property OptionList: TStringList read fOptionList;
property Values[const CID: string]: Variant read FGetValue
write SetValue; default;
end;
implementation
uses CatStrings, CatStringLoop, CatMatch,
{$IFDEF MSWINDOWS}
CatDCP,
{$ELSE}
CatCrypt,
{$ENDIF}
CatCryptKey;
function VariantTypeIDToVariantType(ID:string):word;
begin
result := varEmpty;
case ID[1] of
's': result := varString;
'b': result := varBoolean;
'i': result := varInteger;
'd': result := varDouble;
end;
end;
function GetVariantTypeID(Value:variant):string;
begin
case TVarData(Value).vType of
varEmpty:
result := emptystr;
varString, {$IFDEF UNICODE}varUString, {$ENDIF}varOleStr:
result := 's';
varBoolean:
result := 'b';
varInteger, varByte, varSmallInt, varShortInt, varWord, varLongWord,
{$IFDEF UNICODE}varUInt64, {$ENDIF} varInt64:
result := 'i';
varDouble:
result := 'd';
end;
end;
// Returns true if the value of a CID must be encrypted, false otherwise
function IsEncryptedCID(CID: string): boolean;
begin
result := false;
if endswith(CID, '.password') then
result := true
else if endswith(CID, '.encrypted') then
result := true;
end;
// Encrypts the value of a CID if necessary
function TCatPreferences.Encrypt(const CID: string;
const Value: Variant): Variant;
begin
if IsEncryptedCID(CID) then
result := ansistrtoaes(Value, GetCatKey(CATKEY_PASSWORD))
else
result := Value;
end;
// Decrypts the value of a CID if necessary
function TCatPreferences.Decrypt(const CID: string;
const Value: Variant): Variant;
begin
if IsEncryptedCID(CID) then
result := aestoansistr(Value, GetCatKey(CATKEY_PASSWORD))
else
result := Value;
end;
// Returns the CID of all available options
function TCatPreferences.GetCIDList: string;
begin
result := fOptionList.text;
end;
function TCatPreferences.ContainsTag(const CID, aTag:string):boolean;
var
tags: string;
begin
tags := fTags.GetValue(CID, emptystr);
result := MatchStrInSepStr(aTag, tags);
end;
// Returns a CID list by a specific tag
function TCatPreferences.GetCIDListByTag(const aTag: string): string;
var
CID: TStringLoop;
list: TStringList;
begin
list := TStringList.Create;
CID := TStringLoop.Create(fOptionList);
while CID.Found do
begin
if ContainsTag(CID.Current, aTag) = true then
list.Add(CID.Current);
end;
CID.Free;
result := list.text;
list.Free;
end;
function TCatPreferences.FGetValue(const CID: string): Variant;
begin
result := fCurrent.GetValue(CID, fDefault[CID]);
result := Decrypt(CID, result);
end;
// Gets the default value of a CID.
// A default CID value must be set using the RegisterValue() or GetRegValue()
// methods
function TCatPreferences.GetDefaultValue(const CID: string): Variant;
begin
result := fDefault[CID];
result := Decrypt(CID, result);
end;
// Gets the value of a CID
function TCatPreferences.GetValue(const CID: string): Variant;
begin
result := FGetValue(CID);
end;
// Gets the value of a CID. DefaultValue is returned if the CID is not set
function TCatPreferences.GetValue(const CID: string;
const DefaultValue: Variant): Variant;
begin
result := fCurrent.GetValue(CID, DefaultValue);
result := Decrypt(CID, result);
end;
// Gets and registers a value at the same time
// DefaultValue is returned if the CID is not set
function TCatPreferences.GetRegValue(const CID: string;
const DefaultValue: Variant): Variant;
begin
RegisterDefault(CID, DefaultValue);
result := fCurrent.GetValue(CID, DefaultValue);
result := Decrypt(CID, result);
end;
// Sets the value of a CID
procedure TCatPreferences.SetValue(const CID: string; const Value: Variant);
begin
fCurrent[CID] := Encrypt(CID, Value);
end;
// Sets the value of multiple CIDs at the same time
procedure TCatPreferences.SetValues(const CIDs: array of string;
const Value: Variant);
var
b: integer;
begin
for b := Low(CIDs) to High(CIDs) do
if (CIDs[b] <> emptystr) then
SetValue(CIDs[b], Value);
end;
// Sets the value of multiple CIDs by their tag
procedure TCatPreferences.SetValuesByTag(const Tag: string;
const Value: Variant);
var
CID: TStringLoop;
begin
CID := TStringLoop.Create(GetCIDListByTag(Tag));
while CID.Found do
SetValue(CID.Current, Value);
CID.Free;
end;
// Reverts to the backup configuration
procedure TCatPreferences.RestoreBackup;
begin
fCurrent.text := fCurrentBackup.text;
end;
// Reverts the value of tagged CIDs to the value of the backup configuration,
// This makes the values in backup to overwrite the current configuration values
// if the value in Condition is met
procedure TCatPreferences.RestoreBackupByTag(const Tag: string;
const Condition:boolean = false);
var
CID: TStringLoop;
begin
CID := TStringLoop.Create(GetCIDListByTag(Tag));
while CID.Found do
if fCurrentBackup.GetValue(CID.Current, fDefault[CID.Current]) = Condition then
SetValue(CID.Current, Condition);
CID.Free;
end;
// Reverts to the default configuration
procedure TCatPreferences.RestoreDefaults;
begin
fCurrent.text := fDefault.text;
end;
// Registers the default value of a CID with custom actions (like hiding the
// option from the options list, associating tags, etc)
procedure TCatPreferences.RegisterDefault(const CID: string;
const DefaultValue: Variant; const Custom: TCatPrefsCustomOption);
begin
if Custom.HideInOptionList = false then
begin
if fOptionList.indexof(CID) = -1 then
fOptionList.Add(CID);
end;
if Custom.Tags <> emptystr then
fTags[CID] := Custom.Tags;
fDefault[CID] := DefaultValue;
fDefaultValueTypes[CID] := GetVariantTypeID(DefaultValue);
end;
// Registers the default value of a CID
procedure TCatPreferences.RegisterDefault(const CID: string;
const DefaultValue: Variant);
var
opt: TCatPrefsCustomOption;
begin
opt.HideInOptionList := false;
opt.Tags := emptystr;
RegisterDefault(CID, DefaultValue, opt);
end;
// Registers the default value of a CID with tags
procedure TCatPreferences.RegisterDefault(const CID: string;
const DefaultValue: Variant; const Tags: array of string);
var
b: integer;
taglist: string;
opt: TCatPrefsCustomOption;
begin
taglist := emptystr;
for b := Low(Tags) to High(Tags) do
if (Tags[b] <> emptystr) then
begin
if taglist = emptystr then
taglist := Tags[b]
else
taglist := taglist + ',' + Tags[b];
end;
opt.HideInOptionList := false;
opt.Tags := taglist;
RegisterDefault(CID, DefaultValue, opt);
end;
procedure TCatPreferences.UpdateBackup;
begin
fCurrentBackup.Text := fCurrent.Text;
end;
// Load the preferences from a file
procedure TCatPreferences.LoadFromFile(const f: string);
begin
Filename := f;
fCurrent.LoadFromFile(f);
UpdateBackup;
end;
// Load the preferences from a string
procedure TCatPreferences.LoadFromString(const s: string);
begin
if s = emptystr then
fCurrent.text := EmptyJSONStr
else
fCurrent.text := s;
UpdateBackup;
end;
// Save the preferences to a file
procedure TCatPreferences.SaveToFile(const f: string);
begin
fCurrent.SaveToFile(f);
end;
constructor TCatPreferences.Create;
begin
inherited Create;
fCurrent := TCatJSON.Create;
fCurrentBackup := TCatJSON.Create;
fDefault := TCatJSON.Create;
fDefaultValueTypes := TCatJSON.Create;
fTags := TCatJSON.Create;
fOptionList := TStringList.Create;
end;
destructor TCatPreferences.Destroy;
begin
fOptionList.Free;
fTags.Free;
fDefaultValueTypes.Free;
fDefault.Free;
fCurrentBackup.Free;
fCurrent.Free;
inherited;
end;
end.
|
unit USmetChart;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, TeeProcs, TeEngine, Chart, ComCtrls, Series, pFibDataSet;
type
TChartForm = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
Chart1: TChart;
Series1: TPieSeries;
Chart2: TChart;
PieSeries1: TPieSeries;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
uses USmetStru;
{$R *.dfm}
procedure TChartForm.FormCreate(Sender: TObject);
function GetColor(I:Integer):TColor;
begin
Result:=clRed;
if i mod 3 = 0
then begin
Result:=clGreen;
Exit;
end;
if i mod 4 = 0
then begin
Result:=clYellow;
Exit;
end;
if i mod 5 = 0
then begin
Result:=clBlue;
Exit;
end;
if i mod 6 = 0
then begin
Result:=clGray;
Exit;
end;
if i mod 7 = 0
then begin
Result:=clWhite;
Exit;
end;
end;
var i:Integer;
Color:Integer;
GetInfoDS:TpFibDataSet;
begin
Self.Caption:=TfrmSmetaStru(owner).Caption;
GetInfoDS:=TpFibDataSet.Create(self);
GetInfoDS.Database :=TfrmSmetaStru(owner).WorkDatabase;
GetInfoDS.Transaction:=TfrmSmetaStru(owner).ReadTransaction;
GetInfoDS.SelectSQL.Text:='SELECT * FROM BU_GET_BUDGET_STRU_VALUES('+IntToStr(TfrmSmetaStru(owner).CurIdSmeta)+','+''''+DateToStr(TfrmSmetaStru(owner).PlanDateBeg+1)+''''+')';
GetInfoDS.Open;
Color:=0;
GetInfoDS.FetchAll;
GetInfoDS.First;
for i:=0 to GetInfoDS.RecordCount-1 do
begin
if GetInfoDS.FieldByName('PROFIT_FLAG').AsInteger=1
then begin
Series1.Add(GetInfoDS.FieldByName('PLAN_VALUE').Value,
GetInfoDS.FieldByName('SHOW_TITLE').Value,
getColor(Color));
Color:=Color+1;
end;
GetInfoDS.Next;
end;
Color:=0;
GetInfoDS.First;
for i:=0 to GetInfoDS.RecordCount-1 do
begin
if GetInfoDS.FieldByName('PROFIT_FLAG').AsInteger=0
then begin
PieSeries1.Add(GetInfoDS.FieldByName('PLAN_VALUE').Value,
GetInfoDS.FieldByName('SHOW_TITLE').Value,
getColor(Color));
Color:=Color+1;
end;
GetInfoDS.Next;
end;
end;
end.
|
unit UTypes;
(*====================================================================
Common types and utility functions
======================================================================*)
interface
const
qifFileName = 'DiskBase.Lic';
helpFileName = 'DiskBase.HLP';
stVersion = '5.19';
NumVersion = 5;
NumSubversion = 19;
NumVersionType = 1;
{version 5.00 - 5.07}
{DataFormatVersion = SmallInt(5) shl 8 + 0;}
{version 5.07 - ?}
DataFormatVersion = SmallInt(5) shl 8 + 1;
const
UsePersistentBlocks : boolean = true;
{$ifdef DELPHI1}
const
{$ifdef English}
About2 = 'Version '+ stVersion +' English, for Windows 3.1x';
{$endif}
{$ifdef Czech}
About2 = 'Verze '+ stVersion +' èeská, pro Windows 3.1x';
{$endif}
type
ShortString = string;
SmallInt = integer;
procedure SetLength(var S: ShortString; NewLength: SmallInt);
{$else}
{$ifdef English}
const
About2 = 'Version '+ stVersion +' English, for Linux';
{$endif}
{$ifdef Czech}
const
About2 = 'Verze '+ stVersion +' česká, pro Linux';
{$endif}
{$endif}
function ShortCopy(S: ShortString; Index, Count: SmallInt): ShortString;
procedure ShortDelete(var S: ShortString; Index, Count: SmallInt);
procedure ShortInsert(Source: ShortString; var S: ShortString; Index: SmallInt);
implementation
{$ifdef DELPHI1}
//-----------------------------------------------------------------------------
procedure SetLength(var S: ShortString; NewLength: SmallInt);
begin
S[0] := char(NewLength);
end;
//-----------------------------------------------------------------------------
function ShortCopy(S: ShortString; Index, Count: SmallInt): ShortString;
begin
Result := copy(S, Index, Count);
end;
//-----------------------------------------------------------------------------
procedure ShortDelete(var S: ShortString; Index, Count: SmallInt);
begin
Delete(S, Index, Count);
end;
//-----------------------------------------------------------------------------
procedure ShortInsert(Source: ShortString; var S: ShortString; Index: SmallInt);
begin
Insert(Source, S, Index);
end;
//-----------------------------------------------------------------------------
{$else}
//-----------------------------------------------------------------------------
function ShortCopy(S: ShortString; Index, Count: SmallInt): ShortString;
var
Len: ShortInt;
begin
Len := Length(S);
Result[0] := #0;
if (Index > Len) or (Index <= 0) or (Count <= 0) then exit;
if (Count+Index-1) > Len then Count := Len-Index+1;
move(S[Index], Result[1], Count);
Result[0] := char(Count);
end;
//-----------------------------------------------------------------------------
procedure ShortDelete(var S: ShortString; Index, Count: SmallInt);
var
Len: SmallInt;
ToBeMoved: SmallInt;
begin
Len := byte(S[0]);
if (Index > Len) or (Index <= 0) or (Count <= 0) then exit;
if (Index + Count) > succ(Len) then
begin
S[0] := char(pred(Index));
exit;
end;
S[0] := char(Len-Count);
ToBeMoved := Len - Index - Count + 1;
if ToBeMoved > 0 then
move(S[Index+Count], S[Index], ToBeMoved);
end;
//-----------------------------------------------------------------------------
procedure ShortInsert(Source: ShortString; var S: ShortString; Index: SmallInt);
var
Len: SmallInt;
SourceLen: SmallInt;
ToBeMoved: SmallInt;
begin
Len := byte(S[0]);
SourceLen := byte(Source[0]);
if (Index <= 0) then exit;
if Index >= succ(Len) then
begin
S := S + Source;
exit;
end;
if (Len + SourceLen) > 255 then
begin
SourceLen := 255 - Len;
Source[0] := char(SourceLen);
end;
ToBeMoved := Len - Index + 1;
if ToBeMoved > 0 then
move(S[Index], S[Index+SourceLen], ToBeMoved);
move(Source[1], S[Index], SourceLen);
S[0] := char(Len+SourceLen);
end;
//-----------------------------------------------------------------------------
{$endif}
begin
end.
|
unit Main;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, Menus,
StdCtrls, Dialogs, Buttons, Messages, ExtCtrls, ComCtrls;
type
TMainForm = class(TForm)
MainMenu1: TMainMenu;
File1: TMenuItem;
FileNewItem: TMenuItem;
FileOpenItem: TMenuItem;
FileCloseItem: TMenuItem;
Window1: TMenuItem;
Help1: TMenuItem;
N1: TMenuItem;
FileExitItem: TMenuItem;
WindowCascadeItem: TMenuItem;
WindowTileItem: TMenuItem;
WindowArrangeItem: TMenuItem;
HelpAboutItem: TMenuItem;
OpenDialog: TOpenDialog;
FileSaveItem: TMenuItem;
FileSaveAsItem: TMenuItem;
Edit1: TMenuItem;
CutItem: TMenuItem;
CopyItem: TMenuItem;
PasteItem: TMenuItem;
WindowMinimizeItem: TMenuItem;
SpeedPanel: TPanel;
OpenBtn: TSpeedButton;
SaveBtn: TSpeedButton;
CutBtn: TSpeedButton;
CopyBtn: TSpeedButton;
PasteBtn: TSpeedButton;
ExitBtn: TSpeedButton;
StatusBar: TStatusBar;
procedure FormCreate(Sender: TObject);
procedure FileNewItemClick(Sender: TObject);
procedure WindowCascadeItemClick(Sender: TObject);
procedure UpdateMenuItems(Sender: TObject);
procedure WindowTileItemClick(Sender: TObject);
procedure WindowArrangeItemClick(Sender: TObject);
procedure FileCloseItemClick(Sender: TObject);
procedure FileOpenItemClick(Sender: TObject);
procedure FileExitItemClick(Sender: TObject);
procedure FileSaveItemClick(Sender: TObject);
procedure FileSaveAsItemClick(Sender: TObject);
procedure CutItemClick(Sender: TObject);
procedure CopyItemClick(Sender: TObject);
procedure PasteItemClick(Sender: TObject);
procedure WindowMinimizeItemClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
procedure CreateMDIChild(const Name: string);
procedure ShowHint(Sender: TObject);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
uses ChildWin;
procedure TMainForm.FormCreate(Sender: TObject);
begin
Application.OnHint := ShowHint;
Screen.OnActiveFormChange := UpdateMenuItems;
end;
procedure TMainForm.ShowHint(Sender: TObject);
begin
StatusBar.SimpleText := Application.Hint;
end;
procedure TMainForm.CreateMDIChild(const Name: string);
var
Child: TMDIChild;
begin
{ create a new MDI child window }
Child := TMDIChild.Create(Application);
Child.Caption := Name;
end;
procedure TMainForm.FileNewItemClick(Sender: TObject);
begin
CreateMDIChild('NONAME' + IntToStr(MDIChildCount + 1));
end;
procedure TMainForm.FileOpenItemClick(Sender: TObject);
begin
if OpenDialog.Execute then
CreateMDIChild(OpenDialog.FileName);
end;
procedure TMainForm.FileCloseItemClick(Sender: TObject);
begin
if ActiveMDIChild <> nil then
ActiveMDIChild.Close;
end;
procedure TMainForm.FileSaveItemClick(Sender: TObject);
begin
{ save current file (ActiveMDIChild points to the window) }
end;
procedure TMainForm.FileSaveAsItemClick(Sender: TObject);
begin
{ save current file under new name }
end;
procedure TMainForm.FileExitItemClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.CutItemClick(Sender: TObject);
begin
{cut selection to clipboard}
end;
procedure TMainForm.CopyItemClick(Sender: TObject);
begin
{copy selection to clipboard}
end;
procedure TMainForm.PasteItemClick(Sender: TObject);
begin
{paste from clipboard}
end;
procedure TMainForm.WindowCascadeItemClick(Sender: TObject);
begin
Cascade;
end;
procedure TMainForm.WindowTileItemClick(Sender: TObject);
begin
Tile;
end;
procedure TMainForm.WindowArrangeItemClick(Sender: TObject);
begin
ArrangeIcons;
end;
procedure TMainForm.WindowMinimizeItemClick(Sender: TObject);
var
I: Integer;
begin
{ Must be done backwards through the MDIChildren array }
for I := MDIChildCount - 1 downto 0 do
MDIChildren[I].WindowState := wsMinimized;
end;
procedure TMainForm.UpdateMenuItems(Sender: TObject);
begin
FileCloseItem.Enabled := MDIChildCount > 0;
FileSaveItem.Enabled := MDIChildCount > 0;
FileSaveAsItem.Enabled := MDIChildCount > 0;
CutItem.Enabled := MDIChildCount > 0;
CopyItem.Enabled := MDIChildCount > 0;
PasteItem.Enabled := MDIChildCount > 0;
SaveBtn.Enabled := MDIChildCount > 0;
CutBtn.Enabled := MDIChildCount > 0;
CopyBtn.Enabled := MDIChildCount > 0;
PasteBtn.Enabled := MDIChildCount > 0;
WindowCascadeItem.Enabled := MDIChildCount > 0;
WindowTileItem.Enabled := MDIChildCount > 0;
WindowArrangeItem.Enabled := MDIChildCount > 0;
WindowMinimizeItem.Enabled := MDIChildCount > 0;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
Screen.OnActiveFormChange := nil;
end;
end.
|
unit uBeaconProximo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Beacon,
System.Bluetooth, FMX.ScrollBox, FMX.Memo, System.Beacon.Components,
FMX.Controls.Presentation, FMX.StdCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Beacon1: TBeacon;
Memo1: TMemo;
Button1: TButton;
procedure Beacon1BeaconEnter(const Sender: TObject; const ABeacon: IBeacon;
const CurrentBeaconList: TBeaconList);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.Beacon1BeaconEnter(const Sender: TObject;
const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList);
begin
if ABeacon.GUID.ToString <> '' then
begin
Memo1.Lines.Add('Você está próximo do Beacon!');
Memo1.Lines.Add('UUID: ' + ABeacon.GUID.ToString);
Memo1.Lines.Add('Distância: ' + CurrToStr(ABeacon.Distance) + ' metros');
Beacon1.Enabled := False;
end
else
Memo1.Lines.Add('Beacon não encontrado!');
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Beacon1.Enabled := True;
end;
end.
|
namespace ClassRefs;
interface
type
Class1 = public class
public
constructor; virtual;
class method TestIt; virtual;
end;
Class2 = assembly class(Class1)
public
constructor; override;
class method TestIt; override;
end;
AClass = class of Class1;
implementation
method ClassReferenceTest(var aClassToUse: AClass);
var
instance: Class1;
begin
{ The following line shows how you can invoke methods marked as "class" without an instance
of the class. Class methods allow you to create objects such as the standard Convert, which
basically are repository of quick methods that don't require state or an object instance.
This is the preferred approach to write equivalents of functions in old Delphi libraries
such as SysUtils or Math. }
aClassToUse.TestIt;
Console.WriteLine('Actual Type: '+aClassToUse.ActualType.Name);
Console.WriteLine('');
{ The following code shows how you can use a class type to create an instance of an object
of the type held by "aClassToUse". This mimics old Delphi myvar := myclass.Create kind
of code. If the constrctor of Class1 had parameters, you could have specified them this way:
cls := aClassToUse.New('A String', 123, <etc>); }
instance := aClassToUse.New;
Console.WriteLine('Created instance of type: '+instance.ActualType.Name);
end;
{ The "Main" global method is the application entry point.
Its code will be executed automatically when the application is run. }
method Main;
var
cls: AClass;
begin
Console.WriteLine('Class Reference Sample');
Console.WriteLine('');
cls := Class1;
ClassReferenceTest(var cls);
cls := Class2;
ClassReferenceTest(var cls);
Console.ReadLine;
end;
constructor Class2;
begin
inherited; // Virtual constructors can call the inheried constructor.
Console.WriteLine('Constructing a Class2. This constructor overrides and calls the anchestor''s.');
end;
class method Class2.TestIt;
begin
inherited; // Class methods can call the inherited implementation.
Console.WriteLine('Calling the class method TestIt from Class2. This method overrides and calls the anchestor''s.');
end;
constructor Class1;
begin
Console.WriteLine('Constructing a Class1');
end;
class method Class1.TestIt;
begin
Console.WriteLine('Calling the class method TestIt from Class1');
end;
end.
|
unit DataContext;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpjson;
type
{ TDataContext }
TDataContext = class
private
FParent: TDataContext;
public
function ResolvePath(const Path: array of String): Variant; virtual; abstract;
property Parent: TDataContext read FParent;
end;
{ TRTTIDataContext }
TRTTIDataContext = class(TDataContext)
private
FInstance: TObject;
public
constructor Create(Instance: TObject);
function ResolvePath(const Path: array of String): Variant; override;
end;
{ TJSONDataContext }
TJSONDataContext = class(TDataContext)
private
FData: TJSONData;
public
constructor Create(Data: TJSONData);
function ResolvePath(const Path: array of String): Variant; override;
end;
function CreateContext(Instance: TObject): TDataContext;
implementation
uses
typinfo;
function CreateContext(Instance: TObject): TDataContext;
begin
if Instance is TJSONData then
Result := TJSONDataContext.Create(TJSONData(Instance))
else
Result := TRTTIDataContext.Create(Instance);
end;
{ TJSONDataContext }
constructor TJSONDataContext.Create(Data: TJSONData);
begin
FData := Data;
end;
function TJSONDataContext.ResolvePath(const Path: array of String): Variant;
var
i: Integer;
ObjData: TJSONObject;
PropData: TJSONData;
PropName: String;
begin
Result := Unassigned;
if FData.JSONType = jtObject then
begin
ObjData := TJSONObject(FData);
for i := Low(Path) to High(Path) do
begin
PropName := Path[i];
if i = High(Path) then
Result := ObjData.Get(PropName)
else
begin
PropData := ObjData.Find(PropName, jtObject);
if PropData <> nil then
ObjData := TJSONObject(PropData)
else
break;
end;
end;
end;
end;
{ TRTTIDataContext }
constructor TRTTIDataContext.Create(Instance: TObject);
begin
FInstance := Instance;
end;
function TRTTIDataContext.ResolvePath(const Path: array of String): Variant;
var
i: Integer;
PropName: String;
PropInfo: PPropInfo;
Obj: TObject;
begin
Result := Unassigned;
Obj := FInstance;
for i := Low(Path) to High(Path) do
begin
PropName := Path[i];
PropInfo := GetPropInfo(Obj, PropName);
if PropInfo = nil then
break;
if i = High(Path) then
Result := GetPropValue(Obj, PropName)
else
begin
if PropInfo^.PropType^.Kind = tkClass then
begin
Obj := GetObjectProp(Obj, PropInfo);
if Obj = nil then
break;
end
else
break;
end;
end;
end;
end.
|
unit CMC.EVNTrace;
(*++
Copyright (c) Microsoft Corporation. All rights reserved.
Module Name:
EvnTrace.h
Abstract:
Public headers for event tracing control applications,
consumers and providers
--*)
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Windows, Classes, SysUtils;
const
// EventTraceGuid is used to identify a event tracing session
EventTraceGuid: TGUID = '{68fdd900-4a3e-11d1-84f4-0000f80464e3}';
// SystemTraceControlGuid. Used to specify event tracing for kernel
SystemTraceControlGuid: TGUID = '{9e814aad-3204-11d2-9a82-006008a86939}';
// EventTraceConfigGuid. Used to report system configuration records
EventTraceConfigGuid: TGUID = '{01853a65-418f-4f36-aefc-dc0f1d2fd235}';
// DefaultTraceSecurityGuid. Specifies the default event tracing security
DefaultTraceSecurityGuid: TGUID = '{0811c1af-7a07-4a06-82ed-869455cdf713}';
// PrivateLoggerNotificationGuid
// Used for private cross-process logger notifications.
PrivateLoggerNotificationGuid: TGUID = '{3595ab5c-042a-4c8e-b942-2d059bfeb1b1}';
KERNEL_LOGGER_NAMEW: PWideChar = 'NT Kernel Logger';
GLOBAL_LOGGER_NAMEW: PWideChar = 'GlobalLogger';
EVENT_LOGGER_NAMEW: PWideChar = 'EventLog';
DIAG_LOGGER_NAMEW: PWideChar = 'DiagLog';
KERNEL_LOGGER_NAMEA: PAnsiChar = 'NT Kernel Logger';
GLOBAL_LOGGER_NAMEA: PAnsiChar = 'GlobalLogger';
EVENT_LOGGER_NAMEA: PAnsiChar = 'EventLog';
DIAG_LOGGER_NAMEA: PAnsiChar = 'DiagLog';
MAX_MOF_FIELDS = 16; // Limit of USE_MOF_PTR fields
//types for event data going to System Event Logger
// SYSTEM_EVENT_TYPE 1
// predefined generic event types ($00 to $09 reserved).
EVENT_TRACE_TYPE_INFO = $00; // Info or point event
EVENT_TRACE_TYPE_START = $01; // Start event
EVENT_TRACE_TYPE_END = $02; // End event
EVENT_TRACE_TYPE_STOP = $02; // Stop event (WinEvent compatible)
EVENT_TRACE_TYPE_DC_START = $03; // Collection start marker
EVENT_TRACE_TYPE_DC_END = $04; // Collection end marker
EVENT_TRACE_TYPE_EXTENSION = $05; // Extension/continuation
EVENT_TRACE_TYPE_REPLY = $06; // Reply event
EVENT_TRACE_TYPE_DEQUEUE = $07; // De-queue event
EVENT_TRACE_TYPE_RESUME = $07; // Resume event (WinEvent compatible)
EVENT_TRACE_TYPE_CHECKPOINT = $08; // Generic checkpoint event
EVENT_TRACE_TYPE_SUSPEND = $08; // Suspend event (WinEvent compatible)
EVENT_TRACE_TYPE_WINEVT_SEND = $09; // Send Event (WinEvent compatible)
EVENT_TRACE_TYPE_WINEVT_RECEIVE = $F0; // Receive Event (WinEvent compatible)
// Predefined Event Tracing Levels for Software/Debug Tracing
// Trace Level is UCHAR and passed in through the EnableLevel parameter
// in EnableTrace API. It is retrieved by the provider using the
// GetTraceEnableLevel macro.It should be interpreted as an integer value
// to mean everything at or below that level will be traced.
// Here are the possible Levels.
TRACE_LEVEL_NONE = 0; // Tracing is not on
TRACE_LEVEL_CRITICAL = 1; // Abnormal exit or termination
TRACE_LEVEL_FATAL = 1; // Deprecated name for Abnormal exit or termination
TRACE_LEVEL_ERROR = 2; // Severe errors that need logging
TRACE_LEVEL_WARNING = 3; // Warnings such as allocation failure
TRACE_LEVEL_INFORMATION = 4; // Includes non-error cases(e.g.,Entry-Exit)
TRACE_LEVEL_VERBOSE = 5; // Detailed traces from intermediate steps
TRACE_LEVEL_RESERVED6 = 6;
TRACE_LEVEL_RESERVED7 = 7;
TRACE_LEVEL_RESERVED8 = 8;
TRACE_LEVEL_RESERVED9 = 9;
// Event types for Process & Threads
EVENT_TRACE_TYPE_LOAD = $0A; // Load image
EVENT_TRACE_TYPE_TERMINATE = $0B; // Terminate Process
// Event types for IO subsystem
EVENT_TRACE_TYPE_IO_READ = $0A;
EVENT_TRACE_TYPE_IO_WRITE = $0B;
EVENT_TRACE_TYPE_IO_READ_INIT = $0C;
EVENT_TRACE_TYPE_IO_WRITE_INIT = $0D;
EVENT_TRACE_TYPE_IO_FLUSH = $0E;
EVENT_TRACE_TYPE_IO_FLUSH_INIT = $0F;
EVENT_TRACE_TYPE_IO_REDIRECTED_INIT = $10;
// Event types for Memory subsystem
EVENT_TRACE_TYPE_MM_TF = $0A; // Transition fault
EVENT_TRACE_TYPE_MM_DZF = $0B; // Demand Zero fault
EVENT_TRACE_TYPE_MM_COW = $0C; // Copy on Write
EVENT_TRACE_TYPE_MM_GPF = $0D; // Guard Page fault
EVENT_TRACE_TYPE_MM_HPF = $0E; // Hard page fault
EVENT_TRACE_TYPE_MM_AV = $0F; // Access violation
// Event types for Network subsystem, all protocols
EVENT_TRACE_TYPE_SEND = $0A; // Send
EVENT_TRACE_TYPE_RECEIVE = $0B; // Receive
EVENT_TRACE_TYPE_CONNECT = $0C; // Connect
EVENT_TRACE_TYPE_DISCONNECT = $0D; // Disconnect
EVENT_TRACE_TYPE_RETRANSMIT = $0E; // ReTransmit
EVENT_TRACE_TYPE_ACCEPT = $0F; // Accept
EVENT_TRACE_TYPE_RECONNECT = $10; // ReConnect
EVENT_TRACE_TYPE_CONNFAIL = $11; // Fail
EVENT_TRACE_TYPE_COPY_TCP = $12; // Copy in PendData
EVENT_TRACE_TYPE_COPY_ARP = $13; // NDIS_STATUS_RESOURCES Copy
EVENT_TRACE_TYPE_ACKFULL = $14; // A full data ACK
EVENT_TRACE_TYPE_ACKPART = $15; // A Partial data ACK
EVENT_TRACE_TYPE_ACKDUP = $16; // A Duplicate data ACK
// Event Types for the Header (to handle internal event headers)
EVENT_TRACE_TYPE_GUIDMAP = $0A;
EVENT_TRACE_TYPE_CONFIG = $0B;
EVENT_TRACE_TYPE_SIDINFO = $0C;
EVENT_TRACE_TYPE_SECURITY = $0D;
EVENT_TRACE_TYPE_DBGID_RSDS = $40;
// Event Types for Registry subsystem
EVENT_TRACE_TYPE_REGCREATE = $0A; // NtCreateKey
EVENT_TRACE_TYPE_REGOPEN = $0B; // NtOpenKey
EVENT_TRACE_TYPE_REGDELETE = $0C; // NtDeleteKey
EVENT_TRACE_TYPE_REGQUERY = $0D; // NtQueryKey
EVENT_TRACE_TYPE_REGSETVALUE = $0E; // NtSetValueKey
EVENT_TRACE_TYPE_REGDELETEVALUE = $0F; // NtDeleteValueKey
EVENT_TRACE_TYPE_REGQUERYVALUE = $10; // NtQueryValueKey
EVENT_TRACE_TYPE_REGENUMERATEKEY = $11; // NtEnumerateKey
EVENT_TRACE_TYPE_REGENUMERATEVALUEKEY = $12; // NtEnumerateValueKey
EVENT_TRACE_TYPE_REGQUERYMULTIPLEVALUE = $13; // NtQueryMultipleValueKey
EVENT_TRACE_TYPE_REGSETINFORMATION = $14; // NtSetInformationKey
EVENT_TRACE_TYPE_REGFLUSH = $15; // NtFlushKey
EVENT_TRACE_TYPE_REGKCBCREATE = $16; // KcbCreate
EVENT_TRACE_TYPE_REGKCBDELETE = $17; // KcbDelete
EVENT_TRACE_TYPE_REGKCBRUNDOWNBEGIN = $18; // KcbRundownBegin
EVENT_TRACE_TYPE_REGKCBRUNDOWNEND = $19; // KcbRundownEnd
EVENT_TRACE_TYPE_REGVIRTUALIZE = $1A; // VirtualizeKey
EVENT_TRACE_TYPE_REGCLOSE = $1B; // NtClose (KeyObject)
EVENT_TRACE_TYPE_REGSETSECURITY = $1C; // SetSecurityDescriptor (KeyObject)
EVENT_TRACE_TYPE_REGQUERYSECURITY = $1D; // QuerySecurityDescriptor (KeyObject)
EVENT_TRACE_TYPE_REGCOMMIT = $1E; // CmKtmNotification (TRANSACTION_NOTIFY_COMMIT)
EVENT_TRACE_TYPE_REGPREPARE = $1F; // CmKtmNotification (TRANSACTION_NOTIFY_PREPARE)
EVENT_TRACE_TYPE_REGROLLBACK = $20; // CmKtmNotification (TRANSACTION_NOTIFY_ROLLBACK)
EVENT_TRACE_TYPE_REGMOUNTHIVE = $21; // NtLoadKey variations + system hives
// Event types for system configuration records
EVENT_TRACE_TYPE_CONFIG_CPU = $0A; // CPU Configuration
EVENT_TRACE_TYPE_CONFIG_PHYSICALDISK = $0B; // Physical Disk Configuration
EVENT_TRACE_TYPE_CONFIG_LOGICALDISK = $0C; // Logical Disk Configuration
EVENT_TRACE_TYPE_CONFIG_NIC = $0D; // NIC Configuration
EVENT_TRACE_TYPE_CONFIG_VIDEO = $0E; // Video Adapter Configuration
EVENT_TRACE_TYPE_CONFIG_SERVICES = $0F; // Active Services
EVENT_TRACE_TYPE_CONFIG_POWER = $10; // ACPI Configuration
EVENT_TRACE_TYPE_CONFIG_NETINFO = $11; // Networking Configuration
EVENT_TRACE_TYPE_CONFIG_OPTICALMEDIA = $12; // Optical Media Configuration
EVENT_TRACE_TYPE_CONFIG_IRQ = $15; // IRQ assigned to devices
EVENT_TRACE_TYPE_CONFIG_PNP = $16; // PnP device info
EVENT_TRACE_TYPE_CONFIG_IDECHANNEL = $17; // Primary/Secondary IDE channel Configuration
EVENT_TRACE_TYPE_CONFIG_NUMANODE = $18; // Numa configuration
EVENT_TRACE_TYPE_CONFIG_PLATFORM = $19; // Platform Configuration
EVENT_TRACE_TYPE_CONFIG_PROCESSORGROUP = $1A; // Processor Group Configuration
EVENT_TRACE_TYPE_CONFIG_PROCESSORNUMBER = $1B; // ProcessorIndex -> ProcNumber mapping
EVENT_TRACE_TYPE_CONFIG_DPI = $1C; // Display DPI Configuration
EVENT_TRACE_TYPE_CONFIG_CI_INFO = $1D; // Display System Code Integrity Information
EVENT_TRACE_TYPE_CONFIG_MACHINEID = $1E; // SQM Machine Id
EVENT_TRACE_TYPE_CONFIG_DEFRAG = $1F; // Logical Disk Defragmenter Information
EVENT_TRACE_TYPE_CONFIG_MOBILEPLATFORM = $20; // Mobile Platform Configuration
EVENT_TRACE_TYPE_CONFIG_DEVICEFAMILY = $21; // Device Family Information
EVENT_TRACE_TYPE_CONFIG_FLIGHTID = $22; // Flights on the machine
EVENT_TRACE_TYPE_CONFIG_PROCESSOR = $23; // CentralProcessor records
// Event types for Optical IO subsystem
EVENT_TRACE_TYPE_OPTICAL_IO_READ = $37;
EVENT_TRACE_TYPE_OPTICAL_IO_WRITE = $38;
EVENT_TRACE_TYPE_OPTICAL_IO_FLUSH = $39;
EVENT_TRACE_TYPE_OPTICAL_IO_READ_INIT = $3a;
EVENT_TRACE_TYPE_OPTICAL_IO_WRITE_INIT = $3b;
EVENT_TRACE_TYPE_OPTICAL_IO_FLUSH_INIT = $3c;
// Event types for Filter Manager
EVENT_TRACE_TYPE_FLT_PREOP_INIT = $60; // Minifilter preop initiation
EVENT_TRACE_TYPE_FLT_POSTOP_INIT = $61; // Minifilter postop initiation
EVENT_TRACE_TYPE_FLT_PREOP_COMPLETION = $62; // Minifilter preop completion
EVENT_TRACE_TYPE_FLT_POSTOP_COMPLETION = $63; // Minifilter postop completion
EVENT_TRACE_TYPE_FLT_PREOP_FAILURE = $64; // Minifilter failed preop
EVENT_TRACE_TYPE_FLT_POSTOP_FAILURE = $65; // Minifilter failed postop
// Enable flags for Kernel Events
EVENT_TRACE_FLAG_PROCESS = $00000001; // process start & end
EVENT_TRACE_FLAG_THREAD = $00000002; // thread start & end
EVENT_TRACE_FLAG_IMAGE_LOAD = $00000004; // image load
EVENT_TRACE_FLAG_DISK_IO = $00000100; // physical disk IO
EVENT_TRACE_FLAG_DISK_FILE_IO = $00000200; // requires disk IO
EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS = $00001000; // all page faults
EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS = $00002000; // hard faults only
EVENT_TRACE_FLAG_NETWORK_TCPIP = $00010000; // tcpip send & receive
EVENT_TRACE_FLAG_REGISTRY = $00020000; // registry calls
EVENT_TRACE_FLAG_DBGPRINT = $00040000; // DbgPrint(ex) Calls
// Enable flags for Kernel Events on Vista and above
EVENT_TRACE_FLAG_PROCESS_COUNTERS = $00000008; // process perf counters
EVENT_TRACE_FLAG_CSWITCH = $00000010; // context switches
EVENT_TRACE_FLAG_DPC = $00000020; // deferred procedure calls
EVENT_TRACE_FLAG_INTERRUPT = $00000040; // interrupts
EVENT_TRACE_FLAG_SYSTEMCALL = $00000080; // system calls
EVENT_TRACE_FLAG_DISK_IO_INIT = $00000400; // physical disk IO initiation
EVENT_TRACE_FLAG_ALPC = $00100000; // ALPC traces
EVENT_TRACE_FLAG_SPLIT_IO = $00200000; // split io traces (VolumeManager)
EVENT_TRACE_FLAG_DRIVER = $00800000; // driver delays
EVENT_TRACE_FLAG_PROFILE = $01000000; // sample based profiling
EVENT_TRACE_FLAG_FILE_IO = $02000000; // file IO
EVENT_TRACE_FLAG_FILE_IO_INIT = $04000000; // file IO initiation
// Enable flags for Kernel Events on Win7 and above
EVENT_TRACE_FLAG_DISPATCHER = $00000800; // scheduler (ReadyThread)
EVENT_TRACE_FLAG_VIRTUAL_ALLOC = $00004000; // VM operations
// Enable flags for Kernel Events on Win8 and above
EVENT_TRACE_FLAG_VAMAP = $00008000; // map/unmap (excluding images)
EVENT_TRACE_FLAG_NO_SYSCONFIG = $10000000; // Do not do sys config rundown
// Enable flags for Kernel Events on Threshold and above
EVENT_TRACE_FLAG_JOB = $00080000; // job start & end
EVENT_TRACE_FLAG_DEBUG_EVENTS = $00400000; // debugger events (break/continue/...)
// Pre-defined Enable flags for everybody else
EVENT_TRACE_FLAG_EXTENSION = $80000000; // Indicates more flags
EVENT_TRACE_FLAG_FORWARD_WMI = $40000000; // Can forward to WMI
EVENT_TRACE_FLAG_ENABLE_RESERVE = $20000000; // Reserved
// Logger Mode flags
EVENT_TRACE_FILE_MODE_NONE = $00000000; // Logfile is off
EVENT_TRACE_FILE_MODE_SEQUENTIAL = $00000001; // Log sequentially
EVENT_TRACE_FILE_MODE_CIRCULAR = $00000002; // Log in circular manner
EVENT_TRACE_FILE_MODE_APPEND = $00000004; // Append sequential log
EVENT_TRACE_REAL_TIME_MODE = $00000100; // Real time mode on
EVENT_TRACE_DELAY_OPEN_FILE_MODE = $00000200; // Delay opening file
EVENT_TRACE_BUFFERING_MODE = $00000400; // Buffering mode only
EVENT_TRACE_PRIVATE_LOGGER_MODE = $00000800; // Process Private Logger
EVENT_TRACE_ADD_HEADER_MODE = $00001000; // Add a logfile header
EVENT_TRACE_USE_GLOBAL_SEQUENCE = $00004000; // Use global sequence no.
EVENT_TRACE_USE_LOCAL_SEQUENCE = $00008000; // Use local sequence no.
EVENT_TRACE_RELOG_MODE = $00010000; // Relogger
EVENT_TRACE_USE_PAGED_MEMORY = $01000000; // Use pageable buffers
// Logger Mode flags on XP and above
EVENT_TRACE_FILE_MODE_NEWFILE = $00000008; // Auto-switch log file
EVENT_TRACE_FILE_MODE_PREALLOCATE = $00000020; // Pre-allocate mode
// Logger Mode flags on Vista and above
EVENT_TRACE_NONSTOPPABLE_MODE = $00000040; // Session cannot be stopped (Autologger only)
EVENT_TRACE_SECURE_MODE = $00000080; // Secure session
EVENT_TRACE_USE_KBYTES_FOR_SIZE = $00002000; // Use KBytes as file size unit
EVENT_TRACE_PRIVATE_IN_PROC = $00020000; // In process private logger
EVENT_TRACE_MODE_RESERVED = $00100000; // Reserved bit, used to signal Heap/Critsec tracing
// Logger Mode flags on Win7 and above
EVENT_TRACE_NO_PER_PROCESSOR_BUFFERING = $10000000; // Use this for low frequency sessions.
// Logger Mode flags on Win8 and above
EVENT_TRACE_SYSTEM_LOGGER_MODE = $02000000; // Receive events from SystemTraceProvider
EVENT_TRACE_ADDTO_TRIAGE_DUMP = $80000000; // Add ETW buffers to triage dumps
EVENT_TRACE_STOP_ON_HYBRID_SHUTDOWN = $00400000; // Stop on hybrid shutdown
EVENT_TRACE_PERSIST_ON_HYBRID_SHUTDOWN = $00800000; // Persist on hybrid shutdown
// Logger Mode flags on Blue and above
EVENT_TRACE_INDEPENDENT_SESSION_MODE = $08000000; // Independent logger session
// Logger Mode flags on Redstone and above
EVENT_TRACE_COMPRESSED_MODE = $04000000; // Compressed logger session.
// ControlTrace Codes
EVENT_TRACE_CONTROL_QUERY = 0;
EVENT_TRACE_CONTROL_STOP = 1;
EVENT_TRACE_CONTROL_UPDATE = 2;
// Flush ControlTrace Codes for XP and above
EVENT_TRACE_CONTROL_FLUSH = 3; // Flushes all the buffers
EVENT_TRACE_CONTROL_INCREMENT_FILE = 4; // Causes a session with EVENT_TRACE_FILE_MODE_NEWFILE
// to switch to the next file before the automatic
// switching criteria is met
// Flags used by WMI Trace Message
// Note that the order or value of these flags should NOT be changed as they are processed
// in this order.
TRACE_MESSAGE_SEQUENCE = 1; // Message should include a sequence number
TRACE_MESSAGE_GUID = 2; // Message includes a GUID
TRACE_MESSAGE_COMPONENTID = 4; // Message has no GUID, Component ID instead
TRACE_MESSAGE_TIMESTAMP = 8; // Message includes a timestamp
TRACE_MESSAGE_PERFORMANCE_TIMESTAMP = 16; // *Obsolete* Clock type is controlled by the logger
TRACE_MESSAGE_SYSTEMINFO = 32; // Message includes system information TID,PID
// Vista flags set by system to indicate provider pointer size.
TRACE_MESSAGE_POINTER32 = $0040; // Message logged by 32 bit provider
TRACE_MESSAGE_POINTER64 = $0080; // Message logged by 64 bit provider
TRACE_MESSAGE_FLAG_MASK = $FFFF; // Only the lower 16 bits of flags are placed in the message
// those above 16 bits are reserved for local processing
// Maximum size allowed for a single TraceMessage message.
// N.B. This limit was increased from 8K to 64K in Win8.
TRACE_MESSAGE_MAXIMUM_SIZE = (64 * 1024);
// Flags to indicate to consumer which fields
// in the EVENT_TRACE_HEADER are valid
EVENT_TRACE_USE_PROCTIME = $0001; // ProcessorTime field is valid
EVENT_TRACE_USE_NOCPUTIME = $0002; // No Kernel/User/Processor Times
// TRACE_HEADER_FLAG values are used in the Flags field of EVENT_TRACE_HEADER
// structure while calling into TraceEvent API
TRACE_HEADER_FLAG_USE_TIMESTAMP = $00000200;
TRACE_HEADER_FLAG_TRACED_GUID = $00020000; // denotes a trace
TRACE_HEADER_FLAG_LOG_WNODE = $00040000; // request to log Wnode
TRACE_HEADER_FLAG_USE_GUID_PTR = $00080000; // Guid is actually a pointer
TRACE_HEADER_FLAG_USE_MOF_PTR = $00100000; // MOF data are dereferenced
// Following are structures and macros for use with USE_MOF_PTR
// Trace data types
ETW_NULL_TYPE_VALUE = 0;
ETW_OBJECT_TYPE_VALUE = 1;
ETW_STRING_TYPE_VALUE = 2;
ETW_SBYTE_TYPE_VALUE = 3;
ETW_BYTE_TYPE_VALUE = 4;
ETW_INT16_TYPE_VALUE = 5;
ETW_UINT16_TYPE_VALUE = 6;
ETW_INT32_TYPE_VALUE = 7;
ETW_UINT32_TYPE_VALUE = 8;
ETW_INT64_TYPE_VALUE = 9;
ETW_UINT64_TYPE_VALUE = 10;
ETW_CHAR_TYPE_VALUE = 11;
ETW_SINGLE_TYPE_VALUE = 12;
ETW_DOUBLE_TYPE_VALUE = 13;
ETW_BOOLEAN_TYPE_VALUE = 14;
ETW_DECIMAL_TYPE_VALUE = 15;
// Extended types
ETW_GUID_TYPE_VALUE = 101;
ETW_ASCIICHAR_TYPE_VALUE = 102;
ETW_ASCIISTRING_TYPE_VALUE = 103;
ETW_COUNTED_STRING_TYPE_VALUE = 104;
ETW_POINTER_TYPE_VALUE = 105;
ETW_SIZET_TYPE_VALUE = 106;
ETW_HIDDEN_TYPE_VALUE = 107;
ETW_BOOL_TYPE_VALUE = 108;
ETW_COUNTED_ANSISTRING_TYPE_VALUE = 109;
ETW_REVERSED_COUNTED_STRING_TYPE_VALUE = 110;
ETW_REVERSED_COUNTED_ANSISTRING_TYPE_VALUE = 111;
ETW_NON_NULL_TERMINATED_STRING_TYPE_VALUE = 112;
ETW_REDUCED_ANSISTRING_TYPE_VALUE = 113;
ETW_REDUCED_STRING_TYPE_VALUE = 114;
ETW_SID_TYPE_VALUE = 115;
ETW_VARIANT_TYPE_VALUE = 116;
ETW_PTVECTOR_TYPE_VALUE = 117;
ETW_WMITIME_TYPE_VALUE = 118;
ETW_DATETIME_TYPE_VALUE = 119;
ETW_REFRENCE_TYPE_VALUE = 120;
type
TTRACEHANDLE = ULONG64;
PTRACEHANDLE = ^TTRACEHANDLE;
TETW_COMPRESSION_RESUMPTION_MODE = (
EtwCompressionModeRestart = 0,
EtwCompressionModeNoDisable = 1,
EtwCompressionModeNoRestart = 2);
// Trace header for all legacy events.
{$IFNDEF FPC}
ULONG64 = UInt64;
{$ENDIF}
TEVENT_TRACE_HEADER = record // overlays WNODE_HEADER
Size: USHORT; // Size of entire record
DUMMYUNIONNAME: record
case integer of
0: (FieldTypeFlags: USHORT); // Indicates valid fields
1: (HeaderType: UCHAR; // Header type - internal use only
MarkerFlags: UCHAR); // Marker - internal use only
end;
DUMMYUNIONNAME2: record
case integer of
0: (Version: ULONG);
1: (_Type: UCHAR; // event type
Level: UCHAR; // trace instrumentation level
_Version: USHORT); // version of trace record
end;
ThreadId: ULONG; // Thread Id
ProcessId: ULONG; // Process Id
TimeStamp: LARGE_INTEGER; // time when event happens
DUMMYUNIONNAME3: record
case integer of
0: (Guid: TGUID); // Guid that identifies event
1: (GuidPtr: ULONGLONG); // use with WNODE_FLAG_USE_GUID_PTR
end;
DUMMYUNIONNAME4: record
case integer of
0: (KernelTime: ULONG; // Kernel Mode CPU ticks
UserTime: ULONG); // User mode CPU ticks
1: (ProcessorTime: ULONG64); // Processor Clock
2: (ClientContext: ULONG; // Reserved
Flags: ULONG); // Event Flags
end;
end;
PEVENT_TRACE_HEADER = ^TEVENT_TRACE_HEADER;
implementation
end.
|
(* Copyright 2018 B. Zoltán Gorza
*
* This file is part of Math is Fun!, released under the Modified BSD License.
*)
{ This is the unit of the TOperation class and its supporting types. }
unit OperationClass;
{$mode objfpc}
{$H+}
interface
type
{ Pointer of an operation function }
POperationFunction = function(const a: Integer; const b: Integer): Double;
{ 3 characters long short name }
TShortName = String[3];
{ General name (variable long) }
TName = String;
{ Set of operations --- used in some classes, but should not be used
explicitely! }
TOp = (add, sub, mul, dvi, ind, mdu{, exo});
{ This class contains every needed information of an operation
and the function that is used for this operation. }
TOperation = class
private
_op: TOp;
_sign: Char;
_nam: TShortName;
_name: TName;
_func: POperationFunction;
public
{ The sign of an operation (e.g. '+', '/'... }
property sign: Char read _sign;
{ Short name of an operation (e.g. 'add', 'div'... }
property nam: TShortName read _nam;
{ Name of an operation (e.g. 'addition, 'division'... }
property name: TName read _name;
{ The function of an operation that is used for calculations. }
property func: POperationFunction read _func;
{ The type of this operation. }
property op: TOp read _op;
{ Constructor of an operation.
@param(o Operation)
@param(s Sign)
@param(n3 Short name)
@param(n Name)
@param(f Function) }
constructor create(const o: TOp;
const s: Char;
const n3: TShortName;
const n: TName;
const f: POperationFunction);
end;
{ Fixed long array of operations
@seealso(NUMBER_OF_OPERATIONS)}
TOperationArray = Array[0..5{6}] of TOperation;
const
{ Number of operations }
NUMBER_OF_OPERATIONS = 6; // 7 ;
{ Shorthand for Number Of Operations
@seealso(NUMBER_OF_OPERATIONS)}
NOO = NUMBER_OF_OPERATIONS;
{ Constant array of operations, contains a @link(TOperation) instance for
every operation.
Initially its values are @nil, but it gets new values during
initialization that are used.
@seealso(TOperation)
@seealso(TOperationArray)}
OPERATIONS: TOperationArray = (Nil, Nil, Nil, Nil, Nil, Nil); // , Nil);
//function modulo(const a: Integer; const b: Integer): Double; // just for tests
implementation // --------------------------------------------------------------
uses
Math;
constructor TOperation.create(const o: TOp;
const s: Char;
const n3: TShortName;
const n: TName;
const f: POperationFunction);
begin
_op := o;
_sign := s;
_nam := n3;
_name := n;
_func := f;
end;
function addition(const a: Integer; const b: Integer): Double;
begin
addition := a + b;
end;
function subtraction(const a: Integer; const b: Integer): Double;
begin
subtraction := a - b;
end;
function multiplication(const a: Integer; const b: Integer): Double;
begin
multiplication := a * b;
end;
function division(const a: Integer; const b: Integer): Double;
begin
division := a / b;
end;
function intdiv(const a: Integer; const b: Integer): Double;
begin
intdiv := a div b;
end;
function modulo(const a: Integer; const b: Integer): Double;
begin
modulo := a mod b;
end;
function exponentiation(const a: Integer; const b: Integer): Double;
begin
exponentiation := power(a, b);
end;
initialization // --------------------------------------------------------------
OPERATIONS[0] := TOperation.create(add,
'+',
'add',
'addition',
@addition);
OPERATIONS[1] := TOperation.create(sub,
'-',
'sub',
'subtraction',
@subtraction);
OPERATIONS[2] := TOperation.create(mul,
'*',
'mul',
'multiplication',
@multiplication);
OPERATIONS[3] := TOperation.create(dvi,
'/',
'div',
'division',
@division);
OPERATIONS[4] := TOperation.create(ind,
'\',
'ind',
'integer division',
@intdiv);
OPERATIONS[5] := TOperation.create(mdu,
'%',
'mod',
'modulo',
@modulo);
{OPERATIONS[6] := TOperation.create(exo,
'^',
'exp',
'exponentiation',
@exponentiation);}
end.
|
unit InflatablesList_Manager_Sort;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
InflatablesList_Types,
InflatablesList_Manager_Base;
type
TILManager_Sort = class(TILManager_Base)
protected
fReversedSort: Boolean;
fCaseSensSort: Boolean;
fUsedSortSett: TILSortingSettings;
fDefaultSortSett: TILSortingSettings;
fActualSortSett: TILSortingSettings;
fSortingProfiles: TILSortingProfiles;
procedure SetReversedSort(Value: Boolean); virtual;
procedure SetCaseSensSort(Value: Boolean); virtual;
Function GetSortProfileCount: Integer; virtual;
Function GetSortProfile(Index: Integer): TILSortingProfile; virtual;
procedure SetSortProfile(Index: Integer; Value: TILSortingProfile); virtual;
procedure InitializeSortingSettings; virtual;
procedure FinalizeSortingSettings; virtual;
procedure Initialize; override;
procedure Finalize; override;
Function ItemCompare(Idx1,Idx2: Integer; CaseSensitive: Boolean): Integer; virtual;
Function ItemCompare_CaseSensitive(Idx1,Idx2: Integer): Integer; virtual;
Function ItemCompare_CaseInsensitive(Idx1,Idx2: Integer): Integer; virtual;
procedure ThisCopyFrom_Sort(Source: TILManager_Base; UniqueCopy: Boolean); virtual;
public
constructor CreateAsCopy(Source: TILManager_Base; UniqueCopy: Boolean); override;
procedure CopyFrom(Source: TILManager_Base; UniqueCopy: Boolean); override;
Function SortingProfileIndexOf(const Name: String): Integer; virtual;
Function SortingProfileAdd(const Name: String): Integer; virtual;
procedure SortingProfileRename(Index: Integer; const NewName: String); virtual;
procedure SortingProfileExchange(Idx1,Idx2: Integer); virtual;
procedure SortingProfileDelete(Index: Integer); virtual;
procedure SortingProfileClear; virtual;
procedure ItemSort(SortingProfile: Integer); overload; virtual;
procedure ItemSort; overload; virtual;
property ReversedSort: Boolean read fReversedSort write SetReversedSort;
property CaseSensitiveSort: Boolean read fCaseSensSort write SetCaseSensSort;
property UsedSortingSettings: TILSortingSettings read fUsedSortSett;
property DefaultSortingSettings: TILSortingSettings read fDefaultSortSett write fDefaultSortSett;
property ActualSortingSettings: TILSortingSettings read fActualSortSett write fActualSortSett;
property SortingProfileCount: Integer read GetSortProfileCount;
property SortingProfiles[Index: Integer]: TILSortingProfile read GetSortProfile write SetSortProfile;
end;
implementation
uses
SysUtils,
ListSorters,
InflatablesList_Utils;
procedure TILManager_Sort.SetReversedSort(Value: Boolean);
begin
If fReversedSort <> Value then
begin
fReversedSort := Value;
UpdateSettings;
end;
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.SetCaseSensSort(Value: Boolean);
begin
If fCaseSensSort <> Value then
begin
fCaseSensSort := Value;
UpdateSettings;
end;
end;
//------------------------------------------------------------------------------
Function TILManager_Sort.GetSortProfileCount: Integer;
begin
Result := Length(fSortingProfiles);
end;
//------------------------------------------------------------------------------
Function TILManager_Sort.GetSortProfile(Index: Integer): TILSortingProfile;
begin
If (Index >= Low(fSortingProfiles)) and (Index <= High(fSortingProfiles)) then
Result := fSortingProfiles[Index]
else
raise Exception.CreateFmt('TILManager_Sort.GetSortProfile: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.SetSortProfile(Index: Integer; Value: TILSortingProfile);
begin
If (Index >= Low(fSortingProfiles)) and (Index <= High(fSortingProfiles)) then
fSortingProfiles[Index] := IL_ThreadSafeCopy(Value)
else
raise Exception.CreateFmt('TILManager_Sort.SetSortProfile: Index (%d) out of bounds.',[Index]);
end;
//==============================================================================
procedure TILManager_Sort.InitializeSortingSettings;
begin
fReversedSort := False;
fCaseSensSort := False;
FillChar(fDefaultSortSett,SizeOf(fDefaultSortSett),0);
fDefaultSortSett.Count := 2;
fDefaultSortSett.Items[0].ItemValueTag := ilivtManufacturer;
fDefaultSortSett.Items[0].Reversed := False;
fDefaultSortSett.Items[1].ItemValueTag := ilivtNumID;
fDefaultSortSett.Items[1].Reversed := False;
fActualSortSett := fDefaultSortSett;
fUsedSortSett := fDefaultSortSett;
SetLength(fSortingProfiles,0);
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.FinalizeSortingSettings;
begin
SetLength(fSortingProfiles,0);
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.Initialize;
begin
inherited Initialize;
InitializeSortingSettings;
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.Finalize;
begin
FinalizeSortingSettings;
inherited Finalize;
end;
//------------------------------------------------------------------------------
Function TILManager_Sort.ItemCompare(Idx1,Idx2: Integer; CaseSensitive: Boolean): Integer;
var
i: Integer;
begin
Result := 0;
If Idx1 <> Idx2 then
begin
For i := Low(fUsedSortSett.Items) to Pred(fUsedSortSett.Count) do
Result := (Result shl 1) + fList[Idx1].Compare(fList[Idx2],
fUsedSortSett.Items[i].ItemValueTag,fUsedSortSett.Items[i].Reversed,CaseSensitive);
// stabilize sorting using indices
If Result = 0 then
Result := IL_SortCompareInt32(fList[Idx1].Index,fList[Idx2].Index);
end;
end;
//------------------------------------------------------------------------------
Function TILManager_Sort.ItemCompare_CaseSensitive(Idx1,Idx2: Integer): Integer;
begin
Result := ItemCompare(Idx1,Idx2,True);
end;
//------------------------------------------------------------------------------
Function TILManager_Sort.ItemCompare_CaseInsensitive(Idx1,Idx2: Integer): Integer;
begin
Result := ItemCompare(Idx1,Idx2,False);
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.ThisCopyFrom_Sort(Source: TILManager_Base; UniqueCopy: Boolean);
var
i: Integer;
begin
If Source is TILManager_Sort then
begin
fReversedSort := TILManager_Sort(Source).ReversedSort;
fCaseSensSort := TILManager_Sort(Source).CaseSensitiveSort;
fUsedSortSett := TILManager_Sort(Source).UsedSortingSettings;
fDefaultSortSett := TILManager_Sort(Source).DefaultSortingSettings;
fActualSortSett := TILManager_Sort(Source).ActualSortingSettings;
// copy new ones
SetLength(fSortingProfiles,TILManager_Sort(Source).SortingProfileCount);
For i := Low(fSortingProfiles) to High(fSortingProfiles) do
fSortingProfiles[i] := IL_ThreadSafeCopy(TILManager_Sort(Source).SortingProfiles[i]);
end;
end;
//==============================================================================
constructor TILManager_Sort.CreateAsCopy(Source: TILManager_Base; UniqueCopy: Boolean);
begin
inherited CreateAsCopy(Source,UniqueCopy);
ThisCopyFrom_Sort(Source,UniqueCopy);
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.CopyFrom(Source: TILManager_Base; UniqueCopy: Boolean);
begin
inherited CopyFrom(Source,UniqueCopy);
ThisCopyFrom_Sort(Source,UniqueCopy);
end;
//------------------------------------------------------------------------------
Function TILManager_Sort.SortingProfileIndexOf(const Name: String): Integer;
var
i: Integer;
begin
Result := -1;
For i := Low(fSortingProfiles) to High(fSortingProfiles) do
If IL_SameText(fSortingProfiles[i].Name,Name) then
begin
Result := i;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
Function TILManager_Sort.SortingProfileAdd(const Name: String): Integer;
begin
SetLength(fSortingProfiles,Length(fSortingProfiles) + 1);
Result := High(fSortingProfiles);
fSortingProfiles[Result].Name := Name;
UniqueString(fSortingProfiles[Result].Name);
FillChar(fSortingProfiles[Result].Settings,SizeOf(TILSortingSettings),0);
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.SortingProfileRename(Index: Integer; const NewName: String);
begin
If (Index >= Low(fSortingProfiles)) and (Index <= High(fSortingProfiles)) then
begin
fSortingProfiles[Index].Name := NewName;
UniqueString(fSortingProfiles[Index].Name);
end
else raise Exception.CreateFmt('TILManager_Sort.SortingProfileRename: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.SortingProfileExchange(Idx1,Idx2: Integer);
var
Temp: TILSortingProfile;
begin
If Idx1 <> Idx2 then
begin
// sanity checks
If (Idx1 < Low(fSortingProfiles)) or (Idx1 > High(fSortingProfiles)) then
raise Exception.CreateFmt('TILManager_Sort.SortingProfileExchange: First index (%d) out of bounds.',[Idx1]);
If (Idx2 < Low(fSortingProfiles)) or (Idx2 > High(fSortingProfiles)) then
raise Exception.CreateFmt('TILManager_Sort.SortingProfileExchange: Second index (%d) out of bounds.',[Idx2]);
Temp := fSortingProfiles[Idx1];
fSortingProfiles[Idx1] := fSortingProfiles[Idx2];
fSortingProfiles[Idx2] := Temp;
end;
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.SortingProfileDelete(Index: Integer);
var
i: Integer;
begin
If (Index >= Low(fSortingProfiles)) and (Index <= High(fSortingProfiles)) then
begin
For i := Index to Pred(High(fSortingProfiles)) do
fSortingProfiles[Index] := fSortingProfiles[Index + 1];
SetLength(fSortingProfiles,Length(fSortingProfiles) - 1);
end
else raise Exception.CreateFmt('TILManager_Sort.SortingProfileDelete: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.SortingProfileClear;
begin
SetLength(fSortingProfiles,0);
end;
//------------------------------------------------------------------------------
procedure TILManager_Sort.ItemSort(SortingProfile: Integer);
var
Sorter: TListSorter;
begin
If Length(fList) > 1 then
begin
ReIndex; // to be sure
case SortingProfile of
-2: fUsedSortSett := fDefaultSortSett;
-1: fUsedSortSett := fActualSortSett;
else
If (SortingProfile >= Low(fSortingProfiles)) and (SortingProfile <= High(fSortingProfiles)) then
fUsedSortSett := fSortingProfiles[SortingProfile].Settings
else
raise Exception.CreateFmt('TILManager_Sort.ItemSort: Invalid sorting profile index (%d).',[SortingProfile]);
end;
If fCaseSensSort then
Sorter := TListQuickSorter.Create(ItemCompare_CaseSensitive,ItemExchange)
else
Sorter := TListQuickSorter.Create(ItemCompare_CaseInsensitive,ItemExchange);
try
fSorting := True;
try
Sorter.Reversed := fReversedSort;
Sorter.Sort(ItemLowIndex,ItemHighIndex);
finally
fSorting := False;
end;
finally
Sorter.Free;
end;
ReIndex;
UpdateList;
end;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TILManager_Sort.ItemSort;
begin
ItemSort(-1);
end;
end.
|
/// <summary> 使用Prim算法求图的最小生成树 </summary>
unit DSA.Graph.LazyPrimMST;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Tree.Heap,
DSA.Interfaces.DataStructure,
DSA.Interfaces.Comparer,
DSA.List_Stack_Queue.ArrayList,
DSA.Graph.Edge;
type
generic TLazyPrimMST<T> = class
private
type
TArr_bool = specialize TArray<boolean>;
TEdge_T = specialize TEdge<T>;
TMinHeap = specialize THeap<TEdge_T, TEdge_T.TEdgeComparer>;
TList_Edge = specialize TArrayList<TEdge_T>;
TArrEdge = specialize TArray<TEdge_T>;
TWeightGraph_T = specialize TWeightGraph<T>;
var
__g: TWeightGraph_T;
__pq: TMinHeap; // 最小堆, 算法辅助数据结构
__marked: TArr_bool; // 标记数组, 在算法运行过程中标记节点i是否被访问
__mstList: TList_Edge; // 最小生成树所包含的所有边
__mstWeight: T; // 最小生成树的权值
/// <summary> 访问节点v </summary>
procedure __visit(v: integer);
public
constructor Create(g: TWeightGraph_T);
destructor Destroy; override;
/// <summary> 返回最小生成树的所有边 </summary>
function MstEdges: TArrEdge;
/// <summary> 返回最小生成树的权值 </summary>
function Weight: T;
end;
procedure Main;
implementation
uses
DSA.Graph.DenseWeightedGraph,
DSA.Graph.SparseWeightedGraph,
DSA.Utils;
type
TDenseWeightedGraph_dbl = specialize TDenseWeightedGraph<double>;
TSparseWeightedGraph_dbl = specialize TSparseWeightedGraph<double>;
TWeightGraph_dbl = specialize TWeightGraph<double>;
TReadGraphWeight_dbl = specialize TReadGraphWeight<double>;
TLazyPrimMST_dbl = specialize TLazyPrimMST<double>;
procedure Main;
var
fileName: string;
v, i: integer;
g: TWeightGraph_dbl;
lazyPrimMst: TLazyPrimMST_dbl;
mst: TLazyPrimMST_dbl.TArrEdge;
begin
fileName := WEIGHT_GRAPH_FILE_NAME_1;
v := 8;
begin
g := TDenseWeightedGraph_dbl.Create(v, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + fileName);
// Test Lazy Prim MST
WriteLn('Test Lazy Prim MST:');
lazyPrimMst := TLazyPrimMST_dbl.Create(g);
mst := lazyPrimMst.MstEdges;
for i := 0 to High(mst) do
WriteLn(mst[i].ToString);
WriteLn('The MST weight is: ', lazyPrimMst.Weight.ToString);
end;
TDSAUtils.DrawLine;
begin
g := TSparseWeightedGraph_dbl.Create(v, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + fileName);
// Test Lazy Prim MST
WriteLn('Test Lazy Prim MST:');
LazyPrimMST := TLazyPrimMST_dbl.Create(g);
mst := LazyPrimMST.MstEdges;
for i := 0 to high(mst) do
WriteLn(mst[i].ToString);
WriteLn('The MST weight is: ', LazyPrimMST.Weight.ToString);
end;
end;
{ TLazyPrimMST }
constructor TLazyPrimMST.Create(g: TWeightGraph_T);
var
i: integer;
e: TEdge_T;
begin
__g := g;
__mstList := TList_Edge.Create;
__pq := TMinHeap.Create(g.Edge);
// 算法初始化
SetLength(__marked, g.Vertex);
for i := 0 to Pred(g.Vertex) do
__marked[i] := False;
// Lazy Prim
__visit(0);
while not __pq.IsEmpty do
begin
// 使用最小堆找出已经访问的边中权值最小的边
e := __pq.ExtractFirst;
// 如果这条边的两端都已经访问过了, 则扔掉这条边
if __marked[e.VertexA] = __marked[e.VertexB] then
Continue;
// 这条边存于最小生成树中
__mstList.AddLast(e);
// 访问和这条边连接的还没有被访问过的节点
if __marked[e.VertexA] = False then
__visit(e.VertexA)
else
__visit(e.VertexB);
end;
// 计算最小生成树的权值
__mstWeight := Default(T);
for i := 0 to __mstList.GetSize - 1 do
begin
__mstWeight += __mstList[i].Weight;
end;
end;
destructor TLazyPrimMST.Destroy;
begin
FreeAndNil(__pq);
FreeAndNil(__mstList);
inherited Destroy;
end;
function TLazyPrimMST.MstEdges: TArrEdge;
begin
Result := __mstList.ToArray;
end;
function TLazyPrimMST.Weight: T;
begin
Result := __mstWeight;
end;
procedure TLazyPrimMST.__visit(v: integer);
var
e: TEdge_T;
begin
Assert(__marked[v] = False);
__marked[v] := True;
for e in __g.AdjIterator(v) do
begin
if (__marked[e.OtherVertex(v)] = False) then
__pq.Add(e);
end;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.OpenGL,
Winapi.OpenGLext,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.Imaging.Jpeg,
GLWin32Viewer,
GLTexture,
GLCadencer,
GLScene,
GLContext,
GLKeyboard, GLUtils, GLFileTGA, GLHUDObjects,
GLBitmapFont, GLWindowsFont, GLMaterial, GLCoordinates, GLCrossPlatform,
GLRenderContextInfo, GLBaseClasses;
type
TForm1 = class(TForm)
Scene: TGLScene;
Timer1: TTimer;
Viewer: TGLSceneViewer;
GLCadencer: TGLCadencer;
Mandelbrot: TGLDirectOpenGL;
GLMatLib: TGLMaterialLibrary;
GLCamera: TGLCamera;
OpenDialog1: TOpenDialog;
GLHUDText: TGLHUDText;
GLWindowsBitmapFont: TGLWindowsBitmapFont;
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure GLCadencerProgress(Sender: TObject; const deltaTime,
newTime: Double);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure MandelbrotRender(Sender: TObject;
var rci: TGLRenderContextInfo);
private
public
MandelbrotProgram: TGLProgramHandle;
end;
const
HELP_TEXT = '+: Zoom in'#13#10
+'-: Zoom out'#13#10
+'Arrow keys: Move around'#13#10
+'F3: Load colormap';
var
Form1: TForm1;
PositionX, PositionY, Scale: Single;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
PositionX:=-0.5;
PositionY:= 0.0;
Scale:=1.0;
with GLMatLib do begin
Materials[0].Material.Texture.Image.LoadFromFile('Textures\hot_metal.bmp');
end;
GLHUDText.Text:=HELP_TEXT;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Caption:=Format('Mandelbrot %.1f FPS', [Viewer.FramesPerSecond]);
Viewer.ResetPerformanceMonitor;
end;
procedure TForm1.GLCadencerProgress(Sender: TObject; const deltaTime,
newTime: Double);
var
deltax, deltay: single;
pt: TPoint;
begin
if IsKeyDown(VK_F3)
then
if OpenDialog1.Execute
then GLMatLib.Materials[0].Material.Texture.Image.LoadFromFile(OpenDialog1.FileName);
if IsKeyDown('+') or IsKeyDown(VK_ADD)
then Scale:= Scale * 1.0 / (1.0 + deltaTime * 0.5);
if IsKeyDown('-') or IsKeyDown(VK_SUBTRACT)
then Scale:= Scale * (1.0 + deltaTime * 0.5);
if IsKeyDown(VK_UP) or IsKeyDown(VK_NUMPAD8)
then PositionY:= PositionY + deltaTime*Scale*0.5;
if IsKeyDown(VK_DOWN) or IsKeyDown(VK_NUMPAD2)
then PositionY:= PositionY - deltaTime*Scale*0.5;
if IsKeyDown(VK_RIGHT) or IsKeyDown(VK_NUMPAD6)
then PositionX:= PositionX + deltaTime*Scale*0.5;
if IsKeyDown(VK_LEFT) or IsKeyDown(VK_NUMPAD4)
then PositionX:= PositionX - deltaTime*Scale*0.5;
Viewer.Invalidate;
end;
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
var
DistDelta: Single;
begin
end;
procedure TForm1.MandelbrotRender(Sender: TObject;
var rci: TGLRenderContextInfo);
begin
// shader init
if not Assigned(MandelbrotProgram) then begin
MandelbrotProgram := TGLProgramHandle.CreateAndAllocate;
MandelbrotProgram.AddShader(TGLFragmentShaderHandle,
LoadAnsiStringFromFile('Shaders\Mandelbrot.frag'),
True);
MandelbrotProgram.AddShader(TGLVertexShaderHandle,
LoadAnsiStringFromFile('Shaders\Mandelbrot.vert'),
True);
if not MandelbrotProgram.LinkProgram
then raise Exception.Create(MandelbrotProgram.InfoLog);
if not MandelbrotProgram.ValidateProgram then
raise Exception.Create(MandelbrotProgram.InfoLog);
end;
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glLoadIdentity;
glMatrixMode(GL_PROJECTION);
glPushMatrix;
glLoadIdentity;
MandelbrotProgram.UseProgramObject;
MandelbrotProgram.Uniform1f['positionX']:=PositionX;
MandelbrotProgram.Uniform1f['positionY']:=PositionY;
MandelbrotProgram.Uniform1f['scale']:=Scale;
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, GLMatLib.Materials[0].Material.Texture.Handle);
MandelbrotProgram.Uniform1i['colorMap']:=0;
// drawing rectangle over screen
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0); glVertex2f(-1.0, -1.0);
glTexCoord2f(1.0, 0.0); glVertex2f( 1.0, -1.0);
glTexCoord2f(1.0, 1.0); glVertex2f( 1.0, 1.0);
glTexCoord2f(0.0, 1.0); glVertex2f(-1.0, 1.0);
glEnd;
MandelbrotProgram.EndUseProgramObject;
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
glPopMatrix;
glPopAttrib;
///-CheckOpenGLError;
end;
end.
|
////////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PAXCOMP_SYMBOL_TABLE.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PAXCOMP_SYMBOL_TABLE;
interface
uses {$I uses.def}
TypInfo,
SysUtils,
Classes,
PAXCOMP_CONSTANTS,
PAXCOMP_TYPES,
PAXCOMP_SYS,
PAXCOMP_VAROBJECT,
PAXCOMP_BASESYMBOL_TABLE,
PAXCOMP_LOCALSYMBOL_TABLE,
PAXCOMP_SYMBOL_REC,
PAXCOMP_OFFSET,
PAXCOMP_MAP,
PAXCOMP_STDLIB;
type
TSymbolTable = class(TLocalSymbolTable)
private
kernel: Pointer;
public
InCode: array of Boolean;
CompileCard: Integer;
LinkCard: Integer;
IsExtraTable: Boolean;
constructor Create(i_kernel: Pointer);
procedure Reset; override;
procedure ResetCompilation;
procedure SetShifts(prog: Pointer);
procedure RaiseError(const Message: string; params: array of const);
procedure CreateOffsets(JS1, JS2: Integer);
function GetValueAsString(P: Pointer;
StackFrameNumber: Integer;
Id: Integer;
TypeMapRec: TTypeMapRec = nil;
BriefCls: Boolean = false): String; override;
function GetSizeOfParams(SubId: Integer): Integer;
end;
implementation
uses
PAXCOMP_BYTECODE,
PAXCOMP_BASERUNNER,
PAXCOMP_KERNEL;
// TSymbolTable ----------------------------------------------------------------
constructor TSymbolTable.Create(i_kernel: Pointer);
begin
inherited Create(TKernel(i_kernel).GT);
Self.kernel := i_kernel;
IsExtraTable := false;
end;
procedure TSymbolTable.Reset;
begin
inherited;
ExternList.Clear;
CompileCard := Card;
LinkCard := Card;
end;
procedure TSymbolTable.ResetCompilation;
var
I, Id: Integer;
S: String;
begin
while Card > CompileCard do
begin
S := Records[Card].Name;
Id := Records[Card].Id;
HashArray.DeleteName(S, Id);
I := Card - FirstLocalId - 1;
{$IFDEF ARC}
A[I] := nil;
{$ELSE}
TSymbolRec(A[I]).Free;
{$ENDIF}
A.Delete(I);
Dec(Card);
end;
if TypeHelpers <> nil then
begin
FreeAndNil(TypeHelpers);
TypeHelpers := GlobalST.TypeHelpers.Clone;
end;
end;
procedure TSymbolTable.SetShifts(prog: Pointer);
procedure SetInCode;
var
Code: TCode;
I, Id: Integer;
begin
InCode := nil;
SetLength(InCode, Card + Card);
Code := TKernel(kernel).Code;
for I := 1 to StdCard do
InCode[I] := true;
for I:= 1 to Code.Card do
begin
Id := Code[I].Arg1;
if Id > 0 then
if Id <= Card then
InCode[Id] := true;
Id := Code[I].Arg2;
if Id > 0 then
if Id <= Card then
InCode[Id] := true;
Id := Code[I].Res;
if Id > 0 then
if Id <= Card then
InCode[Id] := true;
end;
end;
procedure ProcessType(T: Integer); forward;
procedure ProcessRecordType(T: Integer);
var
J, J1, FT, FT1, S, CurrAlign, DefAlign, VJ, VK, VS: Integer;
VarPathList: TVarPathList;
Path: TVarPath;
RJ: TSymbolRec;
begin
if Records[T].Host then
Exit;
if Records[T].TypeID = typeALIAS then
T := Records[T].PatternId;
VarPathList := TVarPathList.Create;
try
for J:=T + 1 to Card do
begin
RJ := Records[J];
if RJ.Kind = KindSUB then
if RJ.Level <> T then
break;
if (RJ.Kind = KindTYPE_FIELD) and (RJ.Level = T) then
if RJ.VarCount > 0 then
VarPathList.Add(J, RJ.VarCount);
end;
S := 0;
if Records[T].IsPacked then
begin
if VarPathList.Count = 0 then
begin
for J:=T + 1 to Card do
begin
RJ := Records[J];
if RJ.Kind = KindSUB then
if RJ.Level <> T then
break;
if (RJ.Kind = KindTYPE_FIELD) and (RJ.Level = T) then
begin
RJ.Shift := S;
ProcessType(RJ.TypeId);
Inc(S, RJ.Size);
end;
end;
end // VarCnt = 0
else
begin
for J:=T + 1 to Card do
begin
RJ := Records[J];
if RJ.Kind = KindSUB then
if RJ.Level <> T then
break;
if (RJ.Kind = KindTYPE_FIELD) and (RJ.Level = T) then
begin
if RJ.VarCount > 0 then
break;
RJ.Shift := S;
ProcessType(RJ.TypeId);
Inc(S, RJ.Size);
end;
end;
// process variant part of record
VS := S;
for VK :=0 to VarPathList.Count - 1 do
begin
Path := VarPathList[VK];
S := VS;
for VJ := 0 to Path.Count - 1 do
begin
J := Path[VJ].Id;
RJ := Records[J];
RJ.Shift := S;
ProcessType(RJ.TypeId);
Inc(S, RJ.Size);
end;
end;
end;
end
else
begin
DefAlign := Records[T].DefaultAlignment;
if VarPathList.Count = 0 then
begin
J1 := -1;
for J:=T + 1 to Card do
begin
RJ := Records[J];
if RJ.Kind = KindSUB then
if RJ.Level <> T then
break;
if (RJ.Kind = KindTYPE_FIELD) and (RJ.Level = T) then
begin
CurrAlign := GetAlignmentSize(RJ.TypeId, DefAlign);
if J1 > 0 then
begin
FT1 := Records[J-1].FinalTypeId;
FT := RJ.FinalTypeId;
if FT = FT1 then
begin
CurrAlign := 1;
J1 := -1;
end
else
J1 := J;
end
else
J1 := J;
if CurrAlign > 1 then
while S mod CurrAlign <> 0 do
Inc(S);
RJ.Shift := S;
ProcessType(RJ.TypeId);
Inc(S, RJ.Size);
end;
end;
end // VarCnt = 0
else
begin // VarCnt > 0
J1 := -1;
for J:=T + 1 to Card do
begin
RJ := Records[J];
if RJ.Kind = KindSUB then
if RJ.Level <> T then
break;
if (RJ.Kind = KindTYPE_FIELD) and (RJ.Level = T) then
begin
if RJ.VarCount > 0 then
break;
CurrAlign := GetAlignmentSize(RJ.TypeId, DefAlign);
if J1 > 0 then
begin
FT1 := Records[J-1].FinalTypeId;
FT := RJ.FinalTypeId;
if FT = FT1 then
begin
CurrAlign := 1;
J1 := -1;
end
else
J1 := J;
end
else
J1 := J;
if CurrAlign > 1 then
while S mod CurrAlign <> 0 do
Inc(S);
RJ.Shift := S;
ProcessType(RJ.TypeId);
Inc(S, RJ.Size);
end;
end;
// process variant part of record
VS := S;
for VK :=0 to VarPathList.Count - 1 do
begin
S := VS;
Path := VarPathList[VK];
for VJ := 0 to Path.Count - 1 do
begin
J := Path[VJ].Id;
RJ := Records[J];
CurrAlign := GetAlignmentSize(RJ.TypeId, DefAlign);
if J1 > 0 then
begin
FT1 := Records[J-1].FinalTypeId;
FT := RJ.FinalTypeId;
if FT = FT1 then
begin
CurrAlign := 1;
J1 := -1;
end
else
J1 := J;
end
else
J1 := J;
if CurrAlign > 1 then
while S mod CurrAlign <> 0 do
Inc(S);
RJ.Shift := S;
ProcessType(RJ.TypeId);
Inc(S, RJ.Size);
end;
end;
end; // VarCnt > 0
end;
finally
FreeAndNil(VarPathList);
end;
end;
procedure ProcessClassType(T: Integer);
var
J, S, AncestorId: Integer;
RJ: TSymbolRec;
begin
if Records[T].Host then
Exit;
if Records[T].TypeID = typeALIAS then
T := Records[T].PatternId;
AncestorId := Records[T].AncestorId;
if AncestorId = 0 then
S := 0
else
begin
if not Records[AncestorId].Completed then
begin
ProcessClassType(AncestorId);
Records[AncestorId].Completed := true;
end;
S := Records[AncestorId].GetSizeOfAllClassFields(prog);
end;
if Records[T].IsPacked then
begin
for J:=T + 1 to Card do
begin
RJ := Records[J];
if (RJ.Kind = KindTYPE_FIELD) and (RJ.Level = T) then
begin
RJ.Shift := S;
ProcessType(RJ.TypeId);
Inc(S, RJ.Size);
end;
end;
end
else
RaiseError(errInternalError, []);
end;
procedure ProcessArrayType(T: Integer);
var
J, PatternId: Integer;
RJ: TSymbolRec;
begin
for J:=T + 1 to Card do
begin
RJ := Records[J];
if RJ.Level = T then
begin
if RJ.Kind in [KindLABEL, KindNONE] then
continue;
if RJ.Kind <> KindTYPE then
RaiseError(errInternalError, []);
if RJ.TypeID = typeALIAS then
begin
PatternId := RJ.PatternId;
ProcessType(PatternId);
end
else
ProcessType(J);
end;
end;
end;
procedure ProcessType(T: Integer);
begin
if Records[T].Kind <> kindTYPE then
RaiseError(errInternalError, []);
T := Records[T].TerminalTypeId;
if Records[T].Completed then
Exit;
Records[T].Completed := true;
case Records[T].FinalTypeId of
typeRECORD: ProcessRecordType(T);
typeCLASS: ProcessClassType(T);
typeBOOLEAN,
{$IFNDEF PAXARM}
typeANSICHAR,
typeANSISTRING,
typeWIDESTRING,
typeSHORTSTRING,
{$ENDIF}
typeBYTE, typeWORD,
typeINTEGER, typeDOUBLE,
typeSINGLE, typeEXTENDED, typeCURRENCY,
typeCLASSREF, typeWIDECHAR,
typeVARIANT, typeOLEVARIANT,
typeDYNARRAY, typeOPENARRAY,
typeINT64, typeUINT64, typeINTERFACE, typeCARDINAL,
typeSMALLINT, typeSHORTINT, typeBYTEBOOL, typeWORDBOOL, typeLONGBOOL,
typeENUM, typePOINTER, typePROC, typeEVENT,
typeSET: begin end;
typeTYPEPARAM: begin end;
typeHELPER: begin end;
typeARRAY: ProcessArrayType(T);
typeALIAS: ProcessType(Records[T].PatternID);
else
RaiseError(errInternalError, []);
end;
// Records[T].Completed := true;
end;
var
I, J, OwnerId, PatternId, ArrayTypeId, RangeTypeId, ElemTypeId: Integer;
S, SP, SL, H1, TypeID, SZ, RegCount, NP, K, FT: Integer;
ExtraParamNeeded, IsMethod: Boolean;
RI, RJ: TSymbolRec;
RI_FinalTypeId: Integer;
K1, K2, KK: Integer;
RI_Kind: Integer;
KK1, KK2: Integer;
LL: TIntegerList;
RSPOffset, SubRSPSize: Integer;
begin
KK1 := 1;
KK2 := 2;
if IsExtraTable then
begin
KK1 := 3;
KK2 := 3;
end;
LL := TIntegerList.Create;
if LinkCard > 0 then
LastShiftValue := GetDataSize(LinkCard)
else
LastShiftValue := GetDataSize(LinkCard);
S := LastShiftValue;
SetInCode;
for KK := KK1 to KK2 do
begin
if KK = 1 then
begin
K1 := ResultId + 1;
K2 := GlobalST.Card;
end
else if KK = 2 then
begin
K1 := FirstLocalId + 1;
K2 := Card;
end
else // KK = 3
begin
K1 := LinkCard;
K2 := Card;
end;
for I := K1 to K2 do
begin
RI := Records[I];
RI_Kind := RI.Kind;
if RI_Kind = kindPROP then
continue;
if KK = 1 then
if (RI.Shift <> 0) and (not RI.Host) then
begin
if RI_Kind = KindCONST then
begin
{$IFNDEF PAXARM}
if RI.HasPAnsiCharType then
begin
if InCode[I] then
TKernel(kernel).Code.Add(OP_INIT_PANSICHAR_LITERAL, I, 0, 0, 0, true, PASCAL_LANGUAGE, 0, -1);
end
else
{$ENDIF}
if RI.HasPWideCharType then
begin
if InCode[I] then
TKernel(kernel).Code.Add(OP_INIT_PWIDECHAR_LITERAL, I, 0, 0, 0, true, PASCAL_LANGUAGE, 0, -1);
end;
end;
continue;
end;
if KK = 2 then
if I <= LinkCard then
if (RI.Shift <> 0) and (not RI.Host) then
begin
if RI_Kind = KindCONST then
begin
{$IFNDEF PAXARM}
if RI.HasPAnsiCharType then
begin
if InCode[I] then
TKernel(kernel).Code.Add(OP_INIT_PANSICHAR_LITERAL, I, 0, 0, 0, true, PASCAL_LANGUAGE, 0, -1);
end
else
{$ENDIF}
if RI.HasPWideCharType then
begin
if InCode[I] then
TKernel(kernel).Code.Add(OP_INIT_PWIDECHAR_LITERAL, I, 0, 0, 0, true, PASCAL_LANGUAGE, 0, -1);
end;
end;
continue;
end;
if RI.UnionId <> 0 then
begin
RI.Shift := Records[RI.UnionId].Shift;
if RI.UnionId > I then
LL.Add(I);
continue;
end;
RI_FinalTypeId := RI.FinalTypeId;
if RI.Host then
begin
case RI_Kind of
kindSUB, KindCONSTRUCTOR, KindDESTRUCTOR:
begin
if RI.CallConv = cc64 then
begin
NP := RI.Count;
if NP = 0 then
continue;
RegCount := 0;
RSPOffset := $20;
if RI.ExtraParamNeeded then
Inc(RegCount);
if (RI.IsMethod or RI.IsSubPartOfEventType) and (RI.CallMode <> cmSTATIC) then
Inc(RegCount);
if I = JS_AlertId then
if RI.Name = 'alert' then
Inc(RegCount);
for J:=I + 1 to GetParamId(I, NP - 1) do
begin
RJ := Records[J];
if RJ.Level <> I then
break;
if RJ.Param then
begin
FT := RJ.FinalTypeId;
if FT in RealTypes then
begin
Inc(RegCount);
case RegCount of
1: RJ.XMMReg := _XMM0;
2: RJ.XMMReg := _XMM1;
3: RJ.XMMReg := _XMM2;
4: RJ.XMMReg := _XMM3;
else
begin
RJ.RSPOffset := RSPOffset;
Inc(RSPOffset, 8);
end;
end;
continue;
end;
if FT in [typeRECORD, typeARRAY] then
begin
if RJ.Size > 4 then
RJ.ByRefEx := true;
end;
if RJ.ByRef or RJ.ByRefEx
or
(
(RJ.Size <= SizeOfPointer) and (not (FT in RealTypes))
)
or
(FT in [
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT, typeEVENT, typeSET])
then
begin
Inc(RegCount);
if RI_Kind = KindCONSTRUCTOR then
begin
if Records[RI.Level].FinalTypeId = typeRECORD then
case RegCount of
1: RJ.Register := _EDX;
2: RJ.Register := _R8;
3: RJ.Register := _R9;
else
begin
RJ.RSPOffset := RSPOffset;
Inc(RSPOffset, 8);
end;
end
else
case RegCount of
1: RJ.Register := _R8;
2: RJ.Register := _R9;
else
begin
RJ.RSPOffset := RSPOffset;
Inc(RSPOffset, 8);
end;
end;
end
else
case RegCount of
1: RJ.Register := _ECX;
2: RJ.Register := _EDX;
3: RJ.Register := _R8;
4: RJ.Register := _R9;
else
begin
RJ.RSPOffset := RSPOffset;
Inc(RSPOffset, 8);
end;
end;
if FT in [typeDYNARRAY, typeOPENARRAY] then
if RJ.IsOpenArray then
begin
Inc(RegCount);
Inc(RSPOffset, 8);
end;
end;
end;
end;
end // cc64
else if RI.CallConv = ccREGISTER then
begin
NP := RI.Count;
if NP = 0 then
continue;
RegCount := 0;
for J:=I + 1 to GetParamId(I, NP - 1) do
begin
RJ := Records[J];
if RJ.Level <> I then
break;
if RJ.Param then
begin
FT := RJ.FinalTypeId;
if FT in [typeRECORD, typeARRAY] then
begin
if RJ.Size > 4 then
RJ.ByRefEx := true;
end;
if RJ.ByRef or RJ.ByRefEx
or
(
(RJ.Size <= 4) and (FT <> typeSINGLE)
)
or
(FT in [
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT, typeEVENT, typeSET])
then
begin
Inc(RegCount);
if RI_Kind = KindCONSTRUCTOR then
begin
if Records[RI.Level].FinalTypeId = typeRECORD then
case RegCount of
1: RJ.Register := _EDX;
2: RJ.Register := _ECX;
end
else
case RegCount of
1: RJ.Register := _ECX;
end;
end
else
if (RI.IsMethod or RI.IsSubPartOfEventType) and
(RI.CallMode <> cmSTATIC) then
case RegCount of
1: RJ.Register := _EDX;
2: RJ.Register := _ECX;
end
else
case RegCount of
1: RJ.Register := _EAX;
2: RJ.Register := _EDX;
3: RJ.Register := _ECX;
end;
if FT in [typeDYNARRAY, typeOPENARRAY] then
if RJ.IsOpenArray then
Inc(RegCount);
end;
end;
end;
end // ccREGISTER
else
if RI.CallConv = ccMSFASTCALL then
begin
NP := RI.Count;
if NP = 0 then
continue;
RegCount := 1;
for J:=I + 1 to GetParamId(I, NP - 1) do
begin
RJ := Records[J];
if RJ.Level <> I then
break;
if RJ.Param then
begin
if RJ.ByRef
or
(
(RJ.Size <= 4) and (RJ.FinalTypeId <> typeSINGLE)
)
or
(RJ.FinalTypeId in [
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT])
then
begin
Inc(RegCount);
if RI_Kind = KindCONSTRUCTOR then
case RegCount of
1: RJ.Register := _ECX;
end
else
if (RI.IsMethod) and (RI.CallMode <> cmSTATIC) then
case RegCount of
1: RJ.Register := _ECX;
end
else
case RegCount of
2: RJ.Register := _ECX;
3: RJ.Register := _EDX;
end;
if RJ.FinalTypeId in [typeDYNARRAY, typeOPENARRAY] then
if RJ.IsOpenArray then
Inc(RegCount);
end;
end;
end;
end; // ccMS_FASTCALL
end; // kindSUB, KindCONSTRUCTOR, KindDESTRUCTOR (HOST)
KindTYPE:
begin
RI.Completed := true;
end;
end // case
end
else // not host
case RI_Kind of
kindVAR:
begin
if RI.Param then
begin
// already done
end
else if RI.Local then
begin
// already done
end
else // global
begin
if RI.InternalField then
begin
OwnerId := RI.OwnerId;
TypeId := Records[OwnerId].FinalTypeId;
case TypeId of
typeRECORD:
begin
PatternId := RI.PatternId;
RI.Shift := Records[OwnerId].Shift + Records[PatternId].Shift;
end;
typeARRAY:
begin
ArrayTypeId := Records[OwnerId].TerminalTypeId;
GetArrayTypeInfo(ArrayTypeId, RangeTypeId, ElemTypeId);
H1 := GetLowBoundRec(RangeTypeId).Value;
RI.Shift := Records[OwnerId].Shift +
Records[ElemTypeId].Size * (RI.Value - H1);
end;
else
begin
RI.Kind := kindNONE;
RI.Name := '';
RI.OwnerId := 0;
continue;
// RaiseError(errInternalError, []);
end;
end;
end
else
begin
TypeId := RI.TypeId;
if TypeId = 0 then
RI.Kind := kindNONE
else
begin
ProcessType(TypeId);
RI.Shift := S;
Inc(S, RI.Size);
end;
end;
end;
end;
kindCONST:
begin
if RI_FinalTypeId = typeDOUBLE then
begin
RI.Shift := S;
Inc(S, SizeOf(Double));
end
else if RI_FinalTypeId = typeSINGLE then
begin
RI.Shift := S;
Inc(S, SizeOf(Single));
end
else if RI_FinalTypeId = typeEXTENDED then
begin
RI.Shift := S;
Inc(S, SizeOf(Extended));
end
else if RI_FinalTypeId = typeCURRENCY then
begin
RI.Shift := S;
Inc(S, SizeOf(Currency));
end
else if RI_FinalTypeId in INT64Types then
begin
RI.Shift := S;
Inc(S, SizeOf(Int64));
end
else if RI_FinalTypeId = typeRECORD then
begin
RI.Shift := S;
Inc(S, RI.Size);
end
else if RI_FinalTypeId = typeARRAY then
begin
RI.Shift := S;
Inc(S, RI.Size);
end
else if RI_FinalTypeId in VariantTypes then
begin
RI.Shift := S;
Inc(S, SizeOf(Variant));
end
else if RI_FinalTypeId = typeSET then
begin
RI.Shift := S;
ProcessType(RI.TypeId);
Inc(S, RI.Size);
end
{$IFNDEF PAXARM}
else if RI.HasPAnsiCharType then
begin
RI.Shift := S;
Inc(S, SizeOfPointer); // pointer to string literal
Inc(S, SizeOfPointer); // ref counter
Inc(S, SizeOfPointer); // length
if InCode[I] then
TKernel(kernel).Code.Add(OP_INIT_PANSICHAR_LITERAL, I, 0, 0, 0, true, PASCAL_LANGUAGE, 0, -1);
// reserve place for literal
Inc(S, Length(RI.Value) + 1);
end
{$ENDIF}
else if RI.HasPWideCharType then
begin
RI.Shift := S;
Inc(S, SizeOfPointer); // pointer to string literal
Inc(S, SizeOfPointer); // length
if InCode[I] then
TKernel(kernel).Code.Add(OP_INIT_PWIDECHAR_LITERAL, I, 0, 0, 0, true, PASCAL_LANGUAGE, 0, -1);
// reserve place for literal
Inc(S, Length(RI.Value) * 2 + 2);
end
else
begin
if RI.MustBeAllocated then
begin
RI.Shift := S;
Inc(S, RI.Size);
end;
end;
end;
kindSUB, KindCONSTRUCTOR, KindDESTRUCTOR:
begin
RI.Shift := S;
Inc(S, SizeOfPointer);
SP := 8 + 3 * 4;
SL := 0;
ExtraParamNeeded := RI.ExtraParamNeeded;
IsMethod := (Records[GetSelfId(I)].Name <> '') and
(Records[I].CallMode <> cmSTATIC);
if ExtraParamNeeded then
if RI.CallConv in [ccSTDCALL, ccSAFECALL, ccCDECL] then
Inc(SP, 4);
if RI.CallConv in [ccSTDCALL, ccSAFECALL, ccCDECL] then
begin
for J:=I + 1 to Card do
begin
if ExtraParamNeeded then
begin
if J = GetResultId(I) then
continue;
end;
RJ := Records[J];
if RJ.Level <> I then
continue;
if RJ.UnionId <> 0 then
begin
RJ.Shift := Records[RJ.UnionId].Shift;
if RI.UnionId > I then
LL.Add(I);
continue;
end;
if RJ.Param then
begin
RJ.Shift := SP;
if RJ.FinalTypeId in [typeDYNARRAY, typeOPENARRAY] then
if RJ.IsOpenArray then
Inc(SP, 4);
// RJ.Shift := SP;
FT := RJ.FinalTypeId;
if FT in [typeRECORD, typeARRAY] then
begin
if RJ.IsConst then
if RJ.Size > 4 then
RJ.ByRefEx := true;
end;
case FT of
{$IFNDEF PAXARM}
typeSHORTSTRING: RJ.ByRefEx := true;
{$ENDIF}
typeVARIANT, typeOLEVARIANT: RJ.ByRefEx := true;
end;
if RJ.ByRef or RJ.ByRefEx then
Inc(SP, SizeOfPointer)
else
begin
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
SZ := RJ.Size;
while SZ mod 4 <> 0 do
Inc(SZ);
Inc(SP, SZ);
end;
end
else if RJ.Local then
begin
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
if RJ.FinalTypeId = typeSET then
Dec(SL, SizeOf(TByteSet))
else
Dec(SL, MPtr(RJ.Size));
RJ.Shift := SL;
end
else if RJ.InternalField then
begin
OwnerId := RJ.OwnerId;
TypeId := Records[OwnerId].FinalTypeId;
case TypeId of
typeRECORD:
begin
PatternId := RJ.PatternId;
RJ.Shift := Records[OwnerId].Shift + Records[PatternId].Shift;
end;
typeARRAY:
begin
ArrayTypeId := Records[OwnerId].TerminalTypeId;
GetArrayTypeInfo(ArrayTypeId, RangeTypeId, ElemTypeId);
H1 := GetLowBoundRec(RangeTypeId).Value;
RJ.Shift := Records[OwnerId].Shift +
Records[ElemTypeId].Size * (RJ.Value - H1);
end;
else
RaiseError(errInternalError, []);
end;
end
else if RJ.Kind = KindTYPE then
ProcessType(J);
end; // for
if ExtraParamNeeded then
begin
J := GetResultId(I);
TypeId := Records[J].TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
Records[J].Shift := 8 + 3 * 4;
Records[J].ByRef := true;
end; // J-loop
if RI.CallConv = ccSAFECALL then
begin
J := GetResultId(I);
RJ := Records[J];
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
RJ.Shift := GetSizeOfParams(I) + 4;
RJ.ByRef := true;
end;
end // of ccSTDCALL, ccCDECL ccSAFECALL
else if RI.CallConv = ccPASCAL then
begin
if IsMethod then
Inc(SP, 4);
for J:=Card downto I + 1 do
begin
if ExtraParamNeeded then
begin
if J = GetResultId(I) then
continue;
end;
if IsMethod then
begin
if J = GetSelfId(I) then
continue;
end;
RJ := Records[J];
if RJ.Level <> I then
continue;
if RJ.UnionId <> 0 then
begin
RJ.Shift := Records[RJ.UnionId].Shift;
if RI.UnionId > I then
LL.Add(I);
continue;
end;
if RJ.Param then
begin
RJ.Shift := SP;
FT := RJ.FinalTypeId;
if FT in [typeRECORD, typeARRAY] then
begin
if RJ.IsConst then
if RJ.Size > 4 then
RJ.ByRefEx := true;
end;
if FT in [
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT] then
RJ.ByRefEx := true;
if RJ.ByRef or RJ.ByRefEx then
Inc(SP, SizeOfPointer)
else
begin
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
SZ := RJ.Size;
if RJ.FinalTypeId in [typeDYNARRAY, typeOPENARRAY] then
if RJ.IsOpenArray then
Inc(SP, 4);
while SZ mod 4 <> 0 do
Inc(SZ);
Inc(SP, SZ);
end;
end
else if RJ.Local then
begin
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
if RJ.FinalTypeId = typeSET then
Dec(SL, SizeOf(TByteSet))
else
Dec(SL, MPtr(RJ.Size));
RJ.Shift := SL;
end
else if RJ.InternalField then
begin
continue;
end
else if RJ.Kind = KindTYPE then
ProcessType(J);
end; // for loop - J
for J:=Card downto I + 1 do
begin
RJ := Records[J];
if RJ.InternalField then
begin
OwnerId := RJ.OwnerId;
TypeId := Records[OwnerId].FinalTypeId;
case TypeId of
typeRECORD:
begin
PatternId := RJ.PatternId;
RJ.Shift := Records[OwnerId].Shift + Records[PatternId].Shift;
end;
typeARRAY:
begin
ArrayTypeId := Records[OwnerId].TerminalTypeId;
GetArrayTypeInfo(ArrayTypeId, RangeTypeId, ElemTypeId);
H1 := GetLowBoundRec(RangeTypeId).Value;
RJ.Shift := Records[OwnerId].Shift +
Records[ElemTypeId].Size * (RJ.Value - H1);
end;
else
RaiseError(errInternalError, []);
end;
end
end;
if IsMethod then
begin
J := GetSelfId(I);
Records[J].Shift := 8;
end;
if ExtraParamNeeded then
begin
J := GetResultId(I);
RJ := Records[J];
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
if IsMethod then
RJ.Shift := 12
else
RJ.Shift := 8;
RJ.ByRef := true;
end;
end // ccPASCAL
else if RI.CallConv = ccREGISTER then
begin
RegCount := 0;
if RI.IsMethod or RI.IsSubPartOfEventType or
RI.IsConstructor or RI.IsDestructor then
if RI.CallMode <> cmSTATIC then
begin
J := GetSelfId(I);
Records[J].Register := _EAX;
Inc(RegCount);
if RI.IsConstructor then //!!
begin
if Records[RI.Level].FinalTypeId <> typeRECORD then
Inc(RegCount);
end;
Dec(SL, 4);
Records[J].Shift := SL;
end;
for NP := 0 to RI.Count - 1 do
begin
J := GetParamId(I, NP);
RJ := Records[J];
FT := RJ.FinalTypeId;
if FT in [typeRECORD, typeARRAY] then
if RJ.Size > 4 then
RJ.ByRefEx := true;
if RJ.ByRef or RJ.ByRefEx
or
(
(RJ.Size <= 4) and (FT <> typeSINGLE)
)
or
(FT in [
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT])
then
begin
if FT in [
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT] then
RJ.ByRefEx := true;
Inc(RegCount);
case RegCount of
1: RJ.Register := _EAX;
2: RJ.Register := _EDX;
3: RJ.Register := _ECX;
end;
if RegCount <= 3 then
begin
Dec(SL, 4);
RJ.Shift := SL;
end;
if FT in [typeDYNARRAY, typeOPENARRAY] then
if RJ.IsOpenArray then
begin
Inc(RegCount);
end;
end;
end; // set register params
K := I + 1;
if ExtraParamNeeded then
begin
Inc(K);
J := GetResultId(I);
RJ := Records[J];
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
if RegCount >= 3 then
begin
RJ.Shift := SP;
RJ.ByRef := true;
Inc(SP, 4);
end
else
begin
Inc(RegCount);
case RegCount of
1: RJ.Register := _EAX;
2: RJ.Register := _EDX;
3: RJ.Register := _ECX;
end;
Dec(SL, 4);
RJ.Shift := SL;
end;
RJ.ByRef := true;
end;
for J:=Card downto K do
begin
RJ := Records[J];
if RJ.Level <> I then
continue;
if RJ.Register > 0 then
continue;
if RJ.UnionId <> 0 then
begin
RJ.Shift := Records[RJ.UnionId].Shift;
if RI.UnionId > I then
LL.Add(I);
continue;
end;
if RJ.Param then
begin
if RJ.FinalTypeId in [typeDYNARRAY, typeOPENARRAY] then
if RJ.IsOpenArray then
Inc(SP, 4);
RJ.Shift := SP;
if RJ.FinalTypeId in
[
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT] then
RJ.ByRefEx := true;
if RJ.ByRef or RJ.ByRefEx then
Inc(SP, SizeOfPointer)
else
begin
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
SZ := RJ.Size;
while SZ mod 4 <> 0 do
Inc(SZ);
Inc(SP, SZ);
end;
end
else if RJ.Local then
begin
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
if RJ.FinalTypeId = typeSET then
Dec(SL, SizeOf(TByteSet))
else
Dec(SL, MPtr(RJ.Size));
RJ.Shift := SL;
end
else if RJ.InternalField then
begin
continue; // later
end
else if RJ.Kind = KindTYPE then
ProcessType(J);
end; // for
for J:=Card downto K do
begin
RJ := Records[J];
if RJ.Level <> I then
continue;
if RJ.Register > 0 then
continue;
if RJ.InternalField then
begin
OwnerId := RJ.OwnerId;
TypeId := Records[OwnerId].FinalTypeId;
case TypeId of
typeRECORD:
begin
PatternId := RJ.PatternId;
RJ.Shift := Records[OwnerId].Shift + Records[PatternId].Shift;
end;
typeARRAY:
begin
ArrayTypeId := Records[OwnerId].TerminalTypeId;
GetArrayTypeInfo(ArrayTypeId, RangeTypeId, ElemTypeId);
H1 := GetLowBoundRec(RangeTypeId).Value;
Records[J].Shift := Records[OwnerId].Shift +
Records[ElemTypeId].Size * (RJ.Value - H1);
end;
else
begin
RJ.Kind := kindNONE;
RJ.Name := '';
RJ.OwnerId := 0;
continue;
// RaiseError(errInternalError, []);
end;
end;
end;
end; // for
end // ccREGISTER
else if RI.CallConv = cc64 then
begin
RegCount := 0;
RSPOffset := $20;
SL := $100;
if RI.IsMethod or
RI.IsSubPartOfEventType or
RI.IsJSFunction or
RI.IsConstructor or RI.IsDestructor then
if RI.CallMode <> cmSTATIC then
begin
Inc(RegCount);
J := GetSelfId(I);
RJ := Records[J];
case RegCount of
1: RJ.Register := _ECX;
2: RJ.Register := _EDX;
else
RaiseError(errInternalError, []);
end;
if RI.IsConstructor then //!!
begin
if Records[RI.Level].FinalTypeId <> typeRECORD then
begin
J := GetDL_Id(I);
Records[J].Shift := SL;
Inc(SL, 8);
Inc(RegCount);
end;
end;
end;
if ExtraParamNeeded then
begin
J := GetResultId(I);
RJ := Records[J];
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
Inc(RegCount);
case RegCount of
1: RJ.Register := _ECX;
2: RJ.Register := _EDX;
else
RaiseError(errInternalError, []);
end;
RJ.ByRef := true;
end;
if RI.IsNestedSub and (not RI.IsJSFunction) then
begin
J := GetRBP_Id(I);
Records[J].Shift := SL;
Inc(SL, 8);
Inc(RegCount);
end;
// set params
for NP := 0 to RI.Count - 1 do
begin
J := GetParamId(I, NP);
RJ := Records[J];
if not Records[RJ.TypeId].Completed then
ProcessType(RJ.TypeId);
FT := RJ.FinalTypeId;
if FT in [typeRECORD, typeARRAY] then
if RJ.Size > 4 then
RJ.ByRefEx := true;
if (FT in RealTypes) and (not (RJ.ByRef or RJ.ByRefEx)) then
begin
Inc(RegCount);
case RegCount of
1: RJ.XMMReg := _XMM0;
2: RJ.XMMReg := _XMM1;
3: RJ.XMMReg := _XMM2;
4: RJ.XMMReg := _XMM3;
else
begin
RJ.RSPOffset := RSPOffset;
Inc(RSPOffset, 8);
end;
end;
end
else if RJ.ByRef or RJ.ByRefEx
or
(
(RJ.Size <= SizeOfPointer) and (not (FT in RealTypes))
)
or
(FT in [
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT, typeEVENT, typeSET])
then
begin
if FT in [
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT] then
RJ.ByRefEx := true;
Inc(RegCount);
case RegCount of
1: RJ.Register := _ECX;
2: RJ.Register := _EDX;
3: RJ.Register := _R8;
4: RJ.Register := _R9;
else
begin
RJ.RSPOffset := RSPOffset;
Inc(RSPOffset, 8);
end;
end;
if FT in [typeDYNARRAY, typeOPENARRAY] then
if RJ.IsOpenArray then
begin
Inc(RegCount);
end;
end
else
begin
RJ.RSPOffset := RSPOffset;
Inc(RSPOffset, 8);
end;
end; // set register params
K := I + 1;
for J:=Card downto K do
begin
RJ := Records[J];
if RJ.Level <> I then
continue;
if RJ.Param then
continue;
if RJ.Local then
begin
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
end;
end;
SubRSPSize := GetSubRSPSize(I);
SP := SubRSPSize + $10 + 24;
J := GetResultId(I);
RJ := Records[J];
case RJ.Register of
_ECX: RJ.Shift := SP;
_EDX: RJ.Shift := SP + 8;
else
begin
RJ.Shift := SL;
Inc(SL, 8);
end;
end;
J := GetSelfId(I);
RJ := Records[J];
case RJ.Register of
_ECX: RJ.Shift := SP;
_EDX: RJ.Shift := SP + 8;
end;
K := J + 1;
for NP := 0 to RI.Count - 1 do
begin
J := GetParamId(I, NP);
RJ := Records[J];
if RJ.Register = _ECX then
RJ.Shift := SP
else if RJ.Register = _EDX then
RJ.Shift := SP + 8
else if RJ.Register = _R8 then
RJ.Shift := SP + 16
else if RJ.Register = _R9 then
RJ.Shift := SP + 24
else if RJ.XMMReg = _XMM0 then
RJ.Shift := SP
else if RJ.XMMReg = _XMM1 then
RJ.Shift := SP + 8
else if RJ.XMMReg = _XMM2 then
RJ.Shift := SP + 16
else if RJ.XMMReg = _XMM3 then
RJ.Shift := SP + 24
else
RJ.Shift := SP + RJ.RSPOffset;
end;
for J:=K to Card do
begin
RJ := Records[J];
if RJ.Level <> I then
continue;
if RJ.Param then
continue;
if RJ.UnionId <> 0 then
begin
RJ.Shift := Records[RJ.UnionId].Shift;
if RI.UnionId > I then
LL.Add(I);
continue;
end;
if RJ.Local then
begin
RJ.Shift := SL;
Inc(SL, MPtr(RJ.Size));
end
else if RJ.InternalField then
begin
OwnerId := RJ.OwnerId;
TypeId := Records[OwnerId].FinalTypeId;
case TypeId of
typeRECORD:
begin
PatternId := RJ.PatternId;
RJ.Shift := Records[OwnerId].Shift + Records[PatternId].Shift;
end;
typeARRAY:
begin
ArrayTypeId := Records[OwnerId].TerminalTypeId;
GetArrayTypeInfo(ArrayTypeId, RangeTypeId, ElemTypeId);
H1 := GetLowBoundRec(RangeTypeId).Value;
Records[J].Shift := Records[OwnerId].Shift +
Records[ElemTypeId].Size * (RJ.Value - H1);
end;
else
begin
RJ.Kind := kindNONE;
RJ.Name := '';
RJ.OwnerId := 0;
continue;
end;
end;
end
else if RJ.Kind = KindTYPE then
ProcessType(J);
end; // for
end // cc64
else if RI.CallConv = ccMSFASTCALL then
begin
RegCount := 1;
{
if Records[I].IsMethod or Records[I].IsConstructor or Records[I].IsDestructor then
begin
J := GetSelfId(I);
Records[J].Register := _EAX;
Inc(RegCount);
Dec(SL, 4);
Records[J].Shift := SL;
end;
}
for NP := 0 to RI.Count - 1 do
begin
J := GetParamId(I, NP);
RJ := Records[J];
FT := RJ.FinalTypeId;
if FT in [typeRECORD, typeARRAY] then
begin
if RJ.IsConst then
if RJ.Size > 4 then
RJ.ByRefEx := true;
end;
if RJ.ByRef or RJ.ByRefEx
or
(
(RJ.Size <= 4) and (FT <> typeSINGLE)
)
or
(FT in [
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT])
then
begin
if FT in [
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT] then
RJ.ByRefEx := true;
Inc(RegCount);
case RegCount of
2: RJ.Register := _ECX;
3: RJ.Register := _EDX;
end;
Dec(SL, 4);
RJ.Shift := SL;
end;
end; // set register params
K := I + 1;
if ExtraParamNeeded then
begin
Inc(K);
J := GetResultId(I);
RJ := Records[J];
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
if RegCount >= 3 then
begin
RJ.Shift := 8;
RJ.ByRef := true;
end
else
begin
Inc(RegCount);
case RegCount of
2: RJ.Register := _ECX;
3: RJ.Register := _EDX;
end;
Dec(SL, 4);
RJ.Shift := SL;
end;
RJ.ByRef := true;
end
else
begin
J := GetResultId(I);
Records[J].ByRef := false;
end;
for J:=Card downto K do
begin
RJ := Records[J];
if RJ.Level <> I then
continue;
if RJ.Register > 0 then
continue;
if RJ.UnionId <> 0 then
begin
RJ.Shift := Records[RJ.UnionId].Shift;
if RI.UnionId > I then
LL.Add(I);
continue;
end;
if RJ.Param then
begin
if RJ.FinalTypeId in [typeDYNARRAY, typeOPENARRAY] then
if RJ.IsOpenArray then
Inc(SP, 4);
RJ.Shift := SP;
if RJ.FinalTypeId in
[
{$IFNDEF PAXARM}
typeSHORTSTRING,
{$ENDIF}
typeVARIANT, typeOLEVARIANT] then
RJ.ByRefEx := true;
if RJ.ByRef or RJ.ByRefEx then
Inc(SP, SizeOfPointer)
else
begin
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
SZ := RJ.Size;
while SZ mod 4 <> 0 do
Inc(SZ);
Inc(SP, SZ);
end;
end
else if RJ.Local then
begin
TypeId := RJ.TypeId;
if not Records[TypeId].Completed then
ProcessType(TypeId);
if RJ.FinalTypeId = typeSET then
Dec(SL, SizeOf(TByteSet))
else
Dec(SL, MPtr(RJ.Size));
RJ.Shift := SL;
end
else if RJ.InternalField then
begin
continue;
end
else if Records[J].Kind = KindTYPE then
ProcessType(J);
end; // for
for J:=Card downto K do
begin
RJ := Records[J];
if RJ.Level <> I then
continue;
if RJ.Register > 0 then
continue;
if RJ.InternalField then
begin
OwnerId := RJ.OwnerId;
TypeId := Records[OwnerId].FinalTypeId;
case TypeId of
typeRECORD:
begin
PatternId := Records[J].PatternId;
RJ.Shift := Records[OwnerId].Shift + Records[PatternId].Shift;
end;
typeARRAY:
begin
ArrayTypeId := Records[OwnerId].TerminalTypeId;
GetArrayTypeInfo(ArrayTypeId, RangeTypeId, ElemTypeId);
H1 := GetLowBoundRec(RangeTypeId).Value;
Records[J].Shift := Records[OwnerId].Shift +
Records[ElemTypeId].Size * (RJ.Value - H1);
end;
else
RaiseError(errInternalError, []);
end;
end;
end; // for
end // ccMS_FASTCALL
else
RaiseError(errInternalError, []);
end; // KindSUB, KindCONSTRUCTOR, KindDESTRUCTOR (Script)
kindTYPE:
ProcessType(I);
end;
end; // loop - I
end; // loop KK
for J := 0 to LL.Count - 1 do
begin
I := LL[J];
RI := Records[I];
RI.Shift := Records[RI.UnionId].Shift;
end;
FreeAndNil(LL);
end;
procedure TSymbolTable.RaiseError(const Message: string; params: array of Const);
begin
TKernel(kernel).RaiseError(Message, params);
end;
procedure TSymbolTable.CreateOffsets(JS1, JS2: Integer);
var
KK, K1, K2, I, S, SZ, OwnerId, OwnerOffset, D, L: Integer;
RI: TSymbolRec;
OffsetList: TOffsetList;
SignClassHeader: Boolean;
Id_GetOLEProperty, Id_SetOLEProperty: Integer;
HostMapTable: TMapTable;
Id: Integer;
ClassLst, SubLst: TIntegerList;
InCodeClass: Boolean;
MapRec: TMapRec;
begin
HostMapTable := TKernel(kernel).prog.HostMapTable;
ClassLst := TIntegerList.Create;
SubLst := TIntegerList.Create;
for I := 0 to HostMapTable.Count - 1 do
case HostMapTable[I].Kind of
KindTYPE:
begin
Id := LookupFullName(HostMapTable[I].FullName, true);
if Id > 0 then
if Records[Id].FinalTypeId = typeCLASS then
ClassLst.Add(Id);
end;
KindSUB, KindCONSTRUCTOR, KindDESTRUCTOR:
begin
MapRec := HostMapTable[I];
Id := MapRec.SubDesc.SId;
if Id > 0 then
SubLst.Add(Id);
end;
end;
try
Id_GetOLEProperty := Lookup(_strGetOLEProperty, 0, false);
Id_SetOLEProperty := Lookup(_strSetOLEProperty, 0, false);
OffsetList := TKernel(kernel).OffsetList;
SignClassHeader := false;
InCodeClass := false;
S := StdSize;
OffsetList.Clear;
OffsetList.InitSize := S;
for I:= JS1 to JS2 do
if (I > 0) and (I < System.Length(InCode)) then
InCode[I] := true;
I := Id_GetOLEProperty;
if (I > 0) and (I < System.Length(InCode)) then
InCode[I] := true;
SubLst.Add(I);
I := Id_SetOLEProperty;
if (I > 0) and (I < System.Length(InCode)) then
InCode[I] := true;
SubLst.Add(I);
for KK := 1 to 2 do
begin
if KK = 1 then
begin
K1 := StdCard;
K2 := GlobalST.Card;
end
else
begin
K1 := FirstLocalId + 1;
K2 := Card;
end;
I := K1 - 1;
repeat
Inc(I);
if I > K2 then
break;
RI := Records[I];
if RI.Host then
begin
if RI.Kind = KindTYPE then
if RI.FinalTypeId = typeCLASS then
begin
SignClassHeader := true;
InCodeClass := ClassLst.IndexOf(I) >= 0;
if InCodeClass then
InCode[I] := true;
end;
if RI.Kind = kindTYPE then
if RI.TypeID = typeINTERFACE then
if InCode[I] then
begin
InCode[I + 1] := true;
InCode[I + 2] := true;
end;
end;
if SignClassHeader and InCodeClass then
InCode[I] := true;
if RI.Kind = kindEND_CLASS_HEADER then
begin
SignClassHeader := false;
InCodeClass := false;
continue;
end;
if I > CompileCard then
begin
InCode[I] := true;
if SignClassHeader and (not InCodeClass) then
InCode[I] := false;
end;
if InCode[I] then
if (RI.Shift > 0) and
(RI.Kind in (KindSUBS + [KindVAR, KindCONST])) then
begin
if RI.Param or RI.Local or RI.LocalInternalField then
continue;
if RI.UnionId > 0 then
continue;
SZ := 0;
if RI.Host then
begin
L := RI.Level;
if RI.Kind in KindSUBS then
if not (RI.IsSubPartOfEventType or RI.IsSubPartOfProcType) then
if (L = 0) or (Records[L].FinalTypeId <> typeINTERFACE) then
begin
if SubLst.IndexOf(I) = -1 then
begin
InCode[I] := false;
InCode[I+1] := false;
InCode[I+2] := false;
Inc(I, 2);
continue;
end;
end;
SZ := SizeOfPointer;
end
{$IFNDEF PAXARM}
else if RI.HasPAnsiCharType then
begin
SZ := 0;
Inc(SZ, SizeOfPointer); // pointer to string literal
Inc(SZ, SizeOfPointer); // ref counter
Inc(SZ, SizeOfPointer); // length
// reserve place for literal
Inc(SZ, Length(RI.Value) + 1);
end
{$ENDIF}
else if RI.HasPWideCharType then
begin
SZ := 0;
Inc(SZ, SizeOfPointer); // pointer to string literal
Inc(SZ, SizeOfPointer); // length
// reserve place for literal
Inc(SZ, Length(RI.Value) * 2 + 2);
end
else
SZ := RI.Size;
if RI.InternalField then
begin
SZ := 0;
OwnerId := RI.OwnerId;
D := RI.Shift - Records[OwnerId].Shift;
OwnerOffset := TKernel(kernel).GetOffset(Records[OwnerId]);
OffsetList.Add(I, RI.Shift, OwnerOffset + D, SZ);
continue;
end;
SZ := MPtr(SZ);
OffsetList.Add(I, RI.Shift, S, SZ);
Inc(S, SZ);
end;
until false;
end;
finally
FreeAndNil(ClassLst);
FreeAndNil(SubLst);
end;
end;
function TSymbolTable.GetValueAsString(P: Pointer;
StackFrameNumber: Integer;
Id: Integer;
TypeMapRec: TTypeMapRec = nil;
BriefCls: Boolean = false): String;
var
Address: Pointer;
TypeId: Integer;
Code: TCode;
N: Integer;
begin
result := '???';
if not Records[Id].Host then
if Records[Id].Param then
if Records[Id].ByRef then
begin
Code := TKernel(kernel).Code;
N := TBaseRunner(P).CurrN;
if Code.ParamHasBeenChanged(N, Id) then
Exit;
end;
Address := GetFinalAddress(P, StackFrameNumber, Id);
TypeId := Self[Id].TerminalTypeId;
if Address = nil then
Exit;
result := GetStrVal(Address, TypeId, TypeMapRec, BriefCls);
end;
function TSymbolTable.GetSizeOfParams(SubId: Integer): Integer;
var
I, J, SZ, RegCount: Integer;
R: TSymbolRec;
FinTypeId: Integer;
MaxRegCount: Integer;
begin
if Records[SubId].CallConv = cc64 then
MaxRegCount := 4
else
MaxRegCount := 3;
result := 0;
RegCount := 0;
if Records[SubId].IsMethod then
begin
if Records[SubId].CallConv in [ccREGISTER, ccMSFASTCALL, cc64] then
Inc(RegCount)
else
Inc(result, 4);
end;
for J:=0 to Records[SubId].Count - 1 do
begin
I := GetParamId(SubId, J);
R := Records[I];
if Records[SubId].CallConv in [ccREGISTER, ccMSFASTCALL, cc64] then
begin
if R.Register > 0 then
begin
Inc(RegCount);
if R.FinalTypeId in [typeDYNARRAY, typeOPENARRAY] then
if R.IsOpenArray then
begin
Inc(RegCount);
if RegCount > MaxRegCount then
Inc(result, 4);
end;
continue;
end;
end;
if R.ByRef or R.ByRefEx then
Inc(result, SizeOfPointer)
else
begin
SZ := R.Size;
FinTypeId := R.FinalTypeId;
if FinTypeId = typeEXTENDED then
if TKernel(kernel).TargetPlatform in [tpOSX32, tpIOSSim] then
SZ := 16;
if FinTypeId in [typeDYNARRAY, typeOPENARRAY] then
if R.IsOpenArray then
Inc(SZ, 4);
while SZ mod 4 <> 0 do
Inc(SZ);
Inc(result, SZ);
end;
end;
result := Abs(result);
if Records[SubId].ExtraParamNeeded then
begin
if Records[SubId].CallConv in [ccREGISTER, cc64] then
begin
if RegCount >= MaxRegCount then
Inc(result, 4);
end
else
Inc(result, 4);
end;
if Records[SubId].CallConv = ccSAFECALL then
Inc(result, 4);
end;
end.
|
namespace TestApplication;
interface
uses
proholz.xsdparser,
RemObjects.Elements.EUnit;
type
(**
* Each test represents an example of errors that might be present in a XSD file and test for the expected exception.
*)
XsdLanguageRestrictionsTest = public class(TestBaseClass)
private
protected
public
/**
* The parsed file has an invalid attribute, the top level xsd:element element shouldn't have a ref attribute,
* an exception is expected.
*/
method testLanguageRestriction1;
begin
Assert.Throws(->
gettestParser('language_restriction_1.xsd')
, typeOf(ParsingException)
);
end;
(**
* The value passed in the minOccurs attribute should be a non negative integer, therefore the parsing throws
* a parsing exception.
*)
method testLanguageRestriction2;
begin
Assert.Throws(->
gettestParser('language_restriction_2.xsd')
, typeOf(ParsingException)
);
end;
/**
* The value passed in the form attribute should belong to the {@link FormEnum}. Since it doesn't belong a parsing
* exception is expected.
*/
method testLanguageRestriction3;
begin
Assert.Throws(->
gettestParser('language_restriction_3.xsd')
, typeOf(ParsingException)
);
end;
end;
implementation
end. |
unit IslUtils;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus,
XmlObjModel;
type
{- an object dictionary is a TStringList which automatically disposes
of all child objects when free'd (list is sorted, duplicates are ignored)-}
TObjDict = class(TStringList)
protected
FOwnTheData : Boolean;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Clear; override;
procedure Delete(Index: Integer); override;
property OwnTheData : Boolean read FOwnTheData write FOwnTheData;
end;
TObjList = class(TList)
protected
FOwnTheData : Boolean;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Clear; override;
property OwnTheData : Boolean read FOwnTheData write FOwnTheData;
end;
PSearchRec = ^TSearchRec;
TFileNamesList = class(TStringList) // key is full path to file, value is PSearchRec
protected
function GetFileInfo(Index : Integer) : PSearchRec;
public
constructor Create; virtual;
destructor Destroy; override;
procedure AddFile(const AFullPath : String; var ASearchRec : TSearchRec);
property FileInfo[Index : Integer] : PSearchRec read GetFileInfo;
end;
//function ForceIntoAppPath(ARelativePath : String) : String;
{-given a path, force it to be relative to the active application}
procedure DisposeObject(Data : Pointer); far;
{-the generic DisposeData procedure that can free any object}
function Join(const ASeparator : String; AList : TStringList) : String;
{-join the given AList elements separated by ASeparator}
function Reverse(const S : String) : String;
{-reverse the contents of S and return the reverted string}
procedure ClearMenu(const AMenu : TMenu);
{-clear the menu items in AMenu }
function ColorToHtmlColor(Color : LongInt) : String;
{-return a TColor as an HTML color string}
function GetChildElem(const AElem : TXmlElement; const AFirst : Boolean) : TXmlElement;
{-find the first or last child element in AElem}
function GetSiblingElem(const AElem : TXmlElement; const ANext : Boolean) : TXmlElement;
{-find the next or previous sibling element in AElem}
function GetElemAttr(const ANode : TXmlElement; const AName, ADefault : String) : String; overload;
{-return an element attribute or the default if not found}
function GetElemAttr(const ANode : TXmlElement; const AName : String; const ADefault : Integer) : Integer; overload;
{-return an element attribute or the default if not found}
function GetElementText(const AElem : TXmlElement; const ANormalize : Boolean = False) : String;
{-given an element, get only the text at the immediate child level}
function SplitText(const ASource, ADelim : String; var ALeft, ARight : String) : Boolean;
{-split the source text into Left and Right and return true if ADelim found}
function DosWildMatch(const APattern, ASource : ShortString) : Boolean;
{ Returns TRUE if pattern defined in "pat" matches string passed in "s". }
{ Allows wild cards '?' (single character) and '*' (zero or more of any }
{ character) as in DOS. }
procedure ReadFilesInDirTree(const ADirPath : String; AMask : String; const AList : TFileNamesList);
{-given a path, read all files that match AMask in that directory and all subdirectories into AList}
function ReadFilesInDirTrees(const ADirPaths : String; AMask : String = '*.*'; const APathsDelim : String = ';') : TFileNamesList;
{-given a path (or paths separated by ;) get all files in those directories that match AMask
-caller should free the result}
//function ReadFilesInAppTrees(const ADirPaths : String; AMask : String = '*.*'; const APathsDelim : String = ';') : TFileNamesList;
{-given a path (or paths separated by ;) get all files in those directories that match AMask
-all paths in APaths are considered to be relative to the application directory (Exe)
-caller should free the result}
function FindString(const AMatch : String; const AList : array of String; const ADefault : Integer = -1) : Integer;
{-given a list of string, find out which one the match string is (-1 if none)}
function GetAppVersionInfo : String;
implementation
uses StStrS, StStrL;
constructor TObjDict.Create;
begin
inherited Create;
Sorted := True;
Duplicates := dupIgnore;
FOwnTheData := True;
end;
destructor TObjDict.Destroy;
var
I : Cardinal;
begin
if (Count > 0) and FOwnTheData then begin
for I := 0 to Count-1 do
if Objects[I] <> Nil then begin
Objects[I].Free;
Objects[I] := Nil;
end;
end;
inherited Destroy;
end;
procedure TObjDict.Clear;
var
I : Cardinal;
begin
if (Count > 0) and FOwnTheData then begin
for I := 0 to Count-1 do
if Objects[I] <> Nil then begin
Objects[I].Free;
Objects[I] := Nil;
end;
end;
inherited Clear;
end;
procedure TObjDict.Delete(Index: Integer);
begin
if FOwnTheData and (Objects[Index] <> Nil) then begin
Objects[Index].Free;
Objects[Index] := Nil;
end;
inherited Delete(Index);
end;
constructor TObjList.Create;
begin
inherited Create;
FOwnTheData := True;
end;
destructor TObjList.Destroy;
var
I : Cardinal;
begin
if (Count > 0) and FOwnTheData then begin
for I := 0 to Count-1 do
if Items[I] <> Nil then begin
TObject(Items[I]).Free;
Items[I] := Nil;
end;
end;
inherited Destroy;
end;
procedure TObjList.Clear;
var
I : Cardinal;
begin
if (Count > 0) and FOwnTheData then begin
for I := 0 to Count-1 do
if Items[I] <> Nil then begin
TObject(Items[I]).Free;
Items[I] := Nil;
end;
end;
inherited Clear;
end;
function ForceIntoAppPath(ARelativePath : String) : String;
begin
Result := AddBackSlashL(JustPathNameL(Application.ExeName))+ARelativePath;
end;
procedure DisposeObject(Data : Pointer); far;
begin
if (Data <> Nil) then
TObject(Data).Free;
end;
function Join(const ASeparator : String; AList : TStringList) : String;
var
I : Integer;
begin
Result := '';
if AList.Count > 0 then begin
for I := 0 to AList.Count-1 do begin
if I > 0 then
Result := Result + ASeparator + AList.Strings[I]
else
Result := AList.Strings[I];
end;
end;
end;
function Reverse(const S : String) : String;
var
I : Cardinal;
begin
Result := '';
for I := Length(S) downto 1 do
Result := Result + S[I];
end;
procedure ClearMenu(const AMenu : TMenu);
begin
while AMenu.Items.Count > 0 do
AMenu.Items.Remove(AMenu.Items[0]);
end;
function ColorToHtmlColor(Color : LongInt) : String;
begin
Result := '#' + HexBS(GetRValue(Color)) + HexBS(GetGValue(Color)) + HexBS(GetBValue(Color));
end;
function GetChildElem(const AElem : TXmlElement; const AFirst : Boolean) : TXmlElement;
var
E : TXmlNode;
begin
if AFirst then begin
E := AElem.FirstChild;
while (E <> Nil) and (E.NodeType <> ELEMENT_NODE) do
E := E.NextSibling;
Result := TXmlElement(E);
end else begin
E := AElem.LastChild;
while (E <> Nil) and (E.NodeType <> ELEMENT_NODE) do
E := E.PreviousSibling;
Result := TXmlElement(E);
end;
end;
function GetElemAttr(const ANode : TXmlElement; const AName, ADefault : String) : String; overload;
var
Attr : String;
begin
Attr := ANode.GetAttribute(AName);
if Attr = '' then Result := ADefault else Result := Attr;
end;
function GetElemAttr(const ANode : TXmlElement; const AName : String; const ADefault : Integer) : Integer; overload;
var
Attr : String;
begin
try
Attr := GetElemAttr(ANode, AName, IntToStr(ADefault));
Result := StrToInt(Attr);
except
Result := ADefault;
end;
end;
function GetSiblingElem(const AElem : TXmlElement; const ANext : Boolean) : TXmlElement;
var
E : TXmlNode;
begin
if ANext then begin
E := AElem.NextSibling;
while (E <> Nil) and (E.NodeType <> ELEMENT_NODE) do
E := E.NextSibling;
Result := TXmlElement(E);
end else begin
E := AElem.PreviousSibling;
while (E <> Nil) and (E.NodeType <> ELEMENT_NODE) do
E := E.PreviousSibling;
Result := TXmlElement(E);
end;
end;
function GetElementText(const AElem : TXmlElement; const ANormalize : Boolean) : String;
var
Node : TXmlNode;
I, ChildCount : Integer;
begin
Result := '';
if AElem = Nil then
Exit;
ChildCount := AElem.ChildNodes.Length;
if ChildCount > 0 then begin
Dec(ChildCount);
if ANormalize then begin
for I := 0 to ChildCount do begin
Node := AElem.ChildNodes.Item(I);
if Node.NodeType = TEXT_NODE then
Result := Result + FilterL(TrimL((Node as TXmlText).Data), #13#10#9) + ' ';
end;
end else begin
for I := 0 to ChildCount do begin
Node := AElem.ChildNodes.Item(I);
if Node.NodeType = TEXT_NODE then
Result := Result + (Node as TXmlText).Data;
end;
end;
end;
end;
function SplitText(const ASource, ADelim : String; var ALeft, ARight : String) : Boolean;
var
P : Integer;
begin
P := Pos(ADelim, ASource);
if P > 0 then begin
ALeft := Copy(ASource, 1, P-1);
ARight := Copy(ASource, P+Length(ADelim), Length(ASource));
Result := True;
end else
Result := False;
end;
function Remainder(start : Integer; s : ShortString) : ShortString;
{ returns portion of string to right of index "start" }
begin
Remainder := Copy(s, start, Length(s) - start + 1);
end {Remainder} ;
function DosWildMatch(const APattern, ASource : ShortString) : Boolean;
var
Pat, S : String;
PatLen : Integer;
{ Returns TRUE if pattern defined in "pat" matches string passed in "s". }
{ Allows wild cards '?' (single character) and '*' (zero or more of any }
{ character) as in DOS. }
function Match(pIndex, sIndex : Integer) : Boolean;
{ Used to handle recursive match process. Engineered to take up as }
{ little stack space as possible. }
var i : Integer;
begin
if (pIndex = Length(pat) + 1) and (sIndex = Length(s) + 1) then Match := True
else if Remainder(pIndex, pat) = '*' then Match := True
else if (pIndex > Length(pat)) or (sIndex > Length(s)) then Match := False
else
case pat[pIndex] of
'?' : Match := Match(pIndex + 1, sIndex + 1);
'*' : begin
for i := sIndex to Length(s) do
if Match(pIndex + 1, i) then
begin
Match := True;
Exit;
end;
Match := False;
end;
else Match := (pat[pIndex] = s[sIndex]) and Match(pIndex + 1, sIndex + 1);
end;
end {Match} ;
begin
PatLen := Length(APattern);
if PatLen = 0 then begin
DosWildMatch := True;
Exit;
end;
Pat := AnsiUpperCase(APattern);
S := AnsiUpperCase(ASource);
DosWildMatch := Match(1, 1);
end {Dos Wild Match} ;
constructor TFileNamesList.Create;
begin
inherited Create;
Sorted := True;
end;
destructor TFileNamesList.Destroy;
var
I : Integer;
begin
if Count > 0 then
for I := 0 to Count-1 do
Dispose(PSearchRec(Objects[I]));
inherited Destroy;
end;
function TFileNamesList.GetFileInfo(Index : Integer) : PSearchRec;
begin
Result := PSearchRec(Objects[Index]);
end;
procedure TFileNamesList.AddFile(const AFullPath : String; var ASearchRec : TSearchRec);
var
PRec : PSearchRec;
begin
New(PRec);
PRec^ := ASearchRec;
AddObject(AFullPath, TObject(PRec));
end;
procedure ReadFilesInDirTree(const ADirPath : String; AMask : String; const AList : TFileNamesList);
var
FRes : Integer;
FRec : TSearchRec;
PathWithSlash : String;
begin
PathWithSlash := AddBackSlashL(ADirPath);
FRes := FindFirst(PathWithSlash + '*.*', faAnyFile, FRec);
if FRes <> 0 then begin
FindClose(FRec);
Exit;
end;
repeat
if (FRec.Attr and faDirectory = faDirectory) then begin
if (FRec.Name <> '.') and (FRec.Name <> '..') then
ReadFilesInDirTree(PathWithSlash + FRec.Name, AMask, AList);
end else begin
if DosWildMatch(AMask, FRec.Name) then begin
AList.AddFile(PathWithSlash + FRec.Name, FRec);
end;
end;
FRes := FindNext(FRec);
until FRes <> 0;
FindClose(FRec);
end;
function ReadFilesInDirTrees(const ADirPaths : String; AMask : String; const APathsDelim : String) : TFileNamesList;
var
PC, P : Integer;
begin
Result := TFileNamesList.Create;
PC := WordCountL(ADirPaths, APathsDelim);
if PC > 1 then begin
for P := 1 to PC do
ReadFilesInDirTree(ExtractWordL(P, ADirPaths, APathsDelim), AMask, Result);
end else
ReadFilesInDirTree(ADirPaths, AMask, Result);
end;
function ReadFilesInAppTrees(const ADirPaths : String; AMask : String; const APathsDelim : String) : TFileNamesList;
var
PC, P : Integer;
begin
Result := TFileNamesList.Create;
PC := WordCountL(ADirPaths, APathsDelim);
if PC > 1 then begin
for P := 1 to PC do
ReadFilesInDirTree(ForceIntoAppPath(ExtractWordL(P, ADirPaths, APathsDelim)), AMask, Result);
end else
ReadFilesInDirTree(ForceIntoAppPath(ADirPaths), AMask, Result);
end;
function FindString(const AMatch : String; const AList : array of String; const ADefault : Integer) : Integer;
var
I : Integer;
begin
Result := ADefault;
if (AMatch = '') or (Length(AList) <= 0) then
Exit;
for I := 0 to High(AList) do begin
if CompareText(AMatch, AList[I]) = 0 then begin
Result := I;
Exit;
end;
end;
end;
function GetAppVersionInfo : String;
const
vqvFmt = '\StringFileInfo\%4.4x%4.4x\%s';
var
VFileDescription : String;
VFileVersion : String;
VInternalName : String;
VOriginalFileName : String;
VProductName : String;
VProductVersion : String;
FInfoSize : longint ;
FInfo : pointer;
FLang : PInteger;
vptr : pchar;
vlen : DWord;
FName : String;
begin
Result := '';
FName := Paramstr(0);
FInfoSize := GetFileVersionInfoSize(pchar(fname), vlen);
if FInfoSize > 0 then begin
GetMem(FInfo, FInfoSize);
if not GetFileVersionInfo(pchar(fname), vlen, FInfoSize, FInfo) then
raise Exception.Create('Cannot retrieve Version Information for ' + fname);
VerQueryValue(FInfo, '\VarFileInfo\Translation', pointer(FLang), vlen);
end
else exit;
try
if VerQueryValue(FInfo, pchar(Format(vqvFmt, [LoWord(FLang^), HiWord(FLang^),
'FileDescription'])), pointer(vptr), vlen)
then VFileDescription := vptr;
if VerQueryValue(FInfo, pchar(Format(vqvFmt, [LoWord(FLang^), HiWord(FLang^),
'FileVersion'])), pointer(vptr), vlen)
then VFileVersion := vptr;
if VerQueryValue(FInfo, pchar(Format(vqvFmt, [LoWord(FLang^), HiWord(FLang^),
'InternalName'])), pointer(vptr), vlen)
then VInternalName := vptr;
if VerQueryValue(FInfo, pchar(Format(vqvFmt, [LoWord(FLang^), HiWord(FLang^),
'OriginalFileName'])), pointer(vptr), vlen)
then VOriginalFileName := vptr;
if VerQueryValue(FInfo, pchar(Format(vqvFmt, [LoWord(FLang^), HiWord(FLang^),
'ProductName'])), pointer(vptr), vlen)
then VProductName := vptr;
if VerQueryValue(FInfo, pchar(Format(vqvFmt, [LoWord(FLang^), HiWord(FLang^),
'ProductVersion'])), pointer(vptr), vlen)
then VProductVersion := vptr;
finally
if FInfoSize > 0 then
FreeMem(FInfo, FInfoSize);
end;{ try }
Result := VFileVersion;
end;
end.
|
unit MainFormLib;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls,ScktComp,Common,SmsObj,superobject,ErrorLogsUnit,
SmsLib,Clipbrd,StrUtils;
(*
命令格式
type:command
type --
forces 密钥认证 如 forces:sihekejimustgo,如果返回给java的是 forces:sihekejibugo,则认证完毕
form 关闭或重启窗体 如 form:close form:restart
com 关闭或重启串口 如 com:close com:restart 关掉当前并开启某个串口 传一个数字即可 如com:2
msg 发送消息 如 msg:{msg:[{tel:'',msg:''}]},可以发送多个短信.消息内容异或加密
所有的命令要用^_^结尾
*)
type
TMainForm = class(TForm)
Logs: TMemo;
ClearLogBtn: TButton;
LogClear: TCheckBox;
DeBugCk: TCheckBox;
Timer: TTimer;
TimerFree: TTimer;
procedure TimerTimer(Sender: TObject);
procedure TimerFreeTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ClearLogBtnClick(Sender: TObject);
private
ScoketServer : TServerSocket; //本地监听scoket
SmsList : TSmsList; //消息集合
CloseCount : Integer; //有发送记录的标记
ClientSocket : TCustomWinSocket ;//客户端连接
CommandCashe : string; //命令缓存
Sms : TSmsLoad;
//**ScoketServer事件定义开始
procedure OnClientRead(Sender: TObject;Socket: TCustomWinSocket);
procedure OnClientConnect(Sender: TObject;Socket: TCustomWinSocket);
procedure OnClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
//**ScoketServer事件定义结束
procedure AddLogs(Content:string);
procedure RestartApp; //重启程序
public
Port : Integer;
Com : Integer;
BaudRate : Integer;
function OpenPort:Integer; //打开tcp
function OpenCom(NeedReapt :Boolean = True):Integer; //建立短信猫连接
function CloseCom:Integer; //关闭短信猫连接
function SendMsg(Tel,Msg:string):Integer; //发送短信
function DesFree:Integer; //释放、关闭资源
end;
var
MainForm: TMainForm;
key : string = 'sihekejikillall'; //加密密钥
cipher : string = 'sihekejimustgo'; //暗号
cipher2 : string = 'sihekejibugo';
App : TApplication;
IsSendIng:Boolean = False;
implementation
{$R *.dfm}
procedure TMainForm.AddLogs(Content:string);
begin
if DeBugCk.Checked then
begin
Logs.Lines.Add(FormatDateTime('hh:mm:ss', now) + ' ' + Content);
end
else
begin
if (LogClear.Checked) and (Logs.Lines.Count >= 100) then
begin
Logs.Lines.Clear;
end;
ErrorLogsUnit.addErrors(Content);
end;
end;
procedure TMainForm.OnClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
var
address : string;
begin
address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
AddLogs(address + '发生异常');
ErrorCode := 0;
end;
procedure TMainForm.OnClientConnect(Sender: TObject;Socket: TCustomWinSocket);
var
address : string;
begin
address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
AddLogs(address + '已经连接');
end;
procedure TMainForm.OnClientRead(Sender: TObject;Socket: TCustomWinSocket);
var
RevText : string; //接收到的消息
CommandType : string; //命令类型
Command : string; //命令内容
Index : Integer; //下标
RevObj : ISuperObject;//msg总对象
Msgs : TSuperArray; //msg数组们
begin
RevText := Trim(Socket.ReceiveText);
Addlogs('收到命令 >>' + RevText);
Index := Pos('^_^',RevText);
if (Index = 0) and (RevText <> '') then
begin
CommandCashe := CommandCashe + RevText;
Exit;
end;
CommandCashe := CommandCashe + LeftStr(RevText,Length(RevText)-3);
Index := Pos(':',RevText);
if Index = 0 then Exit;
CommandType := Common.SplitToStrings(CommandCashe,':')[0];
Command := RightStr(RevText,Length(RevText) - Index);
Command := LeftStr(Command,Length(Command) - 3);
SetLength(CommandCashe,0);
if CommandType = 'forces' then
begin
Addlogs('处理命令forces >>' + Command);
if Command = cipher then
begin
ClientSocket := Socket;
ClientSocket.SendText('forces:'+cipher2+#$D#$A);
end;
end
else if CommandType = 'form' then
begin
Addlogs('处理命令form >>' + Command);
ClientSocket.SendText('form'+#$D#$A);
if Command = 'close' then
begin
Close;
end
else if Command = 'restart' then
begin
RestartApp;
end;
end
else if CommandType = 'com' then
begin
Addlogs('处理命令com >>' + Command);
if Command = 'close' then
begin
CloseCom;
end
else if Command = 'restart' then
begin
CloseCom;
OpenCom;
end
else
begin
CloseCom;
Com := StrToInt(Command);
OpenCom;
end;
ClientSocket.SendText('com'+#$D#$A);
end
else if CommandType = 'msg' then
begin
IsSendIng := True;
Addlogs('处理命令msg >>' + Command);
RevObj := SO(Command);
if not Assigned(RevObj) then
begin
ClientSocket.SendText('msg'+#$D#$A);
AddLogs('解析格式错误'+Command);
Exit;
end;
Msgs := RevObj.A['msg'];
for Index := 0 to Msgs.Length - 1 do
begin
RevObj := Msgs.O[Index];
SendMsg(RevObj.S['tel'],RevObj.S['msg']);
end;
ClientSocket.SendText('msg'+#$D#$A);
IsSendIng := False;
end;
end;
function TMainForm.OpenPort:Integer;
begin
ScoketServer := TServerSocket.Create(App);
ScoketServer.Port := Port;
ScoketServer.OnClientConnect := OnClientConnect;
ScoketServer.OnClientRead := OnClientRead;
ScoketServer.Socket.OnClientError := OnClientError;
try
ScoketServer.Open;
Result := 1;
AddLogs(InttoStr(Port) + '端口准备over');
except
Result := 0;
end;
end;
function TMainForm.OpenCom(NeedReapt :Boolean = True):Integer;
var
Mobile_Type :pchar;
CopyRightToCOM:pchar;
begin
Result := 0;
Mobile_Type := nil;
CopyRightToCOM := nil;
AddLogs(InttoStr(Com) + '串口打开中');
if not Assigned(Sms) then Sms := TSmsLoad.Create(Result);
if Result = 1 then Result := Sms.Connection('//上海迅赛信息技术有限公司,网址www.xunsai.com//',COM,BaudRate,Mobile_Type,CopyRightToCOM);
if Result <> 1 then closeCom
else
begin
Timer.Enabled := True;
AddLogs(InttoStr(Com) + '串口打开了');
TimerFree.Enabled := True;
if NeedReapt and Assigned(ClientSocket)then
ClientSocket.SendText('com'+#$D#$A)
end;
end;
procedure TMainForm.ClearLogBtnClick(Sender: TObject);
begin
Clipboard.AsText := Logs.Text;
Logs.Lines.Clear;
end;
function TMainForm.CloseCom:Integer;
begin
Result := 0;
CloseCount := 0;
if Assigned(Sms) then
begin
Sms.Disconnection;
Timer.Enabled := False;
Sms := nil;
AddLogs('串口关闭了');
Result := 1;
TimerFree.Enabled := False;
end;
end;
function TMainForm.SendMsg(Tel,Msg:string):Integer;
begin
Result := 0;
if not Assigned(Sms) then OpenCom(False);
if Assigned(Sms) then Result := Sms.Send(Common.deLargeCode(Tel,key),Common.deLargeCode(Msg,key));
if Result = 1 then AddLogs('发送完毕>>'+Common.deLargeCode(Msg,key) + '>>>' + Common.deLargeCode(Tel,key))
else AddLogs('发送失败>>'+Common.deLargeCode(Msg,key) + '>>>' + Common.deLargeCode(Tel,key));
CloseCount := 0;
end;
function TMainForm.DesFree:Integer;
begin
CloseCom;
Result := 1;
AddLogs('资源释放完毕');
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
if not DeBugCk.Checked then
Application.ShowMainForm := False;
if not DirectoryExists(ExtractFileDir(PARAMSTR(0)) + '\logs') then CreateDirectory(PChar(ExtractFilePath(ParamStr(0)) + '\logs'), nil);
CloseCount := 0;
SetLength(CommandCashe,0);
end;
procedure TMainForm.TimerFreeTimer(Sender: TObject);
begin
Inc(CloseCount);
if (CloseCount >= 5) and (not IsSendIng) then
begin
CloseCom;
AddLogs('闲置时间超过5分钟,关闭串口');
end;
end;
procedure TMainForm.TimerTimer(Sender: TObject);
var
StrSmsReceive:PChar;
I : Integer;
SmsOne :TSms;
RObject :ISuperObject;
begin
StrSmsReceive := PChar('');
if Assigned(Sms) and Assigned(ClientSocket) and ( Sms.NewFlag = 1 )then
begin
if Sms.Receive('4',StrSmsReceive) = 1 then
begin
SmsObj.getSmsListFromString(StrSmsReceive,SmsList);
if Assigned(SmsList) then
begin
CloseCount := 0;
for I := 0 to SmsList.Count - 1 do
begin
SmsOne := SmsList.Values[I];
if SmsOne.SmsType = '24' then
begin
RObject := SO('{}');
RObject.S['tel'] := Common.enLargeCode(SmsOne.Tel,key);
RObject.S['msg'] := Common.enLargeCode(SmsOne.Text,key);
AddLogs('收到消息' + SmsOne.Text + '来自' + SmsOne.Tel);
ClientSocket.SendText(RObject.AsString + #$D#$A);
end;
Sms.Delete(SmsOne.Index);
end;
SmsList.clear;
end;
end;
end;
end;
procedure TMainForm.RestartApp;
var
BatchFile: TextFile;
BatchFileName: string;
ProcessInfo: TProcessInformation;
StartUpInfo: TStartupInfo;
begin
try
BatchFileName := ExtractFilePath(ParamStr(0)) + '_D.bat';
AssignFile(BatchFile, BatchFileName);
Rewrite(BatchFile);
Writeln(BatchFile, ExtractFileName(Application.ExeName) + ' ' + IntToStr(Port) + ' ' + IntToStr(Com) + ' '+IntToStr(BaudRate));
Writeln(BatchFile, 'del %0');
CloseFile(BatchFile);
FillChar(StartUpInfo, SizeOf(StartUpInfo), $00);
StartUpInfo.dwFlags := STARTF_USESHOWWINDOW;
StartUpInfo.wShowWindow := SW_HIDE;
if CreateProcess(nil, PChar(BatchFileName), nil, nil,False, IDLE_PRIORITY_CLASS, nil, nil, StartUpInfo,ProcessInfo) then
begin
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
end;
Close;
Application.Terminate;
except
ErrorLogsUnit.addErrors('系统重启失败');
end;
end;
end.
|
Retiré de Elphy le 24 juin 2010
unit stmD3Dobj;
interface
uses windows,DirectXGraphics, D3DX81mo,
util1,Dgraphic,dibG,listG,
stmDef,stmObj,
stmMat1;
type
Tobject3D=class(typeUO)
constructor create;override;
class function stmClassName:string;override;
procedure display3D(D3dDevice:IDIRECT3DDEVICE8;x,y,z,tx,ty,tz:single);virtual;
procedure releaseDevice;virtual;
end;
function rgbaValue(r,g,b,a:single):TD3DColorValue;
function D3Dvector(x,y,z:single):TD3Dvector;
function rgbToD3D(col:integer;a:single):TD3DColorValue;
implementation
function rgbaValue(r,g,b,a:single):TD3DColorValue;
begin
result.r:=r;
result.g:=g;
result.b:=b;
result.a:=a;
end;
function D3Dvector(x,y,z:single):TD3Dvector;
begin
result.x:=x;
result.y:=y;
result.z:=z;
end;
function rgbToD3D(col:integer;a:single):TD3DColorValue;
begin
result.r:=(col and $FF)/255;
result.g:=((col shr 8) and $FF)/255;
result.b:=((col shr 16) and $FF)/255;
result.a:=a;
end;
{ Tobject3D }
constructor Tobject3D.create;
begin
inherited;
end;
procedure Tobject3D.display3D(D3dDevice:IDIRECT3DDEVICE8;x,y,z,tx,ty,tz:single);
begin
end;
class function Tobject3D.stmClassName: string;
begin
result:='Object3D';
end;
procedure Tobject3D.releaseDevice;
begin
end;
end.
|
{
OSM tile images cache.
Stores tile images for the map, could read/save them from/to local files but
doesn't request them from network. See OSM.NetworkRequest unit
}
unit OSM.TileStorage;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{$IFDEF FPC}
LazPNG,
{$ENDIF}
{$IFDEF DCC}
PngImage,
{$ENDIF}
SysUtils, Classes, Graphics,
OSM.SlippyMapUtils;
const
// Amount of bytes that a single tile bitmap occupies in memory.
// Bitmap consumes ~4 byte per pixel. This constant could be used to
// determine acceptable cache size knowing acceptable memory usage.
TILE_BITMAP_SIZE = 4*TILE_IMAGE_WIDTH*TILE_IMAGE_HEIGHT;
// Default pattern of tile file path. Placeholders are for: Zoom, X, Y
// Define custom patt in TTileStorage.Create to modify tiles disposition
// (f.ex., place them all in a single folder with names like tile_%zoom%_%x%_%y%.png)
DefaultTilePathPatt = '%d'+PathDelim+'%d'+PathDelim+'%d.png';
type
// List of cached tile bitmaps with fixed capacity organised as queue
TTileBitmapCache = class
strict private
type
TTileBitmapRec = record
Tile: TTile;
Bmp: TBitmap;
end;
PTileBitmapRec = ^TTileBitmapRec;
strict private
FCache: TList;
class function NewItem(const Tile: TTile; Bmp: TBitmap): PTileBitmapRec;
class procedure FreeItem(pItem: PTileBitmapRec);
public
constructor Create(Capacity: Integer);
destructor Destroy; override;
procedure Push(const Tile: TTile; Bmp: TBitmap);
function Find(const Tile: TTile): TBitmap;
end;
TTileStorageOption = (
tsoNoFileCache, // disable all file cache operations
tsoReadOnlyFileCache // disable write file cache operations
);
TTileStorageOptions = set of TTileStorageOption;
// Class that encapsulates memory and file cache of tile images
TTileStorage = class
strict private
FBmpCache: TTileBitmapCache;
FFileCacheBaseDir: string;
FTilePathPatt: string;
FOptions: TTileStorageOptions;
function GetTileFilePath(const Tile: TTile): string; inline;
function GetFromFileCache(const Tile: TTile): TBitmap;
procedure StoreInFileCache(const Tile: TTile; Ms: TMemoryStream);
public
constructor Create(CacheSize: Integer; const TilePathPatt: string = DefaultTilePathPatt);
destructor Destroy; override;
function GetTile(const Tile: TTile): TBitmap;
procedure StoreTile(const Tile: TTile; Ms: TMemoryStream);
property Options: TTileStorageOptions read FOptions write FOptions;
property FileCacheBaseDir: string read FFileCacheBaseDir write FFileCacheBaseDir;
end;
implementation
// For some reason this is 4x faster than bmp.Assign(png)...
function PNGtoBitmap(png: TPngImage): TBitmap;
begin
Result := TBitmap.Create;
{$IFDEF FPC}
Result.Assign(png); {}// TODO - maybe alternative option
{$ENDIF}
{$IFDEF DCC}
Result.PixelFormat := pf32bit;
Result.SetSize(png.Width, png.Height);
png.Draw(Result.Canvas, Rect(0, 0, png.Width, png.Height));
{$ENDIF}
end;
{$REGION 'TTileBitmapCache'}
class function TTileBitmapCache.NewItem(const Tile: TTile; Bmp: TBitmap): PTileBitmapRec;
begin
New(Result);
Result.Tile := Tile;
Result.Bmp := Bmp;
end;
class procedure TTileBitmapCache.FreeItem(pItem: PTileBitmapRec);
begin
pItem.Bmp.Free;
Dispose(pItem);
end;
constructor TTileBitmapCache.Create(Capacity: Integer);
begin
FCache := TList.Create;
FCache.Capacity := Capacity;
end;
destructor TTileBitmapCache.Destroy;
begin
while FCache.Count > 0 do
begin
FreeItem(PTileBitmapRec(FCache[0]));
FCache.Delete(0);
end;
FreeAndNil(FCache);
end;
procedure TTileBitmapCache.Push(const Tile: TTile; Bmp: TBitmap);
begin
if FCache.Count = FCache.Capacity then
begin
FreeItem(PTileBitmapRec(FCache[0]));
FCache.Delete(0);
end;
FCache.Add(NewItem(Tile, Bmp));
end;
function TTileBitmapCache.Find(const Tile: TTile): TBitmap;
var idx: Integer;
begin
for idx := 0 to FCache.Count - 1 do
if TilesEqual(Tile, PTileBitmapRec(FCache[idx]).Tile) then
Exit(PTileBitmapRec(FCache[idx]).Bmp);
Result := nil;
end;
{$ENDREGION}
{$REGION 'TTileStorage'}
// CacheSize - capacity of image cache.
constructor TTileStorage.Create(CacheSize: Integer; const TilePathPatt: string);
begin
FBmpCache := TTileBitmapCache.Create(CacheSize);
FTilePathPatt := TilePathPatt;
end;
destructor TTileStorage.Destroy;
begin
FreeAndNil(FBmpCache);
end;
function TTileStorage.GetTileFilePath(const Tile: TTile): string;
begin
Result := FFileCacheBaseDir + Format(FTilePathPatt, [Tile.Zoom, Tile.ParameterX, Tile.ParameterY]);
end;
function TTileStorage.GetFromFileCache(const Tile: TTile): TBitmap;
var
png: TPngImage;
Path: string;
begin
Result := nil;
Path := GetTileFilePath(Tile);
if FileExists(Path) then
begin
png := TPngImage.Create;
png.LoadFromFile(Path);
Result := PNGtoBitmap(png);
FreeAndNil(png);
end;
end;
procedure TTileStorage.StoreInFileCache(const Tile: TTile; Ms: TMemoryStream);
var
Path: string;
begin
Path := GetTileFilePath(Tile);
ForceDirectories(ExtractFileDir(Path));
Ms.SaveToFile(Path);
end;
// Try to get tile bitmap, return nil if not available locally.
// If bitmap has been loaded from file, store it in cache
function TTileStorage.GetTile(const Tile: TTile): TBitmap;
begin
// try to load from memory cache
Result := FBmpCache.Find(Tile);
if Result <> nil then
Exit;
// try to load from disk cache
if not (tsoNoFileCache in FOptions) then
begin
Result := GetFromFileCache(Tile);
if Result <> nil then
FBmpCache.Push(Tile, Result);
end;
end;
// Add tile PNG to memory and file cache
procedure TTileStorage.StoreTile(const Tile: TTile; Ms: TMemoryStream);
var
png: TPngImage;
SavePos: Int64;
begin
png := nil;
try
SavePos := Ms.Position;
// Save to disk as PNG
if ([tsoNoFileCache, tsoReadOnlyFileCache] * FOptions = []) then
StoreInFileCache(Tile, Ms);
Ms.Position := SavePos;
// Convert to bitmap and store in memory cache
png := TPngImage.Create;
png.LoadFromStream(Ms);
Ms.Position := SavePos;
FBmpCache.Push(Tile, PNGtoBitmap(png));
finally
FreeAndNil(png);
end;
end;
{$ENDREGION}
end.
|
// ************************************************************************ //
// このファイルに宣言されている型は、下記の WSDL ファイルから
// 読み取られたデータから生成されました:
// WSDL : http://localhost:5000/wsdl/IMathResource
// バージョン : 1.0
// (2014/04/13 22:13:57 - - $Rev: 56641 $)
// ************************************************************************ //
unit Nullpobug.Example.Spring4d.MathResource;
interface
uses
Soap.InvokeRegistry
, Soap.SOAPHTTPClient
, Soap.XSBuiltIns
, System.Types
{$IFDEF MSWINDOWS}
, System.Win.ComObj
, Winapi.ActiveX
{$ENDIF}
, Xml.xmldom
;
type
// ************************************************************************ //
// WSDL ドキュメントで参照される、次の型は、
// このファイルで表現されていません。これらは、表現された、または参照された、別の型のエイリアス [@] ですが、
// ドキュメントで [!] 宣言されていません。後者のカテゴリの型は
// 一般に事前定義/既知の XML (Embarcadero 型) にマップされます。ただし
// スキーマ型の宣言またはインポートに失敗した無効な WSDL ドキュメントを示すこともできます。
// ************************************************************************ //
// !:int - "http://www.w3.org/2001/XMLSchema"[]
// ************************************************************************ //
// 名前空間 : urn:MathResourceIntf-IMathResource
// SOAP アクション: urn:MathResourceIntf-IMathResource#%operationName%
// トランスポート : http://schemas.xmlsoap.org/soap/http
// スタイル : rpc
// 使用 : encoded
// バインディング : IMathResourcebinding
// サービス : IMathResourceservice
// ポート : IMathResourcePort
// URL : http://localhost:5000/soap/IMathResource
// ************************************************************************ //
IMathResource = interface(IInvokable)
['{ED670BD7-8A5C-37AC-0A43-09B7ADD5A0C5}']
function Add(const A: Integer; const B: Integer): Integer; stdcall;
function Multiply(const A: Integer; const B: Integer): Integer; stdcall;
end;
function GetIMathResource(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IMathResource;
implementation
uses System.SysUtils;
function GetIMathResource(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IMathResource;
const
defWSDL = 'http://localhost:5000/wsdl/IMathResource';
defURL = 'http://localhost:5000/soap/IMathResource';
defSvc = 'IMathResourceservice';
defPrt = 'IMathResourcePort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as IMathResource);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
initialization
{$IFDEF MACOS}
DefaultDOMVendor := 'ADOM XML v4';
{$ELSE}
CoInitializeEx(nil, COINIT_MULTITHREADED);
DefaultDOMVendor := 'MSXML';
{$ENDIF}
{ IMathResource }
InvRegistry.RegisterInterface(TypeInfo(IMathResource), 'urn:MathResourceIntf-IMathResource', '');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IMathResource), 'urn:MathResourceIntf-IMathResource#%operationName%');
end.
|
unit SheetToBankAllDataModul;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
frxClass, frxDBSet, frxDesgn, IBase, IniFiles, Forms, Dates, Variants,
ZProc, ZSvodTypesUnit, Controls, FIBQuery,
pFIBQuery, pFIBStoredProc, ZMessages, Dialogs, Math, ZSvodProcUnit, Unit_ZGlobal_Consts,
frxExportXLS;
type
TDMAll = class(TDataModule)
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
Designer: TfrxDesigner;
DSetData: TpFIBDataSet;
ReportDsetData: TfrxDBDataset;
DSetGlobalData: TpFIBDataSet;
ReportDSetGlobalData: TfrxDBDataset;
Report: TfrxReport;
DSetSetup: TpFIBDataSet;
ReportDSetSetup: TfrxDBDataset;
StProc: TpFIBStoredProc;
WriteTransaction: TpFIBTransaction;
frxXLSExport: TfrxXLSExport;
procedure ReportGetValue(const VarName: String; var Value: Variant);
procedure DataModuleCreate(Sender: TObject);
procedure ReportAfterPrintReport(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
PId_man:integer;
PId_Session:integer;
PTn:integer;
PKodSetup:integer;
PStrIdBank:string;
PIdBank:integer;
PStrOrderBy:string;
PlanguageIndex:byte;
Is_Printed:boolean;
IsCopy:boolean;
procedure SetBank(ABank:integer);
public
function PrintSpr(var AParameter:TSheetToBankAllParameter):variant;
property Bank:integer read PIdBank write SetBank;
property OrderBy:String read PStrOrderBy write PStrOrderBy;
property KodSetup:Integer read PKodSetup write PKodSetup;
property Printed:boolean read Is_Printed;
end;
implementation
{$R *.dfm}
const Path_IniFile_Reports = 'Reports\Zarplata\Reports.ini';
const SectionOfIniFile = 'SheetToBank';
const NameReport = 'Reports\Zarplata\SheetToBank.fr3';
function TDMAll.PrintSpr(var AParameter:TSheetToBankAllParameter):variant;
var IniFile:TIniFile;
ViewMode:integer;
PathReport,TPathReport:string;
LengthOfFileNameExt:byte;
function PrepareData:integer;
begin
try
StProc.Transaction.StartTransaction;
StProc.StoredProcName := 'UV_SHEET_TO_BANK_ALLDATA_PREP';
StProc.Prepare;
StProc.ParamByName('KOD_SETUP').AsInteger := PKodSetup;
StProc.ParamByName('ID_TYPE_PAYMENT').AsInteger := PIdBank;
StProc.ExecProc;
PrepareData := StProc.ParamByName('ID_SESSION').AsInteger;
StProc.Transaction.Commit;
except
on E:exception do
begin
ZShowMessage(Error_Caption[PlanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
PrepareData:=-1;
end;
end;
end;
begin
Is_Printed:=False;
IsCopy:=AParameter.Id_session>0;
PLanguageIndex:=LanguageIndex;
IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports);
ViewMode:=IniFile.ReadInteger(SectionOfIniFile,'ViewMode',1);
PathReport:=IniFile.ReadString(SectionOfIniFile,'SheetToBank',NameReport);
TPathReport:=ExtractFilePath(Application.ExeName)+PathReport;
LengthOfFileNameExt:=length(ExtractFileExt(TPathReport));
TPathReport:=copy(TPathReport,1,Length(TPathReport)-LengthOfFileNameExt)+PStrIdBank+ExtractFileExt(TPathReport);
if FileExists(TPathReport) then
PathReport:=TPathReport
else
if FileExists(ExtractFilePath(Application.ExeName)+PathReport) then
PathReport:=ExtractFilePath(Application.ExeName)+PathReport
else
begin
ZShowMessage(Error_Caption[PlanguageIndex],ZePrintShablonNotFound_Error_Text[PLanguageIndex],mtError,[mbOK]);
Exit;
end;
IniFile.Free;
PId_man:=0;
PTn:=0;
Screen.Cursor:=crHourGlass;
DSetSetup.SQLs.SelectSQL.Text:='SELECT FULL_NAME,DIRECTOR,GLAV_BUHG,OKPO,NAME_MANEG,GlBuhg_post_short FROM Z_SETUP';
if AParameter.Id_session=0 then
DSetData.SQLs.SelectSQL.Text := 'SELECT * FROM UV_SHEET_TO_BANK_ALLDATA('+
PStrIdBank+','+IntToStr(PKodSetup)+') '+PStrOrderBy
else
DSetData.SQLs.SelectSQL.Text := 'SELECT * FROM UV_SHEET_TO_BANK_ALLDATA('+
IntToStr(AParameter.Id_session)+',0)'+PStrOrderBy;
DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT KOD_SETUP,SUMMA FROM UV_SHEET_TO_BANK_ALLDATA_GLOBAL(?ID_SESSION)';
try
DB.Handle:=AParameter.DB_Handle;
if AParameter.Id_session=0 then AParameter.Id_session:=PrepareData;
if AParameter.Id_session=-1 then
begin
if not ReadTransaction.InTransaction then
ReadTransaction.StartTransaction;
ReadTransaction.Rollback;
Exit;
end;
PId_Session:=AParameter.Id_session;
DSetSetup.SQLs.SelectSQL.Text:='SELECT FULL_NAME,DIRECTOR,GLAV_BUHG,OKPO,NAME_MANEG,GlBuhg_post_short FROM Z_SETUP';
DSetData.SQLs.SelectSQL.Text := 'SELECT * FROM UV_SHEET_TO_BANK_ALLDATA('+
IntToStr(AParameter.Id_session)+')'+PStrOrderBy;
DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT KOD_SETUP,SUMMA FROM UV_SHEET_TO_BANK_ALLDATA_GLOBAL('+IntToStr(AParameter.id_session)+')';
DSetData.Open;
DSetGlobalData.Open;
DSetSetup.Open;
except
on E:Exception do
begin
Screen.Cursor:=crDefault;
ZShowMessage(Error_Caption[LanguageIndex],e.Message,mtError,[mbOK]);
Exit;
end;
end;
if DSetData.IsEmpty then
begin
Screen.Cursor:=crDefault;
ZShowMessage(Error_Caption[LanguageIndex],Message_Data_Nothing_Selected[LanguageIndex],mtInformation,[mbOK]);
Exit;
end;
Report.Clear;
Report.LoadFromFile(PathReport,True);
Report.Variables.Clear;
Screen.Cursor:=crDefault;
if zDesignReport then Report.DesignReport
else Report.ShowReport;
// Report.DesignReport;
Report.Free;
if IsCopy then Exit;
try
StProc.Transaction.StartTransaction;
StProc.StoredProcName := 'UV_AFTER_PRINT_TP_BANK';
StProc.Prepare;
if Is_Printed then StProc.ParamByName('KOD_SETUP').AsInteger := PKodSetup
else StProc.ParamByName('KOD_SETUP').AsInteger := -1;
StProc.ParamByName('ID_SESSION').AsInteger:= PId_Session;
StProc.ParamByName('ID_TYPE_PAYMENT').AsInteger:=PIdBank;
StProc.ExecProc;
StProc.Transaction.Commit;
except
on E:exception do
begin
ZShowMessage(Error_Caption[PlanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
end;
end;
end;
procedure TDMAll.ReportGetValue(const VarName: String; var Value: Variant);
begin
if UpperCase(VarName)='PPERIOD' then
Value:= '<b><u>'+AnsiLowercase(KodSetupToPeriod(DSetGlobalData['KOD_SETUP'],5))+'</u></b>';
if UpperCase(VarName)='PSUMMASTR' then
Value:= SumToString(DSetGlobalData['SUMMA']);
end;
procedure TDMAll.DataModuleCreate(Sender: TObject);
begin
PStrIdBank:='';
PStrOrderBy:='';
end;
procedure TDMAll.SetBank(ABank:integer);
begin
PIdBank:=ABank;
PStrIdBank:=IntToStr(ABank);
end;
procedure TDMAll.ReportAfterPrintReport(Sender: TObject);
begin
if IsCopy then Exit;
Is_Printed:=True;
end;
procedure TDMAll.DataModuleDestroy(Sender: TObject);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
end.
|
{Задание №19
Даны 3 вещественных числа. Вывести на экран:
а) те из них, которые принадлежат интервалу 1,6 — 3,8}
var
a, b, c: real;
begin
read(a, b, c);
if(a > 1.6)and(a < 3.8)then
begin
writeln(a);
end
else
begin
writeln(' Число a не входит в данный интервал.');
end;
if (b > 1.6) and (b < 3.8) then
begin
writeln(b);
end
else
begin
writeln(' Число b не входит в данный интервал.');
end;
if (c > 1.6) and (c < 3.8) then
begin
writeln(c);
end
else
begin
writeln(' Число c не входит в данный интервал.');
end;
end.
{проверочные данные:0.0, 1.0, 4.0,
(Число a не входит в данный интервал.
Число b не входит в данный интервал.
Число c не входит в данный интервал.)
проверочные данные:-2.0, 3.0, 6.0,
( Число a не входит в данный интервал.
3
Число c не входит в данный интервал.)
проверочные данные:2.0, 10.0, 3.5
(2
Число b не входит в данный интервал.
3.5)
} |
unit line_reader;
interface
uses
classes;
type
TLineReader = class
private
FStream: TStream;
FBuf: String;
FBufFill,
FBufPos: SizeInt;
public
constructor Create(Stream: TStream);
function ReadLine(out s: String): Boolean;
end;
implementation
uses
sysutils;
constructor TLineReader.Create(Stream: TStream);
begin
inherited Create;
if Stream = NIL then
raise EArgumentException.Create('Stream is NIL');
FStream := Stream;
SetLength(FBuf, 1024);
FBufFill := 0;
FBufPos := 1;
end;
function TLineReader.ReadLine(out s: String): Boolean;
const
CR = #13;
LF = #10;
var
WasCr: Boolean;
i,
PartEnd: SizeInt;
begin
s := '';
WasCr := (FBufPos > 1) and (FBuf[FBufPos - 1] = CR);
while TRUE do
begin
Assert(FBufPos <= FBufFill + 1);
if FBufPos = FBufFill + 1 then
begin
FBufFill := FStream.read(FBuf[1], Length(FBuf));
FBufPos := 1;
if FBufFill = 0 then
break;
end;
if WasCr then
begin
WasCr := FALSE;
if FBuf[FBufPos] = LF then
begin
Inc(FBufPos);
continue;
end;
end;
PartEnd := FBufFill + 1;
for i := FBufPos to FBufFill do
if (FBuf[i] = CR) or (FBuf[i] = LF) then
begin
PartEnd := i;
break;
end;
s := s + Copy(FBuf, FBufPos, PartEnd - FBufPos);
FBufPos := PartEnd;
if FBufPos < FBufFill + 1 then
begin
Inc(FBufPos);
break;
end;
end;
result := (s <> '') or (FBufFill > 0);
end;
end.
|
unit frmOrders;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, dbfunc, uKernel;
type
TfOrders = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
Label3: TLabel;
Label5: TLabel;
Label2: TLabel;
cmbStatusOrder2: TComboBox;
cmbTypeOrders2: TComboBox;
cmbAcademicYear2: TComboBox;
bSave: TButton;
bClose: TButton;
Label4: TLabel;
Label6: TLabel;
Label7: TLabel;
eNumberOrder: TEdit;
dtpDateOrder: TDateTimePicker;
dtpDateEvent: TDateTimePicker;
mCommentOrder: TMemo;
GroupBox2: TGroupBox;
cmbTypeOrders1: TComboBox;
cmbStatusOrder1: TComboBox;
cmbAcademicYear1: TComboBox;
Label10: TLabel;
Label8: TLabel;
Label9: TLabel;
lvOrders: TListView;
bAddOrder: TButton;
Label11: TLabel;
dtpEventEnding: TDateTimePicker;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cmbAcademicYear1Change(Sender: TObject);
procedure cmbTypeOrders1Change(Sender: TObject);
procedure cmbStatusOrder1Change(Sender: TObject);
procedure lvOrdersSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure bSaveClick(Sender: TObject);
procedure bAddOrderClick(Sender: TObject);
procedure cmbTypeOrders2Change(Sender: TObject);
private
IDOrder: integer;
AcademicYear: TResultTable;
OrderType: TResultTable;
StatusOrder: TResultTable;
Orders: TResultTable;
FIDCurAcademicYear: integer;
procedure ShowOrdersList;
procedure SetIDCurAcademicYear(const Value: integer);
procedure DoClearOrder;
public
property IDCurAcademicYear: integer read FIDCurAcademicYear
write SetIDCurAcademicYear;
end;
var
fOrders: TfOrders;
implementation
{$R *.dfm}
// TODO: добавить сортировку приказов: по дате, по типу, по статусу
// TODO: продумать вывод в комбик с типами приказов - добавить объединенные типы а'ля: Для расписания, Для нагрузки
procedure TfOrders.bAddOrderClick(Sender: TObject);
var
i: integer;
begin
DoClearOrder;
for i := 0 to AcademicYear.Count - 1 do
if AcademicYear[i].ValueByName('ID') = IDCurAcademicYear then
cmbAcademicYear2.ItemIndex := i;
IDOrder := -1;
end;
procedure TfOrders.bSaveClick(Sender: TObject);
var
EventEnding: string;
begin
if (cmbAcademicYear2.ItemIndex = -1) or (cmbTypeOrders2.ItemIndex = -1) or
(cmbStatusOrder2.ItemIndex = -1) or (Trim(eNumberOrder.Text) = '') then
begin
ShowMessage('Не все поля заполнены!');
Exit;
end;
if dtpEventEnding.Visible = false then
EventEnding := ''
else
EventEnding := dateToStr(dtpEventEnding.Date);
if Kernel.SaveOrder([IDOrder, OrderType[cmbTypeOrders2.ItemIndex]
.ValueByName('ID'), AcademicYear[cmbAcademicYear2.ItemIndex]
.ValueByName('ID'), StatusOrder[cmbStatusOrder2.ItemIndex]
.ValueByName('CODE'), StrToInt(eNumberOrder.Text),
dateToStr(dtpDateOrder.Date), dateToStr(dtpDateEvent.Date), EventEnding,
mCommentOrder.Text]) then
ShowMessage('Сохранение выполнено!')
else
ShowMessage('Ошибка при сохранении!');
ShowOrdersList;
end;
procedure TfOrders.cmbAcademicYear1Change(Sender: TObject);
begin
ShowOrdersList;
end;
procedure TfOrders.cmbStatusOrder1Change(Sender: TObject);
var
i: integer;
begin
ShowOrdersList;
i := cmbStatusOrder1.ItemIndex;
end;
procedure TfOrders.cmbTypeOrders1Change(Sender: TObject);
begin
ShowOrdersList;
end;
procedure TfOrders.cmbTypeOrders2Change(Sender: TObject);
var
id: integer;
begin
// тип приказа с ID = 6 это командировка
id := OrderType[cmbTypeOrders2.ItemIndex].ValueByName('ID');
if OrderType[cmbTypeOrders2.ItemIndex].ValueByName('ID') = 6 then
begin
dtpEventEnding.Visible := true;
dtpEventEnding.Date := Date;
end
else
dtpEventEnding.Visible := false;
end;
procedure TfOrders.DoClearOrder;
begin
eNumberOrder.Clear;
mCommentOrder.Clear;
dtpDateOrder.Date := Date;
dtpDateEvent.Date := Date;
dtpEventEnding.Visible := false;
cmbAcademicYear2.ItemIndex := -1;
cmbTypeOrders2.ItemIndex := -1;
cmbStatusOrder2.ItemIndex := -1;
end;
procedure TfOrders.FormCreate(Sender: TObject);
begin
AcademicYear := nil;
OrderType := nil;
StatusOrder := nil;
Orders := nil;
end;
procedure TfOrders.FormDestroy(Sender: TObject);
begin
if Assigned(AcademicYear) then
FreeAndNil(AcademicYear);
if Assigned(OrderType) then
FreeAndNil(OrderType);
if Assigned(StatusOrder) then
FreeAndNil(StatusOrder);
if Assigned(Orders) then
FreeAndNil(Orders);
end;
procedure TfOrders.FormShow(Sender: TObject);
var
i: integer;
begin
if not Assigned(AcademicYear) then
AcademicYear := Kernel.GetAcademicYear;
with cmbAcademicYear1 do
begin
Clear;
Items.Add('Все');
for i := 0 to AcademicYear.Count - 1 do
Items.Add(AcademicYear[i].ValueStrByName('NAME'));
DropDownCount := AcademicYear.Count + 1;
for i := 0 to AcademicYear.Count - 1 do
if AcademicYear[i].ValueByName('ID') = IDCurAcademicYear then
cmbAcademicYear1.ItemIndex := i + 1;
end;
with cmbAcademicYear2 do
begin
Clear;
for i := 0 to AcademicYear.Count - 1 do
Items.Add(AcademicYear[i].ValueStrByName('NAME'));
// DropDownCount := AcademicYear.Count + 1;
DropDownCount := AcademicYear.Count; // с этой строкой ничего не меняется
// да ваще без разницы! Сво-во прописывается автоматом даже без спецустановки?
end;
if not Assigned(StatusOrder) then
StatusOrder := Kernel.GetStatusOrders(5);
with cmbStatusOrder1 do
begin
Clear;
Items.Add('Все');
for i := 0 to StatusOrder.Count - 1 do
Items.Add(StatusOrder[i].ValueStrByName('NOTE'));
DropDownCount := StatusOrder.Count + 1;
cmbStatusOrder1.ItemIndex := 0; // не комментирвать строку!
end;
with cmbStatusOrder2 do
begin
Clear;
for i := 0 to StatusOrder.Count - 1 do
Items.Add(StatusOrder[i].ValueStrByName('NOTE'));
DropDownCount := StatusOrder.Count;
// cmbStatusOrder1.ItemIndex := 0;
end;
if not Assigned(OrderType) then
OrderType := Kernel.GetOrderType;
with cmbTypeOrders1 do
begin
Clear;
Items.Add('Все');
for i := 0 to OrderType.Count - 1 do
Items.Add(OrderType[i].ValueStrByName('NAME'));
DropDownCount := OrderType.Count + 1;
cmbTypeOrders1.ItemIndex := 0; // если закоммить, то исключение лезет
end;
with cmbTypeOrders2 do
begin
Clear;
for i := 0 to OrderType.Count - 1 do
Items.Add(OrderType[i].ValueStrByName('NAME'));
DropDownCount := OrderType.Count;
// cmbTypeOrders1.ItemIndex := 0;
end;
dtpEventEnding.Date := Date;
ShowOrdersList;
end;
procedure TfOrders.lvOrdersSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
var
i: integer;
EventEnding: string;
begin
if Orders.Count > 0 then
with Orders[Item.Index] do
begin
IDOrder := ValueByName('ID');
eNumberOrder.Text := ValueByName('NAMBER_ORDER');
mCommentOrder.Text := ValueStrByName('NOTE');
dtpDateOrder.Date := ValueByName('DATE_ORDER');
dtpDateEvent.Date := ValueByName('DATE_EVENT');
EventEnding := ValueStrByName('DATE_ENDING');
if ValueStrByName('DATE_ENDING') = '' then
dtpEventEnding.Visible := false
else
begin
dtpEventEnding.Date := ValueByName('DATE_ENDING');
dtpEventEnding.Visible := true;
end;
for i := 0 to AcademicYear.Count - 1 do
if cmbAcademicYear2.Items[i] = ValueStrByName('ACADEMIC_YEAR') then
cmbAcademicYear2.ItemIndex := i;
for i := 0 to OrderType.Count - 1 do
if cmbTypeOrders2.Items[i] = ValueStrByName('TYPE_ORDER') then
cmbTypeOrders2.ItemIndex := i;
for i := 0 to StatusOrder.Count - 1 do
if cmbStatusOrder2.Items[i] = ValueStrByName('NAME_STATUS') then
cmbStatusOrder2.ItemIndex := i;
end
else
begin
DoClearOrder;
IDOrder := -1;
end;
end;
procedure TfOrders.SetIDCurAcademicYear(const Value: integer);
begin
if FIDCurAcademicYear <> Value then
FIDCurAcademicYear := Value;
end;
procedure TfOrders.ShowOrdersList;
var
in_type, academic_year, status: integer;
begin
if cmbAcademicYear1.ItemIndex = 0 then
academic_year := 0
else
academic_year := AcademicYear[cmbAcademicYear1.ItemIndex - 1]
.ValueByName('ID');
if cmbTypeOrders1.ItemIndex = 0 then
in_type := 0
else
in_type := OrderType[cmbTypeOrders1.ItemIndex - 1].ValueByName('ID');
if cmbStatusOrder1.ItemIndex = 0 then
status := 0
else
status := StatusOrder[cmbStatusOrder1.ItemIndex - 1].ValueByName('CODE');
if Assigned(Orders) then
FreeAndNil(Orders);
Orders := Kernel.GetOrders(in_type, academic_year, status);
Kernel.GetLVOrders(lvOrders, Orders);
if lvOrders.Items.Count > 0 then
lvOrders.ItemIndex := 0
else
DoClearOrder;
// else
// lvOrders.Clear;
end;
end.
|
unit view.principal;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Actions,
FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions, FMX.Objects,
FMX.Controls.Presentation, FMX.StdCtrls, System.IoUtils,
System.Permissions,
FMX.DialogService, FMX.ScrollBox, FMX.Memo
{$IFDEF Android}
, Androidapi.jni.Os,
Androidapi.jni.Support,
Androidapi.jni.GraphicsContentViewText,
Androidapi.Helpers
{$ENDIF};
type
TForm1 = class(TForm)
Image1: TImage;
btnCamera: TButton;
ActionList1: TActionList;
btnGaleria: TButton;
TakePhotoFromCameraAction1: TTakePhotoFromCameraAction;
TakePhotoFromLibraryAction1: TTakePhotoFromLibraryAction;
Memo1: TMemo;
Button1: TButton;
procedure btnCameraClick(Sender: TObject);
procedure btnGaleriaClick(Sender: TObject);
procedure TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap);
procedure TakePhotoFromLibraryAction1DidFinishTaking(Image: TBitmap);
procedure Button1Click(Sender: TObject);
private
procedure DisplayRationale(Sender: TObject;
const APermissions: TArray<string>; const APostRationaleProc: TProc);
procedure TakeCameraPermissionRequestResult(Sender: TObject;
const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
procedure TakeGaleriaPermissionRequestResult(Sender: TObject;
const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
procedure PermissionCamera;
procedure PermissionGaleria;
procedure ListarArquivos(Diretorio: string; Sub: Boolean);
function TemAtributo(Attr, Val: Integer): Boolean;
var
FPermissionCamera, FPermissionReadExternalStorage,
FPermissionWriteExternalStorage: string;
public
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.btnCameraClick(Sender: TObject);
begin
{$IF Defined(IOS)}
// atenção
TakePhotoFromCameraAction1.Editable := true;
TakePhotoFromCameraAction1.Execute;
{$ENDIF}
{$IF Defined(ANDROID)}
// atenção
TakePhotoFromCameraAction1.Editable := false;
PermissionCamera;
{$ENDIF}
end;
procedure TForm1.btnGaleriaClick(Sender: TObject);
begin
{$IF Defined(IOS)}
// atenção
TakePhotoFromLibraryAction1.Editable := true;
TakePhotoFromLibraryAction1.Execute;
{$ENDIF}
{$IF Defined(ANDROID)}
// atenção
TakePhotoFromLibraryAction1.Editable := false;
PermissionGaleria;
{$ENDIF}
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Lines.Add(TPath.GetSharedPicturesPath);
ListarArquivos(TPath.GetSharedDownloadsPath, true);
ListarArquivos(TPath.GetSharedDownloadsPath, true);
end;
procedure TForm1.TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap);
begin
Image1.Bitmap := Image;
end;
procedure TForm1.TakePhotoFromLibraryAction1DidFinishTaking(Image: TBitmap);
begin
Image1.Bitmap := Image;
end;
{$REGION 'Permission Camera'}
procedure TForm1.PermissionCamera;
begin
{$IF Defined(ANDROID)}
FPermissionCamera := JStringToString(TJManifest_permission.JavaClass.CAMERA);
FPermissionReadExternalStorage :=
JStringToString(TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE);
FPermissionWriteExternalStorage :=
JStringToString(TJManifest_permission.JavaClass.WRITE_EXTERNAL_STORAGE);
if ((TJContextCompat.JavaClass.checkSelfPermission(TAndroidHelper.Activity,
TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE) <>
TJPackageManager.JavaClass.PERMISSION_GRANTED) or
(TJContextCompat.JavaClass.checkSelfPermission(TAndroidHelper.Activity,
TJManifest_permission.JavaClass.WRITE_EXTERNAL_STORAGE) <>
TJPackageManager.JavaClass.PERMISSION_GRANTED) or
(TJContextCompat.JavaClass.checkSelfPermission(TAndroidHelper.Activity,
TJManifest_permission.JavaClass.CAMERA) <>
TJPackageManager.JavaClass.PERMISSION_GRANTED)) then
begin
PermissionsService.RequestPermissions([FPermissionReadExternalStorage,
FPermissionWriteExternalStorage, FPermissionCamera],
TakeCameraPermissionRequestResult, DisplayRationale);
end
else
TakePhotoFromCameraAction1.Execute;
{$ENDIF}
end;
procedure TForm1.TakeCameraPermissionRequestResult(Sender: TObject;
const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
begin
if (Length(AGrantResults) = 3) and
(AGrantResults[0] = TPermissionStatus.Granted) and
(AGrantResults[1] = TPermissionStatus.Granted) and
(AGrantResults[2] = TPermissionStatus.Granted) then
TakePhotoFromCameraAction1.Execute
else
TDialogService.ShowMessage
('Cannot take a photo because the required permissions are not all granted');
end;
{$ENDREGION}
{$REGION 'Permission Galeria'}
procedure TForm1.PermissionGaleria;
begin
{$IF Defined(ANDROID)}
FPermissionReadExternalStorage :=
JStringToString(TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE);
FPermissionWriteExternalStorage :=
JStringToString(TJManifest_permission.JavaClass.WRITE_EXTERNAL_STORAGE);
if ((TJContextCompat.JavaClass.checkSelfPermission(TAndroidHelper.Activity,
TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE) <>
TJPackageManager.JavaClass.PERMISSION_GRANTED) or
(TJContextCompat.JavaClass.checkSelfPermission(TAndroidHelper.Activity,
TJManifest_permission.JavaClass.WRITE_EXTERNAL_STORAGE) <>
TJPackageManager.JavaClass.PERMISSION_GRANTED)) then
begin
PermissionsService.RequestPermissions([FPermissionReadExternalStorage,
FPermissionWriteExternalStorage, FPermissionCamera],
TakeCameraPermissionRequestResult, DisplayRationale);
end
else
TakePhotoFromLibraryAction1.Execute;
{$ENDIF}
end;
procedure TForm1.TakeGaleriaPermissionRequestResult(Sender: TObject;
const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
begin
if (Length(AGrantResults) = 3) and
(AGrantResults[0] = TPermissionStatus.Granted) and
(AGrantResults[1] = TPermissionStatus.Granted) then
TakePhotoFromLibraryAction1.Execute
else
TDialogService.ShowMessage
('Cannot take a photo because the required permissions are not all granted');
end;
{$ENDREGION}
procedure TForm1.DisplayRationale(Sender: TObject;
const APermissions: TArray<string>; const APostRationaleProc: TProc);
var
I: Integer;
RationaleMsg: string;
begin
for I := 0 to High(APermissions) do
begin
if APermissions[I] = FPermissionCamera then
RationaleMsg := RationaleMsg +
'The app needs to access the camera to take a photo' + SLineBreak +
SLineBreak
else if APermissions[I] = FPermissionReadExternalStorage then
RationaleMsg := RationaleMsg +
'The app needs to read a photo file from your device';
end;
// Show an explanation to the user *asynchronously* - don't block this thread waiting for the user's response!
// After the user sees the explanation, invoke the post-rationale routine to request the permissions
TDialogService.ShowMessage(RationaleMsg,
procedure(const AResult: TModalResult)
begin
APostRationaleProc;
end);
end;
procedure TForm1.ListarArquivos(Diretorio: string; Sub: Boolean);
var
F: TSearchRec;
Ret: Integer;
TempNome: string;
s: string;
DirList: TStringDynArray;
begin
DirList := TDirectory.GetFiles(Diretorio, '*');
if Length(DirList) = 0 then
Memo1.Lines.Add('No files found in ' + Diretorio)
else // Files found. List them.
begin
for s in DirList do
Memo1.Lines.Add(s);
end;
//
// Ret := FindFirst(Diretorio + '\*.*', faAnyFile, F);
// try
// while Ret = 0 do
// begin
// if TemAtributo(F.Attr, faDirectory) then
// begin
// if (F.Name <> '.') And (F.Name <> '..') then
// if Sub = True then
// begin
// TempNome := Diretorio + '\' + F.Name;
// ListarArquivos(TempNome, True);
// end;
// end
// else
// begin
// Memo1.Lines.Add(Diretorio + '\' + F.Name);
// end;
// Ret := FindNext(F);
// end;
// finally
// begin
// FindClose(F);
// end;
// end;
end;
function TForm1.TemAtributo(Attr, Val: Integer): Boolean;
begin
Result := Attr and Val = Val;
end;
end.
|
unit HashAlg_U;
// Description: Hash Algorithm Wrapper Base Class
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Classes,
HashValue_U;
type
THashAlg = class(TComponent)
private
{ Private declarations }
protected
// These must be set in the constructor by descendant classes
fTitle: string;
fHashLength: integer;
fBlockLength: integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
// ------------------------------------------------------------------
// Main methods
//
// Most users will only need to use the following methods:
// Simple function to hash a string
function HashString(const theString: Ansistring; digest: THashValue): boolean; overload; virtual;
// Simple function to hash a file's contents
function HashFile(const filename: string; digest: THashValue): boolean; overload; virtual;
// Simple function to hash a chunk of memory
function HashMemory(const memBlock: Pointer; const len: cardinal; digest: THashValue): boolean; overload; virtual;
// Simple function to hash a stream
// Note: This will operate from the *current* *position* in the stream, right
// up to the end
function HashStream(const stream: TStream; digest: THashValue): boolean; virtual;
// Generate a prettyprinted version of the supplied hash value, using the
// conventional ASCII-hex byte order for displaying values by the hash
// algorithm.
// Note: ValueAsASCIIHex(...) can be called on hash value objects instead,
// though this will only give a non-prettyprinted version
function PrettyPrintHashValue(const theHashValue: THashValue): string; virtual;
// ------------------------------------------------------------------
// Lower level functions to incrementally generate a hash
//
// Most users probably won't need to use these
// Note: Only Init(...), Update(<with byte array>), and Final(...) should
// be implemented in descendant classes. The others will call this in
// this class.
// Usage: Call:
// Call Init(...)
// Call Update(...)
// Call Update(...)
// ... (call Update(...) repeatedly until all your data
// ... is processed)
// Call Update(...)
// Call Final(...)
procedure Init(); virtual; abstract;
procedure Update(const input: Ansistring); overload; virtual;
procedure Update(const input: array of byte; const inputLen: cardinal); overload; virtual; abstract;
// Note: This will operate from the *current* *position* in the stream
procedure Update(input: TStream; const inputLen: int64); overload; virtual;
// Note: This will operate from the *current* *position* in the stream, right
// up to the end
procedure Update(input: TStream); overload; virtual;
procedure Final(digest: THashValue); virtual; abstract;
// ------------------------------------------------------------------
// Depreciated methods
//
// The following methods are depreciated, and should not be used in new
// developments.
// Use replacement HashString(...)
function HashString(theString: string): THashArray; overload; virtual; deprecated;
// Use replacement HashMemory(...)
function HashMemory(memBlock: Pointer; len: cardinal): THashArray; overload; virtual; deprecated;
// Use replacement HashFile(...)
function HashFile(filename: string; var digest: THashArray): boolean; overload; virtual; deprecated;
// Use PrettyPrintHashValue(...)
function HashToDisplay(theHash: THashArray): string; virtual; deprecated;
// Use THashValue.ValueAsBinary property
function HashToDataString(theHash: THashArray): string; virtual; deprecated;
// Use THashValue.Clear(...)
procedure ClearHash(var theHash: THashArray); virtual; deprecated;
// Use HashLength property
function DigestSize(): integer; virtual; deprecated;
published
// Title of hash algorithm
property Title: string read fTitle;
// Length of output hashes (in bits)
property HashLength: integer read fHashLength;
// Block length (in bits)
property BlockLength: integer read fBlockLength;
end;
implementation
uses
Math,
sysutils,
SDUGeneral;
const
// This dictates the buffer size when processing streams (and files, etc)
// Relativly arbitary (as long as you've got enough memory); you may well be
// able to improve performace by increasing the size of this
// !! WARNING !!
// Increasing this can give stack overflows:
// *) When it gets to the stream handling part
// *) On the MD2 "transform" operation, with strings of about 30 chars or
// more
// the stack frame isn't big enough
// !! WARNING !!
STREAM_BUFFER_SIZE = 1024;
constructor THashAlg.Create(AOwner: TComponent);
begin
inherited;
fTitle := '<<UNDEFINED>>';
fHashLength := 0;
fBlockLength := 0;
end;
destructor THashAlg.Destroy();
begin
inherited;
end;
function THashAlg.PrettyPrintHashValue(const theHashValue: THashValue): string;
begin
// Default to the boring ASCII hex dump...
Result := theHashValue.ValueAsASCIIHex;
end;
function THashAlg.HashString(const theString: Ansistring; digest: THashValue): boolean;
var
stream: TStringStream;
begin
stream := TStringStream.Create(theString);
try
Result := HashStream(stream, digest);
finally
stream.Free();
end;
end;
function THashAlg.HashFile(const filename: string; digest: THashValue): boolean;
var
stream: TFileStream;
begin
Result := FALSE;
try
stream := TFileStream.Create(filename, fmOpenRead OR fmShareDenyWrite);
try
Result := HashStream(stream, digest);
finally
stream.Free();
end;
except
// Nothing - Result already = FALSE
end;
end;
function THashAlg.HashMemory(const memBlock: Pointer; const len: cardinal; digest: THashValue): boolean;
var
stream: TMemoryStream;
begin
Result := FALSE;
try
stream := TMemoryStream.Create();
try
stream.SetSize(len);
stream.Write(memBlock, len);
Result := HashStream(stream, digest);
finally
stream.Free();
end;
except
// Nothing - Result already = FALSE
end;
end;
function THashAlg.HashStream(const stream: TStream; digest: THashValue): boolean;
begin
Result := FALSE;
try
Init();
Update(stream);
Final(digest);
Result := TRUE;
except
// Nothing - Result already = FALSE
end;
end;
procedure THashAlg.Update(const input: Ansistring);
var
buffer: array of byte;
i: integer;
begin
SetLength(buffer, length(input));
for i:=1 to length(input) do
begin
buffer[i-1] := byte(input[i]);
end;
Update(buffer, length(input))
end;
procedure THashAlg.Update(input: TStream; const inputLen: int64);
var
buffer: array [0..(STREAM_BUFFER_SIZE-1)] of byte;
len: integer;
totalRead: int64;
begin
len := input.Read(buffer, min(sizeof(buffer), inputLen));
totalRead := len;
while (len>0) do
begin
Update(buffer, len);
// Cast to int64 to prevent Delphi casting to integer
len := input.Read(buffer, min(sizeof(buffer), (inputLen-totalRead)));
inc(totalRead, int64(len));
end;
end;
procedure THashAlg.Update(input: TStream);
begin
Update(input, (input.Size - input.Position));
end;
// -- begin depreciated methods --
// WARNING: Depreciated method
// This method is depreciated and should not be used in new
// developments
// This method may be removed at a later date
// Replaced by: HashString(...), taking a THashValue
function THashAlg.HashString(theString: string): THashArray;
var
hashValue: THashValue;
begin
hashValue:= THashValue.Create();
try
HashString(theString, hashValue);
Result := hashValue.GetValueAsArray();
finally
hashValue.Free();
end;
end;
// WARNING: Depreciated method
// This method is depreciated and should not be used in new
// developments
// This method may be removed at a later date
// Replaced by: HashMemory(...), taking a THashValue
function THashAlg.HashMemory(memBlock: Pointer; len: cardinal): THashArray;
var
hashValue: THashValue;
begin
hashValue:= THashValue.Create();
try
HashMemory(memBlock, len, hashValue);
Result := hashValue.GetValueAsArray();
finally
hashValue.Free();
end;
end;
// WARNING: Depreciated method
// This method is depreciated and should not be used in new
// developments
// This method may be removed at a later date
// Replaced by: HashFile(...), taking a THashValue
function THashAlg.HashFile(filename: string; var digest: THashArray): boolean;
var
hashValue: THashValue;
begin
Result := FALSE;
hashValue:= THashValue.Create();
try
if HashFile(filename, hashValue) then
begin
digest := hashValue.GetValueAsArray;
Result := TRUE;
end;
finally
hashValue.Free();
end;
end;
// WARNING: Depreciated method
// This method is depreciated and should not be used in new
// developments
// This method may be removed at a later date
// Replaced by: PrettyPrintHashValue(...)
function THashAlg.HashToDisplay(theHash: THashArray): string;
var
hashValue: THashValue;
begin
hashValue:= THashValue.Create();
try
hashValue.SetValueAsArray(theHash, HashLength);
Result := PrettyPrintHashValue(HashValue);
finally
hashValue.Free();
end;
end;
// WARNING: Depreciated method
// This method is depreciated and should not be used in new
// developments
// This method may be removed at a later date
// Replaced by: The appropriate method on THashValue
function THashAlg.HashToDataString(theHash: THashArray): string;
var
hashValue: THashValue;
begin
hashValue:= THashValue.Create();
try
hashValue.SetValueAsArray(theHash, HashLength);
Result := hashValue.ValueAsBinary;
finally
hashValue.Free();
end;
end;
// WARNING: Depreciated method
// This method is depreciated and should not be used in new
// developments
// This method may be removed at a later date
// Replaced by: Clear(...) on THashValue
procedure THashAlg.ClearHash(var theHash: THashArray);
var
i: integer;
begin
for i:=low(theHash) to high(theHash) do
begin
theHash[i] := 0;
end;
end;
// WARNING: Depreciated method
// This method is depreciated and should not be used in new
// developments
// This method may be removed at a later date
// Replaced by: HashLength property
function THashAlg.DigestSize(): integer;
begin
Result := HashLength;
end;
// -- end depreciated methods --
END.
|
unit uAutorLivroModel;
interface
uses uGenericEntity, uCustomAttributesEntity, uAutorModel, uLivroModel;
type
[TableName('autor_livro')]
TAutorLivroModel = class(TGenericEntity)
private
FAutor: TAutorModel;
FCodigo: Integer;
FLivro: TLivroModel;
procedure SetAutor(const Value: TAutorModel);
procedure SetCodigo(const Value: Integer);
procedure SetLivro(const Value: TLivroModel);
public
[KeyField('codigo')]
[FieldName('codigo')]
property Codigo: Integer read FCodigo write SetCodigo;
[FieldName('autor_codigo')]
[ForeignKey('autor_codigo', 'codigo', 'autor')]
property Autor: TAutorModel read FAutor write SetAutor;
[FieldName('livro_codigo')]
[ForeignKey('livro_codigo', 'codigo', 'livro')]
property Livro: TLivroModel read FLivro write SetLivro;
function ToString(): String; override;
end;
implementation
uses SysUtils;
{ TAutorLivroModel }
procedure TAutorLivroModel.SetAutor(const Value: TAutorModel);
begin
FAutor := Value;
end;
procedure TAutorLivroModel.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TAutorLivroModel.SetLivro(const Value: TLivroModel);
begin
FLivro := Value;
end;
function TAutorLivroModel.ToString: String;
begin
Result := Self.FCodigo.ToString + ' - ' +
'Autor: ' + Self.FAutor.ToString + ' ' +
'Livro: ' + Self.FLivro.ToString;
end;
end.
|
unit frmJournalPedagogueByIndividualGroupChild;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.ComCtrls, dbfunc, uKernel,
DateUtils, Vcl.Buttons;
type
TfJournalPedagogueByIndividualGroupChild = class(TForm)
Panel3: TPanel;
pPedagogue_: TPanel;
pGroup_: TPanel;
lvIndividualJournal: TListView;
Button4: TButton;
Panel4: TPanel;
Button1: TButton;
Button2: TButton;
Panel5: TPanel;
cmbStatusLesson: TComboBox;
mThemeComment: TMemo;
Label1: TLabel;
Label2: TLabel;
eNumberTheme: TEdit;
Label3: TLabel;
Label4: TLabel;
bChangeTheme: TButton;
bSave: TButton;
pTimesheet_: TPanel;
cbMonth: TComboBox;
eDateLesson: TEdit;
PageControl1: TPageControl;
TSh_9: TTabSheet;
TSh_10: TTabSheet;
TSh_11: TTabSheet;
TSh_12: TTabSheet;
TSh_1: TTabSheet;
TSh_2: TTabSheet;
TSh_3: TTabSheet;
TSh_4: TTabSheet;
TSh_5: TTabSheet;
sbDisplacement: TSpeedButton;
cmbPedagogue: TComboBox;
bSaveDisplacement: TBitBtn;
sbDelete: TSpeedButton;
bDelete: TButton;
procedure Button2Click(Sender: TObject);
procedure bChangeThemeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbMonthChange(Sender: TObject);
procedure lvIndividualJournalSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure bSaveClick(Sender: TObject);
procedure PageControl1Change(Sender: TObject);
procedure sbDisplacementClick(Sender: TObject);
procedure bSaveDisplacementClick(Sender: TObject);
procedure bDeleteClick(Sender: TObject);
procedure sbDeleteClick(Sender: TObject);
private
LessonStatus: TResultTable;
IndividualPage: TResultTable; // лишняя, не использую, зачем задумала?))
TimesheetForGroup: TResultTable;
IndividualJournal: TResultTable;
PedagogueSurnameNP: TResultTable;
FIDPedagogue: integer;
FStrPedagogue: string;
FIDAcademicYear: integer;
FStrAcademicYear: string;
FIDLearningGroup: integer;
FMonth: integer;
FStrLGName: string;
FStrEducationProgram: string;
FStrLearningLevel: string;
FWeekCountHour: integer;
IDlesson: integer;
in_status: integer;
in_themes_number, in_theme_note: string;
procedure SetIDPedagogue(const Value: integer);
procedure SetStrPedagogue(const Value: string);
procedure SetIDAcademicYear(const Value: integer);
procedure SetStrAcademicYear(const Value: string);
procedure SetIDLearningGroup(const Value: integer);
procedure SetMonth(const Value: integer);
procedure SetStrLGName(const Value: string);
procedure SetStrEducationProgram(const Value: string);
procedure SetStrLearningLevel(const Value: string);
procedure SetWeekCountHour(const Value: integer);
procedure ShowIndividualJournal(const IDLearningGroup, Month: integer);
public
property StrPedagogue: string read FStrPedagogue write SetStrPedagogue;
property IDPedagogue: integer read FIDPedagogue write SetIDPedagogue;
property StrAcademicYear: string read FStrAcademicYear
write SetStrAcademicYear;
property IDAcademicYear: integer read FIDAcademicYear
write SetIDAcademicYear;
property IDLearningGroup: integer read FIDLearningGroup
write SetIDLearningGroup;
property Month: integer read FMonth write SetMonth;
property StrLGName: string read FStrLGName write SetStrLGName;
property StrEducationProgram: string read FStrEducationProgram
write SetStrEducationProgram;
property StrLearningLevel: string read FStrLearningLevel
write SetStrLearningLevel;
property WeekCountHour: integer read FWeekCountHour write SetWeekCountHour;
end;
var
fJournalPedagogueByIndividualGroupChild
: TfJournalPedagogueByIndividualGroupChild;
implementation
{$R *.dfm}
// Расписание: пн. 13.00-19.00, ср. 8.00-20.00, приказ №... от ...(NUMBER_DATE), изм. расп.....
// добавить кнопки смены месяца
// пока не готовы КТП нужно будет только заполнить lv с расписанием
// и обработать кнопку "открыть журнал"
procedure TfJournalPedagogueByIndividualGroupChild.bSaveClick(Sender: TObject);
begin
in_status := LessonStatus[cmbStatusLesson.ItemIndex].ValueByName('CODE');
in_themes_number := eNumberTheme.Text;
in_theme_note := mThemeComment.Text;
if Kernel.UpdateJournal([IDlesson, in_status, in_themes_number, in_theme_note])
then
begin
// ShowMessage('Сохранение выполнено!');
end
else
begin
ShowMessage('Ошибка при сохранении!');
// Close;
end;
ShowIndividualJournal(IDLearningGroup, Month);
end;
procedure TfJournalPedagogueByIndividualGroupChild.bSaveDisplacementClick
(Sender: TObject);
var
i, s: integer;
begin
// производить проверу, чтобы педагог не замещад сам себя
s := 0;
for i := 0 to lvIndividualJournal.Items.Count - 1 do
begin
if lvIndividualJournal.Items[i].Checked then
s := s + 1;
end;
if s = 0 then
begin
ShowMessage('Выберите записи для редактирования!');
Exit;
end;
for i := 0 to lvIndividualJournal.Items.Count - 1 do
begin
if lvIndividualJournal.Items[i].Checked then
begin
IDlesson := IndividualJournal[i].ValueByName('ID_OUT');
in_status := 1;
in_themes_number := IndividualJournal[i].ValueStrByName('NUMBER_THEME');
in_theme_note := IndividualJournal[i].ValueStrByName('NOTE_THEME') +
' Замещение: ' + PedagogueSurnameNP[cmbPedagogue.ItemIndex]
.ValueStrByName('SURNAMENP');
if Kernel.UpdateJournal([IDlesson, in_status, in_themes_number,
in_theme_note]) then
begin
// ShowMessage('Сохранение выполнено!');
end
else
begin
ShowMessage('Ошибка при сохранении!');
end;
end;
end;
ShowIndividualJournal(IDLearningGroup, Month);
end;
procedure TfJournalPedagogueByIndividualGroupChild.Button2Click
(Sender: TObject);
begin
// тута будет прописано заполнение КТП автоматом - для всех записей
end;
procedure TfJournalPedagogueByIndividualGroupChild.bDeleteClick(
Sender: TObject);
begin
// удалить запись из журнала - ошибка в расписании может привести к необходимости делат это
end;
procedure TfJournalPedagogueByIndividualGroupChild.bChangeThemeClick
(Sender: TObject);
begin
// заполним тему КТП вручную (редактируем одну тему)
end;
procedure TfJournalPedagogueByIndividualGroupChild.cbMonthChange
(Sender: TObject);
begin
if cbMonth.ItemIndex <= 3 then
Month := cbMonth.ItemIndex + 9
else
Month := cbMonth.ItemIndex - 3;
ShowIndividualJournal(IDLearningGroup, Month);
PageControl1.ActivePageIndex := cbMonth.ItemIndex;
end;
procedure TfJournalPedagogueByIndividualGroupChild.FormCreate(Sender: TObject);
begin
LessonStatus := nil;
IndividualPage := nil;
TimesheetForGroup := nil;
IndividualJournal := nil;
PedagogueSurnameNP := nil;
end;
procedure TfJournalPedagogueByIndividualGroupChild.FormDestroy(Sender: TObject);
begin
if Assigned(LessonStatus) then
FreeAndNil(LessonStatus);
if Assigned(IndividualPage) then
FreeAndNil(IndividualPage);
if Assigned(TimesheetForGroup) then
FreeAndNil(TimesheetForGroup);
if Assigned(IndividualJournal) then
FreeAndNil(IndividualJournal);
if Assigned(PedagogueSurnameNP) then
FreeAndNil(PedagogueSurnameNP);
end;
procedure TfJournalPedagogueByIndividualGroupChild.FormShow(Sender: TObject);
var
weekday, time, date_beginig, order: string;
i, ii: integer;
begin
// подумать, что делать с летними месяцами, если месяц будет определяться автоматом
pPedagogue_.Caption := 'Педагог: ' + StrPedagogue + ', ' + StrAcademicYear +
' учебный год, ' +
// получение месяца строкой из текущей даты:
// Kernel.MonthStr(MonthOf(Date)) + '.';
Kernel.MonthStr(Month);
pGroup_.Caption := 'Группа/учащийся: ' + StrLGName + ' Программа: ' +
StrEducationProgram + ', уровень: ' + StrLearningLevel;
if not Assigned(TimesheetForGroup) then
TimesheetForGroup := Kernel.GetTimesheetForGroup(IDLearningGroup,
IDAcademicYear);
pTimesheet_.Caption := 'Расписание: ';
// сделать еще проверку количество строк на кратность количеству уроков в неделю,
// иначе будет исключение, означающее, что расписание для данной группы составлено не полностью
if TimesheetForGroup.Count > 0 then
try
for i := 0 to WeekCountHour - 1 do
begin
weekday := TimesheetForGroup[i].ValueStrByName('WEEK_DAY');
time := TimesheetForGroup[i].ValueStrByName('LESSON_BEGIN_END');
pTimesheet_.Caption := pTimesheet_.Caption + weekday + ' ' + time + ' ';
end;
if TimesheetForGroup.Count > WeekCountHour then
begin
for ii := 0 to round(TimesheetForGroup.Count / WeekCountHour) - 2 do
begin
date_beginig := TimesheetForGroup[1 + WeekCountHour * ii]
.ValueStrByName('DATE_BEGINING');
order := TimesheetForGroup[1 + WeekCountHour * ii].ValueStrByName
('NUMBER_DATE_ORDER');
pTimesheet_.Caption := pTimesheet_.Caption + 'Изм. расп. с ' +
date_beginig + ' ' + order + ' ';
for i := 1 to WeekCountHour do
begin
weekday := TimesheetForGroup[i + WeekCountHour * ii].ValueStrByName
('WEEK_DAY');
time := TimesheetForGroup[i + WeekCountHour * ii].ValueStrByName
('LESSON_BEGIN_END');
pTimesheet_.Caption := pTimesheet_.Caption + weekday + ' ' +
time + ' ';
end;
end;
end;
except
on EArgumentOutOfRangeException do
ShowMessage('Ошибка! Проверьте расписание!' + #13#10 +
'Количество уроков в неделю должно соответствовать программе');
end;
if not Assigned(LessonStatus) then
LessonStatus := Kernel.GetLessonStatus(7);
Kernel.FillingComboBox(cmbStatusLesson, LessonStatus, 'NOTE', false);
ShowIndividualJournal(IDLearningGroup, Month);
if Month >= 9 then
begin
cbMonth.ItemIndex := Month - 9;
PageControl1.ActivePageIndex := Month - 9;
end
else if Month <= 5 then
begin
cbMonth.ItemIndex := Month + 3;
PageControl1.ActivePageIndex := Month + 3;
end;
// else
// cbMonth.ItemIndex := 8;
eDateLesson.Enabled := false;
if not Assigned(PedagogueSurnameNP) then
PedagogueSurnameNP := Kernel.GetPedagogueSurnameNP;
Kernel.FillingComboBox(cmbPedagogue, PedagogueSurnameNP, 'SurnameNP', false);
cmbPedagogue.ItemIndex := 0;
end;
procedure TfJournalPedagogueByIndividualGroupChild.lvIndividualJournalSelectItem
(Sender: TObject; Item: TListItem; Selected: Boolean);
var
i: integer;
EventEnding: string;
begin
if IndividualJournal.Count > 0 then
with IndividualJournal[Item.Index] do
begin
IDlesson := ValueByName('ID_OUT');
eDateLesson.Text := ValueByName('LESSON_DATE');
eNumberTheme.Text := ValueStrByName('NUMBER_THEME');
Kernel.ChooseComboBoxItemIndex(cmbStatusLesson, LessonStatus, true,
'CODE', ValueByName('LESSON_STATUS'));
// Kernel.ChooseComboBoxItemIndex(cmbPedagogue, PedagogueSurnameNP, true,
// 'ID_OUT', IDPedagogue);
mThemeComment.Text := ValueStrByName('NOTE_THEME');
// if ValueStrByName('DATE_ENDING') = '' then
// dtpEventEnding.Visible := false
// else
// begin
// dtpEventEnding.Date := ValueByName('DATE_ENDING');
// dtpEventEnding.Visible := true;
// end;
// for i := 0 to AcademicYear.Count - 1 do
// if cmbAcademicYear2.Items[i] = ValueStrByName('ACADEMIC_YEAR') then
// cmbAcademicYear2.ItemIndex := i;
// for i := 0 to OrderType.Count - 1 do
// if cmbTypeOrders2.Items[i] = ValueStrByName('TYPE_ORDER') then
// cmbTypeOrders2.ItemIndex := i;
// for i := 0 to StatusOrder.Count - 1 do
// if cmbStatusOrder2.Items[i] = ValueStrByName('NAME_STATUS') then
// cmbStatusOrder2.ItemIndex := i;
bSave.Enabled := true;
bChangeTheme.Enabled := true;
end
else
begin
// DoClearOrder;
bSave.Enabled := false;
bChangeTheme.Enabled := false;
end;
end;
procedure TfJournalPedagogueByIndividualGroupChild.PageControl1Change
(Sender: TObject);
begin
if PageControl1.ActivePageIndex <= 3 then
Month := PageControl1.ActivePageIndex + 9
else
Month := PageControl1.ActivePageIndex - 3;
ShowIndividualJournal(IDLearningGroup, Month);
cbMonth.ItemIndex := PageControl1.ActivePageIndex;
end;
procedure TfJournalPedagogueByIndividualGroupChild.SetIDAcademicYear
(const Value: integer);
begin
if FIDAcademicYear <> Value then
FIDAcademicYear := Value;
end;
procedure TfJournalPedagogueByIndividualGroupChild.SetIDLearningGroup
(const Value: integer);
begin
if FIDLearningGroup <> Value then
FIDLearningGroup := Value;
end;
procedure TfJournalPedagogueByIndividualGroupChild.SetIDPedagogue
(const Value: integer);
begin
if FIDPedagogue <> Value then
FIDPedagogue := Value;
end;
procedure TfJournalPedagogueByIndividualGroupChild.SetMonth
(const Value: integer);
begin
if FMonth <> Value then
FMonth := Value;
end;
procedure TfJournalPedagogueByIndividualGroupChild.SetStrAcademicYear
(const Value: string);
begin
if FStrAcademicYear <> Value then
FStrAcademicYear := Value;
end;
procedure TfJournalPedagogueByIndividualGroupChild.SetStrEducationProgram
(const Value: string);
begin
if FStrEducationProgram <> Value then
FStrEducationProgram := Value;
end;
procedure TfJournalPedagogueByIndividualGroupChild.SetStrLearningLevel
(const Value: string);
begin
if FStrLearningLevel <> Value then
FStrLearningLevel := Value;
end;
procedure TfJournalPedagogueByIndividualGroupChild.SetStrLGName
(const Value: string);
begin
if FStrLGName <> Value then
FStrLGName := Value;
end;
procedure TfJournalPedagogueByIndividualGroupChild.SetStrPedagogue
(const Value: string);
begin
if FStrPedagogue <> Value then
FStrPedagogue := Value;
end;
procedure TfJournalPedagogueByIndividualGroupChild.SetWeekCountHour
(const Value: integer);
begin
if FWeekCountHour <> Value then
FWeekCountHour := Value;
end;
procedure TfJournalPedagogueByIndividualGroupChild.ShowIndividualJournal
(const IDLearningGroup, Month: integer);
begin
if Assigned(IndividualJournal) then
FreeAndNil(IndividualJournal);
IndividualJournal := Kernel.GetIndividualJournal(IDLearningGroup, Month);
Kernel.GetLVIndividualJournal(lvIndividualJournal, IndividualJournal);
if lvIndividualJournal.Items.Count > 0 then
lvIndividualJournal.ItemIndex := 0;
end;
procedure TfJournalPedagogueByIndividualGroupChild.sbDeleteClick(
Sender: TObject);
begin
if sbDelete.Down = false then
begin
sbDelete.Caption := 'Выбрать и удалить';
bDelete.Caption := 'Удалить записи';
lvIndividualJournal.Checkboxes := false;
end
else
begin
sbDelete.Caption := 'Отменить выбор';
bDelete.Caption := 'Удалить запись';
lvIndividualJournal.Checkboxes := true;
// bSaveDisplacement.Visible := true;
end;
end;
procedure TfJournalPedagogueByIndividualGroupChild.sbDisplacementClick
(Sender: TObject);
begin
if sbDisplacement.Down = false then
begin
sbDisplacement.Caption := 'Заполнить замещение';
lvIndividualJournal.Checkboxes := false;
cmbPedagogue.Visible := false;
bSaveDisplacement.Visible := false;
end
else
begin
sbDisplacement.Caption := 'Обычный режим';
lvIndividualJournal.Checkboxes := true;
cmbPedagogue.Visible := true;
bSaveDisplacement.Visible := true;
end;
end;
end.
|
{*****************************************************************}
{ ceosmessages 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 ceosmessages;
{$mode objfpc}{$H+}
interface
resourcestring
ERROR_INTERNAL_ERROR = 'Internal error.';
ERROR_REQUEST_ERROR = 'Request error.';
ERROR_UNKNOW_FUNCTION = 'Unknown function.';
ERROR_REQUEST_CONTENT = 'Request Content Error.';
ERROR_INVALID_CONTENT = 'Invalid Content.';
ERROR_INVALID_QUERY = 'Invalid Query.';
MSG_NO_RESPONSE = 'No response assigned in server.';
implementation
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.Package.Metadata;
interface
uses
Spring.Collections,
JsonDataObjects,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Package.Interfaces,
DPM.Core.Dependency.Version,
DPM.Core.Spec.Interfaces;
type
TPackageId = class(TInterfacedObject, IPackageId)
private
FCompilerVersion : TCompilerVersion;
FId : string;
FPlatform : TDPMPlatform;
FVersion : TPackageVersion;
protected
function GetCompilerVersion : TCompilerVersion;
function GetId : string;
function GetPlatform : TDPMPlatform;
function GetVersion : TPackageVersion;
function ToIdVersionString : string; virtual;
public
constructor Create(const id : string; const version : TPackageVersion; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform); overload; virtual;
function ToString : string; override;
end;
TPackageIdentity = class(TPackageId, IPackageIdentity, IPackageId)
private
FSourceName : string;
protected
function GetSourceName : string;
constructor Create(const sourceName : string; const spec : IPackageSpec); overload; virtual;
constructor Create(const sourceName : string; const jsonObj : TJsonObject);overload;virtual;
public
constructor Create(const sourceName : string; const id : string; const version : TPackageVersion; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform); overload; virtual;
class function TryCreateFromString(const logger : ILogger; const value : string; const source : string; out packageIdentity : IPackageIdentity) : boolean;
class function CreateFromSpec(const sourceName : string; const spec : IPackageSpec) : IPackageIdentity;
class function TryLoadFromJson(const logger : ILogger; const jsonObj : TJsonObject; const source : string; out packageIdentity : IPackageIdentity) : boolean;
end;
TPackageInfo = class(TPackageIdentity, IPackageInfo, IPackageIdentity, IPackageId)
private
FDependencies : IList<IPackageDependency>;
FUseSource : boolean;
protected
function GetDependencies : IList<IPackageDependency>;
function GetUseSource : boolean;
procedure SetUseSource(const value : boolean);
constructor Create(const sourceName : string; const spec : IPackageSpec); override;
constructor Create(const sourceName : string; const jsonObj : TJsonObject);override;
public
class function CreateFromSpec(const sourceName : string; const spec : IPackageSpec) : IPackageInfo;
class function TryLoadFromJson(const logger : ILogger; const jsonObj : TJsonObject; const source : string; out packageInfo : IPackageInfo) : boolean;
end;
TPackageMetadata = class(TPackageInfo, IPackageMetadata, IPackageInfo, IPackageIdentity, IPackageId)
private
FAuthors : string;
FCopyright : string;
FDescription : string;
FIcon : string;
FIsCommercial : Boolean;
FIsTrial : Boolean;
FLicense : string;
FTags : string;
FSearchPaths : IList<string>;
FProjectUrl : string;
FRepositoryUrl : string;
FRepositoryType : string;
FRepositoryBranch : string;
FRepositoryCommit : string;
protected
function GetAuthors : string;
function GetCopyright : string;
function GetDescription : string;
function GetIcon : string;
function GetIsCommercial : Boolean;
function GetIsTrial : Boolean;
function GetLicense : string;
function GetTags : string;
function GetSearchPaths : IList<string>;
function GetProjectUrl : string;
function GetRepositoryUrl: string;
function GetRepositoryType : string;
function GetRepositoryBranch : string;
function GetRepositoryCommit : string;
constructor Create(const sourceName : string; const spec : IPackageSpec); override;
public
constructor Create(const sourceName : string; const jsonObj : TJsonObject); override;
class function CreateFromSpec(const sourceName : string; const spec : IPackageSpec) : IPackageMetadata;
class function TryLoadFromJson(const logger : ILogger; const jsonObj : TJsonObject; const source : string; out packageMetadata : IPackageMetadata) : boolean;
end;
TPackageMetadataExtractor = class
public
//these will read the manifest
class function TryExtractFull(const logger : ILogger; const fileName : string; out metadata : IPackageMetadata; const source : string = '') : boolean;
class function TryExtractInfo(const logger : ILogger; const fileName : string; out info : IPackageInfo; const source : string = '') : boolean;
//this just parses the filename
class function TryExtractIdentity(const logger : ILogger; const fileName : string; out identity : IPackageIdentity; const source : string = '') : boolean;
end;
// TPackageMetadataComparer = class
implementation
uses
DPM.Core.Constants,
DPM.Core.Spec.Reader,
DPM.Core.Package.Dependency,
System.SysUtils,
System.RegularExpressions,
System.Zip,
System.Classes;
{ TPackageMetadata }
constructor TPackageIdentity.Create(const sourceName: string; const jsonObj: TJsonObject);
var
id : string;
stmp : string;
cv : TCompilerVersion;
platform : TDPMPlatform;
packageVersion : TPackageVersion;
begin
id := jsonObj.S['id'];
stmp := jsonObj.S['compiler'];
cv := StringToCompilerVersion(stmp);
if cv = TCompilerVersion.UnknownVersion then
raise Exception.Create('Compiler segment is not a valid version [' + stmp+ ']');
stmp := jsonObj.S['platform'];
platform := StringToDPMPlatform(stmp);
if platform = TDPMPlatform.UnknownPlatform then
raise Exception.Create('Platform is not a valid platform [' + stmp+ ']');
stmp := jsonObj.S['version'];
if not TPackageVersion.TryParse(stmp, packageVersion) then
raise Exception.Create('Version is not a valid version [' + stmp + ']');
inherited Create(id, packageVersion, cv, platform);
FSourceName := sourceName;
end;
constructor TPackageIdentity.Create(const sourceName : string; const id: string; const version: TPackageVersion; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform);
begin
inherited Create(id, version, compilerVersion, platform);
FSourceName := sourceName;
end;
class function TPackageIdentity.CreateFromSpec(const sourceName : string; const spec : IPackageSpec) : IPackageIdentity;
begin
result := TPackageIdentity.Create(sourceName, spec);
end;
constructor TPackageIdentity.Create(const sourceName : string; const spec : IPackageSpec);
begin
inherited Create(spec.MetaData.Id, spec.MetaData.Version, spec.TargetPlatform.Compiler, spec.TargetPlatform.Platforms[0]);
FSourceName := sourceName;
end;
function TPackageIdentity.GetSourceName : string;
begin
result := FSourceName;
end;
class function TPackageIdentity.TryLoadFromJson(const logger : ILogger; const jsonObj : TJsonObject; const source : string; out packageIdentity : IPackageIdentity) : boolean;
begin
result := false;
try
packageIdentity := TPackageIdentity.Create(source, jsonObj);
except
on e : Exception do
begin
logger.Error(e.Message);
exit
end;
end;
result := true;
end;
class function TPackageIdentity.TryCreateFromString(const logger : ILogger; const value : string; const source : string; out packageIdentity : IPackageIdentity) : boolean;
var
match : TMatch;
id : string;
cv : TCompilerVersion;
platform : TDPMPlatform;
packageVersion : TPackageVersion;
begin
result := false;
match := TRegEx.Match(value, cPackageFileRegex, [roIgnoreCase]);
if not match.Success then
begin
logger.Error('Package name is not a valid package [' + value + ']');
exit;
end;
id := match.Groups[1].Value;
cv := StringToCompilerVersion(match.Groups[2].Value);
if cv = TCompilerVersion.UnknownVersion then
begin
logger.Error('Compiler version segment is not a valid version [' + match.Groups[2].Value + ']');
exit;
end;
platform := StringToDPMPlatform(match.Groups[3].Value);
if platform = TDPMPlatform.UnknownPlatform then
begin
logger.Error('Platform segment is not a valid platform [' + match.Groups[3].Value + ']');
exit;
end;
if not TPackageVersion.TryParse(match.Groups[4].Value, packageVersion) then
begin
logger.Error('Version segment is not a valid version [' + match.Groups[4].Value + ']');
exit;
end;
packageIdentity := TPackageIdentity.Create(source, id, packageVersion, cv, platform);
result := true;
end;
{ TPackageMetaDataWithDependencies }
constructor TPackageInfo.Create(const sourceName : string; const spec : IPackageSpec);
var
dep : ISpecDependency;
newDep : IPackageDependency;
begin
inherited Create(sourceName, spec);
FDependencies := TCollections.CreateList<IPackageDependency>;
for dep in spec.TargetPlatform.Dependencies do
begin
newDep := TPackageDependency.Create(dep.Id, dep.Version, FPlatform);
FDependencies.Add(newDep);
end;
end;
constructor TPackageInfo.Create(const sourceName: string; const jsonObj: TJsonObject);
var
depArr : TJsonArray;
depId : string;
depVersion : string;
i: Integer;
range : TVersionRange;
dependency : IPackageDependency;
begin
inherited Create(sourceName, jsonObj);
FDependencies := TCollections.CreateList<IPackageDependency>;
//check for isnull is needed due to jd barfing on nulls
if jsonObj.Contains('dependencies') and (not jsonObj.IsNull('dependencies')) then
begin
depArr := jsonObj.A['dependencies'];
for i := 0 to depArr.Count -1 do
begin
depId := depArr.O[i].S['packageId'];
depVersion := depArr.O[i].S['versionRange'];
if TVersionRange.TryParse(depVersion, range) then
begin
dependency := TPackageDependency.Create(depId, range, FPlatform);
FDependencies.Add(dependency);
end;
end;
end;
end;
class function TPackageInfo.CreateFromSpec(const sourceName : string; const spec : IPackageSpec) : IPackageInfo;
begin
result := TPackageInfo.Create(sourceName, spec);
end;
function TPackageInfo.GetDependencies : IList<IPackageDependency>;
begin
result := FDependencies;
end;
function TPackageInfo.GetUseSource: boolean;
begin
result := FUseSource;
end;
procedure TPackageInfo.SetUseSource(const value: boolean);
begin
FUseSource := value;
end;
class function TPackageInfo.TryLoadFromJson(const logger: ILogger; const jsonObj: TJsonObject; const source: string; out packageInfo: IPackageInfo): boolean;
begin
result := false;
try
packageInfo := TPackageInfo.Create(source, jsonObj);
except
on e : Exception do
begin
logger.Error(e.Message);
exit;
end;
end;
result := true;
end;
{ TPackageMetadataFull }
constructor TPackageMetadata.Create(const sourceName : string; const spec : IPackageSpec);
var
specSearchPath : ISpecSearchPath;
begin
inherited Create(sourceName, spec);
FSearchPaths := TCollections.CreateList<string>;
FAuthors := spec.MetaData.Authors;
FCopyright := spec.MetaData.Copyright;
FDescription := spec.MetaData.Description;
FIcon := spec.MetaData.Icon;
FIsCommercial := spec.MetaData.IsCommercial;
FIsTrial := spec.MetaData.IsTrial;
FLicense := spec.MetaData.License;
FProjectUrl := spec.MetaData.ProjectUrl;
FTags := spec.MetaData.Tags;
FProjectUrl := spec.MetaData.ProjectUrl;
FRepositoryUrl := spec.MetaData.RepositoryUrl;
FRepositoryType := spec.MetaData.RepositoryType;
FRepositoryBranch := spec.MetaData.RepositoryBranch;
FRepositoryCommit := spec.MetaData.RepositoryCommit;
for specSearchPath in spec.TargetPlatform.SearchPaths do
FSearchPaths.Add(specSearchPath.Path);
end;
constructor TPackageMetadata.Create(const sourceName: string; const jsonObj: TJsonObject);
var
searchPaths : string;
sList : TStringList;
i: Integer;
begin
inherited Create(sourceName, jsonObj);
FSearchPaths := TCollections.CreateList<string>;
FAuthors := jsonObj.S['authors'];;
FCopyright := jsonObj.S['copyright'];
FDescription := jsonObj.S['description'];
FIcon := jsonObj.S['icon'];
FIsCommercial := jsonObj.B['isCommercial'];
FIsTrial := jsonObj.B['isTrial'];
FLicense := jsonObj.S['License'];
FProjectUrl := jsonObj.S['ProjectUrl'];
FTags := jsonObj.S['Tags'];
FProjectUrl := jsonObj.S['ProjectUrl'];
FRepositoryUrl := jsonObj.S['RepositoryUrl'];
FRepositoryType := jsonObj.S['RepositoryType'];
FRepositoryBranch := jsonObj.S['RepositoryBranch'];
FRepositoryCommit := jsonObj.S['RepositoryCommit'];
FRepositoryCommit := jsonObj.S['RepositoryCommit'];
searchPaths := jsonObj.S['searchPaths'];
if searchPaths <> '' then
begin
sList := TStringList.Create;
try
sList.Delimiter := ';';
sList.DelimitedText := searchPaths;
for i := 0 to sList.Count -1 do
FSearchPaths.Add(sList.Strings[i]);
finally
sList.Free;
end;
end;
end;
class function TPackageMetadata.CreateFromSpec(const sourceName : string; const spec : IPackageSpec) : IPackageMetadata;
begin
result := TPackageMetadata.Create(sourceName, spec);
end;
function TPackageMetadata.GetAuthors : string;
begin
result := FAuthors;
end;
function TPackageMetadata.GetCopyright : string;
begin
result := FCopyright;
end;
function TPackageMetadata.GetDescription : string;
begin
result := FDescription;
end;
function TPackageMetadata.GetIcon : string;
begin
result := FIcon;
end;
function TPackageMetadata.GetIsCommercial : Boolean;
begin
result := FIsCommercial;
end;
function TPackageMetadata.GetIsTrial : Boolean;
begin
result := FIsTrial;
end;
function TPackageMetadata.GetLicense : string;
begin
result := FLicense;
end;
function TPackageMetadata.GetProjectUrl: string;
begin
result := FProjectUrl;
end;
function TPackageMetadata.GetRepositoryBranch: string;
begin
result := FRepositoryBranch;
end;
function TPackageMetadata.GetRepositoryCommit: string;
begin
result := FRepositoryCommit;
end;
function TPackageMetadata.GetRepositoryType: string;
begin
result := FRepositoryBranch;
end;
function TPackageMetadata.GetRepositoryUrl: string;
begin
result := FRepositoryUrl;
end;
function TPackageMetadata.GetSearchPaths : IList<string>;
begin
result := FSearchPaths;
end;
function TPackageMetadata.GetTags : string;
begin
result := FTags;
end;
class function TPackageMetadata.TryLoadFromJson(const logger: ILogger; const jsonObj: TJsonObject; const source: string; out packageMetadata: IPackageMetadata): boolean;
begin
result := false;
try
packageMetadata := TPackageMetadata.Create(source, jsonObj);
except
on e : Exception do
begin
logger.Error(e.Message);
exit;
end;
end;
result := true;
end;
{ TPackageMetadataExtractor }
class function TPackageMetadataExtractor.TryExtractIdentity(const logger : ILogger; const fileName : string; out identity : IPackageIdentity; const source : string) : boolean;
var
match : TMatch;
id : string;
cv : TCompilerVersion;
platform : TDPMPlatform;
packageVersion : TPackageVersion;
value : string;
begin
identity := nil;
value := ExtractFileName(fileName);
result := false;
match := TRegEx.Match(filename, cPackageFileRegex, [roIgnoreCase]);
if not match.Success then
begin
logger.Error('Package name is not a valid package [' + value + ']');
exit;
end;
id := match.Groups[1].Value;
cv := StringToCompilerVersion(match.Groups[2].Value);
if cv = TCompilerVersion.UnknownVersion then
begin
logger.Error('Compiler version segment is not a valid version [' + match.Groups[2].Value + ']');
exit;
end;
platform := StringToDPMPlatform(match.Groups[3].Value);
if platform = TDPMPlatform.UnknownPlatform then
begin
logger.Error('Platform segment is not a valid platform [' + match.Groups[3].Value + ']');
exit;
end;
if not TPackageVersion.TryParse(match.Groups[4].Value, packageVersion) then
begin
logger.Error('Version segment is not a valid version [' + match.Groups[4].Value + ']');
exit;
end;
//we dont' have a source.
identity := TPackageIdentity.Create(id, source, packageVersion, cv, platform);
result := true;
end;
class function TPackageMetadataExtractor.TryExtractInfo(const logger : ILogger; const fileName : string; out info : IPackageInfo; const source : string) : boolean;
var
zipFile : TZipFile;
metaBytes : TBytes;
metaString : string;
spec : IPackageSpec;
reader : IPackageSpecReader;
begin
result := false;
zipFile := TZipFile.Create;
try
try
zipFile.Open(fileName, TZipMode.zmRead);
zipFile.Read(cPackageMetaFile, metaBytes);
except
on e : Exception do
begin
Logger.Error('Error opening package file [' + fileName + ']');
exit;
end;
end;
finally
zipFile.Free;
end;
//doing this outside the try/finally to avoid locking the package for too long.
metaString := TEncoding.UTF8.GetString(metaBytes);
reader := TPackageSpecReader.Create(Logger);
spec := reader.ReadSpecString(metaString);
if spec = nil then
exit;
info := TPackageMetadata.CreateFromSpec(source, spec);
result := true;
end;
class function TPackageMetadataExtractor.TryExtractFull(const logger : ILogger; const fileName : string; out metadata : IPackageMetadata; const source : string = '') : boolean;
var
zipFile : TZipFile;
metaBytes : TBytes;
metaString : string;
spec : IPackageSpec;
reader : IPackageSpecReader;
begin
result := false;
zipFile := TZipFile.Create;
try
try
zipFile.Open(fileName, TZipMode.zmRead);
zipFile.Read(cPackageMetaFile, metaBytes);
except
on e : Exception do
begin
Logger.Error('Error opening package file [' + fileName + ']');
exit;
end;
end;
finally
zipFile.Free;
end;
//doing this outside the try/finally to avoid locking the package for too long.
metaString := TEncoding.UTF8.GetString(metaBytes);
reader := TPackageSpecReader.Create(Logger);
spec := reader.ReadSpecString(metaString);
if spec = nil then
exit;
metadata := TPackageMetadata.CreateFromSpec(source, spec);
result := true;
end;
{ TPackageId }
constructor TPackageId.Create(const id : string; const version : TPackageVersion; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform);
begin
FId := id;
FVersion := version;
FCompilerVersion := compilerVersion;
FPlatform := platform;
end;
function TPackageId.GetCompilerVersion : TCompilerVersion;
begin
result := FCompilerVersion;
end;
function TPackageId.GetId : string;
begin
result := FId;
end;
function TPackageId.GetPlatform : TDPMPlatform;
begin
result := FPlatform;
end;
function TPackageId.GetVersion : TPackageVersion;
begin
result := FVersion;
end;
function TPackageId.ToIdVersionString : string;
begin
result := FId + ' [' + FVersion.ToStringNoMeta + ']';
end;
function TPackageId.ToString : string;
begin
result := FId + '-' + CompilerToString(FCompilerVersion) + '-' + DPMPlatformToString(FPlatform) + '-' + FVersion.ToStringNoMeta;
end;
//initialization
// JsonSerializationConfig.NullConvertsToValueTypes := true;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [FIN_PARCELA_PAGAR]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit FinParcelaPagarVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
FinParcelaPagamentoVO, FinChequeEmitidoVO;
type
TFinParcelaPagarVO = class(TVO)
private
FID: Integer;
FID_CONTA_CAIXA: Integer;
FID_FIN_LANCAMENTO_PAGAR: Integer;
FID_FIN_STATUS_PARCELA: Integer;
FNUMERO_PARCELA: Integer;
FDATA_EMISSAO: TDateTime;
FDATA_VENCIMENTO: TDateTime;
FDESCONTO_ATE: TDateTime;
FSOFRE_RETENCAO: String;
FVALOR: Extended;
FTAXA_JURO: Extended;
FTAXA_MULTA: Extended;
FTAXA_DESCONTO: Extended;
FVALOR_JURO: Extended;
FVALOR_MULTA: Extended;
FVALOR_DESCONTO: Extended;
//Objetos utilizados apenas para persistência - Não serão utilizados nas consultas
//Serão usados no método BaixarParcela
FFinParcelaPagamentoVO: TFinParcelaPagamentoVO;
FFinChequeEmitidoVO: TFinChequeEmitidoVO;
//FListaParcelaPagarVO: TListaFinParcelaPagarVO;
FListaParcelaPagamentoVO: TListaFinParcelaPagamentoVO;
published
property Id: Integer read FID write FID;
property IdContaCaixa: Integer read FID_CONTA_CAIXA write FID_CONTA_CAIXA;
property IdFinLancamentoPagar: Integer read FID_FIN_LANCAMENTO_PAGAR write FID_FIN_LANCAMENTO_PAGAR;
property IdFinStatusParcela: Integer read FID_FIN_STATUS_PARCELA write FID_FIN_STATUS_PARCELA;
property NumeroParcela: Integer read FNUMERO_PARCELA write FNUMERO_PARCELA;
property DataEmissao: TDateTime read FDATA_EMISSAO write FDATA_EMISSAO;
property DataVencimento: TDateTime read FDATA_VENCIMENTO write FDATA_VENCIMENTO;
property DescontoAte: TDateTime read FDESCONTO_ATE write FDESCONTO_ATE;
property SofreRetencao: String read FSOFRE_RETENCAO write FSOFRE_RETENCAO;
property Valor: Extended read FVALOR write FVALOR;
property TaxaJuro: Extended read FTAXA_JURO write FTAXA_JURO;
property TaxaMulta: Extended read FTAXA_MULTA write FTAXA_MULTA;
property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO;
property ValorJuro: Extended read FVALOR_JURO write FVALOR_JURO;
property ValorMulta: Extended read FVALOR_MULTA write FVALOR_MULTA;
property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO;
//Objetos utilizados apenas para persistência - Não serão utilizados nas consultas
//Serão usados no método BaixarParcela
property FinParcelaPagamentoVO: TFinParcelaPagamentoVO read FFinParcelaPagamentoVO write FFinParcelaPagamentoVO;
property FinChequeEmitidoVO: TFinChequeEmitidoVO read FFinChequeEmitidoVO write FFinChequeEmitidoVO;
//property ListaParcelaPagarVO: TListaFinParcelaPagarVO read FListaParcelaPagarVO write FListaParcelaPagarVO;
property ListaParcelaPagamentoVO: TListaFinParcelaPagamentoVO read FListaParcelaPagamentoVO write FListaParcelaPagamentoVO;
end;
TListaFinParcelaPagarVO = specialize TFPGObjectList<TFinParcelaPagarVO>;
implementation
initialization
Classes.RegisterClass(TFinParcelaPagarVO);
finalization
Classes.UnRegisterClass(TFinParcelaPagarVO);
end.
|
unit fos_firmbox_net_routing_mod;
{$mode objfpc}{$H+}
{$modeswitch nestedprocvars}
interface
uses
Classes, SysUtils, FRE_SYSTEM,
FOS_TOOL_INTERFACES,
FRE_DB_INTERFACE,
FRE_DB_COMMON,
fos_firmbox_subnet_ip_mod,
fre_hal_schemes,fre_zfs;
type
{ TFRE_FIRMBOX_NET_ROUTING_MOD }
TFRE_FIRMBOX_NET_ROUTING_MOD = class (TFRE_DB_APPLICATION_MODULE)
private
fNetIPMod : TFRE_FIRMBOX_SUBNET_IP_MOD;
function _checkZoneStatus (const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean;
function _checkObjAndZoneStatus (const dbo: IFRE_DB_Object; const ses: IFRE_DB_Usersession; 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 zone: TFRE_DB_ZONE; 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 _canDelete (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION):Boolean;
function _canModify (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION):Boolean;
function _canDelegate (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION):Boolean;
function _canDelegate (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object):Boolean;
function _canRetract (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION):Boolean;
function _canRetract (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object):Boolean;
function _canAddVNIC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION):Boolean;
function _canAddVNIC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object):Boolean;
procedure _canAddIP (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var ipv4,ipv6,dhcp,slaac: Boolean);
procedure _canAddIP (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var ipv4,ipv6,dhcp,slaac: Boolean; var dbo: IFRE_DB_Object);
function _canMoveToAggr (const input:IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION):Boolean;
function _canMoveToAggr (const input:IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object):Boolean;
function _canRemoveFromAggr (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION):Boolean;
function _canRemoveFromAggr (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object):Boolean;
function _canMoveToBridge (const input:IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION):Boolean;
function _canMoveToBridge (const input:IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object):Boolean;
function _canRemoveFromBridge (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION):Boolean;
function _canRemoveFromBridge (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object):Boolean;
function _canLinkToIPMP (const input:IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION; const isGlobal:Boolean):Boolean;
function _canLinkToIPMP (const input:IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION; const isGlobal:Boolean; var dbo: IFRE_DB_Object):Boolean;
function _canUnlinkFromIPMP (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION):Boolean;
function _canUnlinkFromIPMP (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object):Boolean;
function _delegateRightsCheck (const zDomainId: TFRE_DB_GUID; const serviceClass: ShortString; const conn: IFRE_DB_CONNECTION): Boolean;
function _getZone (const dbo: IFRE_DB_Object; const conn: IFRE_DB_CONNECTION; const preferGlobal: Boolean): TFRE_DB_ZONE;
function _isDelegated (const dbo: IFRE_DB_Object; const conn: IFRE_DB_CONNECTION): Boolean;
procedure _updateDatalinkGridTB (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION);
function _storeModify (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function _hasVLANChanged (const conn: IFRE_DB_CONNECTION; const input, dbo: IFRE_DB_Object; var newVlan: UInt16): Boolean;
function _getVLAN (const conn: IFRE_DB_CONNECTION; const vlanNumber: UInt16; const domain_id: TFRE_DB_GUID): TFRE_DB_GUID;
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;
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_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_Modify (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_StoreModify (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_StoreModifyConfirmed (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_AddRoute (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_StoreRoute (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_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_DatalinkGridSC (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_DatalinkGridMenu (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_DLObjChanged (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_Delegate (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_StoreDelegation (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_Retract (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_RetractConfirmed (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_AddVNIC (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_StoreVNIC (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_AddIP (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_StoreIP (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_MoveToAggr (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_StoreMoveToAggr (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_RemoveFromAggr (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_MoveToBridge (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_StoreMoveToBridge (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_RemoveFromBridge (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_LinkToIPMP (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_StoreLinkToIPMP (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_UnlinkFromIPMP (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_IFSC (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_ContentIF (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_SliderChanged (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
fre_hal_schemes.Register_DB_Extensions;
GFRE_DBI.RegisterObjectClassEx(TFRE_FIRMBOX_NET_ROUTING_MOD);
end;
{ TFRE_FIRMBOX_NET_ROUTING_MOD }
function TFRE_FIRMBOX_NET_ROUTING_MOD._checkZoneStatus(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean;
var
zone : IFRE_DB_Object;
plugin : TFRE_DB_ZONESTATUS_PLUGIN;
begin
if Assigned(dbo) then begin
zone:=_getZone(dbo,conn,ses.GetSessionModuleData(ClassName).Field('zoneIsGlobal').AsBoolean);
end else begin
CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedZone').AsGUID,zone));
end;
zone.GetPlugin(TFRE_DB_ZONESTATUS_PLUGIN,plugin);
Result:=not plugin.isLockedOrDeleted;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._checkObjAndZoneStatus(const dbo: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
var
plugin : TFRE_DB_SERVICE_STATUS_PLUGIN;
begin
dbo.GetPlugin(TFRE_DB_SERVICE_STATUS_PLUGIN,plugin);
Result:=not plugin.isLockedOrDeleted and _checkZoneStatus(ses,conn,dbo);
end;
function TFRE_FIRMBOX_NET_ROUTING_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;
hcObj : TObject;
form: TFRE_DB_FORM_PANEL_DESC;
scheme: IFRE_DB_SchemeObject;
begin
ses.GetSessionModuleData(ClassName).DeleteField('selectedZone');
ses.UnregisterDBOChangeCB('netRoutingMod');
ses.UnregisterDBOChangeCB('netRoutingModDatalink');
if input.FieldExists('selected') and (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
hcObj:=dbo.Implementor_HC;
if (hcObj is TFRE_DB_ZONE) then begin
res:=_getZoneDetails(hcObj as TFRE_DB_ZONE,input,ses,app,conn);
end else begin
form:=TFRE_DB_FORM_PANEL_DESC.create.Describe('',true,false);
GFRE_DBI.GetSystemSchemeByName(dbo.Implementor_HC.ClassName,scheme);
form.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses);
form.FillWithObjectValues(dbo,ses);
res:=form;
end;
end else begin
res:=TFRE_DB_HTML_DESC.create.Describe(FetchModuleTextShort(ses,'info_details_select_one'));
end;
res.contentId:='netRoutingDetails';
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._getZoneDetails(const zone: TFRE_DB_ZONE; 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_VIEW_LIST_DESC;
dc : IFRE_DB_DERIVED_COLLECTION;
menu : TFRE_DB_MENU_DESC;
canAdd : 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;
canDelete : Boolean;
canDelegate : Boolean;
isGlobal : Boolean;
canAddIP : Boolean;
canAddVNIC : Boolean;
canMoveToAggr : Boolean;
canRemoveFromAggr : Boolean;
canModify : Boolean;
canMoveToBridge : Boolean;
canRemoveFromBridge: Boolean;
canLinkToIPMP : Boolean;
canUnlinkFromIPMP : Boolean;
canAddRoute : Boolean;
begin
CheckClassVisibility4MyDomain(ses);
isGlobal:=(zone is TFRE_DB_GLOBAL_ZONE);
ses.GetSessionModuleData(ClassName).DeleteField('selected');
ses.GetSessionModuleData(ClassName).DeleteField('selectedExt');
ses.GetSessionModuleData(ClassName).Field('zoneIsGlobal').AsBoolean:=isGlobal;
ses.GetSessionModuleData(ClassName).Field('selectedZone').AsGUID:=zone.UID;
ses.RegisterDBOChangeCB(zone.UID,CWSF(@WEB_ZoneObjChanged),'netRoutingMod');
if isGlobal then begin
dc:=ses.FetchDerivedCollection('DATALINK_GRID_GZ');
end else begin
dc:=ses.FetchDerivedCollection('DATALINK_GRID');
end;
dc.Filters.RemoveFilter('zone');
dc.Filters.AddRootNodeFilter('zone','zuid',zone.UID,dbnf_OneValueFromFilter);
res:=dc.GetDisplayDescription.Implementor_HC as TFRE_DB_VIEW_LIST_DESC;
dc:=ses.FetchDerivedCollection('AGGREGATION_CHOOSER');
dc.Filters.RemoveFilter('zone');
dc.Filters.AddUIDFieldFilter('zone','zid',[zone.UID],dbnf_OneValueFromFilter);
dc:=ses.FetchDerivedCollection('BRIDGE_CHOOSER');
dc.Filters.RemoveFilter('zone');
dc.Filters.AddUIDFieldFilter('zone','zid',[zone.UID],dbnf_OneValueFromFilter);
dc:=ses.FetchDerivedCollection('IPMP_CHOOSER');
dc.Filters.RemoveFilter('zone');
dc.Filters.AddUIDFieldFilter('zone','zid',[zone.UID],dbnf_OneValueFromFilter);
canAdd:=false;
canDelete:=false;
canModify:=false;
canDelegate:=false;
menu:=TFRE_DB_MENU_DESC.create.Describe;
submenu:=menu.AddMenu.Describe(FetchModuleTextShort(ses,'tb_add'),'');
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 serviceClass=TFRE_DB_DATALINK_VNIC.ClassName then begin
canDelete:=canDelete or conn.SYS.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_DATALINK_VNIC.ClassName,zone.DomainID);
canModify:=canModify or (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_VNIC.ClassName,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_IPV4.ClassName,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_IPV6.ClassName,zone.DomainID));
end else begin
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='datalink') and conf.Field('enabled').AsBoolean then begin
canDelete:=canDelete or conn.SYS.CheckClassRight4DomainId(sr_DELETE,serviceClass,zone.DomainID);
canModify:=canModify or conn.SYS.CheckClassRight4DomainId(sr_UPDATE,serviceClass,zone.DomainID);
canDelegate:=isGlobal and (canDelegate or _delegateRightsCheck(zone.DomainID,serviceClass,conn));
if conn.SYS.CheckClassRight4DomainId(sr_STORE,serviceClass,zone.DomainID) then begin
canAdd:=true;
sf:=CWSF(@WEB_Add);
sf.AddParam.Describe('serviceClass',serviceClass);
sf.AddParam.Describe('zoneId',zone.UID_String);
submenu.AddEntry.Describe(conf.Field('caption').AsString,'',sf);
end;
end;
end;
end;
end;
canAddIP:=conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV4,zone.DomainID) or conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV6,zone.DomainID);
canAddRoute:=conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV4_ROUTE,zone.DomainID) or conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV6_ROUTE,zone.DomainID);
canAddVNIC:=conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_DATALINK_VNIC,zone.DomainID) and conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_VLAN,zone.DomainID) and
(isGlobal or TFRE_DB_DATALINK_PHYS.DelegationEnabled(ses) or TFRE_DB_DATALINK_AGGR.DelegationEnabled(ses) or
TFRE_DB_DATALINK_STUB.DelegationEnabled(ses) or TFRE_DB_DATALINK_SIMNET.DelegationEnabled(ses));
canMoveToAggr:=false;
canRemoveFromAggr:=false;
canMoveToBridge:=false;
canRemoveFromBridge:=false;
canLinkToIPMP:=false;
canUnlinkFromIPMP:=false;
if isGlobal then begin
if TFRE_DB_DATALINK_AGGR.TypeEnabled(ses) then begin
canMoveToAggr:=conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_VNIC,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4_DHCP,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6_SLAAC,zone.DomainID);
canMoveToAggr:=canMoveToAggr and (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_PHYS,zone.DomainID) or conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_SIMNET,zone.DomainID));
canRemoveFromAggr:=(conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_PHYS,zone.DomainID) or conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_SIMNET,zone.DomainID));
end;
if TFRE_DB_DATALINK_BRIDGE.TypeEnabled(ses) then begin
canMoveToBridge:=conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4_DHCP,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6_SLAAC,zone.DomainID);
canMoveToBridge:=canMoveToBridge and (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_PHYS,zone.DomainID) or conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_SIMNET,zone.DomainID));
canRemoveFromBridge:=(conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_PHYS,zone.DomainID) or conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_SIMNET,zone.DomainID));
end;
if TFRE_DB_DATALINK_IPMP.TypeEnabled(ses) then begin
canLinkToIPMP:=conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4_DHCP,zone.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6_SLAAC,zone.DomainID);
canLinkToIPMP:=canLinkToIPMP and (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_PHYS,zone.DomainID) or conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_SIMNET,zone.DomainID));
canUnlinkFromIPMP:=(conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_PHYS,zone.DomainID) or conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_SIMNET,zone.DomainID));
end;
end;
if canAddRoute then begin
canAdd:=true;
sf:=CWSF(@WEB_AddRoute);
sf.AddParam.Describe('zoneId',zone.UID_String);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_add_route'),'',sf,false,'add_route');
end;
if canAdd or canDelete or canModify or canDelegate or canAddVNIC or canAddIP or canMoveToAggr or canRemoveFromAggr or canMoveToBridge or canRemoveFromBridge or canLinkToIPMP or canUnlinkFromIPMP 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'),'',CWSF(@WEB_Modify),true,'net_routing_modify');
end;
if canDelete then begin
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_delete'),'',CWSF(@WEB_Delete),true,'net_routing_delete');
end;
if canDelegate then begin
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_delegate'),'',CWSF(@WEB_Delegate),true,'net_routing_delegate');
end;
if canAddVNIC then begin
menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_add_vnic'),'',CWSF(@WEB_AddVNIC),true,'net_routing_add_vnic');
end;
if canAddIP then begin
submenu:=menu.AddMenu.Describe(FetchModuleTextShort(ses,'tb_add_ip'),'');
if conn.SYS.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_IPV4) then begin
sf:=CWSF(@WEB_AddIP);
sf.AddParam.Describe('serviceClass',TFRE_DB_IPV4.ClassName);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_add_ip_ipv4'),'',sf,true,'net_routing_add_ipv4');
end;
if conn.SYS.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_IPV6) then begin
sf:=CWSF(@WEB_AddIP);
sf.AddParam.Describe('serviceClass',TFRE_DB_IPV6.ClassName);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_add_ip_ipv6'),'',sf,true,'net_routing_add_ipv6');
end;
if conn.SYS.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_IPV4_DHCP) then begin
sf:=CWSF(@WEB_AddIP);
sf.AddParam.Describe('serviceClass',TFRE_DB_IPV4_DHCP.ClassName);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_add_ip_ipv4_dhcp'),'',sf,true,'net_routing_add_dhcp');
end;
if conn.SYS.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_IPV6_SLAAC) then begin
sf:=CWSF(@WEB_AddIP);
sf.AddParam.Describe('serviceClass',TFRE_DB_IPV6_SLAAC.ClassName);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_add_ip_ipv6_slaac'),'',sf,true,'net_routing_add_slaac');
end;
end;
if canMoveToAggr or canRemoveFromAggr then begin
submenu:=menu.AddMenu.Describe(FetchModuleTextShort(ses,'tb_aggregation'),'');
if canMoveToAggr then begin
sf:=CWSF(@WEB_MoveToAggr);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_aggregation_move_to'),'',sf,true,'net_routing_move_to_aggr');
end;
if canRemoveFromAggr then begin
sf:=CWSF(@WEB_RemoveFromAggr);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_aggregation_remove_from'),'',sf,true,'net_routing_remove_from_aggr');
end;
end;
if canMoveToBridge or canRemoveFromBridge then begin
submenu:=menu.AddMenu.Describe(FetchModuleTextShort(ses,'tb_bridge'),'');
if canMoveToAggr then begin
sf:=CWSF(@WEB_MoveToBridge);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_bridge_move_to'),'',sf,true,'net_routing_move_to_bridge');
end;
if canRemoveFromAggr then begin
sf:=CWSF(@WEB_RemoveFromBridge);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_bridge_remove_from'),'',sf,true,'net_routing_remove_from_bridge');
end;
end;
if canLinkToIPMP or canUnlinkFromIPMP then begin
submenu:=menu.AddMenu.Describe(FetchModuleTextShort(ses,'tb_ipmp'),'');
if canLinkToIPMP then begin
sf:=CWSF(@WEB_LinkToIPMP);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_ipmp_link_to'),'',sf,true,'net_routing_link_to_ipmp');
end;
if canUnlinkFromIPMP then begin
sf:=CWSF(@WEB_UnlinkFromIPMP);
submenu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_ipmp_unlink_from'),'',sf,true,'net_routing_unlink_from_ipmp');
end;
end;
res.SetMenu(menu);
end;
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canDelete(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
var
dbo : IFRE_DB_Object;
begin
Result:=false;
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if dbo.IsA(TFRE_DB_DATALINK_PHYS.ClassName) then exit; //physical datalinks cannot be deleted
Result:=_checkObjAndZoneStatus(dbo,ses,conn) and conn.sys.CheckClassRight4DomainId(sr_DELETE,dbo.Implementor_HC.ClassType,dbo.DomainID) and //check plugin & rights
(conn.GetReferencesCount(dbo.UID,false)=0) and //no children
(ses.GetSessionModuleData(ClassName).Field('zoneIsGlobal').AsBoolean or not _isDelegated(dbo,conn)); //delegated obj not deletable in client zone
if Result and (conn.GetReferencesCount(dbo.UID,true,TFRE_DB_DATALINK_AGGR.ClassName,'datalinkParent')>0) then begin //within aggregation
if not (dbo.IsA(TFRE_DB_DATALINK_VNIC.ClassName) or dbo.IsA(TFRE_DB_IPV4.ClassName) or dbo.IsA(TFRE_DB_IPV4_DHCP.ClassName) or dbo.IsA(TFRE_DB_IPV6.ClassName) or dbo.IsA(TFRE_DB_IPV6_SLAAC.ClassName)) then begin
Result:=false;
end;
end;
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canModify(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
var
dbo : IFRE_DB_Object;
begin
Result:=false;
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if dbo.IsA(TFRE_DB_IP_ROUTE) then exit; //a route can not be modified (delete and create a new one)
Result:=_checkObjAndZoneStatus(dbo,ses,conn) and conn.sys.CheckClassRight4DomainId(sr_UPDATE,dbo.Implementor_HC.ClassType,dbo.DomainID) and //check plugin & rights
(not dbo.IsA(TFRE_DB_DATALINK_VNIC) or (conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_VLAN,dbo.DomainID) and //in case of a vnic vlan and ip rights are also needed
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_IPV4,dbo.DomainID) and
conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_IPV6,dbo.DomainID)));
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canDelegate(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
var
dbo : IFRE_DB_Object;
begin
Result:=_canDelegate(input,ses,conn,dbo);
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canDelegate(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object): Boolean;
var
hcObj : TObject;
datalink : TFRE_DB_DATALINK;
begin
Result:=false;
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if dbo.IsA(TFRE_DB_DATALINK,datalink) then begin
if not datalink.DelegationEnabled(ses) then exit; //delegation for this datalink type not enabled
if not _checkObjAndZoneStatus(datalink,ses,conn) then begin
exit;
end;
if _isDelegated(datalink,conn) then begin //already delegated
exit;
end;
if conn.GetReferencesCount(datalink.UID,true,TFRE_DB_DATALINK_IPMP.ClassName,'datalinkParent')>0 then begin
exit; //object is within an IPMP
end;
hcObj:=datalink.Implementor_HC;
if (hcObj is TFRE_DB_DATALINK_PHYS) or (hcObj is TFRE_DB_DATALINK_SIMNET) then begin //only if empty
if (conn.GetReferencesCount(datalink.UID,false,TFRE_DB_DATALINK_VNIC.ClassName,'datalinkParent')=0) and (conn.GetReferencesCount(datalink.UID,true,TFRE_DB_DATALINK_AGGR.ClassName,'datalinkParent')=0) then begin
Result:=_delegateRightsCheck(datalink.DomainID,hcObj.ClassName,conn);
end;
end else
if hcObj is TFRE_DB_DATALINK_AGGR then begin
Result:=_delegateRightsCheck(datalink.DomainID,TFRE_DB_DATALINK_AGGR.ClassName,conn) and
_delegateRightsCheck(datalink.DomainID,TFRE_DB_DATALINK_PHYS.ClassName,conn) and
_delegateRightsCheck(datalink.DomainID,TFRE_DB_DATALINK_SIMNET.ClassName,conn);
end else
if hcObj is TFRE_DB_DATALINK_VNIC then begin
Result:=_delegateRightsCheck(datalink.DomainID,TFRE_DB_DATALINK_VNIC.ClassName,conn);
end;
end;
Result:=Result and _delegateRightsCheck(datalink.DomainID,TFRE_DB_IPV4.ClassName,conn) and _delegateRightsCheck(datalink.DomainID,TFRE_DB_IPV6.ClassName,conn)
and _delegateRightsCheck(datalink.DomainID,TFRE_DB_IPV4_DHCP.ClassName,conn) and _delegateRightsCheck(datalink.DomainID,TFRE_DB_IPV6_SLAAC.ClassName,conn);
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canRetract(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
var
dbo : IFRE_DB_Object;
begin
Result:=_canRetract(input,ses,conn,dbo);
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canRetract(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object): Boolean;
var
hcObj : TObject;
datalink : TFRE_DB_DATALINK;
begin
Result:=false;
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if dbo.IsA(TFRE_DB_DATALINK,datalink) then begin
if not _checkObjAndZoneStatus(datalink,ses,conn) then begin
exit;
end;
if not _isDelegated(datalink,conn) then begin //not delegated
exit;
end;
hcObj:=datalink.Implementor_HC;
if (hcObj is TFRE_DB_DATALINK_PHYS) or (hcObj is TFRE_DB_DATALINK_SIMNET) then begin //only if empty
if (conn.GetReferencesCount(datalink.UID,false,TFRE_DB_DATALINK_VNIC.ClassName,'datalinkParent')=0) and (conn.GetReferencesCount(datalink.UID,true,TFRE_DB_DATALINK_AGGR.ClassName,'datalinkParent')=0) then begin
Result:=_delegateRightsCheck(datalink.DomainID,hcObj.ClassName,conn);
end;
end else
if hcObj is TFRE_DB_DATALINK_AGGR then begin
Result:=_delegateRightsCheck(datalink.DomainID,TFRE_DB_DATALINK_AGGR.ClassName,conn) and
_delegateRightsCheck(datalink.DomainID,TFRE_DB_DATALINK_PHYS.ClassName,conn) and
_delegateRightsCheck(datalink.DomainID,TFRE_DB_DATALINK_SIMNET.ClassName,conn);
end else
if hcObj is TFRE_DB_DATALINK_VNIC then begin
Result:=_delegateRightsCheck(datalink.DomainID,TFRE_DB_DATALINK_VNIC.ClassName,conn);
end;
end;
Result:=Result and _delegateRightsCheck(datalink.DomainID,TFRE_DB_IPV4.ClassName,conn) and _delegateRightsCheck(datalink.DomainID,TFRE_DB_IPV6.ClassName,conn)
and _delegateRightsCheck(datalink.DomainID,TFRE_DB_IPV4_DHCP.ClassName,conn) and _delegateRightsCheck(datalink.DomainID,TFRE_DB_IPV6_SLAAC.ClassName,conn);
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canAddVNIC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
var
dbo : IFRE_DB_Object;
begin
Result:=_canAddVNIC(input,ses,conn,dbo);
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canAddVNIC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object): Boolean;
begin
Result:=false;
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if not _checkObjAndZoneStatus(dbo,ses,conn) then exit;
if not (conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_DATALINK_VNIC,dbo.DomainID) and conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_VLAN,dbo.DomainID)) then exit;
if dbo.Implementor_HC is TFRE_DB_DATALINK_VNIC then begin
exit; //vinc can not be added to a vinc
end;
if dbo.Implementor_HC is TFRE_DB_IP then begin
exit; //vinc can not be added to an IP
end;
if dbo.Implementor_HC is TFRE_DB_DATALINK_IPTUN then begin
exit; //vinc can not be added to a IPTUN
end;
if dbo.Implementor_HC is TFRE_DB_DATALINK_BRIDGE then begin
exit; //vinc can not be added to a bridge
end;
if conn.GetReferencesCount(dbo.UID,true,TFRE_DB_DATALINK_AGGR.ClassName,'datalinkParent')>0 then begin
exit; //vnic has to be added on the aggregation
end;
if ses.GetSessionModuleData(ClassName).Field('zoneIsGlobal').AsBoolean and _isDelegated(dbo,conn) then begin
exit; //delegated interface - vnic has to be added there
end;
end;
Result:=true;
end;
procedure TFRE_FIRMBOX_NET_ROUTING_MOD._canAddIP(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var ipv4, ipv6, dhcp, slaac: Boolean);
var
dbo : IFRE_DB_Object;
begin
_canAddIP(input,ses,conn,ipv4,ipv6,dhcp,slaac,dbo);
end;
procedure TFRE_FIRMBOX_NET_ROUTING_MOD._canAddIP(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var ipv4, ipv6, dhcp, slaac: Boolean; var dbo: IFRE_DB_Object);
begin
ipv4:=false;
ipv6:=false;
dhcp:=false;
slaac:=false;
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if not _checkObjAndZoneStatus(dbo,ses,conn) then begin
exit;
end;
if conn.GetReferencesCount(dbo.UID,true,TFRE_DB_DATALINK_AGGR.ClassName,'datalinkParent')>0 then begin
exit; //IP has to be added on the aggregation
end;
if conn.GetReferencesCount(dbo.UID,true,TFRE_DB_DATALINK_BRIDGE.ClassName,'datalinkParent')>0 then begin
exit; //IP has to be added on the bridge
end;
if dbo.Implementor_HC is TFRE_DB_IP then begin
exit; //ips can not be added to an ip
end;
if conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV4,dbo.DomainID) then begin
ipv4:=true;
end;
if conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV4_DHCP,dbo.DomainID) then begin
dhcp:=conn.GetReferencesCount(dbo.UID,false,TFRE_DB_IPV4_DHCP.ClassName,'datalinkparent')=0;
end;
if conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV6,dbo.DomainID) then begin
ipv6:=true;
end;
if conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV6_SLAAC,dbo.DomainID) then begin
slaac:=conn.GetReferencesCount(dbo.UID,false,TFRE_DB_IPV6_SLAAC.ClassName,'datalinkparent')=0;
end;
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canMoveToAggr(const input: IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION): Boolean;
var
dbo : IFRE_DB_Object;
begin
Result:=_canMoveToAggr(input,ses,conn,dbo);
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canMoveToAggr(const input: IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object): Boolean;
var
hcObj : TObject;
dc : IFRE_DB_DERIVED_COLLECTION;
refs : TFRE_DB_GUIDArray;
i : Integer;
vnic : IFRE_DB_Object;
parentDbo: IFRE_DB_Object;
begin
Result:=false;
if not TFRE_DB_DATALINK_AGGR.TypeEnabled(ses) then exit; //datalink type not enabled
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if not _checkObjAndZoneStatus(dbo,ses,conn) then begin
exit;
end;
hcObj:=dbo.Implementor_HC;
if ((hcObj is TFRE_DB_DATALINK_PHYS) or (hcObj is TFRE_DB_DATALINK_SIMNET)) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,hcObj.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_DATALINK_VNIC.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4_DHCP.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6_SLAAC.ClassName,dbo.DomainID) then begin
if _isDelegated(dbo,conn) then begin
exit; //delegated
end;
refs:=conn.GetReferences(dbo.UID,true,'','datalinkParent');
for i := 0 to High(refs) do begin
CheckDbResult(conn.Fetch(refs[i],parentDbo));
if (parentDbo.Implementor_HC is TFRE_DB_DATALINK_AGGR) or (parentDbo.Implementor_HC is TFRE_DB_DATALINK_BRIDGE) then begin //already within an aggregation or bridge
exit;
end;
end;
refs:=conn.GetReferences(dbo.UID,false,TFRE_DB_DATALINK_VNIC.ClassName,'datalinkParent');
for i := 0 to High(refs) do begin
CheckDbResult(conn.Fetch(refs[i],vnic));
if _isDelegated(vnic,conn) then begin //at least on vnic is delegated
exit;
end;
end;
if (conn.GetReferencesCount(dbo.UID,true,TFRE_DB_DATALINK_AGGR.ClassName,'datalinkParent')=0) then begin //not already in an aggregation
//check possible aggregations count
dc:=ses.FetchDerivedCollection('AGGREGATION_CHOOSER');
dc.Filters.RemoveFilter('rights');
dc.Filters.RemoveFilter('domain');
dc.Filters.AddStdClassRightFilter('rights','domainid','','',hcObj.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
if not (conn.SYS.CheckClassRight4DomainId(sr_DELETE,hcObj.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_DATALINK_VNIC.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_IPV4.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_IPV6.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_IPV4_DHCP.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_IPV6_SLAAC.ClassName,dbo.DomainID)) then begin //can not delete => only aggregations in own domain editable
dc.Filters.AddUIDFieldFilter('domain','domainid',[dbo.DomainID],dbnf_OneValueFromFilter);
end;
Result:=dc.ItemCount>0;
end;
end;
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canRemoveFromAggr(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
var
dbo : IFRE_DB_Object;
begin
Result:=_canRemoveFromAggr(input,ses,conn,dbo);
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canRemoveFromAggr(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object): Boolean;
var
hcObj : TObject;
zone : TFRE_DB_ZONE;
begin
Result:=false;
if not TFRE_DB_DATALINK_AGGR.TypeEnabled(ses) then exit; //datalink type not enabled
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if not _checkObjAndZoneStatus(dbo,ses,conn) then begin
exit;
end;
hcObj:=dbo.Implementor_HC;
if ((hcObj is TFRE_DB_DATALINK_VNIC) or (hcObj is TFRE_DB_IP)) then exit; //have to be deleted not removed
if conn.GetReferencesCount(dbo.UID,true,TFRE_DB_DATALINK_AGGR.ClassName,'datalinkParent')=0 then begin
exit; //object is not within an aggregation
end;
zone:=_getZone(dbo,conn,true);
if zone.DomainID=dbo.DomainID then begin
Result:=conn.SYS.CheckClassRight4DomainId(sr_UPDATE,hcObj.ClassName,dbo.DomainID);
end else begin
Result:=conn.SYS.CheckClassRight4DomainId(sr_DELETE,hcObj.ClassName,dbo.DomainID) and conn.SYS.CheckClassRight4DomainId(sr_STORE,hcObj.ClassName,zone.DomainID);
end;
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canMoveToBridge(const input: IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION): Boolean;
var
dbo: IFRE_DB_Object;
begin
Result:=_canMoveToBridge(input,ses,conn,dbo);
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canMoveToBridge(const input: IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object): Boolean;
var
hcObj : TObject;
dc : IFRE_DB_DERIVED_COLLECTION;
refs : TFRE_DB_GUIDArray;
parentDbo: IFRE_DB_Object;
i : Integer;
begin
Result:=false;
if not TFRE_DB_DATALINK_BRIDGE.TypeEnabled(ses) then exit; //datalink type not enabled
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if not _checkObjAndZoneStatus(dbo,ses,conn) then begin
exit;
end;
hcObj:=dbo.Implementor_HC;
if ((hcObj is TFRE_DB_DATALINK_PHYS) or (hcObj is TFRE_DB_DATALINK_SIMNET) or (hcObj is TFRE_DB_DATALINK_STUB)) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,hcObj.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4_DHCP.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6_SLAAC.ClassName,dbo.DomainID) then begin
refs:=conn.GetReferences(dbo.UID,true,'','datalinkParent');
for i := 0 to High(refs) do begin
CheckDbResult(conn.Fetch(refs[i],parentDbo));
if (parentDbo.Implementor_HC is TFRE_DB_DATALINK_AGGR) or (parentDbo.Implementor_HC is TFRE_DB_DATALINK_BRIDGE) then begin //already within an aggregation or bridge
exit;
end;
end;
if _isDelegated(dbo,conn) then begin //delegated datalinks can not be used
exit;
end;
dc:=ses.FetchDerivedCollection('BRIDGE_CHOOSER');
Result:=dc.ItemCount>0;
end;
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canRemoveFromBridge(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
var
dbo: IFRE_DB_Object;
begin
Result:=_canRemoveFromBridge(input,ses,conn,dbo);
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canRemoveFromBridge(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object): Boolean;
var
hcObj : TObject;
begin
Result:=false;
if not TFRE_DB_DATALINK_BRIDGE.TypeEnabled(ses) then exit; //datalink type not enabled
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if not _checkObjAndZoneStatus(dbo,ses,conn) then begin
exit;
end;
hcObj:=dbo.Implementor_HC;
if (hcObj is TFRE_DB_IP) then exit; //has to be deleted not removed
if conn.GetReferencesCount(dbo.UID,true,TFRE_DB_DATALINK_BRIDGE.ClassName,'datalinkParent')=0 then begin
exit; //object is not within an bridge
end;
Result:=conn.SYS.CheckClassRight4DomainId(sr_UPDATE,dbo.Implementor_HC.ClassName,dbo.DomainID);
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canLinkToIPMP(const input: IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION; const isGlobal:Boolean): Boolean;
var
dbo: IFRE_DB_Object;
begin
Result:=_canLinkToIPMP(input,ses,conn,isGlobal,dbo);
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canLinkToIPMP(const input: IFRE_DB_Object; const ses: IFRE_DB_UserSession; const conn: IFRE_DB_CONNECTION; const isGlobal:Boolean; var dbo: IFRE_DB_Object): Boolean;
var
hcObj : TObject;
dc : IFRE_DB_DERIVED_COLLECTION;
i : Integer;
parentDbo: IFRE_DB_Object;
refs : TFRE_DB_GUIDArray;
begin
Result:=false;
if not TFRE_DB_DATALINK_IPMP.TypeEnabled(ses) then exit; //datalink type not enabled
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if not _checkObjAndZoneStatus(dbo,ses,conn) then begin
exit;
end;
hcObj:=dbo.Implementor_HC;
if ((hcObj is TFRE_DB_DATALINK_PHYS) or (hcObj is TFRE_DB_DATALINK_SIMNET) or (hcObj is TFRE_DB_DATALINK_VNIC)) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,hcObj.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV4_DHCP.ClassName,dbo.DomainID) and
conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_IPV6_SLAAC.ClassName,dbo.DomainID) then begin
if _isDelegated(dbo,conn) then begin //delegated datalinks can not be used
exit;
end;
if conn.GetReferencesCount(dbo.UID,true,TFRE_DB_DATALINK_IPMP.ClassName,'datalinkParent')>0 then begin
exit; //object is already within an IPMP
end;
if (hcObj is TFRE_DB_DATALINK_VNIC) then begin
if isGlobal then begin //in case of global zone check if parent is already delgated
refs:=conn.GetReferences(dbo.UID,true,'','datalinkParent');
for i := 0 to High(refs) - 1 do begin
CheckDbResult(conn.Fetch(refs[i],parentDbo));
if _isDelegated(parentDbo,conn) then
exit;
end;
end;
end;
dc:=ses.FetchDerivedCollection('IPMP_CHOOSER');
Result:=dc.ItemCount>0;
end;
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canUnlinkFromIPMP(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION): Boolean;
var
dbo: IFRE_DB_Object;
begin
Result:=_canUnlinkFromIPMP(input,ses,conn,dbo);
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._canUnlinkFromIPMP(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; var dbo: IFRE_DB_Object): Boolean;
var
hcObj : TObject;
begin
Result:=false;
if not TFRE_DB_DATALINK_IPMP.TypeEnabled(ses) then exit; //datalink type not enabled
if (input.Field('selected').ValueCount=1) then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if not _checkObjAndZoneStatus(dbo,ses,conn) then begin
exit;
end;
hcObj:=dbo.Implementor_HC;
if ((hcObj is TFRE_DB_DATALINK_VNIC) or (hcObj is TFRE_DB_IP)) then exit; //have to be deleted not removed
if conn.GetReferencesCount(dbo.UID,true,TFRE_DB_DATALINK_IPMP.ClassName,'datalinkParent')=0 then begin
exit; //object is not within an IPMP
end;
Result:=conn.SYS.CheckClassRight4DomainId(sr_UPDATE,dbo.Implementor_HC.ClassName,dbo.DomainID);
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._delegateRightsCheck(const zDomainId: TFRE_DB_GUID; const serviceClass: ShortString; const conn: IFRE_DB_CONNECTION): Boolean;
begin
if conn.SYS.CheckClassRight4DomainId(sr_DELETE,serviceClass,zDomainId) and conn.SYS.CheckClassRight4AnyDomain(sr_STORE,serviceClass) then begin
Result:=true;
end else begin
Result:=false;
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._getZone(const dbo: IFRE_DB_Object; const conn:IFRE_DB_CONNECTION; const preferGlobal: Boolean): TFRE_DB_ZONE;
function _checkParents(const dbo: IFRE_DB_Object): IFRE_DB_Object;
var
parentObj : IFRE_DB_Object;
parentUids: TFRE_DB_ObjLinkArray;
i : Integer;
begin
parentUids:=dbo.Field('datalinkParent').AsObjectLinkArray;
for i := 0 to High(parentUids) do begin
CheckDbResult(conn.Fetch(parentUids[i],parentObj));
if not (parentObj.Implementor_HC is TFRE_DB_ZONE) then begin
Result:=_checkParents(parentObj);
end else begin
Result:=parentObj;
end;
if Result.Implementor_HC is TFRE_DB_GLOBAL_ZONE and preferGlobal then begin
exit; //global zone prefered and found
end;
if not (Result.Implementor_HC is TFRE_DB_GLOBAL_ZONE) and not preferGlobal then begin
exit; //client zone preferd and found
end;
end;
end;
begin
Result:=_checkParents(dbo).Implementor_HC as TFRE_DB_ZONE;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._isDelegated(const dbo: IFRE_DB_Object; const conn: IFRE_DB_CONNECTION): Boolean;
var
zoneCount: Integer;
procedure _checkParents(const dbo: IFRE_DB_Object);
var
parentObj : IFRE_DB_Object;
parentUids: TFRE_DB_ObjLinkArray;
i : Integer;
begin
parentUids:=dbo.Field('datalinkParent').AsObjectLinkArray;
for i := 0 to High(parentUids) do begin
CheckDbResult(conn.Fetch(parentUids[i],parentObj));
if parentObj.Implementor_HC is TFRE_DB_DATALINK_IPMP then continue; //skip IPMP paths
if (parentObj.Implementor_HC is TFRE_DB_ZONE) then begin
zoneCount:=zoneCount+1;
end else begin
_checkParents(parentObj);
end;
end;
end;
begin
zoneCount:=0;
_checkParents(dbo);
Result:=zoneCount>1;
end;
procedure TFRE_FIRMBOX_NET_ROUTING_MOD._updateDatalinkGridTB(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION);
var
delDisabled : Boolean;
delegateDisabled : Boolean;
retractDisabled : Boolean;
vnicDisabled : Boolean;
ipv4Enabled : Boolean;
ipv6Enabled : Boolean;
moveToAggrDisabled : Boolean;
removeFromAggrDisabled : Boolean;
moveToBridgeDisabled : Boolean;
removeFromBridgeDisabled : Boolean;
linkToIPMPDisabled : Boolean;
unlinkFromIPMPDisabled : Boolean;
isGlobal : Boolean;
modifyDisabled : Boolean;
dhcpEnabled : Boolean;
slaacEnabled : Boolean;
dbo : IFRE_DB_Object;
delegated : Boolean;
begin
if not ses.GetSessionModuleData(ClassName).FieldExists('selectedZone') then exit;
isGlobal:=ses.GetSessionModuleData(ClassName).Field('zoneIsGlobal').AsBoolean;
delDisabled:=true;
modifyDisabled:=true;
delegateDisabled:=true;
retractDisabled:=true;
vnicDisabled:=true;
ipv4Enabled:=false;
ipv6Enabled:=false;
dhcpEnabled:=false;
slaacEnabled:=false;
moveToAggrDisabled:=true;
removeFromAggrDisabled:=true;
moveToBridgeDisabled:=true;
removeFromBridgeDisabled:=true;
linkToIPMPDisabled:=true;
unlinkFromIPMPDisabled:=true;
if _checkZoneStatus(ses,conn,nil) and ses.GetSessionModuleData(ClassName).FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
delDisabled:=not _canDelete(input,ses,conn);
modifyDisabled:=not _canModify(input,ses,conn);
vnicDisabled:=not _canAddVNIC(input,ses,conn);
_canAddIP(input,ses,conn,ipv4Enabled,ipv6Enabled,dhcpEnabled,slaacEnabled);
moveToBridgeDisabled:=not _canMoveToBridge(input,ses,conn);
removeFromBridgeDisabled:=not _canRemoveFromBridge(input,ses,conn);
linkToIPMPDisabled:=not _canLinkToIPMP(input,ses,conn,isGlobal);
unlinkFromIPMPDisabled:=not _canUnlinkFromIPMP(input,ses,conn);
if isGlobal then begin
moveToAggrDisabled:=not _canMoveToAggr(input,ses,conn);
removeFromAggrDisabled:=not _canRemoveFromAggr(input,ses,conn);
if input.Field('selected').ValueCount=1 then begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if _isDelegated(dbo,conn) then begin
delegated:=true;
retractDisabled:=not _canRetract(input,ses,conn);
end else begin
delegated:=false;
delegateDisabled:=not _canDelegate(input,ses,conn);
end;
end else begin
delegateDisabled:=not _canDelegate(input,ses,conn);
end;
end;
end;
if isGlobal then begin;
if delegated then begin
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_delegate',retractDisabled,FetchModuleTextShort(ses,'tb_retract'),'',CWSF(@WEB_Retract)));
end else begin
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_delegate',delegateDisabled,FetchModuleTextShort(ses,'tb_delegate'),'',CWSF(@WEB_Delegate)));
end;
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_move_to_aggr',moveToAggrDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_remove_from_aggr',removeFromAggrDisabled));
end;
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_modify',modifyDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_delete',delDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_add_vnic',vnicDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_add_ipv4',not ipv4Enabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_add_ipv6',not ipv6Enabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_add_dhcp',not dhcpEnabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_add_slaac',not slaacEnabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_move_to_bridge',moveToBridgeDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_remove_from_bridge',removeFromBridgeDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_link_to_ipmp',linkToIPMPDisabled));
ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('net_routing_unlink_from_ipmp',unlinkFromIPMPDisabled));
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._storeModify(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;
scheme : IFRE_DB_SchemeObject;
zone : TFRE_DB_ZONE;
hcObj : TObject;
idx : String;
coll : IFRE_DB_COLLECTION;
parentDbo: IFRE_DB_Object;
hnObjname: String;
ips : TFRE_DB_GUIDArray;
i : Integer;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canModify(input,ses,conn) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
hcObj:=dbo.Implementor_HC;
if input.FieldPathExists('data.objname') and (input.FieldPath('data.objname').AsString<>dbo.Field('objname').AsString) then begin
zone:=_getZone(dbo,conn,true);
if hcObj is TFRE_DB_DATALINK_VNIC then begin
idx:=TFRE_DB_DATALINK_VNIC.ClassName + '_' + 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,'vnic_create_error_exists_cap'),FetchModuleTextShort(ses,'vnic_create_error_exists_msg'),fdbmt_error);
exit;
end;
end else
if hcObj is TFRE_DB_DATALINK then begin
idx:=hcObj.ClassName + '_' + 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,'datalink_modify_error_exists_cap'),StringReplace(FetchModuleTextShort(ses,'datalink_modify_error_exists_msg'),'%datalink_str%',(hcObj as TFRE_DB_DATALINK).GetCaption(conn),[rfReplaceAll]),fdbmt_error);
exit;
end;
end;
end;
if (hcObj is TFRE_DB_DATALINK_VNIC) then begin
if input.FieldPath('data.vlan').IsSpecialClearMarked or (input.FieldPath('data.vlan').AsUInt16=0) then begin
dbo.DeleteField('vid');
end else begin
dbo.Field('vid').AsObjectLink:=_getVLAN(conn,input.FieldPath('data.vlan').AsUInt16,dbo.DomainID);
end;
ips:=conn.GetReferences(dbo.UID,false,TFRE_DB_IPV4.ClassName,'datalinkParent');
for i := 0 to Length(ips) - 1 do begin
CheckDbResult(conn.Delete(ips[i]));
end;
ips:=conn.GetReferences(dbo.UID,false,TFRE_DB_IPV6.ClassName,'datalinkParent');
for i := 0 to Length(ips) - 1 do begin
CheckDbResult(conn.Delete(ips[i]));
end;
input.Field('data').AsObject.DeleteField('vlan');
end;
if (hcObj is TFRE_DB_IP) then begin //FIXXME
hnObjname:=input.FieldPath('data.ip').AsString;
if (hnObjname<>dbo.Field('objname').AsString) then begin
dbo.Field('objname').AsString:=hnObjname;
CheckDbResult(conn.Fetch(dbo.UID,parentDbo));
idx:=hcObj.ClassName + '_' + dbo.Field('objname').AsString + '@' + parentDbo.UID_String;
coll:=conn.GetCollection(CFRE_DB_IP_COLLECTION);
if coll.ExistsIndexedText(idx)<>0 then begin
Result:=TFRE_DB_MESSAGE_DESC.Create.Describe(FetchModuleTextShort(ses,'hostnet_modify_error_exists_cap'),FetchModuleTextShort(ses,'hostnet_modify_error_exists_msg'),fdbmt_error); //FIXXME
exit;
end;
end;
end;
GFRE_DBI.GetSystemSchemeByName(dbo.Implementor_HC.ClassName,scheme);
scheme.SetObjectFieldsWithScheme(input.Field('data').AsObject,dbo,false,conn);
CheckDbResult(conn.update(dbo));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._hasVLANChanged(const conn: IFRE_DB_CONNECTION; const input, dbo: IFRE_DB_Object; var newVlan: UInt16): Boolean;
var
vlan : UInt16;
fld,nfld : IFRE_DB_FIELD;
vlanObj : IFRE_DB_Object;
begin
vlan:=0;
if dbo.FieldOnlyExisting('vid',fld) then begin
CheckDbResult(conn.Fetch(fld.AsObjectLink,vlanObj));
vlan:=vlanObj.Field('number').AsUInt16;
end;
if input.FieldPathExists('data.vlan',nfld) then begin
if nfld.IsSpecialClearMarked then begin
newVlan:=0;
end else begin
newVlan:=nfld.AsInt16;
end;
end;
Result:=vlan<>newVlan;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD._getVLAN(const conn: IFRE_DB_CONNECTION; const vlanNumber: UInt16; const domain_id: TFRE_DB_GUID): TFRE_DB_GUID;
var
vlanColl: IFRE_DB_COLLECTION;
vlan : TFRE_DB_VLAN;
vlanDbo : IFRE_DB_Object;
begin
vlanColl:=conn.GetCollection(CFRE_DB_VLAN_COLLECTION);
vlan:=TFRE_DB_VLAN.CreateForDB;
vlan.Field('number').AsUInt16:=vlanNumber;
if vlanColl.GetIndexedObjFieldval(vlan.Field('number'),vlanDbo,'def',domain_id.AsHexString)=0 then begin
vlan.SetDomainID(domain_id);
CheckDbResult(vlanColl.Store(vlan.CloneToNewObject()));
Result:=vlan.UID;
end else begin
Result:=vlanDbo.UID;
end;
end;
class procedure TFRE_FIRMBOX_NET_ROUTING_MOD.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName('TFRE_DB_APPLICATION_MODULE');
end;
procedure TFRE_FIRMBOX_NET_ROUTING_MOD.SetupAppModuleStructure;
begin
inherited SetupAppModuleStructure;
InitModuleDesc('net_routing_description');
GFRE_DBI.RegisterFeature('ADVANCED_NETWORK');
fNetIPMod:=TFRE_FIRMBOX_SUBNET_IP_MOD.create;
AddApplicationModule(fNetIPMod);
end;
class procedure TFRE_FIRMBOX_NET_ROUTING_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,'net_routing_description','Networks','Networks','Networks');
CreateModuleText(conn,'grid_zone_name','Name');
CreateModuleText(conn,'grid_zone_status','Status');
CreateModuleText(conn,'grid_name','Name');
CreateModuleText(conn,'grid_mtu','MTU');
CreateModuleText(conn,'grid_vlan','VLAN');
CreateModuleText(conn,'grid_status','Status');
CreateModuleText(conn,'grid_delegation_zone','Delegated to');
CreateModuleText(conn,'grid_descr_delimiter',' - ');
CreateModuleText(conn,'grid_descr_forward','Forward enabled');
CreateModuleText(conn,'grid_descr_protection','Protection: %protection_str%');
CreateModuleText(conn,'grid_descr_speed','Speed: %speed_str%');
CreateModuleText(conn,'grid_descr_full_duplex','Full-duplex');
CreateModuleText(conn,'grid_descr_half_duplex','Half-duplex');
CreateModuleText(conn,'tb_add','Add');
CreateModuleText(conn,'tb_delete','Delete');
CreateModuleText(conn,'tb_delegate','Delegate');
CreateModuleText(conn,'tb_retract','Retract');
CreateModuleText(conn,'cm_delete','Delete');
CreateModuleText(conn,'cm_delegate','Delegate');
CreateModuleText(conn,'cm_retract','Retract');
CreateModuleText(conn,'tb_modify','Modify');
CreateModuleText(conn,'cm_modify','Modify');
CreateModuleText(conn,'tb_add_route','Add Route');
CreateModuleText(conn,'tb_add_vnic','Add VNIC');
CreateModuleText(conn,'cm_add_vnic','Add VNIC');
CreateModuleText(conn,'tb_aggregation','Aggregation');
CreateModuleText(conn,'tb_aggregation_move_to','Move to');
CreateModuleText(conn,'tb_aggregation_remove_from','Remove from');
CreateModuleText(conn,'cm_aggregation_move_to','Move to aggregation');
CreateModuleText(conn,'cm_aggregation_remove_from','Remove from aggregation');
CreateModuleText(conn,'tb_bridge','Bridge');
CreateModuleText(conn,'tb_bridge_move_to','Move to');
CreateModuleText(conn,'tb_bridge_remove_from','Remove from');
CreateModuleText(conn,'cm_bridge_move_to','Move to bridge');
CreateModuleText(conn,'cm_bridge_remove_from','Remove from bridge');
CreateModuleText(conn,'tb_ipmp','IPMP');
CreateModuleText(conn,'tb_ipmp_link_to','Link to');
CreateModuleText(conn,'tb_ipmp_unlink_from','Unlink from');
CreateModuleText(conn,'cm_ipmp_link_to','Link to IPMP');
CreateModuleText(conn,'cm_ipmp_unlink_from','Unlink from IPMP');
CreateModuleText(conn,'info_details_select_one','Please select an object to get detailed information about it.');
CreateModuleText(conn,'add_datalink_diag_cap','Add %datalink_str%');
CreateModuleText(conn,'add_vnic_diag_cap','Add VNIC');
CreateModuleText(conn,'add_vnic_diag_vlan','VLAN');
CreateModuleText(conn,'modify_vnic_diag_vlan','VLAN');
CreateModuleText(conn,'modify_vnic_vlan_msg_cap','Modfiy VNIC');
CreateModuleText(conn,'modify_vnic_vlan_msg_message','You have changed the VLAN. This will remove all IPs from the VNIC. Are you sure?');
CreateModuleText(conn,'datalink_create_error_exists_cap','Error: Add datalink');
CreateModuleText(conn,'datalink_create_error_exists_msg','A %datalink_str% datalink with the given name already exists!');
CreateModuleText(conn,'vnic_create_error_exists_cap','Error: Add VNIC');
CreateModuleText(conn,'vnic_create_error_exists_msg','A VNIC with the given name already exists within this zone!');
CreateModuleText(conn,'delete_datalink_diag_cap','Remove Datalink');
CreateModuleText(conn,'delete_datalink_diag_msg','Remove datalink "%datalink_str%"?');
CreateModuleText(conn,'error_delete_single_select','Exactly one object has to be selected for deletion.');
CreateModuleText(conn,'delegate_datalink_diag_cap','Delegate Interface');
CreateModuleText(conn,'delegate_datalink_diag_no_zone_msg','There are no zones available for delgation.');
CreateModuleText(conn,'delegate_datalink_diag_zone','Zone');
CreateModuleText(conn,'delegate_interface_zone_value','%zone_str% (%service_obj_str%)');
CreateModuleText(conn,'delegate_interface_zone_value_no_service_obj','%zone_str%');
CreateModuleText(conn,'retract_datalink_diag_cap','Retract Datalink');
CreateModuleText(conn,'retract_datalink_diag_msg','Remove the delegation of datalink "%datalink_str%"?');
CreateModuleText(conn,'move_to_aggregation_diag_cap','Move to Aggregation');
CreateModuleText(conn,'move_to_aggregation_chooser_cap','Aggregation');
CreateModuleText(conn,'move_to_bridge_diag_cap','Move to Bridge');
CreateModuleText(conn,'move_to_bridge_chooser_cap','Bridge');
CreateModuleText(conn,'link_to_ipmp_diag_cap','Link to IPMP');
CreateModuleText(conn,'link_to_ipmp_chooser_cap','IPMP');
CreateModuleText(conn,'add_route_diag_cap','Add Route');
CreateModuleText(conn,'add_route_diag_type','Type');
CreateModuleText(conn,'add_route_diag_type_ipv4','IPv4');
CreateModuleText(conn,'add_route_diag_type_ipv4_default','Default IPv4');
CreateModuleText(conn,'add_route_diag_type_ipv6','IPv6');
CreateModuleText(conn,'add_route_diag_type_ipv6_default','Default IPv6');
CreateModuleText(conn,'modify_datalink_diag_cap','Modify %datalink_str%');
CreateModuleText(conn,'modify_diag_cap','Modify');
CreateModuleText(conn,'datalink_modify_error_exists_cap','Error: Modify datalink');
CreateModuleText(conn,'datalink_modify_error_exists_msg','A %datalink_str% datalink with the given name already exists!');
CreateModuleText(conn,'vnic_modify_error_exists_cap','Error: Modify VNIC');
CreateModuleText(conn,'vnic_modify_error_exists_msg','A VNIC with the given name already exists within this zone!');
CreateModuleText(conn,'add_ip_diag_cap','Add IP');
CreateModuleText(conn,'add_ip_diag_ip_block','IP');
CreateModuleText(conn,'add_ip_diag_new_ip_button','New');
CreateModuleText(conn,'tb_add_ip','Add IP');
CreateModuleText(conn,'tb_add_ip_ipv4','IPv4');
CreateModuleText(conn,'tb_add_ip_ipv6','IPv6');
CreateModuleText(conn,'cm_add_ip_ipv4','Add IPv4');
CreateModuleText(conn,'cm_add_ip_ipv6','Add IPv6');
CreateModuleText(conn,'tb_add_ip_ipv4_dhcp','IPv4 DHCP');
CreateModuleText(conn,'tb_add_ip_ipv6_slaac','IPv6 SLAAC');
CreateModuleText(conn,'cm_add_ip_ipv4_dhcp','Add IPv4 DHCP');
CreateModuleText(conn,'cm_add_ip_ipv6_slaac','Add IPv6 SLAAC');
CreateModuleText(conn,'ip_subnet_chooser_value','(%base_ip_str%/%bits_str%)');
CreateModuleText(conn,'route_create_error_exists_cap','Error: Add Route');
CreateModuleText(conn,'route_create_error_exists_msg','The route already exists within this zone!');
end;
end;
procedure TFRE_FIRMBOX_NET_ROUTING_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;
i : Integer;
filterClasses : TFRE_DB_StringArray;
ipFilterClasses: TFRE_DB_StringArray;
langres : TFRE_DB_StringArray;
procedure _calcIcon(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
begin
transformed_object.Field('icon').AsString:=FREDB_getThemedResource('images_apps/classicons/'+LowerCase(transformed_object.Field('sc').AsString)+'.svg');
end;
procedure _setZGridFields(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
var
zplugin: TFRE_DB_ZONESTATUS_PLUGIN;
begin
_calcIcon(input,transformed_object,[]);
if input.IsA(TFRE_DB_GLOBAL_ZONE) then begin
transformed_object.Field('_sortorder_').AsString:='A'+input.Field('objname').AsString;
end else begin
transformed_object.Field('_sortorder_').AsString:='B'+input.Field('objname').AsString;
end;
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;
procedure _setIPSubnetLabel(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
begin
transformed_object.Field('label').AsString:=input.Field('ip').AsString + ' ' + StringReplace(StringReplace(langres[0],'%base_ip_str%',transformed_object.Field('bip').AsString,[rfReplaceAll]),'%bits_str%',transformed_object.Field('bits').AsString,[rfReplaceAll]);
end;
procedure _calcZoneChooserLabel(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
var
str: String;
begin
if transformed_object.Field('serviceObj').AsString<>'' then begin
str:=StringReplace(langres[0],'%zone_str%',transformed_object.Field('objname').AsString,[rfReplaceAll]);
str:=StringReplace(str,'%service_obj_str%',transformed_object.Field('serviceObj').AsString,[rfReplaceAll]);
end else begin
str:=StringReplace(langres[1],'%zone_str%',transformed_object.Field('objname').AsString,[rfReplaceAll]);
end;
transformed_object.Field('label').AsString:=str;
end;
procedure _calcDatalinkFields(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
var
fld : IFRE_DB_FIELD;
delimiter : String;
plugin : TFRE_DB_DATALINKSTATUS_PLUGIN;
begin
_calcIcon(input,transformed_object,[]);
if not input.IsA(TFRE_DB_IP_ROUTE) then begin //do not display status for routes
G_setServiceStatusFields(input,transformed_object,langres);
end;
delimiter:='';
if input.FieldOnlyExistingBoolean('forward') then begin
delimiter:=langres[Length(langres)-6];
transformed_object.Field('descr').AsString:=langres[Length(langres)-5];
end;
if transformed_object.FieldOnlyExisting('protection',fld) then begin
delimiter:=langres[Length(langres)-6];
transformed_object.Field('descr').AsString:=transformed_object.Field('descr').AsString+delimiter+StringReplace(langres[Length(langres)-4],'%protection_str%',fld.AsString,[rfReplaceAll]);
end;
if input.HasPlugin(TFRE_DB_DATALINKSTATUS_PLUGIN,plugin) then begin
if plugin.FieldOnlyExisting('speed',fld) then begin
delimiter:=langres[Length(langres)-6];
transformed_object.Field('descr').AsString:=transformed_object.Field('descr').AsString+delimiter+StringReplace(langres[Length(langres)-3],'%speed_str%',fld.AsString,[rfReplaceAll]);
end;
if plugin.FieldOnlyExisting('fullduplex',fld) then begin
if fld.AsBoolean then begin
transformed_object.Field('descr').AsString:=transformed_object.Field('descr').AsString+delimiter+langres[Length(langres)-2];
end else begin
transformed_object.Field('descr').AsString:=transformed_object.Field('descr').AsString+delimiter+langres[Length(langres)-1];
end;
end;
end;
end;
begin
inherited MySessionInitializeModule(session);
if session.IsInteractiveSession then begin
app := GetEmbeddingApp;
conn := session.GetDBConnection;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname','',FetchModuleTextShort(session,'grid_zone_name'),dt_string,true,false,false,true,1,'icon');
AddOneToOnescheme('status_icon','',FetchModuleTextShort(session,'grid_zone_status'),dt_icon,true,false,false,true,1,'','','',nil,'status_icon_tooltip');
AddOneToOnescheme('_sortorder_','','',dt_string,false);
AddOneToOnescheme('status_icon_tooltip','','',dt_string,false);
AddMatchingReferencedField(['<SERVICEDOMAIN'],'objname','serviceObj','',true,dt_description,false,false,1,'','',nil,'',false,'domainid');
AddMatchingReferencedField(['TEMPLATEID>'+TFRE_DB_FBZ_TEMPLATE.ClassName],'unknown','utempl','',false,dt_boolean,false,false,1,'','false');
AddOneToOnescheme('schemeclass','sc','',dt_string,false);
AddOneToOnescheme('icon','','',dt_string,false);
SetSimpleFuncTransformNested(@_setZGridFields,TFRE_DB_ZONESTATUS_PLUGIN.getZoneStatusLangRes(conn));
end;
dc := session.NewDerivedCollection('NET_ZONES_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.HasFeature('DOMAIN') then begin
SetParentToChildLinkField ('<SERVICEPARENT',[TFRE_DB_ZFS_POOL.ClassName,TFRE_DB_ZFS_DATASET_FILESYSTEM.ClassName,TFRE_DB_ZFS_ZONE_CONTAINER_DATASET.ClassName],[],[TFRE_DB_GLOBAL_ZONE.ClassName,TFRE_DB_ZONE.ClassName]);
end else begin
SetParentToChildLinkField ('<SERVICEPARENT',[TFRE_DB_DATACENTER.ClassName,TFRE_DB_MACHINE.ClassName,TFRE_DB_ZFS_POOL.ClassName,TFRE_DB_ZFS_DATASET_FILESYSTEM.ClassName,TFRE_DB_ZFS_ZONE_CONTAINER_DATASET.ClassName],[],[TFRE_DB_GLOBAL_ZONE.ClassName,TFRE_DB_ZONE.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]);
Filters.AddBooleanFieldFilter('utempl','utempl',true,false);
SetDefaultOrderField('_sortorder_',true);
end;
filterClasses:=TFRE_DB_DATALINK.getAllDataLinkClasses;
ipFilterClasses:=TFRE_DB_IP.getAllIPClasses;
for i := 0 to High(ipFilterClasses) do begin
SetLength(filterClasses,Length(filterClasses)+1);
filterClasses[Length(filterClasses)-1]:=ipFilterClasses[i];
end;
ipFilterClasses:=TFRE_DB_IP_ROUTE.getAllRouteClasses;
for i := 0 to High(ipFilterClasses) do begin
SetLength(filterClasses,Length(filterClasses)+1);
filterClasses[Length(filterClasses)-1]:=ipFilterClasses[i];
end;
ipFilterClasses:=TFRE_DB_IP_SUBNET.getAllSubnetClasses;
for i := 0 to High(ipFilterClasses) do begin
SetLength(filterClasses,Length(filterClasses)+1);
filterClasses[Length(filterClasses)-1]:=ipFilterClasses[i];
end;
SetLength(filterClasses,Length(filterClasses)+2);
filterClasses[Length(filterClasses)-2]:=TFRE_DB_ZONE.ClassName;
filterClasses[Length(filterClasses)-1]:=TFRE_DB_GLOBAL_ZONE.ClassName;
langres:=TFRE_DB_SERVICE_STATUS_PLUGIN.getStatusLangres(conn);
SetLength(langres,Length(langres)+6);
langres[Length(langres)-6]:=FetchModuleTextShort(session,'grid_descr_delimiter');
langres[Length(langres)-5]:=FetchModuleTextShort(session,'grid_descr_forward');
langres[Length(langres)-4]:=FetchModuleTextShort(session,'grid_descr_protection');
langres[Length(langres)-3]:=FetchModuleTextShort(session,'grid_descr_speed');
langres[Length(langres)-2]:=FetchModuleTextShort(session,'grid_descr_full_duplex');
langres[Length(langres)-1]:=FetchModuleTextShort(session,'grid_descr_half_duplex');
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname','',FetchModuleTextShort(session,'grid_name'),dt_string,true,false,false,true,2,'icon');
AddOneToOnescheme('mtu','',FetchModuleTextShort(session,'grid_mtu'),dt_number,true,false,false,true);
AddMatchingReferencedField(['VID>TFRE_DB_VLAN'],'number','vlan',FetchModuleTextShort(session,'grid_vlan'),true,dt_number);
AddOneToOnescheme('protection','','',dt_string,false);
AddMatchingReferencedField(['DATALINKPARENT>TFRE_DB_ZONE'],'objname','czone',FetchModuleTextShort(session,'grid_delegation_zone'),true,dt_string,false,false,1,'','',nil,'',false,'uid',false);
AddOneToOnescheme('status_icons','',FetchModuleTextShort(session,'grid_status'),dt_icon,true,false,false,true,1,'','','',nil,'status_icon_tooltips');
AddOneToOnescheme('descr','','',dt_description);
AddMatchingReferencedField(['DATALINKPARENT>TFRE_DB_GLOBAL_ZONE'],'uid','zuid','',false);
AddMatchingReferencedObjPlugin(['DATALINKPARENT>>TFRE_DB_GLOBAL_ZONE'],TFRE_DB_ZONESTATUS_PLUGIN,'zplugin');
AddOneToOnescheme('schemeclass','sc','',dt_string,false);
AddOneToOnescheme('serviceparent','','',dt_string,false);
AddOneToOnescheme('icon','','',dt_string,false);
SetSimpleFuncTransformNested(@_calcDatalinkFields,langres);
end;
dc := session.NewDerivedCollection('DATALINK_GRID_GZ');
with dc do begin
SetDeriveParent(conn.GetCollection(CFOS_DB_ZONES_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Listview,[cdgf_Children],'',CWSF(@WEB_DatalinkGridMenu),nil,CWSF(@WEB_DatalinkGridSC));
SetParentToChildLinkField ('<DATALINKPARENT',[TFRE_DB_GLOBAL_ZONE.ClassName,TFRE_DB_ZONE.ClassName]);
Filters.AddSchemeObjectFilter('schemes',filterClasses);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname','',FetchModuleTextShort(session,'grid_name'),dt_string,true,false,false,true,2,'icon');
AddOneToOnescheme('mtu','',FetchModuleTextShort(session,'grid_mtu'),dt_number);
AddMatchingReferencedField(['VID>TFRE_DB_VLAN'],'number','vlan',FetchModuleTextShort(session,'grid_vlan'),true,dt_number);
AddOneToOnescheme('protection','','',dt_string,false);
AddOneToOnescheme('status_icons','',FetchModuleTextShort(session,'grid_status'),dt_icon,true,false,false,true,1,'','','',nil,'status_icon_tooltips');
AddOneToOnescheme('descr','','',dt_description);
AddMatchingReferencedField(['DATALINKPARENT>TFRE_DB_ZONE'],'uid','zuid','',false);
AddMatchingReferencedObjPlugin(['DATALINKPARENT>>TFRE_DB_ZONE'],TFRE_DB_ZONESTATUS_PLUGIN,'zplugin');
AddOneToOnescheme('schemeclass','sc','',dt_string,false);
AddOneToOnescheme('serviceparent','','',dt_string,false);
AddOneToOnescheme('icon','','',dt_string,false);
SetSimpleFuncTransformNested(@_calcDatalinkFields,langres);
end;
dc := session.NewDerivedCollection('DATALINK_GRID');
with dc do begin
SetDeriveParent(conn.GetCollection(CFOS_DB_ZONES_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Listview,[cdgf_Children],'',CWSF(@WEB_DatalinkGridMenu),nil,CWSF(@WEB_DatalinkGridSC));
SetParentToChildLinkField ('<DATALINKPARENT',[TFRE_DB_GLOBAL_ZONE.ClassName,TFRE_DB_ZONE.ClassName]);
Filters.AddSchemeObjectFilter('schemes',filterClasses);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('label');
AddOneToOnescheme('objname');
AddMatchingReferencedField(['<SERVICEDOMAIN'],'objname','serviceObj','',true,dt_string,true,true,1,'','',nil,'',false,'domainid');
AddMatchingReferencedField(['TEMPLATEID>'+TFRE_DB_FBZ_TEMPLATE.ClassName],'unknown','utempl','',false,dt_boolean,false,false,1,'','false');
AddOneToOnescheme('hostid');
SetSimpleFuncTransformNested(@_calcZoneChooserLabel,[FetchModuleTextShort(session,'delegate_interface_zone_value'),FetchModuleTextShort(session,'delegate_interface_zone_value_no_service_obj')]);
end;
dc := session.NewDerivedCollection('ZONE_CHOOSER');
with dc do begin
SetDeriveParent(conn.GetCollection(CFOS_DB_ZONES_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('label',true);
Filters.AddSchemeObjectFilter('scheme',[TFRE_DB_GLOBAL_ZONE.ClassName],false);
Filters.AddBooleanFieldFilter('utempl','utempl',true,false);
Filters.AddStdClassRightFilter('rightsip4','domainid','','',TFRE_DB_IPV4.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
Filters.AddStdClassRightFilter('rightsip6','domainid','','',TFRE_DB_IPV6.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
Filters.AddStdClassRightFilter('rightsdhcp','domainid','','',TFRE_DB_IPV4_DHCP.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
Filters.AddStdClassRightFilter('rightsslaac','domainid','','',TFRE_DB_IPV6_SLAAC.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname');
AddMatchingReferencedField(['DATALINKPARENT>'],'uid','zid');
end;
dc := session.NewDerivedCollection('AGGREGATION_CHOOSER');
with dc do begin
SetDeriveParent(conn.GetCollection(CFOS_DB_SERVICES_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('objname',true);
Filters.AddSchemeObjectFilter('scheme',[TFRE_DB_DATALINK_AGGR.ClassName]);
Filters.AddStdClassRightFilter('rightsvnic','domainid','','',TFRE_DB_DATALINK_VNIC.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
Filters.AddStdClassRightFilter('rightsip4','domainid','','',TFRE_DB_IPV4.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
Filters.AddStdClassRightFilter('rightsip6','domainid','','',TFRE_DB_IPV6.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
Filters.AddStdClassRightFilter('rightsdhcp','domainid','','',TFRE_DB_IPV4_DHCP.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
Filters.AddStdClassRightFilter('rightsslaac','domainid','','',TFRE_DB_IPV6_SLAAC.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname');
AddMatchingReferencedField(['DATALINKPARENT>'],'uid','zid');
end;
dc := session.NewDerivedCollection('BRIDGE_CHOOSER');
with dc do begin
SetDeriveParent(conn.GetCollection(CFOS_DB_SERVICES_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('objname',true);
Filters.AddSchemeObjectFilter('scheme',[TFRE_DB_DATALINK_BRIDGE.ClassName]);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('objname');
AddMatchingReferencedField(['DATALINKPARENT>'],'uid','zid');
end;
dc := session.NewDerivedCollection('IPMP_CHOOSER');
with dc do begin
SetDeriveParent(conn.GetCollection(CFOS_DB_SERVICES_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('objname',true);
Filters.AddSchemeObjectFilter('scheme',[TFRE_DB_DATALINK_IPMP.ClassName]);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('ip','label');
AddOneToOnescheme('ip_type');
AddOneToOnescheme('domainid');
AddMatchingReferencedField(['SUBNET>','VID>TFRE_DB_VLAN'],'uid','vid','',true,dt_string,false,false,1,'',CFRE_DB_NullGUID.AsHexString);
end;
dc := session.NewDerivedCollection('IPV4_CHOOSER');
with dc do begin
SetDeriveParent(conn.GetCollection(CFRE_DB_IP_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('label',true);
Filters.AddSchemeObjectFilter('scheme',[TFRE_DB_IPV4.ClassName]);
Filters.AddStringFieldFilter('type','ip_type','IP',dbft_EXACT);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOneToOnescheme('ip','label');
AddOneToOnescheme('ip_type');
AddOneToOnescheme('domainid');
AddMatchingReferencedField(['SUBNET>','VID>TFRE_DB_VLAN'],'uid','vid','',true,dt_string,false,false,1,'',CFRE_DB_NullGUID.AsHexString);
end;
dc := session.NewDerivedCollection('IPV6_CHOOSER');
with dc do begin
SetDeriveParent(conn.GetCollection(CFRE_DB_IP_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('label',true);
Filters.AddSchemeObjectFilter('scheme',[TFRE_DB_IPV6.ClassName]);
Filters.AddStringFieldFilter('type','ip_type','IP',dbft_EXACT);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOutputFieldUntransformed('label');
AddOneToOnescheme('ip');
AddOneToOnescheme('ip_type');
AddOneToOnescheme('domainid');
AddMatchingReferencedField(['SUBNET>','BASE_IP>'],'ip','bip');
AddMatchingReferencedField(['SUBNET>'],'subnet_bits','bits');
AddMatchingReferencedField(['SUBNET>','VID>TFRE_DB_VLAN'],'uid','vid','',true,dt_string,false,false,1,'',CFRE_DB_NullGUID.AsHexString);
SetSimpleFuncTransformNested(@_setIPSubnetLabel,[FetchModuleTextShort(session,'ip_subnet_chooser_value')]);
end;
dc := session.NewDerivedCollection('IPV4_SUBNET_CHOOSER');
with dc do begin
SetDeriveParent(conn.GetCollection(CFRE_DB_IP_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('label',true);
Filters.AddSchemeObjectFilter('scheme',[TFRE_DB_IPV4.ClassName]);
Filters.AddStringFieldFilter('type','ip_type','IP',dbft_EXACT);
end;
GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform);
with transform do begin
AddOutputFieldUntransformed('label');
AddOneToOnescheme('ip');
AddOneToOnescheme('ip_type');
AddOneToOnescheme('domainid');
AddMatchingReferencedField(['SUBNET>','BASE_IP>'],'ip','bip');
AddMatchingReferencedField(['SUBNET>'],'subnet_bits','bits');
AddMatchingReferencedField(['SUBNET>','VID>TFRE_DB_VLAN'],'uid','vid','',true,dt_string,false,false,1,'',CFRE_DB_NullGUID.AsHexString);
SetSimpleFuncTransformNested(@_setIPSubnetLabel,[FetchModuleTextShort(session,'ip_subnet_chooser_value')]);
end;
dc := session.NewDerivedCollection('IPV6_SUBNET_CHOOSER');
with dc do begin
SetDeriveParent(conn.GetCollection(CFRE_DB_IP_COLLECTION));
SetDeriveTransformation(transform);
SetDisplayType(cdt_Chooser,[],'');
SetDefaultOrderField('label',true);
Filters.AddSchemeObjectFilter('scheme',[TFRE_DB_IPV6.ClassName]);
Filters.AddStringFieldFilter('type','ip_type','IP',dbft_EXACT);
end;
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_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
res : TFRE_DB_LAYOUT_DESC;
grid : TFRE_DB_VIEW_LIST_DESC;
begin
CheckClassVisibility4AnyDomain(ses);
ses.GetSessionModuleData(ClassName).DeleteField('selected');
ses.GetSessionModuleData(ClassName).DeleteField('selectedExt');
grid:=ses.FetchDerivedCollection('NET_ZONES_GRID').GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC;
res:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(grid,_getDetails(input,ses,app,conn),nil,nil,nil,true,1,2);
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_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
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 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_datalink_diag_cap'),'%datalink_str%',conf.Field('caption').AsString,[rfReplaceAll]),600,true,true,false);
GFRE_DBI.GetSystemSchemeByName(serviceClass,scheme);
res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses);
sf:=CWSF(@WEB_Store);
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;
function TFRE_FIRMBOX_NET_ROUTING_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;
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;
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,'datalink_create_error_exists_cap'),StringReplace(FetchModuleTextShort(ses,'datalink_create_error_exists_msg'),'%datalink_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('datalinkParent').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));
_updateDatalinkGridTB(input,ses,app,conn);
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_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 input.FieldExists('selectedExt') then begin
input.Field('selectedExt').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selectedExt').AsStringArr;
end;
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canDelete(input,ses,conn) 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);
sf.AddParam.Describe('selectedExt',input.Field('selectedExt').AsStringArr);
cap:=FetchModuleTextShort(ses,'delete_datalink_diag_cap');
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsStringArr[0]),dbo));
msg:=StringReplace(FetchModuleTextShort(ses,'delete_datalink_diag_msg'),'%datalink_str%',dbo.Field('objname').AsString,[rfReplaceAll]);
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(cap,msg,fdbmt_confirm,sf);
end;
function TFRE_FIRMBOX_NET_ROUTING_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;
path : String;
parentDbo : IFRE_DB_Object;
begin
if not _canDelete(input,ses,conn) 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('selectedExt').ValueCount-1 do begin
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsStringArr[i]),dbo));
if dbo.IsA(TFRE_DB_IPV4) or dbo.IsA(TFRE_DB_IPV6) then begin //in case of an ip only remove the links
path:=GFRE_BT.SepRight(input.Field('selectedExt').AsStringArr[i],'@');
CheckDbResult(conn.Fetch(FREDB_H2G(GFRE_BT.SepLeft(path,'@')),parentDbo));
dbo.Field('serviceParent').RemoveObjectLinkByUID(parentDbo.UID);
dbo.Field('datalinkParent').RemoveObjectLinkByUID(parentDbo.UID);
CheckDbResult(conn.Update(dbo));
end else begin
CheckDbResult(conn.Delete(dbo.UID));
end;
end;
ses.GetSessionModuleData(ClassName).DeleteField('selected');
ses.GetSessionModuleData(ClassName).DeleteField('selectedExt');
end;
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_Modify(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;
cap : String;
res : TFRE_DB_FORM_DIALOG_DESC;
scheme : IFRE_DB_SchemeObject;
sf : TFRE_DB_SERVER_FUNC_DESC;
mtu_input : TFRE_DB_CONTENT_DESC;
fld : IFRE_DB_FIELD;
num : TFRE_DB_INPUT_NUMBER_DESC;
vlanVal : String;
vlanObj : IFRE_DB_Object;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canModify(input,ses,conn) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if dbo.Implementor_HC is TFRE_DB_DATALINK then begin
cap:=StringReplace(FetchModuleTextShort(ses,'modify_datalink_diag_cap'),'%datalink_str%',(dbo.Implementor_HC as TFRE_DB_DATALINK).GetCaption(conn),[rfReplaceAll]);
end else begin
cap:=FetchModuleTextShort(ses,'modify_diag_cap');
end;
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(cap,600,true,true,false);
GFRE_DBI.GetSystemSchemeByName(dbo.Implementor_HC.ClassName,scheme);
res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses);
res.FillWithObjectValues(dbo,ses);
mtu_input:=res.GetFormElement('mtu');
if Assigned(mtu_input) then begin
if dbo.FieldOnlyExisting('mtu_min',fld) then begin
(mtu_input.Implementor_HC as TFRE_DB_INPUT_NUMBER_DESC).setMin(fld.AsUInt32);
end;
if dbo.FieldOnlyExisting('mtu_max',fld) then begin
(mtu_input.Implementor_HC as TFRE_DB_INPUT_NUMBER_DESC).setMax(fld.AsUInt32);
end;
end;
if dbo.Implementor_HC is TFRE_DB_DATALINK_VNIC then begin
if dbo.FieldOnlyExisting('vid',fld) then begin
CheckDbResult(conn.Fetch(fld.AsObjectLink,vlanObj));
vlanVal:=vlanObj.Field('number').AsString;
end else begin
vlanVal:='';
end;
num:=res.AddNumber.Describe(FetchModuleTextShort(ses,'modify_vnic_diag_vlan'),'vlan',false,false,false,false,vlanVal,0);
num.setMin(0);
end;
sf:=CWSF(@WEB_StoreModify);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit);
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_StoreModify(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;
newVlan : UInt16;
sf : TFRE_DB_SERVER_FUNC_DESC;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canModify(input,ses,conn) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo));
if dbo.IsA(TFRE_DB_DATALINK_VNIC) then begin
if ((conn.GetReferencesCount(dbo.UID,false,TFRE_DB_IPV4.ClassName,'datalinkParent')>0) or (conn.GetReferencesCount(dbo.UID,false,TFRE_DB_IPV6.ClassName,'datalinkParent')>0)) and
_hasVLANChanged(conn,input,dbo,newVlan) then begin
ses.GetSessionModuleData(ClassName).Field('modifyData').AsObject:=input.Field('data').AsObject.CloneToNewObject();
sf:=CWSF(@WEB_StoreModifyConfirmed);
sf.AddParam.Describe('selected',dbo.UID_String);
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'modify_vnic_vlan_msg_cap'),FetchModuleTextShort(ses,'modify_vnic_vlan_msg_message'),fdbmt_confirm,sf);
end else begin
Result:=_storeModify(input,ses,app,conn);
end;
end else begin
Result:=_storeModify(input,ses,app,conn);
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_StoreModifyConfirmed(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 input.field('confirmed').AsBoolean then begin
input.Field('data').AsObject:=ses.GetSessionModuleData(ClassName).Field('modifyData').AsObject.CloneToNewObject();
Result:=_storeModify(input,ses,app,conn);
end else begin
Result:=GFRE_DB_NIL_DESC;
end;
ses.GetSessionModuleData(ClassName).DeleteField('modifyData');
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_AddRoute(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;
sf : TFRE_DB_SERVER_FUNC_DESC;
zone : IFRE_DB_Object;
store : TFRE_DB_STORE_DESC;
ch : TFRE_DB_INPUT_CHOOSER_DESC;
dc : IFRE_DB_DERIVED_COLLECTION;
block : TFRE_DB_INPUT_BLOCK_DESC;
addIPSf : TFRE_DB_SERVER_FUNC_DESC;
begin
conn.Fetch(FREDB_H2G(input.Field('zoneId').AsString),zone);
if not (conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV4_ROUTE,zone.DomainID) or conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV6_ROUTE,zone.DomainID)) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'add_route_diag_cap'),600,true,true,false);
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_IPV4.ClassName,scheme); //fixxme
store:=TFRE_DB_STORE_DESC.create.Describe('id');
ch:=res.AddChooser.Describe(FetchModuleTextShort(ses,'add_route_diag_type'),'type',store,dh_chooser_combo,true,false,true);
if conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV4_ROUTE,zone.DomainID) and conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV4_SUBNET,zone.DomainID) and conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV4,zone.DomainID) then begin
//add ipv4 default
store.AddEntry.Describe(FetchModuleTextShort(ses,'add_route_diag_type_ipv4_default'),'ipv4default');
block:=res.AddBlock.Describe(FetchModuleTextShort(ses,'add_ip_diag_ip_block'),'ipv4default');
dc := ses.FetchDerivedCollection('IPV4_CHOOSER');
dc.Filters.RemoveFilter('domain');
dc.Filters.AddUIDFieldFilter('domain','domainid',zone.DomainID,dbnf_OneValueFromFilter);
block.AddChooser().Describe('','ipv4default.ip',dc.GetStoreDescription as TFRE_DB_STORE_DESC,dh_chooser_combo,true,false,true);
addIPSf:=CWSF(@fNetIPMod.WEB_AddIP);
addIPSf.AddParam.Describe('cbclass',self.ClassName);
addIPSf.AddParam.Describe('cbuidpath',FREDB_CombineString(self.GetUIDPath,','));
addIPSf.AddParam.Describe('cbfunc','AddRoute');
addIPSf.AddParam.Describe('cbparamnames','zoneId');
addIPSf.AddParam.Describe('cbparamvalues',zone.UID_String);
addIPSf.AddParam.Describe('selected',zone.UID_String);
addIPSf.AddParam.Describe('field','ipv4default.ip');
addIPSf.AddParam.Describe('ipversion','ipv4');
dc.Filters.RemoveFilter('vlan');
dc.Filters.AddUIDFieldFilter('vlan','vid',CFRE_DB_NullGUID,dbnf_OneValueFromFilter);
block.AddInputButton(3).Describe('',FetchModuleTextShort(ses,'add_ip_diag_new_ip_button'),addIPSf,true);
ch.addDependentInput('ipv4default','ipv4default',fdv_visible);
//add ipv4
store.AddEntry.Describe(FetchModuleTextShort(ses,'add_route_diag_type_ipv4'),'ipv4');
block:=res.AddBlock.Describe(FetchModuleTextShort(ses,'add_ip_diag_ip_block'),'ipv4');
dc := ses.FetchDerivedCollection('IPV4_SUBNET_CHOOSER');
dc.Filters.RemoveFilter('domain');
dc.Filters.AddUIDFieldFilter('domain','domainid',zone.DomainID,dbnf_OneValueFromFilter);
block.AddChooser().Describe('','ipv4.ip',dc.GetStoreDescription as TFRE_DB_STORE_DESC,dh_chooser_combo,true,false,true);
addIPSf:=CWSF(@fNetIPMod.WEB_AddIP);
addIPSf.AddParam.Describe('cbclass',self.ClassName);
addIPSf.AddParam.Describe('cbuidpath',FREDB_CombineString(self.GetUIDPath,','));
addIPSf.AddParam.Describe('cbfunc','AddRoute');
addIPSf.AddParam.Describe('cbparamnames','zoneId');
addIPSf.AddParam.Describe('cbparamvalues',zone.UID_String);
addIPSf.AddParam.Describe('selected',zone.UID_String);
addIPSf.AddParam.Describe('field','ipv4.ip');
addIPSf.AddParam.Describe('ipversion','ipv4');
dc.Filters.RemoveFilter('vlan');
dc.Filters.AddUIDFieldFilter('vlan','vid',CFRE_DB_NullGUID,dbnf_OneValueFromFilter);
block.AddInputButton(3).Describe('',FetchModuleTextShort(ses,'add_ip_diag_new_ip_button'),addIPSf,true);
ch.addDependentInput('ipv4','ipv4',fdv_visible);
end;
if conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV6_ROUTE,zone.DomainID) and conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV6_SUBNET,zone.DomainID) and conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV6,zone.DomainID) then begin
//add ipv6 default
store.AddEntry.Describe(FetchModuleTextShort(ses,'add_route_diag_type_ipv6_default'),'ipv6default');
block:=res.AddBlock.Describe(FetchModuleTextShort(ses,'add_ip_diag_ip_block'),'ipv6default');
dc := ses.FetchDerivedCollection('IPV6_CHOOSER');
dc.Filters.RemoveFilter('domain');
dc.Filters.AddUIDFieldFilter('domain','domainid',zone.DomainID,dbnf_OneValueFromFilter);
block.AddChooser().Describe('','ipv6default.ip',dc.GetStoreDescription as TFRE_DB_STORE_DESC,dh_chooser_combo,true,false,true);
addIPSf:=CWSF(@fNetIPMod.WEB_AddIP);
addIPSf.AddParam.Describe('cbclass',self.ClassName);
addIPSf.AddParam.Describe('cbuidpath',FREDB_CombineString(self.GetUIDPath,','));
addIPSf.AddParam.Describe('cbfunc','AddRoute');
addIPSf.AddParam.Describe('cbparamnames','zoneId');
addIPSf.AddParam.Describe('cbparamvalues',zone.UID_String);
addIPSf.AddParam.Describe('selected',zone.UID_String);
addIPSf.AddParam.Describe('field','ipv6default.ip');
addIPSf.AddParam.Describe('ipversion','ipv6');
dc.Filters.RemoveFilter('vlan');
dc.Filters.AddUIDFieldFilter('vlan','vid',CFRE_DB_NullGUID,dbnf_OneValueFromFilter);
block.AddInputButton(3).Describe('',FetchModuleTextShort(ses,'add_ip_diag_new_ip_button'),addIPSf,true);
ch.addDependentInput('ipv6default','ipv6default',fdv_visible);
//add ipv6
store.AddEntry.Describe(FetchModuleTextShort(ses,'add_route_diag_type_ipv6'),'ipv6');
block:=res.AddBlock.Describe(FetchModuleTextShort(ses,'add_ip_diag_ip_block'),'ipv6');
dc := ses.FetchDerivedCollection('IPV6_SUBNET_CHOOSER');
dc.Filters.RemoveFilter('domain');
dc.Filters.AddUIDFieldFilter('domain','domainid',zone.DomainID,dbnf_OneValueFromFilter);
block.AddChooser().Describe('','ipv6.ip',dc.GetStoreDescription as TFRE_DB_STORE_DESC,dh_chooser_combo,true,false,true);
addIPSf:=CWSF(@fNetIPMod.WEB_AddIP);
addIPSf.AddParam.Describe('cbclass',self.ClassName);
addIPSf.AddParam.Describe('cbuidpath',FREDB_CombineString(self.GetUIDPath,','));
addIPSf.AddParam.Describe('cbfunc','AddRoute');
addIPSf.AddParam.Describe('cbparamnames','zoneId');
addIPSf.AddParam.Describe('cbparamvalues',zone.UID_String);
addIPSf.AddParam.Describe('selected',zone.UID_String);
addIPSf.AddParam.Describe('field','ipv6.ip');
addIPSf.AddParam.Describe('ipversion','ipv6');
dc.Filters.RemoveFilter('vlan');
dc.Filters.AddUIDFieldFilter('vlan','vid',CFRE_DB_NullGUID,dbnf_OneValueFromFilter);
block.AddInputButton(3).Describe('',FetchModuleTextShort(ses,'add_ip_diag_new_ip_button'),addIPSf,true);
ch.addDependentInput('ipv6','ipv6',fdv_visible);
end;
sf:=CWSF(@WEB_StoreRoute);
sf.AddParam.Describe('zoneId',zone.UID_String);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit);
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_StoreRoute(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 : IFRE_DB_Object;
coll : IFRE_DB_COLLECTION;
ipv4 : Boolean;
route : TFRE_DB_IP_ROUTE;
gateway : IFRE_DB_Object;
subnet: IFRE_DB_Object;
baseIp: IFRE_DB_Object;
begin
conn.Fetch(FREDB_H2G(input.Field('zoneId').AsString),zone);
if not input.FieldPathExists('data.type') then
raise EFRE_DB_Exception.Create('Missing input parameter type!');
ipv4:=(input.FieldPath('data.type').AsString='ipv4') or (input.FieldPath('data.type').AsString='ipv4default');
if ipv4 and not conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV4_ROUTE,zone.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if not ipv4 and not conn.SYS.CheckClassRight4DomainId(sr_STORE,TFRE_DB_IPV6_ROUTE,zone.DomainID) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
CheckDbResult(conn.Fetch(FREDB_H2G(input.FieldPath('data.'+input.FieldPath('data.type').AsString+'.ip').AsString),gateway));
if ipv4 then begin
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_IPV4_ROUTE.ClassName,scheme);
route:=TFRE_DB_IPV4_ROUTE.CreateForDB;
end else begin
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_IPV6_ROUTE.ClassName,scheme);
route:=TFRE_DB_IPV6_ROUTE.CreateForDB;
end;
route.Field('gateway').AsObjectLink:=gateway.UID;
if (input.FieldPath('data.type').AsString='ipv4default') or (input.FieldPath('data.type').AsString='ipv6default') then begin
route.Field('default').AsBoolean:=true;
route.Field('objname').AsString:=gateway.Field('ip').AsString;
end else begin
route.Field('default').AsBoolean:=false;
conn.Fetch(gateway.Field('subnet').AsObjectLink,subnet);
conn.Fetch(subnet.Field('base_ip').AsObjectLink,baseIp);
route.Field('objname').AsString:=gateway.Field('ip').AsString + ' ('+baseIp.Field('ip').AsString+'/'+subnet.Field('subnet_bits').AsString+')';
end;
route.Field('serviceParent').AsObjectLink:=zone.UID;
route.Field('datalinkParent').AsObjectLink:=zone.UID;
route.generateUCT;
route.SetDomainID(zone.DomainID);
coll:=conn.GetCollection(CFOS_DB_SERVICES_COLLECTION);
if coll.ExistsIndexedText(route.uct)>0 then begin
Result:=TFRE_DB_MESSAGE_DESC.Create.Describe(FetchModuleTextShort(ses,'route_create_error_exists_cap'),FetchModuleTextShort(ses,'route_create_error_exists_msg'),fdbmt_error);
exit;
end;
CheckDbResult(coll.Store(route));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_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;
begin
Result:=GFRE_DB_NIL_DESC;
end;
function TFRE_FIRMBOX_NET_ROUTING_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;
begin
Result:=_getDetails(input,ses,app,conn);
end;
function TFRE_FIRMBOX_NET_ROUTING_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='UPD' then begin
_updateDatalinkGridTB(input,ses,app,conn);
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_DatalinkGridSC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
ses.UnregisterDBOChangeCB('netRoutingModDatalink');
if input.FieldExists('selected') then begin
ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr:=input.Field('selected').AsStringArr;
ses.GetSessionModuleData(ClassName).Field('selectedExt').AsStringArr:=input.Field('selectedExt').AsStringArr;
if input.Field('selected').ValueCount=1 then begin
ses.RegisterDBOChangeCB(FREDB_H2G(input.Field('selected').AsString),CWSF(@WEB_DLObjChanged),'netRoutingModDatalink');
end;
end else begin
ses.GetSessionModuleData(ClassName).DeleteField('selected');
ses.GetSessionModuleData(ClassName).DeleteField('selectedExt');
end;
_updateDatalinkGridTB(input,ses,app,conn);
Result:=GFRE_DB_NIL_DESC;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_DatalinkGridMenu(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;
ipv4Enabled : Boolean;
ipv6Enabled : Boolean;
isGlobal : Boolean;
dhcpEnabled : Boolean;
slaacEnabled: Boolean;
begin
isGlobal:=ses.GetSessionModuleData(ClassName).Field('zoneIsGlobal').AsBoolean;
res:=TFRE_DB_MENU_DESC.create.Describe;
if _canModify(input,ses,conn) then begin
sf:=CWSF(@WEB_Modify);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_modify'),'',sf);
end;
if _canDelete(input,ses,conn) then begin
sf:=CWSF(@WEB_Delete);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
sf.AddParam.Describe('selectedExt',input.Field('selectedExt').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_delete'),'',sf);
end;
if isGlobal and _canDelegate(input,ses,conn) then begin
sf:=CWSF(@WEB_Delegate);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_delegate'),'',sf);
end;
if isGlobal and _canRetract(input,ses,conn) then begin
sf:=CWSF(@WEB_Retract);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_retract'),'',sf);
end;
if _canAddVNIC(input,ses,conn) then begin
sf:=CWSF(@WEB_AddVNIC);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_add_vnic'),'',sf);
end;
_canAddIP(input,ses,conn,ipv4Enabled,ipv6Enabled,dhcpEnabled,slaacEnabled);
if ipv4Enabled then begin
sf:=CWSF(@WEB_AddIP);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
sf.AddParam.Describe('serviceClass',TFRE_DB_IPV4.ClassName);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_add_ip_ipv4'),'',sf);
end;
if ipv6Enabled then begin
sf:=CWSF(@WEB_AddIP);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
sf.AddParam.Describe('serviceClass',TFRE_DB_IPV6.ClassName);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_add_ip_ipv6'),'',sf);
end;
if dhcpEnabled then begin
sf:=CWSF(@WEB_AddIP);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
sf.AddParam.Describe('serviceClass',TFRE_DB_IPV4_DHCP.ClassName);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_add_ip_ipv4_dhcp'),'',sf);
end;
if slaacEnabled then begin
sf:=CWSF(@WEB_AddIP);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
sf.AddParam.Describe('serviceClass',TFRE_DB_IPV6_SLAAC.ClassName);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_add_ip_ipv6_slaac'),'',sf);
end;
if isGlobal and _canMoveToAggr(input,ses,conn) then begin
sf:=CWSF(@WEB_MoveToAggr);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_aggregation_move_to'),'',sf);
end;
if isGlobal and _canRemoveFromAggr(input,ses,conn) then begin
sf:=CWSF(@WEB_RemoveFromAggr);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_aggregation_remove_from'),'',sf);
end;
if _canMoveToBridge(input,ses,conn) then begin
sf:=CWSF(@WEB_MoveToBridge);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_bridge_move_to'),'',sf);
end;
if _canRemoveFromBridge(input,ses,conn) then begin
sf:=CWSF(@WEB_RemoveFromBridge);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_bridge_remove_from'),'',sf);
end;
if _canLinkToIPMP(input,ses,conn,isGlobal) then begin
sf:=CWSF(@WEB_LinkToIPMP);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_ipmp_link_to'),'',sf);
end;
if _canUnlinkFromIPMP(input,ses,conn) then begin
sf:=CWSF(@WEB_UnlinkFromIPMP);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_ipmp_unlink_from'),'',sf);
end;
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_DLObjChanged(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
_updateDatalinkGridTB(input,ses,app,conn);
end;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_Delegate(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;
dc : IFRE_DB_DERIVED_COLLECTION;
dbo : IFRE_DB_Object;
zone : TFRE_DB_ZONE;
sf : TFRE_DB_SERVER_FUNC_DESC;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canDelegate(input,ses,conn,dbo) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
zone:=_getZone(dbo,conn,true);
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'delegate_datalink_diag_cap'));
dc:=ses.FetchDerivedCollection('ZONE_CHOOSER');
dc.Filters.RemoveFilter('machine');
dc.Filters.RemoveFilter('rights');
dc.Filters.RemoveFilter('rightsPH');
dc.Filters.RemoveFilter('rightsSIM');
dc.Filters.AddUIDFieldFilter('machine','hostid',[zone.Field('hostid').AsObjectLink],dbnf_OneValueFromFilter);
dc.Filters.AddStdClassRightFilter('rights','domainid','','',dbo.Implementor_HC.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
if dbo.Implementor_HC is TFRE_DB_DATALINK_AGGR then begin
dc.Filters.AddStdClassRightFilter('rightsPH','domainid','','',TFRE_DB_DATALINK_PHYS.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
dc.Filters.AddStdClassRightFilter('rightsSIM','domainid','','',TFRE_DB_DATALINK_SIMNET.ClassName,[sr_STORE],conn.SYS.GetCurrentUserTokenClone);
end;
if dc.ItemCount=0 then begin
res.AddDescription.Describe('',FetchModuleTextShort(ses,'delegate_datalink_diag_no_zone_msg'));
end else begin
res.AddChooser.Describe(FetchModuleTextShort(ses,'delegate_datalink_diag_zone'),'dzone',dc.GetStoreDescription.Implementor_HC as TFRE_DB_STORE_DESC,dh_chooser_combo,true);
sf:=CWSF(@WEB_StoreDelegation);
sf.AddParam.Describe('selected',dbo.UID_String);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit);
end;
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_StoreDelegation(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;
dbo : IFRE_DB_Object;
refs : TFRE_DB_GUIDArray;
i : Integer;
datalink: IFRE_DB_Object;
procedure _handleIPs(const parentDbo: IFRE_DB_Object; const zone: TFRE_DB_ZONE);
var
i : Integer;
ip : IFRE_DB_Object;
refs : TFRE_DB_GUIDArray;
begin
refs:=conn.GetReferences(parentDbo.UID,false,'','datalinkParent');
for i := 0 to High(refs) do begin
CheckDbResult(conn.Fetch(refs[i],ip));
ip.SetDomainID(zone.DomainID);
ip.Field('zoneId').AsObjectLink:=zone.UID;
CheckDbResult(conn.Update(ip));
end;
end;
begin
if not _canDelegate(input,ses,conn,dbo) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if not input.FieldPathExists('data.dzone') then
raise EFRE_DB_Exception.Create('Missing input parameter zone!');
CheckDbResult(conn.FetchAs(FREDB_H2G(input.FieldPath('data.dzone').AsString),TFRE_DB_ZONE,zone));
if dbo.DomainID<>zone.DomainID then begin
dbo.SetDomainID(zone.DomainID);
if dbo.Implementor_HC is TFRE_DB_DATALINK_AGGR then begin
refs:=conn.GetReferences(dbo.UID,false,'','datalinkParent');
for i := 0 to High(refs) do begin //handle datalinks of the aggregation
CheckDbResult(conn.Fetch(refs[i],datalink));
datalink.SetDomainID(zone.DomainID);
CheckDbResult(conn.Update(datalink.CloneToNewObject()));
_handleIPs(datalink,zone);
end;
end else begin
_handleIPs(dbo,zone);
end;
end;
dbo.Field('datalinkParent').AddObjectLink(zone.UID);
dbo.Field('serviceParent').AddObjectLink(zone.UID);
CheckDbResult(conn.Update(dbo));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_Retract(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 input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canRetract(input,ses,conn) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
sf:=CWSF(@WEB_RetractConfirmed);
sf.AddParam.Describe('selected',input.Field('selected').AsStringArr);
cap:=FetchModuleTextShort(ses,'retract_datalink_diag_cap');
CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsStringArr[0]),dbo));
msg:=StringReplace(FetchModuleTextShort(ses,'retract_datalink_diag_msg'),'%datalink_str%',dbo.Field('objname').AsString,[rfReplaceAll]);
Result:=TFRE_DB_MESSAGE_DESC.create.Describe(cap,msg,fdbmt_confirm,sf);
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_RetractConfirmed(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;
zone : TFRE_DB_ZONE;
gzone : TFRE_DB_ZONE;
refs : TFRE_DB_GUIDArray;
i : Integer;
datalink: IFRE_DB_Object;
procedure _handleIPs(const parentDbo: IFRE_DB_Object; const gzone: TFRE_DB_ZONE);
var
i : Integer;
ip : IFRE_DB_Object;
refs : TFRE_DB_GUIDArray;
begin
refs:=conn.GetReferences(parentDbo.UID,false,'','datalinkParent');
for i := 0 to High(refs) do begin
CheckDbResult(conn.Fetch(refs[i],ip));
ip.SetDomainID(gzone.DomainID);
ip.Field('zoneId').AsObjectLink:=gzone.UID;
CheckDbResult(conn.Update(ip));
end;
end;
begin
if not _canRetract(input,ses,conn,dbo) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
zone:=_getZone(dbo,conn,false);
gzone:=_getZone(dbo,conn,true);
if dbo.DomainID<>gzone.DomainID then begin
dbo.SetDomainID(gzone.DomainID);
if dbo.Implementor_HC is TFRE_DB_DATALINK_AGGR then begin
refs:=conn.GetReferences(dbo.UID,false,'','datalinkParent');
for i := 0 to High(refs) do begin //handle datalinks of the aggregation
CheckDbResult(conn.Fetch(refs[i],datalink));
datalink.SetDomainID(gzone.DomainID);
CheckDbResult(conn.Update(datalink.CloneToNewObject()));
_handleIPs(datalink,gzone);
end;
end else begin
_handleIPs(dbo,gzone);
end;
end;
dbo.Field('datalinkParent').RemoveObjectLinkByUID(zone.UID);
dbo.Field('serviceParent').RemoveObjectLinkByUID(zone.UID);
CheckDbResult(conn.Update(dbo));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_AddVNIC(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;
sf : TFRE_DB_SERVER_FUNC_DESC;
dbo : IFRE_DB_Object;
num : TFRE_DB_INPUT_NUMBER_DESC;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canAddVNIC(input,ses,conn,dbo) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'add_vnic_diag_cap'),600,true,true,false);
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_DATALINK_VNIC.ClassName,scheme);
res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses);
num:=res.AddNumber.Describe(FetchModuleTextShort(ses,'add_vnic_diag_vlan'),'vlan',false,false,false,false,'',0);
num.setMin(0);
sf:=CWSF(@WEB_StoreVNIC);
sf.AddParam.Describe('selected',dbo.UID_String);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit);
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_StoreVNIC(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;
idx : String;
vnic : TFRE_DB_DATALINK_VNIC;
begin
if not _canAddVNIC(input,ses,conn,dbo) 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!');
zone:=_getZone(dbo,conn,false);
idx:=TFRE_DB_DATALINK_VNIC.ClassName + '_' + 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,'vnic_create_error_exists_cap'),FetchModuleTextShort(ses,'vnic_create_error_exists_msg'),fdbmt_error);
exit;
end;
GFRE_DBI.GetSystemSchemeByName(TFRE_DB_DATALINK_VNIC.ClassName,scheme);
vnic:=TFRE_DB_DATALINK_VNIC.CreateForDB;
if input.FieldPathExistsAndNotMarkedClear('data.vlan') and (input.FieldPath('data.vlan').AsUInt16<>0) then begin
vnic.Field('vid').AsObjectLink:=_getVLAN(conn,input.FieldPath('data.vlan').AsUInt16,dbo.DomainID);
end;
input.Field('data').AsObject.DeleteField('vlan');
vnic.Field('serviceParent').AsObjectLink:=dbo.UID;
vnic.Field('datalinkParent').AsObjectLink:=dbo.UID;
vnic.SetDomainID(dbo.DomainID);
vnic.uct := idx;
scheme.SetObjectFieldsWithScheme(input.Field('data').AsObject,vnic,true,conn);
CheckDbResult(coll.Store(vnic));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_AddIP(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;
sf : TFRE_DB_SERVER_FUNC_DESC;
dbo : IFRE_DB_Object;
ipv4Enabled : Boolean;
ipv6Enabled : Boolean;
serviceClass: TFRE_DB_String;
dhcpEnabled : Boolean;
slaacEnabled: Boolean;
block : TFRE_DB_INPUT_BLOCK_DESC;
addIPSf : TFRE_DB_SERVER_FUNC_DESC;
dc : IFRE_DB_DERIVED_COLLECTION;
fld : IFRE_DB_FIELD;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
_canAddIP(input,ses,conn,ipv4Enabled,ipv6Enabled,dhcpEnabled,slaacEnabled,dbo);
serviceClass:=input.Field('serviceClass').AsString;
if not ((ipv4Enabled and (serviceClass=TFRE_DB_IPV4.ClassName)) or (ipv6Enabled and (serviceClass=TFRE_DB_IPV6.ClassName)) or
(dhcpEnabled and (serviceClass=TFRE_DB_IPV4_DHCP.ClassName)) or (slaacEnabled and (serviceClass=TFRE_DB_IPV6_SLAAC.ClassName))) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if serviceClass=TFRE_DB_IPV4_DHCP.ClassName then begin
input.FieldPathCreate('data.objname').AsString:='DHCP';
WEB_StoreIP(input,ses,app,conn);
Result:=GFRE_DB_NIL_DESC;
exit;
end;
if serviceClass=TFRE_DB_IPV6_SLAAC.ClassName then begin
input.FieldPathCreate('data.objname').AsString:='SLAAC';
WEB_StoreIP(input,ses,app,conn);
Result:=GFRE_DB_NIL_DESC;
exit;
end;
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'add_ip_diag_cap'),600,true,true,false);
GFRE_DBI.GetSystemSchemeByName(serviceClass,scheme);
block:=res.AddBlock.Describe(FetchModuleTextShort(ses,'add_ip_diag_ip_block'));
addIPSf:=CWSF(@fNetIPMod.WEB_AddIP);
if serviceClass=TFRE_DB_IPV4.ClassName then begin
dc := ses.FetchDerivedCollection('IPV4_CHOOSER');
addIPSf.AddParam.Describe('ipversion','ipv4');
end else begin
dc := ses.FetchDerivedCollection('IPV6_CHOOSER');
addIPSf.AddParam.Describe('ipversion','ipv6');
end;
dc.Filters.RemoveFilter('domain');
dc.Filters.AddUIDFieldFilter('domain','domainid',dbo.DomainID,dbnf_OneValueFromFilter);
block.AddChooser().Describe('','ip',dc.GetStoreDescription as TFRE_DB_STORE_DESC,dh_chooser_combo,true,false,true);
addIPSf.AddParam.Describe('cbclass',self.ClassName);
addIPSf.AddParam.Describe('cbuidpath',FREDB_CombineString(self.GetUIDPath,','));
addIPSf.AddParam.Describe('cbfunc','AddIP');
addIPSf.AddParam.Describe('cbparamnames','serviceClass');
addIPSf.AddParam.Describe('cbparamvalues',serviceClass);
addIPSf.AddParam.Describe('selected',dbo.UID_String);
addIPSf.AddParam.Describe('field','ip');
dc.Filters.RemoveFilter('vlan');
if dbo.IsA(TFRE_DB_DATALINK_VNIC) and dbo.FieldOnlyExisting('vid',fld) then begin
addIPSf.AddParam.Describe('vlan',fld.AsObjectLink.AsHexString);
dc.Filters.AddUIDFieldFilter('vlan','vid',fld.AsObjectLink,dbnf_OneValueFromFilter);
end else begin
dc.Filters.AddUIDFieldFilter('vlan','vid',CFRE_DB_NullGUID,dbnf_OneValueFromFilter);
end;
block.AddInputButton(3).Describe('',FetchModuleTextShort(ses,'add_ip_diag_new_ip_button'),addIPSf,true);
sf:=CWSF(@WEB_StoreIP);
sf.AddParam.Describe('selected',dbo.UID_String);
sf.AddParam.Describe('serviceClass',serviceClass);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit);
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_StoreIP(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
ipv4Enabled : Boolean;
ipv6Enabled : Boolean;
dhcpEnabled : Boolean;
slaacEnabled: Boolean;
dbo : IFRE_DB_Object;
serviceClass: TFRE_DB_String;
ip : TFRE_DB_IP;
coll : IFRE_DB_COLLECTION;
begin
_canAddIP(input,ses,conn,ipv4Enabled,ipv6Enabled,dhcpEnabled,slaacEnabled,dbo);
serviceClass:=input.Field('serviceClass').AsString;
if not ((ipv4Enabled and (serviceClass=TFRE_DB_IPV4.ClassName)) or (ipv6Enabled and (serviceClass=TFRE_DB_IPV6.ClassName)) or
(dhcpEnabled and (serviceClass=TFRE_DB_IPV4_DHCP.ClassName)) or (slaacEnabled and (serviceClass=TFRE_DB_IPV6_SLAAC.ClassName))) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if (serviceClass=TFRE_DB_IPV4_DHCP.ClassName) or (serviceClass=TFRE_DB_IPV6_SLAAC.ClassName) then begin //DHCP & SLAAC
ip:=GFRE_DBI.NewObjectSchemeByName(serviceClass).Implementor_HC as TFRE_DB_IP;
ip.SetDomainID(dbo.DomainID);
ip.Field('objname').AsString:=input.FieldPath('data.objname').AsString;
ip.Field('serviceParent').AsObjectLink:=dbo.UID;
ip.Field('datalinkParent').AsObjectLink:=dbo.UID;
ip.generateUCT;
coll:=conn.GetCollection(CFRE_DB_IP_COLLECTION);
CheckDbResult(coll.Store(ip));
end else begin //IPv4 & IPv6
conn.FetchAs(FREDB_H2G(input.FieldPath('data.ip').AsString),TFRE_DB_IP,ip);
ip.Field('serviceParent').AddObjectLink(dbo.UID);
ip.Field('datalinkParent').AddObjectLink(dbo.UID);
CheckDbResult(conn.Update(ip));
end;
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_MoveToAggr(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;
res : TFRE_DB_FORM_DIALOG_DESC;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canMoveToAggr(input,ses,conn) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'move_to_aggregation_diag_cap'),600,true,true,false);
res.AddChooser.Describe(FetchModuleTextShort(ses,'move_to_aggregation_chooser_cap'),'aggr',ses.FetchDerivedCollection('AGGREGATION_CHOOSER').GetStoreDescription.Implementor_HC as TFRE_DB_STORE_DESC,dh_chooser_combo,true,true,true);
sf:=CWSF(@WEB_StoreMoveToAggr);
sf.AddParam.Describe('selected',input.Field('selected').AsStringArr);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit);
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_StoreMoveToAggr(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;
zone : TFRE_DB_ZONE;
aggrUid : TFRE_DB_GUID;
refs : TFRE_DB_GUIDArray;
i : Integer;
childDbo: IFRE_DB_Object;
begin
if not _canMoveToAggr(input,ses,conn,dbo) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if not input.FieldPathExists('data.aggr') then
raise EFRE_DB_Exception.Create('Missing input parameter aggr!');
aggrUid:=FREDB_H2G(input.FieldPath('data.aggr').AsString);
zone:=_getZone(dbo,conn,true);
dbo.Field('datalinkParent').RemoveObjectLinkByUID(zone.UID);
dbo.Field('datalinkParent').AddObjectLink(aggrUid);
dbo.Field('serviceParent').RemoveObjectLinkByUID(zone.UID);
dbo.Field('serviceParent').AddObjectLink(aggrUid);
refs:=conn.GetReferences(dbo.UID,false,'','datalinkParent');
for i := 0 to High(refs) do begin //move vnics and IPs to aggregation
CheckDbResult(conn.Fetch(refs[i],childDbo));
childDbo.Field('datalinkParent').RemoveObjectLinkByUID(dbo.UID);
childDbo.Field('datalinkParent').AddObjectLink(aggrUid);
childDbo.Field('serviceParent').RemoveObjectLinkByUID(dbo.UID);
childDbo.Field('serviceParent').AddObjectLink(aggrUid);
CheckDbResult(conn.Update(childDbo));
end;
CheckDbResult(conn.Update(dbo));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_RemoveFromAggr(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;
zone: TFRE_DB_ZONE;
refs: TFRE_DB_GUIDArray;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canRemoveFromAggr(input,ses,conn,dbo) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
zone:=_getZone(dbo,conn,true);
refs:=conn.GetReferences(dbo.UID,true,TFRE_DB_DATALINK_AGGR.ClassName,'datalinkParent');
if Length(refs)=0 then
raise EFRE_DB_Exception.Create('No aggregation found for given object!');
dbo.Field('datalinkParent').RemoveObjectLinkByUID(refs[0]);
dbo.Field('serviceParent').RemoveObjectLinkByUID(refs[0]);
dbo.Field('datalinkParent').AddObjectLink(zone.UID);
dbo.Field('serviceParent').AddObjectLink(zone.UID);
CheckDbResult(conn.Update(dbo));
Result:=GFRE_DB_NIL_DESC;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_MoveToBridge(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;
res : TFRE_DB_FORM_DIALOG_DESC;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canMoveToBridge(input,ses,conn) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'move_to_bridge_diag_cap'),600,true,true,false);
res.AddChooser.Describe(FetchModuleTextShort(ses,'move_to_bridge_chooser_cap'),'bridge',ses.FetchDerivedCollection('BRIDGE_CHOOSER').GetStoreDescription.Implementor_HC as TFRE_DB_STORE_DESC,dh_chooser_combo,true,true,true);
sf:=CWSF(@WEB_StoreMoveToBridge);
sf.AddParam.Describe('selected',input.Field('selected').AsStringArr);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit);
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_StoreMoveToBridge(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;
zone : TFRE_DB_ZONE;
bridgeUid : TFRE_DB_GUID;
refs : TFRE_DB_GUIDArray;
i : Integer;
childDbo : IFRE_DB_Object;
begin
if not _canMoveToBridge(input,ses,conn,dbo) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if not input.FieldPathExists('data.bridge') then
raise EFRE_DB_Exception.Create('Missing input parameter bridge!');
bridgeUid:=FREDB_H2G(input.FieldPath('data.bridge').AsString);
zone:=_getZone(dbo,conn,true);
dbo.Field('datalinkParent').RemoveObjectLinkByUID(zone.UID);
dbo.Field('datalinkParent').AddObjectLink(bridgeUid);
dbo.Field('serviceParent').RemoveObjectLinkByUID(zone.UID);
dbo.Field('serviceParent').AddObjectLink(bridgeUid);
refs:=conn.GetReferences(dbo.UID,false,'','datalinkParent');
for i := 0 to High(refs) do begin //move IPs to bridge
CheckDbResult(conn.Fetch(refs[i],childDbo));
childDbo.Field('datalinkParent').RemoveObjectLinkByUID(dbo.UID);
childDbo.Field('datalinkParent').AddObjectLink(bridgeUid);
childDbo.Field('serviceParent').RemoveObjectLinkByUID(dbo.UID);
childDbo.Field('serviceParent').AddObjectLink(bridgeUid);
CheckDbResult(conn.Update(childDbo));
end;
CheckDbResult(conn.Update(dbo));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_RemoveFromBridge(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;
zone : TFRE_DB_ZONE;
refs : TFRE_DB_GUIDArray;
bridgeDbo: IFRE_DB_Object;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canRemoveFromBridge(input,ses,conn,dbo) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
refs:=conn.GetReferences(dbo.UID,true,TFRE_DB_DATALINK_BRIDGE.ClassName,'datalinkParent');
if Length(refs)=0 then
raise EFRE_DB_Exception.Create('No bridge found for given object!');
CheckDbResult(conn.Fetch(refs[0],bridgeDbo));
zone:=_getZone(bridgeDbo,conn,true);
dbo.Field('datalinkParent').RemoveObjectLinkByUID(bridgeDbo.UID);
dbo.Field('serviceParent').RemoveObjectLinkByUID(bridgeDbo.UID);
dbo.Field('datalinkParent').AddObjectLink(zone.UID);
dbo.Field('serviceParent').AddObjectLink(zone.UID);
CheckDbResult(conn.Update(dbo));
Result:=GFRE_DB_NIL_DESC;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_LinkToIPMP(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;
res : TFRE_DB_FORM_DIALOG_DESC;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canLinkToIPMP(input,ses,conn,ses.GetSessionModuleData(ClassName).Field('zoneIsGlobal').AsBoolean) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'link_to_ipmp_diag_cap'),600,true,true,false);
res.AddChooser.Describe(FetchModuleTextShort(ses,'link_to_ipmp_chooser_cap'),'ipmp',ses.FetchDerivedCollection('IPMP_CHOOSER').GetStoreDescription.Implementor_HC as TFRE_DB_STORE_DESC,dh_chooser_combo,true,true,true);
sf:=CWSF(@WEB_StoreLinkToIPMP);
sf.AddParam.Describe('selected',input.Field('selected').AsStringArr);
res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit);
Result:=res;
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_StoreLinkToIPMP(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;
ipmpUid : TFRE_DB_GUID;
begin
if not _canLinkToIPMP(input,ses,conn,ses.GetSessionModuleData(ClassName).Field('zoneIsGlobal').AsBoolean,dbo) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
if not input.FieldPathExists('data.ipmp') then
raise EFRE_DB_Exception.Create('Missing input parameter ipmp!');
ipmpUid:=FREDB_H2G(input.FieldPath('data.ipmp').AsString);
dbo.Field('datalinkParent').AddObjectLink(ipmpUid);
dbo.Field('serviceParent').AddObjectLink(ipmpUid);
CheckDbResult(conn.Update(dbo));
Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe();
end;
function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_UnlinkFromIPMP(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;
refs : TFRE_DB_GUIDArray;
ipmpDbo : IFRE_DB_Object;
begin
if not input.FieldExists('selected') then begin
input.Field('selected').AsStringArr:=ses.GetSessionModuleData(ClassName).Field('selected').AsStringArr;
end;
if not _canUnlinkFromIPMP(input,ses,conn,dbo) then
raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
refs:=conn.GetReferences(dbo.UID,true,TFRE_DB_DATALINK_IPMP.ClassName,'datalinkParent');
if Length(refs)=0 then
raise EFRE_DB_Exception.Create('No ipmp datlink found for given object!');
CheckDbResult(conn.Fetch(refs[0],ipmpDbo));
dbo.Field('datalinkParent').RemoveObjectLinkByUID(ipmpDbo.UID);
dbo.Field('serviceParent').RemoveObjectLinkByUID(ipmpDbo.UID);
CheckDbResult(conn.Update(dbo));
Result:=GFRE_DB_NIL_DESC;
end;
//function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_IFSC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
//begin
// CheckClassVisibility4AnyDomain(ses);
//
// if input.FieldExists('selected') and (input.Field('selected').ValueCount>0) then begin
// ses.GetSessionModuleData(ClassName).Field('selectedIF').AsStringArr:=input.Field('selected').AsStringArr;
// end else begin
// ses.GetSessionModuleData(ClassName).DeleteField('selectedIF');
// end;
//
// Result:=WEB_ContentIF(input,ses,app,conn);
//end;
//
//function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_ContentIF(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_CONTENT_DESC;
// ifObj : IFRE_DB_Object;
// form : TFRE_DB_FORM_PANEL_DESC;
// scheme: IFRE_DB_SchemeObject;
// slider: TFRE_DB_FORM_PANEL_DESC;
// group : TFRE_DB_INPUT_GROUP_DESC;
//begin
// if ses.GetSessionModuleData(ClassName).FieldExists('selectedIF') and (ses.GetSessionModuleData(ClassName).Field('selectedIF').ValueCount=1) then begin
// CheckDbResult(conn.Fetch(FREDB_H2G(ses.GetSessionModuleData(ClassName).Field('selectedIF').AsStringItem[0]),ifObj));
//
// //editable:=conn.sys.CheckClassRight4DomainId(sr_UPDATE,ifObj.Implementor_HC.ClassType,ifObj.DomainID);
//
// if not GFRE_DBI.GetSystemScheme(ifObj.Implementor_HC.ClassType,scheme) then
// raise EFRE_DB_Exception.Create(edb_ERROR,'the scheme [%s] is unknown!',[ifObj.Implementor_HC.ClassType]);
//
// form:=TFRE_DB_FORM_PANEL_DESC.create.Describe('',true,false);
// form.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses);
// form.FillWithObjectValues(ifObj,ses);
//
// if (ifObj.Field('type').AsString='internet') then begin
// slider:=TFRE_DB_FORM_PANEL_DESC.create.Describe('',true,true,CWSF(@WEB_SliderChanged),500);
// slider.contentId:='slider_form';
// group:=slider.AddGroup.Describe(FetchModuleTextShort(ses,'bandwidth_group'));
// group.AddNumber.DescribeSlider('','slider',10,100,true,'20',0,10);
//
// res:=TFRE_DB_LAYOUT_DESC.create.Describe().SetAutoSizedLayout(nil,form,nil,slider);
// end else begin
// res:=form;
// end;
// end else begin
// res:=TFRE_DB_HTML_DESC.create.Describe(FetchModuleTextShort(ses,'info_if_details_select_one'));
// end;
//
// res.contentId:='IF_DETAILS';
// Result:=res;
//end;
//
//function TFRE_FIRMBOX_NET_ROUTING_MOD.WEB_SliderChanged(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
//var machineid : TFRE_DB_GUID;
// inp,opd : IFRE_DB_Object;
//
// 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
// res : TFRE_DB_CONTENT_DESC;
// i : NativeInt;
// cnt : NativeInt;
// newnew : IFRE_DB_Object;
//
// begin
// case status of
// cdcs_OK:
// begin
//// res:=TFRE_DB_MESSAGE_DESC.create.Describe('BW','SETUP OK',fdbmt_info);
// res := GFRE_DB_NIL_DESC;
// end;
// cdcs_TIMEOUT:
// begin
// Res := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','COMMUNICATION TIMEOUT SET BW',fdbmt_error); { FIXXME }
// end;
// cdcs_ERROR:
// begin
// Res := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','COULD NOT SET BW ['+new_input.Field('ERROR').AsString+']',fdbmt_error); { FIXXME }
// end;
// end;
// ses.SendServerClientAnswer(res,ocid);
// cnt := 0;
// end;
//
//
//begin
// writeln('SWL: SLIDER CHANGED', input.DumpToString);
// inp := GFRE_DBI.NewObject;
// inp.Field('BW').Asstring :=input.field('SLIDER').asstring;
// if ses.InvokeRemoteRequestMachineMac('00:25:90:82:bf:ae','TFRE_BOX_FEED_CLIENT','UPDATEBANDWIDTH',inp,@GotAnswer,nil)=edb_OK then //FIXXME
// begin
// Result := GFRE_DB_SUPPRESS_SYNC_ANSWER;
// exit;
// end
// else
// begin
// Result := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','COULD NOT SET BANDWIDTH',fdbmt_error); { FIXXME }
// inp.Finalize;
// end
//end;
end.
|
Program Perever_array;
const N=1000;
type TArray=array[1..N]of integer;
procedure Readarr(var x:tarray;var z:integer);
var i:integer;
begin
i:=0;
repeat
inc(i);
Readln(x[i]);
until x[i]=0;
z:=i-1;
end;
procedure Writearr(c:tarray; z:integer);
var i:integer;
begin
for i:=1 to z do
begin
Write(c[i], ' ');
end;
Writeln;
end;
procedure Swap(var x,y:integer);
var tp:integer;
begin
tp:=x;
x:=y;
y:=tp;
end;
procedure Sort(var numbers:tarray; len:integer);
var i:integer;
begin
for i:=1 to len div 2 do
Swap(numbers[i], numbers[len-i+1]);
end;
var len:integer;
z:tarray;
begin
Readarr(z,len);
Sort(z,len);
Writearr(z,len);
Readln;
end.
|
//------------------------------------------------------------------------------
//ConsoleOptions UNIT
//------------------------------------------------------------------------------
// What it does-
// This unit is used to gain access to configuration variables loaded from
// Console.ini.
//
// Changes -
// February 24th, 2007 - RaX - Broken out from HeliosOptions.
//
//------------------------------------------------------------------------------
unit ConsoleOptions;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
IniFiles;
type
//------------------------------------------------------------------------------
//TConsoleOptions CLASS
//------------------------------------------------------------------------------
TConsoleOptions = class(TMemIniFile)
private
//private variables
fInfoEnabled : boolean;
fNoticeEnabled : boolean;
fWarningEnabled : boolean;
fErrorEnabled : boolean;
fDebugEnabled : boolean;
fLogsEnabled : boolean;
fLogsFileName : String;
fInfoLogsEnabled : boolean;
fNoticeLogsEnabled : boolean;
fWarningLogsEnabled : boolean;
fErrorLogsEnabled : boolean;
fDebugLogsEnabled : boolean;
public
property ShowInfo : boolean read fInfoEnabled;
property ShowNotices : boolean read fNoticeEnabled;
property ShowWarnings : boolean read fWarningEnabled;
property ShowErrors : boolean read fErrorEnabled;
property ShowDebug : boolean read fDebugEnabled;
property LogsEnabled : boolean read fLogsEnabled;
property LogsFileName : String read fLogsFileName;
property LogInfo : boolean read fInfoLogsEnabled;
property LogNotices : boolean read fNoticeLogsEnabled;
property LogWarnings : boolean read fWarningLogsEnabled;
property LogErrors : boolean read fErrorLogsEnabled;
property LogDebug : boolean read fDebugLogsEnabled;
//Public methods
procedure Load;
procedure Save;
end;
//------------------------------------------------------------------------------
implementation
uses
Classes,
SysUtils;
//------------------------------------------------------------------------------
//Load() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This routine is called to load the ini file values from file itself.
// This routine contains multiple subroutines. Each one loads a different
// portion of the ini. All changes to said routines should be documented in
// THIS changes block.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TConsoleOptions.Load;
var
Section : TStringList;
//--------------------------------------------------------------------------
//LoadOutput SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadOutput;
begin
ReadSectionValues('Output', Section);
fInfoEnabled := StrToBoolDef(Section.Values['Info'] ,true);
fNoticeEnabled := StrToBoolDef(Section.Values['Notices'] ,true);
fWarningEnabled := StrToBoolDef(Section.Values['Warnings'] ,true);
fErrorEnabled := StrToBoolDef(Section.Values['Errors'] ,true);
fDebugEnabled := StrToBoolDef(Section.Values['Debug'] ,true);
end;{Subroutine LoadOutput}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadLogs SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadLogs;
begin
ReadSectionValues('Logs', Section);
fLogsEnabled := StrToBoolDef(Section.Values['Enabled'] , false);
fLogsFileName := Section.Values['File'] ;
fInfoLogsEnabled := StrToBoolDef(Section.Values['Info'] , false);
fNoticeLogsEnabled := StrToBoolDef(Section.Values['Notices'] , false);
fWarningLogsEnabled := StrToBoolDef(Section.Values['Warnings'] , true);
fErrorLogsEnabled := StrToBoolDef(Section.Values['Errors'] , true);
fDebugLogsEnabled := StrToBoolDef(Section.Values['Debug'] , false);
end;{Subroutine LoadOutput}
//--------------------------------------------------------------------------
begin
Section := TStringList.Create;
Section.QuoteChar := '"';
Section.Delimiter := ',';
LoadOutput;
LoadLogs;
Section.Free;
end;{Load}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Save() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This routine saves all configuration values defined here to the .ini
// file.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TConsoleOptions.Save;
begin
//Output
WriteString('Output','Info',BoolToStr(ShowInfo));
WriteString('Output','Notices',BoolToStr(ShowNotices));
WriteString('Output','Warnings',BoolToStr(ShowWarnings));
WriteString('Output','Errors',BoolToStr(ShowErrors));
WriteString('Output','Debug',BoolToStr(ShowDebug));
//Logs
WriteString('Logs','Enabled',BoolToStr(LogsEnabled));
WriteString('Logs','File', LogsFileName);
WriteString('Logs','Info',BoolToStr(LogInfo));
WriteString('Logs','Notices',BoolToStr(LogNotices));
WriteString('Logs','Warnings',BoolToStr(LogWarnings));
WriteString('Logs','Errors',BoolToStr(LogErrors));
WriteString('Logs','Debug',BoolToStr(LogDebug));
UpdateFile;
end;{Save}
//------------------------------------------------------------------------------
end{ServerOptions}.
|
(*
SM4 加密、解密库。
SM3 杂凑算法编码。
适用 Delphi 版本:Delpih 7, 2010
(仅在这两个版本下测试过,使用过程尽量考虑兼容。因此其他版本的兼容必问题不大)
关于国密算法,网上基本只有 C/Java 的实现。Delphi 唯一能找到的版本,还是一个网友实现的不完整版本。
仅有 SM4 ECB 模式,CBC 模式的实现还是错误的。为此,我们只好让部门的小美女完整实现了下列功能:
SM4 ECB 模式(标准模式)
SM4 CBC 模式(密文分组链接方式)
SM3 国标 hash 算法
在整个过程经过了一周时间,过程中也是遇坑无数。所以完成后把源码分享出来,希望其他同学不用再从轮子
做起,少经历一些波折。
如果在使用过程中发现这个库有所不足,还望指出纠正。问题可以发送至邮箱:delphi2006@163.com
苏州沈苏自动化技术股份有限公司(金苗部) 2018-12-30
主要的坑:
* SM4 加密前和加密后的数据长度是不一致的,而原始代码中,只是传指针,需要自己分配空间,因此这里
修改为带长度的数据类型 array of Byte / AnsiString。
SM4(加密前,长度任意) ---> SM4(加密后,长度会变为 16 的倍数,采用 PKCS5Padding)
SM4(解密前,16的倍数) ---> SM4(解密后,原来的长度)
* 原有函数调用规则混乱,经过重新调整,把接口进行了重新设计,现在需要以下几个即可实现加密、解密:
SM3.calcBuf(buf: SMByteArray): SMByteArray;
SM3.calcAnsiString(buf: AnsiString): AnsiString;
SM4.ECB_encodeBuf(srcBuf, password: SMByteArray): SMByteArray;
SM4.ECB_decodeBuf(srcBuf, password: SMByteArray): SMByteArray;
SM4.ECB_encodeAnsiString(srcStr, passwordStr: AnsiString): AnsiString;
SM4.ECB_decodeAnsiString(srcStr, passwordStr: AnsiString): AnsiString;
SM4.CBC_encodeBuf(srcBuf, password, IV: SMByteArray): SMByteArray;
SM4.CBC_decodeBuf(srcBuf, password, IV: SMByteArray): SMByteArray;
SM4.CBC_encodeAnsiString(srcStr, passwordStr, IV: AnsiString): AnsiString;
SM4.CBC_decodeAnsiString(srcStr, passwordStr, IV: AnsiString): AnsiString;
* 数据格式混乱,我们参考的代码中,有的使用 HexString, 有的使用 bytes。有 GBK, UTF-8, Hex, Base64。
在这里,基础加密库不包含任何编码,都是二进制。如果需要编码转换,可以使用下述函数:
AnsiToUTF8 -------> GBK->UTF-8
UTF8ToAnsi -------> UTF-8->GBK
*)
unit SM;
interface
uses
Windows, SysUtils;
type
SMByteArray = array of byte;
{ ***********************************************************************
国密SM4算法
以下算法参考网上的代码和资料,并对其中的问题进行修改,添加了PKCS5Padding进行明文填充,
并对其进行封装成以下接口,能够方便大家调用。
SM4算法参考资料:http://www.docin.com/p-1304033437.html
秘钥长度16字节(128位)有效,超出长度的数据自动截取,分组长度为128位
解密时使用PKCS5Padding方式填充明文
加密解密前后输出长度不一致,处理时需要注意
解密时输入的密文长度要是16的倍数
对称加密的模式参考资料:https://blog.csdn.net/sunqiujing/article/details/75065218
ECB模式:所有分组的加密方式一致。
CBC模式:先将明文切分成若干小段,然后每一小段与初始块或者上一段的密文段进行异或运算后,再与密钥进行加密。
*********************************************************************** }
SM4 = class
{==========================================================================
ECB模式
==========================================================================}
{--------------------------------------------------------------------------
函数名: encodeBuf
函数功能: 数组类型的明文加密
参数: srcBuf 明文 byte数组
password 秘钥 byte数组
返回值: 加密后的数据 SMByteArray byte数组
测试用例:
procedure TSimpleMainTest.SM4_ECB_AnsiString_Test;
var
sKey, srcStr, dstStr, decodeStr: AnsiString;
begin
sKey := '0123456789ABCDEFFEDCBA9876543210';
SrcStr := AnsiString(AnsiToUtf8('011234567890测试'));
dstStr := SM.SM4.ECB_encodeAnsiString(srcStr, sKey);
Status('dstStr: ' + StrToHex(dstStr)); // 输出:dstStr: 4356153999C1046859556F324B7CA5F806FBB9DB755372FAD2EF9CA8DD7EB944
decodeStr := SM.SM4.ECB_decodeAnsiString(dstStr, sKey);
Status('decodeStr(src):' + Utf8ToAnsi(decodeStr)); // 输出:decodeStr: 011234567890测试
end;
--------------------------------------------------------------------------}
class function ECB_encodeBuf(srcBuf, password: SMByteArray): SMByteArray;
{--------------------------------------------------------------------------
函数名: decodeBuf
函数功能: 数组类型的密文解密
参数: srcBuf 密文 byte数组
password 秘钥 byte数组
返回值: 解密后的数据 SMByteArray byte数组
--------------------------------------------------------------------------}
class function ECB_decodeBuf(srcBuf, password: SMByteArray): SMByteArray;
{--------------------------------------------------------------------------
函数名: encodeAnsiString
函数功能: 明文加密
参数: srcStr 明文 AnsiString
passwordStr 秘钥 AnsiString
返回值: 加密后的数据 AnsiString
测试用例:
procedure TSimpleMainTest.SM4_ECB_Buf_Test;
var
sKey, srcStr, dstStr, decodeStr: AnsiString;
srcArray, keyArray, retArray, decArray: SMByteArray;
begin
sKey := '0123456789ABCDEFFEDCBA9876543210';
SrcStr := AnsiString(AnsiToUtf8('011234567890测试'));
SetLength(srcArray, Length(SrcStr));
SetLength(keyArray, Length(sKey));
CopyMemory(srcArray, PAnsiChar(SrcStr), Length(SrcStr));
CopyMemory(keyArray, PAnsiChar(sKey), Length(sKey));
retArray := SM.SM4.ECB_encodeBuf(srcArray, keyArray);
SetLength(dstStr, Length(retArray));
CopyMemory(PAnsiChar(dstStr), @retArray[0], length(retArray));
Status('dstStr: ' + StrToHex(dstStr)); // 输出:dstStr: 4356153999C1046859556F324B7CA5F806FBB9DB755372FAD2EF9CA8DD7EB944
decArray := SM.SM4.ECB_decodeBuf(retArray, keyArray);
SetLength(decodeStr, Length(decArray));
CopyMemory(PAnsiChar(decodeStr), @decArray[0], length(decArray));
Status('decodeStr: ' + Utf8ToAnsi(decodeStr)); // 输出:decodeStr: 011234567890测试
end;
--------------------------------------------------------------------------}
class function ECB_encodeAnsiString(srcStr, passwordStr: AnsiString): AnsiString;
{--------------------------------------------------------------------------
函数名: decodeAnsiString
函数功能: 密文解密
参数: srcStr 密文 AnsiString
passwordStr 秘钥 AnsiString
返回值: 解密后的数据 AnsiString
--------------------------------------------------------------------------}
class function ECB_decodeAnsiString(srcStr, passwordStr: AnsiString): AnsiString;
{==========================================================================
CBC模式
==========================================================================}
{--------------------------------------------------------------------------
函数名: encodeBuf
函数功能: 数组类型的明文加密
参数: srcBuf 明文 byte数组
password 秘钥 byte数组
IV 初始化向量 byte数组
返回值: 加密后的数据 SMByteArray byte数组
测试用例:
procedure TSimpleMainTest.SM4_CBC_Buf_Test;
var
sKey, srcStr, pIv, dstStr, decodeStr: AnsiString;
srcArray, keyArray, ivArray, retArray, decArray: SMByteArray;
begin
sKey := 'JeF8U9wHFOMfs2Y8';
pIv := 'UISwD9fW6cFh9SNS';
SrcStr := AnsiString(AnsiToUtf8('011234567890测试'));
SetLength(srcArray, Length(SrcStr));
SetLength(keyArray, Length(sKey));
SetLength(ivArray, Length(pIv));
CopyMemory(srcArray, PAnsiChar(srcStr), Length(srcStr));
CopyMemory(keyArray, PAnsiChar(sKey), Length(sKey));
CopyMemory(ivArray, PAnsiChar(pIv), Length(pIv));
retArray := SM.SM4.CBC_encodeBuf(srcArray, keyArray, ivArray);
SetLength(dstStr, Length(retArray));
CopyMemory(PAnsiChar(dstStr), @retArray[0], length(retArray));
Status('dstStr: ' + StrToHex(dstStr)); // 输出:dstStr: 0456F645A06778DF0C3623AC5EB578F0765EE559CC7466CE71F05F94E9E10D45
decArray := SM.SM4.CBC_decodeBuf(retArray, keyArray, ivArray);
SetLength(decodeStr, Length(decArray));
CopyMemory(PAnsiChar(decodeStr), @decArray[0], length(decArray));
Status('decodeStr: ' + Utf8ToAnsi(decodeStr)); // 输出:decodeStr(src):011234567890测试
end;
--------------------------------------------------------------------------}
class function CBC_encodeBuf(srcBuf, password, IV: SMByteArray): SMByteArray;
{--------------------------------------------------------------------------
函数名: decodeBuf
函数功能: 数组类型的密文解密
参数: srcBuf 密文 byte数组
password 秘钥 byte数组
IV 初始化向量 byte数组
返回值: 解密后的数据 SMByteArray byte数组
--------------------------------------------------------------------------}
class function CBC_decodeBuf(srcBuf, password, IV: SMByteArray): SMByteArray;
{--------------------------------------------------------------------------
函数名: encodeAnsiString
函数功能: 明文加密
参数: srcStr 明文 AnsiString
passwordStr 秘钥 AnsiString
IV 初始化向量 AnsiString
返回值: 加密后的数据 AnsiString
测试用例:
procedure TSimpleMainTest.SM4_CBC_AnsiString_Test;
var
sKey, srcStr, pIv, dstStr, decodeStr: AnsiString;
begin
sKey := 'JeF8U9wHFOMfs2Y8';
pIv := 'UISwD9fW6cFh9SNS';
SrcStr := AnsiString(AnsiToUtf8('011234567890测试'));
dstStr := SM.SM4.CBC_encodeAnsiString(srcStr, sKey, pIv); // 输出:dstStr: 0456F645A06778DF0C3623AC5EB578F0765EE559CC7466CE71F05F94E9E10D45
Status('dstStr: ' + StrToHex(dstStr));
decodeStr := SM.SM4.CBC_decodeAnsiString(dstStr, sKey, pIv);
Status('decodeStr(src):' + Utf8ToAnsi(decodeStr)); // 输出:decodeStr(src):011234567890测试
end;
--------------------------------------------------------------------------}
class function CBC_encodeAnsiString(srcStr, passwordStr, IV: AnsiString): AnsiString;
{--------------------------------------------------------------------------
函数名: decodeAnsiString
函数功能: 密文解密
参数: srcStr 密文 AnsiString
passwordStr 秘钥 AnsiString
IV 初始化向量 AnsiString
返回值: 解密后的数据 AnsiString
--------------------------------------------------------------------------}
class function CBC_decodeAnsiString(srcStr, passwordStr, IV: AnsiString): AnsiString;
end;
SM3 = class
{--------------------------------------------------------------------------
函数名: calcBuf
函数功能: 计算密码散列
参数: buf 消息 SMByteArray
返回值: 摘要 SMByteArray
测试用例:
procedure TSimpleMainTest.SM3_Test;
var
md, msgArr: SMByteArray;
msgStr: AnsiString;
begin
msgStr := 'B299B04047767655FEAB540E6BFE2B335000220180507224028201805072240288D';
SetLength(msgArr, Length(msgStr));
SetLength(md, 32);
CopyMemory(msgArr, PAnsiChar(msgStr), Length(msgStr));
md := SM.SM3.calcBuf(msgArr);
Status('结果:' + StrToHex(byteArrayToAnsiString(md))); // 结果:357530A05333779826BE7F93374E9C97F915B5B1626923F8B5D943CD378E574D
Status('结果1:' + StrToHex(SM.SM3.calcAnsiString(msgStr))); // 结果1:357530A05333779826BE7F93374E9C97F915B5B1626923F8B5D943CD378E574D
end;
---------------------------------------------------------------------------}
class function calcBuf(buf: SMByteArray): SMByteArray;
{--------------------------------------------------------------------------
函数名: calcAnsiString
函数功能: 计算密码散列
参数: buf 消息 AnsiString
返回值: 摘要 AnsiString
---------------------------------------------------------------------------}
class function calcAnsiString(buf: AnsiString): AnsiString;
end;
SMUtils = class
class function StrToHex(const AString: AnsiString): String;
class function HexToStr(const S:String): AnsiString;
class procedure testAll;
end;
implementation
const
SM4_ENCRYPT = 1 ;
SM4_DECRYPT = 0 ;
BYTE_LENGTH = 32;
BLOCK_LENGTH = 64;
BUFFER_LENGTH = 64;
var
SboxTable: array[0..15, 0..15] of Byte = (
($d6, $90, $e9, $fe, $cc, $e1, $3d, $b7, $16, $b6, $14, $c2, $28, $fb, $2c, $05),
($2b, $67, $9a, $76, $2a, $be, $04, $c3, $aa, $44, $13, $26, $49, $86, $06, $99),
($9c, $42, $50, $f4, $91, $ef, $98, $7a, $33, $54, $0b, $43, $ed, $cf, $ac, $62),
($e4, $b3, $1c, $a9, $c9, $08, $e8, $95, $80, $df, $94, $fa, $75, $8f, $3f, $a6),
($47, $07, $a7, $fc, $f3, $73, $17, $ba, $83, $59, $3c, $19, $e6, $85, $4f, $a8),
($68, $6b, $81, $b2, $71, $64, $da, $8b, $f8, $eb, $0f, $4b, $70, $56, $9d, $35),
($1e, $24, $0e, $5e, $63, $58, $d1, $a2, $25, $22, $7c, $3b, $01, $21, $78, $87),
($d4, $00, $46, $57, $9f, $d3, $27, $52, $4c, $36, $02, $e7, $a0, $c4, $c8, $9e),
($ea, $bf, $8a, $d2, $40, $c7, $38, $b5, $a3, $f7, $f2, $ce, $f9, $61, $15, $a1),
($e0, $ae, $5d, $a4, $9b, $34, $1a, $55, $ad, $93, $32, $30, $f5, $8c, $b1, $e3),
($1d, $f6, $e2, $2e, $82, $66, $ca, $60, $c0, $29, $23, $ab, $0d, $53, $4e, $6f),
($d5, $db, $37, $45, $de, $fd, $8e, $2f, $03, $ff, $6a, $72, $6d, $6c, $5b, $51),
($8d, $1b, $af, $92, $bb, $dd, $bc, $7f, $11, $d9, $5c, $41, $1f, $10, $5a, $d8),
($0a, $c1, $31, $88, $a5, $cd, $7b, $bd, $2d, $74, $d0, $12, $b8, $e5, $b4, $b0),
($89, $69, $97, $4a, $0c, $96, $77, $7e, $65, $b9, $f1, $09, $c5, $6e, $c6, $84),
($18, $f0, $7d, $ec, $3a, $dc, $4d, $20, $79, $ee, $5f, $3e, $d7, $cb, $39, $48)
);
FK: array[0..3] of DWORD = ($a3b1bac6, $56aa3350, $677d9197, $b27022dc);
CK: array[0..31] of DWORD = (
$00070e15, $1c232a31, $383f464d, $545b6269,
$70777e85, $8c939aa1, $a8afb6bd, $c4cbd2d9,
$e0e7eef5, $fc030a11, $181f262d, $343b4249,
$50575e65, $6c737a81, $888f969d, $a4abb2b9,
$c0c7ced5, $dce3eaf1, $f8ff060d, $141b2229,
$30373e45, $4c535a61, $686f767d, $848b9299,
$a0a7aeb5, $bcc3cad1, $d8dfe6ed, $f4fb0209,
$10171e25, $2c333a41, $484f565d, $646b7279
);
iv: array[0..31] of Byte = (
$73, $80, $16, $6f, $49, $14, $b2, $b9,
$17, $24, $42, $d7, $da, $8a, $06, $00,
$a9, $6f, $30, $bc, $16, $31, $38, $aa,
$e3, $8d, $ee, $4d, $b0, $fb, $0e, $4e
);
Tj: array[0..63] of Integer = (
$79cc4519, $79cc4519, $79cc4519, $79cc4519, $79cc4519, $79cc4519, $79cc4519, $79cc4519,
$79cc4519, $79cc4519, $79cc4519, $79cc4519, $79cc4519, $79cc4519, $79cc4519, $79cc4519,
$7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a,
$7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a,
$7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a,
$7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a,
$7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a,
$7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a, $7a879d8a
);
type
TSM4SubKeyArray = array[0..31] of DWORD;
TSM4_Context = record
mode: Integer;
subkeys: TSM4SubKeyArray;
end ;
PSM4_Context = ^TSM4_Context;
SM3IntArray = array of Integer;
TSM3Digest = class
private
v: SMByteArray;
xBufOff: Integer;
xBuf: array[0..63] of Byte;
cntBlock: Integer;
public
constructor Create;
procedure update(inBuf: SMByteArray; inOff, len: Integer);
procedure doHash(bArr: SMByteArray);
function interDoFinal(): SMByteArray;
function doFinal(outBuf: SMByteArray; outOff: Integer): Integer;
procedure doUpdate();
end;
function ReverseInt(const iValue: Integer): Integer;
var
pBuf: array[0..3] of Byte;
tmp: Byte;
begin
Move(iValue, pBuf, 4);
tmp := pBuf[0];
pBuf[0] := pBuf[3];
pBuf[3] := tmp;
tmp := pBuf[1];
pBuf[1] := pBuf[2];
pBuf[2] := tmp;
Move(pBuf, Result, 4);
end ;
procedure GET_ULONG_BE(var n: DWORD; pBuffer: PAnsiChar; iIndex: Integer);
begin
Move((@pBuffer[iIndex])^, n, 4);
n := DWORD(ReverseInt(n));
end ;
procedure PUT_ULONG_BE(const n: DWORD; pBuffer: PAnsiChar; iIndex: Integer);
var
i: DWORD ;
begin
i := DWORD(ReverseInt(n));
Move(i, (@pBuffer[iIndex])^, 4);
end ;
function ROTL(x: DWORD; n: Integer): DWORD;
begin
Result := DWORD((x shl n) or (x shr (32 - n)));
end ;
procedure SWAP(var a, b: DWORD);
var
t: DWORD;
begin
t := a;
a := b;
b := t;
end ;
function sm4Sbox(inch: Byte): Byte;
var
pTable: PAnsiChar;
begin
pTable := PAnsiChar(@SboxTable[0, 0]);
Result := Ord(pTable[inch]) ;
end ;
function sm4Lt(ka: DWORD): DWORD;
var
bb, c: DWORD;
a, b: array[0..3] of Byte;
begin
bb := 0;
PUT_ULONG_BE(ka, PAnsiChar(@a[0]), 0);
b[0] := sm4Sbox(a[0]);
b[1] := sm4Sbox(a[1]);
b[2] := sm4Sbox(a[2]);
b[3] := sm4Sbox(a[3]);
GET_ULONG_BE(bb, PAnsiChar(@b[0]), 0) ;
c := bb xor (ROTL(bb, 2)) xor (ROTL(bb, 10)) xor (ROTL(bb, 18)) xor (ROTL(bb, 24));
Result := c;
end ;
function sm4F(x0, x1, x2, x3, rk: DWORD): DWORD;
begin
Result := x0 xor sm4Lt(x1 xor x2 xor x3 xor rk);
end ;
function sm4CalcRK(ka: DWORD): DWORD;
var
bb, rk: DWORD;
a, b :array[0..3] of Byte;
begin
bb := 0;
PUT_ULONG_BE(ka, PAnsiChar(@a[0]), 0);
b[0] := sm4Sbox(a[0]);
b[1] := sm4Sbox(a[1]);
b[2] := sm4Sbox(a[2]);
b[3] := sm4Sbox(a[3]);
GET_ULONG_BE(bb, PAnsiChar(@b[0]), 0) ;
rk := bb xor (ROTL(bb, 13)) xor (ROTL(bb, 23));
Result := rk;
end ;
procedure sm4_setkey(var SK: TSM4SubKeyArray; pKey: PAnsiChar);
var
MK: array[0..3] of DWORD;
k: array[0..35] of DWORD;
i: DWORD;
begin
GET_ULONG_BE(MK[0], pkey, 0);
GET_ULONG_BE(MK[1], pkey, 4);
GET_ULONG_BE(MK[2], pkey, 8);
GET_ULONG_BE(MK[3], pkey, 12);
k[0] := MK[0] xor FK[0];
k[1] := MK[1] xor FK[1];
k[2] := MK[2] xor FK[2];
k[3] := MK[3] xor FK[3];
for i := 0 to 31 do begin
k[i + 4] := k[i] xor (sm4CalcRK(k[i + 1] xor k[i + 2] xor k[i + 3] xor CK[i]));
SK[i] := k[i + 4];
end ;
end ;
procedure sm4_one_round(sk: TSM4SubKeyArray; pInput, pOutput: PAnsiChar);
var
i: DWORD;
ulBuf: array[0..35] of DWORD;
begin
i := 0;
ZeroMemory(@ulBuf, SizeOf(ulBuf));
GET_ULONG_BE(ulbuf[0], pInput, 0);
GET_ULONG_BE(ulbuf[1], pInput, 4);
GET_ULONG_BE(ulbuf[2], pInput, 8);
GET_ULONG_BE(ulbuf[3], pInput, 12);
while(i < 32) do begin
ulbuf[i + 4] := sm4F(ulbuf[i], ulbuf[i + 1], ulbuf[i + 2], ulbuf[i + 3], sk[i]);
i := i + 1 ;
end ;
PUT_ULONG_BE(ulbuf[35], pOutput, 0);
PUT_ULONG_BE(ulbuf[34], pOutput, 4);
PUT_ULONG_BE(ulbuf[33], pOutput, 8);
PUT_ULONG_BE(ulbuf[32], pOutput, 12);
end ;
procedure sm4_setkey_enc(pCtx: PSM4_context; szkey: PAnsiChar);
begin
pCtx^.mode := SM4_ENCRYPT;
sm4_setkey(pCtx^.subkeys, szkey);
end ;
procedure sm4_setkey_dec(pCtx: PSM4_context; szkey: PAnsiChar);
var
i: Integer;
begin
pCtx^.mode := SM4_ENCRYPT;
sm4_setkey(pCtx^.subkeys, szkey);
for i := 0 to 15 do
SWAP(pCtx^.subkeys[i], pCtx^.subkeys[31 - i]);
end ;
function padding(Buf: PAnsiChar; dataLen: Integer): SMByteArray;
var
paddingSize, i: Integer;
begin
paddingSize := 16 - dataLen mod 16;
SetLength(Result, dataLen + paddingSize);
CopyMemory(@Result[0], Buf, dataLen);
for I := 0 to paddingSize - 1 do begin
Result[dataLen + i] := paddingSize;
end;
end;
procedure sm4_crypt_ecb(pCtx: PSM4_context; mode, iDataSize: Integer; pInput, pOutput: PAnsiChar);
var
i, iLeftSize: Integer;
pData, pOut: PAnsiChar;
inBuf: SMByteArray;
begin
if mode = 1 then begin
inBuf := padding(pInput, iDataSize);
end else begin
SetLength(inBuf, iDataSize);
CopyMemory(@inBuf[0], pInput, iDataSize);
end;
iLeftSize := Length(inBuf);
i := 0 ;
while( iLeftSize > 0 ) do begin
pData := PAnsiChar(@inBuf[i * 16]);
pOut := @pOutput[i * 16];
ZeroMemory(pOut, 16);
sm4_one_round(pCtx^.subkeys, pData, pOut);
i := i + 1;
iLeftSize := iLeftSize - 16 ;
end ;
end ;
procedure sm4_crypt_cbc(pCtx: PSM4_context; mode, iDataSize: Integer; pIV, pInput, pOutput: PAnsiChar);
var
i, j, iLeftSize: Integer;
pData, pOut: PAnsiChar;
inBuf: SMByteArray;
tmp: array[0..15] of Byte;
tIV: array[0..15] of Byte;
begin
inBuf := nil;
CopyMemory(@tIV[0], pIV, 16);
if (mode = SM4_ENCRYPT) then begin
inBuf := padding(pInput, iDataSize);
iLeftSize := Length(inBuf);
j := 0;
while (iLeftSize > 0) do begin
pData := @inBuf[j * 16]; // += 16;
pOut := @pOutput[j * 16]; // += 16;
for i := 0 to 15 do
pOut[i] := AnsiChar(Ord(pData[i]) xor Ord(tIV[i]));
sm4_one_round(pCtx^.subkeys, pOut, @tmp[0]);
CopyMemory(@tIV[0], @tmp[0], 16);
j := j + 1;
CopyMemory(pOut, @tmp[0], Length(tmp));
iLeftSize := iLeftSize - 16;
end;
end else begin
//* SM4_DECRYPT */
iLeftSize := iDataSize;
j := 0;
while (iLeftSize > 0) do begin
pData := @pInput[j * 16]; // input += 16;
pOut := @pOutput[j * 16]; // output += 16;
Move(pData^, (@tmp[0])^, 16);// memcpy( temp, input, 16 );
sm4_one_round(pCtx^.subkeys, pData, pOut);
for i := 0 to 15 do
pOut[i] := AnsiChar(Ord(pOut[i]) xor Ord(tIV[i])); // output[i] = (unsigned char)( output[i] ^ iv[i] );
CopyMemory(@tIV[0], @tmp[0], 16);
j := j + 1;
iLeftSize := iLeftSize - 16;
end;
end;
end;
function sm4_crypt_ecb_ansiString(inStr, password: AnsiString; isEncrypt: Boolean): AnsiString;
var
sm4Ctx: TSM4_context;
begin
// 密码有效长度为 16 字节(64位),自动补足或截断。
password := Copy(password + #0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0, 1, 16);
if isEncrypt then begin
sm4_setkey_enc(@sm4Ctx, PAnsiChar(password));
SetLength(Result, Length(inStr) + (16 - Length(inStr) mod 16));
sm4_crypt_ecb(@sm4Ctx, SM4_ENCRYPT, Length(inStr), PAnsiChar(inStr), PAnsiChar(Result));
end else begin
sm4_setkey_dec(@sm4Ctx, PAnsiChar(password));
SetLength(Result, Length(inStr));
sm4_crypt_ecb(@sm4Ctx, SM4_DECRYPT, Length(inStr), PAnsiChar(inStr), PAnsiChar(Result));
// 把后面的填充位去除。
SetLength(Result, Length(Result) - Ord(Result[Length(Result)]));
end;
end;
{ SM4.ecb }
class function SM4.ECB_decodeAnsiString(srcStr, passwordStr: AnsiString): AnsiString;
var
sm4Ctx: TSM4_Context;
begin
if (Length(srcStr) mod 16) <> 0 then
raise Exception.Create('Error Message');
passwordStr := Copy(passwordStr + #0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0, 1, 16);
sm4_setkey_dec(@sm4Ctx, PAnsiChar(passwordStr));
SetLength(Result, Length(srcStr));
sm4_crypt_ecb(@sm4Ctx, SM4_DECRYPT, Length(srcStr), PAnsiChar(srcStr), PAnsiChar(Result));
// 把后面的填充位去除。
SetLength(Result, Length(Result) - Ord(Result[Length(Result)]));
end;
class function SM4.ECB_decodeBuf(srcBuf, password: SMByteArray): SMByteArray;
var
ret, srcStr, passwordStr:AnsiString;
begin
SetLength(srcStr, Length(srcBuf));
CopyMemory(PAnsiChar(srcStr), @srcBuf[0], Length(srcBuf));
SetLength(passwordStr, Length(password));
CopyMemory(PAnsiChar(passwordStr), @password[0], Length(password));
ret := SM4.ECB_decodeAnsiString(srcStr, passwordStr);
SetLength(Result, Length(ret));
CopyMemory(Result, PAnsiChar(ret), Length(ret));
end;
class function SM4.ECB_encodeAnsiString(srcStr, passwordStr: AnsiString): AnsiString;
var
sm4Ctx: TSM4_context;
begin
passwordStr := Copy(passwordStr + #0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0, 1, 16);
sm4_setkey_enc(@sm4Ctx, PAnsiChar(passwordStr));
SetLength(Result, Length(srcStr) + (16 - Length(srcStr) mod 16));
sm4_crypt_ecb(@sm4Ctx, SM4_ENCRYPT, Length(srcStr), PAnsiChar(srcStr), PAnsiChar(Result));
end;
class function SM4.ECB_encodeBuf(srcBuf, password: SMByteArray): SMByteArray;
var
ret, srcStr, passwordStr:AnsiString;
begin
SetLength(srcStr, Length(srcBuf));
CopyMemory(PAnsiChar(srcStr), @srcBuf[0], Length(srcBuf));
SetLength(passwordStr, Length(password));
CopyMemory(PAnsiChar(passwordStr), @password[0], Length(password));
ret := SM4.ECB_encodeAnsiString(srcStr, passwordStr);
SetLength(Result, Length(ret));
CopyMemory(Result, PAnsiChar(ret), Length(ret));
end;
{ SM4Algol.CBC }
class function SM4.CBC_decodeAnsiString(srcStr, passwordStr, IV: AnsiString): AnsiString;
var
sm4Ctx: TSM4_context;
begin
if (Length(srcStr) mod 16) <> 0 then
raise Exception.Create('Error Message');
passwordStr := Copy(passwordStr + #0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0, 1, 16);
sm4_setkey_dec(@sm4Ctx, PAnsiChar(passwordStr));
SetLength(Result, Length(srcStr));
sm4_crypt_cbc(@sm4Ctx, SM4_DECRYPT, Length(srcStr), PAnsiChar(IV), PAnsiChar(srcStr), PAnsiChar(Result));
// 把后面的填充位去除。
SetLength(Result, Length(Result) - Ord(Result[Length(Result)]));
end;
class function SM4.CBC_decodeBuf(srcBuf, password, IV: SMByteArray): SMByteArray;
var
ret, srcStr, passwordStr, pIv:AnsiString;
begin
SetLength(srcStr, Length(srcBuf));
CopyMemory(PAnsiChar(srcStr), @srcBuf[0], Length(srcBuf));
SetLength(passwordStr, Length(password));
CopyMemory(PAnsiChar(passwordStr), @password[0], Length(password));
SetLength(pIv, Length(IV));
CopyMemory(PAnsiChar(pIv), @IV[0], Length(IV));
ret := SM4.CBC_decodeAnsiString(srcStr, passwordStr, pIv);
SetLength(Result, Length(ret));
CopyMemory(Result, PAnsiChar(ret), Length(ret));
end;
class function SM4.CBC_encodeAnsiString(srcStr, passwordStr, IV: AnsiString): AnsiString;
var
sm4Ctx: TSM4_context;
begin
passwordStr := Copy(passwordStr + #0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0, 1, 16);
sm4_setkey_enc(@sm4Ctx, PAnsiChar(passwordStr));
SetLength(Result, Length(srcStr) + (16 - Length(srcStr) mod 16));
sm4_crypt_cbc(@sm4Ctx, SM4_ENCRYPT, Length(srcStr), PAnsiChar(IV), PAnsiChar(srcStr), PAnsiChar(Result));
end;
class function SM4.CBC_encodeBuf(srcBuf, password, IV: SMByteArray): SMByteArray;
var
ret, srcStr, passwordStr, pIv:AnsiString;
begin
SetLength(srcStr, Length(srcBuf));
CopyMemory(PAnsiChar(srcStr), @srcBuf[0], Length(srcBuf));
SetLength(passwordStr, Length(password));
CopyMemory(PAnsiChar(passwordStr), @password[0], Length(password));
SetLength(pIv, Length(IV));
CopyMemory(PAnsiChar(pIv), @IV[0], Length(IV));
ret := SM4.CBC_encodeAnsiString(srcStr, passwordStr, pIv);
SetLength(Result, Length(ret));
CopyMemory(Result, PAnsiChar(ret), Length(ret));
end;
// =============================================================================
// ================================SM3==========================================
// =============================================================================
function byteCycleLeft(inBuf: SMByteArray; byteLen: Integer): SMByteArray;
begin
SetLength(Result, Length(inBuf));
CopyMemory(@Result[0], @inBuf[byteLen], Length(inBuf) - byteLen);
CopyMemory(@Result[Length(inBuf) - byteLen], @inBuf[0], byteLen);
end;
function bitSmall8CycleLeft(inBuf: SMByteArray; len: Integer): SMByteArray;
var
I, t1, t2, t3: Integer;
begin
SetLength(Result, Length(inBuf));
for I := 0 to Length(Result) - 1 do begin
t1 := byte((inBuf[i] and $000000ff) shl len);
t2 := byte((inBuf[(i + 1) mod Length(Result)] and $000000ff) shr (8 - len));
t3 := byte(t1 or t2);
Result[i] := byte(t3);
end;
end;
function intToBytes(num: Integer): SMByteArray;
begin
SetLength(Result, 4);
Result[0] := byte($ff and (num shr 0));
Result[1] := byte($ff and (num shr 8));
Result[2] := byte($ff and (num shr 16));
Result[3] := byte($ff and (num shr 24));
end;
function byteToInt(bytes: SMByteArray): Integer;
var
temp: Integer;
begin
Result := 0;
temp := ($000000ff and (bytes[0])) shl 0; Result := Result or temp;
temp := ($000000ff and (bytes[1])) shl 8; Result := Result or temp;
temp := ($000000ff and (bytes[2])) shl 16; Result := Result or temp;
temp := ($000000ff and (bytes[3])) shl 24; Result := Result or temp;
end;
function back(inBuf: SMByteArray): SMByteArray;
var
outBuf: SMByteArray;
I: Integer;
begin
SetLength(outBuf, Length(inBuf));
for I := 0 to (Length(outBuf) - 1) do begin
outBuf[I] := inBuf[Length(outBuf) - I - 1];
end;
Result := outBuf;
end;
function bigEndianIntToByte(num: Integer): SMByteArray;
begin
Result := back(intToBytes(num));
end;
function bigEndianByteToInt(bytes: SMByteArray): Integer;
begin
Result := byteToInt(back(bytes));
end;
function bitCycleLeft(n, bitLen: Integer): Integer;
var
tmp: SMByteArray;
byteLen, len: Integer;
begin
bitLen := bitLen mod 32;
tmp := bigEndianIntToByte(n);
byteLen := bitLen div 8;
len := bitLen mod 8;
if byteLen > 0 then begin
tmp := byteCycleLeft(tmp, byteLen);
end;
if len > 0 then begin
tmp := bitSmall8CycleLeft(tmp, len);
end;
result := bigEndianByteToInt(tmp);
end;
function rotateLeft(x, n: Integer): Integer;
begin
Result := (x shl n) or (x shr (32 - n));
end;
function longToBytes(num: Int64): SMByteArray;
var
I: Integer;
begin
SetLength(Result, 8);
for I := 0 to 7 do begin
Result[I] := byte ($ff and (num shr (i * 8)));
end;
end;
function P1(X: Integer): Integer;
begin
Result := X xor bitCycleLeft(X, 15) xor bitCycleLeft(X, 23);
end;
function P0(X: Integer): Integer;
var
y, z: Integer;
begin
// y := rotateLeft(X, 9);
y := bitCycleLeft(X, 9);
// z := rotateLeft(X, 17);
z := bitCycleLeft(X, 17);
Result := X xor y xor z;
end;
function FF1j(X, Y, Z: Integer): Integer;
begin
Result := X xor Y xor Z;
end;
function FF2j(X, Y, Z: Integer): Integer;
begin
Result := ((X and Y) or (X and Z) or (Y and Z));
end;
function GG1j(X, Y, Z: Integer): Integer;
begin
Result := X xor Y xor Z;
end;
function GG2j(X, Y, Z: Integer): Integer;
begin
Result := (X and Y) or (not X and Z);
end;
function GGj(X, Y, Z, j: Integer): Integer;
begin
if (j >= 0) and (j <= 15) then begin
Result := GG1j(X, Y, Z);
end else begin
Result := GG2j(X, Y, Z);
end;
end;
function FFj(X, Y, Z, j: Integer): Integer;
begin
if (j >= 0) and (j <= 15) then begin
Result := FF1j(X, Y, Z);
end else begin
Result := FF2j(X, Y, Z);
end;
end;
procedure expand(bArr: SM3IntArray; var W: SM3IntArray; var W1: SM3IntArray);
var
I: Integer;
begin
SetLength(W, 68);
SetLength(W1, 64);
for I := 0 to Length(bArr) - 1 do begin
W[I] := bArr[i];
end;
for I := 16 to 67 do begin
W[i] := P1(W[I - 16] xor W[I - 9] xor bitCycleLeft(W[I - 3], 15)) xor bitCycleLeft(W[I - 13], 7) xor W[I - 6];
end;
for I := 0 to 63 do begin
W1[i] := W[i] xor W[i + 4];
end;
end;
function sm3_padding(inBuf: SMByteArray; bLen: Integer): SMByteArray;
var
k, pos: Integer;
padd, tmp: SMByteArray;
n: Int64;
begin
k := 448 - (8 * Length(inBuf) + 1) mod 512;
if k < 0 then begin
k := 960 - (8 * Length(inBuf) + 1) mod 512;
end;
k := k + 1;
SetLength(padd, k div 8);
padd[0] := $80;
n := Length(inBuf) * 8 + bLen * 512;
SetLength(Result, Length(inBuf) + k div 8 + 64 div 8);
pos := 0;
CopyMemory(@Result[0], @inBuf[0], Length(inBuf));
pos := pos + Length(inBuf);
CopyMemory(@Result[pos], @padd[0], Length(padd));
pos := pos + Length(padd);
tmp := back(longToBytes(n));
CopyMemory(@Result[pos], @tmp[0], Length(tmp));
end;
function convertIntToByte(arr: SM3IntArray): SMByteArray;
var
tmp, outArr: SMByteArray;
I: Integer;
begin
SetLength(outArr, Length(arr) * 4);
SetLength(tmp, Length(arr));
for I := 0 to Length(arr) - 1 do begin
tmp := bigEndianIntToByte(arr[i]);
CopyMemory(@outArr[i * 4], @tmp[0], 4);
end;
Result := @outArr[0];
end;
function convertByteToInt(arr: SMByteArray): SM3IntArray;
var
outArr: SM3IntArray;
tmp: SMByteArray;
I: Integer;
begin
SetLength(outArr, Length(arr) div 4);
SetLength(tmp, 4);
I := 0;
while i < Length(arr) do begin
CopyMemory(@tmp[0], @arr[i], 4);
outArr[i div 4] := bigEndianByteToInt(tmp);
I := I + 4;
end;
Result := @outArr[0];
end;
function CF2(vArr, bArr: SM3IntArray): SM3IntArray;
var
a, b, c, d, e, f, g, h, j: Integer;
ss1, ss2, tt1, tt2: Integer;
w, w1: SM3IntArray;
outBuf: SM3IntArray;
begin
a := vArr[0];
b := vArr[1];
c := vArr[2];
d := vArr[3];
e := vArr[4];
f := vArr[5];
g := vArr[6];
h := vArr[7];
expand(bArr, w, w1);
for j := 0 to 63 do begin
ss1 := (bitCycleLeft(a, 12) + e + bitCycleLeft(Tj[j], j));
ss1 := bitCycleLeft(ss1, 7);
ss2 := ss1 xor bitCycleLeft(a, 12);
tt1 := FFj(a, b, c, j) + d + ss2 + w1[j];
tt2 := GGj(e, f, g, j) + h + ss1 + w[j];
d := c;
c := bitCycleLeft(b, 9);
b := a;
a := tt1;
h := g;
g := bitCycleLeft(f, 19);
f := e;
e := P0(tt2);
end;
SetLength(outBuf, 8);
outBuf[0] := a xor vArr[0];
outBuf[1] := b xor vArr[1];
outBuf[2] := c xor vArr[2];
outBuf[3] := d xor vArr[3];
outBuf[4] := e xor vArr[4];
outBuf[5] := f xor vArr[5];
outBuf[6] := g xor vArr[6];
outBuf[7] := h xor vArr[7];
Result := outBuf;
end;
function CF(V, B: SMByteArray): SMByteArray;
var
convV, convB: SM3IntArray;
begin
convV := convertByteToInt(V);
convB := convertByteToInt(B);
Result := convertIntToByte(CF2(convV, convB))
end;
procedure TSM3Digest.doHash(bArr: SMByteArray);
var
tmp: SMByteArray;
begin
tmp := CF(V, bArr);
CopyMemory(@V[0], @tmp[0], Length(V));
cntBlock := cntBlock + 1;
end;
function TSM3Digest.interDoFinal(): SMByteArray;
var
bArr, buffer, tmp: SMByteArray;
I: Integer;
begin
SetLength(bArr, BLOCK_LENGTH);
SetLength(buffer, xBufOff);
CopyMemory(@buffer[0], @xBuf[0], Length(buffer));
tmp := sm3_padding(buffer, cntBlock);
I := 0;
while I < Length(tmp) do begin
CopyMemory(@bArr[0], @tmp[i], Length(bArr));
doHash(bArr);
I := I + BLOCK_LENGTH;
end;
Result := V;
end;
constructor TSM3Digest.Create;
begin
cntBlock := 0;
xBufOff := 0;
SetLength(v, Length(IV));
CopyMemory(@v[0], @IV[0], Length(IV));
end;
function TSM3Digest.doFinal(outBuf: SMByteArray; outOff: Integer): Integer;
var
tmp: SMByteArray;
begin
tmp := interDoFinal();
CopyMemory(@outBuf[0], @tmp[0], Length(tmp));
Result := BYTE_LENGTH;
end;
procedure TSM3Digest.doUpdate();
var
bArr: SMByteArray;
I: Integer;
begin
SetLength(bArr, BLOCK_LENGTH);
I := 0;
while I < BUFFER_LENGTH do
begin
CopyMemory(@bArr[0], @xBuf[i], Length(bArr));
doHash(bArr);
I := I + BLOCK_LENGTH;
end;
xBufOff := 0;
end;
procedure TSM3Digest.update(inBuf: SMByteArray; inOff, len: Integer);
var
partLen, inputLen, dPos: Integer;
begin
partLen := BUFFER_LENGTH - xBufOff;
inputLen := len;
dPos := inOff;
if partLen < inputLen then begin
CopyMemory(@xBuf[xBufOff], @inBuf[dPos], partLen);
inputLen := inputLen - partLen;
dPos := dPos + partLen;
doUpdate();
while inputLen > BUFFER_LENGTH do begin
CopyMemory(@xBuf[0], @inBuf[dPos], BUFFER_LENGTH);
inputLen := inputLen - BUFFER_LENGTH;
dPos := dPos + BUFFER_LENGTH;
doUpdate();
end;
end;
CopyMemory(@xBuf[xBufOff], @inBuf[dPos], inputLen);
xBufOff := xBufOff + inputLen;
end;
{ SM3 }
function byteArrayToAnsiString(arr: SMByteArray): AnsiString;
begin
SetLength(Result, Length(arr));
CopyMemory(PAnsiChar(Result), @arr[0], Length(arr));
end;
class function SM3.calcAnsiString(buf: AnsiString): AnsiString;
var
inArr, outArr: SMByteArray;
I: Integer;
begin
SetLength(inArr, Length(buf));
for I := 1 to Length(buf) do
inArr[I - 1] := ord(buf[I]);
outArr := SM3.calcBuf(inArr);
Result := byteArrayToAnsiString(outArr);
end;
class function SM3.calcBuf(buf: SMByteArray): SMByteArray;
var
sm3: TSM3Digest;
begin
sm3 := TSM3Digest.Create;
try
Setlength(Result, 32);
sm3.update(buf, 0, Length(buf));
sm3.doFinal(Result, 0);
finally
sm3.Free;
end;
end;
{ SMUtils }
class function SMUtils.HexToStr(const S: String): AnsiString;
//16进制字符串转换成字符串
var
t: Integer;
ts: String;
M, Code: Integer;
begin
t := 1;
Result := '';
while t <= Length(S) do
begin
while (t <= Length(S)) and (not (AnsiChar(S[t]) in ['0'..'9','A'..'F','a'..'f'])) do
inc(t);
if (t + 1 > Length(S)) or (not (AnsiChar(S[t + 1]) in ['0'..'9','A'..'F','a'..'f'])) then
ts:='$' + S[t]
else
ts:='$' + S[t] + S[t+1];
Val(ts, M, Code);
if Code = 0 then
Result := Result + AnsiChar(M);
inc(t, 2);
end;
end;
class function SMUtils.StrToHex(const AString: AnsiString): String;
var I: integer;
begin
Result := '';
for I := 1 to length(AString) do begin
Result := Result + IntToHex(ord(AString[I]), 2) + ' ';
if i mod 16 = 0 then
Result := Result + #13#10;
end
end;
class procedure SMUtils.testAll;
var
sKey, srcStr, dstStr, decodeStr, pIv, msgStr: AnsiString;
srcArray, keyArray, retArray, ivArray, decArray, md, msgArr: SMByteArray;
res, t: string;
procedure Status(msg: String);
begin
Writeln(msg);
end;
begin
// 分配一个控制台窗口,用于输出调试信息。
// 原来是采用 DUnit 进行测试,怕其他人环境不完整,修改为不依赖于第三方库的方式。
AllocConsole;
sKey := '0123456789ABCDEFFEDCBA9876543210';
SrcStr := AnsiString(AnsiToUtf8('011234567890测试'));
Status('=====================SM4测试=====================');
Status('');
Status('*************ECB模式*************');
Status('原文:(src): 011234567890测试');
Status('秘钥:(key): 0123456789ABCDEFFEDCBA9876543210');
Status('加密正确结果为:4356153999C1046859556F324B7CA5F806FBB9DB755372FAD2EF9CA8DD7EB944');
Status('解密正确结果为:011234567890测试');
Status('--------AnsiString测试--------');
dstStr := SM.SM4.ECB_encodeAnsiString(srcStr, sKey);
if CompareText(StrToHex(dstStr), '4356153999C1046859556F324B7CA5F806FBB9DB755372FAD2EF9CA8DD7EB944') = 0 then
res := '正确'
else
res := '错误';
Status('encodeAnsiString加密结果为:dstStr: ' + StrToHex(dstStr) + ', 加密结果' + res); // 输出:dstStr: 4356153999C1046859556F324B7CA5F806FBB9DB755372FAD2EF9CA8DD7EB944
decodeStr := SM.SM4.ECB_decodeAnsiString(dstStr, sKey);
if CompareText(Utf8ToAnsi(decodeStr), '011234567890测试') = 0 then
res := '正确'
else
res := '错误';
Status('decodeAnsiString解密结果为:decodeStr(src):' + Utf8ToAnsi(decodeStr) + ', 解密结果' + res); // 输出:decodeStr: 011234567890测试
Status('--------buf测试--------');
SetLength(srcArray, Length(SrcStr));
SetLength(keyArray, Length(sKey));
CopyMemory(srcArray, PAnsiChar(SrcStr), Length(SrcStr));
CopyMemory(keyArray, PAnsiChar(sKey), Length(sKey));
retArray := SM.SM4.ECB_encodeBuf(srcArray, keyArray);
SetLength(dstStr, Length(retArray));
CopyMemory(PAnsiChar(dstStr), @retArray[0], length(retArray));
if CompareText(StrToHex(dstStr), '4356153999C1046859556F324B7CA5F806FBB9DB755372FAD2EF9CA8DD7EB944') = 0 then
res := '正确'
else
res := '错误';
Status('encodeBuf加密结果为:dstStr: ' + StrToHex(dstStr) + ', 加密结果' + res); // 输出:dstStr: 4356153999C1046859556F324B7CA5F806FBB9DB755372FAD2EF9CA8DD7EB944
decArray := SM.SM4.ECB_decodeBuf(retArray, keyArray);
SetLength(decodeStr, Length(decArray));
CopyMemory(PAnsiChar(decodeStr), @decArray[0], length(decArray));
if CompareText(Utf8ToAnsi(decodeStr), '011234567890测试') = 0 then
res := '正确'
else
res := '错误';
Status('decodeBuf解密结果为:decodeStr(src):' + Utf8ToAnsi(decodeStr) + ', 解密结果' + res); // 输出:decodeStr: 011234567890测试
Status('');
Status('*************CBC模式*************');
sKey := 'JeF8U9wHFOMfs2Y8';
pIv := 'UISwD9fW6cFh9SNS';
Status('原文:(src): 011234567890测试');
Status('秘钥:(key): UISwD9fW6cFh9SNS');
Status('初始向量:(IV): JeF8U9wHFOMfs2Y8');
Status('加密正确结果为:0456F645A06778DF0C3623AC5EB578F0765EE559CC7466CE71F05F94E9E10D45');
Status('解密正确结果为:011234567890测试');
Status('--------AnsiString测试--------');
dstStr := SM.SM4.CBC_encodeAnsiString(srcStr, sKey, pIv); // 输出:dstStr: 0456F645A06778DF0C3623AC5EB578F0765EE559CC7466CE71F05F94E9E10D45
if CompareText(StrToHex(dstStr), '0456F645A06778DF0C3623AC5EB578F0765EE559CC7466CE71F05F94E9E10D45') = 0 then
res := '正确'
else
res := '错误';
Status('encodeAnsiString加密结果为:dstStr: ' + StrToHex(dstStr) + ', 加密结果' + res);
if CompareText(Utf8ToAnsi(decodeStr), '011234567890测试') = 0 then
res := '正确'
else
res := '错误';
decodeStr := SM.SM4.CBC_decodeAnsiString(dstStr, sKey, pIv);
Status('decodeAnsiString解密结果为:decodeStr(src):' + Utf8ToAnsi(decodeStr) + ', 解密结果' + res); // 输出:decodeStr(src):011234567890测试
Status('--------Buf测试--------');
SetLength(srcArray, Length(SrcStr));
SetLength(keyArray, Length(sKey));
SetLength(ivArray, Length(pIv));
CopyMemory(srcArray, PAnsiChar(srcStr), Length(srcStr));
CopyMemory(keyArray, PAnsiChar(sKey), Length(sKey));
CopyMemory(ivArray, PAnsiChar(pIv), Length(pIv));
retArray := SM.SM4.CBC_encodeBuf(srcArray, keyArray, ivArray);
SetLength(dstStr, Length(retArray));
CopyMemory(PAnsiChar(dstStr), @retArray[0], length(retArray));
if CompareText(StrToHex(dstStr), '0456F645A06778DF0C3623AC5EB578F0765EE559CC7466CE71F05F94E9E10D45') = 0 then
res := '正确'
else
res := '错误';
Status('encodeBuf加密结果为:dstStr: ' + StrToHex(dstStr) + ', 加密结果' + res); // 输出:dstStr: 0456F645A06778DF0C3623AC5EB578F0765EE559CC7466CE71F05F94E9E10D45
decArray := SM.SM4.CBC_decodeBuf(retArray, keyArray, ivArray);
SetLength(decodeStr, Length(decArray));
CopyMemory(PAnsiChar(decodeStr), @decArray[0], length(decArray));
if CompareText(Utf8ToAnsi(decodeStr), '011234567890测试') = 0 then
res := '正确'
else
res := '错误';
decodeStr := SM.SM4.CBC_decodeAnsiString(dstStr, sKey, pIv);
Status('decodeBuf解密结果为:decodeStr(src):' + Utf8ToAnsi(decodeStr) + ', 解密结果' + res); // 输出:decodeStr(src):011234567890测试
Status('');
Status('=====================SM3测试=====================');
msgStr := 'B299B04047767655FEAB540E6BFE2B335000220180507224028201805072240288D';
Status('输入消息为:B299B04047767655FEAB540E6BFE2B335000220180507224028201805072240288D');
Status('输出正确摘要为:357530A05333779826BE7F93374E9C97F915B5B1626923F8B5D943CD378E574D');
SetLength(msgArr, Length(msgStr));
SetLength(md, 32);
CopyMemory(msgArr, PAnsiChar(msgStr), Length(msgStr));
md := SM.SM3.calcBuf(msgArr);
if CompareText(StrToHex(byteArrayToAnsiString(md)), '357530A05333779826BE7F93374E9C97F915B5B1626923F8B5D943CD378E574D') = 0 then
res := '正确'
else
res := '错误';
Status('buf测试:calcBuf方法结果:' + StrToHex(byteArrayToAnsiString(md)) + ',结果' + res); // 结果:357530A05333779826BE7F93374E9C97F915B5B1626923F8B5D943CD378E574D
if CompareText(StrToHex(SM.SM3.calcAnsiString(msgStr)), '357530A05333779826BE7F93374E9C97F915B5B1626923F8B5D943CD378E574D') = 0 then
res := '正确'
else
res := '错误';
Status('AnsiString测试:calcAnsiString方法结果:' + StrToHex(SM.SM3.calcAnsiString(msgStr)) + ',结果' + res); // 结果1:357530A05333779826BE7F93374E9C97F915B5B1626923F8B5D943CD378E574D
Status('');
Status('');
Status('测试结束,按回车键关闭!');
Readln(t);
FreeConsole;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado ās tabelas
[PCP_OP_CABECALHO] e [PCP_OP_DETALHE]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit PcpOpController;
interface
uses
Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller,
VO, ZDataset, PcpOpCabecalhoVO, PcpOpDetalheVO, PcpInstrucaoOpVO,
PcpServicoVO, PcpServicoColaboradorVO, PcpServicoEquipamentoVO;
type
TPcpOpController = class(TController)
private
public
class function Consulta(pFiltro: string; pPagina: string): TZQuery;
class function ConsultaLista(pFiltro: string): TListaPcpOpCabecalhoVO;
class function ConsultaObjeto(pFiltro: string): TPcpOpCabecalhoVO;
class procedure Insere(pObjeto: TPcpOpCabecalhoVO);
class function Altera(pObjeto: TPcpOpCabecalhoVO): boolean;
class function Exclui(pId: integer): boolean;
class function ExcluiInstrucao(pId: integer): boolean;
class function ExcluiItem(pId: integer): boolean;
class function ExcluiServico(pId: integer): boolean;
class function ExcluiColaborador(pId: integer): boolean;
class function ExcluiEquipamento(pId: integer): boolean;
end;
implementation
uses
UDataModule, T2TiORM;
var
ObjetoLocal: TPcpOpCabecalhoVO;
class function TPcpOpController.Consulta(pFiltro: string; pPagina: string): TZQuery;
begin
try
ObjetoLocal := TPcpOpCabecalhoVO.Create;
Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina);
finally
ObjetoLocal.Free;
end;
end;
class function TPcpOpController.ConsultaLista(pFiltro: string): TListaPcpOpCabecalhoVO;
begin
try
ObjetoLocal := TPcpOpCabecalhoVO.Create;
Result := TListaPcpOpCabecalhoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True));
finally
ObjetoLocal.Free;
end;
end;
class function TPcpOpController.ConsultaObjeto(pFiltro: string): TPcpOpCabecalhoVO;
begin
try
Result := TPcpOpCabecalhoVO.Create;
Result := TPcpOpCabecalhoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
finally
end;
end;
class procedure TPcpOpController.Insere(pObjeto: TPcpOpCabecalhoVO);
var
UltimoID, IDDetalhe, IDServico: integer;
I, J, K: integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
// Instrucoes
try
for I := 0 to pObjeto.ListaPcpInstrucaoOpVO.Count - 1 do ;
begin
pObjeto.ListaPcpInstrucaoOpVO[I].IdPcpOpCabecalho := UltimoID;
TT2TiORM.Inserir(pObjeto.ListaPcpInstrucaoOpVO[I]);
end;
finally
end;
// Detalhe
try
for I := 0 to pObjeto.ListaPcpOpDetalheVO.Count -1 do
begin
pObjeto.ListaPcpOpDetalheVO[I].IdPcpOpCabecalho := UltimoID;
IDDetalhe := TT2TiORM.Inserir(pObjeto.ListaPcpOpDetalheVO[I]);
for J := 0 to TPcpOpDetalheVO(pObjeto.ListaPcpOpDetalheVO[I]).ListaPcpServicoVO.Count -1 do
begin
TPcpOpDetalheVO(pObjeto.ListaPcpOpDetalheVO[I]).ListaPcpServicoVO[J].IdPcpOpDetalhe:= IDDetalhe;
IDServico := TT2TiORM.Inserir(TPcpOpDetalheVO(pObjeto.ListaPcpOpDetalheVO[I]).ListaPcpServicoVO[J]);
for K := 0 to TPcpServicoVO(pObjeto.ListaPcpOpDetalheVO[I].ListaPcpServicoVO[J]).ListaPcpColabradorVO.Count -1 do
begin
TPcpServicoVO(pObjeto.ListaPcpOpDetalheVO[I].ListaPcpServicoVO[J]).ListaPcpColabradorVO[K].IdPcpServico := IDServico;
TT2TiORM.Inserir(TPcpServicoVO(pObjeto.ListaPcpOpDetalheVO[I].ListaPcpServicoVO[J]).ListaPcpColabradorVO[K]);
end;
for K := 0 to TPcpServicoVO(pObjeto.ListaPcpOpDetalheVO[I].ListaPcpServicoVO[J]).ListaPcpServicoEquipamentoVO.Count -1 do
begin
TPcpServicoVO(pObjeto.ListaPcpOpDetalheVO[I].ListaPcpServicoVO[J]).ListaPcpServicoEquipamentoVO[K].IdPcpServico := IDServico;
TT2TiORM.Inserir(TPcpServicoVO(pObjeto.ListaPcpOpDetalheVO[I].ListaPcpServicoVO[J]).ListaPcpServicoEquipamentoVO[K]);
end;
end;
end;
finally
end;
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TPcpOpController.Altera(pObjeto: TPcpOpCabecalhoVO): boolean;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
finally
end;
end;
class function TPcpOpController.Exclui(pId: integer): boolean;
var
ObjetoLocal: TPcpOpCabecalhoVO;
begin
try
ObjetoLocal := TPcpOpCabecalhoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.ExcluiColaborador(pId: integer): boolean;
var
ObjetoLocal: TPcpServicoColaboradorVO;
begin
try
ObjetoLocal := TPcpServicoColaboradorVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.ExcluiEquipamento(pId: integer): boolean;
var
ObjetoLocal: TPcpServicoEquipamentoVO;
begin
try
ObjetoLocal := TPcpServicoEquipamentoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.ExcluiInstrucao(pId: integer): boolean;
var
ObjetoLocal: TPcpInstrucaoOpVO;
begin
try
ObjetoLocal := TPcpInstrucaoOpVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.ExcluiItem(pId: integer): boolean;
var
ObjetoLocal: TPcpOpDetalheVO;
begin
try
ObjetoLocal := TPcpOpDetalheVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.ExcluiServico(pId: integer): boolean;
var
ObjetoLocal: TPcpServicoVO;
begin
try
ObjetoLocal := TPcpServicoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
initialization
Classes.RegisterClass(TPcpOpController);
finalization
Classes.UnRegisterClass(TPcpOpController);
end.
|
unit uRepParentListFilter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uRepParentLookupFilter, Buttons, StdCtrls, DB, DBClient,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxListBox, siComp;
type
TRepParentListFilter = class(TRepParentLookupFilter)
btAdd: TSpeedButton;
btRemove: TSpeedButton;
clbFilter: TcxListBox;
btAddAll: TSpeedButton;
btRemoveAll: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btAddClick(Sender: TObject);
procedure btRemoveClick(Sender: TObject);
procedure btAddAllClick(Sender: TObject);
procedure btRemoveAllClick(Sender: TObject);
private
FListValues: TStringList;
procedure FilterLookup;
procedure AddToList(AID, AValue: String);
procedure RemoveFromList;
function GetListValues: String;
public
function GetValue: Variant; override;
function GetFilterString: String; override;
end;
implementation
uses uRepParentFilter;
{$R *.dfm}
{ TRepParentListFilter }
procedure TRepParentListFilter.AddToList(AID, AValue: String);
begin
FListValues.Add(AID);
clbFilter.Items.Add(AValue);
FilterLookup;
end;
function TRepParentListFilter.GetValue: Variant;
begin
Result := GetListValues;
end;
procedure TRepParentListFilter.RemoveFromList;
begin
if clbFilter.ItemIndex <> -1 then
begin
FListValues.Delete(clbFilter.ItemIndex);
clbFilter.DeleteSelected;
end;
FilterLookup;
end;
procedure TRepParentListFilter.FormCreate(Sender: TObject);
begin
inherited;
FMultValue := True;
FListValues := TStringList.Create;
end;
function TRepParentListFilter.GetListValues: String;
var
i: integer;
begin
Result := '';
for i := 0 to Pred(clbFilter.Items.Count) do
Result := Result + FListValues[i] + ';';
end;
procedure TRepParentListFilter.FilterLookup;
var
i: Integer;
sFilter: String;
begin
sFilter := '';
cdsFilter.Filtered := True;
for i := 0 to Pred(clbFilter.Items.Count) do
begin
if sFilter <> '' then
sFilter := sFilter + ' AND ';
sFilter := sFilter + lcFilter.Properties.KeyFieldNames + ' <> ' + FListValues[i];
end;
cdsFilter.Filter := sFilter;
end;
procedure TRepParentListFilter.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FListValues);
end;
procedure TRepParentListFilter.btAddClick(Sender: TObject);
begin
inherited;
if lcFilter.Text <> '' then
begin
AddToList(lcFilter.EditValue, lcFilter.Text);
lcFilter.SetFocus;
end;
end;
procedure TRepParentListFilter.btRemoveClick(Sender: TObject);
begin
inherited;
RemoveFromList;
end;
procedure TRepParentListFilter.btAddAllClick(Sender: TObject);
begin
inherited;
with cdsFilter do
while not Eof do
begin
First;
AddToList(FieldByName(lcFilter.Properties.KeyFieldNames).AsString,
FieldByName(lcFilter.Properties.ListFieldNames).AsString);
end;
end;
procedure TRepParentListFilter.btRemoveAllClick(Sender: TObject);
begin
inherited;
FListValues.Clear;
clbFilter.Clear;
FilterLookup;
end;
function TRepParentListFilter.GetFilterString: String;
var
sFilter, sAll : String;
begin
IDLanguage := 1;
Case IDLanguage of
1 : sAll := ' All; ';
2 : sAll := ' Tudo; ';
3 : sAll := ' Tudo; ';
end;
if cdsFilter.RecordCount = 0 then
begin
Result := lblFilter.Caption + sAll;
end
else
begin
sFilter := StringReplace(clbFilter.Items.CommaText, '"','', [rfReplaceAll]);
if sFilter <> '' then
if Length(sFilter) > 100 then
Result := lblFilter.Caption + ' ' + Copy(sFilter,0,200)+' ...; '
else
Result := lblFilter.Caption + ' ' + sFilter+'; ';
end;
end;
end.
|
unit MOMainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Ibase, FIBDatabase, pFIBDatabase, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData,
cxTextEdit, ComCtrls, ToolWin, ImgList, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridBandedTableView,
cxGridDBBandedTableView, cxClasses, cxControls, cxGridCustomView, cxGrid,
pFibDataSet, cxLookAndFeelPainters, cxContainer, cxRadioGroup, StdCtrls,
cxButtons, ExtCtrls, cxMaskEdit, cxButtonEdit, FIBDataSet, frxClass,
frxDBSet, frxCross, frxExportHTML, frxExportPDF, frxExportRTF,
frxExportXML, frxExportXLS, cxDropDownEdit;
type
TTMoMainForm = class(TForm)
WorkDatabase: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
Panel1: TPanel;
cxButton1: TcxButton;
cxButton2: TcxButton;
frxDBDataset1: TfrxDBDataset;
ResultsDataSet: TpFIBDataSet;
frxCrossObject1: TfrxCrossObject;
frxXLSExport1: TfrxXLSExport;
frxXMLExport1: TfrxXMLExport;
frxRTFExport1: TfrxRTFExport;
frxPDFExport1: TfrxPDFExport;
frxHTMLExport1: TfrxHTMLExport;
Panel4: TPanel;
cbMonthBeg: TcxComboBox;
cbYearBeg: TcxComboBox;
Label3: TLabel;
frxReport1: TfrxReport;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
private
{ Private declarations }
ActualDate:TDateTime;
public
{ Public declarations }
constructor Create(AOwner:TComponent;DbHandle:TISC_DB_HANDLE;id_User:Int64);reintroduce;
end;
implementation
uses GlobalSpr, BaseTypes, Resources_unitb, DateUtils;
{$R *.dfm}
{ TTMoMainForm }
constructor TTMoMainForm.Create(AOwner: TComponent;
DbHandle: TISC_DB_HANDLE; id_User: Int64);
var I:Integer;
begin
inherited Create(AOwner);
WorkDatabase.Handle:=DbHandle;
ReadTransaction.StartTransaction;
self.ActualDate:=Date;
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_01));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_02));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_03));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_04));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_05));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_06));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_07));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_08));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_09));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_10));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_11));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_12));
for i:=BASE_YEAR to YearOf(ActualDate) do
begin
cbYearBeg.Properties.Items.Add(TRIM(IntToStr(i)));
end;
cbMonthBeg.ItemIndex:=MonthOf(ActualDate)-1;
for i:=0 to cbYearBeg.Properties.Items.Count-1 do
begin
if pos(cbYearBeg.Properties.Items[i],IntToStr(YearOf(ActualDate)))>0
then begin
cbYearBeg.ItemIndex:=i;
break;
end;
end;
end;
procedure TTMoMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TTMoMainForm.cxButton1Click(Sender: TObject);
begin
ActualDate:=StrToDate('01.'+IntToStr(cbMonthBeg.ItemIndex+1)+'.'+cbYearBeg.Properties.Items[cbYearBeg.ItemIndex]);
if ResultsDataSet.Active then ResultsDataSet.Close;
ResultsDataSet.SelectSQL.Text:='select * from MBOOK_MO_GET_DATA('+''''+DateToStr(ActualDate)+''''+',0)';
ResultsDataSet.Open;
frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Mbook\ReportMOMain.fr3',true);
frxReport1.Variables['DATA']:=ActualDate;
frxReport1.PrepareReport(true);
frxReport1.ShowPreparedReport;
end;
procedure TTMoMainForm.cxButton2Click(Sender: TObject);
begin
Close;
end;
end.
|
unit Modules.Database;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
Data.DB, FireDAC.Comp.Client, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef,
FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteWrapper.Stat, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet,
System.Generics.Collections, Classes.StormTrack;
type
TDbController = class(TDataModule)
Connection: TFDConnection;
QuYears: TFDQuery;
QuStorms: TFDQuery;
QuStormsSID: TStringField;
QuStormsYEAR: TWideStringField;
QuStormsNAME: TStringField;
QuYearsYEAR: TWideStringField;
QuTracks: TFDQuery;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure OpenStorms( AYear: String );
procedure GetTrack(
AId: String;
ATrack: TObjectList<TStormTrack>
) ;
end;
//var
// DbController: TDbController;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TDbController.DataModuleCreate(Sender: TObject);
begin
QuYears.Active := True;
end;
procedure TDbController.DataModuleDestroy(Sender: TObject);
begin
Connection.Close;
end;
procedure TDbController.GetTrack(
AId: String;
ATrack: TObjectList<TStormTrack>
);
var
LTrack: TStormTrack;
begin
QuTracks.Active := False;
QuTracks.ParamByName('id').AsString := AId;
QuTracks.Active := True;
while not QuTracks.Eof do
begin
LTrack := TStormTrack.Create;
LTrack.Latitude := QuTracks.FieldByName('lat').AsFloat;
LTrack.Longitude := QuTracks.FieldByName('lon').AsFloat;
LTrack.Wind := QuTracks.FieldByName('wmo_wind').AsInteger;
LTrack.DT := QuTracks.FieldByName('iso_time').AsDateTime;
LTrack.Pressure := QuTracks.FieldByName('wmo_pres').AsInteger;
ATrack.Add(LTrack);
QuTracks.Next;
end;
QuTracks.Active := False;
end;
procedure TDbController.OpenStorms(AYear: String);
begin
QuStorms.Active := False;
QuStorms.ParamByName('year').AsString := AYear;
QuStorms.Active := True;
end;
end.
|
unit Common;
interface
uses pFIBDataBase, pFIBStoredProc, FIBDatabase, FIBDataSet, pFIBDataSet;
type
TSPOptions = record
soAdd : boolean;
soDel : boolean;
soMod : boolean;
soSel : boolean;
end;
const
COMMON_SP_OPTIONS_ALL : TSPOptions = (soAdd: true; soDel: true; soMod: true; soSel: true);
COMMON_SP_OPTIONS_WITHOUT_SEL : TSPOptions = (soAdd: true; soDel: true; soMod: true; soSel: false);
var
common_database : TpFIBDatabase;
common_read_transaction : TpFIBTransaction;
common_write_transaction : TpFIBTransaction;
procedure CommonInitialize(Database : TpFIBDatabase; ReadTransaction : TpFIBTransaction; WriteTransaction : TpFIBTransaction);
procedure GetNewPrimaryKey(StoredProc : TpFIBStoredProc; const TableName : string; var NewID : integer);
procedure GetNewPrimaryKey2(DS : TpFIBDataSet; const TableName : string; var NewID : integer);
//String functions
function GetFirstWord(const text : string) : string;
function CutFirstWord(const text : string) : string;
implementation
uses SysUtils, SYS_OPTIONS;
function GetFirstWord(const text : string) : string;
var
i : integer;
begin
Result := '';
if text = '' then exit;
i := 1;
while (i <= Length(text)) and (Text[i] <> ' ') and (Text[i] <> '.') do inc(i);
Result := Copy(Text, 1, i - 1);
end;
function CutFirstWord(const text : string) : string;
var
i : integer;
begin
Result := '';
if text = '' then exit;
i := 1;
while (i <= Length(text)) and (Text[i] <> ' ') and (Text[i] <> '.') do inc(i);
Result := Trim(Copy(Text, i + 1, Length(Text) - i));
end;
procedure CommonInitialize(Database : TpFIBDatabase; ReadTransaction : TpFIBTransaction; WriteTransaction : TpFIBTransaction);
begin
common_database := Database;
common_read_transaction := ReadTransaction;
common_write_transaction := WriteTransaction;
end;
procedure GetNewPrimaryKey(StoredProc : TpFIBStoredProc; const TableName : string; var NewID : integer);
var
id : integer;
tr : TFIBTransaction;
begin
// StoredProc.Transaction.StartTransaction;
tr := StoredProc.Transaction;
StoredProc.Transaction := COMMON_READ_TRANSACTION;
if not StoredProc.Transaction.Active then StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PROC_GEN_'+ TableName, []);
// StoredProc.Transaction.Commit;
id := StoredProc['NEW_ID'].AsInteger;
StoredProc.Close;
StoredProc.Transaction := tr;
NewID := StrToInt(IntToStr(id) + IntToStr(SYS_SERVER));
end;
procedure GetNewPrimaryKey2(DS : TpFIBDataSet; const TableName : string; var NewID : integer);
var
id : integer;
begin
DS.SelectSQL.Text := 'select * from PROC_GEN_'+ TableName;
DS.Open;
id := DS['NEW_ID'];
DS.Close;
NewID := StrToInt(IntToStr(id) + IntToStr(SYS_SERVER));
end;
end.
|
unit Dialog_EditUser;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, RzEdit,ADODB,Class_User,Class_DBPool;
type
TDialogEditUser = class(TForm)
Button1: TButton;
Button2: TButton;
Edit_Name: TRzEdit;
Edit_Code: TRzEdit;
Edit_Pswd: TRzEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FEditCode:Integer;
FUser :TUser;
protected
procedure SetInitialize;
procedure SetCommonParams;
public
procedure RendUser;
function CheckLicit:Boolean;
procedure DoSaveDB;
procedure InsertDB;
procedure UpdateDB;
end;
var
DialogEditUser: TDialogEditUser;
function FuncEditUser(AEditCode:Integer;AUser:TUser):Integer;
implementation
uses
UtilLib,UtilLib_UiLib;
{$R *.dfm}
function FuncEditUser(AEditCode:Integer;AUser:TUser):Integer;
begin
try
DialogEditUser:=TDialogEditUser.Create(nil);
DialogEditUser.FEditCode:=AEditCode;
DialogEditUser.FUser :=AUser;
Result:=DialogEditUser.ShowModal;
finally
FreeAndNil(DialogEditUser);
end;
end;
{ TDialogEditUser }
procedure TDialogEditUser.SetCommonParams;
const
ArrCaption:array[0..2] of string=('新增用户','编辑用户','修改密码');
begin
Caption:=ArrCaption[FEditCode];
end;
procedure TDialogEditUser.SetInitialize;
begin
SetCommonParams;
if FEditCode in [1,2] then
begin
RendUser;
end;
end;
procedure TDialogEditUser.FormShow(Sender: TObject);
begin
SetInitialize;
end;
procedure TDialogEditUser.Button1Click(Sender: TObject);
begin
DoSaveDB;
end;
procedure TDialogEditUser.DoSaveDB;
begin
if not CheckLicit then Exit;
case FEditCode of
0:InsertDB;
1:UpdateDB;
2:UpdateDB;
end;
end;
procedure TDialogEditUser.InsertDB;
var
ADOCon:TADOConnection;
begin
if ShowBox('是否确定新增用户')<>Mrok then Exit;
try
ADOCon:=TDBPool.GetConnect();
FUser:=TUser.Create;
FUser.UserIdex:=FUser.GetNextCode(ADOCon);
FUser.UserCode:=Trim(Edit_Code.Text);
FUser.UserName:=Trim(Edit_Name.Text);
FUser.UserPswd:=Trim(Edit_Pswd.Text);
FUser.UserMemo:='';
FUser.InsertDB(ADOCon);
ShowMessage('保存成功');
ModalResult:=mrOk;
finally
FreeAndNil(ADOCon);
end;
end;
procedure TDialogEditUser.UpdateDB;
var
ADOCon:TADOConnection;
StrA :string;
begin
case FEditCode of
1:StrA:='是否确定更改用户信息';
2:StrA:='是否确定更改密码';
end;
try
if ShowBox(StrA)<>Mrok then Exit;
ADOCon:=TDBPool.GetConnect();
FUser.UserCode:=Trim(Edit_Code.Text);
FUser.UserName:=Trim(Edit_Name.Text);
FUser.UserPswd:=Trim(Edit_Pswd.Text);
FUser.UserMemo:='';
FUser.UpdateDB(ADOCon);
ShowMessage('保存成功');
ModalResult:=mrOk;
finally
FreeAndNil(ADOCon);
end;
end;
function TDialogEditUser.CheckLicit: Boolean;
begin
Result:=False;
Result:=True;
end;
procedure TDialogEditUser.RendUser;
begin
Edit_Name.Text:=FUser.UserName;
Edit_Code.Text:=FUser.UserCode;
Edit_Pswd.Text:=FUser.UserPswd;
if FEditCode=1 then
begin
Edit_Pswd.Enabled:=False;
end else
if FEditCode=2 then
begin
Edit_Code.Enabled:=False;
Edit_Name.Enabled:=False;
end;
end;
procedure TDialogEditUser.Button2Click(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TDialogEditUser.FormCreate(Sender: TObject);
begin
UtilLib_UiLib.SetCommonDialogParams(Self);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.