text stringlengths 14 6.51M |
|---|
unit ncDebug;
{
ResourceString: Dario 12/03/13
}
interface
uses
SyncObjs,
SysUtils,
Dialogs;
var
AbriuArqDebug : Boolean = False;
DebugAtivo : Boolean = False;
arqDebug : TextFile;
debugCS : TCriticalSection = nil;
nomearqdebug : String = 'debug.txt'; // do not localize
procedure DebugMsg(S: String; const aShowMsg: Boolean = False); overload;
procedure DebugMsg(Sender:TObject; S: String; const aShowMsg: Boolean = False); overload;
procedure DebugMsgEsp(S: String; const aShowMsg, aForcar: Boolean); overload;
procedure DebugMsgEsp(Sender:TObject; S: String; const aShowMsg, aForcar: Boolean); overload;
procedure DesativaDebug;
implementation
uses
uLogs;
procedure AbreArquivo;
var S: String;
begin
debugCS.Enter;
try
try
S := ExtractFilePath(ParamStr(0))+nomearqdebug;
AssignFile(arqDebug, S);
if FileExists(S) then
Append(arqDebug) else
Rewrite(arqDebug);
Writeln(arqDebug, '-------------------------------------------------');
Writeln(arqDebug, ' INICIO: '+FormatDateTime('dd/mm/yyyy hh:mm:ss', Now)); // do not localize
Writeln(arqDebug, '-------------------------------------------------');
except
end;
AbriuArqDebug := True;
finally
debugCS.Leave;
end;
end;
procedure DebugMsgEsp(S: String; const aShowMsg, aForcar: Boolean);
//var SaveAtivo : Boolean;
begin
{debugCS.Enter;
try
try
SaveAtivo := DebugAtivo;
if aForcar or DebugAtivo then begin
if not AbriuArqDebug then AbreArquivo;
if Trim(S)>'' then
Writeln(arqDebug, FormatDateTime('dd/mm/yyyy hh:mm:ss - ', Now)+S) else
Writeln(arqDebug);
Flush(arqDebug);
end;
if aForcar and (not SaveAtivo) then
DesativaDebug;
except
end;
finally
debugCS.Leave;
end;}
if aForcar then
gLog.ForceLog(nil, [lcDebug], S) else
gLog.Log(nil, [lcDebug], S);
gLog.ForceLogWrite;
end;
procedure DebugMsgEsp(Sender:TObject;S: String; const aShowMsg, aForcar: Boolean);
begin
if aForcar then
gLog.ForceLog(Sender, [lcDebug], S) else
gLog.Log(Sender, [lcDebug], S);
gLog.ForceLogWrite;
end;
procedure DebugMsg(S: String; const aShowMsg: Boolean = False);
begin
//DebugMsgEsp(S, aShowMsg, False);
gLog.Log(nil, [lcDebug], S);
gLog.ForceLogWrite;
end;
procedure DebugMsg(Sender:TObject;S: String; const aShowMsg: Boolean = False);
begin
//DebugMsgEsp(S, aShowMsg, False);
gLog.Log(Sender, [lcDebug], S);
gLog.ForceLogWrite;
end;
procedure DesativaDebug;
begin
DebugCS.Enter;
try
DebugAtivo := False;
if AbriuArqDebug then begin
CloseFile(arqDebug);
AbriuArqDebug := False;
end;
finally
DebugCS.Leave;
end;
end;
initialization
DebugCS := TCriticalSection.Create;
AbriuArqDebug := False;
finalization
try
DesativaDebug;
except
end;
FreeAndNil(DebugCS);
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, FileCtrl, ExtCtrls, Monkey;
type
TMainForm = class(TForm)
DriveList: TDriveComboBox;
FolderList: TDirectoryListBox;
FileList: TFileListBox;
CloseButton: TButton;
InfoBevel: TBevel;
IconImage: TImage;
ValidHeaderLabel: TLabel;
FileLengthLabel: TLabel;
ValidHeaderValue: TEdit;
ChannelModeValue: TEdit;
ChannelModeLabel: TLabel;
SampleRateLabel: TLabel;
BitsPerSampleLabel: TLabel;
DurationLabel: TLabel;
SampleRateValue: TEdit;
BitsPerSampleValue: TEdit;
DurationValue: TEdit;
FileLengthValue: TEdit;
CompressionLabel: TLabel;
CompressionValue: TEdit;
PeakLevelLabel: TLabel;
PeakLevelValue: TEdit;
FramesLabel: TLabel;
FramesValue: TEdit;
FlagsLabel: TLabel;
FlagsValue: TEdit;
SeekElementsLabel: TLabel;
SeekElementsValue: TEdit;
TotalSamplesLabel: TLabel;
TotalSamplesValue: TEdit;
procedure CloseButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FileListChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
Monkey: TMonkey;
procedure ClearAll;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure TMainForm.ClearAll;
begin
{ Clear all captions }
ValidHeaderValue.Text := '';
FileLengthValue.Text := '';
ChannelModeValue.Text := '';
SampleRateValue.Text := '';
BitsPerSampleValue.Text := '';
DurationValue.Text := '';
FlagsValue.Text := '';
FramesValue.Text := '';
TotalSamplesValue.Text := '';
PeakLevelValue.Text := '';
SeekElementsValue.Text := '';
CompressionValue.Text := '';
end;
procedure TMainForm.CloseButtonClick(Sender: TObject);
begin
{ Exit }
Close;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
{ Create object and reset captions }
Monkey := TMonkey.Create;
ClearAll;
end;
procedure TMainForm.FileListChange(Sender: TObject);
begin
{ Clear captions }
ClearAll;
if FileList.FileName = '' then exit;
if FileExists(FileList.FileName) then
{ Load Monkey's Audio data }
if Monkey.ReadFromFile(FileList.FileName) then
if Monkey.Valid then
begin
{ Fill captions }
ValidHeaderValue.Text := 'Yes, version ' + Monkey.Version;
FileLengthValue.Text := IntToStr(Monkey.FileLength) + ' bytes';
ChannelModeValue.Text := Monkey.ChannelMode;
SampleRateValue.Text := IntToStr(Monkey.Header.SampleRate) + ' hz';
BitsPerSampleValue.Text := IntToStr(Monkey.Bits) + ' bit';
DurationValue.Text := FormatFloat('.000', Monkey.Duration) + ' sec.';
FlagsValue.Text := IntToStr(Monkey.Header.Flags);
FramesValue.Text := IntToStr(Monkey.Header.Frames);
TotalSamplesValue.Text := IntToStr(Monkey.Samples);
PeakLevelValue.Text := FormatFloat('00.00', Monkey.Peak) + '% - ' +
IntToStr(Monkey.Header.PeakLevel);
SeekElementsValue.Text := IntToStr(Monkey.Header.SeekElements);
CompressionValue.Text := FormatFloat('00.00', Monkey.Ratio) + '% - ' +
Monkey.Compression;
end
else
{ Header not found }
ValidHeaderValue.Text := 'No'
else
{ Read error }
ShowMessage('Can not read header in the file: ' + FileList.FileName)
else
{ File does not exist }
ShowMessage('The file does not exist: ' + FileList.FileName);
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ Free memory }
Monkey.Free;
end;
end.
|
unit xProtocolSendScreen;
interface
uses System.Types,System.Classes, xFunction, system.SysUtils, xUDPServerBase,
xConsts, System.IniFiles, Winapi.WinInet, winsock, Graphics,
xProtocolBase, System.Math;
const
C_SEND_SCREEN = 1; // 发送屏幕
const
C_SEND_PACKS_COUNT = 8000; // 每条命令发送包长度
type
TProtocolSendScreen = class(TProtocolBase)
private
protected
/// <summary>
/// 生成数据包
/// </summary>
function CreatePacks: TBytes; override;
public
constructor Create; override;
destructor Destroy; override;
/// <summary>
/// 发送数据包
/// </summary>
function SendData(nOrderType: Integer; ADev: TObject; sParam1, sParam2 : string) : Boolean; override;
end;
implementation
{ TProtocolSendScreen }
constructor TProtocolSendScreen.Create;
begin
inherited;
IsReplay := False;
end;
function TProtocolSendScreen.CreatePacks: TBytes;
//var
// i : Integer;
begin
// SetLength(Result, 0);
// if Assigned(FDev) and (FDev is TMemoryStream) then
// begin
// case FOrderType of
// C_SEND_SCREEN :
// begin
// TMemoryStream(FDev).Position := 0;
// SetLength(Result, TMemoryStream(FDev).Size);
//
// repeat
//
//
//
// until (i);
//
// TMemoryStream(FDev).Position := 0;
// TMemoryStream(FDev).ReadBuffer(Result[0], 3500);
// end;
// end;
//
// end;
end;
destructor TProtocolSendScreen.Destroy;
begin
inherited;
end;
function TProtocolSendScreen.SendData(nOrderType: Integer; ADev: TObject;
sParam1, sParam2: string): Boolean;
var
aBuf : TBytes;
i : Integer;
nPos : Integer;
aSendBuf : TBytes;
nLen : Integer;
nPackIndex : Integer;
nPackSign : Byte; // 包标识
nRandom : Byte; // 随机数
nPackCount : Byte; // 包总数
begin
FOrderType := nOrderType;
FDev := ADev;
BeforeSend;
SetLength(aBuf, 0);
if Assigned(FDev) and (FDev is TMemoryStream) then
begin
case FOrderType of
C_SEND_SCREEN :
begin
TMemoryStream(FDev).Position := 0;
SetLength(aBuf, TMemoryStream(FDev).Size);
TMemoryStream(FDev).Position := 0;
TMemoryStream(FDev).ReadBuffer(aBuf[0], TMemoryStream(FDev).Size);
nLen := Length(aBuf);
nPackCount := Ceil(nLen / C_SEND_PACKS_COUNT);
nPos := 0;
Randomize;
nRandom := Random(254);
nPackIndex := 0;
repeat
nPackSign := 0;
// 每个数据包都有固定包头FFAA55 + 随机数(同一组包随机数一致) + 头尾标志 + 包序号(从0开始) + 包总数
// 头尾标志用位标示,从低到高位, 是否是起始包,是否是中间包,是否是结尾包 如:$05 代表起始和结尾包
if nPos + C_SEND_PACKS_COUNT >= nLen then
begin
SetLength(aSendBuf, nLen - nPos + 7);
nPackSign := nPackSign + 4;
end
else
begin
SetLength(aSendBuf, C_SEND_PACKS_COUNT + 7);
nPackSign := nPackSign + 2;
end;
for i := 0 to Length(aSendBuf) - 1-7 do
aSendBuf[i+7] := aBuf[i+nPos];
if nPos = 0 then
nPackSign := nPackSign + 1;
aSendBuf[0] := $FF;
aSendBuf[1] := $AA;
aSendBuf[2] := $55;
aSendBuf[3] := nRandom;
aSendBuf[4] := nPackSign;
aSendBuf[5] := nPackIndex;
aSendBuf[6] := nPackCount;
CommSenRev(aSendBuf, True, sParam1, sParam2);
Sleep(10);
nPos := nPos + C_SEND_PACKS_COUNT;
Inc(nPackIndex);
until (nPos >= nLen);
end;
end;
end;
AfterSend;
if IsReplay then
Result := IsReplied
else
Result := True;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.Design.Items;
interface
uses
SysUtils, Types, Classes, Variants, System.UITypes, TypInfo, FMX.Types,
DesignIntf, FmxDesignWindows, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.ListBox,
FMX.Layouts, FMX.TreeView, FMX.StdCtrls, FMX.Objects, FMX.SearchBox, FMX.Controls.Presentation;
type
// Not every item can accept similar item
// For Example: TListBoxItem doesn't accept TListBox Item
// TMenuItem can accept TMenuItem
TItemClassDesc = record
ItemClass: TFmxObjectClass;
CanContainSimilarItem: Boolean; // Can accept ItemClass Items
ShowOnlyInMenu: Boolean;
constructor Create(const AItemClass: TFmxObjectClass;
const ACanContaineSimilarItem: Boolean = False;
const AShowOnlyInMenu: Boolean = False);
end;
TDesignItemsForm = class(TFmxDesignWindow, IFreeNotification)
ItemsTree: TTreeView;
ItemsClasses: TComboBox;
btnAdd: TButton;
ControlsLayout: TLayout;
btnAddChild: TButton;
btnDelete: TButton;
Layout2: TLayout;
btnUp: TButton;
btnDown: TButton;
Path1: TPath;
Path2: TPath;
procedure btnAddClick(Sender: TObject);
procedure btnAddChildClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure ItemsTreeChange(Sender: TObject);
procedure btnUpClick(Sender: TObject);
procedure btnDownClick(Sender: TObject);
procedure ItemsTreeDragChange(SourceItem, DestItem: TTreeViewItem;
var Allow: Boolean);
procedure FormCreate(Sender: TObject);
private
FItemsDescription: array of TItemClassDesc;
FContainer: IItemsContainer;
FDeletedItem: TTreeViewItem;
procedure UpdateTree;
procedure UpdateStates;
function AcceptsChildItem(const AItem: TObject): Boolean;
procedure RealignItems;
protected
procedure FreeNotification(AObject: TObject); override;
public
destructor Destroy; override;
procedure SetItemClasses(const AContainer: IItemsContainer; const AItemDescriptions: array of TItemClassDesc);
procedure ItemDeleted(const ADesigner: IDesigner; Item: TPersistent); override;
procedure ItemsModified(const Designer: IDesigner); override;
procedure DesignerClosed(const Designer: IDesigner; AGoingDormant: Boolean); override;
end;
var
DesignItemsForm: TDesignItemsForm;
implementation
uses
Math, FmxDsnConst;
{$R *.fmx}
type
TCloseWatcher = class
procedure DesignerClosed(Sender: TObject; var Action: TCloseAction);
end;
var
Watcher: TCloseWatcher;
procedure TCloseWatcher.DesignerClosed(Sender: TObject; var Action: TCloseAction);
begin
if Sender = DesignItemsForm then
begin
Action := TCloseAction.caFree;
DesignItemsForm := nil;
end;
end;
procedure TDesignItemsForm.SetItemClasses(const AContainer: IItemsContainer; const AItemDescriptions: array of TItemClassDesc);
var
I: Integer;
Item: TListBoxItem;
ItemIndex: Integer;
begin
if Length(AItemDescriptions) = 0 then Exit;
ItemsClasses.Clear;
SetLength(FItemsDescription, Length(AItemDescriptions));
ItemIndex := 0;
for I := 0 to High(AItemDescriptions) do
begin
if AItemDescriptions[I].ShowOnlyInMenu then
Continue;
Item := TListBoxItem.Create(nil);
Item.Parent := ItemsClasses;
Item.Text := AItemDescriptions[I].ItemClass.ClassName;
Item.TextAlign := TTextAlign.Center;
FItemsDescription[ItemIndex] := AItemDescriptions[I];
Inc(ItemIndex);
end;
SetLength(FItemsDescription, ItemIndex);
ItemsClasses.ItemIndex := 0;
FContainer := AContainer;
FContainer.GetObject.AddFreeNotify(Self);
UpdateTree;
end;
function TDesignItemsForm.AcceptsChildItem(const AItem: TObject): Boolean;
function FindItemDescription(AItemClass: TClass): Integer;
var
I: Integer;
Founded: Boolean;
begin
I := 0;
Founded := False;
while (I < Length(FItemsDescription)) and not Founded do
if FItemsDescription[I].ItemClass = AItemClass then
Founded := True
else
Inc(I);
if Founded then
Result := I
else
Result := -1;
end;
var
Index: Integer;
begin
Result := True;
if Assigned(AItem) then
begin
Index := FindItemDescription(AItem.ClassType);
Result := (Index <> -1) and FItemsDescription[Index].CanContainSimilarItem;
end;
end;
procedure TDesignItemsForm.btnAddChildClick(Sender: TObject);
var
Node: TTreeViewItem;
Item: TFmxObject;
SelectedItem: TTreeViewItem;
ItemParent: TFmxObject;
begin
Node := TTreeViewItem.Create(Self);
SelectedItem:= ItemsTree.Selected;
if ItemsTree.Selected <> nil then
Node.Parent := ItemsTree.Selected
else
Node.Parent := ItemsTree;
if Node.ParentItem <> nil then
ItemParent := TFmxObject(Node.ParentItem.TagObject)
else
ItemParent := FContainer.GetObject;
Item := TfmxObject(Designer.CreateChild(FItemsDescription[ItemsClasses.ItemIndex].ItemClass, ItemParent));
if GetPropInfo(Item, 'text') <> nil then
Node.Text := GetStrProp(Item, 'text');
if Node.Text = '' then
Node.Text := Item.Name;
if Node.Text = '' then
Node.Text := SUnnamed;
Node.TagObject := Item;
// ItemsTree.Selected := Node;
ItemsTree.Selected:= SelectedItem;
ItemsTree.Selected.IsExpanded:= True;
UpdateStates;
end;
procedure TDesignItemsForm.btnAddClick(Sender: TObject);
var
Node: TTreeViewItem;
Item: TFmxObject;
ItemParent: TFmxObject;
begin
Node := TTreeViewItem.Create(Self);
if ItemsTree.Selected <> nil then
Node.Parent := ItemsTree.Selected.Parent
else
Node.Parent := ItemsTree;
if Node.ParentItem <> nil then
ItemParent := TFmxObject(Node.ParentItem.TagObject)
else
ItemParent := TFmxObject(FContainer.GetObject);
Item := TFmxObject(Designer.CreateChild(FItemsDescription[ItemsClasses.ItemIndex].ItemClass, ItemParent));
if GetPropInfo(Item, 'text') <> nil then
Node.Text := GetStrProp(Item, 'text');
if Node.Text = '' then
Node.Text := Item.Name;
if Node.Text = '' then
Node.Text := SUnnamed;
Node.TagObject := Item;
ItemsTree.Selected := Node;
UpdateStates;
end;
procedure TDesignItemsForm.btnDeleteClick(Sender: TObject);
var
Idx: integer;
begin
if ItemsTree.Selected <> nil then
begin
Idx := ItemsTree.Selected.GlobalIndex;
Designer.DeleteSelection(False);
if ItemsTree.GlobalCount > 0 then
if Idx > 0 then
ItemsTree.Selected := ItemsTree.ItemByGlobalIndex(Idx - 1)
else
ItemsTree.Selected := ItemsTree.ItemByGlobalIndex(0);
UpdateStates;
end;
end;
procedure TDesignItemsForm.btnDownClick(Sender: TObject);
var
OldIndex: Integer;
Modified: Boolean;
begin
{ down }
Modified := False;
if ItemsTree.Selected <> nil then
begin
ItemsTree.Selected.Index := ItemsTree.Selected.Index + 1;
if ItemsTree.Selected.TagObject <> nil then
begin
OldIndex := TFmxObject(ItemsTree.Selected.TagObject).Index;
TFmxObject(ItemsTree.Selected.TagObject).Index := TFmxObject(ItemsTree.Selected.TagObject).Index + 1;
Modified := OldIndex <> TFmxObject(ItemsTree.Selected.TagObject).Index;
end;
RealignItems;
end;
UpdateStates;
if Modified then
Designer.Modified;
end;
procedure TDesignItemsForm.btnUpClick(Sender: TObject);
var
OldIndex: Integer;
Modified: Boolean;
begin
{ up }
Modified := False;
if ItemsTree.Selected <> nil then
begin
ItemsTree.Selected.Index := ItemsTree.Selected.Index - 1;
if ItemsTree.Selected.TagObject <> nil then
begin
OldIndex := TFmxObject(ItemsTree.Selected.TagObject).Index;
TFmxObject(ItemsTree.Selected.TagObject).Index := TFmxObject(ItemsTree.Selected.TagObject).Index - 1;
Modified := OldIndex <> TFmxObject(ItemsTree.Selected.TagObject).Index;
end;
RealignItems;
end;
UpdateStates;
if Modified then
Designer.Modified;
end;
procedure TDesignItemsForm.DesignerClosed(const Designer: IDesigner; AGoingDormant: Boolean);
begin
inherited;
if Assigned(FContainer) then
begin
FContainer.GetObject.RemoveFreeNotify(Self);
FContainer := nil;
end;
Close;
end;
destructor TDesignItemsForm.Destroy;
begin
if Assigned(FContainer) then
begin
FContainer.GetObject.RemoveFreeNotify(Self);
FContainer := nil;
end;
inherited;
end;
procedure TDesignItemsForm.FormCreate(Sender: TObject);
const
ButtonMargin: Integer = 8;
var
RequiredWidth: Integer;
begin
// Layout buttons for localization
RequiredWidth := Round(Canvas.TextWidth(btnAdd.Text)) + ButtonMargin * 2;
RequiredWidth := Math.Max(RequiredWidth,
Round(Canvas.TextWidth(btnAddChild.Text)) + ButtonMargin * 2);
// Finally examine the UpDownDelete buttons as a group
RequiredWidth := Math.Max(RequiredWidth,
Round(btnUp.Width) + ButtonMargin + Round(btnDown.Width) + ButtonMargin +
Round(Canvas.TextWidth(btnDelete.Text)) + ButtonMargin * 2);
// Make the changes
ControlsLayout.Width := RequiredWidth + 2 * ButtonMargin;
// Setup the watcher
if not Assigned(Watcher) then
Watcher := TCloseWatcher.Create;
OnClose := Watcher.DesignerClosed;
end;
procedure TDesignItemsForm.FreeNotification(AObject: TObject);
begin
inherited;
if Assigned(FContainer) and (AObject = FContainer.GetObject) then
begin
FContainer := nil;
Close;
end;
end;
procedure TDesignItemsForm.ItemDeleted(const ADesigner: IDesigner;
Item: TPersistent);
var
I: Integer;
begin
inherited;
{ check for deletion }
for I := 0 to ItemsTree.GlobalCount - 1 do
if ItemsTree.ItemByGlobalIndex(I).TagObject = Item then
begin
FDeletedItem := ItemsTree.ItemByGlobalIndex(I);
FDeletedItem.Free;
Exit;
end;
end;
procedure TDesignItemsForm.ItemsModified(const Designer: IDesigner);
var
I, J: Integer;
Sel: TDesignerSelections;
Obj: TPersistent;
Node: TTreeViewItem;
begin
inherited;
{ check selection for object in tree }
Sel := TDesignerSelections.Create;
Designer.GetSelections(Sel);
for I := 0 to IDesignerSelections(Sel).Count - 1 do
begin
Obj := IDesignerSelections(Sel).Items[i];
for J := 0 to ItemsTree.GlobalCount - 1 do
begin
Node := ItemsTree.ItemByGlobalIndex(J);
if Node.TagObject = Obj then
begin
{ change text }
if GetPropInfo(Obj, 'text') <> nil then
Node.Text := GetStrProp(Obj, 'text');
if Node.Text = '' then
if Obj is TComponent then
Node.Text := TComponent(Obj).Name
else
Node.Text := SUnnamed;
Break;
end;
end;
end;
end;
procedure TDesignItemsForm.ItemsTreeChange(Sender: TObject);
begin
if (ItemsTree.Selected <> nil) and (ItemsTree.Selected.TagObject <> nil) then
Designer.SelectComponent(TFmxObject(ItemsTree.Selected.TagObject))
else
Designer.SelectComponent(nil);
UpdateStates;
end;
procedure TDesignItemsForm.ItemsTreeDragChange(SourceItem,
DestItem: TTreeViewItem; var Allow: Boolean);
var
i: integer;
Modified: Boolean;
begin
Modified := False;
Allow := btnAddChild.Visible;
if Allow then
begin
if Assigned(DestItem) and not (SourceItem.IsChild(TFmxObject(DestItem)))
and AcceptsChildItem(DestItem.TagObject) then
begin
TFmxObject(SourceItem.TagObject).Parent := TFmxObject(DestItem.TagObject);
Modified := True;
end
else
begin
if DestItem = nil then
if not (TFmxObject(SourceItem).Parent is TScrollContent) then
begin
TFmxObject(SourceItem.TagObject).Parent:= FContainer.GetObject;
Modified := True;
end
else
begin
for i := 1 to ItemsTree.Count - SourceItem.Index - 1 do
begin
TFmxObject(SourceItem).Index:= TFmxObject(SourceItem).Index + 1;
TFmxObject(SourceItem.TagObject).Index:= TFmxObject(SourceItem.TagObject).Index + 1;
Modified := True;
end;
end
else
//changing the order of the THeaderItems/ TListBoxItem/ TTabItem; dragged item will be moved before/after DestItem
if not AcceptsChildItem(DestItem.TagObject) then
begin
if DestItem.Index > SourceItem.Index then
for i := 1 to DestItem.Index - SourceItem.Index do
begin
TFmxObject(SourceItem).Index:= TFmxObject(SourceItem).Index + 1;
TFmxObject(SourceItem.TagObject).Index:= TFmxObject(SourceItem.TagObject).Index + 1;
Modified := True;
end
else
for i := 1 to SourceItem.Index - DestItem.Index do
begin
TFmxObject(SourceItem).Index:= TFmxObject(SourceItem).Index - 1;
TFmxObject(SourceItem.TagObject).Index:= TFmxObject(SourceItem.TagObject).Index - 1;
Modified := True;
end
end;
end;
end;
UpdateStates;
RealignItems;
if Modified then
Designer.Modified;
end;
procedure TDesignItemsForm.RealignItems;
var
AlignRoot: IAlignRoot;
begin
if FContainer.GetObject.GetInterface(IAlignRoot, IInterface(AlignRoot)) then
begin
AlignRoot.Realign;
AlignRoot := nil;
end;
Designer.SelectComponent(TFmxObject(ItemsTree.Selected.TagObject));
end;
procedure TDesignItemsForm.UpdateStates;
function AreAllItemsStored: Boolean;
var
I: Integer;
begin
Result := True;
for I := 0 to ItemsTree.GlobalCount - 1 do
if not TFmxObject(ItemsTree.ItemByGlobalIndex(I).TagObject).Stored then
Exit(False);
end;
var
Editable: Boolean;
begin
Editable := AreAllItemsStored;
btnUp.Enabled := Editable and (ItemsTree.Selected <> nil) and (ItemsTree.Selected.Index > 0);
btnDown.Enabled := Editable and (ItemsTree.Selected <> nil) and (ItemsTree.Selected.Parent <> nil) and (ItemsTree.Selected.Index < ItemsTree.Selected.Parent.ChildrenCount - 1);
btnDelete.Enabled := Editable and (Designer.GetAncestorDesigner = nil) and (ItemsTree.Selected <> nil);
btnAddChild.Enabled := Editable and (ItemsTree.Selected <> nil);
btnAdd.Enabled := Editable;
end;
procedure TDesignItemsForm.UpdateTree;
procedure UpdateItem(AItem: IItemsContainer; AParentNode: TFmxObject);
var
Node: TTreeViewItem;
ChildContainer: IItemsContainer;
IsItem: Boolean;
i, j: integer;
begin
for i := 0 to AItem.GetItemsCount - 1 do
begin
IsItem := false;
for j := 0 to High(FItemsDescription) do
if (AItem.GetItem(i) is FItemsDescription[j].ItemClass) and (AItem.GetItem(i).Owner <> nil) then
begin
IsItem := true;
Break;
end;
if not IsItem then Continue;
Node := TTreeViewItem.Create(nil);
Node.Parent := AParentNode;
if GetPropInfo(AItem.GetItem(i), 'text') <> nil then
Node.Text := GetStrProp(AItem.GetItem(i), 'text');
if Node.Text = '' then
Node.Text := AItem.GetItem(i).Name;
if Node.Text = '' then
Node.Text := SUnnamed;
Node.TagObject := AItem.GetItem(i);
if Supports(AItem.GetItem(i), IItemsContainer, ChildContainer) then
UpdateItem(ChildContainer, Node);
end;
end;
begin
if FContainer = nil then Exit;
ItemsTree.Clear;
UpdateItem(FContainer, ItemsTree);
UpdateStates;
end;
{ TItemClassDesc }
constructor TItemClassDesc.Create(const AItemClass: TFmxObjectClass;
const ACanContaineSimilarItem: Boolean;
const AShowOnlyInMenu: Boolean);
begin
Self.ItemClass := AItemClass;
Self.CanContainSimilarItem := ACanContaineSimilarItem;
Self.ShowOnlyInMenu := AShowOnlyInMenu;
end;
initialization
finalization
if Assigned(DesignItemsForm) then
DesignItemsForm.Free;
if Assigned(Watcher) then
Watcher.Free;
end.
|
unit frContact;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, frameBase, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, frListBase,
frPhones, cxDBEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, Vcl.StdCtrls, Data.DB,
IBX.IBCustomDataSet, IBX.IBQuery, IBX.IBUpdateSQL, IBX.IBDatabase;
type
TFrameContact = class(TDbFrameBase)
Label1: TLabel;
cmbType: TcxDBLookupComboBox;
Label3: TLabel;
cxDBTextEdit1: TcxDBTextEdit;
FramePhones: TFramePhones;
private
{ Private declarations }
protected
procedure SetTransaction(AValue: TIBTransaction); override;
public
function OpenData(Aid: integer = 0): Boolean; override;
function SaveData: Boolean; override;
end;
var
FrameContact: TFrameContact;
implementation
{$R *.dfm}
uses
DM_Main;
{ TFrameContact }
function TFrameContact.OpenData(Aid: integer): Boolean;
begin
Result := inherited OpenData(Aid);
if not result then
Exit;
Result := False;
try
FramePhones.AddParam('CLIENT_ID', Query.FieldByName('ID'));
FramePhones.typePhone := 3;
FramePhones.OpenData;
Result := True;
except
Result := False;
end;
end;
function TFrameContact.SaveData: Boolean;
begin
Result := false;
try
try
Result := inherited SaveData;
if not result then
Exit;
//сохраняем телефоны
Result := FramePhones.SaveData;
except
Result := false;
fErr := 'SaveData error:'+ #13#10 + Exception(ExceptObject).Message;
end;
finally
end;
end;
procedure TFrameContact.SetTransaction(AValue: TIBTransaction);
begin
inherited;
FramePhones.Transaction := AValue;
end;
end.
|
program final_2017;
const
DIM1=4;
DIM2=4;
type Tmat = array[1..DIM1,1..DIM2] of Longint;
procedure CargarMatriz(var M: Tmat);
var i,j,f,k,c,fac: Longint;
begin
for i := 1 to DIM1 do
begin
for j:=1 to DIM2 do
begin
f:=i+j;
fac:=1;
c:=1;
for k:=1 to f do
begin
fac:=fac*c;
c:=c+1;
end;
M[i,j]:=fac;
end;
end;
end;
procedure MostrarMatriz(M:Tmat);
var
i,j: Integer;
begin
for i := 1 to DIM1 do
begin
for j:=1 to DIM2 do
begin
write(M[i,j]:5);
end;
writeln;
end;
end;
function Pertenece(M: Tmat; n: Integer):Integer;
var
i,j,c: Integer;
begin
c:=0;
for i := 1 to DIM1 do
begin
for j := 1 to DIM2 do
begin
if n=M[i,j] then
begin
c:=c+1;
end;
end;
end;
Pertenece:=c;
end;
var
M: Tmat;
BEGIN
randomize;
CargarMatriz(M);
MostrarMatriz(M);
END. |
program DATEKILL;
{ deletes Fidomail BBS messages by date }
uses FileOps;
CONST
rootpath = 'c:\msg\';
ValidChars : set of 0..127 = [32..127];
CutOffDay = 16;
CutOffMonth = 'Oct';
VAR
Dir : POINTER;
filename : string;
infile : file;
{---------------------------------------------------------}
PROCEDURE Abort(msg :string);
begin
writeln(msg);
HALT;
end;
{---------------------------------------------------------}
function ExtractDate(var infile : file) : string;
CONST
startpos = 144;
strlength = 20;
VAR
ch : CHAR;
datestr : string;
Buffer : ARRAY[0..255] OF CHAR;
recsread,
n : WORD;
Quit : BOOLEAN;
BEGIN
n := 0;
BlockRead(infile,Buffer,2,recsread);
IF recsread < 1 THEN Abort('nothing read');
REPEAT
ch := Buffer[startpos+n];
Quit := NOT (BYTE(ch) IN ValidChars);
datestr[n+1] := ch;
INC(n);
UNTIL (n = StrLength) OR Quit;
datestr[0] := CHAR(n-1);
ExtractDate := datestr;
END;
{---------------------------------------------------------}
FUNCTION CheckDate(datestr : string) : BOOLEAN;
CONST
digits : set of CHAR = ['0'..'9',' '];
VAR
day,
code,
n : WORD;
month : string;
BEGIN
n := 1;
IF NOT (datestr[n] IN digits) THEN n := 5;
val(copy(datestr,n,2),day,code);
month := copy(datestr,n+3,3);
IF day < CutOffDay THEN
CheckDate := FALSE
ELSE
CheckDate := TRUE;
END;
{---------------------------------------------------------}
PROCEDURE ProcessFile(name : string);
VAR
datestr : String;
BEGIN
Assign(infile,name);
Reset(infile);
datestr := ExtractDate(infile);
Close(infile);
IF NOT CheckDate(datestr) THEN
BEGIN
Writeln('Erasing: ',name);
Erase(infile);
END;
END;
{---------------------------------------------------------}
BEGIN { main }
CheckPath(rootpath+paramstr(1));
GetDirectory('*.msg',Dir,filename);
IF Dir = NIL THEN Abort('directory error');
IF filename <> nofile THEN ProcessFile(filename);
REPEAT
filename := GetNextFile(Dir);
IF filename <> nofile THEN ProcessFile(filename);
UNTIL filename = nofile;
END. |
unit BrickCamp.Model;
interface
type
TResourceType = (rProduct, rUser, rQuestion, rAnswer);
const
RESOURCESTRINGS: array[TResourceType] of string = ('/product', '/user', '/question', '/answer');
GET_GENERIC_GETONE: string = '/getone';
GET_GENERIC_GETLIST: string = '/getlist';
POST_GENERIC: string = '';
PUT_GENERIC: string = '';
DELETE_GENERIC: string = '';
GET_USER_ONEBYNAME: string = '/getonebyname';
GET_QUESTION_GETLISTBYPRODUCT: string = '/getlistbyproductid';
GET_ANSWER_GETLISTBYQUESTION: string = '/getlistbyquetionid';
implementation
end.
|
unit UTimeFutebol;
interface
uses
UCampeonato,System.Generics.Collections;
type
TTimeFutebol = class
private
FId : Integer;
FNome : String;
FQuantidadeTorcida : double;
FTitulos : TObjectList<TCampeonatos>;
function getId : Integer;
function getNome : String;
function getQuantidadeTorcida : double;
function getTitulos: TObjectList<TCampeonatos>;
procedure SetId(const Value: Integer);
procedure SetNome(const Value: String);
procedure setQuantidadeTorcida(const Value: double);
procedure setTitulos(const Value: TObjectList<TCampeonatos>);
protected
public
property id : Integer read getId write SetId;
property nome : String read getNome write SetNome;
property quantidadeTorcida : double read getQuantidadeTorcida write setQuantidadeTorcida;
property titulos : TObjectList<TCampeonatos> read getTitulos write setTitulos;
procedure CopyFromObejct(timeFutebol :TTimeFutebol);
end;
implementation
{ TTimeFutebol }
procedure TTimeFutebol.CopyFromObejct(timeFutebol: TTimeFutebol);
begin
Self.FId := timeFutebol.id;
Self.FNome := timeFutebol.nome;
Self.quantidadeTorcida := timeFutebol.quantidadeTorcida;
Self.FTitulos := timeFutebol.titulos;
end;
function TTimeFutebol.getId: Integer;
begin
Result:= FId;
end;
function TTimeFutebol.getNome: String;
begin
Result:= FNome;
end;
function TTimeFutebol.getQuantidadeTorcida: double;
begin
Result:= FQuantidadeTorcida;
end;
function TTimeFutebol.getTitulos: TObjectList<TCampeonatos>;
begin
Result:= FTitulos;
end;
procedure TTimeFutebol.SetId(const Value: Integer);
begin
Self.FId:= Value;
end;
procedure TTimeFutebol.SetNome(const Value: String);
begin
Self.FNome:= Value;
end;
procedure TTimeFutebol.setQuantidadeTorcida(const Value: double);
begin
Self.FQuantidadeTorcida:= Value;
end;
procedure TTimeFutebol.setTitulos(const Value: TObjectList<TCampeonatos>);
begin
Self.FTitulos:= Value;
end;
end.
|
unit WatchDog.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs,
IniFiles, Threads.Base, Generics.Collections, GMGenerics, GMGlobals, Connection.Base, Connection.TCP, WinApi.WinSvc,
ShellAPI, StdRequest, StdResponce, GMConst, ActiveX;
type
TGMService = class
public
SvcName: string;
Port: int;
LastAccess, LastRun, LastStop: TDateTime;
end;
GMWDThread = class(TGMThread)
private
const SVC_TIMEOUT_RESTART = 1 / 24 / 60 * 2;
{$ifdef DEBUG}
const SVC_TIMEOUT_REPLY = 1 / 24 / 60 / 10;
{$else}
const SVC_TIMEOUT_REPLY = 1 / 24 / 60 * 5;
{$endif}
private
FServers: TGMCollection<TGMService>;
FIniFile: string;
FConnection: TConnectionObjectTCP_OwnSocket;
function ReadINI: bool;
procedure PingServices;
procedure AddService(const AName: string; APort: int);
procedure PingService(svc: TGMService);
procedure RestartService(svc: TGMService);
function GetTerminated(): bool;
function KillService(pid: DWORD): bool;
protected
procedure SafeExecute; override;
public
constructor Create();
destructor Destroy; override;
end;
TSiriusWatchDog = class(TService)
procedure ServiceExecute(Sender: TService);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
private
{ Private declarations }
thr: GMWDThread;
{$ifdef Application}
public
{$endif}
procedure InitService();
public
function GetServiceController: TServiceController; override;
{ Public declarations }
end;
var
SiriusWatchDog: TSiriusWatchDog;
implementation
{$R *.DFM}
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
SiriusWatchDog.Controller(CtrlCode);
end;
function TSiriusWatchDog.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
{ GMWDThread }
procedure GMWDThread.AddService(const AName: string; APort: int);
var i: int;
begin
for i := 0 to FServers.Count - 1 do
if AnsiSameText(FServers[i].SvcName, AName) then
begin
FServers[i].Port := APort;
Exit;
end;
with FServers.Add() do
begin
SvcName := AName;
Port := APort;
LastAccess := Now();
LastRun := 0;
LastStop := 0;
end;
end;
function GMWDThread.ReadINI(): bool;
var f: TIniFile;
n, port: int;
name: string;
begin
Result := false;
if not FileExists(FIniFile) then
begin
AddService('GMIOPService', 65500); // без INI пытаемся найти сервис по умолчанию
Result := true;
Exit();
end;
try
f := TIniFile.Create(FIniFile);
n := 1;
while f.SectionExists(IntToStr(n)) do
begin
port := f.ReadInteger(IntToStr(n), 'PORT', 65500);
name := f.ReadString(IntToStr(n), 'NAME', '');
if (port > 0) and (Trim(name) <> '') then
AddService(name, port);
inc(n);
end;
Result := true;
except end; // не смог и хрен с ним
end;
constructor GMWDThread.Create;
begin
inherited Create();
FConnection := TConnectionObjectTCP_OwnSocket.Create();
FConnection.Host := '127.0.0.1';
FConnection.WaitFirst := 7000;
FConnection.WaitNext := 100;
FConnection.CheckTerminated := GetTerminated;
FConnection.NumAttempts := 1;
FServers := TGMCollection<TGMService>.Create();
FIniFile := ChangeFileExt(ParamStr(0), '.ini');
end;
destructor GMWDThread.Destroy;
begin
FConnection.Free();
FServers.Free();
inherited;
end;
function GMWDThread.GetTerminated: bool;
begin
Result := Terminated;
end;
procedure GMWDThread.PingService(svc: TGMService);
var req: IXMLGMIORequestType;
resp: IXMLGMIOResponceType;
begin
FConnection.Port := svc.Port;
if FConnection.ExchangeBlockData(etRec) = ccrBytes then
begin
req := NewGMIORequest();
req.State.RemoteServerReady := 1;
if FConnection.RequestUniversal(req.XML, AUTH_DEFAULT_LOGIN, true, ruxcRequest, resp) = ccrBytes then
svc.LastAccess := Now();
end;
FConnection.FreePort();
req := nil;
resp := nil;
end;
function RunAsAdmin(const Path, Params: string): Boolean;
var
sei: TShellExecuteInfo;
begin
FillChar(sei, SizeOf(sei), 0);
sei.cbSize := SizeOf(sei);
sei.Wnd := 0;
sei.fMask := SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI;
sei.lpVerb := 'runas';
sei.lpFile := PChar(Path);
sei.lpParameters := PChar(Params);
sei.nShow := SW_SHOWNORMAL;
Result := ShellExecuteEx(@sei);
end;
function GMWDThread.KillService(pid: DWORD): bool;
begin
Result := RunAsAdmin('taskkill.exe', '/F /PID ' + IntToStr(pid));
end;
procedure GMWDThread.RestartService(svc: TGMService);
var hscm, hsvc: SC_HANDLE;
st: TServiceStatus;
ssStatus: SERVICE_STATUS_PROCESS;
dwBytesNeeded: DWORD;
lpServiceArgVectors: LPCWSTR;
begin
hscm := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if hscm = 0 then Exit;
try
hsvc := OpenService(hscm, PChar(svc.SvcName), SC_MANAGER_ALL_ACCESS);
if hsvc = 0 then Exit;
try
if not QueryServiceStatusEx(hsvc, SC_STATUS_PROCESS_INFO, @ssStatus, sizeof(SERVICE_STATUS_PROCESS), dwBytesNeeded) then Exit;
case ssStatus.dwCurrentState of
SERVICE_RUNNING:
begin
// остановим, если давно запущен, но не работает
if (Now() - svc.LastRun > SVC_TIMEOUT_RESTART) and ControlService(hsvc, SERVICE_CONTROL_STOP, st) then
svc.LastStop := Now();
end;
SERVICE_STOPPED:
begin
lpServiceArgVectors := nil;
if StartService(hsvc, 0, lpServiceArgVectors) then
svc.LastRun := Now();
end;
SERVICE_STOP_PENDING:
begin
if Now() - svc.LastStop > SVC_TIMEOUT_RESTART then // если никак не может закрыться - прибьём
KillService(ssStatus.dwProcessId);
end;
end;
finally
CloseServiceHandle(hsvc);
end;
finally
CloseServiceHandle(hscm);
end;
end;
procedure GMWDThread.PingServices;
var i: int;
begin
for i := 0 to FServers.Count - 1 do
begin
PingService(FServers[i]);
if Abs(Now() - FServers[i].LastAccess) > SVC_TIMEOUT_REPLY then
RestartService(FServers[i]);
end;
end;
procedure GMWDThread.SafeExecute;
begin
CoInitialize(nil);
while not Terminated do
begin
if ReadINI() then
PingServices();
SleepThread(1000);
end;
end;
procedure TSiriusWatchDog.InitService;
begin
thr := GMWDThread.Create();
end;
procedure TSiriusWatchDog.ServiceExecute(Sender: TService);
begin
InitService();
while not Terminated do
begin
ServiceThread.ProcessRequests(True);
end;
end;
procedure TSiriusWatchDog.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
thr.Free();
end;
end.
|
unit search_drive;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, windows;
function ssss(i:integer):string;
implementation
function ssss(i:integer):string;
var C: string;
DType: Integer;
//DriveString: string;
begin
{ Loop from A..Z to determine available drives }
C := chr(i) + ':\';
DType := GetDriveType(PChar(C));
case DType of
{0: DriveString := C + ' The drive type cannot be determined.';
1: DriveString := C + ' The root directory does not exist.';
DRIVE_REMOVABLE: DriveString :=
C + ' The drive can be removed from the drive.';
DRIVE_FIXED: DriveString :=
C + ' The disk cannot be removed from the drive.';
DRIVE_REMOTE: DriveString :=
C + ' The drive is a remote (network) drive.';
DRIVE_CDROM: DriveString := C + ' The drive is a CD-ROM drive.';}
//DRIVE_RAMDISK: DriveString := C + ' The drive is a RAM disk.';
DRIVE_FIXED:
begin
ssss:=c;
end;
else ssss:='err';
end;
// Only add drive types that can be determined.
{if not ((DType = 0) or (DType = 1)) then
//lbDrives.Items.AddObject(DriveString, Pointer(i));
sttext := 'Диск: ' + c ;
Synchronize(@Showstatus);
end; }
end;
end.
|
unit uFrmContador;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uReduxStore,
System.Generics.Collections;
type
TActionType = (INCREMENT = 0,DECREMENT = 1);
TFrmContador = class(TForm)
Label1: TLabel;
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
ReduxStore : TReduxStore<Integer>;
{ Private declarations }
public
{ Public declarations }
end;
var
FrmContador: TFrmContador;
implementation
{$R *.dfm}
{ TFrmContador }
procedure TFrmContador.Button1Click(Sender: TObject);
begin
ReduxStore.DispatchAction(Ord(TActionType.INCREMENT));
end;
procedure TFrmContador.Button2Click(Sender: TObject);
begin
ReduxStore.DispatchAction(Ord(TActionType.DECREMENT));
end;
procedure TFrmContador.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FreeAndNil(ReduxStore);
end;
procedure TFrmContador.FormCreate(Sender: TObject);
var
Reducer : TReducer<Integer>;
Listener : TListener<Integer>;
begin
Reducer := function(State : Integer; Action : Integer):Integer
var
StateValue : Integer;
begin
StateValue := State;
case Action of
Ord(TActionType.INCREMENT) : StateValue := StateValue + 1;
Ord(TActionType.DECREMENT) : StateValue := StateValue - 1;
end;
State := StateValue;
Result := State;
end;
Listener := procedure(State : Integer)
var
StateValue : Integer;
begin
StateValue := State;
FrmContador.Label1.Caption := IntToStr( State );
FrmContador.Button2.Enabled := True;
FrmContador.Button1.Enabled := True;
if StateValue = 0 then
FrmContador.Button2.Enabled := False
else if StateValue = 10 then
FrmContador.Button1.Enabled := False
end;
ReduxStore := TReduxStore<Integer>.Create(0,Reducer);
ReduxStore.AddListener(Listener);
Label1.Caption := IntToStr( ReduxStore.GetState );
Button2.Enabled := False;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q+,R+,S+,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 47 O(1) Box Intersect and Turn Left Alg.
}
program
TwoSegmentsIntersectSegment;
const
Epsilon = 1E-5;
type
TPoint = record
X, Y : Extended;
end;
TSegment = record
P : array [1 .. 2] of TPoint;
end;
function Comp (A, B : Extended) : Integer;
begin
if Abs(A - B) < Epsilon then
Comp := 0
else
if A < B then
Comp := -1
else
Comp := 1;
end;
function InRange (A, I, J : Extended) : Boolean;
begin
InRange := ((Comp(I, A) <= 0) and (Comp(A, J) <= 0)) or
((Comp(I, A) >= 0) and (Comp(A, J) >= 0));
end;
function TurnComp (P1, P2, P3 : TPoint) : Integer;
var
V2, V3 : TPoint;
begin
Minus(P2, P1, V2);
Minus(P3, P1, V3);
TurnComp := Compare(ExternProd(V2, V3), 0);
end;
function IsIntersect (S1, S2: TSegment) : Boolean;
begin
IsIntersect :=
( InRange(S1.P[1].X, S2.P[1].X, S2.P[2].X) or
InRange(S1.P[2].X, S2.P[1].X, S2.P[2].X) ) and
( InRange(S1.P[1].Y, S2.P[1].Y, S2.P[2].Y) or
InRange(S1.P[2].Y, S2.P[1].Y, S2.P[2].Y) ) and
( InRange(S2.P[1].X, S1.P[1].X, S1.P[2].X) or
InRange(S2.P[2].X, S1.P[1].X, S1.P[2].X) ) and
( InRange(S2.P[1].Y, S1.P[1].Y, S1.P[2].Y) or
InRange(S2.P[2].Y, S1.P[1].Y, S1.P[2].Y) ) and
( TurnComp(S1.P[1], S1.P[2], S2.P[1]) *
TurnComp(S1.P[1], S1.P[2], S2.P[2]) <= 0 ) and
( TurnComp(S2.P[1], S2.P[2], S1.P[1]) *
TurnComp(S2.P[1], S2.P[2], S1.P[2]) <= 0 );
end;
function IntersectSeg;
begin
end;
function Intersect;
var
L1, L2 : TLine;
V1, V2 : TPoint;
begin
Minus(S1.P1, S1.P2, V1);
Minus(S2.P1, S2.P2, V2);
if Compare(ExternProd(V1, V2), 0) <> 0 then
begin
FindLine(S1.P1, S1.P2, L1);
FindLine(S2.P1, S2.P2, L2);
P1.X := (L1.C * L2.B - L1.B * L2.C) / (L1.C * L2.B - L1.B * L2.C);
P1.Y := (L1.A * L2.B - L1.B * L2.A) / (L1.A * L2.B - L1.B * L2.A);
Intersect := True;
end
else
Intersect := False;
end;
function IntersectSeg (var Q, R : TSegment; var P1, P2 : TPoint) : Integer;
var
INum : Integer;
Z : Extended;
begin
Z := Q.A * R.B - Q.B * R.A;
if Z = 0 then
begin
if (Q.C * R.B = Q.B * R.C) and (Q.A * R.C = Q.C * R.A) and
(InRange(Q.P[1].X, R.P[1].X, R.P[2].X) or InRange(Q.P[2].X, R.P[1].X, R.P[2].X) or
InRange(R.P[1].X, Q.P[1].X, Q.P[2].X) or InRange(R.P[2].X, Q.P[1].X, Q.P[2].X)) and
(InRange(Q.P[1].Y, R.P[1].Y, R.P[2].Y) or InRange(Q.P[2].Y, R.P[1].Y, R.P[2].Y) or
InRange(R.P[1].Y, Q.P[1].Y, Q.P[2].Y) or InRange(R.P[2].Y, Q.P[1].Y, Q.P[2].Y))
then
begin
IntersectSeg := 2;
if Comp(Q.A, 0) = 0 then
begin
P1.X := Q.P[1].X;
P1.Y := Min(Max(Q.P[1].Y, Q.P[2].Y), Max(R.P[1].Y, R.P[2].Y));
P2.X := Q.P[1].X;
P2.Y := Max(Min(Q.P[1].Y, Q.P[2].Y), Min(R.P[1].Y, R.P[2].Y));
end
else
if Comp(Q.B / Q.A, 0) <= 0 then
begin
P1.X := Min(Max(Q.P[1].X, Q.P[2].X), Max(R.P[1].X, R.P[2].X));
P1.Y := Min(Max(Q.P[1].Y, Q.P[2].Y), Max(R.P[1].Y, R.P[2].Y));
P2.X := Max(Min(Q.P[1].X, Q.P[2].X), Min(R.P[1].X, R.P[2].X));
P2.Y := Max(Min(Q.P[1].Y, Q.P[2].Y), Min(R.P[1].Y, R.P[2].Y));
end
else
begin
P1.X := Max(Min(Q.P[1].X, Q.P[2].X), Min(R.P[1].X, R.P[2].X));
P1.Y := Min(Max(Q.P[1].Y, Q.P[2].Y), Max(R.P[1].Y, R.P[2].Y));
P2.X := Min(Max(Q.P[1].X, Q.P[2].X), Max(R.P[1].X, R.P[2].X));
P2.Y := Max(Min(Q.P[1].Y, Q.P[2].Y), Min(R.P[1].Y, R.P[2].Y));
end;
end
else
IntersectSeg := 0;
Exit;
end;
P1.X := (Q.B * R.C - Q.C * R.B) / Z;
P1.Y := (Q.C * R.A - Q.A * R.C) / Z;
if not (InRange(P1.X, Q.P[1].X, Q.P[2].X) and InRange(P1.X, R.P[1].X, R.P[2].X)
and InRange(P1.Y, Q.P[1].Y, Q.P[2].Y) and InRange(P1.Y, R.P[1].Y, R.P[2].Y)) then
begin
IntersectSeg := 0;
Exit;
end;
IntersectSeg := 1;
end;
var
A : array [1 .. MaxN, 1 .. MaxN] of Integer;
I, J : Integer;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Close(Input);
end;
procedure WriteOutput;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
Close(Output);
end;
begin
ReadInput;
WriteOutput;
end.
|
unit AppSettings;
interface
uses
System.SysUtils, System.Classes, BaseDocked, Vcl.Controls, Vcl.StdCtrls,
RzLabel, Vcl.ExtCtrls, RzPanel, Vcl.Mask, RzEdit,
RzDBEdit, RzButton, RzRadChk, System.UITypes, StrUtils, SaveIntf,
Vcl.ComCtrls, RzDTP;
type
TfrmAppSettings = class(TfrmBaseDocked,ISave)
RzGroupBox1: TRzGroupBox;
edBranchCode: TRzEdit;
edBranchPrefix: TRzEdit;
RzGroupBox2: TRzGroupBox;
RzEdit2: TRzEdit;
cbxNew: TRzCheckBox;
cbxEnableBacklog: TRzCheckBox;
RzGroupBox3: TRzGroupBox;
dteCutoff: TRzDateTimeEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure SaveConfig;
procedure SetControlValue;
public
{ Public declarations }
function Save: boolean;
procedure Cancel;
end;
const
// match the number at the right to the tag property of the control
LOCATION_CODE = 'LOCATION_CODE'; // 0
LOCATION_PREFIX = 'LOCATION_PREFIX'; // 1
BACKLOG_ENTRY_ENABLED = 'BACKLOG_ENTRY_ENABLED'; // 2
CUT_OFF_DATE = 'CUT_OFF_DATE'; // 3
CONFIG: array [1..4] of string =
(LOCATION_CODE,
LOCATION_PREFIX,
BACKLOG_ENTRY_ENABLED,
CUT_OFF_DATE
);
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
uses
AppData;
procedure TfrmAppSettings.Cancel;
begin
SetControlValue;
end;
procedure TfrmAppSettings.FormCreate(Sender: TObject);
begin
inherited;
SetControlValue;
end;
function TfrmAppSettings.Save: boolean;
begin
SaveConfig;
Result := true;
end;
procedure TfrmAppSettings.SaveConfig;
var
code: string;
begin
with dmApplication.dstConfig do
begin
Open;
for code in CONFIG do
begin
if Locate('sysconfig_code',code,[]) then Edit
else
begin
Append;
FieldByName('sysconfig_code').AsString := code;
FieldByName('sysconfig_name').AsString := code;
end;
case AnsiIndexStr(code,CONFIG) of
0: FieldbyName('sysconfig_value').AsString := edBranchCode.Text;
1: FieldbyName('sysconfig_value').AsString := edBranchPrefix.Text;
2: FieldbyName('sysconfig_value').AsInteger := Ord(cbxEnableBacklog.Checked);
3: FieldByName('sysconfig_value').AsString := DateToStr(dteCutoff.Date);
end;
end;
Post;
Close;
end;
end;
procedure TfrmAppSettings.SetControlValue;
var
code, value: string;
i, LTag: integer;
begin
with dmApplication.dstConfig do
begin
Open;
for code in CONFIG do
begin
if Locate('sysconfig_code',code,[]) then
begin
value := FieldByName('sysconfig_value').AsString;
LTag := AnsiIndexStr(code,CONFIG);
for i := 0 to self.ControlCount - 1 do
begin
if self.Controls[i].Tag = LTag then
begin
if self.Controls[i] is TRzEdit then (self.Controls[i] as TRzEdit).Text := value
else if self.Controls[i] is TRzCheckBox then (self.Controls[i] as TRzCheckBox).Checked := StrToBool(value)
else if self.Controls[i] is TRzDateTimeEdit then (self.Controls[i] as TRzDateTimeEdit).Date := StrToDate(value);
end;
end;
end;
end;
Close;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.NetConsts;
interface
resourcestring
{ HTTP }
SSchemeAlreadyRegistered = 'Scheme "%s" already registered for %s';
SSchemeNotRegistered = 'Scheme "%s" is not registered';
SCredentialInvalidUserPassword = 'Credential without user and password';
SNetPlatformFunctionNotImplemented = 'Platform-dependant function not implemented';
SNetSchemeFunctionNotImplemented = 'Scheme-dependant function not implemented';
SNetUriMethodAlreadyAssigned = 'Method already assigned';
SNetUriURLAlreadyAssigned = 'URL already assigned';
SNetUriIndexOutOfRange = 'Parameter index (%d) out of range (%d..%d)';
SNetUriInvalid = 'Invalid URL: "%s"';
SNetUriParamNotFound = 'Parameter "%s" not found';
SNetHttpMaxRedirections = 'Maximum number of redirections (%d) exceeded';
SNetHttpGetServerCertificate = 'Error getting Server Certificate';
SNetHttpAndroidHttpsMainThread = 'HTTPS requests on Android platform are not supported in main thread';
SNetHttpInvalidServerCertificate = 'Server Certificate Invalid or not present';
SNetHttpServerCertificateNotAccepted = 'Server Certificate not accepted';
SNetHttpEmptyCertificateList = 'Empty certificate list';
SNetHttpUnspecifiedCertificate = 'Unspecified certificate from client';
SNetHttpRejectedCertificate = 'Client rejected the certificate';
SNetHttpIdentitiesError = 'Error obtaining identities';
SNetHttpCertificatesError = 'Error obtaining certificates';
SNetHttpIdentityCertError = 'Error getting the identity of the certificate';
SNetHttpCertificateImportError = 'Error importing certificate';
SNetHttpClientUnknownError = 'Execution of request terminated with unknown error';
SNetHttpClientErrorAccessing = 'Error %d accessing to %s: %s';
SNetHttpComponentRequestClient = 'Client not assigned to request component';
SNetHttpHeadersError = 'Error querying headers: (%d) %s';
SNetHttpClientHandleError = 'Error obtaining session handle';
SNetHttpClientSendError = 'Error sending data: (%d) %s';
SNetHttpClientReceiveError = 'Error receiving data: (%d) %s';
SNetHttpRequestConnectError = 'Error connecting to server: %s';
SNetHttpRequestOpenError = 'Error opening request: (%d) %s';
SNetHttpRequestAddHeaderError = 'Error adding header: (%d) %s';
SNetHttpRequestRemoveHeaderError = 'Error removing header: (%d) %s';
SNetHttpRequestQueryDataError = 'Error querying data available: (%d) %s';
SNetHttpRequestReadDataError = 'Error reading data: (%d) %s';
SNetHttpRequestSetTimeoutError = 'Error setting timeout for the request: (%d) %s';
SNetHttpClientResponseError = 'Error obtaining response data';
{ Beacon }
SAPINotAvailable = 'Beacon API not available on this platform';
SBeaconNoDeviceRegister = 'No Beacon device registered';
SNotAllowedLocationServices = 'You are not allowed to use location services.';
SCannotChangeBeaconType = 'Beacon type cannot be changed in this mode';
SMonitoringNotAvailable = 'Monitoring is not available on this device.';
SManagerOnlyInMode = 'This manager can only be used in %s mode.';
SBeaconDeviceNoUUID = 'You must provide a proximity UUID';
SBeaconIncorrectMID = 'Incorrect ManufacturerId';
SBeaconIncorrectEddyNamespace = 'Invalid Namespace ID (10 Hex num)';
SBeaconIncorrectEddyInstance = 'Invalid Instance ID (6 Hex num)';
SiOSiBeaconMustBeRegistered = 'A region must be registered in order to scan for iBeacons due to Core Location framework.';
SBeaconMDHelperModesNotPermitted = 'These modes are not permitted';
SEddystoneAdvertiseNotSupported = 'Eddystone format not supported';
SInvalidEddystoneNamespace = '%s is not a valid Eddystone namespace';
SInvalidEddystoneInstance = '%s is not a valid Eddystone instance';
SIncorrectTxPower = 'We have fixed the TxValue for this beacon, previous value was %d';
{ Sockets }
sSocketError = 'Network socket error: %s (%d), on API ''%s''';
sSocketAlreadyClosed = 'Socket already closed';
sSocketNotListening = 'Socket not listening';
sIncorrectSocketType = 'Socket type not compatible with call';
sBroadcastOnUDPOnly = 'Only UDP socket types support broadcasts';
sSocketNotValid = 'Invalid socket handle';
sFDSetSizeTooLarge = 'Number of sockets must not exceed FD_SETSIZE(%d)';
sFunctionNil = 'Async function must not be nil';
{ Bluetooth }
SBluetoothOperationNotSupported = 'Operation not supported with this descriptor kind: %s';
SBluetoothMissingImplementation = 'No BluetoothManager implementation found';
SBluetoothInvalidServiceName = 'Invalid service name, you must provide one.';
SBluetoothNotImplemented = 'Not supported on this platform';
SBluetoothDeviceNotFound = 'Bluetooth device not found: disconnected or turned off';
SBluetoothNoDiscoverable = 'Cannot set discoverable mode';
SBluetoothCanNotConnect = 'Cannot connect to device: %s';
SBluetoothNoService = 'Cannot get service record for the service: %s on device: %s';
SBluetoothNoRFChannel = 'Cannot get RFCOMM channel ID to connect to the device: %s, service: %s';
SBluetoothCanNotRemoveService = 'Cannot remove service: %s';
SBluetoothRFChannelClosed = 'Channel is closed, cannot read data';
SBluetoothCanNotSendData = 'Error sending data over current channel';
SBluetoothScanModeError = 'The bluetooth adapter is in unknown scan mode';
SBluetoothStateError = 'Cannot retrieve the state of the bluetooth adapter';
SBluetoothNotSupported = 'Operation "%s" not supported on %s';
SBluetoothDeviceStateError = 'Cannot get state for device: %s';
SBluetoothSocketOutputStreamError = 'Cannot create Socket Output Stream';
SBluetoothCharacteristicError = 'Error while working with characteristic, error message: %s, %d';
SBluetoothDescriptorTypeError = 'Not applicable to this descriptor type';
SBluetoothSettingPropertyError = 'Error setting property: %s';
SBluetoothAndroidVersionError = 'Need at least Android %s (API %s)';
SBluetoothServiceListError = 'Error getting service list: (%d) %s';
SBluetoothDeviceInfoError = 'Error getting device info: (%d) %s';
SBluetoothAcceptError = 'Error trying to accept connections';
SBluetoothUnregisterError = 'Error unregistering service: %s';
SBluetoothCreateSocketError = 'Unable to create server socket';
SBluetoothServerSocket = 'Cannot create server socket: %s';
SBluetoothServiceError = 'Service registration error(%d): %s';
SBluetoothServiceAlreadyExists = 'Service %s is already added to this server';
SBluetoothRCVTIMEOError = 'Error calling setsockopt SO_RCVTIMEO: %s';
SBluetoothWisockInitError = 'Bluetooth: Unable to initialize Winsock';
SBluetoothWisockCleanupError = 'Bluetooth: Unable to clean up Winsock';
SBluetoothSetSockOptError = 'Error calling setsockopt: %s';
SBluetoothClientsocketError = 'Cannot create client socket';
SBluetoothClientConnectError = 'Cannot connect to device: (%d) %s';
SBluetoothSendDataError = 'Cannot send data: (%d) %s';
SBluetoothWSALookupError = 'Bluetooth: WSALookupServiceBegin error: (%d) %s';
SBluetoothUsedGUIDError = 'Unable to create server socket: the specified GUID is in use';
SBluetoothIntegerFormatType = 'Format type (%d) for Integer conversion is not supported';
SBluetoothSingleFormatType = 'Format type (%d) for Single conversion is not supported';
{ Bluetooth LE }
SBluetoothLECanNotFindCharacteristic = 'Cannot find characteristic: %s';
SBluetoothLECanNotFindDescriptor = 'Cannot find descriptor: %s';
SBluetoothLECanNotDiscoverServices = 'Cannot discover services for device: %s';
SBluetoothLECanNotGetIncludedServices = 'Cannot get list of included services for service: %s';
SBluetoothLECharacteristicExists = 'Characteristic with UUID: %s already exists';
SBluetoothLENoCharacteristics = 'Cannot get list of characteristics for service: %s';
SBluetoothLENoDescriptors = 'Cannot get list of descriptors for characteristic: %s';
SBluetoothOSVersionError = 'At least MacOS X 10.9 or iOS 6 is required to create Gatt servers';
SBluetoothLEGetDevicesError = 'Cannot get list of LE devices: (%d) %s';
SBluetoothLEGetDeviceError = 'Cannot get the LE device';
SBluetoothLENoDeviceAssigned = 'No Device assigned';
SBluetoothLEDeviceHandleError = 'Bluetooth: Create LE device handle error: (%d) %s';
SBluetoothLEGattServiceError = 'Bluetooth: BluetoothGATTGetServices res: %d(%X) error: (%d) %s';
SBluetoothLEGattIncludedServicesError = 'Bluetooth: BluetoothGATTGetIncludedServices error: (%d) %s';
SBluetoothLEGetServicesHandle = 'SetupDiGetClassDevs error: (%d) %s';
SBluetoothLENoServiceAssigned = 'No Service assigned';
SBluetoothLEDeviceNotPaired = 'This device is not paired';
SBluetoothLEDeviceDisconnectedExplicity = 'This device was explicitly disconnected';
SBluetoothLEAdvertisementEmpty = 'The advertisement is empty';
ADVERTISE_FAILED_DEVICE_NOT_SUPPORTED = 'The device does not support peripheral mode';
ADVERTISE_FAILED_DATA_TOO_LARGE = 'Failed to start advertising as the advertise data to be broadcasted is larger than 31 bytes';
ADVERTISE_FAILED_TOO_MANY_ADVERTISERS = 'Failed to start advertising because no advertising instance is available';
ADVERTISE_FAILED_ALREADY_STARTED = 'Failed to start advertising as the advertising is already started';
ADVERTISE_FAILED_INTERNAL_ERROR = 'Operation failed due to an internal error';
ADVERTISE_FAILED_FEATURE_UNSUPPORTED = 'This feature is not supported on this platform';
ADVERTISE_FAILED_UNKNOWN_ERROR = 'There was an unknown error';
{ Mime }
SMimeDuplicateType = 'Pair of extension and mime type already exists';
SMimeTypeEmpty = 'Mime type cannot be empty';
SMimeValueEmpty = 'Value name cannot be empty';
SMimeWeightOutOfRange = 'Quality weight is out of range';
const
DefaultUserAgent = 'Embarcadero URI Client/1.0'; // Do not translate
// Common Header Names
sUserAgent = 'User-Agent'; // Do not translate
sAccept = 'Accept'; // Do not translate
sAcceptCharset = 'Accept-Charset'; // Do not translate
sAcceptEncoding = 'Accept-Encoding'; // Do not translate
sAcceptLanguage = 'Accept-Language'; // Do not translate
sAcceptRanges = 'Accept-Ranges'; // Do not translate
sContentEncoding = 'Content-Encoding'; // Do not translate
sContentLanguage = 'Content-Language'; // Do not translate
sContentLength = 'Content-Length'; // Do not translate
sContentType = 'Content-Type'; // Do not translate
sLastModified = 'Last-Modified'; // Do not translate
sContentDisposition = 'Content-Disposition'; // Do not translate
sLocation = 'Location'; // Do not translate
sSetCookie = 'Set-Cookie'; // Do not translate
sCookie = 'Cookie'; // Do not translate
sRange = 'Range'; // Do not translate
sXMethodOverride = 'x-method-override'; // Do not translate
sWWWAuthenticate = 'WWW-Authenticate'; // Do not translate
sProxyAuthenticate = 'Proxy-Authenticate'; // Do not translate
sAuthorization = 'Authorization'; // Do not translate
sProxyAuthorization = 'Proxy-Authorization'; // Do not translate
implementation
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: DataModule
The MIT License
Copyright: Copyright (C) 2015 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
******************************************************************************* }
unit UDataModule;
interface
uses
SysUtils, Classes, DB, DBClient, Provider, ImgList, Controls, JvDataSource,
JvDBGridExport, JvComponentBase, Dialogs, JvPageList, Variants, Tipos,
Graphics,
ACBrBase, JvBaseDlg,
JvBrowseFolder, ACBrSpedFiscal, ACBrDFe,
ACBrSATExtratoClass, ACBrSATExtratoFortes, ACBrSATExtratoFortesFr, ACBrSAT;
type
TFDataModule = class(TDataModule)
ACBrSAT: TACBrSAT;
ACBrSATExtratoFortes: TACBrSATExtratoFortes;
procedure ACBrSATGetsignAC(var Chave: AnsiString);
procedure ACBrSATGetcodigoDeAtivacao(var Chave: AnsiString);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FDataModule: TFDataModule;
implementation
{$R *.dfm}
{ TFDataModule }
procedure TFDataModule.ACBrSATGetcodigoDeAtivacao(var Chave: AnsiString);
begin
Chave := '12345678';
end;
procedure TFDataModule.ACBrSATGetsignAC(var Chave: AnsiString);
begin
Chave := 'eije11111111111111111111111111111111111111111111111111111111111'+
'111111111111111111111111111111111111111111111111111111111111111'+
'111111111111111111111111111111111111111111111111111111111111111'+
'111111111111111111111111111111111111111111111111111111111111111'+
'111111111111111111111111111111111111111111111111111111111111111'+
'11111111111111111111111111111';
end;
end.
|
1 unit Lists;
2 { Oktober 2003; Tom Verhoeff; versie 1.0 }
3 { unit om lijsten te manipuleren }
4 { Oefenversie zonder implementatie van Find }
5
6 interface
7
8 const
9 MaxListLen = 24; { maximum lengte van een lijst, 1 <= MaxListLen }
10 MinEntry = 0; { kleinste waarde in een lijst }
11 MaxEntry = 99; { grootste waarde in een lijst, MinEntry <= MaxEntry }
12
13 type
14 Index = 0 .. MaxListLen - 1; { index in een lijst }
15 Entry = MinEntry .. MaxEntry; { waarde in een lijst }
16 List = record
17 len: 0 .. MaxListLen; { actuele lengte van de lijst }
18 val: array [ Index ] of Entry; { de rij van waarden in de lijst }
19 { de lijst bestaat uit de waarden val[0] t/m val[len-1] }
20 end;
21 { Voor s: List, is vereist dat s.val[i] gedefinieerd is voor 0 <= i < s.len }
22
23 procedure Find ( const s: List; const x: Entry;
24 var found: Boolean; var pos: Index );
25 { zoek x in lijst s }
26 { pre: s is oplopend gesorteerd (duplicaten toegestaan)
27 post: found = `er bestaat een i met 0<=i<s.len en s.val[i]=x', en
28 found impliceert 0<=pos<s.len en s.val[pos] = x }
29
30 procedure WriteList ( var f: Text; const ident: String; const s: List );
31 { schrijf lijst s naar f }
32 { pre: f is geopend om te schrijven
33 post: lijst s is geschreven naar f, volgens het formaat
34 ident.len: ...
35 ident.val: ... }
36
37 procedure GenerateList ( var s: List; const n, m, d, c: Integer );
38 { genereer lijst s met lengte n volgens patroon m, d, c:
39 blokken van lengte d met gelijke waarden c, c+m, c+2m, ... }
40 { pre: 0 <= n <= MaxListLen, d > 0,
41 MinEntry <= m * (i div d) + c <= MaxEntry voor 0 <= i < n
42 post: s.len = n en s.val[i] = m * (i div d) + c voor 0 <= i < n }
43
44 implementation
45
46 //** PROCEDURE FIND ************************
47
48
49 procedure Find ( const s: List; const x: Entry;
50 var found: Boolean; var pos: Index );
51 { zie interface }
52
53 var
54 h: Integer; // var voor het bepalen van het midden
55 i: Integer; // de lower limit
56 j: Integer; // de upper limit
57
58 begin
59
60 // ** INITIALISATION ***
61 i := -1; // vaststellen lower limit
62 j := s.len; // vaststellen upper limit
63 found := false; // we gaan ervanuit dat het getal we we zoeken
64 // niet word gevonden
65 pos := 0; // we gaan ervanuit dat het getal we we zoeken
66 // niet word gevonden
67
68
69 // de zoekende while lus. Zolang i + 1 < j moet er gezocht worden.
70 while ( ( i + 1 ) < j ) do
71 begin
72
73 h := ( i + j ) div 2; // bepaal het midden
74
75 if s.val[h] <= x then // als de waarde van het midden kleiner of
76 begin // gelijk is aan x, dan stellen we de lower
77 i := h // limit bij
78 end // end if
79 else if s.val[h] > x then // als de waarde van het midden groter is dan
80 begin // x, dan stellen we de upper limit bij
81 j := h
82 end // end if
83
84 end; // end while
85
86 if ( i >= 0 ) then // we controleren nu of het gevonden getal in
87 begin // de lijst staat.
88 if s.val[i] = x then // is de waarde van getal i gelijk aan x?
89 begin
90 found := True; // we hebben ons geta; gevonden
91 pos := i; // en de positie van x
92 end;
93 end;
94
95
96
97 end; // end Procedure Find
98
99 procedure WriteList ( var f: Text; const ident: String; const s: List );
100 { zie interface }
101 var
102 i: Integer; { om waarden van s te doorlopen }
103 { i: Index, but then for-loop fails with Range Check error when s.len=0 }
104 begin
105 with s do begin
106 writeln ( f, ident, '.len: ', len )
107 ; write ( f, ident, '.val:' )
108
109 ; for i := 0 to len - 1 do begin
110 write ( f, ' ', val [ i ] )
111 end { for i }
112
113 ; writeln ( f )
114 end { with s }
115 end; { WriteList }
116
117 procedure GenerateList ( var s: List; const n, m, d, c: Integer );
118 { zie interface }
119 begin
120 with s do begin
121 len := 0
122
123 { invariant: val[i] ingevuld voor alle i met 0 <= i < len <= n }
124 ; while len <> n do begin
125 val[len] := m * ( len div d ) + c
126 ; len := len + 1
127 end { for len }
128
129 end { with s }
130 end; { GenerateList }
131
132 end. |
(* AbsTreeTest: MM, 2020-05-01 *)
(* ------ *)
(* Program to test the Abstract Syntax Tree *)
(* ========================================================================= *)
PROGRAM AbsTreeTest;
USES syntaxtree_abstract;
VAR t: SynTree;
PROCEDURE TestTree(l: STRING);
BEGIN (* TestTree *)
NewTree(t);
line := l;
WriteLn(line);
WriteLn('**************');
S(t);
IF (t = NIL) THEN BEGIN
WriteLn('Could not create Tree, calculation is invalid');
END ELSE BEGIN
WriteTree(t);
WriteLn('---------- Pre-Order ----------');
WriteTreePreOrder(t);
WriteLn('---------- In-Order ----------');
WriteTreeInOrder(t);
WriteLn('---------- Post-Order ----------');
WriteTreePostOrder(t);
WriteLn('---------- Value-Of ----------');
WriteLn('Value: ', ValueOf(t));
DisposeTree(t);
END; (* IF *)
END; (* TestTree *)
VAR s: STRING;
BEGIN (* AbsTreeTest *)
REPEAT
Write('Enter Calculation > ');
ReadLn(s);
TestTree(s);
UNTIL (s = ''); (* REPEAT *)
END. (* AbsTreeTest *) |
{ InternetExpress sample application.
The InetXCenter sample application displays information
about various InternetExpress components. This information
is stored in a local file created by TClientDataSet.
This application is used to edit the information in the
local file.
ClientDataSet1.FileName is the file used to store the CDS.
When ClientDataSet1 is activated at design time, you may
not see the data seen at runtime because the application
output directory may be different than the project directory.
}
unit ComponentsInfoEditorUnit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, DBCtrls, ExtCtrls, Grids, DBGrids, Db, DBClient;
type
TForm1 = class(TForm)
DataSource1: TDataSource;
DBNavigator1: TDBNavigator;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Splitter1: TSplitter;
DBGrid1: TDBGrid;
DBComboBox1: TDBComboBox;
DBMemo1: TDBMemo;
DBMemo2: TDBMemo;
Button1: TButton;
Button2: TButton;
ClientDataSet1: TClientDataSet;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ClientDataSet1AfterInsert(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
if ClientDataSet1.Modified then
ClientDataSet1.Post;
ClientDataSet1.SaveToFile(ClientDataSet1.FileName);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
ClientDataSet1.Close;
ClientDataSet1.LoadFromFile(ClientDataSet1.FileName);
end;
procedure TForm1.ClientDataSet1AfterInsert(DataSet: TDataSet);
begin
{ Workaround bug in which memo text can't be created once
a record is inserted. }
DBMemo1.Text := ' ';
DBMemo2.Text := ' ';
end;
{ The structure of a client data set can't be changed
without losing the data. To change the structure, create
a new clientdataset and use code like this to copy data
from the old dataset to the new dataset.
}
{
procedure TForm1.Button5Click(Sender: TObject);
procedure CopyValue(FieldName: string);
begin
ClientDataSet2.FieldByName(FieldName).Value :=
ClientDataSet1.FieldByName(FieldName).Value;
end;
begin
ClientDataSet1.Active := true;
ClientDataSet2.Active := true;
while not ClientDataSet1.eof do
begin
ClientDataSet2.Insert;
CopyValue('ClassName');
CopyValue('Description');
CopyValue('ShortDescription');
CopyValue('Usage');
ClientDataSet2.Post;
ClientDataSet1.Next;
end;
end;
}
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSMWaveOut<p>
Basic sound manager based on WinMM <p>
<b>History : </b><font size=-1><ul>
<li>17/11/09 - DaStr - Improved Unix compatibility
(thanks Predator) (BugtrackerID = 2893580)
<li>25/07/09 - DaStr - Added $I GLScene.inc
<li>30/05/09 - DanB - Fixes for AV when sound finishes, and was repeating the same code more than necessary.
<li>24/04/09 - DanB - Creation, split from GLSound.pas, to remove windows dependency
</ul></font>
}
unit GLSMWaveOut;
interface
{$I GLScene.inc}
{$IFDEF UNIX}{$Message Error 'Unit not supported'}{$ENDIF}
uses Classes, GLSound, MMSystem, GLSoundFileObjects;
type
// TGLSMWaveOut
//
{: Basic sound manager based on WinMM <i>waveOut</i> function.<p>
This manager has NO 3D miximing capacity, this is merely a default manager
that should work on any windows based system, and help showcasing/testing
basic GLSS core functionality.<p>
Apart from 3D, mute, pause, priority and volume are ignored too, and only
sampling conversions supported by the windows ACM driver are supported
(ie. no 4bits samples playback etc.). }
TGLSMWaveOut = class (TGLSoundManager)
private
{ Private Declarations }
protected
{ Protected Declarations }
function DoActivate : Boolean; override;
procedure DoDeActivate; override;
procedure KillSource(aSource : TGLBaseSoundSource); override;
public
{ Public Declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure UpdateSources; override;
published
{ Published Declarations }
property MaxChannels default 4;
end;
procedure PlayOnWaveOut(pcmData : Pointer; lengthInBytes : Integer;
sampling : TGLSoundSampling); overload;
function PlayOnWaveOut(pcmData : Pointer; lengthInBytes : Integer;
waveFormat : TWaveFormatEx) : HWaveOut; overload;
implementation
uses SysUtils;
type
TSoundState = (ssPlaying, ssFinished);
TWaveOutPlayingRec = record
CurrentState: TSoundState;
WaveOutDevice: hwaveout;
WaveHeader: wavehdr;
end;
PWaveOutPlayingRec = ^TWaveOutPlayingRec;
procedure _waveOutCallBack2(hwo : HWAVEOUT; uMsg : Cardinal;
dwInstance, dwParam1, dwParam2 : Integer); stdcall;
begin
if uMsg=WOM_DONE then
waveOutClose(hwo);
end;
// PlayOnWaveOut (waveformat)
//
function PlayOnWaveOut(pcmData : Pointer; lengthInBytes : Integer;
waveFormat : TWaveFormatEx) : HWaveOut;
var
hwo : hwaveout;
wh : wavehdr;
mmres : MMRESULT;
begin
mmres:=waveOutOpen(@hwo, WAVE_MAPPER, @waveFormat, Cardinal(@_waveOutCallBack2),
0, CALLBACK_FUNCTION);
Assert(mmres=MMSYSERR_NOERROR, IntToStr(mmres));
wh.dwBufferLength:=lengthInBytes;
wh.lpData:=pcmData;
wh.dwFlags:=0;
wh.dwLoops:=1;
wh.lpNext:=nil;
mmres:=waveOutPrepareHeader(hwo, @wh, SizeOf(wavehdr));
Assert(mmres=MMSYSERR_NOERROR, IntToStr(mmres));
mmres:=waveOutWrite(hwo, @wh, SizeOf(wavehdr));
Assert(mmres=MMSYSERR_NOERROR, IntToStr(mmres));
Result:=hwo;
end;
// PlayOnWaveOut (sampling)
//
procedure PlayOnWaveOut(pcmData : Pointer; lengthInBytes : Integer;
sampling : TGLSoundSampling);
var
wfx : TWaveFormatEx;
begin
wfx:=sampling.WaveFormat;
PlayOnWaveOut(pcmData, lengthInBytes, wfx);
end;
// ------------------
// ------------------ TGLSMWaveOut ------------------
// ------------------
// Create
//
constructor TGLSMWaveOut.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
MaxChannels:=4;
end;
// Destroy
//
destructor TGLSMWaveOut.Destroy;
begin
inherited Destroy;
end;
// DoActivate
//
function TGLSMWaveOut.DoActivate : Boolean;
begin
Result:=True;
end;
// DoDeActivate
//
procedure TGLSMWaveOut.DoDeActivate;
var
i : Integer;
begin
for i:=Sources.Count-1 downto 0 do
KillSource(Sources[i]);
end;
// KillSource
//
procedure TGLSMWaveOut.KillSource(aSource : TGLBaseSoundSource);
var
pRec: PWaveOutPlayingRec;
begin
if aSource.ManagerTag<>0 then begin
pRec := PWaveOutPlayingRec(aSource.ManagerTag);
if pRec.CurrentState=ssPlaying then
waveOutReset(pRec.WaveOutDevice);
waveOutUnprepareHeader(pRec.WaveOutDevice, @pRec.WaveHeader, sizeof(wavehdr));
waveOutClose(pRec.WaveOutDevice);
Dispose(pRec);
aSource.ManagerTag:=0;
end;
end;
// Note: This callback function is called from another thread, from MSDN docs:
// "Applications should not call any system-defined functions from inside a
// callback function, except for EnterCriticalSection, LeaveCriticalSection,
// midiOutLongMsg, midiOutShortMsg, OutputDebugString, PostMessage,
// PostThreadMessage, SetEvent, timeGetSystemTime, timeGetTime, timeKillEvent,
// and timeSetEvent. Calling other wave functions will cause deadlock."
procedure _waveOutCallBack(hwo : HWAVEOUT; uMsg : Cardinal;
dwInstance, dwParam1, dwParam2 : Integer); stdcall;
begin
if uMsg=WOM_DONE then begin
PWaveOutPlayingRec(TGLSoundSource(dwInstance).ManagerTag).CurrentState:=ssFinished;
end;
end;
// UpdateSource
//
procedure TGLSMWaveOut.UpdateSources;
var
i, n : Integer;
wfx : TWaveFormatEx;
smp : TGLSoundSample;
wh : wavehdr;
mmres : MMRESULT;
hwo : hwaveout;
pRec: PWaveOutPlayingRec;
begin
// count nb of playing sources and delete done ones
n:=0;
for i:=Sources.Count-1 downto 0 do
if Sources[i].ManagerTag<>0 then
if PWaveOutPlayingRec(Sources[i].ManagerTag).currentState=ssPlaying then
Inc(n)
else
Sources.Delete(i);
// start sources if some capacity remains, and forget the others
for i:=Sources.Count-1 downto 0 do if Sources[i].ManagerTag=0 then begin
if n<MaxChannels then begin
smp:=Sources[i].Sample;
if Assigned(smp) and (smp.Data<>nil) then begin
wfx:=smp.Data.Sampling.WaveFormat;
mmres:=waveOutOpen(@hwo, WAVE_MAPPER, @wfx,
Cardinal(@_waveOutCallBack), Integer(Sources[i]),
CALLBACK_FUNCTION);
Assert(mmres=MMSYSERR_NOERROR, IntToStr(mmres));
FillChar(wh,sizeof(wh),0);
wh.dwBufferLength:=smp.LengthInBytes;
wh.lpData:=smp.Data.PCMData;
wh.dwLoops:=Sources[i].NbLoops;
if wh.dwLoops>1 then
wh.dwFlags:=WHDR_BEGINLOOP+WHDR_ENDLOOP
else wh.dwFlags:=0;
wh.lpNext:=nil;
new(pRec);
pRec.waveoutdevice:=hwo;
pRec.waveheader:=wh;
pRec.CurrentState:=ssPlaying;
mmres:=waveOutPrepareHeader(hwo, @pRec.waveheader, SizeOf(wavehdr));
Assert(mmres=MMSYSERR_NOERROR, IntToStr(mmres));
Sources[i].ManagerTag:=Integer(prec);
mmres:=waveOutWrite(hwo, @pRec.waveheader, SizeOf(wavehdr));
Assert(mmres=MMSYSERR_NOERROR, IntToStr(mmres));
Inc(n);
end else
Sources.Delete(i);
end else
Sources.Delete(i);
end;
end;
initialization
RegisterClasses([TGLSMWaveOut]);
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000-2002 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QDialogs;
{$R-,T-,H+,X+}
interface
uses
{$IFDEF MSWINDOWS} Windows, Messages, ShlObj, ActiveX, CommDlg, {$ENDIF}
SysUtils, Types, QTypes, Qt, Classes, QGraphics, QControls, QStdCtrls, QForms,
QExtCtrls;
const
{ Maximum number of custom colors in color dialog }
MaxCustomColors = 16;
type
EQtDialogException = class(Exception);
TDialog = class(TComponent)
private
FHelpType: THelpType;
FScaleFlags: TScalingFlags;
FPosition: TPoint;
FModal: Boolean;
FShowing: Boolean;
FHelpKeyword: string;
FOnClose: TNotifyEvent;
FOnShow: TNotifyEvent;
FWidth: Integer;
FHeight: Integer;
FTitle: WideString;
FHelpContext: THelpContext;
procedure SetPosition(const Value: TPoint);
function GetPosition: TPoint;
function GetHeight: Integer;
function GetWidth: Integer;
procedure SetHeight(const Value: Integer);
procedure SetWidth(const Value: Integer);
protected
procedure DoClose; dynamic;
function DoExecute: Boolean; virtual; abstract;
procedure DoShow; dynamic;
function GetBounds: TRect; virtual; abstract;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); virtual; abstract;
procedure SetTitle(const Value: WideString); virtual;
property Height: Integer read GetHeight write SetHeight;
property Modal: Boolean read FModal write FModal default True;
property Position: TPoint read GetPosition write SetPosition;
property Title: WideString read FTitle write SetTitle;
property Width: Integer read GetWidth write SetWidth;
property OnClose: TNotifyEvent read FOnClose write FOnClose;
property OnShow: TNotifyEvent read FOnShow write FOnShow;
public
constructor Create(AOwner: TComponent); override;
function Execute: Boolean; virtual;
published
property HelpType: THelpType read FHelpType write FHelpType default htKeyword;
property HelpContext: THelpContext read FHelpContext write FHelpContext default 0;
property HelpKeyword: string read FHelpKeyword write FHelpKeyword;
end;
{ TQtDialog }
TQtDialog = class(TDialog)
private
FHooks: QObject_hookH;
FHandle: QDialogH;
{$IFDEF MSWINDOWS}
FUseNative: Boolean;
FNativeFlags: Integer;
{$ENDIF}
function GetHandle: QDialogH;
procedure CreateHandle;
procedure DestroyedHook; cdecl;
procedure HandleNeeded;
procedure InvokeHelp;
function GetHooks: QObject_hookH;
protected
function AppEventFilter(Sender: QObjectH; Event: QEventH): Boolean; virtual; cdecl;
procedure CreateWidget; virtual;
procedure DestroyWidget;
procedure InitWidget; virtual;
function GetBounds: TRect; override;
procedure HookEvents; virtual;
function DoExecute: Boolean; override;
procedure DoShow; override;
{$IFDEF MSWINDOWS}
function NativeExecute(Flags: Integer): Boolean; virtual;
{$ENDIF}
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure SetTitle(const Value: WideString); override;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; virtual; cdecl;
function WidgetFlags: Integer; virtual;
property Hooks: QObject_hookH read GetHooks write FHooks;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: Boolean; override;
function HandleAllocated: Boolean;
property Handle: QDialogH read GetHandle;
property Position;
published
property Height default 0;
{$IFDEF MSWINDOWS}
property NativeFlags: Integer read FNativeFlags write FNativeFlags default 0;
property UseNativeDialog: Boolean read FUseNative write FUseNative default True;
{$ENDIF}
property Width default 0;
end;
{ TColorDialog }
TCustomColors = array[0..MaxCustomColors - 1] of Longint;
TColorDialog = class(TQtDialog)
private
FColor: TColor;
FCustomColors: TStrings;
procedure SetCustomColors(Value: TStrings);
protected
function DoExecute: Boolean; override;
{$IFDEF MSWINDOWS}
function NativeExecute(Flags: Integer): Boolean; override;
{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Color: TColor read FColor write FColor default clBlack;
property CustomColors: TStrings read FCustomColors write SetCustomColors;
end;
{ TFontDialog }
TFontDialog = class(TQtDialog)
private
FFont: TFont;
procedure SetFont(Value: TFont);
protected
function DoExecute: Boolean; override;
{$IFDEF MSWINDOWS}
function NativeExecute(Flags: Integer): Boolean; override;
{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Font: TFont read FFont write SetFont;
end;
TCustomDialog = class;
TDialogForm = class(TForm)
private
FDialog: TCustomDialog;
public
procedure InvokeHelp; override;
property Dialog: TCustomDialog read FDialog;
end;
TDialogFormClass = class of TDialogForm;
TCustomDialog = class(TDialog)
private
FForm: TDialogForm;
procedure Close(Sender: TObject; var Action: TCloseAction);
protected
function CreateForm: TDialogForm; virtual; abstract;
function DoExecute: Boolean; override;
procedure DoShow; override;
procedure DoClose; override;
function GetBounds: TRect; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure SetTitle(const Value: WideString); override;
public
destructor Destroy; override;
function Execute: Boolean; override;
property Form: TDialogForm read FForm;
procedure InvokeHelp;
end;
{ TOpenDialog }
var
FileDialogFormClass: TDialogFormClass = nil;
type
IFilePreviewer = interface
['{A1CE46CC-8358-4823-8743-C81787BE9263}']
function CanPreview(const Filename: string): Boolean;
procedure GetPreviewSize(Filename: string; Canvas: TCanvas; var Size: TSize);
procedure Preview(const Filename: string; Canvas: TCanvas; const Rect: TRect;
Progress: TProgressEvent);
procedure StopPreview;
end;
TOpenDialog = class;
TOpenOption = (ofShowHidden, ofOverwritePrompt, ofNoChangeDir, ofAllowMultiSelect,
ofExtensionDifferent, ofPathMustExist, ofFileMustExist, ofEnableSizing, ofShowHelp,
ofHideReadOnly, ofReadOnly, ofViewDetail, ofViewIcon, ofViewList, ofPreview,
ofAutoPreview);
TOpenOptions = set of TOpenOption;
TFileAddEvent = procedure(Sender: TObject; const Filename: string; const Readable,
Writeable, Executable: Boolean; var CanAdd: Boolean) of object;
TFileSelectEvent = procedure(Sender: TObject; const Filename: string) of object;
TFilePreviewEvent = procedure(Sender: TObject; const Filename: string;
Canvas: TCanvas; const Rect: TRect; Progress: TProgressEvent; var Handled: Boolean) of object;
TDirChangeEvent = procedure(Sender: TObject; const Dir: string) of object;
TFilterChangeEvent = procedure(Sender: TObject; NewIndex: Integer) of object;
TFileSelectedEvent = procedure(Sender: TObject; AFile: PFileInfo;
Selected: Boolean) of object;
IOpenDialog = interface
['{D88505E5-3A59-D611-9577-00B0D006527D}']
procedure CanClose(var CanClose: Boolean);
procedure DirChanged(NewDir: WideString);
function FileAdd(const Filename: WideString; const Readable, Writeable,
Executable: Boolean): Boolean;
procedure FilePreview(const Filename: WideString; Canvas: TCanvas;
const Rect: TRect; Progress: TProgressEvent; var Handled: Boolean);
procedure FileSelected(AFile: PFileInfo; Selected: Boolean);
procedure FilterChanged(Index: Integer);
procedure Help;
end;
IFileDialogForm = interface
['{D8C78BC3-15FB-D511-9898-94D131D16641}']
procedure GetOptions(OpenDlg: TOpenDialog; Accepted: Boolean);
function GetSelected: TFileInfos;
procedure ListFiles(List: TStrings);
procedure ResizePreview(const NewSize: TSize);
procedure SetOptions(OpenDlg: TOpenDialog);
end;
TOpenDialog = class(TCustomDialog, IOpenDialog)
private
FOptions: TOpenOptions;
FSaveDlg: Boolean;
FHistoryList: TStrings;
FFilter: string;
FInitialDir: string;
FSaveDir: string;
FDefaultExt: string;
FFileName: WideString;
FFiles: TStrings;
FFilterIndex: Integer;
FOnFileAdd: TFileAddEvent;
FOnFolderChange: TDirChangeEvent;
FOnSelected: TFileSelectedEvent;
FOnCanClose: TCloseQueryEvent;
FOnFilterChange: TFilterChangeEvent;
{$IFDEF MSWINDOWS}
FNativeFlags: Integer;
FUseNative: Boolean;
FHandle: HWnd;
{$ENDIF}
FOnHelpClick: TNotifyEvent;
FOnPreview: TFilePreviewEvent;
procedure SetHistoryList(Value: TStrings);
procedure SetSaveDlg(const Value: Boolean);
protected
function CreateForm: TDialogForm; override;
function DoExecute: Boolean; override;
procedure SetOptions; virtual;
procedure RetrieveOptions(Accepted: Boolean); virtual;
property SaveDlg: Boolean read FSaveDlg write SetSaveDlg default False;
// IOpenDialog
procedure DirChanged(NewDir: WideString); virtual;
procedure CanClose(var CanClose: Boolean); virtual;
function FileAdd(const Filename: WideString; const Readable, Writeable,
Executable: Boolean): Boolean; virtual;
procedure FilePreview(const Filename: WideString; Canvas: TCanvas;
const Rect: TRect; Progress: TProgressEvent; var Handled: Boolean); virtual;
procedure FileSelected(AFile: PFileInfo; Selected: Boolean); virtual;
procedure FilterChanged(Index: Integer); virtual;
procedure Help; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: Boolean; override;
{$IFDEF MSWINDOWS}
function NativeExecute(Flags: Integer): Boolean; virtual;
{$ENDIF}
procedure Refresh;
property Files: TStrings read FFiles;
property HistoryList: TStrings read FHistoryList write SetHistoryList;
published
property DefaultExt: string read FDefaultExt write FDefaultExt;
property FileName: WideString read FFileName write FFileName;
property Filter: string read FFilter write FFilter;
property FilterIndex: Integer read FFilterIndex write FFilterIndex default 1;
property InitialDir: string read FInitialDir write FInitialDir;
property Options: TOpenOptions read FOptions write FOptions
default [ofHideReadOnly, ofEnableSizing];
property Height default 350;
{$IFDEF MSWINDOWS}
property NativeFlags: Integer read FNativeFlags write FNativeFlags default 0;
property UseNativeDialog: Boolean read FUseNative write FUseNative default True;
{$ENDIF}
property Title;
property Width default 550;
property OnClose;
property OnCanClose: TCloseQueryEvent read FOnCanClose write FOnCanClose;
property OnFileAdd: TFileAddEvent read FOnFileAdd write FOnFileAdd;
property OnFilePreview: TFilePreviewEvent read FOnPreview write FOnPreview;
property OnFilterChange: TFilterChangeEvent read FOnFilterChange
write FOnFilterChange;
property OnFolderChange: TDirChangeEvent read FOnFolderChange
write FOnFolderChange;
property OnHelpButtonClick: TNotifyEvent read FOnHelpClick write FOnHelpClick;
property OnSelected: TFileSelectedEvent read FOnSelected write FOnSelected;
property OnShow;
end;
{ TSaveDialog }
TSaveDialog = class(TOpenDialog)
protected
procedure SetOptions; override;
public
{$IFDEF MSWINDOWS}
function NativeExecute(Flags: Integer): Boolean; override;
{$ENDIF}
constructor Create(AOwner: TComponent); override;
end;
{ TFindDialog }
TFindOption = (frDown, frFindNext, frHideMatchCase, frHideWholeWord,
frHideUpDown, frMatchCase, frDisableMatchCase, frDisableUpDown,
frDisableWholeWord, frReplace, frReplaceAll, frWholeWord, frShowHelp);
TFindOptions = set of TFindOption;
TFindDialogForm = class(TDialogForm)
private
FindEdit: TEdit;
FindLabel: TLabel;
WholeWord: TCheckBox;
MatchCase: TCheckBox;
Direction: TRadioGroup;
FindNext: TButton;
Cancel: TButton;
Help: TButton;
DialogUnits: TPoint;
protected
procedure ButtonPress(Sender: TObject); virtual;
procedure CheckboxCheck(Sender: TObject);
procedure DirectionClick(Sender: TObject);
procedure EditChanged(Sender: TObject); virtual;
procedure SetDialogOption(Option: TFindOption; Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
end;
TFindDialog = class(TCustomDialog)
private
FOptions: TFindOptions;
FOnFind: TNotifyEvent;
FFindText: WideString;
procedure SetFindText(const Value: WideString);
protected
function CreateForm: TDialogForm; override;
procedure DoShow; override;
procedure Find; dynamic;
public
constructor Create(AOwner: TComponent); override;
property Position;
published
property FindText: WideString read FFindText write SetFindText;
property Modal default False;
property Options: TFindOptions read FOptions write FOptions default [frDown];
property Title;
property OnClose;
property OnFind: TNotifyEvent read FOnFind write FOnFind;
property OnShow;
end;
TReplaceDialogForm = class(TFindDialogForm)
private
ReplaceBtn: TButton;
ReplaceAll: TButton;
ReplaceEdit: TEdit;
ReplaceLabel: TLabel;
protected
procedure EditChanged(Sender: TObject); override;
procedure ButtonPress(Sender: TObject); override;
public
constructor Create(AOwner: TComponent); override;
end;
{ TReplaceDialog }
TReplaceDialog = class(TFindDialog)
private
FReplaceText: WideString;
FOnReplace: TNotifyEvent;
procedure SetReplaceText(const Value: WideString);
protected
function CreateForm: TDialogForm; override;
procedure DoShow; override;
procedure Replace; dynamic;
public
constructor Create(AOwner: TComponent); override;
published
property ReplaceText: WideString read FReplaceText write SetReplaceText;
property OnReplace: TNotifyEvent read FOnReplace write FOnReplace;
end;
type
TPreviewThread = class(TThread)
private
FPercent: Byte;
FRedrawNow: Boolean;
FContinue: Boolean;
FCanvas: TCanvas;
FFilename: WideString;
FMessage: WideString;
FProgress: TProgressEvent;
FRect: TRect;
FStage: TProgressStage;
procedure DoProgress;
protected
procedure Draw; virtual; abstract;
procedure Execute; override;
public
constructor Create(const Filename: WideString; ProgressEvent: TProgressEvent;
Canvas: TCanvas; Rect: TRect); virtual;
procedure UpdateProgress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
const Msg: WideString; var Continue: Boolean);
property Canvas: TCanvas read FCanvas;
property Filename: WideString read FFilename;
property Rect: TRect read FRect;
end;
TPreviewThreadClass = class of TPreviewThread;
TThreadedPreviewer = class(TInterfacedObject, IFilePreviewer)
private
FThread: TPreviewThread;
FFilename: WideString;
protected
function ThreadClass: TPreviewThreadClass; virtual;
public
function CanPreview(const Filename: string): Boolean; virtual;
procedure GetPreviewSize(Filename: string; Canvas: TCanvas; var Size: TSize); virtual;
procedure Preview(const Filename: string; Canvas: TCanvas; const Rect: TRect;
Progress: TProgressEvent); virtual;
procedure StopPreview; virtual;
end;
TGraphicThread = class(TPreviewThread)
private
FImage: TBitmap;
procedure ImageProgress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
const Msg: WideString; var Continue: Boolean);
protected
procedure Draw; override;
procedure Execute; override;
public
constructor Create(const Filename: WideString; ProgressEvent: TProgressEvent;
Canvas: TCanvas; Rect: TRect); override;
destructor Destroy; override;
end;
TGraphicPreviewer = class(TThreadedPreviewer)
protected
function ThreadClass: TPreviewThreadClass; override;
public
function CanPreview(const Filename: string): Boolean; override;
end;
{ Message dialog }
type
TMsgDlgType = (mtCustom, mtInformation, mtWarning, mtError, mtConfirmation);
TMsgDlgBtn = (mbNone, mbOk, mbCancel, mbYes, mbNo, mbAbort, mbRetry, mbIgnore);
TMsgDlgButtons = set of TMsgDlgBtn;
const
mbYesNoCancel = [mbYes, mbNo, mbCancel];
mbYesNo = [mbYes, mbNo];
mbOKCancel = [mbOK, mbCancel];
mbAbortRetryIgnore = [mbAbort, mbRetry, mbIgnore];
function MessageDlg(const Msg: WideString; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; DefaultBtn: TMsgDlgBtn = mbNone;
Bitmap: TBitmap = nil): Integer; overload;
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint;
DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer; overload;
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint;
X, Y: Integer; DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer; overload;
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Button1, Button2, Button3: TMsgDlgBtn; HelpCtx: Longint;
X, Y: Integer; DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer; overload;
function MessageDlgPos(const Msg: WideString; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer;
DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer;
procedure ShowMessage(const Msg: WideString); overload;
procedure ShowMessage(const Msg: WideString; Params: array of const); overload;
procedure ShowMessageFmt(const Msg: WideString; Params: array of const);
procedure ShowMessagePos(const Msg: WideString; X, Y: Integer);
{ Input dialogs }
function InputBox(const ACaption, APrompt, ADefault: WideString): WideString; overload;
function InputBox(const ACaption, APrompt: WideString; ADefault: Integer;
Min: Integer = Low(Integer); Max: Integer = High(Integer);
Increment: Integer = 1): Integer; overload;
function InputBox(const ACaption, APrompt: WideString; ADefault: Double;
Min: Double = Low(Integer); Max: Double = High(Integer);
Decimals: Integer = 1): Double; overload;
function InputQuery(const ACaption, APrompt: WideString;
var Value: WideString): Boolean; overload;
function InputQuery(const ACaption, APrompt: WideString;
var Value: string): Boolean; overload;
function InputQuery(const ACaption, APrompt: WideString; var Value: Integer;
Min: Integer = Low(Integer); Max: Integer = High(Integer);
Increment: Integer = 1): Boolean; overload;
function InputQuery(const ACaption, APrompt: WideString; var Value: Double;
Min: Double = Low(Integer); Max: Double = High(Integer);
Decimals: Integer = 1): Boolean; overload;
function PromptForFileName(var AFileName: WideString; const AFilter: WideString = '';
const ADefaultExt: WideString = ''; const ATitle: WideString = '';
const AInitialDir: WideString = ''; SaveDialog: Boolean = False;
Options: TOpenOptions = []): Boolean;
{$IFDEF LINUX}
function SelectDirectory(const Caption, Root: WideString;
var Directory: WideString; ShowHidden: Boolean = False): Boolean;
{$ENDIF}
{$IFDEF MSWINDOWS}
function SelectDirectory(const Caption: string; const Root: WideString;
out Directory: WideString): Boolean;
{$ENDIF}
procedure RegisterFilePreviewer(const Previewer: IFilePreviewer);
procedure UnregisterFilePreviewer(const Previewer: IFilePreviewer);
implementation
uses QConsts, QFileDialog {$IFDEF LINUX}, DirSel {$ENDIF};
{$R *.res}
var
CustomColorCount: Integer;
GFilePreviewers: TInterfaceList = nil;
type
TOpenApplication = class(TApplication);
{$IFDEF LINUX}
function SelectDirectory(const Caption, Root: WideString;
var Directory: WideString; ShowHidden: Boolean = False): Boolean;
var
Dlg: TDirSelDlg;
SaveDir: string;
begin
Dlg := TDirSelDlg.Create(Application);
try
SaveDir := Directory;
Result := Dlg.GetDirectory(Caption, Root, Directory, ShowHidden);
finally
Dlg.Free;
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
type
PTaskWindow = ^TTaskWindow;
TTaskWindow = record
Next: PTaskWindow;
Window: HWnd;
end;
var
TaskActiveWindow: HWnd = 0;
TaskFirstWindow: HWnd = 0;
TaskFirstTopMost: HWnd = 0;
TaskWindowList: PTaskWindow = nil;
function DoDisableWindow(Window: HWnd; Data: Longint): Bool; stdcall;
var
P: PTaskWindow;
begin
if (Window <> TaskActiveWindow) and IsWindowVisible(Window) and
IsWindowEnabled(Window) then
begin
New(P);
P^.Next := TaskWindowList;
P^.Window := Window;
TaskWindowList := P;
EnableWindow(Window, False);
end;
Result := True;
end;
procedure EnableTaskWindows(WindowList: Pointer);
var
P: PTaskWindow;
begin
while WindowList <> nil do
begin
P := WindowList;
if IsWindow(P^.Window) then EnableWindow(P^.Window, True);
WindowList := P^.Next;
Dispose(P);
end;
end;
function DisableTaskWindows(ActiveWindow: HWnd): Pointer;
var
SaveActiveWindow: HWND;
SaveWindowList: Pointer;
begin
Result := nil;
SaveActiveWindow := TaskActiveWindow;
SaveWindowList := TaskWindowList;
TaskActiveWindow := ActiveWindow;
TaskWindowList := nil;
try
try
EnumThreadWindows(GetCurrentThreadID, @DoDisableWindow, 0);
Result := TaskWindowList;
except
EnableTaskWindows(TaskWindowList);
raise;
end;
finally
TaskWindowList := SaveWindowList;
TaskActiveWindow := SaveActiveWindow;
end;
end;
var
CreationControl: TQtDialog = nil;
WndProcPtrAtom: TAtom = 0;
InstancePtrAtom: TAtom = 0;
function TaskModalDialog(DialogFunc: Pointer; var DialogData): Bool;
type
TDialogFunc = function(var DialogData): Bool stdcall;
var
ActiveWindow: HWnd;
WindowList: Pointer;
FPUControlWord: Word;
AtomText: array[0..31] of Char;
begin
ActiveWindow := GetActiveWindow;
WindowList := DisableTaskWindows(0);
WndProcPtrAtom := GlobalAddAtom(StrFmt(AtomText,
'WndProcPtr%.8X%.8X', [HInstance, GetCurrentThreadID]));
InstancePtrAtom := GlobalAddAtom(StrFmt(AtomText,
'DlgInstancePtr%.8X%.8X', [HInstance, GetCurrentThreadID]));
try
asm
// Avoid FPU control word change in NETRAP.dll, NETAPI32.dll, etc
FNSTCW FPUControlWord
end;
try
Result := TDialogFunc(DialogFunc)(DialogData);
finally
asm
FNCLEX
FLDCW FPUControlWord
end;
end;
finally
if WndProcPtrAtom <> 0 then GlobalDeleteAtom(WndProcPtrAtom);
if InstancePtrAtom <> 0 then GlobalDeleteAtom(WndProcPtrAtom);
EnableTaskWindows(WindowList);
SetActiveWindow(ActiveWindow);
end;
end;
{ Open and Save dialog routines for Windows native dialog }
procedure GetFileNames(OpenDialog: TOpenDialog; var OpenFileName: TOpenFileName);
var
Separator: Char;
function ExtractFileName(P: PChar; var S: TFilename): PChar;
begin
Result := AnsiStrScan(P, Separator);
if Result = nil then
begin
S := P;
Result := StrEnd(P);
end
else
begin
SetString(S, P, Result - P);
Inc(Result);
end;
end;
procedure ExtractFileNames(P: PChar);
var
DirName, FileName: TFilename;
begin
P := ExtractFileName(P, DirName);
P := ExtractFileName(P, FileName);
if FileName = '' then
OpenDialog.FFiles.Add(DirName)
else
begin
if AnsiLastChar(DirName)^ <> '\' then
DirName := DirName + '\';
repeat
if (FileName[1] <> '\') and ((Length(FileName) <= 3) or
(FileName[2] <> ':') or (FileName[3] <> '\')) then
FileName := DirName + FileName;
OpenDialog.FFiles.Add(FileName);
P := ExtractFileName(P, FileName);
until FileName = '';
end;
end;
var
FName: TFileName;
begin
Separator := #0;
with OpenFileName do
begin
if ofAllowMultiSelect in OpenDialog.FOptions then
begin
ExtractFileNames(lpstrFile);
OpenDialog.FFileName := OpenDialog.FFiles[0];
end else
begin
FName := OpenDialog.FFileName;
ExtractFileName(lpstrFile, FName);
OpenDialog.FFiles.Add(FName);
end;
end;
end;
function OpenWndProc(Wnd: HWND; Msg, WParam, LParam: Longint): Longint; stdcall;
function StrRetToString(PIDL: PItemIDList; StrRet: TStrRet): string;
var
P: PChar;
begin
case StrRet.uType of
STRRET_CSTR:
SetString(Result, StrRet.cStr, lStrLen(StrRet.cStr));
STRRET_OFFSET:
begin
P := @PIDL.mkid.abID[StrRet.uOffset - SizeOf(PIDL.mkid.cb)];
SetString(Result, P, PIDL.mkid.cb - StrRet.uOffset);
end;
STRRET_WSTR:
Result := StrRet.pOleStr;
end;
end;
function CallDefWndProc: Longint;
begin
Result := CallWindowProc(Pointer(GetProp(Wnd,
MakeIntAtom(WndProcPtrAtom))), Wnd, Msg, WParam, LParam);
end;
var
Instance: TOpenDialog;
CanClose: Boolean;
Include: Boolean;
StrRet: TStrRet;
Path: array[0..MAX_PATH] of Char;
SR: TSearchRec;
FileInfo: PFileInfo;
begin
Result := 0;
{ If not ofOldStyleDialog then DoShow on CDN_INITDONE, not WM_INITDIALOG }
if (Msg = WM_INITDIALOG) {and not (ofOldStyleDialog in Options) }then Exit;
Instance := TOpenDialog(GetProp(Wnd, MakeIntAtom(InstancePtrAtom)));
case Msg of
WM_NOTIFY:
case (POFNotify(LParam)^.hdr.code) of
CDN_FILEOK:
begin
CanClose := True;
GetFileNames(Instance, POFNotify(LParam)^.lpOFN^);
Instance.CanClose(CanClose);
Instance.FFiles.Clear;
if not CanClose then
begin
Result := 1;
SetWindowLong(Wnd, DWL_MSGRESULT, Result);//Wnd??
Exit;
end;
end;
CDN_INITDONE:
Instance.DoShow;
CDN_SELCHANGE:
begin
SendMessage(GetParent(Longint(Instance.FHandle)), CDM_GETFILEPATH,
SizeOf(Path), Integer(@Path));
if FindFirst(Path, faAnyFile, SR) = 0 then
begin
New(FileInfo);
try
FileInfo.SR := SR;
Instance.FileSelected(FileInfo, True);
finally
Dispose(FileInfo);
end;
FindClose(SR);
end;
end;
CDN_FOLDERCHANGE:
begin
SendMessage(GetParent(Longint(Instance.FHandle)), CDM_GETFOLDERPATH,
SizeOf(Path), Integer(@Path));
Instance.DirChanged(Path);
end;
CDN_INCLUDEITEM:
if (LParam <> 0) and Assigned(Instance.OnFileAdd) then
begin
POFNotifyEx(LParam)^.psf.GetDisplayNameOf(POFNotifyEx(LParam)^.pidl, SHGDN_FORPARSING, StrRet);
Include := Instance.FileAdd(StrRetToString(POFNotifyEx(LParam)^.pidl, StrRet), True, True, True);
Result := Byte(Include);
Exit;
end;
end;
WM_NCDESTROY:
begin
Result := CallDefWndProc;
Instance.FHandle := 0;
RemoveProp(Wnd, MakeIntAtom(InstancePtrAtom));
RemoveProp(Wnd, MakeIntAtom(WndProcPtrAtom));
Exit;
end;
end;
Result := CallDefWndProc;
end;
function OpenDialogHook(Wnd: HWnd; Msg: UINT; WParam: WPARAM; LParam: LPARAM): UINT; stdcall;
begin
Result := 0;
if Msg = WM_INITDIALOG then
begin
SetProp(Wnd, MakeIntAtom(InstancePtrAtom), Longint(POpenFileName(LParam)^.lCustData));
SetProp(Wnd, MakeIntAtom(WndProcPtrAtom), GetWindowLong(Wnd, GWL_WNDPROC));
TOpenDialog(POpenFileName(LParam)^.lCustData).FHandle := Wnd;
SetWindowLong(Wnd, GWL_WNDPROC, Longint(@OpenWndProc));
Result := 1;
end;
end;
function WinFileDialogExecute(Dialog: TOpenDialog; DlgFunc: Pointer; ODFlags: DWORD = 0): Boolean;
const
MultiSelectBufferSize = High(Word) - 16;
OpenOptions: array [TOpenOption] of DWORD = (
OFN_FORCESHOWHIDDEN, OFN_OVERWRITEPROMPT, OFN_NOCHANGEDIR,
OFN_ALLOWMULTISELECT, OFN_EXTENSIONDIFFERENT, OFN_PATHMUSTEXIST,
OFN_FILEMUSTEXIST, OFN_ENABLESIZING, OFN_SHOWHELP, OFN_HIDEREADONLY,
0, 0, 0, 0, 0, 0);
function AllocFilterStr(const S: string): string;
var
P: PChar;
begin
Result := '';
if S <> '' then
begin
Result := S + #0; // double null terminators
P := AnsiStrScan(PChar(Result), '|');
while P <> nil do
begin
P^ := #0;
Inc(P);
P := AnsiStrScan(P, '|');
end;
end;
end;
var
Option: TOpenOption;
OpenFilename: TOpenFilename;
TempFilename, TempExt: string;
TempFilter: string;
ATitle: string;
FileNameAsStr: string;
begin
Dialog.FFiles.Clear;
FillChar(OpenFileName, SizeOf(OpenFileName), 0);
with OpenFilename do
begin
if (Win32MajorVersion >= 5) and (Win32Platform = VER_PLATFORM_WIN32_NT) or { Win2k }
((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and (Win32MajorVersion >= 4) and (Win32MinorVersion >= 90)) then { WinME }
lStructSize := SizeOf(TOpenFilename)
else
lStructSize := SizeOf(TOpenFilename) - (SizeOf(DWORD) shl 1) - SizeOf(Pointer); { subtract size of added fields }
hInstance := SysInit.HInstance;
TempFilter := AllocFilterStr(Dialog.Filter);
lpstrFilter := PChar(TempFilter);
nFilterIndex := Dialog.FilterIndex;
if ofAllowMultiSelect in Dialog.Options then
nMaxFile := MultiSelectBufferSize else
nMaxFile := MAX_PATH;
SetLength(TempFilename, nMaxFile + 2);
lpstrFile := PChar(TempFilename);
FillChar(lpstrFile^, nMaxFile + 2, 0);
FileNameAsStr := Dialog.Filename; { Convert the WideString to an AnsiString }
StrLCopy(lpstrFile, PChar(FileNameAsStr), nMaxFile);
if (Dialog.InitialDir = '') then
lpstrInitialDir := '.'
else
lpstrInitialDir := PChar(Dialog.InitialDir);
ATitle := Dialog.Title;
lpstrTitle := PChar(ATitle);
if ODFlags = 0 then
begin
Flags := OFN_NOREADONLYRETURN;
for Option := Low(Option) to High(Option) do
if Option in Dialog.Options then
Flags := Flags or OpenOptions[Option];
end
else
Flags := ODFlags;
Flags := Flags or OFN_ENABLEHOOK or OFN_ENABLEINCLUDENOTIFY or OFN_EXPLORER;
TempExt := Dialog.DefaultExt;
if (TempExt = '') and (Flags and OFN_EXPLORER = 0) then
begin
TempExt := ExtractFileExt(Dialog.Filename);
Delete(TempExt, 1, 1);
end;
if TempExt <> '' then lpstrDefExt := PChar(TempExt);
lCustData := Integer(Dialog);
lpfnHook := OpenDialogHook;
hWndOwner := GetActiveWindow;
Result := TaskModalDialog(DlgFunc, OpenFileName);
if Result then
begin
GetFileNames(Dialog, OpenFilename);
if (Flags and OFN_EXTENSIONDIFFERENT) <> 0 then
Include(Dialog.FOptions, ofExtensionDifferent) else
Exclude(Dialog.FOptions, ofExtensionDifferent);
Dialog.FFilterIndex := nFilterIndex;
end;
end;
end;
{ Font dialog routine for Windows native dialog }
function WinFontDialogExecute(FontDialog: TFontDialog; FDFlags: DWORD = 0): Boolean;
var
FontCharSetModified: Boolean;
procedure UpdateFromLogFont(const LogFont: TLogFont);
var
Style: TFontStyles;
begin
with LogFont do
begin
FontDialog.Font.Name := LogFont.lfFaceName;
FontDialog.Font.Height := LogFont.lfHeight;
if FontCharsetModified then
FontDialog.Font.Charset := TFontCharset(LogFont.lfCharSet);
Style := [];
with LogFont do
begin
if lfWeight > FW_REGULAR then Include(Style, fsBold);
if lfItalic <> 0 then Include(Style, fsItalic);
if lfUnderline <> 0 then Include(Style, fsUnderline);
if lfStrikeOut <> 0 then Include(Style, fsStrikeOut);
end;
FontDialog.Font.Style := Style;
end;
end;
var
ChooseFontRec: TChooseFont;
LogFont: TLogFont;
OriginalFaceName: string;
begin
with ChooseFontRec do
begin
lStructSize := SizeOf(ChooseFontRec);
hDC := 0;
lpLogFont := @LogFont;
GetObject(QFont_handle(FontDialog.Font.Handle), SizeOf(LogFont), @LogFont);
OriginalFaceName := LogFont.lfFaceName;
if FDFlags = 0 then
Flags := CF_BOTH or CF_EFFECTS
else
Flags := FDFlags;
Flags := Flags or CF_INITTOLOGFONTSTRUCT;
rgbColors := FontDialog.Font.Color;
lCustData := 0;
lpfnHook := nil;
hWndOwner := GetActiveWindow;
Result := TaskModalDialog(@ChooseFont, ChooseFontRec);
if Result then
begin
if AnsiCompareText(OriginalFaceName, LogFont.lfFaceName) <> 0 then
FontCharsetModified := True;
UpdateFromLogFont(LogFont);
FontDialog.Font.Color := rgbColors;
end;
end;
end;
function WinColorDialogExecute(ColorDialog: TColorDialog; CDFlags: DWORD = 0): Boolean;
var
ChooseColorRec: TChooseColor;
CustomColorsArray: TCustomColors;
const
ColorPrefix = 'Color';
procedure GetCustomColorsArray;
var
I: Integer;
begin
for I := 0 to MaxCustomColors - 1 do
ColorDialog.CustomColors.Values[ColorPrefix + Char(Ord('A') + I)] :=
Format('%.6x', [CustomColorsArray[I]]);
end;
procedure SetCustomColorsArray;
var
Value: string;
I: Integer;
begin
for I := 0 to MaxCustomColors - 1 do
begin
Value := ColorDialog.CustomColors.Values[ColorPrefix + Char(Ord('A') + I)];
if Value <> '' then
CustomColorsArray[I] := StrToInt('$' + Value) else
CustomColorsArray[I] := -1;
end;
end;
begin
FillChar(ChooseColorRec, SizeOf(ChooseColorRec), 0);
with ChooseColorRec do
begin
SetCustomColorsArray;
lStructSize := SizeOf(ChooseColorRec);
hInstance := SysInit.HInstance;
rgbResult := ColorToRGB(ColorDialog.Color);
lpCustColors := @CustomColorsArray;
if CDFlags = 0 then
Flags := CC_FULLOPEN or CC_ANYCOLOR
else
Flags := CDFlags;
Flags := Flags or CC_RGBINIT;
hWndOwner := GetActiveWindow;
Result := TaskModalDialog(@ChooseColor, ChooseColorRec);
if Result then
begin
ColorDialog.Color := rgbResult;
GetCustomColorsArray;
end;
end;
end;
function SelectDirectory(const Caption: string; const Root: WideString;
out Directory: WideString): Boolean;
var
WindowList: Pointer;
BrowseInfo: TBrowseInfo;
Buffer: PChar;
RootItemIDList, ItemIDList: PItemIDList;
ShellMalloc: IMalloc;
IDesktopFolder: IShellFolder;
Eaten, Flags: LongWord;
ActiveWindow: HWND;
begin
Result := False;
Directory := '';
FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then
begin
Buffer := ShellMalloc.Alloc(MAX_PATH);
try
RootItemIDList := nil;
if Root <> '' then
begin
SHGetDesktopFolder(IDesktopFolder);
IDesktopFolder.ParseDisplayName(0, nil,
POleStr(Root), Eaten, RootItemIDList, Flags);
end;
with BrowseInfo do
begin
hwndOwner := 0;
pidlRoot := RootItemIDList;
pszDisplayName := Buffer;
lpszTitle := PChar(Caption);
ulFlags := BIF_RETURNONLYFSDIRS;
end;
ActiveWindow := GetActiveWindow;
WindowList := DisableTaskWindows(0);
try
ItemIDList := ShBrowseForFolder(BrowseInfo);
finally
EnableTaskWindows(WindowList);
SetActiveWindow(ActiveWindow);
end;
Result := ItemIDList <> nil;
if Result then
begin
ShGetPathFromIDList(ItemIDList, Buffer);
ShellMalloc.Free(ItemIDList);
Directory := Buffer;
end;
finally
ShellMalloc.Free(Buffer);
end;
end;
end;
{$ENDIF}
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Button1, Button2, Button3: TMsgDlgBtn; HelpCtx: Longint;
X, Y: Integer; DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer; overload;
const
ConfirmResName = 'MSGDLG_CONFIRM';
MessageBox_DefaultMask = $100;
MessageBox_EscapeMask = $200;
var
MB: QMessageBoxH;
I: Integer;
Btns: array[0..2] of Integer;
CaptureControl: TControl;
Title: WideString;
FreeBitmap: Boolean;
DlgParent: QWidgetH;
DlgLabel: QLabelH;
{$IFDEF LINUX}
SigQuitStatus,
SigIntStatus: TSignalState;
{$ENDIF}
begin
Result := -1;
if Application.Terminated then
Exit;
FreeBitmap := (Bitmap = nil) and (DlgType = mtConfirmation);
case DlgType of
mtCustom: Title := Caption;
mtInformation: Title := SMsgDlgInformation;
mtError: Title := SMsgDlgError;
mtWarning: Title := SMsgDlgWarning;
mtConfirmation:
begin
Title := SMsgDlgConfirm;
if Bitmap = nil then
begin
Bitmap := TBitmap.Create;
Bitmap.LoadFromResourceName(hInstance, ConfirmResName);
end;
end;
end;
if DefaultBtn = mbNone then DefaultBtn := Button1;
I := 0;
FillChar(Btns, SizeOf(Btns), Ord(mbNone));
if Button1 <> mbNone then
begin
Btns[I] := Ord(Button1);
if DefaultBtn = Button1 then
Btns[I] := Btns[I] or MessageBox_DefaultMask;
Inc(I);
end;
if Button2 <> mbNone then
begin
Btns[I] := Ord(Button2);
if DefaultBtn = Button2 then
Btns[I] := Btns[I] or MessageBox_DefaultMask;
Inc(I);
end;
if Button3 <> mbNone then
begin
Btns[I] := Ord(Button3);
if DefaultBtn = Button3 then
Btns[I] := Btns[I] or MessageBox_DefaultMask;
end;
if DlgType = mtConfirmation then
begin
DlgType := mtCustom;
Bitmap.Transparent := True;
end;
DlgParent := QApplication_activeWindow(Application.Handle);
if DlgParent = nil then
if (Screen.ActiveCustomForm <> nil) and Screen.ActiveCustomForm.HandleAllocated then
DlgParent := Screen.ActiveCustomForm.Handle
else
DlgParent := TOpenApplication(Application).AppWidget;
MB := QMessageBox_create(PWideString(@Title), PWideString(@Msg),
QMessageBoxIcon(DlgType), Btns[0], Btns[1], Btns[2], DlgParent, nil, True, WFlags(WidgetFlags_WStyle_StaysOnTop));
try
if Bitmap <> nil then
QMessageBox_setIconPixmap(MB, Bitmap.Handle);
if (X >= 0) and (Y >= 0) then QDialog_move(MB, X, Y);
//force wordbreak alignment of dialog label.
DlgLabel := QLabelH(QObject_child(MB, 'text', nil)); //do not localize
if DlgLabel <> nil then
QLabel_setAlignment(DlgLabel, QLabel_alignment(DlgLabel)
or Integer(AlignmentFlags_WordBreak));
CaptureControl := GetCaptureControl;
try
SetCaptureControl(nil);
QForms.Application.ModalStarted(nil);
try
{$IFDEF LINUX}
SigIntStatus := InquireSignal(RTL_SIGINT);
SigQuitStatus := InquireSignal(RTL_SIGQUIT);
if SigIntStatus = ssHooked then
UnhookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
UnhookSignal(RTL_SIGQUIT);
try
{$ENDIF}
try
Result := QDialog_exec(MB);
except
Application.HandleException(DlgParent);
end;
{$IFDEF LINUX}
finally
if SigIntStatus = ssHooked then
HookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
HookSignal(RTL_SIGQUIT);
end;
{$ENDIF}
finally
QForms.Application.ModalFinished(nil);
end;
finally
SetCaptureControl(CaptureControl);
QWidget_setActiveWindow(DlgParent);
end;
finally
QMessageBox_destroy(MB);
if FreeBitmap then Bitmap.Free;
end;
end;
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint;
X, Y: Integer; DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer; overload;
var
Btns: array[0..2] of TMsgDlgBtn;
B: TMsgDlgBtn;
I: Integer;
begin
{ Button order is hard-coded in Windows. We follow their conventions here. }
if Buttons = mbYesNoCancel then
begin
Btns[0] := mbYes;
Btns[1] := mbNo;
Btns[2] := mbCancel;
end
else
if Buttons = mbYesNo then
begin
Btns[0] := mbYes;
Btns[1] := mbNo;
Btns[2] := mbNone;
end
else
if Buttons = mbOkCancel then
begin
Btns[0] := mbOk;
Btns[1] := mbCancel;
Btns[2] := mbNone;
end
else
if Buttons = mbAbortRetryIgnore then
begin
Btns[0] := mbAbort;
Btns[1] := mbRetry;
Btns[2] := mbIgnore;
end
else
begin
I := 0;
FillChar(Btns, SizeOf(Btns), Ord(mbNone));
for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
if (B in Buttons) and (B <> mbNone) then
begin
if I > High(Btns) then
raise EInvalidOperation.CreateRes(@STooManyMessageBoxButtons);
Btns[I] := B;
Inc(I);
end;
end;
Result := MessageDlg(Caption, Msg, DlgType, Btns[0], Btns[1], Btns[2],
HelpCtx, X, Y, DefaultBtn, Bitmap);
end;
function MessageDlg(const Msg: WideString; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; DefaultBtn: TMsgDlgBtn = mbNone;
Bitmap: TBitmap = nil): Integer;
begin
Result := MessageDlg(Application.Title, Msg, DlgType, Buttons, HelpCtx, -1,
-1, DefaultBtn, Bitmap);
end;
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint;
DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer;
begin
Result := MessageDlg(Caption, Msg, DlgType, Buttons, HelpCtx, -1, -1,
DefaultBtn, Bitmap);
end;
function MessageDlgPos(const Msg: WideString; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer;
DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer;
begin
Result := MessageDlg(Application.Title, Msg, DlgType, Buttons, HelpCtx,
X, Y, DefaultBtn, Bitmap);
end;
procedure ShowMessage(const Msg: WideString);
begin
MessageDlg(Msg, mtCustom, [mbOk], 0);
end;
procedure ShowMessage(const Msg: WideString; Params: array of const);
begin
ShowMessageFmt(Msg, Params);
end;
procedure ShowMessageFmt(const Msg: WideString; Params: array of const);
begin
ShowMessage(Format(Msg, Params));
end;
procedure ShowMessagePos(const Msg: WideString; X, Y: Integer);
begin
MessageDlg(Application.Title, Msg, mtCustom, [mbOk], 0, X, Y);
end;
function InputQuery(const ACaption, APrompt: WideString;
var Value: WideString): Boolean;
var
RetVal: WideString;
CaptureControl: TControl;
{$IFDEF LINUX}
SigIntStatus,
SigQuitStatus: TSignalState;
{$ENDIF}
begin
CaptureControl := GetCaptureControl;
try
SetCaptureControl(nil);
QForms.Application.ModalStarted(nil);
try
{$IFDEF LINUX}
SigIntStatus := InquireSignal(RTL_SIGINT);
SigQuitStatus := InquireSignal(RTL_SIGQUIT);
if SigIntStatus = ssHooked then
UnhookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
UnhookSignal(RTL_SIGQUIT);
try
{$ENDIF}
QInputDialog_getText(PWideString(@RetVal), PWideString(@ACaption),
PWideString(@APrompt), PWideString(@Value), @Result, nil, nil);
{$IFDEF LINUX}
finally
if SigIntStatus = ssHooked then
HookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
HookSignal(RTL_SIGQUIT);
end;
{$ENDIF}
if Result then Value := RetVal;
finally
QForms.Application.ModalFinished(nil);
end;
finally
SetCaptureControl(CaptureControl);
end;
end;
function InputQuery(const ACaption, APrompt: WideString;
var Value: string): Boolean;
var
WValue: WideString;
begin
WValue := Value;
Result := InputQuery(ACaption, APrompt, WValue);
if Result then Value := WValue;
end;
function InputQuery(const ACaption, APrompt: WideString; var Value: Integer;
Min: Integer = Low(Integer); Max: Integer = High(Integer);
Increment: Integer = 1): Boolean;
var
RetVal: Integer;
CaptureControl: TControl;
{$IFDEF LINUX}
SigIntStatus,
SigQuitStatus: TSignalState;
{$ENDIF}
begin
CaptureControl := GetCaptureControl;
try
SetCaptureControl(nil);
QForms.Application.ModalStarted(nil);
try
{$IFDEF LINUX}
SigIntStatus := InquireSignal(RTL_SIGINT);
SigQuitStatus := InquireSignal(RTL_SIGQUIT);
if SigIntStatus = ssHooked then
UnhookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
UnhookSignal(RTL_SIGQUIT);
try
{$ENDIF}
RetVal := QInputDialog_getInteger(PWideString(@ACaption),
PWideString(@APrompt), Value, Min, Max, Increment, @Result, nil, nil);
{$IFDEF LINUX}
finally
if SigIntStatus = ssHooked then
HookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
HookSignal(RTL_SIGQUIT);
end;
{$ENDIF}
if Result then Value := RetVal;
finally
QForms.Application.ModalFinished(nil);
end;
finally
SetCaptureControl(CaptureControl);
end;
end;
function InputQuery(const ACaption, APrompt: WideString; var Value: Double;
Min: Double = Low(Integer); Max: Double = High(Integer);
Decimals: Integer = 1): Boolean;
var
RetVal: Double;
CaptureControl: TControl;
{$IFDEF LINUX}
SigIntStatus,
SigQuitStatus: TSignalState;
{$ENDIF}
begin
CaptureControl := GetCaptureControl;
try
SetCaptureControl(nil);
QForms.Application.ModalStarted(nil);
try
{$IFDEF LINUX}
SigIntStatus := InquireSignal(RTL_SIGINT);
SigQuitStatus := InquireSignal(RTL_SIGQUIT);
if SigIntStatus = ssHooked then
UnhookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
UnhookSignal(RTL_SIGQUIT);
try
{$ENDIF}
RetVal := QInputDialog_getDouble(PWideString(@ACaption), PWideString(@APrompt),
Value, Min, Max, Decimals, @Result, nil, nil);
{$IFDEF LINUX}
finally
if SigIntStatus = ssHooked then
HookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
HookSignal(RTL_SIGQUIT);
end;
{$ENDIF}
if Result then Value := RetVal;
finally
QForms.Application.ModalFinished(nil);
end;
finally
SetCaptureControl(CaptureControl);
end;
end;
function InputBox(const ACaption, APrompt, ADefault: WideString): WideString;
begin
Result := ADefault;
InputQuery(ACaption, APrompt, Result);
end;
function InputBox(const ACaption, APrompt: WideString; ADefault: Integer;
Min: Integer = Low(Integer); Max: Integer = High(Integer);
Increment: Integer = 1): Integer;
begin
Result := ADefault;
InputQuery(ACaption, APrompt, Result, Min, Max, Increment);
end;
function InputBox(const ACaption, APrompt: WideString; ADefault: Double;
Min: Double = Low(Integer); Max: Double = High(Integer);
Decimals: Integer = 1): Double;
begin
Result := ADefault;
InputQuery(ACaption, APrompt, Result, Min, Max, Decimals);
end;
function PromptForFileName(var AFileName: WideString; const AFilter: WideString = '';
const ADefaultExt: WideString = ''; const ATitle: WideString = '';
const AInitialDir: WideString = ''; SaveDialog: Boolean = False;
Options: TOpenOptions = []): Boolean;
var
Dialog: TOpenDialog;
begin
if SaveDialog then
Dialog := TSaveDialog.Create(nil)
else
Dialog := TOpenDialog.Create(nil);
if Options <> [] then
Dialog.Options := Options
else
if SaveDialog then
Dialog.Options := Dialog.Options + [ofOverwritePrompt];
with Dialog do
try
Title := ATitle;
DefaultExt := ADefaultExt;
if AFilter = '' then
Filter := SDefaultFilter else
Filter := AFilter;
InitialDir := AInitialDir;
FileName := AFileName;
Result := Execute;
if Result then
AFileName := FileName;
finally
Free;
end;
end;
{ TPreviewThread }
constructor TPreviewThread.Create(const Filename: WideString;
ProgressEvent: TProgressEvent; Canvas: TCanvas; Rect: TRect);
begin
FCanvas := Canvas;
FProgress := ProgressEvent;
FFilename := Filename;
FRect := Rect;
inherited Create(False);
end;
procedure TPreviewThread.DoProgress;
begin
if Terminated then Exit;
if FRedrawNow then
Draw;
FProgress(Self, FStage, FPercent, FRedrawNow, FRect, FMessage, FContinue);
end;
procedure TPreviewThread.Execute;
begin
// override
end;
procedure TPreviewThread.UpdateProgress(Sender: TObject;
Stage: TProgressStage; PercentDone: Byte; RedrawNow: Boolean;
const R: TRect; const Msg: WideString; var Continue: Boolean);
begin
FPercent := PercentDone;
FStage := Stage;
FRedrawNow := RedrawNow;
FMessage := Msg;
FContinue := Continue;
if not Terminated then
Synchronize(DoProgress);
end;
{ TGraphicThread }
constructor TGraphicThread.Create(const Filename: WideString;
ProgressEvent: TProgressEvent; Canvas: TCanvas; Rect: TRect);
begin
FImage := TBitmap.Create;
inherited Create(Filename, ProgressEvent, Canvas, Rect);
FImage.OnProgress := ImageProgress;
end;
destructor TGraphicThread.Destroy;
begin
inherited Destroy;
if Assigned(FImage) then
FImage.Free;
end;
procedure TGraphicThread.Draw;
var
H, W: Integer;
HScale, WScale, Scale: Single;
R: TRect;
begin
WScale := (FRect.Right - FRect.Left) / FImage.Width;
HScale := (FRect.Bottom - FRect.Top) / FImage.Height;
if (HScale < 1) or (WScale < 1) then
begin
if HScale < WScale then
Scale := HScale
else
Scale := WScale;
end else
Scale := 1;
H := Round(FImage.Height * Scale);
W := Round(FImage.Width * Scale);
R.Top := (FRect.Bottom - FRect.Top - H) div 2;
R.Left := (FRect.Right - FRect.Left - W) div 2;
R.Bottom := R.Top + H;
R.Right := R.Left + W;
Canvas.StretchDraw(R, FImage);
end;
procedure TGraphicThread.Execute;
var
Icon: TIcon;
begin
try
if AnsiLowerCase(ExtractFileExt(Filename)) = '.ico' then
begin
Icon := TIcon.Create;
try
Icon.LoadFromFile(Filename);
FImage.Assign(Icon);
finally
Icon.Free;
end;
end else
FImage.LoadFromFile(Filename);
FRedrawNow := True;
FPercent := 100;
FStage := psEnding;
if not Terminated then
Synchronize(DoProgress);
except
on EInvalidGraphicOperation do
//squelch
end;
end;
procedure TGraphicThread.ImageProgress(Sender: TObject;
Stage: TProgressStage; PercentDone: Byte; RedrawNow: Boolean;
const R: TRect; const Msg: WideString; var Continue: Boolean);
var
AMessage: WideString;
begin
if Stage = psRunning then
AMessage := SLoadingEllipsis;
UpdateProgress(Self, Stage, PercentDone, Stage = psEnding, R,
AMessage, Continue);
Continue := Continue and not Terminated;
end;
{ TThreadedPreviewer }
function TThreadedPreviewer.CanPreview(const Filename: string): Boolean;
begin
Result := False;
end;
procedure TThreadedPreviewer.GetPreviewSize(Filename: string; Canvas: TCanvas;
var Size: TSize);
begin
// accept default.
end;
procedure TThreadedPreviewer.Preview(const Filename: string; Canvas: TCanvas;
const Rect: TRect; Progress: TProgressEvent);
begin
if FFilename <> Filename then
begin
FFilename := Filename;
FThread := ThreadClass.Create(Filename, Progress, Canvas, Rect);
end;
end;
procedure TThreadedPreviewer.StopPreview;
begin
if Assigned(FThread) then
FreeAndNil(FThread);
FFilename := '';
end;
function TThreadedPreviewer.ThreadClass: TPreviewThreadClass;
begin
Result := TPreviewThread;
end;
{ TGraphicPreviewer }
function TGraphicPreviewer.CanPreview(const Filename: string): Boolean;
var
Formats: TFileFormatsList;
Ext: string;
begin
Formats := GetFileFormats;
Ext := ExtractFileExt(Filename);
if (Length(Ext) > 0) and (Ext[1] = '.') then
Delete(Ext, 1, 1);
Result := Formats.FindExt(Ext) <> nil;
end;
function TGraphicPreviewer.ThreadClass: TPreviewThreadClass;
begin
Result := TGraphicThread;
end;
function FilePreviewers: TInterfaceList;
begin
if not Assigned(GFilePreviewers) then
GFilePreviewers := TInterfaceList.Create;
Result := GFilePreviewers;
end;
procedure RegisterFilePreviewer(const Previewer: IFilePreviewer);
begin
FilePreviewers.Insert(0, Previewer);
end;
procedure UnregisterFilePreviewer(const Previewer: IFilePreviewer);
var
Index: Integer;
begin
Index := FilePreviewers.IndexOf(Previewer);
if (Index >= 0) and (Index < FilePreviewers.Count) then
FilePreviewers.Delete(Index);
end;
{ TDialog }
constructor TDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FModal := True;
end;
procedure TDialog.DoClose;
begin
FWidth := Width;
FHeight := Height;
if Assigned(FOnClose) then FOnClose(Self);
end;
procedure TDialog.DoShow;
begin
if Assigned(FOnShow) then FOnShow(Self);
end;
function TDialog.Execute: Boolean;
var
ALeft, ATop, AWidth, AHeight: Integer;
GrabControl: TControl;
begin
GrabControl := GetMouseGrabControl;
try
SetMouseGrabControl(nil);
{ accept defaults if necessary. }
if not (sfLeft in FScaleFlags) then ALeft := GetPosition.X else ALeft := FPosition.X;
if not (sfTop in FScaleFlags) then ATop := GetPosition.Y else ATop := FPosition.Y;
if not (sfWidth in FScaleFlags) then AWidth := GetWidth else AWidth := FWidth;
if not (sfHeight in FScaleFlags) then AHeight := GetHeight else AHeight := FHeight;
SetBounds(ALeft, ATop, AWidth, AHeight);
Result := DoExecute;
finally
SetMouseGrabControl(GrabControl);
end;
end;
function TDialog.GetHeight: Integer;
begin
Result := GetBounds.Bottom;
end;
function TDialog.GetPosition: TPoint;
begin
Result.X := GetBounds.Left;
Result.Y := GetBounds.Top;
end;
function TDialog.GetWidth: Integer;
begin
Result := GetBounds.Right;
end;
procedure TDialog.SetHeight(const Value: Integer);
begin
if GetWidth = Value then Exit;
SetBounds(Position.X, Position.Y, Width, Value);
Include(FScaleFlags, sfHeight);
end;
procedure TDialog.SetPosition(const Value: TPoint);
begin
SetBounds(Value.X, Value.Y, Width, Height);
Include(FScaleFlags, sfLeft);
Include(FScaleFlags, sfTop);
end;
procedure TDialog.SetTitle(const Value: WideString);
begin
FTitle := Value;
end;
procedure TDialog.SetWidth(const Value: Integer);
begin
if GetWidth = Value then Exit;
SetBounds(Position.X, Position.Y, Value, Height);
Include(FScaleFlags, sfWidth);
end;
{ TQtDialog }
function TQtDialog.AppEventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
Result := False;
try
Result := (QEvent_type(Event) = QEventType_KeyPress)
and (QKeyEvent_key(QKeyEventH(Event)) = Application.HelpKey) and
(QWidget_topLevelWidget(QWidgetH(Sender)) = Handle);
if Result then InvokeHelp;
except
Application.HandleException(Self);
end;
end;
constructor TQtDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FModal := True;
FShowing := False;
{$IFDEF MSWINDOWS}
FUseNative := True;
{$ENDIF}
end;
procedure TQtDialog.CreateHandle;
begin
{$IFDEF MSWINDOWS}
if UseNativeDialog then Exit;
{$ENDIF}
if FHandle = nil then
begin
CreateWidget;
InitWidget;
HookEvents;
if (FHandle = nil) then
raise EQtDialogException.CreateResFmt(@SInvalidCreateWidget, [ClassName]);
QClxObjectMap_add(QWidgetH(FHandle), Integer(Self));
end;
end;
procedure TQtDialog.CreateWidget;
begin
FHandle := QDialog_create(nil, nil, FModal, WidgetFlags);
FHooks := QWidget_hook_create(FHandle);
end;
procedure TQtDialog.DestroyedHook;
begin
try
QClxObjectMap_remove(FHandle);
FHandle := nil;
QObject_hook_destroy(FHooks);
FHooks := nil;
Application.EnableQtAccelerators := False;
except
Application.HandleException(Self);
end;
end;
function TQtDialog.DoExecute: Boolean;
begin
QDialog_show(Handle);
if FModal then
begin
try
Result := QDialog_result(Handle) = Integer(QDialogDialogCode_Accepted);
finally
QDialog_destroy(Handle);
end;
end
else
Result := True;
end;
function TQtDialog.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
try
Result := False;
case QEvent_type(Event) of
QEventType_WindowActivate:
{ for modeless Qt dialogs}
Application.EnableQtAccelerators := True;
QEventType_WindowDeactivate:
{ for modeless Qt dialogs}
Application.EnableQtAccelerators := False;
QEventType_Show:
begin
Application.EnableQtAccelerators := True;
FShowing := True;
DoShow;
end;
QEventType_Hide:
begin
Application.EnableQtAccelerators := False;
DoClose;
FShowing := False;
end;
end;
except
Application.HandleException(Self);
Result := False;
end;
end;
function TQtDialog.GetHandle: QDialogH;
begin
{$IFDEF MSWINDOWS}
if not UseNativeDialog then
{$ENDIF}
HandleNeeded;
Result := FHandle;
end;
function TQtDialog.GetHooks: QObject_hookH;
begin
HandleNeeded;
Result := FHooks;
end;
function TQtDialog.HandleAllocated: Boolean;
begin
Result := FHandle <> nil;
end;
procedure TQtDialog.HandleNeeded;
begin
if FHandle = nil then CreateHandle;
end;
procedure TQtDialog.HookEvents;
var
Method: TMethod;
begin
if FHooks = nil then
begin
Assert(FHandle <> nil);
FHooks := QObject_hook_create(Handle);
end;
TEventFilterMethod(Method) := EventFilter;
Qt_hook_hook_events(FHooks, Method);
QObject_destroyed_event(Method) := Self.DestroyedHook;
QObject_hook_hook_destroyed(FHooks, Method);
end;
procedure TQtDialog.InitWidget;
begin
Application.EnableQtAccelerators := True;
end;
procedure TQtDialog.InvokeHelp;
begin
case HelpType of
htKeyword:
Application.KeywordHelp(HelpKeyword);
htContext:
Application.ContextHelp(HelpContext);
end;
end;
procedure TQtDialog.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
if not (csDesigning in ComponentState) and HandleAllocated then
begin
QWidget_move(Handle, ALeft, ATop);
QWidget_resize(Handle, AWidth, AHeight);
end;
FPosition.X := ALeft;
FPosition.Y := ATop;
FWidth := AWidth;
FHeight := AHeight;
end;
procedure TQtDialog.SetTitle(const Value: WideString);
begin
inherited;
if {$IFDEF MSWINDOWS} not UseNativeDialog and {$ENDIF} HandleAllocated then
QWidget_setCaption(Handle, PWideString(@FTitle));
end;
function TQtDialog.WidgetFlags: Integer;
begin
Result := Integer(WidgetFlags_WStyle_DialogBorder) or
Integer(WidgetFlags_WStyle_Title) or
Integer(WidgetFlags_WStyle_Customize) or
Integer(WidgetFlags_WStyle_SysMenu) or
Integer(WidgetFlags_WStyle_ContextHelp);
end;
procedure TQtDialog.DestroyWidget;
begin
if FHandle <> nil then QObject_destroy(FHandle);
FHandle := nil;
end;
destructor TQtDialog.Destroy;
begin
if FHandle <> nil then
begin
DestroyWidget;
FHandle := nil;
end;
inherited Destroy;
end;
function TQtDialog.GetBounds: TRect;
begin
if HandleAllocated {$IFDEF MSWINDOWS} and not UseNativeDialog {$ENDIF} then
begin
QWidget_geometry(Handle, @Result);
Result.Right := Result.Right - Result.Left;
Result.Bottom := Result.Bottom - Result.Top;
end
else
Result := Rect(FPosition.X, FPosition.Y, FWidth, FHeight);
end;
procedure TQtDialog.DoShow;
begin
{$IFDEF MSWINDOWS}
if not UseNativeDialog then
{$ENDIF}
QWidget_setCaption(Handle, PWideString(@FTitle));
inherited;
end;
{$IFDEF MSWINDOWS}
function TQtDialog.NativeExecute(Flags: Integer): Boolean;
begin
Result := False;
end;
{$ENDIF}
function TQtDialog.Execute: Boolean;
var
AppHook: QObject_hookH;
Method: TMethod;
{$IFDEF MSWINDOWS}
GrabControl: TControl;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
if UseNativeDialog then
begin
GrabControl := GetMouseGrabControl;
try
SetMouseGrabControl(nil);
Result := NativeExecute(FNativeFlags);
finally
SetMouseGrabControl(GrabControl);
end;
end
else
{$ENDIF}
if FShowing then
begin
QWidget_raise(Handle);
Result := True;
end
else
begin
Application.ModalStarted(Self);
try
HandleNeeded;
AppHook := QObject_Hook_create(Application.Handle);
try
TEventFilterMethod(Method) := AppEventFilter;
Qt_hook_hook_events(AppHook, Method);
Result := inherited Execute;
finally
QObject_hook_destroy(AppHook);
if FModal then DestroyWidget;
end;
finally
Application.ModalFinished(Self);
end;
end;
end;
{ TOpenDialog }
constructor TOpenDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFiles := TStringList.Create;
Modal := True;
FSaveDlg := False;
FOptions := [ofHideReadOnly, ofEnableSizing];
{$IFDEF MSWINDOWS}
FUseNative := True;
{$ENDIF}
end;
function TOpenDialog.CreateForm: TDialogForm;
begin
if Form = nil then
begin
if not Assigned(FileDialogFormClass) then
FileDialogFormClass := QFileDialog.TFileDialogForm;
Result := FileDialogFormClass.Create(Self);
end
else
Result := Form;
end;
destructor TOpenDialog.Destroy;
begin
FFiles.Free;
inherited Destroy;
end;
procedure TOpenDialog.DirChanged(NewDir: WideString);
begin
if Assigned(FOnFolderChange) then
FOnFolderChange(Self, NewDir);
end;
function TOpenDialog.DoExecute: Boolean;
var
I: Integer;
begin
SetOptions;
Result := inherited DoExecute;
for I := 0 to FilePreviewers.Count - 1 do
IFilePreviewer(FilePreviewers[I]).StopPreview;
RetrieveOptions(Result);
FPosition := Point(FForm.Left, FForm.Top);
FWidth := FForm.Width;
FHeight := FForm.Height;
FScaleFlags := [sfLeft, sfTop, sfWidth, sfHeight];
FForm.Free;
FForm := nil;
end;
procedure TOpenDialog.FilterChanged(Index: Integer);
begin
if Assigned(FOnFilterChange) then
FOnFilterChange(Self, Index);
end;
{$IFDEF MSWINDOWS}
function TOpenDialog.NativeExecute(Flags: Integer): Boolean;
begin
Result := WinFileDialogExecute(Self, @GetOpenFileName, Flags);
end;
{$ENDIF}
procedure TOpenDialog.Refresh;
begin
end;
procedure TOpenDialog.RetrieveOptions(Accepted: Boolean);
begin
if Accepted then
begin
if not (ofNoChangeDir in FOptions) then
FSaveDir := ExtractFilePath(FFilename);
SetCurrentDir(FSaveDir);
end;
Exclude(FOptions, ofReadOnly);
Exclude(FOptions, ofViewDetail);
Exclude(FOptions, ofViewIcon);
Exclude(FOptions, ofViewList);
(Form as IFileDialogForm).GetOptions(Self, Accepted);
end;
procedure TOpenDialog.SetHistoryList(Value: TStrings);
begin
end;
procedure TOpenDialog.SetOptions;
begin
FSaveDir := GetCurrentDir;
FFiles.Clear;
(Form as IFileDialogForm).SetOptions(Self);
end;
procedure TOpenDialog.SetSaveDlg(const Value: Boolean);
begin
if FSaveDlg <> Value then
begin
FSaveDlg := Value;
if FSaveDlg then
begin
if (AnsiCompareStr(Title, SOpen) = 0) then
Title := SSave;
end else
if (AnsiCompareStr(Title, SSave) = 0) then
Title := SOpen;
end;
end;
function TOpenDialog.Execute: Boolean;
{$IFDEF MSWINDOWS}
var
GrabControl: TControl;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
if UseNativeDialog then
begin
GrabControl := GetMouseGrabControl;
try
SetMouseGrabControl(nil);
Result := NativeExecute(FNativeFlags);
finally
SetMouseGrabControl(GrabControl);
end;
end
else
{$ENDIF}
Result := inherited Execute;
end;
procedure TOpenDialog.FilePreview(const Filename: WideString; Canvas: TCanvas;
const Rect: TRect; Progress: TProgressEvent; var Handled: Boolean);
var
I: Integer;
Previewer: IFilePreviewer;
Size: TSize;
R: TRect;
begin
Handled := False;
if Assigned(FOnPreview) then
FOnPreview(Self, Filename, Canvas, Rect, Progress, Handled);
if not Handled then
begin
for I := 0 to FilePreviewers.Count - 1 do
begin
Previewer := IFilePreviewer(FilePreviewers[I]);
Previewer.StopPreview;
Handled := Previewer.CanPreview(Filename);
if Handled then
begin
R := Rect;
Size.cy := R.Bottom - R.Top;
Size.cx := R.Right - R.Left;
Previewer.GetPreviewSize(Filename, Canvas, Size);
(Form as IFileDialogForm).ResizePreview(Size);
R.Right := R.Left + Size.cx;
R.Bottom := R.Top + Size.cy;
Previewer.Preview(Filename, Canvas, R, Progress);
Exit;
end;
end;
Canvas.Font.Color := clText;
Canvas.Brush.Color := clBackground;
Canvas.FillRect(Rect);
Canvas.TextRect(Rect, Rect.Left, Rect.Top, SNoPreview,
Integer(AlignmentFlags_AlignCenter));
end;
end;
procedure TOpenDialog.CanClose(var CanClose: Boolean);
var
I: Integer;
{$IFDEF MSWINDOWS}
Drive: string;
DT: Cardinal;
{$ENDIF}
begin
if Form <> nil then
(Form as IFileDialogForm).ListFiles(FFiles);
if FFiles.Count > 0 then
begin
FFilename := FFiles[0];
{$IFDEF MSWINDOWS}
if (Length(FFilename) > 1) and (FFilename[2] = DriveDelim) then
begin
Drive := Copy(FFilename, 1, 2);
DT := Windows.GetDriveType(PChar(Drive));
CanClose := (DT <> DRIVE_UNKNOWN) and (DT <> DRIVE_NO_ROOT_DIR);
if not CanClose then
begin
MessageDlg(Title, Format(SDriveNotFound, [Drive]), mtError, [mbOk],
0);
Exit;
end;
if DT = DRIVE_REMOVABLE then
begin
ChDir(Drive);
CanClose := IOResult = 0;
if not CanClose then
begin
MessageDlg(Title, Format(SCannotReadDirectory, [ExtractFilePath(FFilename)]),
mtError, [mbOk], 0);
Exit;
end;
end;
end;
{$ENDIF}
end;
//ofOverwritePrompt
if SaveDlg and (ofOverwritePrompt in Options) and FileExists(FFilename)
and not UseNativeDialog then
CanClose := MessageDlg(Format(SOverwriteCaption, [FFilename]),
Format(SOverwriteText, [FFilename]), mtWarning, [mbNo, mbYes], 0, mbNo) = mrYes
//ofFileMustExist, ofPathMustExist
//TODO: drive must exist.
else if CanClose
then
for I := 0 to FFiles.Count - 1 do
begin
if ofFileMustExist in Options then
begin
CanClose := FileExists(FFiles[I]);
if not CanClose then
MessageDlg(Title, Format(SFileMustExist, [ExtractFileName(FFiles[I])]),
mtCustom, [mbOk], 0);
end;
if CanClose and (ofPathMustExist in Options) then
begin
CanClose := DirectoryExists(ExtractFilePath(FFiles[I]));
if not CanClose then
MessageDlg(Title, Format(SPathMustExist, [ExtractFilePath(FFiles[I])]),
mtCustom, [mbOk], 0);
end;
if (FDefaultExt <> '') and (AnsiCompareStr('.' + FDefaultExt,
ExtractFileExt(FFiles[I])) <> 0) then
Include(FOptions, ofExtensionDifferent);
end;
if CanClose and Assigned(FOnCanClose) then
FOnCanClose(Self, CanClose);
end;
function TOpenDialog.FileAdd(const Filename: WideString; const Readable,
Writeable, Executable: Boolean): Boolean;
begin
Result := True;
if Assigned(FOnFileAdd) then
FOnFileAdd(Self, Filename, Readable, Writeable, Executable, Result);
end;
procedure TOpenDialog.FileSelected(AFile: PFileInfo; Selected: Boolean);
begin
if Assigned(FOnSelected) then
FOnSelected(Self, AFile, Selected);
end;
procedure TOpenDialog.Help;
begin
if Assigned(FOnHelpClick) then
FOnHelpClick(Self)
else
InvokeHelp;
end;
{ TSaveDialog }
constructor TSaveDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTitle := SSave;
FSaveDlg := True;
end;
{$IFDEF MSWINDOWS}
function TSaveDialog.NativeExecute(Flags: Integer): Boolean;
begin
Result := WinFileDialogExecute(Self, @GetSaveFileName, Flags);
end;
{$ENDIF}
procedure TSaveDialog.SetOptions;
begin
inherited SetOptions;
// QClxFileDialog_setMode(Handle, QClxFileDialogMode_AnyFile);
end;
{ TFontDialog }
constructor TFontDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFont := TFont.Create;
end;
destructor TFontDialog.Destroy;
begin
inherited Destroy;
FFont.Free;
end;
function TFontDialog.DoExecute: Boolean;
var
QFont: QFontH;
{$IFDEF LINUX}
SigIntStatus,
SigQuitStatus: TSignalState;
{$ENDIF}
begin
QFont := QFont_create;
try
{$IFDEF LINUX}
SigIntStatus := InquireSignal(RTL_SIGINT);
SigQuitStatus := InquireSignal(RTL_SIGQUIT);
if SigIntStatus = ssHooked then
UnhookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
UnhookSignal(RTL_SIGQUIT);
try
{$ENDIF}
QFontDialog_getFont(QFont, @Result, FFont.Handle, Screen.ActiveWidget, nil);
if Result then
begin
FFont.Handle := QFont;
FFont.OwnHandle;
end;
{$IFDEF LINUX}
finally
if SigIntStatus = ssHooked then
HookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
HookSignal(RTL_SIGQUIT);
end;
{$ENDIF}
finally
if not Result then QFont_destroy(QFont);
end;
end;
{$IFDEF MSWINDOWS}
function TFontDialog.NativeExecute(Flags: Integer): Boolean;
begin
Result := WinFontDialogExecute(Self, Flags);
end;
{$ENDIF}
procedure TFontDialog.SetFont(Value: TFont);
begin
FFont.Assign(Value);
end;
{ TColorDialog }
constructor TColorDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCustomColors := TStringList.Create;
end;
destructor TColorDialog.Destroy;
begin
FCustomColors.Free;
inherited Destroy;
end;
function TColorDialog.DoExecute: Boolean;
const
ColorPrefix = 'Color';
procedure GetCustomColors;
var
I: Integer;
Color: QRgb;
begin
Color := 0;
for I := 0 to CustomColorCount - 1 do
begin
QColorDialog_customColor(@Color, I);
FCustomColors.Values[ColorPrefix + Char(Ord('A') + I)] :=
Format('%.6x', [Color]);
end;
end;
procedure SetCustomColors;
var
Value: string;
I: Integer;
CustomColor: QRgb;
begin
for I := 0 to CustomColorCount - 1 do
begin
Value := FCustomColors.Values[ColorPrefix + Char(Ord('A') + I)];
if Value <> '' then
CustomColor := QRgb(StrToInt('$' + Value))
else
CustomColor := QRgb(0);
QColorDialog_setCustomColor(I, @CustomColor);
end;
end;
var
QC: QColorH;
{$IFDEF LINUX}
SigIntStatus,
SigQuitStatus: TSignalState;
{$ENDIF}
begin
SetCustomColors;
QC := QColor_create;
try
{$IFDEF LINUX}
SigIntStatus := InquireSignal(RTL_SIGINT);
SigQuitStatus := InquireSignal(RTL_SIGQUIT);
if SigIntStatus = ssHooked then
UnhookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
UnhookSignal(RTL_SIGQUIT);
try
{$ENDIF}
QColorDialog_getColor(QC, QColor(FColor), Screen.ActiveWidget, nil);
{$IFDEF LINUX}
finally
if SigIntStatus = ssHooked then
HookSignal(RTL_SIGINT);
if SigQuitStatus = ssHooked then
HookSignal(RTL_SIGQUIT);
end;
{$ENDIF}
Result := QColor_isValid(QC);
if Result then
begin
FColor := QColorColor(QC);
GetCustomColors;
end;
finally
QColor_destroy(QC);
end;
end;
{$IFDEF MSWINDOWS}
function TColorDialog.NativeExecute(Flags: Integer): Boolean;
begin
Result := WinColorDialogExecute(Self, Flags);
end;
{$ENDIF}
procedure TColorDialog.SetCustomColors(Value: TStrings);
begin
FCustomColors.Assign(Value);
end;
{ TDialogForm }
procedure TDialogForm.InvokeHelp;
begin
if ((HelpType = htKeyword) and (HelpKeyword = '')) or
((HelpType = htContext) and (HelpContext = 0)) then
FDialog.InvokeHelp
else
inherited;
end;
{ TCustomDialog }
function TCustomDialog.DoExecute: Boolean;
begin
Result := True;
if (sfLeft in FScaleFlags) or (sfTop in FScaleFlags) then
FForm.Position := poDefault;
DoShow;
if FModal then
Result := FForm.ShowModal = mrOK
else
FForm.Show;
end;
procedure TCustomDialog.Close(Sender: TObject; var Action: TCloseAction);
begin
DoClose;
end;
procedure TCustomDialog.DoClose;
begin
FWidth := FForm.Width;
FHeight := FForm.Height;
FPosition.Y := FForm.Top;
FPosition.X := FForm.Left;
inherited;
end;
procedure TCustomDialog.DoShow;
begin
if FForm <> nil then
begin
FForm.Caption := FTitle;
FForm.OnClose := Self.Close;
end;
inherited;
end;
procedure TCustomDialog.InvokeHelp;
begin
case HelpType of
htKeyword:
Application.KeywordHelp(HelpKeyword);
htContext:
Application.ContextHelp(HelpContext);
end;
end;
procedure TCustomDialog.SetTitle(const Value: WideString);
begin
inherited;
if FForm <> nil then FForm.Caption := Value;
end;
procedure TCustomDialog.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
ResizeEvent: QResizeEventH;
Size: TSize;
begin
if not (csDesigning in ComponentState) and Assigned(FForm) and FForm.HandleAllocated then
begin
QWidget_move(FForm.Handle, ALeft, ATop);
QWidget_resize(FForm.Handle, AWidth, AHeight);
Size.cx := AWidth;
Size.cy := AHeight;
ResizeEvent := QResizeEvent_create(@Size, @Size);
try
QObject_event(FForm.Handle, ResizeEvent);
finally
QResizeEvent_destroy(ResizeEvent);
end;
end;
FPosition.X := ALeft;
FPosition.Y := ATop;
FWidth := AWidth;
FHeight := AHeight;
end;
function TCustomDialog.GetBounds: TRect;
begin
if FForm <> nil then
Result := Rect(FForm.Left, FForm.Top, FForm.Width, FForm.Height)
else
Result := Rect(FPosition.X, FPosition.Y, FWidth, FHeight);
end;
function TCustomDialog.Execute: Boolean;
begin
if FForm = nil then
begin
FForm := CreateForm;
FForm.FDialog := Self;
end;
Result := inherited Execute;
end;
destructor TCustomDialog.Destroy;
begin
FForm.Free;
inherited Destroy;
end;
{ TFindDialog }
function Max(L, R: Integer): Integer;
begin
if L > R then Result := L
else Result := R;
end;
constructor TFindDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FModal := False;
FTitle := SFindTitle;
FOptions := [frDown];
Position := Point(Screen.Width div 3, Screen.Height div 3);
end;
function TFindDialog.CreateForm: TDialogForm;
begin
Result := TFindDialogForm.Create(Self);
end;
procedure TFindDialog.DoShow;
begin
with TFindDialogForm(FForm) do
begin
FindEdit.Text := FindText;
WholeWord.Visible := not (frHideWholeWord in FOptions);
WholeWord.Checked := frWholeWord in FOptions;
WholeWord.Enabled := not (frDisableWholeWord in FOptions);
MatchCase.Visible := not (frHideMatchCase in FOptions);
MatchCase.Checked := frMatchCase in Options;
MatchCase.Enabled := not (frDisableMatchCase in FOptions);
if frDown in FOptions then Direction.ItemIndex := 1 else Direction.ItemIndex := 0;
Direction.Enabled := not (frDisableUpDown in FOptions);
Direction.Visible := not (frHideUpDown in FOptions);
Help.Visible := frShowHelp in FOptions;
if Help.Visible then
Height := Max(Direction.Top + Direction.Height + 5, Help.Top + Help.Height + 5)
else
Height := Direction.Top + Direction.Height + 8;
FindEdit.SetFocus;
FindEdit.SelectAll;
end;
inherited DoShow;
end;
procedure TFindDialog.Find;
begin
if Assigned(FOnFind) then FOnFind(Self);
end;
type
TWidgetAccess = class(TWidgetControl);
function TextWidth(Control: TWidgetControl; const Text: WideString): Integer;
var
FM: QFontMetricsH;
begin
FM := QFontMetrics_create(TWidgetAccess(Control).Font.Handle);
try
QWidget_FontMetrics(Control.Handle, FM);
Result := QFontMetrics_width(FM, PWideString(@Text), -1);
finally
QFontMetrics_destroy(FM);
end;
end;
function TextHeight(Control: TWidgetControl): Integer;
var
FM: QFontMetricsH;
begin
FM := QFontMetrics_create(TWidgetAccess(Control).Font.Handle);
try
QWidget_FontMetrics(Control.Handle, FM);
Result := QFontMetrics_height(FM);
finally
QFontMetrics_destroy(FM);
end;
end;
procedure TFindDialog.SetFindText(const Value: WideString);
begin
if FindText <> Value then
begin
FFindText := Value;
if FForm <> nil then
TFindDialogForm(FForm).FindEdit.Text := Value;
end;
end;
{ TFindDialogForm }
procedure TFindDialogForm.ButtonPress(Sender: TObject);
begin
with TFindDialog(FDialog) do
if Sender = FindNext then
begin
Include(FOptions, frFindNext);
FFindText := FindEdit.Text;
if FModal then ModalResult := mrOk;
Find;
end
else if Sender = Cancel then
begin
SetDialogOption(frFindNext, False);
Exclude(FOptions, frFindNext);
Exclude(FOptions, frReplace);
if FModal then
ModalResult := mrCancel
else
Self.Close;
end;
end;
procedure TFindDialogForm.CheckboxCheck(Sender: TObject);
var
Option: TFindOption;
begin
if Sender = WholeWord then
Option := frWholeWord
else
Option := frMatchCase;
if (Sender as TCheckBox).Checked then
Include(TFindDialog(FDialog).FOptions, Option)
else
Exclude(TFindDialog(FDialog).FOptions, Option);
end;
constructor TFindDialogForm.Create(AOwner: TComponent);
begin
inherited CreateNew(AOwner);
FormStyle := fsStayOnTop;
BorderStyle := fbsDialog;
DialogUnits := Types.Point(6, 13);
SetBounds(FLeft, FTop, MulDiv(245, DialogUnits.x, 4),
MulDiv(65, DialogUnits.y, 8));
Scaled := True;
AutoScroll := False;
FindLabel := TLabel.Create(Self);
with FindLabel do
begin
Parent := Self;
Caption := SFindWhat;
AutoSize := True;
SetBounds(MulDiv(5, DialogUnits.y, 8), MulDiv(10, DialogUnits.x, 4),
TextWidth(FindLabel, Caption), Font.Height + 2);
Visible := True;
Name := 'FindLabel';
end;
WholeWord := TCheckBox.Create(Self);
with WholeWord do
begin
Parent := Self;
Caption := SWholeWord;
Left := FindLabel.Left;
Top := MulDiv(30, DialogUnits.y, 8);
Width := TextWidth(WholeWord, Caption) + 20;
Height := Font.Height + 2;
OnClick := CheckBoxCheck;
Name := 'WholeWordCheckbox';
TabOrder := 1;
end;
MatchCase := TCheckBox.Create(Self);
with MatchCase do
begin
Parent := Self;
Caption := SMatchCase;
Left := FindLabel.Left;
Top := WholeWord.Top + WholeWord.Height + 7;
Width := TextWidth(MatchCase, Caption) + 20;
Height := Font.Height + 2;
OnClick := CheckBoxCheck;
Name := 'MatchCaseCheckbox';
TabOrder := 2;
end;
Direction := TRadioGroup.Create(Self);
with Direction do
begin
Parent := Self;
Caption := SDirection;
Left := Max(WholeWord.Left + WholeWord.Width + 5, MatchCase.Left +
MatchCase.Width + 5);
Columns := 2;
ColumnLayout := clAutoSize;
Items.Add(SUp);
Items.Add(SDown);
RequestAlign;
Top := WholeWord.Top - TextHeight(Direction) div 2;
Width := Controls[1].Left + Controls[1].Width + 5;
Height := (MatchCase.Top + MatchCase.Height) - Top + 5;
OnClick := Self.DirectionClick;
Name := 'DirectionRadioGroup';
TabStop := True;
TabOrder := 3;
end;
FindEdit := TEdit.Create(Self);
with FindEdit do
begin
Parent := Self;
HandleNeeded;
AutoSize := True;
Left := FindLabel.Left + FindLabel.Width + 5;
Top := FindLabel.Top + ((FindLabel.Height - Height) div 2);
Width := Direction.Left + Direction.Width - Left;
FindLabel.FocusControl := FindEdit;
Visible := True;
OnChange := EditChanged;
AutoSelect := True;
TabOrder := 0;
// Name := 'FindEdit';
end;
FindNext := TButton.Create(Self);
with FindNext do
begin
Parent := Self;
Caption := SFindNext;
Enabled := False;
Left := FindEdit.Left + FindEdit.Width + 10;
Top := FindEdit.Top - 1;
Height := TextHeight(FindNext) * 9 div 5;
Width := Max(TextWidth(FindNext, SFindNext + ' '),
Max(TextWidth(FindNext, SCancel + ' '),
Max(TextWidth(FindNext, SHelp + ' '),
Width)));
Default := True;
OnClick := Self.ButtonPress;
Visible := True;
Name := 'FindNextButton';
TabOrder := 4;
end;
Cancel := TButton.Create(Self);
with Cancel do
begin
Parent := Self;
Caption := SCancel;
Left := FindNext.Left;
Top := FindNext.Top + FindNext.Height + 3;
Width := FindNext.Width;
Height := FindNext.Height;
Cancel := True;
OnClick := Self.ButtonPress;
Visible := True;
Name := 'CancelButton';
TabOrder := 5;
end;
Help := TButton.Create(Self);
with Help do
begin
Parent := Self;
Caption := SHelp;
Left := FindNext.Left;
Top := Self.Cancel.Top + Self.Cancel.Height + 3;
Width := FindNext.Width;
Height := FindNext.Height;
OnClick := Self.ButtonPress;
Name := 'HelpButton';
TabOrder := 6;
end;
Width := FindNext.Left + FindNext.Width + 10;
end;
procedure TFindDialogForm.DirectionClick(Sender: TObject);
begin
case Direction.ItemIndex of
0: SetDialogOption(frDown, False);
1: SetDialogOption(frDown, True);
end;
end;
procedure TFindDialogForm.EditChanged(Sender: TObject);
begin
FindNext.Enabled := FindEdit.Text <> '';
end;
procedure TFindDialogForm.SetDialogOption(Option: TFindOption;
Value: Boolean);
begin
if Value then
Include(TFindDialog(FDialog).FOptions, Option)
else
Exclude(TFindDialog(FDialog).FOptions, Option);
end;
{ TReplaceDialog }
constructor TReplaceDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTitle := SReplaceTitle;
end;
function TReplaceDialog.CreateForm: TDialogForm;
begin
Result := TReplaceDialogForm.Create(Self);
end;
procedure TReplaceDialog.DoShow;
begin
with TReplaceDialogForm(FForm) do
ReplaceEdit.Text := FReplaceText;
inherited;
end;
procedure TReplaceDialog.Replace;
begin
if Assigned(FOnReplace) then FOnReplace(Self);
end;
procedure TReplaceDialog.SetReplaceText(const Value: WideString);
begin
if ReplaceText <> Value then
begin
FReplaceText := Value;
if FForm <> nil then
TReplaceDialogForm(FForm).ReplaceEdit.Text := FReplaceText;
end;
end;
{ TReplaceDialogForm }
procedure TReplaceDialogForm.ButtonPress(Sender: TObject);
begin
if Sender = ReplaceBtn then
begin
SetDialogOption(frReplace, True);
SetDialogOption(frReplaceAll, False);
end
else if Sender = ReplaceAll then
begin
SetDialogOption(frReplaceAll, True);
SetDialogOption(frReplace, False);
end;
TReplaceDialog(FDialog).FFindText := FindEdit.Text;
TReplaceDialog(FDialog).FReplaceText := ReplaceEdit.Text;
if (Sender = ReplaceBtn) or (Sender = ReplaceAll) then
with TReplaceDialog(FDialog) do
begin
if FModal then ModalResult := mrOk;
Replace;
end;
inherited ButtonPress(Sender);
end;
constructor TReplaceDialogForm.Create(AOwner: TComponent);
var
ButtonWidth: Integer;
begin
inherited;
Height := MulDiv(95, DialogUnits.y, 8);
ButtonWidth := Max(TextWidth(FindNext, SReplace + ' '),
Max(TextWidth(FindNext, SReplaceAll + ' '),
FindNext.Width));
FindNext.Width := ButtonWidth;
Cancel.Width := ButtonWidth;
Help.Width := ButtonWidth;
Width := FindNext.Left + ButtonWidth + 10;
ReplaceLabel := TLabel.Create(Self);
with ReplaceLabel do
begin
Parent := Self;
Caption := SReplaceWith;
SetBounds(FindLabel.Left, FindEdit.Top + FindEdit.Height + 13,
TextWidth(ReplaceLabel, ReplaceLabel.Caption), Font.Height + 2);
Visible := True;
Name := 'ReplaceLabel';
end;
FindEdit.Left := ReplaceLabel.Left + Max(ReplaceLabel.Width, FindLabel.Width) + 5;
FindEdit.Width := FindNext.Left - FindEdit.Left - 5;
WholeWord.Top := MulDiv(50, DialogUnits.Y, 8);
MatchCase.Top := WholeWord.Top + WholeWord.Height + 10;
ReplaceBtn := TButton.Create(Self);
with ReplaceBtn do
begin
Parent := Self;
HandleNeeded;
SetBounds(Self.Cancel.Left, Self.Cancel.Top, ButtonWidth,
Self.Cancel.Height);
Caption := SReplace;
OnClick := ButtonPress;
Visible := True;
Enabled := False;
Name := 'ReplaceButton';
TabOrder := 5;
end;
ReplaceAll := TButton.Create(Self);
with ReplaceAll do
begin
Parent := Self;
HandleNeeded;
SetBounds(FindNext.Left, ReplaceBtn.Top + ReplaceBtn.Height + 3,
ButtonWidth, FindNext.Height);
Caption := SReplaceAll;
OnClick := ButtonPress;
Visible := True;
Enabled := False;
Name := 'ReplaceAllButton';
TabOrder := 6;
end;
Cancel.Top := ReplaceAll.Top + ReplaceAll.Height + 3;
ReplaceEdit := TEdit.Create(Self);
with ReplaceEdit do
begin
Parent := Self;
HandleNeeded;
AutoSize := True;
Left := ReplaceLabel.Left + ReplaceLabel.Width + 5;
Top := ReplaceLabel.Top + ((ReplaceLabel.Height - Height) div 2);
Width := FindEdit.Width;
Visible := True;
Name := 'ReplaceEdit';
TabOrder := 1;
end;
ReplaceLabel.FocusControl := ReplaceEdit;
Direction.Top := WholeWord.Top - 5;
Help.Top := Cancel.Top + Cancel.Height + 3;
end;
procedure TReplaceDialogForm.EditChanged(Sender: TObject);
begin
inherited EditChanged(Sender);
ReplaceBtn.Enabled := FindEdit.Text <> '';
ReplaceAll.Enabled := FindEdit.Text <> '';
end;
initialization
CustomColorCount := QColorDialog_customCount;
StartClassGroup(TControl);
ActivateClassGroup(TControl);
GroupDescendentsWith(TDialog, TControl);
finalization
if Assigned(GFilePreviewers) then
FreeAndNil(GFilePreviewers);
end.
|
unit pFIBRepositoryOperations;
interface
{$i ..\FIBPlus.inc}
uses pFIBInterfaces;
procedure AdjustFRepositaryTable(DB:IFIBConnect);
procedure CreateErrorRepositoryTable(DB:IFIBConnect);
procedure CreateDataSetRepositoryTable(DB:IFIBConnect);
implementation
uses pFIBEditorsConsts;
{const
qryCreateTabFieldsRepository=
'CREATE TABLE FIB$FIELDS_INFO (TABLE_NAME VARCHAR(31) NOT NULL,'#13#10+
'FIELD_NAME VARCHAR(31) NOT NULL,'#13#10+
'DISPLAY_LABEL VARCHAR(25),'#13#10+
'VISIBLE FIB$BOOLEAN DEFAULT 1 NOT NULL,'#13#10+
'DISPLAY_FORMAT VARCHAR(15),'#13#10+
'EDIT_FORMAT VARCHAR(15),'#13#10+
'TRIGGERED FIB$BOOLEAN DEFAULT 0 NOT NULL,'#13#10+
'CONSTRAINT PK_FIB$FIELDS_INFO PRIMARY KEY (TABLE_NAME, FIELD_NAME))';
}
procedure AdjustFRepositaryTable(DB:IFIBConnect);
begin
if db.QueryValueAsStr(qryExistTable,0,['FIB$FIELDS_INFO'])='0' then
begin
if db.QueryValueAsStr(qryExistDomain,0,['FIB$BOOLEAN'])='0' then
db.Execute(qryCreateBooleanDomain);
db.Execute(qryCreateTabFieldsRepository);
db.Execute('GRANT SELECT ON TABLE FIB$FIELDS_INFO TO PUBLIC');
end;
//Adjust1
if db.QueryValueAsStr(qryExistField,0,['FIB$FIELDS_INFO','DISPLAY_WIDTH'])='0' then
begin
try
db.Execute(qryCreateFieldInfoVersionGen);
except
end;
try
db.Execute('ALTER TABLE FIB$FIELDS_INFO ADD DISPLAY_WIDTH INTEGER DEFAULT 0');
except
end;
try
db.Execute('ALTER TABLE FIB$FIELDS_INFO ADD FIB$VERSION INTEGER');
except
end;
try
db.Execute(
'CREATE TRIGGER FIB$FIELDS_INFO_BI FOR FIB$FIELDS_INFO '+
'ACTIVE BEFORE INSERT POSITION 0 as '+#13#10+
'begin '+#13#10+
'new.fib$version=gen_id(fib$field_info_version,1);'+#13#10+
'end');
except
end;
try
db.Execute(
'CREATE TRIGGER FIB$FIELDS_INFO_BU FOR FIB$FIELDS_INFO '+
'ACTIVE BEFORE UPDATE POSITION 0 as '+#13#10+
'begin '+#13#10+
'new.fib$version=gen_id(fib$field_info_version,1);'+#13#10+
'end');
except
end;
end;
if db.QueryValueAsStr(qryExistField,0,['FIB$FIELDS_INFO','DISPLAY_WIDTH'])='0' then
begin
//Adjust2
try
db.Execute('ALTER TABLE FIB$DATASETS_INFO ADD UPDATE_TABLE_NAME VARCHAR(68)');
except
end;
try
db.Execute('ALTER TABLE FIB$DATASETS_INFO ADD UPDATE_ONLY_MODIFIED_FIELDS FIB$BOOLEAN NOT NULL');
except
end;
try
db.Execute('ALTER TABLE FIB$DATASETS_INFO ADD CONDITIONS BLOB sub_type 1 segment size 80');
except
end;
end;
end;
procedure CreateErrorRepositoryTable(DB:IFIBConnect);
begin
if db.QueryValueAsStr(qryExistTable,0,['FIB$ERROR_MESSAGES'])='0' then
begin
db.Execute('CREATE TABLE FIB$ERROR_MESSAGES ('+
'CONSTRAINT_NAME VARCHAR(67) NOT NULL,'+
'MESSAGE_STRING VARCHAR(100),'+
'FIB$VERSION INTEGER,'+
'CONSTR_TYPE VARCHAR(11) DEFAULT ''UNIQUE'' NOT NULL,'+
'CONSTRAINT PK_FIB$ERROR_MESSAGES PRIMARY KEY (CONSTRAINT_NAME))');
db.Execute('GRANT SELECT ON TABLE FIB$ERROR_MESSAGES TO PUBLIC');
if db.QueryValueAsStr(qryGeneratorExist,0,['FIB$FIELD_INFO_VERSION'])='0' then
db.Execute(qryCreateFieldInfoVersionGen);
db.Execute('CREATE TRIGGER BI_FIB$ERROR_MESSAGES FOR FIB$ERROR_MESSAGES '+
'ACTIVE BEFORE INSERT POSITION 0 AS '#13#10+
'begin '#13#10'new.fib$version=gen_id(fib$field_info_version,1);'#13#10' end');
db.Execute( 'CREATE TRIGGER BU_FIB$ERROR_MESSAGES FOR FIB$ERROR_MESSAGES '+
'ACTIVE BEFORE UPDATE POSITION 0 AS '#13#10+
'begin '#13#10'new.fib$version=gen_id(fib$field_info_version,1);'#13#10' end');
end;
end;
procedure CreateDataSetRepositoryTable(DB:IFIBConnect);
begin
if db.QueryValueAsStr(qryExistTable,0,['FIB$DATASETS_INFO'])='0' then
begin
db.Execute('CREATE TABLE FIB$DATASETS_INFO (DS_ID INTEGER NOT NULL,'#13#10+
'DESCRIPTION VARCHAR(40),'+
'SELECT_SQL BLOB sub_type 1 segment size 80,'#13#10+
'UPDATE_SQL BLOB sub_type 1 segment size 80,'#13#10+
'INSERT_SQL BLOB sub_type 1 segment size 80,'#13#10+
'DELETE_SQL BLOB sub_type 1 segment size 80,'#13#10+
'REFRESH_SQL BLOB sub_type 1 segment size 80,'#13#10+
'NAME_GENERATOR VARCHAR(68), '+
'KEY_FIELD VARCHAR(68),'+
'CONSTRAINT PK_FIB$DATASETS_INFO PRIMARY KEY (DS_ID))');
db.Execute('GRANT SELECT ON TABLE FIB$DATASETS_INFO TO PUBLIC');
end;
//Adjust
if db.QueryValueAsStr(qryExistDomain,0,['FIB$BOOLEAN'])='0' then
db.Execute(qryCreateBooleanDomain);
if db.QueryValueAsStr(qryGeneratorExist,0,['FIB$FIELD_INFO_VERSION'])='0' then
db.Execute(qryCreateFieldInfoVersionGen);
if db.QueryValueAsStr(qryExistField,0,['FIB$DATASETS_INFO','UPDATE_TABLE_NAME'])='0' then
db.Execute('ALTER TABLE FIB$DATASETS_INFO ADD UPDATE_TABLE_NAME VARCHAR(68)');
if db.QueryValueAsStr(qryExistField,0,['FIB$DATASETS_INFO','UPDATE_ONLY_MODIFIED_FIELDS'])='0' then
db.Execute('ALTER TABLE FIB$DATASETS_INFO ADD UPDATE_ONLY_MODIFIED_FIELDS FIB$BOOLEAN NOT NULL');
if db.QueryValueAsStr(qryExistField,0,['FIB$DATASETS_INFO','CONDITIONS'])='0' then
db.Execute('ALTER TABLE FIB$DATASETS_INFO ADD CONDITIONS BLOB sub_type 1 segment size 80');
if db.QueryValueAsStr(qryExistField,0,['FIB$DATASETS_INFO','FIB$VERSION'])='0' then
db.Execute('ALTER TABLE FIB$DATASETS_INFO ADD FIB$VERSION INTEGER');
try
db.Execute('CREATE TRIGGER FIB$DATASETS_INFO_BI FOR FIB$DATASETS_INFO '+
'ACTIVE BEFORE INSERT POSITION 0 as '+#13#10+
'begin'#13#10+
'new.fib$version=gen_id(fib$field_info_version,1);'#13#10+
'end');
except
end;
try
db.Execute('CREATE TRIGGER FIB$DATASETS_INFO_BU FOR FIB$DATASETS_INFO '+
'ACTIVE BEFORE UPDATE POSITION 0 as '+#13#10+
'begin'#13#10+
'new.fib$version=gen_id(fib$field_info_version,1);'#13#10+
'end');
except
end;
end;
end.
|
unit p2_baseless_VCL_orderbook_example_main;
interface
uses
Windows, SysUtils, Classes, ActiveX, Forms, Controls, StdCtrls, Grids,
P2ClientGate_TLB,
p2_orderbook_collector, ExtCtrls;
const
INI_FILE_NAME = 'P2ClientGate.ini';
STREAM_INFO_NAME = 'FORTS_FUTINFO_REPL';
STREAM_AGGR_NAME = 'FORTS_FUTAGGR50_REPL';
TABLE_AGGR_NAME = 'orders_aggr';
TABLE_FUTSESS_NAME = 'fut_sess_contents';
// класс для получения времени с точностью до милисекунд
type
TPreciseTime = class(TComponent)
private
fTime: tDateTime;
fStart: int64;
fFreq: int64;
public
constructor Create(AOwner: TComponent); override;
function Now: TDateTime; overload;
end;
// главная форма приложения
type
TForm1 = class(TForm)
LogListBox: TListBox;
ConnectButton: TButton;
DisconnectButton: TButton;
InstrumentComboBox: TComboBox;
OrderBookGrid: TStringGrid;
procedure FormCreate(Sender: TObject);
procedure ConnectButtonClick(Sender: TObject);
procedure DisconnectButtonClick(Sender: TObject);
procedure InstrumentComboBoxChange(Sender: TObject);
private
fPreciseTime: TPreciseTime;
fApp: TCP2Application;
fConn: TCP2Connection;
fInfoStream: TCP2DataStream;
fAggrStream: TCP2DataStream;
procedure ProcessPlaza2Messages(Sender: TObject; var Done: Boolean);
procedure ConnectionStatusChanged(Sender: TObject; var conn: OleVariant; newStatus: TConnectionStatus);
procedure StreamStateChanged(Sender: TObject; var stream: OleVariant; newState: TDataStreamState);
procedure StreamLifeNumChanged(Sender: TObject; var stream: OleVariant; LifeNum: Integer);
procedure StreamDataInserted(Sender: TObject; var stream: OleVariant; var tableName: OleVariant; var rec: OleVariant);
procedure StreamDataDeleted(Sender: TObject; var stream: OleVariant; var tableName: OleVariant; Id: Int64; var rec: OleVariant);
procedure StreamDataEnd(Sender: TObject; var stream: OleVariant);
procedure StreamDatumDeleted(Sender: TObject; var stream: OleVariant; var tableName: OleVariant; rev: Int64);
procedure RedrawOrderBook(forceredraw: boolean);
public
function CheckAndReopen(AStream: TCP2DataStream): boolean;
procedure log(const alogstr: string); overload;
procedure log(const alogstr: string; const aparams: array of const); overload;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
function _StrToFloatDef(const str: string; Default: extended): extended;
begin if not TextToFloat(PChar(str), Result, fvExtended) then Result:= Default; end;
{ TPreciseTime }
constructor TPreciseTime.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
QueryPerformanceFrequency(fFreq);
FTime:= SysUtils.now;
QueryPerformanceCounter(fStart);
end;
function TPreciseTime.Now: TDateTime;
var fEnd : int64;
begin
QueryPerformanceCounter(fEnd);
result:= fTime + (((fEnd - fStart) * 1000) div fFreq) / 86400000.0;
end;
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
// устанавливаем обработчик события Application.OnIdle, в нем мы будем запускать
// обработку сообщений plaza2
Application.OnIdle:= ProcessPlaza2Messages;
// создаем счетчик времени
fPreciseTime:= TPreciseTime.Create(Self);
// проверяем наличие конфигурационного файла
if not fileexists(INI_FILE_NAME) then begin
// если файл отсутствует, выводим сообщение
MessageBox(0, 'Отсутствует файл настроек P2ClientGate.ini; создаем пустой...', 'Ошибка', 0);
// создаем файл
fileclose(filecreate(INI_FILE_NAME));
end;
// создаем экземпляр приложения plaza2
fApp:= TCP2Application.Create(Self);
// указываем имя ini-файла с настройками библиотеки
fApp.StartUp(INI_FILE_NAME);
// создаем соединение plaza2
fConn:= TCP2Connection.create(Self);
with fConn do begin
// устанавливаем адрес машины с роутером (в данном случае - локальный)
Host:= 'localhost';
// указываем порт, к которому подключается это приложение
Port:= 4001;
// задаем произвольное имя приложения
AppName:= 'P2VCLTestApp';
// устанавливаем обработчик изменения статуса потока (connected, error...)
OnConnectionStatusChanged:= ConnectionStatusChanged;
end;
// создаем потоки plaza2
fInfoStream := TCP2DataStream.create(Self);
with fInfoStream do begin
// указываем режим открытия потока (в delphi слово type - ключевое, при импорте
// библиотеки типов оно было автоматически переименовано
type_:= RT_COMBINED_DYNAMIC;
// задаем имя потока, например сделки по фьючерсам
StreamName:= STREAM_INFO_NAME;
// устанавливаем обработчик изменения статуса потока (remote_snapshot, online...)
OnStreamStateChanged:= StreamStateChanged;
// устанавливаем обработчик смены номера жизни, он необходим для корректного
// перехода потока в online
OnStreamLifeNumChanged:= StreamLifeNumChanged;
// устанавливаем обработчик DatumDeleted
OnStreamDatumDeleted:= StreamDatumDeleted;
// устанавливаем обработчик получения данных
OnStreamDataInserted:= StreamDataInserted;
// устанавливаем обработчик удаления данных
OnStreamDataDeleted:= StreamDataDeleted;
// устанавливаем обработчик "конец данных"
OnStreamDataEnd:= StreamDataEnd;
end;
fAggrStream := TCP2DataStream.create(Self);
with fAggrStream do begin
// указываем режим открытия потока (в delphi слово type - ключевое, при импорте
// библиотеки типов оно было автоматически переименовано
type_:= RT_COMBINED_DYNAMIC;
// задаем имя потока, например сделки по фьючерсам
StreamName:= STREAM_AGGR_NAME;
// устанавливаем обработчик изменения статуса потока (remote_snapshot, online...)
OnStreamStateChanged:= StreamStateChanged;
// устанавливаем обработчик смены номера жизни, он необходим для корректного
// перехода потока в online
OnStreamLifeNumChanged:= StreamLifeNumChanged;
// устанавливаем обработчик DatumDeleted
OnStreamDatumDeleted:= StreamDatumDeleted;
// устанавливаем обработчик получения данных
OnStreamDataInserted:= StreamDataInserted;
// устанавливаем обработчик удаления данных
OnStreamDataDeleted:= StreamDataDeleted;
// устанавливаем обработчик "конец данных"
OnStreamDataEnd:= StreamDataEnd;
end;
end;
procedure TForm1.ProcessPlaza2Messages(Sender: TObject; var Done: Boolean);
const cs_connected = CS_CONNECTION_CONNECTED or CS_ROUTER_CONNECTED;
var cookie : longword;
begin
// проверяем статус потока и переоткрываем его, если это необходимо
if assigned(fConn) and (fConn.Status and cs_connected = cs_connected) then begin
CheckAndReopen(fInfoStream);
CheckAndReopen(fAggrStream);
end;
// запускаем обработку сообщения plaza2
cookie:= 0;
if assigned(fConn) then fConn.ProcessMessage(cookie, 1);
// указываем, что обработка не завершена, для того чтобы vcl не уходил в ожидание сообщений windows
Done:= false;
end;
function TForm1.CheckAndReopen(AStream: TCP2DataStream): boolean;
begin
// проверка и переоткрытие потока
result:= true;
if assigned(AStream) then
with AStream do try
// если статус потока - ошибка или закрыт
if (State = DS_STATE_ERROR) or (State = DS_STATE_CLOSE) then begin
// ксли ошибка, то закрываем
if (State = DS_STATE_ERROR) then Close;
// далее пытаемся открыть его вновь
if assigned(fConn) then Open(fConn.DefaultInterface);
end;
except result:= false; end;
end;
procedure TForm1.ConnectionStatusChanged(Sender: TObject; var conn: OleVariant; newStatus: TConnectionStatus);
begin
// выводим сообщение об изменении статуса соединения
log('Статус соединения изменился на: %.8x', [longint(newStatus)]);
end;
procedure TForm1.StreamStateChanged(Sender: TObject; var stream: OleVariant; newState: TDataStreamState);
const state_unknown = -1;
const streamstates: array[state_unknown..DS_STATE_ERROR] of pChar = ('UNKNOWN', 'DS_STATE_CLOSE',
'DS_STATE_LOCAL_SNAPSHOT', 'DS_STATE_REMOTE_SNAPSHOT', 'DS_STATE_ONLINE', 'DS_STATE_CLOSE_COMPLETE',
'DS_STATE_REOPEN', 'DS_STATE_ERROR');
var st: longint;
begin
// выводим сообщение об изменении статуса потока
st:= newState;
if (st <= low(streamstates)) or (st > high(streamstates)) then st:= state_unknown;
log('Поток %s статус изменился на %s (%.8x)', [stream.StreamName, streamstates[st], st]);
end;
procedure TForm1.StreamLifeNumChanged(Sender: TObject; var stream: OleVariant; LifeNum: Integer);
var strmname : string;
begin
// при изменении номера жизни потока, указываем потоку новый номер жизни
stream.TableSet.LifeNum:= olevariant(lifenum);
strmname:= string(stream.StreamName);
// очищаем таблицы, согласно документации
if (CompareText(strmname, STREAM_INFO_NAME) = 0) then begin
InstrumentComboBox.Items.Clear;
end else
if (CompareText(strmname, STREAM_AGGR_NAME) = 0) then begin
if assigned(OrderBookList) then OrderBookList.Clear;
end;
// выводим сообщение об этом
log('Поток %s LifeNum изменился на: %d', [strmname, lifenum]);
end;
procedure TForm1.StreamDataInserted(Sender: TObject; var stream, tableName, rec: OleVariant);
var isin_id, idx : longint;
strmname, tblname : string;
begin
if (StrToInt64Def(rec.GetValAsString('replAct'), 1) = 0) then begin
strmname := string(stream.StreamName);
tblname := string(tableName);
// обработка пришедших данных
if (CompareText(strmname, STREAM_INFO_NAME) = 0) then begin
// поток INFO
if (CompareText(tblname, TABLE_FUTSESS_NAME) = 0) then begin
// таблица fut_sess_contents, формируем список инструментов
isin_id:= rec.GetValAsString('isin_id');
with InstrumentComboBox.Items do begin
// добавляем инструмент combobox, если его там еще нет
idx:= IndexOfObject(pointer(isin_id));
if (idx < 0) then
Objects[Add(format('%s [%s]', [rec.GetValAsString('short_isin'), rec.GetValAsString('name')]))]:= pointer(isin_id);
end;
end;
end else
if (CompareText(strmname, STREAM_AGGR_NAME) = 0) then begin
// поток AGGR
if (CompareText(tblname, TABLE_AGGR_NAME) = 0) then begin
// добавляем строку в один из стаканов
if assigned(OrderBookList) then OrderBookList.addrecord(rec.GetValAsLong('isin_id'),
StrToInt64Def(rec.GetValAsString('replID'), 0),
StrToInt64Def(rec.GetValAsString('replRev'), 0),
_StrToFloatDef(rec.GetValAsString('price'), 0),
_StrToFloatDef(rec.GetValAsString('volume'), 0),
rec.GetValAsLong('dir'));
end;
end;
end;
end;
procedure TForm1.StreamDataDeleted(Sender: TObject; var stream, tableName: OleVariant; Id: Int64; var rec: OleVariant);
var strmname, tblname : string;
begin
strmname := string(stream.StreamName);
tblname := string(tableName);
if (CompareText(strmname, STREAM_AGGR_NAME) = 0) then begin
// поток AGGR
if (CompareText(tblname, TABLE_AGGR_NAME) = 0) then begin
// удаляем строку из одного из стаканов
if assigned(OrderBookList) then OrderBookList.delrecord(Id);
end;
end;
end;
procedure TForm1.StreamDatumDeleted(Sender: TObject; var stream, tableName: OleVariant; rev: Int64);
var strmname, tblname : string;
begin
strmname := string(stream.StreamName);
tblname := string(tableName);
if (CompareText(strmname, STREAM_AGGR_NAME) = 0) then begin
// поток AGGR
if (CompareText(tblname, TABLE_AGGR_NAME) = 0) then begin
// удаляем строки из всех стаканов с ревиженом меньше заданного
if assigned(OrderBookList) then OrderBookList.clearbyrev(rev);
// перерисовываем стакан
RedrawOrderBook(false);
end;
end;
end;
procedure TForm1.StreamDataEnd(Sender: TObject; var stream: OleVariant);
var strmname : string;
begin
strmname := string(stream.StreamName);
if (CompareText(strmname, STREAM_AGGR_NAME) = 0) then begin
// если закончился прием изменений потока AGGR, перерисовываем стакан
RedrawOrderBook(false);
end;
end;
procedure TForm1.ConnectButtonClick(Sender: TObject);
begin
// установление соединения по кнопке connect
// при импорте библиотеки типов метод Connect был автоматически переименован в
// Connect1 для того, чтобы избежать пересечения со стандартным методом Connect
// Ole-сервера дельфи
if assigned(fConn) then try
fConn.Connect1;
except
on e: exception do log('Исключение при попытке соединения: %s', [e.message]);
end;
end;
procedure TForm1.DisconnectButtonClick(Sender: TObject);
begin
// разрыв соединения по кнопке disconnect
// при импорте библиотеки типов метод Disconnect был автоматически переименован в
// Disconnect1 для того, чтобы избежать пересечения со стандартным методом Disconnect
// Ole-сервера дельфи
if assigned(fConn) then try
fConn.Disconnect1;
except
on e: exception do log('Исключение при разрыве соединения: %s', [e.message]);
end;
end;
procedure TForm1.log(const alogstr: string);
begin
// вывод информации в LogListBox
if assigned(LogListBox) then with LogListBox.Items do begin
// храним только 50 строк
if (Count > 50) then Delete(Count - 1);
// добавляем строки в начало
Insert(0, formatdatetime('hh:nn:ss.zzz ', fPreciseTime.Now) + alogstr);
end;
end;
procedure TForm1.log(const alogstr: string; const aparams: array of const);
begin
// вывод лога с форматированием строки
log(format(alogstr, aparams));
end;
procedure TForm1.InstrumentComboBoxChange(Sender: TObject);
begin
// переключаем инструмент в стакане
if assigned(Sender) and (Sender is TComboBox) then begin
with TComboBox(Sender) do begin
// если в комбобоксе что-то выбрано, то устанавливаем isin_id для отрисовывания гридом,
// если нет, присваиваем -1
if ItemIndex >= 0 then OrderBookGrid.Tag:= longint(Items.Objects[ItemIndex])
else OrderBookGrid.Tag:= -1;
end;
// принудительно перерисовываем стакан
RedrawOrderBook(true);
end;
end;
procedure TForm1.RedrawOrderBook(forceredraw: boolean);
var itm : tOrderBook;
i : longint;
const bsn : array[boolean] of longint = (0, 2);
// очистка грида
procedure ClearGrid;
var i : longint;
begin
// устанавливаем кол-во строк = 1
OrderBookGrid.RowCount:= 1;
// очищаем ячейки строки
for i:= 0 to OrderBookGrid.ColCount - 1 do OrderBookGrid.Cells[i, 0]:= '';
end;
begin
// если установлен isin_id для отрисовки
if (OrderBookGrid.Tag >= 0) then begin
if assigned(OrderBookList) then begin
// ищем стакан, соответствующий isin_id
itm:= OrderBookList.searchadditem(OrderBookGrid.Tag);
// если он есть и изменился либо принудительная отрисовка
if assigned(itm) and (forceredraw or itm.changed) then with itm do begin
// если стакан не пуст
if Count > 0 then begin
// устанавливаем кол-во строк в гриде
OrderBookGrid.RowCount:= Count;
// заполняем ячейки грида
for i:= 0 to Count - 1 do
with pOrderBookItem(items[i])^ do begin
// заполняем цену
OrderBookGrid.Cells[1, i]:= FloatToStr(price);
// помещаем кол-во справа или слева от цены, в зависимости от buysell
OrderBookGrid.Cells[bsn[(buysell and 1 = 1)], i] := FloatToStr(volume);
// противоположную ячейку очищаем
OrderBookGrid.Cells[bsn[not (buysell and 1 = 1)], i] := '';
end;
end else ClearGrid;
changed:= false;
end;
end;
end else ClearGrid;
end;
initialization
// нужно для корректного перевода из строк, возвращаемых методом GetValAsString, в числа
decimalseparator:= '.';
// инициализируем COM
CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
finalization
CoUnInitialize;
end.
|
unit Main;
interface
uses
System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ExtDlgs, Vcl.Imaging.Jpeg,
//GLScene
GLScene, GLObjects, GLTexture, GLWin32Viewer, GLMaterial, GLCoordinates, GLCrossPlatform,
GLBaseClasses, GLUtils;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
Plane1: TGLPlane;
GLCamera1: TGLCamera;
GLMaterialLibrary1: TGLMaterialLibrary;
Image1: TImage;
Image2: TImage;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
TrackBar1: TTrackBar;
Label4: TLabel;
OpenPictureDialog1: TOpenPictureDialog;
CBClampTex2: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure Image1Click(Sender: TObject);
procedure Image2Click(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure CBClampTex2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
// prepare images to merge in the multitexture
with GLMaterialLibrary1 do begin
Image1.Picture.LoadFromFile('ashwood.jpg');
Materials[0].Material.Texture.Image.Assign(Image1.Picture);
Image2.Picture.LoadFromFile('Flare1.bmp');
Materials[1].Material.Texture.Image.Assign(Image2.Picture);
end;
end;
procedure TForm1.Image1Click(Sender: TObject);
begin
// load a new Image1
if OpenPictureDialog1.Execute then begin
Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
GLMaterialLibrary1.Materials[0].Material.Texture.Image.Assign(Image1.Picture);
end;
end;
procedure TForm1.Image2Click(Sender: TObject);
begin
// load a new Image2
if OpenPictureDialog1.Execute then begin
Image2.Picture.LoadFromFile(OpenPictureDialog1.FileName);
GLMaterialLibrary1.Materials[1].Material.Texture.Image.Assign(Image2.Picture);
end;
end;
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
// adjust scale
with GLMaterialLibrary1.Materials[1].TextureScale do begin
X:=TrackBar1.Position/10;
Y:=TrackBar1.Position/10;
end;
end;
procedure TForm1.CBClampTex2Click(Sender: TObject);
begin
with GLMaterialLibrary1.Materials[1].Material.Texture do
if CBClampTex2.Checked then
TextureWrap:=twNone
else TextureWrap:=twBoth;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 65520,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 39 BackTrack Method
}
program
DegreeBoundedSpanningTree;
const
MaxN = 170 + 1;
var
N, K : Integer;
G : array [1 .. MaxN, 1 .. MaxN] of Integer;
Mark : array [1 .. MaxN] of Boolean;
Q, D, P, M : array [1 .. MaxN] of Integer;
QU, QD : Integer;
I, J : Integer;
F : Text;
TT, C : Longint;
Time : Longint absolute $40:$6C;
procedure Sort(l, r: Integer);
var
i, j, x, y: integer;
begin
i := l; j := r; x := d[m[(l+r) DIV 2]];
repeat
while d[m[i]] < x do i := i + 1;
while x < d[m[j]] do j := j - 1;
if i <= j then
begin
y := m[i]; m[i] := m[j]; m[j] := y;
i := i + 1; j := j - 1;
end;
until i > j;
if l < j then Sort(l, j);
if i < r then Sort(i, r);
end;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N, K);
for I := 2 to N do
begin
for J := 1 to I - 1 do
begin
Read(F, G[I, J]); G[J, I] := G[I, J];
Inc(D[I], G[I, J]); Inc(D[J], G[J, I]);
end;
Readln(F);
end;
Close(F);
end;
procedure NoSolution;
begin
Assign(F, 'output.txt');
ReWrite(F);
Writeln(F, 'No Solution');
Close(F);
Writeln((Time - TT) / 18.2 : 0 : 2, ' ', C);
end;
procedure Found;
begin
Assign(F, 'output.txt');
ReWrite(F);
for I := 1 to N do
if P[I] <> N + 1 then
Writeln(F, M[P[I]], ' ', M[I]);
Close(F);
Writeln((Time - TT) / 18.2 : 0 : 2, ' ', C);
Halt;
end;
procedure BT (KK, II : Integer);
var
I, VV : Integer;
begin
Inc(C);
VV := Q[QD];
if QU > QD then
begin Inc(QD); BT(K - 1, 1); Dec(QD); end;
if (II <= N) and (KK > 0) then
begin
if (P[II] = 0) and (G[M[VV], M[II]] > 0) then
begin
P[II] := VV;
Inc(QU); Q[QU] := II;
BT(KK - 1, II + 1);
Dec(QU);
P[II] := 0;
end;
BT(KK, II + 1);
end;
if QU = N then Found;
end;
procedure Solve;
begin
P[1] := N + 1;
for I := 1 to N do
M[I] := I;
QU := 1; QD := 1; Q[1] := 1;
Sort(1, N);
BT(K, 1);
end;
begin
TT := Time;
ReadInput;
Solve;
NoSolution;
end.
|
Unit UnCondicaoPagamento;
Interface
Uses Classes, UnDadosCR,SQLExpr, tabela, SysUtils;
//classe funcoes
Type TRBFuncoesCondicaoPagamento = class
private
Cadastro : TSQL;
Tabela,
Aux : TSqlQuery;
function RCodCondicaoPagamentoDisponivel : Integer;
function GravaDParcelas(VpaDCondicaoPagamento : TRBDCondicaoPagamento) : String;
procedure CarDParcelas(VpaDCondicaoPagamento : TRBDCondicaoPagamento);
public
constructor cria(VpaBaseDados : TSqlConnection);
destructor destroy;override;
procedure CriaParcelas(VpaDCondicaoPagamento : TRBDCondicaoPagamento);
procedure VerificaPercentuais(VpaDCondicaoPagamento : TRBDCondicaoPagamento);
function GravaDCondicaoPagamento(VpaDCondicaoPagamento : TRBDCondicaoPagamento):string;
procedure CarDCondicaoPagamento(VpaDCondicaoPagamento : TRBDCondicaoPagamento;VpaCodCondicaoPagamento : Integer);
end;
implementation
Uses FunSql, FunNumeros, FunObjeto, Fundata, Constantes, UnSistema;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
eventos da classe TRBFuncoesCondicaoPagamento
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{********************************* cria a classe ********************************}
constructor TRBFuncoesCondicaoPagamento.cria(VpaBaseDados : TSqlConnection);
begin
inherited create;
Cadastro := TSQL.create(nil);
Cadastro.ASQlConnection := VpaBaseDados;
Aux := TSQLQuery.Create(nil);
Aux.SQLConnection := VpaBaseDados;
Tabela := TSQLQuery.Create(nil);
Tabela.SQLConnection := VpaBaseDados;
end;
{******************************************************************************}
destructor TRBFuncoesCondicaoPagamento.destroy;
begin
Cadastro.free;
Aux.free;
Tabela.Free;
inherited;
end;
{******************************************************************************}
procedure TRBFuncoesCondicaoPagamento.CarDParcelas(VpaDCondicaoPagamento: TRBDCondicaoPagamento);
var
VpfDParcela : TRBDParcelaCondicaoPagamento;
begin
AdicionaSQLAbreTabela(Tabela,'Select * from MOVCONDICAOPAGTO '+
' Where I_COD_PAG = '+ IntToStr(VpaDCondicaoPagamento.CodCondicaoPagamento)+
' ORDER BY I_NRO_PAR');
while not Tabela.eof do
begin
VpfDParcela := VpaDCondicaoPagamento.AddParcela;
with VpfDParcela do
begin
NumParcela := Tabela.FieldByName('I_NRO_PAR').AsInteger;
QtdDias := Tabela.FieldByName('I_NUM_DIA').AsInteger;
DiaFixo := Tabela.FieldByName('I_DIA_FIX').AsInteger;
PerParcela := Tabela.FieldByName('N_PER_PAG').AsFloat;
PerAcrescimoDesconto := Tabela.FieldByName('N_PER_CON').AsFloat;
TipAcrescimoDesconto := Tabela.FieldByName('C_CRE_DEB').AsString;
CodFormaPagamento := Tabela.FieldByName('I_COD_FRM').AsInteger;
DatFixa := Tabela.FieldByName('D_DAT_FIX').AsDateTime;
if Tabela.FieldByName('I_DIA_FIX').AsInteger = 100 then
TipoParcela := tpProximoMes
else
if Tabela.FieldByName('I_DIA_FIX').AsInteger <> 0 then
TipoParcela := tpDiaFixo
else
if Tabela.FieldByName('D_DAT_FIX').AsDateTime > MontaData(1,1,1900) then
TipoParcela := tpDataFixa
else
TipoParcela := tpQtdDias;
end;
Tabela.Next;
end;
Tabela.close;
end;
{******************************************************************************}
procedure TRBFuncoesCondicaoPagamento.CarDCondicaoPagamento(VpaDCondicaoPagamento: TRBDCondicaoPagamento;VpaCodCondicaoPagamento : Integer);
begin
AdicionaSQLAbreTabela(Tabela,'Select * from CADCONDICOESPAGTO '+
' Where I_COD_PAG = '+IntToStr(VpaCodCondicaoPagamento));
with VpaDCondicaoPagamento do
begin
CodCondicaoPagamento := VpaCodCondicaoPagamento;
NomCondicaoPagamento := Tabela.FieldByName('C_NOM_PAG').AsString;
QtdParcelas := Tabela.FieldByName('I_QTD_PAR').AsInteger;
end;
CarDParcelas(VpaDCondicaoPagamento);
end;
{******************************************************************************}
function TRBFuncoesCondicaoPagamento.RCodCondicaoPagamentoDisponivel : Integer;
begin
AdicionaSQLAbreTabela(Aux,'Select max(I_COD_PAG) ULTIMO from CADCONDICOESPAGTO ');
Result := aux.FieldByName('ULTIMO').AsInteger +1;
Aux.close;
end;
{******************************************************************************}
procedure TRBFuncoesCondicaoPagamento.CriaParcelas(VpaDCondicaoPagamento : TRBDCondicaoPagamento);
var
VpfLaco : Integer;
VpfTotalPercentual : Double;
VpfDParcela : TRBDParcelaCondicaoPagamento;
begin
VpfTotalPercentual := 0;
FreeTObjectsList(VpaDCondicaoPagamento.Parcelas);
for VpfLaco := 1 to VpaDCondicaoPagamento.QtdParcelas do
begin
VpfDParcela := VpaDCondicaoPagamento.AddParcela;
VpfDParcela.NumParcela := VpfLaco;
VpfDParcela.PerParcela := ArredondaDecimais(100 / VpaDCondicaoPagamento.QtdParcelas,2);
VpfTotalPercentual := VpfTotalPercentual + VpfDParcela.PerParcela;
if VpaDCondicaoPagamento.QtdParcelas = VpfDParcela.NumParcela then
begin
if VpfTotalPercentual < 100 then
VpfDParcela.PerParcela := VpfDParcela.PerParcela + (100 - VpfTotalPercentual)
end;
end;
end;
{******************************************************************************}
procedure TRBFuncoesCondicaoPagamento.VerificaPercentuais(VpaDCondicaoPagamento : TRBDCondicaoPagamento);
var
VpfLaco : Integer;
VpfTotalPercentual : Double;
VpfDPercentual : TRBDParcelaCondicaoPagamento;
begin
VpfTotalPercentual := 0;
for VpfLaco := 0 to VpaDCondicaoPagamento.Parcelas.Count -1 do
begin
VpfDPercentual := TRBDParcelaCondicaoPagamento(VpaDCondicaoPagamento.Parcelas.Items[VpfLaco]);
VpfTotalPercentual := VpfTotalPercentual + VpfDPercentual.PerParcela;
if VpfLaco = VpaDCondicaoPagamento.Parcelas.Count -1 then
begin
if VpfTotalPercentual <> 100 then
VpfDPercentual.PerParcela := VpfDPercentual.PerParcela + (100 - VpfTotalPercentual);
end;
end;
end;
{******************************************************************************}
function TRBFuncoesCondicaoPagamento.GravaDCondicaoPagamento(VpaDCondicaoPagamento : TRBDCondicaoPagamento) : string;
begin
result := '';
AdicionaSQLAbreTabela(Cadastro,'Select * from CADCONDICOESPAGTO '+
' Where I_COD_PAG = '+IntToStr(VpaDCondicaoPagamento.CodCondicaoPagamento));
if VpaDCondicaoPagamento.CodCondicaoPagamento = 0 then
Cadastro.insert
else
Cadastro.edit;
Cadastro.FieldByName('C_NOM_PAG').AsString := VpaDCondicaoPagamento.NomCondicaoPagamento;
Cadastro.FieldByName('I_QTD_PAR').AsInteger := VpaDCondicaoPagamento.QtdParcelas;
Cadastro.FieldByName('D_VAL_CON').AsDateTime := MontaData(1,1,2100);
Cadastro.FieldByName('N_IND_REA').AsInteger := 0;
Cadastro.FieldByName('N_PER_DES').AsInteger := 0;
Cadastro.FieldByName('I_DIA_CAR').AsInteger := 0;
Cadastro.FieldByName('C_GER_CRE').AsString := 'S';
Cadastro.FieldByName('D_ULT_ALT').AsDateTime := DATE;
Cadastro.FieldByName('I_COD_USU').AsInteger := varia.CodigoUsuario;
if VpaDCondicaoPagamento.CodCondicaoPagamento = 0 then
VpaDCondicaoPagamento.CodCondicaoPagamento := RCodCondicaoPagamentoDisponivel;
Cadastro.FieldByName('I_COD_PAG').AsInteger := VpaDCondicaoPagamento.CodCondicaoPagamento;
cadastro.FieldByName('D_ULT_ALT').AsDateTime := Sistema.RDataServidor;
cadastro.post;
result := Cadastro.AMensagemErroGravacao;
Sistema.MarcaTabelaParaImportar('CADCONDICOESPAGTO');
if result = '' then
result := GravaDParcelas(VpaDCondicaoPagamento);
end;
{******************************************************************************}
function TRBFuncoesCondicaoPagamento.GravaDParcelas(VpaDCondicaoPagamento: TRBDCondicaoPagamento): String;
var
VpfDParcela : TRBDParcelaCondicaoPagamento;
VpfLaco : Integer;
begin
ExecutaComandoSql(Aux,'Delete from MOVCONDICAOPAGTO '+
' Where I_COD_PAG = '+IntToStr(VpaDCondicaoPagamento.CodCondicaoPagamento));
AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONDICAOPAGTO '+
' Where I_COD_PAG = 0 AND I_NRO_PAR = 0');
for VpfLaco := 0 to VpaDCondicaoPagamento.Parcelas.Count - 1 do
begin
VpfDParcela := TRBDParcelaCondicaoPagamento(VpaDCondicaoPagamento.Parcelas.Items[VpfLaco]);
Cadastro.insert;
Cadastro.FieldByName('I_COD_PAG').AsInteger := VpaDCondicaoPagamento.CodCondicaoPagamento;
Cadastro.FieldByName('I_NRO_PAR').AsInteger := VpfLaco+1;
case VpfDParcela.TipoParcela of
tpProximoMes:
begin
Cadastro.FieldByName('I_NUM_DIA').AsInteger := 0;
Cadastro.FieldByName('I_DIA_FIX').AsInteger := 100;
end;
tpQtdDias:
begin
Cadastro.FieldByName('I_NUM_DIA').AsInteger := VpfDParcela.QtdDias;
Cadastro.FieldByName('I_DIA_FIX').AsInteger := 0;
end;
tpDiaFixo:
begin
Cadastro.FieldByName('I_NUM_DIA').AsInteger := 0;
Cadastro.FieldByName('I_DIA_FIX').AsInteger := VpfDParcela.DiaFixo;
end;
tpDataFixa:
begin
Cadastro.FieldByName('I_NUM_DIA').AsInteger := 0;
Cadastro.FieldByName('I_DIA_FIX').AsInteger := 0;
Cadastro.FieldByName('D_DAT_FIX').AsDateTime := VpfDParcela.DatFixa;
end;
end;
Cadastro.FieldByName('N_PER_CON').AsFloat := VpfDParcela.PerAcrescimoDesconto;
Cadastro.FieldByName('C_CRE_DEB').AsString := VpfDParcela.TipAcrescimoDesconto;
Cadastro.FieldByName('N_PER_PAG').AsFloat := VpfDParcela.PerParcela;
Cadastro.FieldByName('N_PER_COM').AsFloat := VpfDParcela.PerParcela;
Cadastro.FieldByName('I_TIP_COM').AsInteger := 1;
Cadastro.FieldByName('D_ULT_ALT').AsDateTime := Sistema.RDataServidor;
Cadastro.FieldByName('I_COD_FRM').AsInteger := VpfDParcela.CodFormaPagamento;
cadastro.post;
result := Cadastro.AMensagemErroGravacao;
if Cadastro.AErronaGravacao then
break;
end;
Sistema.MarcaTabelaParaImportar('MOVCONDICAOPAGTO');
cadastro.close;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2015-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
Unit Winapi.MsCTF;
{ TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers.
{ WARN SYMBOL_PLATFORM OFF}
{ WRITEABLECONST ON}
{ VARPROPSETTER ON}
{$IFDEF WIN64}
{$ALIGN 8}
{$ELSE}
{$ALIGN 4}
{$ENDIF}
{$MINENUMSIZE 4}
{$WEAKPACKAGEUNIT}
{$HPPEMIT ''}
{$HPPEMIT '#include <msctf.h>'}
{$HPPEMIT '#include <inputscope.h>'}
{$HPPEMIT ''}
interface
uses
Winapi.Windows, Winapi.ActiveX;
// Text Framework declarations.
const
TF_E_LOCKED = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0500);
{$EXTERNALSYM TF_E_LOCKED}
TF_E_STACKFULL = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0501);
{$EXTERNALSYM TF_E_STACKFULL}
TF_E_NOTOWNEDRANGE = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0502);
{$EXTERNALSYM TF_E_NOTOWNEDRANGE}
TF_E_NOPROVIDER = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0503);
{$EXTERNALSYM TF_E_NOPROVIDER}
TF_E_DISCONNECTED = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0504);
{$EXTERNALSYM TF_E_DISCONNECTED}
TF_E_INVALIDVIEW = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0505);
{$EXTERNALSYM TF_E_INVALIDVIEW}
TF_E_ALREADY_EXISTS = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0506);
{$EXTERNALSYM TF_E_ALREADY_EXISTS}
TF_E_RANGE_NOT_COVERED = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0507);
{$EXTERNALSYM TF_E_RANGE_NOT_COVERED}
TF_E_COMPOSITION_REJECTED = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0508);
{$EXTERNALSYM TF_E_COMPOSITION_REJECTED}
TF_E_EMPTYCONTEXT = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0509);
{$EXTERNALSYM TF_E_EMPTYCONTEXT}
TF_E_INVALIDPOS = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0200);
{$EXTERNALSYM TF_E_INVALIDPOS}
TF_E_NOLOCK = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0201);
{$EXTERNALSYM TF_E_NOLOCK}
TF_E_NOOBJECT = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0202);
{$EXTERNALSYM TF_E_NOOBJECT}
TF_E_NOSERVICE = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0203);
{$EXTERNALSYM TF_E_NOSERVICE}
TF_E_NOINTERFACE = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0204);
{$EXTERNALSYM TF_E_NOINTERFACE}
TF_E_NOSELECTION = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0205);
{$EXTERNALSYM TF_E_NOSELECTION}
TF_E_NOLAYOUT = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0206);
{$EXTERNALSYM TF_E_NOLAYOUT}
TF_E_INVALIDPOINT = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0207);
{$EXTERNALSYM TF_E_INVALIDPOINT}
TF_E_SYNCHRONOUS = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0208);
{$EXTERNALSYM TF_E_SYNCHRONOUS}
TF_E_READONLY = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $0209);
{$EXTERNALSYM TF_E_READONLY}
TF_E_FORMAT = HRESULT((SEVERITY_ERROR shL 31) or (FACILITY_ITF shl 16) or $020a);
{$EXTERNALSYM TF_E_FORMAT}
TF_S_ASYNC = HRESULT((SEVERITY_SUCCESS shl 31) or (FACILITY_ITF shl 16) or $0300);
{$EXTERNALSYM TF_S_ASYNC}
TF_RCM_COMLESS = $00000001;
{$EXTERNALSYM TF_RCM_COMLESS}
TF_RCM_VKEY = $00000002;
{$EXTERNALSYM TF_RCM_VKEY}
TF_RCM_HINT_READING_LENGTH = $00000004;
{$EXTERNALSYM TF_RCM_HINT_READING_LENGTH}
TF_RCM_HINT_COLLISION = $00000008;
{$EXTERNALSYM TF_RCM_HINT_COLLISION}
TF_INVALID_EDIT_COOKIE = 0;
{$EXTERNALSYM TF_INVALID_EDIT_COOKIE}
TKB_ALTERNATES_STANDARD = $00000001;
{$EXTERNALSYM TKB_ALTERNATES_STANDARD}
TKB_ALTERNATES_FOR_AUTOCORRECTION = $00000002;
{$EXTERNALSYM TKB_ALTERNATES_FOR_AUTOCORRECTION}
TKB_ALTERNATES_FOR_PREDICTION = $00000003;
{$EXTERNALSYM TKB_ALTERNATES_FOR_PREDICTION}
TKB_ALTERNATES_AUTOCORRECTION_APPLIED = $00000004;
{$EXTERNALSYM TKB_ALTERNATES_AUTOCORRECTION_APPLIED}
TF_INVALID_GUIDATOM = 0; //TfGuidAtom(0);
{$EXTERNALSYM TF_INVALID_GUIDATOM}
TF_CLIENTID_NULL = 0; //TfClientId(0);
{$EXTERNALSYM TF_CLIENTID_NULL}
TF_TMAE_NOACTIVATETIP = $00000001;
{$EXTERNALSYM TF_TMAE_NOACTIVATETIP}
TF_TMAE_SECUREMODE = $00000002;
{$EXTERNALSYM TF_TMAE_SECUREMODE}
TF_TMAE_UIELEMENTENABLEDONLY = $00000004;
{$EXTERNALSYM TF_TMAE_UIELEMENTENABLEDONLY}
TF_TMAE_COMLESS = $00000008;
{$EXTERNALSYM TF_TMAE_COMLESS}
TF_TMAE_WOW16 = $00000010;
{$EXTERNALSYM TF_TMAE_WOW16}
TF_TMAE_NOACTIVATEKEYBOARDLAYOUT = $00000020;
{$EXTERNALSYM TF_TMAE_NOACTIVATEKEYBOARDLAYOUT}
TF_TMAE_CONSOLE = $00000040;
{$EXTERNALSYM TF_TMAE_CONSOLE}
TF_TMF_NOACTIVATETIP = TF_TMAE_NOACTIVATETIP;
{$EXTERNALSYM TF_TMF_NOACTIVATETIP}
TF_TMF_SECUREMODE = TF_TMAE_SECUREMODE;
{$EXTERNALSYM TF_TMF_SECUREMODE}
TF_TMF_UIELEMENTENABLEDONLY = TF_TMAE_UIELEMENTENABLEDONLY;
{$EXTERNALSYM TF_TMF_UIELEMENTENABLEDONLY}
TF_TMF_COMLESS = TF_TMAE_COMLESS;
{$EXTERNALSYM TF_TMF_COMLESS}
TF_TMF_WOW16 = TF_TMAE_WOW16;
{$EXTERNALSYM TF_TMF_WOW16}
TF_TMF_CONSOLE = TF_TMAE_CONSOLE;
{$EXTERNALSYM TF_TMF_CONSOLE}
TF_TMF_IMMERSIVEMODE = $40000000;
{$EXTERNALSYM TF_TMF_IMMERSIVEMODE}
TF_TMF_ACTIVATED = $80000000;
{$EXTERNALSYM TF_TMF_ACTIVATED}
TF_MOD_ALT = $0001;
{$EXTERNALSYM TF_MOD_ALT}
TF_MOD_CONTROL = $0002;
{$EXTERNALSYM TF_MOD_CONTROL}
TF_MOD_SHIFT = $0004;
{$EXTERNALSYM TF_MOD_SHIFT}
TF_MOD_RALT = $0008;
{$EXTERNALSYM TF_MOD_RALT}
TF_MOD_RCONTROL = $0010;
{$EXTERNALSYM TF_MOD_RCONTROL}
TF_MOD_RSHIFT = $0020;
{$EXTERNALSYM TF_MOD_RSHIFT}
TF_MOD_LALT = $0040;
{$EXTERNALSYM TF_MOD_LALT}
TF_MOD_LCONTROL = $0080;
{$EXTERNALSYM TF_MOD_LCONTROL}
TF_MOD_LSHIFT = $0100;
{$EXTERNALSYM TF_MOD_LSHIFT}
TF_MOD_ON_KEYUP = $0200;
{$EXTERNALSYM TF_MOD_ON_KEYUP}
TF_MOD_IGNORE_ALL_MODIFIER = $0400;
{$EXTERNALSYM TF_MOD_IGNORE_ALL_MODIFIER}
TF_US_HIDETIPUI = $00000001;
{$EXTERNALSYM TF_US_HIDETIPUI}
TF_DISABLE_SPEECH = $00000001;
{$EXTERNALSYM TF_DISABLE_SPEECH}
TF_DISABLE_DICTATION = $00000002;
{$EXTERNALSYM TF_DISABLE_DICTATION}
TF_DISABLE_COMMANDING = $00000004;
{$EXTERNALSYM TF_DISABLE_COMMANDING}
TF_PROCESS_ATOM = '_CTF_PROCESS_ATOM_';
{$EXTERNALSYM TF_PROCESS_ATOM}
TF_ENABLE_PROCESS_ATOM = '_CTF_ENABLE_PROCESS_ATOM_';
{$EXTERNALSYM TF_ENABLE_PROCESS_ATOM}
TF_INVALID_UIELEMENTID = DWORD(-1);
{$EXTERNALSYM TF_INVALID_UIELEMENTID}
TF_CLUIE_DOCUMENTMGR = $00000001;
{$EXTERNALSYM TF_CLUIE_DOCUMENTMGR}
TF_CLUIE_COUNT = $00000002;
{$EXTERNALSYM TF_CLUIE_COUNT}
TF_CLUIE_SELECTION = $00000004;
{$EXTERNALSYM TF_CLUIE_SELECTION}
TF_CLUIE_STRING = $00000008;
{$EXTERNALSYM TF_CLUIE_STRING}
TF_CLUIE_PAGEINDEX = $00000010;
{$EXTERNALSYM TF_CLUIE_PAGEINDEX}
TF_CLUIE_CURRENTPAGE = $00000020;
{$EXTERNALSYM TF_CLUIE_CURRENTPAGE}
TF_RIUIE_CONTEXT = $00000001;
{$EXTERNALSYM TF_RIUIE_CONTEXT}
TF_RIUIE_STRING = $00000002;
{$EXTERNALSYM TF_RIUIE_STRING}
TF_RIUIE_MAXREADINGSTRINGLENGTH = $00000004;
{$EXTERNALSYM TF_RIUIE_MAXREADINGSTRINGLENGTH}
TF_RIUIE_ERRORINDEX = $00000008;
{$EXTERNALSYM TF_RIUIE_ERRORINDEX}
TF_RIUIE_VERTICALORDER = $00000010;
{$EXTERNALSYM TF_RIUIE_VERTICALORDER}
TF_CONVERSIONMODE_ALPHANUMERIC = $0000;
{$EXTERNALSYM TF_CONVERSIONMODE_ALPHANUMERIC}
TF_CONVERSIONMODE_NATIVE = $0001;
{$EXTERNALSYM TF_CONVERSIONMODE_NATIVE}
TF_CONVERSIONMODE_KATAKANA = $0002;
{$EXTERNALSYM TF_CONVERSIONMODE_KATAKANA}
TF_CONVERSIONMODE_FULLSHAPE = $0008;
{$EXTERNALSYM TF_CONVERSIONMODE_FULLSHAPE}
TF_CONVERSIONMODE_ROMAN = $0010;
{$EXTERNALSYM TF_CONVERSIONMODE_ROMAN}
TF_CONVERSIONMODE_CHARCODE = $0020;
{$EXTERNALSYM TF_CONVERSIONMODE_CHARCODE}
TF_CONVERSIONMODE_SOFTKEYBOARD = $0080;
{$EXTERNALSYM TF_CONVERSIONMODE_SOFTKEYBOARD}
TF_CONVERSIONMODE_NOCONVERSION = $0100;
{$EXTERNALSYM TF_CONVERSIONMODE_NOCONVERSION}
TF_CONVERSIONMODE_EUDC = $0200;
{$EXTERNALSYM TF_CONVERSIONMODE_EUDC}
TF_CONVERSIONMODE_SYMBOL = $0400;
{$EXTERNALSYM TF_CONVERSIONMODE_SYMBOL}
TF_CONVERSIONMODE_FIXED = $0800;
{$EXTERNALSYM TF_CONVERSIONMODE_FIXED}
TF_SENTENCEMODE_NONE = $0000;
{$EXTERNALSYM TF_SENTENCEMODE_NONE}
TF_SENTENCEMODE_PLAURALCLAUSE = $0001;
{$EXTERNALSYM TF_SENTENCEMODE_PLAURALCLAUSE}
TF_SENTENCEMODE_SINGLECONVERT = $0002;
{$EXTERNALSYM TF_SENTENCEMODE_SINGLECONVERT}
TF_SENTENCEMODE_AUTOMATIC = $0004;
{$EXTERNALSYM TF_SENTENCEMODE_AUTOMATIC}
TF_SENTENCEMODE_PHRASEPREDICT = $0008;
{$EXTERNALSYM TF_SENTENCEMODE_PHRASEPREDICT}
TF_SENTENCEMODE_CONVERSATION = $0010;
{$EXTERNALSYM TF_SENTENCEMODE_CONVERSATION}
TF_TRANSITORYEXTENSION_NONE = $0000;
{$EXTERNALSYM TF_TRANSITORYEXTENSION_NONE}
TF_TRANSITORYEXTENSION_FLOATING = $0001;
{$EXTERNALSYM TF_TRANSITORYEXTENSION_FLOATING}
TF_TRANSITORYEXTENSION_ATSELECTION = $0002;
{$EXTERNALSYM TF_TRANSITORYEXTENSION_ATSELECTION}
TF_PROFILETYPE_INPUTPROCESSOR = $0001;
{$EXTERNALSYM TF_PROFILETYPE_INPUTPROCESSOR}
TF_PROFILETYPE_KEYBOARDLAYOUT = $0002;
{$EXTERNALSYM TF_PROFILETYPE_KEYBOARDLAYOUT}
TF_RIP_FLAG_FREEUNUSEDLIBRARIES = $00000001;
{$EXTERNALSYM TF_RIP_FLAG_FREEUNUSEDLIBRARIES}
TF_IPP_FLAG_ACTIVE = $00000001;
{$EXTERNALSYM TF_IPP_FLAG_ACTIVE}
TF_IPP_FLAG_ENABLED = $00000002;
{$EXTERNALSYM TF_IPP_FLAG_ENABLED}
TF_IPP_FLAG_SUBSTITUTEDBYINPUTPROCESSOR = $00000004;
{$EXTERNALSYM TF_IPP_FLAG_SUBSTITUTEDBYINPUTPROCESSOR}
TF_IPP_CAPS_DISABLEONTRANSITORY = $00000001;
{$EXTERNALSYM TF_IPP_CAPS_DISABLEONTRANSITORY}
TF_IPP_CAPS_SECUREMODESUPPORT = $00000002;
{$EXTERNALSYM TF_IPP_CAPS_SECUREMODESUPPORT}
TF_IPP_CAPS_UIELEMENTENABLED = $00000004;
{$EXTERNALSYM TF_IPP_CAPS_UIELEMENTENABLED}
TF_IPP_CAPS_COMLESSSUPPORT = $00000008;
{$EXTERNALSYM TF_IPP_CAPS_COMLESSSUPPORT}
TF_IPP_CAPS_WOW16SUPPORT = $00000010;
{$EXTERNALSYM TF_IPP_CAPS_WOW16SUPPORT}
TF_IPP_CAPS_IMMERSIVESUPPORT = $00010000;
{$EXTERNALSYM TF_IPP_CAPS_IMMERSIVESUPPORT}
TF_IPP_CAPS_SYSTRAYSUPPORT = $00020000;
{$EXTERNALSYM TF_IPP_CAPS_SYSTRAYSUPPORT}
TF_IPPMF_FORPROCESS = $10000000;
{$EXTERNALSYM TF_IPPMF_FORPROCESS}
TF_IPPMF_FORSESSION = $20000000;
{$EXTERNALSYM TF_IPPMF_FORSESSION}
TF_IPPMF_FORSYSTEMALL = $40000000;
{$EXTERNALSYM TF_IPPMF_FORSYSTEMALL}
TF_IPPMF_ENABLEPROFILE = $00000001;
{$EXTERNALSYM TF_IPPMF_ENABLEPROFILE}
TF_IPPMF_DISABLEPROFILE = $00000002;
{$EXTERNALSYM TF_IPPMF_DISABLEPROFILE}
TF_IPPMF_DONTCARECURRENTINPUTLANGUAGE = $00000004;
{$EXTERNALSYM TF_IPPMF_DONTCARECURRENTINPUTLANGUAGE}
TF_RP_HIDDENINSETTINGUI = $00000002;
{$EXTERNALSYM TF_RP_HIDDENINSETTINGUI}
TF_RP_LOCALPROCESS = $00000004;
{$EXTERNALSYM TF_RP_LOCALPROCESS}
TF_RP_LOCALTHREAD = $00000008;
{$EXTERNALSYM TF_RP_LOCALTHREAD}
TF_RP_SUBITEMINSETTINGUI = $00000010;
{$EXTERNALSYM TF_RP_SUBITEMINSETTINGUI}
TF_URP_ALLPROFILES = $00000002;
{$EXTERNALSYM TF_URP_ALLPROFILES}
TF_URP_LOCALPROCESS = $00000004;
{$EXTERNALSYM TF_URP_LOCALPROCESS}
TF_URP_LOCALTHREAD = $00000008;
{$EXTERNALSYM TF_URP_LOCALTHREAD}
TF_IPSINK_FLAG_ACTIVE = $0001;
{$EXTERNALSYM TF_IPSINK_FLAG_ACTIVE}
//============================================================================================================================
// ************************************************************************ //
// Errors:
// Hint: Symbol 'type' renamed to 'type_'
// Cmdline:
// tlibimp -P -Hs- -Hr- -Fe- msctf.tlb
// ************************************************************************ //
const
IID_ITfThreadMgrEventSink: TGUID = '{AA80E80E-2021-11D2-93E0-0060B067B86E}';
IID_ITfDocumentMgr: TGUID = '{AA80E7F4-2021-11D2-93E0-0060B067B86E}';
IID_ITfContext: TGUID = '{AA80E7FD-2021-11D2-93E0-0060B067B86E}';
IID_ITfEditSession: TGUID = '{AA80E803-2021-11D2-93E0-0060B067B86E}';
IID_ITfRange: TGUID = '{AA80E7FF-2021-11D2-93E0-0060B067B86E}';
IID_ISequentialStream: TGUID = '{0C733A30-2A1C-11CE-ADE5-00AA0044773D}';
IID_ITfContextView: TGUID = '{2433BF8E-0F9B-435C-BA2C-180611978C30}';
IID_IEnumTfContextViews: TGUID = '{F0C0F8DD-CF38-44E1-BB0F-68CF0D551C78}';
IID_ITfReadOnlyProperty: TGUID = '{17D49A3D-F8B8-4B2F-B254-52319DD64C53}';
IID_ITfProperty: TGUID = '{E2449660-9542-11D2-BF46-00105A2799B5}';
IID_IEnumTfRanges: TGUID = '{F99D3F40-8E32-11D2-BF46-00105A2799B5}';
IID_ITfPropertyStore: TGUID = '{6834B120-88CB-11D2-BF45-00105A2799B5}';
IID_IEnumTfProperties: TGUID = '{19188CB0-ACA9-11D2-AFC5-00105A2799B5}';
IID_ITfRangeBackup: TGUID = '{463A506D-6992-49D2-9B88-93D55E70BB16}';
IID_IEnumTfContexts: TGUID = '{8F1A7EA6-1654-4502-A86E-B2902344D507}';
IID_ITfTextInputProcessor: TGUID = '{AA80E7F7-2021-11D2-93E0-0060B067B86E}';
IID_ITfThreadMgr: TGUID = '{AA80E801-2021-11D2-93E0-0060B067B86E}';
IID_IEnumTfDocumentMgrs: TGUID = '{AA80E808-2021-11D2-93E0-0060B067B86E}';
IID_ITfFunctionProvider: TGUID = '{101D6610-0990-11D3-8DF0-00105A2799B5}';
IID_IEnumTfFunctionProviders: TGUID = '{E4B24DB0-0990-11D3-8DF0-00105A2799B5}';
IID_ITfCompartmentMgr: TGUID = '{7DCF57AC-18AD-438B-824D-979BFFB74B7C}';
IID_ITfCompartment: TGUID = '{BB08F7A9-607A-4384-8623-056892B64371}';
IID_ITfRangeACP: TGUID = '{057A6296-029B-4154-B79A-0D461D4EA94C}';
IID_ITfPersistentPropertyLoaderACP: TGUID = '{4EF89150-0807-11D3-8DF0-00105A2799B5}';
IID_ITfKeyEventSink: TGUID = '{AA80E7F5-2021-11D2-93E0-0060B067B86E}';
IID_ITfSource: TGUID = '{4EA48A35-60AE-446F-8FD6-E6A8D82459F7}';
IID_ITfMouseSink: TGUID = '{A1ADAAA2-3A24-449D-AC96-5183E7F5C217}';
IID_IEnumTfLanguageProfiles: TGUID = '{3D61BF11-AC5F-42C8-A4CB-931BCC28C744}';
IID_ITfUIElement: TGUID = '{EA1EA137-19DF-11D7-A6D2-00065B84435C}';
IID_IEnumTfUIElements: TGUID = '{887AA91E-ACBA-4931-84DA-3C5208CF543F}';
IID_IEnumTfInputProcessorProfiles: TGUID = '{71C6E74D-0F28-11D8-A82A-00065B84435C}';
IID_ITfThreadMgrEx: TGUID = '{3E90ADE3-7594-4CB0-BB58-69628F5F458C}';
IID_ITfThreadMgr2: TGUID = '{0AB198EF-6477-4EE8-8812-6780EDB82D5E}';
IID_ITfConfigureSystemKeystrokeFeed: TGUID = '{0D2C969A-BC9C-437C-84EE-951C49B1A764}';
IID_ITfCompositionView: TGUID = '{D7540241-F9A1-4364-BEFC-DBCD2C4395B7}';
IID_IEnumITfCompositionView: TGUID = '{5EFD22BA-7838-46CB-88E2-CADB14124F8F}';
IID_ITfComposition: TGUID = '{20168D64-5A8F-4A5A-B7BD-CFA29F4D0FD9}';
IID_ITfCompositionSink: TGUID = '{A781718C-579A-4B15-A280-32B8577ACC5E}';
IID_ITfContextComposition: TGUID = '{D40C8AAE-AC92-4FC7-9A11-0EE0E23AA39B}';
IID_ITfContextOwnerCompositionServices: TGUID = '{86462810-593B-4916-9764-19C08E9CE110}';
IID_ITfContextOwnerCompositionSink: TGUID = '{5F20AA40-B57A-4F34-96AB-3576F377CC79}';
IID_ITfQueryEmbedded: TGUID = '{0FAB9BDB-D250-4169-84E5-6BE118FDD7A8}';
IID_ITfInsertAtSelection: TGUID = '{55CE16BA-3014-41C1-9CEB-FADE1446AC6C}';
IID_ITfCleanupContextSink: TGUID = '{01689689-7ACB-4E9B-AB7C-7EA46B12B522}';
IID_ITfCleanupContextDurationSink: TGUID = '{45C35144-154E-4797-BED8-D33AE7BF8794}';
IID_IEnumTfPropertyValue: TGUID = '{8ED8981B-7C10-4D7D-9FB3-AB72E9C75F72}';
IID_ITfMouseTracker: TGUID = '{09D146CD-A544-4132-925B-7AFA8EF322D0}';
IID_ITfMouseTrackerACP: TGUID = '{3BDD78E2-C16E-47FD-B883-CE6FACC1A208}';
IID_ITfEditRecord: TGUID = '{42D4D099-7C1A-4A89-B836-6C6F22160DF0}';
IID_ITfTextEditSink: TGUID = '{8127D409-CCD3-4683-967A-B43D5B482BF7}';
IID_ITfTextLayoutSink: TGUID = '{2AF2D06A-DD5B-4927-A0B4-54F19C91FADE}';
IID_ITfStatusSink: TGUID = '{6B7D8D73-B267-4F69-B32E-1CA321CE4F45}';
IID_ITfEditTransactionSink: TGUID = '{708FBF70-B520-416B-B06C-2C41AB44F8BA}';
IID_ITfContextOwner: TGUID = '{AA80E80C-2021-11D2-93E0-0060B067B86E}';
IID_ITfContextOwnerServices: TGUID = '{B23EB630-3E1C-11D3-A745-0050040AB407}';
IID_ITfContextKeyEventSink: TGUID = '{0552BA5D-C835-4934-BF50-846AAA67432F}';
IID_ITextStoreACPServices: TGUID = '{AA80E901-2021-11D2-93E0-0060B067B86E}';
IID_ITfCreatePropertyStore: TGUID = '{2463FBF0-B0AF-11D2-AFC5-00105A2799B5}';
IID_ITfCompartmentEventSink: TGUID = '{743ABD5F-F26D-48DF-8CC5-238492419B64}';
IID_ITfFunction: TGUID = '{DB593490-098F-11D3-8DF0-00105A2799B5}';
IID_ITfInputProcessorProfiles: TGUID = '{1F02B6C5-7842-4EE6-8A0B-9A24183A95CA}';
IID_ITfInputProcessorProfilesEx: TGUID = '{892F230F-FE00-4A41-A98E-FCD6DE0D35EF}';
IID_ITfInputProcessorProfileSubstituteLayout: TGUID = '{4FD67194-1002-4513-BFF2-C0DDF6258552}';
IID_ITfActiveLanguageProfileNotifySink: TGUID = '{B246CB75-A93E-4652-BF8C-B3FE0CFD7E57}';
IID_ITfLanguageProfileNotifySink: TGUID = '{43C9FE15-F494-4C17-9DE2-B8A4AC350AA8}';
IID_ITfInputProcessorProfileMgr: TGUID = '{71C6E74C-0F28-11D8-A82A-00065B84435C}';
IID_ITfInputProcessorProfileActivationSink: TGUID = '{71C6E74E-0F28-11D8-A82A-00065B84435C}';
IID_ITfKeystrokeMgr: TGUID = '{AA80E7F0-2021-11D2-93E0-0060B067B86E}';
IID_ITfKeyTraceEventSink: TGUID = '{1CD4C13B-1C36-4191-A70A-7F3E611F367D}';
IID_ITfPreservedKeyNotifySink: TGUID = '{6F77C993-D2B1-446E-853E-5912EFC8A286}';
IID_ITfMessagePump: TGUID = '{8F1B8AD8-0B6B-4874-90C5-BD76011E8F7C}';
IID_ITfThreadFocusSink: TGUID = '{C0F1DB0C-3A20-405C-A303-96B6010A885F}';
IID_ITfTextInputProcessorEx: TGUID = '{6E4E2102-F9CD-433D-B496-303CE03A6507}';
IID_ITfClientId: TGUID = '{D60A7B49-1B9F-4BE2-B702-47E9DC05DEC3}';
IID_ITfDisplayAttributeInfo: TGUID = '{70528852-2F26-4AEA-8C96-215150578932}';
IID_IEnumTfDisplayAttributeInfo: TGUID = '{7CEF04D7-CB75-4E80-A7AB-5F5BC7D332DE}';
IID_ITfDisplayAttributeProvider: TGUID = '{FEE47777-163C-4769-996A-6E9C50AD8F54}';
IID_ITfDisplayAttributeMgr: TGUID = '{8DED7393-5DB1-475C-9E71-A39111B0FF67}';
IID_ITfDisplayAttributeNotifySink: TGUID = '{AD56F402-E162-4F25-908F-7D577CF9BDA9}';
IID_ITfCategoryMgr: TGUID = '{C3ACEFB5-F69D-4905-938F-FCADCF4BE830}';
IID_ITfSourceSingle: TGUID = '{73131F9C-56A9-49DD-B0EE-D046633F7528}';
IID_ITfUIElementMgr: TGUID = '{EA1EA135-19DF-11D7-A6D2-00065B84435C}';
IID_ITfUIElementSink: TGUID = '{EA1EA136-19DF-11D7-A6D2-00065B84435C}';
IID_ITfCandidateListUIElement: TGUID = '{EA1EA138-19DF-11D7-A6D2-00065B84435C}';
IID_ITfCandidateListUIElementBehavior: TGUID = '{85FAD185-58CE-497A-9460-355366B64B9A}';
IID_ITfReadingInformationUIElement: TGUID = '{EA1EA139-19DF-11D7-A6D2-00065B84435C}';
IID_ITfTransitoryExtensionUIElement: TGUID = '{858F956A-972F-42A2-A2F2-0321E1ABE209}';
IID_ITfTransitoryExtensionSink: TGUID = '{A615096F-1C57-4813-8A15-55EE6E5A839C}';
IID_ITfToolTipUIElement: TGUID = '{52B18B5C-555D-46B2-B00A-FA680144FBDB}';
IID_ITfReverseConversionList: TGUID = '{151D69F0-86F4-4674-B721-56911E797F47}';
IID_ITfReverseConversion: TGUID = '{A415E162-157D-417D-8A8C-0AB26C7D2781}';
IID_ITfReverseConversionMgr: TGUID = '{B643C236-C493-41B6-ABB3-692412775CC4}';
// *********************************************************************//
// Declaration of Enumerations defined in Type Library
// *********************************************************************//
type
TfActiveSelEnd = (
TF_AE_NONE = $00000000,
TF_AE_START = $00000001,
TF_AE_END = $00000002
);
{$EXTERNALSYM TfActiveSelEnd}
TfAnchor = (
TF_ANCHOR_START = $00000000,
TF_ANCHOR_END = $00000001
);
{$EXTERNALSYM TfAnchor}
TfShiftDir = (
TF_SD_BACKWARD = $00000000,
TF_SD_FORWARD = $00000001
);
{$EXTERNALSYM TfShiftDir}
TfGravity = (
TF_GRAVITY_BACKWARD = $00000000,
TF_GRAVITY_FORWARD = $00000001
);
{$EXTERNALSYM TfGravity}
TfLayoutCode = (
TF_LC_CREATE = $00000000,
TF_LC_CHANGE = $00000001,
TF_LC_DESTROY = $00000002
);
{$EXTERNALSYM TfLayoutCode}
TF_DA_LINESTYLE = (
TF_LS_NONE = $00000000,
TF_LS_SOLID = $00000001,
TF_LS_DOT = $00000002,
TF_LS_DASH = $00000003,
TF_LS_SQUIGGLE = $00000004
);
{$EXTERNALSYM TF_DA_LINESTYLE}
TF_DA_COLORTYPE = (
TF_CT_NONE = $00000000,
TF_CT_SYSCOLOR = $00000001,
TF_CT_COLORREF = $00000002
);
{$EXTERNALSYM TF_DA_COLORTYPE}
TF_DA_ATTR_INFO = (
TF_ATTR_INPUT = $00000000,
TF_ATTR_TARGET_CONVERTED = $00000001,
TF_ATTR_CONVERTED = $00000002,
TF_ATTR_TARGET_NOTCONVERTED = $00000003,
TF_ATTR_INPUT_ERROR = $00000004,
TF_ATTR_FIXEDCONVERTED = $00000005,
TF_ATTR_OTHER = -1 // $FFFFFFFF
);
{$EXTERNALSYM TF_DA_ATTR_INFO}
// *********************************************************************//
// Forward declaration of types defined in TypeLibrary
// *********************************************************************//
ITfThreadMgrEventSink = interface;
ITfDocumentMgr = interface;
ITfContext = interface;
ITfEditSession = interface;
ITfRange = interface;
ISequentialStream = interface;
ITfContextView = interface;
IEnumTfContextViews = interface;
ITfReadOnlyProperty = interface;
ITfProperty = interface;
IEnumTfRanges = interface;
ITfPropertyStore = interface;
IEnumTfProperties = interface;
ITfRangeBackup = interface;
IEnumTfContexts = interface;
ITfTextInputProcessor = interface;
ITfThreadMgr = interface;
IEnumTfDocumentMgrs = interface;
ITfFunctionProvider = interface;
IEnumTfFunctionProviders = interface;
ITfCompartmentMgr = interface;
ITfCompartment = interface;
ITfRangeACP = interface;
ITfPersistentPropertyLoaderACP = interface;
ITfKeyEventSink = interface;
ITfSource = interface;
ITfMouseSink = interface;
IEnumTfLanguageProfiles = interface;
ITfUIElement = interface;
IEnumTfUIElements = interface;
IEnumTfInputProcessorProfiles = interface;
ITfThreadMgrEx = interface;
ITfThreadMgr2 = interface;
ITfConfigureSystemKeystrokeFeed = interface;
ITfCompositionView = interface;
IEnumITfCompositionView = interface;
ITfComposition = interface;
ITfCompositionSink = interface;
ITfContextComposition = interface;
ITfContextOwnerCompositionServices = interface;
ITfContextOwnerCompositionSink = interface;
ITfQueryEmbedded = interface;
ITfInsertAtSelection = interface;
ITfCleanupContextSink = interface;
ITfCleanupContextDurationSink = interface;
IEnumTfPropertyValue = interface;
ITfMouseTracker = interface;
ITfMouseTrackerACP = interface;
ITfEditRecord = interface;
ITfTextEditSink = interface;
ITfTextLayoutSink = interface;
ITfStatusSink = interface;
ITfEditTransactionSink = interface;
ITfContextOwner = interface;
ITfContextOwnerServices = interface;
ITfContextKeyEventSink = interface;
ITextStoreACPServices = interface;
ITfCreatePropertyStore = interface;
ITfCompartmentEventSink = interface;
ITfFunction = interface;
ITfInputProcessorProfiles = interface;
ITfInputProcessorProfilesEx = interface;
ITfInputProcessorProfileSubstituteLayout = interface;
ITfActiveLanguageProfileNotifySink = interface;
ITfLanguageProfileNotifySink = interface;
ITfInputProcessorProfileMgr = interface;
ITfInputProcessorProfileActivationSink = interface;
ITfKeystrokeMgr = interface;
ITfKeyTraceEventSink = interface;
ITfPreservedKeyNotifySink = interface;
ITfMessagePump = interface;
ITfThreadFocusSink = interface;
ITfTextInputProcessorEx = interface;
ITfClientId = interface;
ITfDisplayAttributeInfo = interface;
IEnumTfDisplayAttributeInfo = interface;
ITfDisplayAttributeProvider = interface;
ITfDisplayAttributeMgr = interface;
ITfDisplayAttributeNotifySink = interface;
ITfCategoryMgr = interface;
ITfSourceSingle = interface;
ITfUIElementMgr = interface;
ITfUIElementSink = interface;
ITfCandidateListUIElement = interface;
ITfCandidateListUIElementBehavior = interface;
ITfReadingInformationUIElement = interface;
ITfTransitoryExtensionUIElement = interface;
ITfTransitoryExtensionSink = interface;
ITfToolTipUIElement = interface;
ITfReverseConversionList = interface;
ITfReverseConversion = interface;
ITfReverseConversionMgr = interface;
// *********************************************************************//
// Declaration of structures, unions and aliases.
// *********************************************************************//
PPGUID = ^PGUID;
PPWord = ^PWord;
TfClientId = LongWord;
{$EXTERNALSYM TfClientId}
TfEditCookie = LongWord;
{$EXTERNALSYM TfEditCookie}
TF_HALTCOND = record
pHaltRange: ITfRange;
aHaltPos: TfAnchor;
dwFlags: LongWord;
end {$IFDEF CPUX64} align 8 {$ENDIF};
{$EXTERNALSYM TF_HALTCOND}
TF_SELECTIONSTYLE = record
ase: TfActiveSelEnd;
fInterimChar: Integer;
end;
{$EXTERNALSYM TF_SELECTIONSTYLE}
TF_SELECTION = record
range: ITfRange;
style: TF_SELECTIONSTYLE;
end {$IFDEF CPUX64} align 8 {$ENDIF};
{$EXTERNALSYM TF_SELECTION}
TS_STATUS = record
dwDynamicFlags: LongWord;
dwStaticFlags: LongWord;
end;
{$EXTERNALSYM TS_STATUS}
TF_STATUS = TS_STATUS;
{$EXTERNALSYM TF_STATUS}
TF_PERSISTENT_PROPERTY_HEADER_ACP = record
guidType: TGUID;
ichStart: Integer;
cch: Integer;
cb: LongWord;
dwPrivate: LongWord;
clsidTIP: TGUID;
end;
{$EXTERNALSYM TF_PERSISTENT_PROPERTY_HEADER_ACP}
TF_LANGUAGEPROFILE = record
clsid: TGUID;
langid: Word;
catid: TGUID;
fActive: Integer;
guidProfile: TGUID;
end;
{$EXTERNALSYM TF_LANGUAGEPROFILE}
TF_INPUTPROCESSORPROFILE = record
dwProfileType: LongWord;
langid: Word;
clsid: TGUID;
guidProfile: TGUID;
catid: TGUID;
hklSubstitute: HKL;
dwCaps: LongWord;
HKL: HKL;
dwFlags: LongWord;
end;
{$EXTERNALSYM TF_INPUTPROCESSORPROFILE}
TfGuidAtom = LongWord;
{$EXTERNALSYM TfGuidAtom}
{$ALIGN 8}
TF_PROPERTYVAL = record
guidId: TGUID;
varValue: OleVariant;
end;
{$EXTERNALSYM TF_PROPERTYVAL}
{$ALIGN 4}
TF_PRESERVEDKEY = record
uVKey: SYSUINT;
uModifiers: SYSUINT;
end;
{$EXTERNALSYM TF_PRESERVEDKEY}
TF_DA_COLOR = record
type_: TF_DA_COLORTYPE;
case Integer of
0: (nIndex: SYSINT);
1: (cr: TColorRef);
end;
{$EXTERNALSYM TF_DA_COLOR}
TF_DISPLAYATTRIBUTE = record
crText: TF_DA_COLOR;
crBk: TF_DA_COLOR;
lsStyle: TF_DA_LINESTYLE;
fBoldLine: Integer;
crLine: TF_DA_COLOR;
bAttr: TF_DA_ATTR_INFO;
end;
{$EXTERNALSYM TF_DISPLAYATTRIBUTE}
// *********************************************************************//
// Interface: ITfThreadMgrEventSink
// Flags: (0)
// GUID: {AA80E80E-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITfThreadMgrEventSink = interface(IUnknown)
['{AA80E80E-2021-11D2-93E0-0060B067B86E}']
function OnInitDocumentMgr(const pdim: ITfDocumentMgr): HResult; stdcall;
function OnUninitDocumentMgr(const pdim: ITfDocumentMgr): HResult; stdcall;
function OnSetFocus(const pdimFocus: ITfDocumentMgr; const pdimPrevFocus: ITfDocumentMgr): HResult; stdcall;
function OnPushContext(const pic: ITfContext): HResult; stdcall;
function OnPopContext(const pic: ITfContext): HResult; stdcall;
end;
{$EXTERNALSYM ITfThreadMgrEventSink}
// *********************************************************************//
// Interface: ITfDocumentMgr
// Flags: (0)
// GUID: {AA80E7F4-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITfDocumentMgr = interface(IUnknown)
['{AA80E7F4-2021-11D2-93E0-0060B067B86E}']
function CreateContext(tidOwner: TfClientId; dwFlags: LongWord; const punk: IUnknown;
out ppic: ITfContext; out pecTextStore: TfEditCookie): HResult; stdcall;
function Push(const pic: ITfContext): HResult; stdcall;
function Pop(dwFlags: LongWord): HResult; stdcall;
function GetTop(out ppic: ITfContext): HResult; stdcall;
function GetBase(out ppic: ITfContext): HResult; stdcall;
function EnumContexts(out ppenum: IEnumTfContexts): HResult; stdcall;
end;
{$EXTERNALSYM ITfDocumentMgr}
// *********************************************************************//
// Interface: ITfContext
// Flags: (0)
// GUID: {AA80E7FD-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITfContext = interface(IUnknown)
['{AA80E7FD-2021-11D2-93E0-0060B067B86E}']
function RequestEditSession(tid: TfClientId; const pes: ITfEditSession; dwFlags: LongWord;
out phrSession: HResult): HResult; stdcall;
function InWriteSession(tid: TfClientId; out pfWriteSession: Integer): HResult; stdcall;
function GetSelection(ec: TfEditCookie; ulIndex: LongWord; ulCount: LongWord;
out pSelection: TF_SELECTION; out pcFetched: LongWord): HResult; stdcall;
function SetSelection(ec: TfEditCookie; ulCount: LongWord; var pSelection: TF_SELECTION): HResult; stdcall;
function GetStart(ec: TfEditCookie; out ppStart: ITfRange): HResult; stdcall;
function GetEnd(ec: TfEditCookie; out ppEnd: ITfRange): HResult; stdcall;
function GetActiveView(out ppView: ITfContextView): HResult; stdcall;
function EnumViews(out ppenum: IEnumTfContextViews): HResult; stdcall;
function GetStatus(out pdcs: TF_STATUS): HResult; stdcall;
function GetProperty(var guidProp: TGUID; out ppProp: ITfProperty): HResult; stdcall;
function GetAppProperty(var guidProp: TGUID; out ppProp: ITfReadOnlyProperty): HResult; stdcall;
function TrackProperties(prgProp: PPGUID; cProp: LongWord; prgAppProp: PPGUID;
cAppProp: LongWord; out ppProperty: ITfReadOnlyProperty): HResult; stdcall;
function EnumProperties(out ppenum: IEnumTfProperties): HResult; stdcall;
function GetDocumentMgr(out ppDm: ITfDocumentMgr): HResult; stdcall;
function CreateRangeBackup(ec: TfEditCookie; const pRange: ITfRange;
out ppBackup: ITfRangeBackup): HResult; stdcall;
end;
{$EXTERNALSYM ITfContext}
// *********************************************************************//
// Interface: ITfEditSession
// Flags: (0)
// GUID: {AA80E803-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITfEditSession = interface(IUnknown)
['{AA80E803-2021-11D2-93E0-0060B067B86E}']
function DoEditSession(ec: TfEditCookie): HResult; stdcall;
end;
{$EXTERNALSYM ITfEditSession}
// *********************************************************************//
// Interface: ITfRange
// Flags: (0)
// GUID: {AA80E7FF-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITfRange = interface(IUnknown)
['{AA80E7FF-2021-11D2-93E0-0060B067B86E}']
// !! "out word" -> PWideChar
function GetText(ec: TfEditCookie; dwFlags: LongWord; pchText: PWideChar; cchMax: LongWord;
out pcch: LongWord): HResult; stdcall;
// !! "var word" -> PWideChary
function SetText(ec: TfEditCookie; dwFlags: LongWord; pchText: PWideChar; cch: Integer): HResult; stdcall;
function GetFormattedText(ec: TfEditCookie; out ppDataObject: IDataObject): HResult; stdcall;
function GetEmbedded(ec: TfEditCookie; var rguidService: TGUID; var riid: TGUID;
out ppunk: IUnknown): HResult; stdcall;
function InsertEmbedded(ec: TfEditCookie; dwFlags: LongWord; const pDataObject: IDataObject): HResult; stdcall;
function ShiftStart(ec: TfEditCookie; cchReq: Integer; out pcch: Integer; var pHalt: TF_HALTCOND): HResult; stdcall;
function ShiftEnd(ec: TfEditCookie; cchReq: Integer; out pcch: Integer; var pHalt: TF_HALTCOND): HResult; stdcall;
function ShiftStartToRange(ec: TfEditCookie; const pRange: ITfRange; aPos: TfAnchor): HResult; stdcall;
function ShiftEndToRange(ec: TfEditCookie; const pRange: ITfRange; aPos: TfAnchor): HResult; stdcall;
function ShiftStartRegion(ec: TfEditCookie; dir: TfShiftDir; out pfNoRegion: Integer): HResult; stdcall;
function ShiftEndRegion(ec: TfEditCookie; dir: TfShiftDir; out pfNoRegion: Integer): HResult; stdcall;
function IsEmpty(ec: TfEditCookie; out pfEmpty: Integer): HResult; stdcall;
function Collapse(ec: TfEditCookie; aPos: TfAnchor): HResult; stdcall;
function IsEqualStart(ec: TfEditCookie; const pWith: ITfRange; aPos: TfAnchor;
out pfEqual: Integer): HResult; stdcall;
function IsEqualEnd(ec: TfEditCookie; const pWith: ITfRange; aPos: TfAnchor;
out pfEqual: Integer): HResult; stdcall;
function CompareStart(ec: TfEditCookie; const pWith: ITfRange; aPos: TfAnchor;
out plResult: Integer): HResult; stdcall;
function CompareEnd(ec: TfEditCookie; const pWith: ITfRange; aPos: TfAnchor;
out plResult: Integer): HResult; stdcall;
function AdjustForInsert(ec: TfEditCookie; cchInsert: LongWord; out pfInsertOk: Integer): HResult; stdcall;
function GetGravity(out pgStart: TfGravity; out pgEnd: TfGravity): HResult; stdcall;
function SetGravity(ec: TfEditCookie; gStart: TfGravity; gEnd: TfGravity): HResult; stdcall;
function Clone(out ppClone: ITfRange): HResult; stdcall;
function GetContext(out ppContext: ITfContext): HResult; stdcall;
end;
{$EXTERNALSYM ITfRange}
// *********************************************************************//
// Interface: ISequentialStream
// Flags: (0)
// GUID: {0C733A30-2A1C-11CE-ADE5-00AA0044773D}
// *********************************************************************//
ISequentialStream = interface(IUnknown)
['{0C733A30-2A1C-11CE-ADE5-00AA0044773D}']
function RemoteRead(out pv: Byte; cb: LongWord; out pcbRead: LongWord): HResult; stdcall;
function RemoteWrite(var pv: Byte; cb: LongWord; out pcbWritten: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ISequentialStream}
// *********************************************************************//
// Interface: ITfContextView
// Flags: (0)
// GUID: {2433BF8E-0F9B-435C-BA2C-180611978C30}
// *********************************************************************//
ITfContextView = interface(IUnknown)
['{2433BF8E-0F9B-435C-BA2C-180611978C30}']
function GetRangeFromPoint(ec: TfEditCookie; var ppt: TPoint; dwFlags: LongWord;
out ppRange: ITfRange): HResult; stdcall;
function GetTextExt(ec: TfEditCookie; const pRange: ITfRange; out prc: TRect;
out pfClipped: Integer): HResult; stdcall;
function GetScreenExt(out prc: TRect): HResult; stdcall;
// !! "out wireHWND" -> "out HWND"
function GetWnd(out phwnd: HWND): HResult; stdcall;
end;
{$EXTERNALSYM ITfContextView}
// *********************************************************************//
// Interface: IEnumTfContextViews
// Flags: (0)
// GUID: {F0C0F8DD-CF38-44E1-BB0F-68CF0D551C78}
// *********************************************************************//
IEnumTfContextViews = interface(IUnknown)
['{F0C0F8DD-CF38-44E1-BB0F-68CF0D551C78}']
function Clone(out ppenum: IEnumTfContextViews): HResult; stdcall;
function Next(ulCount: LongWord; out rgViews: ITfContextView; out pcFetched: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfContextViews}
// *********************************************************************//
// Interface: ITfReadOnlyProperty
// Flags: (0)
// GUID: {17D49A3D-F8B8-4B2F-B254-52319DD64C53}
// *********************************************************************//
ITfReadOnlyProperty = interface(IUnknown)
['{17D49A3D-F8B8-4B2F-B254-52319DD64C53}']
function GetType(out pguid: TGUID): HResult; stdcall;
function EnumRanges(ec: TfEditCookie; out ppenum: IEnumTfRanges; const pTargetRange: ITfRange): HResult; stdcall;
function GetValue(ec: TfEditCookie; const pRange: ITfRange; out pvarValue: OleVariant): HResult; stdcall;
function GetContext(out ppContext: ITfContext): HResult; stdcall;
end;
{$EXTERNALSYM ITfReadOnlyProperty}
// *********************************************************************//
// Interface: ITfProperty
// Flags: (0)
// GUID: {E2449660-9542-11D2-BF46-00105A2799B5}
// *********************************************************************//
ITfProperty = interface(ITfReadOnlyProperty)
['{E2449660-9542-11D2-BF46-00105A2799B5}']
function FindRange(ec: TfEditCookie; const pRange: ITfRange; out ppRange: ITfRange;
aPos: TfAnchor): HResult; stdcall;
function SetValueStore(ec: TfEditCookie; const pRange: ITfRange;
const pPropStore: ITfPropertyStore): HResult; stdcall;
function SetValue(ec: TfEditCookie; const pRange: ITfRange; const pvarValue: OleVariant): HResult; stdcall;
function Clear(ec: TfEditCookie; const pRange: ITfRange): HResult; stdcall;
end;
{$EXTERNALSYM ITfProperty}
// *********************************************************************//
// Interface: IEnumTfRanges
// Flags: (0)
// GUID: {F99D3F40-8E32-11D2-BF46-00105A2799B5}
// *********************************************************************//
IEnumTfRanges = interface(IUnknown)
['{F99D3F40-8E32-11D2-BF46-00105A2799B5}']
function Clone(out ppenum: IEnumTfRanges): HResult; stdcall;
function Next(ulCount: LongWord; out ppRange: ITfRange; out pcFetched: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfRanges}
// *********************************************************************//
// Interface: ITfPropertyStore
// Flags: (0)
// GUID: {6834B120-88CB-11D2-BF45-00105A2799B5}
// *********************************************************************//
ITfPropertyStore = interface(IUnknown)
['{6834B120-88CB-11D2-BF45-00105A2799B5}']
function GetType(out pguid: TGUID): HResult; stdcall;
function GetDataType(out pdwReserved: LongWord): HResult; stdcall;
function GetData(out pvarValue: OleVariant): HResult; stdcall;
function OnTextUpdated(dwFlags: LongWord; const pRangeNew: ITfRange; out pfAccept: Integer): HResult; stdcall;
function Shrink(const pRangeNew: ITfRange; out pfFree: Integer): HResult; stdcall;
function Divide(const pRangeThis: ITfRange; const pRangeNew: ITfRange;
out ppPropStore: ITfPropertyStore): HResult; stdcall;
function Clone(out pPropStore: ITfPropertyStore): HResult; stdcall;
function GetPropertyRangeCreator(out pclsid: TGUID): HResult; stdcall;
function Serialize(const pStream: IStream; out pcb: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ITfPropertyStore}
// *********************************************************************//
// Interface: IEnumTfProperties
// Flags: (0)
// GUID: {19188CB0-ACA9-11D2-AFC5-00105A2799B5}
// *********************************************************************//
IEnumTfProperties = interface(IUnknown)
['{19188CB0-ACA9-11D2-AFC5-00105A2799B5}']
function Clone(out ppenum: IEnumTfProperties): HResult; stdcall;
function Next(ulCount: LongWord; out ppProp: ITfProperty; out pcFetched: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfProperties}
// *********************************************************************//
// Interface: ITfRangeBackup
// Flags: (0)
// GUID: {463A506D-6992-49D2-9B88-93D55E70BB16}
// *********************************************************************//
ITfRangeBackup = interface(IUnknown)
['{463A506D-6992-49D2-9B88-93D55E70BB16}']
function Restore(ec: TfEditCookie; const pRange: ITfRange): HResult; stdcall;
end;
{$EXTERNALSYM ITfRangeBackup}
// *********************************************************************//
// Interface: IEnumTfContexts
// Flags: (0)
// GUID: {8F1A7EA6-1654-4502-A86E-B2902344D507}
// *********************************************************************//
IEnumTfContexts = interface(IUnknown)
['{8F1A7EA6-1654-4502-A86E-B2902344D507}']
function Clone(out ppenum: IEnumTfContexts): HResult; stdcall;
function Next(ulCount: LongWord; out rgContext: ITfContext; out pcFetched: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfContexts}
// *********************************************************************//
// Interface: ITfTextInputProcessor
// Flags: (0)
// GUID: {AA80E7F7-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITfTextInputProcessor = interface(IUnknown)
['{AA80E7F7-2021-11D2-93E0-0060B067B86E}']
function Activate(const ptim: ITfThreadMgr; tid: TfClientId): HResult; stdcall;
function Deactivate: HResult; stdcall;
end;
{$EXTERNALSYM ITfTextInputProcessor}
// *********************************************************************//
// Interface: ITfThreadMgr
// Flags: (0)
// GUID: {AA80E801-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITfThreadMgr = interface(IUnknown)
['{AA80E801-2021-11D2-93E0-0060B067B86E}']
function Activate(out ptid: TfClientId): HResult; stdcall;
function Deactivate: HResult; stdcall;
function CreateDocumentMgr(out ppdim: ITfDocumentMgr): HResult; stdcall;
function EnumDocumentMgrs(out ppenum: IEnumTfDocumentMgrs): HResult; stdcall;
function GetFocus(out ppdimFocus: ITfDocumentMgr): HResult; stdcall;
function SetFocus(const pdimFocus: ITfDocumentMgr): HResult; stdcall;
// !! "var hwnd: _RemotableHandle" -> "hwnd: HWND"
function AssociateFocus(hwnd: HWND; const pdimNew: ITfDocumentMgr;
out ppdimPrev: ITfDocumentMgr): HResult; stdcall;
function IsThreadFocus(out pfThreadFocus: Integer): HResult; stdcall;
function GetFunctionProvider(var clsid: TGUID; out ppFuncProv: ITfFunctionProvider): HResult; stdcall;
function EnumFunctionProviders(out ppenum: IEnumTfFunctionProviders): HResult; stdcall;
function GetGlobalCompartment(out ppCompMgr: ITfCompartmentMgr): HResult; stdcall;
end;
{$EXTERNALSYM ITfThreadMgr}
// *********************************************************************//
// Interface: IEnumTfDocumentMgrs
// Flags: (0)
// GUID: {AA80E808-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
IEnumTfDocumentMgrs = interface(IUnknown)
['{AA80E808-2021-11D2-93E0-0060B067B86E}']
function Clone(out ppenum: IEnumTfDocumentMgrs): HResult; stdcall;
function Next(ulCount: LongWord; out rgDocumentMgr: ITfDocumentMgr; out pcFetched: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfDocumentMgrs}
// *********************************************************************//
// Interface: ITfFunctionProvider
// Flags: (0)
// GUID: {101D6610-0990-11D3-8DF0-00105A2799B5}
// *********************************************************************//
ITfFunctionProvider = interface(IUnknown)
['{101D6610-0990-11D3-8DF0-00105A2799B5}']
function GetType(out pguid: TGUID): HResult; stdcall;
function GetDescription(out pbstrDesc: WideString): HResult; stdcall;
function GetFunction(var rguid: TGUID; var riid: TGUID; out ppunk: IUnknown): HResult; stdcall;
end;
{$EXTERNALSYM ITfFunctionProvider}
// *********************************************************************//
// Interface: IEnumTfFunctionProviders
// Flags: (0)
// GUID: {E4B24DB0-0990-11D3-8DF0-00105A2799B5}
// *********************************************************************//
IEnumTfFunctionProviders = interface(IUnknown)
['{E4B24DB0-0990-11D3-8DF0-00105A2799B5}']
function Clone(out ppenum: IEnumTfFunctionProviders): HResult; stdcall;
function Next(ulCount: LongWord; out ppCmdobj: ITfFunctionProvider; out pcFetch: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfFunctionProviders}
// *********************************************************************//
// Interface: ITfCompartmentMgr
// Flags: (0)
// GUID: {7DCF57AC-18AD-438B-824D-979BFFB74B7C}
// *********************************************************************//
ITfCompartmentMgr = interface(IUnknown)
['{7DCF57AC-18AD-438B-824D-979BFFB74B7C}']
function GetCompartment(var rguid: TGUID; out ppcomp: ITfCompartment): HResult; stdcall;
function ClearCompartment(tid: TfClientId; var rguid: TGUID): HResult; stdcall;
function EnumCompartments(out ppenum: IEnumGUID): HResult; stdcall;
end;
{$EXTERNALSYM ITfCompartmentMgr}
// *********************************************************************//
// Interface: ITfCompartment
// Flags: (0)
// GUID: {BB08F7A9-607A-4384-8623-056892B64371}
// *********************************************************************//
ITfCompartment = interface(IUnknown)
['{BB08F7A9-607A-4384-8623-056892B64371}']
function SetValue(tid: TfClientId; const pvarValue: OleVariant): HResult; stdcall;
function GetValue(out pvarValue: OleVariant): HResult; stdcall;
end;
{$EXTERNALSYM ITfCompartment}
// *********************************************************************//
// Interface: ITfRangeACP
// Flags: (0)
// GUID: {057A6296-029B-4154-B79A-0D461D4EA94C}
// *********************************************************************//
ITfRangeACP = interface(ITfRange)
['{057A6296-029B-4154-B79A-0D461D4EA94C}']
function GetExtent(out pacpAnchor: Integer; out pcch: Integer): HResult; stdcall;
function SetExtent(acpAnchor: Integer; cch: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfRangeACP}
// *********************************************************************//
// Interface: ITfPersistentPropertyLoaderACP
// Flags: (0)
// GUID: {4EF89150-0807-11D3-8DF0-00105A2799B5}
// *********************************************************************//
ITfPersistentPropertyLoaderACP = interface(IUnknown)
['{4EF89150-0807-11D3-8DF0-00105A2799B5}']
function LoadProperty(var pHdr: TF_PERSISTENT_PROPERTY_HEADER_ACP; out ppStream: IStream): HResult; stdcall;
end;
{$EXTERNALSYM ITfPersistentPropertyLoaderACP}
// *********************************************************************//
// Interface: ITfKeyEventSink
// Flags: (0)
// GUID: {AA80E7F5-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITfKeyEventSink = interface(IUnknown)
['{AA80E7F5-2021-11D2-93E0-0060B067B86E}']
function OnSetFocus(fForeground: Integer): HResult; stdcall;
function OnTestKeyDown(const pic: ITfContext; wParam: WPARAM; lParam: LPARAM;
out pfEaten: Integer): HResult; stdcall;
function OnTestKeyUp(const pic: ITfContext; wParam: WPARAM; lParam: LPARAM;
out pfEaten: Integer): HResult; stdcall;
function OnKeyDown(const pic: ITfContext; wParam: WPARAM; lParam: LPARAM;
out pfEaten: Integer): HResult; stdcall;
function OnKeyUp(const pic: ITfContext; wParam: WPARAM; lParam: LPARAM; out pfEaten: Integer): HResult; stdcall;
function OnPreservedKey(const pic: ITfContext; var rguid: TGUID; out pfEaten: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfKeyEventSink}
// *********************************************************************//
// Interface: ITfSource
// Flags: (0)
// GUID: {4EA48A35-60AE-446F-8FD6-E6A8D82459F7}
// *********************************************************************//
ITfSource = interface(IUnknown)
['{4EA48A35-60AE-446F-8FD6-E6A8D82459F7}']
function AdviseSink(var riid: TGUID; const punk: IUnknown; out pdwCookie: LongWord): HResult; stdcall;
function UnadviseSink(dwCookie: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ITfSource}
// *********************************************************************//
// Interface: ITfMouseSink
// Flags: (0)
// GUID: {A1ADAAA2-3A24-449D-AC96-5183E7F5C217}
// *********************************************************************//
ITfMouseSink = interface(IUnknown)
['{A1ADAAA2-3A24-449D-AC96-5183E7F5C217}']
function OnMouseEvent(uEdge: LongWord; uQuadrant: LongWord; dwBtnStatus: LongWord;
out pfEaten: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfMouseSink}
// *********************************************************************//
// Interface: IEnumTfLanguageProfiles
// Flags: (0)
// GUID: {3D61BF11-AC5F-42C8-A4CB-931BCC28C744}
// *********************************************************************//
IEnumTfLanguageProfiles = interface(IUnknown)
['{3D61BF11-AC5F-42C8-A4CB-931BCC28C744}']
function Clone(out ppenum: IEnumTfLanguageProfiles): HResult; stdcall;
function Next(ulCount: LongWord; out pProfile: TF_LANGUAGEPROFILE; out pcFetch: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfLanguageProfiles}
// *********************************************************************//
// Interface: ITfUIElement
// Flags: (0)
// GUID: {EA1EA137-19DF-11D7-A6D2-00065B84435C}
// *********************************************************************//
ITfUIElement = interface(IUnknown)
['{EA1EA137-19DF-11D7-A6D2-00065B84435C}']
function GetDescription(out pbstrDescription: WideString): HResult; stdcall;
function GetGUID(out pguid: TGUID): HResult; stdcall;
function Show(bShow: Integer): HResult; stdcall;
function IsShown(out pbShow: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfUIElement}
// *********************************************************************//
// Interface: IEnumTfUIElements
// Flags: (0)
// GUID: {887AA91E-ACBA-4931-84DA-3C5208CF543F}
// *********************************************************************//
IEnumTfUIElements = interface(IUnknown)
['{887AA91E-ACBA-4931-84DA-3C5208CF543F}']
function Clone(out ppenum: IEnumTfUIElements): HResult; stdcall;
function Next(ulCount: LongWord; out ppElement: ITfUIElement; out pcFetched: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfUIElements}
// *********************************************************************//
// Interface: IEnumTfInputProcessorProfiles
// Flags: (0)
// GUID: {71C6E74D-0F28-11D8-A82A-00065B84435C}
// *********************************************************************//
IEnumTfInputProcessorProfiles = interface(IUnknown)
['{71C6E74D-0F28-11D8-A82A-00065B84435C}']
function Clone(out ppenum: IEnumTfInputProcessorProfiles): HResult; stdcall;
function Next(ulCount: LongWord; out pProfile: TF_INPUTPROCESSORPROFILE; out pcFetch: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfInputProcessorProfiles}
// *********************************************************************//
// Interface: ITfThreadMgrEx
// Flags: (0)
// GUID: {3E90ADE3-7594-4CB0-BB58-69628F5F458C}
// *********************************************************************//
ITfThreadMgrEx = interface(ITfThreadMgr)
['{3E90ADE3-7594-4CB0-BB58-69628F5F458C}']
function ActivateEx(out ptid: TfClientId; dwFlags: LongWord): HResult; stdcall;
function GetActiveFlags(out lpdwFlags: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ITfThreadMgrEx}
// *********************************************************************//
// Interface: ITfThreadMgr2
// Flags: (0)
// GUID: {0AB198EF-6477-4EE8-8812-6780EDB82D5E}
// *********************************************************************//
ITfThreadMgr2 = interface(IUnknown)
['{0AB198EF-6477-4EE8-8812-6780EDB82D5E}']
function Activate(out ptid: TfClientId): HResult; stdcall;
function Deactivate: HResult; stdcall;
function CreateDocumentMgr(out ppdim: ITfDocumentMgr): HResult; stdcall;
function EnumDocumentMgrs(out ppenum: IEnumTfDocumentMgrs): HResult; stdcall;
function GetFocus(out ppdimFocus: ITfDocumentMgr): HResult; stdcall;
function SetFocus(const pdimFocus: ITfDocumentMgr): HResult; stdcall;
function IsThreadFocus(out pfThreadFocus: Integer): HResult; stdcall;
function GetFunctionProvider(var clsid: TGUID; out ppFuncProv: ITfFunctionProvider): HResult; stdcall;
function EnumFunctionProviders(out ppenum: IEnumTfFunctionProviders): HResult; stdcall;
function GetGlobalCompartment(out ppCompMgr: ITfCompartmentMgr): HResult; stdcall;
function ActivateEx(out ptid: TfClientId; dwFlags: LongWord): HResult; stdcall;
function GetActiveFlags(out lpdwFlags: LongWord): HResult; stdcall;
function SuspendKeystrokeHandling: HResult; stdcall;
function ResumeKeystrokeHandling: HResult; stdcall;
end;
{$EXTERNALSYM ITfThreadMgr2}
// *********************************************************************//
// Interface: ITfConfigureSystemKeystrokeFeed
// Flags: (0)
// GUID: {0D2C969A-BC9C-437C-84EE-951C49B1A764}
// *********************************************************************//
ITfConfigureSystemKeystrokeFeed = interface(IUnknown)
['{0D2C969A-BC9C-437C-84EE-951C49B1A764}']
function DisableSystemKeystrokeFeed: HResult; stdcall;
function EnableSystemKeystrokeFeed: HResult; stdcall;
end;
{$EXTERNALSYM ITfConfigureSystemKeystrokeFeed}
// *********************************************************************//
// Interface: ITfCompositionView
// Flags: (0)
// GUID: {D7540241-F9A1-4364-BEFC-DBCD2C4395B7}
// *********************************************************************//
ITfCompositionView = interface(IUnknown)
['{D7540241-F9A1-4364-BEFC-DBCD2C4395B7}']
function GetOwnerClsid(out pclsid: TGUID): HResult; stdcall;
function GetRange(out ppRange: ITfRange): HResult; stdcall;
end;
{$EXTERNALSYM ITfCompositionView}
// *********************************************************************//
// Interface: IEnumITfCompositionView
// Flags: (0)
// GUID: {5EFD22BA-7838-46CB-88E2-CADB14124F8F}
// *********************************************************************//
IEnumITfCompositionView = interface(IUnknown)
['{5EFD22BA-7838-46CB-88E2-CADB14124F8F}']
function Clone(out ppenum: IEnumITfCompositionView): HResult; stdcall;
function Next(ulCount: LongWord; out rgCompositionView: ITfCompositionView;
out pcFetched: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumITfCompositionView}
// *********************************************************************//
// Interface: ITfComposition
// Flags: (0)
// GUID: {20168D64-5A8F-4A5A-B7BD-CFA29F4D0FD9}
// *********************************************************************//
ITfComposition = interface(IUnknown)
['{20168D64-5A8F-4A5A-B7BD-CFA29F4D0FD9}']
function GetRange(out ppRange: ITfRange): HResult; stdcall;
function ShiftStart(ecWrite: TfEditCookie; const pNewStart: ITfRange): HResult; stdcall;
function ShiftEnd(ecWrite: TfEditCookie; const pNewEnd: ITfRange): HResult; stdcall;
function EndComposition(ecWrite: TfEditCookie): HResult; stdcall;
end;
{$EXTERNALSYM ITfComposition}
// *********************************************************************//
// Interface: ITfCompositionSink
// Flags: (0)
// GUID: {A781718C-579A-4B15-A280-32B8577ACC5E}
// *********************************************************************//
ITfCompositionSink = interface(IUnknown)
['{A781718C-579A-4B15-A280-32B8577ACC5E}']
function OnCompositionTerminated(ecWrite: TfEditCookie; const pComposition: ITfComposition): HResult; stdcall;
end;
{$EXTERNALSYM ITfCompositionSink}
// *********************************************************************//
// Interface: ITfContextComposition
// Flags: (0)
// GUID: {D40C8AAE-AC92-4FC7-9A11-0EE0E23AA39B}
// *********************************************************************//
ITfContextComposition = interface(IUnknown)
['{D40C8AAE-AC92-4FC7-9A11-0EE0E23AA39B}']
function StartComposition(ecWrite: TfEditCookie; const pCompositionRange: ITfRange;
const pSink: ITfCompositionSink; out ppComposition: ITfComposition): HResult; stdcall;
function EnumCompositions(out ppenum: IEnumITfCompositionView): HResult; stdcall;
function FindComposition(ecRead: TfEditCookie; const pTestRange: ITfRange;
out ppenum: IEnumITfCompositionView): HResult; stdcall;
function TakeOwnership(ecWrite: TfEditCookie; const pComposition: ITfCompositionView;
const pSink: ITfCompositionSink; out ppComposition: ITfComposition): HResult; stdcall;
end;
{$EXTERNALSYM ITfContextComposition}
// *********************************************************************//
// Interface: ITfContextOwnerCompositionServices
// Flags: (0)
// GUID: {86462810-593B-4916-9764-19C08E9CE110}
// *********************************************************************//
ITfContextOwnerCompositionServices = interface(ITfContextComposition)
['{86462810-593B-4916-9764-19C08E9CE110}']
function TerminateComposition(const pComposition: ITfCompositionView): HResult; stdcall;
end;
{$EXTERNALSYM ITfContextOwnerCompositionServices}
// *********************************************************************//
// Interface: ITfContextOwnerCompositionSink
// Flags: (0)
// GUID: {5F20AA40-B57A-4F34-96AB-3576F377CC79}
// *********************************************************************//
ITfContextOwnerCompositionSink = interface(IUnknown)
['{5F20AA40-B57A-4F34-96AB-3576F377CC79}']
function OnStartComposition(const pComposition: ITfCompositionView; out pfOk: Integer): HResult; stdcall;
function OnUpdateComposition(const pComposition: ITfCompositionView; const pRangeNew: ITfRange): HResult; stdcall;
function OnEndComposition(const pComposition: ITfCompositionView): HResult; stdcall;
end;
{$EXTERNALSYM ITfContextOwnerCompositionSink}
// *********************************************************************//
// Interface: ITfQueryEmbedded
// Flags: (0)
// GUID: {0FAB9BDB-D250-4169-84E5-6BE118FDD7A8}
// *********************************************************************//
ITfQueryEmbedded = interface(IUnknown)
['{0FAB9BDB-D250-4169-84E5-6BE118FDD7A8}']
function QueryInsertEmbedded(var pguidService: TGUID; var pformatetc: TFormatEtc;
out pfInsertable: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfQueryEmbedded}
// *********************************************************************//
// Interface: ITfInsertAtSelection
// Flags: (0)
// GUID: {55CE16BA-3014-41C1-9CEB-FADE1446AC6C}
// *********************************************************************//
ITfInsertAtSelection = interface(IUnknown)
['{55CE16BA-3014-41C1-9CEB-FADE1446AC6C}']
// !! "var word" -> PWideChar
function InsertTextAtSelection(ec: TfEditCookie; dwFlags: LongWord; pchText: PWideChar;
cch: Integer; out ppRange: ITfRange): HResult; stdcall;
function InsertEmbeddedAtSelection(ec: TfEditCookie; dwFlags: LongWord;
const pDataObject: IDataObject; out ppRange: ITfRange): HResult; stdcall;
end;
{$EXTERNALSYM ITfInsertAtSelection}
// *********************************************************************//
// Interface: ITfCleanupContextSink
// Flags: (0)
// GUID: {01689689-7ACB-4E9B-AB7C-7EA46B12B522}
// *********************************************************************//
ITfCleanupContextSink = interface(IUnknown)
['{01689689-7ACB-4E9B-AB7C-7EA46B12B522}']
function OnCleanupContext(ecWrite: TfEditCookie; const pic: ITfContext): HResult; stdcall;
end;
{$EXTERNALSYM ITfCleanupContextSink}
// *********************************************************************//
// Interface: ITfCleanupContextDurationSink
// Flags: (0)
// GUID: {45C35144-154E-4797-BED8-D33AE7BF8794}
// *********************************************************************//
ITfCleanupContextDurationSink = interface(IUnknown)
['{45C35144-154E-4797-BED8-D33AE7BF8794}']
function OnStartCleanupContext: HResult; stdcall;
function OnEndCleanupContext: HResult; stdcall;
end;
{$EXTERNALSYM ITfCleanupContextDurationSink}
// *********************************************************************//
// Interface: IEnumTfPropertyValue
// Flags: (0)
// GUID: {8ED8981B-7C10-4D7D-9FB3-AB72E9C75F72}
// *********************************************************************//
IEnumTfPropertyValue = interface(IUnknown)
['{8ED8981B-7C10-4D7D-9FB3-AB72E9C75F72}']
function Clone(out ppenum: IEnumTfPropertyValue): HResult; stdcall;
function Next(ulCount: LongWord; out rgValues: TF_PROPERTYVAL; out pcFetched: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfPropertyValue}
// *********************************************************************//
// Interface: ITfMouseTracker
// Flags: (0)
// GUID: {09D146CD-A544-4132-925B-7AFA8EF322D0}
// *********************************************************************//
ITfMouseTracker = interface(IUnknown)
['{09D146CD-A544-4132-925B-7AFA8EF322D0}']
function AdviseMouseSink(const range: ITfRange; const pSink: ITfMouseSink;
out pdwCookie: LongWord): HResult; stdcall;
function UnadviseMouseSink(dwCookie: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ITfMouseTracker}
// *********************************************************************//
// Interface: ITfMouseTrackerACP
// Flags: (0)
// GUID: {3BDD78E2-C16E-47FD-B883-CE6FACC1A208}
// *********************************************************************//
ITfMouseTrackerACP = interface(IUnknown)
['{3BDD78E2-C16E-47FD-B883-CE6FACC1A208}']
function AdviseMouseSink(const range: ITfRangeACP; const pSink: ITfMouseSink;
out pdwCookie: LongWord): HResult; stdcall;
function UnadviseMouseSink(dwCookie: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ITfMouseTrackerACP}
// *********************************************************************//
// Interface: ITfEditRecord
// Flags: (0)
// GUID: {42D4D099-7C1A-4A89-B836-6C6F22160DF0}
// *********************************************************************//
ITfEditRecord = interface(IUnknown)
['{42D4D099-7C1A-4A89-B836-6C6F22160DF0}']
function GetSelectionStatus(out pfChanged: Integer): HResult; stdcall;
function GetTextAndPropertyUpdates(dwFlags: LongWord; prgProperties: PPGUID;
cProperties: LongWord; out ppenum: IEnumTfRanges): HResult; stdcall;
end;
{$EXTERNALSYM ITfEditRecord}
// *********************************************************************//
// Interface: ITfTextEditSink
// Flags: (0)
// GUID: {8127D409-CCD3-4683-967A-B43D5B482BF7}
// *********************************************************************//
ITfTextEditSink = interface(IUnknown)
['{8127D409-CCD3-4683-967A-B43D5B482BF7}']
function OnEndEdit(const pic: ITfContext; ecReadOnly: TfEditCookie;
const pEditRecord: ITfEditRecord): HResult; stdcall;
end;
{$EXTERNALSYM ITfTextEditSink}
// *********************************************************************//
// Interface: ITfTextLayoutSink
// Flags: (0)
// GUID: {2AF2D06A-DD5B-4927-A0B4-54F19C91FADE}
// *********************************************************************//
ITfTextLayoutSink = interface(IUnknown)
['{2AF2D06A-DD5B-4927-A0B4-54F19C91FADE}']
function OnLayoutChange(const pic: ITfContext; lcode: TfLayoutCode; const pView: ITfContextView): HResult; stdcall;
end;
{$EXTERNALSYM ITfTextLayoutSink}
// *********************************************************************//
// Interface: ITfStatusSink
// Flags: (0)
// GUID: {6B7D8D73-B267-4F69-B32E-1CA321CE4F45}
// *********************************************************************//
ITfStatusSink = interface(IUnknown)
['{6B7D8D73-B267-4F69-B32E-1CA321CE4F45}']
function OnStatusChange(const pic: ITfContext; dwFlags: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ITfStatusSink}
// *********************************************************************//
// Interface: ITfEditTransactionSink
// Flags: (0)
// GUID: {708FBF70-B520-416B-B06C-2C41AB44F8BA}
// *********************************************************************//
ITfEditTransactionSink = interface(IUnknown)
['{708FBF70-B520-416B-B06C-2C41AB44F8BA}']
function OnStartEditTransaction(const pic: ITfContext): HResult; stdcall;
function OnEndEditTransaction(const pic: ITfContext): HResult; stdcall;
end;
{$EXTERNALSYM ITfEditTransactionSink}
// *********************************************************************//
// Interface: ITfContextOwner
// Flags: (0)
// GUID: {AA80E80C-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITfContextOwner = interface(IUnknown)
['{AA80E80C-2021-11D2-93E0-0060B067B86E}']
function GetACPFromPoint(var ptScreen: TPoint; dwFlags: LongWord; out pacp: Integer): HResult; stdcall;
function GetTextExt(acpStart: Integer; acpEnd: Integer; out prc: TRect; out pfClipped: Integer): HResult; stdcall;
function GetScreenExt(out prc: TRect): HResult; stdcall;
function GetStatus(out pdcs: TF_STATUS): HResult; stdcall;
// !! "out wireHWND" -> "out HWND"
function GetWnd(out phwnd: HWND): HResult; stdcall;
function GetAttribute(var rguidAttribute: TGUID; out pvarValue: OleVariant): HResult; stdcall;
end;
{$EXTERNALSYM ITfContextOwner}
// *********************************************************************//
// Interface: ITfContextOwnerServices
// Flags: (0)
// GUID: {B23EB630-3E1C-11D3-A745-0050040AB407}
// *********************************************************************//
ITfContextOwnerServices = interface(IUnknown)
['{B23EB630-3E1C-11D3-A745-0050040AB407}']
function OnLayoutChange: HResult; stdcall;
function OnStatusChange(dwFlags: LongWord): HResult; stdcall;
function OnAttributeChange(var rguidAttribute: TGUID): HResult; stdcall;
function Serialize(const pProp: ITfProperty; const pRange: ITfRange;
out pHdr: TF_PERSISTENT_PROPERTY_HEADER_ACP; const pStream: IStream): HResult; stdcall;
function Unserialize(const pProp: ITfProperty; var pHdr: TF_PERSISTENT_PROPERTY_HEADER_ACP;
const pStream: IStream; const pLoader: ITfPersistentPropertyLoaderACP): HResult; stdcall;
function ForceLoadProperty(const pProp: ITfProperty): HResult; stdcall;
function CreateRange(acpStart: Integer; acpEnd: Integer; out ppRange: ITfRangeACP): HResult; stdcall;
end;
{$EXTERNALSYM ITfContextOwnerServices}
// *********************************************************************//
// Interface: ITfContextKeyEventSink
// Flags: (0)
// GUID: {0552BA5D-C835-4934-BF50-846AAA67432F}
// *********************************************************************//
ITfContextKeyEventSink = interface(IUnknown)
['{0552BA5D-C835-4934-BF50-846AAA67432F}']
function OnKeyDown(wParam: WPARAM; lParam: LPARAM; out pfEaten: Integer): HResult; stdcall;
function OnKeyUp(wParam: WPARAM; lParam: LPARAM; out pfEaten: Integer): HResult; stdcall;
function OnTestKeyDown(wParam: WPARAM; lParam: LPARAM; out pfEaten: Integer): HResult; stdcall;
function OnTestKeyUp(wParam: WPARAM; lParam: LPARAM; out pfEaten: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfContextKeyEventSink}
// *********************************************************************//
// Interface: ITextStoreACPServices
// Flags: (0)
// GUID: {AA80E901-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITextStoreACPServices = interface(IUnknown)
['{AA80E901-2021-11D2-93E0-0060B067B86E}']
function Serialize(const pProp: ITfProperty; const pRange: ITfRange;
out pHdr: TF_PERSISTENT_PROPERTY_HEADER_ACP; const pStream: IStream): HResult; stdcall;
function Unserialize(const pProp: ITfProperty; var pHdr: TF_PERSISTENT_PROPERTY_HEADER_ACP;
const pStream: IStream; const pLoader: ITfPersistentPropertyLoaderACP): HResult; stdcall;
function ForceLoadProperty(const pProp: ITfProperty): HResult; stdcall;
function CreateRange(acpStart: Integer; acpEnd: Integer; out ppRange: ITfRangeACP): HResult; stdcall;
end;
{$EXTERNALSYM ITextStoreACPServices}
// *********************************************************************//
// Interface: ITfCreatePropertyStore
// Flags: (0)
// GUID: {2463FBF0-B0AF-11D2-AFC5-00105A2799B5}
// *********************************************************************//
ITfCreatePropertyStore = interface(IUnknown)
['{2463FBF0-B0AF-11D2-AFC5-00105A2799B5}']
function IsStoreSerializable(var guidProp: TGUID; const pRange: ITfRange;
const pPropStore: ITfPropertyStore; out pfSerializable: Integer): HResult; stdcall;
function CreatePropertyStore(var guidProp: TGUID; const pRange: ITfRange; cb: LongWord;
const pStream: IStream; out ppStore: ITfPropertyStore): HResult; stdcall;
end;
{$EXTERNALSYM ITfCreatePropertyStore}
// *********************************************************************//
// Interface: ITfCompartmentEventSink
// Flags: (0)
// GUID: {743ABD5F-F26D-48DF-8CC5-238492419B64}
// *********************************************************************//
ITfCompartmentEventSink = interface(IUnknown)
['{743ABD5F-F26D-48DF-8CC5-238492419B64}']
function OnChange(var rguid: TGUID): HResult; stdcall;
end;
{$EXTERNALSYM ITfCompartmentEventSink}
// *********************************************************************//
// Interface: ITfFunction
// Flags: (0)
// GUID: {DB593490-098F-11D3-8DF0-00105A2799B5}
// *********************************************************************//
ITfFunction = interface(IUnknown)
['{DB593490-098F-11D3-8DF0-00105A2799B5}']
function GetDisplayName(out pbstrName: WideString): HResult; stdcall;
end;
{$EXTERNALSYM ITfFunction}
// *********************************************************************//
// Interface: ITfInputProcessorProfiles
// Flags: (0)
// GUID: {1F02B6C5-7842-4EE6-8A0B-9A24183A95CA}
// *********************************************************************//
ITfInputProcessorProfiles = interface(IUnknown)
['{1F02B6C5-7842-4EE6-8A0B-9A24183A95CA}']
function Register(var rclsid: TGUID): HResult; stdcall;
function Unregister(var rclsid: TGUID): HResult; stdcall;
// !! "var word" -> PWideChar
function AddLanguageProfile(var rclsid: TGUID; langid: Word; var guidProfile: TGUID;
pchDesc: PWideChar; cchDesc: LongWord; pchIconFile: PWideChar;
cchFile: LongWord; uIconIndex: LongWord): HResult; stdcall;
function RemoveLanguageProfile(var rclsid: TGUID; langid: Word; var guidProfile: TGUID): HResult; stdcall;
function EnumInputProcessorInfo(out ppenum: IEnumGUID): HResult; stdcall;
function GetDefaultLanguageProfile(langid: Word; var catid: TGUID; out pclsid: TGUID;
out pguidProfile: TGUID): HResult; stdcall;
function SetDefaultLanguageProfile(langid: Word; var rclsid: TGUID; var guidProfiles: TGUID): HResult; stdcall;
function ActivateLanguageProfile(var rclsid: TGUID; langid: Word; var guidProfiles: TGUID): HResult; stdcall;
function GetActiveLanguageProfile(var rclsid: TGUID; out plangid: Word; out pguidProfile: TGUID): HResult; stdcall;
function GetLanguageProfileDescription(var rclsid: TGUID; langid: Word; var guidProfile: TGUID;
out pbstrProfile: WideString): HResult; stdcall;
function GetCurrentLanguage(out plangid: Word): HResult; stdcall;
function ChangeCurrentLanguage(langid: Word): HResult; stdcall;
function GetLanguageList(ppLangId: PPWord; out pulCount: LongWord): HResult; stdcall;
function EnumLanguageProfiles(langid: Word; out ppenum: IEnumTfLanguageProfiles): HResult; stdcall;
function EnableLanguageProfile(var rclsid: TGUID; langid: Word; var guidProfile: TGUID;
fEnable: Integer): HResult; stdcall;
function IsEnabledLanguageProfile(var rclsid: TGUID; langid: Word; var guidProfile: TGUID;
out pfEnable: Integer): HResult; stdcall;
function EnableLanguageProfileByDefault(var rclsid: TGUID; langid: Word; var guidProfile: TGUID;
fEnable: Integer): HResult; stdcall;
function SubstituteKeyboardLayout(var rclsid: TGUID; langid: Word; var guidProfile: TGUID;
HKL: HKL): HResult; stdcall;
end;
{$EXTERNALSYM ITfInputProcessorProfiles}
// *********************************************************************//
// Interface: ITfInputProcessorProfilesEx
// Flags: (0)
// GUID: {892F230F-FE00-4A41-A98E-FCD6DE0D35EF}
// *********************************************************************//
ITfInputProcessorProfilesEx = interface(ITfInputProcessorProfiles)
['{892F230F-FE00-4A41-A98E-FCD6DE0D35EF}']
// !! "var word" -> PWideChar
function SetLanguageProfileDisplayName(var rclsid: TGUID; langid: Word; var guidProfile: TGUID;
pchFile: PWideChar; cchFile: LongWord; uResId: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ITfInputProcessorProfilesEx}
// *********************************************************************//
// Interface: ITfInputProcessorProfileSubstituteLayout
// Flags: (0)
// GUID: {4FD67194-1002-4513-BFF2-C0DDF6258552}
// *********************************************************************//
ITfInputProcessorProfileSubstituteLayout = interface(IUnknown)
['{4FD67194-1002-4513-BFF2-C0DDF6258552}']
function GetSubstituteKeyboardLayout(var rclsid: TGUID; langid: Word; var guidProfile: TGUID;
out phKL: HKL): HResult; stdcall;
end;
{$EXTERNALSYM ITfInputProcessorProfileSubstituteLayout}
// *********************************************************************//
// Interface: ITfActiveLanguageProfileNotifySink
// Flags: (0)
// GUID: {B246CB75-A93E-4652-BF8C-B3FE0CFD7E57}
// *********************************************************************//
ITfActiveLanguageProfileNotifySink = interface(IUnknown)
['{B246CB75-A93E-4652-BF8C-B3FE0CFD7E57}']
function OnActivated(var clsid: TGUID; var guidProfile: TGUID; fActivated: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfActiveLanguageProfileNotifySink}
// *********************************************************************//
// Interface: ITfLanguageProfileNotifySink
// Flags: (0)
// GUID: {43C9FE15-F494-4C17-9DE2-B8A4AC350AA8}
// *********************************************************************//
ITfLanguageProfileNotifySink = interface(IUnknown)
['{43C9FE15-F494-4C17-9DE2-B8A4AC350AA8}']
function OnLanguageChange(langid: Word; out pfAccept: Integer): HResult; stdcall;
function OnLanguageChanged: HResult; stdcall;
end;
{$EXTERNALSYM ITfLanguageProfileNotifySink}
// *********************************************************************//
// Interface: ITfInputProcessorProfileMgr
// Flags: (0)
// GUID: {71C6E74C-0F28-11D8-A82A-00065B84435C}
// *********************************************************************//
ITfInputProcessorProfileMgr = interface(IUnknown)
['{71C6E74C-0F28-11D8-A82A-00065B84435C}']
function ActivateProfile(dwProfileType: LongWord; langid: Word; var clsid: TGUID;
var guidProfile: TGUID; HKL: HKL; dwFlags: LongWord): HResult; stdcall;
function DeactivateProfile(dwProfileType: LongWord; langid: Word; var clsid: TGUID;
var guidProfile: TGUID; HKL: HKL; dwFlags: LongWord): HResult; stdcall;
function GetProfile(dwProfileType: LongWord; langid: Word; var clsid: TGUID;
var guidProfile: TGUID; HKL: HKL; out pProfile: TF_INPUTPROCESSORPROFILE): HResult; stdcall;
function EnumProfiles(langid: Word; out ppenum: IEnumTfInputProcessorProfiles): HResult; stdcall;
function ReleaseInputProcessor(var rclsid: TGUID; dwFlags: LongWord): HResult; stdcall;
// !! "var word" -> PWideChar
function RegisterProfile(var rclsid: TGUID; langid: Word; var guidProfile: TGUID;
pchDesc: PWideChar; cchDesc: LongWord; pchIconFile: PWideChar;
cchFile: LongWord; uIconIndex: LongWord; hklSubstitute: HKL;
dwPreferredLayout: LongWord; bEnabledByDefault: Integer;
dwFlags: LongWord): HResult; stdcall;
function UnregisterProfile(var rclsid: TGUID; langid: Word; var guidProfile: TGUID;
dwFlags: LongWord): HResult; stdcall;
function GetActiveProfile(var catid: TGUID; out pProfile: TF_INPUTPROCESSORPROFILE): HResult; stdcall;
end;
{$EXTERNALSYM ITfInputProcessorProfileMgr}
// *********************************************************************//
// Interface: ITfInputProcessorProfileActivationSink
// Flags: (0)
// GUID: {71C6E74E-0F28-11D8-A82A-00065B84435C}
// *********************************************************************//
ITfInputProcessorProfileActivationSink = interface(IUnknown)
['{71C6E74E-0F28-11D8-A82A-00065B84435C}']
function OnActivated(dwProfileType: LongWord; langid: Word; var clsid: TGUID; var catid: TGUID;
var guidProfile: TGUID; HKL: HKL; dwFlags: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ITfInputProcessorProfileActivationSink}
// *********************************************************************//
// Interface: ITfKeystrokeMgr
// Flags: (0)
// GUID: {AA80E7F0-2021-11D2-93E0-0060B067B86E}
// *********************************************************************//
ITfKeystrokeMgr = interface(IUnknown)
['{AA80E7F0-2021-11D2-93E0-0060B067B86E}']
function AdviseKeyEventSink(tid: TfClientId; const pSink: ITfKeyEventSink; fForeground: Integer): HResult; stdcall;
function UnadviseKeyEventSink(tid: TfClientId): HResult; stdcall;
function GetForeground(out pclsid: TGUID): HResult; stdcall;
function TestKeyDown(wParam: WPARAM; lParam: LPARAM; out pfEaten: Integer): HResult; stdcall;
function TestKeyUp(wParam: WPARAM; lParam: LPARAM; out pfEaten: Integer): HResult; stdcall;
function KeyDown(wParam: WPARAM; lParam: LPARAM; out pfEaten: Integer): HResult; stdcall;
function KeyUp(wParam: WPARAM; lParam: LPARAM; out pfEaten: Integer): HResult; stdcall;
function GetPreservedKey(const pic: ITfContext; var pprekey: TF_PRESERVEDKEY; out pguid: TGUID): HResult; stdcall;
function IsPreservedKey(var rguid: TGUID; var pprekey: TF_PRESERVEDKEY; out pfRegistered: Integer): HResult; stdcall;
// !! "var word" -> PWideChar
function PreserveKey(tid: TfClientId; var rguid: TGUID; var prekey: TF_PRESERVEDKEY;
pchDesc: PWideChar; cchDesc: LongWord): HResult; stdcall;
function UnpreserveKey(var rguid: TGUID; var pprekey: TF_PRESERVEDKEY): HResult; stdcall;
// !! "var word" -> PWideChar
function SetPreservedKeyDescription(var rguid: TGUID; pchDesc: PWideChar; cchDesc: LongWord): HResult; stdcall;
function GetPreservedKeyDescription(var rguid: TGUID; out pbstrDesc: WideString): HResult; stdcall;
function SimulatePreservedKey(const pic: ITfContext; var rguid: TGUID; out pfEaten: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfKeystrokeMgr}
// *********************************************************************//
// Interface: ITfKeyTraceEventSink
// Flags: (0)
// GUID: {1CD4C13B-1C36-4191-A70A-7F3E611F367D}
// *********************************************************************//
ITfKeyTraceEventSink = interface(IUnknown)
['{1CD4C13B-1C36-4191-A70A-7F3E611F367D}']
function OnKeyTraceDown(wParam: WPARAM; lParam: LPARAM): HResult; stdcall;
function OnKeyTraceUp(wParam: WPARAM; lParam: LPARAM): HResult; stdcall;
end;
{$EXTERNALSYM ITfKeyTraceEventSink}
// *********************************************************************//
// Interface: ITfPreservedKeyNotifySink
// Flags: (0)
// GUID: {6F77C993-D2B1-446E-853E-5912EFC8A286}
// *********************************************************************//
ITfPreservedKeyNotifySink = interface(IUnknown)
['{6F77C993-D2B1-446E-853E-5912EFC8A286}']
function OnUpdated(var pprekey: TF_PRESERVEDKEY): HResult; stdcall;
end;
{$EXTERNALSYM ITfPreservedKeyNotifySink}
// *********************************************************************//
// Interface: ITfMessagePump
// Flags: (0)
// GUID: {8F1B8AD8-0B6B-4874-90C5-BD76011E8F7C}
// *********************************************************************//
ITfMessagePump = interface(IUnknown)
['{8F1B8AD8-0B6B-4874-90C5-BD76011E8F7C}']
// !! "var hwnd: _RemotableHandle" -> "hwnd: HWND"
function PeekMessageA(out pMsg: TMSG; hwnd: HWND; wMsgFilterMin: SYSUINT;
wMsgFilterMax: SYSUINT; wRemoveMsg: SYSUINT; out pfResult: Integer): HResult; stdcall;
// !! "var hwnd: _RemotableHandle" -> "hwnd: HWND"
function GetMessageA(out pMsg: TMSG; hwnd: HWND; wMsgFilterMin: SYSUINT;
wMsgFilterMax: SYSUINT; out pfResult: Integer): HResult; stdcall;
// !! "var hwnd: _RemotableHandle" -> "hwnd: HWND"
function PeekMessageW(out pMsg: TMSG; hwnd: HWND; wMsgFilterMin: SYSUINT;
wMsgFilterMax: SYSUINT; wRemoveMsg: SYSUINT; out pfResult: Integer): HResult; stdcall;
// !! "var hwnd: _RemotableHandle" -> "hwnd: HWND"
function GetMessageW(out pMsg: TMSG; hwnd: HWND; wMsgFilterMin: SYSUINT;
wMsgFilterMax: SYSUINT; out pfResult: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfMessagePump}
// *********************************************************************//
// Interface: ITfThreadFocusSink
// Flags: (0)
// GUID: {C0F1DB0C-3A20-405C-A303-96B6010A885F}
// *********************************************************************//
ITfThreadFocusSink = interface(IUnknown)
['{C0F1DB0C-3A20-405C-A303-96B6010A885F}']
function OnSetThreadFocus: HResult; stdcall;
function OnKillThreadFocus: HResult; stdcall;
end;
{$EXTERNALSYM ITfThreadFocusSink}
// *********************************************************************//
// Interface: ITfTextInputProcessorEx
// Flags: (0)
// GUID: {6E4E2102-F9CD-433D-B496-303CE03A6507}
// *********************************************************************//
ITfTextInputProcessorEx = interface(ITfTextInputProcessor)
['{6E4E2102-F9CD-433D-B496-303CE03A6507}']
function ActivateEx(const ptim: ITfThreadMgr; tid: TfClientId; dwFlags: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ITfTextInputProcessorEx}
// *********************************************************************//
// Interface: ITfClientId
// Flags: (0)
// GUID: {D60A7B49-1B9F-4BE2-B702-47E9DC05DEC3}
// *********************************************************************//
ITfClientId = interface(IUnknown)
['{D60A7B49-1B9F-4BE2-B702-47E9DC05DEC3}']
function GetClientId(var rclsid: TGUID; out ptid: TfClientId): HResult; stdcall;
end;
{$EXTERNALSYM ITfClientId}
// *********************************************************************//
// Interface: ITfDisplayAttributeInfo
// Flags: (0)
// GUID: {70528852-2F26-4AEA-8C96-215150578932}
// *********************************************************************//
ITfDisplayAttributeInfo = interface(IUnknown)
['{70528852-2F26-4AEA-8C96-215150578932}']
function GetGUID(out pguid: TGUID): HResult; stdcall;
function GetDescription(out pbstrDesc: WideString): HResult; stdcall;
function GetAttributeInfo(out pda: TF_DISPLAYATTRIBUTE): HResult; stdcall;
function SetAttributeInfo(var pda: TF_DISPLAYATTRIBUTE): HResult; stdcall;
function Reset: HResult; stdcall;
end;
{$EXTERNALSYM ITfDisplayAttributeInfo}
// *********************************************************************//
// Interface: IEnumTfDisplayAttributeInfo
// Flags: (0)
// GUID: {7CEF04D7-CB75-4E80-A7AB-5F5BC7D332DE}
// *********************************************************************//
IEnumTfDisplayAttributeInfo = interface(IUnknown)
['{7CEF04D7-CB75-4E80-A7AB-5F5BC7D332DE}']
function Clone(out ppenum: IEnumTfDisplayAttributeInfo): HResult; stdcall;
function Next(ulCount: LongWord; out rgInfo: ITfDisplayAttributeInfo; out pcFetched: LongWord): HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(ulCount: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM IEnumTfDisplayAttributeInfo}
// *********************************************************************//
// Interface: ITfDisplayAttributeProvider
// Flags: (0)
// GUID: {FEE47777-163C-4769-996A-6E9C50AD8F54}
// *********************************************************************//
ITfDisplayAttributeProvider = interface(IUnknown)
['{FEE47777-163C-4769-996A-6E9C50AD8F54}']
function EnumDisplayAttributeInfo(out ppenum: IEnumTfDisplayAttributeInfo): HResult; stdcall;
function GetDisplayAttributeInfo(var GUID: TGUID; out ppInfo: ITfDisplayAttributeInfo): HResult; stdcall;
end;
{$EXTERNALSYM ITfDisplayAttributeProvider}
// *********************************************************************//
// Interface: ITfDisplayAttributeMgr
// Flags: (0)
// GUID: {8DED7393-5DB1-475C-9E71-A39111B0FF67}
// *********************************************************************//
ITfDisplayAttributeMgr = interface(IUnknown)
['{8DED7393-5DB1-475C-9E71-A39111B0FF67}']
function OnUpdateInfo: HResult; stdcall;
function EnumDisplayAttributeInfo(out ppenum: IEnumTfDisplayAttributeInfo): HResult; stdcall;
function GetDisplayAttributeInfo(var GUID: TGUID; out ppInfo: ITfDisplayAttributeInfo;
out pclsidOwner: TGUID): HResult; stdcall;
end;
{$EXTERNALSYM ITfDisplayAttributeMgr}
// *********************************************************************//
// Interface: ITfDisplayAttributeNotifySink
// Flags: (0)
// GUID: {AD56F402-E162-4F25-908F-7D577CF9BDA9}
// *********************************************************************//
ITfDisplayAttributeNotifySink = interface(IUnknown)
['{AD56F402-E162-4F25-908F-7D577CF9BDA9}']
function OnUpdateInfo: HResult; stdcall;
end;
{$EXTERNALSYM ITfDisplayAttributeNotifySink}
// *********************************************************************//
// Interface: ITfCategoryMgr
// Flags: (0)
// GUID: {C3ACEFB5-F69D-4905-938F-FCADCF4BE830}
// *********************************************************************//
ITfCategoryMgr = interface(IUnknown)
['{C3ACEFB5-F69D-4905-938F-FCADCF4BE830}']
function RegisterCategory(var rclsid: TGUID; var rcatid: TGUID; var rguid: TGUID): HResult; stdcall;
function UnregisterCategory(var rclsid: TGUID; var rcatid: TGUID; var rguid: TGUID): HResult; stdcall;
function EnumCategoriesInItem(var rguid: TGUID; out ppenum: IEnumGUID): HResult; stdcall;
function EnumItemsInCategory(var rcatid: TGUID; out ppenum: IEnumGUID): HResult; stdcall;
function FindClosestCategory(var rguid: TGUID; out pcatid: TGUID; ppcatidList: PPGUID;
ulCount: LongWord): HResult; stdcall;
// !! "var word" -> PWideChar
function RegisterGUIDDescription(var rclsid: TGUID; var rguid: TGUID; pchDesc: PWideChar;
cch: LongWord): HResult; stdcall;
function UnregisterGUIDDescription(var rclsid: TGUID; var rguid: TGUID): HResult; stdcall;
function GetGUIDDescription(var rguid: TGUID; out pbstrDesc: WideString): HResult; stdcall;
function RegisterGUIDDWORD(var rclsid: TGUID; var rguid: TGUID; dw: LongWord): HResult; stdcall;
function UnregisterGUIDDWORD(var rclsid: TGUID; var rguid: TGUID): HResult; stdcall;
function GetGUIDDWORD(var rguid: TGUID; out pdw: LongWord): HResult; stdcall;
function RegisterGUID(var rguid: TGUID; out pguidatom: TfGuidAtom): HResult; stdcall;
function GetGUID(guidatom: TfGuidAtom; out pguid: TGUID): HResult; stdcall;
function IsEqualTfGuidAtom(guidatom: TfGuidAtom; var rguid: TGUID; out pfEqual: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfCategoryMgr}
// *********************************************************************//
// Interface: ITfSourceSingle
// Flags: (0)
// GUID: {73131F9C-56A9-49DD-B0EE-D046633F7528}
// *********************************************************************//
ITfSourceSingle = interface(IUnknown)
['{73131F9C-56A9-49DD-B0EE-D046633F7528}']
function AdviseSingleSink(tid: TfClientId; var riid: TGUID; const punk: IUnknown): HResult; stdcall;
function UnadviseSingleSink(tid: TfClientId; var riid: TGUID): HResult; stdcall;
end;
{$EXTERNALSYM ITfSourceSingle}
// *********************************************************************//
// Interface: ITfUIElementMgr
// Flags: (0)
// GUID: {EA1EA135-19DF-11D7-A6D2-00065B84435C}
// *********************************************************************//
ITfUIElementMgr = interface(IUnknown)
['{EA1EA135-19DF-11D7-A6D2-00065B84435C}']
function BeginUIElement(const pElement: ITfUIElement; var pbShow: Integer;
out pdwUIElementId: LongWord): HResult; stdcall;
function UpdateUIElement(dwUIElementId: LongWord): HResult; stdcall;
function EndUIElement(dwUIElementId: LongWord): HResult; stdcall;
function GetUIElement(dwUIElementId: LongWord; out ppElement: ITfUIElement): HResult; stdcall;
function EnumUIElements(out ppenum: IEnumTfUIElements): HResult; stdcall;
end;
{$EXTERNALSYM ITfUIElementMgr}
// *********************************************************************//
// Interface: ITfUIElementSink
// Flags: (0)
// GUID: {EA1EA136-19DF-11D7-A6D2-00065B84435C}
// *********************************************************************//
ITfUIElementSink = interface(IUnknown)
['{EA1EA136-19DF-11D7-A6D2-00065B84435C}']
function BeginUIElement(dwUIElementId: LongWord; var pbShow: Integer): HResult; stdcall;
function UpdateUIElement(dwUIElementId: LongWord): HResult; stdcall;
function EndUIElement(dwUIElementId: LongWord): HResult; stdcall;
end;
{$EXTERNALSYM ITfUIElementSink}
// *********************************************************************//
// Interface: ITfCandidateListUIElement
// Flags: (0)
// GUID: {EA1EA138-19DF-11D7-A6D2-00065B84435C}
// *********************************************************************//
ITfCandidateListUIElement = interface(ITfUIElement)
['{EA1EA138-19DF-11D7-A6D2-00065B84435C}']
function GetUpdatedFlags(out pdwFlags: LongWord): HResult; stdcall;
function GetDocumentMgr(out ppdim: ITfDocumentMgr): HResult; stdcall;
function GetCount(out puCount: SYSUINT): HResult; stdcall;
function GetSelection(out puIndex: SYSUINT): HResult; stdcall;
function GetString(uIndex: SYSUINT; out pstr: WideString): HResult; stdcall;
function GetPageIndex(out pIndex: SYSUINT; uSize: SYSUINT; out puPageCnt: SYSUINT): HResult; stdcall;
function SetPageIndex(var pIndex: SYSUINT; uPageCnt: SYSUINT): HResult; stdcall;
function GetCurrentPage(out puPage: SYSUINT): HResult; stdcall;
end;
{$EXTERNALSYM ITfCandidateListUIElement}
// *********************************************************************//
// Interface: ITfCandidateListUIElementBehavior
// Flags: (0)
// GUID: {85FAD185-58CE-497A-9460-355366B64B9A}
// *********************************************************************//
ITfCandidateListUIElementBehavior = interface(ITfCandidateListUIElement)
['{85FAD185-58CE-497A-9460-355366B64B9A}']
function SetSelection(nIndex: SYSUINT): HResult; stdcall;
function Finalize: HResult; stdcall;
function Abort: HResult; stdcall;
end;
{$EXTERNALSYM ITfCandidateListUIElementBehavior}
// *********************************************************************//
// Interface: ITfReadingInformationUIElement
// Flags: (0)
// GUID: {EA1EA139-19DF-11D7-A6D2-00065B84435C}
// *********************************************************************//
ITfReadingInformationUIElement = interface(ITfUIElement)
['{EA1EA139-19DF-11D7-A6D2-00065B84435C}']
function GetUpdatedFlags(out pdwFlags: LongWord): HResult; stdcall;
function GetContext(out ppic: ITfContext): HResult; stdcall;
function GetString(out pstr: WideString): HResult; stdcall;
function GetMaxReadingStringLength(out pcchMax: SYSUINT): HResult; stdcall;
function GetErrorIndex(out pErrorIndex: SYSUINT): HResult; stdcall;
function IsVerticalOrderPreferred(out pfVertical: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfReadingInformationUIElement}
// *********************************************************************//
// Interface: ITfTransitoryExtensionUIElement
// Flags: (0)
// GUID: {858F956A-972F-42A2-A2F2-0321E1ABE209}
// *********************************************************************//
ITfTransitoryExtensionUIElement = interface(ITfUIElement)
['{858F956A-972F-42A2-A2F2-0321E1ABE209}']
function GetDocumentMgr(out ppdim: ITfDocumentMgr): HResult; stdcall;
end;
{$EXTERNALSYM ITfTransitoryExtensionUIElement}
// *********************************************************************//
// Interface: ITfTransitoryExtensionSink
// Flags: (0)
// GUID: {A615096F-1C57-4813-8A15-55EE6E5A839C}
// *********************************************************************//
ITfTransitoryExtensionSink = interface(IUnknown)
['{A615096F-1C57-4813-8A15-55EE6E5A839C}']
function OnTransitoryExtensionUpdated(const pic: ITfContext; ecReadOnly: TfEditCookie;
const pResultRange: ITfRange;
const pCompositionRange: ITfRange;
out pfDeleteResultRange: Integer): HResult; stdcall;
end;
{$EXTERNALSYM ITfTransitoryExtensionSink}
// *********************************************************************//
// Interface: ITfToolTipUIElement
// Flags: (0)
// GUID: {52B18B5C-555D-46B2-B00A-FA680144FBDB}
// *********************************************************************//
ITfToolTipUIElement = interface(ITfUIElement)
['{52B18B5C-555D-46B2-B00A-FA680144FBDB}']
function GetString(out pstr: WideString): HResult; stdcall;
end;
{$EXTERNALSYM ITfToolTipUIElement}
// *********************************************************************//
// Interface: ITfReverseConversionList
// Flags: (0)
// GUID: {151D69F0-86F4-4674-B721-56911E797F47}
// *********************************************************************//
ITfReverseConversionList = interface(IUnknown)
['{151D69F0-86F4-4674-B721-56911E797F47}']
function GetLength(out puIndex: SYSUINT): HResult; stdcall;
function GetString(uIndex: SYSUINT; out pbstr: WideString): HResult; stdcall;
end;
{$EXTERNALSYM ITfReverseConversionList}
// *********************************************************************//
// Interface: ITfReverseConversion
// Flags: (0)
// GUID: {A415E162-157D-417D-8A8C-0AB26C7D2781}
// *********************************************************************//
ITfReverseConversion = interface(IUnknown)
['{A415E162-157D-417D-8A8C-0AB26C7D2781}']
function DoReverseConversion(lpstr: PWideChar; out ppList: ITfReverseConversionList): HResult; stdcall;
end;
{$EXTERNALSYM ITfReverseConversion}
// *********************************************************************//
// Interface: ITfReverseConversionMgr
// Flags: (0)
// GUID: {B643C236-C493-41B6-ABB3-692412775CC4}
// *********************************************************************//
ITfReverseConversionMgr = interface(IUnknown)
['{B643C236-C493-41B6-ABB3-692412775CC4}']
function GetReverseConversion(langid: Word; var guidProfile: TGUID; dwflag: LongWord;
out ppReverseConversion: ITfReverseConversion): HResult; stdcall;
end;
{$EXTERNALSYM ITfReverseConversionMgr}
//============================================================================================================================
//------------------------------------------------------------------------------------------------------------------------------
// Moved C language section
type
PTfThreadMgr = ^ITfThreadMgr;
{$EXTERNALSYM PTfThreadMgr}
PPTfThreadMgr = ^PTfThreadMgr;
{$EXTERNALSYM PPTfThreadMgr}
PTfInputProcessorProfiles = ^ITfInputProcessorProfiles;
{$EXTERNALSYM PTfInputProcessorProfiles}
PPTfInputProcessorProfiles = ^PTfInputProcessorProfiles;
{$EXTERNALSYM PPTfInputProcessorProfiles}
PTfDisplayAttributeMgr = ^ITfDisplayAttributeMgr;
{$EXTERNALSYM PTfDisplayAttributeMgr}
PPTfDisplayAttributeMgr = ^PTfDisplayAttributeMgr;
{$EXTERNALSYM PPTfDisplayAttributeMgr}
// PTfLangBarMgr = ^ITfLangBarMgr;
// {$EXTERNALSYM PTfLangBarMgr}
// PPTfLangBarMgr = ^PTfLangBarMgr;
// {$EXTERNALSYM PPTfLangBarMgr}
// PTfLangBarItemMgr = ^ITfLangBarItemMgr;
// {$EXTERNALSYM PTfLangBarItemMgr}
// PPTfLangBarItemMgr = ^PTfLangBarItemMgr;
// {$EXTERNALSYM PPTfLangBarItemMgr}
PTfCategoryMgr = ^ITfCategoryMgr;
{$EXTERNALSYM PTfCategoryMgr}
PPTfCategoryMgr = ^PTfCategoryMgr;
{$EXTERNALSYM PPTfCategoryMgr}
function TF_CreateThreadMgr(pptim: PPTfThreadMgr): HRESULT; stdcall;
{$EXTERNALSYM TF_CreateThreadMgr}
function TF_GetThreadMgr(pptim: PPTfThreadMgr): HRESULT; stdcall;
{$EXTERNALSYM TF_GetThreadMgr}
function TF_CreateInputProcessorProfiles(ppipr: PPTfInputProcessorProfiles): HRESULT; stdcall;
{$EXTERNALSYM TF_CreateInputProcessorProfiles}
function TF_CreateDisplayAttributeMgr(ppdam: PPTfDisplayAttributeMgr): HRESULT; stdcall;
{$EXTERNALSYM TF_CreateDisplayAttributeMgr}
//function TF_CreateLangBarMgr(pppbm: PPTfLangBarMgr): HRESULT; stdcall;
//{$EXTERNALSYM TF_CreateLangBarMgr}
//function TF_CreateLangBarItemMgr(pplbim: PPTfLangBarItemMgr): HRESULT; stdcall;
//{$EXTERNALSYM TF_CreateLangBarItemMgr}
function TF_CreateCategoryMgr(ppcat: PPTfCategoryMgr): HRESULT; stdcall;
{$EXTERNALSYM TF_CreateCategoryMgr}
//============================================================================================================================
// InputScope declarations.
type
InputScope = (
// common input scopes
IS_DEFAULT = 0,
IS_URL = 1,
IS_FILE_FULLFILEPATH = 2,
IS_FILE_FILENAME = 3,
IS_EMAIL_USERNAME = 4,
IS_EMAIL_SMTPEMAILADDRESS = 5,
IS_LOGINNAME = 6,
IS_PERSONALNAME_FULLNAME = 7,
IS_PERSONALNAME_PREFIX = 8,
IS_PERSONALNAME_GIVENNAME = 9,
IS_PERSONALNAME_MIDDLENAME = 10,
IS_PERSONALNAME_SURNAME = 11,
IS_PERSONALNAME_SUFFIX = 12,
IS_ADDRESS_FULLPOSTALADDRESS = 13,
IS_ADDRESS_POSTALCODE = 14,
IS_ADDRESS_STREET = 15,
IS_ADDRESS_STATEORPROVINCE = 16,
IS_ADDRESS_CITY = 17,
IS_ADDRESS_COUNTRYNAME = 18,
IS_ADDRESS_COUNTRYSHORTNAME = 19,
IS_CURRENCY_AMOUNTANDSYMBOL = 20,
IS_CURRENCY_AMOUNT = 21,
IS_DATE_FULLDATE = 22,
IS_DATE_MONTH = 23,
IS_DATE_DAY = 24,
IS_DATE_YEAR = 25,
IS_DATE_MONTHNAME = 26,
IS_DATE_DAYNAME = 27,
IS_DIGITS = 28,
IS_NUMBER = 29,
IS_ONECHAR = 30,
IS_PASSWORD = 31,
IS_TELEPHONE_FULLTELEPHONENUMBER = 32,
IS_TELEPHONE_COUNTRYCODE = 33,
IS_TELEPHONE_AREACODE = 34,
IS_TELEPHONE_LOCALNUMBER = 35,
IS_TIME_FULLTIME = 36,
IS_TIME_HOUR = 37,
IS_TIME_MINORSEC = 38,
IS_NUMBER_FULLWIDTH = 39,
IS_ALPHANUMERIC_HALFWIDTH = 40,
IS_ALPHANUMERIC_FULLWIDTH = 41,
IS_CURRENCY_CHINESE = 42,
IS_BOPOMOFO = 43,
IS_HIRAGANA = 44,
IS_KATAKANA_HALFWIDTH = 45,
IS_KATAKANA_FULLWIDTH = 46,
IS_HANJA = 47,
IS_HANJA_HALFWIDTH = 48,
IS_HANJA_FULLWIDTH = 49,
IS_SEARCH = 50,
IS_FORMULA = 51,
// special input scopes for ITfInputScope
IS_PHRASELIST = -1,
IS_REGULAREXPRESSION = -2,
IS_SRGS = -3,
IS_XML = -4,
IS_ENUMSTRING = -5
);
TInputScope = InputScope;
PInputScope = ^TInputScope;
PEnumString = ^IEnumString;
//
// MSCTF entry
//
function SetInputScope(hwnd: HWND; inputscope: TInputScope): HRESULT; stdcall;
{ EXTERNALSYM SetInputScope}
function SetInputScopes(hwnd: HWND; pInputScopes: PInputScope; cInputScopes: UINT;
ppszPhraseList: PLPWSTR; cPhrases: UINT; pszRegExp: LPWSTR; pszSRGS: LPWSTR): HRESULT; stdcall;
{$EXTERNALSYM SetInputScopes}
function SetInputScopeXML(hwnd: HWND; pszXML: LPWSTR): HRESULT; stdcall;
{$EXTERNALSYM SetInputScopeXML}
function SetInputScopes2(hwnd: HWND; pInputScopes: PInputScope; cInputScopes: UINT;
pEnumString: PEnumString; pszRegExp: LPWSTR; pszSRGS: LPWSTR): HRESULT; stdcall;
{$EXTERNALSYM SetInputScopes2}
const
// GUIDs for interfaces declared in this unit
SID_ITfInputScope = '{fde1eaee-6924-4cdf-91e7-da38cff5559d}';
SID_ITfInputScope2 = '{5731eaa0-6bc2-4681-a532-92fbb74d7c41}';
IID_ITfInputScope: TGUID = SID_ITfInputScope;
IID_ITfInputScope2: TGUID = SID_ITfInputScope2;
GUID_PROP_INPUTSCOPE: TGUID = '{1713dd5a-68e7-4a5b-9af6-592a595c778d}';
type
PPInputScope = ^PInputScope;
PPBSTR = ^PBSTR;
ppEnumString = ^PEnumString;
ITfInputScope = interface(IUnknown)
[SID_ITfInputScope]
function GetInputScopes(pprgInputScopes: PPInputScope; pcCount: PUINT): HRESULT; stdcall;
function GetPhrase(ppbstrPhrases: PPBSTR; pcCount: PUINT): HRESULT; stdcall;
function GetRegularExpression( pbstrRegExp: PBSTR ): HRESULT; stdcall;
function GetSRGS(pbstrSRGS: PBSTR ): HRESULT; stdcall;
function GetXML(pbstrXML: PBSTR ): HRESULT; stdcall;
end;
{$EXTERNALSYM ITfInputScope}
ITfInputScope2 = interface(ITfInputScope)
[SID_ITfInputScope2]
function EnumWordList(ppEnumString: PPEnumString): HRESULT; stdcall;
end;
{$EXTERNALSYM ITfInputScope2}
var
// To disable TSF, you can set 0 to this global control variable.
MsCTFHandle: THandle = 0;
function IsMSCTFAvailable: Boolean;
implementation
uses
System.SysUtils, System.Win.ComObj;
const
MsCTFModName = 'Msctf.dll';
function TF_CreateThreadMgr; external MsCTFModName name 'TF_CreateThreadMgr' delayed;
function TF_GetThreadMgr; external MsCTFModName name 'TF_GetThreadMgr' delayed;
function TF_CreateInputProcessorProfiles; external MsCTFModName name 'TF_CreateInputProcessorProfiles' delayed;
function TF_CreateDisplayAttributeMgr; external MsCTFModName name 'TF_CreateDisplayAttributeMgr' delayed;
//function TF_CreateLangBarMgr; external MsCTFModName name 'TF_CreateLangBarMgr' delayed;
//function TF_CreateLangBarItemMgr; external MsCTFModName name 'TF_CreateLangBarItemMgr' delayed;
function TF_CreateCategoryMgr; external MsCTFModName name 'TF_CreateCategoryMgr' delayed;
//function SetInputScope; external MsCTFModName name 'SetInputScope' delayed;
type
TSetInputScopeProc = function(hwnd: HWND; inputscope: TInputScope): HRESULT; stdcall;
var
SetInputScopeProc: TSetInputScopeProc = nil;
function SetInputScope;
begin
if not Assigned(SetInputScopeProc) and (MsCTFHandle <> 0) then
@SetInputScopeProc := GetProcAddress(MsCTFHandle, 'SetInputScope');
if Assigned(SetInputScopeProc) then
Result := SetInputScopeProc(hwnd, inputscope)
else
Result := E_FAIL;
end;
function SetInputScopes; external MsCTFModName name 'SetInputScopes' delayed;
function SetInputScopeXML; external MsCTFModName name 'SetInputScopeXML' delayed;
function SetInputScopes2; external MsCTFModName name 'SetInputScopes2' delayed;
function IsMSCTFAvailable: Boolean;
begin
Result := MsCTFHandle <> 0;
end;
procedure InitMSCTF;
begin
if MsCTFHandle = 0 then
MsCTFHandle := SafeLoadLibrary(MsCTFModName);
end;
procedure DoneMSCTF;
begin
if MsCTFHandle <> 0 then
FreeLibrary(MsCTFHandle);
end;
initialization
InitMSCTF;
finalization
DoneMSCTF;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Edit;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
Button3: TButton;
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure SetWifiEnabled(AEnable: Boolean);
function IsWifiEnabled: Boolean;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
Androidapi.Helpers,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNIBridge,
Androidapi.JNI.WifiManager;
// Uses Permissions > Change wifi state
procedure SetWifiEnabled(AEnable: Boolean);
var
Obj: JObject;
WifiManager: JWifiManager;
begin
Obj := SharedActivityContext.getSystemService(TJContext.JavaClass.WIFI_SERVICE);
if Obj = nil then
Exit;
WifiManager := TJWifiManager.Wrap((Obj as ILocalObject).GetObjectID);
WifiManager.setWifiEnabled(AEnable);
end;
// Uses Permissions > Access wifi state
function IsWifiEnabled: Boolean;
var
Obj: JObject;
WifiManager: JWifiManager;
begin
Obj := SharedActivityContext.getSystemService(TJContext.JavaClass.WIFI_SERVICE);
if Obj = nil then
Exit;
WifiManager := TJWifiManager.Wrap((Obj as ILocalObject).GetObjectID);
Result := WifiManager.isWifiEnabled;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
SetWifiEnabled(True);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
SetWifiEnabled(False);
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
if IsWifiEnabled then
Edit1.Text := 'On'
else
Edit1.Text := 'Off';
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Controls,
SysUtils, Dialogs, OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC: HDC;
hrc: HGLRC;
function DoSelect (x, y : GLUInt) : Integer;
procedure ortho;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
antialiasing : Boolean = False;
gridSize : Integer = 20;
selectBuffer : Array [0..63] of GLuint;
modelMatrix, projMatrix : Array [0..15] of GLdouble;
viewport : Array [0..3] of GLint;
selectedPoint : GLInt = -1;
var
grid4x4 : Array [0..3, 0..3, 0..2] of GLfloat =
(
(
(-2.0, -2.0, 0.0),
(-0.5, -2.0, 0.0),
(0.5, -2.0, 0.0),
(2.0, -2.0, 0.0)),
(
(-2.0, -0.5, 0.0),
(-0.5, -0.5, 0.0),
(0.5, -0.5, 0.0),
(2.0, -0.5, 0.0)),
(
(-2.0, 0.5, 0.0),
(-0.5, 0.5, 0.0),
(0.5, 0.5, 0.0),
(2.0, 0.5, 0.0)),
(
(-2.0, 2.0, 0.0),
(-0.5, 2.0, 0.0),
(0.5, 2.0, 0.0),
(2.0, 2.0, 0.0))
);
const
uSize = 4;
vSize = 4;
implementation
{$R *.DFM}
procedure DrawControlPoints (mode : GLEnum);
var
i, j : GLUInt;
begin
glColor3f(1.0, 0.0, 0.0);
For i := 0 to 3 do
For j := 0 to 3 do begin
If mode = GL_SELECT then glLoadName (i * 4 + j);
glBegin (GL_POINTS);
glVertex3fv (@grid4x4[i][j]);
glEnd;
end;
end;
procedure TfrmGL.ortho;
begin
if ClientWidth <= ClientHeight
then
glOrtho(-4.0, 4.0, -4.0 * ClientHeight / ClientWidth,
4.0 * ClientHeight / ClientWidth, -4.0, 4.0)
else
glOrtho(-4.0 * ClientWidth / ClientHeight,
4.0 * ClientWidth / ClientHeight, -4.0, 4.0, -4.0, 4.0);
end;
function TfrmGL.DoSelect (x, y : GLUInt) : Integer;
var
hits : GLUInt;
begin
glRenderMode(GL_SELECT);
glInitNames;
glPushName(0);
glMatrixMode(GL_PROJECTION);
glPushMatrix;
glLoadIdentity;
gluPickMatrix(x, ClientHeight - y, 8.0, 8.0, @viewport);
ortho;
glMatrixMode(GL_MODELVIEW);
DrawControlPoints (GL_SELECT);
glMatrixMode(GL_PROJECTION);
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
hits := glRenderMode(GL_RENDER);
if hits <= 0
then Result := -1
else Result := selectBuffer[3];
end;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glMap2f(GL_MAP2_VERTEX_3, 0, 1, 3, uSize, 0, 1,
uSize * 3, vSize, @grid4x4);
glEvalMesh2(GL_LINE, 0, gridSize, 0, gridSize);
DrawControlPoints (GL_RENDER);
SwapBuffers(DC); // конец работы
EndPaint(Handle, ps);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
glSelectBuffer(sizeof(selectBuffer), @selectBuffer);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(gridSize, 0.0, 1.0, gridSize, 0.0, 1.0);
glPointSize(10.0);
glClearColor (0.5, 0.5, 0.75, 1.0); // цвет фона
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or
PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport (0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
ortho;
glGetDoublev(GL_PROJECTION_MATRIX, @projMatrix);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glGetDoublev(GL_MODELVIEW_MATRIX, @modelMatrix);
viewport[0] := 0;
viewport[1] := 0;
viewport[2] := ClientWidth;
viewport[3] := ClientHeight;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
selectedPoint := DoSelect (x, y);
end;
procedure TfrmGL.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
objx, objy, objz : GLdouble;
begin
If selectedPoint >= 0 then begin
gluUnProject(x, ClientHeight - y , 0.95, @modelMatrix, @projMatrix,
@viewport, objx, objy, objz);
grid4x4 [selectedPoint div 4, selectedPoint mod 4, 0] := objx;
grid4X4 [selectedPoint div 4, selectedPoint mod 4, 1] := objy;
InvalidateRect(Handle, nil, False);
end
end;
procedure TfrmGL.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
selectedPoint := -1;
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_SPACE then begin
antialiasing := not antialiasing;
If antialiasing then begin
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
end
else begin
glDisable(GL_BLEND);
glDisable(GL_LINE_SMOOTH);
glDisable(GL_POINT_SMOOTH);
end;
InvalidateRect(Handle, nil, False);
end;
If Key = VK_ESCAPE then Close
end;
end.
|
{*********************************************}
{ TeeChart Gauge Series Types }
{ Copyright (c) 2002-2004 by David Berneda }
{ All Rights Reserved }
{*********************************************}
unit TeeGauges;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
{$IFDEF CLX}
Types,
{$ENDIF}
Classes,
{$IFDEF CLR}
Types,
{$ENDIF}
Series, TeEngine;
const TeeHandDistance=30; // default pixels distance from center to labels
type
THandStyle=(hsLine,hsTriangle);
TGaugeSeries=class(TCircledSeries)
private
FAngle : Double;
FCenter : TSeriesPointer;
FDistance : Integer;
FEndPoint : TSeriesPointer;
FFullRepaint : Boolean;
FMax : Double;
FMin : Double;
FMinorDistance : Integer;
FStyle : THandStyle;
FOnChange: TNotifyEvent;
ICenter : TPoint;
FLabelsInside: Boolean;
procedure CalcLinePoints(var P0,P1:TPoint);
Function CalcPoint(const Angle:Double; Center:TPoint;
const RadiusX,RadiusY:Double):TPoint;
procedure DrawValueLine;
procedure SetAngle(const Value: Double);
procedure SetCenter(const Value: TSeriesPointer);
procedure SetDistance(const Value: Integer);
procedure SetMax(const AValue: Double);
procedure SetMin(const AValue: Double);
procedure SetStyle(const Value: THandStyle);
procedure SetValue(const AValue: Double);
procedure SetFullRepaint(const Value: Boolean);
function GetValue: Double;
procedure SetEndPoint(const Value: TSeriesPointer);
function SizePointer(APointer:TSeriesPointer):Integer;
procedure SetMinorDistance(const Value: Integer);
procedure SetLabelsInside(const Value: Boolean);
protected
Procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); override;
procedure DrawAllValues; override;
Procedure GalleryChanged3D(Is3D:Boolean); override;
class Function GetEditorClass:String; override;
Procedure NotifyNewValue(Sender:TChartSeries; ValueIndex:Integer); override; // 7.0
Procedure PrepareForGallery(IsEnabled:Boolean); override;
Procedure SetParentChart(Const Value:TCustomAxisPanel); override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
function Axis:TChartAxis;
Function Clicked(x,y:Integer):Integer; override;
Function NumSampleValues:Integer; override;
function MaxYValue:Double; override;
function MinYValue:Double; override;
published
property Center:TSeriesPointer read FCenter write SetCenter;
property Circled default True;
property CircleGradient;
property EndPoint:TSeriesPointer read FEndPoint write SetEndPoint;
property FullRepaint:Boolean read FFullRepaint write SetFullRepaint default False;
property Maximum:Double read FMax write SetMax;
property Minimum:Double read FMin write SetMin;
property MinorTickDistance:Integer read FMinorDistance write SetMinorDistance default 0;
property HandDistance:Integer read FDistance write SetDistance default TeeHandDistance;
property HandStyle:THandStyle read FStyle write SetStyle default hsLine;
property LabelsInside:Boolean read FLabelsInside write SetLabelsInside default True;
property RotationAngle default 135;
property ShowInLegend default False;
property TotalAngle:Double read FAngle write SetAngle;
property Value:Double read GetValue write SetValue;
{ events }
property OnChange:TNotifyEvent read FOnChange write FOnChange;
end;
implementation
uses {$IFDEF CLR}
Graphics,
Math,
SysUtils,
{$ELSE}
{$IFDEF CLX}
QGraphics,
{$ELSE}
Graphics,
{$ENDIF}
SysUtils, Math,
{$ENDIF}
Chart, TeCanvas, TeeProcs, TeeConst, TeeProCo;
{ TGaugeSeries }
constructor TGaugeSeries.Create(AOwner: TComponent);
begin
inherited;
FDistance:=TeeHandDistance;
Circled:=True;
ShowInLegend:=False;
FLabelsInside:=True;
FCenter:=TSeriesPointer.Create(Self);
with FCenter do
begin
Brush.Style:=bsSolid;
Color:=clBlack;
Style:=psCircle;
HorizSize:=8;
VertSize:=8;
Gradient.Visible:=True;
end;
FEndPoint:=TSeriesPointer.Create(Self);
with FEndPoint do
begin
Brush.Style:=bsSolid;
Color:=clWhite;
Style:=psCircle;
HorizSize:=3;
VertSize:=3;
Visible:=False;
end;
Add(0);
Maximum:=100;
TotalAngle:=90;
RotationAngle:=135;
end;
destructor TGaugeSeries.Destroy;
begin
FEndPoint.Free;
FCenter.Free;
inherited;
end;
Function TGaugeSeries.CalcPoint(const Angle:Double; Center:TPoint;
const RadiusX,RadiusY:Double):TPoint;
var tmpSin,
tmpCos : Extended;
begin
SinCos(Angle,tmpSin,tmpCos);
result.X:=Center.X-Round(RadiusX*tmpCos);
result.Y:=Center.Y-Round(RadiusY*tmpSin);
end;
procedure TGaugeSeries.DrawAllValues;
Procedure DrawAxis;
var P3,P4 : TPoint;
tmpR : TRect;
begin
ParentChart.Canvas.AssignVisiblePen(Axis.Axis);
P3:=CalcPoint(TeePiStep*RotationAngle,ICenter,CircleWidth,CircleHeight);
P4:=CalcPoint(TeePiStep*(360-TotalAngle+RotationAngle),ICenter,CircleWidth,CircleHeight);
tmpR:=ParentChart.ChartRect;
if Circled then
with ParentChart do
begin
if ChartWidth>ChartHeight then
begin
tmpR.Left:=ChartXCenter-(ChartHeight div 2);
tmpR.Right:=ChartXCenter+(ChartHeight div 2);
end
else
begin
tmpR.Top:=ChartYCenter-(ChartWidth div 2);
tmpR.Bottom:=ChartYCenter+(ChartWidth div 2);
end;
end;
with tmpR do
ParentChart.Canvas.Arc(Left+1,Top+1,Right,Bottom,P3.x,P3.y,P4.x,P4.y);
end;
var
tmpStep2 : Double;
IRange : Double;
tmpXRad : Double;
tmpYRad : Double;
procedure DrawMinorTicks(const Value:Double);
var t : Integer;
tmp : Double;
tmpValue : Double;
begin
for t:=1 to Axis.MinorTickCount do
begin
tmpValue:=(Value+t*tmpStep2);
if tmpValue>Maximum then break
else
begin
tmp:=TotalAngle-(tmpValue*TotalAngle/IRange);
tmp:=TeePiStep*(360-tmp+RotationAngle);
ParentChart.Canvas.Line( CalcPoint(tmp,ICenter,tmpXRad,tmpYRad),
CalcPoint(tmp,ICenter,XRadius-MinorTickDistance,YRadius-MinorTickDistance));
end;
end;
end;
var tmp : Double;
tmpAngle : Double;
tmpSin,
tmpCos : Extended;
tmpS : String;
tmpValue,
tmpStep : Double;
tmpFontH : Integer;
P3 : TPoint;
P4 : TPoint;
begin
ICenter.X:=CircleXCenter;
ICenter.Y:=CircleYCenter;
IRange:=Maximum-Minimum;
tmpStep:=Axis.Increment;
if tmpStep=0 then tmpStep:=10;
if CircleGradient.Visible then
DrawCircleGradient;
// center
if FCenter.Visible then
begin
FCenter.PrepareCanvas(ParentChart.Canvas,FCenter.Color);
FCenter.Draw(ICenter);
end;
with ParentChart,Canvas do
begin
// ticks and labels
if Axis.Ticks.Visible or Axis.Labels then
begin
AssignFont(Axis.Items.Format.Font);
AssignVisiblePen(Axis.Ticks);
BackMode:=cbmTransparent;
tmpXRad:=(XRadius-Axis.TickLength);
tmpYRad:=(YRadius-Axis.TickLength);
tmpFontH:=FontHeight;
if tmpStep<>0 then
begin
tmpValue:=Minimum;
repeat
tmp:=TotalAngle-(tmpValue*TotalAngle/IRange);
tmpAngle:=360-tmp+RotationAngle;
tmp:=TeePiStep*tmpAngle;
P3:=CalcPoint(tmp,ICenter,tmpXRad,tmpYRad);
P4:=CalcPoint(tmp,ICenter,XRadius,YRadius);
if Axis.Ticks.Visible then Line(P3,P4);
if Axis.Labels then
begin
tmpS:=FormatFloat(ValueFormat,tmpValue);
if not LabelsInside then
P3:=CalcPoint(tmp,ICenter,XRadius+tmpFontH,YRadius+tmpFontH);
Dec(P3.x,Round(TextWidth(tmpS)*0.5));
if LabelsInside then // 7.0
begin
if tmpAngle>360 then tmpAngle:=tmpAngle-360;
if tmpAngle<0 then tmpAngle:=360+tmpAngle;
SinCos(TeePiStep*tmpAngle,tmpsin,tmpCos);
Inc(P3.x,Round(TextWidth(tmpS)*0.5*tmpCos));
if (tmpAngle>180) and (tmpAngle<360) then
Inc(P3.y,Round(FontHeight*tmpSin));
end;
TextOut(P3.x,P3.y,tmpS);
end;
tmpValue:=tmpValue+tmpStep;
Until ((TotalAngle<360) and (tmpValue>Maximum)) or
((TotalAngle>=360) and (tmpValue>=Maximum));
end;
end;
// minor ticks
if Axis.MinorTicks.Visible and (Axis.MinorTickCount>0) then
begin
AssignVisiblePen(Axis.MinorTicks);
tmpXRad:=XRadius-Axis.MinorTickLength-MinorTickDistance;
tmpYRad:=YRadius-Axis.MinorTickLength-MinorTickDistance;
if tmpStep<>0 then
begin
tmpStep2:=tmpStep/(Axis.MinorTickCount+1);
tmpValue:=Minimum;
repeat
DrawMinorTicks(tmpValue);
tmpValue:=tmpValue+tmpStep;
Until tmpValue>(Maximum-tmpStep);
if tmpValue<Maximum then
DrawMinorTicks(tmpValue);
end;
end;
// axis
if Axis.Axis.Visible then DrawAxis;
// value line
if Self.Pen.Visible then DrawValueLine;
end;
end;
Function TGaugeSeries.Clicked(x,y:Integer):Integer;
var P0,P1 : TPoint;
begin
CalcLinePoints(P0,P1);
if Assigned(ParentChart) then
ParentChart.Canvas.Calculate2DPosition(X,Y,MiddleZ);
if PointInLine(TeePoint(x,y),P0,P1,2) then
result:=0
else
result:=TeeNoPointClicked;
end;
function TGaugeSeries.SizePointer(APointer:TSeriesPointer):Integer;
begin
if APointer.Visible then
begin
result:=2*APointer.VertSize;
if APointer.Pen.Visible then Inc(result,APointer.Pen.Width);
end
else result:=0;
end;
procedure TGaugeSeries.CalcLinePoints(var P0,P1:TPoint);
var tmp : Double;
tmpDist : Integer;
begin
tmp:=TeePiStep*(360-(TotalAngle-((Value-Minimum)*TotalAngle/(Maximum-Minimum)))+RotationAngle);
P1:=CalcPoint(tmp,ICenter,XRadius,YRadius);
tmpDist:=HandDistance+SizePointer(FEndPoint);
if tmpDist>0 then
P1:=PointAtDistance(ICenter,P1,tmpDist);
if FCenter.Visible and (FCenter.Style=psCircle) then
P0:=PointAtDistance(P1,ICenter,SizePointer(FCenter) div 2)
else
P0:=ICenter;
end;
procedure TGaugeSeries.DrawValueLine;
var tmp : Double;
P4 : TPoint;
tmpCenter : TPoint;
begin
CalcLinePoints(tmpCenter,P4);
if not FullRepaint then Pen.Mode:=pmNotXor
else Pen.Mode:=pmCopy;
ParentChart.Canvas.AssignVisiblePen(Pen);
if HandStyle=hsLine then
ParentChart.Canvas.Line(tmpCenter,P4)
else
begin
tmp:=ArcTan2(P4.y-tmpCenter.X,P4.x-tmpCenter.Y);
ParentChart.Canvas.Polygon([CalcPoint(tmp,tmpCenter,4,4),P4,CalcPoint(tmp+Pi,tmpCenter,4,4)]);
end;
// end point
if FEndPoint.Visible then
begin
if not FullRepaint then FEndPoint.Pen.Mode:=pmNotXor
else FEndPoint.Pen.Mode:=pmCopy;
FEndPoint.PrepareCanvas(ParentChart.Canvas,FEndPoint.Color);
if not FullRepaint then ParentChart.Canvas.Brush.Style:=bsClear;
P4:=PointAtDistance(ICenter,P4,-SizePointer(FEndPoint) div 2);
FEndPoint.Draw(P4);
end;
end;
procedure TGaugeSeries.SetAngle(const Value: Double);
begin
SetDoubleProperty(FAngle,Value);
end;
procedure TGaugeSeries.SetCenter(const Value: TSeriesPointer);
begin
FCenter.Assign(Value);
end;
procedure TGaugeSeries.SetDistance(const Value: Integer);
begin
SetIntegerProperty(FDistance,Value);
end;
procedure TGaugeSeries.SetMax(const AValue: Double);
begin
SetDoubleProperty(FMax,AValue);
Value:=Math.Min(Maximum,Value);
end;
procedure TGaugeSeries.SetMin(const AValue: Double);
begin
SetDoubleProperty(FMin,AValue);
Value:=Math.Max(Minimum,Value);
end;
procedure TGaugeSeries.SetParentChart(const Value: TCustomAxisPanel);
begin
inherited;
if not (csDestroying in ComponentState) then
begin
FCenter.ParentChart:=ParentChart;
FEndPoint.ParentChart:=ParentChart;
end;
if Assigned(ParentChart) then
begin
with TCustomChart(ParentChart) do
begin
Walls.Visible:=False;
View3D:=False;
Frame.Hide;
end;
Axis.TickLength:=14;
Axis.MinorTickLength:=6;
end;
end;
procedure TGaugeSeries.SetStyle(const Value: THandStyle);
begin
if FStyle<>Value then
begin
FStyle:=Value;
Repaint;
end;
end;
procedure TGaugeSeries.SetValue(const AValue: Double);
begin
if Value<>AValue then
begin
if not FullRepaint then DrawValueLine;
MandatoryValueList.Value[0]:=AValue;
if FullRepaint then Repaint
else DrawValueLine;
if Assigned(FOnChange) then FOnChange(Self);
end;
end;
procedure TGaugeSeries.SetFullRepaint(const Value: Boolean);
begin
SetBooleanProperty(FFullRepaint,Value);
end;
function TGaugeSeries.GetValue: Double;
begin
if Count=0 then Add(0);
result:=MandatoryValueList.Value[0];
end;
procedure TGaugeSeries.SetEndPoint(const Value: TSeriesPointer);
begin
FEndPoint.Assign(Value);
end;
procedure TGaugeSeries.AddSampleValues(NumValues: Integer; OnlyMandatory:Boolean=False);
begin
Value:=Minimum+(Maximum-Minimum)*Random;
end;
procedure TGaugeSeries.PrepareForGallery(IsEnabled: Boolean);
begin
inherited;
with Axis do
begin
MinorTickCount:=1;
TickLength:=4;
MinorTickLength:=2;
Increment:=25;
end;
HandDistance:=3;
Center.VertSize:=2;
Center.HorizSize:=2;
FullRepaint:=True;
if IsEnabled then Pen.Color:=clBlue
else Pen.Color:=clDkGray;
end;
function TGaugeSeries.NumSampleValues: Integer;
begin
result:=1;
end;
procedure TGaugeSeries.SetMinorDistance(const Value: Integer);
begin
SetIntegerProperty(FMinorDistance,Value);
end;
procedure TGaugeSeries.GalleryChanged3D(Is3D: Boolean);
begin
inherited;
ParentChart.View3D:=False;
Circled:=True;
end;
class function TGaugeSeries.GetEditorClass: String;
begin
result:='TGaugeSeriesEditor';
end;
function TGaugeSeries.MaxYValue: Double;
begin
result:=FMax;
end;
function TGaugeSeries.MinYValue: Double;
begin
result:=FMin;
end;
function TGaugeSeries.Axis: TChartAxis;
begin
result:=GetVertAxis;
end;
procedure TGaugeSeries.SetLabelsInside(const Value: Boolean);
begin
SetBooleanProperty(FLabelsInside,Value);
end;
procedure TGaugeSeries.NotifyNewValue(Sender: TChartSeries;
ValueIndex: Integer);
begin
Value:=MandatoryValueList[ValueIndex];
inherited;
end;
initialization
RegisterTeeSeries(TGaugeSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryGauge,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryExtended,1);
finalization
UnRegisterTeeSeries([TGaugeSeries]);
end.
|
unit class_props_0;
interface
implementation
uses System;
type
TNested = class
private
FCnt: Int32;
function GetCnt: Int32;
public
property Cnt: Int32 read GetCnt;
end;
TRoot = class
private
FNested: TNested;
public
property Nested: TNested read FNested;
constructor Create;
end;
function TNested.GetCnt: Int32;
begin
Result := FCNT;
end;
constructor TRoot.Create;
begin
FNested := TNested.Create();
FNested.FCNT := 8;
end;
var G: Int32;
procedure Test;
var
Obj: TRoot;
begin
Obj := TRoot.Create();
G := Obj.Nested.Cnt;
end;
initialization
Test();
finalization
Assert(G = 8);
end. |
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXSybaseASAMetaDataWriter;
interface
uses
Data.DBXCommonTable,
Data.DBXMetaDataWriter,
Data.DBXPlatform;
type
TDBXSybaseASACustomMetaDataWriter = class(TDBXBaseMetaDataWriter)
protected
procedure MakeSqlNullable(const Buffer: TDBXStringBuffer; const Column: TDBXTableRow); override;
procedure MakeSqlDropSecondaryIndex(const Buffer: TDBXStringBuffer; const Index: TDBXTableRow); override;
end;
TDBXSybaseASAMetaDataWriter = class(TDBXSybaseASACustomMetaDataWriter)
public
constructor Create;
procedure Open; override;
protected
function IsCatalogsSupported: Boolean; override;
function IsSchemasSupported: Boolean; override;
function IsSerializedIsolationSupported: Boolean; override;
function IsMultipleStatementsSupported: Boolean; override;
function IsDDLTransactionsSupported: Boolean; override;
function IsDescendingIndexConstraintsSupported: Boolean; override;
function GetSqlAutoIncrementKeyword: UnicodeString; override;
function GetSqlRenameTable: UnicodeString; override;
end;
implementation
uses
Data.DBXMetaDataNames,
Data.DBXSybaseASAMetaDataReader;
procedure TDBXSybaseASACustomMetaDataWriter.MakeSqlNullable(const Buffer: TDBXStringBuffer; const Column: TDBXTableRow);
begin
if not Column.Value[TDBXColumnsIndex.IsNullable].GetBoolean(True) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.&Not);
end;
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Nullable);
end;
procedure TDBXSybaseASACustomMetaDataWriter.MakeSqlDropSecondaryIndex(const Buffer: TDBXStringBuffer; const Index: TDBXTableRow);
var
Original: TDBXTableRow;
begin
Original := Index.OriginalRow;
Buffer.Append(TDBXSQL.Drop);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Index);
Buffer.Append(TDBXSQL.Space);
MakeSqlIdentifier(Buffer, Original.Value[TDBXIndexesIndex.SchemaName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Dot);
MakeSqlIdentifier(Buffer, Original.Value[TDBXIndexesIndex.TableName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Dot);
MakeSqlIdentifier(Buffer, Original.Value[TDBXIndexesIndex.IndexName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
constructor TDBXSybaseASAMetaDataWriter.Create;
begin
inherited Create;
Open;
end;
procedure TDBXSybaseASAMetaDataWriter.Open;
begin
if FReader = nil then
FReader := TDBXSybaseASAMetaDataReader.Create;
end;
function TDBXSybaseASAMetaDataWriter.IsCatalogsSupported: Boolean;
begin
Result := False;
end;
function TDBXSybaseASAMetaDataWriter.IsSchemasSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASAMetaDataWriter.IsSerializedIsolationSupported: Boolean;
begin
Result := False;
end;
function TDBXSybaseASAMetaDataWriter.IsMultipleStatementsSupported: Boolean;
begin
Result := False;
end;
function TDBXSybaseASAMetaDataWriter.IsDDLTransactionsSupported: Boolean;
begin
Result := False;
end;
function TDBXSybaseASAMetaDataWriter.IsDescendingIndexConstraintsSupported: Boolean;
begin
Result := False;
end;
function TDBXSybaseASAMetaDataWriter.GetSqlAutoIncrementKeyword: UnicodeString;
begin
Result := 'DEFAULT AUTOINCREMENT';
end;
function TDBXSybaseASAMetaDataWriter.GetSqlRenameTable: UnicodeString;
begin
Result := 'ALTER TABLE :SCHEMA_NAME.:TABLE_NAME RENAME :NEW_TABLE_NAME';
end;
end.
|
{*********************************************}
{ TeeGrid Software Library }
{ VCL TTextFormat Editor }
{ Copyright (c) 2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit VCLTee.Editor.Format.Text;
{$I Tee.inc}
interface
uses
{Winapi.}Windows, {Winapi.}Messages, {System.}SysUtils, {System.}Classes, {Vcl.}Graphics,
{Vcl.}Controls, {Vcl.}Forms, {Vcl.}Dialogs, {Vcl.}ComCtrls, {Vcl.}StdCtrls, Tee.Format,
{Vcl.}ExtCtrls,
{$IFDEF FPC}
ColorBox,
{$ENDIF}
VCLTee.Editor.Stroke, VCLTee.Editor.Brush;
type
TTextFormatEditor = class(TForm)
PageFormat: TPageControl;
TabFont: TTabSheet;
TabStroke: TTabSheet;
TabBrush: TTabSheet;
Label2: TLabel;
TBFontSize: TTrackBar;
Label1: TLabel;
LBFontName: TListBox;
CBFontColor: TColorBox;
GroupBox1: TGroupBox;
CBFontBold: TCheckBox;
CBFontItalic: TCheckBox;
CBFontUnderline: TCheckBox;
CBFontStrikeOut: TCheckBox;
LFontSize: TLabel;
procedure TBFontSizeChange(Sender: TObject);
procedure CBFontColorChange(Sender: TObject);
procedure LBFontNameClick(Sender: TObject);
procedure CBFontBoldClick(Sender: TObject);
procedure CBFontItalicClick(Sender: TObject);
procedure CBFontUnderlineClick(Sender: TObject);
procedure CBFontStrikeOutClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure PageFormatChange(Sender: TObject);
private
{ Private declarations }
IFormat : TTextFormat;
IBrush : TBrushEditor;
IStroke : TStrokeEditor;
procedure ChangeFontStyle(const Enable:Boolean; const AStyle:TFontStyle);
procedure SetFontSettings(const AFont:TFont);
public
{ Public declarations }
procedure RefreshFormat(const AFormat:TTextFormat);
class function Edit(const AOwner:TComponent; const AFormat:TTextFormat):Boolean; static;
class function Embedd(const AOwner:TComponent; const AParent:TWinControl;
const AFormat:TTextFormat):TTextFormatEditor; static;
end;
implementation
|
unit junor2;
interface
implementation
Function FreeSel;
begin
GlobalUnlock(gwFrameBufSel);
if FreeSelector(gwFrameBufSel) = 0 then
result:=TRUE
else result:=FALSE;
end;
{************************************************************************
* SetConfiguration
*
* This routine is responsible for setting OVERLAY JUNIOR hardware
* (registers) from the configuration information we got by ini filw.
*
* Exported: Yes
* Entry: None
* Return: TRUE, if success,
* ErrorCode, else failure.
************************************************************************}
Function SetConfiguration:Boolean;
begin
// 2x2 card-id register */
JUN_set_card_id(gConfig.bCardID);
//* 2x1 color-key register */
JUN_set_color_key(gConfig.bColorKey);
// 2x0 control register */
JUN_set_display_mode(gConfig.bDisplayMode);
// 2x3 crt-select(02:blank-timing) register */
JUN_reset_whole_display_color(); // the whole TV not set to a color
JUN_set_scan_mode(gConfig.bScanMode);
// Get status of JUNIOR card from status register */
gfExtrnVideoExist := JUN_external_video_exist();
gbTVsystemType := JUN_get_TVsystem_type();
// 3/8/94 Tang added for PAL
PortWriteByte($80, gbTVsystemType);
if gbTVsystemType = PAL then
gwVertRegOffset := $F0
else
gwVertRegOffset := 0;
// Vertical Scroll Reg. is set to F0 for PAL ver., but the origin of
// the video memory is (0,0) as usual !
gConfig.wVertScanStart := gConfig.wVertScanStart+gwVertRegOffset;
// 3/8/94 Tang added for PAL
// 2x3 crt-select(00:vertical-scroll) register */
set_vert_scroll_reg(gConfig.wVertScanStart);
// 2x3 crt-select(03:horizontal-shift) register */
set_horz_shift_reg (gConfig.wHorzScanStart);
// 2x6 ramdac-input-mask register */
set_ramdac_input_mask_reg(ramdac_input_mask_reg_val);
// 2x4,2x5 set RAMDAC register */
if JUN_GetSystemPalette(system_palette)=false then
begin
Portwritebyte($80, $99);
// use default palette to set RAMDAC */
JUN_init_ramdac_entry(palette_table);
end
else
// set RAMDAC to Windows system palette */
JUN_init_ramdac_entry(system_palette);
result:=TRUE;
end;
Function alloc_and_check_bank_access:integer;
var
i, j, nLines, bank_pos:integer;
display_mode:BYTE;
lpData:LPSTR;
label change_bank;
begin
// set video mode to video only, so write to memory cannot show at screen */
display_mode := gConfig.bDisplayMode;
JUN_set_display_mode(EXTERNAL_VIDEO_ONLY);
gbBankType:= BANK_SIZE_16K; //default bank size
bank_pos := 3; //default bank base
while (TRUE) do
case ( gbBankType ) of
1:
begin
if gwFrameBufSel or gbDiagnose =0 then
if AllocSel(bank_pos*MEMORY_SIZE_16K, MEMORY_SIZE_16K)=0 then
result:=ERR_CANNOT_ALLOCATE_SELECTOR;
nLines := 16;
break;
end;
2://BANK_SIZE_8K :
begin
if gwFrameBufSel or gbDiagnose =0 then
if AllocSel(bank_pos*MEMORY_SIZE_8K, MEMORY_SIZE_8K) =0 then
result:=ERR_CANNOT_ALLOCATE_SELECTOR;
nLines := 8;
break;
end;
end;
// special process for test version */
// restore to original mode */
// set corresponding bank address */
select_bank_address(gbBankType, bank_pos);
// select a video memory segment and a bank segment to test */
memory_seg_select(bank_pos);
select_bank_segment(gbBankType, bank_pos);
// fill this segment with pattern 0x55
for i:=0 to nLines do
for j:=0 to 1024 do
//f glpVideoMemory[(i shl 10) + j] = 0x55;
;
// check if this segment if full of pattern 0x55
for i:=0 to nLines do
for j:=0 to 1024 do
//f if ( glpVideoMemory[(i shl 10) + j] <> 0x55 )
goto change_bank;
// fill this segment with pattern 0xaa
for i:=0 to nLines do
for j:=0 to 1024 do
//f glpVideoMemory[(i shl 10) + j] = 0xaa;
;
// check if this segment if full of pattern 0xaa
for i:=0 to nLines do
for j:=0 to 1024 do
// if ( glpVideoMemory[(i<<10) + j] <> 0xaa )
goto change_bank;
// restore to original mode */
gConfig.bDisplayMode := display_mode;
JUN_set_display_mode(gConfig.bDisplayMode);
result:=1;
change_bank:
FreeSel();
gwFrameBufSel := 0;
gwNSelectors := 1;
if ( (--bank_pos) < 0 ) then
begin
PortwriteByte($80, gbBankType);
result:=ERR_BANK_ACCESS_CHECK_ERROR;
end;
end;
{***********************************************************************
* VerifyConfiguration
*
* This routine is responsible for verifying that the configuration
* information is correct. We attempt to detect the hardware and gaurantee
* that the configuration information is valid. Note! This is "verify"
* setting, not "test" hardware.
*
* Exported: Yes
* Entry: None
* Return: TRUE, if success,
* ErrorCode, else failure.
************************************************************************}
Function VerifyConfiguration:integer;
var
wReturnCode:integer;
begin
// 1. Verify I/O Port AND Card ID */
wReturnCode := VerifyPortAndID(gConfig.wPortBaseAddr, gConfig.bCardID);
if ( wReturnCode <> 1 ) then
result:=wReturnCode;
// 2. Verify Frame Address */
wReturnCode := VerifyFrameAddr(gConfig.wFrameAddr);
if ( wReturnCode <> 1 ) then
result:=wReturnCode;
// 3. Vefify IRQ */
wReturnCode := VerifyIRQ(gConfig.bIRQUsed);
if ( wReturnCode <> 1 ) then
result:=wReturnCode;
if ( (gConfig.bDisplayMode <> EXTERNAL_VIDEO_ONLY) and
(gConfig.bDisplayMode <> OVERLAY) ) then
gConfig.bDisplayMode := OVERLAY;
if ( (gConfig.bScanMode <> UNDERSCAN) and
(gConfig.bScanMode <> OVERSCAN) ) then
gConfig.bScanMode := OVERSCAN;
if ( gConfig.wVertScanStart > $ff ) then
gConfig.wVertScanStart :=gConfig.wVertScanStart and $ff;
if ( gConfig.wHorzScanStart > $1ff ) then
gConfig.wHorzScanStart := gConfig.wHorzScanStart and $1ff;
result:=1;
end;
Function init_io_reg_val:integer;
begin
// initialize addresses of I/O registers
control_reg := gConfig.wPortBaseAddr + $00; // control reg.
status_reg := gConfig.wPortBaseAddr + $00; // status reg.
color_key_reg := gConfig.wPortBaseAddr + $01; // color key reg.
card_id_reg := gConfig.wPortBaseAddr + $02; // card ID reg.
crt_sel_reg := gConfig.wPortBaseAddr + $03; // CRT select reg.
crt_data_reg := gConfig.wPortBaseAddr + $08; // CRT data reg.
ramdac_addr_write_reg := gConfig.wPortBaseAddr + $04; // RAMDAC address write reg.
ramdac_addr_read_reg := gConfig.wPortBaseAddr + $07; // RAMDAC address read reg.
ramdac_data_reg := gConfig.wPortBaseAddr + $05; // RAMDAC data reg.
ramdac_input_mask_reg := gConfig.wPortBaseAddr + $06; // RAMDAC input mask reg.
// initialize values of I/O registers
control_reg_val := $20; // 0010 0000 control reg.
status_reg_val := $61; // 0000 0000 status reg.
color_key_reg_val := $fc; // 1111 1100 color key reg.
card_id_reg_val := $0e; // 0000 1110 card ID reg.
crt_sel_reg_val := $64; // 1100 0000 CRT select reg.
crt_data_reg_val := $00; // 0110 0100 CRT data reg.
ramdac_addr_write_reg_val := $00; // 0000 0000 RAMDAC address write reg.
ramdac_addr_read_reg_val := $00; // 0000 0000 RAMDAC address read reg.
ramdac_input_mask_reg_val := $ff; // 0000 0000 RAMDAC input mask reg.
ramdac_data_reg_val := 0; // 0000 0000 RAMDAC data reg.
result:=1;
end; // end Function init_io_register()
Function JUN_Initialize():integer;
begin
if gbInitial=true then
begin
PortWritebyte($80, $80);
gwErrorCode := ERR_INITIALIZED_BEFORE;
result:=gwErrorCode;
end;
InitialGlobals();
if JUN_LoadConfiguration()=false then
begin
PortWriteByte($80, $81);
gwErrorCode := ERR_JUNIOR_INI_NOT_FOUND;
result:=gwErrorCode;
end;
init_io_reg_val();
gwErrorCode := 1;
gwErrorCode := VerifyConfiguration();
if gwErrorCode =0 then
begin
PortWriteByte($80, $81);
result:=gwErrorCode;
end;
SetConfiguration();
if JUN_junior_exist()=false then
begin
PortWriteByte($80, $82);
gwErrorCode := ERR_JUNIOR_CARD_NOT_EXIST;
result:=gwErrorCode;
end;
gwNSelectors := 1;
gwErrorCode := alloc_and_check_bank_access();
if gwErrorCode =0 then
result:=gwErrorCode;
//f JUN_flash_video_memory(gConfig.bColorKey);
if AllocPageBuffer() <> TRUE then
begin
FreeSel();
result:=ERR_INSUFFICIENT_MEMORY;
end;
inc(gbInitial); //Increment times of Initialization
result:=1;
end;
procedure InitialGlobals();
var
i:integer;
begin
gwVideoWidth:=720; // width of video memory at current scan mode
gwVideoHeight:=480; // height of video memory at current scan mode
// Used in libinit.asm */
gwFrameBufSel:=0; // frame buffer selector(given by Windows)
gwNSelectors:=1; // no of selectors to allocate
gbInitial:=false; // times of initialization
gbTVsystemType:=0; // type of TV system(0:NTSC, 2:PAL)
gbMemReadMode :=0; // read mode of video memory(ENABLE/DISABLE)
gbMemWriteMode:=0; // write mode of video memory(ENABLE/DISABLE)
gfExtrnVideoExist:=false;// flag of external video exist
gulEnterIntCount:=0; // times of interrupt occur
// junisr.c for scrolling */
gfHandleScroll:=FALSE; // flag to initinate ISR to start
gfScrollStop:=TRUE; // flag indicate last page
for i:=0 to 2 do
begin
gwPadded[i]:=0; // padded no. to make a multiple of 2
ghMem[i]:=0; // global handle of memory
gfBufferFull[i]:=FALSE; // flag to indicate buffer is full or not
end;
// 11/18/93 Tang added
// gfStartScroll:=FALSE; // semaphore to isr to start scrolling
// 12/06/93 Tang added */
gbBankType:=1;
gbDiagnose:=0;
// 12/22/93 Tang added */
gbVideoMode:=0;
gwImgWidthPad:=0;
gbPreMemSeg:=9; // previous selected memory segment
gbPreBnkNo:=9; // previous selected bank no.
// 3/9/94 Tang added //
gwVertRegOffset:=0;
end;
Function JUN_LoadConfiguration:Boolean;
var
fd:integer;
begin
GetWindowsDirectory(szCfgFileSpec, 144);
wsprintf(szCfgFileSpec, CFG_FILE_NAMEW);
fd := fileopen(szCfgFileSpec, fmOpenRead);
if fd = -1 then
begin
portwritebyte($80, $01);
result:=FALSE; // File does not exist. */
end;
//f if fileclose(fd) <> 0 then
//f result:=FALSE);
fileclose(fd) ;
GetPrivateProfileString('JUNIOR', 'FrameAddr', '$D000', szData, 10, szCfgFileSpec);
gConfig.wFrameAddr := strtoint(szData{, @endptr, 0});
// gConfig.wFrameAddr:=(WORD)atol(szData);
GetPrivateProfileString('JUNIOR', 'PortBaseAddr', '$280', szData, 10, szCfgFileSpec);
gConfig.wPortBaseAddr:=strtoint(szData{, ANDendptr, 0});
// gConfig.wPortBaseAddr:=(WORD)atol(szData);
GetPrivateProfileString('JUNIOR', 'CardID', '$0E', szData, 10, szCfgFileSpec);
gConfig.bCardID:=strtoint(szData{, ANDendptr, 0});
// gConfig.bCardID:=(BYTE)atol(szData);
GetPrivateProfileString('JUNIOR', 'IRQUsed', '$05', szData, 10, szCfgFileSpec);
gConfig.bIRQUsed:=strtoint(szData{, AND{endptr, 0});
// gConfig.bIRQUsed:=(BYTE)atol(szData);
GetPrivateProfileString('JUNIOR', 'ColorKey', '$FC', szData, 10, szCfgFileSpec);
gConfig.bColorKey:=strtoint(szData{, ANDendptr, 0});
// gConfig.bColorKey:=(BYTE)atol(szData);
GetPrivateProfileString('JUNIOR', 'DisplayMode', 'OVERLAY', szData, 10, szCfgFileSpec);
if ( stricomp(szData, 'EXTERNAL_VIDEO_ONLY') = 0 ) then
gConfig.bDisplayMode:=EXTERNAL_VIDEO_ONLY // EXTERNAL_VIDEO_ONLY mode //
else
gConfig.bDisplayMode:=OVERLAY; // OVERLAY mode //
GetPrivateProfileString('JUNIOR', 'ScanMode', 'OVERSCAN', szData, 10, szCfgFileSpec);
if ( stricomp(szData, 'OVERSCAN') = 0 ) then
gConfig.bScanMode:=OVERSCAN // OVERSCAN mode //
else
gConfig.bScanMode:=UNDERSCAN; // UNDERSCAN mode //
GetPrivateProfileString('JUNIOR', 'VertScanStart', '$00', szData, 10, szCfgFileSpec);
gConfig.wVertScanStart:=strtoint(szData{, ANDendptr, 0});
// gConfig.wVertScanStart:=(WORD)atol(szData);
GetPrivateProfileString('JUNIOR', 'HorzScanStart', '$00', szData, 10, szCfgFileSpec);
gConfig.wHorzScanStart:=strtoint(szData{, ANDendptr, 0});
// gConfig.wHorzScanStart:=(WORD)atol(szData);
result:=TRUE;
end;
// ***************************************************************************
// JUN_flash_video_memory(BYTE color_entry) : clear video memory
// input
// flag : TRUE => enable
// FALSE => disable
// ***************************************************************************
Function JUN_flash_video_memory( color_entry:BYTE):integer;
var
i, j, temp_ss:integer;
begin
// step 1. write color_entry to border register
set_screen_border_reg(color_entry);
for j:=0 to 4 do
begin
// step 2. set control register bit 7
// control_reg_val AND $7f(0111 1111):=$XX XXXX
// $XX XXXX
// OR A000 0000
// = AXXX XXXX
control_reg_val:=(control_reg_val AND $7f) OR FLASH_VIDEO_MEMORY;
PortWriteByte(control_reg, control_reg_val);
// step 3. wait for status register bit 7 go down (1->0)
status_reg_val:=PortReadByte(status_reg);
i:=0;
while ( (status_reg_val AND $80) and (i < 32767) ) <>0 do //add time out
begin
status_reg_val:=myinportb(status_reg);
i++;
end;
// step 4. clear control register bit 7 immediately */
control_reg_val:=(control_reg_val AND $7f);
PortWriteByte(control_reg, control_reg_val);
// flash another 3 areas to clear all video memory */
wait_vert_retrace_start();
switch ( j ) {
case 0 :
set_vert_scroll_reg( (BYTE)(gConfig.wVertScanStart+(gwVideoHeight/4)) );
break;
case 1 :
temp_ss:=( gConfig.wHorzScanStart+(gwVideoWidth/4) );
// 11/26/93 Tang added */
temp_ss %= $200;
set_horz_shift_reg(temp_ss);
// set_horz_shift_reg1(temp_ss);
break;
case 2 :
set_vert_scroll_reg( (BYTE)gConfig.wVertScanStart );
break;
//01/04/94 case 3 :
//01/04/94 set_horz_shift_reg( gConfig.wHorzScanStart );
// set_horz_shift_reg1( gConfig.wHorzScanStart );
//01/04/94 break;
}
} // end of FOR loop */
//01/04/94 Tang, Reset coordinate to original
gConfig.wVertScanStart:=0;
gConfig.wHorzScanStart:=0;
// 3/9/94 Tang added
gConfig.wVertScanStart += gwVertRegOffset;
set_vert_scroll_reg( (BYTE)gConfig.wVertScanStart );
set_horz_shift_reg ( gConfig.wHorzScanStart );
gbPreMemSeg:=9; // previous selected memory segment
gbPreBnkNo :=9; // previous selected bank no.
//01/04/94 Tang, Reset coordinate to original
result:=TRUE);
} // end Function JUN_enable_vert_sync_int()
Function AllocPageBuffer(void)
{
DWORD dwDataSize, dwActAllocSize;
WORD padded;
// Allocate 2 buffers used for WriteBitmap and ISR to scroll pages */
padded:=gwVideoWidth % 2;
// insure to make the width is a multiple of 2 */
dwDataSize:=(DWORD)(gwVideoWidth+padded) * gwVideoHeight;
//01/06/94 Tang added
dwActAllocSize:=GlobalCompact(dwDataSize);
//01/06/94 Tang added
ghMem[0]:=GlobalAlloc(GHND, dwDataSize);
if ( !ghMem[0] ) {
PortWriteByte($80, $08);
#ifdef TEST_VER
dwActAllocSize:=GlobalCompact(dwDataSize);
wsprintf(debugstr, '1: Request=%ld, Actual=%ld', dwDataSize, dwActAllocSize);
MessageBox(NULL, debugstr, 'GlobalAlloc Memory Error!', MB_OK OR MB_ICONEXCLAMATION);
#endif
gwErrorCode:=ERR_MEMORY_ALLOCATE_ERROR;
result:=gwErrorCode);
}
ghpBitsStart[0]:=glpPageBuf:=GlobalLock(ghMem[0]);
//01/06/94 Tang added
dwActAllocSize:=GlobalCompact(dwDataSize);
//01/06/94 Tang added
ghMem[1]:=GlobalAlloc(GHND, dwDataSize);
if ( !ghMem[1] ) {
PortWriteByte($80, $08);
#ifdef TEST_VER
wsprintf(debugstr, '2: Request=%ld, Actual=%ld', dwDataSize, dwActAllocSize);
MessageBox(NULL, debugstr, 'GlobalAlloc Memory Error!', MB_OK OR MB_ICONEXCLAMATION);
#endif
GlobalUnlock( ghMem[0] );
GlobalFree( ghMem[0] );
gwErrorCode:=ERR_MEMORY_ALLOCATE_ERROR;
result:=gwErrorCode);
}
ghpBitsStart[1]:=GlobalLock(ghMem[1]);
InitialPageBuffer();
result:=TRUE);
}
;****************************************************************************
; FreeSelectors
;
; Routine to free all selectors allocated at initialization time.
;
; Exported: No
; Entry: None
; Destroys: AX,BX,CX,FLAGS
;****************************************************************************
_FreeSelectors PROC far
push bp
mov bp, sp
push si
push di
mov bx, _gwFrameBufSel ;First selector.
mov ax, 0001 ;Free selector.
int 31H
; xor ax, ax
mov ax, 1
jnc freeOK
mov ax, -1
freeOK:
pop di
pop si
mov sp, bp
pop bp
ret
_FreeSelectors ENDP
// ---------------------------------------------------------------------------
// 2X2(WRITE) card ID register Functions
// ---------------------------------------------------------------------------
// ***************************************************************************
// JUN_set_card_id() : set card ID value
// ***************************************************************************
Function JUN_set_card_id(BYTE id)
{
card_id_reg_val:=id AND $0f;
PortWriteByte(card_id_reg, card_id_reg_val);
return(TRUE);
}
// ---------------------------------------------------------------------------
// 2X1(WRITE) corlor key register Functions
// ---------------------------------------------------------------------------
// ***************************************************************************
// JUN_set_color_key() : set color key value
// input
// color_key_ramdac_entry : RAMDAC entry of color key
// ***************************************************************************
Function PASCAL JUN_set_color_key(BYTE color_key_ramdac_entry)
{
color_key_reg_val:=color_key_ramdac_entry;
PortWriteByte(color_key_reg, color_key_reg_val);
// 10/27 Tang added
gConfig.bColorKey:=color_key_reg_val;
return(TRUE);
}
// ***************************************************************************
// JUN_set_display_mode() : set one of 2 display modes
// input
// display_mode : EXTERNAL_VIDEO_ONLY ($00 : 0000 0000)
// OVERLAY ($20 : 0010 0000)
// ***************************************************************************
Function PASCAL JUN_set_display_mode(BYTE display_mode)
{
// step 1. control_reg_val AND $df(1101 1111):=$$ XXXX
// step 2. XX$ XXXX
// OR 00A0 0000 (video_mode)
// = XXAX XXXX
control_reg_val:=(control_reg_val AND $df) OR display_mode;
PortWriteByte(control_reg, control_reg_val);
// 10/27 Tang added
gConfig.bDisplayMode:=display_mode;
return(TRUE);
} // end Function JUN_set_display_mode()
// ***************************************************************************
// JUN_reset_whole_display_color() : not set the whole display to a certain color
// ***************************************************************************
Function PASCAL JUN_reset_whole_display_color(void)
{
crt_sel_reg_val:=( crt_sel_reg_val AND $fc ) OR BLANK_TIMING_REG_SEL;
select_crt_register(crt_sel_reg_val); // select horizontal shift register
// step 00$X$X
// OR 00000100 ($04)
// := 000$1XX
crt_data_reg_val OR= RESET_WHOLE_DISPLAY_COLOR; // $04 : reset whole display to a color
PortWriteByte(crt_data_reg, crt_data_reg_val);
return(TRUE);
} // end Function JUN_reset_whole_display_color(void)
// ***************************************************************************
// JUN_set_scan_mode : set TV in underscan/overscan mode
// ***************************************************************************
Function PASCAL JUN_set_scan_mode(BYTE time_interval)
{
if ( time_interval = UNDERSCAN ) {
if ( JUN_get_TVsystem_type() = NTSC ) {
select_horizontal_width640();
select_vertical_height400();
gwVideoWidth :=NTSC_XRES_UNDERSCAN;
gwVideoHeight:=NTSC_YRES_UNDERSCAN;
}
else { // PAL
select_horizontal_width720(); //800 for PAL
select_vertical_height480(); //480 for PAL
gwVideoWidth :=PAL_XRES_UNDERSCAN;
gwVideoHeight:=PAL_XRES_UNDERSCAN;
}
}
else { // Overscan
if ( JUN_get_TVsystem_type() = NTSC ) {
select_horizontal_width720();
select_vertical_height480();
gwVideoWidth :=NTSC_XRES_OVERSCAN;
gwVideoHeight:=NTSC_YRES_OVERSCAN;
}
else { // PAL
select_horizontal_width756(); //924 for PAL
select_vertical_height510(); //510 for PAL
gwVideoWidth :=PAL_XRES_OVERSCAN;
gwVideoHeight:=PAL_YRES_OVERSCAN;
}
}
// 10/27 Tang added
gConfig.bScanMode:=time_interval;
return(TRUE);
} // end Function JUN_set_scan_mode
// ***************************************************************************
// JUN_clear_TVscreen() : clear the TV screen to black color
// ***************************************************************************
Function PASCAL JUN_clear_TVscreen(void)
{
// set video mode to OVERLAY mode
JUN_set_display_mode(OVERLAY);
/*
JUN_set_whole_display_color(palette_table[JUN_BLACK].peRed,
palette_table[JUN_BLACK].peGreen,
palette_table[JUN_BLACK].peBlue);
*/
JUN_set_whole_display_color(JUN_BLACK);
return(TRUE);
} // end Function JUN_clear_TVscreen()
// ***************************************************************************
// JUN_external_video_exist() : check if external video source exists
// return
// TRUE => exist
// FALSE => not exist
// ***************************************************************************
Function PASCAL JUN_external_video_exist(void)
{
/* 10/28/93 Tang added to set OVERLAY mode */
control_reg_val:=(control_reg_val OR $20); //FORCEPC bit, OVERLAY-0010 0000
PortWriteByte(control_reg, control_reg_val);
/* 10/28/93 Tang added to set OVERLAY mode */
status_reg_val:=myinportb(status_reg);
// status_reg_val:=inportb(status_reg);
if ( status_reg_val AND EXTERNAL_VIDEO_EXIST ) // 0000 0001:=01
return(TRUE);
else
return(FALSE);
} // end Function external_video_exist(void)
// ***************************************************************************
// JUN_get_TVsystem_type() : get the TV system type of Junior
// return
// NTSC => NTSC TV system 0000 0000:=00
// PAL => PAL TV system 0000 0010:=02
// ***************************************************************************
Function PASCAL JUN_get_TVsystem_type(void)
{
status_reg_val:=inportb(status_reg);
if ( status_reg_val AND PAL ) //PAL=0000 0010
return(PAL);
else
return(NTSC);
}
// 2X8(WRITE) CRT data register Functions
// ---------------------------------------------------------------------------
// ***************************************************************************
// set_vert_scroll_reg() : set vertical scroll register (vertical scan start
// point)
// input
// scan_start : vertical scan start point
// ***************************************************************************
Function set_vert_scroll_reg(BYTE scan_start)
{
/* first clear bit 0,1, i.e., 1111 1100:=$fc then
OR 0100 0000:=$00:=VERTICAL_SCROLL_REG_SEL */
crt_sel_reg_val:=( crt_sel_reg_val AND $fc ) OR VERT_SCROLL_REG_SEL;
select_crt_register(crt_sel_reg_val); // select vertical scroll register
PortWriteByte(crt_data_reg, scan_start);
return(TRUE);
}
// ***************************************************************************
// set_horz_shift_reg() : set horizontal shift register
// input
// shift_pixel : #pixel of horizontal shift(9 bits)
// ***************************************************************************
Function set_horz_shift_reg(UINT shift_pixel)
{
BYTE low_byte, msb_byte;
/* 1. Set horz scan start's msb */
msb_byte :=(BYTE) ((shift_pixel>>8) AND $01);
set_horz_shift_reg_msb(msb_byte); // set MSB value into CRT select register
/* first clear bit 0,1, i.e., 1111 1100:=$fc then
OR 0100 0011:=$03:=HORZ_SHIFT_REG_SEL */
crt_sel_reg_val:=( crt_sel_reg_val AND $fc ) OR HORZ_SHIFT_REG_SEL;
select_crt_register(crt_sel_reg_val); // select horizontal shift register
low_byte:=(BYTE) shift_pixel;
PortWriteByte(crt_data_reg, low_byte);
return(TRUE);
}
// ***************************************************************************
// JUN_init_ramdac_entry() : initialize RAMDAC entries values
//
// Note: each R.G.B color is 6-bit long, but the RGB color of input palette
// is rang from 0 to FF(8-bit), so we must round to 6-bit.
// ***************************************************************************
Function PASCAL JUN_init_ramdac_entry(PALETTEENTRY far *palette)
{
int i;
set_ramdac_address_write_reg(0); // set the first RAMDAC entry to write
for(i=0; i<256; i++)
{
// set_ramdac_address_write_reg(i);
set_ramdac_data_reg((palette[i].peRed>>2),
(palette[i].peGreen>>2),
(palette[i].peBlue>>2) );
// set_ramdac_data_reg(palette[i].rgbRed,
// palette[i].rgbGreen,
// palette[i].rgbBlue);
} // for(i=0; i<256; i++)
return(TRUE);
} // end Function JUN_init_ramdac_entry(void)
// ***************************************************************************
// select_bank_address() : select address of a bank
// input
// bank_no : the desired bank no(from 0 to 7, 8*8K=64K)
// 0 3, 4*16K=64K
// ***************************************************************************
Function select_bank_address(BYTE type, BYTE bank_no)
{
// step 1. crt_sel_reg_val AND $1f(0001 1111):=00$ XXXX
// step 2. 00$ XXXX
// OR ABC0 0000
// = ABCX XXXX
switch ( type ) {
case BANK_SIZE_64K :
return(TRUE);
case BANK_SIZE_16K :
crt_sel_reg_val:=( crt_sel_reg_val AND $1f ) OR ( bank_no << 6 );
break;
case BANK_SIZE_8K :
crt_sel_reg_val:=( crt_sel_reg_val AND $1f ) OR ( bank_no << 5 );
break;
}
PortWriteByte(crt_sel_reg, crt_sel_reg_val);
return(TRUE);
} // end Function select_bank_address(BYTE type, BYTE bank_no)
// ***************************************************************************
// memory_seg_select() : select a memory segment(64K) from Video memory whose
// size is 8 segments(512K)
// input
// seg_no : segment number ranging from
// MEMORY_SEGMENT0(0)
// to
// MEMORY_SEGMENT7(7)
// ***************************************************************************
Function memory_seg_select(BYTE seg_no)
{
// step 1. control_reg_val AND $f8(X111 1000):=XXXX X000
// step 2. XXXX X000
// OR 0000 0ABC (seg_no)
// = XXXX XABC
control_reg_val:=(control_reg_val AND $f8) OR seg_no;
PortWriteByte(control_reg, control_reg_val);
return(TRUE);
} // end Function memory_seg_select()
// ***************************************************************************
// select_bank_segment() : select 1(8k or 16k) of a 64K segment
// input
// bank_no : the desired bank no(from 0 to 7 for 8k, 8*8K=64K)
// 0 3 16k,4*16K=64K
// ***************************************************************************
Function select_bank_segment(BYTE type, BYTE bank_no)
{
// step 1. crt_sel_reg_val AND $e3(1110 0011):=XXX0 0$X
// step 2. XXX0 0$X
// OR 000A BC00
// = XXXA BC00
switch ( type ) {
case BANK_SIZE_64K :
return(TRUE);
case BANK_SIZE_16K :
crt_sel_reg_val:=( crt_sel_reg_val AND $e3 ) OR ( bank_no << 3 );
break;
case BANK_SIZE_8K :
crt_sel_reg_val:=( crt_sel_reg_val AND $e3 ) OR ( bank_no << 2 );
break;
}
PortWriteByte(crt_sel_reg, crt_sel_reg_val);
return(TRUE);
} // end Function select_bank_segment(BYTE type, BYTE bank_no)
int NEAR VerifyPortAndID(WORD wPort, BYTE bCardID)
{
int i, wCurrStatus;
/* I/O port must be 2x0, or we know it is bad. */
if ( ! ( (wPort >= $200 and wPort <= $2ff) and !(wPort AND $000f) ) )
return(ERR_IO_PORT_SETTING_BAD);
/* Card ID must be from 0 to 14, or we know it is bad. */
if ( ! ( bCardID <= 14 ) )
return(ERR_CARD_ID_SETTING_BAD);
/* Check card ID */
JUN_set_card_id(bCardID);
wCurrStatus:=JUN_get_junior_status();
if ( (BYTE)(wCurrStatus) = $ff )
return(ERR_JUNIOR_CARD_NOT_EXIST);
/* Check I/O port */
randomize(); //Initialize the random number generator
for ( i=0; i<3; i++ )
if ( ! VerifyRamdac() )
return(ERR_JUNIOR_CARD_NOT_EXIST);
return(TRUE);
}
int NEAR VerifyFrameAddr(WORD wFrameAddr)
{
/* Frame address must be $D000 or $E000, or we know it is bad. */
if ( ((BYTE)(wFrameAddr>>12) >= $0B and (BYTE)(wFrameAddr>>12) <= $0E) ) {
if ( wFrameAddr AND $0FFF )
return(ERR_FRAME_ADDR_SETTING_BAD);
}
else
return(ERR_FRAME_ADDR_SETTING_BAD);
return(TRUE);
}
int NEAR VerifyIRQ(BYTE bIRQ)
{
time_t first, second;
UINT count, int_count;
BYTE status_reg;
/* Interrupt must be from 3 to 7, or we know it is bad. */
if ( ! ( bIRQ >= 3 and bIRQ <= 7 ) )
return(ERR_IRQ_SETTING_BAD);
/* Set interrupt vector AND mask interrupt no */
init_interrupt_test(bIRQ);
/* Step 1. Test Vsync period by polling status reg. bit 4 */
count:=0;
first:=time(NULL); /* Gets system time */
do {
/* polling Vsync to ask Vsync is generated */
wait_vert_retrace_start();
count++;
second:=time(NULL); /* Gets system time again */
/* calculates the elapsed time in seconds, return as a double */
} while ( difftime(second, first) < 1 ); //wait for 1 second
/* Step 2. Test Vsync interrupt with ISR(junaux.c) */
gulEnterIntCount:=0;
// enable interrupt
JUN_enable_vert_sync_int(TRUE);
first:=time(NULL); /* Gets system time */
do {
second:=time(NULL); /* Gets system time again */
/* calculates the elapsed time in seconds, return as a double */
} while ( difftime(second, first) < 1 ); //wait for 1 second
// disable interrupt
disable();
JUN_enable_vert_sync_int(FALSE);
enable();
/* Restore interrupt vector AND unmask interrupt no */
restore_interrupt(bIRQ);
// wsprintf(debugstr, 'IntCount=%d, VsyncCount=%d', gulEnterIntCount, count);
// MessageBox(NULL, debugstr, 'Verify IRQ', MB_OK OR MB_ICONEXCLAMATION);
/* Fv:=60 Hz, so 60 times at 1 second period, error allow to 5 */
if ( JUN_get_TVsystem_type() = NTSC )
int_count:=60;
else
int_count:=50;
if ( (gulEnterIntCount>=(int_count+10)) OROR (gulEnterIntCount<=(int_count-10)) ) {
// wsprintf(debugstr, 'Int count after 1 sec:=%d', gulEnterIntCount);
// MessageBox(NULL, debugstr, 'Verify IRQ', MB_OK OR MB_ICONEXCLAMATION);
PortWriteByte($80, gulEnterIntCount);
return(ERR_IRQ_SETTING_BAD);
}
return(TRUE);
}
// *********221******************************************************************
// set_screen_border_reg() : set screnn border register
// input
// color_entry : color_entry
// ***************************************************************************
int FAR set_screen_border_reg(BYTE color_entry)
{
/* first clear bit 0,1, i.e., 1111 1100 = 0xfc then
OR 0100 0001 = 0x01 = SCREEN_BORDER_REG_SEL */
crt_sel_reg_val = (crt_sel_reg_val AND 0xfc) OR SCREEN_BORDER_REG_SEL;
select_crt_register(crt_sel_reg_val); // select vertical scroll register
PortWriteByte(crt_data_reg, color_entry);
return(TRUE);
} /* end of set_screen_border_reg(BYTE color_entry) */
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.SyncObjs;
{$H+,X+}
{$IFDEF CPUX86}
{$DEFINE X86ASM}
{$ELSE !CPUX86}
{$DEFINE PUREPASCAL}
{$DEFINE X64ASM}
{$ENDIF !CPUX86}
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
Winapi.Messages,
{$ENDIF}
{$IFDEF POSIX}
Posix.SysTypes,
Posix.SysTime,
Posix.Time,
Posix.Semaphore,
Posix.Pthread,
Posix.Errno,
{$ENDIF POSIX}
{$IFDEF MACOS}
Macapi.CoreServices,
{$ENDIF}
System.TimeSpan,
System.SysUtils,
System.Classes;
type
ESyncObjectException = class(Exception);
{$IFNDEF MSWINDOWS}
PSecurityAttributes = Pointer;
{$ENDIF}
{$IFDEF MSWINDOWS}
TCriticalSectionHelper = record helper for TRTLCriticalSection
procedure Initialize; inline;
procedure Destroy; inline;
procedure Free; inline;
procedure Enter; inline;
procedure Leave; inline;
function TryEnter: Boolean; inline;
end;
TConditionVariableHelper = record helper for TRTLConditionVariable
public
class function Create: TRTLConditionVariable; static;
procedure Free; inline;
function SleepCS(var CriticalSection: TRTLCriticalSection; dwMilliseconds: DWORD): Boolean;
procedure Wake;
procedure WakeAll;
end;
{$ENDIF}
TWaitResult = (wrSignaled, wrTimeout, wrAbandoned, wrError, wrIOCompletion);
TSynchroObject = class(TObject)
{$IFDEF POSIX}
protected
procedure GetPosixEndTime(var EndTime: timespec; TimeOut: LongWord); inline;
procedure CheckNamed(const Name: string); inline;
{$ENDIF}
public
procedure Acquire; virtual;
procedure Release; virtual;
function WaitFor(Timeout: LongWord = INFINITE): TWaitResult; overload; virtual;
function WaitFor(const Timeout: TTimeSpan): TWaitResult; overload;
end;
THandleObject = class;
THandleObjectArray = array of THandleObject;
THandleObject = class(TSynchroObject)
{$IFDEF MSWINDOWS}
protected
FHandle: THandle;
FLastError: Integer;
FUseCOMWait: Boolean;
public
{ Specify UseCOMWait to ensure that when blocked waiting for the object
any STA COM calls back into this thread can be made. }
constructor Create(UseCOMWait: Boolean = False);
destructor Destroy; override;
{$ENDIF}
public
{$IFDEF MSWINDOWS}
function WaitFor(Timeout: LongWord): TWaitResult; overload; override;
class function WaitForMultiple(const HandleObjs: THandleObjectArray;
Timeout: LongWord; AAll: Boolean; out SignaledObj: THandleObject;
UseCOMWait: Boolean = False; Len: Integer = 0): TWaitResult;
property LastError: Integer read FLastError;
property Handle: THandle read FHandle;
{$ENDIF}
end;
TEvent = class(THandleObject)
{$IFDEF POSIX}
private
FManualReset: Boolean;
{$IFDEF LINUX}
FEvent: sem_t;
{$ENDIF}
{$IFDEF MACOS}
FEvent: MPEventID;
function WaitNoReset(Timeout: LongWord): TWaitResult;
{$ENDIF}
{$ENDIF}
public
constructor Create(EventAttributes: PSecurityAttributes; ManualReset,
InitialState: Boolean; const Name: string; UseCOMWait: Boolean = False); overload;
constructor Create(UseCOMWait: Boolean = False); overload;
{$IFDEF POSIX}
destructor Destroy; override;
function WaitFor(Timeout: LongWord): TWaitResult; override;
{$ENDIF}
procedure SetEvent;
procedure ResetEvent;
end;
TSimpleEvent = class(TEvent);
TMutex = class(THandleObject)
{$IFDEF POSIX}
private
FMutex: pthread_mutex_t;
{$ENDIF}
public
constructor Create(UseCOMWait: Boolean = False); overload;
constructor Create(MutexAttributes: PSecurityAttributes; InitialOwner: Boolean; const Name: string; UseCOMWait: Boolean = False); overload;
constructor Create(DesiredAccess: LongWord; InheritHandle: Boolean; const Name: string; UseCOMWait: Boolean = False); overload;
{$IFDEF POSIX}
destructor Destroy; override;
function WaitFor(Timeout: LongWord): TWaitResult; override;
{$ENDIF}
procedure Acquire; override;
procedure Release; override;
end;
TSemaphore = class(THandleObject)
{$IFDEF LINUX}
private
FSem: sem_t;
{$ENDIF}
{$IFDEF MACOS}
private
FSem: MPSemaphoreID;
{$ENDIF}
public
constructor Create(UseCOMWait: Boolean = False); overload;
constructor Create(SemaphoreAttributes: PSecurityAttributes; AInitialCount, AMaximumCount: Integer; const Name: string; UseCOMWait: Boolean = False); overload;
constructor Create(DesiredAccess: LongWord; InheritHandle: Boolean; const Name: string; UseCOMWait: Boolean = False); overload;
{$IFDEF POSIX}
destructor Destroy; override;
function WaitFor(Timeout: LongWord = INFINITE): TWaitResult; override;
{$ENDIF}
procedure Acquire; override;
procedure Release; overload; override;
function Release(AReleaseCount: Integer): Integer; reintroduce; overload;
end;
TCriticalSection = class(TSynchroObject)
{$IFDEF POSIX}
private type
TCritSec = record
FSync: TObject;
procedure Initialize; inline;
procedure Free; inline;
procedure Enter; inline;
procedure Leave; inline;
function TryEnter: Boolean; inline;
end;
{$ENDIF}
protected
{$IFDEF MSWINDOWS}
FSection: TRTLCriticalSection;
{$ENDIF}
{$IFDEF POSIX}
FSection: TCritSec;
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
procedure Acquire; override;
procedure Release; override;
function TryEnter: Boolean;
procedure Enter; inline;
procedure Leave; inline;
end;
TConditionVariableMutex = class(TSynchroObject)
private
{$IFDEF POSIX}
FCondVar: pthread_cond_t;
{$ENDIF}
{$IFDEF MSWINDOWS}
FWaiterCount: Integer;
FCountLock: TCriticalSection;
FWaitSemaphore: TSemaphore;
FWaitersDoneEvent: TEvent;
FBroadcasting: Boolean;
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
procedure Acquire; override;
procedure Release; override;
procedure ReleaseAll;
function WaitFor(AExternalMutex: TMutex; TimeOut: LongWord = INFINITE): TWaitResult;
end;
TConditionVariableCS = class(TSynchroObject)
protected
{$IFDEF MSWINDOWS}
FConditionVariable: TRTLConditionVariable;
{$ENDIF}
{$IFDEF POSIX}
FCondVar: TObject;
{$ENDIF}
public
{$IFDEF POSIX}
constructor Create;
destructor Destroy; override;
{$ENDIF}
procedure Acquire; override;
procedure Release; override;
procedure ReleaseAll;
function WaitFor(CriticalSection: TCriticalSection; TimeOut: LongWord = INFINITE): TWaitResult; overload;
{$IFDEF MSWINDOWS}
function WaitFor(var CriticalSection: TRTLCriticalSection; TimeOut: LongWord = INFINITE): TWaitResult; overload;
{$ENDIF}
end;
{ TSpinWait implements an exponential backoff algorithm for spin or busy waiting (http://en.wikipedia.org/wiki/Busy_waiting).
The algorithm is as follows: If the CPUCount > 1, then the first 10 (YieldThreshold) spin cycles
(calls to SpinCycle) will use a base 2 exponentially increasing spin count starting at 4. After 10 cycles,
then the behavior reverts to the same behavior as when CPUCount = 1.
If the CPUCount = 1, then it will sleep (TThread.Sleep) 1ms every modulus 20 cycles and sleep 0ms every modulus
5 cycles. All other cycles simply yield (TThread.Yield).
This type is modeled after a similar type available in .NET 4.0 as System.Threading.SpinWait.
}
TSpinWait = record
private const
YieldThreshold = 10;
Sleep1Threshold = 20;
Sleep0Threshold = 5;
private
FCount: Integer;
function GetNextSpinCycleWillYield: Boolean;
public
procedure Reset;
procedure SpinCycle;
class procedure SpinUntil(const ACondition: TFunc<Boolean>); overload; static;
class function SpinUntil(const ACondition: TFunc<Boolean>; Timeout: LongWord): Boolean; overload; static;
class function SpinUntil(const ACondition: TFunc<Boolean>; const Timeout: TTimeSpan): Boolean; overload; static;
property Count: Integer read FCount;
property NextSpinCycleWillYield: Boolean read GetNextSpinCycleWillYield;
end;
{ TSpinLock implements a very simple non-reentrant spin lock. This lock does not block the calling thread using a
synchronization object. Instead it opts to burn a few extra CPU cycles using a technique similar to the above
TSpinWait type. This is typically faster than fully blocking if the length of time the lock is held is
relatively few cycles. In these cases the thread switching overhead will usually far outpace the few cycles
burned by simply spin waiting. This is typically only true for multicore or SMP situations. However, that case
is taken into account and the CPU is yielded instead of actually busy-waiting during the current thread's
quantum.
Since this lock is non-reentrant, attempts to call Enter a second time from the same thread will cause either
an exception to be raised if threadID tracking is enabled, otherwise it will deadlock.
The PublishNow parameter on Exit indicated whether or not a full memory fence should be used to ensure that all
other threads see the exit immediately. In this case the fairness of the lock is better at the expense of a little
performance.
This type is modeled after a similar type available in .NET 4.0 as System.Threading.SpinLock.
}
ELockRecursionException = class(ESyncObjectException);
ELockException = class(ESyncObjectException);
TSpinLock = record
private const
ThreadTrackingDisabled = $80000000;
MaxWaitingThreads = $7FFFFFFE;
WaitingThreadMask = $7FFFFFFE;
AnonymouslyOwned = 1;
LockAvailable = 0;
private
FLock: Integer;
function InternalTryEnter(Timeout: LongWord): Boolean;
function GetIsLocked: Boolean;
function GetIsLockedByCurrentThread: Boolean;
function GetIsThreadTrackingEnabled: Boolean;
procedure RemoveWaiter;
public
constructor Create(EnableThreadTracking: Boolean);
procedure Enter; inline;
procedure Exit(PublishNow: Boolean = True);
function TryEnter: Boolean; overload; inline;
function TryEnter(Timeout: LongWord): Boolean; overload;
function TryEnter(const Timeout: TTimeSpan): Boolean; overload;
property IsLocked: Boolean read GetIsLocked;
property IsLockedByCurrentThread: Boolean read GetIsLockedByCurrentThread;
property IsThreadTrackingEnabled: Boolean read GetIsThreadTrackingEnabled;
end;
{ TLightweightEvent implements a manual reset event using only atomic operations from the TInterlocked class and the
built-in TMonitor. Similar to TSpinLock above, TLightweightEvent.WaitFor prefers to try and burn a few CPU cycles
in a spin-loop before fully blocking the calling thread. This class should really be used in scenarios where the
signaled-to-blocked ratio is relatively small. In other words, the time that a thread would expect to spend in
TLightweightEvent.WaitFor is relatively short (in terms of CPU cycles, not absolute time). If used in scenarios
where the the internal spin count is routinely exhausted and it does finally block, the performance may be slightly
below that of a regular TSimpleEvent.
This type is modeled after a similar type available in .NET 4.0 as System.Threading.ManualResetEventSlim.
}
TLightweightEvent = class(TSynchroObject)
strict private const
DefaultSpinMulticore = 10;
DefaultSpinSinglecore = 1;
SpinMask = $FFF;
MaxSpin = $FFF;
EventSignaled = Integer($80000000);
EventUnsignaled = 0;
SignalMask = Integer($80000000);
strict private
FLock: TObject;
FStateAndSpin: Integer;
FWaiters: Integer;
FBlockedCount: Integer;
function GetIsSet: Boolean;
function GetSpinCount: Integer;
procedure SetNewStateAtomically(NewValue, Mask: Integer);
public
constructor Create; overload;
constructor Create(InitialState: Boolean); overload;
constructor Create(InitialState: Boolean; SpinCount: Integer); overload;
destructor Destroy; override;
procedure ResetEvent;
procedure SetEvent;
function WaitFor(Timeout: LongWord = INFINITE): TWaitResult; overload; override;
property BlockedCount: Integer read FBlockedCount;
property IsSet: Boolean read GetIsSet;
property SpinCount: Integer read GetSpinCount;
end;
{ TLightweightSemaphore implements a classic "semaphore" synchronization primitive using only the atomic operations
from the TInterlocked class and the built-in TMonitor. Similar to TSpinLock and TLightweightEvent above,
TLightweightSemaphore.WaitFor will prefer to burn a few CPU cycles in a spin-loop before performing a fully
blocking operation. Again, like the above TLightweightEvent, TLightweightSemaphore should be used in scenarios where
the semaphore count regularly stays > 0. This will ensure that calls to WaitFor will rarely block. When compared to
the TSemaphore class in scenarios where the semaphore count is regularly 0, the performance of this class may be
slightly below that of the TSemaphore class above.
This type is modeled after a similar type available in .NET 4.0 as System.Threading.SemaphoreSlim.
}
TLightweightSemaphore = class(TSynchroObject)
strict private
FCountLock: TObject;
FCurrentCount: Integer;
FInitialCount: Integer;
FMaxCount: Integer;
FWaitCount: Integer;
FBlockedCount: Integer;
public
constructor Create(AInitialCount: Integer; AMaxCount: Integer = MaxInt);
destructor Destroy; override;
function Release(AReleaseCount: Integer = 1): Integer; reintroduce;
function WaitFor(Timeout: LongWord = INFINITE): TWaitResult; overload; override;
property BlockedCount: Integer read FBlockedCount;
property CurrentCount: Integer read FCurrentCount;
end;
{ TCountdownEvent is a synchronization object that behaves similar to a "manual reset semaphore" only it is signaled
when the count is zero (0) instead of non-zero. Once the count reaches zero, the only way to "unsignal" the event
is to call one of the Reset methods. AddCount can only be called if the current count is > 0. TryAddCount will
return true if the count was > 0 and the count was added, otherwise it will return false if the count is already
zero.
This type is modeled after a similar type available in .NET 4.0 as System.Threading.CountdownEvent.
}
TCountdownEvent = class(TSynchroObject)
strict private
FEvent: TLightweightEvent;
FInitialCount, FCurrentCount: Integer;
function GetIsSet: Boolean;
public
constructor Create(Count: Integer);
destructor Destroy; override;
function Signal(Count: Integer = 1): Boolean;
procedure AddCount(Count: Integer = 1);
procedure Reset; overload;
procedure Reset(Count: Integer); overload;
function TryAddCount(Count: Integer = 1): Boolean;
function WaitFor(Timeout: LongWord = INFINITE): TWaitResult; overload; override;
property CurrentCount: Integer read FCurrentCount;
property InitialCount: Integer read FInitialCount;
property IsSet: Boolean read GetIsSet;
end;
{ TInterlocked implements various common atomic opererations for the purpose of ensuring "thread" or "multi-core"
safety when modifying variables that could be accessed from multiple threads simultaneously. The TInterlocked class
is not intended to be instantiated nor derived from. All the methods are "class static" and are merely defined in
a class as a way to group their like-functionality.
}
TBitOffset = 0..31;
TInterlocked = class sealed
class function Increment(var Target: Integer): Integer; overload; static; inline;
class function Increment(var Target: Int64): Int64; overload; static; inline;
class function Decrement(var Target: Integer): Integer; overload; static; inline;
class function Decrement(var Target: Int64): Int64; overload; static; inline;
class function Add(var Target: Integer; Increment: Integer): Integer; overload; static;
class function Add(var Target: Int64; Increment: Int64): Int64; overload; static;
class function BitTestAndSet(var Target: Integer; BitOffset: TBitOffset): Boolean; static;
class function BitTestAndClear(var Target: Integer; BitOffset: TBitOffset): Boolean; static;
class function Exchange(var Target: Pointer; Value: Pointer): Pointer; overload; static;
class function Exchange(var Target: Integer; Value: Integer): Integer; overload; static;
class function Exchange(var Target: Int64; Value: Int64): Int64; overload; static;
class function Exchange(var Target: TObject; Value: TObject): TObject; overload; static; inline;
class function Exchange(var Target: Double; Value: Double): Double; overload; static;
class function Exchange(var Target: Single; Value: Single): Single; overload; static;
class function Exchange<T: class>(var Target: T; Value: T): T; overload; static; inline;
class function CompareExchange(var Target: Pointer; Value: Pointer; Comparand: Pointer): Pointer; overload; static;
class function CompareExchange(var Target: Integer; Value: Integer; Comparand: Integer): Integer; overload; static;
class function CompareExchange(var Target: Integer; Value: Integer; Comparand: Integer; out Succeeded: Boolean): Integer; overload; static;
class function CompareExchange(var Target: Int64; Value: Int64; Comparand: Int64): Int64; overload; static;
class function CompareExchange(var Target: TObject; Value: TObject; Comparand: TObject): TObject; overload; static; inline;
class function CompareExchange(var Target: Double; Value: Double; Comparand: Double): Double; overload; static;
class function CompareExchange(var Target: Single; Value: Single; Comparand: Single): Single; overload; static;
class function CompareExchange<T: class>(var Target: T; Value: T; Comparand: T): T; overload; static; inline;
end;
implementation
uses System.RTLConsts,
System.Diagnostics,
{$IFDEF POSIX}
System.Types,
{$ENDIF}
System.Math;
{$IFDEF MSWINDOWS}
type
PInternalConditionVariable = ^TInternalConditionVariable;
TInternalConditionVariable = record
strict private
type
PWaitingThread = ^TWaitingThread;
TWaitingThread = record
Next: PWaitingThread;
Thread: Cardinal;
WaitEvent: THandle;
end;
var
FWaitQueue: PWaitingThread;
function LockQueue: PWaitingThread;
procedure UnlockQueue(WaitQueue: PWaitingThread);
procedure QueueWaiter(var WaitingThread: TWaitingThread);
function DequeueWaiterNoLock(var WaitQueue: PWaitingThread): PWaitingThread;
function DequeueWaiter: PWaitingThread;
procedure RemoveWaiter(var WaitingThread: TWaitingThread);
public
class function Create: TInternalConditionVariable; static;
function SleepCriticalSection(var CriticalSection: TRTLCriticalSection; Timeout: DWORD): Boolean;
procedure Wake;
procedure WakeAll;
end;
TCoWaitForMultipleHandlesProc = function (dwFlags: DWORD; dwTimeOut: DWORD;
cHandles: LongWord; var Handles; var lpdwIndex: DWORD): HRESULT; stdcall;
TInitializeConditionVariableProc = procedure (out ConditionVariable: TRTLConditionVariable); stdcall;
TSleepConditionVariableCSProc = function (var ConditionVariable: TRTLConditionVariable; var CriticalSection: TRTLCriticalSection; dwMilliseconds: DWORD): BOOL; stdcall;
TWakeConditionVariableProc = procedure (var ConditionVariable: TRTLConditionVariable); stdcall;
TWakeAllConditionVariableProc = procedure (var ConditionVariable: TRTLConditionVariable); stdcall;
var
CoWaitForMultipleHandlesProc: TCoWaitFormultipleHandlesProc;
InitializeConditionVariableProc: TInitializeConditionVariableProc;
SleepConditionVariableCSProc: TSleepConditionVariableCSProc;
WakeConditionVariableProc: TWakeConditionVariableProc;
WakeAllConditionVariableProc: TWakeAllConditionVariableProc;
threadvar
OleThreadWnd: HWND;
const
OleThreadWndClassName = 'OleMainThreadWndClass'; //do not localize
COWAIT_WAITALL = $00000001;
COWAIT_ALERTABLE = $00000002;
function GetOleThreadWindow: HWND;
var
ChildWnd: HWND;
ParentWnd: HWND;
begin
if (OleThreadWnd = 0) or not IsWindow(OleThreadWnd) then
begin
if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 5) then
ParentWnd := HWND_MESSAGE
else
ParentWnd := 0;
ChildWnd := 0;
repeat
OleThreadWnd := FindWindowEx(ParentWnd, ChildWnd, OleThreadWndClassName, nil);
ChildWnd := OleThreadWnd;
until (OleThreadWnd = 0) or (GetWindowThreadProcessId(OleThreadWnd, nil) = GetCurrentThreadId);
end;
Result := OleThreadWnd;
end;
function InternalCoWaitForMultipleHandles(dwFlags: DWORD; dwTimeOut: DWORD;
cHandles: LongWord; var Handles; var lpdwIndex: DWORD): HRESULT; stdcall;
var
WaitResult: DWORD;
OleThreadWnd: HWnd;
Msg: TMsg;
begin
WaitResult := 0; // supress warning
OleThreadWnd := GetOleThreadWindow;
if OleThreadWnd <> 0 then
while True do
begin
WaitResult := MsgWaitForMultipleObjectsEx(cHandles, Handles, dwTimeOut, QS_ALLEVENTS, dwFlags);
if WaitResult = WAIT_OBJECT_0 + cHandles then
begin
if PeekMessage(Msg, OleThreadWnd, 0, 0, PM_REMOVE) then
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end else
Break;
end
else
WaitResult := WaitForMultipleObjectsEx(cHandles, @Handles,
dwFlags and COWAIT_WAITALL <> 0, dwTimeOut, dwFlags and COWAIT_ALERTABLE <> 0);
if WaitResult = WAIT_TIMEOUT then
Result := RPC_E_TIMEOUT
else if WaitResult = WAIT_IO_COMPLETION then
Result := RPC_S_CALLPENDING
else
begin
Result := S_OK;
if (WaitResult >= WAIT_ABANDONED_0) and (WaitResult < WAIT_ABANDONED_0 + cHandles) then
lpdwIndex := WaitResult - WAIT_ABANDONED_0
else
lpdwIndex := WaitResult - WAIT_OBJECT_0;
end;
end;
function CoWaitForMultipleHandles(dwFlags: DWORD; dwTimeOut: DWORD;
cHandles: LongWord; var Handles; var lpdwIndex: DWORD): HRESULT;
procedure LookupProc;
var
Ole32Handle: HMODULE;
begin
Ole32Handle := GetModuleHandle('ole32.dll'); //do not localize
if Ole32Handle <> 0 then
CoWaitForMultipleHandlesProc := GetProcAddress(Ole32Handle, 'CoWaitForMultipleHandles'); //do not localize
if not Assigned(CoWaitForMultipleHandlesProc) then
CoWaitForMultipleHandlesProc := InternalCoWaitForMultipleHandles;
end;
begin
if not Assigned(CoWaitForMultipleHandlesProc) then
LookupProc;
Result := CoWaitForMultipleHandlesProc(dwFlags, dwTimeOut, cHandles, Handles, lpdwIndex)
end;
{$ENDIF}
{ TSynchroObject }
procedure TSynchroObject.Acquire;
begin
WaitFor(INFINITE);
end;
{$IFDEF POSIX}
procedure TSynchroObject.GetPosixEndTime(var EndTime: timespec; TimeOut: LongWord);
var
Now: timeval;
NanoSecTimeout: Int64;
begin
CheckOSError(gettimeofday(Now, nil));
NanoSecTimeout := (Now.tv_usec * 1000) + (Integer(Timeout) * 1000000);
EndTime.tv_sec := Now.tv_sec + (NanoSecTimeout div 1000000000);
EndTime.tv_nsec := NanoSecTimeout mod 1000000000;
end;
procedure TSynchroObject.CheckNamed(const Name: string);
begin
if Name <> '' then
raise ESyncObjectException.CreateRes(@sNamedSyncObjectsNotSupported);
end;
{$ENDIF}
procedure TSynchroObject.Release;
begin
end;
function TSynchroObject.WaitFor(Timeout: LongWord): TWaitResult;
begin
Result := wrError;
end;
function TSynchroObject.WaitFor(const Timeout: TTimeSpan): TWaitResult;
var
Total: Int64;
begin
Total := Trunc(Timeout.TotalMilliseconds);
if (Total < 0) or (Total > $7FFFFFFF) then
raise EArgumentOutOfRangeException.CreateResFmt(@sInvalidTimeoutValue, [string(Timeout)]);
Result := WaitFor(Integer(Total));
end;
{ THandleObject }
{$IFDEF MSWINDOWS}
constructor THandleObject.Create(UseComWait: Boolean);
begin
inherited Create;
FUseCOMWait := UseCOMWait;
end;
destructor THandleObject.Destroy;
begin
CloseHandle(FHandle);
inherited Destroy;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
function THandleObject.WaitFor(Timeout: LongWord): TWaitResult;
var
Index: DWORD;
begin
if FUseCOMWait then
begin
case CoWaitForMultipleHandles(0, TimeOut, 1, FHandle, Index) of
S_OK: Result := wrSignaled;
RPC_S_CALLPENDING: Result := wrIOCompletion;
RPC_E_TIMEOUT: Result := wrTimeout;
else
Result := wrError;
FLastError := Integer(GetLastError);
end;
end else
begin
case WaitForMultipleObjectsEx(1, @FHandle, True, Timeout, False) of
WAIT_ABANDONED: Result := wrAbandoned;
WAIT_OBJECT_0: Result := wrSignaled;
WAIT_TIMEOUT: Result := wrTimeout;
WAIT_FAILED:
begin
Result := wrError;
FLastError := Integer(GetLastError);
end;
else
Result := wrError;
end;
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
class function THandleObject.WaitForMultiple(
const HandleObjs: THandleObjectArray; Timeout: LongWord; AAll: Boolean;
out SignaledObj: THandleObject; UseCOMWait: Boolean; Len: Integer): TWaitResult;
var
I: Integer;
Index: DWORD;
Handles: array of THandle;
CoWaitFlags: Integer;
WaitResult: DWORD;
begin
if Len > 0 then
Len := Min(Len, Length(HandleObjs))
else
Len := Length(HandleObjs);
SetLength(Handles, Len);
for I := Low(Handles) to High(Handles) do
Handles[I] := HandleObjs[I].Handle;
if UseCOMWait then
begin
if AAll then
CoWaitFlags := COWAIT_WAITALL
else
CoWaitFlags := 0;
case CoWaitForMultipleHandles(CoWaitFlags, Timeout, Length(Handles), Handles[0], Index) of
S_OK: Result := wrSignaled;
RPC_S_CALLPENDING: Result := wrIOCompletion;
RPC_E_TIMEOUT: Result := wrTimeout;
else
Result := wrError;
end;
if not AAll and (Result = wrSignaled) then
SignaledObj := HandleObjs[Index]
else
SignaledObj := nil;
end else
begin
WaitResult := WaitForMultipleObjectsEx(Length(Handles), @Handles[0], AAll, Timeout, False);
case WaitResult of
WAIT_ABANDONED_0..WAIT_ABANDONED_0 + MAXIMUM_WAIT_OBJECTS - 1:
begin
Result := wrAbandoned;
SignaledObj := HandleObjs[WaitResult - WAIT_ABANDONED_0];
end;
WAIT_TIMEOUT: Result := wrTimeout;
WAIT_FAILED: Result := wrError;
WAIT_IO_COMPLETION: Result := wrIOCompletion;
WAIT_OBJECT_0..WAIT_OBJECT_0 + MAXIMUM_WAIT_OBJECTS - 1:
begin
Result := wrSignaled;
SignaledObj := HandleObjs[WaitResult - WAIT_OBJECT_0];
end;
else
Result := wrError;
end;
end;
end;
{$ENDIF}
{ TEvent }
constructor TEvent.Create(EventAttributes: PSecurityAttributes; ManualReset,
InitialState: Boolean; const Name: string; UseCOMWait: Boolean);
{$IFDEF MSWINDOWS}
begin
inherited Create(UseCOMWait);
FHandle := CreateEvent(EventAttributes, ManualReset, InitialState, PChar(Name));
end;
{$ENDIF}
{$IFDEF MACOS}
var
Value: Integer;
begin
inherited Create;
CheckNamed(Name);
if MPCreateEvent(FEvent) <> 0 then
RaiseLastOSError;
if InitialState then
Value := 1
else
Value := 0;
MPSetEvent(FEvent, Value);
FManualReset := ManualReset;
end;
{$ENDIF}
{$IFDEF LINUX}
var
Value: Integer;
begin
inherited Create;
CheckNamed(Name);
if InitialState then
Value := 1
else
Value := 0;
FManualReset := ManualReset;
sem_init(FEvent, False, Value);
end;
{$ENDIF}
constructor TEvent.Create(UseCOMWait: Boolean);
begin
Create(nil, True, False, '', UseCOMWait);
end;
{$IFDEF POSIX}
destructor TEvent.Destroy;
begin
{$IFDEF LINUX}
sem_destroy(FEvent);
{$ENDIF}
{$IFDEF MACOS}
MPDeleteEvent(FEvent);
{$ENDIF}
inherited Destroy;
end;
{$ENDIF}
{$IFDEF MACOS}
function TEvent.WaitNoReset(Timeout: LongWord): TWaitResult;
var
Flags: MPEventFlags;
begin
case MPWaitForEvent(FEvent, Flags, Timeout and kDurationForever) of
noErr: Result := wrSignaled;
kMPTimeoutErr: Result := wrTimeout;
else
Result := wrError;
end;
end;
{$ENDIF}
{$IFDEF POSIX}
function TEvent.WaitFor(Timeout: LongWord): TWaitResult;
{$IFDEF LINUX}
var
Err: Integer;
EndTime: timespec;
begin
if (Timeout > 0) and (Timeout < INFINITE) then
begin
GetPosixEndTime(EndTime, Timeout);
if sem_timedwait(FEvent, EndTime) <> 0 then
begin
Err := GetLastError;
if Err = ETIMEDOUT then
Result := wrTimeout
else
Result := wrError;
end else
Result := wrSignaled;
end else if Timeout = INFINITE then
begin
if sem_wait(FEvent) = 0 then
Result := wrSignaled
else
Result := wrError;
end else
begin
if sem_trywait(FEvent) <> 0 then
begin
Err := GetLastError;
if Err = EAGAIN then
Result := wrTimeout
else
Result := wrError;
end else
Result := wrSignaled;
end;
if (Result = wrSignaled) and FManualReset then
sem_post(FEvent);
end;
{$ENDIF}
{$IFDEF MACOS}
begin
Result := WaitNoReset(Timeout);
if (Result = wrSignaled) and FManualReset then
MPSetEvent(FEvent, 1);
end;
{$ENDIF}
{$ENDIF}
procedure TEvent.SetEvent;
{$IFDEF MSWINDOWS}
begin
Winapi.Windows.SetEvent(Handle);
end;
{$ENDIF}
{$IFDEF LINUX}
var
I: Integer;
begin
sem_getvalue(FEvent, I);
if I = 0 then
sem_post(FEvent);
end;
{$ENDIF}
{$IFDEF MACOS}
begin
MPSetEvent(FEvent, 1);
end;
{$ENDIF}
procedure TEvent.ResetEvent;
begin
{$IFDEF MSWINDOWS}
Winapi.Windows.ResetEvent(Handle);
{$ENDIF}
{$IFDEF LINUX}
while sem_trywait(FEvent) = 0 do { nothing };
{$ENDIF}
{$IFDEF MACOS}
WaitNoReset(0);
{$ENDIF}
end;
{ TCriticalSectionHelper }
{$IFDEF MSWINDOWS}
procedure TCriticalSectionHelper.Initialize;
begin
InitializeCriticalSection(Self);
end;
procedure TCriticalSectionHelper.Destroy;
begin
DeleteCriticalSection(Self);
end;
procedure TCriticalSectionHelper.Enter;
begin
EnterCriticalSection(Self);
end;
procedure TCriticalSectionHelper.Free;
begin
Destroy;
end;
procedure TCriticalSectionHelper.Leave;
begin
LeaveCriticalSection(Self);
end;
function TCriticalSectionHelper.TryEnter: Boolean;
begin
Result := TryEnterCriticalSection(Self);
end;
{$ENDIF}
{$IFDEF POSIX}
{ TCriticalSection.TCritSec }
procedure TCriticalSection.TCritSec.Initialize;
begin
FSync := TObject.Create;
end;
procedure TCriticalSection.TCritSec.Free;
begin
FSync.Free;
end;
procedure TCriticalSection.TCritSec.Enter;
begin
TMonitor.Enter(FSync);
end;
procedure TCriticalSection.TCritSec.Leave;
begin
TMonitor.Exit(FSync);
end;
function TCriticalSection.TCritSec.TryEnter: Boolean;
begin
Result := TMonitor.TryEnter(FSync);
end;
{$ENDIF}
{ TCriticalSection }
constructor TCriticalSection.Create;
begin
inherited Create;
FSection.Initialize;
end;
destructor TCriticalSection.Destroy;
begin
FSection.Free;
inherited Destroy;
end;
procedure TCriticalSection.Acquire;
begin
FSection.Enter;
end;
procedure TCriticalSection.Release;
begin
FSection.Leave;
end;
function TCriticalSection.TryEnter: Boolean;
begin
Result := FSection.TryEnter;
end;
procedure TCriticalSection.Enter;
begin
Acquire;
end;
procedure TCriticalSection.Leave;
begin
Release;
end;
{ TMutex }
procedure TMutex.Acquire;
begin
if WaitFor(INFINITE) = wrError then
RaiseLastOSError;
end;
constructor TMutex.Create(UseCOMWait: Boolean);
begin
Create(nil, False, '', UseCOMWait);
end;
constructor TMutex.Create(MutexAttributes: PSecurityAttributes;
InitialOwner: Boolean; const Name: string; UseCOMWait: Boolean);
{$IFDEF MSWINDOWS}
var
lpName: PChar;
begin
inherited Create(UseCOMWait);
if Name <> '' then
lpName := PChar(Name)
else
lpName := nil;
FHandle := CreateMutex(MutexAttributes, InitialOwner, lpName);
if FHandle = 0 then
RaiseLastOSError;
end;
{$ENDIF}
{$IFDEF POSIX}
begin
inherited Create;
CheckNamed(Name);
CheckOSError(pthread_mutex_init(FMutex, nil));
if InitialOwner then
Acquire;
end;
{$ENDIF}
constructor TMutex.Create(DesiredAccess: LongWord; InheritHandle: Boolean;
const Name: string; UseCOMWait: Boolean);
{$IFDEF MSWINDOWS}
var
lpName: PChar;
begin
inherited Create(UseCOMWait);
if Name <> '' then
lpName := PChar(Name)
else
lpName := nil;
FHandle := OpenMutex(DesiredAccess, InheritHandle, lpName);
if FHandle = 0 then
RaiseLastOSError;
end;
{$ENDIF}
{$IFDEF POSIX}
begin
Create(nil, False, Name, UseCOMWait);
end;
destructor TMutex.Destroy;
begin
pthread_mutex_destroy(FMutex); // do not call CheckOSError since the mutex could be invalid if object was partially
// constructed due to an exception.
inherited Destroy;
end;
{$ENDIF}
procedure TMutex.Release;
begin
{$IFDEF MSWINDOWS}
if not ReleaseMutex(FHandle) then
RaiseLastOSError;
{$ENDIF}
{$IFDEF POSIX}
CheckOSError(pthread_mutex_unlock(FMutex));
{$ENDIF}
end;
{$IFDEF POSIX}
function TMutex.WaitFor(Timeout: LongWord): TWaitResult;
var
Err: Integer;
{$IFDEF LINUX}
EndTime: timespec;
{$ENDIF}
begin
if (Timeout > 0) and (Timeout < INFINITE) then
begin
{$IFDEF LINUX}
GetPosixEndTime(EndTime, Timeout);
Err := pthread_mutex_timedlock(FMutex, EndTime);
if Err = ETIMEDOUT then
Result := wrTimeout
else if Err = 0 then
Result := wrSignaled
else
{$ENDIF}
Result := wrError;
end else if Timeout = INFINITE then
begin
if pthread_mutex_lock(FMutex) = 0 then
Result := wrSignaled
else
Result := wrError;
end else
begin
Err := pthread_mutex_trylock(FMutex);
if Err = 0 then
Result := wrSignaled
else if Err = EBUSY then
Result := wrTimeout
else
Result := wrError;
end;
end;
{$ENDIF}
{ TSemaphore }
procedure TSemaphore.Acquire;
begin
if WaitFor(INFINITE) = wrError then
RaiseLastOSError;
end;
constructor TSemaphore.Create(UseCOMWait: Boolean);
begin
Create(nil, 1, 1, '', UseCOMWait);
end;
constructor TSemaphore.Create(DesiredAccess: LongWord; InheritHandle: Boolean;
const Name: string; UseCOMWait: Boolean);
{$IFDEF MSWINDOWS}
var
lpName: PChar;
begin
inherited Create(UseCOMWait);
if Name <> '' then
lpName := PChar(Name)
else
lpName := nil;
FHandle := OpenSemaphore(DesiredAccess, InheritHandle, lpName);
if FHandle = 0 then
RaiseLastOSError;
end;
{$ENDIF}
{$IFDEF POSIX}
begin
Create(nil, 1, 1, Name, UseCOMWait);
end;
{$ENDIF}
constructor TSemaphore.Create(SemaphoreAttributes: PSecurityAttributes;
AInitialCount, AMaximumCount: Integer; const Name: string; UseCOMWait: Boolean);
{$IFDEF MSWINDOWS}
var
lpName: PChar;
begin
inherited Create(UseCOMWait);
if Name <> '' then
lpName := PChar(Name)
else
lpName := nil;
FHandle := CreateSemaphore(SemaphoreAttributes, AInitialCount, AMaximumCount, lpName);
if FHandle = 0 then
RaiseLastOSError;
end;
{$ENDIF}
{$IFDEF LINUX}
begin
inherited Create;
CheckNamed(Name);
if sem_init(FSem, 0, AInitialCount) <> 0 then
RaiseLastOSError;
end;
{$ENDIF}
{$IFDEF MACOS}
begin
inherited Create;
CheckNamed(Name);
if MPCreateSemaphore(AMaximumCount, AInitialCount, FSem) <> noErr then
RaiseLastOSError;
end;
{$ENDIF}
{$IFDEF POSIX}
destructor TSemaphore.Destroy;
begin
{$IFDEF LINUX}
sem_destroy(FSem);
{$ENDIF}
{$IFDEF MACOS}
MPDeleteSemaphore(FSem);
{$ENDIF}
inherited Destroy;
end;
{$ENDIF}
function TSemaphore.Release(AReleaseCount: Integer): Integer;
begin
{$IFDEF MSWINDOWS}
if not ReleaseSemaphore(FHandle, AReleaseCount, @Result) then
RaiseLastOSError;
{$ENDIF}
{$IFDEF LINUX}
Result := 0;
if AReleaseCount < 1 then
raise ESyncObjectException.CreateResFmt(@SInvalidSemaphoreReleaseCount, [AReleaseCount]);
repeat
if sem_post(FSem) <> 0 then
RaiseLastOSError;
Dec(AReleaseCount);
Inc(Result);
until AReleaseCount = 0;
{$ENDIF}
{$IFDEF MACOS}
Result := 0;
if AReleaseCount < 1 then
raise ESyncObjectException.CreateResFmt(@SInvalidSemaphoreReleaseCount, [AReleaseCount]);
repeat
case MPSignalSemaphore(FSem) of
noErr: begin end;
kMPInsufficientResourcesErr: Exit;
else
RaiseLastOSError;
end;
Dec(AReleaseCount);
Inc(Result);
until AReleaseCount = 0;
{$ENDIF}
end;
procedure TSemaphore.Release;
begin
Release(1);
end;
{$IFDEF POSIX}
function TSemaphore.WaitFor(Timeout: LongWord): TWaitResult;
{$IFDEF LINUX}
var
EndTime: timespec;
{$ENDIF}
begin
{$IFDEF LINUX}
if (Timeout > 0) and (Timeout < INFINITE) then
begin
GetPosixEndTime(EndTime);
if sem_timedwait(FSem, EndTime) <> 0 then
begin
if GetLastError = ETIMEDOUT then
Result := wrTimeout
else
Result := wrError;
end else
Result := wrSignaled;
end else if Timeout = INFINITE then
begin
if sem_wait(FSem) = 0 then
Result := wrSignaled
else
Result := wrError;
end else
begin
if sem_trywait(FSem) = 0 then
Exit(wrSignaled);
if GetLastError = EAGAIN then
Result := wrTimeout
else
Result := wrError;
end;
{$ENDIF}
{$IFDEF MACOS}
case MPWaitOnSemaphore(FSem, Timeout and kDurationForever) of
noErr: Result := wrSignaled;
kMPTimeoutErr: Result := wrTimeout;
else
Result := wrError;
end;
{$ENDIF}
end;
{$ENDIF}
{ TConditionVariableMutex }
procedure TConditionVariableMutex.Acquire;
begin
raise ESyncObjectException.Create(sCannotCallAcquireOnConditionVar);
end;
constructor TConditionVariableMutex.Create;
begin
inherited Create;
{$IFDEF MSWINDOWS}
FCountLock := TCriticalSection.Create;
FWaitSemaphore := TSemaphore.Create(nil, 0, MaxInt, '');
FWaitersDoneEvent := TEvent.Create(nil, False, False, '');
{$ENDIF}
{$IFDEF POSIX}
CheckOSError(pthread_cond_init(FCondVar, nil));
{$ENDIF}
end;
destructor TConditionVariableMutex.Destroy;
begin
{$IFDEF MSWINDOWS}
FWaitersDoneEvent.Free;
FWaitSemaphore.Free;
FCountLock.Free;
{$ENDIF}
{$IFDEF POSIX}
CheckOSError(pthread_cond_destroy(FCondVar));
{$ENDIF}
inherited;
end;
procedure TConditionVariableMutex.Release;
{$IFDEF MSWINDOWS}
var
AnyWaiters: Boolean;
begin
FCountLock.Enter;
try
AnyWaiters := FWaiterCount > 0;
finally
FCountLock.Leave;
end;
if AnyWaiters then
FWaitSemaphore.Release;
end;
{$ENDIF}
{$IFDEF POSIX}
begin
CheckOSError(pthread_cond_signal(FCondVar));
end;
{$ENDIF}
procedure TConditionVariableMutex.ReleaseAll;
{$IFDEF MSWINDOWS}
var
AnyWaiters: Boolean;
begin
AnyWaiters := False;
FCountLock.Enter;
try
if FWaiterCount > 0 then
begin
FBroadcasting := True;
FWaitSemaphore.Release(FWaiterCount);
AnyWaiters := True;
FCountLock.Leave;
FWaitersDoneEvent.WaitFor(INFINITE);
FBroadcasting := False;
end;
finally
if not AnyWaiters then
FCountLock.Leave;
end;
end;
{$ENDIF}
{$IFDEF POSIX}
begin
CheckOSError(pthread_cond_broadcast(FCondVar));
end;
{$ENDIF}
function TConditionVariableMutex.WaitFor(AExternalMutex: TMutex; TimeOut: LongWord): TWaitResult;
{$IFDEF MSWINDOWS}
var
LastWaiter: Boolean;
begin
if AExternalMutex = nil then
raise EArgumentNilException.CreateRes(@SArgumentNil);
FCountLock.Enter;
try
Inc(FWaiterCount);
finally
FCountLock.Leave;
end;
case SignalObjectAndWait(AExternalMutex.Handle, FWaitSemaphore.Handle, TimeOut, False) of
WAIT_FAILED, WAIT_IO_COMPLETION: Result := wrError;
WAIT_ABANDONED: Result := wrAbandoned;
WAIT_TIMEOUT: Result := wrTimeout;
else
Result := wrSignaled;
end;
FCountLock.Enter;
try
Dec(FWaiterCount);
LastWaiter := FBroadcasting and (FWaiterCount = 0);
finally
FCountLock.Leave;
end;
if Result <> wrSignaled then
begin
if Result = wrTimeout then
AExternalMutex.WaitFor(INFINITE);
Exit;
end;
if LastWaiter then
case SignalObjectAndWait(FWaitersDoneEvent.Handle, AExternalMutex.Handle, INFINITE, False) of
WAIT_FAILED, WAIT_IO_COMPLETION: Result := wrError;
WAIT_ABANDONED: Result := wrAbandoned;
WAIT_TIMEOUT: Result := wrTimeout;
else
Result := wrSignaled;
end
else
Result := AExternalMutex.WaitFor(INFINITE);
end;
{$ENDIF}
{$IFDEF POSIX}
var
Err: Integer;
EndTime: timespec;
begin
if AExternalMutex = nil then
raise EArgumentNilException.CreateRes(@SArgumentNil);
if (TimeOut > 0) and (Timeout < INFINITE) then
begin
GetPosixEndTime(EndTime, Timeout);
if pthread_cond_timedwait(FCondVar, AExternalMutex.FMutex, EndTime) = 0 then
Exit(wrSignaled);
Err := GetLastError;
if Err = ETIMEDOUT then
Result := wrTimeout
else
Result := wrError;
end else if Timeout = INFINITE then
begin
if pthread_cond_wait(FCondVar, AExternalMutex.FMutex) = 0 then
Result := wrSignaled
else
Result := wrError;
end else
Result := wrTimeout;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
{ TConditionVariableHelper }
class function TConditionVariableHelper.Create: TRTLConditionVariable;
begin
InitializeConditionVariableProc(Result);
end;
procedure TConditionVariableHelper.Free;
begin
// do nothing here;
end;
function TConditionVariableHelper.SleepCS(var CriticalSection: TRTLCriticalSection; dwMilliseconds: DWORD): Boolean;
begin
Result := SleepConditionVariableCSProc(Self, CriticalSection, dwMilliseconds);
end;
procedure TConditionVariableHelper.Wake;
begin
WakeConditionVariableProc(Self);
end;
procedure TConditionVariableHelper.WakeAll;
begin
WakeAllConditionVariableProc(Self);
end;
procedure InternalInitConditionVariable(out ConditionVariable: TRTLConditionVariable); stdcall;
begin
ConditionVariable.Ptr := nil;
end;
procedure InternalWakeConditionVariable(var ConditionVariable: TRTLConditionVariable); stdcall;
begin
PInternalConditionVariable(@ConditionVariable).Wake;
end;
procedure InternalWakeAllConditionVariable(var ConditionVariable: TRTLConditionVariable); stdcall;
begin
PInternalConditionVariable(@ConditionVariable).WakeAll;
end;
function InternalSleepConditionVariableCS(var ConditionVariable: TRTLConditionVariable; var CriticalSection: TRTLCriticalSection; dwMilliseconds: DWORD): BOOL; stdcall;
begin
Result := PInternalConditionVariable(@ConditionVariable).SleepCriticalSection(CriticalSection, dwMilliseconds);
end;
{$ENDIF}
{ TConditionVariableCS }
{$IFDEF POSIX}
constructor TConditionVariableCS.Create;
begin
inherited Create;
FCondVar := TObject.Create;
end;
destructor TConditionVariableCS.Destroy;
begin
FCondVar.Free;
inherited Destroy;
end;
{$ENDIF}
procedure TConditionVariableCS.Acquire;
begin
raise ESyncObjectException.CreateRes(@sCannotCallAcquireOnConditionVar);
end;
procedure TConditionVariableCS.Release;
begin
{$IFDEF MSWINDOWS}
WakeConditionVariableProc(FConditionVariable);
{$ENDIF}
{$IFDEF POSIX}
TMonitor.Pulse(FCondVar);
{$ENDIF}
end;
procedure TConditionVariableCS.ReleaseAll;
begin
{$IFDEF MSWINDOWS}
WakeAllConditionVariableProc(FConditionVariable);
{$ENDIF}
{$IFDEF POSIX}
TMonitor.PulseAll(FCondVar);
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
function TConditionVariableCS.WaitFor(var CriticalSection: TRTLCriticalSection;
TimeOut: LongWord): TWaitResult;
begin
if SleepConditionVariableCSProc(FConditionVariable, CriticalSection, Timeout) then
Result := wrSignaled
else
case GetLastError of
ERROR_TIMEOUT: Result := wrTimeout;
WAIT_ABANDONED: Result := wrAbandoned;
else
Result := wrError;
end;
end;
{$ENDIF}
function TConditionVariableCS.WaitFor(CriticalSection: TCriticalSection;
TimeOut: LongWord): TWaitResult;
begin
if CriticalSection = nil then
raise EArgumentNilException.CreateRes(@SArgumentNil);
{$IFDEF MSWINDOWS}
Result := WaitFor(CriticalSection.FSection, TimeOut);
{$ENDIF}
{$IFDEF POSIX}
if TMonitor.Wait(FCondVar, CriticalSection.FSection.FSync, Integer(TimeOut)) then
Result := wrSignaled
else
Result := wrTimeout;
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
{ TInternalConditionVariable }
class function TInternalConditionVariable.Create: TInternalConditionVariable;
begin
Result.FWaitQueue := nil;
end;
function TInternalConditionVariable.DequeueWaiter: PWaitingThread;
var
WaitQueue: PWaitingThread;
begin
WaitQueue := LockQueue;
try
Result := DequeueWaiterNoLock(WaitQueue);
finally
UnlockQueue(WaitQueue);
end;
end;
function TInternalConditionVariable.DequeueWaiterNoLock(var WaitQueue: PWaitingThread): PWaitingThread;
begin
Result := WaitQueue;
if (Result = nil) or (Result.Next = Result) then
begin
WaitQueue := nil;
System.Exit;
end else
begin
Result := WaitQueue.Next;
WaitQueue.Next := WaitQueue.Next.Next;
end;
end;
function TInternalConditionVariable.LockQueue: PWaitingThread;
var
SpinLock: Boolean;
SpinCount: Integer;
begin
SpinLock := CPUCount > 1;
if SpinLock then
SpinCount := 4000
else
SpinCount := -1;
repeat
Result := PWaitingThread(IntPtr(FWaitQueue) and not 1);
if PWaitingThread(InterlockedCompareExchangePointer(Pointer(FWaitQueue), Pointer(IntPtr(Result) or 1), Pointer(Result))) = Result then
Break;
if SpinCount < 0 then
begin
SwitchToThread;
if SpinLock then
SpinCount := 4000
else
SpinCount := 0;
end else
{$IFDEF PUREPASCAL}
YieldProcessor;
{$ELSE !PUREPASCAL}
{$IFDEF X86ASM}
asm
PAUSE
end;
{$ENDIF X86ASM}
{$ENDIF !PUREPASCAL}
Dec(SpinCount);
until False;
end;
procedure TInternalConditionVariable.QueueWaiter(var WaitingThread: TWaitingThread);
var
WaitQueue: PWaitingThread;
begin
// Lock the list
Assert(Integer(@WaitingThread) and 1 = 0);
WaitQueue := LockQueue;
try
if WaitQueue = nil then
begin
WaitQueue := @WaitingThread;
WaitingThread.Next := @WaitingThread
end else
begin
WaitingThread.Next := WaitQueue.Next;
WaitQueue.Next := @WaitingThread;
WaitQueue := @WaitingThread;
end;
finally
UnlockQueue(WaitQueue);
end;
end;
procedure TInternalConditionVariable.RemoveWaiter(var WaitingThread: TWaitingThread);
var
WaitQueue, Last, Walker: PWaitingThread;
begin
if Pointer(IntPtr(FWaitQueue) and not 1) <> nil then
begin
WaitQueue := LockQueue;
try
Last := WaitQueue;
Walker := Last.Next;
while Walker <> WaitQueue do
begin
if Walker = @WaitingThread then
begin
Last.Next := Walker.Next;
Break;
end;
Last := Walker;
Walker := Walker.Next;
end;
if (Walker = WaitQueue) and (Walker = @WaitingThread) then
if Walker.Next = Walker then
WaitQueue := nil
else
begin
WaitQueue := Walker.Next;
Last.Next := WaitQueue;
end;
finally
UnlockQueue(WaitQueue);
end;
end;
end;
function TInternalConditionVariable.SleepCriticalSection(
var CriticalSection: TRTLCriticalSection; Timeout: DWORD): Boolean;
var
WaitingThread: TWaitingThread;
RecursionCount: Integer;
begin
if CriticalSection.OwningThread = GetCurrentThreadId then
begin
WaitingThread.Next := nil;
WaitingThread.Thread := CriticalSection.OwningThread;
WaitingThread.WaitEvent := CreateEvent(nil, False, False, nil);
try
// Save the current recursion count
RecursionCount := CriticalSection.RecursionCount;
// Add the current thread to the waiting queue
QueueWaiter(WaitingThread);
// Set it back to almost released
CriticalSection.RecursionCount := 1;
InterlockedExchangeAdd(CriticalSection.LockCount, -(RecursionCount - 1));
// Release and get in line for someone to do a Pulse or PulseAll
CriticalSection.Leave;
// This is, admitedly, a potential race condition
case WaitForSingleObject(WaitingThread.WaitEvent, Timeout) of
WAIT_TIMEOUT:
begin
Result := False;
SetLastError(ERROR_TIMEOUT);
end;
WAIT_OBJECT_0: Result := True;
else
Result := False;
SetLastError(ERROR);
end;
// Got to get the lock back and block waiting for it.
CriticalSection.Enter;
// Remove any dangling waiters from the list
RemoveWaiter(WaitingThread);
// Lets restore all the recursion and lock counts
InterlockedExchangeAdd(Integer(CriticalSection.LockCount), RecursionCount - 1);
CriticalSection.RecursionCount := RecursionCount;
finally
CloseHandle(WaitingThread.WaitEvent);
end;
end else
Result := False;
end;
procedure TInternalConditionVariable.UnlockQueue(WaitQueue: PWaitingThread);
begin
FWaitQueue := PWaitingThread(IntPtr(WaitQueue) and not 1);
end;
procedure TInternalConditionVariable.Wake;
var
WaitingThread: PWaitingThread;
begin
WaitingThread := DequeueWaiter;
if WaitingThread <> nil then
SetEvent(WaitingThread.WaitEvent);
end;
procedure TInternalConditionVariable.WakeAll;
var
WaitQueue, WaitingThread: PWaitingThread;
begin
WaitQueue := LockQueue;
try
WaitingThread := DequeueWaiterNoLock(WaitQueue);
while WaitingThread <> nil do
begin
SetEvent(WaitingThread.WaitEvent);
WaitingThread := DequeueWaiterNoLock(WaitQueue);
end;
finally
UnlockQueue(WaitQueue);
end;
end;
{$ENDIF}
{ TInterlocked }
class function TInterlocked.Add(var Target: Integer; Increment: Integer): Integer;
{$IFDEF X64ASM}
asm
.NOFRAME
MOV EAX,EDX
LOCK XADD [RCX].Integer,EAX
ADD EAX,EDX
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
MOV ECX,EDX
XCHG EAX,EDX
LOCK XADD [EDX],EAX
ADD EAX,ECX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.Add(var Target: Int64; Increment: Int64): Int64;
{$IFDEF X64ASM}
asm
.NOFRAME
MOV RAX,RDX
LOCK XADD [RCX],RAX
ADD RAX,RDX
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
PUSH EBX
PUSH ESI
MOV ESI,Target
MOV EAX,DWORD PTR [ESI]
MOV EDX,DWORD PTR [ESI+4]
@@1:
MOV EBX,EAX
MOV ECX,EDX
ADD EBX,LOW Increment
ADC ECX,HIGH Increment
LOCK CMPXCHG8B [ESI]
JNZ @@1
ADD EAX,LOW Increment
ADC EDX,HIGH Increment
POP ESI
POP EBX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.BitTestAndSet(var Target: Integer; BitOffset: TBitOffset): Boolean;
{$IFDEF X64ASM}
asm
.NOFRAME
AND EDX,31
LOCK BTS [RCX].Integer,EDX
SETC AL
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
AND EDX,31
LOCK BTS [EAX],EDX
SETC AL
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.BitTestAndClear(var Target: Integer; BitOffset: TBitOffset): Boolean;
{$IFDEF X64ASM}
asm
.NOFRAME
AND EDX,31
LOCK BTR [RCX],EDX
SETC AL
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
AND EDX,31
LOCK BTR [EAX],EDX
SETC AL
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.CompareExchange(var Target: Pointer; Value: Pointer; Comparand: Pointer): Pointer;
{$IFDEF X64ASM}
asm
.NOFRAME
MOV RAX,R8
LOCK CMPXCHG [RCX],RDX
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
XCHG EAX,EDX
XCHG EAX,ECX
LOCK CMPXCHG [EDX],ECX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.CompareExchange(var Target: TObject; Value, Comparand: TObject): TObject;
begin
Result := TObject(CompareExchange(Pointer(Target), Pointer(Value), Pointer(Comparand)));
end;
class function TInterlocked.CompareExchange(var Target: Int64; Value, Comparand: Int64): Int64;
{$IFDEF X64ASM}
asm
.NOFRAME
MOV RAX,R8
LOCK CMPXCHG [RCX],RDX
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
PUSH EBX
PUSH ESI
MOV ESI,Target
MOV EDX,HIGH Comparand
MOV EAX,LOW Comparand
MOV ECX,HIGH Value
MOV EBX,LOW Value
LOCK CMPXCHG8B [ESI]
POP ESI
POP EBX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.CompareExchange(var Target: Integer; Value, Comparand: Integer): Integer;
{$IFDEF X64ASM}
asm
.NOFRAME
MOV EAX,R8d
LOCK CMPXCHG [RCX].Integer,EDX
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
XCHG EAX,EDX
XCHG EAX,ECX
LOCK CMPXCHG [EDX],ECX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.CompareExchange(var Target: Integer; Value: Integer; Comparand: Integer; out Succeeded: Boolean): Integer;
{$IFDEF X64ASM}
asm
.NOFRAME
MOV EAX,R8d
LOCK CMPXCHG [RCX].Integer,EDX
SETZ [R9].Boolean
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
XCHG EAX,EDX
XCHG EAX,ECX
LOCK CMPXCHG [EDX],ECX
MOV ECX,[ESP+4]
SETZ [ECX].Boolean
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.CompareExchange(var Target: Double; Value, Comparand: Double): Double;
{$IFDEF X64ASM}
asm
.NOFRAME
MOVQ RDX,XMM1
MOVQ RAX,XMM2
LOCK CMPXCHG [RCX],RDX
MOVQ XMM0,RAX
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
PUSH EBX
PUSH ESI
MOV ESI,Target
MOV EDX,HIGH Comparand
MOV EAX,LOW Comparand
MOV ECX,HIGH Value
MOV EBX,LOW Value
LOCK CMPXCHG8B [ESI]
MOV HIGH Result,EDX
MOV LOW Result,EAX
POP ESI
POP EBX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.CompareExchange(var Target: Single; Value, Comparand: Single): Single;
{$IFDEF X64ASM}
asm
.NOFRAME
MOVD EDX,XMM1
MOVD EAX,XMM2
LOCK CMPXCHG [RCX].Single,EDX
MOVD XMM0,EAX
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
MOV EDX,EAX
MOV EAX,Comparand
MOV ECX,Value
LOCK CMPXCHG [EDX],ECX
MOV Result,EAX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.CompareExchange<T>(var Target: T; Value, Comparand: T): T;
begin
TObject(Pointer(@Result)^) := CompareExchange(TObject(Pointer(@Target)^), TObject(Pointer(@Value)^), TObject(Pointer(@Comparand)^));
end;
class function TInterlocked.Decrement(var Target: Int64): Int64;
begin
Result := Add(Target, -1);
end;
class function TInterlocked.Decrement(var Target: Integer): Integer;
begin
Result := Add(Target, -1);
end;
class function TInterlocked.Exchange(var Target: Int64; Value: Int64): Int64;
{$IFDEF X64ASM}
asm
.NOFRAME
MOV RAX,[RCX]
@@1:
LOCK CMPXCHG [RCX],RDX
JNZ @@1
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
PUSH EBX
PUSH ESI
MOV ESI,Target
MOV EBX,LOW Value
MOV ECX,HIGH Value
MOV EAX,DWORD PTR [ESI]
MOV EDX,DWORD PTR [ESI+4]
@@1:
LOCK CMPXCHG8B [ESI]
JNZ @@1
POP ESI
POP EBX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.Exchange(var Target: Integer; Value: Integer): Integer;
{$IFDEF X64ASM}
asm
.NOFRAME
MOV EAX,[RCX].Integer
@@1:
LOCK CMPXCHG [RCX].Integer,EDX
JNZ @@1
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
MOV ECX,EAX
MOV EAX,[ECX]
@@1:
LOCK CMPXCHG [ECX],EDX
JNZ @@1
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.Exchange(var Target: TObject; Value: TObject): TObject;
begin
Result := TObject(Exchange(Pointer(Target), Pointer(Value)));
end;
class function TInterlocked.Exchange(var Target: Pointer; Value: Pointer): Pointer;
{$IFDEF X64ASM}
asm
.NOFRAME
LOCK XCHG [RCX],RDX
MOV RAX,RDX
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
LOCK XCHG [EAX],EDX
MOV EAX,EDX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.Exchange(var Target: Single; Value: Single): Single;
{$IFDEF X64ASM}
asm
.NOFRAME
MOVD EDX,XMM1
LOCK XCHG [RCX].Single,EDX
MOVD XMM0,EDX
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
MOV ECX,EAX
MOV EAX,[ECX]
MOV EDX,Value
@@1:
LOCK CMPXCHG [ECX],EAX
JNZ @@1
MOV Result,EAX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.Exchange(var Target: Double; Value: Double): Double;
{$IFDEF X64ASM}
asm
.NOFRAME
MOVQ RDX,XMM1
LOCK XCHG [RCX],RDX
MOVQ XMM0,RDX
end;
{$ELSE !X64ASM}
{$IFDEF X86ASM}
asm
PUSH EBX
PUSH ESI
MOV ESI, Target
MOV EDX,HIGH Value
MOV EAX,LOW Value
MOV ECX,HIGH Value
MOV EBX,LOW Value
@@1:
LOCK CMPXCHG8B [ESI]
JNZ @@1
MOV HIGH Result, EDX
MOV LOW Result, EAX
POP ESI
POP EBX
end;
{$ENDIF X86ASM}
{$ENDIF !X64ASM}
class function TInterlocked.Exchange<T>(var Target: T; Value: T): T;
begin
TObject(Pointer(@Result)^) := Exchange(TObject(Pointer(@Target)^), TObject(Pointer(@Value)^));
end;
class function TInterlocked.Increment(var Target: Integer): Integer;
begin
Result := Add(Target, 1);
end;
class function TInterlocked.Increment(var Target: Int64): Int64;
begin
Result := Add(Target, 1);
end;
{$IFDEF MSWINDOWS}
procedure InitConditionVariableProcs;
var
Module: HMODULE;
begin
Module := GetModuleHandle('kernel32.dll'); // do not localize
InitializeConditionVariableProc := GetProcAddress(Module, 'InitializeConditionVariable'); // do not localize
if @InitializeConditionVariableProc = nil then
begin
InitializeConditionVariableProc := InternalInitConditionVariable;
WakeConditionVariableProc := InternalWakeConditionVariable;
WakeAllConditionVariableProc := InternalWakeAllConditionVariable;
SleepConditionVariableCSProc := InternalSleepConditionVariableCS;
end else
begin
WakeConditionVariableProc := GetProcAddress(Module, 'WakeConditionVariable'); // do not localize
WakeAllConditionVariableProc := GetProcAddress(Module, 'WakeAllConditionVariable'); // do not localize
SleepConditionVariableCSProc := GetProcAddress(Module, 'SleepConditionVariableCS'); // do not localize
end;
end;
{$ENDIF}
{ TSpinWait }
function TSpinWait.GetNextSpinCycleWillYield: Boolean;
begin
Result := (FCount > YieldThreshold) or (CPUCount = 1);
end;
procedure TSpinWait.Reset;
begin
FCount := 0;
end;
procedure TSpinWait.SpinCycle;
var
SpinCount: Integer;
begin
if NextSpinCycleWillYield then
begin
if FCount >= YieldThreshold then
SpinCount := FCount - YieldThreshold
else
SpinCount := FCount;
if SpinCount mod Sleep1Threshold = Sleep1Threshold - 1 then
TThread.Sleep(1)
else if SpinCount mod Sleep0Threshold = Sleep0Threshold - 1 then
TThread.Sleep(0)
else
TThread.Yield;
end else
TThread.SpinWait(4 shl FCount);
Inc(FCount);
if FCount < 0 then
FCount := YieldThreshold + 1;
end;
class procedure TSpinWait.SpinUntil(const ACondition: TFunc<Boolean>);
begin
SpinUntil(ACondition, INFINITE);
end;
class function TSpinWait.SpinUntil(const ACondition: TFunc<Boolean>; Timeout: LongWord): Boolean;
var
Timer: TStopwatch;
Wait: TSpinWait;
begin
if @ACondition = nil then
raise EArgumentNilException.CreateRes(@SArgumentNil);
Timer := TStopwatch.StartNew;
Wait.Reset;
while not ACondition() do
begin
if Timeout = 0 then
Exit(False);
Wait.SpinCycle;
if (Timeout <> INFINITE) and Wait.NextSpinCycleWillYield and (Timeout <= Timer.ElapsedMilliseconds) then
Exit(False);
end;
Result := True;
end;
class function TSpinWait.SpinUntil(const ACondition: TFunc<Boolean>; const Timeout: TTimeSpan): Boolean;
var
Total: Int64;
begin
Total := Trunc(Timeout.TotalMilliseconds);
if (Total < 0) or (Total > $7FFFFFFF) then
raise EArgumentOutOfRangeException.CreateResFmt(@sInvalidTimeoutValue, [string(Timeout)]);
Result := SpinUntil(ACondition, LongWord(Total));
end;
{ TSpinLock }
constructor TSpinLock.Create(EnableThreadTracking: Boolean);
begin
if EnableThreadTracking then
FLock := LockAvailable
else
FLock := Integer(ThreadTrackingDisabled);
end;
procedure TSpinLock.Enter;
begin
TryEnter(INFINITE);
end;
procedure TSpinLock.Exit(PublishNow: Boolean);
begin
if IsThreadTrackingEnabled and not IsLockedByCurrentThread then
raise ELockException.CreateRes(@SSpinLockNotOwned);
if PublishNow then
begin
if IsThreadTrackingEnabled then
TInterlocked.Exchange(FLock, LockAvailable)
else
TInterlocked.Decrement(FLock)
end else if IsThreadTrackingEnabled then
FLock := LockAvailable
else
Dec(FLock);
end;
function TSpinLock.GetIsLocked: Boolean;
begin
if IsThreadTrackingEnabled then
Result := FLock <> LockAvailable
else
Result := FLock and AnonymouslyOwned = AnonymouslyOwned;
end;
function TSpinLock.GetIsLockedByCurrentThread: Boolean;
begin
if not IsThreadTrackingEnabled then
raise EInvalidOpException.CreateRes(@SSpinLockInvalidOperation);
Result := Cardinal(FLock and $7FFFFFFF) = TThread.CurrentThread.ThreadID;
end;
function TSpinLock.GetIsThreadTrackingEnabled: Boolean;
begin
Result := FLock and ThreadTrackingDisabled = 0;
end;
function TSpinLock.InternalTryEnter(Timeout: LongWord): Boolean;
var
CurLock: Integer;
NewLock: Integer;
Timer: TStopwatch;
Wait: TSpinWait;
SpinLock: ^TSpinLock;
begin
SpinLock := @Self;
if IsThreadTrackingEnabled then
begin
NewLock := TThread.CurrentThread.ThreadID;
if FLock = NewLock then
raise ELockRecursionException.CreateRes(@SSpinLockReEntered);
Result := TSpinWait.SpinUntil(
function: Boolean
begin
Result := (SpinLock.FLock = LockAvailable) and (TInterlocked.CompareExchange(SpinLock.FLock, NewLock, LockAvailable) = LockAvailable);
end, Timeout);
end else
begin
Timer := TStopwatch.StartNew;
Wait.Reset;
while True do
begin
CurLock := FLock;
if CurLock and AnonymouslyOwned = LockAvailable then
begin
if TInterlocked.CompareExchange(FLock, CurLock or AnonymouslyOwned, CurLock) = CurLock then
Exit(True);
end else if (CurLock and WaitingThreadMask = MaxWaitingThreads) or (TInterlocked.CompareExchange(FLock, CurLock + 2, CurLock) = CurLock) then
Break;
Wait.SpinCycle;
end;
if (Timeout = 0) or ((Timeout <> INFINITE) and (Timeout <= Timer.ElapsedMilliseconds)) then
begin
RemoveWaiter;
Exit(False);
end;
// Adjust the timeout for any time already spent
Timeout := Timeout - Timer.ElapsedMilliseconds;
Result := TSpinWait.SpinUntil(
function: Boolean
begin
CurLock := SpinLock.FLock;
if CurLock and AnonymouslyOwned = LockAvailable then
begin
if CurLock and WaitingThreadMask = LockAvailable then
NewLock := CurLock or AnonymouslyOwned
else
NewLock := (CurLock - 2) or AnonymouslyOwned;
Result := TInterlocked.CompareExchange(SpinLock.FLock, NewLock, CurLock) = CurLock;
end else
Result := False;
end, Timeout);
if not Result then
RemoveWaiter;
end;
end;
procedure TSpinLock.RemoveWaiter;
var
CurLock: Integer;
Wait: TSpinWait;
begin
Wait.Reset;
while True do
begin
CurLock := FLock;
if (CurLock and WaitingThreadMask = 0) or (TInterlocked.CompareExchange(FLock, CurLock - 2, CurLock) = CurLock) then
Exit;
Wait.SpinCycle;
end;
end;
function TSpinLock.TryEnter: Boolean;
begin
Result := TryEnter(0);
end;
function TSpinLock.TryEnter(const Timeout: TTimeSpan): Boolean;
var
Total: Int64;
begin
Total := Trunc(Timeout.TotalMilliseconds);
if (Total < 0) or (Total > $7FFFFFFF) then
raise EArgumentOutOfRangeException.CreateResFmt(@sInvalidTimeoutValue, [string(Timeout)]);
Result := TryEnter(LongWord(Total));
end;
function TSpinLock.TryEnter(Timeout: LongWord): Boolean;
var
CurLock: Integer;
NewLock: Cardinal;
begin
CurLock := FLock;
NewLock := 0;
if IsThreadTrackingEnabled then
begin
if CurLock = LockAvailable then
NewLock := TThread.CurrentThread.ThreadID;
end else if CurLock and AnonymouslyOwned = LockAvailable then
NewLock := CurLock or AnonymouslyOwned;
if NewLock <> 0 then
if TInterlocked.CompareExchange(FLock, NewLock, CurLock) = CurLock then
Exit(True);
Result := InternalTryEnter(Timeout);
end;
{ TLightweightEvent }
constructor TLightweightEvent.Create;
begin
Create(False);
end;
constructor TLightweightEvent.Create(InitialState: Boolean);
begin
Create(InitialState, DefaultSpinMulticore);
end;
constructor TLightweightEvent.Create(InitialState: Boolean; SpinCount: Integer);
begin
inherited Create;
FLock := TObject.Create;
TMonitor.SetSpinCount(FLock, 10);
if InitialState then
FStateAndSpin := EventSignaled;
if (SpinCount < 0) or (SpinCount > MaxSpin) then
raise EArgumentOutOfRangeException.CreateResFmt(@sSpinCountOutOfRange, [MaxSpin]);
if CPUCount = 1 then
FStateAndSpin := FStateAndSpin or DefaultSpinSinglecore
else
FStateAndSpin := FStateAndSpin or SpinCount;
end;
destructor TLightweightEvent.Destroy;
begin
FLock.Free;
inherited;
end;
function TLightweightEvent.GetIsSet: Boolean;
begin
Result := (FStateAndSpin and SignalMask) = EventSignaled;
end;
function TLightweightEvent.GetSpinCount: Integer;
begin
Result := FStateAndSpin and SpinMask;
end;
procedure TLightweightEvent.ResetEvent;
begin
SetNewStateAtomically(EventUnsignaled, SignalMask);
end;
procedure TLightweightEvent.SetEvent;
begin
SetNewStateAtomically(EventSignaled, SignalMask);
if FWaiters > 0 then
begin
TMonitor.Enter(FLock);
try
TMonitor.PulseAll(FLock);
finally
TMonitor.Exit(FLock);
end;
end;
end;
procedure TLightweightEvent.SetNewStateAtomically(NewValue, Mask: Integer);
var
Spin: TSpinWait;
CurrentState, NewState: Integer;
begin
Spin.Reset;
while True do
begin
CurrentState := FStateAndSpin;
NewState := (CurrentState and not Mask) or NewValue;
if TInterlocked.CompareExchange(FStateAndSpin, NewState, CurrentState) = CurrentState then
Exit;
Spin.SpinCycle;
end;
end;
function TLightweightEvent.WaitFor(Timeout: LongWord): TWaitResult;
var
I: Integer;
Timer: TStopwatch;
SpinWait: TSpinWait;
Elapsed: Int64;
begin
if not IsSet then
begin
if Timeout = 0 then
Exit(wrTimeout);
SpinWait.Reset;
if SpinCount > 0 then
begin
if Timeout < INFINITE then
Timer := TStopwatch.StartNew;
for I := 0 to SpinCount - 1 do
begin
SpinWait.SpinCycle;
if IsSet then
Exit(wrSignaled);
end;
end;
if Timeout < INFINITE then
begin
Elapsed := Timer.ElapsedMilliseconds;
if (Elapsed > $7FFFFFFF) or (Elapsed >= Timeout) then
Exit(wrTimeout);
Timeout := Timeout - Elapsed;
end;
TMonitor.Enter(FLock);
try
TInterlocked.Increment(FWaiters); // Use a full fence here
try
TInterlocked.Increment(FBlockedCount);
if IsSet or TMonitor.Wait(FLock, Timeout) then
Result := wrSignaled
else
Result := wrTimeout;
finally
Dec(FWaiters);
end;
finally
TMonitor.Exit(FLock);
end;
end else
Result := wrSignaled;
end;
{ TLightweightSemaphore }
constructor TLightweightSemaphore.Create(AInitialCount, AMaxCount: Integer);
begin
inherited Create;
if (AInitialCount < 0) or (AInitialCount > AMaxCount) then
raise EArgumentOutOfRangeException.CreateResFmt(@sInvalidInitialSemaphoreCount, [AInitialCount]);
if AMaxCount <= 0 then
raise EArgumentOutOfRangeException.CreateResFmt(@sInvalidMaxSemaphoreCount, [AMaxCount]);
FInitialCount := AInitialCount;
FMaxCount := AMaxCount;
FCountLock := TObject.Create;
TMonitor.SetSpinCount(FCountLock, 10);
FCurrentCount := AInitialCount;
end;
destructor TLightweightSemaphore.Destroy;
begin
FCountLock.Free;
inherited;
end;
function TLightweightSemaphore.Release(AReleaseCount: Integer): Integer;
begin
Result := 0;
if AReleaseCount < 0 then
raise EArgumentOutOfRangeException.CreateResFmt(@sInvalidSemaphoreReleaseCount, [AReleaseCount]);
TMonitor.Enter(FCountLock);
try
if FMaxCount - FCurrentCount < AReleaseCount then
raise ESyncObjectException.CreateRes(@sSemaphoreReachedMaxCount);
Inc(FCurrentCount, AReleaseCount);
if (FCurrentCount = 1) or (FWaitCount = 1) then
TMonitor.Pulse(FCountLock)
else if FWaitCount > 1 then
TMonitor.PulseAll(FCountLock);
Result := FCurrentCount - AReleaseCount;
finally
TMonitor.Exit(FCountLock);
end;
end;
function TLightweightSemaphore.WaitFor(Timeout: LongWord): TWaitResult;
var
Timer: TStopwatch;
Spinner: TSpinWait;
CountDown: Integer;
function UpdateTimeout(const Timer: TStopwatch; OriginalWaitTime: Integer): Integer;
var
Elapsed: Int64;
begin
Elapsed := Timer.ElapsedMilliseconds;
if Elapsed > $7FFFFFFF then
Result := 0
else
Result := OriginalWaitTime - Integer(Elapsed);
if Result < 0 then
Result := 0;
end;
begin
Timer := TStopWatch.Create;
Spinner.Reset;
CountDown := Integer(Timeout);
if Timeout < INFINITE then
Timer.Start;
while True do
begin
if FCurrentCount > 0 then
begin
if TMonitor.TryEnter(FCountLock) then
Break;
end;
if Spinner.NextSpinCycleWillYield then
begin
if Timeout = 0 then
Exit(wrTimeout);
if Timeout < INFINITE then
begin
CountDown := UpdateTimeout(Timer, Timeout);
if CountDown <= 0 then
Exit(wrTimeout);
end;
if not TMonitor.Enter(FCountLock, Cardinal(CountDown)) then
Exit(wrTimeout);
Break;
end;
Spinner.SpinCycle;
end;
Inc(FWaitCount);
try
while FCurrentCount = 0 do
begin
if Timeout < INFINITE then
begin
Countdown := UpdateTimeout(Timer, Timeout);
if CountDown <= 0 then
Exit(wrTimeout);
end;
TInterlocked.Increment(FBlockedCount);
if not TMonitor.Wait(FCountLock, Cardinal(Countdown)) then
Exit(wrTimeout);
end;
Dec(FCurrentCount);
finally
Dec(FWaitCount);
TMonitor.Exit(FCountLock);
end;
Result := wrSignaled;
end;
{ TCountdownEvent }
constructor TCountdownEvent.Create(Count: Integer);
begin
inherited Create;
if Count < 0 then
raise EArgumentOutOfRangeException.CreateResFmt(@sInvalidInitialCount, [Count]);
FInitialCount := Count;
FCurrentCount := Count;
FEvent := TLightweightEvent.Create;
if Count = 0 then
FEvent.SetEvent;
end;
function TCountdownEvent.Signal(Count: Integer): Boolean;
var
CurCount: Integer;
SpinWait: TSpinWait;
begin
if Count <= 0 then
raise EArgumentOutOfRangeException.CreateResFmt(@sInvalidDecrementCount, [Count]);
Result := False;
SpinWait.Reset;
while True do
begin
CurCount := FCurrentCount;
if CurCount < Count then
raise EInvalidOperation.CreateResFmt(@sInvalidDecrementOperation, [Count, CurCount]);
if TInterlocked.CompareExchange(FCurrentCount, CurCount - Count, CurCount) <> CurCount then
begin
SpinWait.SpinCycle;
Continue;
end;
if CurCount = Count then
begin
FEvent.SetEvent;
Result := True;
end;
Break;
end;
end;
destructor TCountdownEvent.Destroy;
begin
FEvent.Free;
inherited;
end;
function TCountdownEvent.GetIsSet: Boolean;
begin
Result := FCurrentCount = 0;
end;
procedure TCountdownEvent.AddCount(Count: Integer);
begin
if not TryAddCount(Count) then
raise EInvalidOperation.CreateRes(@sCountdownAlreadyZero);
end;
procedure TCountdownEvent.Reset(Count: Integer);
begin
if Count < 0 then
raise EArgumentOutOfRangeException.CreateResFmt(@sInvalidResetCount, [Count]);
FCurrentCount := Count;
FInitialCount := Count;
if Count = 0 then
FEvent.SetEvent
else
FEvent.ResetEvent;
end;
procedure TCountdownEvent.Reset;
begin
Reset(FInitialCount);
end;
function TCountdownEvent.TryAddCount(Count: Integer): Boolean;
var
CurCount: Integer;
SpinWait: TSpinWait;
begin
if Count <= 0 then
raise EArgumentOutOfRangeException.CreateResFmt(@sInvalidIncrementCount, [Count]);
SpinWait.Reset;
while True do
begin
CurCount := FCurrentCount;
if CurCount = 0 then
Exit(False);
if CurCount > ($7FFFFFFF - Count) then
raise EInvalidOperation.CreateResFmt(@sInvalidIncrementOperation, [Count, CurCount]);
if TInterlocked.CompareExchange(FCurrentCount, CurCount + Count, CurCount) <> CurCount then
begin
SpinWait.SpinCycle;
Continue;
end;
Break;
end;
Result := True;
end;
function TCountdownEvent.WaitFor(Timeout: LongWord): TWaitResult;
begin
if not IsSet then
Result := FEvent.WaitFor(Timeout)
else
Result := wrSignaled;
end;
initialization
{$IFDEF MSWINDOWS}
InitConditionVariableProcs;
{$ENDIF}
end.
|
unit PrintPreviewFrame;
interface
uses
SysUtils, Forms, ExtCtrls, ToolWin, Preview, Controls, ComCtrls, Classes,
Windows, ActnList, Graphics, ItemsDef, Types, Contnrs, Printers, StdCtrls, Core;
type
TfrmPrintPreview = class(TFrame)
tlbPrintPreview: TToolBar;
panPrintPreview: TPanel;
btnPrint: TToolButton;
btnPrintOnePage: TToolButton;
alPrintPreview: TActionList;
actPrint: TAction;
actPrintOnePage: TAction;
btn1: TToolButton;
btnZoomFit: TToolButton;
btnZoomPlus: TToolButton;
btnZoomMinus: TToolButton;
btn2: TToolButton;
btnPageFirst: TToolButton;
btnPagePrev: TToolButton;
btnPageNext: TToolButton;
btnPageLast: TToolButton;
actZoomFit: TAction;
actZoomPlus: TAction;
actZoomMinus: TAction;
actPageFirst: TAction;
actPagePrev: TAction;
actPageNext: TAction;
actPageLast: TAction;
cbbPageNum: TComboBox;
btn3: TToolButton;
btnPageAdjust: TToolButton;
actPageAdjust: TAction;
btnShowTickets: TToolButton;
actShowTickets: TAction;
actClose: TAction;
btnClose: TToolButton;
actSavePDF: TAction;
btnSavePDF: TToolButton;
procedure actPrintOnePageExecute(Sender: TObject);
procedure alPrintPreviewExecute(Action: TBasicAction;
var Handled: Boolean);
procedure DummyAction(Sender: TObject);
procedure cbbPageNumSelect(Sender: TObject);
private
{ Private declarations }
//PreviewParams: TPreviewParams;
PageAdjustForm: TForm;
procedure SavePDF();
public
{ Public declarations }
GridMode: Boolean;
PreviewMode: Boolean;
Preview: TPrintPreview;
NumProject: TNumProject;
function Start(): Boolean;
procedure DrawPreviewPage(c: TCanvas; pinf: TPrnInfo; NumPage: TNumPage);
procedure DrawPreview(iStartPage, iEndPage: integer);
procedure DrawGrid(c: TCanvas; pinf: TPrnInfo; AUnits: Integer = 0);
procedure DrawGridPreview();
procedure ChangeLanguage();
destructor Destroy; override;
end;
var
PrintPrevCreated: Boolean = False;
sPrintPreview: string = 'Предпросмотр печати';
implementation
uses MainForm, PageAdjustFrame, CopyProtection, IniFiles;
{$R *.dfm}
destructor TfrmPrintPreview.Destroy;
begin
PrintPrevCreated:=False;
inherited Destroy();
end;
function TfrmPrintPreview.Start(): boolean;
var
i: integer;
s: string;
begin
if not Assigned(Preview) then
begin
Preview:=TPrintPreview.Create(self);
Preview.Parent:=panPrintPreview;
end;
NumProject:=Core.CurProject;
// Fill pages list
cbbPageNum.Items.BeginUpdate();
cbbPageNum.Clear();
if not GridMode then
begin
NumProject.Pages.SortByOrder();
for i:=0 to NumProject.Pages.Count-1 do
begin
//s:=IntToStr(i+1)+' / '+IntToStr(NumProject.Pages.Count);
s:=IntToStr(i+1);
cbbPageNum.AddItem(s, NumProject.Pages[i]);
end;
if cbbPageNum.Items.Count > 0 then cbbPageNum.ItemIndex:=0;
end;
cbbPageNum.Items.EndUpdate();
PreviewMode:=True;
if CopyProtection.CheckProtectionKey(ProtectionKey) then PreviewMode:=False;
if GridMode then DrawGridPreview() else DrawPreview(1, 0);
Result:=True;
//
PrintPrevCreated:= True;
ChangeLanguage();
end;
procedure TfrmPrintPreview.ChangeLanguage();
var
Part: string;
begin
if not Assigned(LangFile) then Exit;
if PrintPrevCreated then
begin
Part:='PrintPreview';
Self.btnClose.Caption:= LangFile.ReadString(Part, 'sbtnClose', Self.btnClose.Caption);
Self.btnClose.Hint:= LangFile.ReadString(Part, 'hbtnClose', Self.btnClose.Hint);
Self.btnPageAdjust.Caption:= LangFile.ReadString(Part, 'sbtnPageAdjust', Self.btnPageAdjust.Caption);
Self.btnPageAdjust.Hint:= LangFile.ReadString(Part, 'hbtnPageAdjust', Self.btnPageAdjust.Hint);
Self.btnPageFirst.Caption:= LangFile.ReadString(Part, 'sbtnPageFirst', Self.btnPageFirst.Caption);
Self.btnPageFirst.Hint:= LangFile.ReadString(Part, 'hbtnPageFirst', Self.btnPageFirst.Hint);
Self.btnPageLast.Caption:= LangFile.ReadString(Part, 'sbtnPageLast', Self.btnPageLast.Caption);
Self.btnPageLast.Hint:= LangFile.ReadString(Part, 'hbtnPageLast', Self.btnPageLast.Hint);
Self.btnPageNext.Caption:= LangFile.ReadString(Part, 'sbtnPageNext', Self.btnPageNext.Caption);
Self.btnPageNext.Hint:= LangFile.ReadString(Part, 'hbtnPageNext', Self.btnPageNext.Hint);
Self.btnPagePrev.Caption:= LangFile.ReadString(Part, 'sbtnPagePrev', Self.btnPagePrev.Caption);
Self.btnPagePrev.Hint:= LangFile.ReadString(Part, 'hbtnPagePrev', Self.btnPagePrev.Hint);
Self.btnPrint.Caption:= LangFile.ReadString(Part, 'sbtnPrint', Self.btnPrint.Caption);
Self.btnPrint.Hint:= LangFile.ReadString(Part, 'hbtnPrint', Self.btnPrint.Hint);
Self.btnPrintOnePage.Caption:= LangFile.ReadString(Part, 'sbtnPrintOnePage', Self.btnPrintOnePage.Caption);
Self.btnPrintOnePage.Hint:= LangFile.ReadString(Part, 'hbtnPrintOnePage', Self.btnPrintOnePage.Hint);
Self.btnZoomFit.Caption:= LangFile.ReadString(Part, 'sbtnZoomFit', Self.btnZoomFit.Caption);
Self.btnZoomFit.Hint:= LangFile.ReadString(Part, 'hbtnZoomFit', Self.btnZoomFit.Hint);
Self.btnZoomPlus.Caption:= LangFile.ReadString(Part, 'sbtnZoomPlus', Self.btnZoomPlus.Caption);
Self.btnZoomPlus.Hint:= LangFile.ReadString(Part, 'hbtnZoomPlus', Self.btnZoomPlus.Hint);
Self.btnZoomMinus.Caption:= LangFile.ReadString(Part, 'sbtnZoomMinus', Self.btnZoomMinus.Caption);
Self.btnZoomMinus.Hint:= LangFile.ReadString(Part, 'hbtnZoomMinus', Self.btnZoomMinus.Hint);
end;
end;
procedure TfrmPrintPreview.DrawGrid(c: TCanvas; pinf: TPrnInfo; AUnits: Integer = 0);
var
ix, iy, nx, ny, ih, iw: Integer;
x, y, mx, my, x0, y0: Integer;
step1, step2, step3: Integer;
s: string;
ppmx, ppmy: Real;
Margins: TRect;
function ToPageX(n: integer): Integer;
begin
result:=n;
if AUnits = 1 then result:=Round(n*ppmx);
end;
function ToPageY(n: integer): Integer;
begin
result:=n;
if AUnits = 1 then result:=Round(n*ppmy);
end;
begin
step1:=StrToIntDef(frmMain.edStep1.Text, 100);
step2:=StrToIntDef(frmMain.edStep2.Text, 500);
step3:=StrToIntDef(frmMain.edStep3.Text, 500);
if frmMain.rbGridInMm.Checked then AUnits:=1;
mx:=pinf.PageSizePP.X; // maximum X in units
my:=pinf.PageSizePP.Y; // maximum Y in units
if AUnits = 1 then
begin
//ppmx:=StrToFloatDef(edPpmX.Text, 0);
//ppmy:=StrToFloatDef(edPpmY.Text, 0);
ppmx:=pinf.PageSizePP.X/pinf.PaperSizeMM.X;
ppmy:=pinf.PageSizePP.Y/pinf.PaperSizeMM.Y;
if ppmx = 0 then Exit;
if ppmy = 0 then Exit;
mx:=Round(pinf.PageSizePP.X/ppmx);
my:=Round(pinf.PageSizePP.Y/ppmy);
end;
//mx:=ToPageX(pinf.PageResX); // maximum X in points
//my:=ToPageY(pinf.PageResY); // maximum Y in points
Margins.Left:=ToPageX(pinf.Margins.Left);
Margins.Right:=ToPageX(pinf.Margins.Right);
Margins.Top:=ToPageY(pinf.Margins.Top);
Margins.Bottom:=ToPageY(pinf.Margins.Bottom);
// Линейки по вертикали
ix:=0; iy:=0; nx:=0; ny:=0;
while ix < mx do
begin
if (nx >= step2) or (ix=0) then
begin
nx:=0;
//s:=IntToStr(ix)+':'+IntToStr(iy);
// s:=IntToStr(ix);
// iw:=c.TextWidth(s);
// ih:=c.TextHeight(s);
// c.TextOut(ix-(iw div 2), 0, s);
// c.TextOut(ix-(iw div 2), my-ih, s);
c.Pen.Style:=psSolid;
c.Pen.Width:=3;
end
else
begin
//c.Pen.Style:=psDash;
//c.Pen.Style:=psDot;
c.Pen.Style:=psSolid;
c.Pen.Width:=1;
end;
c.MoveTo(ToPageX(ix), 0);
c.LineTo(ToPageX(ix), ToPageY(my));
Inc(ix, step1);
Inc(nx, step1);
end;
// Линейки по горизонтали
ix:=0; iy:=0; nx:=0; ny:=0;
while iy < my do
begin
Inc(iy, step1);
Inc(ny, step1);
if (ny >= step2) or (iy=0) then
begin
ny:=0;
//s:=IntToStr(ix)+':'+IntToStr(iy);
// s:=IntToStr(iy);
// ih:=c.TextHeight(s);
// c.TextOut(0, iy-(ih div 2), s);
// c.TextOut(mx-iw, iy-(ih div 2), s);
c.Pen.Style:=psSolid;
c.Pen.Width:=2;
end
else
begin
//c.Pen.Style:=psDash;
c.Pen.Style:=psSolid;
c.Pen.Width:=1;
end;
c.MoveTo(0, ToPageY(iy));
c.LineTo(ToPageX(mx), ToPageY(iy));
end;
// Цифры вертикалей
ix:=0; iy:=0; nx:=0; ny:=0;
y0:=Margins.Top;
while ix < mx do
begin
Inc(ix, step1);
Inc(nx, step1);
if (nx >= step3) then
begin
nx:=0;
//s:=IntToStr(ix)+':'+IntToStr(iy);
s:=IntToStr(ix);
iw:=c.TextWidth(s);
ih:=c.TextHeight(s);
x:=ToPageX(ix)-(iw div 2);
y:=ToPageY(my)-ih-Margins.Bottom;
c.FillRect(Rect(x, y0, x+iw, y0+ih));
c.FillRect(Rect(x, y, x+iw, y+ih));
c.TextOut(x, y0, s);
c.TextOut(x, y, s);
end;
end;
// Цифры горизонталей
ix:=0; iy:=0; nx:=0; ny:=0;
x0:=Margins.Left;
while iy < my do
begin
Inc(iy, step1);
Inc(ny, step1);
if (ny >= step3) then
begin
ny:=0;
//s:=IntToStr(ix)+':'+IntToStr(iy);
s:=IntToStr(iy);
iw:=c.TextWidth(s);
ih:=c.TextHeight(s);
x:=ToPageX(mx)-iw-3-Margins.Right;
y:=ToPageY(iy)-(ih div 2);
c.FillRect(Rect(x0, y, x0+iw, y+ih));
c.FillRect(Rect(x, y, x+iw, y+ih));
c.TextOut(x0, y, s);
c.TextOut(x, y, s);
end;
end;
end;
procedure TfrmPrintPreview.DrawPreviewPage(c: TCanvas; pinf: TPrnInfo; NumPage: TNumPage);
var
tx, ty: Integer; // ticket size in mm
cx, cy: Integer; // canvas size in points
tpx, tpy: Integer; // ticket preview size in pixels
PageSize: TPoint; // Page size in mm
CanvasSize, PreviewSize: TPoint; // whole canvas and printable area sizes
PageMargin: TPoint; // printable area margin in points
PageOffset: TPoint; // printable area offset in points
kx, ky, k: Real;
rPage, r: TRect;
x,y, sx,sy, i, n, m: Integer;
Ticket: TTicket;
NumLabel: TNumLabel;
NumLabelData: TNumLabelData;
NumPageTpl: TNumPageTpl;
TicketTpl: TTicketTpl;
Canvas: TCanvas;
s: string;
TempNpiList: TObjectList;
TempNpi: TNumPlanItem;
LogFont: TLogFont;
ViewMode: Integer;
begin
ViewMode:=1;
if not Assigned(NumPage) then Exit;
NumPageTpl:=NumPage.NumPageTpl;
if not Assigned(NumPageTpl) then Exit;
// Get NumPlanItems for current NumPage
TempNpiList:=TObjectList.Create(False);
for i:=0 to NumProject.NumPlanItems.Count-1 do
begin
//NumProject.NumPlanItems[i].Read(true);
if NumProject.NumPlanItems[i].NumPage = NumPage then
begin
TempNpiList.Add(NumProject.NumPlanItems[i]);
end;
end;
Canvas:=c;
// Clear canvas
//Canvas.Brush.Color:=clWhite;
//Canvas.FillRect(Canvas.ClipRect);
// Compute page preview size in pixels
// Page size in mm
PageSize.X:=NumPageTpl.Size.X;
PageSize.Y:=NumPageTpl.Size.Y;
if (PageSize.X=0) or (PageSize.Y=0) then Exit;
// Page size in points
CanvasSize.X:=pinf.PaperSizePP.X;
CanvasSize.Y:=pinf.PaperSizePP.Y;
PreviewSize.X:=pinf.PageRect.Right-pinf.PageRect.Left;
PreviewSize.Y:=pinf.PageRect.Bottom-pinf.PageRect.Top;
//PageMargin:=pinf.PageRect.TopLeft;
rPage:=pinf.PageRect;
// Size coefficient
kx:=PreviewSize.X / PageSize.X;
ky:=PreviewSize.Y / PageSize.Y;
// Set offset
PageOffset.X:=Round((PaperInfo.AdjustPointMm.X-PaperInfo.BaseAdjustPointMm.X)*kx);
PageOffset.Y:=Round((PaperInfo.AdjustPointMm.Y-PaperInfo.BaseAdjustPointMm.Y)*kx);
OffsetRect(rPage, PageOffset.X, PageOffset.Y);
//kx:=StrToFloatDef(edPpmX.Text, 0);
//ky:=StrToFloatDef(edPpmY.Text, 0);
if PreviewMode then
begin
// Draw page frame
Canvas.Pen.Color:=clBlack;
Canvas.Pen.Width:=1;
Canvas.Brush.Style:=bsSolid;
//Canvas.Brush.Color:=clInfoBk; //clYellow;
//Canvas.FillRect(rPage);
Canvas.Rectangle(rPage);
end;
// Draw tickets
for i:=0 to NumPageTpl.Tickets.Count-1 do
begin
Ticket:=NumPageTpl.Tickets[i];
TicketTpl:=Ticket.Tpl;
if not Assigned(TicketTpl) then Continue;
TempNpi:=nil;
for m:=0 to TempNpiList.Count-1 do
begin
if TNumPlanItem(TempNpiList[m]).Ticket.ID=Ticket.ID then
begin
TempNpi:=TNumPlanItem(TempNpiList[m]);
Break;
end;
end;
if not Assigned(TempNpi) then Continue;
r.Left:=rPage.Left+Round(Ticket.Position.X*kx);
r.Top:=rPage.Top+Round(Ticket.Position.Y*ky);
r.Right:=r.Left+Round(TicketTpl.Size.X*kx);
r.Bottom:=r.Top+Round(TicketTpl.Size.Y*ky);
if PreviewMode then
begin
Canvas.Pen.Color:=clBlack;
Canvas.Pen.Width:=1;
Canvas.Brush.Color:=clInfoBk; //clYellow;
Canvas.Brush.Style:=bsSolid;
//Canvas.FillRect(r);
Canvas.Rectangle(r);
end;
// Draw numlabels
Canvas.Brush.Style:=bsClear;
for n:=0 to TicketTpl.NumLabels.Count-1 do
begin
NumLabel:=TicketTpl.NumLabels[n];
if not Assigned(NumLabel.Font) then Continue;
x:=r.Left+Round(NumLabel.Position.X*kx);
y:=r.Top+Round(NumLabel.Position.Y*ky);
Canvas.Pen.Color:=clBlack;
Canvas.Font.Assign(NumLabel.Font);
s:='';
if ViewMode = 0 then s:=NumLabel.Name
else
begin
NumLabelData:=nil;
for m:=0 to TempNpi.NumLabelDataList.Count-1 do
begin
NumLabelData:=TempNpi.NumLabelDataList[m];
if NumLabelData.NumLabelTpl.ID = NumLabel.NumLabelTpl.ID then Break;
end;
if Assigned(NumLabelData) then
begin
if ViewMode = 1 then
begin
s:=Trim(NumLabelData.NumLabelTpl.Prefix)+NumLabelData.Value+Trim(NumLabelData.NumLabelTpl.Suffix);
end;
if ViewMode = 2 then s:=NumLabelData.Action;
end;
end;
// Пересчет размера шрифта
Canvas.Font.Height:=-Round(NumLabel.Size * ky);
if NumLabel.Angle <> 0 then
begin
// Поворот надписи
GetObject(Canvas.Font.Handle, SizeOf(TLogFont), @LogFont);
LogFont.lfEscapement := NumLabel.Angle*10;
Canvas.Font.Handle := CreateFontIndirect(LogFont);
end;
Canvas.TextOut(x, y, s);
end;
end;
end;
procedure TfrmPrintPreview.DrawPreview(iStartPage, iEndPage: integer);
var
frm: TForm;
img: TImage;
i, im: integer;
PrnInf: TPrnInfo;
PageTpl: TNumPageTpl;
R: TRect;
begin
//Preview:=TPrintPreview.Create(self);
//Preview.Parent:=panPrintPreview;
Preview.Clear();
//Preview.Canvas.Assign(Printer.Canvas);
Preview.UsePrinterOptions:=True;
//Preview.GetPrinterOptions();
Preview.Units:=mmLoMetric;
//Preview.Units:=mmPixel;
//Preview.Units:=mmPoints;
PrnInf:=frmMain.GetPrinterInfo('');
//PrnInf.PageRect:=Preview.GetPageSetupParameters(dlgPageSetup);
im:=NumProject.Pages.Count;
if (iEndPage>0) and (iEndPage<im) then im:=iEndPage;
for i:=0 to im-1 do
begin
PageTpl:=NumProject.Pages[i].NumPageTpl;
frmMain.dlgPageSetup.PageWidth:=PageTpl.Size.X*100;
frmMain.dlgPageSetup.PageHeight:=PageTpl.Size.Y*100;
if PageTpl.Size.X < PageTpl.Size.Y then
Printer.Orientation:=poPortrait
else
Printer.Orientation:=poLandscape;
PrnInf.PageRect:=Preview.GetPageSetupParameters(frmMain.dlgPageSetup);
if i=0 then Preview.BeginDoc() else Preview.NewPage();
//Preview.PaperWidth:=PageTpl.Size.X;
//Preview.PaperWidth:=PageTpl.Size.Y;
DrawPreviewPage(Preview.Canvas, PrnInf, NumProject.Pages[i]);
Core.Cmd('STATUS '+sPrintPreview+' '+IntToStr(i)+'/'+IntToStr(im));
Application.ProcessMessages();
end;
Preview.EndDoc();
Core.Cmd('STATUS ОК');
Exit;
Printer.BeginDoc();
//DrawGrid(Printer.Canvas, GetPrinterInfo(''));
frm:=TForm.Create(self);
img:=TImage.Create(frm);
img.Parent:=frm;
img.Align:=alClient;
//img.Canvas.Assign(Printer.Canvas);
//img.Canvas.StretchDraw(img.Canvas.ClipRect, Printer.Canvas);
img.Canvas.CopyRect(img.Canvas.ClipRect, Printer.Canvas, Printer.Canvas.ClipRect);
frm.FreeOnRelease();
frm.Show();
Printer.Abort();
end;
procedure TfrmPrintPreview.DrawGridPreview();
var
PrnInf: TPrnInfo;
begin
// Disable unused buttons
actPageAdjust.Enabled:=False;
actPageFirst.Enabled:=False;
actPagePrev.Enabled:=False;
actPageNext.Enabled:=False;
actPageLast.Enabled:=False;
actShowTickets.Enabled:=False;
cbbPageNum.Enabled:=False;
// Prepare preview
Preview.Clear();
Preview.UsePrinterOptions:=True;
Preview.Units:=mmLoMetric;
PrnInf:=frmMain.GetPrinterInfo('');
PrnInf.PageRect:=Preview.GetPageSetupParameters(frmMain.dlgPageSetup);
//PrnInf.PageRes.X:=PrnInf.PageRect.Right-PrnInf.PageRect.Left;
//PrnInf.PageRes.Y:=PrnInf.PageRect.Bottom-PrnInf.PageRect.Top;
PrnInf.PageSizePP.X:=Preview.PaperWidth;
PrnInf.PageSizePP.Y:=Preview.PaperHeight;
Preview.BeginDoc();
DrawGrid(Preview.Canvas, PrnInf);
Preview.EndDoc();
end;
procedure TfrmPrintPreview.actPrintOnePageExecute(Sender: TObject);
begin
if CopyProtection.CheckProtectionKey(ProtectionKey) then
begin
Preview.PrintPages(Preview.CurrentPage, Preview.CurrentPage);
end
else
begin
Preview.PrintPages(1, 1);
end;
end;
procedure TfrmPrintPreview.DummyAction(Sender: TObject);
begin
//
end;
procedure TfrmPrintPreview.SavePDF();
var
FileName: string;
begin
FileName:=CurProject.Name+'.pdf';
if not Core.GetSaveFileName(FileName, 'pdf') then Exit;
try
Preview.SaveAsPDF(FileName);
except
Exit;
end;
end;
procedure TfrmPrintPreview.alPrintPreviewExecute(Action: TBasicAction;
var Handled: Boolean);
begin
//
if Action = actZoomFit then
begin
//Preview.Zoom:=100;
Preview.ZoomState:=zsZoomToFit;
end
else if Action = actZoomPlus then
begin
Preview.Zoom:=Preview.Zoom+10;
end
else if Action = actZoomMinus then
begin
Preview.Zoom:=Preview.Zoom-10;
end
else if Action = actPageFirst then
begin
Preview.CurrentPage:=1;
cbbPageNum.ItemIndex:=Preview.CurrentPage-1;
end
else if Action = actPageLast then
begin
Preview.CurrentPage:=Preview.TotalPages;
cbbPageNum.ItemIndex:=Preview.CurrentPage-1;
end
else if Action = actPagePrev then
begin
Preview.CurrentPage:=Preview.CurrentPage-1;
cbbPageNum.ItemIndex:=Preview.CurrentPage-1;
end
else if Action = actPageNext then
begin
Preview.CurrentPage:=Preview.CurrentPage+1;
cbbPageNum.ItemIndex:=Preview.CurrentPage-1;
end
else if Action = actShowTickets then
begin
PreviewMode:=not actShowTickets.Checked;
if not CopyProtection.CheckProtectionKey(ProtectionKey) then PreviewMode:=True;
actShowTickets.Checked:=PreviewMode;
DrawPreview(1, 0);
end
else if Action = actPageAdjust then
begin
frmMain.actPageAdjust.Execute();
end
else if Action = actClose then
begin
Core.AddCmd('CLOSE '+IntToStr((Parent as TSomePage).PageID));
end
else if Action = actSavePDF then
begin
SavePDF();
end;
end;
procedure TfrmPrintPreview.cbbPageNumSelect(Sender: TObject);
begin
if Preview.CurrentPage <> (cbbPageNum.ItemIndex+1) then
begin
Preview.CurrentPage := cbbPageNum.ItemIndex+1;
end;
end;
end.
|
unit efatt.xmlwriter;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils
, uefattura
, DOM, XMLWrite
;
type
{ TEFattXmlWriter }
TEFattXmlWriter = class(TObject)
private
FeFattura: TEFattura;
FFormatSettings: TFormatSettings;
function GetXmlFileName: string;
public
constructor Create(AeFattura: TEFattura);
destructor Destroy; override;
function getDocument: TXMLDocument;
function SaveToXml(const AXmlRepository: string; const AFileNameXml: string=''): string;
property eFattura: TEFattura read FeFattura write FeFattura;
property XmlFileName: string read GetXmlFileName;
end;
implementation
{ TEFattXmlWriter }
function TEFattXmlWriter.GetXmlFileName: string;
begin
result:=Format('%2.2s%s_%5.5s.xml',
[ Trim(eFattura.FatturaElettronicaHeader.DatiTrasmissione.IdTrasmittente.IdPaese),
Trim(eFattura.FatturaElettronicaHeader.DatiTrasmissione.IdTrasmittente.IdCodice),
Trim(eFattura.FatturaElettronicaHeader.DatiTrasmissione.ProgressivoInvio)
]);
end;
constructor TEFattXmlWriter.Create(AeFattura: TEFattura);
begin
FeFattura:=AeFattura;
FFormatSettings.DecimalSeparator:='.';
FFormatSettings.ThousandSeparator:=',';
end;
destructor TEFattXmlWriter.Destroy;
begin
inherited Destroy;
end;
function TEFattXmlWriter.getDocument: TXMLDocument;
var Doc: TXMLDocument;
RootNode, parentNode, childNode, currNode: TDOMNode;
procedure _FatturaElettronicaHeader(ARootNode: TDOMNode);
var FatturaElettronicaHeader: TDOMNode;
wsapp: widestring;
begin
// FatturaElettronicaHeader
FatturaElettronicaHeader := Doc.CreateElement(DOMEL_FatturaElettronicaHeader);
ARootNode.Appendchild(FatturaElettronicaHeader);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FatturaElettronicaHeader / DatiTrasmissione
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
parentNode := Doc.CreateElement(DOMEL_DatiTrasmissione);
FatturaElettronicaHeader.AppendChild(parentNode);
// .. IdTrasmittente
childNode := Doc.CreateElement(DOMEL_IdTrasmittente);
parentNode.AppendChild(childNode);
with childNode do begin
AppendChild(Doc.CreateElement(DOMEL_IdPaese)).AppendChild(
Doc.CreateTextNode( eFattura.FatturaElettronicaHeader.DatiTrasmissione.IdTrasmittente.IdPaese )
);
AppendChild(Doc.CreateElement(DOMEL_IdCodice)).AppendChild(
Doc.CreateTextNode( eFattura.FatturaElettronicaHeader.DatiTrasmissione.IdTrasmittente.IdCodice )
);
end;
// .. ProgressivoInvio
parentNode.AppendChild(Doc.CreateElement(DOMEL_ProgressivoInvio)).AppendChild(
Doc.CreateTextNode( eFattura.FatturaElettronicaHeader.DatiTrasmissione.ProgressivoInvio )
);
// .. FormatoTrasmissione
parentNode.AppendChild(Doc.CreateElement(DOMEL_FormatoTrasmissione)).AppendChild(
Doc.CreateTextNode( eFattura.FatturaElettronicaHeader.DatiTrasmissione.FormatoTrasmissione )
);
// .. CodiceDestinatario
// non PA + vuole PEC ==> '0000000'
// non PA + vuole ID ==> ID
parentNode.AppendChild(Doc.CreateElement(DOMEL_CodiceDestinatario)).AppendChild(
Doc.CreateTextNode( eFattura.FatturaElettronicaHeader.DatiTrasmissione.CodiceDestinatario )
);
// .. [ContattiTrasmittente]
if eFattura.FatturaElettronicaHeader.DatiTrasmissione.ContattiTrasmittente.IsAssigned then begin
currNode:=parentNode.AppendChild(Doc.CreateElement(DOMEL_ContattiTrasmittente));
// Telefono
if eFattura.FatturaElettronicaHeader.DatiTrasmissione.ContattiTrasmittente.Telefono<>'' then begin
wsapp:=copy(eFattura.FatturaElettronicaHeader.DatiTrasmissione.ContattiTrasmittente.Telefono,1,12);
currNode.AppendChild(Doc.CreateElement(DOMEL_Telefono)).AppendChild(Doc.CreateTextNode(wsapp));
end;
// Email
if eFattura.FatturaElettronicaHeader.DatiTrasmissione.ContattiTrasmittente.email<>'' then begin
wsapp:=copy(eFattura.FatturaElettronicaHeader.DatiTrasmissione.ContattiTrasmittente.email,1,256);
currNode.AppendChild(Doc.CreateElement(DOMEL_Email)).AppendChild(Doc.CreateTextNode(wsapp));
end;
// Fax: sembra non ci sia....
end;
// .. [PECDestinatario]
// parentNode
// .AppendChild(Doc.CreateElement('PECDestinatario'))
// .AppendChild(Doc.CreateTextNode('ABC1234'));
wsapp := Trim(eFattura.FatturaElettronicaHeader.DatiTrasmissione.PecDestinatario);
if wsapp <> '' then
parentNode.AppendChild( Doc.CreateElement(DOMEL_PECDestinatario) )
.AppendChild( Doc.CreateTextNode( wsapp ) );
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FatturaElettronicaHeader / CedentePrestatore
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
parentNode := Doc.CreateElement(DOMEL_CedentePrestatore);
FatturaElettronicaHeader.AppendChild(parentNode);
// ..
// .. DatiAnagrafici
// ..
childNode := Doc.CreateElement(DOMEL_DatiAnagrafici);
parentNode.AppendChild(childNode);
with childNode do begin
with AppendChild(Doc.CreateElement(DOMEL_IdFiscaleIVA)) do begin
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.DatiAnagrafici.IdFiscaleIVA.IdPaese;
AppendChild(Doc.CreateElement(DOMEL_IdPaese)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.DatiAnagrafici.IdFiscaleIVA.IdCodice;
AppendChild(Doc.CreateElement(DOMEL_IdCodice)).AppendChild(Doc.CreateTextNode(wsapp));
end;
end;
// [CodiceFiscale]
with childNode do begin
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.DatiAnagrafici.CodiceFiscale;
if wsapp <> '' then
with AppendChild(Doc.CreateElement(DOMEL_CodiceFiscale)) do begin
AppendChild(Doc.CreateTextNode(wsapp));
end;
end;
with childNode do begin
with AppendChild(Doc.CreateElement(DOMEL_Anagrafica)) do begin
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.DatiAnagrafici.Anagrafica.Denominazione;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Denominazione)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.DatiAnagrafici.Anagrafica.Nome;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Nome)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.DatiAnagrafici.Anagrafica.Cognome;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Cognome)).AppendChild(Doc.CreateTextNode(wsapp));
end;
end;
// [AlboProfessionale]
// [ProvinciaAlbo]
// [NumeroIscrizioneAlbo]
// [DataIscrizioneAlbo]
with childNode do begin
with AppendChild(Doc.CreateElement(DOMEL_RegimeFiscale)) do begin
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.DatiAnagrafici.RegimeFiscale;
if wsapp<>'' then
AppendChild(Doc.CreateTextNode(wsapp));
end;
end;
// ..
// .. Sede
// ..
childNode := Doc.CreateElement(DOMEL_Sede);
parentNode.AppendChild(childNode);
with childNode do begin
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.Sede.Indirizzo;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Indirizzo)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.Sede.CAP;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_CAP)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.Sede.Comune;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Comune)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.Sede.Provincia;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Provincia)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.Sede.Nazione;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Nazione)).AppendChild(Doc.CreateTextNode(wsapp));
end;
// ..
// .. StabileOrganizzazione
// ..
// ..
// .. IscrizioneREA
// ..
{$IFDEF NOT_EXCLUDE}
wsapp:=Trim(eFattura.FatturaElettronicaHeader.CedentePrestatore.IscrizioneREA.NumeroREA);
if wsapp <> '' then begin
childNode := Doc.CreateElement(DOMEL_IscrizioneREA);
parentNode.AppendChild(childNode);
with childNode do begin
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.IscrizioneREA.Ufficio;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Ufficio)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.IscrizioneREA.NumeroREA;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_NumeroREA)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.IscrizioneREA.CapitaleSociale;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_CapitaleSociale)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.IscrizioneREA.SocioUnico;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_SocioUnico)).AppendChild(Doc.CreateTextNode(wsapp)); // “SU”, nel caso di socio unico, oppure “SM” nel caso di società pluripersonale
wsapp:=eFattura.FatturaElettronicaHeader.CedentePrestatore.IscrizioneREA.StatoLiquidazione;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_StatoLiquidazione)).AppendChild(Doc.CreateTextNode(wsapp)); // “LS” per società in stato di liquidazione, oppure “LN” per società non in liquidazione
end;
end; // IscrizioneREA
{$ENDIF}
// ..
// .. Contatti
if eFattura.FatturaElettronicaHeader.CedentePrestatore.Contatti.IsAssigned then begin
childNode := Doc.CreateElement(DOMEL_Contatti);
parentNode.AppendChild(childNode);
with childNode do begin
wsapp:=Trim(eFattura.FatturaElettronicaHeader.CedentePrestatore.Contatti.Telefono);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Telefono)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=Trim(eFattura.FatturaElettronicaHeader.CedentePrestatore.Contatti.Fax);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Fax)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=Trim(eFattura.FatturaElettronicaHeader.CedentePrestatore.Contatti.email);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Email)).AppendChild(Doc.CreateTextNode(wsapp));
end;
end;
// .. RiferimentoAmministrazione
// ..
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FatturaElettronicaHeader / RappresentanteFiscale
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FatturaElettronicaHeader / CessionarioCommittente
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
parentNode := Doc.CreateElement(DOMEL_CessionarioCommittente);
FatturaElettronicaHeader.AppendChild(parentNode);
// ..
// .. DatiAnagrafici
// ..
childNode := Doc.CreateElement(DOMEL_DatiAnagrafici);
parentNode.AppendChild(childNode);
if eFattura.FatturaElettronicaHeader.CessionarioCommittente.DatiAnagrafici.IdFiscaleIVA.IsAssigned then begin
with childNode do begin
with AppendChild(Doc.CreateElement(DOMEL_IdFiscaleIVA)) do begin
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.DatiAnagrafici.IdFiscaleIVA.IdPaese;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_IdPaese)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.DatiAnagrafici.IdFiscaleIVA.IdCodice;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_IdCodice)).AppendChild(Doc.CreateTextNode(wsapp));
end;
end;
end;
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.DatiAnagrafici.CodiceFiscale;
if wsapp <> '' then
with childNode do begin
AppendChild(Doc.CreateElement(DOMEL_CodiceFiscale)).AppendChild(Doc.CreateTextNode(wsapp));
end;
with childNode do begin
with AppendChild(Doc.CreateElement(DOMEL_Anagrafica)) do begin
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.DatiAnagrafici.Anagrafica.Denominazione;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Denominazione)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.DatiAnagrafici.Anagrafica.Nome;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Nome)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.DatiAnagrafici.Anagrafica.Cognome;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Cognome)).AppendChild(Doc.CreateTextNode(wsapp));
end;
end;
// ..
// .. Sede
// ..
childNode := Doc.CreateElement(DOMEL_Sede);
parentNode.AppendChild(childNode);
with childNode do begin
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.Sede.Indirizzo;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Indirizzo)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.Sede.CAP;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_CAP)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.Sede.Comune;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Comune)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.Sede.Provincia;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Provincia)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=eFattura.FatturaElettronicaHeader.CessionarioCommittente.Sede.Nazione;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Nazione)).AppendChild(Doc.CreateTextNode(wsapp));
end;
end; // _FatturaElettronicaHeader
procedure _FatturaElettronicaBody(ARootNode: TDOMNode);
var FatturaElettronicaBody: TDOMNode;
s: string;
wsapp: WideString;
weapp: extended;
iapp: integer;
body: TEFatturaBody;
doa:TEFatturaBody_DatiGenerali_DatiOrdineAcquisto;
ddt:TEFatturaBody_DatiGenerali_DatiDDT;
linea: TEFatturaBody_DatiBeniServizi_DettaglioLinee;
riep: TEFatturaBody_DatiBeniServizi_DatiRiepilogo;
adg: TEFatturaBody_DatiBeniServizi_DettaglioLinee_AltriDatiGestionali;
pag: TEFatturaBody_DatiPagamento;
scomag: TEFatturaBody_Generico_ScontoMaggiorazione;
begin
for body in eFattura.FatturaElettronicaBody_Lista do begin
// FatturaElettronicaBody
FatturaElettronicaBody := Doc.CreateElement(DOMEL_FatturaElettronicaBody);
ARootNode.Appendchild(FatturaElettronicaBody);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// _FatturaElettronicaBody / DatiGenerali
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
parentNode := Doc.CreateElement(DOMEL_DatiGenerali);
FatturaElettronicaBody.AppendChild(parentNode);
// .. DatiGeneraliDocumento
childNode := Doc.CreateElement(DOMEL_DatiGeneraliDocumento);
parentNode.AppendChild(childNode);
with childNode do begin
wsapp:=body.DatiGenerali.DatiGeneraliDocumento.TipoDocumento;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_TipoDocumento)).AppendChild(Doc.CreateTextNode(wsapp)); // TD01..TD06
wsapp:=body.DatiGenerali.DatiGeneraliDocumento.Divisa;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_Divisa)).AppendChild(Doc.CreateTextNode(wsapp)); // es.: EUR, USD, GBP, CZK
wsapp:=WideString(FormatDateTime('yyyy-mm-dd', body.DatiGenerali.DatiGeneraliDocumento.Data));
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_Data)).AppendChild(Doc.CreateTextNode(wsapp)); // YYYY-MM-DD
wsapp:=body.DatiGenerali.DatiGeneraliDocumento.Numero;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_Numero)).AppendChild(Doc.CreateTextNode(wsapp)); // lunghezza massima di 20 caratteri
end;
// with childNode do begin
// AppendChild(Doc.CreateElement('DatiRitenuta')) do begin
// AppendChild(Doc.CreateElement('TipoRitenuta')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('ImportoRitenuta')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('AliquotaRitenuta')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('CausalePagamento')).AppendChild(Doc.CreateTextNode(''));
// end;
// end;
// with childNode do begin
// AppendChild(Doc.CreateElement('DatiBollo')) do begin
// AppendChild(Doc.CreateElement('BolloVirtuale')).AppendChild(Doc.CreateTextNode('SI')); // 'SI'|''
// AppendChild(Doc.CreateElement('ImportoBollo')).AppendChild(Doc.CreateTextNode('25.00'));
// end;
// end;
// with childNode do begin
// AppendChild(Doc.CreateElement('DatiCassaPrevidenziale')) do begin
// AppendChild(Doc.CreateElement('TipoCassa')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('AlCassa')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('ImportoContributoCassa')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('ImponibileCassa')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('AliquotaIVA')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('Ritenuta')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('Natura')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('RiferimentoAmministrazione')).AppendChild(Doc.CreateTextNode(''));
// end;
// end;
// with childNode do begin
// AppendChild(Doc.CreateElement('ScontoMaggiorazione')) do begin
// AppendChild(Doc.CreateElement('Tipo')).AppendChild(Doc.CreateTextNode('')); // SC sconto, MG maggiorazione
// // Percentuale XOR Importo
// AppendChild(Doc.CreateElement('Percentuale')).AppendChild(Doc.CreateTextNode('')); // es.: 5.00
// AppendChild(Doc.CreateElement('Importo')).AppendChild(Doc.CreateTextNode('')); // es.: 55.00
// end;
// end;
with childNode do begin
if body.DatiGenerali.DatiGeneraliDocumento.ImportoTotaleDocumentoIsAssegned then begin;
weapp:=body.DatiGenerali.DatiGeneraliDocumento.ImportoTotaleDocumento;
wsapp:=WideString(FormatFloat('0.00', weapp, self.FFormatSettings));
AppendChild(Doc.CreateElement(DOMEL_ImportoTotaleDocumento)).AppendChild(Doc.CreateTextNode(wsapp));
end;
weapp:=body.DatiGenerali.DatiGeneraliDocumento.Arrotondamento;
if weapp<>0.0 then begin
wsapp:=WideString(FormatFloat('#,##0.00', weapp));
AppendChild(Doc.CreateElement(DOMEL_Arrotondamento)).AppendChild(Doc.CreateTextNode(wsapp));
end;
if body.DatiGenerali.DatiGeneraliDocumento.Causale.Count > 0 then
for s in body.DatiGenerali.DatiGeneraliDocumento.Causale do begin
wsapp:=WideString(s);
AppendChild(Doc.CreateElement(DOMEL_Causale)).AppendChild(Doc.CreateTextNode(wsapp));
end;
wsapp:=body.DatiGenerali.DatiGeneraliDocumento.Art73;
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_Art73)).AppendChild(Doc.CreateTextNode(wsapp)); // 'SI'|''
end;
// .. DatiOrdineAcquisto (opzionale, ripetuto)
if body.DatiGenerali.DatiOrdineAcquisto_Lista.Count > 0 then begin;
childNode := Doc.CreateElement(DOMEL_DatiOrdineAcquisto);
parentNode.AppendChild(childNode);
for doa in body.DatiGenerali.DatiOrdineAcquisto_Lista do begin
with childNode do begin
if doa.RiferimentoNumeroLinea.Count>0 then
for s in doa.RiferimentoNumeroLinea do begin
wsapp:=WideString(s);
AppendChild(Doc.CreateElement(DOMEL_RiferimentoNumeroLinea)).AppendChild(Doc.CreateTextNode(wsapp)); // [opz]
end;
wsapp:=doa.IdDocumento;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_IdDocumento)).AppendChild(Doc.CreateTextNode(wsapp));
if doa.Data <> 0 then begin
wsapp:=widestring(FormatDateTime('yyyy-mm-dd', doa.Data));
AppendChild(Doc.CreateElement(DOMEL_Data)).AppendChild(Doc.CreateTextNode(wsapp)); // [opz]
end;
wsapp:=doa.NumItem;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_NumItem)).AppendChild(Doc.CreateTextNode(wsapp)); // [opz]
wsapp:=doa.CodiceCommessaConvenzione;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_CodiceCommessaConvenzione)).AppendChild(Doc.CreateTextNode(wsapp)); // [opz]
wsapp:=doa.CodiceCUP;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_CodiceCUP)).AppendChild(Doc.CreateTextNode(wsapp)); // [opz]
wsapp:=doa.CodiceCIG;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_CodiceCIG)).AppendChild(Doc.CreateTextNode(wsapp)); // [opz]
end; // with childNode
end; // for ..
end; // .. DatiOrdineAcquisto
// .. DatiContratto (opzionale, ripetuto)
// .. DatiConvenzione (opzionale, ripetuto)
// .. DatiRicezione (opzionale, ripetuto)
// .. DatiFattureCollegate (opzionale, ripetuto)
// .. DatiSAL (opzionale)
// .. DatiDDT (opzionale, ripetuto)
if body.DatiGenerali.DatiDDT_Lista.Count > 0 then begin
for ddt in body.DatiGenerali.DatiDDT_Lista do begin
childNode := Doc.CreateElement(DOMEL_DatiDDT);
parentNode.AppendChild(childNode);
with childNode do begin
if ddt.NumeroDDT <> '' then
AppendChild(Doc.CreateElement(DOMEL_NumeroDDT)).AppendChild(Doc.CreateTextNode(ddt.NumeroDDT));
if ddt.DataDDT <> 0 then begin
wsapp:=WideString(FormatDateTime('yyyy-mm-dd', ddt.DataDDT));
AppendChild(Doc.CreateElement(DOMEL_DataDDT)).AppendChild(Doc.CreateTextNode(wsapp));
end;
if ddt.RiferimentoNumeroLinea.Count>0 then begin
for s in ddt.RiferimentoNumeroLinea do begin
wsapp:=WideString(s);
AppendChild(Doc.CreateElement(DOMEL_RiferimentoNumeroLinea)).AppendChild(Doc.CreateTextNode(wsapp));
end;
end;
end; // with childNode
end; // for
end; // if DatiDDT
// .. DatiTrasporto (opzionale)
if body.DatiGenerali.DatiTrasporto.IsAssigned then begin
childNode := Doc.CreateElement(DOMEL_DatiTrasporto);
parentNode.AppendChild(childNode);
// ... DatiAnagraficiVettore
if body.DatiGenerali.DatiTrasporto.DatiAnagraficiVettore.IsAssigned then begin
currNode:=childNode.AppendChild(Doc.CreateElement(DOMEL_DatiAnagraficiVettore));
// .... IdFiscaleIVA
if body.DatiGenerali.DatiTrasporto.DatiAnagraficiVettore.IdFiscaleIVA.IsAssigned then begin
with currNode.AppendChild(Doc.CreateElement(DOMEL_IdFiscaleIVA)) do begin
wsapp:=body.DatiGenerali.DatiTrasporto.DatiAnagraficiVettore.IdFiscaleIVA.IdPaese;
AppendChild(Doc.CreateElement(DOMEL_IdPaese)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=body.DatiGenerali.DatiTrasporto.DatiAnagraficiVettore.IdFiscaleIVA.IdCodice;
AppendChild(Doc.CreateElement(DOMEL_IdCodice)).AppendChild(Doc.CreateTextNode(wsapp));
end; // with
end; // if IdFiscaleIVA
// .... CodiceFiscale
wsapp:=body.DatiGenerali.DatiTrasporto.DatiAnagraficiVettore.CodiceFiscale;
if wsapp<>'' then begin
currNode.AppendChild(Doc.CreateElement(DOMEL_CodiceFiscale)).AppendChild(Doc.CreateTextNode(wsapp))
end;
// .... Anagrafica
if body.DatiGenerali.DatiTrasporto.DatiAnagraficiVettore.Anagrafica.IsAssigned then begin
with currNode.AppendChild(Doc.CreateElement(DOMEL_Anagrafica)) do begin
wsapp:=body.DatiGenerali.DatiTrasporto.DatiAnagraficiVettore.Anagrafica.Denominazione;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_Denominazione)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=body.DatiGenerali.DatiTrasporto.DatiAnagraficiVettore.Anagrafica.Cognome;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_Cognome)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=body.DatiGenerali.DatiTrasporto.DatiAnagraficiVettore.Anagrafica.Nome;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_Nome)).AppendChild(Doc.CreateTextNode(wsapp));
end; // with
end; // if IdFiscaleIVA
end; // if DatiAnagraficiVettore
with childNode do begin
// ... MezzoTrasporto
wsapp:=body.DatiGenerali.DatiTrasporto.MezzoTrasporto;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_MezzoTrasporto)).AppendChild(Doc.CreateTextNode(wsapp));
// ... CausaleTrasporto
wsapp:=body.DatiGenerali.DatiTrasporto.CausaleTrasporto;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_CausaleTrasporto)).AppendChild(Doc.CreateTextNode(wsapp));
// ... NumeroColli
if body.DatiGenerali.DatiTrasporto.NumeroColli>0 then begin
wsapp:=Widestring(IntToStr(body.DatiGenerali.DatiTrasporto.NumeroColli));
AppendChild(Doc.CreateElement(DOMEL_NumeroColli)).AppendChild(Doc.CreateTextNode(wsapp));
end;
// ... Descrizione
wsapp:=body.DatiGenerali.DatiTrasporto.Descrizione;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_Descrizione)).AppendChild(Doc.CreateTextNode(wsapp));
// ... UnitaMisuraPeso
wsapp:=body.DatiGenerali.DatiTrasporto.UnitaMisuraPeso;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_UnitaMisuraPeso)).AppendChild(Doc.CreateTextNode(wsapp));
// ... PesoLordo
if body.DatiGenerali.DatiTrasporto.PesoLordo>0 then begin
wsapp:=Widestring(FormatFloat('0.00', body.DatiGenerali.DatiTrasporto.PesoLordo));
AppendChild(Doc.CreateElement(DOMEL_PesoLordo).AppendChild(Doc.CreateTextNode(wsapp)));
end;
// ... PesoNetto
if body.DatiGenerali.DatiTrasporto.PesoNetto>0 then begin
wsapp:=Widestring(FormatFloat('0.00', body.DatiGenerali.DatiTrasporto.PesoNetto));
AppendChild(Doc.CreateElement(DOMEL_PesoNetto)).AppendChild(Doc.CreateTextNode(wsapp));
end;
// ... DataOraRitiro
if body.DatiGenerali.DatiTrasporto.DataOraRitiro<>0 then begin
s:=FormatDateTime('yyyy-mm-ddThh:nn:ss.ccc', body.DatiGenerali.DatiTrasporto.DataOraRitiro);
wsapp:=Widestring(s)+'+02:00';
AppendChild(Doc.CreateElement(DOMEL_DataOraRitiro)).AppendChild(Doc.CreateTextNode(wsapp));
end;
// ... DataInizioTrasporto
if body.DatiGenerali.DatiTrasporto.DataInizioTrasporto<>0 then begin
s:=FormatDateTime('yyyy-mm-dd', body.DatiGenerali.DatiTrasporto.DataInizioTrasporto);
wsapp:=Widestring(s);
AppendChild(Doc.CreateElement(DOMEL_DataInizioTrasporto)).AppendChild(Doc.CreateTextNode(wsapp));
end;
// ... TipoResa
wsapp:=body.DatiGenerali.DatiTrasporto.TipoResa;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_TipoResa)).AppendChild(Doc.CreateTextNode(wsapp));
end; // with childNode
// ... IndirizzoResa
if body.DatiGenerali.DatiTrasporto.IndirizzoResa.IsAssigned then begin
currNode:=childNode.AppendChild(Doc.CreateElement(DOMEL_IndirizzoResa));
// .... Indirizzo
wsapp:=body.DatiGenerali.DatiTrasporto.IndirizzoResa.Indirizzo;
if wsapp<>'' then
currNode.AppendChild(Doc.CreateElement(DOMEL_Indirizzo)).AppendChild(Doc.CreateTextNode(wsapp));
// .... NumeroCivico
wsapp:=body.DatiGenerali.DatiTrasporto.IndirizzoResa.NumeroCivico;
if wsapp<>'' then
currNode.AppendChild(Doc.CreateElement(DOMEL_NumeroCivico)).AppendChild(Doc.CreateTextNode(wsapp));
// .... CAP
wsapp:=body.DatiGenerali.DatiTrasporto.IndirizzoResa.CAP;
if wsapp<>'' then
currNode.AppendChild(Doc.CreateElement(DOMEL_CAP)).AppendChild(Doc.CreateTextNode(wsapp));
// .... Comune
wsapp:=body.DatiGenerali.DatiTrasporto.IndirizzoResa.Comune;
if wsapp<>'' then
currNode.AppendChild(Doc.CreateElement(DOMEL_Comune)).AppendChild(Doc.CreateTextNode(wsapp));
// .... Provincia
wsapp:=body.DatiGenerali.DatiTrasporto.IndirizzoResa.Provincia;
if wsapp<>'' then
currNode.AppendChild(Doc.CreateElement(DOMEL_Provincia)).AppendChild(Doc.CreateTextNode(wsapp));
// .... Nazione
wsapp:=body.DatiGenerali.DatiTrasporto.IndirizzoResa.Nazione;
if wsapp<>'' then
currNode.AppendChild(Doc.CreateElement(DOMEL_Nazione)).AppendChild(Doc.CreateTextNode(wsapp));
end;
with childNode do begin
// ... DataOraConsegna
if body.DatiGenerali.DatiTrasporto.DataOraConsegna<>0 then begin
wsapp:=eFattura_FormatDateTime(body.DatiGenerali.DatiTrasporto.DataOraConsegna);
AppendChild(Doc.CreateElement(DOMEL_DataOraConsegna)).AppendChild(Doc.CreateTextNode(wsapp));
end;
end; // with childNode
end; // .. DatiTrasporto
// .. FatturaPrincipale (opzionale)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// _FatturaElettronicaBody / DatiBeniServizi
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
parentNode := Doc.CreateElement(DOMEL_DatiBeniServizi);
FatturaElettronicaBody.AppendChild(parentNode);
// .. DettaglioLinee
for linea in body.DatiBeniServizi.DettaglioLinee do begin;
childNode := Doc.CreateElement(DOMEL_DettaglioLinee);
parentNode.AppendChild(childNode);
with childNode do begin
// ... NumeroLinea
wsapp:=WideString(IntToStr(linea.NumeroLinea));
AppendChild(Doc.CreateElement(DOMEL_NumeroLinea)).AppendChild(Doc.CreateTextNode(wsapp));
// ... TipoCessionePrestazione
wsapp:=Trim(linea.TipoCessionePrestazione);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_TipoCessionePrestazione)).AppendChild(Doc.CreateTextNode(wsapp));
// ... Codice Articolo (ripetuto, opzionale)
if linea.CodiceArticolo.Count > 0 then
for iapp := 0 to linea.CodiceArticolo.Count - 1 do begin
with AppendChild(Doc.CreateElement(DOMEL_CodiceArticolo)) do begin
wsapp:=linea.CodiceArticolo.Items[iapp].CodiceTipo;
AppendChild(Doc.CreateElement(DOMEL_CodiceTipo)).AppendChild(Doc.CreateTextNode(wsapp)); // es. 'EAN', 'SSC', 'TARIC', 'CPV', oppure 'Codice Art. fornitore', 'Codice Art. cliente' ...
wsapp:=linea.CodiceArticolo.Items[iapp].CodiceValore;
AppendChild(Doc.CreateElement(DOMEL_CodiceValore)).AppendChild(Doc.CreateTextNode(wsapp));
end;
end;
wsapp:=linea.Descrizione;
AppendChild(Doc.CreateElement(DOMEL_Descrizione)).AppendChild(Doc.CreateTextNode(wsapp));
// ... Quantita
if linea.Quantita<>0 then begin
wsapp:=eFattura_FormatQuantita(linea.Quantita);
AppendChild(Doc.CreateElement(DOMEL_Quantita)).AppendChild(Doc.CreateTextNode(wsapp)); // []
wsapp:=Trim(linea.UnitaMisura);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_UnitaMisura)).AppendChild(Doc.CreateTextNode(wsapp)); // []
end;
// AppendChild(Doc.CreateElement('DataInizioPeriodo')).AppendChild(Doc.CreateTextNode('')); // [YYYY-MM-DD]
// AppendChild(Doc.CreateElement('DataFinePeriodo')).AppendChild(Doc.CreateTextNode('')); // [YYYY-MM-DD]
// ... PrezzoUnitario
if (linea.PrezzoUnitario<>0) or linea.LineaDescrittiva then begin
if linea.LineaDescrittiva then
wsapp:=eFattura_FormatPrezzoUnitario(0)
else
wsapp:=eFattura_FormatPrezzoUnitario(linea.PrezzoUnitario);
AppendChild(Doc.CreateElement(DOMEL_PrezzoUnitario)).AppendChild(Doc.CreateTextNode(wsapp)); // [-]N.DDdddddd
end;
// .. DettaglioLinee / ScontoMaggiorazione (opzionale, ripetuto)
if linea.ScontoMaggiorazione.Count > 0 then begin
for scomag in linea.ScontoMaggiorazione do
with AppendChild(Doc.CreateElement(DOMEL_ScontoMaggiorazione)) do begin
AppendChild(Doc.CreateElement(DOMEL_Tipo)).AppendChild(Doc.CreateTextNode(scomag.Tipo)); // [SC=Sconto,MG=Maggiorazione]
if scomag.Percentuale <> 0 then begin
wsapp:=eFattura_FormatScontoMagg(scomag.Percentuale);
AppendChild(Doc.CreateElement(DOMEL_Percentuale)).AppendChild(Doc.CreateTextNode(wsapp));
end;
// Percentuale + Importo -> vince importo
if scomag.Importo <> 0 then begin
wsapp:=eFattura_FormatPrezzoUnitario(scomag.Importo);
AppendChild(Doc.CreateElement(DOMEL_Importo)).AppendChild(Doc.CreateTextNode(wsapp));
end;
end;
end;
// with AppendChild(Doc.CreateElement('ScontoMaggiorazione')) do begin
// AppendChild(Doc.CreateElement('Tipo')).AppendChild(Doc.CreateTextNode('SC')); // [SC=Sconto,MG=Maggiorazione]
// AppendChild(Doc.CreateElement('Percentuale')).AppendChild(Doc.CreateTextNode('5.00'));
// // Percentuale XOR Importo
// AppendChild(Doc.CreateElement('Importo')).AppendChild(Doc.CreateTextNode('55.00'));
// end;
// ... PrezzoTotale
if (linea.PrezzoTotale<>0) or linea.LineaDescrittiva then begin
if linea.LineaDescrittiva then
wsapp:=eFattura_FormatPrezzoUnitario(0)
else
wsapp:=eFattura_FormatPrezzoUnitario(linea.PrezzoTotale);
AppendChild(Doc.CreateElement(DOMEL_PrezzoTotale)).AppendChild(Doc.CreateTextNode(wsapp)); // [-]N.DDdddddd
end;
// ... AliquotaIva
if linea.AliquotaIva<>0 then begin
wsapp:=eFattura_FormatAliquota(linea.AliquotaIva);
AppendChild(Doc.CreateElement(DOMEL_AliquotaIVA)).AppendChild(Doc.CreateTextNode(wsapp)); // 0.00, N.DD
end;
// ... Ritenuta
if linea.Ritenuta<>'' then begin
wsapp:=linea.Ritenuta;
AppendChild(Doc.CreateElement(DOMEL_Ritenuta)).AppendChild(Doc.CreateTextNode(wsapp)); // ['SI']
end;
// ... Natura
if linea.Natura<>'' then begin
wsapp:=linea.Natura;
AppendChild(Doc.CreateElement(DOMEL_Natura)).AppendChild(Doc.CreateTextNode(wsapp)); // ['SI']
end;
// N1=escluse ex art.15
// N2=non soggette
// N3=non imponibili
// N4=esenti
// N5=regime del margine / IVA non esposta in fattura
// N6=inversione contabile (per le operazioni in reverse charge
// ovvero nei casi di autofatturazione per acquisti extra UE
// di servizi ovvero per importazioni di beni nei soli casi
// previsti)
// N7=IVA assolta in altro stato UE (vendite a distanza ex art.
// 40 commi 3 e 4 e art. 41 comma 1 lett. b, DL 331/93;
// prestazione di servizi di telecomunicazioni, tele-
// radiodiffusione ed elettronici ex art. 7-sexies lett. f, g,
// DPR 633/72 e art. 74-sexies, DPR 633/72)
// AppendChild(Doc.CreateElement('RiferimentoAmministrazione')).AppendChild(Doc.CreateTextNode('')); // [commessa?]
// .. DettaglioLinee / AltriDatiGestionali (opzionale, ripetuto)
if linea.AltriDatiGestionali.Count > 0 then
with AppendChild(Doc.CreateElement(DOMEL_AltriDatiGestionali)) do
for adg in linea.AltriDatiGestionali do begin
// .. / TipoDato
wsapp:=Trim(adg.TipoDato);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_TipoDato)).AppendChild(Doc.CreateTextNode(wsapp));
// .. / RiferimentoTesto
wsapp:=Trim(adg.RiferimentoTesto);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_RiferimentoTesto)).AppendChild(Doc.CreateTextNode(wsapp)); // []
// .. // RiferimentoNumero
wsapp:=widestring(IntToStr(adg.RiferimentoNumero));
if wsapp <> '0' then
AppendChild(Doc.CreateElement(DOMEL_RiferimentoNumero)).AppendChild(Doc.CreateTextNode(wsapp)); // []
// .. / RiferimentoData
if adg.RiferimentoData > EncodeDate(2018, 1, 1) then begin
wsapp:=eFattura_FormatDate(adg.RiferimentoData);
AppendChild(Doc.CreateElement(DOMEL_RiferimentoData)).AppendChild(Doc.CreateTextNode(wsapp)); // []
end;
end; // for
end; // .. DettaglioLinee
end; // loop DettaglioLinee
// .. DatiRiepilogo
for riep in body.DatiBeniServizi.DatiRiepilogo do begin;
childNode := Doc.CreateElement(DOMEL_DatiRiepilogo);
parentNode.AppendChild(childNode);
with childNode do begin
// ... AliquotaIVA
wsapp:=eFattura_FormatAliquota(riep.AliquotaIVA);
AppendChild(Doc.CreateElement(DOMEL_AliquotaIVA)).AppendChild(Doc.CreateTextNode(wsapp));
// ... Natura
wsapp:=riep.Natura;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_Natura)).AppendChild(Doc.CreateTextNode(wsapp)); // [se dettaglio con "natura"]
// ... SpeseAccessorie
if riep.SpeseAccessorie <> 0 then begin
wsapp:=eFattura_FormatImporto(riep.SpeseAccessorie);
AppendChild(Doc.CreateElement(DOMEL_SpeseAccessorie)).AppendChild(Doc.CreateTextNode(wsapp)); // []
end;
// ... Arrotondamento
if riep.Arrotondamento <> 0 then begin
wsapp:=eFattura_FormatImporto(riep.Arrotondamento);
AppendChild(Doc.CreateElement(DOMEL_Arrotondamento)).AppendChild(Doc.CreateTextNode(wsapp)); // []
end;
// ... ImponibileImporto
wsapp:=eFattura_FormatImporto(riep.ImponibileImporto);
AppendChild(Doc.CreateElement(DOMEL_ImponibileImporto)).AppendChild(Doc.CreateTextNode(wsapp));
// ... Imposta
wsapp:=eFattura_FormatImporto(riep.Imposta);
AppendChild(Doc.CreateElement(DOMEL_Imposta)).AppendChild(Doc.CreateTextNode(wsapp));
// ... EsigibilitaIVA
wsapp:=Trim(riep.EsigibilitaIVA);
if (wsapp='I') or (wsapp='D') or (wsapp='S') then begin
AppendChild(Doc.CreateElement(DOMEL_EsigibilitaIVA)).AppendChild(Doc.CreateTextNode(wsapp)); // [vedi sotto]
// “I” per IVA ad esigibilità immediata
// “D” per IVA ad esigibilità differita
// “S” per scissione dei pagamenti. Se valorizzato con “S”, il campo Natura (2.2.2.2) non può valere “N6”.
end;
// ... RiferimentoNormativo
wsapp:=riep.RiferimentoNormativo;
if wsapp<>'' then begin
AppendChild(Doc.CreateElement(DOMEL_RiferimentoNormativo)).AppendChild(Doc.CreateTextNode(wsapp)); // []
end;
end;
end; // for
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// _FatturaElettronicaBody / DatiVeicoli (opzionale)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// parentNode := Doc.CreateElement('DatiVeicoli');
// FatturaElettronicaBody.AppendChild(parentNode);
// .. DatiVeicoli
// childNode := Doc.CreateElement('DatiVeicoli');
// parentNode.AppendChild(childNode);
// with childNode do begin
// AppendChild(Doc.CreateElement('Data')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('TotalePercorso')).AppendChild(Doc.CreateTextNode(''));
// end; // .. DettaglioLinee
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// _FatturaElettronicaBody / DatiPagamento (opzionale, ripetuto)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// .. DatiPagamento
for pag in body.Datipagamento do begin
parentNode := Doc.CreateElement(DOMEL_DatiPagamento);
FatturaElettronicaBody.AppendChild(parentNode);
with parentNode do begin
// ... CondizioniPagamento
wsapp:=pag.CondizioniPagamento;
AppendChild(Doc.CreateElement(DOMEL_CondizioniPagamento)).AppendChild(Doc.CreateTextNode(wsapp)); // TP01=pagamento a rate,TP02=pagamento completo,TP03=anticipo
// ... DettaglioPagamento (ripetuto)
for iapp:=0 to pag.DettaglioPagamento_Lista.Count-1 do begin
with AppendChild(Doc.CreateElement(DOMEL_DettaglioPagamento)) do begin
// .... Beneficiario
wsapp:=pag.DettaglioPagamento_Lista[iapp].Beneficiario;
if wsapp<>'' then
AppendChild(Doc.CreateElement(DOMEL_Beneficiario)).AppendChild(Doc.CreateTextNode(wsapp)); // []
// .... ModalitaPagamento
wsapp:=pag.DettaglioPagamento_Lista[iapp].ModalitaPagamento;
AppendChild(Doc.CreateElement(DOMEL_ModalitaPagamento)).AppendChild(Doc.CreateTextNode(wsapp)); // vedi sotto
// MP01=contanti MP02=assegno MP03=assegno circolare
// MP04=contanti presso Tesoreria MP05=bonifico MP06=vaglia cambiario
// MP07=bollettino bancario MP08=carta di pagamento MP09=RID
// MP10=RID utenze MP11=RID veloce MP12=Riba
// MP13=MAV MP14=quietanza erario stato MP15=giroconto su conti di contabilità speciale
// MP16=domiciliazione bancaria MP17=domiciliazione postale MP18=bollettino di c/c postale
// MP19=SEPA Direct Debit MP20=SEPA Direct Debit CORE MP21=SEPA Direct Debit B2B
// MP22=Trattenuta su somme già riscosse
// AppendChild(Doc.CreateElement('DataRiferimentoTerminiPagamento')).AppendChild(Doc.CreateTextNode('')); // []
// AppendChild(Doc.CreateElement('GiorniTerminiPagamento')).AppendChild(Doc.CreateTextNode('')); // []
// .... DataScadenzaPagamento
if pag.DettaglioPagamento_Lista[iapp].DataScadenzaPagamento <> 0 then begin
wsapp:=eFattura_FormatDate(pag.DettaglioPagamento_Lista[iapp].DataScadenzaPagamento);
AppendChild(Doc.CreateElement(DOMEL_DataScadenzaPagamento)).AppendChild(Doc.CreateTextNode(wsapp));
end;
// .... ImportoPagamento
wsapp:=eFattura_FormatImporto(pag.DettaglioPagamento_Lista[iapp].ImportoPagamento);
AppendChild(Doc.CreateElement(DOMEL_ImportoPagamento)).AppendChild(Doc.CreateTextNode(wsapp));
// AppendChild(Doc.CreateElement('CodUfficioPostale')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('CognomeQuietanzante')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('NomeQuietanzante')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('CFQuietanzante')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('TitoloQuietanzante')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('IstitutoFinanziario')).AppendChild(Doc.CreateTextNode(''));
wsapp:=Trim(pag.DettaglioPagamento_Lista[iapp].IBAN);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_IBAN)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=Trim(pag.DettaglioPagamento_Lista[iapp].ABI);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_ABI)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=Trim(pag.DettaglioPagamento_Lista[iapp].CAB);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_CAB)).AppendChild(Doc.CreateTextNode(wsapp));
wsapp:=Trim(pag.DettaglioPagamento_Lista[iapp].BIC);
if wsapp <> '' then
AppendChild(Doc.CreateElement(DOMEL_BIC)).AppendChild(Doc.CreateTextNode(wsapp));
weapp:=pag.DettaglioPagamento_Lista[iapp].ScontoPagamentoAnticipato;
// if weapp<>0 then
AppendChild(Doc.CreateElement(DOMEL_ScontoPagamentoAnticipato)).AppendChild(Doc.CreateTextNode( eFattura_FormatImporto(weapp) ));
weapp:=pag.DettaglioPagamento_Lista[iapp].PenalitaPagamentiRitardati;
// if weapp<>0 then
AppendChild(Doc.CreateElement(DOMEL_PenalitaPagamentiRitardati)).AppendChild(Doc.CreateTextNode( eFattura_FormatImporto(weapp) ));
// AppendChild(Doc.CreateElement('DataLimitePagamentoAnticipato')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('DataDecorrenzaPenale')).AppendChild(Doc.CreateTextNode(''));
// AppendChild(Doc.CreateElement('CodicePagamento')).AppendChild(Doc.CreateTextNode(''));
end; // with
end; // for dettaglio
end; // with parentNode
end; // .. DatiPagamento (for)
// .. Allegati
// childNode := Doc.CreateElement('Allegati');
// parentNode.AppendChild(childNode);
// with childNode do begin
// // AppendChild(Doc.CreateElement('NomeAttachment')).AppendChild(Doc.CreateTextNode(''));
// // AppendChild(Doc.CreateElement('AlgoritmoCompressione')).AppendChild(Doc.CreateTextNode('')); // []
// // AppendChild(Doc.CreateElement('FormatoAttachment')).AppendChild(Doc.CreateTextNode('')); // []
// // AppendChild(Doc.CreateElement('DescrizioneAttachment')).AppendChild(Doc.CreateTextNode('')); // []
// // AppendChild(Doc.CreateElement('Attachment')).AppendChild(Doc.CreateTextNode(''));
// end; // .. Allegati
end; // for body
end; // _FatturaElettronicaBody
begin
Doc := TXMLDocument.Create;
Doc.StylesheetType:='text/xsl';
Doc.StylesheetHRef:='fatturapr_v1.2.xsl';
// root node - p:FatturaElettronica
RootNode := Doc.CreateElement('p:FatturaElettronica');
TDOMElement(RootNode).SetAttribute('versione', self.eFattura.Versione); // 'FPR12'
TDOMElement(RootNode).SetAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
TDOMElement(RootNode).SetAttribute('xmlns:ds', 'http://www.w3.org/2000/09/xmldsig#');
TDOMElement(RootNode).SetAttribute('xmlns:p', 'http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2');
TDOMElement(RootNode).SetAttribute('xsi:schemaLocation', 'http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2 http://www.fatturapa.gov.it/export/fatturazione/sdi/fatturapa/v1.2/Schema_del_file_xml_FatturaPA_versione_1.2.xsd');
Doc.Appendchild(RootNode);
RootNode:= Doc.DocumentElement;
_FatturaElettronicaHeader(RootNode);
_FatturaElettronicaBody(RootNode);
// -----------------------------------
result:=Doc;
end;
function TEFattXmlWriter.SaveToXml(const AXmlRepository: string;
const AFileNameXml: string): string;
var doc: TXMLDocument;
sFile: string;
begin
doc := getDocument;
try
if AFileNameXml = '' then
sFile:=Format('%s\%s', [AXmlRepository, GetXmlFileName ])
else
sFile:=Format('%s\%s', [AXmlRepository, AFileNameXml ]);
XMLWrite.writeXMLFile(doc, sFile);
finally
result:=sFile;
FreeAndNil(doc);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC SAP SQL Anywhere driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$IF DEFINED(IOS) OR DEFINED(ANDROID)}
{$HPPEMIT LINKUNIT}
{$ELSE}
{$IFDEF WIN32}
{$HPPEMIT '#pragma link "FireDAC.Phys.ASA.obj"'}
{$ELSE}
{$HPPEMIT '#pragma link "FireDAC.Phys.ASA.o"'}
{$ENDIF}
{$ENDIF}
unit FireDAC.Phys.ASA;
interface
uses
System.Classes,
FireDAC.Stan.Intf,
FireDAC.Phys, FireDAC.Phys.ODBCWrapper, FireDAC.Phys.ODBCBase, FireDAC.Phys.ASAWrapper;
type
TFDPhysASADriverLink = class;
{$IFDEF MSWINDOWS}
TFDASAService = class;
TFDASABackup = class;
TFDASAValidate = class;
{$ENDIF}
[ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidLinux)]
TFDPhysASADriverLink = class(TFDPhysODBCBaseDriverLink)
private
FToolLib: String;
FToolHome: String;
protected
function GetBaseDriverID: String; override;
function IsConfigured: Boolean; override;
procedure ApplyTo(const AParams: IFDStanDefinition); override;
published
property ToolHome: String read FToolHome write FToolHome;
property ToolLib: String read FToolLib write FToolLib;
end;
{$IFDEF MSWINDOWS}
TFDASAProgressEvent = type TASAToolMessageEvent;
TFDASAService = class (TFDPhysODBCBaseService)
private
FOnProgress: TFDASAProgressEvent;
function GetDriverLink: TFDPhysASADriverLink;
procedure SetDriverLink(const AValue: TFDPhysASADriverLink);
function GetToolLib: TASAToolLib;
protected
function GetEnv: TODBCEnvironment; override;
procedure CheckActive(AAutoActivate, ANeedActivation: Boolean); override;
public
property ToolLib: TASAToolLib read GetToolLib;
published
property DriverLink: TFDPhysASADriverLink read GetDriverLink write SetDriverLink;
property OnProgress: TFDASAProgressEvent read FOnProgress write FOnProgress;
end;
[ComponentPlatformsAttribute(pfidWindows)]
TFDASABackup = class (TFDASAService)
private
FConnectParams: String;
FCheckpointLogType: TASABackupCheckpointLogType;
FPageBlocksize: Cardinal;
FHotlogFilename: String;
FOutputDir: String;
FFlags: TASABackupFlags;
FStartLine: String;
protected
procedure InternalExecute; override;
public
constructor Create(AOwner: TComponent); override;
procedure Backup;
published
property ConnectParams: String read FConnectParams write FConnectParams;
property StartLine: String read FStartLine write FStartLine;
property OutputDir: String read FOutputDir write FOutputDir;
property HotlogFilename: String read FHotlogFilename write FHotlogFilename;
property CheckpointLogType: TASABackupCheckpointLogType read FCheckpointLogType
write FCheckpointLogType default bclDefault;
property PageBlocksize: Cardinal read FPageBlocksize write FPageBlocksize
default 0;
property Flags: TASABackupFlags read FFlags write FFlags default [];
end;
[ComponentPlatformsAttribute(pfidWindows)]
TFDASAValidate = class (TFDASAService)
private
FConnectParams: String;
FStartLine: String;
FValidateType: TASAValidateType;
FTables: TStrings;
FFlags: TASAValidateFlags;
procedure SetTables(const AValue: TStrings);
protected
procedure InternalExecute; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Validate;
published
property ConnectParams: String read FConnectParams write FConnectParams;
property StartLine: String read FStartLine write FStartLine;
property Tables: TStrings read FTables write SetTables;
property Flags: TASAValidateFlags read FFlags write FFlags default [];
property ValidateType: TASAValidateType read FValidateType write FValidateType default vtNormal;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
implementation
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.SysUtils, System.StrUtils, System.Variants,
FireDAC.Stan.Consts, FireDAC.Stan.Error, FireDAC.Stan.Util, FireDAC.Stan.Factory,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Phys.ODBCCli, FireDAC.Phys.ASACli,
FireDAC.Phys.ASAMeta, FireDAC.Phys.ASADef;
type
TFDPhysASADriver = class;
TFDPhysASAConnection = class;
{$IFDEF MSWINDOWS}
TFDPhysASAEventAlerter = class;
{$ENDIF}
TFDPhysASACommand = class;
TFDPhysASACliHandles = array [0..1] of Pointer;
PFDPhysASACliHandles = ^TFDPhysODBCCliHandles;
TFDPhysASADriver = class(TFDPhysODBCDriverBase)
private
FToolLib: TASAToolLib;
FCliObj: TFDPhysASACliHandles;
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
procedure InternalLoad; override;
procedure InternalUnload; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
function GetCliObj: Pointer; override;
procedure GetODBCConnectStringKeywords(AKeywords: TStrings); override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
public
constructor Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); override;
destructor Destroy; override;
end;
TFDPhysASAConnection = class (TFDPhysODBCConnectionBase)
private
procedure CheckPasswordChange;
protected
function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override;
function InternalCreateCommandGenerator(const ACommand:
IFDPhysCommand): TFDPhysCommandGenerator; override;
function InternalCreateMetadata: TObject; override;
function InternalCreateCommand: TFDPhysCommand; override;
procedure GetStrsMaxSizes(AStrDataType: SQLSmallint; AFixedLen: Boolean;
out ACharSize, AByteSize: Integer); override;
function GetExceptionClass: EODBCNativeExceptionClass; override;
procedure SetupConnection; override;
procedure InternalChangePassword(const AUserName, AOldPassword,
ANewPassword: String); override;
procedure InternalConnect; override;
end;
{$IFDEF MSWINDOWS}
TFDPhysASAEventAlerter = class (TFDPhysEventAlerter)
private
FWaitConnection: IFDPhysConnection;
FWaitCommand: IFDPhysCommand;
FWaitThread: TThread;
FMsgCbkThunk: TFDMethodThunk;
procedure DoMsgCallback(SQLCA: Pointer; msg_type: byte; code: LongWord;
len: Word; msg: PFDAnsiString); stdcall;
protected
// TFDPhysEventAlerter
procedure InternalAllocHandle; override;
procedure InternalRegister; override;
procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override;
procedure InternalAbortJob; override;
procedure InternalReleaseHandle; override;
procedure InternalSignal(const AEvent: String; const AArgument: Variant); override;
end;
{$ENDIF}
TFDPhysASACommand = class(TFDPhysODBCCommand)
protected
function InternalFetchRowSet(ATable: TFDDatSTable;
AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord; override;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysASADriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysASADriverLink.GetBaseDriverID: String;
begin
Result := S_FD_ASAId;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASADriverLink.IsConfigured: Boolean;
begin
Result := inherited IsConfigured or (FToolHome <> '') or (FToolLib <> '');
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASADriverLink.ApplyTo(const AParams: IFDStanDefinition);
begin
inherited ApplyTo(AParams);
if FToolHome <> '' then
AParams.AsString[S_FD_ConnParam_ASA_ToolHome] := FToolHome;
if FToolLib <> '' then
AParams.AsString[S_FD_ConnParam_ASA_ToolLib] := FToolLib;
end;
{-------------------------------------------------------------------------------}
{ TFDASAService }
{-------------------------------------------------------------------------------}
{$IFDEF MSWINDOWS}
function TFDASAService.GetDriverLink: TFDPhysASADriverLink;
begin
Result := inherited DriverLink as TFDPhysASADriverLink;
end;
{-------------------------------------------------------------------------------}
procedure TFDASAService.SetDriverLink(const AValue: TFDPhysASADriverLink);
begin
inherited DriverLink := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDASAService.GetEnv: TODBCEnvironment;
begin
Result := TODBCEnvironment(PFDPhysASACliHandles(CliObj)^[0]);
end;
{-------------------------------------------------------------------------------}
function TFDASAService.GetToolLib: TASAToolLib;
begin
Result := TASAToolLib(PFDPhysASACliHandles(CliObj)^[1]);
end;
{-------------------------------------------------------------------------------}
procedure TFDASAService.CheckActive(AAutoActivate, ANeedActivation: Boolean);
begin
inherited CheckActive(AAutoActivate, ANeedActivation);
if not Assigned(ToolLib.DBToolsInit) then
FDException(Self, [S_FD_LPhys, DriverLink.ActualDriverID], er_FD_ASADBToolNotFound, []);
end;
{-------------------------------------------------------------------------------}
{ TFDASABackup }
{-------------------------------------------------------------------------------}
constructor TFDASABackup.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCheckpointLogType := bclDefault;
end;
{-------------------------------------------------------------------------------}
procedure TFDASABackup.InternalExecute;
var
oBckp: TASABackup;
begin
oBckp := TASABackup.Create(ToolLib, Self);
try
oBckp.ConnectParams := ConnectParams;
oBckp.StartLine := StartLine;
oBckp.OutputDir := OutputDir;
oBckp.HotlogFilename := HotlogFilename;
oBckp.CheckpointLogType := CheckpointLogType;
oBckp.PageBlocksize := PageBlocksize;
oBckp.Flags := Flags;
oBckp.OnMessage := OnProgress;
oBckp.Backup;
finally
FDFree(oBckp);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDASABackup.Backup;
begin
Execute;
end;
{-------------------------------------------------------------------------------}
{ TFDASAValidate }
{-------------------------------------------------------------------------------}
constructor TFDASAValidate.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTables := TFDStringList.Create;
end;
{-------------------------------------------------------------------------------}
destructor TFDASAValidate.Destroy;
begin
FDFreeAndNil(FTables);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDASAValidate.SetTables(const AValue: TStrings);
begin
FTables.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDASAValidate.InternalExecute;
var
oVldt: TASAValidate;
begin
oVldt := TASAValidate.Create(ToolLib, Self);
try
oVldt.ConnectParams := ConnectParams;
oVldt.StartLine := StartLine;
oVldt.Tables := Tables;
oVldt.Flags := Flags;
oVldt.ValidateType := ValidateType;
oVldt.OnMessage := OnProgress;
oVldt.Validate;
finally
FDFree(oVldt);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDASAValidate.Validate;
begin
Execute;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TFDPhysASADriver }
{-------------------------------------------------------------------------------}
constructor TFDPhysASADriver.Create(AManager: TFDPhysManager;
const ADriverDef: IFDStanDefinition);
begin
inherited Create(AManager, ADriverDef);
FToolLib := TASAToolLib.Create(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysASADriver.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FToolLib);
end;
{-------------------------------------------------------------------------------}
class function TFDPhysASADriver.GetBaseDriverID: String;
begin
Result := S_FD_ASAId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysASADriver.GetBaseDriverDesc: String;
begin
Result := 'SAP SQL Anywhere';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysASADriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.SQLAnywhere;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysASADriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysASAConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASADriver.InternalLoad;
var
sToolHome, sToolLib: String;
begin
ODBCAdvanced := 'CommLinks=ShMem';
inherited InternalLoad;
if ODBCDriver = '' then
ODBCDriver := FindBestDriver(
{$IFDEF MSWINDOWS} ['SQL Anywhere 17', 'SQL Anywhere 16', 'SQL Anywhere 12',
'SQL Anywhere 11', 'SQL Anywhere 10', 'Adaptive Server Anywhere 9.%',
'Adaptive Server Anywhere 8.%', 'Adaptive Server Anywhere 7.%',
'Sybase SQL Anywhere %'] {$ENDIF}
{$IFDEF POSIX} ['SQL Anywhere%', 'SQLAnywhere%'], C_SQLAnywhere16Lib {$ENDIF});
if Params <> nil then begin
sToolHome := Params.AsXString[S_FD_ConnParam_ASA_ToolHome];
sToolLib := Params.AsXString[S_FD_ConnParam_ASA_ToolLib];
end
else begin
sToolHome := '';
sToolLib := '';
end;
FToolLib.Load(sToolHome, sToolLib);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASADriver.InternalUnload;
begin
FToolLib.Unload;
inherited InternalUnload;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASADriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysASAConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
function TFDPhysASADriver.GetCliObj: Pointer;
begin
FCliObj[0] := ODBCEnvironment;
FCliObj[1] := FToolLib;
Result := @FCliObj[0];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASADriver.GetODBCConnectStringKeywords(AKeywords: TStrings);
begin
inherited GetODBCConnectStringKeywords(AKeywords);
AKeywords.Add(S_FD_ConnParam_Common_Server + '=EngineName');
AKeywords.Add(S_FD_ConnParam_Common_Database + '=DatabaseName');
AKeywords.Add(S_FD_ConnParam_ASA_DatabaseFile + '=' +
S_FD_ConnParam_ASA_DatabaseFile + '*');
AKeywords.Add(S_FD_ConnParam_Common_OSAuthent + '=Integrated');
AKeywords.Add(S_FD_ConnParam_ASA_Compress);
AKeywords.Add(S_FD_ConnParam_ASA_Encrypt + '=Encryption*');
AKeywords.Add(S_FD_ConnParam_Common_ApplicationName + '=AppInfo');
AKeywords.Add('=COMMLINKS');
AKeywords.Add(S_FD_ConnParam_Common_NewPassword + '=NEWPWD*');
end;
{-------------------------------------------------------------------------------}
function TFDPhysASADriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
begin
Result := inherited GetConnParams(AKeys, AParams);
oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + '''');
if oView.Rows.Count = 1 then begin
oView.Rows[0].BeginEdit;
oView.Rows[0].SetValues('LoginIndex', 4);
oView.Rows[0].EndEdit;
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, '@S', '', S_FD_ConnParam_Common_Server, 3]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_ASA_DatabaseFile, '@F:SQL Anywhere Database|*.db', '', S_FD_ConnParam_ASA_DatabaseFile, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_OSAuthent, '@Y', '', S_FD_ConnParam_Common_OSAuthent, 2]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_ASA_Compress, '@Y', '', S_FD_ConnParam_ASA_Compress, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_ASA_Encrypt, '@S', '', S_FD_ConnParam_ASA_Encrypt, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_ApplicationName, '@S', '', S_FD_ConnParam_Common_ApplicationName, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefCatalog, '@S', '', S_FD_ConnParam_Common_MetaDefCatalog, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefSchema, '@S', '', S_FD_ConnParam_Common_MetaDefSchema, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurCatalog, '@S', '', S_FD_ConnParam_Common_MetaCurCatalog, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurSchema, '@S', '', S_FD_ConnParam_Common_MetaCurSchema, -1]);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysASAConnection }
{-------------------------------------------------------------------------------}
function TFDPhysASAConnection.InternalCreateEvent(
const AEventKind: String): TFDPhysEventAlerter;
begin
{$IFDEF MSWINDOWS}
if CompareText(AEventKind, S_FD_EventKind_ASA_Events) = 0 then
Result := TFDPhysASAEventAlerter.Create(Self, AEventKind)
else
{$ENDIF}
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
if ACommand <> nil then
Result := TFDPhysASACommandGenerator.Create(ACommand)
else
Result := TFDPhysASACommandGenerator.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnection.InternalCreateMetadata: TObject;
var
iSrvVer, iClntVer: TFDVersion;
begin
GetVersions(iSrvVer, iClntVer);
Result := TFDPhysASAMetadata.Create(Self, iSrvVer, iClntVer, GetKeywords);
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnection.InternalCreateCommand: TFDPhysCommand;
begin
Result := TFDPhysASACommand.Create(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnection.GetStrsMaxSizes(AStrDataType: SQLSmallint;
AFixedLen: Boolean; out ACharSize, AByteSize: Integer);
begin
AByteSize := 32766;
ACharSize := AByteSize;
case AStrDataType of
SQL_C_CHAR, SQL_C_BINARY:
;
SQL_C_WCHAR:
ACharSize := AByteSize div SizeOf(SQLWChar);
else
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_ASAId]);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnection.GetExceptionClass: EODBCNativeExceptionClass;
begin
Result := EASANativeException;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnection.CheckPasswordChange;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
CreateMetadata(oConnMeta);
if oConnMeta.ServerVersion < cvSybaseASA11 then
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_ASAId]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnection.SetupConnection;
begin
if ConnectionDef.Params.NewPassword <> '' then
CheckPasswordChange;
inherited SetupConnection;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnection.InternalChangePassword(const AUserName,
AOldPassword, ANewPassword: String);
var
oConnDef: IFDStanConnectionDef;
oConn: TODBCConnection;
begin
CheckPasswordChange;
FDCreateInterface(IFDStanConnectionDef, oConnDef);
oConnDef.ParentDefinition := ConnectionDef;
oConnDef.Params.UserName := AUserName;
oConnDef.Params.NewPassword := ANewPassword;
oConnDef.Params.Password := AOldPassword;
oConn := TODBCConnection.Create(ODBCEnvironment, Self);
try
oConn.Connect(TFDPhysODBCDriverBase(DriverObj).BuildODBCConnectString(oConnDef));
finally
FDFree(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnection.InternalConnect;
{$IFDEF MSWINDOWS}
const
CPath: String = 'PATH';
var
sHome, sOldPath, sPath: String;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
sOldPath := '';
if InternalGetSharedCliHandle() <> nil then begin
sHome := DriverObj.Params.AsXString[S_FD_ConnParam_ASA_ToolHome];
if sHome <> '' then begin
sOldPath := GetEnvironmentVariable(CPath);
sPath := FDNormPath(sHome) + {$IFDEF FireDAC_32} 'Bin32' {$ELSE} 'Bin64' {$ENDIF} +
';' + sOldPath;
SetEnvironmentVariable(PChar(CPath), PChar(sPath));
end;
end;
try
{$ENDIF}
inherited InternalConnect;
{$IFDEF MSWINDOWS}
finally
if sOldPath <> '' then
SetEnvironmentVariable(PChar(CPath), PChar(sOldPath));
end;
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
{-------------------------------------------------------------------------------}
{ TFDPhysASAEventThread }
{-------------------------------------------------------------------------------}
type
TFDPhysASAEventThread = class(TThread)
private
[weak] FAlerter: TFDPhysASAEventAlerter;
protected
procedure Execute; override;
public
constructor Create(AAlerter: TFDPhysASAEventAlerter);
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysASAEventThread.Create(AAlerter: TFDPhysASAEventAlerter);
begin
inherited Create(False);
FAlerter := AAlerter;
FreeOnTerminate := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysASAEventThread.Destroy;
begin
FAlerter.FWaitThread := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAEventThread.Execute;
begin
while not Terminated and FAlerter.IsRunning do
try
FAlerter.FWaitCommand.Execute;
except
on E: EFDDBEngineException do
if E.Kind <> ekCmdAborted then begin
Terminate;
FAlerter.AbortJob;
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysASAEventMessage }
{-------------------------------------------------------------------------------}
type
TFDPhysASAEventMessage = class(TFDPhysEventMessage)
private
FEvent,
FMessage: String;
public
constructor Create(const AEvent, AMessage: String);
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysASAEventMessage.Create(const AEvent, AMessage: String);
begin
inherited Create;
FEvent := AEvent;
FMessage := AMessage;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysASAEventAlerter }
{-------------------------------------------------------------------------------}
const
C_Delim = '$$';
{-------------------------------------------------------------------------------}
procedure TFDPhysASAEventAlerter.InternalAllocHandle;
begin
if FDVerStr2Int(TODBCConnection(GetConnection.CliObj).DRIVER_VER) < cvSybaseASA9 then
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
FWaitConnection := GetConnection.Clone;
if FWaitConnection.State = csDisconnected then
FWaitConnection.Open;
FMsgCbkThunk := TFDMethodThunk.Create(Self, @TFDPhysASAEventAlerter.DoMsgCallback);
TODBCConnection(FWaitConnection.CliObj).REGISTER_MESSAGE_CALLBACK := FMsgCbkThunk.CallAddress;
FWaitConnection.CreateCommand(FWaitCommand);
SetupCommand(FWaitCommand);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAEventAlerter.DoMsgCallback(SQLCA: Pointer; msg_type: byte;
code: LongWord; len: Word; msg: PFDAnsiString); stdcall;
var
sEvent, sMsg: String;
i1, i2: Integer;
begin
sMsg := TFDEncoder.Deco(msg, len, ecANSI);
if Pos(C_FD_SysNamePrefix + C_Delim, sMsg) = 1 then begin
i1 := Length(C_FD_SysNamePrefix) + Length(C_Delim) + 1;
i2 := Pos(C_Delim, sMsg, i1);
if i2 = 0 then
i2 := Length(sMsg) + 1;
sEvent := Copy(sMsg, i1, i2 - i1);
sMsg := Copy(sMsg, i2 + Length(C_Delim), MaxInt);
if GetNames.IndexOf(sEvent) >= 0 then
FMsgThread.EnqueueMsg(TFDPhysASAEventMessage.Create(sEvent, sMsg));
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAEventAlerter.InternalHandle(AEventMessage: TFDPhysEventMessage);
var
oMsg: TFDPhysASAEventMessage;
begin
oMsg := TFDPhysASAEventMessage(AEventMessage);
InternalHandleEvent(oMsg.FEvent, oMsg.FMessage);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAEventAlerter.InternalAbortJob;
begin
if FWaitThread <> nil then begin
FWaitThread.Terminate;
FWaitCommand.AbortJob(True);
while (FWaitThread <> nil) and (FWaitThread.ThreadID <> TThread.Current.ThreadID) do
Sleep(1);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAEventAlerter.InternalRegister;
begin
FWaitCommand.CommandText := 'WAITFOR DELAY ''00:00:30'' AFTER MESSAGE BREAK';
FWaitCommand.Prepare;
FWaitThread := TFDPhysASAEventThread.Create(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAEventAlerter.InternalReleaseHandle;
var
oConn: TODBCConnection;
begin
if FWaitConnection <> nil then begin
oConn := TODBCConnection(FWaitConnection.CliObj);
if (oConn <> nil) and oConn.Connected then
oConn.REGISTER_MESSAGE_CALLBACK := nil;
end;
FDFreeAndNil(FMsgCbkThunk);
FWaitCommand := nil;
FWaitConnection := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAEventAlerter.InternalSignal(const AEvent: String;
const AArgument: Variant);
var
s: String;
oCmd: IFDPhysCommand;
begin
// _FD_$$event[$$argument]
s := C_FD_SysNamePrefix + C_Delim + AEvent;
if not (VarIsNull(AArgument) or VarIsEmpty(AArgument)) then
s := s + C_Delim + VarToStr(AArgument);
GetConnection.CreateCommand(oCmd);
SetupCommand(oCmd);
oCmd.Prepare('MESSAGE ' + QuotedStr(s) + ' TYPE INFO TO CLIENT FOR ALL');
oCmd.Execute();
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TFDPhysASACommand }
{-------------------------------------------------------------------------------}
function TFDPhysASACommand.InternalFetchRowSet(ATable: TFDDatSTable;
AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord;
var
ePrevKind: TFDPhysMetaInfoKind;
iCount: TFDCounter;
begin
Result := inherited InternalFetchRowSet(ATable, AParentRow, ARowsetSize);
// ASA ODBC driver does not return primary key index in SQLStatistics resultset.
// KeysInSQLStatistics=yes has no effect. So, merge primary key resultsets into
// index result sets.
if (GetMetaInfoKind = mkIndexes) or
(GetMetaInfoKind = mkIndexFields) and (Result = 0) then begin
ePrevKind := FMetaInfoKind;
try
InternalClose;
InternalUnprepare;
if FMetaInfoKind = mkIndexes then
FMetaInfoKind := mkPrimaryKey
else
FMetaInfoKind := mkPrimaryKeyFields;
InternalPrepare;
InternalOpen(iCount);
FRecordsFetched := Result;
Result := Result + inherited InternalFetchRowSet(ATable, AParentRow, ARowsetSize);
finally
InternalClose;
InternalUnprepare;
FMetaInfoKind := ePrevKind;
end;
end;
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysASADriver);
finalization
FDUnregisterDriverClass(TFDPhysASADriver);
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXDataSets;
interface
uses
System.SysUtils,
System.Classes,
Data.DB,
Data.DBCommon,
Data.DBCommonTypes,
Data.DBXCommon,
System.Generics.Collections
;
type
TDBXReaderDataSet = class(TDataSet)
public const
SOrderBy = ' order by '; { Do not localize }
SParam = '?'; { Do not localize }
DefaultMaxBlobSize = -1; // values are in K; -1 means retrieve actual size
// maps the TDBXDataTypes into FldTypeMap
DataTypeMap: array[0..TDBXDataTypes.MaxBaseTypes - 1] of TFieldType = (
ftUnknown, ftString, ftDate, ftBlob, ftBoolean, ftSmallint,
ftInteger, ftFloat, ftFMTBCD, ftBytes, ftTime, ftDateTime,
ftWord, ftInteger, ftUnknown, ftVarBytes, ftUnknown, ftCursor,
ftLargeInt, ftLargeInt, ftADT, ftArray, ftReference, ftDataSet,
ftTimeStamp, ftBCD, ftWideString, ftSingle, ftShortint, ftByte, ftUnknown,
ftUnknown, ftUnknown, ftUnknown, ftUnknown, ftVariant, ftTimeStampOffset, ftObject,
ftObject);
SUB_TYPE_MEMO = TDBXDataTypes.MemoSubType;
BlobTypeMap: array[SUB_TYPE_MEMO..TDBXDataTypes.BFileSubType] of TFieldType = (
ftMemo, ftBlob, ftFmtMemo, ftParadoxOle, ftGraphic, ftDBaseOle,
ftTypedBinary, ftBlob, ftBlob, ftBlob, ftWideMemo, ftOraClob, ftOraBlob,
ftBlob, ftBlob);
public type
TBlobStream = class(TMemoryStream)
private
[Weak]FDataSet: TDBXReaderDataSet;
[Weak]FField: TBlobField;
FFieldNo: Integer;
FHasData: Boolean;
protected
procedure ReadBlobSize;
public
constructor Create(Field: TBlobField; Mode: TBlobStreamMode = bmRead);
destructor Destroy; override;
procedure ReadBlobData;
function Read(Buffer: TBytes; Offset, Count: Longint): Longint; overload; override;
{$IFNDEF NEXTGEN}
function Read(var Buffer; Count: Longint): Longint; overload; override; deprecated 'Use overloaded method instead';
{$ENDIF !NEXTGEN}
end;
TFLDDesc = class
private
FFldNum: Word; { Field number (1..n) }
FName: string; { Field name }
FFldType: Word; { Field type }
FSubType: Word; { Field subtype (if applicable) }
FUnits1: SmallInt; { Number of Chars, digits etc }
FUnits2: SmallInt; { Decimal places etc. }
FOffset: Word; { Offset in the record (computed) }
FLen: LongWord; { Length in bytes (computed) }
FNullOffset: Word; { For Null bits (computed) }
FFLDVchk: FLDVchk; { Field Has vcheck (computed) }
FFLDRights: FLDRights; { Field Rights (computed) }
FCalcField: WordBool; { Is Calculated field (computed) }
public
property iFldNum: Word read FFldNum write FFldNum;
property szName: string read FName write FName;
property iFldType: Word read FFldType write FFldType;
property iSubType: Word read FSubType write FSubType;
property iUnits1: SmallInt read FUnits1 write FUnits1;
property iUnits2: SmallInt read FUnits2 write FUnits2;
property iOffset: Word read FOffset write FOffset;
property iLen: LongWord read FLen write FLen;
property iNullOffset: Word read FNullOffset write FNullOffset;
property efldvVchk: FLDVchk read FFLDVchk write FFLDVchk;
property efldrRights: FLDRights read FFLDRights write FFLDRights;
property bCalcField: WordBool read FCalcField write FCalcField;
end;
TFieldDescList = array of TFLDDesc;
strict private
FFieldBuffer: TArray<Byte>;
FRefreshing: Boolean;
private
FBlobBuffer: TBlobByteData;
FCalcFieldsBuffer: TArray<Byte>;
FCheckRowsAffected: Boolean;
FCurrentBlobSize: Int64;
FDesignerData: string;
FProvidedDBXReader: Boolean;
FOwnsProvidedDBXReader: Boolean;
FIndexDefs: TIndexDefs;
FMaxBlobSize: Integer;
FMaxColSize: LongWord;
FGetMetadata: Boolean;
FNumericMapping: Boolean;
FPrepared: Boolean;
FRecords: Integer;
FRowsAffected: Integer;
FSortFieldNames: string;
FDBXReader: TDBXReader;
{$IFDEF NEXTGEN}
function GetCalculatedField(Field: TField; Buffer: TValueBuffer): Boolean;
{$ELSE !NEXTGEN}
function GetCalculatedField(Field: TField; Buffer: Pointer): Boolean;
{$ENDIF !NEXTGEN}
function GetQueryFromType: string; virtual;
function GetRowsAffected: Integer;
procedure InitBuffers;
procedure LoadFieldDef(FieldID: Word; var FldDesc: TFLDDesc); overload;
procedure SetCurrentBlobSize(Value: Int64);
procedure SetPrepared(Value: Boolean);
protected
{ IProviderSupport }
procedure PSEndTransaction(Commit: Boolean); override;
procedure PSExecute; override;
function PSExecuteStatement(const ASQL: string; AParams: TParams): Integer; overload; override;
function PSExecuteStatement(const ASQL: string; AParams: TParams;
var ResultSet: TDataSet): Integer; overload; override;
{$IFNDEF NEXTGEN}
function PSExecuteStatement(const ASQL: string; AParams: TParams;
ResultSet: Pointer): Integer; overload; override; deprecated 'Use overloaded method instead';
{$ENDIF !NEXTGEN}
procedure PSGetAttributes(List: TPacketAttributeList); override;
function PSGetDefaultOrder: TIndexDef; override;
function PSGetKeyFields: string; override;
function PSGetQuoteChar: string; override;
function PSGetTableName: string; override;
function PSGetIndexDefs(IndexTypes: TIndexOptions): TIndexDefs; override;
function PSGetParams: TParams; override;
function PSGetUpdateException(E: Exception; Prev: EUpdateError): EUpdateError; override;
function PSInTransaction: Boolean; override;
function PSIsSQLBased: Boolean; override;
function PSIsSQLSupported: Boolean; override;
procedure PSReset; override;
procedure PSSetCommandText(const ACommandText: string); override;
procedure PSSetParams(AParams: TParams); override;
procedure PSStartTransaction; override;
function PSUpdateRecord(UpdateKind: TUpdateKind; Delta: TDataSet): Boolean; override;
function PSGetCommandText: string; override;
function PSGetCommandType: TPSCommandType; override;
protected
{ implementation of abstract TDataSet methods }
procedure InternalClose; override;
procedure InternalHandleException; override;
procedure InternalInitFieldDefs; override;
procedure InternalOpen; override;
function IsCursorOpen: Boolean; override;
protected
procedure AddFieldDesc(FieldDescs: TFieldDescList; DescNo: Integer;
var FieldID: Integer; RequiredFields: TBits; FieldDefs: TFieldDefs);
procedure ClearIndexDefs;
procedure CloseCursor; override;
procedure CloseStatement;
procedure FreeReader;
procedure FreeBuffers;
procedure FreeCommand;
function GetCanModify: Boolean; override;
procedure GetObjectTypeNames(Fields: TFields);
function GetRecord(Buffer: TRecBuf; GetMode: TGetMode; DoCheck: Boolean): TGetResult; overload; override;
{$IFNDEF NEXTGEN}
function GetRecord(Buffer: TRecordBuffer; GetMode: TGetMode; DoCheck: Boolean): TGetResult; overload; override; deprecated 'Use overloaded method instead';
{$ENDIF !NEXTGEN}
function GetSortFieldNames: string;
procedure InitRecord(Buffer: TRecBuf); overload; override;
{$IFNDEF NEXTGEN}
procedure InitRecord(Buffer: TRecordBuffer); overload; override; deprecated 'Use overloaded method instead';
{$ENDIF !NEXTGEN}
procedure InternalRefresh; override;
procedure Loaded; override;
function LocateRecord(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions; SyncCursor: Boolean): Boolean;
procedure OpenCursor(InfoQuery: Boolean); override;
procedure PropertyChanged;
procedure SetBufListSize(Value: Integer); override;
procedure SetFieldData(Field: TField; Buffer: TValueBuffer); overload; override;
{$IFNDEF NEXTGEN}
procedure SetFieldData(Field: TField; Buffer: Pointer); overload; override; deprecated 'Use overloaded method instead';
{$ENDIF !NEXTGEN}
procedure SetSortFieldNames(Value: string);
procedure UpdateIndexDefs; override;
{ protected properties }
property BlobBuffer: TBlobByteData read FBlobBuffer write FBlobBuffer;
property CurrentBlobSize: Int64 read FCurrentBlobSize write SetCurrentBlobSize;
property RowsAffected: Integer read GetRowsAffected;
procedure SetMaxBlobSize(MaxSize: Integer);
protected { publish in TSQLDataSet }
[Default(0)]
property MaxBlobSize: Integer read FMaxBlobSize write SetMaxBlobSize default 0;
function GetRecordCount: Integer; override;
property SortFieldNames: string read GetSortFieldNames write SetSortFieldNames;
public
constructor Create(AOwner: TComponent); overload; override;
constructor Create(AOwner: TComponent; DBXReader: TDBXReader; AOwnsInstance: Boolean); reintroduce; overload;
destructor Destroy; override;
function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; override;
function GetBlobFieldData(FieldNo: Integer; var Buffer: TBlobByteData): Integer; override;
function GetFieldData(FieldNo: Integer; var Buffer: TValueBuffer): Boolean; overload; override;
function GetFieldData(Field: TField; var Buffer: TValueBuffer): Boolean; overload; override;
{$IFNDEF NEXTGEN}
function GetFieldData(FieldNo: Integer; Buffer: Pointer): Boolean; overload; override; deprecated 'Use overloaded method instead';
function GetFieldData(Field: TField; Buffer: Pointer): Boolean; overload; override; deprecated 'Use overloaded method instead';
{$ENDIF !NEXTGEN}
property IndexDefs: TIndexDefs read FIndexDefs write FIndexDefs;
function IsSequenced: Boolean; override;
function Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean; override;
function Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant; override;
[Default(False)]
property Prepared: Boolean read FPrepared write SetPrepared default False;
property DesignerData: string read FDesignerData write FDesignerData;
property RecordCount: Integer read GetRecordCount;
public
[Default(True)]
property GetMetadata: Boolean read FGetMetadata write FGetMetadata default True;
[Default(False)]
property NumericMapping: Boolean read FNumericMapping write FNumericMapping default False;
[Default(False)]
property ObjectView default False;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeScroll;
property AfterScroll;
property BeforeRefresh;
property AfterRefresh;
property OnCalcFields;
[Default(False)]
property Active default False;
end;
implementation
uses
Data.DBConsts,
Data.FmtBcd,
System.Variants,
Data.DBByteBuffer,
System.StrUtils,
Data.SqlTimSt,
Data.DBXPlatform
{$IFDEF MACOS}
, Macapi.CoreFoundation
{$ENDIF MACOS}
;
function GetBlobLength(DataSet: TDBXReaderDataSet; FieldNo: Integer): Int64;
var
IsNull: LongBool;
begin
Result := 0;
if not DataSet.EOF then
begin
if DataSet.MaxBlobSize = 0 then
exit;
DataSet.FDBXReader.ByteReader.GetByteLength(FieldNo-1, Result, isNull);
if isNull then
Result := 0;
end;
DataSet.CurrentBlobSize := Result;
end;
{ TSQLBlobStream }
constructor TDBXReaderDataSet.TBlobStream.Create(Field: TBlobField; Mode: TBlobStreamMode = bmRead);
begin
inherited Create;
if not Field.DataSet.Active then
DataBaseError(SDatasetClosed);
FField := Field;
FDataSet := FField.DataSet as TDBXReaderDataSet;
FFieldNo := FField.FieldNo;
FHasData := false;
ReadBlobSize;
end;
destructor TDBXReaderDataSet.TBlobStream.Destroy;
begin
inherited Destroy;
end;
procedure TDBXReaderDataSet.TBlobStream.ReadBlobSize;
var
LOffset, LRead: Integer;
LIsNull: LongBool;
LBytes: TArray<Byte>;
BlobLength: Int64;
const
sMaxTmpBuffer = 32768;
begin
Clear;
BlobLength := GetBlobLength(FDataSet, FFieldNo);
// For DataSnap connections, blob size can be -1 for large streams
// We need to determine the correct size now to be able to retrieve
// the data properly
if BlobLength = -1 then
begin
//if MaxBlobSize is -1, then we are not limiting the buffer size
// so let's find out what the real blob size is
if FDataSet <> nil then
begin
if FDataSet.MaxBlobSize = -1 then
begin
LOffset := 0;
repeat
SetLength(LBytes, LOffset + sMaxTmpBuffer);
LRead := FDataSet.FDBXReader.ByteReader.GetBytes(FFieldNo-1, LOffset, LBytes, LOffset, sMaxTmpBuffer, LIsNull);
if LRead < sMaxTmpBuffer then
begin
LOffset := LOffset + LRead;
SetLength(LBytes, LOffset)
end
else
LOffset := LOffset + sMaxTmpBuffer;
until LRead < sMaxTmpBuffer;
BlobLength := LOffset;
Write(LBytes[0], BlobLength);
FHasData := True;
Position := 0;
end
else
BlobLength := FDataSet.MaxBlobSize * 1024;
FDataSet.CurrentBlobSize := BlobLength;
end;
end;
if BlobLength > 0 then
SetSize(BlobLength);
end;
procedure TDBXReaderDataSet.TBlobStream.ReadBlobData;
begin
if FDataSet.GetFieldData(FField, FDataSet.FBlobBuffer, True) then
Write(FDataSet.FBlobBuffer[0], FDataSet.FCurrentBlobSize);
Position := 0;
FHasData := true;
end;
function TDBXReaderDataSet.TBlobStream.Read(Buffer: TBytes; Offset, Count: LongInt): LongInt;
begin
if not FHasData then
ReadBlobData;
Result := inherited Read(Buffer, Offset, Count);
end;
{$IFNDEF NEXTGEN}
function TDBXReaderDataSet.TBlobStream.Read(var Buffer; Count: Longint): Longint;
begin
if not FHasData then
ReadBlobData;
Result := inherited Read(Buffer, Count);
end;
{$ENDIF !NEXTGEN}
constructor TDBXReaderDataSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIndexDefs := TIndexDefs.Create(Self);
FRecords := -1;
SetUniDirectional(True);
ObjectView := False;
end;
destructor TDBXReaderDataSet.Destroy;
begin
Close;
if Assigned(FDBXReader) then FreeReader;
FreeAndNil(FIndexDefs);
inherited Destroy;
FreeBuffers;
end;
{ open/close Cursors and Statements }
procedure TDBXReaderDataSet.GetObjectTypeNames(Fields: TFields);
var
I: Integer;
ObjectField: TObjectField;
begin
for I := 0 to Fields.Count - 1 do
begin
if Fields[I] is TObjectField then
begin
ObjectField := TObjectField(Fields[I]);
ObjectField.ObjectType := FDBXReader.GetObjectTypeName(ObjectField.FieldNo-1);
if ObjectField.DataType in [ftADT, ftArray] then
begin
if (ObjectField.DataType = ftArray) and SparseArrays and
(ObjectField.Fields[0].DataType = ftADT) then
GetObjectTypeNames(TObjectField(ObjectField.Fields[0]).Fields) else
GetObjectTypeNames(ObjectField.Fields);
end;
end;
end;
end;
procedure TDBXReaderDataSet.InternalOpen;
begin
Assert(Assigned(FDBXReader));
FieldDefs.Update;
CreateFields;
BindFields(True);
if ObjectView then GetObjectTypeNames(Fields);
InitBuffers;
end;
function TDBXReaderDataSet.IsCursorOpen: Boolean;
begin
Result := (FDBXReader <> nil);
end;
procedure TDBXReaderDataSet.OpenCursor(InfoQuery: Boolean);
begin
SetPrepared(True);
inherited OpenCursor;
end;
procedure TDBXReaderDataSet.CloseCursor;
begin
inherited CloseCursor;
end;
procedure TDBXReaderDataSet.FreeReader;
begin
if Assigned(FDBXReader) then
begin
if FProvidedDBXReader and not FOwnsProvidedDBXReader then
FDBXReader := nil
else
FreeAndNil(FDBXReader);
end;
end;
procedure TDBXReaderDataSet.FreeCommand;
begin
if Assigned(FieldDefs) then
FieldDefs.Updated := False;
ClearIndexDefs;
end;
procedure TDBXReaderDataSet.CloseStatement;
begin
FPrepared := False;
end;
procedure TDBXReaderDataSet.InternalClose;
var
DetailList: TList<TDataSet>;
I: Integer;
begin
BindFields(False);
DestroyFields;
FreeBuffers;
if not FRefreshing then
begin
DetailList := TList<TDataSet>.Create;
try
GetDetailDataSets(DetailList);
for I := 0 to DetailList.Count -1 do
if DetailList[I] is TDBXReaderDataSet then
begin
TDBXReaderDataSet(DetailList[I]).Close;
TDBXReaderDataSet(DetailList[I]).SetPrepared(False);
end;
finally
DetailList.Free;
end;
end;
SetPrepared(False);
end;
procedure TDBXReaderDataSet.Loaded;
begin
inherited Loaded;
end;
procedure TDBXReaderDataSet.InternalRefresh;
begin
FRefreshing := True;
try
SetState(dsInactive);
CloseCursor;
OpenCursor(False);
SetState(dsBrowse);
finally
FRefreshing := False;
end;
end;
procedure TDBXReaderDataSet.InitBuffers;
begin
if (MaxBlobSize > 0) then
SetLength(FBlobBuffer, MaxBlobSize * 1024);
if (CalcFieldsSize > 0) then
SetLength(FCalcFieldsBuffer, CalcFieldsSize);
end;
procedure TDBXReaderDataSet.ClearIndexDefs;
begin
FIndexDefs.Clear;
// FIndexDefsLoaded := False;
end;
procedure TDBXReaderDataSet.FreeBuffers;
begin
if FBlobBuffer <> nil then
SetLength(FBlobBuffer, 0);
FBlobBuffer := nil;
if FFieldBuffer <> nil then
SetLength(FFieldBuffer, 0);
FFieldBuffer := nil;
FCurrentBlobSize := 0;
if FCalcFieldsBuffer <> nil then
begin
SetLength(FCalcFieldsBuffer, 0);
FCalcFieldsBuffer := nil;
end;
end;
procedure TDBXReaderDataSet.InitRecord(Buffer: TRecBuf);
begin
{ NOP }
end;
{$IFNDEF NEXTGEN}
procedure TDBXReaderDataSet.InitRecord(Buffer: TRecordBuffer);
begin
{ NOP }
end;
{$ENDIF !NEXTGEN}
procedure TDBXReaderDataSet.SetBufListSize(Value: Integer);
begin
end;
{ Reader Level Metadata }
procedure TDBXReaderDataSet.AddFieldDesc(FieldDescs: TFieldDescList; DescNo: Integer;
var FieldID: Integer; RequiredFields: TBits; FieldDefs: TFieldDefs);
const
ArrayIndex = '[0]';
var
LType: TFieldType;
LSize: LongWord;
LRequired: Boolean;
LPrecision, I: Integer;
FieldName: string;
FieldDesc: TFLDDesc;
FldDef: TFieldDef;
begin
FieldDesc := FieldDescs[DescNo];
FieldName := FieldDesc.szName;
FieldDesc.FName := FieldName;
I := 0;
while FieldDefs.IndexOf(FieldDesc.FName) >= 0 do
begin
Inc(I);
FieldDesc.FName := Format('%s_%d', [FieldName, I]);
end;
if FieldDesc.iFldType < TDBXDataTypes.MaxBaseTypes then
LType := DataTypeMap[FieldDesc.iFldType]
else
LType := ftUnknown;
if FieldDesc.iFldType in [TDBXDataTypes.CurrencyType, TDBXDataTypes.BcdType] then
begin
FieldDesc.iUnits2 := Abs(FieldDesc.iUnits2);
if FieldDesc.iUnits1 < FieldDesc.iUnits2 then // iUnits1 indicates Oracle 'usable decimals'
FieldDesc.iUnits1 := FieldDesc.iUnits2;
// ftBCD supports only up to 18-4. If Prec > 14 or Scale > 4, make FMTBcd
if (FieldDesc.iUnits1 > (MaxBcdPrecision-4)) or (FieldDesc.iUnits2 > MaxBcdScale) or FNumericMapping then
begin
LType := ftFMTBcd;
FieldDesc.iFldType := TDBXDataTypes.BcdType;
if FieldDesc.iUnits1 > MaxFMTBcdDigits then
FieldDesc.iUnits1 := MaxFMTBcdDigits;
end;
end;
LSize := 0;
LPrecision := 0;
if RequiredFields.Size > FieldID then
LRequired := RequiredFields[FieldID] else
LRequired := False;
case FieldDesc.iFldType of
TDBXDataTypes.AnsiStringType:
begin
if FieldDesc.iUnits1 = 0 then { Ignore MLSLABEL field type on Oracle }
LType := ftUnknown else
LSize := FieldDesc.iUnits1;
end;
TDBXDataTypes.WideStringType:
begin
if FieldDesc.iUnits1 = 0 then { Ignore MLSLABEL field type on Oracle }
LType := ftUnknown else
LSize := FieldDesc.iUnits1;
end;
TDBXDataTypes.BytesType, TDBXDataTypes.VarBytesType, TDBXDataTypes.RefType:
begin
if FieldDesc.iUnits1 = 0 then { Ignore MLSLABEL field type on Oracle }
LType := ftUnknown else
LSize := FieldDesc.iUnits1;
end;
TDBXDataTypes.Int16Type, TDBXDataTypes.UInt16Type:
if FieldDesc.iLen <> 2 then LType := ftUnknown;
TDBXDataTypes.Int32Type:
if FieldDesc.iSubType = TDBXDataTypes.AutoIncSubType then
begin
LType := ftAutoInc;
LRequired := False;
end;
TDBXDataTypes.DoubleType:
if FieldDesc.iSubType = TDBXDataTypes.MoneySubType then LType := ftCurrency;
TDBXDataTypes.CurrencyType, TDBXDataTypes.BcdType:
begin
LSize := Abs(FieldDesc.iUnits2);
LPrecision := FieldDesc.iUnits1;
end;
TDBXDataTypes.AdtType, TDBXDataTypes.ArrayType:
begin
LSize := FieldDesc.iUnits2;
LPrecision := FieldDesc.iUnits1;
end;
TDBXDataTypes.BlobType:
begin
LSize := FieldDesc.iUnits1;
if (FieldDesc.iSubType >= TDBXDataTypes.MemoSubType) and (FieldDesc.iSubType <= TDBXDataTypes.BFileSubType) then
LType := BlobTypeMap[FieldDesc.iSubType];
end;
end;
FldDef := FieldDefs.AddFieldDef;
FldDef.FieldNo := FieldID;
Inc(FieldID);
FldDef.Name := FieldDesc.FName;
FldDef.DataType := LType;
FldDef.Size := LSize;
FldDef.Precision := LPrecision;
if LRequired then
FldDef.Attributes := [faRequired];
if FieldDesc.efldrRights = fldrREADONLY then
FldDef.Attributes := FldDef.Attributes + [faReadonly];
if FieldDesc.iSubType = TDBXDataTypes.FixedSubType then
FldDef.Attributes := FldDef.Attributes + [faFixed];
FldDef.InternalCalcField := FieldDesc.bCalcField;
case LType of
ftBlob, ftMemo, ftWideMemo, ftOraBlob, ftOraClob, ftGraphic, ftFmtMemo, ftParadoxOle, ftDBaseOle:
if FldDef.Size > MaxBlobSize then
MaxBlobSize := FldDef.Size;
ftADT:
begin
if FieldDesc.iSubType = TDBXDataTypes.AdtNestedTableSubType then
FldDef.Attributes := FldDef.Attributes + [faUnNamed];
for I := 1 to FieldDesc.iUnits1 do
begin
LoadFieldDef(Word(FldDef.FieldNo + I), FieldDescs[1]);
AddFieldDesc(FieldDescs, 1, FieldID, RequiredFields, FldDef.ChildDefs);
end;
end;
ftArray:
begin
for I := 1 to FieldDesc.iUnits1 do
begin
LoadFieldDef(Word(FldDef.FieldNo + I), FieldDescs[1]);
FieldDescs[1].szName := FieldDesc.szName + ArrayIndex;
AddFieldDesc(FieldDescs, 1, FieldID, RequiredFields, FldDef.ChildDefs);
end;
end;
end;
end;
procedure TDBXReaderDataSet.LoadFieldDef(FieldID: Word; var FldDesc: TFLDDesc);
var
ValueType: TDBXValueType;
begin
FldDesc.iFldNum := FieldID;
ValueType := FDBXReader.ValueType[FieldID-1];
FldDesc.szName := ValueType.Name;
FldDesc.iFldType := ValueType.DataType;
FldDesc.iSubtype := ValueType.SubType;
FldDesc.iLen := ValueType.Size;
if ValueType.Precision > High(FldDesc.iUnits1) then
FldDesc.iUnits1 := High(FldDesc.iUnits1)
else
FldDesc.iUnits1 := ValueType.Precision;
if ValueType.Scale > High(FldDesc.iUnits2) then
FldDesc.iUnits2 := High(FldDesc.iUnits2)
else
FldDesc.iUnits2 := ValueType.Scale;
if ValueType.ReadOnly then
FldDesc.efldrRights := fldrREADONLY;
if FldDesc.iUnits1 = 0 then
begin
case ValueType.DataType of
TDBXDataTypes.WideStringType:
// Must provide a length in order to create a dataset column. Raid 272101.
// This code is consistent with TDBXDBMetaData.AddClientDataSetFields and
// TDBXDataSetTable.CopyValueTypeProperties when handling TDBXDataTypes.WideStringType
// Don't provide a length when have a DBXCommand so that ORACLE special cases special
// cases will continue to work. Search this file for "{ Ignore MLSLABEL field type on Oracle }".
if (FldDesc.iLen <= 0) then // and (FDBXCommand = nil) then
FldDesc.iUnits1 := 128 // default size (make constant)
else
FldDesc.iUnits1 := FldDesc.iLen;
TDBXDataTypes.AnsiStringType:
FldDesc.iUnits1 := FldDesc.iLen;
TDBXDataTypes.VarBytesType,
TDBXDataTypes.BytesType:
begin
// data size is in scale
FldDesc.iUnits1 := FldDesc.iUnits2;
FldDesc.iLen := FldDesc.iUnits2;
end;
end;
end;
end;
procedure TDBXReaderDataSet.InternalInitFieldDefs;
var
FID: Integer;
FieldDescs: TFieldDescList;
RequiredFields: TBits;
FldDescCount: Word;
begin
if (FDBXReader <> nil) then
begin
RequiredFields := TBits.Create;
try
FldDescCount := FDBXReader.ColumnCount;
SetLength(FieldDescs, FldDescCount);
for FID := 1 to FldDescCount do
FieldDescs[FID-1] := TFldDesc.Create;
try
RequiredFields.Size := FldDescCount + 1;
FieldDefs.Clear;
FID := 1;
FMaxColSize := FldDescCount;
while FID <= FldDescCount do
begin
RequiredFields[FID] := FDBXReader.ValueType[FID-1].Nullable = False;
LoadFieldDef(Word(FID), FieldDescs[0]);
if (FieldDescs[0].iLen > FMaxColSize) and
(FieldDescs[0].iFldType <> TDBXDataTypes.BlobType) then
FMaxColSize := (FMaxColSize + FieldDescs[0].iLen);
AddFieldDesc(FieldDescs, Integer(0), FID, RequiredFields, FieldDefs);
end;
finally
for FID := 1 to FldDescCount do
FreeAndNil(FieldDescs[FID-1]);
FieldDescs := nil;
end;
finally
RequiredFields.Free;
end;
end
else
DatabaseError(SDataSetClosed, self);
end;
{ Field and Record Access }
{$IFDEF NEXTGEN}
procedure NormalizeBcdData(FieldBuffer: TArray<Byte>; BcdData: TValueBuffer; Precision, Scale: Word);
{$ELSE}
procedure NormalizeBcdData(FieldBuffer: TArray<Byte>; BcdData: Pointer; Precision, Scale: Word);
{$ENDIF}
var
InBcd: TBcd;
LBcd: TBcd;
begin
if Assigned(BcdData) then
begin
if Precision > MaxFMTBcdDigits then Precision := MaxFMTBcdDigits;
InBcd := BcdFromBytes(FieldBuffer);
if (LBcd.SignSpecialPlaces = 38) and ((Scale and 63)in [38,0]) then
begin
if (Scale and (1 shl 7)) <> 0 then
NormalizeBcd(InBcd, LBcd, MaxFMTBcdDigits, Word((DefaultFMTBcdScale and 63) or (1 shl 7)))
else
NormalizeBcd(InBcd, LBcd, MaxFMTBcdDigits, DefaultFMTBcdScale);
end else
NormalizeBcd(InBcd, LBcd, Precision, Scale);
TPlatformValueBuffer.Copy(BcdToBytes(LBcd), 0, BcdData, SizeOfTBcd);
end;
end;
function TDBXReaderDataSet.GetFieldData(FieldNo: Integer; var Buffer: TValueBuffer): Boolean;
var
FldType, Precision, Scale: Word;
LBlank: LongBool;
Field: TField;
ByteReader: TDBXByteReader;
ByteBufferLength, DataLength, FieldDataSize, Ordinal: Integer;
ByteBuffer: TArray<Byte>;
BytesRead: Int64;
ValueType: TDBXValueType;
ValueStr: string;
M: TMarshaller;
begin
if (FDBXReader = nil) then
DatabaseError(SDataSetClosed, self);
// When EOF is True or we are dealing with a calculated field (FieldNo < 1)
// we should not be calling into the driver to get Data
//
if (FieldNo < 1) then
begin
Result := False;
Exit;
end;
if EOF and (not BOF) then
begin
Result := False;
Exit;
end;
if (EOF and BOF and FDBXReader.Closed) then
begin
Result := False;
Exit;
end;
LBlank := True;
Ordinal := FieldNo - 1;
ValueType := FDBXReader.ValueType[Ordinal];
DataLength := ValueType.Size;
FldType := ValueType.DataType;
if (Length(FFieldBuffer) < DataLength) and (FldType <> TDBXDataTypes.BlobType) then
SetLength(FFieldBuffer, DataLength);
ByteReader := FDBXReader.ByteReader;
begin
case FldType of
TDBXDataTypes.AnsiStringType:
begin
FillChar(FFieldBuffer[0], Length(FFieldBuffer), 0);
{$IFNDEF NEXTGEN}
if ByteReader <> nil then
ByteReader.GetAnsiString(Ordinal, FFieldBuffer, 0, LBlank)
else
{$ENDIF !NEXTGEN}
begin
ValueStr := FDBXReader.Value[Ordinal].AsString;
LBlank := FDBXReader.Value[Ordinal].IsNull;
if ValueStr.Length > 0 then
TMarshal.Copy(M.AsAnsi(ValueStr), FFieldBuffer, 0, ValueStr.Length);
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.WideStringType:
begin
FieldDataSize := FieldByNumber(FieldNo).DataSize;
if Length(FFieldBuffer) < FieldDataSize then
SetLength(FFieldBuffer, FieldDataSize);
FillChar(FFieldBuffer[0], Length(FFieldBuffer), 0);
if Assigned(ByteReader) then
ByteReader.GetWideString(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
ValueStr := FDBXReader.Value[Ordinal].AsString;
LBlank := FDBXReader.Value[Ordinal].IsNull;
if ValueStr.Length > 0 then
begin
ByteBuffer := TDBXPlatform.WideStrToBytes(ValueStr);
ByteBufferLength := Length(ByteBuffer);
TDBXPlatform.CopyByteArray(ByteBuffer, 0, FFieldBuffer, 0, ByteBufferLength);
end;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, FieldDataSize);
end;
TDBXDataTypes.UInt8Type:
begin
if Assigned(ByteReader) then
ByteReader.GetUInt8(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyUInt8(FDBXReader.Value[Ordinal].AsUInt8, FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.Int8Type:
begin
if Assigned(ByteReader) then
ByteReader.GetInt8(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyInt8(FDBXReader.Value[Ordinal].AsInt8, FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.Int16Type:
begin
if Assigned(ByteReader) then
ByteReader.GetInt16(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyInt16(FDBXReader.Value[Ordinal].AsInt16, FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.UInt16Type:
begin
if Assigned(ByteReader) then
ByteReader.GetInt16(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyUInt16(FDBXReader.Value[Ordinal].AsUInt16, FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.Int32Type, TDBXDataTypes.UInt32Type:
begin
if Assigned(ByteReader) then
ByteReader.GetInt32(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyInt32(FDBXReader.Value[Ordinal].AsInt32, FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.Int64Type:
begin
if Assigned(ByteReader) then
ByteReader.GetInt64(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyInt64(FDBXReader.Value[Ordinal].AsInt64, FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.SingleType:
begin
if Assigned(ByteReader) then
ByteReader.GetSingle(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyInt32(TDBXPlatform.SingleToInt32Bits(FDBXReader.Value[Ordinal].AsSingle), FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.DoubleType:
begin
if Assigned(ByteReader) then
ByteReader.GetDouble(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyInt64(TDBXPlatform.DoubleToInt64Bits(FDBXReader.Value[Ordinal].AsDouble), FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.CurrencyType, TDBXDataTypes.BcdType:
begin
Field := FieldByNumber(FieldNo);
if Length(FFieldBuffer) < Field.DataSize then
SetLength(FFieldBuffer, Field.DataSize);
if Assigned(ByteReader) then
ByteReader.GetBcd(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyBcd(FDBXReader.Value[Ordinal].AsBcd, FFieldBuffer, 0);
LBlank := False;
end;
if (not LBlank) and (Field <> nil) then
begin
if Field.DataType = ftBcd then
begin
Precision := TBcdField(Field).Precision;
Scale := TBcdField(Field).Size;
end else
begin
Precision := TFMTBcdField(Field).Precision;
Scale := TFMTBcdField(Field).Size;
end;
{$IFDEF NEXTGEN}
NormalizeBcdData(FFieldBuffer, Buffer, Precision, Scale);
{$ELSE}
NormalizeBcdData(FFieldBuffer, @Buffer[0], Precision, Scale);
{$ENDIF}
end;
end;
TDBXDataTypes.DateType:
begin
if Assigned(ByteReader) then
ByteReader.GetDate(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyInt32(FDBXReader.Value[Ordinal].AsDate, FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.TimeType:
begin
if Assigned(ByteReader) then
ByteReader.GetTime(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyInt32(FDBXReader.Value[Ordinal].AsTime, FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.TimeStampType:
begin
if Assigned(ByteReader) then
ByteReader.GetTimeStamp(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyInt64(TDBXPlatform.DoubleToInt64Bits(FDBXReader.Value[Ordinal].AsDateTime), FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.TimeStampOffsetType:
begin
ByteReader.GetTimeStampOffset(Ordinal, FFieldBuffer, 0, LBlank);
if not LBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.DateTimeType:
begin
if not FDBXReader.Value[Ordinal].IsNull then
begin
Field := FieldByNumber(FieldNo);
TDBXPlatform.CopyInt64(TDBXPlatform.DoubleToInt64Bits(FDBXReader.Value[Ordinal].AsDateTime), FFieldBuffer, 0);
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
DataConvert(Field, Buffer, Buffer, True);
LBlank := False;
end
end;
TDBXDataTypes.BooleanType:
begin
if Assigned(ByteReader) then
ByteReader.GetInt16(Ordinal, FFieldBuffer, 0, LBlank)
else
begin
TDBXPlatform.CopyInt16(FDBXReader.Value[Ordinal].AsInt16, FFieldBuffer, 0);
LBlank := False;
end;
if not LBlank then
// DbxClient returns DataSize of 1, but we are reading 2 bytes.
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, 2);//DataLength);
end;
TDBXDataTypes.VarBytesType:
begin
DataLength := FDBXReader.ValueType[Ordinal].Size;
SetLength(ByteBuffer, DataLength+2);
if Assigned(ByteReader) then
BytesRead := ByteReader.GetBytes(Ordinal, 0, ByteBuffer, 2, DataLength, LBlank)
else
begin
BytesRead := FDBXReader.Value[Ordinal].GetBytes(0, ByteBuffer, 2, DataLength);
LBlank := False;
end;
ByteBuffer[0] := BytesRead;
ByteBuffer[1] := BytesRead shr 8;
if not LBlank then
TPlatformValueBuffer.Copy(ByteBuffer, 0, Buffer, DataLength+2);
end;
TDBXDataTypes.BytesType:
begin
DataLength := FDBXReader.ValueType[Ordinal].Size;
SetLength(ByteBuffer, DataLength);
if Assigned(ByteReader) then
ByteReader.GetBytes(Ordinal, 0, ByteBuffer, 0, DataLength, LBlank)
else
begin
FDBXReader.Value[Ordinal].GetBytes(0, ByteBuffer, 0, DataLength);
LBlank := False;
end;
if not LBlank then
TPlatformValueBuffer.Copy(ByteBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.BlobType:
begin
// DataLength := GetBlobLength(Self, FieldNo);
if CurrentBlobSize = 0 then
LBlank := True
else
begin
if Assigned(ByteReader) then
begin
// Temporary for bug 249185. Needs to be fixed properly for both managed
// and native in a better way than this. This change will keep things
// working the same way they did in bds2006.
// Need to modify all drivers to return 0 bytes read if they cannot read
// a blob twice. The temporary change below is also an optimization for
// blobs since it avoids a copy of the blob. This is not the right way
// to fix this. Solution should solve the problem for both native and
// managed. One option is to duplicate blob read code from the TSQLBlobStream
// class. Virtually all apps will go through a blob stream to access blob
// data. However there is a path to this method though TField.GetData.
// Sure would be nice if TDataSet could manage record buffers as TArray<Byte>.
// sshaughnessy 2007.04.19.
//
if Buffer = FBlobBuffer then
begin
ByteBuffer := TArray<Byte>(Buffer);
ByteReader.GetBytes(Ordinal, 0, ByteBuffer, 0, CurrentBlobSize, LBlank);
end else
begin
SetLength(ByteBuffer, CurrentBlobSize);
ByteReader.GetBytes(Ordinal, 0, ByteBuffer, 0, CurrentBlobSize, LBlank);
if not LBlank then
TPlatformValueBuffer.Copy(ByteBuffer, 0, Buffer, CurrentBlobSize);
end;
end
else
begin
SetLength(ByteBuffer, CurrentBlobSize);
FDBXReader.Value[Ordinal].GetBytes(0, ByteBuffer, 0, CurrentBlobSize);
TPlatformValueBuffer.Copy(ByteBuffer, 0, Buffer, CurrentBlobSize);
end;
end;
end;
end;
end;
// SetLength(FFieldBuffer, 1);
Result := not LBlank;
end;
function TDBXReaderDataSet.GetFieldData(Field: TField; var Buffer: TValueBuffer): Boolean;
var
FieldNo: Word;
TempBuffer: TValueBuffer;
ThisBuffer: TValueBuffer;
BlobSize: Int64;
BlobNull: LongBool;
begin
if not Self.Active then
DataBaseError(SDatasetClosed);
FieldNo := Field.FieldNo;
if not Assigned(Buffer) then
begin
if Field.IsBlob then
begin
if EOF then
BlobNull := True
else
FDBXReader.ByteReader.GetByteLength(Word(FieldNo)-1, BlobSize, BlobNull);
Result := not Boolean(BlobNull);
Exit;
end
else if Field.Size > Field.DataSize then
TempBuffer := TPlatformValueBuffer.CreateValueBuffer(Field.Size)
else
TempBuffer := TPlatformValueBuffer.CreateValueBuffer(Field.DataSize);
ThisBuffer := TempBuffer;
end else
begin
ThisBuffer := Buffer;
TempBuffer := nil;
end;
try
if Field.FieldNo < 1 then
{$IFDEF NEXTGEN}
Result := GetCalculatedField(Field, ThisBuffer)
{$ELSE}
Result := GetCalculatedField(Field, @ThisBuffer[0])
{$ENDIF}
else
Result := GetFieldData(FieldNo, ThisBuffer);
finally
if Assigned(TempBuffer) then
TPlatformValueBuffer.Free(TempBuffer);
end;
end;
{$IFNDEF NEXTGEN}
function TDBXReaderDataSet.GetFieldData(FieldNo: Integer; Buffer: Pointer): Boolean;
var
FldType: Word;
FBlank: LongBool;
Field: TField;
Precision, Scale: Word;
ByteReader: TDBXByteReader;
Ordinal: Integer;
ByteBuffer: TArray<Byte>;
DataLength, ByteBufferLength: Integer;
BytesRead: Int64;
ValueType: TDBXValueType;
FieldDataSize: Integer;
ValueStr: string;
begin
if (FDBXReader = nil) then
DatabaseError(SDataSetClosed, self);
// When EOF is True or we are dealing with a calculated field (FieldNo < 1)
// we should not be calling into the driver to get Data
//
if (FieldNo < 1) then
begin
Result := False;
Exit;
end;
if EOF and (not BOF) then
begin
Result := False;
Exit;
end;
if (EOF and BOF and FDBXReader.Closed) then
begin
Result := False;
Exit;
end;
FBlank := True;
Ordinal := FieldNo - 1;
ValueType := FDBXReader.ValueType[Ordinal];
DataLength := ValueType.Size;
FldType := ValueType.DataType;
if (Length(FFieldBuffer) < DataLength) and (FldType <> TDBXDataTypes.BlobType) then
SetLength(FFieldBuffer, DataLength);
ByteReader := FDBXReader.ByteReader;
begin
case FldType of
TDBXDataTypes.AnsiStringType:
begin
FillChar(FFieldBuffer[0], Length(FFieldBuffer), 0);
if ByteReader <> nil then
ByteReader.GetAnsiString(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
ValueStr := FDBXReader.Value[Ordinal].AsString;
if ValueStr.Length > 0 then
begin
ByteBuffer := TDBXPlatform.AnsiStrToBytes(AnsiString(ValueStr));
ByteBufferLength := Length(ByteBuffer);
TDBXPlatform.CopyByteArray(ByteBuffer, 0, FFieldBuffer, 0, ByteBufferLength);
FBlank := ByteBufferLength = 0;
end;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.WideStringType:
begin
FieldDataSize := FieldByNumber(FieldNo).DataSize;
if Length(FFieldBuffer) < FieldDataSize then
SetLength(FFieldBuffer, FieldDataSize);
FillChar(FFieldBuffer[0], Length(FFieldBuffer), 0);
if Assigned(ByteReader) then
ByteReader.GetWideString(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
ValueStr := FDBXReader.Value[Ordinal].AsString;
if ValueStr.Length > 0 then
begin
ByteBuffer := TDBXPlatform.WideStrToBytes(ValueStr);
ByteBufferLength := Length(ByteBuffer);
TDBXPlatform.CopyByteArray(ByteBuffer, 0, FFieldBuffer, 0, ByteBufferLength);
FBlank := ByteBufferLength = 0;
end;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, FieldDataSize);
end;
TDBXDataTypes.UInt8Type:
begin
if Assigned(ByteReader) then
ByteReader.GetUInt8(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyUInt8(FDBXReader.Value[Ordinal].AsUInt8, FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.Int8Type:
begin
if Assigned(ByteReader) then
ByteReader.GetInt8(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyInt8(FDBXReader.Value[Ordinal].AsInt8, FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.Int16Type:
begin
if Assigned(ByteReader) then
ByteReader.GetInt16(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyInt16(FDBXReader.Value[Ordinal].AsInt16, FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.UInt16Type:
begin
if Assigned(ByteReader) then
ByteReader.GetInt16(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyUInt16(FDBXReader.Value[Ordinal].AsUInt16, FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.Int32Type, TDBXDataTypes.UInt32Type:
begin
if Assigned(ByteReader) then
ByteReader.GetInt32(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyInt32(FDBXReader.Value[Ordinal].AsInt32, FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.Int64Type:
begin
if Assigned(ByteReader) then
ByteReader.GetInt64(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyInt64(FDBXReader.Value[Ordinal].AsInt64, FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.SingleType:
begin
if Assigned(ByteReader) then
ByteReader.GetSingle(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyInt32(TDBXPlatform.SingleToInt32Bits(FDBXReader.Value[Ordinal].AsSingle), FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.DoubleType:
begin
if Assigned(ByteReader) then
ByteReader.GetDouble(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyInt64(TDBXPlatform.DoubleToInt64Bits(FDBXReader.Value[Ordinal].AsDouble), FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.CurrencyType, TDBXDataTypes.BcdType:
begin
Field := FieldByNumber(FieldNo);
if Length(FFieldBuffer) < Field.DataSize then
SetLength(FFieldBuffer, Field.DataSize);
if Assigned(ByteReader) then
ByteReader.GetBcd(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyBcd(FDBXReader.Value[Ordinal].AsBcd, FFieldBuffer, 0);
FBlank := False;
end;
if (not FBlank) and (Field <> nil) then
begin
if Field.DataType = ftBcd then
begin
Precision := TBcdField(Field).Precision;
Scale := TBcdField(Field).Size;
end else
begin
Precision := TFMTBcdField(Field).Precision;
Scale := TFMTBcdField(Field).Size;
end;
NormalizeBcdData(FFieldBuffer, Buffer, Precision, Scale);
end;
end;
TDBXDataTypes.DateType:
begin
if Assigned(ByteReader) then
ByteReader.GetDate(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyInt32(FDBXReader.Value[Ordinal].AsDate, FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.TimeType:
begin
if Assigned(ByteReader) then
ByteReader.GetTime(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyInt32(FDBXReader.Value[Ordinal].AsTime, FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.TimeStampType:
begin
if Assigned(ByteReader) then
ByteReader.GetTimeStamp(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyInt64(TDBXPlatform.DoubleToInt64Bits(FDBXReader.Value[Ordinal].AsDateTime), FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.TimeStampOffsetType:
begin
ByteReader.GetTimeStampOffset(Ordinal, FFieldBuffer, 0, FBlank);
if not FBlank then
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.DateTimeType:
begin
if not FDBXReader.Value[Ordinal].IsNull then
begin
Field := FieldByNumber(FieldNo);
TDBXPlatform.CopyInt64(TDBXPlatform.DoubleToInt64Bits(FDBXReader.Value[Ordinal].AsDateTime), FFieldBuffer, 0);
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, DataLength);
DataConvert(Field, Buffer, Buffer, True);
FBlank := False;
end
end;
TDBXDataTypes.BooleanType:
begin
if Assigned(ByteReader) then
ByteReader.GetInt16(Ordinal, FFieldBuffer, 0, FBlank)
else
begin
TDBXPlatform.CopyInt16(FDBXReader.Value[Ordinal].AsInt16, FFieldBuffer, 0);
FBlank := False;
end;
if not FBlank then
// DbxClient returns DataSize of 1, but we are reading 2 bytes.
TPlatformValueBuffer.Copy(FFieldBuffer, 0, Buffer, 2);//DataLength);
end;
TDBXDataTypes.VarBytesType:
begin
DataLength := FDBXReader.ValueType[Ordinal].Size;
SetLength(ByteBuffer, DataLength+2);
if Assigned(ByteReader) then
BytesRead := ByteReader.GetBytes(Ordinal, 0, ByteBuffer, 2, DataLength, FBlank)
else
begin
BytesRead := FDBXReader.Value[Ordinal].GetBytes(0, ByteBuffer, 2, DataLength);
FBlank := False;
end;
ByteBuffer[0] := BytesRead;
ByteBuffer[1] := BytesRead shr 8;
if not FBlank then
TPlatformValueBuffer.Copy(ByteBuffer, 0, Buffer, DataLength+2);
end;
TDBXDataTypes.BytesType:
begin
DataLength := FDBXReader.ValueType[Ordinal].Size;
SetLength(ByteBuffer, DataLength);
if Assigned(ByteReader) then
ByteReader.GetBytes(Ordinal, 0, ByteBuffer, 0, DataLength, FBlank)
else
begin
FDBXReader.Value[Ordinal].GetBytes(0, ByteBuffer, 0, DataLength);
FBlank := False;
end;
if not FBlank then
TPlatformValueBuffer.Copy(ByteBuffer, 0, Buffer, DataLength);
end;
TDBXDataTypes.BlobType:
begin
// DataLength := GetBlobLength(Self, FieldNo);
if CurrentBlobSize = 0 then
FBlank := True
else
begin
if Assigned(ByteReader) then
begin
// Temporary for bug 249185. Needs to be fixed properly for both managed
// and native in a better way than this. This change will keep things
// working the same way they did in bds2006.
// Need to modify all drivers to return 0 bytes read if they cannot read
// a blob twice. The temporary change below is also an optimization for
// blobs since it avoids a copy of the blob. This is not the right way
// to fix this. Solution should solve the problem for both native and
// managed. One option is to duplicate blob read code from the TSQLBlobStream
// class. Virtually all apps will go through a blob stream to access blob
// data. However there is a path to this method though TField.GetData.
// Sure would be nice if TDataSet could manage record buffers as TArray<Byte>.
// sshaughnessy 2007.04.19.
//
if Buffer = FBlobBuffer then
begin
ByteBuffer := TArray<Byte>(Buffer);
ByteReader.GetBytes(Ordinal, 0, ByteBuffer, 0, CurrentBlobSize, FBlank);
end else
begin
SetLength(ByteBuffer, CurrentBlobSize);
ByteReader.GetBytes(Ordinal, 0, ByteBuffer, 0, CurrentBlobSize, FBlank);
if not FBlank then
TPlatformValueBuffer.Copy(ByteBuffer, 0, Buffer, CurrentBlobSize);
end;
end
else
begin
SetLength(ByteBuffer, CurrentBlobSize);
FDBXReader.Value[Ordinal].GetBytes(0, ByteBuffer, 0, CurrentBlobSize);
TPlatformValueBuffer.Copy(ByteBuffer, 0, Buffer, CurrentBlobSize);
end;
end;
end;
end;
end;
// SetLength(FFieldBuffer, 1);
Result := not FBlank;
end;
function TDBXReaderDataSet.GetFieldData(Field: TField; Buffer: Pointer): Boolean;
var
FieldNo: Word;
TempBuffer: TValueBuffer;
ThisBuffer: Pointer;
BlobSize: Int64;
BlobNull: LongBool;
begin
if not Self.Active then
DataBaseError(SDatasetClosed);
FieldNo := Field.FieldNo;
if not Assigned(Buffer) then
begin
if Field.IsBlob then
begin
if EOF then
BlobNull := True
else
FDBXReader.ByteReader.GetByteLength(Word(FieldNo)-1, BlobSize, BlobNull);
Result := not Boolean(BlobNull);
Exit;
end
else if Field.Size > Field.DataSize then
TempBuffer := TPlatformValueBuffer.CreateValueBuffer(Field.Size)
else
TempBuffer := TPlatformValueBuffer.CreateValueBuffer(Field.DataSize);
ThisBuffer := TempBuffer;
end else
begin
ThisBuffer := Buffer;
TempBuffer := nil;
end;
try
if Field.FieldNo < 1 then
Result := GetCalculatedField(Field, ThisBuffer)
else
Result := GetFieldData(FieldNo, ThisBuffer);
finally
if Assigned(TempBuffer) then
TPlatformValueBuffer.Free(TempBuffer);
end;
end;
{$ENDIF !NEXTGEN}
procedure TDBXReaderDataSet.SetCurrentBlobSize(Value: Int64);
begin
if Value > FCurrentBlobSize then
SetLength(FBlobBuffer, Value);
FCurrentBlobSize := Value;
end;
function TDBXReaderDataSet.GetBlobFieldData(FieldNo: Integer; var Buffer: TBlobByteData): Integer;
var
IsNull: LongBool;
Ordinal: Integer;
begin
Result := 0;
Ordinal := FieldNo - 1;
GetBlobLength(Self, FieldNo);
if (FDBXReader = nil) then
DatabaseError(SDataSetClosed, self);
if FCurrentBlobSize > 0 then
begin
if LongWord(Length(Buffer)) < CurrentBlobSize then
SetLength(Buffer, CurrentBlobSize);
FDBXReader.ByteReader.GetBytes(Ordinal, 0, TArray<Byte>(Buffer), 0, FCurrentBlobSize, IsNull);
if not IsNull then
Result := CurrentBlobSize;
end;
end;
constructor TDBXReaderDataSet.Create(AOwner: TComponent; DBXReader: TDBXReader; AOwnsInstance: Boolean);
begin
Create(AOwner);
FProvidedDBXReader := true;
FOwnsProvidedDBXReader := AOwnsInstance;
FDBXReader := DBXReader;
// DBXReader's connection properties as well (if possible), but for now, we can set this to
// the default value otherwise assuming it is unspecified there
if FMaxBlobSize = 0 then // means it hasn't been changed
FMaxBlobSize := DefaultMaxBlobSize;
end;
function TDBXReaderDataSet.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
begin
Result := TDBXReaderDataSet.TBlobStream.Create(Field as TBlobField, Mode);
end;
procedure TDBXReaderDataSet.SetFieldData(Field: TField; Buffer: TValueBuffer);
var
RecBuf: TArray<Byte>;
begin
RecBuf := FCalcFieldsBuffer;
if Field.FieldNo < 1 then //{fkCalculated}
begin
if Assigned(Buffer) then
begin
RecBuf[Field.Offset] := 1;
TPlatformValueBuffer.Copy(Buffer, RecBuf, Field.Offset+1, Field.DataSize);
end
else
RecBuf[Field.Offset] := 0;
end;
end;
{$IFNDEF NEXTGEN}
procedure TDBXReaderDataSet.SetFieldData(Field: TField; Buffer: Pointer);
var
RecBuf: TArray<Byte>;
begin
RecBuf := FCalcFieldsBuffer;
if Field.FieldNo < 1 then //{fkCalculated}
begin
if Assigned(Buffer) then
begin
RecBuf[Field.Offset] := 1;
Move(Buffer^, RecBuf[Field.Offset+1], Field.DataSize);
end
else
RecBuf[Field.Offset] := 0;
end;
end;
{$ENDIF !NEXTGEN}
{$IFDEF NEXTGEN}
function TDBXReaderDataSet.GetCalculatedField(Field: TField; Buffer: TValueBuffer): Boolean;
{$ELSE !NEXTGEN}
function TDBXReaderDataSet.GetCalculatedField(Field: TField; Buffer: Pointer): Boolean;
{$ENDIF !NEXTGEN}
var
RecBuf: TArray<Byte>;
begin
Result := False;
RecBuf := FCalcFieldsBuffer;
if Field.FieldNo < 1 then //{fkCalculated}
begin
if Boolean(RecBuf[Field.Offset]) then
begin
TPlatformValueBuffer.Copy(RecBuf, Field.Offset+1, Buffer, Field.DataSize);
Result := True;
end;
end;
end;
function TDBXReaderDataSet.GetCanModify: Boolean;
begin
Result := False;
end;
function TDBXReaderDataSet.GetRecord(Buffer: TRecBuf; GetMode: TGetMode; DoCheck: Boolean): TGetResult;
begin
if FDBXReader.Next then
begin
GetCalcFields(Buffer);
if Buffer <> 0 then
Move(PByte(Buffer)[0], FCalcFieldsBuffer[0], Length(FCalcFieldsBuffer));
Result := grOK
end
else
Result := grEOF;
end;
{$IFNDEF NEXTGEN}
function TDBXReaderDataSet.GetRecord(Buffer: TRecordBuffer; GetMode: TGetMode; DoCheck: Boolean): TGetResult;
begin
if FDBXReader.Next then
begin
GetCalcFields(Buffer);
if Buffer <> nil then
Move(Buffer^, FCalcFieldsBuffer[0], Length(FCalcFieldsBuffer));
Result := grOK
end
else
Result := grEOF;
end;
{$ENDIF !NEXTGEN}
{ Query Management }
procedure TDBXReaderDataSet.SetPrepared(Value: Boolean);
var
Complete: Boolean;
begin
if FProvidedDBXReader then
FPrepared := Value
else
FreeReader;
if Value <> Prepared then
begin
try
if Value then
begin
FRowsAffected := -1;
FCheckRowsAffected := True;
end
else
begin
if FCheckRowsAffected then
FRowsAffected := RowsAffected;
FreeCommand;
end;
FPrepared := Value;
except
FPrepared := False;
end;
Complete := false;
if Value then
try
FRowsAffected := -1;
FCheckRowsAffected := True;
Complete := true;
finally
if not Complete then
FPrepared := False;
end
else
try
if FCheckRowsAffected then
FRowsAffected := RowsAffected;
FreeCommand;
except
FPrepared := False;
end;
FPrepared := Value;
end;
end;
function TDBXReaderDataSet.GetQueryFromType: string;
begin
if (FSortFieldNames > '') then
Result := SOrderBy + FSortFieldNames
else
Result := '';
end;
function TDBXReaderDataSet.GetRecordCount: Integer;
begin
Result := FRecords;
end;
function TDBXReaderDataSet.GetRowsAffected: Integer;
var
UpdateCount: LongWord;
begin
if FRowsAffected > 0 then
Result := Integer(FRowsAffected)
else
begin
UpdateCount := 0;
FRowsAffected := Integer(UpdateCount);
Result := Integer(UpdateCount);
end;
end;
function TDBXReaderDataSet.GetSortFieldNames: string;
begin
Result := FSortFieldNames;
end;
procedure TDBXReaderDataSet.SetSortFieldNames(Value: string);
begin
if Value <> FSortFieldNames then
begin
CheckInactive;
FSortFieldNames := Value;
SetPrepared(False);
end;
end;
procedure TDBXReaderDataSet.SetMaxBlobSize(MaxSize: Integer);
begin
FMaxBlobSize := MaxSize;
end;
procedure TDBXReaderDataSet.PropertyChanged;
begin
if not (csLoading in ComponentState) then
begin
SetPrepared(False);
FRecords := -1;
FreeCommand;
if SortFieldNames <> '' then
FSortFieldNames := '';
end;
end;
{ Miscellaneous }
function TDBXReaderDataSet.IsSequenced: Boolean;
begin
Result := False;
end;
procedure TDBXReaderDataSet.InternalHandleException;
begin
end;
{ Index Support }
procedure TDBXReaderDataSet.UpdateIndexDefs;
begin
end;
{ ProviderSupport }
procedure TDBXReaderDataSet.PSEndTransaction(Commit: Boolean);
begin
end;
procedure TDBXReaderDataSet.PSExecute;
begin
inherited;
end;
function TDBXReaderDataSet.PSExecuteStatement(const ASQL: string; AParams: TParams): Integer;
begin
Result := inherited;
end;
function TDBXReaderDataSet.PSExecuteStatement(const ASQL: string; AParams: TParams;
var ResultSet: TDataSet): Integer;
begin
Result := inherited;
end;
{$IFNDEF NEXTGEN}
function TDBXReaderDataSet.PSExecuteStatement(const ASQL: string; AParams: TParams;
ResultSet: Pointer): Integer;
begin
Result := inherited;
end;
{$ENDIF !NEXTGEN}
procedure TDBXReaderDataSet.PSGetAttributes(List: TPacketAttributeList);
begin
inherited PSGetAttributes(List);
end;
function TDBXReaderDataSet.PSGetIndexDefs(IndexTypes: TIndexOptions): TIndexDefs;
begin
Result := GetIndexDefs(IndexDefs, IndexTypes);
end;
function TDBXReaderDataSet.PSGetDefaultOrder: TIndexDef;
function FieldsInQuery(IdxFields: string): Boolean;
var
I: Integer;
IdxFlds, Flds: TStrings;
FldNames: string;
begin
Result := True;
IdxFlds := TStringList.Create;
try
IdxFlds.CommaText := IdxFields;
Flds := TStringList.Create;
try
Fields.GetFieldNames(Flds);
FldNames := Flds.CommaText;
for I := 0 to IdxFlds.Count -1 do
begin
if FldNames.IndexOf(IdxFlds[I]) = -1 then
begin
Result := False;
Exit;
end;
end;
finally
Flds.Free;
end;
finally
IdxFlds.Free;
end;
end;
var
I: Integer;
begin
Result := inherited PSGetDefaultOrder;
if not Assigned(Result) then
Result := GetIndexForOrderBy(GetQueryFromType, Self);
if not Assigned(Result) then
begin
for I := 0 to IndexDefs.Count - 1 do
begin
if (ixPrimary in TIndexDef(IndexDefs[I]).Options) and
FieldsInQuery(TIndexDef(IndexDefs[I]).Fields) then
begin
Result := TIndexDef.Create(nil);
Result.Assign(IndexDefs[I]);
Break;
end;
end;
end;
end;
function TDBXReaderDataSet.PSGetKeyFields: string;
var
HoldPos, I: Integer;
IndexFound: Boolean;
begin
Result := inherited PSGetKeyFields;
IndexFound := False;
if Result = '' then
begin
for I := 0 to IndexDefs.Count - 1 do
if (ixUnique in IndexDefs[I].Options) or
(ixPrimary in IndexDefs[I].Options) then
begin
Result := IndexDefs[I].Fields;
IndexFound := (FieldCount = 0);
if not IndexFound then
begin
HoldPos := 1;
while HoldPos <= Result.Length do
begin
IndexFound := FindField(ExtractFieldName(Result, HoldPos)) <> nil;
if not IndexFound then Break;
end;
end;
if IndexFound then Break;
end;
if not IndexFound then
Result := '';
end;
end;
function TDBXReaderDataSet.PSGetParams: TParams;
begin
Result := inherited;
end;
function TDBXReaderDataSet.PSGetQuoteChar: string;
begin
Result := '';
end;
procedure TDBXReaderDataSet.PSReset;
begin
inherited PSReset;
if Active and (not BOF) then
First;
end;
function TDBXReaderDataSet.PSGetTableName: string;
begin
Result := inherited;
end;
function TDBXReaderDataSet.PSGetUpdateException(E: Exception; Prev: EUpdateError): EUpdateError;
begin
Result := inherited;
end;
function TDBXReaderDataSet.PSInTransaction: Boolean;
begin
Result := inherited;
end;
function TDBXReaderDataSet.PSIsSQLBased: Boolean;
begin
Result := True;
end;
function TDBXReaderDataSet.PSIsSQLSupported: Boolean;
begin
Result := True;
end;
procedure TDBXReaderDataSet.PSSetParams(AParams: TParams);
begin
Close;
end;
procedure TDBXReaderDataSet.PSSetCommandText(const ACommandText: string);
begin
end;
procedure TDBXReaderDataSet.PSStartTransaction;
begin
inherited;
end;
function TDBXReaderDataSet.PSUpdateRecord(UpdateKind: TUpdateKind; Delta: TDataSet): Boolean;
begin
{ OnUpdateRecord is not supported }
Result := False;
end;
function TDBXReaderDataSet.PSGetCommandText: string;
begin
Result := inherited;
end;
function TDBXReaderDataSet.PSGetCommandType: TPSCommandType;
begin
Result := inherited;
end;
function TDBXReaderDataSet.LocateRecord(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions; SyncCursor: Boolean): Boolean;
function SameValue(V1, V2: Variant; IsString, CaseInsensitive,
PartialLength: Boolean): Boolean;
var
V: Variant;
begin
if not IsString then
Result := VarCompareValue(V1, V2) = vrEqual
else
begin
if PartialLength then
V := string(V1).Substring(0, string(V2).Length)
else
V := V1;
if CaseInsensitive then
Result := string(V).ToLower = string(V2).ToLower
else
Result := V = V2;
end;
end;
function CheckValues(AFields: TStrings; Values: Variant;
CaseInsensitive, PartialLength: Boolean): Boolean;
var
J: Integer;
Field: TField;
begin
Result := True;
for J := 0 to AFields.Count -1 do
begin
Field := FieldByName(AFields[J]);
if not SameValue(Field.Value, Values[J],
Field.DataType in [ftString, ftFixedChar, ftWideString, ftFixedWideChar], CaseInsensitive, PartialLength) then
begin
Result := False;
break;
end;
end;
end;
var
I: Integer;
SaveFields, AFields: TStrings;
PartialLength, CaseInsensitive: Boolean;
Values, StartValues: Variant;
bFound: Boolean;
begin
CheckBrowseMode;
CursorPosChanged;
AFields := TStringList.Create;
SaveFields := TStringList.Create;
try
AFields.CommaText := StringReplace(KeyFields, ';', ',', [rfReplaceAll]);
PartialLength := loPartialKey in Options;
CaseInsensitive := loCaseInsensitive in Options;
if VarIsArray(KeyValues) then
Values := KeyValues
else
Values := VarArrayOf([KeyValues]);
{ save current record in case we cannot locate KeyValues }
StartValues := VarArrayCreate([0, FieldCount], varVariant);
for I := 0 to FieldCount -1 do
begin
StartValues[I] := Fields[I].Value;
SaveFields.Add(Fields[I].FieldName);
end;
First;
while not EOF do
begin
if CheckValues(AFields, Values, CaseInsensitive, PartialLength) then
break;
Next;
end;
{ if not found, reset cursor to starting position }
bFound := not EOF;
if not bFound then
begin
First;
while not EOF do
begin
if CheckValues(SaveFields, StartValues, False, False) then
break;
Next;
end;
end;
Result := bFound;
finally
AFields.Free;
SaveFields.Free;
end;
end;
function TDBXReaderDataSet.Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean;
begin
DoBeforeScroll;
Result := LocateRecord(KeyFields, KeyValues, Options, True);
if Result then
begin
Resync([rmExact, rmCenter]);
DoAfterScroll;
end;
end;
function TDBXReaderDataSet.Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant;
begin
Result := Null;
if LocateRecord(KeyFields, KeyValues, [], False) then
begin
SetTempState(dsCalcFields);
try
CalculateFields(0);
Result := FieldValues[ResultFields];
finally
RestoreState(dsBrowse);
end;
end;
end;
end.
|
unit ufrmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ActnList, diocp.tcp.server, ExtCtrls,
ComCtrls, utils.safeLogger, diocp.ex.server;
type
TfrmMain = class(TForm)
edtPort: TEdit;
btnOpen: TButton;
actlstMain: TActionList;
actOpen: TAction;
actStop: TAction;
btnDisconectAll: TButton;
pgcMain: TPageControl;
TabSheet1: TTabSheet;
tsLog: TTabSheet;
mmoLog: TMemo;
pnlMonitor: TPanel;
btnGetWorkerState: TButton;
btnFindContext: TButton;
pnlTop: TPanel;
tmrKickOut: TTimer;
chkLogDetails: TCheckBox;
procedure actOpenExecute(Sender: TObject);
procedure actStopExecute(Sender: TObject);
procedure btnDisconectAllClick(Sender: TObject);
procedure btnFindContextClick(Sender: TObject);
procedure btnGetWorkerStateClick(Sender: TObject);
procedure btnPostWSACloseClick(Sender: TObject);
procedure chkLogDetailsClick(Sender: TObject);
procedure tmrKickOutTimer(Sender: TObject);
private
iCounter:Integer;
FTcpServer: TDiocpStringTcpServer;
procedure RefreshState;
procedure OnContextStringAction(pvContext: TDiocpStringContext; pvDataString:
String);
procedure OnAccept(pvSocket: THandle; pvAddr: String; pvPort: Integer; var
vAllowAccept: Boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses
uFMMonitor, diocp.core.engine, diocp.core.rawWinSocket;
{$R *.dfm}
constructor TfrmMain.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
sfLogger.setAppender(TStringsAppender.Create(mmoLog.Lines));
sfLogger.AppendInMainThread := true;
TStringsAppender(sfLogger.Appender).MaxLines := 5000;
FTcpServer := TDiocpStringTcpServer.Create(Self);
FTcpServer.Name := 'iocpSVR';
FTcpServer.OnContextStringAction := OnContextStringAction;
FTcpServer.OnContextAccept := OnAccept;
FTcpServer.createDataMonitor;
TFMMonitor.createAsChild(pnlMonitor, FTcpServer);
end;
destructor TfrmMain.Destroy;
begin
inherited Destroy;
end;
procedure TfrmMain.RefreshState;
begin
if FTcpServer.Active then
begin
btnOpen.Action := actStop;
end else
begin
btnOpen.Action := actOpen;
end;
end;
procedure TfrmMain.actOpenExecute(Sender: TObject);
begin
FTcpServer.Port := StrToInt(edtPort.Text);
// 设置最大数据包长度
FTcpServer.SetMaxDataLen(1024);
// 设置开始字符串
FTcpServer.SetPackStartStr('#');
// 设置结束字符串
FTcpServer.SetPackEndStr('!');
FTcpServer.Active := true;
RefreshState;
end;
procedure TfrmMain.actStopExecute(Sender: TObject);
begin
FTcpServer.SafeStop;
RefreshState;
end;
procedure TfrmMain.btnDisconectAllClick(Sender: TObject);
begin
FTcpServer.DisConnectAll();
end;
procedure TfrmMain.btnFindContextClick(Sender: TObject);
var
lvList:TList;
i:Integer;
begin
lvList := TList.Create;
try
FTcpServer.GetOnlineContextList(lvList);
for i:=0 to lvList.Count -1 do
begin
FTcpServer.FindContext(TIocpClientContext(lvList[i]).SocketHandle);
end;
finally
lvList.Free;
end;
end;
procedure TfrmMain.btnGetWorkerStateClick(Sender: TObject);
begin
ShowMessage(FTcpServer.IocpEngine.getWorkerStateInfo(0));
end;
procedure TfrmMain.btnPostWSACloseClick(Sender: TObject);
var
lvList:TList;
i:Integer;
begin
lvList := TList.Create;
try
FTcpServer.GetOnlineContextList(lvList);
for i:=0 to lvList.Count -1 do
begin
TIocpClientContext(lvList[i]).PostWSACloseRequest();
end;
finally
lvList.Free;
end;
end;
procedure TfrmMain.chkLogDetailsClick(Sender: TObject);
begin
if chkLogDetails.Checked then
begin
FTcpServer.Logger.LogFilter := LogAllLevels;
end else
begin
FTcpServer.Logger.LogFilter := [lgvError]; // 只记录致命错误
end;
end;
procedure TfrmMain.OnAccept(pvSocket: THandle; pvAddr: String; pvPort: Integer;
var vAllowAccept: Boolean);
begin
// if pvAddr = '127.0.0.1' then
// vAllowAccept := false;
end;
procedure TfrmMain.OnContextStringAction(pvContext: TDiocpStringContext;
pvDataString: String);
begin
sfLogger.logMessage(pvDataString);
// 可以把一个数据直接写回去
pvContext.WriteAnsiString(pvDataString);
end;
procedure TfrmMain.tmrKickOutTimer(Sender: TObject);
begin
FTcpServer.KickOut(30000);
end;
end.
|
// HRParser v1.0.1 (25.Sep.2000)
// Simple and fast parser classes.
// by Colin A Ridgewell
//
// Copyright (C) 1999,2000 Hayden-R Ltd
// http://www.haydenr.com
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with this program (gnu_license.htm); if not, write to the
//
// Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// To contact us via e-mail use the following addresses...
//
// bug@haydenr.u-net.com - to report a bug
// support@haydenr.u-net.com - for general support
// wishlist@haydenr.u-net.com - add new requirement to wish list
//
unit HRParser;
interface
uses
Classes, SysUtils, HRBuffers;
type
THRTokenType = Byte;
const
HR_PARSER_STREAM_BUFFER_SIZE = 2048; {bytes}
HR_PARSER_TOKEN_BUFFER_SIZE = 1024; {bytes}
{THRParser tokens}
HR_TOKEN_NIL = 0;
HR_TOKEN_EOF = 1;
HR_TOKEN_CHAR = 2;
{THRParserText tokens}
HR_TOKEN_TEXT_SPACE = 3;
HR_TOKEN_TEXT_SYMBOL = 4;
HR_TOKEN_TEXT_INTEGER = 5;
HR_TOKEN_TEXT_FLOAT = 6;
type
THRToken = record
Token: PChar;
TokenType: THRTokenType;
SourcePos: Longint;
Line: Longint;
LinePos: Integer;
end;
THRParser = class( TObject )
private
function GetSource: TStream;
procedure SetSource(Value: TStream);
procedure SetSourcePos(Value: LongInt);
protected
FSourceBuf: THRBufferStream;
FSourcePos: LongInt;
FLine: Longint;
FLineStartSourcePos: Longint;
FTokenBuf: THRBufferChar;
FToken: THRToken;
procedure IncLine;
procedure SkipToSourcePos(const Pos: Longint);
procedure SkipBlanks;
procedure GetNextToken; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
property Source: TStream read GetSource write SetSource;
property SourcePos: Longint read FSourcePos write SetSourcePos;
property Token: THRToken read FToken;
function NextToken: THRToken;
end;
THRParserText = class( THRParser )
private
protected
procedure GetNextToken; override;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
{ T H R P a r s e r }
constructor THRParser.Create;
begin
FSourceBuf := THRBufferStream.Create;
FSourceBuf.Size := HR_PARSER_STREAM_BUFFER_SIZE;
FTokenBuf := THRBufferChar.Create;
FTokenBuf.Size := HR_PARSER_TOKEN_BUFFER_SIZE;
FSourcePos := 0;
end;
destructor THRParser.Destroy;
begin
FTokenBuf.Free;
FTokenBuf := nil;
FSourceBuf.Free;
FSourceBuf := nil;
inherited Destroy;
end;
function THRParser.GetSource: TStream;
begin
Result := FSourceBuf.Stream;
end;
procedure THRParser.SetSource(Value: TStream);
begin
FSourceBuf.Stream := Value;
end;
procedure THRParser.SetSourcePos(Value: LongInt);
begin
SkipToSourcePos( Value );
end;
procedure THRParser.IncLine;
begin
Inc( FLine );
FLineStartSourcePos := FSourcePos;
end;
procedure THRParser.SkipToSourcePos(const Pos: Longint);
begin
FSourcePos := 0;
FLine := 0;
FLineStartSourcePos := 0;
FSourceBuf[ FSourcePos ];
while not FSourceBuf.EOB and ( FSourcePos < Pos ) do
begin
if FSourceBuf[ FSourcePos ] = #10 then IncLine;
Inc( FSourcePos );
FSourceBuf[ FSourcePos ];
end;
end;
procedure THRParser.SkipBlanks;
begin
FSourceBuf[ FSourcePos ];
while not FSourceBuf.EOB do
begin
case FSourceBuf[ FSourcePos ] of
#32..#255 : Exit;
#10 : IncLine;
end;
Inc( FSourcePos );
FSourceBuf[ FSourcePos ];
end;
end;
procedure THRParser.GetNextToken;
begin
FSourceBuf[ FSourcePos ];
if not FSourceBuf.EOB then
begin
{single char}
FTokenBuf.Write( FSourceBuf[ FSourcePos ] );
Inc( FSourcePos );
FToken.TokenType := HR_TOKEN_CHAR;
end
else
begin
{end of buffer}
FToken.TokenType := HR_TOKEN_EOF;
end;
end;
function THRParser.NextToken: THRToken;
begin
FTokenBuf.Position := 0;
SkipBlanks;
{store start pos of token}
with FToken do
begin
SourcePos := FSourcePos;
Line := FLine;
LinePos := FSourcePos - FLineStartSourcePos;
end;
GetNextToken;
FTokenBuf.Write( #0 ); {null terminate.}
FToken.Token := FTokenBuf.Buffer;
Result := FToken;
end;
{ T H R P a r s e r T e x t }
constructor THRParserText.Create;
begin
inherited Create;
end;
destructor THRParserText.Destroy;
begin
inherited Destroy;
end;
procedure THRParserText.GetNextToken;
begin
repeat
{spaces}
if FSourceBuf[ FSourcePos ] = ' ' then
begin
FTokenBuf.Write( FSourceBuf[ FSourcePos ] );
Inc( FSourcePos );
while FSourceBuf[ FSourcePos ] = ' ' do
begin
FTokenBuf.Write( FSourceBuf[ FSourcePos ] );
Inc( FSourcePos );
end;
FToken.TokenType := HR_TOKEN_TEXT_SPACE;
Break;{out of repeat}
end;
{symbols}
if CharInSet(FSourceBuf[ FSourcePos ], [ 'A'..'Z', 'a'..'z', '_' ]) then
begin
FTokenBuf.Write( FSourceBuf[ FSourcePos ] );
Inc( FSourcePos );
while True do
begin
case FSourceBuf[ FSourcePos ] of
'A'..'Z', 'a'..'z', '0'..'9', '_' :
begin
FTokenBuf.Write( FSourceBuf[ FSourcePos ] );
Inc( FSourcePos );
end;
'''' :
begin{apostrophies}
if CharInSet(FSourceBuf[ FSourcePos + 1 ], [ 'A'..'Z', 'a'..'z', '0'..'9', '_' ]) then
begin
FTokenBuf.Write( FSourceBuf[ FSourcePos ] );
Inc( FSourcePos );
end
else
Break;
end;
'-' :
begin{hyphenated words}
if CharInSet(FSourceBuf[ FSourcePos + 1 ], [ 'A'..'Z', 'a'..'z', '0'..'9', '_' ]) then
begin
FTokenBuf.Write( FSourceBuf[ FSourcePos ] );
Inc( FSourcePos );
end
else
Break;
end;
else
Break;
end;{case}
end;
FToken.TokenType := HR_TOKEN_TEXT_SYMBOL;
Break;{out of repeat}
end;
{numbers}
if CharInSet(FSourceBuf[ FSourcePos ], [ '0'..'9' ]) or
( ( FSourceBuf[ FSourcePos ] = '-' ) and CharInSet(FSourceBuf[ FSourcePos + 1 ], [ '.', '0'..'9' ] )) then
begin
{integer numbers}
FTokenBuf.Write( FSourceBuf[ FSourcePos ] );
Inc( FSourcePos );
while CharInSet(FSourceBuf[ FSourcePos ], [ '0'..'9' ]) do
begin
FTokenBuf.Write( FSourceBuf[ FSourcePos ] );
Inc( FSourcePos );
FToken.TokenType := HR_TOKEN_TEXT_INTEGER;
end;
{floating point numbers}
while CharInSet(FSourceBuf[ FSourcePos ], [ '0'..'9', 'e', 'E', '+', '-' ]) or
( ( FSourceBuf[ FSourcePos ] = '.') and ( FSourceBuf[ FSourcePos + 1 ] <> '.' ) ) do
begin
FTokenBuf.Write( FSourceBuf[ FSourcePos ] );
Inc( FSourcePos );
FToken.TokenType := HR_TOKEN_TEXT_FLOAT;
end;
Break;{out of repeat}
end;
inherited GetNextToken;
{Break;}{out of repeat}
until( True );
end;
end.
|
{
This unit defines a custom Gauge descendant which improves the visibility
of the state of the test run. Instead of setting the background color, the
progress bar is painted in the test state color itself.
Copyright (c) 2011 by Graeme Geldenhuys
All rights reserved.
}
unit CustomGauge;
{$mode objfpc}{$H+}
interface
uses
fpg_base, fpg_main, fpg_gauge;
type
TGUIRunnerGauge = class(TfpgBaseGauge)
protected
procedure BarDraw; override;
procedure BackgroundDraw; override;
published
property Align;
property Anchors;
property BorderStyle;
property Color;
property Enabled;
property FirstColor;
property Hint;
property Kind;
property MaxValue;
property MinValue;
property ParentShowHint;
property Progress;
property SecondColor;
property ShowHint;
property ShowText;
property Visible;
property OnShowHint;
end;
implementation
{ TGUIRunnerGauge }
procedure TGUIRunnerGauge.BarDraw;
var
BarLength: Longint;
SavedRect: TfpgRect;
begin
SavedRect := FClientRect; // save client rect for text !!
with FClientRect do
begin
case FKind of
gkHorizontalBar:
begin
{ now paint as normal }
BarLength := Longint(Trunc( (Width * Percentage) / 100.0 ) );
if BarLength > 0 then
begin
if BarLength > Width then
BarLength := Width;
Width := BarLength;
// left top
Canvas.SetColor(fpgLighter(Color, 45));
Canvas.DrawLine(Left, Bottom, Left, Top); // left
Canvas.DrawLine(Left, Top, Right, Top); // top
// right bottom
Canvas.SetColor(fpgDarker(Color, 45));
Canvas.DrawLine(Right, Top, Right, Bottom); // right
Canvas.DrawLine(Right, Bottom, Left, Bottom); // bottom
// inside gradient fill
InflateRect(FClientRect, -1, -1);
Canvas.GradientFill(FClientRect, Color, fpgLighter(Color, 45), gdVertical);
end; { if }
FClientRect := SavedRect;
end;
gkVerticalBar:
begin
inherited BarDraw;
end;
end; { case }
end; { FClientRect }
end;
procedure TGUIRunnerGauge.BackgroundDraw;
begin
FClientRect.SetRect(0, 0, Width, Height);
with FClientRect do
begin
{ Kind specific Bacground }
case FKind of
{ Currently Text doesn't require additional Bacground }
{ And so horizontal and vertical bar - Unless style requires it}
gkHorizontalBar:
begin
{Client area is Widget area, to start with}
Canvas.ClearClipRect;
Canvas.Clear(TfpgColor($c4c4c4));
{ This must be adjusted according the selected style }
Canvas.SetColor(TfpgColor($999999));
Canvas.SetLineStyle(1, lsSolid);
Canvas.DrawRectangle(FClientRect);
{ This must be completed and adjusted with border style }
InflateRect(FClientRect, -1, -1);
Canvas.SetLineStyle(1, lsSolid); // just in case background changed that
end;
else
begin
inherited BackgroundDraw;
end;
end;
end; { with }
end;
end.
|
{ *************************************************************************** }
{ SynWebReqRes.pas is the 2nd file of SynBroker Project }
{ by c5soft@189.cn Version 0.9.2.1 2018-6-7 }
{ *************************************************************************** }
unit SynWebReqRes;
interface
uses SysUtils, Classes, HTTPApp, SynCommons, SynCrtSock, SynWebEnv;
const
// Request Header String
cstInHeaderMethod = 0; // string
cstInHeaderProtocolVersion = 1; // string
cstInHeaderURL = 2; // string
cstInHeaderQuery = 3; // string
cstInHeaderPathInfo = 4; // string
cstInHeaderPathTranslated = 5; // string
cstInHeaderCacheControl = 6; // string
cstInHeaderAccept = 8; // string
cstInHeaderFrom = 9; // string
cstInHeaderHost = 10; // string
cstInHeaderReferer = 12; // string
cstInHeaderUserAgent = 13; // string
cstInContentEncoding = 14; // string
cstInContentType = 15; // string
cstInContentVersion = 17; // string
cstInHeaderDerivedFrom = 18; // string
cstInHeaderTitle = 20; // string
cstInHeaderRemoteAddr = 21; // string
cstInHeaderRemoteHost = 22; // string
cstInHeaderScriptName = 23; // string
cstInContent = 25; // string
cstInHeaderConnection = 26; // string
cstInHeaderCookie = 27; // string
cstInHeaderAuthorization = 28; // string
// Request Header Integer
cstInContentLength = 16; // Integer
cstInHeaderServerPort = 24; // Integer
// Request Header DateTime
cstInHeaderDate = 7; // TDateTime
cstInHeaderIfModifiedSince = 11; // TDateTime
cstInHeaderExpires = 19; // TDateTime
// Response Header String
cstOutHeaderVersion = 0; // string
cstOutHeaderReasonString = 1; // string
cstOutHeaderServer = 2; // string
cstOutHeaderWWWAuthenticate = 3; // string
cstOutHeaderRealm = 4; // string
cstOutHeaderAllow = 5; // string
cstOutHeaderLocation = 6; // string
cstOutHeaderContentEncoding = 7; // string
cstOutHeaderContentType = 8; // string
cstOutHeaderContentVersion = 9; // string
cstOutHeaderDerivedFrom = 10; // string
cstOutHeaderTitle = 11; // string
// Response Header Integer
cstOutHeaderContentLength = 0; // Integer
// Response Header DateTime
cstOutHeaderDate = 0; // TDateTime
cstOutHeaderExpires = 1; // TDateTime
cstOutHeaderLastModified = 2; // TDateTime
// Ver 0.0.0.2 +
// CompilerVersion<Delphi2009 or CompilerVersion>Delphi 10 Seattle
type
{$IF (CompilerVersion<20.0) OR (CompilerVersion>=30.0) }
WBString = string;
{$ELSE}
WBString = AnsiString;
{$IFEND}
TSynWebRequest = class(TWebRequest)
private
function GetContext: THttpServerRequest;
protected
FEnv: TSynWebEnv;
function GetStringVariable(Index: Integer): WBString; override;
function GetDateVariable(Index: Integer): TDateTime; override;
function GetIntegerVariable(Index: Integer): Integer; override;
function GetInternalPathInfo: WBString; override;
function GetInternalScriptName: WBString; override;
{$IFDEF UNICODE}
function GetRemoteIP: string; override;
{$ENDIF}
{$IF CompilerVersion>=30.0}
function GetRawContent: TBytes; override;
{$IFEND}
public
property Context: THttpServerRequest read GetContext;
property Env: TSynWebEnv read FEnv;
constructor Create(const AEnv: TSynWebEnv);
// Read count bytes from client
function ReadClient(var Buffer; Count: Integer): Integer; override;
// Read count characters as a WBString from client
function ReadString(Count: Integer): WBString; override;
// Translate a relative URI to a local absolute path
function TranslateURI(const URI: string): string; override;
// Write count bytes back to client
function WriteClient(var Buffer; Count: Integer): Integer; override;
// Write WBString contents back to client
function WriteString(const AString: WBString): Boolean; override;
// Write HTTP header WBString
function WriteHeaders(StatusCode: Integer;
const ReasonString, Headers: WBString): Boolean; override;
function GetFieldByName(const Name: WBString): WBString; override;
end;
TSynWebResponse = class(TWebResponse)
private
FSent: Boolean;
function GetContext: THttpServerRequest;
function GetEnv: TSynWebEnv;
protected
function GetStringVariable(Index: Integer): WBString; override;
procedure SetStringVariable(Index: Integer; const Value: WBString); override;
function GetDateVariable(Index: Integer): TDateTime; override;
procedure SetDateVariable(Index: Integer; const Value: TDateTime); override;
function GetIntegerVariable(Index: Integer): Integer; override;
procedure SetIntegerVariable(Index: Integer; Value: Integer); override;
function GetContent: WBString; override;
procedure SetContent(const Value: WBString); override;
procedure SetContentStream(Value: TStream); override;
function GetStatusCode: Integer; override;
procedure SetStatusCode(Value: Integer); override;
function GetLogMessage: string; override;
procedure SetLogMessage(const Value: string); override;
procedure OutCookiesAndCustomHeaders;
public
constructor Create(HTTPRequest: TWebRequest);
property Context: THttpServerRequest read GetContext;
property Env: TSynWebEnv read GetEnv;
procedure SendResponse; override;
procedure SendRedirect(const URI: WBString); override;
procedure SendStream(AStream: TStream); override;
function Sent: Boolean; override;
end;
// Ver 0.0.0.2 +
function UTF8ToWBString(const AVal: RawUTF8): WBString;
function WBStringToUTF8(const AVal: WBString): RawUTF8;
implementation
{$IF (CompilerVersion<20.0) OR (CompilerVersion>30.0) }
function UTF8ToWBString(const AVal: RawUTF8): WBString;
begin
Result := UTF8ToString(AVal);
end;
function WBStringToUTF8(const AVal: WBString): RawUTF8;
begin
Result := StringToUTF8(AVal);
end;
{$ELSE}
function UTF8ToWBString(const AVal: RawUTF8): WBString;
begin
Result := CurrentAnsiConvert.UTF8ToAnsi(AVal);
end;
function WBStringToUTF8(const AVal: WBString): RawUTF8;
begin
Result := CurrentAnsiConvert.AnsiToUTF8(AVal);
end;
{$IFEND}
{ TSynWebRequest }
constructor TSynWebRequest.Create(const AEnv: TSynWebEnv);
begin
FEnv := AEnv;
inherited Create;
end;
function TSynWebRequest.GetDateVariable(Index: Integer): TDateTime;
begin
Result := Now;
end;
function TSynWebRequest.GetFieldByName(const Name: WBString): WBString;
begin
Result := '';
end;
function TSynWebRequest.GetIntegerVariable(Index: Integer): Integer;
begin
if Index = cstInContentLength then
Result := StrToIntDef(UTF8ToString(FEnv.GetHeader('CONTENT-LENGTH:')), 0)
else if Index = cstInHeaderServerPort then Result := 80
else Result := 0;
end;
function TSynWebRequest.GetInternalPathInfo: WBString;
begin
Result := PathInfo;
end;
function TSynWebRequest.GetInternalScriptName: WBString;
begin
Result := '';
end;
{$IFDEF UNICODE}
function TSynWebRequest.GetRemoteIP: string;
begin
Result := UTF8ToString(FEnv.GetHeader('REMOTEIP:'));
end;
{$ENDIF}
{$IF CompilerVersion>=30.0}
function TSynWebRequest.GetRawContent: TBytes;
begin
RawByteStringToBytes(Context.InContent, Result);
end;
{$IFEND}
function TSynWebRequest.GetStringVariable(Index: Integer): WBString;
begin
if Index = cstInHeaderMethod then begin
Result := UTF8ToWBString(FEnv.Method);
end else if Index = cstInHeaderProtocolVersion then begin
Result := '';
end else if Index = cstInHeaderURL then begin
Result := UTF8ToWBString(FEnv.URL);
end else if Index = cstInHeaderQuery then begin
Result := UTF8ToWBString(URLDecode(FEnv.QueryString));
end else if Index = cstInHeaderPathInfo then begin
Result := UTF8ToWBString(FEnv.PathInfo);
end else if Index = cstInHeaderPathTranslated then begin
Result := UTF8ToWBString(FEnv.PathInfo);
end else if Index = cstInHeaderCacheControl then begin
Result := '';
end else if Index = cstInHeaderAccept then begin
Result := UTF8ToWBString(FEnv.GetHeader('ACCEPT:'));
end else if Index = cstInHeaderFrom then begin
Result := UTF8ToWBString(FEnv.GetHeader('FROM:'));
end else if Index = cstInHeaderHost then begin
Result := UTF8ToWBString(FEnv.GetHeader('HOST:'));
end else if Index = cstInHeaderReferer then begin
Result := UTF8ToWBString(FEnv.GetHeader('REFERER:'));
end else if Index = cstInHeaderUserAgent then begin
Result := UTF8ToWBString(FEnv.GetHeader('USER-AGENT:'));
end else if Index = cstInContentEncoding then begin
Result := UTF8ToWBString(FEnv.GetHeader('CONTENT-ENCODING:'));
end else if Index = cstInContentType then begin
Result := UTF8ToWBString(FEnv.GetHeader('CONTENT-TYPE:'));
end else if Index = cstInContentVersion then begin
Result := '';
end else if Index = cstInHeaderDerivedFrom then begin
Result := '';
end else if Index = cstInHeaderTitle then begin
Result := '';
end else if Index = cstInHeaderRemoteAddr then begin
Result := UTF8ToWBString(FEnv.GetHeader('REMOTEIP:'));
end else if Index = cstInHeaderRemoteHost then begin
Result := '';
end else if Index = cstInHeaderScriptName then begin
Result := '';
{$IF CompilerVersion<30.0} //Delphi 10.2 move this to function RawContent
end else if Index = cstInContent then begin
Result := Context.InContent;
{$IFEND}
end else if Index = cstInHeaderConnection then begin
Result := UTF8ToWBString(FEnv.GetHeader('CONNECTION:'));
end else if Index = cstInHeaderCookie then begin
Result := UTF8ToWBString(URLDecode(FEnv.GetHeader('COOKIE:')));
end else if Index = cstInHeaderAuthorization then begin
Result := '';
end;
end;
function TSynWebRequest.ReadClient(var Buffer; Count: Integer): Integer;
begin
Result := 0;
end;
function TSynWebRequest.ReadString(Count: Integer): WBString;
begin
Result := '';
end;
function TSynWebRequest.TranslateURI(const URI: string): string;
begin
Result := '';
end;
function TSynWebRequest.WriteClient(var Buffer; Count: Integer): Integer;
begin
Result := 0;
end;
function TSynWebRequest.WriteHeaders(StatusCode: Integer;
const ReasonString, Headers: WBString): Boolean;
begin
Result := False;
end;
function TSynWebRequest.WriteString(const AString: WBString): Boolean;
begin
Result := False;
end;
function TSynWebRequest.GetContext: THttpServerRequest;
begin
Result := FEnv.Context;
end;
{ TSynWebResponse }
constructor TSynWebResponse.Create(HTTPRequest: TWebRequest);
begin
Inherited Create(HTTPRequest);
FSent:=False;
end;
function TSynWebResponse.GetContent: WBString;
begin
Result := UTF8ToWBString(Context.OutContent);
end;
function TSynWebResponse.GetContext: THttpServerRequest;
begin
Result := TSynWebRequest(FHTTPRequest).Context;
end;
function TSynWebResponse.GetDateVariable(Index: Integer): TDateTime;
begin
Result := Now;
end;
function TSynWebResponse.GetEnv: TSynWebEnv;
begin
Result := TSynWebRequest(FHTTPRequest).Env;
end;
function TSynWebResponse.GetIntegerVariable(Index: Integer): Integer;
begin
Result := 0;
end;
function TSynWebResponse.GetLogMessage: string;
begin
Result := '';
end;
function TSynWebResponse.GetStatusCode: Integer;
begin
Result := Env.StatusCode;
end;
function TSynWebResponse.GetStringVariable(Index: Integer): WBString;
begin
Result := '';
if Index = cstOutHeaderContentType then
Result := UTF8ToWBString(Context.OutContentType);
end;
procedure TSynWebResponse.OutCookiesAndCustomHeaders;
var
i: Integer;
begin
for i := 0 to Cookies.Count - 1 do
Env.OutHeader(StringToUTF8('Set-Cookie: ' + Cookies[i].HeaderValue));
for i := 0 to CustomHeaders.Count - 1 do
Env.OutHeader(StringToUTF8(CustomHeaders.Names[i] + ': ' + CustomHeaders.Values[CustomHeaders.Names[i]]));
end;
procedure TSynWebResponse.SendRedirect(const URI: WBString);
begin
Env.Redirect(URI);
FSent := True;
end;
procedure TSynWebResponse.SendResponse;
begin
OutCookiesAndCustomHeaders;
FSent := True;
end;
procedure TSynWebResponse.SendStream(AStream: TStream);
begin
Env.OutStream(AStream);
end;
function TSynWebResponse.Sent: Boolean;
begin
Result := FSent;
end;
procedure TSynWebResponse.SetContent(const Value: WBString);
begin
Context.OutContent := WBStringToUTF8(Value);
end;
procedure TSynWebResponse.SetContentStream(Value: TStream);
begin
inherited;
SendStream(Value);
end;
procedure TSynWebResponse.SetDateVariable(Index: Integer;
const Value: TDateTime);
begin
end;
procedure TSynWebResponse.SetIntegerVariable(Index, Value: Integer);
begin
end;
procedure TSynWebResponse.SetLogMessage(const Value: string);
begin
end;
procedure TSynWebResponse.SetStatusCode(Value: Integer);
begin
Env.StatusCode := Value;
end;
procedure TSynWebResponse.SetStringVariable(Index: Integer;
const Value: WBString);
begin
if Index = cstOutHeaderContentType then
Context.OutContentType := WBStringToUTF8(Value);
end;
initialization
//RegisterContentParser(TContentParser);
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.Bind.Consts;
interface
resourcestring
SBindingComponentsCategory = 'LiveBindings';
SInvalidBindCompRegistration = 'Invalid LiveBinding registration';
SInvalidBindCompUnregistration = 'Invalid LiveBinding unregistration';
SInvalidBindCompEnumeration = 'Invalid LiveBinding enumeration';
SInvalidBindCompCreation = 'Invalid LiveBinding creation';
SInvalidBindCompFactory = 'Invalid LiveBinding factory';
SInvalidBindCompFactoryEnumeration = 'Invalid LiveBinding factory enumeration';
SInvalidBindCompDesigner = 'Invalid LiveBinding designer';
SInvalidBindCompComponents = 'Invalid data bound components';
sArgCount = 'Unexpected argument count';
sNameAttr = 'Name';
sControlAttr = 'Control Expression';
sSourceAttr = 'Source Expression';
sIDAttr = 'ID';
sStateAttr = 'State';
sNotImplemented = 'Not implemented';
sNoEditor = 'Error in %0:s. No editor available for %1:s';
sNoEnumerator = 'Error in %0:s. No enumerator available for %1:s';
sNoInsertItem = 'Error in %0:s. Inserted item not available for %1:s';
sNoControl = 'Error in %0:s. No control component';
sNoControlObserverSupport = 'Error in %0:s. No observer support for %1:s';
sObjectValueExpected = 'TObject value expected';
sLinkFieldNotFound = 'Unable to determine field name';
sLinkUnexpectedGridCurrentType = 'Unexpected grid current type';
// Categories
SDataBindingsCategory_BindingExpressions = 'Binding Expressions';
SDataBindingsCategory_Links = 'Links';
SDataBindingsCategory_Lists = 'Lists';
SDataBindingsCategory_DBLinks = 'DB Links';
// Method
sCheckedState = 'CheckedState';
sCheckedStateDesc = 'Bidirectional method to either get the checked state of a control,'#13#10 +
'or set the checked state in a control'#13#10 +
'Example usage when binding to a TCheckBox:'#13#10 +
' CheckedState(Self)';
sSelectedText = 'SelectedText';
sSelectedTextDesc = 'Bidirectional method to either get the text selected in a control,'#13#10 +
'or set the text selected in a control'#13#10 +
'Example usage when binding to a TListBox:'#13#10 +
' SelectedText(Self)';
sSelectedItem = 'SelectedItem';
sSelectedItemDesc = 'Bidirectional method to either get the selected item in a control,'#13#10 +
'or set the selected item in a control'#13#10 +
'Example usage when binding to a TListBox:'#13#10 +
' SelectedItem(Self).Text';
//LinkObservers
sBindLinkIncompatible = 'Object must implement IBindLink';
sBindPositionIncompatible = 'Object must implement IBindPosition';
implementation
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by Sιrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_Network
* Implements engine generic network objects
***********************************************************************************************************************
}
{-$DEFINE DEBUGMODE}
{-$DEFINE NETDEBUG}
{
@abstract(Network)
@author(Sergio Flores <relfos@gmail.com>)
@created(March 18, 2005)
@lastmod(September 29, 2005)
The Network unit provides a solid client/server system.
Uses UDP, with support for reliable messages.
Version History
18/3/05 Added type definitions and DLL functions import definitions
24/3/05 Bug resolved: External declarations need the StdCall directive
Implemented LNetServer and LNetClient classes
25/3/05 Implemented master class LNetObject
WinSock routines are now methods of this class
LNetServer and LNetClient are now descendants of this class
Contains a message queueing system
Finally Client-Server sample doesnt fail connecting to server
Bug: The same Client is duplicated when enter the server
This is because of multiple Join packets send
Added AddClient and RemoveClient virtual methods
While watching the log files, some messages seem to be corrupted
Added EndOfMessage flag, to verify data integrity
Took me a whole day to remove all major bugs
Client-Server Network session now works stable
Added ConnectionStart and ConnectionEnd virtual methods
Bug: Only one client can connect to server
Other clients trying to connect will receive a duplicate GUID error
Fixed: Remove old debug code used to force duplicated GUIDs
3/6/05 Bug:Solved, Server side - Ping check wasnt working correctly.
All Clients were dropped instantly
The same Clients were droped constatly
The droped client wasnt notified of the disconection
26/6/05 NetClient.Connect() changed, now use a username and password method.
NetServer.Validate is used to validate users.
Default implementation validates any user/password
NetClient.Connect bug fixed
JoinTimer wasnt initialized to zero
Lesson -> Always initialize variables, even with zero
27/6/05 NetClient.Validate() now returns a error code instead of a boolean
Now NetClient checks if the conection was lost and disconnects.
28/6/05 CreateServerMessage() renamed to CreateMessage()
Added CreateExtendedMessage()
2/7/05 Fixed some bugs
Added Network Output/Input bandwith usage status
Added login with version check
Implemented Pong messages
3/7/05 Implemented server behavior, allows switching between
a small centered server, or a large scale aproach
The main diference is that when in large scale mode,
some broadcasts are avoided, like Client drops.
This reduces the server overload, but in order to
notify the other Clients, the server should
implement their own broadcasting system, with a
localized clustering selection.
The following event broadcasts are supressed
ClientJoin: The AddClient event should handle this
ClientLeave,
ClientDrop: The RemoveClient event should handle this
Fixed bug in server responding to Pong queries
Pong querie delay was too short, the overload was desneccessary
Now if the server doesnt respond in 5 seconds, a Pong message is sent
Then if the server doesnt respond in 15 seconds, the connection is shutdown
4/7/05 Implemented reliable message system
Just put a ERM instead of a EOM in the message tail
Then message will be resent until an ack is received
After 25 resends, the message will be ignored
Fixed reliable message system infinite loop
Download/Upload were switched
6/7/05 RM messages caused duplicated messages to be received
Added a GIDSliderWindow to check for duplicated messages
7/7/05 Implemented GIDFlush method
8/7/05 Implemented messages flags
The following flags are implemented
msgEOM - EndOfMessage, for integrity check
msgRM - Reliable Message
msgRMO - Reliable Message, no reply
msgNGID - Disable GID, Ignore duplicates
Fixed disconection bug
12/7/05 Added msgNGID flag to some server messages
Server no longer pings dead Clients
17/7/05 Remodeled and optimized opcode system
Now uses messages handlers
The new system also makes possible to replace default messages
Client now can resolve hostnames
Its possible now to connect to something like "xpow.gameserver.net"
Now reliable messages have individual resend timers
This reduces some desnecessary resends
19/7/05 GID messages now expire after some time
This removes the necessity of combining msgNGID and msgRM flags
Some network messagin problems fixed with this
24/7/05 RM message resend default timer changed to 1500 ms
22/8/05 Fixed memory leak with receive buffer
29/8/05 Fixed Client login bugs
Better debug log support
}
Unit TERRA_Network;
{$I terra.inc}
Interface
Uses SysUtils,
TERRA_Utils, TERRA_IO, TERRA_OS, TERRA_Sockets, TERRA_Application;
Const
//Message types
nmIgnore = 0; // Dummy message
nmPing = 1; // Ping message
nmUnused = 2; // Pong message
nmServerAck = 3; // Server ack,Ok
nmServerError = 4; // Server error
nmServerShutdown = 5; // Server shutdown
nmClientJoin = 6; // Asking permission to enter a server
nmClientDrop = 7; // Client drop
// Server error codes
errNoError = 0; // No error
errServerFull = 1; // Server is full, no more clients allowed
errDuplicatedGUID = 2; // Login GUID duplicated
errInvalidUsername = 3; // Username not valid
errInvalidServerCommand = 4; // Opcode invalid
errUsernameAlreadyInUse = 5; // Username is already used
errUsernameBanned = 6; // Username banned/not allowed
errInvalidVersion = 7; // Wrong client version
errInvalidPassword = 8; // Password not valid
errAlreadyConnected = 9; // account already connected
errConnectionFailed = 31; // Connection failed
errConnectionLost = 32; // Connection lost
errServerShutdown = 33; // Server was shutdown
errServerCrash = 34; // Server crashed
errKicked = 35; // Client was kicked
errConnectionTimeOut = 36; // Connection failed
MessageQueueSize=256;
MaxUserLength=10;
MaxPassLength=10;
SERVER_CONNECT_DURATION = 2000; //5000
SERVER_RETRY_FREQ = 750; // Connection to server retry frequency
ID_UNKNOWN = 65535; // Used for anonymous messages
PING_TIME = 1000; // Ping time
PONG_TIME = 2000; // Pong time
DROP_TIME = 50000; // A Client is kicked when his ping reaches this value
PING_REFRESH = 750; // Search for dead connections time frequency
PONG_REFRESH = 800; // Search for dead server time frequency
RMUPDATE_TIME = 1750; // Used for resending RM Messages
RMDEFAULT_RESEND = 2500; // Each message is resent after this time
RMMAX_RESENDS = 5; // Number of resends before a packet is deleted
GIDEXPIRE_TIME = 500; // GID messages are removed after expire time
Type
NetStatus = (nsDisconnected , nsConnected);
PMessageHeader = ^MessageHeader;
MessageHeader = Packed Record
Opcode:Byte;
Owner:Word;
Length:Word;
End;
// NetMessage
NetMessage = Class(MemoryStream)
Protected
Function GetOwner:Word;
Procedure SetOwner(Value: Word);
Function GetLength:Word;
Procedure SetLength(Value: Word);
Function GetOpcode: Byte;
Public
Constructor Create(Opcode:Byte);
Property Opcode:Byte Read GetOpcode;
Property Owner:Word Read GetOwner Write SetOwner;
Property Length:Word Read GetLength Write SetLength;
End;
MessageHandler = Procedure(Msg:NetMessage; Sock:Socket) Of Object;
NetObject = Class
Protected
_UDPSocket:Integer; //Socket handle
_Input:Cardinal; //Current input in bytes
_Output:Cardinal; //Current output in bytes
Function CreateSocket:Integer;
Function BindSocket(Port:Word):Integer;
Function SendPacket(Dest:SocketAddress; Sock:Socket; Msg:NetMessage):Boolean;
Function OnSendFail(Dest:SocketAddress; Sock:Socket; Msg:NetMessage):Boolean; Virtual;
Procedure OnPacketReceived(Sock:Socket; Msg:NetMessage); Virtual;
Public
_Name:AnsiString; // Local Client Name
_Address:SocketAddress; // Local Address
_Sender:SocketAddress; // Address of message sender
_HostName:AnsiString; // Local host name
_LocalID:Word; // Local ID
_Port:Word; // Local port
_Version:Word; // Object Version
_TotalDownload:Cardinal; // Session download total
_TotalUpload:Cardinal; // Session upload total
_NextUpdate:Cardinal; // Next IO check time
_Upload:Cardinal; // Current upload kb/s
_Download:Cardinal; // Current download kb/s
_OpcodeList:Array[0..255]Of MessageHandler;
// Encodes a message
EncodeMessage:Procedure (Data:PByteArray;Size:Integer);
// Decodes a message
DecodeMessage:Procedure (Data:PByteArray;Size:Integer);
Constructor Create(); //Creates a new object instance
Destructor Destroy;Reintroduce;Virtual; //Shutdown the object
Function MakeSocketAddress(Var SockAddr:SocketAddress; Port:Word; Hostname:AnsiString):SmallInt;
Function ReceivePacket(Sock:Socket):Boolean;
Procedure UpdateIO; //Updates upload/download status
Procedure Update;Virtual;Abstract; //Handles standart messages
Procedure AddHandler(Opcode:Byte; Handler:MessageHandler); Virtual;
// Validates a message
Function ValidateMessage(Msg:NetMessage):Boolean; Virtual; Abstract;
Procedure ReturnMessage(Sock:Socket; Msg:NetMessage); // Sends a message to the last sender
// Message Handlers -> Need one of this for each message type
Procedure InvalidMessage(Msg:NetMessage; Sock:Socket);
Procedure IgnoreMessage(Msg:NetMessage; Sock:Socket);
End;
NetworkManager = Class(ApplicationComponent)
Protected
_Objects:Array Of NetObject;
_ObjectCount:Integer;
Public
Procedure Update; Override;
Procedure AddObject(Obj:NetObject);
Procedure RemoveObject(Obj:NetObject);
Destructor Destroy; Override;
Class Function Instance:NetworkManager;
End;
Function GetMsgDesc(MsgId:Byte):AnsiString;
Function GetNetErrorDesc(ErrorCode:Word):AnsiString;
//Function CreateMessageWithWord(Opcode:Byte; Code:Word):NetMessage; // Creates a server message
Implementation
Uses TERRA_Error, TERRA_Log;
Var
_NetworkManager:ApplicationObject;
Function GetNetErrorDesc(ErrorCode:Word):AnsiString;
Begin
Case ErrorCode Of
errNoError: Result:='No error.';
errServerFull: Result:='Server full.';
errDuplicatedGUID: Result:='Duplicated GUID.';
errInvalidUsername: Result:='Invalid username.';
errInvalidPassword: Result:='Invalid password.';
errAlreadyConnected: Result:='Account already connected.';
errInvalidServerCommand:Result:='Invalid server command.';
errUserNameAlreadyInUse:Result:='Username already in use.';
errUserNameBanned: Result:='Username is banned.';
errInvalidVersion: Result:='Invalid version.';
errConnectionFailed: Result:='Unable to connect to server.';
errConnectionLost: Result:='Connection was lost.';
errServerShutdown: Result:='Server shutdown.';
errServerCrash: Result:='Server crash.';
errKicked: Result:='Kicked!';
Else Result:='Unknown server error.['+IntToString(ErrorCode)+']';
End;
End;
Function _GetOpcode(MsgId:Byte):AnsiString;
Begin
Result:='Unknown message type['+IntToString(MsgId)+']';
End;
Function GetMsgDesc(MsgId:Byte):AnsiString;
Begin
Case MsgId Of
nmServerAck: Result:='Server.Ack';
nmServerError: Result:='Server.Error';
nmServerShutdown: Result:='Server.Shutdown';
nmClientJoin: Result:='Client.Join';
nmClientDrop: Result:='Client drop';
nmIgnore: Result:='Ignore';
nmPing: Result:='Ping';
Else
Result := 'opcode #'+IntToString(MsgID);
End;
End;
Procedure LogMsg(Prefix:AnsiString;Msg:NetMessage;Postfix:AnsiString);
Var
S:AnsiString;
Begin
S:=Prefix+' "'+GetMsgDesc(Msg.Opcode)+'" Size='+IntToString(Msg.Length)+' ';
S:=S+Postfix;
Log(logDebug,'Network', S);
End;
{********************
LNetObject Class
********************}
Procedure NetObject.AddHandler(Opcode: Byte; Handler: MessageHandler);
Begin
Self._OpcodeList[Opcode] := Handler;
End;
Function NetObject.CreateSocket:Integer;
Begin
Result := TERRA_Sockets._socket(PF_INET, SOCK_DGRAM, 0); //Create a network socket
If Result = SOCKET_ERROR Then //Check for errors
Begin
RaiseError('Network.CreateSocket: Unable to open a socket.');
Result := SOCKET_ERROR;
Exit;
End;
MakeNonBlocking(Result, False);
End;
Function NetObject.MakeSocketAddress(Var SockAddr:SocketAddress; Port:Word; Hostname:AnsiString):SmallInt;
Var
IP:AnsiString;
Begin
Result:=0;
IP := LookupHostAddress(Hostname); //Resolve the server address
Log(logDebug, 'Network', 'Calling htons()');
SockAddr.Family := PF_INET; // Set the address format
SockAddr.Port := htons(Port); // Convert to network byte order (using htons) and set port
// Specify the IP
Log(logDebug, 'Network', 'Calling inet_addr()');
SockAddr.Address := inet_addr(PAnsiChar(IP));
FillChar(SockAddr.Zero[1],8,0); //Zero fill
//Check for error in IP
If SockAddr.Address=-1 Then
Begin
RaiseError('Network.'+_Name+'.MakeSocketAddress: Unable to resolve IP address from '+ Hostname +'.');
Result := SOCKET_ERROR;
Exit;
End;
Log(logDebug, 'Network', 'Socket is ready');
End;
Function NetObject.BindSocket(Port:Word):Integer;
Var
SocketInfo:SocketAddress;
Opv:Integer;
Begin
Opv:=1;
If (setsockOpt(_UDPSocket, SOL_Socket, SO_REUSEADDR,@Opv,SizeOf(Opv))=SOCKET_ERROR) Then
Begin
RaiseError('Network.'+_Name+'.BindSocket: Unable to change socket mode.');
Result:=SOCKET_ERROR;
Exit;
End;
SocketInfo.Family:=PF_INET; // Set the address format
SocketInfo.Port := htons(Port); // Convert to network byte order (using htons) and set port
SocketInfo.Address:=0; // Specify local IP
FillChar(SocketInfo.Zero[1],8,0); // Zero fill
// Bind socket
Result := bind(_UDPSocket, SocketInfo, SizeOf(SocketInfo));
//Check for errors
If Result=SOCKET_ERROR Then
Begin
RaiseError('Network.'+_Name+'.BindSocket: Unable to bind socket on port ' + IntToString(Port) + '.');
Exit;
End;
End;
Function NetObject.SendPacket(Dest:SocketAddress; Sock:Socket; Msg:NetMessage):Boolean;
Var
Len, Count:Integer;
N:Integer;
Timer:Cardinal;
P:PByte;
Begin
If (Sock.Closed) Then
Begin
Result := False;
Exit;
End;
Msg.Length := Msg.Position - SizeOf(MessageHeader);
{$IFDEF NETDEBUG}WriteLn('Packet size: ',Msg.Length);{$ENDIF}
//LogMsg(_Name+'.Send():',@Rm,' to '+GetIP(Dest.Address));
//EncodeMessage(Msg);
//Send packet
{$IFDEF NETDEBUG}WriteLn('Writing to socket');{$ENDIF}
Len := Msg.Length + SizeOf(MessageHeader);
Count := Len;
P := Msg.Buffer;
Timer := GetTime();
Repeat
N := Sock.Write(P, Count);
If (N = SOCKET_ERROR) Then
Begin
If Not Self.OnSendFail(Dest, Sock, Msg) Then
Begin
Result := False;
Exit;
End;
End;
If (N>0) Then
Begin
Inc(P, N);
Dec(Count, N);
End;
If (Count<=0) Then
Begin
Result := True;
Exit;
End;
Until (GetTime() - Timer > 500);
//Check for errors
Result := False;
//Log(logWarning,'Network',_Name+'.SendPacket: Socket error');
End;
{Procedure NetMessageDispatcher(Msg:Pointer);
Begin
If Msg = Nil Then
Exit;
_NetObject._OpcodeList[NetMessage(Msg).Opcode](NetMessage(Msg), Nil);
End;}
Function NetObject.ReceivePacket(Sock:Socket):Boolean;
Var
P:PByte;
N,Cnt, Rem:Longint;
ValidMsg:Boolean;
Header:MessageHeader;
Msg:NetMessage;
Begin
Result := False;
If (Sock = Nil) Then
Exit;
//T := GetTime();
{$IFDEF NETDEBUG}WriteLn('Reading from socket');{$ENDIF}
//Check for a message
Cnt := 0;
P := @Header;
Repeat
Rem := SizeOf(MessageHeader) - Cnt;
N := Sock.Read(P, Rem);
{$IFDEF NETDEBUG}WriteLn('Read result: ',N);{$ENDIF}
//Check for errors
If (N=SOCKET_ERROR) Or (N<=0) Then //There was no message waiting
Begin
Exit;
End;
Inc(Cnt, N);
Inc(P, N);
//Log(logDebug, 'Network', 'Received '+IntToString(N)+' bytes');
Until (Cnt>=SizeOf(MessageHeader));
Inc(_Input, SizeOf(MessageHeader) + Header.Length);
Msg := NetMessage.Create(Header.Opcode);
Msg.Resize(Header.Length + SizeOf(MessageHeader));
Msg.Seek(0);
Msg.Write(@Header, SizeOf(MessageHeader));
If (Header.Length>0) Then
Begin
P := Msg._Buffer;
Inc(P, SizeOf(MessageHeader));
Cnt := 0;
Repeat
Rem := Header.Length - Cnt;
N := Sock.Read(P, Rem);
//If (N=SOCKET_ERROR) Or (N<=0) Then //There was no message waiting
If (Sock.Closed) Then
Begin
Exit;
End;
Inc(Cnt, N);
Inc(P, N);
Until (Cnt >= Header.Length);
End;
OnPacketReceived(Sock, Msg);
{$IFDEF NETDEBUG}WriteLn('Validating message');{$ENDIF}
Msg.Seek(SizeOf(MessageHeader));
ValidMsg := ValidateMessage(Msg);
//WriteLn('Rec: ',Msg.Opcode);
If ValidMsg Then
Begin
{$IFDEF NETDEBUG}WriteLn('Invoking opcode ',Msg.Opcode);{$ENDIF}
If Assigned(_OpcodeList[Header.Opcode]) Then
Begin
Msg.Seek(SizeOf(MessageHeader));
_OpcodeList[Header.Opcode](Msg, Sock) // Call message handler
End;
End Else
If (Header.Opcode<>nmServerAck) Then
Log(logWarning,'Network','Network.'+_Name+'.Update: Invalid opcode ['+IntToString(Header.Opcode)+']');
DestroyObject(@Msg);
{$IFDEF NETDEBUG}WriteLn('Opcode ',Header.Opcode,' processed');{$ENDIF}
End;
Procedure NetObject.InvalidMessage(Msg:NetMessage; Sock:Socket);
Begin
Log(logError, 'Network', 'InvalidMessage: Unknown opcode.['+IntToString(Msg.Opcode)+']');
End;
Procedure NetObject.IgnoreMessage(Msg:NetMessage; Sock:Socket);
Begin
// do nothing
End;
Constructor NetObject.Create();
Var
I:Integer;
Begin
_Name:='NetObject';
_Upload := 0;
_Download := 0;
_Input := 0;
_Output := 0;
_TotalUpload := 0;
_TotalDownload := 0;
For I:=0 To 255 Do
_OpcodeList[I] := InvalidMessage;
_OpcodeList[nmIgnore] := IgnoreMessage;
_UDPSocket := -1;
End;
Destructor NetObject.Destroy;
Begin
If (_UDPSocket<>-1) Then
CloseSocket(_UDPSocket);
End;
Procedure NetObject.UpdateIO;
Begin
If GetTime>=_NextUpdate Then
Begin
_Download := _Input;
_Upload := _Output;
Inc(_TotalDownload, _Download);
Inc(_TotalUpload, _Upload);
_Input := 0;
_Output := 0;
_NextUpdate := GetTime+1000;
End;
End;
Procedure NetObject.ReturnMessage(Sock:Socket; Msg:NetMessage); //Sends a message to the last sender
Begin
SendPacket(_Sender, Sock, Msg);
End;
Destructor NetworkManager.Destroy;
Begin
_NetworkManager := Nil;
End;
Class Function NetworkManager.Instance:NetworkManager;
Begin
If Not Assigned(_NetworkManager) Then
_NetworkManager := InitializeApplicationComponent(NetworkManager, Nil);
Result := NetworkManager(_NetworkManager.Instance);
End;
Procedure NetworkManager.AddObject(Obj: NetObject);
Begin
Inc(_ObjectCount);
SetLength(_Objects, _ObjectCount);
_Objects[Pred(_ObjectCount)] := Obj;
End;
Procedure NetworkManager.RemoveObject(Obj: NetObject);
Var
I:Integer;
Begin
I := 0;
While (I<_ObjectCount) Do
If (_Objects[I] = Obj) Then
Begin
_Objects[I] := _Objects[Pred(_ObjectCount)];
Dec(_ObjectCount);
Exit;
End Else
Inc(I);
End;
Procedure NetworkManager.Update;
Var
I:Integer;
Begin
For I:=0 To Pred(_ObjectCount) Do
_Objects[I].Update();
End;
Function NetObject.OnSendFail(Dest: SocketAddress; Sock: Socket; Msg: NetMessage): Boolean;
Begin
Sleep(200);
Result := True;
End;
{$IFDEF DEBUGMODE}
Procedure NetLogFilter(S,S2:AnsiString);
Begin
WriteLn(S2);
End;
{$ENDIF}
Procedure NetObject.OnPacketReceived(Sock:Socket; Msg: NetMessage);
Begin
// do nothing
End;
{ NetMessage }
Constructor NetMessage.Create(Opcode: Byte);
Var
Header:MessageHeader;
Begin
Inherited Create(256);
Header.Opcode := Opcode;
Header.Owner := 0;
Header.Length := 0;
Self.Write(@Header, SizeOf(MessageHeader));
End;
Function NetMessage.GetLength: Word;
Var
Header:PMessageHeader;
Begin
Header := PMessageHeader(_Buffer);
Result := Header.Length;
End;
Function NetMessage.GetOpcode:Byte;
Var
Header:PMessageHeader;
Begin
Header := PMessageHeader(_Buffer);
Result := Header.Opcode;
End;
Function NetMessage.GetOwner: Word;
Var
Header:PMessageHeader;
Begin
Header := PMessageHeader(_Buffer);
Result := Header.Owner;
End;
Procedure NetMessage.SetLength(Value: Word);
Var
Header:PMessageHeader;
Begin
Header := PMessageHeader(_Buffer);
Header.Length := Value;
End;
Procedure NetMessage.SetOwner(Value: Word);
Var
Header:PMessageHeader;
Begin
Header := PMessageHeader(_Buffer);
Header.Owner := Value;
End;
Initialization
{$IFDEF DEBUGMODE}
Log.Instance.SetFilter(logDebug, NetLogFilter);
Log.Instance.SetFilter(logWarning, NetLogFilter);
{$ENDIF}
End.
|
// The caching is very primitive, and probably won't even help all that much in a real
// world situation. Enhancing the caching mechanism is left as an exercise for the user.
{$DEFINE DEBUG}
unit VMMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ExtListView, StdCtrls, ExtCtrls, CommCtrl, EnhListView;
type
{ Don't use huge pointers in here. It'll leak when the record is destroyed }
{ To avoid the leak, you'd have to reset all the strings back to '' before }
{ disposing of it. }
PVirtualItem = ^TVirtualItem;
TVirtualItem = packed record
ImageIndex: integer;
Title: string[255];
State: UINT;
SubText1: string[255];
SubText2: string[255];
end;
TForm1 = class(TForm)
AnExtListView: TdfsExtListView;
Panel1: TPanel;
ComboBox1: TComboBox;
Label1: TLabel;
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure AnExtListViewVMCacheHint(Sender: TObject;
var HintInfo: TNMCacheHint);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure AnExtListViewVMGetItemInfo(Sender: TObject; Item,
SubItem: Integer; var Mask: TLVVMMaskItems; var Image: Integer;
var Param: Longint; var State, StateMask, Indent: Integer;
var Text: string);
private
CacheStart,
CacheStop: integer;
ItemCache: TList;
NumItems: integer;
public
procedure PrepCache(FromIndex, ToIndex: integer);
function GetVirtualItem(Item: integer): TVirtualItem;
function CreateVirtualItem(Item: integer): PVirtualItem;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var
TmpIcon: TIcon;
begin
ItemCache := NIL;
ComboBox1.ItemIndex := 2;
with AnExtListView do begin
LargeImages := TImageList.Create(Self);
with LargeImages do begin
Width := GetSystemMetrics(SM_CXICON);
Height := GetSystemMetrics(SM_CYICON);
AddIcon(Application.Icon);
TmpIcon := TIcon.Create;
TmpIcon.Handle := LoadIcon(0, MakeIntResource(IDI_APPLICATION));
AddIcon(TmpIcon);
end;
SmallImages := TImageList.Create(Self);
with SmallImages do begin
Width := GetSystemMetrics(SM_CXSMICON);
Height := GetSystemMetrics(SM_CYSMICON);
AddIcon(Application.Icon);
AddIcon(TmpIcon);
TmpIcon.Free;
end;
end;
CacheStart := -1;
CacheStop := -1;
NumItems := 500;
AnExtListView.SetItemCountEx(NumItems, [lvsicfNoScroll]);
end;
procedure TForm1.FormDestroy(Sender: TObject);
var
x: integer;
begin
if ItemCache <> NIL then
begin
for x := ItemCache.Count-1 downto 0 do begin
Dispose(ItemCache[x]);
{$IFDEF DEBUG}
OutputDebugString(PChar('disposing at ' + inttostr(x) + #13#10));
{$ENDIF}
ItemCache.Delete(x);
end;
ItemCache.Free;
end;
AnExtListView.LargeImages.Free;
AnExtListView.SmallImages.Free;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
case ComboBox1.ItemIndex of
0: AnExtListView.ViewStyle := vsIcon;
1: AnExtListView.ViewStyle := vsList;
2: AnExtListView.ViewStyle := vsReport;
3: AnExtListView.ViewStyle := vsSmallIcon;
end;
end;
procedure TForm1.PrepCache(FromIndex, ToIndex: integer);
var
x: integer;
begin
if ItemCache = NIL then ItemCache := TList.Create;
if (FromIndex < CacheStart) or (ToIndex > CacheStop) then begin
// Free up the old cache items
if CacheStart > -1 then
for x := ItemCache.Count-1 downto 0 do begin
Dispose(ItemCache[x]);
{$IFDEF DEBUG}
OutputDebugString(PChar('disposing at ' + inttostr(x) + #13#10));
{$ENDIF}
ItemCache.Delete(x);
end;
// load the new cache items
CacheStart := FromIndex;
CacheStop := ToIndex;
for x := CacheStart to CacheStop do
begin
ItemCache.Add(CreateVirtualItem(x));
{$IFDEF DEBUG}
OutputDebugString(PChar('adding at ' + inttostr(x) + #13#10));
{$ENDIF}
end;
end;
end;
function TForm1.GetVirtualItem(Item: integer): TVirtualItem;
var
TmpItem: PVirtualItem;
begin
if (Item < CacheStart) or (Item > CacheStop) then begin
TmpItem := CreateVirtualItem(Item);
Result := TmpItem^;
Dispose(TmpItem);
end else
Result := PVirtualItem(ItemCache[Item-CacheStart])^;
end;
function TForm1.CreateVirtualItem(Item: integer): PVirtualItem;
begin
New(Result);
with Result^ do begin
if odd(Item) then
ImageIndex := 1
else
ImageIndex := 0;
State := 0;
Title := 'VM Test Item #'+IntToStr(Item);
SubText1 := 'Item #'+IntToStr(Item)+': Subitem 1';
SubText2 := 'Item #'+IntToStr(Item)+': Subitem 2';
end;
end;
procedure TForm1.AnExtListViewVMCacheHint(Sender: TObject;
var HintInfo: TNMCacheHint);
begin
with HintInfo do
PrepCache(iFrom, iTo);
end;
procedure TForm1.AnExtListViewVMGetItemInfo(Sender: TObject; Item,
SubItem: Integer; var Mask: TLVVMMaskItems; var Image: Integer;
var Param: Longint; var State, StateMask, Indent: Integer;
var Text: string);
var
AnItem: TVirtualItem;
begin
AnItem := GetVirtualItem(Item);
if lvifText in Mask then
case SubItem of
0: Text := AnItem.Title;
1: Text := AnItem.SubText1;
2: Text := AnItem.SubText2;
else
Text := '';
end;
if lvifImage in Mask then
Image := AnItem.ImageIndex;
if lvifParam in Mask then
Param := 0;
if lvifState in Mask then
State := State or AnItem.State;
if lvifIndent in Mask then
if odd(Item) then { Just to show indenting, no real reason for it }
Indent := 1
else
Indent := 0;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ListView_SetItemState(AnExtListView.Handle, -1, LVIS_SELECTED, LVIS_SELECTED);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
ListView_SetItemState(AnExtListView.Handle, -1, 0, LVIS_SELECTED);
end;
procedure TForm1.Button3Click(Sender: TObject);
var
i: integer;
s: string;
begin
s := 'Selected indices: ';
{ Look for next item starting at the top (-1) }
i := AnExtListView.ELV_GetNextItem(-1, sdAll, [isSelected]);
while i > -1 do
begin
s := s + IntToStr(i) + ' ';
{ Look for next item starting at last index found }
i := AnExtListView.ELV_GetNextItem(i, sdAll, [isSelected]);
end;
ShowMessage(s);
end;
end.
|
unit TestPombo;
interface
uses
TestFramework, System.SysUtils, VooDaPomba, DuckClass, Pruu, Pomba;
type
TestTPomba = class(TTestCase)
strict private
FPomba: TPomba;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure ClassTest_TipoPombo_TPomba;
procedure PruuTest_QuackPombo_Pruu;
procedure PombaTest_VooDoPombo_PruuVoando;
end;
implementation
{ TestTPomba }
procedure TestTPomba.ClassTest_TipoPombo_TPomba;
begin
CheckEquals(FPomba.ClassType, TPomba);
end;
procedure TestTPomba.PombaTest_VooDoPombo_PruuVoando;
begin
CheckEquals('Pruu Estou Voando e Cagando !', FPomba.Fly);
end;
procedure TestTPomba.PruuTest_QuackPombo_Pruu;
begin
CheckEquals('Pruuuuuuu sou um Pombo', FPomba.Quack);
end;
procedure TestTPomba.SetUp;
begin
inherited;
FPomba := TPomba.Create;
end;
procedure TestTPomba.TearDown;
begin
inherited;
FPomba.Free
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTPomba.Suite);
end.
|
unit uMarca;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, uDmMarca, Mask, DBCtrls, Grids, DBGrids, SMDBGrid,
db, Forms, StdCtrls, Buttons, ExtCtrls, Dialogs, RzTabs;
type
TfMarca = class(TForm)
RzPageControl1: TRzPageControl;
TS_Consulta: TRzTabSheet;
TS_Cadastro: TRzTabSheet;
Panel3: TPanel;
Label6: TLabel;
btnConsultar: TBitBtn;
Edit4: TEdit;
Panel2: TPanel;
btnInserir: TBitBtn;
btnExcluir: TBitBtn;
StaticText1: TStaticText;
SMDBGrid1: TSMDBGrid;
Panel1: TPanel;
btnConfirmar: TBitBtn;
btnCancelar: TBitBtn;
btnAlterar: TBitBtn;
RZPageControlDados: TRzPageControl;
pnlCadastro: TPanel;
Label1: TLabel;
Label8: TLabel;
DBEdit1: TDBEdit;
DBEdit2: TDBEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnInserirClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnConsultarClick(Sender: TObject);
procedure btnAlterarClick(Sender: TObject);
procedure btnConfirmarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure SMDBGrid1DblClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure Edit4KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure SMDBGrid1TitleClick(Column: TColumn);
private
{ Private declarations }
fDmMarca: TDmMarca;
procedure prc_Inserir_Registro;
procedure prc_Excluir_Registro;
procedure prc_Gravar_Registro;
procedure prc_Consultar;
public
{ Public declarations }
end;
var
fMarca: TfMarca;
implementation
uses UMenu, uDmDatabase, rsDBUtils;
{$R *.dfm}
procedure TfMarca.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := Cafree;
end;
procedure TfMarca.FormDestroy(Sender: TObject);
begin
FreeAndNil(fdmMarca);
end;
procedure TfMarca.FormShow(Sender: TObject);
begin
fdmMarca := TdmMarca.Create(Self);
oDBUtils.SetDataSourceProperties(Self, fdmMarca);
Edit4.SetFocus;
end;
procedure TfMarca.btnInserirClick(Sender: TObject);
begin
prc_Inserir_Registro;
end;
procedure TfMarca.btnExcluirClick(Sender: TObject);
begin
if fdmMarca.cdsMarca.IsEmpty then
exit;
if MessageDlg('Deseja excluir este registro?',mtConfirmation,[mbYes,mbNo],0) = mrNo then
exit;
prc_Excluir_Registro;
end;
procedure TfMarca.btnConsultarClick(Sender: TObject);
begin
prc_Consultar;
end;
procedure TfMarca.btnAlterarClick(Sender: TObject);
begin
if (fdmMarca.cdsMarca.IsEmpty) or not(fdmMarca.cdsMarca.Active) or
(fdmMarca.cdsMarcaID.AsInteger < 1) then
exit;
fdmMarca.cdsMarca.Edit;
TS_Consulta.TabEnabled := False;
btnAlterar.Enabled := False;
btnConfirmar.Enabled := True;
pnlCadastro.Enabled := True;
end;
procedure TfMarca.btnConfirmarClick(Sender: TObject);
begin
prc_Gravar_Registro;
end;
procedure TfMarca.btnCancelarClick(Sender: TObject);
begin
if (fdmMarca.cdsMarca.State in [dsBrowse]) or not(fdmMarca.cdsMarca.Active) then
begin
RzPageControl1.ActivePage := TS_Consulta;
exit;
end;
if MessageDlg('Deseja cancelar alteração/inclusão do registro?',mtConfirmation,[mbYes,mbNo],0) = mrNo then
exit;
fdmMarca.cdsMarca.CancelUpdates;
TS_Consulta.TabEnabled := True;
RzPageControl1.ActivePage := TS_Consulta;
btnConfirmar.Enabled := False;
btnAlterar.Enabled := True;
pnlCadastro.Enabled := False;
end;
procedure TfMarca.prc_Consultar;
begin
fdmMarca.cdsMarca.Close;
fdmMarca.sdsMarca.CommandText := fdmMarca.ctCommand;
fdmMarca.sdsMarca.CommandText := fdmMarca.sdsMarca.CommandText + ' WHERE 1 = 1';
if Trim(Edit4.Text) <> '' then
fdmMarca.sdsMarca.CommandText := fdmMarca.sdsMarca.CommandText + ' AND (NOME LIKE ' +
QuotedStr('%'+Edit4.Text+'%') + ')';
fdmMarca.cdsMarca.Open;
end;
procedure TfMarca.prc_Excluir_Registro;
var
vCodAux: Integer;
begin
try
vCodAux := fdmMarca.cdsMarcaID.AsInteger;
fdmMarca.prc_Excluir;
except
on e: Exception do
begin
prc_Consultar;
if vCodAux > 0 then
fdmMarca.cdsMarca.Locate('ID',vCodAux,([Locaseinsensitive]));
raise;
end
end;
end;
procedure TfMarca.prc_Gravar_Registro;
begin
fdmMarca.prc_Gravar;
if fdmMarca.cdsMarca.State in [dsEdit,dsInsert] then
begin
MessageDlg(fdmMarca.vMsgMarca, mtError, [mbno], 0);
exit;
end;
TS_Consulta.TabEnabled := not(TS_Consulta.TabEnabled);
RzPageControl1.ActivePage := TS_Consulta;
btnConfirmar.Enabled := False;
btnAlterar.Enabled := True;
end;
procedure TfMarca.prc_Inserir_Registro;
begin
fdmMarca.prc_Inserir;
if fdmMarca.cdsMarca.State in [dsBrowse] then
Exit;
RzPageControl1.ActivePage := TS_Cadastro;
TS_Consulta.TabEnabled := False;
btnAlterar.Enabled := False;
btnConfirmar.Enabled := True;
pnlCadastro.Enabled := True;
DBEdit1.SetFocus;
end;
procedure TfMarca.SMDBGrid1DblClick(Sender: TObject);
begin
RzPageControl1.ActivePage := TS_Cadastro;
end;
procedure TfMarca.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose := True;
if fdmMarca.cdsMarca.State in [dsEdit,dsInsert] then
begin
if MessageDlg('Fechar esta tela sem confirmar?',mtConfirmation,[mbYes,mbNo],0) = mrNo then
CanClose := False
else
CanClose := True;
end;
end;
procedure TfMarca.Edit4KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = Vk_Return then
btnConsultarClick(Sender);
end;
procedure TfMarca.SMDBGrid1TitleClick(Column: TColumn);
var
i: Integer;
ColunaOrdenada: String;
begin
ColunaOrdenada := Column.FieldName;
fdmMarca.cdsMarca.IndexFieldNames := Column.FieldName;
Column.Title.Color := clBtnShadow;
for i := 0 to SMDBGrid1.Columns.Count - 1 do
if not (SMDBGrid1.Columns.Items[I] = Column) then
SMDBGrid1.Columns.Items[I].Title.Color := clBtnFace;
end;
end.
|
unit adot.Strings;
{ Definition of classes/record types:
TReplace = record
we translate all comands to sequence of "replace"
TStr = class
string utils.
TStringEditor = record
List of string edit commands (insert/delete/replace). Can be applied to any string.
Any operation is applied to initial text (without changes made by other commands).
TTokAbstract = class
Abstract class for tokenizer (parsing text and extraction some parts called tokens).
Methods should be implemented by descendants of TTokCustom.
TTokCharDelimitedLines = class
Extract words separated by specific char.
TTokComments = class
Extract comments in Delphi style (line starting from "//", chars between "(*" and "*)" etc.
TTokCompound = class
Organize several tokenizers to chain.
TTokCustom = class
Extends abstract class with basic functionality. All desdendants should be inherited
from TTokCustom, not from TTokAbstract.
TTokCustomText = class
Basic class for simple string tokenizers. Implements all required methods of TTokCustom.
Inherited classes must implement one function for processing of custom tokenizers.
TTokDelegated = class
Custom function to extract specific tokens from the text.
TTokDigits = class
Extract words of digits.
TTokIdentifier = class
Extract identifiers as Delphi defines them.
TTokLetters= class
Extract words of letters.
TTokLettersOrDigits = class
Extract words of letters/digits.
TTokLines = class
Extract lines.
TTokLiterals = class
Extract string literanl as Delphi defines them ('a', 'test literal' etc).
TTokNonSpace = class
Extract words of non-space chars.
TTokNot = class
Reverses result of inner tokenizer. For example in pair with TTokNumbers will extract all text except numbers.
Important: TTokNot will skip all empty results, only non-empty tokens are extracted.
TTokNumbers = class
Extract numbers ("12", "+2", "-1.3" etc).
TTokPascal = class
Lexical analyzer for Pascal code (check TPasTokenType for list of supported lexems).
TTokWhitespaces = class
Extract whitespaces.
TTokenPos = record
Position of token in the text. Starts from zero.
}
interface
uses
adot.Types,
adot.Collections.Vectors,
System.Character,
System.Math,
System.SysUtils,
System.StrUtils,
System.Classes,
System.Generics.Collections,
System.Generics.Defaults;
type
TTextDistance = (tdLevenstein);
TSimilarityOption = (
soStrictNumMatching, // [soStrictNumMatching] -> "Beløp 1200.40"<>"Beløp 7200.40" (1 char diff, but numbers are different)
soStrictIntMatching, // [soStrictIntMatching] -> "År 2014"<>"År 2013" (1 char diff, but int numbers are different)
soIgnoreNums, // [soIgnoreNums] -> "Beløp 999000.50"="Beløp 12" (9 chars diff, but all numbers ignored)
soIgnoreInts, // [soIgnoreInts] -> "År 1999"="År 2014" (4 chars diff, but all int numbers ignored)
soMatchSubst // [soMatchSubst] -> "hap"="New year happens every year" (big diff, but "hap" is substring)
);
TSimilarityOptions = set of TSimilarityOption;
{$IF Defined(MSWindows)}
TAnsiChars = set of AnsiChar;
{$EndIf}
TStrCharsPos = (scAll, scFirst, scLast);
TTextEncoding = (teUnknown, teAnsi, teUTF8, teUTF16LE, teUTF16BE, teUTF32LE, teUTF32BE);
{ Position of token in the text. Starts from zero. }
TTokenPos = record
public
Start, Len: Integer;
constructor Create(AStart,ALen: integer);
procedure SetPos(AStart,ALen: integer);
{ [StartBytes; LenBytes] -> [StartChars; LenChars] }
function BytesToChars: TTokenPos;
class operator Subtract(const A,B: TTokenPos): TTokenPos; { find "space" between }
class operator Add(const A,B: TTokenPos): TTokenPos; { "merge" into one token }
class operator In(const A: integer; const B: TTokenPos): Boolean;
end;
{ List of string edit commands (insert/delete/replace). Can be applied to any string.
Any operation is applied to initial text (without changes made by other commands). }
TStringEditor = record
private
type
{ we translate all comands to sequence of "replace" }
TReplace = record
SrcText : string;
SrcPos : TTokenPos;
DstPos : TTokenPos;
Order : integer;
procedure Clear;
end;
PReplace = ^TReplace;
var
Instructions: TVector<TReplace>;
procedure Add(const Instr: TReplace);
procedure Sort;
public
procedure Init;
procedure Clear;
procedure Delete(const Start,Len: integer); overload;
procedure Delete(const Pos: TTokenPos); overload;
procedure Delete(const Pos: integer); overload;
procedure Insert(Pos: integer; const Substr: string; const SubStrOffset,SubStrLen: integer); overload;
procedure Insert(Pos: integer; const Substr: string; const SubStrPos: TTokenPos); overload;
procedure Insert(Pos: integer; const Substr: string); overload;
procedure Replace(const Start,Len : integer; const Substr: string; const SubStrOffset,SubStrLen : integer); overload;
procedure Replace(const Pos : TTokenPos; const Substr: string; const SubStrPos : TTokenPos); overload;
procedure Replace(const Start,Len : integer; const Substr: string); overload;
procedure Replace(const Pos : TTokenPos; const Substr: string); overload;
{ Apply all commands to string Src and get result }
function Apply(const Src: string): string;
end;
{ string utils }
TStr = class
public
type
TExtractType = (
etNumbers, { keep numbers only : 'a5.7b2012c 12,9' -> '5.7 2012 12,9' }
etNotNumbers, { remove numbers : 'a5.7b2012c' -> 'abc' }
etDigits, { keep digits only : 'a5.7b2012c' -> '572012' }
etNotDigits, { remove digits : 'a5.7b2012c' -> 'a.bc' }
etDigitsToEnd { group digits at end : 'a5.7b2012c' -> 'a.bc572012' }
);
TSplitOptions = record
public
MaxStrLen: integer;
AllowWordToExceedMaxLen: boolean;
procedure Init;
class function Create: TSplitOptions; static;
end;
private
{$IFNDEF NoCaseMap}
class var
FLoCaseMap: array[Char] of Char;
FHiCaseMap: array[Char] of Char;
{$ENDIF}
class var
FOrdinalComparerTrimText: IComparer<String>;
FOrdinalComparerAsInt: IComparer<String>;
class function LevensteinDistance(s, t: string): integer; static;
class function SubstringDistance(const a, b: String; var Dist: integer): Boolean; static;
class function GetNumbers(const s: string): String; static;
class function RemoveNumbers(const s: string): String; static;
class function GetDigits(const s: string): String; static;
class function RemoveDigits(const s: string): String; static;
class function MoveDigitsToEnd(const s: string): String; static;
class procedure InitializeVars; static;
class procedure FinalizeVars; static;
public
{ concatanate not empty values from Src }
class function Concat(const Src: array of string; Delimeter: string = ' '): string; overload; static;
class function Concat(Src: TArray<string>; Delimeter: string = ' '): string; overload; static;
{ concatanate used values from Src (including empty strings) }
class function Concat(const Src: array of string; const InUse: array of boolean; Delimeter: string = ' '): string; overload; static;
{ TStr.AlignLeft ('123',5) = '123 '
TStr.AlignRight ('123',5) = ' 123'
TStr.AlignCenter('123',5) = ' 123 ' }
class function AlignLeft(const Src: string; MinLen: integer): string; static;
class function AlignRight(const Src: string; MinLen: integer): string; static;
class function AlignCenter(const Src: string; MinLen: integer): string; static;
class function Reverse(const S: string): string; static;
{ returns new string where all specified chars replaced by string }
class function Replace(const Src: string; const CharsToReplace: TArray<Char>; const CharReplacement: string): string; static;
{ split text into lines of fixed length with transfering words and punctuation }
class function Split(const Src: string; MaxStrLen: integer = 80): TArray<string>; overload; static;
class function Split(const Src: string; const Options: TSplitOptions): TArray<string>; overload; static;
{ Returns max possible encoded substring for specified bufer. }
class function GetMaxEncodedBytes(const S: string; BufSize: integer; Encoding: TEncoding): TBytes; static;
{ Trancates string without breakig a words. }
class function TruncToWord(const Src: string; MaxCharLen: integer; AddDots: boolean = True): string; static;
{ Replaces any sequence of any space/control chars by single space. }
class function TruncSpaces(const Src: string; TrimRes: boolean = True): string; static;
{ returns new string where all specified chars are deleted }
class function Remove(const Src: string; const CharsToDelete: TArray<Char>): string; static;
{ case insensitive with support of internation chars }
class function SameText(const A,B: string): Boolean; overload;
class function SameText(const A: string; const B: array of string): Boolean; overload;
class function SameText(A,B: PChar; Len: integer): Boolean; overload;
class function SameTrimText(const A,B: string): Boolean; overload;
class function CompareStrings(const A,B: string): integer; overload;
class function CompareText(const A,B: string): integer; overload;
class function CompareTrimText(const A,B: string): integer; overload;
class function CompareAsInt(const A,B: string): integer; overload;
class function ComparerStrings: IComparer<String>; overload;
class function ComparerText: IComparer<String>; overload;
class function ComparerTrimText: IComparer<String>; overload;
class function ComparerAsInt: IComparer<String>; overload;
class function LowerCaseChar(C: Char): Char; static;
class function UpperCaseChar(C: Char): Char; static;
class function LowerCase(const S: string; Chars: TStrCharsPos = scAll): string; static;
class function UpperCase(const S: string; Chars: TStrCharsPos = scAll): string; static;
{ based on TTokLines }
class procedure TextToLines(const Text: string; Dst: TStrings; AClear: boolean = True); overload; static;
class procedure TextToLines(const Text: string; out Dst: TArray<string>); overload; static;
class procedure TextToLines(const Text: string; Delim: Char; out Dst: TArray<string>); overload; static;
{ similarity functions }
class function TextDistance(const a,b: string; StrDistType: TTextDistance = tdLevenstein): integer; static;
class function SimilarStrings(A,B: String; var dist: integer; AOptions: TSimilarityOptions = [soStrictIntMatching]): boolean; overload; static;
class function SimilarStrings(A,B: String; AOptions: TSimilarityOptions = [soStrictIntMatching]): boolean; overload; static;
{ unlike SimilarStrings this function will try to match AQuery with every word of AText (min dist selected) }
class function SimilarWordInText(const AWord, AText: String; var dist: integer; AOptions: TSimilarityOptions = [soStrictIntMatching]): boolean; static;
{ extract numbers/digits etc }
class function Extract(InfoType: TExtractType; const s: string): String; static;
{ System.SysUtils.TextPos doesn't work with international chars "Æ","Å" etc (XE5 at least). }
class function TextPosition(const ASubStr, AText: string; AOffset: integer = 0): Integer; static;
class function Contains(const ASubStr, AText: string): boolean; static;
{ file-string }
class function Load(Src: TStream; Encoding: TEncoding = nil): string; overload; static;
class function Load(const FileName: string; Encoding: TEncoding = nil): string; overload; static;
class procedure Save(Dst: TStream; const S: string; Encoding: TEncoding = nil); overload; static;
class procedure Save(const FileName: string; const S: string; Encoding: TEncoding = nil); overload; static;
class function LoadFileToArray(const Filename: string; Encoding: TEncoding = nil): TArray<string>; static;
class function LoadStreamToArray(Src: TStream; Encoding: TEncoding = nil): TArray<string>; static;
class procedure SaveArrayToFile(const Src: TArray<string>; const Filename: string; Encoding: TEncoding = nil); static;
class procedure SaveArrayToStream(const Src: TArray<string>; const Dst: TStream; Encoding: TEncoding = nil); static;
{ set-string, number-string etc }
{$IF Defined(MSWindows)}
class function CharsCount(const AChars: TAnsiChars): integer;
class function SetToString(const AChars: TAnsiChars): string;
class function StringToSet(const s: string): TAnsiChars;
{$EndIf}
class function IntToString(const N: int64; MinResLen: integer = -1; LeadingSpaceChar: char = '0'): string; static;
{ randomization }
{$IF Defined(MSWindows)}
class function Random(ALen: integer; const AChars: TAnsiChars): string; overload;
{$EndIf}
class function Random(ALen: integer; const AChars: string): string; overload;
class function Random(ALen: integer): string; overload;
class function Random(ALen: integer; AFrom,ATo: Char): string; overload;
class function Random: string; overload;
class function FixDecimalSeparator(const Src: string): string; static;
{ makes uniqueue name/caption/filename }
class function GetUnique(const SrcName: string; UsedNames: TArray<string>; const FmtName: string = '%s(%d)'): string; static;
class function ToInteger(const Src: string): int64; static;
class function ToFloat(const Src: string): double; static;
class function ToBoolean(const Src: string): boolean; static;
class function ToDateTime(const Src: string): TDateTime; static;
class function ToGuid(const Src: string): TGUID; static;
class function ToIntegerDef(const Src: string; DefValue: int64 = 0): int64; static;
class function ToFloatDef(const Src: string; DefValue: int64 = 0): double; static;
class function ToBooleanDef(const Src: string; DefValue: boolean = False): boolean; static;
class function ToDateTimeDef(const Src: string; DefValue: TDateTime = 0): TDateTime; static;
class function ToGuidDef(const Src: string; var Value: TGUID; const DefValue: TGUID): TGUID; static;
class function TryToInteger(const Src: string; var Value: int64): boolean; overload; static;
class function TryToInteger(const Src: string; var Value: integer): boolean; overload; static;
class function TryToFloat(const Src: string; var Value: double): boolean; overload; static;
class function TryToFloat(const Src: string; var Value: single): boolean; overload; static;
class function TryToFloat(const Src: string; var Value: extended): boolean; overload; static;
class function TryToBoolean(const Src: string; var Value: boolean): boolean; static;
class function TryToDateTime(const Src: string; var Value: TDateTime): boolean; static;
class function TryToGuid(const Src: string; var Value: TGUID): boolean; static;
end;
TEnc = class
public
{ xxx -> 'xxx'
Delphi (up to Delphi 10 Seattle at least) doesn't allow string literals to be longer than 255 chars.
MakeStringLiteral will add quote char and split to several lines if necessary }
class function MakeValidStringLiteral(const s: string): string; static;
{ General function for escaping special characters. To be more precise it is allowed to escape
any char except digits and latin chars in range 'A'..'F'. Escaped chars are converted to HEX:
Escape( 'key=value', '=' ) = 'key\3D00value' }
class function HexEscape(const Value,CharsToEscape: string; const EscapeChar: Char = '\'): string; static;
class function HexUnescape(const Value: string; const EscapeChar: Char = '\'): string; static;
{ Can be used to encode strings as Delphi-compatible string literals.
TTokPascal tokenizer can be used to extract and decode strings (or DecodeStringLiterals).
"abc" -> "'abc'"
" abc" -> "' abc'"
"a'bc" -> "a'''bc"
" a'bc " -> "' a'''bc '"}
class function EncodeStringLiteral(const Value: string): string; overload; static;
class procedure EncodeStringLiteral(const Value: string; var Dst: TStringBuilder); overload; static;
{ hex-encoded string of utf8 presentation }
class function EscapeIniValue(const KeyOrValue: string): string; static;
class function TryUnEscapeIniValue(const EscapedKeyOrValue: string; out KeyOrValue: string): boolean; static;
class function UnEscapeIniValueDef(const EscapedKeyOrValue: string; const DefValue: string): string; static;
class function UnEscapeIniValue(const EscapedKeyOrValue: string): string; static;
{ sometimes it is important to keep keys & values readable in ini file }
class function EscapeIniValueReadable(const KeyOrValue: string): string; static;
class function UnEscapeIniValueReadable(const EscapedKeyOrValue: string): string; static;
{ TTestApp -> "Test app" }
class function ClassNameToCaption(const AClassName: string): string; static;
{ make string printable (replace all unprintable/control chars):
GetPrintable( 'line1' + #13#10 + 'line2' + #8 + 'qqq' ) = 'line1 line2?qqq' }
class function GetPrintable(const S: string; ReplChar: Char = '?'): string; overload; static;
class function GetPrintable(S: PChar; Count: integer; ReplChar: Char = '?'): string; overload; static;
{ Count - size of Text used to keep text (allocated storage can be larger that data)
TextPos - where text starts in Text array
TextIsFragment - True if Text is (possibly) cut at the end, for example when we test first bytes of the file }
class function IsValidUtf8(const Text: TArray<Byte>; Count,TextPos: integer; TextIsFragment: boolean = True): boolean; overload; static;
class function IsValidUtf8(const Text: TArray<Byte>): boolean; overload; static;
{ Analyze fragment of text & detect correct encoding:
Count - size of Text used to keep text (allocated storage can be larger that data)
TextStartPos - position where text starts excluding BOM
TextIsFragment - True if Text is (possibly) cut at the end, for example when we test first bytes of the file }
class function DetectEncoding(const Text: TArray<Byte>; Count: integer;
out TextStartPos: integer; TextIsFragment: boolean): TTextEncoding; overload; static;
class function DetectEncoding(const Text: TArray<Byte>; Count: integer;
out TextStartPos: integer; TextIsFragment: boolean; out AEncoding: TEncoding): TTextEncoding; overload; static;
{ Will try to detect code page of input. Advantages over TEncoding.GetEncoding (Delphi 10.2):
- supports UTF32 (little endian / big endian)
- analyzes data for detection (TTEncoding.GetEncoding analyzes BOM only, "preamble" in TEncoding terminology).
- 100% detection of UTF family if encoded data is build according to RFC }
class function DetectCodepage(const AText: TArray<byte>; Count: integer; out CodePage: Cardinal): boolean; overload; static;
class function DetectCodepage(const AText: TArray<byte>; out CodePage: Cardinal): boolean; overload; static;
class function DetectCodepage(const AText: TArray<byte>; out Encoding: TEncoding): boolean; overload; static;
{ False if AText is 100% not encoded with code page ACodePage.
True if AText may (or may not!) be encoded with code page ACodePage.
Can be used to disable UI elements/functionality specific for some code pages only:
1200 UTF16 little endian
1201 UTF16 big endian
12000 UTF32 little endian
12001 UTF32 big endian
65001 UTF8 }
class function IsPossibleEncoding(const AText: TArray<byte>; ACodePage: Cardinal): boolean; static;
{ Extends TEncoding.GetEncoding with some extra code pages (UTF32 is not supported by TEncoding in Delphi 10.2) }
class function GetEncoding(CodePage: Cardinal): TEncoding; static;
end;
{ implementation of UTF32 big endian }
TBigEndianUTF32Encoding = class(TUnicodeEncoding)
strict protected
class var
FBigEndianUnicode32: TEncoding;
function GetByteCount(Chars: PChar; CharCount: Integer): Integer; overload; override;
function GetBytes(Chars: PChar; CharCount: Integer; Bytes: PByte; ByteCount: Integer): Integer; overload; override;
function GetCharCount(Bytes: PByte; ByteCount: Integer): Integer; overload; override;
function GetChars(Bytes: PByte; ByteCount: Integer; Chars: PChar; CharCount: Integer): Integer; overload; override;
function GetCodePage: Cardinal; override;
function GetEncodingName: string; override;
class function GetBigEndianUnicode32: TEncoding; static;
public
function Clone: TEncoding; override;
function GetPreamble: TBytes; override;
function GetMaxByteCount(CharCount: Integer): Integer; override;
function GetMaxCharCount(ByteCount: Integer): Integer; override;
class property BigEndianUnicode32: TEncoding read GetBigEndianUnicode32;
end;
{ implementation of UTF32 little endian }
TLittleEndianUTF32Encoding = class(TBigEndianUTF32Encoding)
strict protected
class var
FLittleEndianUnicode32: TEncoding;
function GetBytes(Chars: PChar; CharCount: Integer; Bytes: PByte; ByteCount: Integer): Integer; overload; override;
function GetChars(Bytes: PByte; ByteCount: Integer; Chars: PChar; CharCount: Integer): Integer; overload; override;
function GetCodePage: Cardinal; override;
function GetEncodingName: string; override;
class function GetLittleEndianUnicode32: TEncoding; static;
public
function Clone: TEncoding; override;
function GetPreamble: TBytes; override;
class property LittleEndianUnicode32: TEncoding read GetLittleEndianUnicode32;
end;
{ Usually all chars of text belong to one code page.
It is more efficient to save such text in single byte encoding with code page id. }
TCodePageId = (
cpiCyr,
cpiEur
);
TCodePages = class
private
const
CyrToUnicode: array[Byte] of Char = (
#0, #1, #2, #3, #4, #5, #6, #7, #8, #9, #$A, #$B, #$C, #$D, #$E, #$F, #$10, #$11, #$12, #$13, #$14, #$15, #$16, #$17, #$18, #$19, #$1A, #$1B, #$1C, #$1D, #$1E, #$1F,
' ', '!', '"', '#', '$', '%', '&','''', '(', ')', '*', '+', ',', '-', '.', '/', '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', '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', '{', '|', '}', '~', #$7F,
'Ђ', 'Ѓ', '‚', 'ѓ', '„', '…', '†', '‡', '€', '‰', 'Љ', '‹', 'Њ', 'Ќ', 'Ћ', 'Џ', 'ђ', '‘', '’', '“', '”', '•', '–', '—',#$0098, '™', 'љ', '›', 'њ', 'ќ', 'ћ', 'џ',
' ', 'Ў', 'ў', 'Ј', '¤', 'Ґ', '¦', '§', 'Ё', '©', 'Є', '«', '¬',#$00AD,'®','Ї', '°', '±', 'І', 'і', 'ґ', 'µ', '¶', '·', 'ё', '№', 'є', '»', 'ј', 'Ѕ', 'ѕ', 'ї',
'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я',
'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я');
EurToUnicode: array[Byte] of Char = (
#0, #1, #2, #3, #4, #5, #6, #7, #8, #9, #$A, #$B, #$C, #$D, #$E, #$F, #$10, #$11, #$12, #$13, #$14, #$15, #$16, #$17, #$18, #$19, #$1A, #$1B, #$1C, #$1D, #$1E, #$1F,
' ', '!', '"', '#', '$', '%', '&','''', '(', ')', '*', '+', ',', '-', '.', '/', '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', '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', '{', '|', '}', '~', #$7F,
'€',#$0081,'‚','ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ',#$008D,'Ž',#$008F,#$0090,'‘','’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ',#$009D, 'ž', 'Ÿ',
' ', '¡','¢','£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬',#$00AD,'®','¯', '°', '±', '²', '³', '´', 'µ', '¶', '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿',
'À', 'Á','Â','Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í','Î','Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß',
'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ', 'ÿ');
class var
UnicodeToCyr: TDictionary<Char, Byte>;
UnicodeToEur: TDictionary<Char, Byte>;
class procedure InitCyr;
class procedure InitEur;
class destructor Destroy;
class function EncodeTextEur(const Text: string; Len: integer; var Dst): Boolean; static;
class function EncodeTextCyr(const Text: string; Len: integer; var Dst): Boolean; static;
class function DecodeTextCyr(const Src; Size: integer): string; static;
class function DecodeTextEur(const Src; Size: integer): string; static;
public
class function EncodeText(const Text: string; var CodePageId: TCodePageId; var Bytes: TArray<byte>): Boolean; static;
class function DecodeText(const Bytes: TArray<byte>; CodePageId: TCodePageId): string; static;
class function StringToBuf(const Text: string; BufSize: integer; var CodePageId: TCodePageId; var Buf; var Len: integer): boolean; static;
class function BufToString(const Buf; BufSize: integer; CodePageId: TCodePageId): string; static;
end;
{# Internal structure to describe the token just found by tokenizer.
Any or even all fields can be zero. }
TTokenInfo = record
Start : integer; { start position in the text }
DelimitersPrefix : integer; { number of preceding delimiters or zero }
Len : integer; { length of the token or zero }
DelimitersSuffix : integer; { number of trailing delimiters or zero }
procedure Clear;
end;
{# Used to save/restore state of TCustomTokenizer class and descendants. }
TTokenizerState = record
private
State: IInterfacedObject<TMemoryStream>;
end;
{ Abstract class for tokenizer (parsing text and extraction some parts called tokens).
Methods should be implemented by descendants of TTokCustom }
TTokAbstract = class abstract
protected
procedure SetText(AText: PChar; ATextLen: integer); virtual; abstract;
function GetText: PChar; virtual; abstract;
function GetAsString: string; virtual; abstract;
function GetTextLen: integer; virtual; abstract;
procedure SetPosition(const AValue: integer); virtual; abstract;
function GetPosition: integer; virtual; abstract;
procedure ResetTokenizer; virtual; abstract;
procedure SaveTokenizerPos(W: TWriter); virtual; abstract; { save .Position and other fields if necessary }
procedure LoadTokenizerPos(R: TReader); virtual; abstract;
function NextToken(out AToken: TTokenInfo): Boolean; virtual; abstract;
public
property Text: PChar read GetText;
property TextLen: integer read GetTextLen;
property Position: integer read GetPosition write SetPosition;
property AsString: string read GetAsString;
end;
{ Extends abstract class with basic functionality. All desdendants should be inherited
from TTokCustom, not from TTokAbstract }
TTokCustom = class abstract (TTokAbstract)
protected
FOmmitEmptyTokens: boolean;
{ get token as string }
function GetTokenAsString(const APos: TTokenPos): string;
{ Get number of words in the text (doesn't change current position) }
function GetTokenCount: integer;
procedure SaveTokenizerPos(W: TWriter); override; { save .Position and other fields if necessary }
procedure LoadTokenizerPos(R: TReader); override;
function GetAsString: string; override;
function GetState: TTokenizerState;
procedure SetState(AState: TTokenizerState);
{ always called by any constructor }
procedure TokenizerCreated; virtual;
public
constructor Create(AText: PChar; ATextLen: integer); overload; virtual;
constructor Create(const AText: string); overload; virtual;
constructor Create; overload; virtual;
{ Find next token (word) in the text }
function Next(out AToken: TTokenPos): Boolean; overload;
function Next(out AToken: String): Boolean; overload;
function Next: String; overload;
{ Reset parser to initial state (Position:=0 etc ) }
procedure Reset; overload;
procedure Reset(ANewText: PChar; ATextLen: integer); overload;
{ high level methods }
procedure GetTokens(ADst: TStrings); overload;
procedure GetTokens(var ADst: TArray<String>); overload;
procedure GetTokens(var ADst: TArray<TTokenPos>); overload;
class procedure Parse(const AText: string; ADst: TStrings); overload;
class procedure Parse(const AText: string; var ADst: TArray<String>); overload;
class procedure Parse(const AText: string; var ADst: TArray<TTokenPos>); overload;
class procedure Parse(const AText: string; const ADelimiter: string; var ADst: string); overload;
class function Parse(const AText: string): string; overload;
{ Parse text and find number of tokens }
property TokenCount: integer read GetTokenCount;
{ Get token (defined as TTokenPos) as string }
property Tokens[const APos: TTokenPos]: string read GetTokenAsString; default;
{ Allows to save current parsing state of tokenizer and restore it later to
proceed text processing from same position. Doesn't save text, only
position and internal state required to proceed from the position. }
property Bookmark: TTokenizerState read GetState write SetState;
end;
{ Example:
- First tokenizer removes comments (extracts parts of text excluding comments).
- Second tokenizer extracting identifiers (Delphi-style ids).
Such TTokenizerCompound can be used to lookup identifiers with correct
processing of comments and string literals. }
{ Organize several tokenizers to chain }
TTokCompound = class(TTokCustom)
protected
FTokenizers: TObjectList<TTokCustom>;
FOffsets: TArray<integer>;
FCurrentTokenizer: integer;
{ Implementation of TTokAbstract }
procedure SetText(AText: PChar; ATextLen: integer); override;
function GetText: PChar; override;
function GetTextLen: integer; override;
function GetAsString: string; override;
procedure SetPosition(const AValue: integer); override;
function GetPosition: integer; override;
procedure ResetTokenizer; override;
procedure SaveTokenizerPos(W: TWriter); override; { save .Position and other fields if necessary }
procedure LoadTokenizerPos(R: TReader); override;
function NextToken(out AToken: TTokenInfo): Boolean; override;
{ Additional methods, specific for this class}
function GetTokenizersCount: integer;
function GetTokenizer(n: integer): TTokCustom;
function GetFirst: TTokCustom;
function GetLast: TTokCustom;
public
constructor Create(const ATokenizers: array of TTokCustom); reintroduce;
destructor Destroy; override;
{ chain of inner tokenizers }
property TokenizersCount: integer read GetTokenizersCount;
property Tokenizers[n: integer]: TTokCustom read GetTokenizer;
property First: TTokCustom read GetFirst;
property Last: TTokCustom read GetLast;
end;
{ Reverses result of inner tokenizer. For example in pair with TTokNumbers will extract all text except numbers.
Important: TTokNot will skip all empty results, only non-empty tokens are extracted. }
TTokNot = class(TTokCustom)
protected
type
TState = (Starting, Running, Finished);
var
FTokenizer: TTokCustom;
FOwnsInnerTokenizer: boolean;
FFinished: boolean;
FValueStart: integer;
FValueLen: integer;
procedure SetText(AText: PChar; ATextLen: integer); override;
function GetText: PChar; override;
function GetTextLen: integer; override;
function GetAsString: string; override;
procedure SetPosition(const AValue: integer); override;
function GetPosition: integer; override;
procedure ResetTokenizer; override;
procedure SaveTokenizerPos(W: TWriter); override; { save .Position and other fields if necessary }
procedure LoadTokenizerPos(R: TReader); override;
function NextToken(out AToken: TTokenInfo): Boolean; override;
public
constructor Create(ATokenizer: TTokCustom; AOwnsInnerTokenizer: boolean);
destructor Destroy; override;
end;
{ Basic class for simple string tokenizers. Implements all required methods of TTokCustom.
Inherited classes must implement one function for processing of custom tokenizers. }
TTokCustomText = class abstract (TTokCustom)
protected
FTextStorage : String; { to keep text if provided as string }
FText : PChar; { full text }
FTextLen : integer; { size }
FPosition : integer;
{ implementation of TTokAbstract methods }
procedure SetText(AText: PChar; ATextLen: integer); override;
function GetText: PChar; override;
function GetTextLen: integer; override;
function GetAsString: string; override;
procedure SetPosition(const AValue: integer); override;
function GetPosition: integer; override;
procedure ResetTokenizer; override;
procedure SaveTokenizerPos(W: TWriter); override; { save .Position and other fields if necessary }
procedure LoadTokenizerPos(R: TReader); override;
function NextToken(out AToken: TTokenInfo): Boolean; override;
{ Usually we need to override this only method in descendant class to implement
specific text tokenizer (extract lines /comments/numbers etc):
- Parameter "Res" preinitialized to zero.
- Returns False if parsing is finished (no token found), Res is undefined.
- Returns True if next token is found, Res is placement of the token in the Text. }
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; virtual; abstract;
public
constructor Create(AText: PChar; ATextLen: integer); override;
constructor Create(const AText: string); override;
procedure Reset(const AText: string); overload;
procedure Reset(const AText: string; AStart,ALen: integer); overload;
procedure Reset(const AText: PChar; ALen: integer); overload;
end;
TTokText = class(TTokCustomText)
public
type
TTextTokenType = (tttWord, tttPunctuation, tttWhitespace);
protected
FLastTokenType: TTextTokenType;
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
public
property LastTokenType: TTextTokenType read FLastTokenType;
end;
{ Custom function to extract specific tokens from the text }
TTokDelegated = class(TTokCustomText)
public
type
TDelegatedTokenizer = reference to function(Text: PChar; Len: integer; var Res: TTokenInfo): boolean;
protected
FProc: TDelegatedTokenizer;
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
public
constructor Create(AText: PChar; ATextLen: integer; AProc: TDelegatedTokenizer); reintroduce; overload;
constructor Create(const AText: string; AProc: TDelegatedTokenizer); reintroduce; overload;
end;
{ Extract words of non-space chars. }
TTokNonSpace = class(TTokCustomText)
protected
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
end;
{ Extract words of letters. }
TTokLetters= class(TTokCustomText)
protected
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
end;
{ Extract words of digits. }
TTokDigits = class(TTokCustomText)
protected
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
public
class function IsStartOfDigits(C: Char): boolean; static;
class function NextDigits(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; static;
end;
{ Extract words of letters/digits. }
TTokLettersOrDigits = class(TTokCustomText)
protected
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
end;
{ Extract numbers ("12", "+2", "-1.3" etc). }
TTokNumbers = class(TTokCustomText)
protected
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
end;
{ Extract lines from text (strings separated by new line markers).
1. If file is empty then returns 0 lines. This has important consequences.
2. If file contains only EOF char, then it contains 1 line finished by that char. If we read it as two lines,
then we can't encode one empty line (empty file - 0 line, EOL char - 2 lines, no way to encode 1 line).
3. As result of 1. and 2.:
- Every EOL char finishes line, not introducing new one.
- Last EOL can be ommited for not empty line.
With such algorithm conversion array->text and text->array is simmetric, TStringList.Load works same way.
Text editors usually use another logic. If we open empty file in NotePad++, it will show 1 line
(editors never show zero lines). Such aproach doesn't provide simmetric conversion array-text. }
{ Extract lines. }
TTokLines = class(TTokCustomText)
protected
procedure TokenizerCreated; override;
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
public
class function GetLine(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; static;
class function GetLineLength(const Text: PChar; Len: integer; IncludeEOL: boolean): Integer; static;
end;
{ Extract words separated by specific char. }
TTokCharDelimitedLines = class(TTokCustomText)
protected
FDelimiter: Char;
FCaseSensitive: boolean;
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
public
constructor Create(AText: PChar; ATextLen: integer; ADelimiter: Char; ACaseSensitive: Boolean = False); overload;
constructor Create(const AText: string; ADelimiter: Char; ACaseSensitive: Boolean = False); overload;
end;
{ Extract identifiers as Delphi defines them. }
TTokIdentifier = class(TTokCustomText)
protected
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
public
class function IsStartOfIdentifier(C: Char): Boolean; static;
class function NextIdentifier(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; static;
end;
{ Search for literals starting/ending by "'". Doesn't support #n style, for example:
- #13#10 will not be recognized as literal
- 'a'#13#10 will be racognized as literal 'a' }
{ Extract string literanl as Delphi defines them ('a', 'test literal' etc). }
TTokLiterals = class(TTokCustomText)
protected
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
public
class function IsStartOfLiteral(C: Char): boolean; static;
class function NextLiteral(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; static;
class function GetLiteralLen(Text: PChar; Len: integer): integer;
end;
{ Extract whitespaces. }
TTokWhitespaces = class(TTokCustomText)
protected
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
public
class function IsStartOfWhitespace(C: Char): Boolean; static;
class function NextWhitespace(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; static;
end;
{ Extract comments in Delphi style (line starting from "//", chars between "(*" and "*)" etc. }
TTokComments = class(TTokCustomText)
protected
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
public
class function IsStartOfComment(Text: PChar; Len: integer): Boolean; static;
class function NextComment(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; static;
end;
TPasTokenType = (Unknown, Whitespace, Literal, Digits, Comment, Identifier, Delimiter);
TPasTokenTypes = set of TPasTokenType;
const
PasAllTokenTypes = [Low(TPasTokenType)..High(TPasTokenType)];
type
{ Lexical analyzer for Pascal code (check TPasTokenType for list of supported lexems). }
TTokPascal = class(TTokCustomText)
protected
FTokenType: TPasTokenType;
const
Delimiters = ',.;#@&^$[({])}+-/*<>=:';
procedure SaveTokenizerPos(W: TWriter); override; { save .Position and other fields if necessary }
procedure LoadTokenizerPos(R: TReader); override;
function FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean; override;
public
type
TToken = record
FPos: TTokenPos;
FType: TPasTokenType;
end;
function Next(ATokenTypes: TPasTokenTypes; out AToken: TTokenPos): Boolean; overload;
function Next(ATokenTypes: TPasTokenTypes; out AToken: String): Boolean; overload;
function Next(ATokenTypes: TPasTokenTypes): String; overload;
class function IsDelimiterChar(C: Char): Boolean; static;
class function RemoveComments(const SrcPasText: string): string; static;
function GetAllTokens: TArray<TToken>;
property LastTokenType: TPasTokenType read FTokenType;
end;
implementation
uses
adot.Tools,
adot.Tools.IO,
adot.Collections.Sets,
adot.Collections;
{ TStr.TSplitOptions }
class function TStr.TSplitOptions.Create: TSplitOptions;
begin
result.Init;
end;
procedure TStr.TSplitOptions.Init;
begin
Self := Default(TStr.TSplitOptions);
MaxStrLen := 80;
AllowWordToExceedMaxLen := False;
end;
{ TStr }
class function TStr.Concat(const Src: array of string; Delimeter: string): string;
var
i: Integer;
begin
result := '';
for i := Low(Src) to High(Src) do
if Src[i]<>'' then
if result='' then
result := Src[i]
else
result := result + Delimeter + Src[i];
end;
class function TStr.Concat(Src: TArray<string>; Delimeter: string): string;
var
i: Integer;
begin
result := '';
for i := Low(Src) to High(Src) do
if Src[i]<>'' then
if result=''
then result := Src[i]
else result := result + Delimeter + Src[i];
end;
class function TStr.Concat(const Src: array of string; const InUse: array of boolean; Delimeter: string = ' '): string;
var
i: Integer;
empty: Boolean;
begin
result := '';
empty := True;
for i := Low(Src) to High(Src) do
if InUse[i] then
if Empty then
begin
result := Src[i];
Empty := False;
end
else
result := result + Delimeter + Src[i];
end;
class function TStr.AlignCenter(const Src: string; MinLen: integer): string;
begin
result := StringOfChar(' ',(MinLen-Length(Src)) div 2) + Src;
result := result + StringOfChar(' ',MinLen-Length(result));
end;
class function TStr.AlignLeft(const Src: string; MinLen: integer): string;
begin
result := Src + StringOfChar(' ',MinLen-Length(Src));
end;
class function TStr.AlignRight(const Src: string; MinLen: integer): string;
begin
result := StringOfChar(' ',MinLen-Length(Src)) + Src;
end;
class function TStr.CompareAsInt(const A, B: string): integer;
var
AI,BI: int64;
begin
if TryStrToInt64(A, AI) and TryStrToInt64(B, BI) then
begin
if AI < BI then Result := -1 else
if AI > BI then Result := 1 else
Result := 0;
end
else
result := CompareText(A, B);
end;
class function TStr.ComparerAsInt: IComparer<String>;
begin
if FOrdinalComparerAsInt = nil then
FOrdinalComparerAsInt := TDelegatedComparer<String>.Create(
function (const A,B: string): integer
begin
result := CompareAsInt(A, B);
end);
result := FOrdinalComparerAsInt;
end;
class function TStr.ComparerStrings: IComparer<String>;
begin
result := TStringComparer.Ordinal;
end;
class function TStr.ComparerText: IComparer<String>;
begin
result := TIStringComparer.Ordinal;
end;
class function TStr.ComparerTrimText: IComparer<String>;
begin
if FOrdinalComparerTrimText = nil then
FOrdinalComparerTrimText := TDelegatedComparer<String>.Create(
function (const A,B: string): integer
begin
result := CompareTrimText(A, B);
end);
result := FOrdinalComparerTrimText;
end;
class function TStr.CompareStrings(const A,B: string): integer;
begin
result := AnsiCompareStr(A, B);
end;
class function TStr.CompareText(const A, B: string): integer;
begin
result := AnsiCompareText(A, B);
end;
class function TStr.CompareTrimText(const A, B: string): integer;
begin
result := CompareText(Trim(A), Trim(B));
end;
class function TStr.UpperCase(const S: string; Chars: TStrCharsPos): string;
begin
case Chars of
scAll:
result := S.ToUpper;
scFirst:
begin
result := S;
if result<>'' then
result[Low(result)] := result.Chars[0].ToUpper;
end;
scLast:
begin
result := S;
if result<>'' then
result[High(result)] := result.Chars[Length(result)-1].ToUpper;
end;
end;
end;
class function TStr.LowerCase(const S: string; Chars: TStrCharsPos): string;
begin
case Chars of
scAll:
result := S.ToLower;
scFirst:
begin
result := S;
if result<>'' then
result[Low(result)] := LowerCaseChar(result[Low(result)]);
end;
scLast:
begin
result := S;
if result<>'' then
result[High(result)] := LowerCaseChar(result[High(result)]);
end;
end;
end;
class function TStr.Extract(InfoType: TExtractType; const s: string): String;
begin
case InfoType of
etNumbers : result := GetNumbers(s);
etNotNumbers : result := RemoveNumbers(s);
etDigits : result := GetDigits(s);
etNotDigits : result := RemoveDigits(s);
etDigitsToEnd : result := MoveDigitsToEnd(s);
else raise Exception.Create('Error');
end;
end;
class function TStr.SameText(const A, B: string): Boolean;
begin
result := AnsiSameText(A,B);
end;
{$IF Defined(MSWindows)}
class function TStr.CharsCount(const AChars: TAnsiChars): integer;
var
C: AnsiChar;
begin
result := 0;
for C in AChars do
inc(result);
end;
{$EndIf}
class function TStr.IntToString(const N: int64; MinResLen: integer = -1; LeadingSpaceChar: char = '0'): string;
begin
result := IntToStr(N);
if Length(result) < MinResLen then
if (LeadingSpaceChar = '0') and (N < 0) then
result := result.Substring(0, 1) + StringOfChar('0', MinResLen-Length(result)) + result.Substring(1)
else
result := StringOfChar(LeadingSpaceChar, MinResLen-Length(result)) + result;
end;
{$IF Defined(MSWindows)}
class function TStr.StringToSet(const s: string): TAnsiChars;
var
I: Integer;
begin
result := [];
for I := Low(s) to High(s) do
include(result, AnsiChar(s[i]));
end;
class function TStr.SetToString(const AChars: TAnsiChars): string;
var
c: AnsiChar;
i: Integer;
begin
SetLength(result, CharsCount(AChars));
i := Low(result);
for c in AChars do
begin
result[i] := Char(c);
inc(i);
end;
end;
{$EndIf}
class function TStr.Random(ALen: integer; const AChars: string): string;
var
I,J: Integer;
begin
J := Length(AChars);
setlength(result, ALen);
for I := Low(result) to High(result) do
result[I] := AChars[Low(AChars)+System.Random(J)];
end;
{$IF Defined(MSWindows)}
class function TStr.Random(ALen: integer; const AChars: TAnsiChars): string;
begin
result := Random(ALen, SetToString(AChars));
end;
{$EndIf}
class function TStr.Random(ALen: integer): string;
var
I,J: Integer;
begin
SetLength(result, ALen);
for I := Low(Result) to High(Result) do
begin
J := System.Random(byte('z')-byte('a')+1 + byte('9')-byte('0')+1);
if J < byte('z')-byte('a')+1
then Result[I] := Char(J+byte('a'))
else Result[I] := Char(J+byte('0'));
end;
end;
class function TStr.RemoveDigits(const s: string): String;
var
i,j: Integer;
begin
j := 0;
for i := 1 to length(s) do
if (s[i]<'0') or (s[i]>'9') then
inc(j);
setlength(result, j);
j := 0;
for i := 1 to length(s) do
if (s[i]<'0') or (s[i]>'9') then
begin
inc(j);
result[j] := s[i];
end;
end;
class function TStr.RemoveNumbers(const s: string): String;
var
i,j: Integer;
begin
j := 0;
for i := 1 to length(s) do
if (s[i]>='0') and (s[i]<='9') or
((s[i]='.') or (s[i]=',')) and (
(i>1) and (s[i-1]>='0') and (s[i-1]<='9') or
(i<length(s)) and (s[i+1]>='0') and (s[i+1]<='9')
)
then
{ part of number }
else
inc(j);
setlength(result, j);
j := 0;
for i := 1 to length(s) do
if (s[i]>='0') and (s[i]<='9') or
((s[i]='.') or (s[i]=',')) and (
(i>1) and (s[i-1]>='0') and (s[i-1]<='9') or
(i<length(s)) and (s[i+1]>='0') and (s[i+1]<='9')
)
then
{ part of number }
else
begin
inc(j);
result[j] := s[i];
end;
end;
class function TStr.Replace(const Src: string; const CharsToReplace: TArray<Char>; const CharReplacement: string): string;
var
Buf: TStringBuilder;
I: Integer;
S: TSet<Char>;
begin
S.Init(CharsToReplace);
Buf := TStringBuilder.Create;
for I := 0 to Src.Length-1 do
if Src.Chars[I] in S
then Buf.Append(CharReplacement)
else Buf.Append(Src.Chars[I]);
result := Buf.ToString;
end;
class function TStr.Remove(const Src: string; const CharsToDelete: TArray<Char>): string;
var
Buf: TStringEditor;
I: Integer;
S: TSet<Char>;
begin
S.Init(CharsToDelete);
Buf.Clear;
for I := 0 to Src.Length-1 do
if Src.Chars[I] in S then
Buf.Delete(I);
result := Buf.Apply(Src);
end;
class function TStr.Reverse(const S: string): string;
var
L,R,I: Integer;
C: Char;
begin
result := S;
L := Low(result);
R := High(result);
for I := 0 to Length(result) div 2-1 do
begin
C := result[L];
result[L] := result[R];
result[R] := C;
inc(L);
dec(R);
end;
end;
class function TStr.GetNumbers(const s: string): String;
type
TState = (stEmpty, stNum, stSpace);
var
i,j: Integer;
State: TState;
begin
j := 0;
State := stEmpty;
for i := 1 to length(s) do
if (s[i]>='0') and (s[i]<='9') or
((s[i]='.') or (s[i]=',')) and (
(i>1) and (s[i-1]>='0') and (s[i-1]<='9') or
(i<length(s)) and (s[i+1]>='0') and (s[i+1]<='9')
)
then { part of number }
begin
if State=stSpace then
inc(j);
inc(j);
State := stNum;
end
else { not part of number }
if State=stNum then
State := stSpace; { space is required before next number }
setlength(result, j);
j := 0;
State := stEmpty;
for i := 1 to length(s) do
if (s[i]>='0') and (s[i]<='9') or
((s[i]='.') or (s[i]=',')) and (
(i>1) and (s[i-1]>='0') and (s[i-1]<='9') or
(i<length(s)) and (s[i+1]>='0') and (s[i+1]<='9')
)
then { part of number }
begin
if State=stSpace then
begin
inc(j);
result[j] := ' ';
end;
inc(j);
result[j] := s[i];
State := stNum;
end
else { not part of number }
if State=stNum then
State := stSpace; { space is required before next number }
end;
class function TStr.GetUnique(const SrcName: string; UsedNames: TArray<string>; const FmtName: string): string;
var
N: Integer;
S: TSet<string>;
begin
N := 1;
S := UsedNames;
result := SrcName;
while result in S do
begin
inc(N);
result := format(FmtName, [SrcName, N]);
end;
end;
class procedure TStr.InitializeVars;
{$IFNDEF NoCaseMap}
var
C: Char;
{$ENDIF}
begin
{$IFNDEF NoCaseMap}
for C := Low(C) to High(C) do
begin
FLoCaseMap[C] := C.ToLower;
FHiCaseMap[C] := C.ToUpper;
end;
{$ENDIF}
end;
class procedure TStr.FinalizeVars;
begin
end;
class function TStr.MoveDigitsToEnd(const s: string): String;
var
i,j: Integer;
begin
setlength(result, length(s));
j := 0;
for i := 1 to length(s) do
if (s[i]<'0') or (s[i]>'9') then
begin
inc(j);
result[j] := s[i];
end;
for i := 1 to length(s) do
if (s[i]>='0') and (s[i]<='9') then
begin
inc(j);
result[j] := s[i];
end;
end;
class function TStr.GetDigits(const s: string): String;
var
i,j: Integer;
begin
j := 0;
for i := 1 to length(s) do
if (s[i]>='0') and (s[i]<='9') then
inc(j);
setlength(result, j);
j := 0;
for i := 1 to length(s) do
if (s[i]>='0') and (s[i]<='9') then
begin
inc(j);
result[j] := s[i];
end;
end;
class function TStr.GetMaxEncodedBytes(const S: string; BufSize: integer; Encoding: TEncoding): TBytes;
var
M,N,I,J: Integer;
begin
{ usually string should fit the buffer, in such case we process it in most efficient way }
if Length(S) <= BufSize then
begin
result := Encoding.GetBytes(S);
if Length(result) <= BufSize then
Exit;
end;
{ find N=number of chars to be encoded and M=required buffer size (<=BufSize) }
M := 0;
N := 0;
for I := Low(S) to High(S) do
begin
J := Encoding.GetByteCount(S[I]);
if M+J > BufSize then
Break;
inc(M, J);
inc(N);
end;
Result := Encoding.GetBytes(S.Substring(0, N));
Assert(Length(Result) = M);
end;
class function TStr.SubstringDistance(const a,b: String; var Dist: integer):Boolean;
var
Substr,Str: string;
begin
if Length(a)<=length(b) then
begin
Substr := a;
Str := b;
end
else
begin
Substr := b;
Str := a;
end;
Result := TextPos(PChar(Str), PChar(SubStr))<>nil;
if Result then
Dist := Length(Str)-Length(SubStr);
end;
class function TStr.SimilarStrings(A, B: String; var dist: integer; AOptions: TSimilarityOptions): boolean;
var
maxerror: Integer;
begin
Result := (soMatchSubst in AOptions) and (Pos(AnsiLowerCase(a), AnsiLowerCase(b))>0);
if Result then
begin
dist := length(b)-length(a);
Exit;
end;
{ numbers must be the same without any errors (2012<>2011 even in long strings) }
if (soStrictNumMatching in AOptions) and (GetNumbers(a)<>GetNumbers(b)) or
(soStrictIntMatching in AOptions) and (GetDigits(a)<>GetDigits(b))
then
Exit;
{ ignore numbers, so "Beløp 12.6 NOK" = "Beløp 5 NOK" }
if soIgnoreNums in AOptions then
begin
a := RemoveNumbers(a);
b := RemoveNumbers(b);
end
else
if soIgnoreInts in AOptions then
begin
a := RemoveDigits(a);
b := RemoveDigits(b);
end;
{ for longer strings we allow more mistakes }
case max(length(a), length(b)) of
0..2: maxerror := 0;
3..4: maxerror := 1;
5..9: maxerror := 2;
10..15: maxerror := 3;
16..33: maxerror := 4;
else maxerror := 0;
end;
{ if length is too different then we do not have to spend time for similar search }
Dist := Abs(length(a)-length(b));
if (Dist>maxerror) then
exit;
{ special case - substring matching (it is faster than calculation of distance) }
Result := SubstringDistance(a,b, Dist);
{ For very short and very long strings we do not use similar search.
(for short strings it is useless, for long strings it is time expensive). }
if not Result and (maxerror>0) then
begin
dist := LevensteinDistance(a,b);
result := dist<=maxerror;
end;
end;
class function TStr.SameText(const A: string; const B: array of string): Boolean;
var
I: Integer;
begin
for I := Low(B) to High(B) do
if SameText(B[I], A) then
Exit(True);
result := False;
end;
class function TStr.SameText(A, B: PChar; Len: integer): Boolean;
var
I: integer;
begin
{$IFNDEF NoCaseMap}
for I := 0 to Len-1 do
if FLoCaseMap[A[I]] <> FLoCaseMap[B[I]] then
Exit(False);
{$ELSE}
for I := 0 to Len-1 do
if Char(A[I]).ToLower <> Char(B[I]).ToLower then
Exit(False);
{$ENDIF}
result := True;
end;
class function TStr.LowerCaseChar(C: Char): Char;
begin
{$IFNDEF NoCaseMap}
result := FLoCaseMap[C];
{$ELSE}
result := C.ToLower;
{$ENDIF}
end;
class function TStr.UpperCaseChar(C: Char): Char;
begin
{$IFNDEF NoCaseMap}
result := FHiCaseMap[C];
{$ELSE}
result := C.ToUpper;
{$ENDIF}
end;
class function TStr.SameTrimText(const A, B: string): Boolean;
begin
result := SameText(Trim(A), Trim(B));
end;
class function TStr.SimilarStrings(A,B: String; AOptions: TSimilarityOptions = [soStrictIntMatching]): boolean;
var
Distance: Integer;
begin
result := SimilarStrings(A,B, Distance, AOptions);
end;
class function TStr.SimilarWordInText(const AWord, AText: String; var dist: integer; AOptions: TSimilarityOptions): boolean;
var
Tok: TTokLettersOrDigits;
W: String;
D: integer;
begin
Result := False;
Tok := TTokLettersOrDigits.Create(AText);
try
while Tok.Next(W) do
begin
if not SimilarStrings(AWord, W, D, AOptions) then
Continue;
if not Result then
Dist := D
else
Dist := Min(Dist, D);
Result := True;
end;
finally
FreeAndNil(Tok);
end;
end;
class function TStr.Split(const Src: string; MaxStrLen: integer): TArray<string>;
var
Options: TSplitOptions;
begin
Options.Init;
Options.MaxStrLen := MaxStrLen;
result := Split(Src, Options);
end;
class function TStr.Split(const Src: string; const Options: TSplitOptions): TArray<string>;
var
Parser: TTokText;
Tokens: TVector<TCompound<TTokenPos, TTokText.TTextTokenType>>;
Pair: TCompound<TTokenPos, TTokText.TTextTokenType>;
Buf: TStringBuilder;
Res: TVector<string>;
I,J,N,L: integer;
begin
if Options.MaxStrLen <= 0 then
begin
if Options.AllowWordToExceedMaxLen then
begin
SetLength(result, 1);
result[0] := Src
end
else
SetLength(result, 0);
Exit;
end;
Parser := TTokText.Create(Src);
try
Pair := Default(TCompound<TTokenPos, TTokText.TTextTokenType>);
Tokens.Clear;
while Parser.Next(Pair.A) do
if Parser.LastTokenType <> tttWhitespace then
begin
Pair.B := Parser.LastTokenType;
Tokens.Add(Pair);
end;
finally
Sys.FreeAndNil(Parser);
end;
Buf := TStringBuilder.Create;
Res.Clear;
I := 0;
while I < Tokens.Count do
begin
Pair := Tokens[I];
if Pair.B = tttWord then
begin
{ number of punctuation chars following the word }
N := 0;
L := 0;
for J := I+1 to Tokens.Count-1 do
if Tokens[J].B <> tttPunctuation then
break
else
begin
inc(N);
inc(L, Tokens[J].A.Len);
end;
{ if word + punctuation is too long for single line }
if Pair.A.Len + L > Options.MaxStrLen then
begin
if Buf.Length > 0 then
begin Res.Add(Buf.ToString); Buf.Clear; end;
if Options.AllowWordToExceedMaxLen then
begin
for J := I to I+N do
Buf.Append(Parser[Tokens[J].A]);
inc(I, N);
end
else
begin
while Pair.A.Len > Options.MaxStrLen do
begin
Res.Add(Src.Substring(Pair.A.Start, Options.MaxStrLen));
inc(Pair.A.Start, Options.MaxStrLen);
dec(Pair.A.Len, Options.MaxStrLen);
end;
Buf.Append(Src, Pair.A.Start, Pair.A.Len);
end;
end
else
{ if word + punctuation is small enough to fit a line }
begin
if Buf.Length + Ifthen(Buf.Length=0,0,1) + Pair.A.Len + N > Options.MaxStrLen then
begin Res.Add(Buf.ToString); Buf.Clear; end;
if Buf.Length > 0 then
Buf.Append(' ');
for J := I to I+N do
begin
Pair := Tokens[J];
Buf.Append(Src, Pair.A.Start, Pair.A.Len);
end;
inc(I, N);
end;
end
else
begin
{ tttPunctuation }
if Buf.Length + Pair.A.Len > Options.MaxStrLen then
begin Res.Add(Buf.ToString); Buf.Clear; end;
Buf.Append(Src, Pair.A.Start, Pair.A.Len);
end;
inc(I);
end;
if Buf.Length > 0 then
Res.Add(Buf.ToString);
result := Res.ToArray;
end;
class procedure TStr.TextToLines(const Text: string; Dst: TStrings; AClear: boolean = True);
begin
if AClear then
Dst.Clear;
TTokLines.Parse(Text, Dst);
end;
class procedure TStr.TextToLines(const Text: string; out Dst: TArray<string>);
begin
TTokLines.Parse(Text, Dst);
end;
class procedure TStr.TextToLines(const Text: string; Delim: Char; out Dst: TArray<string>);
var
T: TTokCharDelimitedLines;
begin
T := TTokCharDelimitedLines.Create(Text, Delim);
try
T.GetTokens(Dst);
finally
T.Free;
end;
end;
class function TStr.FixDecimalSeparator(const Src: string): string;
begin
Result := Src;
if FormatSettings.DecimalSeparator<>'.' then
Result := Result.Replace('.', FormatSettings.DecimalSeparator);
if FormatSettings.DecimalSeparator<>',' then
Result := Result.Replace(',', FormatSettings.DecimalSeparator);
end;
class function TStr.ToFloatDef(const Src: string; DefValue: int64): double;
begin
if not TryToFloat(Src, result) then
result := DefValue;
end;
class function TStr.ToGuid(const Src: string): TGUID;
begin
result := StringToGuid(Src);
end;
class function TStr.ToGuidDef(const Src: string; var Value: TGUID; const DefValue: TGUID): TGUID;
begin
if not TryToGuid(Src, result) then
result := DefValue;
end;
class function TStr.ToInteger(const Src: string): int64;
begin
result := StrToInt64(Src);
end;
class function TStr.ToFloat(const Src: string): double;
begin
result := StrToFloat(FixDecimalSeparator(Src));
end;
class function TStr.ToBoolean(const Src: string): boolean;
begin
if not TryToBoolean(Src, Result) then
raise Exception.Create('Error');
end;
class function TStr.ToBooleanDef(const Src: string; DefValue: boolean): boolean;
begin
if not TryToBoolean(Src, Result) then
Result := DefValue;
end;
class function TStr.ToDateTime(const Src: string): TDateTime;
begin
result := StrToDateTime(Src);
end;
class function TStr.ToDateTimeDef(const Src: string; DefValue: TDateTime): TDateTime;
begin
if not TryToDateTime(Src, result) then
result := DefValue;
end;
class function TStr.ToIntegerDef(const Src: string; DefValue: int64): int64;
begin
if not TryToInteger(Src, result) then
result := DefValue;
end;
class function TStr.TryToFloat(const Src: string; var Value: double): boolean;
begin
result := TryStrToFloat(FixDecimalSeparator(Src), Value);
end;
class function TStr.TryToFloat(const Src: string; var Value: single): boolean;
begin
result := TryStrToFloat(FixDecimalSeparator(Src), Value);
end;
class function TStr.TryToBoolean(const Src: string; var Value: boolean): boolean;
var
S: string;
begin
S := Trim(Src).ToLower;
if (S='1') or (S='y') or (S='yes') or (S='j') or (S='ja') or (s='t') or (S='true') then
begin
Value := True;
Result := True;
end
else
if (S='0') or (S='n') or (S='no') or (S='nei') or (s='f') or (S='false') then
begin
Value := False;
Result := True;
end
else
result := False;
end;
class function TStr.TryToDateTime(const Src: string; var Value: TDateTime): boolean;
begin
result := TryStrToDateTime(Src, Value);
end;
class function TStr.TryToFloat(const Src: string; var Value: extended): boolean;
begin
result := TryStrToFloat(FixDecimalSeparator(Src), Value);
end;
class function TStr.TryToGuid(const Src: string; var Value: TGUID): boolean;
begin
result := TGUIDUtils.IsValid(Src);
if result then
try
Value := StringToGuid(Src);
except
result := False;
end;
end;
class function TStr.TryToInteger(const Src: string; var Value: int64): boolean;
begin
result := TryStrToInt64(Src, Value);
end;
class function TStr.TryToInteger(const Src: string; var Value: integer): boolean;
begin
result := TryStrToInt(Src, Value);
end;
class function TStr.TruncSpaces(const Src: string; TrimRes: boolean = True): string;
type
TState = (sStart, sWord, sSpace);
var
I,WordStart: Integer;
State: TState;
begin
result := '';
State := sStart;
WordStart := 0;
for I := 0 to Length(Src)-1 do
if Src.Chars[I].IsWhiteSpace or Src.Chars[I].IsControl then
begin
case State of
sStart:
begin
result := result + ' ';
State := sSpace;
end;
sWord:
begin
result := result + Src.Substring(WordStart, I-WordStart) + ' ';
State := sSpace;
end;
sSpace:;
end;
end
else
if State<>sWord then
begin
WordStart := I;
State := sWord;
end;
if State=sWord then
result := result + Src.Substring(WordStart, Length(Src)-WordStart);
if TrimRes then
result := Trim(result);
end;
class function TStr.TruncToWord(const Src: string; MaxCharLen: integer; AddDots: boolean = True): string;
var
I: Integer;
begin
result := Trim(Src);
if (MaxCharLen < Length(Src)) and (Src <> '') then
begin
result := '';
for I := MaxCharLen downto 0 do
if (Src.Chars[I] <= ' ') or (Src.Chars[I]={Non-breaking space}#160) then
begin
result := Src.Substring(0,I);
break;
end;
if AddDots then
result := result + '...';
end;
end;
class function TStr.LevensteinDistance(s, t: string): integer;
const
cuthalf = 100;
var
i, j, m, n: integer;
cost: integer;
flip: boolean;
buf: array[0..((cuthalf * 2) - 1)] of integer;
begin
s := copy(s, 1, cuthalf - 1);
t := copy(t, 1, cuthalf - 1);
m := length(s);
n := length(t);
if m = 0 then
Result := n
else if n = 0 then
Result := m
else
begin
flip := false;
for i := 0 to n do
buf[i] := i;
for i := 1 to m do
begin
if flip then
buf[0] := i
else
buf[cuthalf] := i;
for j := 1 to n do
begin
if s[i] = t[j] then
cost := 0
else
cost := 1;
if flip then
buf[j] := Sys.min((buf[cuthalf + j] + 1),
(buf[j - 1] + 1),
(buf[cuthalf + j - 1] + cost))
else
buf[cuthalf + j] := Sys.min((buf[j] + 1),
(buf[cuthalf + j - 1] + 1),
(buf[j - 1] + cost));
end;
flip := not flip;
end;
if flip then
Result := buf[cuthalf + n]
else
Result := buf[n];
end;
end;
class function TStr.Load(Src: TStream; Encoding: TEncoding): string;
var
B: TArray<System.Byte>;
begin
Src.Position := 0;
SetLength(B, Src.Size);
Src.ReadBuffer(B, Length(B));
if Encoding <> nil then
Result := Encoding.GetString(B)
else
if TEnc.IsValidUtf8(B)
then Result := Encoding.UTF8.GetString(B)
else Result := Encoding.ANSI.GetString(B);
end;
class function TStr.Load(const FileName: string; Encoding: TEncoding): string;
var
F: TFileStream;
begin
F := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
result := Load(F, Encoding);
finally
F.Free;
end;
end;
class function TStr.LoadFileToArray(const Filename: string; Encoding: TEncoding = nil): TArray<string>;
var
S: TMemoryStream;
begin
S := TMemoryStream.Create;
try
S.LoadFromFile(Filename);
S.Position := 0;
result := LoadStreamToArray(S, Encoding);
finally
Sys.FreeAndNil(S);
end;
end;
class function TStr.LoadStreamToArray(Src: TStream; Encoding: TEncoding = nil): TArray<string>;
var
L: TStringList;
begin
L := TStringList.Create;
try
if Encoding = nil then
Encoding := TEncoding.UTF8;
L.LoadFromStream(Src, Encoding);
Result := L.ToStringArray;
finally
Sys.FreeAndNil(L);
end;
end;
class procedure TStr.SaveArrayToFile(const Src: TArray<string>; const Filename: string; Encoding: TEncoding);
var
S: TMemoryStream;
begin
S := TMemoryStream.Create;
try
SaveArrayToStream(Src, S, Encoding);
S.SaveToFile(Filename);
finally
Sys.FreeAndNil(S);
end;
end;
class procedure TStr.SaveArrayToStream(const Src: TArray<string>; const Dst: TStream; Encoding: TEncoding);
var
L: TStringList;
I: Integer;
begin
L := TStringList.Create;
try
for I := Low(Src) to High(Src) do
L.Add(Src[I]);
if Encoding = nil then
Encoding := TEncoding.UTF8;
L.SaveToStream(Dst, Encoding);
finally
Sys.FreeAndNil(L);
end;
end;
class procedure TStr.Save(Dst: TStream; const S: string; Encoding: TEncoding);
var
B: TArray<System.Byte>;
begin
if Encoding=nil then
Encoding := TEncoding.UTF8;
B := Encoding.GetBytes(S);
Dst.Write(B, Length(B));
end;
class procedure TStr.Save(const FileName: string; const S: string; Encoding: TEncoding);
var
F: TFileStream;
begin
F := TFileStream.Create(FileName, fmCreate);
try
Save(F, S, Encoding);
finally
F.Free;
end;
end;
class function TStr.TextDistance(const a, b: string; StrDistType: TTextDistance): integer;
begin
case StrDistType of
tdLevenstein: result := LevensteinDistance(a,b);
else raise Exception.Create('Error');
end;
end;
class function TStr.TextPosition(const ASubStr, AText: string; AOffset: integer): Integer;
begin
Result := AText.ToUpper.IndexOf(ASubStr.ToUpper, AOffset);
end;
class function TStr.Contains(const ASubStr, AText: string): boolean;
begin
result := TextPosition(ASubStr, AText) >= 0;
end;
class function TStr.Random(ALen: integer; AFrom, ATo: Char): string;
var
i: Integer;
begin
setlength(result, ALen);
for i := Low(result) to High(result) do
result[i] := Char(
Integer(AFrom) +
System.Random(Integer(ATo)-Integer(AFrom)+1)
);
end;
class function TStr.Random: string;
begin
result := TStr.Random(System.Random(20));
end;
{ TTokenPos }
class operator TTokenPos.Add(const A, B: TTokenPos): TTokenPos;
begin
result.SetPos(
Min(A.Start, B.Start),
Max(A.Start+A.Len, B.Start+B.Len) - result.Start
);
end;
function TTokenPos.BytesToChars: TTokenPos;
begin
Assert((Start mod SizeOf(Char)=0) and (Len mod SizeOf(Char)=0));
result.SetPos(Start div SizeOf(Char), Len div SizeOf(Char));
end;
constructor TTokenPos.Create(AStart, ALen: integer);
begin
{$IF SizeOf(TTokenPos)<>SizeOf(Start)+SizeOf(Len)}
Self := Default(TTokenPos);
{$ENDIF}
Start := AStart;
Len := ALen;
end;
procedure TTokenPos.SetPos(AStart, ALen: integer);
begin
{$IF SizeOf(TTokenPos)<>SizeOf(Start)+SizeOf(Len)}
Self := Default(TTokenPos);
{$ENDIF}
Start := AStart;
Len := ALen;
end;
class operator TTokenPos.In(const A: integer; const B: TTokenPos): Boolean;
begin
result := (A >= B.Start) and (A < B.Start + B.Len);
end;
class operator TTokenPos.Subtract(const A, B: TTokenPos): TTokenPos;
begin
if A.Start>B.Start then
result := B - A
else
result.SetPos(A.Start + A.Len, B.Start-result.Start);
end;
{ TTokLines }
procedure TTokLines.TokenizerCreated;
begin
inherited;
FOmmitEmptyTokens := False;
end;
{ Find strings separated by one of possible end-of-line marker. Check
section "Unicode" for details here: https://en.wikipedia.org/wiki/Newline
LF: Line Feed, U+000A
VT: Vertical Tab, U+000B
FF: Form Feed, U+000C
CR: Carriage Return, U+000D
CR+LF: CR (U+000D) followed by LF (U+000A)
NEL: Next Line, U+0085
LS: Line Separator, U+2028
PS: Paragraph Separator, U+2029
Additionally we support:
LF+CR U+000A + U+000D }
class function TTokLines.GetLine(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
const
LF : Char = #$000A; { Line Feed }
VT : Char = #$000B; { Vertical Tab }
FF : Char = #$000C; { Form Feed }
CR : Char = #$000D; { Carriage Return }
NEL : Char = #$0085; { Next Line }
LS : Char = #$2028; { Line Separator }
PS : Char = #$2029; { Paragraph Separator }
{ Multichar markers of new line: LF+CR and CR+LF }
var
N: Integer;
begin
Result := Len > 0;
if not result then
Exit;
{ empty string terminated by EndOfLine }
if (Text^>=LF) and (Text^<=CR) or (Text^=NEL) or (Text^=LS) or (Text^=PS) then
begin
Res.DelimitersPrefix := 0;
Res.Len := 0;
if (Len>1) and ((Text[0]=LF) and (Text[1]=CR) or (Text[0]=CR) and (Text[1]=LF)) then
Res.DelimitersSuffix := 2
else
Res.DelimitersSuffix := 1;
Exit;
end;
{ not empty string terminated by EndOfLine or EndOfFile }
N := 0;
while (Len > 0) and not ((Text^>=LF) and (Text^<=CR) or (Text^=NEL) or (Text^=LS) or (Text^=PS)) do
begin
Inc(Text);
Dec(Len);
inc(N);
end;
Res.DelimitersPrefix := 0;
Res.Len := N;
if Len <= 0 then
Res.DelimitersSuffix := 0
else
if (Len>1) and ((Text[0]=LF) and (Text[1]=CR) or (Text[0]=CR) and (Text[1]=LF)) then
Res.DelimitersSuffix := 2
else
Res.DelimitersSuffix := 1;
end;
class function TTokLines.GetLineLength(const Text: PChar; Len: integer; IncludeEOL: boolean): Integer;
var
Token: TTokenInfo;
begin
if not GetLine(Text, Len, Token) then
result := 0
else
if IncludeEOL then
result := Token.DelimitersPrefix + Token.Len + Token.DelimitersSuffix
else
result := Token.Len;
end;
function TTokLines.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
begin
result := GetLine(Text, Len, Res);
end;
(* // implementation where "#13#10" is two empty strings (very similar to NotePad++), seem to be not correct
function TTokLines.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
const
LF : Char = #$000A; { Line Feed }
VT : Char = #$000B; { Vertical Tab }
FF : Char = #$000C; { Form Feed }
CR : Char = #$000D; { Carriage Return }
NEL : Char = #$0085; { Next Line }
LS : Char = #$2028; { Line Separator }
PS : Char = #$2029; { Paragraph Separator }
{ Multichar markers of new line: LF+CR and CR+LF }
var
D,T: Integer;
begin
if Len <= 0 then
Exit(False);
D := 0;
if (Text^>=LF) and (Text^<=CR) or (Text^=NEL) or (Text^=LS) or (Text^=PS) then
begin
if (Len>1) and ((Text[0]=LF) and (Text[1]=CR) or (Text[0]=CR) and (Text[1]=LF)) then
begin
inc(Text, 2);
dec(Len, 2);
inc(D, 2);
end
else
begin
inc(Text);
dec(Len);
inc(D);
end;
end;
T := 0;
if (D=0) or FSkipLineFeed then
begin
while (Len > 0) and not ((Text^>=LF) and (Text^<=CR) or (Text^=NEL) or (Text^=LS) or (Text^=PS)) do
begin
Inc(Text);
Dec(Len);
inc(T);
end;
FSkipLineFeed := Len>0;
end;
Res.Delimiters := D;
Res.Len := T;
result := Res.Delimiters+Res.Len>0;
end; *)
{ TTokText }
function TTokText.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
T: Integer;
begin
T := 0;
if Len > 0 then
begin
if Text[0].IsWhiteSpace then
begin
repeat
Inc(Text);
Dec(Len);
inc(T);
until (Len=0) or not Text[0].IsWhiteSpace;
FLastTokenType := tttWhitespace;
end
else
if Text[0].IsPunctuation then
begin
repeat
Inc(Text);
Dec(Len);
inc(T);
until (Len=0) or not Text[0].IsPunctuation;
FLastTokenType := tttPunctuation;
end
else
begin
repeat
Inc(Text);
Dec(Len);
inc(T);
until (Len=0) or Text[0].IsPunctuation or Text[0].IsWhiteSpace;
FLastTokenType := tttWord;
end;
end;
result := T > 0;
if result then
begin
Res.DelimitersPrefix := 0;
Res.Len := T;
end;
end;
{ TTokDelegated }
constructor TTokDelegated.Create(AText: PChar; ATextLen: integer; AProc: TDelegatedTokenizer);
begin
inherited Create(AText, ATextLen);
FProc := AProc;
end;
constructor TTokDelegated.Create(const AText: string; AProc: TDelegatedTokenizer);
begin
inherited Create(AText);
FProc := AProc;
end;
function TTokDelegated.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
begin
result := FProc(Text, Len, Res);
end;
{ TTokNot }
constructor TTokNot.Create(ATokenizer: TTokCustom; AOwnsInnerTokenizer: boolean);
begin
inherited Create;
FTokenizer := ATokenizer;
FOwnsInnerTokenizer := AOwnsInnerTokenizer;
end;
destructor TTokNot.Destroy;
begin
FreeAndNil(FTokenizer);
inherited;
end;
procedure TTokNot.SetText(AText: PChar; ATextLen: integer);
begin
FTokenizer.SetText(AText, ATextLen);
end;
function TTokNot.GetText: PChar;
begin
result := FTokenizer.GetText;
end;
function TTokNot.GetTextLen: integer;
begin
result := FTokenizer.GetTextLen;
end;
procedure TTokNot.SetPosition(const AValue: integer);
begin
FTokenizer.SetPosition(AValue);
end;
function TTokNot.GetAsString: string;
begin
result := FTokenizer.AsString;
end;
function TTokNot.GetPosition: integer;
begin
result := FTokenizer.GetPosition;
end;
procedure TTokNot.ResetTokenizer;
begin
FTokenizer.ResetTokenizer;
FFinished := False;
FValueLen := 0;
end;
procedure TTokNot.SaveTokenizerPos(W: TWriter);
begin
FTokenizer.SaveTokenizerPos(W);
end;
procedure TTokNot.LoadTokenizerPos(R: TReader);
begin
FTokenizer.LoadTokenizerPos(R);
end;
function TTokNot.NextToken(out AToken: TTokenInfo): Boolean;
var
T: TTokenInfo;
S: integer;
begin
if FFinished then
Exit(False);
S := FTokenizer.Position;
repeat
if not FTokenizer.NextToken(T) then
begin
FFinished := True;
result := FValueLen>0;
if result then
begin
AToken.Start := FValueStart;
AToken.DelimitersPrefix := 0;
AToken.Len := FValueLen;
AToken.DelimitersSuffix := 0;
end;
end
else
begin
AToken.DelimitersPrefix := 0;
if FValueLen>0 then
begin
AToken.Start := FValueStart;
AToken.Len := FValueLen + T.DelimitersPrefix;
end
else
begin
AToken.Start := T.Start;
AToken.Len := T.DelimitersPrefix;
end;
AToken.DelimitersSuffix := T.Len;
FValueLen := T.DelimitersSuffix;
if FValueLen>0 then
FValueStart := AToken.Start + AToken.DelimitersPrefix + AToken.Len;
result := AToken.Len>0;
end;
until result or FFinished;
{ if we skiped some empty values, then AToken.Start can be greater than S }
if result and (AToken.Start > S) then
begin
Inc(AToken.DelimitersPrefix, AToken.Start - S);
AToken.Start := S;
end;
end;
{ TTokCustom }
constructor TTokCustom.Create;
begin
TokenizerCreated;
end;
constructor TTokCustom.Create(AText: PChar; ATextLen: integer);
begin
TokenizerCreated;
end;
constructor TTokCustom.Create(const AText: string);
begin
TokenizerCreated;
end;
procedure TTokCustom.TokenizerCreated;
begin
FOmmitEmptyTokens := True;
end;
function TTokCustom.GetAsString: string;
begin
SetLength(result, TextLen);
if Length(result)>0 then
System.Move(Text^, result[Low(result)], length(result)*SizeOf(char));
end;
function TTokCustom.GetState: TTokenizerState;
var
W: TWriter;
begin
result.State := TInterfacedObject<TMemoryStream>.Create(TMemoryStream.Create);
W := TWriter.Create(result.State.Data, 256);
try
SaveTokenizerPos(W);
finally
W.Free;
end;
end;
procedure TTokCustom.SetState(AState: TTokenizerState);
var
R: TReader;
begin
AState.State.Data.Position := 0;
R := TReader.Create(AState.State.Data, 256);
try
LoadTokenizerPos(R);
finally
R.Free;
end;
end;
function TTokCustom.GetTokenAsString(const APos: TTokenPos): string;
var
L: Integer;
begin
L := Max(0, Min(APos.Len, GetTextLen-APos.Start));
SetLength(result, L);
if L>0 then
System.Move(Text[APos.Start], Result[Low(Result)], L*SizeOf(Char));
end;
function TTokCustom.GetTokenCount: integer;
var
P: Integer;
T: TTokenPos;
begin
Result := 0;
P := Position;
Reset;
while Next(T) do
Inc(Result);
Position := P;
end;
procedure TTokCustom.GetTokens(var ADst: TArray<TTokenPos>);
var
I: Integer;
begin
Reset;
SetLength(ADst, TokenCount);
Reset;
for I := 0 to High(ADst) do
Next(ADst[I]);
end;
procedure TTokCustom.GetTokens(var ADst: TArray<String>);
var
I: Integer;
begin
Reset;
SetLength(ADst, TokenCount);
Reset;
for I := 0 to High(ADst) do
Next(ADst[I]);
end;
procedure TTokCustom.GetTokens(ADst: TStrings);
var
S: string;
begin
Reset;
while Next(S) do
ADst.Add(S);
end;
procedure TTokCustom.SaveTokenizerPos(W: TWriter);
begin
{$IFDEF DEBUG}
W.WriteString(ClassName);
{$ENDIF}
W.WriteInteger(1); { state format version }
end;
procedure TTokCustom.LoadTokenizerPos(R: TReader);
begin
{$IFDEF DEBUG}
if not AnsiSameText(R.ReadString, ClassName) then
raise Exception.Create('Error');
{$ENDIF}
if (R.ReadInteger<>1) then
raise Exception.Create('Error');
end;
procedure TTokCustom.Reset;
begin
ResetTokenizer;
end;
procedure TTokCustom.Reset(ANewText: PChar; ATextLen: integer);
begin
SetText(ANewText, ATextLen);
ResetTokenizer;
end;
function TTokCustom.Next(out AToken: TTokenPos): Boolean;
var
TokenInfo: TTokenInfo;
begin
if not FOmmitEmptyTokens then
result := NextToken(TokenInfo)
else
repeat
result := NextToken(TokenInfo);
until not result or (TokenInfo.Len>0);
if result then
begin
AToken.Start := TokenInfo.Start + TokenInfo.DelimitersPrefix;
AToken.Len := TokenInfo.Len;
end;
end;
function TTokCustom.Next(out AToken: String): Boolean;
var
TokenPos: TTokenPos;
begin
result := Next(TokenPos);
if result then
AToken := Tokens[TokenPos];
end;
function TTokCustom.Next: String;
var
TokenPos: TTokenPos;
begin
if Next(TokenPos) then
result := Tokens[TokenPos]
else
result := '';
end;
class procedure TTokCustom.Parse(const AText: string; var ADst: TArray<TTokenPos>);
var
T: TTokCustom;
begin
T := Self.Create;
try
T.SetText(PChar(AText), Length(AText));
T.GetTokens(ADst);
finally
T.Free;
end;
end;
class procedure TTokCustom.Parse(const AText: string; var ADst: TArray<String>);
var
T: TTokCustom;
begin
T := Self.Create;
try
T.SetText(PChar(AText), Length(AText));
T.GetTokens(ADst);
finally
T.Free;
end;
end;
class procedure TTokCustom.Parse(const AText: string; ADst: TStrings);
var
T: TTokCustom;
begin
T := Self.Create;
try
T.SetText(PChar(AText), Length(AText));
T.GetTokens(ADst);
finally
T.Free;
end;
end;
class procedure TTokCustom.Parse(const AText, ADelimiter: string; var ADst: string);
var
T: TTokCustom;
S: string;
begin
T := Self.Create;
try
T.SetText(PChar(AText), Length(AText));
if not T.Next(ADst) then
ADst := ''
else
while T.Next(S) do
ADst := ADst + ADelimiter + S;
finally
T.Free;
end;
end;
class function TTokCustom.Parse(const AText: string): string;
begin
Parse(AText, '', result);
end;
{ TTokCompound }
constructor TTokCompound.Create(const ATokenizers: array of TTokCustom);
var
i: Integer;
begin
inherited Create;
FTokenizers := TObjectList<TTokCustom>.Create;
FTokenizers.Capacity := Length(ATokenizers);
for i := 0 to High(ATokenizers) do
FTokenizers.Add(ATokenizers[i]);
SetLength(FOffsets, Length(ATokenizers));
end;
destructor TTokCompound.Destroy;
begin
FreeAndNil(FTokenizers);
inherited;
end;
procedure TTokCompound.SetText(AText: PChar; ATextLen: integer);
begin
First.SetText(AText, ATextLen);
end;
function TTokCompound.GetText: PChar;
begin
result := First.Text;
end;
function TTokCompound.GetTextLen: integer;
begin
result := First.TextLen;
end;
procedure TTokCompound.SetPosition(const AValue: integer);
begin
{ compound tokenizer can not change position randomly }
raise Exception.Create('invalid op');
end;
function TTokCompound.GetPosition: integer;
var
i: Integer;
begin
i := TokenizersCount-1;
result := FTokenizers[i].Position + FOffsets[i];
end;
procedure TTokCompound.ResetTokenizer;
begin
inherited;
First.Reset;
FCurrentTokenizer := 0;
end;
procedure TTokCompound.SaveTokenizerPos(W: TWriter);
var
i: Integer;
begin
inherited;
W.WriteInteger(1); { state format version }
W.WriteInteger(FTokenizers.Count);
W.WriteInteger(FCurrentTokenizer);
for i := 0 to FTokenizers.Count-1 do
FTokenizers[i].SaveTokenizerPos(W);
end;
procedure TTokCompound.LoadTokenizerPos(R: TReader);
var
i: Integer;
begin
inherited;
if R.ReadInteger<>1 then
raise Exception.Create('Error'); { protocol version - must be 1 }
if R.ReadInteger<>FTokenizers.Count then
raise Exception.Create('Error'); { stored with another set of tokenizers }
FCurrentTokenizer := R.ReadInteger;
if (FCurrentTokenizer<0) or (FCurrentTokenizer>=FTokenizers.Count) then
raise Exception.Create('Error'); { bad index }
for i := 0 to FTokenizers.Count-1 do
FTokenizers[i].LoadTokenizerPos(R);
end;
function TTokCompound.NextToken(out AToken: TTokenInfo): Boolean;
begin
result := False;
while (FCurrentTokenizer >= 0) and (FCurrentTokenizer < FTokenizers.Count) do
begin
result := FTokenizers[FCurrentTokenizer].NextToken(AToken);
{ no more token on this level - go up }
if not result then
begin
dec(FCurrentTokenizer);
Continue;
end;
{ token on last level - match found, we should translate result into coordinates of first tokenizer }
if FCurrentTokenizer>=FTokenizers.Count-1 then
begin
Inc(AToken.Start, FOffsets[FCurrentTokenizer]);
Exit;
end;
{ initialize next level }
inc(FCurrentTokenizer);
FTokenizers[FCurrentTokenizer].SetText(@FTokenizers[FCurrentTokenizer-1].Text[AToken.Start+AToken.DelimitersPrefix], AToken.Len);
FTokenizers[FCurrentTokenizer].Reset;
FOffsets[FCurrentTokenizer] := FOffsets[FCurrentTokenizer-1] + AToken.Start+AToken.DelimitersPrefix;
end;
end;
function TTokCompound.GetAsString: string;
begin
result := First.AsString;
end;
function TTokCompound.GetFirst: TTokCustom;
begin
result := FTokenizers[0];
end;
function TTokCompound.GetLast: TTokCustom;
begin
result := FTokenizers[FTokenizers.Count-1];
end;
function TTokCompound.GetTokenizer(n: integer): TTokCustom;
begin
result := FTokenizers[n];
end;
function TTokCompound.GetTokenizersCount: integer;
begin
result := FTokenizers.Count;
end;
{ TTokCustomText }
constructor TTokCustomText.Create(AText: PChar; ATextLen: integer);
begin
inherited;
FTextStorage := '';
FText := AText;
FTextLen := ATextLen;
Reset;
end;
constructor TTokCustomText.Create(const AText: string);
begin
inherited;
Reset(AText);
end;
procedure TTokCustomText.Reset(const AText: string);
begin
FTextStorage := AText;
FText := PChar(FTextStorage);
FTextLen := Length(FTextStorage);
Reset;
end;
procedure TTokCustomText.Reset(const AText: string; AStart, ALen: integer);
begin
FTextStorage := AText;
FText := @FTextStorage[AStart + Low(FTextStorage)];
FTextLen := ALen;
Reset;
end;
procedure TTokCustomText.Reset(const AText: PChar; ALen: integer);
begin
FTextStorage := '';
FText := AText;
FTextLen := ALen;
Reset;
end;
procedure TTokCustomText.SetText(AText: PChar; ATextLen: integer);
begin
FTextStorage := '';
FText := AText;
FTextLen := ATextLen;
end;
function TTokCustomText.GetText: PChar;
begin
result := FText;
end;
function TTokCustomText.GetTextLen: integer;
begin
result := FTextLen;
end;
procedure TTokCustomText.SetPosition(const AValue: integer);
begin
FPosition := AValue;
end;
function TTokCustomText.GetAsString: string;
begin
if FTextStorage<>'' then
result := FTextStorage
else
result := inherited;
end;
function TTokCustomText.GetPosition: integer;
begin
result := FPosition;
end;
procedure TTokCustomText.ResetTokenizer;
begin
Position := 0;
end;
procedure TTokCustomText.SaveTokenizerPos(W: TWriter);
begin
{inherited;}
W.WriteInteger(1); { state format version }
W.WriteInteger(Position);
end;
procedure TTokCustomText.LoadTokenizerPos(R: TReader);
begin
{inherited;}
if R.ReadInteger<>1 then
raise Exception.Create('Error'); { state format version }
Position := R.ReadInteger;
end;
function TTokCustomText.NextToken(out AToken: TTokenInfo): Boolean;
var
L: Integer;
begin
L := FTextLen-FPosition;
if L<=0 then
result := False
else
begin
AToken.Clear;
result := FindNextToken(pointer(FText+FPosition), L, AToken);
if result then
begin
Assert(AToken.Start = 0);
AToken.Start := FPosition;
inc(FPosition, AToken.DelimitersPrefix+AToken.Len+AToken.DelimitersSuffix);
end;
end;
end;
{ TTokNonSpace }
function TTokNonSpace.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
D,T: Integer;
begin
D := 0;
while (Len > 0) and (Text^ <= ' ') do
begin
Inc(Text);
Dec(Len);
inc(D);
end;
T := 0;
while (Len > 0) and (Text^ > ' ') do
begin
Inc(Text);
Dec(Len);
inc(T);
end;
result := T > 0;
if result then
begin
Res.DelimitersPrefix := D;
Res.Len := T;
end;
end;
{ TTokLetters }
function TTokLetters.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
D,T: Integer;
begin
D := 0;
while (Len > 0) and not Text^.IsLetter do
begin
Inc(Text);
Dec(Len);
inc(D);
end;
T := 0;
while (Len > 0) and Text^.IsLetter do
begin
Inc(Text);
Dec(Len);
inc(T);
end;
result := T > 0;
if result then
begin
Res.DelimitersPrefix := D;
Res.Len := T;
end;
end;
{ TTokDigits }
function TTokDigits.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
begin
result := NextDigits(Text, Len, Res);
end;
class function TTokDigits.IsStartOfDigits(C: Char): boolean;
begin
result := C.IsDigit;
end;
class function TTokDigits.NextDigits(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
I,J: Integer;
begin
J := Len;
for I := 0 to Len-1 do
if IsStartOfDigits(Text[I]) then
begin
J := I;
Break;
end;
inc(Text, J);
dec(Len, J);
Res.DelimitersPrefix := J;
J := Len;
for I := 0 to Len-1 do
if not Char(Text[I]).IsDigit then
begin
J := I;
Break;
end;
Res.Len := J;
result := Res.DelimitersPrefix+Res.Len > 0;
end;
{ TTokLettersOrDigits }
function TTokLettersOrDigits.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
D,T: Integer;
begin
D := 0;
while (Len > 0) and not Text^.IsLetterOrDigit do
begin
Inc(Text);
Dec(Len);
inc(D);
end;
T := 0;
while (Len > 0) and Text^.IsLetterOrDigit do
begin
Inc(Text);
Dec(Len);
inc(T);
end;
result := T > 0;
if result then
begin
Res.DelimitersPrefix := D;
Res.Len := T;
end;
end;
{ TTokNumbers }
{ Find number in string. Only general notation is supported.
Correct: "12" "12." "1.2" "-134.5" "+2"
"1E5" -> "1" "5"
"Date: 12.12.2016" -> "12.12" "2016"
"P12" -> "12" }
function TTokNumbers.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
D,T: Integer;
begin
{ RE: Num = ("+" | "-") Digit Digit* ("." Digit*)? }
D := 0;
repeat
while (Len > 0) and (Text^ <> '+') and (Text^ <> '-') and not Text^.IsDigit do
begin
Inc(Text);
Dec(Len);
inc(D);
end;
{ Len=0 or "+" or "-" or Digit }
if Len <= 0 then
Exit(False);
{ "+" or "-" or Digit }
if Text^.IsDigit then
Break;
{ "+" or "-" }
if Len < 2 then
Exit(False);
if (Text+1)^.IsDigit then
Break;
inc(Text);
Dec(Len);
inc(D);
until false;
if Len<=0 then
Exit(False);
{ we found start pos of number, now we should find whole number }
T := 0;
if (Text^='+') or (Text^='-') then
begin
inc(Text);
dec(Len);
inc(T);
end;
while (Len>0) do
if Text^.IsDigit then
begin
Inc(Text);
Dec(Len);
Inc(T);
end
else
if (Text^=FormatSettings.DecimalSeparator) or (Text^='.') then
begin
repeat
Inc(Text);
Dec(Len);
Inc(T);
until (Len<=0) or not Text^.IsDigit;
Break;
end
else
Break;
result := T > 0;
if result then
begin
Res.DelimitersPrefix := D;
Res.Len := T;
end;
end;
{ TTokIdentifier }
class function TTokIdentifier.IsStartOfIdentifier(C: Char): Boolean;
begin
result := C.IsLetter or (C='_');
end;
class function TTokIdentifier.NextIdentifier(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
I,J: Integer;
begin
{ find first char of identifier }
J := Len;
for I := 0 to Len-1 do
if IsStartOfIdentifier(Text[I]) then
begin
J := I;
Break;
end;
inc(Text, J);
dec(Len, J);
Res.DelimitersPrefix := J;
{ find all other chars of identifier }
J := Len;
for I := 1 to Len-1 do
if not Char(Text[I]).IsLetter and (Text[I]<>'_') and not Char(Text[I]).IsDigit then
begin
J := I;
Break;
end;
Res.Len := J;
result := Res.DelimitersPrefix + Res.Len > 0;
end;
function TTokIdentifier.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
begin
result := NextIdentifier(Text, Len, Res);
end;
{ TTokCharDelimitedLines }
constructor TTokCharDelimitedLines.Create(AText: PChar; ATextLen: integer; ADelimiter: Char; ACaseSensitive: Boolean = False);
begin
inherited Create(AText, ATextLen);
FDelimiter := ADelimiter;
FCaseSensitive := ACaseSensitive;
end;
constructor TTokCharDelimitedLines.Create(const AText: string; ADelimiter: Char; ACaseSensitive: Boolean = False);
begin
inherited Create(AText);
FDelimiter := ADelimiter;
FCaseSensitive := ACaseSensitive;
end;
function TTokCharDelimitedLines.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
T: Integer;
L,U: Char;
begin
if FCaseSensitive then
begin
L := FDelimiter;
T := 0;
while (Len > 0) and (Text^ <> L) do
begin
Inc(Text);
Dec(Len);
inc(T);
end;
end
else
begin
L := FDelimiter.ToLower;
U := FDelimiter.ToUpper;
T := 0;
while (Len > 0) and (Text^<>L) and (Text^<>U) do
begin
Inc(Text);
Dec(Len);
inc(T);
end;
end;
result := T > 0;
if result then
begin
Res.Len := T;
Res.DelimitersSuffix := IfThen(Len > 0, 1, 0);
end;
end;
{ TTokenInfo }
procedure TTokenInfo.Clear;
begin
{ Start := 0; start position in the text
DelimitersPrefix := 0; number of preceding delimiters or zero
Len := 0; length of the token or zero
DelimitersSuffix := 0; number of trailing delimiters or zero }
Self := Default(TTokenInfo);
end;
{ TTokLiterals }
class function TTokLiterals.GetLiteralLen(Text: PChar; Len: integer): integer;
var
Res: TTokenInfo;
begin
if (Len<=0) or not IsStartOfLiteral(Text^) then
result := 0
else
begin
Res.Clear;
if not NextLiteral(Text, Len, Res) then
raise Exception.Create('Error');
Assert((Res.DelimitersPrefix+Res.DelimitersSuffix=0) and (Res.Len>0));
result := Res.Len;
end;
end;
function TTokLiterals.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
begin
result := NextLiteral(Text, Len, Res);
end;
class function TTokLiterals.IsStartOfLiteral(C: Char): boolean;
begin
result := C='''';
end;
class function TTokLiterals.NextLiteral(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
I,J: Integer;
begin
{ find first char of identifier }
J := Len;
for I := 0 to Len-1 do
if IsStartOfLiteral(Text[I]) then
begin
J := I;
Break;
end;
inc(Text, J);
dec(Len, J);
Res.DelimitersPrefix := J;
{ find all other chars of identifier }
if Len>0 then
begin
J := 1;
inc(Text);
dec(Len);
while Len>0 do
if Text^<>'''' then
begin
inc(Text);
dec(Len);
inc(J);
end
else
if (Len>1) and (Text[1]='''') then
begin
inc(Text,2);
dec(Len,2);
inc(J, 2);
end
else
begin
inc(J);
Break;
end;
res.Len := J;
end;
result := Res.DelimitersPrefix + Res.Len > 0;
end;
{ TTokComments }
class function TTokComments.IsStartOfComment(Text: PChar; Len: integer): Boolean;
begin
result := (Text^='{') or
(Len>1) and
(
(Text^='(') and (Text[1]='*') or
(Text^='/') and (Text[1]='/')
);
end;
class function TTokComments.NextComment(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
D,T,I: Integer;
begin
{ { (* // ' }
D := 0;
T := 0;
while Len>0 do
if IsStartOfComment(Text, Len) then
case Text^ of
'{':
begin
T := Len;
for I := 1 to Len-1 do
if Text[I]='}' then
begin
T := I+1;
Break;
end;
Break;
end;
'(':
begin
T := Len;
for I := 2 to Len-2 do
if (Text[I]='*') and (Text[I+1]=')') then
begin
T := I+2;
Break;
end;
Break;
end;
'/':
begin
T := TTokLines.GetLineLength(Text, Len, False);
Break;
end;
else
raise Exception.Create('Error');
end
else
if TTokLiterals.IsStartOfLiteral(Text^) then
begin
I := TTokLiterals.GetLiteralLen(Text, Len);
Inc(D, I);
Inc(Text, I);
Dec(Len, I);
end
else
begin
inc(D);
inc(Text);
dec(Len);
end;
Res.DelimitersPrefix := D;
Res.Len := T;
result := D+T > 0;
end;
function TTokComments.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
begin
result := NextComment(Text, Len, Res);
end;
{ TTokWhitespaces }
function TTokWhitespaces.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
begin
result := NextWhitespace(Text, Len, Res);
end;
class function TTokWhitespaces.IsStartOfWhitespace(C: Char): Boolean;
begin
result := C.IsWhiteSpace;
end;
class function TTokWhitespaces.NextWhitespace(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
var
I,J: Integer;
begin
{ find first char }
J := Len;
for I := 0 to Len-1 do
if IsStartOfWhitespace(Text[I]) then
begin
J := I;
Break;
end;
inc(Text, J);
dec(Len, J);
Res.DelimitersPrefix := J;
{ find all other chars }
J := Len;
for I := 1 to Len-1 do
if not Char(Text[I]).IsWhitespace then
begin
J := I;
Break;
end;
Res.Len := J;
result := Res.DelimitersPrefix + Res.Len > 0;
end;
{ TTokPascal }
function TTokPascal.GetAllTokens: TArray<TToken>;
var
List: TList<TToken>;
Token: TToken;
begin
List := TList<TToken>.Create;
try
List.Capacity := Max(1000, TextLen div 2);
Reset;
while Next(Token.FPos) do
begin
Token.FType := LastTokenType;
List.Add(Token);
end;
result := List.ToArray;
finally
List.Free;
end;
end;
procedure TTokPascal.LoadTokenizerPos(R: TReader);
begin
inherited;
R.Read(FTokenType, SizeOF(FTokenType));
end;
function TTokPascal.Next(ATokenTypes: TPasTokenTypes; out AToken: TTokenPos): Boolean;
begin
while Next(AToken) do
if LastTokenType in ATokenTypes then
Exit(True);
result := False;
end;
function TTokPascal.Next(ATokenTypes: TPasTokenTypes; out AToken: String): Boolean;
begin
while Next(AToken) do
if LastTokenType in ATokenTypes then
Exit(True);
result := False;
end;
function TTokPascal.Next(ATokenTypes: TPasTokenTypes): String;
begin
while Next(result) do
if LastTokenType in ATokenTypes then
Exit;
result := '';
end;
class function TTokPascal.RemoveComments(const SrcPasText: string): string;
var
p: TTokPascal;
e: TStringEditor;
t: TTokenPos;
begin
p := TTokPascal.Create(SrcPasText);
e.Init;
while p.Next([Comment], t) do
e.Delete(t.Start, t.Len);
result := e.Apply(SrcPasText);
end;
procedure TTokPascal.SaveTokenizerPos(W: TWriter);
begin
inherited;
W.Write(FTokenType, SizeOF(FTokenType));
end;
class function TTokPascal.IsDelimiterChar(C: Char): Boolean;
begin
result := String(Delimiters).IndexOf(C) >= Low(String);
end;
function TTokPascal.FindNextToken(Text: PChar; Len: integer; var Res: TTokenInfo): Boolean;
begin
result := Len>0;
if not result then
Exit;
if TTokWhitespaces.IsStartOfWhitespace(Text^) then
begin
result := TTokWhitespaces.NextWhitespace(Text, Len, Res);
Assert(result and (Res.DelimitersPrefix+Res.DelimitersSuffix=0) and (Res.Len>0));
FTokenType := TPasTokenType.Whitespace;
Exit;
end;
if TTokLiterals.IsStartOfLiteral(Text^) then
begin
result := TTokLiterals.NextLiteral(Text, Len, Res);
Assert(result and (Res.DelimitersPrefix+Res.DelimitersSuffix=0) and (Res.Len>0));
FTokenType := TPasTokenType.Literal;
Exit;
end;
if TTokDigits.IsStartOfDigits(Text^) then
begin
result := TTokDigits.NextDigits(Text, Len, Res);
Assert(result and (Res.DelimitersPrefix+Res.DelimitersSuffix=0) and (Res.Len>0));
FTokenType := TPasTokenType.Digits;
Exit;
end;
if TTokComments.IsStartOfComment(Text, Len) then
begin
result := TTokComments.NextComment(Text, Len, Res);
Assert(result and (Res.DelimitersPrefix+Res.DelimitersSuffix=0) and (Res.Len>0));
FTokenType := TPasTokenType.Comment;
Exit;
end;
if TTokIdentifier.IsStartOfIdentifier(Text^) then
begin
result := TTokIdentifier.NextIdentifier(Text, Len, Res);
Assert(result and (Res.DelimitersPrefix+Res.DelimitersSuffix=0) and (Res.Len>0));
FTokenType := TPasTokenType.Identifier;
Exit;
end;
if IsDelimiterChar(Text^) then
begin
Res.Len := 1;
FTokenType := TPasTokenType.Delimiter;
Exit;
end;
FTokenType := TPasTokenType.Unknown;
Res.Len := 1;
end;
{ TStringEditor.TInstr }
procedure TStringEditor.TReplace.Clear;
begin
Self := Default(TReplace);
end;
{ TStringEditor }
procedure TStringEditor.Clear;
begin
Instructions.Clear;
end;
procedure TStringEditor.Add(const Instr: TReplace);
var
I: Integer;
begin
I := Instructions.Add(Instr);
Instructions.Items[I].Order := I;
end;
procedure TStringEditor.Delete(const Pos: TTokenPos);
var
r: TReplace;
begin
r.Clear;
r.DstPos := Pos;
Add(r);
end;
procedure TStringEditor.Delete(const Start, Len: integer);
var
r: TReplace;
begin
r.Clear;
r.DstPos.Start := Start;
r.DstPos.Len := Len;
Add(r);
end;
procedure TStringEditor.Delete(const Pos: integer);
var
r: TReplace;
begin
r.Clear;
r.DstPos.Start := Pos;
r.DstPos.Len := 1;
Add(r);
end;
procedure TStringEditor.Insert(Pos: integer; const Substr: string; const SubStrPos: TTokenPos);
var
r: TReplace;
begin
r.Clear;
r.SrcText := Substr;
r.SrcPos := SubStrPos;
r.DstPos.Start := Pos;
Add(r);
end;
procedure TStringEditor.Insert(Pos: integer; const Substr: string; const SubStrOffset, SubStrLen: integer);
var
r: TReplace;
begin
r.Clear;
r.SrcText := Substr;
r.SrcPos.Start := SubStrOffset;
r.SrcPos.Len := SubStrLen;
r.DstPos.Start := Pos;
Add(r);
end;
procedure TStringEditor.Init;
begin
Self := Default(TStringEditor);
end;
procedure TStringEditor.Insert(Pos: integer; const Substr: string);
var
r: TReplace;
begin
r.Clear;
r.SrcText := Substr;
r.SrcPos.Start := 0;
r.SrcPos.Len := Length(Substr);
r.DstPos.Start := Pos;
Add(r);
end;
procedure TStringEditor.Replace(const Pos: TTokenPos; const Substr: string);
var
r: TReplace;
begin
r.Clear;
r.SrcText := Substr;
r.SrcPos.Start := 0;
r.SrcPos.Len := Length(Substr);
r.DstPos := Pos;
Add(r);
end;
procedure TStringEditor.Replace(const Start, Len: integer; const Substr: string; const SubStrOffset, SubStrLen: integer);
var
r: TReplace;
begin
r.Clear;
r.SrcText := Substr;
r.SrcPos.Start := SubStrOffset;
r.SrcPos.Len := SubStrLen;
r.DstPos.Start := Start;
r.DstPos.Len := Len;
Add(r);
end;
procedure TStringEditor.Replace(const Pos: TTokenPos; const Substr: string; const SubStrPos: TTokenPos);
var
r: TReplace;
begin
r.Clear;
r.SrcText := Substr;
r.SrcPos := SubStrPos;
r.DstPos := Pos;
Add(r);
end;
procedure TStringEditor.Replace(const Start, Len: integer; const Substr: string);
var
r: TReplace;
begin
r.Clear;
r.SrcText := Substr;
r.SrcPos.Start := 0;
r.SrcPos.Len := Length(Substr);
r.DstPos.Start := Start;
r.DstPos.Len := Len;
Add(r);
end;
procedure TStringEditor.Sort;
var
Comparer: IComparer<TReplace>;
begin
Comparer := TDelegatedComparer<TReplace>.Create(
function(const A,B: TReplace): integer
begin
result := A.DstPos.Start-B.DstPos.Start;
if result=0 then
result := A.Order-B.Order;
end);
TArray.Sort<TReplace>(Instructions.Items, Comparer, 0,Instructions.Count);
end;
function TStringEditor.Apply(const Src: string): string;
var
L,I,SrcPos: Integer;
P: PReplace;
Buffer: TStringBuilder;
begin
Buffer := TStringBuilder.Create;
Sort;
SrcPos := 0;
L := Length(Src);
for I := 0 to Instructions.Count-1 do
begin
P := @Instructions.Items[I];
if P.DstPos.Start > L then
Break;
if P.DstPos.Start > SrcPos then
Buffer.Append(Src, SrcPos, P.DstPos.Start-SrcPos);
if P.SrcPos.Len > 0 then
Buffer.Append(P.SrcText, P.SrcPos.Start, P.SrcPos.Len);
SrcPos := Min(Max(P.DstPos.Start + P.DstPos.Len, SrcPos), L);
end;
if SrcPos < L then
Buffer.Append(Src, SrcPos, L-SrcPos);
result := Buffer.ToString;
end;
{ TCodePages }
class procedure TCodePages.InitCyr;
var
I: Integer;
begin
if UnicodeToCyr<>nil then
Exit;
UnicodeToCyr := TDictionary<Char, Byte>.Create;
for I := Low(CyrToUnicode) to High(CyrToUnicode) do
UnicodeToCyr.Add(CyrToUnicode[I], I);
end;
class procedure TCodePages.InitEur;
var
I: Integer;
begin
if UnicodeToEur<>nil then
Exit;
UnicodeToEur := TDictionary<Char, Byte>.Create;
for I := Low(EurToUnicode) to High(EurToUnicode) do
UnicodeToEur.Add(EurToUnicode[I], I);
end;
class function TCodePages.EncodeTextCyr(const Text: string; Len: integer; var Dst): Boolean;
var
I: Integer;
begin
InitCyr;
for I := 0 to Len-1 do
if not UnicodeToCyr.TryGetValue(Text.Chars[I], (PByte(@Dst) + I)^) then
Exit(False);
Result := True;
end;
class function TCodePages.EncodeTextEur(const Text: string; Len: integer; var Dst): Boolean;
var
I: Integer;
begin
InitEur;
for I := 0 to Len-1 do
if not UnicodeToEur.TryGetValue(Text.Chars[I], (PByte(@Dst) + I)^) then
Exit(False);
Result := True;
end;
class function TCodePages.DecodeTextCyr(const Src; Size: integer): string;
var
I: Integer;
begin
SetLength(Result, Size);
for I := 0 to Size-1 do
Result[I+Low(Result)] := CyrToUnicode[(PByte(@Src)+I)^];
end;
class function TCodePages.DecodeTextEur(const Src; Size: integer): string;
var
I: Integer;
begin
SetLength(Result, Size);
for I := 0 to Size-1 do
Result[I+Low(Result)] := EurToUnicode[(PByte(@Src)+I)^];
end;
class destructor TCodePages.Destroy;
begin
FreeAndNil(UnicodeToCyr);
FreeAndNil(UnicodeToEur);
end;
class function TCodePages.EncodeText(const Text: string; var CodePageId: TCodePageId; var Bytes: TArray<byte>): Boolean;
begin
SetLength(Bytes, Length(Text));
if EncodeTextEur(Text, Length(Text), Bytes[0]) then CodePageId := cpiEur else
if EncodeTextCyr(Text, Length(Text), Bytes[0]) then CodePageId := cpiCyr else
Exit(False);
result := True;
end;
class function TCodePages.DecodeText(const Bytes: TArray<byte>; CodePageId: TCodePageId): string;
begin
if Length(Bytes) = 0 then
result := ''
else
case CodePageId of
cpiCyr: result := DecodeTextCyr(Bytes[0], Length(Bytes));
cpiEur: result := DecodeTextEur(Bytes[0], Length(Bytes));
else result := '';
end;
end;
class function TCodePages.StringToBuf(const Text: string; BufSize: integer; var CodePageId: TCodePageId; var Buf; var Len: integer): boolean;
begin
Len := Min(Length(Text), BufSize);
if EncodeTextEur(Text, Len, Buf) then CodePageId := cpiEur else
if EncodeTextCyr(Text, Len, Buf) then CodePageId := cpiCyr else
Exit(False);
result := True;
end;
class function TCodePages.BufToString(const Buf; BufSize: integer; CodePageId: TCodePageId): string;
begin
case CodePageId of
cpiCyr: result := DecodeTextCyr(Buf, BufSize);
cpiEur: result := DecodeTextEur(Buf, BufSize);
else result := '';
end;
end;
{ TBigEndianUTF32Encoding }
function TBigEndianUTF32Encoding.Clone: TEncoding;
begin
Result := TBigEndianUTF32Encoding.Create;
end;
class function TBigEndianUTF32Encoding.GetBigEndianUnicode32: TEncoding;
var
LEncoding: TEncoding;
begin
if FBigEndianUnicode32 = nil then
begin
LEncoding := TBigEndianUTF32Encoding.Create;
if AtomicCmpExchange(Pointer(FBigEndianUnicode32), Pointer(LEncoding), nil) <> nil then
LEncoding.Free;
{$IFDEF AUTOREFCOUNT}
FBigEndianUnicode32.__ObjAddRef;
{$ENDIF AUTOREFCOUNT}
end;
Result := FBigEndianUnicode32;
end;
function TBigEndianUTF32Encoding.GetByteCount(Chars: PChar; CharCount: Integer): Integer;
begin
Result := CharCount * 4;
end;
function TBigEndianUTF32Encoding.GetBytes(Chars: PChar; CharCount: Integer; Bytes: PByte; ByteCount: Integer): Integer;
var
I: Integer;
begin
for I := 0 to CharCount - 1 do
begin
Word(Pointer(Bytes)^) := 0;
Inc(Bytes, 2);
Bytes^ := Hi(Word(Chars^));
Inc(Bytes);
Bytes^ := Lo(Word(Chars^));
Inc(Bytes);
Inc(Chars);
end;
Result := CharCount * 4;
end;
function TBigEndianUTF32Encoding.GetCharCount(Bytes: PByte; ByteCount: Integer): Integer;
begin
Result := ByteCount div 4;
end;
function TBigEndianUTF32Encoding.GetChars(Bytes: PByte; ByteCount: Integer; Chars: PChar; CharCount: Integer): Integer;
begin
Result := CharCount;
while CharCount > 0 do
begin
Assert(ByteCount >= 4);
if Word(Pointer(Bytes)^) <> 0
then Chars^ := '?'
else Chars^ := Char(Pointer(@Bytes[2])^);
Chars^ := Char( (Word(Chars^) shr 8) or (Word(Chars^) shl 8) );
inc(Bytes,4);
dec(ByteCount,4);
inc(Chars);
dec(CharCount);
end;
end;
function TBigEndianUTF32Encoding.GetCodePage: Cardinal;
begin
Result := 12001; // UTF-32BE
end;
function TBigEndianUTF32Encoding.GetEncodingName: string;
begin
{$IFDEF MSWINDOWS}
Result := '12001 (Unicode - Big-Endian)'; // do not localize
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
Result := 'Unicode (UTF-32BE)'; // do not localize
{$ENDIF POSIX}
end;
function TBigEndianUTF32Encoding.GetMaxByteCount(CharCount: Integer): Integer;
begin
Result := (CharCount + 1) * 4;
end;
function TBigEndianUTF32Encoding.GetMaxCharCount(ByteCount: Integer): Integer;
begin
Result := (ByteCount div 4) + (ByteCount and 1) + 1;
end;
function TBigEndianUTF32Encoding.GetPreamble: TBytes;
begin
Result := TBytes.Create(0, 0, $FE, $FF);
end;
{ TLittleEndianUTF32Encoding }
function TLittleEndianUTF32Encoding.Clone: TEncoding;
begin
Result := TLittleEndianUTF32Encoding.Create;
end;
function TLittleEndianUTF32Encoding.GetBytes(Chars: PChar; CharCount: Integer; Bytes: PByte; ByteCount: Integer): Integer;
var
I: Integer;
begin
for I := 0 to CharCount - 1 do
begin
Bytes^ := Lo(Word(Chars^));
Inc(Bytes);
Bytes^ := Hi(Word(Chars^));
Inc(Bytes);
Word(Pointer(Bytes)^) := 0;
Inc(Bytes, 2);
Inc(Chars);
end;
Result := CharCount * 4;
end;
function TLittleEndianUTF32Encoding.GetChars(Bytes: PByte; ByteCount: Integer; Chars: PChar; CharCount: Integer): Integer;
begin
Result := CharCount;
while CharCount > 0 do
begin
Assert(ByteCount >= 4);
if Word((@Bytes[2])^) <> 0
then Chars^ := '?'
else Chars^ := Char(Pointer(Bytes)^);
inc(Bytes,4);
dec(ByteCount,4);
inc(Chars);
dec(CharCount);
end;
end;
function TLittleEndianUTF32Encoding.GetCodePage: Cardinal;
begin
Result := 12000; // UTF-32LE
end;
function TLittleEndianUTF32Encoding.GetEncodingName: string;
begin
{$IFDEF MSWINDOWS}
Result := '12000 (Unicode - Little-Endian)'; // do not localize
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
Result := 'Unicode (UTF-32LE)'; // do not localize
{$ENDIF POSIX}
end;
class function TLittleEndianUTF32Encoding.GetLittleEndianUnicode32: TEncoding;
var
LEncoding: TEncoding;
begin
if FLittleEndianUnicode32 = nil then
begin
LEncoding := TLittleEndianUTF32Encoding.Create;
if AtomicCmpExchange(Pointer(FLittleEndianUnicode32), Pointer(LEncoding), nil) <> nil then
LEncoding.Free;
{$IFDEF AUTOREFCOUNT}
FLittleEndianUnicode32.__ObjAddRef;
{$ENDIF AUTOREFCOUNT}
end;
Result := FLittleEndianUnicode32;
end;
function TLittleEndianUTF32Encoding.GetPreamble: TBytes;
begin
Result := TBytes.Create($FF, $FE, 0, 0);
end;
{ TEnc }
class function TEnc.MakeValidStringLiteral(const s: string): string;
var
i: Integer;
begin
result := '';
i := Low(s);
while High(s)-i+1>250 do
begin
result := result + '''' + System.Copy(s,i,250) + ''' + ';
inc(i, 250);
end;
result := result + '''' + System.Copy(s,i,high(integer)) + '''';
end;
class function TEnc.HexEscape(const Value, CharsToEscape: string; const EscapeChar: Char): string;
var
S: TSet<Char>;
I: Integer;
begin
S.Init;
S.Add(EscapeChar);
for I := Low(CharsToEscape) to High(CharsToEscape) do
begin
Assert( not (((CharsToEscape[I]>='0') and (CharsToEscape[I]<='9')) or ((CharsToEscape[I]>='A') and (CharsToEscape[I]<='F'))) );
S.Add(CharsToEscape[I]);
end;
result := '';
for I := 0 to Length(Value)-1 do
if not (Value.Chars[I] in S) then
result := result + Value.Chars[I]
else
result := result + EscapeChar + THex.Encode(Value.Chars[I]);
end;
class function TEnc.HexUnescape(const Value: string; const EscapeChar: Char): string;
var
I: Integer;
begin
result := '';
I := 0;
while I < Length(Value) do
begin
if Value.Chars[I] <> EscapeChar then
result := result + Value.Chars[I]
else
begin
result := result + THex.DecodeString(Value.SubString(I+1, SizeOf(Char)*2));
Inc(I, SizeOf(Char)*2);
end;
inc(I);
end;
end;
class function TEnc.EncodeStringLiteral(const Value: string): string;
var
Buf: TStringBuilder;
begin
Buf := TStringBuilder.Create;
EncodeStringLiteral(Value, Buf);
Result := Buf.ToString;
end;
class procedure TEnc.EncodeStringLiteral(const Value: string; var Dst: TStringBuilder);
var
I: integer;
begin
for I := Low(Value) to High(Value) do
if Value[I]=''''
then Dst.Append('''''')
else Dst.Append(Value[I]);
end;
class function TEnc.EscapeIniValue(const KeyOrValue: string): string;
var
Bytes: TArray<Byte>;
begin
Bytes := TEncoding.UTF8.GetBytes(KeyOrValue);
Result := THex.Encode(Bytes);
end;
class function TEnc.TryUnEscapeIniValue(const EscapedKeyOrValue: string; out KeyOrValue: string): boolean;
var
Bytes: TArray<Byte>;
begin
Result := THex.IsValid(EscapedKeyOrValue);
if not Result then
Exit;
Bytes := THex.DecodeBytes(EscapedKeyOrValue);
Result := IsValidUtf8(Bytes);
if Result then
KeyOrValue := TEncoding.UTF8.GetString(Bytes);
end;
class function TEnc.UnEscapeIniValueDef(const EscapedKeyOrValue, DefValue: string): string;
begin
if not TryUnEscapeIniValue(EscapedKeyOrValue, Result) then
Result := DefValue;
end;
class function TEnc.UnEscapeIniValue(const EscapedKeyOrValue: string): string;
var
Bytes: TArray<Byte>;
begin
Bytes := THex.DecodeBytes(EscapedKeyOrValue);
result := TEncoding.UTF8.GetString(Bytes);
end;
class function TEnc.EscapeIniValueReadable(const KeyOrValue: string): string;
var
BodyStart,BodyLen: integer;
Prefix, Body, Suffix: string;
C: Char;
begin
{
https://stackoverflow.com/questions/3702647/reading-inifile-to-stringlist-problem-spaces-problem
TIniFile.ReadSectionValues ultimately uses the Windows API function GetPrivateProfileString to read key values
from the ini file. GetPrivateProfileString will remove any leading and trailing white space as well as any
quotation marks surrounding the string.
}
result := KeyOrValue;
BodyStart := 0;
BodyLen := Length(result);
{ prefix (we escape: backslash, equality char, whitespace, quotation chars) }
Prefix := '';
if BodyLen > 0 then
begin
C := result.Chars[0];
if (C = '\') or (C = '=') or C.IsWhiteSpace or (C = '''') or (C = '"') then
begin
Prefix := HexEscape(C, C);
inc(BodyStart);
dec(BodyLen);
end;
end;
{ suffix (we escape: backslash, equality char, whitespace, quotation chars) }
Suffix := '';
if BodyLen > 0 then
begin
C := result.Chars[BodyStart+BodyLen-1];
if (C = '\') or (C = '=') or C.IsWhiteSpace or (C = '''') or (C = '"') then
begin
Suffix := HexEscape(C, C);
dec(BodyLen);
end;
end;
{ body (we escape: backslash, equality char }
Body := HexEscape(result.Substring(BodyStart,BodyLen) , '=');
{ result }
result := Prefix + Body + Suffix;
end;
class function TEnc.UnEscapeIniValueReadable(const EscapedKeyOrValue: string): string;
begin
result := HexUnescape(EscapedKeyOrValue);
end;
class function TEnc.ClassNameToCaption(const AClassName: string): string;
var
i: Integer;
begin
if result.StartsWith('T') then
result := result.Substring(1);
for i := Length(result)-1 downto 1 do
if result.Chars[i].IsUpper and result.Chars[i-1].IsLower then
result := result.Insert(i, ' ');
result := result.UpperCase(result.Substring(0,1)) + result.LowerCase(result.Substring(1));
end;
class function TEnc.GetPrintable(const S: string; ReplChar: Char = '?'): string;
begin
result := GetPrintable(PChar(S), Length(S), ReplChar);
end;
class function TEnc.GetPrintable(S: PChar; Count: integer; ReplChar: Char = '?'): string;
var
I: Integer;
begin
SetLength(Result, Count);
if Count<=0 then
Exit;
System.Move(S^, result[Low(result)], Count*SizeOf(Char));
for I := Low(result) to High(result) do
if result[I].IsWhiteSpace then
result[I] := ' '
else
if result[I].IsControl then
result[I] := ReplChar;
end;
class function TEnc.IsValidUtf8(const Text: TArray<Byte>): boolean;
begin
result := IsValidUtf8(Text, Length(Text), 0, False);
end;
class function TEnc.IsValidUtf8(const Text: TArray<Byte>; Count,TextPos: integer; TextIsFragment: boolean = True): boolean;
const
b2 = 128 + 64 + 0;
b2m = 128 + 64 + 32;
b3 = 128 + 64 + 32 + 0;
b3m = 128 + 64 + 32 + 16;
b4 = 128 + 64 + 32 + 16 + 0;
b4m = 128 + 64 + 32 + 16 + 8;
b5 = 128 + 64 + 32 + 16 + 8 + 0;
b5m = 128 + 64 + 32 + 16 + 8 + 4;
b6 = 128 + 64 + 32 + 16 + 8 + 4 + 0;
b6m = 128 + 64 + 32 + 16 + 8 + 4 + 2;
v = 128 + 0;
vm = 128 + 64;
begin
Result := False;
{ we will kep number of remain bytes in Count }
Dec(Count, TextPos);
{ skip BOM }
if (Count >= 3) and (Text[TextPos]=$EF) and (Text[TextPos+1]=$BB) and (Text[TextPos+2]=$BF) then
begin
inc(TextPos, 3);
dec(Count, 3);
end;
{ we can check faster when we know that all 6 bytes are here }
while Count >= 6 do
{ 1 byte }
if Text[TextPos] < 128 then
begin
inc(TextPos);
dec(Count);
end
else
{ 2 bytes }
if (Text[TextPos] and b2m = b2) then
if Text[TextPos+1] and vm <> v then
Exit
else
begin
inc(TextPos, 2);
dec(Count, 2);
end
else
{ 3 bytes }
if (Text[TextPos] and b3m = b3) then
if (Text[TextPos+1] and vm <> v) or (Text[TextPos+2] and vm <> v) then
Exit
else
begin
inc(TextPos, 3);
dec(Count, 3);
end
else
{ 4 bytes }
if (Text[TextPos] and b4m = b4) then
if (Text[TextPos+1] and vm <> v) or
(Text[TextPos+2] and vm <> v) or
(Text[TextPos+3] and vm <> v)
then
Exit
else
begin
inc(TextPos, 4);
dec(Count, 4);
end
else
{ 5 bytes }
if (Text[TextPos] and b5m = b5) then
if (Text[TextPos+1] and vm <> v) or
(Text[TextPos+2] and vm <> v) or
(Text[TextPos+3] and vm <> v) or
(Text[TextPos+4] and vm <> v)
then
Exit
else
begin
inc(TextPos, 5);
dec(Count, 5);
end
else
{ 6 bytes }
if (Text[TextPos] and b6m = b6) then
if (Text[TextPos+1] and vm <> v) or
(Text[TextPos+2] and vm <> v) or
(Text[TextPos+3] and vm <> v) or
(Text[TextPos+4] and vm <> v) or
(Text[TextPos+5] and vm <> v)
then
Exit
else
begin
inc(TextPos, 6);
dec(Count, 6);
end
else
Exit;
{ we have 0..5 bytes left }
while Count > 0 do
{ 1 byte }
if Text[TextPos] < 128 then
begin
inc(TextPos);
dec(Count);
end
else
{ 2 bytes }
if (Text[TextPos] and b2m = b2) then
if Count < 2 then
Exit(TextIsFragment)
else
if Text[TextPos+1] and vm <> v then
Exit
else
begin
inc(TextPos, 2);
dec(Count, 2);
end
else
{ 3 bytes }
if (Text[TextPos] and b3m = b3) then
if Count < 3 then
Exit(TextIsFragment)
else
if (Text[TextPos+1] and vm <> v) or
(Text[TextPos+2] and vm <> v)
then
Exit
else
begin
inc(TextPos, 3);
dec(Count, 3);
end
else
{ 4 bytes }
if (Text[TextPos] and b4m = b4) then
if Count < 4 then
Exit(TextIsFragment)
else
if (Text[TextPos+1] and vm <> v) or
(Text[TextPos+2] and vm <> v) or
(Text[TextPos+3] and vm <> v)
then
Exit
else
begin
inc(TextPos, 4);
dec(Count, 4);
end
else
{ 5 bytes }
if (Text[TextPos] and b5m = b5) then
if Count < 5 then
Exit(TextIsFragment)
else
if (Text[TextPos+1] and vm <> v) or
(Text[TextPos+2] and vm <> v) or
(Text[TextPos+3] and vm <> v) or
(Text[TextPos+4] and vm <> v)
then
Exit
else
begin
inc(TextPos, 5);
dec(Count, 5);
end
else
{ 6 bytes }
if (Text[TextPos] and b6m = b6) then
if Count < 6 then
Exit(TextIsFragment)
else
if (Text[TextPos+1] and vm <> v) or
(Text[TextPos+2] and vm <> v) or
(Text[TextPos+3] and vm <> v) or
(Text[TextPos+4] and vm <> v) or
(Text[TextPos+5] and vm <> v)
then
Exit
else
begin
inc(TextPos, 6);
dec(Count, 6);
end
else
Exit; { wrong sequence }
{ No wrong sequences detected }
Result := True;
end;
class function TEnc.DetectEncoding(const Text: TArray<Byte>; Count: integer;
out TextStartPos: integer; TextIsFragment: boolean): TTextEncoding;
type
TRec = record
z: array[0..3] of byte;
e: TTextEncoding;
end;
const
Encodings: array[0..4] of TRec = (
(z:(1,1,1,1); e: teUTF8),
(z:(1,0,1,0); e: teUTF16LE),
(z:(0,1,0,1); e: teUTF16BE),
(z:(1,0,0,0); e: teUTF32LE),
(z:(0,0,0,1); e: teUTF32BE)
);
var
i: integer;
begin
TextStartPos := 0;
if Count < 4 then
if not IsValidUtf8(Text, Count, TextStartPos, TextIsFragment) then
Exit(teAnsi)
else
begin
if (Count >= 3) and (Text[TextStartPos]=$EF) and (Text[TextStartPos+1]=$BB) and (Text[TextStartPos+2]=$BF) then
inc(TextStartPos, 3);
Exit(teUTF8)
end;
{ check byte order mark (BOM) }
if (Text[TextStartPos]=$EF) and (Text[TextStartPos+1]=$BB) and (Text[TextStartPos+2]=$BF) then
begin
if not IsValidUtf8(Text, Count, TextStartPos, TextIsFragment) then
Exit(teAnsi);
inc(TextStartPos, 3);
Exit(teUTF8);
end;
if (Text[TextStartPos]=$FF) and (Text[TextStartPos+1]=$FE) and (Text[TextStartPos+2]=0) and (Text[TextStartPos+3]=0) then
begin
inc(TextStartPos, 4);
Exit(teUTF32LE);
end;
if (Text[TextStartPos]=0) and (Text[TextStartPos+1]=0) and (Text[TextStartPos+2]=$FE) and (Text[TextStartPos+3]=$FF) then
begin
inc(TextStartPos, 4);
Exit(teUTF32BE);
end;
if (Text[TextStartPos]=$FF) and (Text[TextStartPos+1]=$FE) then
begin
inc(TextStartPos, 2);
Exit(teUTF16LE);
end;
if (Text[TextStartPos]=$FE) and (Text[TextStartPos+1]=$FF) then
begin
inc(TextStartPos, 2);
Exit(teUTF16BE);
end;
(*
check first characters (according to RFC they must be ASCII)
00 00 00 xx UTF-32BE
00 xx 00 xx UTF-16BE
xx 00 00 00 UTF-32LE
xx 00 xx 00 UTF-16LE
xx xx xx xx UTF-8
*)
for i := low(Encodings) to high(Encodings) do
with Encodings[i] do
if
( (Z[0]=0) = (Text[TextStartPos]=0) ) and
( (Z[1]=0) = (Text[TextStartPos+1]=0) ) and
( (Z[2]=0) = (Text[TextStartPos+2]=0) ) and
( (Z[3]=0) = (Text[TextStartPos+3]=0) )
then
if E <> teUTF8 then
Exit(E)
else
if IsValidUtf8(Text, Count, TextStartPos, TextIsFragment) then
Exit(teUTF8)
else
Exit(teANSI);
result := teANSI;
end;
class function TEnc.DetectEncoding(const Text: TArray<Byte>; Count: integer; out TextStartPos: integer; TextIsFragment: boolean;
out AEncoding: TEncoding): TTextEncoding;
begin
result := DetectEncoding(Text, Count, TextStartPos, TextIsFragment);
case result of
teUnknown : AEncoding := nil;
teAnsi : AEncoding := TEncoding.ANSI;
teUTF8 : AEncoding := TEncoding.UTF8;
teUTF16LE : AEncoding := TEncoding.Unicode;
teUTF16BE : AEncoding := TEncoding.BigEndianUnicode;
teUTF32LE : AEncoding := TLittleEndianUTF32Encoding.LittleEndianUnicode32;
teUTF32BE : AEncoding := TBigEndianUTF32Encoding.BigEndianUnicode32;
else AEncoding := nil;
end;
end;
class function TEnc.DetectCodepage(const AText: TArray<byte>; out Encoding: TEncoding): boolean;
var
CodePage: cardinal;
begin
result := DetectCodepage(AText, CodePage);
if result then
Encoding := TEnc.GetEncoding(CodePage);
end;
class function TEnc.DetectCodepage(const AText: TArray<byte>; Count: integer; out CodePage: Cardinal): boolean;
var
TextEncoding : TTextEncoding;
TextStartPos: Integer;
begin
TextEncoding := DetectEncoding(AText, Length(AText), TextStartPos, False);
result := TextEncoding <> teUnknown;
if result then
case TextEncoding of
teAnsi : CodePage := TEncoding.ANSI.CodePage;
teUTF8 : CodePage := 65001;
teUTF16LE : CodePage := 1200;
teUTF16BE : CodePage := 1201;
teUTF32LE : CodePage := 12000;
teUTF32BE : CodePage := 12001;
else result := False;
end;
end;
class function TEnc.DetectCodepage(const AText: TArray<byte>; out CodePage: Cardinal): boolean;
begin
result := DetectCodepage(AText, Length(AText), CodePage);
end;
class function TEnc.IsPossibleEncoding(const AText: TArray<byte>; ACodePage: Cardinal): boolean;
var
TextEncoding : TTextEncoding;
TextStartPos: Integer;
begin
{ any encoding is allowed for empty src }
if Length(AText) = 0 then
Exit(True);
TextEncoding := DetectEncoding(AText, Length(AText), TextStartPos, False);
case TextEncoding of
teUnknown,teAnsi:
{ it can't be UTF family }
result := not TArrayUtils.Contains<cardinal>(ACodePage, [1200,1201,12000,12001,65001]);
teUTF8:
{ it can't be UTF16/UTF32, but maybe it is UTF8 or single byte encoding }
result := not TArrayUtils.Contains<cardinal>(ACodePage, [1200,1201,12000,12001]);
teUTF16LE:
result := ACodePage = 1200;
teUTF16BE:
result := ACodePage = 1201;
teUTF32LE:
result := ACodePage = 12000;
teUTF32BE:
result := ACodePage = 12001;
else Result := True; { we don't know }
end;
end;
class function TEnc.GetEncoding(CodePage: Cardinal): TEncoding;
begin
case CodePage of
1200 : result := TUnicodeEncoding.Create; { UTF16 little endian }
1201 : result := TBigEndianUnicodeEncoding.Create; { UTF16 big endian }
65000 {CP_UTF7} : result := TUTF7Encoding.Create; { UTF7 }
65001 {CP_UTF8} : result := TUTF8Encoding.Create; { UTF8 }
12000 : result := TLittleEndianUTF32Encoding.Create; { UTF32 little endian }
12001 : result := TBigEndianUTF32Encoding.Create; { UTF32 big endian }
else result := TEncoding.GetEncoding(CodePage);
end;
end;
initialization
TStr.InitializeVars;
finalization
TStr.FinalizeVars;
end.
|
unit WebPageLookMod;
interface
uses
Windows, Messages, SysUtils, Classes, HTTPApp, WebModu, HTTPProd,
CompProd, PagItems, SiteProd, WebAdapt, WebComp,
MidItems, WebForm;
type
TWebPageLookModule = class(TWebPageModule)
AdapterPageProducer1: TAdapterPageProducer;
PicturesIterator: TPagedAdapter;
ThumbWidth: TAdapterField;
ThumbHeight: TAdapterField;
NewPicturePage: TAdapterAction;
DeletePicture: TAdapterAction;
PageProducer1: TPageProducer;
PictureImage: TAdapterImageField;
PictureThumbImage: TAdapterImageField;
ActionGotoPage: TAdapterGotoPageAction;
AdapterForm1: TAdapterForm;
AdapterGrid1: TAdapterGrid;
AdapterCommandGroup1: TAdapterCommandGroup;
DisplayOptions: TAdapter;
MaxPicsPerPage: TAdapterField;
PreferredThumbWidth: TAdapterField;
MaxPicsPerRow: TAdapterField;
SubmitOptions: TAdapterAction;
PicsPerRow: TAdapterField;
procedure WebPageModuleCreate(Sender: TObject);
procedure WebPageModuleDestroy(Sender: TObject);
procedure PictureNameGetValue(Sender: TObject; var Value: Variant);
procedure ThumbWidthGetValue(Sender: TObject; var Value: Variant);
procedure ThumbHeightGetValue(Sender: TObject; var Value: Variant);
procedure WebPageModuleActivate(Sender: TObject);
procedure WebPageModuleDeactivate(Sender: TObject);
procedure SavedThumbWidthGetValue(Sender: TObject; var Value: Variant);
procedure SavedColNumberGetValue(Sender: TObject; var Value: Variant);
procedure MaxCountOldGetValue(Sender: TObject; var Value: Variant);
procedure NewPicturePageExecute(Sender: TObject; Params: TStrings);
procedure DeletePictureGetParams(Sender: TObject; Params: TStrings);
procedure DeletePictureExecute(Sender: TObject; Params: TStrings);
procedure PicturesIteratorIterateRecords(Sender: TObject;
Action: TIteratorMethod; var EOF: Boolean);
procedure PictureImageGetParams(Sender: TObject; Params: TStrings);
procedure PictureImageGetImage(Sender: TObject; Params: TStrings;
var MimeType: String; var Image: TStream; var Owned: Boolean);
procedure PictureThumbImageGetImage(Sender: TObject; Params: TStrings;
var MimeType: String; var Image: TStream; var Owned: Boolean);
procedure PictureImageGetImageName(Sender: TObject; var Value: String);
procedure PicturesIteratorGetFirstRecord(Sender: TObject;
var EOF: Boolean);
procedure PicturesIteratorGetNextRecord(Sender: TObject;
var EOF: Boolean);
procedure PicturesIteratorGetRecordCount(Sender: TObject;
var Count: Integer);
procedure PicturesIteratorGetRecordIndex(Sender: TObject;
var Index: Integer);
procedure PicturesIteratorGetEOF(Sender: TObject; var EOF: Boolean);
procedure MaxPicsPerPageGetValue(Sender: TObject; var Value: Variant);
procedure SubmitOptionsExecute(Sender: TObject; Params: TStrings);
procedure PreferredThumbWidthGetValue(Sender: TObject;
var Value: Variant);
procedure MaxPicsPerRowGetValue(Sender: TObject; var Value: Variant);
procedure PicsPerRowGetValue(Sender: TObject; var Value: Variant);
private
FPictureList: TStringList;
FCurrentIndex: Integer;
FCurrentWidth: Integer;
FCurrentHeight: Integer;
FThumbWidth: Integer;
FPicsPerRow: Integer;
procedure LoadCurrentWidthHeight;
function PicturesIteratorStartIterator: Boolean;
function PicturesIteratorNextIteration: Boolean;
public
{ Public declarations }
end;
function WebPageLookModule: TWebPageLookModule;
implementation
{$R *.dfm} {*.html}
uses WebReq, WebCntxt, AdaptReq, WebFact, Variants, MainPageMod, jpeg, Graphics, SiteComp;
const
cWidthCookie = 'Thumbnail Width';
cColNumberCookie = 'Column Number';
cSavedPicsPerPage = 'Pictures Per Page';
cDefaultWidth = 200;
cDefaultCols = 3;
cDefaultPicsPerPage = 20;
resourcestring
rNoFilenameGiven = 'No filename given to create a thumbnail for.';
rViewMyPictures = 'View My Pictures';
procedure GetFiles(const ADirectory: string; Files: TStringList;
SubFolders: Boolean; FileType: string);
// Helper function to remove any slashes or add them if needed
function SlashSep(const Path, S: string): string;
begin
if AnsiLastChar(Path)^ <> '\' then
Result := Path + '\' + S
else
Result := Path + S;
end;
var
SearchRec: TSearchRec;
nStatus: Integer;
begin
// First find all the files in the current directory
// You could put something else instead of *.*, such as *.jpeg or *.gif
// to find only files of those types.
nStatus := FindFirst(PChar(SlashSep(ADirectory, FileType)), 0, SearchRec);
while nStatus = 0 do
begin
Files.Add(SlashSep(ADirectory, SearchRec.Name));
nStatus := FindNext(SearchRec);
end;
FindClose(SearchRec);
// Next look for subfolders and search them if required to do so
if SubFolders then
begin
nStatus := FindFirst(PChar(SlashSep(ADirectory, FileType)), faDirectory,
SearchRec);
while nStatus = 0 do
begin
// If it is a directory, then use recursion
if ((SearchRec.Attr and faDirectory) <> 0) then
begin
if ( (SearchRec.Name <> '.') and (SearchRec.Name <> '..') ) then
GetFiles(SlashSep(ADirectory, SearchRec.Name), Files, SubFolders,
FileType);
end;
nStatus := FindNext(SearchRec)
end;
FindClose(SearchRec);
end;
end;
function WebPageLookModule: TWebPageLookModule;
begin
Result := TWebPageLookModule(WebContext.FindModuleClass(TWebPageLookModule));
end;
function TWebPageLookModule.PicturesIteratorStartIterator: Boolean;
var
UserName: string;
Directory: string;
begin
try
FPictureList.Clear;
// Find the current user name
UserName := MainPageModule.GetCurrentUserName;
if UserName = '' then raise Exception.Create(rNotLoggedIn);
// Look for all pictures in their directory
Directory := ExtractFilePath(GetModuleName(HInstance)) + 'users\' + UserName;
GetFiles(Directory, FPictureList, False, '*.jpg');
GetFiles(Directory, FPictureList, False, '*.jpeg');
FCurrentIndex := 0;
Result := FCurrentIndex < FPictureList.Count;
if Result then
LoadCurrentWidthHeight;
except
on E: Exception do
begin
PicturesIterator.Errors.AddError(E);
Result := False;
end;
end;
end;
function TWebPageLookModule.PicturesIteratorNextIteration: Boolean;
begin
Inc(FCurrentIndex);
Result := FCurrentIndex < FPictureList.Count;
if Result then
LoadCurrentWidthHeight;
end;
procedure TWebPageLookModule.WebPageModuleCreate(Sender: TObject);
begin
FPictureList := TStringList.Create;
FCurrentIndex := 0;
end;
procedure TWebPageLookModule.WebPageModuleDestroy(Sender: TObject);
begin
FPictureList.Free;
end;
procedure TWebPageLookModule.PictureNameGetValue(Sender: TObject;
var Value: Variant);
begin
try
Value := ExtractFileName(FPictureList[FCurrentIndex]);
except
on E: Exception do
begin
PicturesIterator.Errors.AddError(E);
Value := Unassigned;
end;
end;
end;
procedure TWebPageLookModule.LoadCurrentWidthHeight;
var
Jpeg: TJpegImage;
begin
FCurrentHeight := 0;
Jpeg := TJpegImage.Create;
try
Jpeg.LoadFromFile(FPictureList[FCurrentIndex]);
// Don't shrink small pictures
if FThumbWidth > Jpeg.Width then
FCurrentWidth := Jpeg.Width
else
FCurrentWidth := FThumbWidth;
FCurrentHeight := Trunc(FCurrentWidth * (Jpeg.Height / Jpeg.Width));
finally
Jpeg.Free;
end;
end;
procedure TWebPageLookModule.ThumbWidthGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FCurrentWidth;
end;
procedure TWebPageLookModule.ThumbHeightGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FCurrentHeight;
end;
procedure TWebPageLookModule.WebPageModuleActivate(Sender: TObject);
begin
FThumbWidth := cDefaultWidth;
FPicsPerRow := cDefaultCols;
PicturesIterator.PageSize := cDefaultPicsPerPage;
// Try loading the FCurrentWidth from the cookie
if WebContext.Request.CookieFields.Values[cWidthCookie] <> '' then
begin
try
FThumbWidth := StrToInt(WebContext.Request.CookieFields.Values[cWidthCookie]);
if FThumbWidth < 5 then
FThumbWidth := cDefaultWidth;
except
end;
end;
if WebContext.Request.CookieFields.Values[cColNumberCookie] <> '' then
begin
try
FPicsPerRow := StrToInt(WebContext.Request.CookieFields.Values[cColNumberCookie]);
if FPicsPerRow <= 0 then
FPicsPerRow := cDefaultCols;
except end;
end;
if WebContext.Request.CookieFields.Values[cSavedPicsPerPage] <> '' then
begin
try
PicturesIterator.PageSize := StrToInt(WebContext.Request.CookieFields.Values[cSavedPicsPerPage]);
if PicturesIterator.PageSize <= 0 then
PicturesIterator.PageSize := cDefaultPicsPerPage;
except end;
end;
end;
procedure TWebPageLookModule.WebPageModuleDeactivate(Sender: TObject);
begin
with WebContext.Response.Cookies.Add do
begin
Name := cWidthCookie;
Value := IntToStr(FThumbWidth);
// Domain := 'borland.com'; // Should be set to your domain
Path := WebContext.Request.InternalScriptName;
end;
with WebContext.Response.Cookies.Add do
begin
Name := cColNumberCookie;
Value := IntToStr(FPicsPerRow);
Path := WebContext.Request.InternalScriptName;
end;
with WebContext.Response.Cookies.Add do
begin
Name := cSavedPicsPerPage;
Value := IntToStr(PicturesIterator.PageSize);
Path := WebContext.Request.InternalScriptName;
end;
end;
procedure TWebPageLookModule.SavedThumbWidthGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FThumbWidth;
end;
procedure TWebPageLookModule.SavedColNumberGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FPicsPerRow;
end;
procedure TWebPageLookModule.MaxCountOldGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FPictureList.Count;
end;
procedure TWebPageLookModule.NewPicturePageExecute(Sender: TObject;
Params: TStrings);
begin
try
//jmt.!!! FStartAtIndex := StrToInt(Params.Values['index']);
except
on E: Exception do PicturesIterator.Errors.AddError(E);
end;
end;
procedure TWebPageLookModule.DeletePictureGetParams(Sender: TObject;
Params: TStrings);
begin
Params.Values['filename'] := ExtractFileName(FPictureList[FCurrentIndex]);
end;
procedure TWebPageLookModule.DeletePictureExecute(Sender: TObject;
Params: TStrings);
var
FileName, UserName: string;
begin
try
// NOTE: HttpDecode should be done for us!
FileName := HttpDecode(Params.Values['filename']);
if FileName <> '' then
begin
UserName := MainPageModule.GetCurrentUserName;
if UserName <> '' then
begin
// Delete the actual file
DeleteFile(ExtractFilePath(GetModuleName(HInstance)) +
'users\' + UserName + '\' + FileName);
end;
end;
except
on E: Exception do PicturesIterator.Errors.AddError(E);
end;
end;
procedure TWebPageLookModule.PicturesIteratorIterateRecords(
Sender: TObject; Action: TIteratorMethod; var EOF: Boolean);
begin
case Action of
itStart:
EOF := not PicturesIteratorStartIterator;
itNext:
EOF := not PicturesIteratorNextIteration;
itEnd:
FCurrentIndex := 0;
end;
end;
procedure TWebPageLookModule.PictureImageGetParams(Sender: TObject;
Params: TStrings);
begin
Params.Values['filename'] := ExtractFileName(FPictureList[FCurrentIndex]);
end;
procedure TWebPageLookModule.PictureImageGetImage(Sender: TObject;
Params: TStrings; var MimeType: String; var Image: TStream;
var Owned: Boolean);
var
UserName: string;
FileStream: TFileStream;
begin
try
if Params.Values['filename'] <> '' then
begin
UserName := MainPageModule.GetCurrentUserName;
if UserName <> '' then
begin
FileStream := TFileStream.Create(ExtractFilePath(GetModuleName(HInstance)) +
'users\' + UserName + '\' + HttpDecode(Params.Values['filename']),
fmOpenRead or fmShareDenyWrite);
MimeType := 'image/jpeg'; { do not localize }
Image := FileStream;
Owned := True;
end
else
raise Exception.Create(rNotLoggedIn);
end
else
raise Exception.Create(rNoFilenameGiven);
except
on E: Exception do PicturesIterator.Errors.AddError(E);
end;
end;
procedure TWebPageLookModule.PictureThumbImageGetImage(Sender: TObject;
Params: TStrings; var MimeType: String; var Image: TStream;
var Owned: Boolean);
var
Jpeg: TJpegImage;
UserName: string;
Stream: TMemoryStream;
ThumbPicture: TBitmap;
begin
try
if Params.Values['filename'] <> '' then
begin
UserName := MainPageModule.GetCurrentUserName;
if UserName <> '' then
begin
Jpeg := TJpegImage.Create;
try
Jpeg.LoadFromFile(ExtractFilePath(GetModuleName(HInstance)) +
'users\' + UserName + '\' + HttpDecode(Params.Values['filename']));
// Resize it to be a thumbnail
ThumbPicture := TBitmap.Create;
try
if FThumbWidth > Jpeg.Width then
FCurrentWidth := Jpeg.Width
else
FCurrentWidth := FThumbWidth;
ThumbPicture.Width := FCurrentWidth;
ThumbPicture.Height := Trunc(FCurrentWidth * (Jpeg.Height / Jpeg.Width));
ThumbPicture.Canvas.StretchDraw(Rect(0, 0,
ThumbPicture.Width-1, ThumbPicture.Height-1), Jpeg);
Jpeg.Assign(ThumbPicture);
finally
ThumbPicture.Free;
end;
Stream := TMemoryStream.Create;
Jpeg.SaveToStream(Stream);
MimeType := 'image/jpeg'; { do not localize }
Stream.Position := 0;
Image := Stream;
Owned := True;
finally
Jpeg.Free;
end;
end
else raise Exception.Create(rNotLoggedIn);
end
else raise Exception.Create(rNoFileNameGiven);
except
on E: Exception do PicturesIterator.Errors.AddError(E);
end;
end;
procedure TWebPageLookModule.PictureImageGetImageName(Sender: TObject;
var Value: String);
begin
try
Value := ExtractFileName(FPictureList[FCurrentIndex]);
except
on E: Exception do
begin
PicturesIterator.Errors.AddError(E);
Value := Unassigned;
end;
end;
end;
procedure TWebPageLookModule.PicturesIteratorGetFirstRecord(
Sender: TObject; var EOF: Boolean);
begin
EOF := not PicturesIteratorStartIterator;
end;
procedure TWebPageLookModule.PicturesIteratorGetNextRecord(Sender: TObject;
var EOF: Boolean);
begin
EOF := not PicturesIteratorNextIteration;
end;
procedure TWebPageLookModule.PicturesIteratorGetRecordCount(
Sender: TObject; var Count: Integer);
begin
Count := FPictureList.Count;
end;
procedure TWebPageLookModule.PicturesIteratorGetRecordIndex(
Sender: TObject; var Index: Integer);
begin
Index := FCurrentIndex;
end;
procedure TWebPageLookModule.PicturesIteratorGetEOF(Sender: TObject;
var EOF: Boolean);
begin
EOF := FCurrentIndex >= FPictureList.Count;
end;
procedure TWebPageLookModule.MaxPicsPerPageGetValue(Sender: TObject;
var Value: Variant);
begin
Value := PicturesIterator.PageSize;
end;
procedure TWebPageLookModule.SubmitOptionsExecute(Sender: TObject;
Params: TStrings);
var
Value: IActionFieldValue;
begin
try
Value := PreferredThumbWidth.ActionValue;
if Assigned(Value) then
FThumbWidth := StrToInt(Value.Values[0]);
except
on E: Exception do
begin
DisplayOptions.Errors.AddError(E);
PreferredThumbWidth.EchoActionFieldValue := True;
end;
end;
try
Value := MaxPicsPerRow.ActionValue;
if Assigned(Value) then
begin
FPicsPerRow := StrToInt(Value.Values[0]);
if FPicsPerRow <= 0 then
FPicsPerRow := cDefaultCols;
end;
except
on E: Exception do
begin
DisplayOptions.Errors.AddError(E);
MaxPicsPerRow.EchoActionFieldValue := True;
end;
end;
try
Value := MaxPicsPerPage.ActionValue;
if Assigned(Value) then
begin
PicturesIterator.PageSize := StrToInt(Value.Values[0]);
if PicturesIterator.PageSize < 0 then
PicturesIterator.PageSize := cDefaultPicsPerPage;
end;
except
on E: Exception do
begin
DisplayOptions.Errors.AddError(E);
MaxPicsPerPage.EchoActionFieldValue := True;
end;
end;
end;
procedure TWebPageLookModule.PreferredThumbWidthGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FThumbWidth;
end;
procedure TWebPageLookModule.MaxPicsPerRowGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FPicsPerRow;
end;
procedure TWebPageLookModule.PicsPerRowGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FPicsPerRow;
end;
initialization
if WebRequestHandler <> nil then
WebRequestHandler.AddWebModuleFactory(
TWebPageModuleFactory.Create(TWebPageLookModule,
TWebPageInfo.Create([wpPublished , wpLoginRequired],
'.html', '', rViewMyPictures), crOnDemand, caCache));
end.
|
unit Bullets;
interface
uses
Points, EngineTypes, Level;
procedure CreateBullet (B: PBullet);
procedure CreateWeapon (W : PWeapon; ItemModel : PItemModel; M : PMonster);
procedure ProcessBullets (dt : float);
procedure Shot(M : PMonster; WPModel : PItemModel; Dx : float);
var
CActiveBullets : integer = 0;
LastActiveBulletIndex : integer = -1;
ActiveBullets : array [0..CBullets-1] of PBullet;
implementation
uses
Items, ItemModels, WeaponModels, Collisions, Geometry, Memory, Engine, Sounds, Config;
procedure DischargeNewBullet (
const InitPos : SPoint; const DeltaPos : Point; const Owner : PMonster;
WPModel : PItemModel);
var
newIndex : integer;
c,f : integer;
// где куда чья какой модели
begin
newIndex := LastActiveBulletIndex;
Inc(newIndex);
if newIndex>=CBullets then newIndex := 0;
if (not L.Bullets[newIndex].Active) and (CactiveBullets<CBullets) then begin
Inc(CActiveBullets);
ActiveBullets[CActiveBullets-1] := @L.Bullets[newIndex];
ActiveBullets[CActiveBullets-1].Active := True;
ActiveBullets[CActiveBullets-1].Item.Center := InitPos;
ActiveBullets[CActiveBullets-1].DeltaPos := DeltaPos;
ActiveBullets[CActiveBullets-1].TripDist := 0;
ActiveBullets[CActiveBullets-1].Owner := Owner;
ActiveBullets[CActiveBullets-1].WPModel := WPModel;
ActiveBullets[CActiveBullets-1].Item.Model := WPModel.BulletModel;
with ActiveBullets[CActiveBullets-1].Item do begin // перекраско
for c := 0 to CConvexes-1 do with Convexes[c].G do
for f := 0 to CFaces-1 do Faces[f].Texture := Model.Texture;
end;
UpdateItem(ActiveBullets[CActiveBullets-1].Item);
LastActiveBulletIndex := newIndex;
end;
end;
procedure CreateBullet (B: PBullet);
begin
FillChar(B^, sizeof(B^), 0);
B.Item.Bullet := B;
CreateItem(@B.Item, @L.EmptyS, @IMBullet[0]);
B.Item.Model := nil;
end;
procedure Shot(M : PMonster; WPModel : PItemModel; Dx : float);
var
NewBulletPos : SPoint;
Dh, Dir : Point;
cx,sx,cz,sz : float;
begin
cx := cos(M.anglex);
sx := sin(M.anglex);
cz := cos(M.anglez+Dx*2);
sz := sin(M.anglez+Dx*2);
NewBulletPos := M.Body^;
Dh := ToPoint (sz ,cz , 0);
Dir := ToPoint (sz*sx,cz*sx, cx);
Trace(NewBulletPos, Add(Scale(Dh, M.Item.Model.BodyR+0.1), Scale(Dir, WPModel.HeadR)));
DischargeNewBullet (NewBulletPos, Dir, M, WPModel);
end;
procedure CreateWeapon (W : PWeapon; ItemModel : PItemModel; M : PMonster);
begin
W.ReloadLeft := 0;
W.Item.Weapon := W;
CreateItem(@W.Item, @L.EmptyS, ItemModel);
end;
procedure DeactivateBullet (B : PBullet);
begin
B.Active := False;
B.Item.Center.S := @L.EmptyS;
B.Item.Center.P := CenterSector(B.Item.Center.S^);
end;
procedure DoDamage (M : PMonster; const From : SPoint; Damage : float; dt: float);
var
i : integer;
a,c,s,h,r : float;
d : float;
begin
SetMonsterActive(M);
M.DeltaPos := Add(M.DeltaPos, Scale(Sub(M.Body.P, From.P), dt/M.Item.Model.Mass));
M.LastDamage := 0;
if not (M.Item.Model.Player and (god>0)) then
M.Health := M.Health-Damage*(1-M.Armor/100);
if M.Health<=0 then begin
M.DeathStage := 1;
SetChanel(1);
NoSound;
SetStyle(118);
SetVolume(60);
Sound(80);
end;
M.Armor := M.Armor-2;
if M.Armor<0 then M.Armor := 0;
d := Damage;
for i := 0 to trunc(d)+integer(random<frac(d))-1 do begin
a := random*2*pi;
c := cos(a);
s := sin(a);
h := random*2-1;
r := sqrt(1-h*h);
DischargeNewBullet(From, ToPoint(c*r,s*r,h), nil, @IMWeapon[1]);
end;
end;
procedure TraceBullet(B : PBullet; dt : float);
var
CIS, i : integer;
IP : PAPItem;
OC : SPoint;
s : float;
MS : MemoryState;
Dmg : float;
begin
SaveState(MS);
s := dt * B.WPModel.BulletSpeed;
if B.TripDist+s>B.WPModel.Range then begin
s := B.WPModel.Range-B.TripDist;
B.Active := False;
end;
if B.WPModel.Damage>0 then begin
CIS := 0;
IP := Alloc(CItems*sizeof(PItem));
OC := B.Item.Center;
if not TraceWithItems(B.Item.Center, Scale(B.DeltaPos, s), CIS, IP, false) then
B.Active := False;
if B.WPModel.Sabre then Dmg := B.WPModel.Damage*dt else Dmg := B.WPModel.Damage;
for i := 0 to CIS-1 do if (IP[i].Monster<>nil) and (IP[i].Monster.DeathStage<0) then begin
DoDamage(IP[i].Monster, OC, Dmg, dt);
if not B.WPModel.Sabre then B.Active := False;
end;
for i := 0 to CIS-1 do IP[i].inProcess := False;
end else begin
if not Trace(B.Item.Center, Scale(B.DeltaPos, s)) then
B.Active := False;
end;
B.TripDist := B.TripDist + s;
RestoreState(MS);
end;
procedure ProcessBullets (dt : float);
var
i,j : integer;
begin
j := 0;
i := 0;
while i<CActiveBullets do begin // гавнацикол
// сдвинуть пулю
// рассчитать всех монстров от пули
TraceBullet(ActiveBullets[i], dt);
// если пуля ок, то
if ActiveBullets[i].Active then begin
ActiveBullets[j] := ActiveBullets[i];
Inc(j);
end else
DeactivateBullet(ActiveBullets[i]);
UpdateItem(ActiveBullets[i].Item);
Inc(i);
end;
CActiveBullets := j;
end;
end.
|
unit SIP_Library;
interface
uses Classes,SIP_Script;
type
TSIPLibrary=class(TStringList)
private
function GetScript(ID:Integer): TSipScript;
function GetScriptText(ID:Integer): String;
procedure SetScriptText(ID:Integer; const Value: String);
function GetScriptName(ID: Integer): String;
procedure SetScriptName(ID: Integer; const Value: String);
procedure AddScript(Script:TSipScript);
public
Name:String;
procedure Clear;override;
destructor Destroy;override;
property Script[ID:Integer]:TSipScript read GetScript;
property ScriptText[ID:Integer]:String read GetScriptText write SetScriptText;
property ScriptName[ID:Integer]:String read GetScriptName write SetScriptName;
end;
implementation
uses Util, SysUtils;
{ TSIPScript }
procedure TSIPLibrary.AddScript(Script: TSipScript);
begin
AddObject(IntToStr(Script.ScriptID),Script);
end;
procedure TSIPLibrary.Clear;
var O:TObject;
I:Integer;
begin
for I := 0 to Count - 1 do
begin
O:=Objects[I];
Objects[I]:=nil;
FreeAndNil(O);
end;
inherited;
end;
destructor TSIPLibrary.Destroy;
begin
Clear;
inherited;
end;
function TSIPLibrary.GetScript(ID:Integer): TSipScript;
var I:Integer;
begin
I:=IndexOf(IntToStr(ID));
if I>=0 then
Result:=Objects[I] as TSipScript
else
Result:=nil;
end;
function TSIPLibrary.GetScriptName(ID: Integer): String;
var S:TSIPScript;
begin
S:=Script[ID];
if S=nil then
Result:=''
else
Result:=S.Description;
end;
function TSIPLibrary.GetScriptText(ID:Integer): String;
var S:TSIPScript;
begin
S:=Script[ID];
if S=nil then
Result:=''
else
Result:=Script[ID].Text;
end;
procedure TSIPLibrary.SetScriptName(ID: Integer; const Value: String);
var S:TSIPScript;
begin
if IndexOf(IntToStr(ID))<0 then S:=TSIPScript.Create
else S:=Script[ID];
S.Description:=Value;
S.ScriptID:=ID;
if IndexOf(IntToStr(ID))<0 then AddScript(S);
end;
procedure TSIPLibrary.SetScriptText(ID:Integer; const Value: String);
var S:TSIPScript;
begin
if IndexOf(IntToStr(ID))<0 then S:=TSIPScript.Create
else S:=Script[ID];
S.Text:=Value;
S.ScriptID:=ID;
if IndexOf(IntToStr(ID))<0 then AddScript(S);
end;
end.
|
unit ResourceStrings;
interface
resourcestring
rsAbout = 'About';
rsAreYouSureToPermanen = 'Are you sure to permanently delete this file?';
rsCannotDeleteFileS = 'Cannot delete file: %s.';
rsChineseZh_CN = 'Chinese (zh_CN)';
rsCouldNotDeleteFileS = 'Could not delete file: %s';
rsCreateNewFolder = 'Create new folder';
rsDateS = 'Date: %s';
rsDeleteFile = 'Delete file';
rsDeleteOldFile = 'Delete old file?';
rsDeleteOldFileS = 'Delete old file "%s"?';
rsDestinationFilename = 'Destination filename';
rsDItems0f = '%d items (%.0f%%)';
rsDutchNl_NL = 'Dutch (nl_NL)';
rsEasy80IDEVS = 'Easy80-IDE v%s';
rsEnglishEn_US = 'English (en_US)';
rsEnterThePathForTheNe = 'Enter the path for the new folder';
rsErrorCouldNotCreateD = 'error: could not create directory (%s)';
rsErrorCouldNotDulicat = 'error: could not dulicate file (%s)';
rsErrorCouldNotRenameF = 'error: could not rename file (%s)';
rsFrenchFr_FR = 'French (fr_FR)';
rsGermanDe_DE = 'German (de_DE)';
rsItalianIt_IT = 'Italian (it_IT)';
rsNewFilename = 'New filename';
rsPleaseEnterTheDestin = 'Please enter the destination filename';
rsPleaseEnterTheNewFil = 'Please enter the new filename';
rsPolishPl_PL = 'Polish (pl_PL)';
rsReadonly = '%s [readonly]';
rsSettings = 'Settings';
rsSpanishEs_ES = 'Spanish (es_ES)';
rsSystemLanguage = 'System language';
implementation
end.
|
{*******************************************************}
{ }
{ XMLIniFile Unit ver 1.02 }
{ }
{ Copyright(c) 2010-2012 DEKO }
{ }
{ }
{*******************************************************}
unit XMLInifile;
{$R-,T-,H+,X+}
interface
uses
Sysutils, Classes, XMLDoc, XMLIntf, Variants {$IFDEF MSWINDOWS}, Windows{$ENDIF};
type
TXMLNodeType = (xdtUnknown, xdtBinary, xdtBool, xdtCurrency, xdtDate,
xdtDateTime, xdtExpandString, xdtFloat, xdtInt64, xdtInteger,
xdtString, xdtTime);
TXMLIniFile = class(TObject)
private
FCurrentNode: IXMLNode;
FCurrentLocationPath: string;
FRootNode: IXMLNode;
FXML: IXMLDocument; // not TXMLDocument
// http://edn.embarcadero.com/jp/article/29241
protected
function BuildLocationPath(LocationPath: string): string;
procedure ChangeNode(Value: IXMLNode; const Path: string);
function GetBaseNode(Relative: Boolean): IXMLNode;
function GetNode(const LocationPath: string): IXMLNode;
function GetRawNode(ParentNode: IXMLNode): IXMLNode;
function GetRootNodeName: string;
function GetReadNode(const TagName: string; ParentNode: IXMLNode = nil): IXMLNode;
function GetWriteNode(const TagName: string; ParentNode: IXMLNode = nil): IXMLNode;
public
constructor Create(const FileName: string);
// constructor Create(const FileName, root: string);
destructor Destroy; override;
{ Methods }
procedure CloseNode;
function CreateNode(const TagName: string; ParentNode: IXMLNode = nil): Boolean;
function DeleteNode(const TagName: string; ParentNode: IXMLNode = nil): Boolean;
function GetNodeType(const TagName: String; ParentNode: IXMLNode = nil): TXMLNodeType;
procedure GetNodeNames(Strings: TStrings; ParentNode: IXMLNode = nil);
function HasChildNodes(ParentNode: IXMLNode = nil): Boolean;
function NodeExists(const LocationPath: string): Boolean;
function OpenNode(const LocationPath: string; CanCreate: Boolean): Boolean;
procedure ReadBinaryData(const TagName: string; var Buffer: TBytes; ParentNode: IXMLNode = nil);
function ReadBool(const TagName: string; Default: Boolean; ParentNode: IXMLNode = nil): Boolean;
function ReadCurrency(const TagName: string; Default: Currency; ParentNode: IXMLNode = nil): Currency;
function ReadDate(const TagName: string; Default: TDateTime; ParentNode: IXMLNode = nil): TDateTime;
function ReadDateTime(const TagName: string; Default: TDateTime; ParentNode: IXMLNode = nil): TDateTime;
{$IFDEF MSWINDOWS}
function ReadExpandString(const TagName: string; Default: string; ParentNode: IXMLNode = nil): string; platform;
{$ENDIF}
function ReadFloat(const TagName: string; Default: Double; ParentNode: IXMLNode = nil): Double;
function ReadInt64(const TagName: string; Default: Int64; ParentNode: IXMLNode = nil): Int64;
function ReadInteger(const TagName: string; Default: Integer; ParentNode: IXMLNode = nil): Integer;
function ReadString(const TagName: string; Default: string; ParentNode: IXMLNode = nil): string;
function ReadTime(const TagName: string; Default: TDateTime; ParentNode: IXMLNode = nil): TDateTime;
function ChildNodeByName(const TagName: string; ParentNode: IXMLNode = nil): IXMLNode;
function ChildNodes(const Index: Integer; ParentNode: IXMLNode = nil): IXMLNode;
function ChildNodesCount(ParentNode: IXMLNode = nil): Integer;
procedure UpdateFile;
procedure WriteCurrency(const TagName: string; Value: Currency; ParentNode: IXMLNode = nil);
procedure WriteBinaryData(const TagName: string; var Buffer: TBytes; ParentNode: IXMLNode = nil);
procedure WriteBool(const TagName: string; Value: Boolean; ParentNode: IXMLNode = nil);
procedure WriteDate(const TagName: string; Value: TDateTime; ParentNode: IXMLNode = nil);
procedure WriteDateTime(const TagName: string; Value: TDateTime; ParentNode: IXMLNode = nil);
{$IFDEF MSWINDOWS}
procedure WriteExpandString(const TagName, Value: string; ParentNode: IXMLNode = nil); platform;
{$ENDIF}
procedure WriteFloat(const TagName: string; Value: Double; ParentNode: IXMLNode = nil);
procedure WriteInt64(const TagName: string; Value: Int64; ParentNode: IXMLNode = nil);
procedure WriteInteger(const TagName: string; Value: Integer; ParentNode: IXMLNode = nil);
procedure WriteString(const TagName, Value: string; ParentNode: IXMLNode = nil);
procedure WriteTime(const TagName: string; Value: TDateTime; ParentNode: IXMLNode = nil);
{ Properties }
property CurrentNode: IXMLNode read FCurrentNode;
property CurrentLocationPath: string read FCurrentLocationPath;
property RootNode: IXMLNode read FRootNode;
property RootNodeName: string read GetRootNodeName;
property XMLDocument: IXMLDocument read FXML;
end;
{ functions }
function IsLocationPathDelimiter(const LocationPath: string; Index: Integer): Boolean;
function IncludeTrailingLocationPathDelimiter(const LocationPath: string): string;
function ExcludeTrailingLocationPathDelimiter(const LocationPath: string): string;
function FormatXMLFile(const FileName: string): Boolean;
const
LocationPathDelim = '/';
implementation
const
sType = 'Type';
sCRLF = #$000D#$000A;
constructor TXMLIniFile.Create(const FileName: string);
//constructor TXMLIniFile.Create(const FileName, root: string);
begin
FXML := TXMLDocument.Create(nil);
FXML.Active := True;
FXML.FileName := FileName;
FXML.NodeIndentStr := #$0009;
FXML.Options := [doNodeAutoIndent];
if (FXML.FileName <> '') and FileExists(FXML.FileName) then
FXML.LoadFromFile(FXML.FileName)
else
begin
FXML.Encoding := 'utf-8';
FXML.Version := '1.0';
FXML.AddChild('root');
// FXML.AddChild(root);
if FXML.FileName <> '' then
FXML.SaveToFile(FXML.FileName);
end;
FRootNode := FXML.DocumentElement;
FCurrentNode := FCurrentNode;
FCurrentLocationPath := LocationPathDelim;
end;
destructor TXMLIniFile.Destroy;
begin
FXML.Active := False;
end;
function TXMLIniFile.BuildLocationPath(LocationPath: string): string;
begin
if Copy(LocationPath, 1, 1) = LocationPathDelim then
result := IncludeTrailingLocationPathDelimiter(LocationPath)
else
result := IncludeTrailingLocationPathDelimiter(IncludeTrailingLocationPathDelimiter(CurrentLocationPath) + LocationPath);
end;
procedure TXMLIniFile.ChangeNode(Value: IXMLNode; const Path: string);
begin
CloseNode;
FCurrentNode := Value;
FCurrentLocationPath := Path;
end;
function TXMLIniFile.GetBaseNode(Relative: Boolean): IXMLNode;
begin
if (CurrentNode = nil) or (not Relative) then
Result := RootNode
else
Result := CurrentNode;
end;
function TXMLIniFile.GetNode(const LocationPath: string): IXMLNode;
var
dNode: IXMLNode;
SL: TStringList;
i: Integer;
begin
SL := TStringList.Create;
try
SL.StrictDelimiter := True;
SL.Delimiter := LocationPathDelim;
SL.DelimitedText := BuildLocationPath(LocationPath);
dNode := FXML.DocumentElement;
for i:=1 to SL.Count - 2 do
begin
dNode := dNode.ChildNodes.FindNode(SL[i]);
if dNode = nil then
Break;
end;
finally
SL.Free;
end;
result := dNode;
end;
function TXMLIniFile.GetRawNode(ParentNode: IXMLNode): IXMLNode;
begin
if ParentNode = nil then
result := FCurrentNode
else
result := ParentNode;
end;
function TXMLIniFile.GetRootNodeName: string;
begin
FRootNode.NodeName;
end;
function TXMLIniFile.GetReadNode(const TagName: string; ParentNode: IXMLNode = nil): IXMLNode;
begin
result := GetRawNode(ParentNode).ChildNodes.FindNode(TagName);
end;
function TXMLIniFile.GetWriteNode(const TagName: string; ParentNode: IXMLNode = nil): IXMLNode;
var
dNode: IXMLNode;
begin
dNode := GetRawNode(ParentNode);
result := dNode.ChildNodes.FindNode(TagName);
if result = nil then
result := dNode.AddChild(TagName);
end;
procedure TXMLIniFile.CloseNode;
begin
;
end;
function TXMLIniFile.CreateNode(const TagName: string; ParentNode: IXMLNode = nil): Boolean;
begin
try
GetRawNode(ParentNode).AddChild(TagName);
result := True;
except
result := False;
end;
end;
function TXMLIniFile.DeleteNode(const TagName: string; ParentNode: IXMLNode = nil): Boolean;
begin
try
GetRawNode(ParentNode).ChildNodes.Delete(TagName);
result := True;
except
result := False;
end;
end;
procedure TXMLIniFile.GetNodeNames(Strings: TStrings; ParentNode: IXMLNode = nil);
var
i: integer;
dNode: IXMLNode;
begin
dNode := GetRawNode(ParentNode);
for i:=0 to dNode.ChildNodes.Count-1 do
Strings.Add(dNode.ChildNodes[i].NodeName);
end;
function TXMLIniFile.GetNodeType(const TagName: String; ParentNode: IXMLNode = nil): TXMLNodeType;
begin
result := GetRawNode(ParentNode).ChildNodes.FindNode(TagName).Attributes[sType];
end;
function TXMLIniFile.HasChildNodes(ParentNode: IXMLNode = nil): Boolean;
begin
result := GetRawNode(ParentNode).HasChildNodes;
end;
function TXMLIniFile.NodeExists(const LocationPath: string): Boolean;
begin
result := (GetNode(LocationPath) <> nil);
end;
function TXMLIniFile.OpenNode(const LocationPath: string; CanCreate: Boolean): Boolean;
var
oNode: IXMLNode;
dNode: IXMLNode;
SL: TStringList;
i: Integer;
begin
if CanCreate then
begin
SL := TStringList.Create;
try
result := False;
SL.StrictDelimiter := True;
SL.Delimiter := LocationPathDelim;
SL.DelimitedText := BuildLocationPath(LocationPath);
dNode := FXML.DocumentElement;
oNode := dNode;
for i:=1 to SL.Count - 2 do
begin
dNode := dNode.ChildNodes.FindNode(SL[i]);
if dNode = nil then
dNode := oNode.AddChild(SL[i]);
oNode := dNode;
end;
result := True;
finally
SL.Free;
end;
end
else
begin
dNode := GetNode(LocationPath);
result := (dNode <> nil);
end;
if result then
begin
FCurrentNode := dNode;
FCurrentLocationPath := BuildLocationPath(LocationPath);
end;
end;
function TXMLIniFile.ReadCurrency(const TagName: string; Default: Currency; ParentNode: IXMLNode = nil): Currency;
var
dNode: IXMLNode;
begin
dNode := GetReadNode(TagName, ParentNode);
if dNode = nil then
result := Default
else
result := StrToCurr(dNode.Text);
end;
procedure TXMLIniFile.ReadBinaryData(const TagName: string; var Buffer: TBytes; ParentNode: IXMLNode = nil);
var
dNode: IXMLNode;
Size: Int64;
Dmy: String;
i: Integer;
SL: TStringList;
begin
dNode := GetReadNode(TagName, ParentNode);
if dNode = nil then
SetLength(Buffer, 0)
else
begin
SL := TStringList.Create;
try
Dmy := dNode.Text;
Dmy := StringReplace(Dmy, sCRLF, '', [rfReplaceAll]);
Dmy := StringReplace(Dmy, ' ', '', [rfReplaceAll]);
SL.StrictDelimiter := True;
SL.Delimiter := ',';
SL.DelimitedText := Dmy;
Dmy := '';
Size := 0;
SetLength(Buffer, SL.Count);
for i:=0 to SL.Count-1 do
begin
Dmy := Trim(SL[i]);
if Dmy = '' then
Continue;
Buffer[i] := StrToInt('0x' + Dmy);
Inc(Size);
end;
SetLength(Buffer, Size);
finally
SL.Free;
end;
end;
end;
function TXMLIniFile.ReadBool(const TagName: string; Default: Boolean; ParentNode: IXMLNode = nil): Boolean;
var
dNode: IXMLNode;
begin
dNode := GetReadNode(TagName, ParentNode);
if dNode = nil then
result := Default
else
result := StrToBool(dNode.Text);
end;
function TXMLIniFile.ReadDate(const TagName: string; Default: TDateTime; ParentNode: IXMLNode = nil): TDateTime;
var
dNode: IXMLNode;
begin
dNode := GetReadNode(TagName, ParentNode);
if dNode = nil then
result := Default
else
result := VarToDateTime(dNode.Text);
end;
function TXMLIniFile.ReadDateTime(const TagName: string; Default: TDateTime; ParentNode: IXMLNode = nil): TDateTime;
var
dNode: IXMLNode;
begin
dNode := GetReadNode(TagName, ParentNode);
if dNode = nil then
result := Default
else
result := VarToDateTime(dNode.Text);
end;
{$IFDEF MSWINDOWS}
function TXMLIniFile.ReadExpandString(const TagName: string; Default: string; ParentNode: IXMLNode = nil): string;
var
Dmy: String;
Size: DWORD;
begin
Dmy := ReadString(TagName, Default, ParentNode);
Size := ExpandEnvironmentStrings(PChar(Dmy), nil, 0);
SetLength(result, Size * 2);
Size := ExpandEnvironmentStrings(PChar(Dmy),PChar(result), Size * 2);
SetLength(result, Size);
end;
{$ENDIF}
function TXMLIniFile.ReadFloat(const TagName: string; Default: Double; ParentNode: IXMLNode = nil): Double;
var
dNode: IXMLNode;
begin
dNode := GetReadNode(TagName, ParentNode);
if (dNode = nil) or (dNode.Text = '') then // 値が空白の時もノードなしにする 14/8/31
result := Default
else
result := StrToFloat(dNode.Text);
end;
function TXMLIniFile.ReadInt64(const TagName: string; Default: Int64; ParentNode: IXMLNode = nil): Int64;
var
dNode: IXMLNode;
begin
dNode := GetReadNode(TagName, ParentNode);
if (dNode = nil) or (dNode.Text = '') then // 値が空白の時もノードなしにする 14/8/31
result := Default
else
result := StrToInt64(dNode.Text);
end;
function TXMLIniFile.ReadInteger(const TagName: string; Default: Integer; ParentNode: IXMLNode = nil): Integer;
var
dNode: IXMLNode;
begin
dNode := GetReadNode(TagName, ParentNode);
if (dNode = nil) or (dNode.Text = '') then // 値が空白の時もノードなしにする 14/8/31
result := Default
else
result := StrToInt(dNode.Text);
end;
function TXMLIniFile.ReadString(const TagName: string; Default: string; ParentNode: IXMLNode = nil): string;
var
Dmy: String;
dNode: IXMLNode;
begin
dNode := GetReadNode(TagName, ParentNode);
if dNode = nil then
result := Default
else
begin
Dmy := dNode.Text;
Dmy := StringReplace(Dmy ,'>' ,'>',[rfReplaceAll,rfIgnoreCase]); // >
Dmy := StringReplace(Dmy ,'<' ,'<',[rfReplaceAll,rfIgnoreCase]); // <
Dmy := StringReplace(Dmy ,'"','"',[rfReplaceAll,rfIgnoreCase]); // "
Dmy := StringReplace(Dmy ,'&' ,'&',[rfReplaceAll,rfIgnoreCase]); // &
result := Dmy;
end;
end;
function TXMLIniFile.ReadTime(const TagName: string; Default: TDateTime; ParentNode: IXMLNode = nil): TDateTime;
var
dNode: IXMLNode;
begin
dNode := GetReadNode(TagName, ParentNode);
if (dNode = nil) or (dNode.Text = '') then // 値が空白の時もノードなしにする 14/8/31
result := Default
else
result := VarToDateTime(dNode.Text);
end;
function TXMLIniFile.ChildNodeByName(const TagName: string; ParentNode: IXMLNode = nil): IXMLNode;
begin
result := GetRawNode(ParentNode).ChildNodes.Nodes[TagName];
end;
function TXMLIniFile.ChildNodes(const Index: Integer; ParentNode: IXMLNode = nil): IXMLNode;
begin
result := GetRawNode(ParentNode).ChildNodes.Nodes[Index];
end;
function TXMLIniFile.ChildNodesCount(ParentNode: IXMLNode = nil): Integer;
begin
result := GetRawNode(ParentNode).ChildNodes.Count;
end;
procedure TXMLIniFile.UpdateFile;
begin
if FXML.Modified then
if FXML.FileName <> '' then
FXML.SaveToFile(FXML.FileName);
end;
procedure TXMLIniFile.WriteCurrency(const TagName: string; Value: Currency; ParentNode: IXMLNode = nil);
begin
GetWriteNode(TagName, ParentNode).Text := CurrToStr(Value);
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtCurrency;
end;
procedure TXMLIniFile.WriteBinaryData(const TagName: string; var Buffer: TBytes; ParentNode: IXMLNode = nil);
var
Size: Int64;
Dmy: String;
i: Integer;
begin
Dmy := '';
Size := Length(Buffer);
for i:=0 to Size - 1 do
begin
Dmy := Dmy + Format('%.2x', [Buffer[i]]);
if i < Size - 1 then
begin
Dmy := Dmy + ',';
if (i mod 16) = 15 then
Dmy := Dmy + sCRLF;
end;
end;
GetWriteNode(TagName, ParentNode).Text := Dmy;
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtBinary;
end;
procedure TXMLIniFile.WriteBool(const TagName: string; Value: Boolean; ParentNode: IXMLNode = nil);
begin
GetWriteNode(TagName, ParentNode).Text := BoolToStr(Value);
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtBool;
end;
procedure TXMLIniFile.WriteDate(const TagName: string; Value: TDateTime; ParentNode: IXMLNode = nil);
begin
GetWriteNode(TagName, ParentNode).Text := DateToStr(Value);
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtDate;
end;
procedure TXMLIniFile.WriteDateTime(const TagName: string; Value: TDateTime; ParentNode: IXMLNode = nil);
begin
GetWriteNode(TagName, ParentNode).Text := DateTimeToStr(Value);
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtDateTime;
end;
{$IFDEF MSWINDOWS}
procedure TXMLIniFile.WriteExpandString(const TagName, Value: string; ParentNode: IXMLNode = nil);
begin
WriteString(TagName, Value, ParentNode);
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtExpandString;
end;
{$ENDIF}
procedure TXMLIniFile.WriteFloat(const TagName: string; Value: Double; ParentNode: IXMLNode = nil);
begin
GetWriteNode(TagName, ParentNode).Text := FloatToStr(Value);
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtFloat;
end;
procedure TXMLIniFile.WriteInt64(const TagName: string; Value: Int64; ParentNode: IXMLNode = nil);
begin
GetWriteNode(TagName, ParentNode).Text := IntToStr(Value);
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtInt64;
end;
procedure TXMLIniFile.WriteInteger(const TagName: string; Value: Integer; ParentNode: IXMLNode = nil);
begin
GetWriteNode(TagName, ParentNode).Text := IntToStr(Value);
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtInteger;
end;
procedure TXMLIniFile.WriteString(const TagName, Value: string; ParentNode: IXMLNode = nil);
var
Dmy: String;
begin
Dmy := Value;
Dmy := StringReplace(Dmy ,'&','&' ,[rfReplaceAll,rfIgnoreCase]); // &
Dmy := StringReplace(Dmy ,'>','>' ,[rfReplaceAll,rfIgnoreCase]); // >
Dmy := StringReplace(Dmy ,'<','<' ,[rfReplaceAll,rfIgnoreCase]); // <
Dmy := StringReplace(Dmy ,'"','"',[rfReplaceAll,rfIgnoreCase]); // "
GetWriteNode(TagName, ParentNode).Text := Dmy;
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtString;
end;
procedure TXMLIniFile.WriteTime(const TagName: string; Value: TDateTime; ParentNode: IXMLNode = nil);
begin
GetWriteNode(TagName, ParentNode).Text := TimeToStr(Value);
GetWriteNode(TagName, ParentNode).Attributes[sType] := xdtTime;
end;
{ functions }
function IsLocationPathDelimiter(const LocationPath: string; Index: Integer): Boolean;
begin
Result := (Index > 0) and (Index <= Length(LocationPath)) and (LocationPath[Index] = LocationPathDelim);
end;
function IncludeTrailingLocationPathDelimiter(const LocationPath: string): string;
begin
Result := LocationPath;
if not IsLocationPathDelimiter(Result, Length(Result)) then
Result := Result + LocationPathDelim;
end;
function ExcludeTrailingLocationPathDelimiter(const LocationPath: string): string;
begin
Result := LocationPath;
if IsLocationPathDelimiter(Result, Length(Result)) then
SetLength(Result, Length(Result)-1);
end;
function FormatXMLFile(const FileName: string): Boolean;
var
FXML: IXMLDocument;
begin
result := False;
if not FileExists(FileName) then
Exit;
FXML := TXMLDocument.Create(nil);
try
FXML.LoadFromFile(FileName);
FXML.XML.Text := XMLDoc.FormatXMLData(FXML.XML.Text);
FXML.Active := True;
FXML.SaveToFile(FileName);
result := True;
finally
end;
end;
end.
|
unit BCEditor.Editor.ActiveLine;
interface
uses
Classes, Graphics, BCEditor.Editor.Glyph, BCEditor.Consts;
type
TBCEditorActiveLine = class(TPersistent)
strict private
FColor: TColor;
FIndicator: TBCEditorGlyph;
FOnChange: TNotifyEvent;
FVisible: Boolean;
procedure DoChange(Sender: TObject);
procedure SetColor(const Value: TColor);
procedure SetIndicator(const Value: TBCEditorGlyph);
procedure SetOnChange(Value: TNotifyEvent);
procedure SetVisible(const Value: Boolean);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Color: TColor read FColor write SetColor default clActiveLineBackground;
property Indicator: TBCEditorGlyph read FIndicator write SetIndicator;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
property Visible: Boolean read FVisible write SetVisible default True;
end;
implementation
{ TBCEditorActiveLine }
constructor TBCEditorActiveLine.Create;
begin
inherited;
FColor := clActiveLineBackground;
FIndicator := TBCEditorGlyph.Create(HINSTANCE, 'BCEDITORACTIVELINE', clFuchsia);
FIndicator.Visible := False;
FVisible := True;
end;
destructor TBCEditorActiveLine.Destroy;
begin
FIndicator.Free;
inherited;
end;
procedure TBCEditorActiveLine.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TBCEditorActiveLine) then
with Source as TBCEditorActiveLine do
begin
Self.FColor := FColor;
Self.FVisible := FVisible;
Self.FIndicator.Assign(FIndicator);
Self.DoChange(Self);
end
else
inherited Assign(Source);
end;
procedure TBCEditorActiveLine.SetOnChange(Value: TNotifyEvent);
begin
FOnChange := Value;
FIndicator.OnChange := Value;
end;
procedure TBCEditorActiveLine.DoChange(Sender: TObject);
begin
if Assigned(FOnChange) then
FOnChange(Sender);
end;
procedure TBCEditorActiveLine.SetColor(const Value: TColor);
begin
if FColor <> Value then
begin
FColor := Value;
DoChange(Self);
end;
end;
procedure TBCEditorActiveLine.SetIndicator(const Value: TBCEditorGlyph);
begin
FIndicator.Assign(Value);
end;
procedure TBCEditorActiveLine.SetVisible(const Value: Boolean);
begin
if FVisible <> Value then
begin
FVisible := Value;
DoChange(Self);
end;
end;
end.
|
unit IWCompCheckbox;
{PUBDIST}
interface
uses
Classes, IWHTMLTag,
IWControl, IWTypes, IWScriptEvents;
type
TIWCustomCheckBoxStyle = (stNormal, stCool);
TIWCustomCheckBox = class(TIWControl)
protected
FChecked: Boolean;
FStyle: TIWCustomCheckBoxStyle;
//
procedure HookEvents(AScriptEvents: TIWScriptEvents); override;
//
procedure Submit(const AValue: string); override;
procedure SetValue(const AValue: string); override;
//
procedure SetChecked(AValue: boolean);
public
constructor Create(AOwner: TComponent); override;
//
function RenderHTML: TIWHTMLTag; override;
//
//@@ This property indicates that the checkbox is checked. Setting this to true will cause the
// checkbox to appear checked in the user's web-browser.
property Checked: Boolean read FChecked write SetChecked;
published
//@@ This is the text that is displayed on the to the right of the check box in the browser.
property Caption;
property Editable;
property ExtraTagParams;
property Font;
property ScriptEvents;
//@@ Specifies caption to appear with checkbox.
property DoSubmitValidation;
//@@ OnClick is fired when the user checks or unchecks the check box.
property OnClick;
//@@ Style determines how the checkbox appears to the user.
//stNormal - Appears as a normal checkbox
//stCool - Appears as a graphical checkbox with colors
property Style: TIWCustomCheckBoxStyle read FStyle write FStyle;
property TabOrder;
end;
TIWCheckBox = class(TIWCustomCheckBox)
published
property Checked;
end;
implementation
uses
{$IFDEF Linux}QGraphics,{$ELSE}Graphics,{$ENDIF}
IWAppForm,
SysUtils, SWSystem;
function TIWCustomCheckBox.RenderHTML: TIWHTMLTag;
begin
// Div is a must here becouse the HTML is constructed by TAG + Caption or 2 TAGS
Result := TIWHTMLTag.CreateTag('SPAN'); try
Result.AddStringParam('ID', HTMLName);
Result.AddStringParam('NAME', HTMLName + '_CHECKBOX');
if (Style = stNormal) then begin
Result.ScriptedTag := Result.Contents.AddTag('INPUT');
with Result.ScriptedTag do begin
if Editable then begin
AddStringParam('TYPE', 'CHECKBOX');
Add(iif(FChecked, 'CHECKED'));
AddStringParam('NAME', HTMLName);
AddStringParam('ID', HTMLName + '_CHECKBOX');
end else begin
AddStringParam('TYPE', 'CHECKBOX');
Add(iif(FChecked, 'CHECKED'));
AddStringParam('OnClick', 'return false;');
end;
end;
Result.Contents.AddText(Caption);
end else begin
if Editable then begin
with TIWAppForm(Form) do begin
CacheImage('TIWCustomCheckBox_False', WebApplication.URLBase
+ '/gfx/TIWCustomCheckBox_False.gif');
CacheImage('TIWCustomCheckBox_True', WebApplication.URLBase
+ '/gfx/TIWCustomCheckBox_True.gif');
AddToInitProc('document.images.' + HTMLName + '_Image.src'
+ '=GImageCache_TIWCustomCheckBox_' + iif(FChecked, 'True', 'False') + '.src;' + EOL
+ 'GSubmitter.elements[''' + HTMLName + '''].value="' + iif(FChecked, 'On', 'Off')
+ '";' + EOL);
end;
//TODO: Use a TIWHTMLImage
with Result.Contents.AddTag('A') do begin
AddStringParam('HREF', '#');
AddStringParam('OnClick'
, 'TIWCustomCheckBoxToggle(''' + HTMLName + ''', ' + 'document.images.' + HTMLName
+ '_Image, ' + iif(Assigned(OnClick), 'true', 'false') + ')');
with Contents.AddTag('INPUT') do begin
AddStringParam('TYPE', 'HIDDEN');
AddStringParam('NAME', HTMLName);
AddStringParam('ID', HTMLName);
end;
with Contents.AddTag('IMG') do begin
AddStringParam('NAME', HTMLName + '_Image');
AddIntegerParam('BORDER', 0);
// Width and height tags necessary for NS4, good for others
AddIntegerParam('WIDTH', 10);
AddIntegerParam('HEIGHT', 12);
end;
end;
end else begin
//TODO: Use a TIWHTMLImage
with Result.Contents.AddTag('IMG') do begin
AddStringParam('SRC', WebApplication.URLBase + '/gfx/TIWCustomCheckBox_' + iif(FChecked, 'True', 'False') + '.gif');
AddIntegerParam('BORDER', 0);
// Width and height tags necessary for NS4, good for others
AddIntegerParam('WIDTH', 10);
AddIntegerParam('HEIGHT', 12);
end;
end;
Result.Contents.AddText(Caption);
end;
except FreeAndNil(Result); raise; end;
end;
procedure TIWCustomCheckBox.SetValue(const AValue: string);
begin
FChecked := AnsiSameText(AValue, 'On');
Invalidate;
end;
procedure TIWCustomCheckBox.Submit(const AValue: string);
begin
DoClick;
end;
procedure TIWCustomCheckBox.SetChecked(AValue: boolean);
begin
FChecked := AValue;
Invalidate;
end;
constructor TIWCustomCheckBox.Create(AOwner: TComponent);
begin
inherited;
FNeedsFormTag := True;
FSupportsInput := True;
FSupportsSubmit := True;
FSupportedScriptEvents := 'OnBlur,OnClick,OnFocus';
Height := 21;
Width := 121;
end;
procedure TIWCustomCheckBox.HookEvents(AScriptEvents: TIWScriptEvents);
begin
inherited HookEvents(AScriptEvents);
if (Style = stNormal) and Editable then begin
AScriptEvents.HookEvent('OnClick', iif(Assigned(OnClick), SubmitHandler));
end;
end;
end.
|
unit AbstractView;
interface
uses
System.SysUtils, InterfaceRecursos;
type
TView = class
Recursos: IRecursos;
constructor Create(Recursos: IRecursos);
function Exibir(Artista: string): string; virtual; abstract;
end;
implementation
{ TView }
constructor TView.Create(Recursos: IRecursos);
begin
Self.Recursos := Recursos;
end;
end.
|
unit MyTitles;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,jpeg;
type
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCanResize(Sender: TObject; var NewWidth,
NewHeight: Integer; var Resize: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Button2Click(Sender: TObject);
private
Procedure MoveForm(var M:TWMNCHITTEST);Message WM_NCHITTEST;
//声明一自定义事件,拦截“WM_NCHITTEST”消息 { Private declarations }
// 当在标题栏上按下鼠标左按钮时进入该过程
procedure WMNcLButtonDown(var m: TMessage); message WM_NCLBUTTONDOWN;
// 当在标题栏上放开鼠标左按钮时进入该过程
procedure WMNcLButtonUp(var m: TMessage); message WM_NCLBUTTONUP;
// 当在标题栏上移动鼠标时进入该过程
procedure WMNcMouseMove(var m: TMessage); message WM_NCMOUSEMOVE;
// 当在标题栏上双击鼠标左铵钮时进入该过程
procedure WMNcLButtonDBLClk(var m: TMessage); message WM_NCLBUTTONDBLCLK;
// 当在标题栏上按下鼠标右按钮时进入该过程
procedure WMNcRButtonDown(var m: TMessage); message WM_NCRBUTTONDOWN;
// 当画标题栏时进入该过程
procedure WMNcPaint(var m: TMessage); message WM_NCPAINT;
// 当标题栏在激活与非激活之间切换时进入该过程
procedure WMNcActivate(var m: TMessage); message WM_NCACTIVATE;
public
{ Public declarations }
end;
var
Form1: TForm1;
win:TRect;
implementation
{$R *.dfm}
Procedure TForm1.MoveForm (var M:TWMNCHITTEST);
begin
inHerited; //继承,窗体可以继续处理以后的事件
if (M.Result=HTCLIENT) //如果发生在客户区
//and ((GetKeyState(vk_CONTROL) < 0)) //检测“Ctrl”键是否按下
then M.Result:=HTCAPTION; //更改“.Result”域的值
end;
procedure tform1.WMNcLButtonDown(var m: TMessage);
begin
inherited;
Label1.Caption:='MouseDown';
end;
procedure tform1.WMNcLButtonUp(var m: TMessage);
begin
inherited;
Label1.Caption:=Label1.caption+' MouseUp';
end;
procedure Tform1.WMNcMouseMove(var m: TMessage);
var
bmp:TBitmap;
ttrec,tcrec:TRect;
pt:TPoint;
jpg:TJPEGImage;
begin
inherited;
GetCursorPos(pt);Canvas.Handle:=GetWindowDC(Self.Handle);
caption:=Format('mouse: X,Y:%d,%d',[pt.X,pt.Y]);
GetWindowRect(Self.Handle,ttrec);
tcrec:=GetClientRect;
ttrec.Left:=ttrec.Right-50;
ttrec.Right:=ttrec.Right-25;
bmp:=TBitmap.Create;jpg:=TJPEGImage.Create;
if PtInRect(ttrec,pt) then
begin
// jpg.LoadFromFile('f:\图片\8860092.jpg');
bmp.LoadFromFile('40.bmp');
Canvas.Draw(ttrec.Left,0,jpg);
end else
begin
bmp.LoadFromFile('40.bmp');
Canvas.Draw(ttrec.Left,0,bmp);
end;
end;
procedure TForm1.WMNcLButtonDBLClk(var m: TMessage);
begin
inherited;
Label1.Caption:=label1.caption+'双击左';
end;
procedure TFORM1.WMNcRButtonDown(var m: TMessage);
begin
inherited;
Label1.Caption:=Label1.caption+#13+'RBdown';
end;
procedure TFORM1.WMNcPaint(var m: TMessage);
var
tDC:HDC;
titlebmp:TBitmap;
begin
inherited;
// SetWindowRgn(Self.handle, CreateRoundRectRgn(0,0,self.width,self.height,5,5),True);
Canvas.Handle:=GetWindowDC(Self.Handle);
win:=GetClientRect;
titlebmp:=TBitmap.Create;
// titlebmp.LoadFromFile('f:\图片\4411708.bmp');
// Canvas.Handle:=tDC;
// Canvas.Draw(700,0,titlebmp);
//Canvas.Draw(0,0,titlebmp);
titlebmp.LoadFromFile('4.bmp');
Canvas.Draw(win.right-28,0,titlebmp);
titlebmp.loadfromfile('4.bmp');
canvas.draw(win.right-50,0,titlebmp);
ReleaseDC(Self.Handle,Canvas.Handle);
titlebmp.Free;
Canvas.Handle:=0;
end;
procedure TFORM1.WMNcActivate(var m: TMessage);
begin
inherited;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
tDC:HDC;
titlebmp:TBitmap;
sidew,sideh,bw,bh:Integer;
begin
Canvas.Handle:=GetWindowDC(Self.Handle);
titlebmp:=TBitmap.Create;
titlebmp.LoadFromFile('068.bmp');
// Canvas.Handle:=tDC;
Canvas.Draw(0,0,titlebmp);
ReleaseDC(Self.Handle,Canvas.Handle);
titlebmp.Free;
Canvas.Handle:=0;
sidew:=GetSystemMetrics(SM_CXFRAME);//边框厚度
sideh:=GetSystemMetrics(SM_CYFRAME);
bw :=GetSystemMetrics(SM_CXSIZE); //标题栏按钮的尺寸
bh :=GetSystemMetrics(SM_CYSIZE);
Button1.caption:=IntToStr(sidew)+':'+inttostr(sideh)+':'+inttostr(bw)+':'+inttostr(bh);
end;
procedure TForm1.FormCanResize(Sender: TObject; var NewWidth,
NewHeight: Integer; var Resize: Boolean);
var
tDC:HDC;
titlebmp:TBitmap;
begin
Canvas.Handle:=GetWindowDC(Self.Handle);
titlebmp:=TBitmap.Create;
titlebmp.LoadFromFile('40.bmp');
// Canvas.Handle:=tDC;
Canvas.Draw(700,0,titlebmp);
Canvas.Draw(0,0,titlebmp);
ReleaseDC(Self.Handle,Canvas.Handle);
titlebmp.Free;
Canvas.Handle:=0;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
ExSty:DWORD;
begin
{ ExSty:=GetWindowLong(Handle,GWL_EXSTYLE);
ExSty:=ExSty or WS_EX_TRANSPARENT or WS_EX_LAYERED;
SetWindowLong(Handle,GWL_EXSTYLE,ExSty);
SetLayeredWindowAttributes(Handle,cardinal(clBtnFace),125,LWA_ALPHA);
MoveWindow(Handle,Screen.Width-Self.Width,0,Self.Width,Self.Height,false);
}
SetWindowRgn(Self.handle, CreateRoundRectRgn(0,0,self.width,self.height,5,5),True);
end;
procedure TForm1.FormActivate(Sender: TObject);
var
tDC:HDC;
titlebmp:TBitmap;
begin
getwindowrect(Self.Handle,win);
win:=GetClientRect;
end;
procedure TForm1.FormResize(Sender: TObject);
var
tDC:HDC;
titlebmp:TBitmap;
begin
SetWindowRgn(Self.handle, CreateRoundRectRgn(0,0,self.width,self.height,5,5),True);
Canvas.Handle:=GetWindowDC(Self.Handle);
win:=GetClientRect;
titlebmp:=TBitmap.Create;
titlebmp.LoadFromFile('40.bmp');
// Canvas.Handle:=tDC;
Canvas.Draw(700,0,titlebmp);
//Canvas.Draw(0,0,titlebmp);
titlebmp.LoadFromFile('4.bmp');
Canvas.Draw(win.right-28,0,titlebmp);
titlebmp.loadfromfile('4.bmp');
canvas.draw(win.right-50,0,titlebmp);
ReleaseDC(Self.Handle,Canvas.Handle);
titlebmp.Free;
Canvas.Handle:=0;
end;
procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
pt:TPoint; rc:trect;
begin
GetCursorPos(pt);
GetWindowRect(Self.Handle,rc);
rc.Left:=rc.Left+(rc.Right-rc.left) div 2 -20;
rc.Top:=rc.Top+(rc.Bottom-rc.Top)div 2 -20;
rc.Right:=rc.left+40;
rc.Bottom:=rc.Top+40;
if PtInRect(rc,pt) then
caption:=Format('TTTOOOPP:XY:%d,%d',[pt.x,pt.y])
else
caption:=Format('mouse: X,Y:%d,%d',[pt.X,pt.Y]);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Application.Terminate;
end;
end.
|
unit Recipient;
interface
uses
Entity, ADODB, DB;
type
TRecipient = class(TEntity)
private
FName: string;
public
procedure Add; override;
procedure Save; override;
procedure Edit; override;
procedure Cancel; override;
property Name: string read FName write FName;
constructor Create(const id, name: string); overload;
end;
var
rcp: TRecipient;
implementation
uses
EntitiesData;
constructor TRecipient.Create(const id: string; const name: string);
begin
FId := id;
FName := name;
end;
procedure TRecipient.Add;
var
i: integer;
begin
with dmEntities do
begin
for i:=0 to ComponentCount - 1 do
begin
if Components[i] is TADODataSet then
begin
if (Components[i] as TADODataSet).Tag in [7,8] then
begin
(Components[i] as TADODataSet).Open;
(Components[i] as TADODataSet).Append;
end;
end;
end;
end;
end;
procedure TRecipient.Save;
var
i: integer;
begin
with dmEntities do
begin
for i:=0 to ComponentCount - 1 do
begin
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Tag in [7,8] then
if (Components[i] as TADODataSet).State in [dsInsert,dsEdit] then
(Components[i] as TADODataSet).Post;
end;
end;
end;
procedure TRecipient.Edit;
begin
end;
procedure TRecipient.Cancel;
var
i: integer;
begin
with dmEntities do
begin
for i:=0 to ComponentCount - 1 do
begin
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Tag in [7,8] then
if (Components[i] as TADODataSet).State in [dsInsert,dsEdit] then
(Components[i] as TADODataSet).Cancel;
end;
end;
end;
end.
|
unit uPaperInfoBase;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ComCtrls, StdCtrls, xPaperAction;
type
TfPaperInfoBase = class(TForm)
pnl1: TPanel;
btnCancel: TButton;
btnSave: TButton;
btnPrint: TButton;
pnlMain: TPanel;
lbl3: TLabel;
edtScore: TEdit;
lvQuestList: TListView;
spltr1: TSplitter;
lbl1: TLabel;
procedure edtScoreKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
/// <summary>
/// ÏÔʾ¿¼¾íÐÅÏ¢
/// </summary>
procedure ShowPaperInfo( nPaperID, nStuID: Integer; dScore: Double );
end;
implementation
{$R *.dfm}
procedure TfPaperInfoBase.edtScoreKeyPress(Sender: TObject; var Key: Char);
begin
if not ( Ord(Key) in [8, 13, 45, 46, 48..57] ) then Key := #0;
end;
procedure TfPaperInfoBase.ShowPaperInfo(nPaperID, nStuID: Integer; dScore : Double);
begin
edtScore.Text := FloatToStr(dScore);
if ShowModal = mrOk then
begin
TryStrToFloat(edtScore.Text, dScore);
APaperAction.EditStuScore(nPaperID, nStuID, dScore);
end;
end;
end.
|
unit UnFornecedorListaRegistrosView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, StdCtrls, JvExControls, JvButton, DB,
JvTransparentButton, ExtCtrls,
{ Fluente }
Util, DataUtil, UnModelo, UnFornecedorListaRegistrosModelo,
Componentes, UnAplicacao, JvExDBGrids, JvDBGrid, JvDBUltimGrid;
type
TFornecedorListaRegistrosView = class(TForm, ITela)
Panel1: TPanel;
btnAdicionar: TJvTransparentButton;
JvTransparentButton2: TJvTransparentButton;
pnlFiltro: TPanel;
EdtFornecedor: TEdit;
gFornecedores: TJvDBUltimGrid;
procedure btnAdicionarClick(Sender: TObject);
procedure gFornecedoresDblClick(Sender: TObject);
procedure EdtFornecedorChange(Sender: TObject);
private
FControlador: IResposta;
FFornecedorListaRegistrosModelo: TFornecedorListaRegistrosModelo;
public
function Descarregar: ITela;
function Controlador(const Controlador: IResposta): ITela;
function Modelo(const Modelo: TModelo): ITela;
function Preparar: ITela;
function ExibirTela: Integer;
end;
implementation
{$R *.dfm}
{ TFornecedorListaRegistrosView }
function TFornecedorListaRegistrosView.Controlador(
const Controlador: IResposta): ITela;
begin
Self.FControlador := Controlador;
Result := Self;
end;
function TFornecedorListaRegistrosView.Descarregar: ITela;
begin
Self.FControlador := nil;
Self.FFornecedorListaRegistrosModelo := nil;
Result := Self;
end;
function TFornecedorListaRegistrosView.ExibirTela: Integer;
begin
Result := Self.ShowModal;
end;
function TFornecedorListaRegistrosView.Modelo(
const Modelo: TModelo): ITela;
begin
Self.FFornecedorListaRegistrosModelo :=
(Modelo as TFornecedorListaRegistrosModelo);
Result := Self;
end;
function TFornecedorListaRegistrosView.Preparar: ITela;
begin
Self.gFornecedores.DataSource :=
Self.FFornecedorListaRegistrosModelo.DataSource;
Result := Self;
end;
procedure TFornecedorListaRegistrosView.btnAdicionarClick(Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FFornecedorListaRegistrosModelo.Parametros;
_parametros
.Gravar('acao', 'incluir');
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
procedure TFornecedorListaRegistrosView.gFornecedoresDblClick(
Sender: TObject);
var
_chamada: TChamada;
_dataSet: TDataSet;
begin
_dataSet := Self.FFornecedorListaRegistrosModelo.DataSet;
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(TMap.Create
.Gravar('acao', Ord(adrCarregar))
.Gravar('oid', _dataSet.FieldByName('forn_oid').AsString)
);
Self.FControlador.Responder(_chamada)
end;
procedure TFornecedorListaRegistrosView.EdtFornecedorChange(
Sender: TObject);
begin
if Self.EdtFornecedor.Text = '' then
Self.FFornecedorListaRegistrosModelo.Carregar
else
Self.FFornecedorListaRegistrosModelo.CarregarPor(
Criterio.Campo('forn_nome').como(Self.EdtFornecedor.Text).obter());
end;
end.
|
unit fConsMedRslt;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ORCtrls, ORfn, ExtCtrls, fAutoSz, ORDtTm, fConsultAlertTo, fRptBox,
VA508AccessibilityManager, Vcl.ComCtrls, Vcl.ImgList;
type
TMedResultRec = record
Action: string;
ResultPtr: string;
DateTimeofAction: TFMDateTime;
ResponsiblePerson: Int64;
AlertsTo: TRecipientList;
end;
TfrmConsMedRslt = class(TfrmAutoSz)
pnlBase: TORAutoPanel;
pnlAction: TPanel;
pnlbottom: TPanel;
pnlMiddle: TPanel;
pnlButtons: TPanel;
cmdOK: TButton;
cmdCancel: TButton;
ckAlert: TCheckBox;
cmdDetails: TButton;
calDateofAction: TORDateBox;
lblDateofAction: TOROffsetLabel;
lblActionBy: TOROffsetLabel;
cboPerson: TORComboBox;
SrcLabel: TLabel;
lstMedResults: TCaptionListView;
ImageList1: TImageList;
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure cmdDetailsClick(Sender: TObject);
procedure ckAlertClick(Sender: TObject);
procedure NewPersonNeedData(Sender: TObject; const StartFrom: String;
Direction, InsertAt: Integer);
procedure FormDestroy(Sender: TObject);
// procedure lstMedResultsDrawItem(Control: TWinControl; Index: Integer;
// Rect: TRect; State: TOwnerDrawState);
procedure FormCreate(Sender: TObject);
protected
procedure ShowDetailsDestroyed(Sender: TObject);
private
FShowDetails: TfrmReportBox;
FOldShowDetailsOnDestroy: TNotifyEvent;
FMedResult: TMedResultRec ;
FChanged: Boolean;
end;
function SelectMedicineResult(ConsultIEN: integer; FormTitle: string; var MedResult: TMedResultRec): boolean ;
implementation
{$R *.DFM}
uses rConsults, rCore, uCore, uConst;
const
TX_MEDRSLT_TEXT = 'Select medicine result or press Cancel.';
TX_MEDRSLT_CAP = 'No Result Selected';
var
RecipientList: TRecipientList ;
function SelectMedicineResult(ConsultIEN: integer; FormTitle: string; var MedResult: TMedResultRec): boolean ;
{ displays Medicine Result selection form and returns a record of the selection }
var
frmConsMedRslt: TfrmConsMedRslt;
procedure DisplayImage(LstView: TCaptionListView);
var
x: String;
I: Integer;
begin
for I := 0 to LstView.Items.Count - 1 do
begin
x := LstView.Strings[i];
if StrToIntDef(Piece(x, U, 5), 0) > 0 then
LstView.Items[i].ImageIndex := 0
else
LstView.Items[i].ImageIndex := -1;
end;
end;
begin
frmConsMedRslt := TfrmConsMedRslt.Create(Application);
try
with frmConsMedRslt do
begin
FChanged := False;
FillChar(RecipientList, SizeOf(RecipientList), 0);
FillChar(FMedResult, SizeOf(FMedResult), 0);
Caption := FormTitle;
cboPerson.InitLongList(User.Name);
cboPerson.SelectByIEN(User.DUZ);
ResizeFormToFont(TForm(frmConsMedRslt));
if MedResult.Action = 'ATTACH' then
begin
FastAssign(GetAssignableMedResults(ConsultIEN), lstMedResults.ItemsStrings);
ckAlert.Visible := True;
DisplayImage(lstMedResults);
end
else if MedResult.Action = 'REMOVE' then
begin
FastAssign(GetRemovableMedResults(ConsultIEN), lstMedResults.ItemsStrings);
ckAlert.Visible := False;
DisplayImage(lstMedResults);
end;
if lstMedResults.Items.Count > 0 then
ShowModal
else
FChanged := True;
Result := FChanged;
MedResult := FMedResult;
end; {with frmODConsMedRslt}
finally
frmConsMedRslt.Release;
end;
end;
procedure TfrmConsMedRslt.cmdCancelClick(Sender: TObject);
begin
FillChar(FMedResult, SizeOf(FMedResult), 0);
FChanged := False;
Close;
end;
procedure TfrmConsMedRslt.cmdOKClick(Sender: TObject);
begin
FillChar(FMedResult, SizeOf(FMedResult), 0);
if lstMedResults.ItemIndex = -1 then
begin
InfoBox(TX_MEDRSLT_TEXT, TX_MEDRSLT_CAP, MB_OK or MB_ICONWARNING);
FChanged := False ;
Exit;
end;
FChanged := True;
with FMedResult do
begin
ResultPtr := lstMedResults.ItemID ;
DateTimeofAction := calDateOfAction.FMDateTime;
ResponsiblePerson := cboPerson.ItemIEN;
AlertsTo := RecipientList;
end;
Close;
end;
procedure TfrmConsMedRslt.cmdDetailsClick(Sender: TObject);
const
TX_RESULTS_CAP = 'Detailed Results Display';
var
x: string;
//MsgString, HasImages: string;
begin
inherited;
if lstMedResults.ItemIndex = -1 then exit;
x := Piece(Piece(Piece(lstMedResults.ItemID, ';', 2), '(', 2), ',', 1) + ';' + Piece(lstMedResults.ItemID, ';', 1);
// ---------------------------------------------------------------
// Don't do this until MED API is changed for new/unassigned results, or false '0' will be broadcast
(* MsgString := 'MED^' + x;
HasImages := BOOLCHAR[StrToIntDef(Piece(x, U, 5), 0) > 0];
SetPiece(HasImages, U, 10, HasImages);
NotifyOtherApps(NAE_REPORT, MsgString);*)
// ---------------------------------------------------------------
NotifyOtherApps(NAE_REPORT, 'MED^' + x);
if(not assigned(FShowDetails)) then
begin
FShowDetails := ModelessReportBox(GetDetailedMedicineResults(lstMedResults.ItemID), TX_RESULTS_CAP, True);
FOldShowDetailsOnDestroy := FShowDetails.OnDestroy;
FShowDetails.OnDestroy := ShowDetailsDestroyed;
cmdDetails.Enabled := (not assigned(FShowDetails));
lstMedResults.Enabled := (not assigned(FShowDetails));
end;
end;
procedure TfrmConsMedRslt.ShowDetailsDestroyed(Sender: TObject);
begin
if(assigned(FOldShowDetailsOnDestroy)) then
FOldShowDetailsOnDestroy(Sender);
FShowDetails := nil;
cmdDetails.Enabled := (not assigned(FShowDetails));
lstMedResults.Enabled := (not assigned(FShowDetails));
end;
procedure TfrmConsMedRslt.ckAlertClick(Sender: TObject);
begin
FillChar(RecipientList, SizeOf(RecipientList), 0);
if ckAlert.Checked then SelectRecipients(Font.Size, 0, RecipientList) ;
end;
procedure TfrmConsMedRslt.NewPersonNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
begin
inherited;
(Sender as TORComboBox).ForDataUse(SubSetOfPersons(StartFrom, Direction));
end;
procedure TfrmConsMedRslt.FormCreate(Sender: TObject);
var
AnImage: TBitMap;
begin
inherited;
AnImage := TBitMap.Create;
try
AnImage.LoadFromResourceName(hInstance, 'BMP_IMAGEFLAG_1');
ImageList1.Add(AnImage,nil);
finally
AnImage.Free;
end;
end;
procedure TfrmConsMedRslt.FormDestroy(Sender: TObject);
begin
inherited;
KillObj(@FShowDetails);
end;
{procedure TfrmConsMedRslt.lstMedResultsDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
x: string;
AnImage: TBitMap;
const
STD_PROC_TEXT = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
STD_DATE = 'MMM DD,YY@HH:NNXX';
begin
inherited;
AnImage := TBitMap.Create;
try
with (Control as TORListBox).Canvas do { draw on control canvas, not on the form }
{ begin
x := (Control as TORListBox).Items[Index];
FillRect(Rect); { clear the rectangle }
{ AnImage.LoadFromResourceName(hInstance, 'BMP_IMAGEFLAG_1');
(Control as TORListBox).ItemHeight := HigherOf(TextHeight(x), AnImage.Height);
if StrToIntDef(Piece(x, U, 5), 0) > 0 then
begin
BrushCopy(Bounds(Rect.Left, Rect.Top, AnImage.Width, AnImage.Height),
AnImage, Bounds(0, 0, AnImage.Width, AnImage.Height), clRed); {render ImageFlag}
{ end;
TextOut(Rect.Left + AnImage.Width, Rect.Top, Piece(x, U, 2));
TextOut(Rect.Left + AnImage.Width + TextWidth(STD_PROC_TEXT), Rect.Top, Piece(x, U, 3));
TextOut(Rect.Left + AnImage.Width + TextWidth(STD_PROC_TEXT) + TextWidth(STD_DATE), Rect.Top, Piece(x, U, 4));
end;
finally
AnImage.Free;
end;
end; }
end.
|
{
Convex Hull - Shortest Polygon
Jordan Gift Wrapping Algorithm O(N.K)
Input:
N: Number of points
P[I]: Coordinates of point I
Output:
K: Number of points on ConvexHull
C: Index of points in ConvexHull
Note:
It finds the shortest ConvexHull (In case of many points on a line)
Reference:
Creative
By Behdad
}
program
ConvexHullJordan;
const
MaxN = 1000 + 2;
type
Point = record
X, Y : Integer;
end;
var
N, K : Integer;
P : array [1 .. MaxN] of Point;
C : array [1 .. MaxN] of Integer;
Mark : array [1 .. MaxN] of Boolean;
function Left (var A, B, C : Point) : Longint;
begin
Left := (Longint(A.X)-B.X)*(Longint(C.Y)-B.Y) -
(Longint(A.Y)-B.Y)*(Longint(C.X)-B.X);
end;
function D (var A, B : Point) : Extended;
begin
D := Sqrt(Sqr(Longint(A.X) - B.X) + Sqr(Longint(A.Y) - B.Y));
end;
procedure ConvexHull;
var
I, J: Integer;
begin
FillChar(Mark, SizeOf(Mark), 0);
C[1] := 1;
for I := 1 to N do
if P[I].Y < P[C[1]].Y then
C[1] := I
else
if (P[I].Y = P[C[1]].Y) and (P[I].X < P[C[1]].X) then
C[1] := I;
Mark[C[1]] := True;
K := 1;
repeat
J := C[1];
for I := 1 to N do
if (not Mark[I]) then
if Left(P[J], P[C[K]], P[I]) < 0 then
J := I
else
if (Left(P[J], P[C[K]], P[I]) = 0) and (D(P[C[K]], P[I]) > D(P[C[K]], P[J])) then
J := I;
Inc(K);
C[K] := J;
until C[K] = C[1];
end;
begin
ConvexHull;
end.
|
{
Tools for serializing and deserializing TForm position on screen.
@author(Tomáš Borek <tomas.borek@post.cz>)
}
unit UFormSettings;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, IniFiles;
type
{ Manages form settings shared data. }
{ TFormSettingsManager }
TFormSettingsManager = class
private
FIniFilePath: String;
FIniFileName: String;
public
{ Gets configured ini file path. }
property IniFilePath: String read FIniFilePath;
{ Gets configured ini file name. }
property IniFileName: String read FIniFileName;
{ Initializes manager default values.
Ini file folder is set to application folder. Ini file name is set to
application exe file name with extension changed to ini. }
constructor Create;
{ Sets ini file location to application folder. }
procedure UseAppFolder;
{ Sets ini file location to <User>\AppData\<AFolder>.
When AFolder not set, exe name without folder will be used. }
procedure UseRoamingFolder(const AFolder: String = '');
{ Sets custom ini file location and name. }
procedure UseCustomFolder(const AIniFilePath: String);
{ Sets ini file name to given value. if empty string given, ni file name is
set to application exe file name with extension changed to ini. }
procedure SetIniFileName(const AIniFileName: String = '');
end;
{ TFormSettings }
TFormSettings = class
private
FForm: TForm;
protected
{ Builds settings file name. }
function GetIniFileName: String;
public
{ Binds current instance to AForm. }
constructor Create(AForm: TForm);
{ Loads stored form settings. }
procedure Load;
{ Stores current from settings. }
procedure Save;
end;
var
FormSettingsManager: TFormSettingsManager;
implementation
{ TFormSettingsManager }
constructor TFormSettingsManager.Create;
begin
UseAppFolder;
SetIniFileName('');
end;
procedure TFormSettingsManager.UseAppFolder;
begin
if (Application <> nil) then
FIniFilePath
:= IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName));
end;
procedure TFormSettingsManager.UseRoamingFolder(const AFolder: String);
var
SubFolder: String;
AppData: String;
begin
SubFolder := AFolder;
if (SubFolder = '') and (Application <> nil) then
SubFolder := ExtractFileName(ChangeFileExt(Application.ExeName, ''));
AppData := GetEnvironmentVariable('appdata');
FIniFilePath := IncludeTrailingPathDelimiter(
IncludeTrailingPathDelimiter(AppData) + SubFolder);
end;
procedure TFormSettingsManager.UseCustomFolder(const AIniFilePath: String);
begin
FIniFilePath := IncludeTrailingPathDelimiter(AIniFilePath);
end;
procedure TFormSettingsManager.SetIniFileName(const AIniFileName: String);
begin
FIniFileName := AIniFileName;
// Set same name as app
if (AIniFileName = '') and (Application <> nil) then
FIniFileName := ExtractFileName(ChangeFileExt(Application.ExeName, '.ini'));
end;
{ TFormSettings }
function TFormSettings.GetIniFileName: String;
begin
Result := FormSettingsManager.IniFilePath + FormSettingsManager.IniFileName;
end;
constructor TFormSettings.Create(AForm: TForm);
begin
inherited Create;
FForm := AForm;
end;
procedure TFormSettings.Load;
begin
end;
procedure TFormSettings.Save;
begin
end;
initialization
FormSettingsManager := TFormSettingsManager.Create;
finalization;
if (FormSettingsManager <> nil) then
FreeAndNil(FormSettingsManager);
end.
|
unit v.main;
interface
uses
mvw.vForm,
Spring.Collections,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, RzPanel, RzSplit;
type
TvMain = class(TvForm)
Splitter: TRzSplitter;
Panel1: TPanel;
Panel2: TPanel;
ButtonRplc: TButton;
MemoRplc: TMemo;
Label2: TLabel;
ButtonSaveFile: TButton;
ButtonRplcAllSave: TButton;
RzSplitter1: TRzSplitter;
ListBoxFiles: TListBox;
Panel4: TPanel;
LabelFile: TLabel;
MemoFile: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ListBoxFilesClick(Sender: TObject);
procedure ButtonRplcClick(Sender: TObject);
procedure ButtonSaveFileClick(Sender: TObject);
procedure ButtonRplcAllSaveClick(Sender: TObject);private
private
FFiles: TStringList;
FRplcDic: IDictionary<String, String>;
FBakDir: String;
procedure BuildRplcDic;
procedure CreateBakDirectory;
procedure CreasteRplcFile;
function BackupFile(const AFileName: String): Boolean;
protected
procedure DoDropFile(const ACnt: Integer; const AFiles: TStringList); override;
public
end;
var
vMain: TvMain;
implementation
{$R *.dfm}
uses
svc.option,
mFontHelper, System.IOUtils, mListBoxHelper, System.Generics.Collections, mDateTimeHelper, mIOUtils, System.UITypes,
System.DateUtils
;
procedure TvMain.ButtonRplcAllSaveClick(Sender: TObject);
var
LFile: String;
LBuf: TStringList;
begin
ButtonRplcAllSave.Enabled := False;
LBuf := TStringList.Create;
try
BuildRplcDic;
CreateBakDirectory;
CreasteRplcFile;
for LFile in FFiles do
if TFile.Exists(LFile) then
begin
LBuf.LoadFromFile(LFile);
FRplcDic.ForEach(
procedure(const AItem: TPair<String, String>)
begin
LBuf.Text := LBuf.Text.Replace(AItem.Key, AItem.Value, [rfReplaceAll])
end);
if not BackupFile(LFile) then
Break;
LBuf.SaveToFile(LFile);
end;
MessageDlg('작업이 완료되었습니다.', mtInformation, [mbOK], 0);
finally
FreeAndNil(LBuf);
ButtonRplcAllSave.Enabled := True;
end;
end;
procedure TvMain.ButtonRplcClick(Sender: TObject);
var
LRplc: String;
begin
BuildRplcDic;
MemoFile.Lines.BeginUpdate;
LRplc := MemoFile.Lines.Text;
FRplcDic.ForEach(
procedure(const AItem: TPair<String, String>)
begin
LRplc := LRplc.Replace(AItem.Key, AItem.Value, [rfReplaceAll])
end);
MemoFile.Lines.Text := LRplc;
MemoFile.Lines.EndUpdate;
end;
procedure TvMain.ButtonSaveFileClick(Sender: TObject);
begin
if not ListBoxFiles.ItemSelected then
Exit;
CreateBakDirectory;
CreasteRplcFile;
BackupFile(FFiles[ListBoxFiles.ItemIndex]);
MessageDlg('작업이 완료되었습니다.', mtWarning, [mbOK], 0);
end;
procedure TvMain.DoDropFile(const ACnt: Integer; const AFiles: TStringList);
var
i: Integer;
begin
FFiles.Assign(AFiles);
ListBoxFiles.Items.BeginUpdate;
try
ListBoxFiles.Clear;
for i := 0 to AFiles.Count -1 do
ListBoxFiles.Items.Add(TPath.GetFileName(AFiles[i]));
finally
ListBoxFiles.Items.EndUpdate;
end;
end;
procedure TvMain.CreasteRplcFile;
begin
svcOption.LastRplcTxt := TPath.Combine(FBakDir, Now.ToString('YYYYMMDD HHNN') + '.txt');
MemoRplc.Lines.SaveToFile(svcOption.LastRplcTxt);
end;
function TvMain.BackupFile(const AFileName: String): Boolean;
var
LBak: String;
begin
Result := True;
if TFile.Exists(AFileName) then
begin
try
LBak := TPath.Combine(FBakDir, TPath.GetFileName(AFileName));
TFile.Move(AFileName, LBak);
except on E: Exception do
if (MessageDlg('백업간 다음 오류가 발생하였습니다.'#13#10+E.Message+#13#10#13#10'중단 하시겠습니까 ?', mtError, [mbYes, mbNo], 0) = mrYes) then
Exit(False)
end;
end;
end;
procedure TvMain.CreateBakDirectory;
begin
FBakDir := TPath.Combine(TDirectory.GetCurrentDirectory, 'gstrRplc '+Now.ToString('YYYYMMDD HHNN'));
if not TDirectory.Exists(FBakDir) then
TDirectory.CreateDirectory(FBakDir);
end;
procedure TvMain.BuildRplcDic;
var
LLine: string;
LBuf: TArray<String>;
begin
FRplcDic.Clear;
for LLine in MemoRplc.Lines do
begin
LBuf := LLine.Split([',']);
if Length(LBuf) = 2 then
FRplcDic.AddOrSetValue(LBuf[0], LBuf[1]);
end;
end;
procedure TvMain.FormCreate(Sender: TObject);
var
LLasRplcFile: String;
begin
FFiles := TStringList.Create;
FRplcDic := TCollections.CreateDictionary<String, String>;
EnableDropdownFiles := True;
TFixedWidthFont.AssingToCtrls([MemoFile, MemoRplc, ListBoxFiles, LabelFile]);
LLasRplcFile := svcOption.LastRplcTxt;
if not LLasRplcFile.IsEmpty and TFile.Exists(LLasRplcFile) then
MemoRplc.Lines.LoadFromFile(LLasRplcFile);
end;
procedure TvMain.FormDestroy(Sender: TObject);
begin
FreeAndNil(FFiles);
end;
procedure TvMain.ListBoxFilesClick(Sender: TObject);
var
LBox: TListBox absolute Sender;
begin
if not LBox.ItemSelected then
Exit;
if TFile.Exists(FFiles[LBox.ItemIndex]) then
begin
LabelFile.Caption := FFiles[LBox.ItemIndex];
MemoFile.Lines.LoadFromFile(FFiles[LBox.ItemIndex]);
end;
end;
end.
|
unit account_impl;
{This file was generated on 13 Jun 2000 21:12:13 GMT by version 03.03.03.C1.04}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file account.idl. }
{Delphi Pascal unit : account_impl }
{derived from IDL module : default }
interface
uses
SysUtils,
CORBA,
account_i,
account_c;
type
TAccount = class;
TAccount = class(TInterfacedObject, account_i.Account)
protected
_balance : Single;
public
constructor Create;
function balance ( const mySeq : account_i.IntSeq): Single;
end;
implementation
uses ServerMain;
constructor TAccount.Create;
begin
inherited;
_balance := Random * 1000;
end;
function TAccount.balance ( const mySeq : account_i.IntSeq): Single;
var k : integer;
begin
Result := _balance;
//display the sequence that comes over the wire
for k := 0 to High(mySeq) do
Form1.Memo1.Lines.Add('mySeq[' + IntToStr(k) + '] = ' + IntToStr(mySeq[k]));
end;
initialization
Randomize;
end.
|
////////////////////////////////////////////
// Формирование запросов к приборам
// Поток опроса приборов по RS485 через Геомер
////////////////////////////////////////////
unit GM485;
interface
uses Windows, Classes, SysUtils, GMGlobals, Math, StrUtils, ADODB, DB, ActiveX,
Forms, GMConst, GMSqlQuery, Generics.Collections, Threads.Base,
Devices.ReqCreatorBase;
type
TPrepareRequestBufferInfo = record
ReqID: int;
end;
TSpecDevReqListItem = class
private
procedure PrepareTeconBuffer(ExtInfo: TPrepareRequestBufferInfo);
procedure PrepareModbusTCPBuffer(ExtInfo: TPrepareRequestBufferInfo);
public
ReqDetails: TRequestDetails;
Processed: bool;
constructor Create();
procedure PrepareBuffer(ExtInfo: TPrepareRequestBufferInfo);
end;
T485RequestCreator = class
private
FAddRequestToSendBuf: TGMAddRequestToSendBufProc;
function CreateReqCreator(ID_DevType: int): TDevReqCreator;
protected
function GetDevReqCreatorClass(ID_DevType: int): TDevReqCreatorClass; virtual;
public
ReqDetails: TRequestDetails;
procedure AddDeviceToSendBuf();
function SetChannelValue(prmIds: TChannelIds; Val: double; timeHold: int): bool;
constructor Create(AAddRequestToSendBuf: TGMAddRequestToSendBufProc);
end;
T485RequestListCreator = class(T485RequestCreator)
private
reqList: TList<TRequestDetails>;
procedure AddRequest(ReqDetails: TRequestDetails);
public
constructor Create();
end;
implementation
uses Devices.UBZ, Devices.Owen, Devices.Vzlet, Devices.Vacon, Devices.Tecon.Common, Devices.Tecon,
DateUtils, ProgramLogFile, ArchIntervalBuilder, Devices.Termotronic, Devices.Mercury,
Devices.TR101, Devices.ICP, Devices.Isco4250, Devices.Simag, Devices.Altistart22, Devices.Geostream,
Devices.AllenBradley.Micro8xx, Devices.MainSrv, Devices.Logica.SPT941, Devices.Logica.SPT943,
Devices.Logica.SPT961, Devices.Modbus.ReqCreatorBase, Devices.ModbusBase, Devices.DRK, Devices.ADCPChannelMaster, Devices.Geomer,
Devices.Streamlux700f;
constructor T485RequestCreator.Create(AAddRequestToSendBuf: TGMAddRequestToSendBufProc);
begin
inherited Create();
FAddRequestToSendBuf := AAddRequestToSendBuf;
ReqDetails.Init();
end;
function T485RequestCreator.GetDevReqCreatorClass(ID_DevType: int): TDevReqCreatorClass;
begin
Result := nil;
if ID_DevType in Tecon19_Family then
Result := TTecon19ReqCreator
else
if ID_DevType in GeomerFamily then
Result := TGeomerDevReqCreator
else
case ID_DevType of
DEVTYPE_I7041D: Result := TICP7041DReqCreator;
DEVTYPE_I7017: Result := TICP7017ReqCreator;
DEVTYPE_UBZ: Result := TUBZReqCreator;
DEVTYPE_TR101: Result := TTR101ReqCreator;
DEVTYPE_TRM138: Result := TOwenTRM138ReqCreator;
DEVTYPE_VZLET_URSV: Result := TVzletURSVReqCreator;
DEVTYPE_VACON_NXL: Result := TVaconNXLReqCreator;
DEVTYPE_ISCO_4250: Result := TIsco4250ReqCreator;
DEVTYPE_SPT_941: Result := TSPT941ReqCreator;
DEVTYPE_SPT_943: Result := TSPT943ReqCreator;
DEVTYPE_SPT_961: Result := TSPT961ReqCreator;
DEVTYPE_SIMAG11: Result := TSimag11ReqCreator;
DEVTYPE_PETERFLOWRS: Result := TPeterflowRSReqCreator;
DEVTYPE_MERCURY_230: Result := TMercury230ReqCreator;
DEVTYPE_ALTISTART_22: Result := TAltistart22ReqCreator;
DEVTYPE_GEOSTREAM_71: Result := TGeostreamReqCreator;
DEVTYPE_ALLEN_BRADLEY_MICRO_8XX: Result := TAllenBradleyMicro8xxReqCreator;
DEVTYPE_MAIN_SRV: Result := TMainSrvReqCreator;
DEVTYPE_MODBUS_RTU: Result := TModbusRTUDevReqCreator;
DEVTYPE_DRK: Result := TDRK4OPReqCreator;
DEVTYPE_ADCP_CHANNEL_MASTER: Result := TADCPChannelMasterReqCreator;
DEVTYPE_STREAMLUX700F: Result := TStreamlux700fReqCreator;
end;
end;
function T485RequestCreator.SetChannelValue(prmIds: TChannelIds; Val: double; timeHold: int): bool;
var
cr: TDevReqCreator;
begin
Result := false;
cr := CreateReqCreator(ReqDetails.ID_DevType);
if cr <> nil then
try
Result := cr.SetChannelValue(prmIds, Val, timeHold);
finally
cr.Free();
end;
end;
function T485RequestCreator.CreateReqCreator(ID_DevType: int): TDevReqCreator;
var devclass: TDevReqCreatorClass;
begin
Result := nil;
devclass := GetDevReqCreatorClass(ID_DevType);
if devclass <> nil then
Result := devclass.Create(FAddRequestToSendBuf, ReqDetails)
else
ProgramLog.AddError('T485RequestCreator.CreateReqCreator unknown DevType = ' + IntToStr(ID_DevType));
end;
procedure T485RequestCreator.AddDeviceToSendBuf();
var cr: TDevReqCreator;
begin
cr := CreateReqCreator(ReqDetails.ID_DevType);
if cr <> nil then
try
cr.AddRequests();
finally
cr.Free();
end;
end;
{ TSpecDevReqListItem }
constructor TSpecDevReqListItem.Create;
begin
inherited;
ReqDetails.Init();
Processed := false;
end;
procedure TSpecDevReqListItem.PrepareBuffer(ExtInfo: TPrepareRequestBufferInfo);
begin
if ReqDetails.ID_DevType in Tecon19_Family then
PrepareTeconBuffer(ExtInfo);
if (ReqDetails.ID_DevType = DEVTYPE_ALLEN_BRADLEY_MICRO_8XX)
or ((ReqDetails.ID_DevType in ModbusRTUBasedDevices) and (ReqDetails.Converter = PROTOCOL_CONVETER_MODBUS_TCP_RTU)) then
PrepareModbusTCPBuffer(ExtInfo);
end;
procedure TSpecDevReqListItem.PrepareModbusTCPBuffer(ExtInfo: TPrepareRequestBufferInfo);
begin
// ModbusTCP Transaction Identifier 2 Bytes
ReqDetails.buf[0] := ExtInfo.ReqID div 256;
ReqDetails.buf[1] := ExtInfo.ReqID mod 256;
ReqDetails.ReqID := ExtInfo.reqID;
end;
procedure TSpecDevReqListItem.PrepareTeconBuffer(ExtInfo: TPrepareRequestBufferInfo);
var dt: TDateTime;
reqID: byte;
begin
reqID := ExtInfo.ReqID and $0F;
if (ReqDetails.BufCnt = 9) and (ReqDetails.buf[0] = $10) and (ReqDetails.buf[3] = $11) then
begin // запрос параметра ТЭКОН ф-ей $11. Cтруктура известна, вставим номер пачки, пересчитаем CRC
ReqDetails.buf[1] := $40 + reqID;
ReqDetails.ReqID := reqID;
end;
if (ReqDetails.BufCnt = 15) and (ReqDetails.buf[0] = $68) and (ReqDetails.buf[6] = $19) then
begin // запрос параметра ТЭКОН ф-ей $11. Cтруктура известна, вставим номер пачки, пересчитаем CRC
ReqDetails.buf[4] := $40 + reqID;
ReqDetails.ReqID := reqID;
end;
if (ReqDetails.BufCnt >= 14) and (ReqDetails.buf[0] = $68) and (ReqDetails.buf[6] in [$05, $14]) then
begin // установка параметра ТЭКОН ф-ей $14. Cтруктура известна, вставим номер пачки, пересчитаем CRC
ReqDetails.buf[4] := $40 + reqID;
ReqDetails.ReqID := reqID;
if ReqDetails.rqtp = rqtTECON_SET_TIME then
begin // установка времени прибора
dt := Now() + (OneSecond / 2.0); // полсекунды на передачу
if ReqDetails.buf[6] = $05 then // COM
begin
ReqDetails.buf[9] := $00;
ReqDetails.buf[10] := DecToHexDigits(SecondOf(dt));
ReqDetails.buf[11] := DecToHexDigits(MinuteOf(dt));
ReqDetails.buf[12] := DecToHexDigits(HourOf(dt));
end;
if ReqDetails.buf[6] = $14 then // K-104, K-105
begin
ReqDetails.buf[12] := $00;
ReqDetails.buf[13] := DecToHexDigits(SecondOf(dt));
ReqDetails.buf[14] := DecToHexDigits(MinuteOf(dt));
ReqDetails.buf[15] := DecToHexDigits(HourOf(dt));
end;
end;
end;
Tecon_CRC(ReqDetails.buf, ReqDetails.BufCnt - 2);
end;
{ T485RequestListCreator }
procedure T485RequestListCreator.AddRequest(ReqDetails: TRequestDetails);
begin
reqList.Add(ReqDetails);
end;
constructor T485RequestListCreator.Create;
begin
inherited Create(AddRequest);
reqList := TList<TRequestDetails>.Create();
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit BluetoothReg;
interface
procedure Register;
implementation
uses
DesignIntf, DesignEditors, DsnConst, System.Classes, System.Bluetooth.Components;
type
TBluetoothSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
procedure Register;
begin
RegisterComponents(srSystem, [TBluetoothLE]);
RegisterSelectionEditor(TBluetoothLE, TBluetoothSelectionEditor);
RegisterComponents(srSystem, [TBluetooth]);
RegisterSelectionEditor(TBluetooth, TBluetoothSelectionEditor);
end;
{ TBluetoothSelectionEditor }
procedure TBluetoothSelectionEditor.RequiresUnits(Proc: TGetStrProc);
begin
inherited;
Proc('System.Bluetooth');
end;
end.
|
unit glslang.ResourceLimits;
interface //#################################################################### ■
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//Copyright (C) 2013 LunarG, Inc.
//
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
uses LUX.Code.C;
type TLimits = record
nonInductiveForLoops :T_bool;
whileLoops :T_bool;
doWhileLoops :T_bool;
generalUniformIndexing :T_bool;
generalAttributeMatrixVectorIndexing :T_bool;
generalVaryingIndexing :T_bool;
generalSamplerIndexing :T_bool;
generalVariableIndexing :T_bool;
generalConstantMatrixVectorIndexing :T_bool;
end;
type PBuiltInResource = ^TBuiltInResource;
TBuiltInResource = record
maxLights :T_int;
maxClipPlanes :T_int;
maxTextureUnits :T_int;
maxTextureCoords :T_int;
maxVertexAttribs :T_int;
maxVertexUniformComponents :T_int;
maxVaryingFloats :T_int;
maxVertexTextureImageUnits :T_int;
maxCombinedTextureImageUnits :T_int;
maxTextureImageUnits :T_int;
maxFragmentUniformComponents :T_int;
maxDrawBuffers :T_int;
maxVertexUniformVectors :T_int;
maxVaryingVectors :T_int;
maxFragmentUniformVectors :T_int;
maxVertexOutputVectors :T_int;
maxFragmentInputVectors :T_int;
minProgramTexelOffset :T_int;
maxProgramTexelOffset :T_int;
maxClipDistances :T_int;
maxComputeWorkGroupCountX :T_int;
maxComputeWorkGroupCountY :T_int;
maxComputeWorkGroupCountZ :T_int;
maxComputeWorkGroupSizeX :T_int;
maxComputeWorkGroupSizeY :T_int;
maxComputeWorkGroupSizeZ :T_int;
maxComputeUniformComponents :T_int;
maxComputeTextureImageUnits :T_int;
maxComputeImageUniforms :T_int;
maxComputeAtomicCounters :T_int;
maxComputeAtomicCounterBuffers :T_int;
maxVaryingComponents :T_int;
maxVertexOutputComponents :T_int;
maxGeometryInputComponents :T_int;
maxGeometryOutputComponents :T_int;
maxFragmentInputComponents :T_int;
maxImageUnits :T_int;
maxCombinedImageUnitsAndFragmentOutputs :T_int;
maxCombinedShaderOutputResources :T_int;
maxImageSamples :T_int;
maxVertexImageUniforms :T_int;
maxTessControlImageUniforms :T_int;
maxTessEvaluationImageUniforms :T_int;
maxGeometryImageUniforms :T_int;
maxFragmentImageUniforms :T_int;
maxCombinedImageUniforms :T_int;
maxGeometryTextureImageUnits :T_int;
maxGeometryOutputVertices :T_int;
maxGeometryTotalOutputComponents :T_int;
maxGeometryUniformComponents :T_int;
maxGeometryVaryingComponents :T_int;
maxTessControlInputComponents :T_int;
maxTessControlOutputComponents :T_int;
maxTessControlTextureImageUnits :T_int;
maxTessControlUniformComponents :T_int;
maxTessControlTotalOutputComponents :T_int;
maxTessEvaluationInputComponents :T_int;
maxTessEvaluationOutputComponents :T_int;
maxTessEvaluationTextureImageUnits :T_int;
maxTessEvaluationUniformComponents :T_int;
maxTessPatchComponents :T_int;
maxPatchVertices :T_int;
maxTessGenLevel :T_int;
maxViewports :T_int;
maxVertexAtomicCounters :T_int;
maxTessControlAtomicCounters :T_int;
maxTessEvaluationAtomicCounters :T_int;
maxGeometryAtomicCounters :T_int;
maxFragmentAtomicCounters :T_int;
maxCombinedAtomicCounters :T_int;
maxAtomicCounterBindings :T_int;
maxVertexAtomicCounterBuffers :T_int;
maxTessControlAtomicCounterBuffers :T_int;
maxTessEvaluationAtomicCounterBuffers :T_int;
maxGeometryAtomicCounterBuffers :T_int;
maxFragmentAtomicCounterBuffers :T_int;
maxCombinedAtomicCounterBuffers :T_int;
maxAtomicCounterBufferSize :T_int;
maxTransformFeedbackBuffers :T_int;
maxTransformFeedbackInterleavedComponents :T_int;
maxCullDistances :T_int;
maxCombinedClipAndCullDistances :T_int;
maxSamples :T_int;
limits :TLimits;
end;
implementation //############################################################### ■
end. //######################################################################### ■
|
unit ADemosntrativoFaturamento;
{ Autor: Rafael Budag
Data Criação: 19/05/1999;
Função: Consultar as notas fiscais.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
StdCtrls, Componentes1, ExtCtrls, PainelGradiente, Localizacao, Buttons,
Db, DBTables, ComCtrls, Grids, DBGrids, printers, Mask,
numericos, Tabela, DBCtrls, DBKeyViolation, Geradores, DBClient;
type
TFDemonstrativoFaturamento = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
Localiza: TConsultaPadrao;
DATANOTAS: TDataSource;
BitBtn3: TBitBtn;
PageControl1: TPageControl;
PanelColor3: TPanelColor;
Label8: TLabel;
Label10: TLabel;
Label7: TLabel;
SpeedButton4: TSpeedButton;
Label11: TLabel;
Data1: TCalendario;
data2: TCalendario;
EClientes: TEditLocaliza;
NotaGrid: TGridIndice;
RDemonstrativo: TRadioGroup;
ETotalNotas: Tnumerico;
ETotalServico: Tnumerico;
EICMS: Tnumerico;
EISQN: Tnumerico;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
CEmpresaFilial: TComboBoxColor;
Label5: TLabel;
NOTAS: TSQL;
NOTASEMISSAO: TWideStringField;
NOTASNOTAS: TFMTBCDField;
NOTASICMS: TFMTBCDField;
NOTASSERVICO: TFMTBCDField;
NOTASISQN: TFMTBCDField;
AUX: TSQL;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EClientesSelect(Sender: TObject);
procedure ENotasRetorno(Retorno1, Retorno2: String);
procedure Data1Exit(Sender: TObject);
procedure BitBtn3Click(Sender: TObject);
procedure BitBtn4Click(Sender: TObject);
private
procedure PosicionaNota;
public
{ Public declarations }
end;
var
FDemonstrativoFaturamento: TFDemonstrativoFaturamento;
implementation
uses APrincipal, constantes, fundata, constMsg,
funstring, funNumeros, FunSql;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFDemonstrativoFaturamento.FormCreate(Sender: TObject);
begin
CEmpresaFilial.ItemIndex := 0;
Data1.DateTime := PrimeiroDiaMes(date);
Data2.DateTime := UltimoDiaMes(Date);
PosicionaNota;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFDemonstrativoFaturamento.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FechaTabela(Notas);
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações dos Localizas da nota de Saida
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
procedure TFDemonstrativoFaturamento.PosicionaNota;
begin
LimpaSQLTabela(Notas);
case RDemonstrativo.ItemIndex of
0 : NotaGrid.Columns[0].Title.Caption := 'Ano';
1 : NotaGrid.Columns[0].Title.Caption := 'Mês';
2 : NotaGrid.Columns[0].Title.Caption := 'Data de Emissão';
end;
InseriLinhaSQL(Notas, 0, ' select ');
InseriLinhaSQL(Notas, 1, ' ');
InseriLinhaSQL(Notas, 2,
' SUM(COALESCE(N_TOT_NOT, 0)) NOTAS, ' +
' SUM(COALESCE(N_VLR_ICM, 0)) ICMS, ' +
' SUM(COALESCE(N_TOT_SER, 0)) SERVICO, ' +
' SUM(COALESCE(N_VLR_ISQ, 0)) ISQN from ' +
' CadNotaFiscais NF ' +
' WHERE C_NOT_CAN = ''N''');
InseriLinhaSQL(Notas, 3, SQLTextoDataEntreAAAAMMDD( ' and D_DAT_EMI ', Data1.Date, Data2.Date, False) );
if CEmpresaFilial.ItemIndex = 0 then
InseriLinhaSQL(Notas, 4, ' and NF.I_EMP_FIL = ' + IntToStr(varia.CodigoEmpFil) )
else
InseriLinhaSQL(Notas, 4, ' and left(NF.I_EMP_FIL,1) = ' + IntToStr(varia.CodigoEmpresa) );
if (EClientes.Text <> '') then
InseriLinhaSQL(Notas, 5, ' and I_COD_CLI = ' + EClientes.Text)
else
InseriLinhaSQL(Notas, 5, '');
AUX.SQL.Clear;
AUX.SQL := Notas.SQL;
AbreTabela(AUX);
// Soma Valores;
ETotalNotas.AValor := AUX.FieldByName('NOTAS').AsFloat;
ETotalServico.AValor := AUX.FieldByName('SERVICO').AsFloat;
EICMS.AValor := AUX.FieldByName('ICMS').AsFloat;
EISQN.AValor := AUX.FieldByName('ISQN').AsFloat;
DeletaLinhaSQL(Notas, 1);
case RDemonstrativo.ItemIndex of
0 : InseriLinhaSQL(Notas, 1, ' CAST(EXTRACT(YEAR FROM D_DAT_EMI) AS CHAR(10)) EMISSAO, ');
1 : InseriLinhaSQL(Notas, 1, ' CAST(EXTRACT(MONTH FROM D_DAT_EMI) AS CHAR(10)) EMISSAO, ');
2 : InseriLinhaSQL(Notas, 1, ' CAST(D_DAT_EMI AS CHAR(10)) EMISSAO, ');
end;
case RDemonstrativo.ItemIndex of
0 : InseriLinhaSQL(Notas, 6, ' GROUP BY CAST(EXTRACT(YEAR FROM D_DAT_EMI) AS CHAR(10)) ');
1 : InseriLinhaSQL(Notas, 6, ' GROUP BY CAST(EXTRACT(YEAR FROM D_DAT_EMI) AS CHAR(10)) ');
2 : InseriLinhaSQL(Notas, 6, ' GROUP BY D_DAT_EMI ORDER BY D_DAT_EMI ');
end;
AbreTabela(Notas);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações das Notas de Entrada
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{************************Procura pelo Cliente**********************************}
procedure TFDemonstrativoFaturamento.EClientesSelect(Sender: TObject);
begin
EClientes.ASelectValida.Clear;
EClientes.ASelectValida.Add(' select * from CadClientes Cli ' +
' where c_ind_cli = ''S'''+
' and CLI.C_NOM_CLI = ''@'' ' );
EClientes.ASelectLocaliza.Clear;
EClientes.ASelectLocaliza.Add(' select * from CadClientes Cli ' +
' where c_ind_cli = ''S'''+
' and CLI.C_NOM_CLI like ''@%'' order by c_nom_cli' );
end;
procedure TFDemonstrativoFaturamento.ENotasRetorno(Retorno1, Retorno2: String);
begin
PosicionaNota;
end;
procedure TFDemonstrativoFaturamento.Data1Exit(Sender: TObject);
begin
PosicionaNota;
end;
procedure TFDemonstrativoFaturamento.BitBtn3Click(Sender: TObject);
begin
Close;
end;
procedure TFDemonstrativoFaturamento.BitBtn4Click(Sender: TObject);
begin
// CARREGA A NOTA FISCAL.
end;
Initialization
RegisterClasses([TFDemonstrativoFaturamento]);
end.
|
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
}
unit SMCalendar;
interface
{$I SMVersion.inc}
uses Windows, Messages, Classes, Graphics, Grids, Calendar;
type
TGetCellParams = procedure(Sender: TObject; ACol, ARow: Longint; AFont: TFont; var Background: TColor) of object;
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TSMCalendar = class(TCalendar)
private
{ FCaption: string;
FCaptionHeight: Integer;
}
FOnDrawCell: TDrawCellEvent;
FGetCellParams: TGetCellParams;
{ procedure SetCaption(Value: string);
procedure SetCaptionHeight(Value: Integer);
} protected
{ constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CreateWnd; override;
procedure Paint; override;
function GetClientRect: TRect; override;
procedure SetEditRect;
}
procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override;
published
{ property Caption: string read FCaption write SetCaption;
property CaptionHeight: Integer read FCaptionHeight write SetCaptionHeight default 21;
}
property Options;
property OnDrawCell: TDrawCellEvent read FOnDrawCell write FOnDrawCell;
property OnGetCellParams: TGetCellParams read FGetCellParams write FGetCellParams;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('SMComponents', [TSMCalendar]);
end;
{ TSMCalendar }
{constructor TSMCalendar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCaptionHeight := 21;
end;
destructor TSMCalendar.Destroy;
begin
inherited Destroy;
end;
procedure TSMCalendar.CreateWnd;
begin
inherited CreateWnd;
SetEditRect;
end;
procedure TSMCalendar.SetEditRect;
var
Loc: TRect;
begin
SetRect(Loc, 0, FCaptionHeight, ClientWidth, ClientHeight-FCaptionHeight);
SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@Loc));
end;
procedure TSMCalendar.SetCaption(Value: string);
begin
if (Value <> FCaption) then
begin
FCaption := Value;
Invalidate
end;
end;
procedure TSMCalendar.SetCaptionHeight(Value: Integer);
begin
if (Value <> FCaptionHeight) then
begin
FCaptionHeight := Value;
Invalidate
end;
end;
}
procedure TSMCalendar.DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState);
var
TheText: string;
AColor: TColor;
AFont: TFont;
begin
TheText := CellText[ACol, ARow];
with ARect, Canvas do
begin
AFont := TFont.Create;
{save a current font of canvas}
AFont.Assign(Font);
if (gdSelected in AState) then
begin
Brush.Color := Color;
Font.Assign(Self.Font);
end;
if Assigned(FGetCellParams) then
begin
AColor := Brush.Color;
FGetCellParams(Self, ACol, ARow, Font, AColor);
Brush.Color := AColor;
end;
TextRect(ARect, Left + (Right - Left - TextWidth(TheText)) div 2,
Top + (Bottom - Top - TextHeight(TheText)) div 2, TheText);
{restore a saved font of canvas}
Font.Assign(AFont);
AFont.Free;
end;
// inherited;
if Assigned(FOnDrawCell) then
FOnDrawCell(Self, ACol, ARow, ARect, AState);
end;
{
function TSMCalendar.GetClientRect: TRect;
begin
Result := inherited GetClientRect;
Result.Top := Result.Top + CaptionHeight
end;
procedure TSMCalendar.Paint;
var
ARect: TRect;
begin
inherited Paint;
if (Caption = '') or
(CaptionHeight = 0) then exit;
ARect := Bounds(0, 0, Width, CaptionHeight);
DrawText(Canvas.Handle, PChar(Caption), -1, ARect,
DT_CENTER or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX or DT_VCENTER)
end;
}
end.
|
unit AMotivoInadimplencia;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, Grids, DBGrids, Tabela,
DBKeyViolation, StdCtrls, Localizacao, Mask, DBCtrls, Db, DBTables,
CBancoDados, BotaoCadastro, Buttons, DBClient,unSistema;
type
TFMotivoInadimplencia = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
MotivoInadimplecia: TRBSQL;
MotivoInadimpleciaCODMOTIVO: TFMTBCDField;
MotivoInadimpleciaNOMMOTIVO: TWideStringField;
Label1: TLabel;
DataMotivoInadimplecia: TDataSource;
Label2: TLabel;
ECodigo: TDBKeyViolation;
DBEditColor1: TDBEditColor;
Bevel1: TBevel;
Label3: TLabel;
ELocaliza: TLocalizaEdit;
GridIndice1: TGridIndice;
BotaoCadastrar1: TBotaoCadastrar;
BotaoAlterar1: TBotaoAlterar;
BotaoExcluir1: TBotaoExcluir;
BotaoGravar1: TBotaoGravar;
BotaoCancelar1: TBotaoCancelar;
BFechar: TBitBtn;
MoveBasico1: TMoveBasico;
MotivoInadimpleciaDATULTIMAALTERACAO: TSQLTimeStampField;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure GridIndice1Ordem(Ordem: String);
procedure BFecharClick(Sender: TObject);
procedure MotivoInadimpleciaAfterInsert(DataSet: TDataSet);
procedure MotivoInadimpleciaAfterEdit(DataSet: TDataSet);
procedure MotivoInadimpleciaBeforePost(DataSet: TDataSet);
procedure MotivoInadimpleciaAfterPost(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FMotivoInadimplencia: TFMotivoInadimplencia;
implementation
uses APrincipal;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFMotivoInadimplencia.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
ELocaliza.AtualizaConsulta;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFMotivoInadimplencia.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFMotivoInadimplencia.GridIndice1Ordem(Ordem: String);
begin
ELocaliza.AOrdem := ordem;
end;
procedure TFMotivoInadimplencia.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFMotivoInadimplencia.MotivoInadimpleciaAfterInsert(
DataSet: TDataSet);
begin
ECodigo.ProximoCodigo;
ECodigo.ReadOnly := false;
end;
{******************************************************************************}
procedure TFMotivoInadimplencia.MotivoInadimpleciaAfterEdit(
DataSet: TDataSet);
begin
ECodigo.ReadOnly := true;
end;
{******************************************************************************}
procedure TFMotivoInadimplencia.MotivoInadimpleciaBeforePost(
DataSet: TDataSet);
begin
if MotivoInadimplecia.State = dsinsert then
ECodigo.VerificaCodigoUtilizado;
MotivoInadimpleciaDATULTIMAALTERACAO.AsDateTime := Sistema.RDataServidor;
Sistema.MarcaTabelaParaImportar('MOTIVOINADIMPLENCIA');
end;
{******************************************************************************}
procedure TFMotivoInadimplencia.MotivoInadimpleciaAfterPost(
DataSet: TDataSet);
begin
ELocaliza.AtualizaConsulta;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFMotivoInadimplencia]);
end.
|
unit ExtendedAdapterObj;
interface
uses Classes, Sample_TLB, SiteComp, HTTPProd, WebAdapt, DBAdapt, AutoAdap;
type
IGetSampleValue = interface
['{88139B17-B93F-4CF2-9C5D-23A4B39C0F77}']
function GetSampleValue: string;
end;
TExtendedAdapter = class(TAdapter, IGetSampleValue)
private
FSampleValue: string;
protected
{ IGetSampleValue }
function GetSampleValue: string;
{ IGetScriptObject }
function ImplGetScriptObject: IDispatch; override;
published
property SampleValue: string read FSampleValue write FSampleValue;
end;
TExtendedDataSetAdapter = class(TDataSetAdapter, IGetSampleValue)
private
FSampleValue: string;
protected
{ IGetSampleValue }
function GetSampleValue: string;
{ IGetScriptObject }
function ImplGetScriptObject: IDispatch; override;
published
property SampleValue: string read FSampleValue write FSampleValue;
end;
TExtendedAdapterWrapper = class(TAdapterWrapper, IExtendedAdapterWrapper)
protected
{ IExtendedAdapterWrapper }
function Get_SampleValue: WideString; safecall;
end;
implementation
uses WebAuto, ActiveX, SysUtils, SimpleScriptObj;
{ TExtendedAdapter }
function TExtendedAdapter.GetSampleValue: string;
begin
Result := FSampleValue;
end;
function TExtendedAdapter.ImplGetScriptObject: IDispatch;
begin
Result := TExtendedAdapterWrapper.Create(Self);
end;
{ TExtendedDataSetAdapter }
function TExtendedDataSetAdapter.GetSampleValue: string;
begin
Result := FSampleValue;
end;
function TExtendedDataSetAdapter.ImplGetScriptObject: IDispatch;
begin
Result := TExtendedAdapterWrapper.Create(Self);
end;
{ TExtendedAdapterWrapper }
function TExtendedAdapterWrapper.Get_SampleValue: WideString;
var
Intf: IGetSampleValue;
begin
if Supports(Obj, IGetSampleValue, Intf) then
Result := Intf.GetSampleValue
else
Result := '';
end;
initialization
SampleComServer.RegisterScriptClass(TExtendedAdapterWrapper, Class_ExtendedAdapterWrapper);
end.
|
unit uJSONUtil;
interface
uses REST.Json, System.JSON, System.SysUtils;
const cJsonOptions : TJsonOptions = [joIgnoreEmptyStrings, joIgnoreEmptyArrays, joDateFormatISO8601];
type TJSONUtil = class
public
class function objectToJsonObject(AObject: TObject): TJSONObject;
class function objectToJsonString(AObject: TObject): String;
class procedure jsonObjectToObject(var AObject: TObject; AJsonObject: TJSONObject);
end;
implementation
{ TJSONUtil }
class procedure TJSONUtil.jsonObjectToObject(var AObject: TObject; AJsonObject: TJSONObject);
var
strJson: string;
begin
strJson := AJsonObject.ToJSON;
//AJsonObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes( strJson), 0) as TJSONObject;
TJson.JsonToObject(AObject, AJsonObject, cJsonOptions);
AJsonObject := objectToJsonObject(AObject);
TJson.JsonToObject(AObject, AJsonObject, cJsonOptions);
end;
class function TJSONUtil.objectToJsonObject(AObject: TObject): TJSONObject;
begin
Result := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(
// Converto primeiro o Objeto pra JsonString pra depois usar o Parse com UTF-8
TJson.ObjectToJsonString(AObject, cJsonOptions)
), 0) as TJSONObject;
end;
class function TJSONUtil.objectToJsonString(AObject: TObject): String;
begin
result := objectToJsonObject(AObject).ToString;
end;
end.
|
unit HKModel;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpjson, LResources, Forms, Controls, Graphics, Dialogs,
HKConnection, HKStringGrid, Requester;
type
TOnFilteringData=procedure(Sender:TObject; aRow:TJSONObject; Query:String;
var aResult:Boolean)of object;
{ THKModel }
THKModel = class(TComponent)
private
FConnection: THKConnection;
FDocument: String;
FHKStringGrid: THKStringGrid;
FData:TJSONArray;
FonFilterData: TOnFilteringData;
fFilter:String;
procedure SetConnection(AValue: THKConnection);
procedure SetHKStringGrid(AValue: THKStringGrid);
procedure SetonFilterData(AValue: TOnFilteringData);
protected
function GetDocument: String;virtual;
procedure SetDocument(AValue: String);virtual;
procedure ProcessGrid;
function DoResponseData(aResp:TJSONData):TJSONData;virtual;
//procedure ProcessResponse;virtual;
function doFilterData(aRow: TJSONObject): Boolean;
public
procedure Refresh;
function CreateNew(aData: TJSONObject; withNotif: Boolean=True): Boolean;
function UpdateData(aData: TJSONObject; aId: String; withNotif: Boolean=True
): Boolean;
procedure Filter(aStr:String);
procedure ClearFilter;
destructor Destroy; override;
published
property Connection:THKConnection read FConnection write SetConnection;
property Document:String read GetDocument write SetDocument;
property HKStringGrid:THKStringGrid read FHKStringGrid write SetHKStringGrid;
property onFilterData:TOnFilteringData read FonFilterData write SetonFilterData;
end;
procedure Register;
implementation
uses HKCompPacksTypes, DateUtils;
procedure Register;
begin
{$I hkmodel_icon.lrs}
RegisterComponents('HKCompPacks',[THKModel]);
end;
{ THKModel }
procedure THKModel.SetConnection(AValue: THKConnection);
begin
if FConnection=AValue then Exit;
FConnection:=AValue;
end;
function THKModel.GetDocument: String;
begin
Result:=FDocument;
end;
procedure THKModel.SetDocument(AValue: String);
begin
if FDocument=AValue then Exit;
FDocument:=AValue;
end;
procedure THKModel.SetHKStringGrid(AValue: THKStringGrid);
begin
if FHKStringGrid=AValue then Exit;
FHKStringGrid:=AValue;
end;
procedure THKModel.SetonFilterData(AValue: TOnFilteringData);
begin
if FonFilterData=AValue then Exit;
FonFilterData:=AValue;
end;
procedure THKModel.ProcessGrid;
var
aaa, bbb, newCount: Integer;
vCol: THKGridColumn;
//row: TStrings;
aJson: TJSONObject;
str: String;
begin
HKStringGrid.RowCount:=1;
for aaa:=0 to FData.Count-1 do
begin
aJson:=FData.Objects[aaa];
if not doFilterData(aJson)then Continue;
newCount:=HKStringGrid.RowCount;
HKStringGrid.RowCount:=newCount+1;
//row:=HKStringGrid.Rows[newCount-1];
//row.Add((aaa+1).ToString);
HKStringGrid.Cells[0, newCount]:=(aaa+1).ToString;
for bbb:=0 to HKStringGrid.HKGridColumns.Count-1 do
begin
vCol:=HKStringGrid.HKGridColumns.Items[bbb] as THKGridColumn;
case vCol.ColumnType of
CTTxt:str:=GetJsonStringValue(aJson, vCol.FieldName);
CTNumber:str:=FormatFloat('#,##0', GetJsonNumberValue(aJson, vCol.FieldName));
CTBtnEdit:str:='Edit';
CTBtnDelete:str:='Remove';
CTButton:str:='Action';
CTDateTimeISO:
begin
str:=GetJsonStringValue(aJson, vCol.FieldName);
str:=FormatDateTime('DD-MMM-YYYY HH:mm',ISO8601ToDate(str, False));
end;
end;
//row.Add(str);
HKStringGrid.Cells[bbb+1, newCount]:=str;
end;
end;
end;
function THKModel.DoResponseData(aResp: TJSONData): TJSONData;
begin
Result:=aResp;
end;
function THKModel.doFilterData(aRow: TJSONObject):Boolean;
begin
Result:=True;
if fFilter='' then exit;
if Assigned(onFilterData)then onFilterData(Self, aRow, fFilter, Result);
end;
procedure THKModel.Refresh;
var
con: TJsonRequester;
resp: TJSONData;
begin
if FData<>nil then FreeAndNil(FData);
if FConnection<>nil then
begin
con:=FConnection.CreateConnection;
try
resp:=con.JsonGet(Document);
if resp<>nil then
begin
FData:=DoResponseData(resp) as TJSONArray;
ProcessGrid;
end;
finally
con.Free;
end;
end;
end;
function THKModel.CreateNew(aData: TJSONObject; withNotif:Boolean=True): Boolean;
var
con: TJsonRequester;
resp: TJSONData;
begin
Result:=False;
if FConnection<>nil then
begin
con:=FConnection.CreateConnection;
try
aData.Booleans['isCreate']:=True;
resp:=con.JsonPost(Document, aData);
if resp<>nil then
begin
if withNotif then ShowMessage('Create Data Success');
Result:=True;
Refresh;
end;
finally
if resp<>nil then FreeAndNil(resp);
con.Free;
end;
end;
end;
function THKModel.UpdateData(aData: TJSONObject; aId: String; withNotif:Boolean=True): Boolean;
var
con: TJsonRequester;
resp: TJSONData;
begin
Result:=False;
if FConnection<>nil then
begin
con:=FConnection.CreateConnection;
try
aData.Booleans['isCreate']:=False;
aData.Strings['id']:=aId;
resp:=con.JsonPost(Document, aData);
if resp<>nil then
begin
if withNotif then ShowMessage('Edit Data Success');
Result:=True;
Refresh;
end;
finally
if resp<>nil then FreeAndNil(resp);
con.Free;
end;
end;
end;
procedure THKModel.Filter(aStr: String);
begin
fFilter:=aStr;
ProcessGrid;
end;
procedure THKModel.ClearFilter;
begin
Filter('');
end;
destructor THKModel.Destroy;
begin
if FData<>nil then FData.Free;
inherited Destroy;
end;
end.
|
unit Frm_CompressionRatio;
interface
uses
Windows, Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Dialogs, Vcl.StdCtrls, GLVfsPAK;
type
TFrmCompressionRatio = class(TForm)
BtnForOk: TButton;
BtnForCancel: TButton;
CbForRatio: TComboBox;
procedure FormCreate(Sender: TObject);
procedure BtnForCancelClick(Sender: TObject);
procedure BtnForOkClick(Sender: TObject);
private
{ Private declarations }
FCompressionRatio: TZCompressedMode;
FDefaultCbrMode: TZCompressedMode;
procedure SetDefaultCbrMode(const Value: TZCompressedMode);
public
{ Public declarations }
property CompressionRatio: TZCompressedMode read FCompressionRatio
write FCompressionRatio;
property DefaultCbrMode: TZCompressedMode read FDefaultCbrMode
write SetDefaultCbrMode;
end;
var
FrmCompressionRatio: TFrmCompressionRatio;
function SelectCompressionRatio(const ADefaultCbrMode: TZCompressedMode = Auto): TZCompressedMode;
implementation
uses
TypInfo;
{$R *.dfm}
// SelectCompressionRatio
//
function SelectCompressionRatio(const ADefaultCbrMode: TZCompressedMode = Auto): TZCompressedMode;
begin
if not Assigned(FrmCompressionRatio) then
FrmCompressionRatio.Create(nil);
FrmCompressionRatio.DefaultCbrMode := ADefaultCbrMode;
FrmCompressionRatio.ShowModal;
Result := FrmCompressionRatio.CompressionRatio;
end;
// TFrmCompressionRatio.FormCreate
//
procedure TFrmCompressionRatio.FormCreate(Sender: TObject);
var
I: TZCompressedMode;
begin
FCompressionRatio := Auto;
FDefaultCbrMode := Auto;
for I := Low(TZCompressedMode) to High(TZCompressedMode) do
CbForRatio.Items.Add(GetEnumName(TypeInfo(TZCompressedMode), Ord(I)));
end;
procedure TFrmCompressionRatio.SetDefaultCbrMode(
const Value: TZCompressedMode);
begin
FDefaultCbrMode := Value;
CbForRatio.ItemIndex := ord(DefaultCbrMode);
end;
// TFrmCompressionRatio.BtnForCancelClick
//
procedure TFrmCompressionRatio.BtnForCancelClick(Sender: TObject);
begin
FCompressionRatio := None;
end;
// TFrmCompressionRatio.BtnForOkClick
//
procedure TFrmCompressionRatio.BtnForOkClick(Sender: TObject);
begin
FCompressionRatio := TZCompressedMode(CbForRatio.ItemIndex);
end;
end.
|
unit ncaFrmConfigPrecoAuto;
{
ResourceString: Dario 11/03/13
Nada para para fazer
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ncaFrmBaseOpcaoImgTxtCheckBox, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Menus, StdCtrls,
cxButtons, cxLabel, cxCheckBox, ExtCtrls, LMDControl, LMDCustomControl,
LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, LMDPNGImage, cxTextEdit,
cxCurrencyEdit, DB, nxdb;
type
TFrmConfigPrecoAuto = class(TFrmBaseOpcaoImgTxtCheckBox)
panMargem: TLMDSimplePanel;
lbMargem: TcxLabel;
edMargem: TcxCurrencyEdit;
private
{ Private declarations }
public
{ Public declarations }
procedure Ler; override;
procedure Salvar; override;
function Alterou: Boolean; override;
procedure Renumera; override;
function NumItens: Integer; override;
end;
var
FrmConfigPrecoAuto: TFrmConfigPrecoAuto;
implementation
uses ncaDM, ncClassesBase;
{$R *.dfm}
{ TFrmBaseOpcaoImgTxtCheckBox1 }
function TFrmConfigPrecoAuto.Alterou: Boolean;
begin
Result := (gConfig.PrecoAuto<>CB.Checked) or
(gConfig.Margem<>edMargem.Value);
end;
procedure TFrmConfigPrecoAuto.Ler;
begin
inherited;
CB.Enabled := Dados.CM.UA.Admin;
CB.Checked := gConfig.PrecoAuto;
edMargem.Value := gConfig.Margem;
end;
function TFrmConfigPrecoAuto.NumItens: Integer;
begin
Result := 2;
end;
procedure TFrmConfigPrecoAuto.Renumera;
begin
inherited;
lbMargem.Caption := IntToStr(InicioNumItem+1)+'. ' + lbMargem.Caption;
end;
procedure TFrmConfigPrecoAuto.Salvar;
begin
inherited;
gConfig.PrecoAuto := CB.Checked;
gConfig.Margem := edMargem.Value;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, MQTT;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
GroupBox1: TGroupBox;
Memo1: TMemo;
Memo2: TMemo;
Panel1: TPanel;
Panel2: TPanel;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
public
Client:TMQTTClient;
procedure OnConnAck(Sender: TObject; ReturnCode: integer);
procedure OnPingResp(Sender: TObject);
procedure OnPublish(Sender: TObject; topic, payload: ansistring; retain: boolean);
procedure OnSubAck(Sender: TObject; MessageID: integer; GrantedQoS: integer);
procedure OnUnsubAck(Sender: TObject; MessageID: integer);
end;
var
Form1: TForm1;
implementation
{$R *.frm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
Client:=TMQTTClient.Create('192.168.0.95',1883);
Client.OnConnAck:=@OnConnAck;
Client.OnPingResp:=@OnPingResp;
Client.OnPublish:=@OnPublish;
Client.OnSubAck:=@OnSubAck;
Client.OnUnSubAck:=@OnUnsubAck;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Client.PingReq;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Client.Connect;
Sleep(1000);
Button2Click(nil);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if Client.isConnected then
Client.Subscribe('testtopic/#');
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
if Client.isConnected then
Client.Publish('testtopic','This is a message');
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
if Client.isConnected then
Client.Publish('testtopic', Trim(Memo2.Text));
end;
procedure TForm1.OnConnAck(Sender: TObject; ReturnCode: integer);
begin
Memo1.Lines.Add('ConnACK: '+inttostr(ReturnCode));
end;
procedure TForm1.OnPingResp(Sender: TObject);
begin
Memo1.Lines.Add('PingResp !');
end;
procedure TForm1.OnPublish(Sender: TObject; topic, payload: ansistring;
retain: boolean);
begin
Memo1.Lines.Add('Publish: topic='+topic+' payload='+payload);
end;
procedure TForm1.OnSubAck(Sender: TObject; MessageID: integer;
GrantedQoS: integer);
begin
Memo1.Lines.Add('SubAck: MessageId='+inttostr(MessageId)+' QoS='+inttostr(GrantedQoS));
end;
procedure TForm1.OnUnsubAck(Sender: TObject; MessageID: integer);
begin
Memo1.Lines.Add('UbSubAck:'+inttostr(MessageID));
end;
end.
|
unit MainUnit;
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the PolyLine Example code.
*
* The Initial Developer of the Original Code is Angus Johnson
*
* The Original Code is Copyright (C) 2008-9. All Rights Reserved.
*
* ***** END LICENSE BLOCK ***** *)
interface
uses
Windows, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
{$IFDEF FPC} LResources, {$ENDIF}
GR32, GR32_Image, GR32_Misc, GR32_Lines, GR32_Polygons, Math, ExtCtrls,
GR32_Transforms,GR32_Layers, ComCtrls, Messages;
type
TBtnState = (bsDefault, bsHighlight, bsPressed);
TForm1 = class(TForm)
Image: TImage32;
ScrollBar1: TScrollBar;
procedure FormCreate(Sender: TObject);
procedure ScrollBar1Change(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
procedure ImageMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer; Layer: TCustomLayer);
procedure ImageMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
private
btnState: TBtnState;
CloseBtn: TLine32;
CloseBtnPts: TArrayOfFixedPoint;
CloseBtnPts2: TArrayOfFixedPoint;
procedure BuildImage;
procedure OnShortCut(var Message: TWMKey; var Handled: boolean);
public
end;
var
Form1: TForm1;
clCaptionActive32, clCaptionActiveGrad32: TColor32;
clBtnShadow32, clBtnHighlight32, clBtnFace32: TColor32;
implementation
{$IFNDEF FPC}
{$R *.DFM}
{$ENDIF}
{$R PATTERN.RES}
procedure TForm1.FormCreate(Sender: TObject);
begin
Gr32.SetGamma(1.0);
Image.SetupBitmap;
//setup the CloseBtn line/shape object (which will be drawn in BuildImage)
CloseBtn := TLine32.Create;
CloseBtn.EndStyle := esClosed;
CloseBtn.SetPoints(GetEllipsePoints(FloatRect(415, 337, 505, 373)));
CloseBtnPts := CloseBtn.Points;
CloseBtnPts2 := CloseBtn.GetOuterEdge(3);
Application.OnShortCut := OnShortCut;
Application.Title := 'TLine32 Demo';
clCaptionActive32 := Color32(clActiveCaption);
clCaptionActiveGrad32 := Color32(clGradientActiveCaption);
clBtnShadow32 := Color32(clBtnShadow);
clBtnHighlight32 := Color32(clBtnHighlight);
clBtnFace32 := Color32(clBtnFace);
Image.Bitmap.Canvas.Font.Assign(self.Font);
Image.Bitmap.Canvas.Brush.Style := bsClear;
BuildImage;
end;
//------------------------------------------------------------------------------
procedure TForm1.FormDestroy(Sender: TObject);
begin
CloseBtn.Free;
end;
//------------------------------------------------------------------------------
procedure TForm1.OnShortCut(var Message: TWMKey; var Handled: boolean);
procedure AnimatedClose;
begin
handled := true;
btnState := bsPressed;
BuildImage;
sleep(200);
btnState := bsDefault;
BuildImage;
sleep(200);
close;
end;
begin
//close on ESC and Alt+C ...
case Message.CharCode of
VK_ESCAPE: AnimatedClose;
Ord('C'): if (GetKeyState(VK_MENU) < 0) then AnimatedClose;
end;
end;
//------------------------------------------------------------------------------
procedure TForm1.ImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
begin
//check if it's the CloseBtn being pressed ...
if PtInPolygon(FixedPoint(X,Y), CloseBtn.GetOuterEdge) then
begin
btnState := bsPressed;
BuildImage;
end;
end;
//------------------------------------------------------------------------------
procedure TForm1.ImageMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer; Layer: TCustomLayer);
var
oldBtnState: TBtnState;
begin
//update the CloseBtn state and redraw if necessary ...
if btnState = bsPressed then exit;
oldBtnState := btnState;
if PtInPolygon(FixedPoint(X,Y), CloseBtn.GetOuterEdge) then
begin
screen.Cursor := crHandPoint;
btnState := bsHighlight;
if btnState <> oldBtnState then BuildImage;
end else
begin
screen.Cursor := crDefault;
btnState := bsDefault;
if btnState <> oldBtnState then BuildImage;
end;
end;
//------------------------------------------------------------------------------
procedure TForm1.ImageMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
procedure AnimatedClose;
begin
btnState := bsPressed;
BuildImage;
sleep(200);
btnState := bsDefault;
BuildImage;
sleep(200);
close;
end;
begin
if btnState <> bsPressed then exit;
//update the CloseBtn state and redraw if necessary ...
if PtInPolygon(FixedPoint(X,Y), CloseBtn.GetOuterEdge) then
begin
btnState := bsHighlight;
AnimatedClose;
end else
begin
btnState := bsDefault;
BuildImage;
end;
end;
//------------------------------------------------------------------------------
procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
BuildImage;
end;
//------------------------------------------------------------------------------
procedure TForm1.BuildImage;
var
bmp: TBitmap32;
pts, outerPts, innerPts: TArrayOfFixedPoint;
rec, closeBtnTextRec: TRect;
dashes: TArrayOfFloat;
begin
Image.Bitmap.BeginUpdate;
Image.Bitmap.Clear($FFF3F3E4);
Image.Bitmap.StippleStep := ScrollBar1.Position * 0.01;
Image.Bitmap.Canvas.Font.Color := $330033;
with TLine32.Create do
try
////////////////////////////////////////////////////////////////////////////////
// Rectangle with rounded corners (varying with rotation) ...
////////////////////////////////////////////////////////////////////////////////
EndStyle := esClosed;
SetPoints(
GetRoundedRectanglePoints(
FloatRect(57, 57, 343, 343),
ScrollBar1.Position div 2)); //amount of rounding (but between 5 & 90)
//various transformation options...
//Scale(ScrollBar1.Position/50,ScrollBar1.Position/50);
//Translate(-ScrollBar1.Position+50,-ScrollBar1.Position+50);
Rotate(FloatPoint(200,200), -ScrollBar1.Position/100* pi);
//SimpleFill() is not a method of TLine32 (because it's not really
//a line drawing operation) but is a helper function that creates a
//TPolygon32 object, adds the array of points (in this case TLine32.Points)
//and fills the polygon with the specified colors ...
SimpleFill(Image.Bitmap, Points, $00000000, $100033FF);
//draw the polyline (ie rounded rectangle) with a stippling pattern ...
Draw(image.Bitmap, 3, [$800000FF, $800000FF, $800000FF, $800000FF,
$800000FF, $40ECE9D8, $40ECE9D8]);
//Draw(3, $800000FF);
////////////////////////////////////////////////////////////////////////////////
// Single straight line with rounded ends ...
////////////////////////////////////////////////////////////////////////////////
EndStyle := esRounded;
SetPoints([FixedPoint(30,90), FixedPoint(370,90)]);
Draw(image.Bitmap, 7, $99800040);
////////////////////////////////////////////////////////////////////////////////
// Fancy diamond (with horizontal color gradient fill and also outlined)...
////////////////////////////////////////////////////////////////////////////////
EndStyle := esClosed;
JoinStyle := jsMitered;
//set the 4 points of the diamond shape ...
SetPoints([
FixedPoint(35,200), FixedPoint(200,35),
FixedPoint(365,200), FixedPoint(200,365)]);
//gradient fill a 9px wide polyline (diamond) ...
DrawGradient(image.Bitmap, 9, [$CCFF6600,$CCFFFF00], 115);
//now draw the outer edges of the diamond shape Black ...
//nb: if Line32 object wasn't 'closed' getOuterEdge would return outline
SetPoints(GetOuterEdge);
Draw(image.Bitmap, 1, clBlack32);
//reset the original (diamond) points before getting another outline
//otherwise we'd get an outline of an outline!
SetPoints([
FixedPoint(35,200), FixedPoint(200,35),
FixedPoint(365,200), FixedPoint(200,365)]);
//nb: specify the previous 9px linewidth, since last Draw set linewidth = 1
SetPoints(GetInnerEdge(9));
//fill the interior of the diamond shape, also drawing an edge which
//corresponds to the inner edge of the diamond ...
SimpleRadialFill(Image.Bitmap,Points,[$EEFFFF00,$2033FFFF]);
Draw(image.Bitmap, 1, $FF990000);
//gr32_lines.SimpleFill(Image.Bitmap, Points, $FF990000, $eeECE9D8);
////////////////////////////////////////////////////////////////////////////////
// Single line gradient filled and with an 'arrow' on each end ...
////////////////////////////////////////////////////////////////////////////////
EndStyle := esSquared;
ArrowStart.Style := asDiamond;
ArrowStart.Size := 25;
ArrowStart.Color := $30AA00AA;
ArrowStart.Pen.Width := 2;
ArrowStart.Pen.Color := $FF800040;
ArrowEnd.Style := asSquare;
ArrowEnd.Size := 12;
ArrowEnd.Color := $30CC8000;
ArrowEnd.Pen.Width := 2;
ArrowEnd.Pen.Color := $FFAA6600;
SetPoints([FixedPoint(30,310), FixedPoint(380,310)]);
DrawGradient(image.Bitmap, 3, [$FF800040,$FFCC8000], 0);
//now disable arrows ...
ArrowStart.Style := asNone;
ArrowEnd.Style := asNone;
////////////////////////////////////////////////////////////////////////////////
// Dashed circle ...
////////////////////////////////////////////////////////////////////////////////
//dash, dot, dot, dash, dot, dot ... pattern ...
dashes := MakeArrayOfFloat([18, 5, 5, 5, 5, 5]);
pts := GetEllipsePoints(FloatRect(155, 155, 245, 245));
SetPoints(pts);
EndStyle := esClosed;
Draw(image.Bitmap, 10, dashes, $40ffaa00, clBlack32);
////////////////////////////////////////////////////////////////////////////////
// Small triangle ...
////////////////////////////////////////////////////////////////////////////////
EndStyle := esClosed;
SetPoints([FixedPoint(90,190),
FixedPoint(200,110), FixedPoint(310,190)]);
//add a subtle 3D shadow effect ...
pts := GetInnerEdge(9);
SimpleShadow(Image.Bitmap,pts,5,5,MAXIMUM_SHADOW_FADE,$FF336633, true);
pts := GetOuterEdge(9);
SimpleShadow(Image.Bitmap,pts,5,5,MAXIMUM_SHADOW_FADE,$FF336633, true);
Draw(image.Bitmap, 9, $CC00FF00, $FF003300);
////////////////////////////////////////////////////////////////////////////////
// Inverted small triangle ...
////////////////////////////////////////////////////////////////////////////////
JoinStyle := jsRounded;
SetPoints([FixedPoint(90,210),
FixedPoint(200,290), FixedPoint(310,210)]);
//add a subtle 3D shadow effect ...
pts := GetInnerEdge(9);
SimpleShadow(Image.Bitmap,pts,5,5,MAXIMUM_SHADOW_FADE,$FF336633, true);
pts := GetOuterEdge(9);
SimpleShadow(Image.Bitmap,pts,5,5,MAXIMUM_SHADOW_FADE,$FF336633, true);
Draw(image.Bitmap, 9, $CC00FF00, $FF003300);
//Draw(image.Bitmap, 9, [$CC00FF00, $CC00FF00, $CC00FF00, $FFECE9D8, $FFECE9D8]);
//DrawGradient(image.Bitmap, 9, [$FF00CCCC,$FF00FF00], 135);
////////////////////////////////////////////////////////////////////////////////
// Bezier Curve (rotating) ...
////////////////////////////////////////////////////////////////////////////////
EndStyle := esRounded;
JoinStyle := jsMitered;
SetPoints(
GetCBezierPoints([FixedPoint(320,190),
FixedPoint(200,50), FixedPoint(200,350), FixedPoint(80,210)]));
Rotate(FloatPoint(200,200), ScrollBar1.Position/100 *pi + pi/2);
Draw(image.Bitmap, 9, $20000066); //v. translucent blue (but looks gray due to background)
//now draw a stippled outline of this bezier ...
SetPoints(GetOutline);
Draw(image.Bitmap, 2, [$FF666666, $FF666666, $FF666666, $00000000, $00000000]);
////////////////////////////////////////////////////////////////////////////////
// Ellipse (circle) with a pattern fill and fancy outlines ...
////////////////////////////////////////////////////////////////////////////////
EndStyle := esClosed;
pts := GetEllipsePoints(FloatRect(60,60,340,340));
SetPoints(pts);
outerPts := GetOuterEdge(12);
innerPts := GetInnerEdge(9);
//load a bitmap pattern and draw a 9px wide line (circle) ...
bmp := TBitmap32.Create;
try
bmp.LoadFromResourceName(hInstance, 'PATTERN2');
Draw(image.Bitmap, 9, bmp);
finally
bmp.Free;
end;
SetPoints(outerPts);
Draw(Image.Bitmap,2.5,$FF003366);
SetPoints(innerPts);
Draw(Image.Bitmap,1.5,$FF003388);
////////////////////////////////////////////////////////////////////////////////
// Lots of arrowed lines with text ...
////////////////////////////////////////////////////////////////////////////////
//setup the basics ...
EndStyle := esSquared;
ArrowStart.Pen.Width := 1.5;
ArrowEnd.Pen.Width := 1.5;
ArrowEnd.Size := 15;
ArrowStart.Style := asCircle;
ArrowStart.Size := 5;
///////////////////////////////////////////////////
ArrowStart.Color := $80FFCC00;
ArrowEnd.Color := $80FFCC00;
ArrowStart.Pen.Color := $FF662200;
ArrowEnd.Pen.Color := $FF662200;
ArrowEnd.Style := asFourPoint;
pts := GetCBezierPoints([FixedPoint(415,125), FixedPoint(350,125),
FixedPoint(385,55), FixedPoint(425,110)]);
SetPoints(pts);
Draw(image.Bitmap, 2, $FF993300);
//some text (using the canvas so there's optimal rendering) ...
Image.Bitmap.Canvas.TextOut(422, 115,'Arrow ends');
///////////////////////////////////////////////////
ArrowStart.Color := $CC00CCCC;
ArrowStart.Pen.Color := $FF333399;
ArrowEnd.Color := $AA00E0E0;
ArrowEnd.Pen.Color := $FF333399;
ArrowEnd.Size := 14;
pts := GetQBezierPoints([
FixedPoint(415,155), FixedPoint(200,200),
RotatePoint(FixedPoint(80,80), FixedPoint(200,200),
-ScrollBar1.Position/100* pi)]);
SetPoints(pts);
//Draw(image.Bitmap, 2, $FF333399);
Draw(image.Bitmap, 2.5, [$FF333399,$FF333399,$00000000, $00000000, $00000000],0.65);
Image.Bitmap.Canvas.TextOut(422,145,'Rounded rectangles');
///////////////////////////////////////////////////
ArrowStart.Color := $8000FF33;
ArrowStart.Pen.Color := $FF004800;
ArrowEnd.Color := $FF00FF33;
ArrowEnd.Pen.Color := $FF004800;
ArrowEnd.Size := 12;
ArrowEnd.Pen.Width := 2;
SetPoints([FixedPoint(415,200),FixedPoint(324,190)]);
Draw(image.Bitmap, 2, $FF004800);
SetPoints([FixedPoint(415,200), FixedPoint(325,210)]);
Draw(image.Bitmap, 2, $FF004800);
Image.Bitmap.Canvas.TextOut(422,185,'Bevelled and');
Image.Bitmap.Canvas.TextOut(422,200,'rounded line joins');
///////////////////////////////////////////////////
ArrowStart.Color := $CC00CCCC;
ArrowStart.Pen.Color := $FF333399;
ArrowEnd.Color := $AA00E0E0;
ArrowEnd.Pen.Width := 2;
ArrowEnd.Pen.Color := $FF333399;
ArrowEnd.Style := asThreePoint;
ArrowEnd.Size := 14;
SetPoints([FixedPoint(415,255),FixedPoint(345,255)]);
Draw(image.Bitmap, 2, $FF333399);
Image.Bitmap.Canvas.TextOut(422,230,'Lines with pattern fills');
Image.Bitmap.Canvas.TextOut(422,245,'and lines outlining');
Image.Bitmap.Canvas.TextOut(422,260,'other lines');
///////////////////////////////////////////////////
ArrowStart.Color := $80FFCC00;
ArrowStart.Pen.Color := $FF662200;
ArrowEnd.Color := $FFFFCC00;
ArrowEnd.Pen.Color := $FF662200;
ArrowEnd.Size := 12;
ArrowEnd.Pen.Width := 1.5;
ArrowEnd.Style := asFourPoint;
pts := GetQBezierPoints([FixedPoint(415,300),
FixedPoint(380,270),FixedPoint(345,305)]);
SetPoints(pts);
Draw(image.Bitmap, 2, [$FF662200, $FF662200, $00000000, $00000000, $00000000],0.65);
pts := GetCBezierPoints([FixedPoint(415,300),
FixedPoint(385,270),FixedPoint(315,285),FixedPoint(305,275)]);
SetPoints(pts);
Draw(image.Bitmap, 2, [$FF662200, $FF662200, $00000000, $00000000, $00000000],0.65);
Image.Bitmap.Canvas.TextOut(422,290,'Gradient filling of lines');
///////////////////////////////////////////////////
//now just a bit of silliness to show off SimpleRadialFill ...
pts := GetEllipsePoints(FloatRect(385,20,515,80));
SimpleRadialFill(Image.Bitmap,pts,[$00FFFFFF,$00FFFFFF,$30FFFF00,$30FFAA00,$00FF00FF]);
rec := Rect(385,20,515,80);
windows.DrawText(Image.Bitmap.Canvas.handle, 'TLine32', 7,
rec, DT_CENTER or DT_VCENTER or DT_SINGLELINE or DT_NOCLIP);
//////////////////////////////////////////////////////////////////////////////////
finally
free;
end;
//finally draw the CloseBtn ...
closeBtnTextRec := Rect(415, 337, 505, 373);
SimpleFill(Image.Bitmap,CloseBtnPts,$0,clBtnFace32);
case btnState of
bsHighlight:
begin
CloseBtn.DrawGradient(image.Bitmap, 3, [clBtnHighlight32,clBtnShadow32], -80);
SimpleLine(Image.Bitmap,CloseBtnPts2,clCaptionActive32,true);
Image.Bitmap.Canvas.Font.Color := clWhite;
windows.DrawText(Image.Bitmap.Canvas.handle,
'&Close',6,closeBtnTextRec, DT_CENTER or DT_VCENTER or DT_SINGLELINE or DT_NOCLIP);
Image.Bitmap.Canvas.Font.Color := clBlack;
OffsetRect(closeBtnTextRec,1,1);
windows.DrawText(Image.Bitmap.Canvas.handle,
'&Close',6,closeBtnTextRec, DT_CENTER or DT_VCENTER or DT_SINGLELINE or DT_NOCLIP);
end;
bsPressed:
begin
CloseBtn.DrawGradient(image.Bitmap, 3, [clBtnHighlight32,clBtnShadow32], 100);
SimpleLine(Image.Bitmap,CloseBtnPts2,clCaptionActive32,true);
OffsetRect(closeBtnTextRec,-1,-1);
Image.Bitmap.Canvas.Font.Color := clWhite;
windows.DrawText(Image.Bitmap.Canvas.handle,
'&Close',6,closeBtnTextRec, DT_CENTER or DT_VCENTER or DT_SINGLELINE or DT_NOCLIP);
Image.Bitmap.Canvas.Font.Color := clBlack;
OffsetRect(closeBtnTextRec,1,1);
windows.DrawText(Image.Bitmap.Canvas.handle,
'&Close',6,closeBtnTextRec, DT_CENTER or DT_VCENTER or DT_SINGLELINE or DT_NOCLIP);
end;
bsDefault:
begin
CloseBtn.DrawGradient(image.Bitmap, 3, [clBtnHighlight32,clBtnShadow32], -80);
Image.Bitmap.Canvas.Font.Color := clWhite;
windows.DrawText(Image.Bitmap.Canvas.handle,
'&Close',6,closeBtnTextRec, DT_CENTER or DT_VCENTER or DT_SINGLELINE or DT_NOCLIP);
Image.Bitmap.Canvas.Font.Color := clBlack;
OffsetRect(closeBtnTextRec,1,1);
windows.DrawText(Image.Bitmap.Canvas.handle,
'&Close',6,closeBtnTextRec, DT_CENTER or DT_VCENTER or DT_SINGLELINE or DT_NOCLIP);
end;
end;
Image.Bitmap.Canvas.Font.Color := clWindowText;
Image.Bitmap.EndUpdate;
Image.Repaint;
end;
//------------------------------------------------------------------------------
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
if WheelDelta > 0 then
ScrollBar1.Position := ScrollBar1.Position - 2 else
ScrollBar1.Position := ScrollBar1.Position + 2;
end;
//------------------------------------------------------------------------------
end.
|
unit MediaProcessing.Processor.VA.Any;
interface
uses SysUtils,Windows,Classes, MediaProcessing.Definitions,MediaProcessing.Global,
MediaProcessing.VideoAnalytics.Definitions;
type
TScheduleItem = packed record
From: TTime;
To_: TTime;
end;
TMediaProcessor_VA_Any=class (TMediaProcessor,IMediaProcessor_Convertor_Rgb_H264)
protected
FConfig_VaConfigFileName: string;
FConfig_VaModelFileName: string;
FConfig_VaAsyncProcessing: boolean;
FConfig_VaFilters : TVaFilterArray;
FConfig_ScheduleEnabled: boolean;
FConfig_Schedule: TArray<TScheduleItem>;
FConfig_VaLuEnabled: boolean;
FConfig_VaLuMinY: integer;
FConfig_VaLuMaxY: integer;
FConfig_VaOtEnabled: boolean;
FConfig_VaOtEngine: TObjectTrackingEngine;
protected
procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override;
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
class function MetaInfo:TMediaProcessorInfo; override;
public
constructor Create; override;
destructor Destroy; override;
function HasCustomProperties: boolean; override;
procedure ShowCustomProperiesDialog;override;
end;
implementation
uses IdGlobal, Controls,uBaseClasses,MediaProcessing.Convertor.RGB.H264.SettingsDialog,MediaProcessing.Processor.VA.Any.SettingsDialog;
{ TMediaProcessor_VA_Any }
constructor TMediaProcessor_VA_Any.Create;
begin
inherited;
end;
destructor TMediaProcessor_VA_Any.Destroy;
begin
inherited;
end;
function TMediaProcessor_VA_Any.HasCustomProperties: boolean;
begin
result:=true;
end;
class function TMediaProcessor_VA_Any.MetaInfo: TMediaProcessorInfo;
begin
result.Clear;
result.TypeID:=IMediaProcessor_Processor_Va_Any;
result.Name:='Видеоаналитика';
result.Description:='Обрабатывает кадры (в любом формате) и идентифицирует объекты';
result.SetInputStreamType(stCOPY);
result.OutputStreamType:=stCOPY;
result.ConsumingLevel:=9;
end;
procedure TMediaProcessor_VA_Any.LoadCustomProperties(const aReader: IPropertiesReader);
var
aBytes: TBytes;
begin
inherited;
FConfig_VaConfigFileName:=aReader.ReadString('ConfigFileName','');
FConfig_VaModelFileName:=aReader.ReadString('ModelFileName','');
FConfig_VaAsyncProcessing:=aReader.ReadBool('AsyncProcessing',false);
FConfig_VaOtEnabled:=aReader.ReadBool('Ot.Enabled',true);
FConfig_VaLuEnabled:=aReader.ReadBool('Lu.Enabled',false);
FConfig_VaLuMinY:=aReader.ReadInteger('Lu.MinY',50);
FConfig_VaLuMaxY:=aReader.ReadInteger('Lu.MaxY',200);
FConfig_VaOtEngine:=TObjectTrackingEngine(aReader.ReadInteger('Ot.Engine',1));
aBytes:=aReader.ReadBytes('Filters');
SetLength(FConfig_VaFilters,Length(aBytes) div sizeof(TVaFilter));
CopyMemory(FConfig_VaFilters,aBytes,Length(FConfig_VaFilters)*sizeof(TVaFilter));
FConfig_ScheduleEnabled:=aReader.ReadBool('Schedule.Enabled',false);
aBytes:=aReader.ReadBytes('Schedule.Items');
SetLength(FConfig_Schedule,Length(aBytes) div sizeof(TScheduleItem));
CopyMemory(FConfig_Schedule,aBytes,Length(FConfig_Schedule)*sizeof(TScheduleItem));
end;
procedure TMediaProcessor_VA_Any.SaveCustomProperties(const aWriter: IPropertiesWriter);
begin
inherited;
aWriter.WriteString('ConfigFileName',FConfig_VaConfigFileName);
aWriter.WriteString('ModelFileName',FConfig_VaModelFileName);
aWriter.WriteBool('AsyncProcessing',FConfig_VaAsyncProcessing);
aWriter.WriteBool('Ot.Enabled',FConfig_VaOtEnabled);
aWriter.WriteBool('Lu.Enabled',FConfig_VaLuEnabled);
aWriter.WriteInteger('Lu.MinY',FConfig_VaLuMinY);
aWriter.WriteInteger('Lu.MaxY',FConfig_VaLuMaxY);
aWriter.WriteInteger('Ot.Engine',integer(FConfig_VaOtEngine));
aWriter.WriteBytes('Filters',RawToBytes(pointer(FConfig_VaFilters)^,Length(FConfig_VaFilters)*sizeof(TVaFilter)));
aWriter.WriteBool('Schedule.Enabled',FConfig_ScheduleEnabled);
aWriter.WriteBytes('Schedule.Items',RawToBytes(pointer(FConfig_Schedule)^,Length(FConfig_Schedule)*sizeof(TScheduleItem)));
end;
procedure TMediaProcessor_VA_Any.ShowCustomProperiesDialog;
var
aDialog: TfmMediaProcessingSettingsVa_Any;
i,k: Integer;
j: TVaEventType;
begin
aDialog:=TfmMediaProcessingSettingsVa_Any.Create(nil);
try
aDialog.edVideoAnalyticsConfigFilePath.Path:=FConfig_VaConfigFileName;
aDialog.edVideoAnalyticsModelFilePath.Path:=FConfig_VaModelFileName;
aDialog.ckVideoAnalyticsAsyncProcess.Checked:=FConfig_VaAsyncProcessing;
aDialog.ckVideoAnalyticsOtEnabled.Checked:=FConfig_VaOtEnabled;
aDialog.ckSchedule.Checked:=FConfig_ScheduleEnabled;
aDialog.taSchedule.DisableControls;
try
aDialog.taSchedule.EmptyTable;
aDialog.taSchedule.Open;
for i:=0 to High(FConfig_Schedule) do
begin
aDialog.taSchedule.Append;
aDialog.taScheduleFROM.Value:=FConfig_Schedule[i].From;
aDialog.taScheduleTO.Value:=FConfig_Schedule[i].To_;
aDialog.taSchedule.Post;
end;
aDialog.taSchedule.First;
finally
aDialog.taSchedule.EnableControls;
end;
aDialog.ckVaLuEnabled.Checked:=FConfig_VaLuEnabled;
aDialog.edVaLuMinLevel.Value:=FConfig_VaLuMinY;
aDialog.edVaLuMaxLevel.Value:=FConfig_VaLuMaxY;
aDialog.ckOtUseSynesis.Checked:=FConfig_VaOtEngine=otvSynesis;
if Length(FConfig_VaFilters)>0 then
begin
for i := 0 to High(FConfig_VaFilters) do
begin
if FConfig_VaFilters[i].FilterType=vaftTresholds then
begin
aDialog.ckVideoAnalyticsFiltersTresholds.Checked:=true;
aDialog.edMinSquarePx.Value:=FConfig_VaFilters[i].MinSquarePx;
aDialog.edMinWidthPx.Value:=FConfig_VaFilters[i].MinWidthPx;
aDialog.edMinHeightPx.Value:=FConfig_VaFilters[i].MinHeightPx;
aDialog.edMinPeriodMs.Value:=FConfig_VaFilters[i].MinPeriodMs;
end
else if FConfig_VaFilters[i].FilterType=vaftEvents then
begin
aDialog.ckVideoAnalyticsFiltersEvents.Checked:=true;
for j:=Low(TVaEventType) to High(TVaEventType) do
aDialog.lvVideoAnalyticsFiltersEvents.FindData(0,pointer(j),true,false).Checked:=j in FConfig_VaFilters[i].Events;
end;
end;
end;
aDialog.UpdateControlStates;
if aDialog.ShowModal=mrOk then
begin
FConfig_VaConfigFileName:=aDialog.edVideoAnalyticsConfigFilePath.Path;
FConfig_VaModelFileName:=aDialog.edVideoAnalyticsModelFilePath.Path;
FConfig_VaAsyncProcessing:=aDialog.ckVideoAnalyticsAsyncProcess.Checked;
FConfig_VaOtEnabled:=aDialog.ckVideoAnalyticsOtEnabled.Checked;
FConfig_ScheduleEnabled:=aDialog.ckSchedule.Checked;
FConfig_VaLuEnabled:=aDialog.ckVaLuEnabled.Checked;
FConfig_VaLuMinY:=aDialog.edVaLuMinLevel.Value;
FConfig_VaLuMaxY:=aDialog.edVaLuMaxLevel.Value;
if aDialog.ckOtUseSynesis.Checked then
FConfig_VaOtEngine:=otvSynesis
else
FConfig_VaOtEngine:=otvOpenCV;
aDialog.taSchedule.DisableControls;
try
aDialog.taSchedule.First;
SetLength(FConfig_Schedule,aDialog.taSchedule.RecordCount);
i:=0;
while not aDialog.taSchedule.Eof do
begin
FConfig_Schedule[i].From:=aDialog.taScheduleFROM.Value;
FConfig_Schedule[i].To_:=aDialog.taScheduleTO.Value;
inc(i);
aDialog.taSchedule.Next;
end;
finally
aDialog.taSchedule.EnableControls;
end;
SetLength(FConfig_VaFilters,0);
if aDialog.ckVideoAnalyticsFiltersTresholds.Checked then
begin
i:=Length(FConfig_VaFilters);
SetLength(FConfig_VaFilters,i+1);
FConfig_VaFilters[i].FilterType:=vaftTresholds;
FConfig_VaFilters[i].MinSquarePx:=aDialog.edMinSquarePx.Value;
FConfig_VaFilters[i].MinWidthPx:=aDialog.edMinWidthPx.Value;
FConfig_VaFilters[i].MinHeightPx:=aDialog.edMinHeightPx.Value;
FConfig_VaFilters[i].MinPeriodMs:=aDialog.edMinPeriodMs.Value;
end;
if aDialog.ckVideoAnalyticsFiltersEvents.Checked then
begin
i:=Length(FConfig_VaFilters);
SetLength(FConfig_VaFilters,i+1);
FConfig_VaFilters[i].FilterType:=vaftEvents;
FConfig_VaFilters[i].Events:=[];
for k := 0 to aDialog.lvVideoAnalyticsFiltersEvents.Items.Count-1 do
begin
if aDialog.lvVideoAnalyticsFiltersEvents.Items[k].Checked then
include(FConfig_VaFilters[i].Events,TVaEventType(aDialog.lvVideoAnalyticsFiltersEvents.Items[k].Data));
end;
end;
end;
finally
aDialog.Free;
end;
end;
initialization
MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_VA_Any);
end.
|
unit TestOSFile;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, SysUtils, OSFile, Windows, Dialogs;
type
// Test methods for class TOSFile
TConcreteTOSFile = class(TOSFile)
end;
TestTOSFile = class(TTestCase)
strict private
FOSFile: TConcreteTOSFile;
const
DefaultPath = '\\.\TestDrive1';
DefaultPathUpperCase = '\\.\TESTDRIVE1';
DefaultPathWithoutPrefix = 'TESTDRIVE1';
type
TTestOSFile = class(TOSFile)
public
procedure IfOSErrorRaiseException;
end;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestIsPathEqual;
procedure TestGetPathOfFileAccessing;
procedure TestGetPathOfFileAccessingWithoutPrefix;
procedure TestIfOSErrorRaiseException;
end;
implementation
procedure TestTOSFile.SetUp;
begin
FOSFile := TConcreteTOSFile.Create(DefaultPath);
end;
procedure TestTOSFile.TearDown;
begin
FOSFile.Free;
FOSFile := nil;
end;
procedure TestTOSFile.TestIsPathEqual;
var
ReturnValue: Boolean;
PathToCompare: string;
begin
FOSFile.Free;
FOSFile := TConcreteTOSFile.Create('TeSt');
PathToCompare := 'TeSt';
ReturnValue := FOSFile.IsPathEqual(PathToCompare);
CheckEquals(true, ReturnValue, 'Error comparing same path');
PathToCompare := 'Test';
ReturnValue := FOSFile.IsPathEqual(PathToCompare);
CheckEquals(true, ReturnValue, 'Error comparing case-different path');
PathToCompare := 'Not Test';
ReturnValue := FOSFile.IsPathEqual(PathToCompare);
CheckEquals(false, ReturnValue, 'Error comparing different path');
end;
procedure TestTOSFile.TestGetPathOfFileAccessing;
var
ReturnValue: string;
begin
ReturnValue := FOSFile.GetPathOfFileAccessing;
CheckEquals(DefaultPathUpperCase, ReturnValue);
end;
procedure TestTOSFile.TestGetPathOfFileAccessingWithoutPrefix;
var
ReturnValue: string;
begin
ReturnValue := FOSFile.GetPathOfFileAccessingWithoutPrefix;
CheckEquals(DefaultPathWithoutPrefix, ReturnValue);
end;
procedure TestTOSFile.TTestOSFile.IfOSErrorRaiseException;
begin
inherited IfOSErrorRaiseException;
end;
procedure TestTOSFile.TestIfOSErrorRaiseException;
const
ErrorCodeToTest = 501;
var
TestOSFile: TTestOSFile;
begin
TestOSFile := TTestOSFile.Create('');
SetLastError(ErrorCodeToTest);
StartExpectingException(EOSError);
TestOSFile.IfOSErrorRaiseException;
StopExpectingException('OS Error did not checked properly');
TestOSFile.Free;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTOSFile.Suite);
end.
|
(*
* This code was generated by the TaskGen tool from file
* "TASM32Task.xml"
* Version: 16.0.0.0
* Runtime Version: v2.0.50727
* Changes to this file may cause incorrect behavior and will be
* overwritten when the code is regenerated.
*)
unit TasmStrs;
interface
const
sTaskName = 'tasm32';
// DirectoriesAndConditionals
sDefines = 'TASM_Defines';
sIncludePath = 'TASM_IncludePath';
sDirectives = 'TASM_Directives';
sOutputDir = 'TASM_OutputDir';
// Options
sOverlay = 'TASM_Overlay';
sOverlay_Standard = 'Standard';
sOverlay_TLINK = 'TLINK';
sOverlay_PharLap = 'PharLap';
sOverlay_IBM = 'IBM';
sSegmentOrdering = 'TASM_SegmentOrdering';
sSegmentOrdering_Alphabetic = 'Alphabetic';
sSegmentOrdering_Sequential = 'Sequential';
sFloatingPoint = 'TASM_FloatingPoint';
sFloatingPoint_Emulator = 'Emulator';
sFloatingPoint_Real = 'Real';
sCaseSensitivity = 'TASM_CaseSensitivity';
sCaseSensitivity_CaseInsensitive = 'CaseInsensitive';
sCaseSensitivity_All = 'All';
sCaseSensitivity_Global = 'Global';
sGenerateCrossReferences = 'TASM_GenerateCrossReferences';
sGenerateCrossRefFile = 'TASM_GenerateCrossRefFile';
sGenerateExpandedListingFile = 'TASM_GenerateExpandedListingFile';
sGenerateListingFile = 'TASM_GenerateListingFile';
sSuppressSymbolsInListing = 'TASM_SuppressSymbolsInListing';
sFalseCondsInListing = 'TASM_FalseCondsInListing';
sDebugging = 'TASM_Debugging';
sDebugging_Full = 'Full';
sDebugging_LineNumbersOnly = 'LineNumbersOnly';
sDebugging_None = 'None';
sHashTableCapacity = 'TASM_HashTableCapacity';
sMaxSymbolLength = 'TASM_MaxSymbolLength';
sPasses = 'TASM_Passes';
sImpureCodeCheck = 'TASM_ImpureCodeCheck';
sSuppressObjRecords = 'TASM_SuppressObjRecords';
sSuppressMessages = 'TASM_SuppressMessages';
sVersionId = 'TASM_VersionId';
sDisplaySourceLines = 'TASM_DisplaySourceLines';
sAdditionalSwitches = 'TASM_AdditionalSwitches';
// Warnings
sAllWarnings = 'TASM_AllWarnings';
sDisableWarnings = 'TASM_DisableWarnings';
sSelectedWarnings = 'TASM_SelectedWarnings';
swaln = 'TASM_waln';
swass = 'TASM_wass';
swbrk = 'TASM_wbrk';
swgtp = 'TASM_wgtp';
swicg = 'TASM_wicg';
swint = 'TASM_wint';
swlco = 'TASM_wlco';
swmcp = 'TASM_wmcp';
swopi = 'TASM_wopi';
swopp = 'TASM_wopp';
swops = 'TASM_wops';
swovf = 'TASM_wovf';
swpdc = 'TASM_wpdc';
swpqk = 'TASM_wpqk';
swpro = 'TASM_wpro';
swres = 'TASM_wres';
swtpi = 'TASM_wtpi';
swuni = 'TASM_wuni';
// InternalOptions
sCommandString = 'TASM_CommandString';
// Outputs
sOutput_ObjFiles = 'ObjFiles';
sOutput_ListingFile = 'ListingFile';
sOutput_CrossRefFile = 'CrossRefFile';
implementation
end.
|
program fixlp;
uses
SysUtils, Classes, FileUtil, laz2_xmlread, laz2_xmlwrite, laz2_dom;
const
PARENTS_OF_NUMBERED_NODES: array[0..9] of string = (
'BuildModes', 'RequiredPackages', 'RequiredPkgs', 'Files', 'Units',
'Exceptions', 'JumpHistory', 'Modes', 'HistoryLists', 'OtherDefines'
);
{ Rename the given node. ANode.NodeName is readonly. Therefore, we create
a new empty node, give it the new name and copy all children and attributes
from the old node to the new node.
NOTE:
We cannot call parentNode.CloneNode because this would copy the node name
--> we must do everything manually step by step. }
procedure RenameNode(ANode: TDOMNode; ANewName: String);
var
doc: TDOMDocument;
parentNode: TDOMNode;
newNode: TDOMNode;
childNode: TDOMNode;
newChildNode: TDOMNode;
i: Integer;
begin
parentNode := ANode.ParentNode;
doc := ANode.OwnerDocument;
// Create a new node
newNode := doc.CreateElement(ANewName);
// copy children of old node to new node
childNode := ANode.FirstChild;
while childNode <> nil do begin
newChildNode := childNode.CloneNode(true);
newNode.AppendChild(newChildNode);
childNode := childNode.NextSibling;
end;
// Copy attributes to the new node
for i := 0 to ANode.Attributes.Length - 1 do
TDOMElement(newNode).SetAttribute(
ANode.Attributes[i].NodeName,
ANode.Attributes[i].NodeValue
);
// Replace old node by new node in xml document
parentNode.Replacechild(newNode, ANode);
// Destroy old node
ANode.Free;
end;
procedure FixNode(ANode: TDOMNode);
var
nodeName: String;
subnode: TDOMNode;
nextSubNode: TDOMNode;
numItems: Integer;
i: Integer;
found: Boolean;
begin
if ANode = nil then
exit;
nodeName := ANode.NodeName;
found := false;
for i := Low(PARENTS_OF_NUMBERED_NODES) to High(PARENTS_OF_NUMBERED_NODES) do
if PARENTS_OF_NUMBERED_NODES[i] = nodeName then
begin
found := true;
break;
end;
if found then
begin
subnode := ANode.FirstChild;
numItems := 0;
while subnode <> nil do begin
nodeName := subnode.NodeName;
nextSubNode := subNode.NextSibling;
// 1-based numbered nodes
if (nodeName = 'Item') or (nodeName = 'Position') then
begin
inc(numItems);
RenameNode(subnode, nodeName + IntToStr(numItems));
end else
// 0-based numbered nodes
if (nodeName = 'Unit') or (nodeName = 'Mode') or (nodeName = 'List') or
(nodeName = 'Define') then
begin
RenameNode(subnode, nodeName + IntToStr(numItems));
inc(numItems);
end;
subnode := nextSubNode;
end;
if numItems > 0 then
TDOMElement(ANode).SetAttribute('Count', IntToStr(numItems));
end;
FixNode(ANode.FirstChild);
FixNode(ANode.NextSibling);
end;
procedure FixXML(AFileName: string);
var
L: TStrings;
doc: TXMLDocument;
ext: String;
fn: String;
begin
if (pos('*', AFileName) > 0) or (pos('?', AFileName) > 0) then
begin
L := TStringList.Create;
try
FindAllFiles(L, ExtractFileDir(AFileName), ExtractFileName(AfileName), true);
for fn in L do
FixXML(fn);
finally
L.Free;
end;
exit;
end;
ext := Lowercase(ExtractFileExt(AFileName));
if not ((ext = '.lpi') or (ext = '.lpk') or (ext = '.lps')) then
exit;
WriteLn('Processing ', AFilename, '...');
ReadXMLFile(doc, AFileName);
try
FixNode(doc.DocumentElement);
fn := AFileName + '.bak';
if FileExists(fn) then DeleteFile(fn);
RenameFile(AFileName, fn);
WriteXMLFile(doc, AFileName);
finally
doc.Free;
end;
end;
procedure WriteHelp;
begin
WriteLn('fixlp <filename1>[, <filename2> [...]]');
WriteLn(' Wildcards allowed in file names.');
end;
var
i: Integer;
begin
if ParamCount = 0 then
begin
WriteHelp;
Halt;
end;
for i := 1 to ParamCount do
FixXML(ParamStr(i));
end.
|
unit FC.Trade.LiveDialog;
{$I Compiler.inc}
interface
uses
BaseUtils, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogClose_B, StdCtrls, ExtendControls, ExtCtrls, ActnList,
TeEngine, Series, TeeProcs, Chart, ComCtrls, Spin, ToolWin, JvComponentBase,
JvCaptionButton, ImgList, DB, MemoryDS,
Properties.Definitions,
StockChart.Definitions,
FC.fmUIDataStorage,
FC.Definitions,
FC.Singletons,
FC.Trade.Statistics,
FC.Trade.ResultPage, FC.Dialogs.DockedDialogCloseAndAppWindow_B, JvDockControlForm;
type
TfmTradeLiveDialog = class(TfmDockedDialogCloseAndAppWindow_B,IStockBrokerEventHandler)
pcPages: TPageControl;
tsStart: TTabSheet;
tsResults: TTabSheet;
lvTraders: TExtendListView;
Label1: TLabel;
ActionList1: TActionList;
acStartTrading: TAction;
buStartTesting: TButton;
paTrading: TPanel;
buStop: TButton;
acTraderProperties: TAction;
Button1: TButton;
acGetStatistic: TAction;
acExportOrders: TAction;
acCaptionButton: TAction;
frmStockTradeResult: TfrmStockTradeResult;
laProcess: TPanel;
tmRefresh: TTimer;
procedure buSeparateWindowClick(Sender: TObject);
procedure acTraderPropertiesUpdate(Sender: TObject);
procedure acTraderPropertiesExecute(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure buStopClick(Sender: TObject);
procedure lvOrdersColumnClick(Sender: TObject; Column: TListColumn);
procedure buOKClick(Sender: TObject);
procedure acStartTradingUpdate(Sender: TObject);
procedure acStartTradingExecute(Sender: TObject);
private
FClosedOrderCount : integer;
FLastSortOrderColumn: integer;
FTimeStep : TTime;
FCharts : TInterfaceList; //of IStockChart
FTraders : TInterfaceList; //of IStockTrader
function CurrentTrader: IStockTrader;
//from IStockBrokerEventHandler
procedure OnStart (const aSender: IStockBroker);
procedure OnNewData(const aSender: IStockBroker; const aSymbol: string);
procedure OnNewOrder (const aSender: IStockBroker; const aOrder: IStockOrder);
procedure OnModifyOrder(const aSender: IStockBroker; const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
procedure OnNewMessage (const aSender: IStockBroker; const aMessage: IStockBrokerMessage); overload;
procedure OnNewMessage (const aSender: IStockBroker; const aOrder: IStockOrder; const aMessage: IStockBrokerMessage); overload;
function GetChart(index: integer): IStockChart;
protected
procedure CreateParams(var Params: TCreateParams); override;
public
procedure RunTrading;
procedure StopTrading;
function IsRunning: boolean;
procedure AddTrader(aTrader: IStockTrader);
procedure AddChart(aChart: IStockChart);
function ChartCount: integer;
property Charts[index:integer]: IStockChart read GetChart;
constructor Create; reintroduce;
destructor Destroy; override;
end;
implementation
uses DateUtils, SystemService, Math,Application.Definitions,
StockChart.Indicators.Properties, StockChart.Obj,
ufmDialogOKCancel_B,FC.Trade.TesterTrainPropsDialog,FC.Trade.TesterTrainReportDialog;
{$R *.dfm}
{ TfmTradeLiveDialog }
procedure TfmTradeLiveDialog.acStartTradingExecute(Sender: TObject);
begin
RunTrading;
end;
procedure TfmTradeLiveDialog.acStartTradingUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=CurrentTrader<>nil;
end;
constructor TfmTradeLiveDialog.Create;
begin
inherited Create(nil);
TWaitCursor.SetUntilIdle;
FTraders:=TInterfaceList.Create;
FTimeStep:=EncodeTime(0,1,0,0); //1 min
FCharts:=TInterfaceList.Create;
frmStockTradeResult.Mode:=tmReal;
pcPages.ActivePageIndex:=0;
FLastSortOrderColumn:=-1;
buSeparateWindow.Down:=true;
buSeparateWindowClick(nil);
//ssDoNormalCursor;
end;
destructor TfmTradeLiveDialog.Destroy;
begin
lvTraders.Items.Clear;
FreeAndNil(FCharts);
FreeAndNil(FTraders);
inherited;
end;
function TfmTradeLiveDialog.CurrentTrader: IStockTrader;
begin
result:=nil;
if lvTraders.Selected<>nil then
result:=FTraders[integer(lvTraders.Selected.Data)] as IStockTrader;
end;
procedure TfmTradeLiveDialog.buOKClick(Sender: TObject);
begin
inherited;
buStopClick(nil);
Close;
end;
procedure TfmTradeLiveDialog.OnModifyOrder(const aSender: IStockBroker; const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
begin
Forms.Application.ProcessMessages;
frmStockTradeResult.OnModifyOrder(aOrder,aModifyEventArgs);
end;
procedure TfmTradeLiveDialog.OnNewData(const aSender: IStockBroker; const aSymbol: string);
begin
if AnsiSameText(aSymbol,CurrentTrader.GetProject.GetStockSymbol) then
begin
frmStockTradeResult.OnNewData(aSender,aSymbol);
CurrentTrader.Update(aSender.GetCurrentTime);
end;
end;
procedure TfmTradeLiveDialog.OnNewMessage(const aSender: IStockBroker; const aOrder: IStockOrder; const aMessage: IStockBrokerMessage);
begin
frmStockTradeResult.OnNewMessage(aSender,aOrder,aMessage);
end;
procedure TfmTradeLiveDialog.OnNewMessage(const aSender: IStockBroker; const aMessage: IStockBrokerMessage);
begin
frmStockTradeResult.OnNewMessage(aSender,aMessage);
end;
procedure TfmTradeLiveDialog.OnNewOrder(const aSender: IStockBroker; const aOrder: IStockOrder);
begin
frmStockTradeResult.OnNewOrder(aOrder);
end;
procedure TfmTradeLiveDialog.OnStart(const aSender: IStockBroker);
begin
end;
procedure TfmTradeLiveDialog.lvOrdersColumnClick(Sender: TObject; Column: TListColumn);
begin
if FLastSortOrderColumn = Column.Index then
begin
FLastSortOrderColumn := -1;
//lvOrders.SortColumn(Column,Sorts[Column.Index],true);
end
else
begin
FLastSortOrderColumn := Column.Index;
//lvOrders.SortColumn(Column,Sorts[Column.Index],false);
end;
end;
procedure TfmTradeLiveDialog.buStopClick(Sender: TObject);
begin
StopTrading;
end;
procedure TfmTradeLiveDialog.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
inherited;
if CanClose then
StopTrading;
end;
procedure TfmTradeLiveDialog.AddTrader(aTrader: IStockTrader);
begin
FTraders.Add(aTrader);
lvTraders.AddItem(aTrader.GetName,TObject(FTraders.Count-1));
if lvTraders.Items.Count=1 then
lvTraders.Items[0].Selected:=true;
end;
procedure TfmTradeLiveDialog.AddChart(aChart: IStockChart);
var
i,j: integer;
aCharts : array of IStockChart;
begin
//Вставляем так, чтобы были по порядку, сначала самые большие
j:=0;
for i:=0 to ChartCount-1 do
begin
if integer(Charts[i].StockSymbol.TimeInterval)<integer(aChart.StockSymbol.TimeInterval) then
break;
inc(j);
end;
FCharts.Insert(j,aChart);
SetLength(aCharts,FCharts.Count);
for j:=0 to FCharts.Count-1 do
aCharts[j]:=FCharts[j] as IStockChart;
frmStockTradeResult.Init(aCharts);
end;
procedure TfmTradeLiveDialog.acTraderPropertiesExecute(Sender: TObject);
begin
CurrentTrader.ShowPropertyWindow;
end;
procedure TfmTradeLiveDialog.acTraderPropertiesUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=lvTraders.Selected<>nil;
end;
function TfmTradeLiveDialog.GetChart(index: integer): IStockChart;
begin
result:=FCharts[index] as IStockChart;
end;
function TfmTradeLiveDialog.ChartCount: integer;
begin
result:=FCharts.Count;
end;
procedure TfmTradeLiveDialog.CreateParams(var Params: TCreateParams);
begin
inherited;
if PopupMode=Forms.pmNone then
Params.ExStyle:=Params.ExStyle or WS_EX_APPWINDOW
end;
procedure TfmTradeLiveDialog.RunTrading;
var
aTrader : IStockTrader;
aBroker : IStockBroker;
aCharts : array of IStockChart;
j: integer;
begin
if StockBrokerConnectionRegistry.CurrentConnection=nil then
begin
MsgBox.MessageFailure(0,'Connection to broker is not set. Setup broker connection in Tools\Stock Brokers');
exit;
end;
aTrader:=CurrentTrader;
//aInputData:=FStockChart.GetInputData;
StockBrokerConnectionRegistry.AddBrokerEventHandler(self);
aBroker:=StockBrokerConnectionRegistry.CurrentConnection.GetBroker;
aTrader.SetBroker(aBroker);
aTrader.Invalidate();
SetLength(aCharts,FCharts.Count);
for j:=0 to FCharts.Count-1 do
aCharts[j]:=FCharts[j] as IStockChart;
frmStockTradeResult.OnStart(aBroker,aTrader);
frmStockTradeResult.Statictics.Balance:=aBroker.GetBalance;
frmStockTradeResult.Statictics.StartDate:=Now;
FLastSortOrderColumn:=-1;
FClosedOrderCount:=0;
tsStart.Enabled:=false;
pcPages.ActivePage:=tsResults;
paTrading.Visible:=true;
end;
procedure TfmTradeLiveDialog.StopTrading;
begin
frmStockTradeResult.Statictics.StopDate:=Now;
StockBrokerConnectionRegistry.RemoveBrokerEventHandler(self);
tmRefresh.Enabled:=false;
paTrading.Visible:=false;
tsStart.Enabled:=true;
end;
procedure TfmTradeLiveDialog.buSeparateWindowClick(Sender: TObject);
begin
if buSeparateWindow.Down then
PopupMode:=Forms.pmNone
else
PopupMode:=pmAuto;
end;
function TfmTradeLiveDialog.IsRunning: boolean;
begin
result:=paTrading.Visible;
end;
{ TStockBrokerEventHandler }
end.
|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.WD;
interface
uses
BufferInterpreter, Device.SMART.List, SMARTSupport, Support;
type
TWDSMARTSupport = class(TSMARTSupport)
public
function IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean; override;
function GetTypeName: String; override;
function IsSSD: Boolean; override;
function IsInsufficientSMART: Boolean; override;
function GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted; override;
function IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean; override;
end;
implementation
{ TWDSMARTSupport }
function TWDSMARTSupport.GetTypeName: String;
begin
result := 'Smart';
end;
function TWDSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := false;
end;
function TWDSMARTSupport.IsSSD: Boolean;
begin
result := false;
end;
function TWDSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
(FindAtFirst('WDC ', IdentifyDevice.Model)) and
(not CheckIsSSDInCommonWay(IdentifyDevice));
end;
function TWDSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
begin
result := false;
end;
function TWDSMARTSupport.GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted;
const
ReadError = true;
EraseError = false;
UsedHourID = $09;
ThisErrorType = ReadError;
ErrorID = $01;
ReplacedSectorsID = $05;
begin
FillChar(result, SizeOf(result), 0);
result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID);
result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError;
result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID);
result.ReplacedSectors :=
SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID);
end;
end.
|
{
InternetExpress sample application component.
TInetXCenterProducer is a custom TMidasPageProducer that implements
standard behavior for pages in the INetXCenter sample application.
Creating a custom producer has benefits:
1) Can create customized, common appearance for web pages. Easy
to change appearance of all web pages.
2) Formatted page can be viewed at design time.
3) Can share code across applications.
}
unit InetXCenterProd;
interface
uses Classes, MidItems, MidProd, WebComp, HTTPApp, HTTPProd, DB, SysUtils;
procedure Register;
type
TPageCategory = (catExample);
const
PageExampleCategories = [catExample];
type
IComponentsInfo = interface;
TPageCategories = set of TPageCategory;
TTopicPage = (topNone, topHome, topComponents, topExamples,
topComponentsFilter, topXML, topJavaScript, topAboutComponents);
TPageLayout = (plStandard, plDescription);
TInetXCenterProducer = class(TCustomMidasPageProducer)
private
FPageCategories: TPageCategories;
FTopicPage: TTopicPage;
FPageLayout: TPageLayout;
FDescription: TStrings;
FDescriptionFile: TFileName;
FTitle: string;
FCaption: string;
FLinkName: string;
FComponentsInfoIntf: IComponentsInfo;
FComponentsInfo: TDataSet;
FClassNames: TStrings;
FInstructions: TStrings;
procedure SetDescription(const Value: TStrings);
procedure FindComponents;
function GetLinkName: string;
function GetCaption: string;
function GetTitle: string;
function GetTitleElement: string;
function GetComponentsInfo: IComponentsInfo;
procedure SetComponentsInfo(const Value: TDataSet);
procedure SetCaption(const Value: string);
procedure SetTitle(const Value: string);
procedure SetLinkName(const Value: string);
function GetSelectClassName: string;
function FormatGlobalLinks(Topics: array of TTopicPage): string;
function GetGlobalLinks: string;
procedure AddTopicLinks(ALinks: TStrings);
procedure GetExampleProducers(AList: TList);
function GetSelectExample: string;
function DefaultTitle: string;
procedure SetInstructions(const Value: TStrings);
protected
function GetDefaultTemplate: string; override;
procedure DoTagEvent(Tag: TTag; const TagString: string;
TagParams: TStrings; var ReplaceText: string); override;
function CreatePageElements: TMidasPageElements; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetHREF: string;
function GetTopicName: string;
function GetBanner: string;
function GetDescription(ALinks: TStrings): string;
function GetUsesComponents(ALinks: TStrings): string;
procedure GetClassNames;
function GetComponentDetails(ALinks: TStrings): string;
function GetComponentSummary(ALinks: TStrings): string;
function GetComponentsList(ALinks: TStrings): string;
function GetExamplesList(ALinks: TStrings): string;
function GetExampleSummary(AProducers: TList; ALinks: TStrings): string;
function GetExampleDetails(AProducers: TList; ALinks: TStrings): string;
function GetDumpRequest: string;
function FindTopicPage(
ATopic: TTopicPage): TInetXCenterProducer;
function IsExample: Boolean;
property ClassNames: TStrings read FClassNames;
property ComponentsInfoIntf: IComponentsInfo read GetComponentsInfo;
published
property HTMLDoc;
property HTMLFile;
property IncludePathURL;
property OnBeforeGetXMLData;
property OnAfterGetXMLData;
property OnBeforeGetContent;
property OnAfterGetContent;
property Styles;
property StylesFile;
property WebPageItems;
property EnableXMLIslands;
property LinkName: string read GetLinkName write SetLinkName;
property HREF: string read GetHREF;
property TopicPage: TTopicPage read FTopicPage write FTopicPage;
property PageCategories: TPageCategories read FPageCategories write FPageCategories;
property Description: TStrings read FDescription write SetDescription;
property Title: string read GetTitle write SetTitle;
property Caption: string read GetCaption write SetCaption;
property ComponentsInfo: TDataSet read FComponentsInfo write SetComponentsInfo;
property DescriptionFile: TFileName read FDescriptionFile write FDescriptionFile;
property PageLayout: TPageLayout read FPageLayout write FPageLayout;
property Instructions: TStrings read FInstructions write SetInstructions;
end;
IComponentsInfo = interface
['{D9792F5D-34BD-11D3-B016-00C04FB16EC3}']
procedure Reset;
function Next: Boolean;
function ClassName: string;
function ShortDescription: string;
function Description: string;
function Eof: Boolean;
function Usage: string;
function Package: string;
function GetType: string;
function Example: string;
procedure SetFilter(PackageFilter, UsageFilter, TypeFilter: string);
procedure ClearFilter;
function FieldByName(FieldName: string): TField;
procedure LocateClassName(AClassName: string);
function GetFilter: string;
end;
TComponentsInfo = class(TInterfacedObject, IComponentsInfo)
private
FDataSet: TDataSet;
FReset: Boolean;
protected
procedure Reset;
function Next: Boolean;
function ClassName: string;
function Description: string;
function ShortDescription: string;
function Usage: string;
function Eof: Boolean;
function Package: string;
function GetType: string;
function Example: string;
procedure SetFilter(PackageFilter, UsageFilter, TypeFilter: string);
function FieldByName(FieldName: string): TField;
procedure LocateClassName(AClassName: string);
procedure ClearFilter;
function GetFilter: string;
public
constructor Create(ADataSet: TDataSet);
end;
implementation
uses Windows, dbclient, MidComp;
const
sBannerFile = 'inetxbanner.jpg';
BannerWidth = 436;
BannerHeight = 73;
resourcestring
sTitle = 'InternetExpress %s';
sTitleExample = 'InternetExpress %s Example';
sBanner = 'InternetExpress Center';
sComponentTable =
'<table width="100%%">'#13#10 +
'<tr>'#13#10 +
'<th align="left"><b><A Name=%0:s>%0:s<A></b>'#13#10 +
'</th>'#13#10 +
'</tr>'#13#10 +
'<tr>'#13#10 +
'<td valign="top"><p style="margin-left: 20">%1:s</td>'#13#10 +
'</tr>'#13#10 +
'%2:s'#13#10 +
'%3:s'#13#10 +
'</table>';
sPrimaryExampleTitle = 'Primary Example:';
sOtherExamplesTitle = 'Other Examples:';
sExamplesTitle = 'Examples:';
sComponentExamples =
'<tr>'#13#10 +
'<td><p style="margin-left: 20">%0:s</td>'#13#10 +
'<td valign="top"></td>'#13#10 +
'</tr>'#13#10 +
'<tr>'#13#10 +
'<td><p style="margin-left: 40">%1:s'#13#10 +
'</td>'#13#10 +
'</tr>';
sExampleTable =
'<table width="100%%">'#13#10 +
'<tr>'#13#10 +
'<th align="left"><b><A HREF=%1:s Name=%0:s>%0:s</A>'#13#10 +
'</th>'#13#10 +
'</tr>'#13#10 +
'<tr>'#13#10 +
'<td valign="top"><p style="margin-left: 20">%2:s</td>'#13#10 +
'</tr>'#13#10 +
'<tr>'#13#10 +
'<td><p style="margin-left: 20">Components used by this example:</td>'#13#10 +
'<td valign="top"></td>'#13#10 +
'</tr>'#13#10 +
'<tr>'#13#10 +
'<td><p style="margin-left: 40">%3:s'#13#10 +
'</td>'#13#10 +
'</tr>'#13#10 +
'</table>';
sUsesComponentsAnchorTitle = 'Page Components';
sUsesComponentsAnchor = 'UsesComponents';
sUsesComponents =
'<hr><table width="100%%">'#13#10 +
'<tr>'#13#10 +
'<td><p style="margin-left: 0"><b><A Name=%1:s>%0:s</A></b><br>The following components were used to generate this page:</td>'#13#10 +
'<td valign="top"></td>'#13#10 +
'</tr>'#13#10 +
'<tr>'#13#10 +
'<td><p style="margin-left: 20">%2:s'#13#10 +
'</td>'#13#10 +
'</tr>'#13#10 +
'</table>';
sDescriptionAnchor = 'Description';
sDescriptionAnchorTitle = 'Page Description';
sDescription =
'<hr><table width="100%%">'#13#10 +
'<tr>'#13#10 +
'<td><p style="margin-left: 0"><b><A Name=%0:s>Page Description:</A></b></td>'#13#10 +
'<td valign="top"></td>'#13#10 +
'</tr>'#13#10 +
'<tr>'#13#10 +
'<td><p style="margin-left: 20">%1:s'#13#10 +
'</td>'#13#10 +
'</tr>'#13#10 +
'</table>';
type
TCustomPageElements = class(TMidasPageElements)
protected
Banner: string;
LocalLinks: TStrings;
List: string;
Description: string;
UsesComponents: string;
GlobalLinks: string;
Caption: string;
Instructions: string;
function FormatLocalLinks: string;
public
function BodyContent: string; override;
constructor Create;
destructor Destroy; override;
end;
TDescriptionPageElements = class(TCustomPageElements)
protected
function BodyContent: string; override;
end;
const
sBannerTag = 'BANNER';
sTitleTag = 'TITLE';
sLinksTag = 'LINKS';
sDescriptionTag = 'DESCRIPTION';
sUsesComponentsTag = 'USESCOMPONENTS';
sComponentsListTag = 'COMPONENTSLIST';
sExamplesListTag = 'EXAMPLESLIST';
sDumpRequestTag = 'DUMPREQUEST';
sComponentDetailsTag = 'COMPONENTDETAILS';
function ModulePath: string;
var
ModuleName: array[0..255] of Char;
begin
GetModuleFileName(hinstance, ModuleName, sizeof(ModuleName));
Result := ExtractFilePath(ModuleName);
end;
function QualifyFileName(var AFileName: string): Boolean;
begin
if (AFileName <> '') and (ExtractFilePath(AFileName) = '') then
begin
Result := True;
AFileName := ModulePath + AFileName;
end
else
Result := False;
end;
procedure Register;
begin
RegisterComponents('InternetExpress', [ { do not localize }
TInetXCenterProducer
]);
RegisterNonActiveX([TInetXCenterProducer], axrIncludeDescendants);
end;
{ TInetXCenterProducer }
function TInetXCenterProducer.GetDefaultTemplate: string;
begin
Result :=
'<HTML>'#13#10 +
'<HEAD>'#13#10 +
'<#TITLE>'#13#10 +
'</HEAD>'#13#10 +
'<BODY>'#13#10 +
'<#BODYELEMENTS>'#13#10 +
'</BODY>'#13#10 +
'</HTML>'#13#10;
end;
procedure TInetXCenterProducer.DoTagEvent(Tag: TTag; const TagString: string;
TagParams: TStrings; var ReplaceText: string);
begin
if (Tag = tgCustom) and (CompareText(TagString, sBannerTag) = 0) then
begin
ReplaceText := TCustomPageElements(PageElements).Banner;
Exit;
end
else if (Tag = tgCustom) and (CompareText(TagString, sTitleTag) = 0) then
begin
ReplaceText := GetTitleElement;
Exit;
end
else if (Tag = tgCustom) and (CompareText(TagString, sLinksTag) = 0) then
begin
ReplaceText := TCustomPageElements(PageElements).FormatLocalLinks;
Exit;
end
else if (Tag = tgCustom) and (CompareText(TagString, sDescriptionTag) = 0) then
begin
ReplaceText := TCustomPageElements(PageElements).Description;
Exit;
end
else if (Tag = tgCustom) and (CompareText(TagString, sComponentsListTag) = 0) then
begin
ReplaceText := TCustomPageElements(PageElements).List;
Exit;
end
else if (Tag = tgCustom) and (CompareText(TagString, sExamplesListTag) = 0) then
begin
ReplaceText := TCustomPageElements(PageElements).List;
Exit;
end
else if (Tag = tgCustom) and (CompareText(TagString, sDumpRequestTag) = 0) then
begin
ReplaceText := GetDumpRequest;
Exit;
end
else if (Tag = tgCustom) and (CompareText(TagString, sUsesComponentsTag) = 0) then
begin
ReplaceText := TCustomPageElements(PageElements).UsesComponents;
Exit;
end;
inherited DoTagEvent(Tag, TagString, TagParams, ReplaceText);
end;
function TInetXCenterProducer.GetBanner: string;
var
Path: string;
begin
Path := '';
//Result := Format(sBanner, [Caption]);
if Assigned(Dispatcher) and Assigned(Dispatcher.Request) then
if Dispatcher.Request.InternalPathInfo <> '' then
Path := PathInfoToRelativePath(Dispatcher.Request.InternalPathInfo);
Result := Format('<P><IMG SRC="%0:s%1:s" ALT="%2:s" WIDTH="%3:d" HEIGHT="%4:d"></P>',
[Path, sBannerFile, sBanner,
BannerWidth, BannerHeight]);
end;
function TInetXCenterProducer.FormatGlobalLinks(Topics: array of TTopicPage): string;
procedure Add(var Result: string; const Value: string);
begin
if Result <> '' then
Result := Result + '</BR>';
Result := Result + Value;
end;
var
I: Integer;
Producer: TInetXCenterProducer;
begin
Result := '';
for I := Low(Topics) to High(Topics) do
begin
Producer := FindTopicPage(Topics[I]);
if Assigned(Producer) then
begin
Add(Result, Format('<A HREF="%0:s">%1:s</A>'#13#10,
[Producer.HRef, Producer.LinkName]));
end;
end;
Result := Format('%s', [Result]);
end;
function TInetXCenterProducer.GetGlobalLinks: string;
begin
Result := FormatGlobalLinks([topHome, topComponents, topExamples,
topJavaScript, topXML, topAboutComponents]);
end;
function TInetXCenterProducer.GetTopicName: string;
begin
Result := 'Topic ' + Name;
end;
function TInetXCenterProducer.GetHREF: string;
begin
if Assigned(Dispatcher) and Assigned(Dispatcher.Request) then
begin
// Assume name is path
Result := Format('%0:s/%1:s',
[Dispatcher.Request.InternalScriptName, Name]);
end
else
Result := '';
end;
constructor TInetXCenterProducer.Create(AOwner: TComponent);
begin
inherited;
FDescription := TStringList.Create;
FInstructions := TStringList.Create;
FClassNames := TStringList.Create;
end;
destructor TInetXCenterProducer.Destroy;
begin
inherited;
FDescription.Free;
FInstructions.Free;
FClassNames.Free;
end;
procedure TInetXCenterProducer.SetDescription(
const Value: TStrings);
begin
FDescription.Assign(Value);
end;
resourcestring
sFileError = 'Could not access file %s';
function TInetXCenterProducer.GetDescription(ALinks: TStrings): string;
var
S: string;
FileStream: TFileStream;
FileName: string;
begin
if DescriptionFile <> '' then
begin
FileName := DescriptionFile;
if not (csDesigning in ComponentState) then
QualifyFileName(FileName);
try
FileStream := TFileStream.Create(FileName, fmOpenRead + fmShareDenyWrite);
try
with TStringStream.Create('') do
try
CopyFrom(FileStream, 0);
S := DataString;
finally
Free;
end;
finally
FileStream.Free;
end
except
S := Format(sFileError, [FileName]);
end;
end
else
S := Description.Text;
case PageLayout of
plStandard:
if Length(S) > 0 then
begin
ALinks.Add(Format('%s=%s', [sDescriptionAnchorTitle, sDescriptionAnchor]));
Result := Format(sDescription,
[sDescriptionAnchor, S])
end
else
Result := '';
else
Result := S;
end;
end;
function ComponentLink(ComponentListProducer: TInetXCenterProducer;
AClassName: string): string;
var
HRef: string;
begin
if Assigned(ComponentListProducer) then
HRef := ComponentListProducer.HRef;
Result := Format('<A HREF="%0:s?ClassName=%1:s">%1:s</A>'#13#10,
[HRef, AClassName]);
end;
function TInetXCenterProducer.GetUsesComponents(ALinks: TStrings): string;
var
ComponentsPage: TInetXCenterProducer;
procedure AddComponent(var Result: string);
begin
if Result <> '' then Result := Result + ', ';
Result := Result + ComponentLink(ComponentsPage, ComponentsInfoIntf.ClassName);
end;
var
Components: string;
begin
Result := '';
if not Assigned(ComponentsInfoIntf) then Exit;
ComponentsPage := FindTopicPage(topComponents);
GetClassNames;
ComponentsInfoIntf.ClearFilter;
ComponentsInfoIntf.Reset;
while ComponentsInfoIntf.Next do
begin
if ClassNames.IndexOf(ComponentsInfoIntf.ClassName) <> -1 then
AddComponent(Components);
end;
if Components <> '' then
begin
ALinks.Add(Format('%s=%s', [sUsesComponentsAnchorTitle, sUsesComponentsAnchor]));
Result := Format(sUsesComponents, [sUsesComponentsAnchorTitle, sUsesComponentsAnchor, Components]);
end;
end;
procedure TInetXCenterProducer.FindComponents;
procedure AddComponent(AComponent: TComponent);
begin
if ClassNames.IndexOf(AComponent.ClassName) = -1 then
ClassNames.Add(AComponent.ClassName);
end;
procedure TraverseSubComponents(AContainer: TComponent);
var
WebComponentContainer: IWebComponentContainer;
I: Integer;
ScriptComponent: IScriptComponent;
SubComponents: TObject;
Component: TComponent;
begin
if AContainer.GetInterface(IScriptComponent, ScriptComponent) then
begin
SubComponents := ScriptComponent.SubComponents;
if Assigned(SubComponents) and SubComponents.GetInterface(IWebComponentContainer, WebComponentContainer) then
begin
for I := 0 to WebComponentContainer.ComponentCount - 1 do
begin
Component := WebComponentContainer.Components[I];
AddComponent(Component);
if Component.GetInterface(IScriptComponent, ScriptComponent) then
TraverseSubComponents(Component);
end;
end;
end;
end;
var
I: Integer;
begin
//AddComponent(Self);
if (ClassNames.Count = 0) or
(csDesigning in ComponentState) then
begin
ClassNames.Clear;
for I := 0 to Self.WebPageItems.Count - 1 do
begin
AddComponent(WebPageItems.WebComponents[I]);
TraverseSubComponents(WebPageItems.WebComponents[I]);
end;
end;
end;
procedure TInetXCenterProducer.GetClassNames;
begin
FindComponents;
end;
function TInetXCenterProducer.FindTopicPage(ATopic: TTopicPage): TInetXCenterProducer;
var
I: Integer;
begin
for I := 0 to Owner.ComponentCount - 1 do
begin
if (Owner.Components[I] is TInetXCenterProducer) then
begin
Result := TInetXCenterProducer(Owner.Components[I]);
if Result.TopicPage = ATopic then
Exit;
end;
end;
Result := nil;
end;
function ExampleLink(ExampleListProducer, ExampleProducer: TInetXCenterProducer): string;
begin
(* This code causes jump to example description
var
HRef: string;
if Assigned(ExampleListProducer) then
HRef := ExampleListProducer.HRef;
Result := Format('<A HREF="%0:s?Example=%1:s">%1:s</A>'#13#10,
[HRef, ExampleProducer.LinkName]);
*)
// Run example
Result := Format('<A HREF="%0:s">%1:s</A>'#13#10,
[ExampleProducer.HRef, ExampleProducer.LinkName]);
end;
function TInetXCenterProducer.GetSelectClassName: string;
begin
Result := '';
if Assigned(Dispatcher) and Assigned(Dispatcher.Request) then
with Dispatcher.Request do
begin
Result := QueryFields.Values['ClassName'];
if (Result <> '') and (Copy(Result, 1,1) <> 'T') then
Result := 'T' + Result;
end;
end;
function TInetXCenterProducer.GetComponentDetails(ALinks: TStrings): string;
var
SelectClassName: string;
function AddComponent(PrimaryExample, OtherExamples: string): string;
begin
if PrimaryExample <> '' then
PrimaryExample := Format(sComponentExamples,
[sPrimaryExampleTitle, PrimaryExample]);
if OtherExamples <> '' then
if PrimaryExample <> '' then
OtherExamples := Format(sComponentExamples,
[sOtherExamplesTitle, OtherExamples])
else
OtherExamples := Format(sComponentExamples,
[sExamplesTitle, OtherExamples]);
Result := Format(sComponentTable,
[ComponentsInfoIntf.ClassName,
ComponentsInfoIntf.Description, PrimaryExample, OtherExamples]);
end;
function IncludeComponent: Boolean;
begin
Result := (SelectClassName = '') or
(ComponentsInfoIntf.ClassName = SelectClassName);
end;
var
Producer, ExamplesList: TInetXCenterProducer;
I: Integer;
PrimaryExample, OtherExamples: String;
Component: TComponent;
Producers: TList;
begin
Result := '';
if not Assigned(ComponentsInfoIntf) then Exit;
ExamplesList := FindTopicPage(topExamples);
Producers := TList.Create;
try
for I := 0 to Owner.ComponentCount - 1 do
begin
if (Owner.Components[I] is TInetXCenterProducer) then
begin
Producer := TInetXCenterProducer(Owner.Components[I]);
if Producer.IsExample then
begin
Producer.GetClassNames;
Producers.Add(Producer);
end;
end;
end;
SelectClassName := GetSelectClassName;
ComponentsInfoIntf.Reset;
while ComponentsInfoIntf.Next do
begin
if SelectClassName <> '' then
ComponentsInfoIntf.LocateClassName(SelectClassName);
PrimaryExample := '';
if ComponentsInfoIntf.Example <> '' then
begin
Component := Owner.FindComponent(ComponentsInfoIntf.Example);
if Assigned(Component) and (Component is TInetXCenterProducer) then
begin
Producers.Remove(Component);
PrimaryExample := ExampleLink(ExamplesList, TInetXCenterProducer(Component));
end;
end;
OtherExamples := '';
for I := 0 to Producers.Count - 1 do
begin
Producer := TInetXCenterProducer(Producers[I]);
if Producer.ClassNames.IndexOf(ComponentsInfoIntf.ClassName) <> -1 then
begin
if OtherExamples <> '' then
OtherExamples := OtherExamples + ', ';
OtherExamples := OtherExamples + ExampleLink(ExamplesList, Producer);
end;
end;
Result := Result + AddComponent(PrimaryExample, OtherExamples);
if SelectClassName <> '' then
Break;
end;
finally
Producers.Free;
end;
end;
function TInetXCenterProducer.GetExamplesList(ALinks: TStrings): string;
var
List: TList;
begin
List := TList.Create;
try
GetExampleProducers(List);
if GetSelectExample = '' then
Result := { GetExampleSummary(List, ALinks) + } GetExampleDetails(List, ALinks)
else
Result := GetExampleDetails(List, ALinks);
finally
List.Free;
end;
end;
function TInetXCenterProducer.GetSelectExample: string;
begin
Result := '';
if Assigned(Dispatcher) and Assigned(Dispatcher.Request) then
with Dispatcher.Request do
Result := QueryFields.Values['Example'];
end;
function CompareExampleProducer(Item1, Item2: Pointer): Integer;
begin
Result := CompareText(TInetXCenterProducer(Item1).LinkName,
TInetXCenterProducer(Item2).LinkName);
end;
procedure TInetXCenterProducer.GetExampleProducers(AList: TList);
var
SelectName: string;
function IncludeExample(Producer: TInetXCenterProducer): Boolean;
begin
Result := (SelectName = '') or
(Producer.LinkName = SelectName);
end;
var
Producer: TInetXCenterProducer;
I: Integer;
begin
SelectName := GetSelectExample;
for I := 0 to Owner.ComponentCount - 1 do
begin
if (Owner.Components[I] is TInetXCenterProducer) then
begin
Producer := TInetXCenterProducer(Owner.Components[I]);
if Producer.IsExample then
if IncludeExample(Producer) then
AList.Add(Producer);
end;
end;
AList.Sort(CompareExampleProducer);
end;
function TInetXCenterProducer.GetExampleDetails(AProducers: TList; ALinks: TStrings): string;
var
ComponentsPage: TInetXCenterProducer;
SelectName: string;
function AddExample(Producer: TInetXCenterProducer; Components: string): string;
var
Description: string;
begin
Description := Producer.Description.Text;
if Description = '' then
Description := ' ';
Result := Format(sExampleTable,
[Producer.LinkName, Producer.HRef,
Description, Components]);
end;
procedure AddComponent(var Result: string);
begin
if Result <> '' then Result := Result + ', ';
Result := Result + ComponentLink(ComponentsPage, ComponentsInfoIntf.ClassName);
end;
var
Producer: TInetXCenterProducer;
I: Integer;
Components: String;
begin
if Assigned(Dispatcher) and Assigned(Dispatcher.Request) then
with Dispatcher.Request do
SelectName := QueryFields.Values['Example'];
ComponentsPage := FindTopicPage(topComponents);
for I := 0 to AProducers.Count - 1 do
begin
Producer := TInetXCenterProducer(AProducers[I]);
Components := '';
if Assigned(ComponentsInfoIntf) then
begin
Producer.GetClassNames;
ComponentsInfoIntf.Reset;
while ComponentsInfoIntf.Next do
if Producer.ClassNames.IndexOf(ComponentsInfoIntf.ClassName) <> -1 then
AddComponent(Components);
end;
Result := Result + AddExample(Producer, Components);
end;
end;
procedure TInetXCenterProducer.AddTopicLinks(ALinks: TStrings);
procedure Add(Producer: TInetXCenterProducer);
begin
if Assigned(Producer) then
ALinks.AddObject('', Producer);
end;
begin
case TopicPage of
topComponents:
Add(FindTopicPage(topComponentsFilter));
end;
end;
function TInetXCenterProducer.CreatePageElements: TMidasPageElements;
var
Elements: TCustomPageElements;
begin
case PageLayout of
plDescription: Elements := TDescriptionPageElements.Create;
else
Elements := TCustomPageElements.Create;
end;
AddTopicLinks(Elements.LocalLinks);
Elements.Description := GetDescription(Elements.LocalLinks);
case TopicPage of
topComponents,
topComponentsFilter: Elements.List := GetComponentsList(Elements.LocalLinks);
topExamples: Elements.List := GetExamplesList(Elements.LocalLinks);
end;
Elements.UsesComponents := GetUsesComponents(Elements.LocalLinks);
Elements.Banner := GetBanner;
Elements.GlobalLinks := GetGlobalLinks;
Elements.Caption := Caption;
Elements.Instructions := Instructions.Text;
Result := Elements;
end;
function TInetXCenterProducer.GetCaption: string;
begin
Result := '';
case TopicPage of
topComponents:
Result := GetSelectClassName;
topExamples:
Result := GetSelectExample;
end;
if Result = '' then
Result := FCaption;
if Result = '' then
Result := Name;
end;
function TInetXCenterProducer.GetTitle: string;
begin
if FTitle = '' then
Result := DefaultTitle
else
Result := FTitle;
end;
function TInetXCenterProducer.DefaultTitle: string;
var
F: string;
begin
if IsExample then
F := sTitleExample
else
F := sTitle;
if FCaption <> '' then
Result := Format(F, [FCaption])
else
Result := Format(F, [Name])
end;
function TInetXCenterProducer.GetTitleElement: string;
begin
Result := Format('<TITLE>%s</TITLE>', [Title]);
end;
function TInetXCenterProducer.GetDumpRequest: string;
function AddRow(const Name: string; Value: string): string;
begin
if Trim(Value) = '' then
Value := ' ';
Result := Format('<tr><td>%s</td><td>%s</td></tr>', [Name, Value]);
end;
function FormatStrings(Value: TStrings): string;
var
I: Integer;
begin
Result := '';
if Value.Count > 0 then
begin
for I := 0 to Value.Count - 1 do
Result := Result + AddRow(Value.Names[I], Value.Values[Value.Names[I]]);
Result := Format('<table border=1 >%s</table>', [Result]);
end;
end;
function FormatString(const Value: string): string;
begin
Result := '';
if Value <> '' then
begin
Result := Format('%s'#13#10, [Value]);
end;
end;
begin
if Assigned(Dispatcher) and Assigned(Dispatcher.Request) then
with Dispatcher do
begin
Result := Result + AddRow('ContentFields',
FormatStrings(Request.ContentFields));
Result := Result + AddRow('QueryFields',
FormatStrings(Request.QueryFields));
Result := Result + AddRow('Query',
FormatString(Request.Query));
Result := Result + AddRow('PathInfo',
FormatString(Request.InternalPathInfo));
Result := Result + AddRow('ScriptName',
FormatString(Request.InternalScriptName));
Result := Result + AddRow('Referer',
FormatString(Request.Referer));
Result := Result + AddRow('UserAgent',
FormatString(Request.UserAgent));
Result := Format(
'<table border="1" width="100%%">'#13#10 +
'<tr>'#13#10 +
'<th align="center" colspan=2>Request Fields</td>'#13#10 +
'</tr>'#13#10 +
'%s' +
'</table>'#13#10, [Result]);
end;
end;
function TInetXCenterProducer.IsExample: Boolean;
begin
Result := PageExampleCategories * PageCategories <> [];
end;
function TInetXCenterProducer.GetComponentsInfo: IComponentsInfo;
begin
if not Assigned(FComponentsInfoIntf) and
Assigned(FComponentsInfo) then
FComponentsInfoIntf := TComponentsInfo.Create(FComponentsInfo);
Result := FComponentsInfoIntf;
end;
procedure TInetXCenterProducer.SetComponentsInfo(
const Value: TDataSet);
begin
FComponentsInfo := Value;
FComponentsInfoIntf := nil;
end;
procedure TInetXCenterProducer.SetCaption(const Value: string);
begin
if Value = Name then
FCaption := ''
else
FCaption := Value;
end;
procedure TInetXCenterProducer.SetTitle(const Value: string);
begin
if Value = DefaultTitle then
FTitle := ''
else
FTitle := Value;
end;
function TInetXCenterProducer.GetLinkName: string;
begin
if FLinkName = '' then
if FCaption <> '' then
Result := FCaption
else
Result := Name
else
Result := FLinkName;
end;
procedure TInetXCenterProducer.SetLinkName(const Value: string);
begin
if (Value = FCaption) or (Value = Name) then
FLinkName := ''
else
FLinkName := Value;
end;
//{$DEFINE DEBUG}
function TInetXCenterProducer.GetComponentsList(ALinks: TStrings): string;
begin
if GetSelectClassName = '' then
Result := GetComponentSummary(ALinks) + GetComponentDetails(ALinks)
else
Result := GetComponentDetails(ALinks);
{$IFDEF DEBUG}
Result := Format('<p><b>ComponentsInfoIntf.Filter=%s<p>',
[ComponentsInfoIntf.GetFilter]) + Result;
{$ENDIF}
end;
resourcestring
sComponentSummary =
'<tr><th align="left">%0:s</th></tr>'#13#10 +
'<tr><td valign="top"><p style="margin-left: 20">%1:s</td></tr>';
sFormGroup = 'Forms';
sGroupGroup = 'Groups';
sInputGroup = 'Inputs';
sButtonGroup = 'Buttons';
sSpecialGroup = 'Special';
sUnknownGroup = 'Other';
function TInetXCenterProducer.GetComponentSummary(ALinks: TStrings): string;
type
TGroup = (gpForm, gpGroup, gpInput, gpButton, gpSpecial, gpUnknown);
const
GroupKeys: array[TGroup] of string =
('Form', 'Group', 'Input', 'Button', 'Special', '');
var
Groups: array[TGroup] of string;
procedure AddComponent;
var
G: TGroup;
begin
for G := Low(TGroup) to High(TGroup) do
if CompareText(GroupKeys[G], ComponentsInfoIntf.GetType) = 0 then
begin
if Groups[G] <> '' then Groups[G] := Groups[G] + ', ';
Groups[G] := Groups[G] + Format('<A HREF=#%0:s>%0:s</A>',
[ComponentsInfoIntf.ClassName]);
break;
end;
end;
var
G: TGroup;
Title: string;
begin
Result := '';
if not Assigned(ComponentsInfoIntf) then Exit;
ComponentsInfoIntf.Reset;
while ComponentsInfoIntf.Next do
begin
AddComponent;
end;
Result := '';
for G := Low(Groups) to High(Groups) do
begin
if Groups[G] <> '' then
begin
case G of
gpForm: Title := sFormGroup;
gpGroup: Title := sGroupGroup;
gpButton: Title := sButtonGroup;
gpSpecial: Title := sSpecialGroup;
gpUnknown: Title := sUnknownGroup;
gpInput: Title := sInputGroup;
else
Assert(False, 'Unknown group');
end;
Result := Result + Format(sComponentSummary, [Title,
Groups[G]]);
end;
end;
if Result <> '' then
Result := Format('<table width="100%%">%s</table><hr>', [Result]);
end;
function TInetXCenterProducer.GetExampleSummary(AProducers: TList;
ALinks: TStrings): string;
var
Producer: TInetXCenterProducer;
procedure AddExample(var Result: string);
begin
if Result <> '' then Result := Result + ', ';
Result := Result + Format('<A HREF=#%0:s>%0:s</A>',
[Producer.LinkName]);
end;
var
I: Integer;
begin
Result := '';
for I := 0 to AProducers.Count - 1 do
begin
Producer := AProducers[I];
AddExample(Result);
end;
end;
procedure TInetXCenterProducer.SetInstructions(const Value: TStrings);
begin
FInstructions.Assign(Value);
end;
{ TDescriptionPageElements }
function TDescriptionPageElements.BodyContent: string;
begin
Result := inherited BodyContent;
end;
{ TCustomPageElements }
resourcestring
sStandardPageLayout =
'<Table >'#13#10 +
'<TR><TD VALIGN="CENTER" ALIGN="LEFT" WIDTH="%0:d">%1:s</TD><TD VALIGN="TOP" >%2:s</TD></TR>'#13#10 +
'<TR><TD VALIGN="TOP" ALIGN="LEFT" WIDTH="%0:d">%3:s</TD><TD VALIGN="TOP" >%4:s</TD></TR></TABLE>';
function TCustomPageElements.BodyContent: string;
begin
Result :=
IncludesContent +
StylesContent +
WarningsContent +
Format(sStandardPageLayout,
[{Width} 140,
{Page Caption}Format('<p><b><i>%s</p>',[ Caption]),
{Page Banner} Banner,
{Links}Format('<p>%s</p><p>%s</p>', [GlobalLinks, FormatLocalLinks]),
{ Body }
'<br>'+
Instructions +
FormsContent +
List + // Custom
Description + // Custom
UsesComponents // Custom
]) +
ScriptContent;
end;
constructor TCustomPageElements.Create;
begin
inherited;
LocalLinks := TStringList.Create;
end;
destructor TCustomPageElements.Destroy;
begin
inherited;
LocalLinks.Free;
end;
function TCustomPageElements.FormatLocalLinks: string;
procedure Add(HRef, LinkName: string);
var
Link: string;
begin
Link := Format('<A HREF="%0:s">%1:s</A>'#13#10,
[HRef, LinkName]);
if Result <> '' then
Result := Result + '</BR>';
Result := Result + Link;
end;
var
I: Integer;
begin
Result := '';
for I := 0 to LocalLinks.Count - 1 do
begin
if Assigned(LocalLinks.Objects[I]) then
with LocalLinks.Objects[I] as TInetXCenterProducer do
Add(HREF, LinkName)
else
if LocalLinks.Values[LocalLinks.Names[I]] <> '' then
Add('#'+LocalLinks.Values[LocalLinks.Names[I]], LocalLinks.Names[I])
else
Add('#'+LocalLinks[I], LocalLinks[I]);
end;
end;
{ TComponentsInfo }
function TComponentsInfo.ClassName: string;
begin
Result := FDataSet.FieldByName('ClassName').AsString;
end;
constructor TComponentsInfo.Create(ADataSet: TDataSet);
var
F: string;
begin
inherited Create;
FDataSet := ADataSet;
if not (csDesigning in ADataSet.ComponentState) then
begin
if ADataSet is TClientDataSet then
with TClientDataSet(ADataSet) do
begin
F := FileName;
if QualifyFileName(F) then
begin
ADataSet.Active := False;
FileName := F;
end;
end;
end;
Reset;
end;
procedure TComponentsInfo.Reset;
begin
FDataSet.Active := True;
FDataSet.First;
FReset := True;
end;
function TComponentsInfo.Next: Boolean;
begin
if (not FReset) and (not Eof) then
FDataSet.Next;
FReset := False;
Result := not Eof;
end;
function TComponentsInfo.Eof: Boolean;
begin
Result := FDataSet.Eof;
end;
function TComponentsInfo.ShortDescription: string;
begin
Result := FDataSet.FieldByName('ShortDescription').AsString;
end;
function TComponentsInfo.Usage: string;
begin
Result := FDataSet.FieldByName('Usage').AsString;
end;
function TComponentsInfo.Description: string;
begin
Result := FDataSet.FieldByName('Description').AsString;
if Trim(Result) = '' then
Result := FDataSet.FieldByName('ShortDescription').AsString;
end;
function TComponentsInfo.FieldByName(FieldName: string): TField;
begin
Result := FDataSet.FieldByName(FieldName);
end;
function TComponentsInfo.GetType: string;
begin
Result := FDataSet.FieldByName('Type').AsString;
end;
function TComponentsInfo.Package: string;
begin
Result := FDataSet.FieldByName('Package').AsString;
end;
procedure TComponentsInfo.SetFilter(PackageFilter, UsageFilter, TypeFilter: string);
procedure AddFilter(var S: string; Value: string);
begin
if S <> '' then
S := S + ' and ';
S := S + Value;
end;
function CreateFilter: string;
begin
Result := '';
if PackageFilter <> 'All' then
if PackageFilter = 'Custom' then
AddFilter(Result,
'(Package <> ''Standard'') and (Usage <> '''')')
else
AddFilter(Result,
Format('Package = ''%s''', [PackageFilter]));
if UsageFilter <> 'All' then
begin
if (UsageFilter = 'XMLData') or (UsageFilter = 'Query') then
AddFilter(Result,
Format('(Usage = ''%s'' or Usage = ''Layout'')', [UsageFilter]))
else
AddFilter(Result,
Format('Usage = ''%s''', [UsageFilter]));
end;
if TypeFilter <> 'All' then
AddFilter(Result,
Format('Type = ''%s''', [TypeFilter]));
end;
begin
FDataSet.Filter := CreateFilter;
FDataSet.Filtered := True;
end;
function TComponentsInfo.Example: string;
begin
Result := FDataSet.FieldByName('Example').AsString;
end;
procedure TComponentsInfo.LocateClassName(AClassName: string);
begin
FDataSet.Locate('ClassName', AClassName, []);
end;
procedure TComponentsInfo.ClearFilter;
begin
FDataSet.Filtered := False;
FDataSet.Filter := '';
end;
function TComponentsInfo.GetFilter: string;
begin
Result := FDataSet.Filter;
end;
initialization
finalization
UnRegisterWebComponents([
TInetXCenterProducer]);
end.
|
{ Trapping runtime errors
The Trap unit allows you to trap runtime errors, so a runtime
error will not abort the program, but pass the control back to a
point within the program.
The usage is simple. The TrapExec procedure can be called with a
function (p) as an argument. p must take a Boolean argument. p
will immediately be called with False given as its argument. When
a runtime error would otherwise be caused while p is active, p
will instead be called again with True as its argument. After p
returns, runtime error trapping ends.
When the program terminates (e.g. by reaching its end or by a Halt
statement) and a runtime error was trapped during the run, Trap
will set the ExitCode and ErrorAddr variables to indicate the
trapped error.
Notes:
- After trapping a runtime error, your program might not be in a
stable state. If the runtime error was a "minor" one (such as a
range checking or arithmetic error), it should not be a problem.
But if you, e.g., write a larger application and use Trap to
prevent a sudden abort caused by an unexpected runtime error,
you should make the program terminate regularly as soon as
possible after a trapped error (perhaps by telling the user to
save the data, then terminate the program and report the bug to
you).
- Since the trapping mechanism *jumps* back, it has all the
negative effects that a (non-local!) `goto' can have! You should
be aware of the consequences of all active procedures being
terminated at an arbitrary point!
- Nested traps are supported, i.e. you can call TrapExec again
within a routine called by another TrapExec instance. Runtime
errors trapped within the inner TrapExec invocation will be
trapped by the inner TrapExec, while runtime errors trapped
after its termination will be trapped by the outer TrapExec
again.
Copyright (C) 1996-2005 Free Software Foundation, Inc.
Author: Frank Heckenbach <frank@pascal.gnu.de>
This file is part of GNU Pascal.
GNU Pascal is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2, or (at your
option) any later version.
GNU Pascal is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030303}
{$error This unit requires GPC release 20030303 or newer.}
{$endif}
unit Trap;
interface
uses GPC;
var
TrappedExitCode: Integer = 0;
TrappedErrorAddr: Pointer = nil;
TrappedErrorMessageString: TString = '';
{ Trap runtime errors. See the comment at the top. }
procedure TrapExec (procedure p (Trapped: Boolean));
{ Forget about saved errors from the innermost TrapExec instance. }
procedure TrapReset;
implementation
{ @@ Implementation in pure Pascal without need of trapc.c. Fails under
Solaris with gcc-2.95.x (backend bug); 2.8.1 and 3.x seem to be OK.
The old code can probably removed after the transition to 3.x.
Nonlocal `goto's still fail with gcc-3.x on Linux/S390 and
Mac OS X. :-( `--longjmp-all-nonlocal-labels' helps. }
{.$define NEW_TRAP}
{$ifdef NEW_TRAP}
var
TrapJump: ^procedure = nil;
{$else}
{$L trapc.c}
procedure DoSetJmp (procedure p (Trapped: Boolean)); external name 'dosetjmp';
procedure DoLongJmp; external name 'dolongjmp';
{$endif}
var
TrapCount: Integer = 0;
procedure TrapExit;
begin
if ErrorAddr <> nil then
begin
if TrapCount <> 0 then
begin
TrappedExitCode := ExitCode;
TrappedErrorAddr := ErrorAddr;
TrappedErrorMessageString := ErrorMessageString;
ErrorAddr := nil;
ExitCode := 0;
ErrorMessageString := '';
{$ifdef NEW_TRAP}
TrapJump^
{$else}
DoLongJmp
{$endif}
end
end
else
if TrappedErrorAddr <> nil then
begin
ExitCode := TrappedExitCode;
ErrorAddr := TrappedErrorAddr;
ErrorMessageString := TrappedErrorMessageString;
TrappedErrorAddr := nil
end
end;
procedure TrapExec (procedure p (Trapped: Boolean));
var
SavedTrappedExitCode: Integer { @@ } = 0;
SavedTrappedErrorAddr: Pointer { @@ } = nil;
SavedTrappedErrorMessageString: TString;
{$ifdef NEW_TRAP}
SavedTrapJump: ^procedure { @@ } = nil;
Trapped: Boolean;
label TrapLabel;
procedure DoTrapJump;
begin
Trapped := True;
goto TrapLabel
end;
{$else}
procedure DoCall (Trapped: Boolean);
begin
AtExit (TrapExit);
p (Trapped)
end;
{$endif}
begin
SavedTrappedExitCode := TrappedExitCode;
SavedTrappedErrorAddr := TrappedErrorAddr;
SavedTrappedErrorMessageString := TrappedErrorMessageString;
Inc (TrapCount);
{$ifdef NEW_TRAP}
SavedTrapJump := TrapJump;
TrapJump := @DoTrapJump;
Trapped := False;
TrapLabel:
AtExit (TrapExit);
p (Trapped);
TrapJump := SavedTrapJump;
{$else}
DoSetJmp (DoCall);
{$endif}
Dec (TrapCount);
if TrappedErrorAddr = nil then
begin
TrappedExitCode := SavedTrappedExitCode;
TrappedErrorAddr := SavedTrappedErrorAddr;
TrappedErrorMessageString := SavedTrappedErrorMessageString
end;
AtExit (TrapExit)
end;
procedure TrapReset;
begin
TrappedExitCode := 0;
TrappedErrorAddr := nil;
TrappedErrorMessageString := ''
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
/// <summary>Unit that holds common functionality relative to a generic URL Client (HTTP, FTP, ...) </summary>
unit System.Net.URLClient;
interface
{$SCOPEDENUMS ON}
uses
System.Classes, System.Generics.Defaults, System.Generics.Collections, System.SysUtils, System.Types;
{$IFDEF MSWINDOWS}
{$HPPEMIT '#pragma comment(lib, "winhttp")'}
{$HPPEMIT '#pragma comment(lib, "crypt32")'}
{$ENDIF}
type
/// <summary>Generic Exception class for System.Net exceptions</summary>
ENetException = class(Exception);
/// <summary>Exception class for Credentials related exceptions.</summary>
ENetCredentialException = class(ENetException);
/// <summary>Exception class for URI related exceptions.</summary>
ENetURIException = class(ENetException);
/// <summary>Exception class for URI related exceptions.</summary>
ENetURIClientException = class(ENetException);
/// <summary>Exception class for URI related exceptions.</summary>
ENetURIRequestException = class(ENetException);
/// <summary>Exception class for URI related exceptions.</summary>
ENetURIResponseException = class(ENetException);
// -------------------------------------------------------------------------------- //
type
/// <summary>Record to manage a Name-Value pair</summary>
TNameValuePair = record
/// <summary>Name part of a Name-Value pair</summary>
Name: string;
/// <summary>Value part of a Name-Value pair</summary>
Value: string;
/// <summary>Initializes a Name-Value pair</summary>
constructor Create(const AName, AValue: string);
end;
TNameValueArray = TArray<TNameValuePair>;
//TNameValueArray = array of TNameValuePair;
/// <summary>Alias for a URI Parameter</summary>
TURIParameter = TNameValuePair;
/// <summary> Array of URI Parameters. </summary>
TURIParameters = TNameValueArray;
// Forwarded class declaration;
TURLClient = class;
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
/// <summary>Record type to help compose and decompose a URI from/into its parts. </summary>
/// <remarks>It is a record to ease its use and avoid manage its life cycle.</remarks>
TURI = record
private
FScheme: string;
FUsername: string;
FPassword: string;
FHost: string;
FPort: Integer;
FPath: string;
FQuery: string;
FParams: TURIParameters;
FFragment: string;
private type
TEncType = (URLEnc, FormEnc);
private type
TSchemeDecomposeProc = procedure(const AURIStr: string;
Pos, Limit, SlashCount: Integer) of object;
private
procedure DecomposeBaseScheme(const AURIStr: string;
Pos, Limit, SlashCount: Integer);
procedure DecomposeNoAuthorityScheme(const AURIStr: string;
Pos, Limit, SlashCount: Integer);
private
function IsMailtoScheme: Boolean;
function IsSchemeNoAuthority: Boolean;
function IsValidPort: Boolean;
function GetDefaultPort(const AScheme: string): Integer;
procedure ParseParams(Encode: Boolean = False);
function FindParameterIndex(const AName: string): Integer;
function GetParameter(const I: Integer): TURIParameter;
function GetParameterByName(const AName: string): string;
procedure SetParameter(const I: Integer; const Value: TURIParameter);
procedure SetParameterByName(const AName: string; const Value: string);
function GetQuery: string;
/// <summary>Decompose a string into its parts</summary>
procedure DecomposeURI(const AURIStr: string; ARaiseNoSchema: Boolean);
procedure SetScheme(const Value: string);
procedure SetUserName(const Value: string);
procedure SetPassword(const Value: string);
procedure SetHost(const Value: string);
procedure SetPath(const Value: string);
procedure SetQuery(const Value: string);
procedure SetParams(const Value: TURIParameters);
public const
SCHEME_HTTP = 'http'; // DO NOT LOCALIZE
SCHEME_HTTPS = 'https'; // DO NOT LOCALIZE
SCHEME_MAILTO = 'mailto'; // DO NOT LOCALIZE
SCHEME_NEWS = 'news'; // DO NOT LOCALIZE
SCHEME_TEL = 'tel'; // DO NOT LOCALIZE
SCHEME_URN = 'urn'; // DO NOT LOCALIZE
public
/// <summary>Initializes a TURI from a string</summary>
constructor Create(const AURIStr: string);
/// <summary>Generate a urlencoded string from the URI parts</summary>
/// <returns>A string representing the URI</returns>
function ToString: string;
/// <summary>Generate a URI from the string parts</summary>
procedure ComposeURI(const AScheme, AUsername, APassword, AHostname: string; APort: Integer; const APath: string;
const AParams: TURIParameters; const AFragment: string);
/// <summary>Adds a Parameter to the URI</summary>
procedure AddParameter(const AName, AValue: string); overload;
procedure AddParameter(const AParameter: TURIParameter); overload; inline;
/// <summary>Removes a Parameter from the URI</summary>
procedure DeleteParameter(AIndex: Integer); overload;
procedure DeleteParameter(const AName: string); overload;
/// <summary>URL percent encoding of a text.</summary>
/// <param name="AValue">The text to be encoded.</param>
/// <param name="SpacesAsPlus">If true the spaces are translated as '+' instead %20.</param>
class function URLEncode(const AValue: string; SpacesAsPlus: Boolean = False): string; static; deprecated 'Use TNetEncoding.URL.Encode';
/// <summary>URL percent decoding of a text.</summary>
/// <param name="AValue">The text to be decoded.</param>
/// <param name="PlusAsSpaces">If true the character '+' is translated as space.</param>
class function URLDecode(const AValue: string; PlusAsSpaces: Boolean = False): string; static; deprecated 'Use TNetEncoding.URL.Decode';
function Encode: string;
/// <summary>Converts a Unicode hostname into it's ASCII equivalent using IDNA</summary>
class function UnicodeToIDNA(const AHostName: string): string; static;
/// <summary>Converts a IDNA encoded ASCII hostname into it's Unicode equivalent</summary>
class function IDNAToUnicode(const AHostName: string): string; static;
/// <summary>Normalize a relative path using a given URI as base.</summary>
/// <remarks>This function will remove '.' and '..' from path and returns an absolute URL.</remarks>
class function PathRelativeToAbs(const RelPath: string; const Base: TURI): string; static;
/// <summary>
/// Clean up/fix the given URL. Add a possibly missing protocol (http is default), remove trailing white spaces.
/// Ensures no trailing slash exists.
/// </summary>
/// <example>
/// <see href="http://www.example.com">www.example.com</see> -> <see href="http://www.example.com/" /><br />
/// <see href="http://www.example.com/some/path">www.example.com/some/path</see> ->
/// <see href="http://www.example.com/some/path" />
/// </example>
class function FixupForREST(const AURL: string): string; static;
/// <summary>Property to obtain/set a parameter by it's index</summary>
property Parameter[const I: Integer]: TURIParameter read GetParameter write SetParameter;
/// <summary>Property to obtain/set a parameter value by it's Name</summary>
property ParameterByName[const AName: string]: string read GetParameterByName write SetParameterByName;
/// <summary>Scheme part of the URI.</summary>
property Scheme: string read FScheme write SetScheme;
/// <summary>Username part of the URI.</summary>
property Username: string read FUsername write SetUserName;
/// <summary>Password part of the URI.</summary>
property Password: string read FPassword write SetPassword;
/// <summary>Host part of the URI.</summary>
property Host: string read FHost write SetHost;
/// <summary>Port part of the URI.</summary>
property Port: Integer read FPort write FPort;
/// <summary>Path part of the URI.</summary>
property Path: string read FPath write SetPath;
/// <summary>Query part of the URI.</summary>
property Query: string read FQuery write SetQuery;
/// <summary>Params part of the URI.</summary>
property Params: TURIParameters read FParams write SetParams;
/// <summary>Fragment part of the URI.</summary>
property Fragment: string read FFragment write FFragment;
end;
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
/// <summary>Enumeration defining different persistences of a credential</summary>
TAuthPersistenceType = (Request, Client);
/// <summary>Different types of authentication targets for the credential</summary>
TAuthTargetType = (Proxy, Server);
/// <summary>Storage for credentials used in TURLClient and TURLRequest</summary>
TCredentialsStorage = class
public type
/// <summary>Different types of Authorization Schemes</summary>
TAuthSchemeType = (Basic, Digest, NTLM, Negotiate);
/// <summary>Callback to request user credentials when server asks for them</summary>
TCredentialAuthCallback = procedure(const Sender: TObject; AnAuthTarget: TAuthTargetType;
const ARealm, AURL: string; var AUserName, APassword: string; var AbortAuth: Boolean;
var Persistence: TAuthPersistenceType);
/// <summary>Callback to request user credentials when server asks for them</summary>
TCredentialAuthEvent = procedure(const Sender: TObject; AnAuthTarget: TAuthTargetType;
const ARealm, AURL: string; var AUserName, APassword: string; var AbortAuth: Boolean;
var Persistence: TAuthPersistenceType) of object;
/// <summary>Record to manage all the data from a single credential.</summary>
TCredential = record
/// <summary> Target type for the credential</summary>
AuthTarget: TAuthTargetType;
/// <summary> Realm where the credential can be used</summary>
Realm: string;
/// <summary> URL that defines the scope of the credential </summary>
URL: string; // Scope? Comment it...
/// <summary> UserName of the credential</summary>
UserName: string;
/// <summary> Password associated to the UserName </summary>
Password: string;
/// <summary>Initializes a Credential.</summary>
constructor Create(AnAuthTarget: TAuthTargetType; const ARealm, AURL, AUserName, APassword: string);
end;
/// <summary>Type alias for an array of TCredential</summary>
TCredentialArray = TArray<TCredential>;
/// <summary>Comparer class used to sort credentials</summary>
TCredentialComparer = class(TComparer<TCredential>)
public
/// <summary>Function that compares two credentials</summary>
function Compare(const Left, Right: TCredential): Integer; override;
end;
ICredComparer = IComparer<TCredential>;
private
function GetCredentials: TCredentialArray; inline;
protected
/// <summary>List that stores current instance credentials</summary>
FCredentials: TList<TCredential>;
protected
class var
/// <summary>Global comparer instance used to sort credentials</summary>
FCredComparer: TCredentialComparer;
public
/// <summary>Initializes class Variables</summary>
class constructor Create;
/// <summary>Cleanup class Variables</summary>
class destructor Destroy;
/// <summary>Creates a credential storage</summary>
constructor Create;
destructor Destroy; override;
/// <summary>Clears the credentials stored</summary>
procedure ClearCredentials;
/// <summary>Adds a credential to the credential storage.</summary>
/// <param name="ACredential"> Credential to be added.</param>
/// <returns>True if the Add operation was successful.</returns>
function AddCredential(const ACredential: TCredential): Boolean;
/// <summary>Removes a credential from the credential storage.</summary>
/// <returns>True if the Remove operation was successful.</returns>
function RemoveCredential(AnAuthTargetType: TAuthTargetType; const ARealm: string; const AURL: string = '';
const AUser: string = ''): Boolean;
/// <summary>Finds credentials inside the storage filtered by the parameters</summary>
function FindCredentials(AnAuthTargetType: TAuthTargetType; const ARealm: string; const AURL: string = '';
const AUser: string = ''): TCredentialArray;
/// <summary>Finds the fittest credential inside the storage filtered by the parameters</summary>
function FindAccurateCredential(AnAuthTargetType: TAuthTargetType; const ARealm: string; const AURL: string = '';
const AUser: string = ''): TCredential;
/// <summary>Property to access the credentials of the credential storage</summary>
property Credentials: TCredentialArray read GetCredentials;
/// <summary>Sorts the given credentials array.</summary>
class function SortCredentials(const ACredentials: TCredentialArray): TCredentialArray;
end;
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
/// <summary>Stores the settings of a proxy to be used by the URLClient</summary>
TProxySettings = record
private
FHost: string;
FPort: Integer;
FScheme: string;
FUserName: string;
FPassword: string;
FCredential: TCredentialsStorage.TCredential;
function GetCredential: TCredentialsStorage.TCredential;
public
/// <summary>Creates the proxy settings from the given arguments.</summary>
constructor Create(const AURL: string); overload;
constructor Create(const AHost: string; APort: Integer; const AUserName: string = ''; const APassword: string = ''; const AScheme: string = ''); overload;
/// <summary> Host to be used as a proxy</summary>
property Host: string read FHost write FHost;
/// <summary> Port used to communicate to the proxy</summary>
property Port: Integer read FPort write FPort;
/// <summary> Scheme to be used with the proxy</summary>
property Scheme: string read FScheme write FScheme;
/// <summary> UserName needed to be authenticated to the proxy</summary>
property UserName: string read FUserName write FUserName;
/// <summary> PassWord needed to be authenticated to the proxy</summary>
property Password: string read FPassword write FPassword;
/// <summary> Credential information constructed with the ProxySettings</summary>
property Credential: TCredentialsStorage.TCredential read GetCredential;
end;
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
/// <summary>Record to manage a Name-Value pair</summary>
TNetHeader = TNameValuePair;
/// <summary>Array of Name-Value pairs</summary>
TNetHeaders = TNameValueArray;
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
/// <summary>This class encapsulates the URL request and all of it's parameters</summary>
IURLRequest = interface(IInterface)
/// <summary>Getter for the Credential property</summary>
function GetCredential: TCredentialsStorage.TCredential;
/// <summary>Setter for the Credential property</summary>
procedure SetCredential(const ACredential: TCredentialsStorage.TCredential); overload;
procedure SetCredential(const AUserName, APassword: string); overload;
/// <summary>Property that exposes the Credential object that has the URLRequest object</summary>
property Credential: TCredentialsStorage.TCredential read GetCredential write SetCredential;
/// <summary>Getter for the URL property</summary>
function GetURL: TURI;
/// <summary>Setter for the URL property</summary>
procedure SetURL(const AValue: TURI);
/// <summary>Property that exposes the URI object that generated the current URLRequest object</summary>
property URL: TURI read GetURL write SetURL;
/// <summary>Getter for the Method property</summary>
function GetMethodString: string;
/// <summary>Setter for the Method property</summary>
procedure SetMethodString(const AValue: string);
/// <summary>The request method that is going to be Executed</summary>
property MethodString: string read GetMethodString write SetMethodString;
/// <summary>Getter for the SourceStream property</summary>
function GetSourceStream: TStream;
/// <summary>Setter for the SourceStream property</summary>
procedure SetSourceStream(const ASourceStream: TStream);
/// <summary>Property to Get/Set the SourceStream of a Request</summary>
/// <returns>The source stream associated to the Request.</returns>
property SourceStream: TStream read GetSourceStream write SetSourceStream;
end;
/// <summary>This class encapsulates the URL Request and all of it's related data</summary>
TURLRequest = class(TInterfacedObject, IURLRequest)
private
FConnectionTimeout,
FResponseTimeout: Integer;
protected
/// <summary>URI To be accessed by the request</summary>
FURL: TURI;
/// <summary>Method to be executed by the request</summary>
FMethodString: string;
/// <summary>Credential given to the Request in the Userinfo part of the request URI</summary>
FLocalCredential: TCredentialsStorage.TCredential;
/// <summary>Client associated with the request object</summary>
[Weak] FClient: TURLClient;
/// <summary>Stream with data to be sent by the request</summary>
[Weak] FSourceStream: TStream;
/// <summary>Stores the cancelation status of the current request</summary>
FCancelled: Boolean;
{IURLRequest}
function GetCredential: TCredentialsStorage.TCredential;
procedure SetCredential(const ACredential: TCredentialsStorage.TCredential); overload; virtual;
procedure SetCredential(const AUserName, APassword: string); overload; virtual;
function GetURL: TURI;
procedure SetURL(const AValue: TURI);
function GetMethodString: string;
procedure SetMethodString(const AValue: string);
function GetSourceStream: TStream; virtual;
procedure SetSourceStream(const ASourceStream: TStream); virtual;
/// <summary>Creates the URLRequest from the given parameters.</summary>
/// <remarks>This constructor is protected because is not intended to be used explicitly.
/// If an user wants an URLRequest needs to use specific Client.GetRequest (Example: THTTPClient.GetREquest)</remarks>
constructor Create(const AClient: TURLClient; const AMethodString: string; const AURI: TURI);
/// <summary> Setter for the ConnectionTimeout property.</summary>
procedure SetConnectionTimeout(const Value: Integer); virtual;
/// <summary> Setter for the ResponseTimeout property.</summary>
procedure SetResponseTimeout(const Value: Integer); virtual;
public
destructor Destroy; override;
/// <summary> ConnectionTimeout property. Value is in milliseconds..</summary>
property ConnectionTimeout: Integer read FConnectionTimeout write SetConnectionTimeout;
/// <summary> ResponseTimeout property. Value is in milliseconds..</summary>
property ResponseTimeout: Integer read FResponseTimeout write SetResponseTimeout;
end;
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
/// <summary>Common interface for an URL response and all of it's related data</summary>
IURLResponse = interface(IInterface)
['{5D687C75-5C36-4302-B0AB-989DDB7558FE}']
/// <summary>Getter for the Headers property</summary>
function GetHeaders: TNetHeaders;
/// <summary>Property to retrieve all Headers from the response</summary>
/// <returns>An Array of TNetHeader containing all Headers with theirs respective values.</returns>
property Headers: TNetHeaders read GetHeaders;
/// <summary>Getter for the MimeType property</summary>
function GetMimeType: string;
/// <summary>Property to retrieve the MimeType Header Value from the response</summary>
/// <returns>A string containing the MimeType value.</returns>
property MimeType: string read GetMimeType;
/// <summary>Getter for the ContentStream property</summary>
function GetContentStream: TStream;
/// <summary>Property to retrieve the ContentStream from the response</summary>
/// <returns>A stream whith the content of the response.</returns>
property ContentStream: TStream read GetContentStream;
/// <summary>Function that transforms the ContentStream into a string</summary>
function ContentAsString(const AnEncoding: TEncoding = nil): string;
end;
/// <summary>This class encapsulates the URL response and all of it's related data</summary>
TURLResponse = class(TBaseAsyncResult, IURLResponse)
private
FAsyncCallback: TAsyncCallback;
FAsyncCallbackEvent: TAsyncCallbackEvent;
FProc: TProc;
protected
/// <summary>Request that originate the response</summary>
FRequest: IURLRequest;
/// <summary>Field that holds a temporary stream when user do not provide a response stream</summary>
FInternalStream: TStream;
/// <summary>Field intended as a common stream to be used internally</summary>
/// <remarks>This field will point to an external Stream or FInternalStream. It's a mere pointer</remarks>
[Weak] FStream: TStream;
constructor Create(const AContext: TObject; const AProc: TProc; const AAsyncCallback: TAsyncCallback;
const AAsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest; const AContentStream: TStream); overload;
constructor Create(const AContext: TObject; const ARequest: IURLRequest; const AContentStream: TStream); overload;
/// <summary>Contructs InternalStream Field. Can be overrided to create a different kind of stream</summary>
function DoCreateInternalStream: TStream; virtual;
procedure AsyncDispatch; override;
procedure Complete; override;
procedure Schedule; override;
function DoCancel: Boolean; override;
public
destructor Destroy; override;
{IURLResponse}
/// <summary>Implementation of IURLResponse Getter for the ContentStream property</summary>
function GetContentStream: TStream;
/// <summary>Implementation of IURLResponse Getter for the MimeType property</summary>
function GetMimeType: string; virtual; abstract;
/// <summary>Implementation of IURLResponse Getter for the Headers property</summary>
/// <remarks>Must be overriden in platform Implementation.</remarks>
function GetHeaders: TNetHeaders; virtual; abstract;
/// <summary>Implementation of IURLResponse ContentAsString</summary>
/// <remarks>If you do not provide AEncoding then the system will try to get it from the response</remarks>
function ContentAsString(const AnEncoding: TEncoding = nil): string; virtual; abstract;
end;
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
/// <summary>Class that encapsulates the managing of a common URL client.
/// A derivative of this class can be a THTTPClient.</summary>
TURLClient = class
public const
DefaultConnectionTimeout = 60000;
DefaultResponseTimeout = 60000;
var
FInstances: TObjectDictionary<string, TURLClient>;
FAuthCallback: TCredentialsStorage.TCredentialAuthCallback;
FAuthEvent: TCredentialsStorage.TCredentialAuthEvent;
FInternalCredentialsStorage: TCredentialsStorage;
FProxySettings: TProxySettings;
[Weak] FCredentialsStorage: TCredentialsStorage;
FConnectionTimeout: Integer;
FResponseTimeout: Integer;
function GetInternalInstance(const AScheme: string): TURLClient;
function GetUserAgent: string;
procedure SetUserAgent(const Value: string);
protected
/// <summary> CustomHeaders to be used by the client.</summary>
FCustomHeaders: TNetHeaders;
/// <summary> Setter for the ConnectionTimeout property.</summary>
procedure SetConnectionTimeout(const Value: Integer);
/// <summary> Setter for the ResponseTimeout property.</summary>
procedure SetResponseTimeout(const Value: Integer);
/// <summary> Getter for the CustomHeaders property.</summary>
function GetCustomHeaderValue(const Name: string): string;
/// <summary> Setter for the CustomHeaders property.</summary>
procedure SetCustomHeaderValue(const Name, Value: string);
/// <summary>Function that transforms the ContentStream into a string</summary>
function SupportedSchemes: TArray<string>; virtual;
/// <summary>Function that executes a Request and obtains a response</summary>
/// <remarks>This function must be overriden by specific clients (HTTP, FTP, ...)</remarks>
function DoExecute(const ARequestMethod: string; const AURI: TURI;
const ASourceStream, AContentStream: TStream; const AHeaders: TNetHeaders): IURLResponse; virtual;
/// <summary>Function that executes a Request and obtains a response</summary>
/// <remarks>This function must be overriden by specific clients (HTTP, FTP, ...)</remarks>
function DoExecuteAsync(const AsyncCallback: TAsyncCallback; const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequestMethod: string; const AURI: TURI;
const ASourceStream, AContentStream: TStream; const AHeaders: TNetHeaders; AOwnsSourceStream: Boolean = False): IAsyncResult; virtual;
/// <summary>Function that obtains a Response instance</summary>
/// <remarks>This function must be overriden by specific clients (HTTP, FTP, ...)</remarks>
function DoGetResponseInstance(const AContext: TObject; const AProc: TProc; const AsyncCallback: TAsyncCallback;
const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest; const AContentStream: TStream): IAsyncResult; virtual;
/// <summary>Function that obtains a Request instance</summary>
/// <remarks>This function must be overriden by specific clients (HTTP, FTP, ...)</remarks>
function DoGetRequestInstance(const ARequestMethod: string; const AURI: TURI): IURLRequest; virtual;
/// <summary> Function used to invoke the Authorization callback or the Authorization envent.</summary>
procedure DoAuthCallback(AnAuthTarget: TAuthTargetType; const ARealm, AURL: string;
var AUserName, APassword: string; var AbortAuth: Boolean; var Persistence: TAuthPersistenceType); virtual;
/// <summary>Create a Client instance</summary>
class function CreateInstance: TURLClient; virtual;
/// <summary>To obtain a Client instance</summary>
/// <remarks></remarks>
/// <param name="AScheme">The scheme that is going to be used with the Client</param>
/// <returns>The GetInstance method returns the protocol dependant TURLClient object associated to the given Scheme</returns>
class function GetInstance(const AScheme: string): TURLClient; static;
/// <summary>Setter for CredentialsStorage Property</summary>
procedure SetCredentialsStorage(const Value: TCredentialsStorage); virtual;
/// <summary>Get the compatible credentials with the given parameters</summary>
function GetCredentials(AuthTarget: TAuthTargetType; const ARealm, URL: string): TCredentialsStorage.TCredentialArray; virtual;
/// <summary>Setter for ProxySettings Property</summary>
procedure SetProxySettings(const Value: TProxySettings); virtual;
public
/// <summary>To obtain a Client instance</summary>
constructor Create;
destructor Destroy; override;
/// <summary>Function that obtains a Request instance</summary>
function GetRequest(const ARequestMethod: string; const AURI: TURI): IURLRequest; overload;
/// <summary>Function that obtains a Request instance</summary>
function GetRequest(const ARequestMethod, AURI: string): IURLRequest; overload; inline;
/// <summary>You have to use this function to Execute a Request</summary>
/// <remarks></remarks>
/// <param name="ARequestMethod">The request method that is going to be Executed</param>
/// <param name="AURI">The URI that contains the information for the request that is going to be Executed</param>
/// <param name="ASourceStream">The stream to provide the request data.</param>
/// <param name="AContentStream">The stream to store the response data. If provided the user is responsible
/// of releasing it. If not provided will be created internally and released when not needed.</param>
/// <param name="AHeaders">Additional headers to be passed to the request that is going to be Executed</param>
/// <returns>The platform dependant response object associated to the given request. It's an Interface and It's
/// released automatically.</returns>
function Execute(const ARequestMethod: string; const AURI: TURI; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IURLResponse; overload;
/// <summary>You have to use this function to Execute a given Request</summary>
/// <remarks></remarks>
/// <param name="ARequestMethod">The request method that is going to be Executed</param>
/// <param name="AURIStr">The URI string that contains the information for the request that is going to be Executed</param>
/// <param name="ASourceStream">The stream to provide the request data.</param>
/// <param name="AContentStream">The stream to store the response data. If provided the user is responsible
/// of releasing it. If not provided will be created internally and released when not needed.</param>
/// <param name="AHeaders">Additional headers to be passed to the request that is going to be Executed</param>
/// <returns>The platform dependant response object associated to the given request. It's an Interface and It's
/// released automatically.</returns>
function Execute(const ARequestMethod: string; const AURIStr: string; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IURLResponse; overload;
/// <summary>You have to use this function to Execute a Request</summary>
/// <remarks></remarks>
/// <param name="ARequestMethod">The request method that is going to be Executed</param>
/// <param name="AURI">The URI that contains the information for the request that is going to be Executed</param>
/// <param name="ASourceStream">The stream to provide the request data.</param>
/// <param name="AContentStream">The stream to store the response data. If provided the user is responsible
/// of releasing it. If not provided will be created internally and released when not needed.</param>
/// <param name="AHeaders">Additional headers to be passed to the request that is going to be Executed</param>
/// <returns>The platform dependant response object associated to the given request. It's an Interface and It's
/// released automatically.</returns>
function BeginExecute(const ARequestMethod: string; const AURI: TURI; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IAsyncResult; overload;
function BeginExecute(const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequestMethod: string; const AURI: TURI; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IAsyncResult; overload;
function BeginExecute(const AsyncCallback: TAsyncCallback; const ARequestMethod: string; const AURI: TURI; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IAsyncResult; overload;
/// <summary>You have to use this function to Execute a given Request</summary>
/// <remarks></remarks>
/// <param name="ARequestMethod">The request method that is going to be Executed</param>
/// <param name="AURIStr">The URI string that contains the information for the request that is going to be Executed</param>
/// <param name="ASourceStream">The stream to provide the request data.</param>
/// <param name="AContentStream">The stream to store the response data. If provided the user is responsible
/// of releasing it. If not provided will be created internally and released when not needed.</param>
/// <param name="AHeaders">Additional headers to be passed to the request that is going to be Executed</param>
/// <returns>The platform dependant response object associated to the given request. It's an Interface and It's
/// released automatically.</returns>
function BeginExecute(const ARequestMethod: string; const AURIStr: string; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IAsyncResult; overload;
function BeginExecute(const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequestMethod: string; const AURIStr: string; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IAsyncResult; overload;
function BeginExecute(const AsyncCallback: TAsyncCallback; const ARequestMethod: string; const AURIStr: string; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IAsyncResult; overload;
/// <summary>You have to use this function to Wait for the result of a given Request</summary>
/// <remarks>You must use this class function to ensure that any pending exceptions are raised in the proper context</remarks>
/// <returns>The platform dependant response object associated to the given request. It's an Interface and It's
/// released automatically.</returns>
class function EndAsyncURL(const AAsyncResult: IAsyncResult): IURLResponse; overload;
class function EndAsyncURL(const AAsyncResult: IURLResponse): IURLResponse; overload;
/// <summary> Property to set/get the ConnectionTimeout. Value is in milliseconds.</summary>
property ConnectionTimeout: Integer read FConnectionTimeout write SetConnectionTimeout;
/// <summary> Property to set/get the ResponseTimeout. Value is in milliseconds.</summary>
property ResponseTimeout: Integer read FResponseTimeout write SetResponseTimeout;
/// <summary> Property to set the UserAgent sent with the request </summary>
property UserAgent: string read GetUserAgent write SetUserAgent;
/// <summary> Authorization CallBack to ask for user and password</summary>
/// <remarks> If the AuthCallback is defined, the AuthEvent is not fired</remarks>
property AuthCallback: TCredentialsStorage.TCredentialAuthCallback read FAuthCallback write FAuthCallback;
/// <summary> Authorization Event to ask for user and password</summary>
/// <remarks> If the AuthCallback is defined, the AuthEvent is not fired</remarks>
property AuthEvent: TCredentialsStorage.TCredentialAuthEvent read FAuthEvent write FAuthEvent;
/// <summary> Credential Storage to be used by the client</summary>
/// <remarks> By default the client has his own CredentialStorage</remarks>
property CredentialsStorage: TCredentialsStorage read FCredentialsStorage write SetCredentialsStorage;
/// <summary> Proxy Settings to be used by the client.</summary>
property ProxySettings: TProxySettings read FProxySettings write SetProxySettings;
/// <summary> CustomHeaders to be used by the client.</summary>
property CustomHeaders[const AName: string]: string read GetCustomHeaderValue write SetCustomHeaderValue;
end;
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
/// <summary> Record to store the information of a certificate.</summary>
TCertificate = record
/// <summary> Expiry date of the certificate</summary>
Expiry: TDateTime;
/// <summary> Start date of the certificate</summary>
Start: TDateTime;
/// <summary> Subject of the certificate</summary>
Subject: string;
/// <summary> Issuer of the certificate</summary>
Issuer: string;
/// <summary> ProtocolName of the certificate</summary>
ProtocolName: string; // deprecated;
/// <summary> Algorithm Signature of the certificate</summary>
AlgSignature: string;
/// <summary> Algorithm Encryption of the certificate</summary>
AlgEncryption: string; // deprecated;
/// <summary> Encryption's KeySize of the certificate</summary>
KeySize: Integer;
end;
TCertificateHelper = record helper for TCertificate
private
function GetCertName: string;
function GetSerialNum: string;
procedure SetCertName(const AValue: string);
procedure SetSerialNum(const AValue: string);
public
function IsDefined: Boolean;
property CertName: string read GetCertName write SetCertName;
property SerialNum: string read GetSerialNum write SetSerialNum;
end;
/// <summary> List of Certificates.</summary>
TCertificateList = class(TList<TCertificate>);
/// <summary> Certificate selection callback signature</summary>
TNeedClientCertificateCallback = procedure(const Sender: TObject; const ARequest: TURLRequest; const ACertificateList: TCertificateList;
var AnIndex: Integer);
/// <summary> Certificate selection Event signature</summary>
TNeedClientCertificateEvent = procedure(const Sender: TObject; const ARequest: TURLRequest; const ACertificateList: TCertificateList;
var AnIndex: Integer) of object;
/// <summary> Certificate validation callback signature</summary>
/// <param name="Sender"> HTTPClient that invoked the callback</param>
/// <param name="ARequest">Request that invoked the callback</param>
/// <param name="Certificate">Certificate to validate</param>
/// <param name="Accepted">boolean, expected to be true if the certificate is valid</param>
TValidateCertificateCallback = procedure(const Sender: TObject; const ARequest: TURLRequest; const Certificate: TCertificate; var Accepted: Boolean);
/// <summary> Certificate validation Event signature</summary>
/// <param name="Sender"> HTTPClient that invoked the Event</param>
/// <param name="ARequest">Request that invoked the Event</param>
/// <param name="Certificate">Certificate to validate</param>
/// <param name="Accepted">boolean, expected to be true if the certificate is valid</param>
TValidateCertificateEvent = procedure(const Sender: TObject; const ARequest: TURLRequest; const Certificate: TCertificate; var Accepted: Boolean) of object;
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
/// <summary>Factory for creating objects associated to currently registered schemes</summary>
TURLSchemes = class
private type
/// <summary>Metaclass used to store platform dependant TURLClient classes associated to schemes</summary>
TURLClientClass = class of TURLClient;
private
class var FSchemeClients: TDictionary<string, TURLClientClass>;
public
class constructor Create;
class destructor Destroy;
/// <summary>Register a platform URLClient class associated to a given scheme</summary>
class procedure RegisterURLClientScheme(const AURLClientClass: TURLClientClass; const AScheme: string);
/// <summary>Unregister a given scheme and it's associated platform URLClient class</summary>
class procedure UnRegisterURLClientScheme(const AScheme: string);
/// <summary>Obtain a platform URLClient object instance associated to a given scheme</summary>
/// <remarks>Obtained instance must be released by the user.</remarks>
/// <param name="AScheme"></param>
/// <returns>The platform dependant client object valid for the given scheme.</returns>
class function GetURLClientInstance(const AScheme: string): TURLClient;
end;
implementation
uses
{$IFDEF MACOS}
Macapi.CoreFoundation,
{$ENDIF MACOS}
System.NetConsts, System.Threading, System.NetEncoding, System.StrUtils;
{ TPunyCode }
type
TPunyCode = class
private
const
BASE: Cardinal = 36;
TMIN: Cardinal = 1;
TMAX: Cardinal = 26;
SKEW: Cardinal = 38;
DAMP: Cardinal = 700;
INITIAL_BIAS: Cardinal = 72;
INITIAL_N: Cardinal = 128;
MAX_INT: Cardinal = 4294967295;
Delimiter = '-';
private
class function GetMinCodePoint(const AMinLimit: Cardinal; const AString: UCS4String): Cardinal;
class function IsBasic(const AString: UCS4String; const AIndex, AMinLimit: Cardinal): Boolean; inline;
class function Adapt(const ADelta, ANumPoints: Cardinal; const FirstTime: Boolean): Cardinal;
class function Digit2Codepoint(const ADigit: Cardinal): Cardinal;
class function Codepoint2Digit(const ACodePoint: Cardinal): Cardinal;
class function DoEncode(const AString: UCS4String): UCS4String; overload;
class function DoDecode(const AString: UCS4String): UCS4String; overload;
class function DoEncode(const AString: string): string; overload;
class function DoDecode(const AString: string): string; overload;
public
class function Encode(const AString: string): string;
class function Decode(const AString: string): string;
end;
{ TNameValuePair }
constructor TNameValuePair.Create(const AName, AValue: string);
begin
Name := AName;
Value := AValue;
end;
{ TURI }
procedure TURI.AddParameter(const AParameter: TURIParameter);
begin
AddParameter(AParameter.Name, AParameter.Value);
end;
function TURI.GetQuery: string;
var
I: Integer;
begin
Result := '';
for I := 0 to Length(Params) - 1 do
Result := Result + Params[I].Name + '=' + Params[I].Value + '&';
if Result <> '' then
Result := Result.Substring(0, Result.Length - 1); //Remove last '&'
end;
procedure TURI.AddParameter(const AName, AValue: string);
var
Len: Integer;
begin
Len := Length(Params);
SetLength(FParams, Len + 1);
FParams[Len].Name := TNetEncoding.URL.EncodeQuery(AName);
FParams[Len].Value := TNetEncoding.URL.EncodeQuery(AValue);
FQuery := GetQuery;
end;
procedure TURI.ComposeURI(const AScheme, AUsername, APassword, AHostname: string; APort: Integer; const APath: string;
const AParams: TURIParameters; const AFragment: string);
begin
FScheme := AScheme.ToLower;
FUsername := TNetEncoding.URL.EncodeQuery(AUsername);
FPassword := TNetEncoding.URL.EncodeQuery(APassword);
FHost := AHostname;
FPort := APort;
FPath := TNetEncoding.URL.EncodePath(APath);
Params := AParams;
FFragment := TNetEncoding.URL.EncodeQuery(AFragment);
end;
constructor TURI.Create(const AURIStr: string);
begin
DecomposeURI(AURIStr, True);
end;
procedure TURI.DecomposeBaseScheme(const AURIStr: string; Pos, Limit, SlashCount: Integer);
function PortColonOffset(Pos, Limit: Integer): Integer;
begin
while Pos <= Limit do
begin
case AURIStr.Chars[Pos] of
'[':
repeat
Inc(Pos);
until (Pos >= Limit) or (AURIStr.Chars[Pos] = ']');
':':
Exit(Pos);
end;
Inc(Pos);
end;
Result := Limit; // No colon
end;
function ParsePort(Pos, Limit: Integer): Integer;
begin
Result := AURIStr.Substring(Pos, Limit - Pos).ToInteger;
end;
var
LCompDelimiterOffset: Integer;
LPasswordColonOffset: Integer;
LPortColonOffset: Integer;
LQueryDelimiterOffset: Integer;
LPathDelimiterOffset: Integer;
C: Char;
LHasPassword: Boolean;
LHasUsername: Boolean;
LEncodedUsername: string;
begin
// Read an authority if either:
// * The input starts with 2 or more slashes. These follow the scheme if it exists.
// * The input scheme exists and is different from the base URL's scheme.
//
// The structure of an authority is:
// username:password@host:port
//
// Username, password and port are optional.
// [username[:password]@]host[:port]
if (SlashCount >= 2) then
Inc(Pos, 2);//work around: Only remove the first 2 slashes to be able to omit the authority.
LHasPassword := False;
LHasUsername := False;
while True do
begin
LCompDelimiterOffset := AURIStr.IndexOfAny(['@', '/', '\', '?', '#'], Pos, Limit + 1 - Pos);
if LCompDelimiterOffset = -1 then
LCompDelimiterOffset := Limit + 1;
if LCompDelimiterOffset <> Limit + 1 then
C := AURIStr.Chars[LCompDelimiterOffset]
else
C := Char(-1);
case C of
'@':
begin
if not LHasPassword then
begin
LPasswordColonOffset := AURIStr.IndexOf(':', Pos, LCompDelimiterOffset - Pos);
if LPasswordColonOffset = -1 then
LPasswordColonOffset := LCompDelimiterOffset;
LEncodedUsername := TNetEncoding.URL.EncodeAuth(AURIStr.Substring(Pos, LPasswordColonOffset - Pos));
if LHasUsername then
Username := Username + '%40' + LEncodedUsername
else
Username := LEncodedUsername;
if LPasswordColonOffset <> LCompDelimiterOffset then
begin
LHasPassword := True;
Password := TNetEncoding.URL.Encode(AURIStr.Substring(LPasswordColonOffset + 1,
LCompDelimiterOffset - (LPasswordColonOffset + 1)));
end;
LHasUsername := True;
end
else
Password := Password + '%40' + TNetEncoding.URL.Encode(AURIStr.Substring(Pos, LCompDelimiterOffset - Pos));
Pos := LCompDelimiterOffset + 1;
end;
Char(-1), '/', '\', '?', '#':
begin
LPortColonOffset := PortColonOffset(Pos, LCompDelimiterOffset);
Host := AURIStr.Substring(Pos, LPortColonOffset - Pos);
if LPortColonOffset + 1 < LCompDelimiterOffset then
try
Port := ParsePort(LPortColonOffset + 1, LCompDelimiterOffset)
except
raise ENetURIException.CreateResFmt(@SNetUriInvalid, [AURIStr]);
end
else
Port := GetDefaultPort(Scheme);
//It is only wrong if host was not omitted.
if (Host = '') and (SlashCount = 2) then
raise ENetURIException.CreateResFmt(@SNetUriInvalid, [AURIStr]);
Pos := LCompDelimiterOffset;
Break;
end;
end;
end;
LPathDelimiterOffset := AURIStr.IndexOfAny(['?', '#'], Pos, Limit); // PathDelimiterOffset
if LPathDelimiterOffset = -1 then
LPathDelimiterOffset := Limit + 1;
Path := TNetEncoding.URL.EncodePath(AURIStr.Substring(Pos, LPathDelimiterOffset - Pos));
Pos := LPathDelimiterOffset;
// Query
if (Pos < Limit) and (AURIStr.Chars[Pos] = '?') then
begin
LQueryDelimiterOffset := AURIStr.IndexOf('#', Pos, Limit + 1 - Pos);
if LQueryDelimiterOffset = -1 then
LQueryDelimiterOffset := Limit + 1;
Query := TNetEncoding.URL.EncodeQuery(AURIStr.Substring(Pos + 1, LQueryDelimiterOffset - (Pos + 1)));
Pos := LQueryDelimiterOffset;
end;
// Fragment
if (Pos < Limit) and (AURIStr.Chars[Pos] = '#') then
Fragment := TNetEncoding.URL.Encode(AURIStr.Substring(Pos + 1, Limit + 1 - (Pos + 1)), [], []);
ParseParams(True);
end;
procedure TURI.DecomposeNoAuthorityScheme(const AURIStr: string; Pos, Limit, SlashCount: Integer);
begin
// scheme without authority have 2 parts: <scheme name>:<path>
// Example urn:oasis:names:specification:docbook:dtd:xml:4.1.2
// scheme = urn
// path = oasis:names:specification:docbook:dtd:xml:4.1.2
Path := AURIStr.Substring(Pos);
Port := GetDefaultPort(Scheme);
end;
procedure TURI.DecomposeURI(const AURIStr: string; ARaiseNoSchema: Boolean);
function SchemeDelimiterOffset(Pos, Limit: Integer): Integer;
var
I: Integer;
begin
if Limit - Pos > 0 then
for I := Pos to Limit do
case AURIStr.Chars[I] of
// Scheme character. Keep going.
'0'..'9', 'a'..'z', 'A'..'Z', '+', '-', '.':
{continue};
':':
Exit(I);
else
// Non-scheme character before the first ':'.
Exit(-1);
end;
// No ':'; doesn't start with a scheme.
Result := -1;
end;
function SlashCount(Pos, Limit: Integer): Integer;
begin
Result := 0;
while Pos < Limit do
if (AURIStr.Chars[Pos] = '\') or (AURIStr.Chars[Pos] = '/') then
begin
Inc(Result);
Inc(Pos);
end
else
Break;
end;
function GetSchemeDecomposProc(const AScheme: string; ASlashcount: Integer): TSchemeDecomposeProc;
begin
Result := nil;
// Typical scheme with "://" delimiters
if ASlashCount >= 2 then
Result := DecomposeBaseScheme
else
// Mailto scheme. This scheme is "No autority". But it should decompose
// by base decomposer for detect host, user name
if IsMailtoScheme then
Result := DecomposeBaseScheme
else
// News, tel, urn schemes
if IsSchemeNoAuthority then
Result := DecomposeNoAuthorityScheme;
end;
var
PosScheme: Integer;
Pos: Integer;
Limit: Integer;
LSlashCount: Integer;
SchemeDecomposeProc: TSchemeDecomposeProc;
begin
Self := Default(TURI);
// Skip leading white spaces
Pos := 0;
while (Pos < High(AURIStr)) and (
(AURIStr.Chars[Pos] = ' ') or
(AURIStr.Chars[Pos] = #9) or
(AURIStr.Chars[Pos] = #10) or
(AURIStr.Chars[Pos] = #13) or
(AURIStr.Chars[Pos] = #12)) do
Inc(Pos);
// Skip trailing white spaces
//Limit := High(AURIStr);
Limit := AURIStr.Length - 1;
while (Limit > 0) and (
(AURIStr.Chars[Limit] = ' ') or
(AURIStr.Chars[Limit] = #9) or
(AURIStr.Chars[Limit] = #10) or
(AURIStr.Chars[Limit] = #13) or
(AURIStr.Chars[Limit] = #12)) do
Dec(Limit);
PosScheme := SchemeDelimiterOffset(Pos, Limit);
if PosScheme = -1 then
if ARaiseNoSchema then
raise ENetURIException.CreateResFmt(@SNetUriInvalid, [AURIStr])
else
Exit;
Scheme := AURIStr.Substring(Pos, PosScheme - Pos);
Pos := Pos + Scheme.Length + 1;
LSlashCount := SlashCount(Pos, Limit);
SchemeDecomposeProc := GetSchemeDecomposProc(Scheme, LSlashCount);
if Assigned(SchemeDecomposeProc) then
SchemeDecomposeProc(AURIStr, Pos, Limit, LSlashCount)
else
raise ENetURIException.CreateResFmt(@SNetUriInvalid, [AURIStr]);
end;
procedure TURI.DeleteParameter(const AName: string);
var
LIndex: Integer;
begin
LIndex := FindParameterIndex(AName);
if LIndex >= 0 then
begin
repeat
DeleteParameter(LIndex);
LIndex := FindParameterIndex(AName);
until LIndex = -1;
end
else
raise ENetURIException.CreateResFmt(@SNetUriParamNotFound, [AName]);
end;
function TURI.FindParameterIndex(const AName: string): Integer;
var
I: Integer;
LName: string;
begin
Result := -1;
LName := TNetEncoding.URL.EncodeQuery(AName);
for I := 0 to Length(Params) - 1 do
if Params[I].Name = LName then
Exit(I);
end;
procedure TURI.DeleteParameter(AIndex: Integer);
begin
if (AIndex >= Low(Params)) and (AIndex <= High(Params)) then
begin
if AIndex < High(Params) then
begin
Finalize(Params[AIndex]);
System.Move(Params[AIndex + 1], Params[AIndex], (Length(Params) - AIndex - 1) * SizeOf(TURIParameter));
FillChar(Params[High(Params)], SizeOf(TURIParameter), 0);
end;
SetLength(FParams, Length(FParams) - 1);
FQuery := GetQuery;
end
else
raise ENetURIException.CreateResFmt(@SNetUriIndexOutOfRange, [AIndex, Low(Params), High(Params)]);
end;
function TURI.GetDefaultPort(const AScheme: string): Integer;
begin
Result := -1;
if AScheme.Equals(SCHEME_HTTP) then
Result := 80;
if AScheme.Equals(SCHEME_HTTPS) then
Result := 443;
end;
function TURI.GetParameter(const I: Integer): TURIParameter;
begin
if (I >= Low(Params)) and (I <= High(Params)) then
Result := Params[I]
else
raise ENetURIException.CreateResFmt(@SNetUriIndexOutOfRange, [I, Low(Params), High(Params)]);
end;
function TURI.GetParameterByName(const AName: string): string;
var
LIndex: Integer;
begin
LIndex := FindParameterIndex(AName);
if LIndex >= 0 then
Result := GetParameter(LIndex).Value
else
raise ENetURIException.CreateResFmt(@SNetUriParamNotFound, [AName]);
end;
class function TURI.IDNAToUnicode(const AHostName: string): string;
var
I: Integer;
LDecoded: string;
LPart: string;
LParts: TArray<string>;
LIsEncoded: Boolean;
begin
LIsEncoded := False;
LParts := AHostName.Split(['.']);
for I := Low(LParts) to High(LParts) do
if LParts[I].StartsWith('xn--') then
begin
LPart := LParts[I].Substring('xn--'.Length);
if LPart.IndexOf('-') = -1 then
LPart := '-' + LPart;
LDecoded := TPunyCode.Decode(LPart);
if LDecoded <> LPart then
begin
LParts[I] := LDecoded;
LIsEncoded := True;
end;
end;
if LIsEncoded then
Result := string.Join('.', LParts)
else
Result := AHostName;
end;
function TURI.IsMailtoScheme: Boolean;
begin
Result := Scheme.Equals(SCHEME_MAILTO);
end;
function TURI.IsSchemeNoAuthority: Boolean;
begin
Result := Scheme.Equals(SCHEME_MAILTO) or
Scheme.Equals(SCHEME_NEWS) or
Scheme.Equals(SCHEME_TEL) or
Scheme.Equals(SCHEME_URN);
end;
function TURI.IsValidPort: Boolean;
begin
Result := (Port <> 0) and (Port <> -1);
end;
procedure TURI.ParseParams(Encode: Boolean);
var
LParts: TArray<string>;
I: Integer;
Pos: Integer;
begin
LParts := Query.Split([Char(';'), Char('&')]);
SetLength(FParams, Length(LParts));
for I := 0 to Length(LParts) - 1 do
begin
Pos := LParts[I].IndexOf(Char('='));
if Pos > 0 then
begin
if Encode then
begin
FParams[I].Name := TNetEncoding.URL.EncodeQuery(LParts[I].Substring(0, Pos));
FParams[I].Value := TNetEncoding.URL.EncodeQuery(LParts[I].Substring(Pos + 1));
end
else
begin
FParams[I].Name := LParts[I].Substring(0, Pos);
FParams[I].Value := LParts[I].Substring(Pos + 1);
end;
end
else
begin
if Encode then
FParams[I].Name := TNetEncoding.URL.EncodeQuery(LParts[I])
else
FParams[I].Name := LParts[I];
FParams[I].Value := '';
end;
end;
end;
class function TURI.PathRelativeToAbs(const RelPath: string; const Base: TURI): string;
function GetURLBase(const AURI: TURI): string;
begin
if (AURI.Scheme.Equals(SCHEME_HTTP) and (AURI.Port = 80)) or (AURI.Scheme.Equals(SCHEME_HTTPS) and (AURI.Port = 443)) then
Result := AURI.Scheme + '://' + AURI.Host
else
begin
if AURI.IsSchemeNoAuthority then
Result := AURI.Scheme + ':' + AURI.Host
else
Result := AURI.Scheme + '://' + AURI.Host;
if AURI.IsValidPort then
Result := Result + ':' + AURI.Port.ToString;
end;
end;
function GetURLPath(const AURI: TURI): string;
begin
Result := AURI.Path;
Result := Result.Substring(0, Result.LastIndexOf(Char('/')) + 1);
end;
var
List: TStringList;
Path: string;
I, K: Integer;
begin
if RelPath.Trim.IsEmpty then
Exit(Base.ToString);
I := RelPath.IndexOf(':');
K := RelPath.IndexOf('/');
if (I = -1) or (K <= I) then // not found ':' before '/' so there is no scheme, it's a relative path
begin
if K = 0 then // Begins with '/'
Result := GetURLBase(Base) + RelPath
else
begin
Path := GetURLPath(Base) + RelPath;
List := TStringList.Create;
try
List.LineBreak := '/';
List.SetText(PChar(Path));
I := 0;
while I < List.Count do
begin
if (List[I] = '.') then
List.Delete(I)
else
if (I > 0) and (List[I] = '..') then
begin
List.Delete(I);
if I > 0 then
begin
Dec(I);
List.Delete(I);
end;
end
else Inc(I);
end;
Result := '';
for I := 0 to List.Count - 1 do
begin
if List[I] = '' then
Result := Result + '/'
else
Result := Result + List[I] + '/';
end;
if RelPath[High(RelPath)] <> '/' then
Result := Result.Substring(0, Result.Length - 1); // remove last '/'
Result := GetURLBase(Base) + Result;
finally
List.Free;
end;
end;
end
else
Result := RelPath;
end;
procedure TURI.SetHost(const Value: string);
begin
FHost := UnicodeToIDNA(Value);
end;
procedure TURI.SetParameter(const I: Integer; const Value: TURIParameter);
begin
if (I >= Low(Params)) and (I <= High(Params)) then
begin
Params[I].Name := TNetEncoding.URL.EncodeQuery(Value.Name);
Params[I].Value := TNetEncoding.URL.EncodeQuery(Value.Value);
FQuery := GetQuery;
end
else
raise ENetURIException.CreateResFmt(@SNetUriIndexOutOfRange, [I, Low(Params), High(Params)]);
end;
procedure TURI.SetParameterByName(const AName: string; const Value: string);
var
LIndex: Integer;
begin
LIndex := FindParameterIndex(AName);
if LIndex >= 0 then
begin
Params[LIndex].Value := TNetEncoding.URL.EncodeQuery(Value);
FQuery := GetQuery;
end
else
raise ENetURIException.CreateResFmt(@SNetUriParamNotFound, [AName]);
end;
procedure TURI.SetParams(const Value: TURIParameters);
var
I: Integer;
begin
FParams := Value;
for I := Low(FParams) to High(FParams) do
begin
FParams[I].Name := TNetEncoding.URL.EncodeQuery(FParams[I].Name);
FParams[I].Value := TNetEncoding.URL.EncodeQuery(FParams[I].Value);
end;
FQuery := GetQuery;
end;
procedure TURI.SetPassword(const Value: string);
begin
FPassword := TNetEncoding.URL.EncodeAuth(Value);
end;
procedure TURI.SetPath(const Value: string);
begin
if Value = '' then
FPath := '/'
else
FPath := TNetEncoding.URL.EncodePath(Value);
if IsSchemeNoAuthority and FPath.StartsWith('/') then
FPath := FPath.Remove(0, 1);
end;
procedure TURI.SetQuery(const Value: string);
begin
FQuery := Value;
ParseParams(True);
end;
procedure TURI.SetScheme(const Value: string);
begin
FScheme := Value.ToLower;
end;
procedure TURI.SetUserName(const Value: string);
begin
FUsername := TNetEncoding.URL.EncodeAuth(Value);
end;
function TURI.ToString: string;
var
Auth: string;
begin
if Username <> '' then
if Password <> '' then
Auth := Username + ':' + Password + '@'
else
Auth := Username + '@'
else
Auth := '';
if Scheme <> '' then
begin
if IsSchemeNoAuthority then
Result := Scheme + ':'
else
Result := Scheme + '://';
end else
Result := '';
Result := Result + Auth + Host;
if (IsValidPort) and
((Scheme.Equals(SCHEME_HTTP) and (Port <> 80)) or (Scheme.Equals(SCHEME_HTTPS) and (Port <> 443))) then
Result := Result + ':' + Port.ToString;
Result := Result + Path;
if Length(Params) > 0 then
Result := Result + '?' + Query;
if Fragment <> '' then
Result := Result + '#' + Fragment;
end;
class function TURI.UnicodeToIDNA(const AHostName: string): string;
procedure FixHostNamePart(var APart: string); inline;
begin
// This function is for solving issues related to: Internationalized Domain Names (IDN) in .museum - Orthographic issues
// See: http://about.museum/idn/issues.html
// U+00DF LATIN SMALL LETTER SHARP S
APart := APart.Replace(#$00DF, 'ss', [rfReplaceAll]);
// U+03C2 GREEK SMALL LETTER FINAL SIGMA
// U+03C3 GREEK SMALL LETTER SIGMA
APart := APart.Replace(#$03C2, #$03C3, [rfReplaceAll]);
// case 0x200c: // Ignore/remove ZWNJ.
APart := APart.Replace(#$200C, '', [rfReplaceAll]);
// case 0x200d: // Ignore/remove ZWJ.
APart := APart.Replace(#$200D, '', [rfReplaceAll]);
end;
var
I: Integer;
LNormalizedHostName: string;
LEncoded: string;
LParts: TArray<string>;
begin
// Normalize HostName. We do a LowerCase conversion. This manages casing issues.
LNormalizedHostName := AHostName.ToLower;
LParts := LNormalizedHostName.Split(['.']);
for I := Low(LParts) to High(LParts) do
begin
FixHostNamePart(LParts[I]);
LEncoded := TPunyCode.Encode(LParts[I]);
if LEncoded <> LParts[I] then
begin
if LEncoded.StartsWith('-') then
LParts[I] := 'xn-' + LEncoded
else
LParts[I] := 'xn--' + LEncoded;
end;
end;
Result := string.Join('.', LParts)
end;
class function TURI.URLDecode(const AValue: string; PlusAsSpaces: Boolean): string;
const
H2BConvert: array[Ord('0')..Ord('f')] of SmallInt =
( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,10,11,12,13,14,15);
function IsHexChar(C: Byte): Boolean;
begin
case C of
Ord('0')..Ord('9'), Ord('a')..Ord('f'), Ord('A')..Ord('F'): Result := True;
else
Result := False;
end;
end;
var
ValueBuff: TBytes;
Buff: TBytes;
Cnt: Integer;
Pos: Integer;
Len: Integer;
begin
Cnt := 0;
Pos := 0;
ValueBuff := TEncoding.UTF8.GetBytes(AValue);
Len := Length(ValueBuff);
SetLength(Buff, Len);
while Pos < Len do
begin
if (ValueBuff[Pos] = Ord('%')) and ((Pos + 2) < Len) and IsHexChar(ValueBuff[Pos + 1]) and IsHexChar(ValueBuff[Pos + 2]) then
begin
Buff[Cnt] := (H2BConvert[ValueBuff[Pos + 1]]) shl 4 or H2BConvert[ValueBuff[Pos + 2]];
Inc(Pos, 3);
end
else
begin
if (ValueBuff[Pos] = Ord('+')) and PlusAsSpaces then
Buff[Cnt] := Ord(' ')
else
Buff[Cnt] := ValueBuff[Pos];
Inc(Pos);
end;
Inc(Cnt);
end;
Result := TEncoding.UTF8.GetString(Buff, 0 , Cnt);
end;
class function TURI.URLEncode(const AValue: string; SpacesAsPlus: Boolean): string;
const
FormUnsafeChars: TURLEncoding.TUnsafeChars = [Ord('!'), Ord('"'), Ord('#'), Ord('$'), Ord('%'), Ord('&'), Ord(''''),
Ord('('), Ord(')'), Ord('*'), Ord('+'), Ord(','), Ord('"'), Ord('/'), Ord(':'), Ord(';'), Ord('<'), Ord('>'),
Ord('='), Ord('?'), Ord('@'), Ord('['), Ord(']'), Ord('\'), Ord('^'), Ord('`'), Ord('{'), Ord('}'), Ord('|')];
var
LEncoding: TURLEncoding;
begin
LEncoding := TURLEncoding.Create;
try
if SpacesAsPlus then
Result := LEncoding.Encode(AValue, FormUnsafeChars, [TURLEncoding.TEncodeOption.SpacesAsPlus])
else
Result := LEncoding.Encode(AValue, FormUnsafeChars, []);
finally
LEncoding.Free;
end;
end;
class function TURI.FixupForREST(const AURL: string): string;
var
LUri: TURI;
begin
if Trim(AURL) = '' then
Result := ''
else
begin
LUri.DecomposeURI(AURL, False);
if LUri.Scheme = '' then
LUri.DecomposeURI(SCHEME_HTTP + '://' + AURL, True);
Result := Trim(LUri.ToString);
end;
end;
function TURI.Encode: string;
begin
ComposeURI(FScheme, FUsername, FPassword, FHost, FPort, FPath, FParams, FFragment);
Result := ToString;
end;
{ TProxySettings }
constructor TProxySettings.Create(const AURL: string);
var
LURL: TURI;
begin
LURL := TURI.Create(AURL);
FScheme := LURL.Scheme;
FHost := LURL.Host;
FPort := LURL.Port;
FUserName := LURL.Username;
FPassword := LURL.Password;
FCredential := TCredentialsStorage.TCredential.Create(TAuthTargetType.Proxy, '', '', FUserName, FPassword);
end;
constructor TProxySettings.Create(const AHost: string; APort: Integer; const AUserName, APassword, AScheme: string);
begin
FScheme := AScheme;
FHost := AHost;
FPort := APort;
FUserName := AUsername;
FPassword := APassword;
FCredential := TCredentialsStorage.TCredential.Create(TAuthTargetType.Proxy, '', '', FUserName, FPassword);
end;
function TProxySettings.GetCredential: TCredentialsStorage.TCredential;
begin
Result := TCredentialsStorage.TCredential.Create(TAuthTargetType.Proxy, '', '', FUserName, FPassword);
end;
{ TURLClient }
constructor TURLClient.Create;
begin
inherited;
FCustomHeaders := [TNetHeader.Create(sUserAgent, DefaultUserAgent)];
FInternalCredentialsStorage := TCredentialsStorage.Create;
FInstances := TObjectDictionary<string, TURLClient>.Create;
FCredentialsStorage := FInternalCredentialsStorage;
FConnectionTimeout := DefaultConnectionTimeout;
FResponseTimeout := DefaultResponseTimeout;
end;
function TURLClient.GetCredentials(AuthTarget: TAuthTargetType;
const ARealm, URL: string): TCredentialsStorage.TCredentialArray;
begin
Result := TCredentialsStorage.SortCredentials(FCredentialsStorage.FindCredentials(AuthTarget, ARealm, URL));
end;
function TURLClient.GetCustomHeaderValue(const Name: string): string;
var
I, Max: Integer;
begin
Result := '';
I := 0;
Max := Length(FCustomHeaders);
while I < Max do
begin
if string.CompareText(FCustomHeaders[I].Name, Name) = 0 then
begin
Result := FCustomHeaders[I].Value;
Break;
end;
Inc(I);
end;
end;
class function TURLClient.GetInstance(const AScheme: string): TURLClient;
begin
Result := TURLSchemes.GetURLClientInstance(AScheme);
end;
function TURLClient.GetInternalInstance(const AScheme: string): TURLClient;
function IsSupportedScheme(const AScheme: string): Boolean;
var
I: Integer;
begin
for I := 0 to High(SupportedSchemes) do
if string.CompareText(SupportedSchemes[I], AScheme) = 0 then
Exit(True);
Result := False;
end;
begin
if IsSupportedScheme(AScheme) then
Result := Self
else
begin
TMonitor.Enter(FInstances);
try
if not FInstances.TryGetValue(AScheme, Result) then
begin
Result := GetInstance(AScheme);
if Result <> nil then
FInstances.Add(AScheme, Result)
else
raise ENetURIClientException.CreateResFmt(@SSchemeNotRegistered, [AScheme]);
end;
finally
TMonitor.Exit(FInstances);
end;
end;
end;
function TURLClient.GetUserAgent: string;
begin
Result := GetCustomHeaderValue(sUserAgent);
end;
class function TURLClient.CreateInstance: TURLClient;
begin
raise ENetURIClientException.CreateRes(@SNetPlatformFunctionNotImplemented);
end;
destructor TURLClient.Destroy;
begin
FInstances.Free;
FInternalCredentialsStorage.Free;
inherited;
end;
procedure TURLClient.DoAuthCallback(AnAuthTarget: TAuthTargetType; const ARealm, AURL: string;
var AUserName, APassword: string; var AbortAuth: Boolean; var Persistence: TAuthPersistenceType);
begin
if Assigned(FAuthCallback) then
FAuthCallback(Self, AnAuthTarget, ARealm, AURL, AUserName, APassword, AbortAuth, Persistence)
else if Assigned(FAuthEvent) then
FAuthEvent(Self, AnAuthTarget, ARealm, AURL, AUserName, APassword, AbortAuth, Persistence);
end;
function TURLClient.DoExecute(const ARequestMethod: string; const AURI: TURI; const ASourceStream,
AContentStream: TStream; const AHeaders: TNetHeaders): IURLResponse;
begin
raise ENetURIClientException.CreateRes(@SNetSchemeFunctionNotImplemented);
end;
function TURLClient.DoExecuteAsync(const AsyncCallback: TAsyncCallback; const AsyncCallbackEvent: TAsyncCallbackEvent;
const ARequestMethod: string; const AURI: TURI; const ASourceStream, AContentStream: TStream;
const AHeaders: TNetHeaders; AOwnsSourceStream: Boolean): IAsyncResult;
begin
raise ENetURIClientException.CreateRes(@SNetSchemeFunctionNotImplemented);
end;
function TURLClient.DoGetRequestInstance(const ARequestMethod: string; const AURI: TURI): IURLRequest;
begin
raise ENetURIClientException.CreateRes(@SNetSchemeFunctionNotImplemented);
end;
function TURLClient.GetRequest(const ARequestMethod: string; const AURI: TURI): IURLRequest;
begin
Result := DoGetRequestInstance(ARequestMethod, AURI);
end;
function TURLClient.GetRequest(const ARequestMethod, AURI: string): IURLRequest;
begin
Result := DoGetRequestInstance(ARequestMethod, TURI.Create(AURI));
end;
function TURLClient.DoGetResponseInstance(const AContext: TObject; const AProc: TProc; const AsyncCallback: TAsyncCallback;
const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest; const AContentStream: TStream): IAsyncResult;
begin
raise ENetURIClientException.CreateRes(@SNetSchemeFunctionNotImplemented);
end;
class function TURLClient.EndAsyncURL(const AAsyncResult: IAsyncResult): IURLResponse;
begin
(AAsyncResult as TURLResponse).WaitForCompletion;
Result := AAsyncResult as IURLResponse;
end;
class function TURLClient.EndAsyncURL(const AAsyncResult: IURLResponse): IURLResponse;
begin
(AAsyncResult as TURLResponse).WaitForCompletion;
Result := AAsyncResult;
end;
function TURLClient.Execute(const ARequestMethod: string; const AURI: TURI; const ASourceStream, AContentStream: TStream; const AHeaders: TNetHeaders): IURLResponse;
begin
Result := GetInternalInstance(AURI.Scheme).DoExecute(ARequestMethod, AURI, ASourceStream, AContentStream, AHeaders);
end;
function TURLClient.Execute(const ARequestMethod, AURIStr: string; const ASourceStream, AContentStream: TStream; const AHeaders: TNetHeaders): IURLResponse;
begin
Result := Execute(ARequestMethod, TURI.Create(AURIStr), ASourceStream, AContentStream, AHeaders);
end;
function TURLClient.BeginExecute(const AsyncCallback: TAsyncCallback; const ARequestMethod: string; const AURI: TURI;
const ASourceStream, AContentStream: TStream; const AHeaders: TNetHeaders): IAsyncResult;
begin
Result := GetInternalInstance(AURI.Scheme).DoExecuteAsync(AsyncCallback, nil, ARequestMethod, AURI, ASourceStream, AContentStream, AHeaders);
end;
function TURLClient.BeginExecute(const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequestMethod: string;
const AURI: TURI; const ASourceStream, AContentStream: TStream; const AHeaders: TNetHeaders): IAsyncResult;
begin
Result := GetInternalInstance(AURI.Scheme).DoExecuteAsync(nil, AsyncCallbackEvent, ARequestMethod, AURI, ASourceStream, AContentStream, AHeaders);
end;
function TURLClient.BeginExecute(const AsyncCallback: TAsyncCallback; const ARequestMethod, AURIStr: string;
const ASourceStream, AContentStream: TStream; const AHeaders: TNetHeaders): IAsyncResult;
begin
Result := BeginExecute(AsyncCallback, ARequestMethod, TURI.Create(AURIStr), ASourceStream, AContentStream, AHeaders);
end;
function TURLClient.BeginExecute(const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequestMethod, AURIStr: string;
const ASourceStream, AContentStream: TStream; const AHeaders: TNetHeaders): IAsyncResult;
begin
Result := BeginExecute(AsyncCallbackEvent, ARequestMethod, TURI.Create(AURIStr), ASourceStream, AContentStream, AHeaders);
end;
function TURLClient.BeginExecute(const ARequestMethod: string; const AURI: TURI; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IAsyncResult;
begin
Result := GetInternalInstance(AURI.Scheme).DoExecuteAsync(nil, nil, ARequestMethod, AURI, ASourceStream, AContentStream, AHeaders);
end;
function TURLClient.BeginExecute(const ARequestMethod: string; const AURIStr: string; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IAsyncResult;
begin
Result := BeginExecute(ARequestMethod, TURI.Create(AURIStr), ASourceStream, AContentStream, AHeaders);
end;
procedure TURLClient.SetCustomHeaderValue(const Name, Value: string);
var
I, Max: Integer;
begin
I := 0;
Max := Length(FCustomHeaders);
while I < Max do
begin
if string.CompareText(FCustomHeaders[I].Name, Name) = 0 then
Break;
Inc(I);
end;
if I = Max then
begin
SetLength(FCustomHeaders, Max + 1);
FCustomHeaders[I].Name := Name;
end;
FCustomHeaders[I].Value := Value;
end;
procedure TURLClient.SetConnectionTimeout(const Value: Integer);
begin
FConnectionTimeout := Value;
end;
procedure TURLClient.SetCredentialsStorage(const Value: TCredentialsStorage);
begin
if Value = nil then
begin
FCredentialsStorage := FInternalCredentialsStorage;
//FCredentialsStorage.ClearCredentials; //TODO -ojulianm: decide if we clear the cached credentials
end
else
FCredentialsStorage := Value;
end;
procedure TURLClient.SetProxySettings(const Value: TProxySettings);
var
LCredential: TCredentialsStorage.TCredential;
LURI: TURI;
begin
FProxySettings := Value;
// If there is a user information, we create the credential needed for authenticating, and add it to the storage.
if Value.Username <> '' then
begin
LURI.FHost := Value.FHost;
LURI.FPort := Value.FPort;
LURI.FScheme := Value.FScheme.ToLower;
if LURI.FScheme = '' then
LURI.FScheme := TURI.SCHEME_HTTP;
LCredential := TCredentialsStorage.TCredential.Create(TAuthTargetType.Proxy, '', LURI.ToString,
Value.FUserName, Value.FPassword);
FCredentialsStorage.AddCredential(LCredential);
end;
end;
procedure TURLClient.SetResponseTimeout(const Value: Integer);
begin
FResponseTimeout := Value;
end;
procedure TURLClient.SetUserAgent(const Value: string);
begin
SetCustomHeaderValue(sUserAgent, Value);
end;
function TURLClient.SupportedSchemes: TArray<string>;
begin
Result := [];
end;
{ TURLClientSchemes }
class constructor TURLSchemes.Create;
begin
FSchemeClients := TDictionary<string, TURLClientClass>.Create;
end;
class destructor TURLSchemes.Destroy;
begin
FSchemeClients.Free;
end;
class function TURLSchemes.GetURLClientInstance(const AScheme: string): TURLClient;
var
LClientClass: TURLClientClass;
begin
Result := nil;
FSchemeClients.TryGetValue(AScheme.ToUpper, LClientClass);
if LClientClass <> nil then
Result := LClientClass.CreateInstance;
end;
class procedure TURLSchemes.RegisterURLClientScheme(const AURLClientClass: TURLClientClass; const AScheme: string);
var
LScheme: string;
begin
LScheme := AScheme.ToUpper;
if FSchemeClients.ContainsKey(LScheme) then
raise ENetException.CreateResFmt(@SSchemeAlreadyRegistered, [LScheme, 'Client']); // Do not translate
FSchemeClients.Add(LScheme, AURLClientClass);
end;
class procedure TURLSchemes.UnRegisterURLClientScheme(const AScheme: string);
begin
FSchemeClients.Remove(AScheme.ToUpper);
end;
{ TURLRequest }
constructor TURLRequest.Create(const AClient: TURLClient; const AMethodString: string; const AURI: TURI);
begin
inherited Create;
FURL := AURI;
FClient := AClient;
FMethodString := AMethodString;
FConnectionTimeout := FClient.FConnectionTimeout;
FResponseTimeout := FClient.FResponseTimeout;
FLocalCredential := TCredentialsStorage.TCredential.Create(TAuthTargetType.Server, '',
AURI.Host, AURI.Username, AUri.Password);
end;
destructor TURLRequest.Destroy;
begin
inherited;
end;
function TURLRequest.GetCredential: TCredentialsStorage.TCredential;
begin
Result := FLocalCredential;
end;
function TURLRequest.GetMethodString: string;
begin
Result := FMethodString;
end;
function TURLRequest.GetSourceStream: TStream;
begin
Result := FSourceStream;
end;
function TURLRequest.GetURL: TURI;
begin
Result := FURL;
end;
procedure TURLRequest.SetCredential(const ACredential: TCredentialsStorage.TCredential);
begin
FLocalCredential := ACredential;
end;
procedure TURLRequest.SetConnectionTimeout(const Value: Integer);
begin
FConnectionTimeout := Value;
end;
procedure TURLRequest.SetCredential(const AUserName, APassword: string);
begin
SetCredential(TCredentialsStorage.TCredential.Create(TAuthTargetType.Server, '', FURL.Host, AUserName, APassword));
end;
procedure TURLRequest.SetMethodString(const AValue: string);
begin
if FMethodString <> '' then
raise ENetURIRequestException.CreateRes(@SNetUriMethodAlreadyAssigned);
FMethodString := AValue.ToUpper;
end;
procedure TURLRequest.SetResponseTimeout(const Value: Integer);
begin
FResponseTimeout := Value;
end;
procedure TURLRequest.SetSourceStream(const ASourceStream: TStream);
begin
FSourceStream := ASourceStream;
end;
procedure TURLRequest.SetURL(const AValue: TURI);
begin
if FURL.Host <> '' then
raise ENetURIRequestException.CreateRes(@SNetUriURLAlreadyAssigned);
FURL := AValue;
end;
{ TCredentialsStorage.TCredential }
constructor TCredentialsStorage.TCredential.Create(AnAuthTarget: TAuthTargetType;
const ARealm, AURL, AUserName, APassword: string);
begin
AuthTarget := AnAuthTarget;
Realm := ARealm;
URL := AURL;
UserName := AUserName;
Password := APassword;
end;
{ TCredentialsStorage }
function TCredentialsStorage.AddCredential(const ACredential: TCredential): Boolean;
var
LCredentials: TCredentialArray;
begin
if (ACredential.AuthTarget = TAuthTargetType.Server) and
((ACredential.UserName = '') and (ACredential.Password = '')) then
raise ENetCredentialException.CreateRes(@SCredentialInvalidUserPassword);
LCredentials := FindCredentials(ACredential.AuthTarget, ACredential.Realm, ACredential.URL, ACredential.UserName);
if Length(LCredentials) = 0 then
begin
TMonitor.Enter(FCredentials);
try
FCredentials.Add(ACredential);
Result := True;
finally
TMonitor.Exit(FCredentials);
end;
end
else
Result := False;
end;
function TCredentialsStorage.FindCredentials(AnAuthTargetType: TAuthTargetType;
const ARealm, AURL, AUser: string): TCredentialArray;
var
LCredential: TCredential;
LValid: Boolean;
// LValidURL: Boolean;
LHost: string;
LCredentialHost: string;
begin
Result := [];
TMonitor.Enter(FCredentials);
try
if AURL = '' then
LHost := ''
else
LHost := TURI.Create(AURL).Host;
for LCredential in FCredentials do
begin
if LCredential.URL = '' then
LCredentialHost := ''
else
LCredentialHost := TURI.Create(LCredential.URL).Host;
LValid := AnAuthTargetType = LCredential.AuthTarget;
LValid := LValid and ((ARealm = '') or ((ARealm <> '') and ((LCredential.Realm = '') or
((LCredential.Realm <> '') and
(string.CompareText(LCredential.Realm, ARealm) = 0)
)
)));
// LValidURL := ((LCredential.URL <> '') and (AURL.StartsWith(LCredential.URL, True)));
// LValid := LValid and ((AURL = '') or ((AURL <> '') and ((LCredential.URL = '') or
// ((LCredential.URL <> '') and (AURL.StartsWith(LCredential.URL, True)))
// )));
LValid := LValid and ((AURL = '') or ((AURL <> '') and ((LCredentialHost = '') or
((LCredentialHost <> '') and (LHost.StartsWith(LCredentialHost, True)))
)));
LValid := LValid and ((AUser = '') or (string.CompareText(LCredential.UserName, AUser) = 0));
if LValid then
Result := Result + [LCredential];
end;
finally
TMonitor.Exit(FCredentials);
end;
end;
class constructor TCredentialsStorage.Create;
begin
FCredComparer := TCredentialComparer.Create;
end;
class destructor TCredentialsStorage.Destroy;
begin
FCredComparer.Free;
end;
procedure TCredentialsStorage.ClearCredentials;
begin
TMonitor.Enter(FCredentials);
try
FCredentials.Clear;
finally
TMonitor.Exit(FCredentials);
end;
end;
constructor TCredentialsStorage.Create;
begin
inherited;
FCredentials := TList<TCredential>.Create;
end;
destructor TCredentialsStorage.Destroy;
begin
FCredentials.Free;
inherited;
end;
function TCredentialsStorage.FindAccurateCredential(AnAuthTargetType: TAuthTargetType;
const ARealm, AURL, AUser: string): TCredential;
var
LCredential: TCredential;
LValid: Boolean;
begin
Result := Default(TCredential);
TMonitor.Enter(FCredentials);
try
for LCredential in FCredentials do
begin
LValid := AnAuthTargetType = LCredential.AuthTarget;
LValid := LValid and ((ARealm = '') or (string.CompareText(LCredential.Realm, ARealm) = 0));
LValid := LValid and ((AURL = '') or AURL.StartsWith(LCredential.URL));
LValid := LValid and ((AUser = '') or (string.CompareText(LCredential.UserName, AUser) = 0));
if LValid and (Result.URL.Length < LCredential.URL.Length) then
Result := LCredential;
end;
finally
TMonitor.Exit(FCredentials);
end;
end;
function TCredentialsStorage.GetCredentials: TCredentialArray;
begin
Result := FCredentials.ToArray;
end;
function TCredentialsStorage.RemoveCredential(AnAuthTargetType: TAuthTargetType;
const ARealm, AURL, AUser: string): Boolean;
var
I: Integer;
LEqual: Boolean;
begin
Result := False;
TMonitor.Enter(FCredentials);
try
for I := FCredentials.Count - 1 downto 0 do
begin
LEqual := AnAuthTargetType = FCredentials[I].AuthTarget;
LEqual := LEqual and (string.CompareText(FCredentials[I].Realm, ARealm) = 0);
LEqual := LEqual and (string.CompareText(FCredentials[I].URL, AURL) = 0);
LEqual := LEqual and (string.CompareText(FCredentials[I].UserName, AUser) = 0);
if LEqual then
begin
FCredentials.Delete(I);
Result := True;
end;
end;
finally
TMonitor.Exit(FCredentials);
end;
end;
class function TCredentialsStorage.SortCredentials(
const ACredentials: TCredentialsStorage.TCredentialArray): TCredentialsStorage.TCredentialArray;
begin
Result := ACredentials;
TArray.Sort<TCredentialsStorage.TCredential>(Result, FCredComparer);
end;
{ TCredentialsStorage.TCredentialComparer }
function TCredentialsStorage.TCredentialComparer.Compare(const Left, Right: TCredential): Integer;
begin
Result := 0;
if (Left.Realm <> '') then
begin
if (Right.Realm = '') then
Result := -1
else
Result := string.CompareText(Left.Realm, Right.Realm);
end
else
begin
if (Right.Realm <> '') then
Result := 1;
end;
if Result = 0 then
Result := - string.CompareText(Left.URL, Right.URL);
if Result = 0 then
Result := string.CompareText(Left.UserName, Right.UserName);
end;
{ TURLResponse }
procedure TURLResponse.AsyncDispatch;
begin
if Assigned(FProc) then
FProc;
end;
procedure TURLResponse.Complete;
begin
inherited Complete;
if Assigned(FAsyncCallback) then
FAsyncCallback(Self as IAsyncResult)
else if Assigned(FAsyncCallbackEvent) then
FAsyncCallbackEvent(Self as IAsyncResult);
FProc := nil;
FAsyncCallback := nil;
end;
constructor TURLResponse.Create(const AContext: TObject; const ARequest: IURLRequest; const AContentStream: TStream);
begin
inherited Create(AContext);
FRequest := ARequest;
if AContentStream <> nil then
FStream := AContentStream
else
begin
FInternalStream := DoCreateInternalStream;
FStream := FInternalStream;
end;
end;
constructor TURLResponse.Create(const AContext: TObject; const AProc: TProc; const AAsyncCallback: TAsyncCallback;
const AAsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest; const AContentStream: TStream);
begin
Create(AContext, ARequest, AContentStream);
FAsyncCallback := AAsyncCallback;
FAsyncCallbackEvent := AAsyncCallbackEvent;
FProc := AProc;
end;
destructor TURLResponse.Destroy;
begin
inherited;
FInternalStream.Free;
end;
function TURLResponse.DoCancel: Boolean;
begin
Result := FRequest <> nil;
if Result then
(FRequest as TURLRequest).FCancelled := True;
end;
function TURLResponse.DoCreateInternalStream: TStream;
begin
Result := TMemoryStream.Create;
end;
function TURLResponse.GetContentStream: TStream;
begin
Result := FStream;
end;
procedure TURLResponse.Schedule;
begin
// If FProc is assigned, this is an asynchronous response. Otherwise process it sequentially
if Assigned(FProc) then
TTask.Run(DoAsyncDispatch)
else
DoAsyncDispatch;
end;
{ TPunyCode }
class function TPunyCode.DoEncode(const AString: UCS4String): UCS4String;
var
N, LDelta, LBias, b, q, m, k, t: Cardinal;
I: Integer;
h: Integer;
LenAStr: Integer;
begin
Result := nil;
if AString = nil then
Exit;
try
N := INITIAL_N;
LBias := INITIAL_BIAS;
LenAStr := Length(AString) - 1;
for I := 0 to LenAStr - 1 do
if IsBasic(AString, I, INITIAL_N) then
Result := Result + [AString[I]];
b := Length(Result);
if (Length(Result) < LenAStr) and (Length(Result) >= 0) then
Result := Result + [Cardinal(Delimiter)];
h := b;
LDelta := 0;
while h < LenAStr do
begin
m := GetMinCodePoint(N, AString);
LDelta := LDelta + (m - N) * Cardinal(h + 1);
N := m;
for I := 0 to LenAStr - 1 do
begin
if IsBasic(AString, I, N) then
Inc(LDelta)
else if AString[I] = N then
begin
q := LDelta;
k := BASE;
while k <= MAX_INT do
begin
if k <= (LBias + TMIN) then
t := TMIN
else if k >= (LBias + TMAX) then
t := TMAX
else
t := k - LBias;
if q < t then
break;
Result := Result + [Digit2Codepoint(t + ((q - t) mod (BASE - t)))];
q := (q - t) div (BASE - t);
Inc(k, BASE);
end;
Result := Result + [Digit2Codepoint(q)];
LBias := Adapt(LDelta, h + 1, Cardinal(h) = b);
LDelta := 0;
Inc(h);
end;
end;
Inc(LDelta);
Inc(n);
end;
Result := Result + [0];
except
Result := AString;
end;
end;
class function TPunyCode.DoDecode(const AString: UCS4String): UCS4String;
function LastIndexOf(const ADelimiter: UCS4Char; const AString: UCS4String): Integer;
var
Pos: Integer;
begin
Result := -1;
for Pos := Length(AString) - 1 downto 0 do
if AString[Pos] = ADelimiter then
begin
Result := Pos;
Break;
end;
end;
var
J: Integer;
I, OldI, N, LBias, w, k, t: Cardinal;
LPos, textLen, LCurrentLen: Integer;
LDigit: Cardinal;
c: UCS4Char;
begin
Result := [];
if Length(AString) = 0 then
Exit;
try
N := INITIAL_N;
LBias := INITIAL_BIAS;
LPos := LastIndexOf(UCS4Char(Delimiter), AString);
if LPos < 0 then
Exit(AString);
for J := 0 to (LPos - 1) do
if AString[J] >= INITIAL_N then
Exit;
Result := Copy(AString, 0, LPos);// + 1);
I := 0;
Inc(LPos);
textLen := Length(AString) - 1;
while LPos < textLen do
begin
OldI := I;
w := 1;
k := BASE;
while (k <= MAX_INT) and (LPos < textLen) do
begin
c := AString[LPos];
Inc(LPos);
LDigit := Codepoint2Digit(c);
if ((LDigit >= BASE) or (LDigit > ((MAX_INT - i) / w))) then
Exit(Result);
I := I + LDigit * w;
if k <= LBias then
t := TMIN
else
if k >= (LBias + TMAX) then
t := TMAX
else
t := k - LBias;
if LDigit < t then
break;
if w > (MAX_INT / (base - t)) then
Exit(nil);
w := w * (BASE - t);
Inc(k, BASE);
end;
LCurrentLen := Length(Result) + 1;
LBias := Adapt(I - OldI, LCurrentLen, OldI = 0);
if (I / LCurrentLen) > (MAX_INT - N) then
Exit(nil);
N := N + I div Cardinal(LCurrentLen);
I := I mod Cardinal(LCurrentLen);
if IsBasic([N], 0, INITIAL_N) then
Exit(nil);
Result := Copy(Result, 0, I) + [N] + Copy(Result, I, Length(Result) - Integer(I));
Inc(I);
end;
Result := Result + [0];
except
Result := AString;
end;
end;
class function TPunyCode.DoEncode(const AString: string): string;
var
LStr, LResult: UCS4String;
begin
LStr := UnicodeStringToUCS4String(AString);
LResult := DoEncode(LStr);
if LResult <> nil then
Result := UCS4StringToUnicodeString(LResult)
else
Result := AString;
end;
class function TPunyCode.DoDecode(const AString: string): string;
var
LStr, LResult: UCS4String;
begin
LStr := UnicodeStringToUCS4String(AString);
LResult := DoDecode(LStr);
if LResult <> nil then
Result := UCS4StringToUnicodeString(LResult)
else
Result := AString;
end;
class function TPunyCode.IsBasic(const AString: UCS4String; const AIndex, AMinLimit: Cardinal): Boolean;
begin
Result := AString[AIndex] < AMinLimit;
end;
class function TPunyCode.Adapt(const ADelta, ANumPoints: Cardinal; const FirstTime: Boolean): Cardinal;
var
k, dt: Cardinal;
begin
if FirstTime = True then
dt := ADelta div DAMP
else
dt := ADelta div 2;
dt := dt + (dt div ANumPoints);
k := 0;
while dt > (((BASE - TMIN) * TMAX) div 2) do
begin
dt := dt div (BASE - TMIN);
Inc(k, BASE);
end;
Result := k + (((BASE - TMIN + 1) * dt) div (dt + SKEW));
end;
class function TPunyCode.Encode(const AString: string): string;
var
Aux: string;
begin
Result := DoEncode(AString);
Aux := DoDecode(Result);
if Aux <> AString then
Result := AString;
end;
class function TPunyCode.Decode(const AString: string): string;
var
Aux: string;
begin
Result := DoDecode(AString);
Aux := DoEncode(Result);
if Aux <> AString then
Result := AString;
end;
class function TPunyCode.Digit2Codepoint(const ADigit: Cardinal): Cardinal;
begin
Result := 0;
if ADigit < 26 then
Result := ADigit + 97
else if ADigit < 36 then
Result := ADigit - 26 + 48;
end;
class function TPunyCode.Codepoint2Digit(const ACodePoint: Cardinal): Cardinal;
begin
Result := BASE;
if (ACodePoint - 48) < 10 then
Result := ACodePoint - 22
else if (ACodePoint - 65) < 26 then
Result := ACodePoint - 65
else if (ACodePoint - 97) < 26 then
Result := ACodePoint - 97;
end;
class function TPunyCode.GetMinCodePoint(const AMinLimit: Cardinal; const AString: UCS4String): Cardinal;
var
I: Integer;
LMinCandidate: Cardinal;
begin
Result := Cardinal.MaxValue;
for I := 0 to Length(AString) - 1 do
begin
LMinCandidate := AString[I];
if (LMinCandidate >= AMinLimit) and (LMinCandidate < Result) then
Result := LMinCandidate;
end;
end;
{ TCertificateHelper }
{$WARN SYMBOL_DEPRECATED OFF}
function TCertificateHelper.GetCertName: string;
begin
Result := ProtocolName;
end;
procedure TCertificateHelper.SetCertName(const AValue: string);
begin
ProtocolName := AValue;
end;
function TCertificateHelper.GetSerialNum: string;
begin
Result := AlgEncryption;
end;
procedure TCertificateHelper.SetSerialNum(const AValue: string);
begin
AlgEncryption := AValue;
end;
function TCertificateHelper.IsDefined: Boolean;
begin
Result := (Expiry <> 0) or (Subject <> '') or (Issuer <> '') or
(CertName <> '') or (SerialNum <> '');
end;
{$WARN SYMBOL_DEPRECATED ON}
end.
|
unit uEngine;
{$ZEROBASEDSTRINGS OFF}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
System.Math.Vectors,System.JSON, DateUtils,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,FMX.Objects,
uEngine2DModel, uEngine2DSprite, uEngineUtils, uEngineThread,
uEngineResource, NewScript;
{TEngine2D类负责场景内容的重绘,统一管理各模块}
Type
TEngine2D = class(TShape)
private
FEngineTimer : TTimer;
FEngineModel : TEngine2DModel;
FResManager : TEngineResManager;
FImage: TImage; // 画布 ...
FThread : TEngineThread;
FBackground : TBitmap;
FDrawBuffer : TBitmap;
FWidth : Single;
FHeight : Single;
FTime : TDateTime;
FOnMouseDown,FOnMouseUp : TMouseEvent;
FOnMouseMove : TMouseMoveEvent;
procedure SetImage(const Value: TImage);
procedure SetHeight(value : Single);
procedure MouseDown(Button: TMouseButton;
Shift: TShiftState; x, y: single); override;
procedure MouseUp(Button: TMouseButton;
Shift: TShiftState; x, y: single); override;
procedure MouseMove(Shift: TShiftState; X,
Y: Single); override;
protected
procedure Draw(Sender : TObject);
procedure UpdateSpriteBitmap;
Procedure Paint; Override;
public
Constructor Create(AOwner : TComponent);
Destructor Destroy;override;
procedure LoadAnimation(AConfigName:String; AResManager : TEngineResManager);
procedure Resize(const AWidth, AHeight: Integer);
Procedure ThreadWork;
property IMGCanvas : TImage read FImage write SetImage;
property Background : TBitmap Read FBackground;
Property DrawBuffer : TBitmap Read FDrawBuffer;
property EngineModel : TEngine2DModel read FEngineModel;
property OnMouseDown : TMouseEvent read FOnMouseDown write FOnMouseDown;
property OnMouseUp : TMouseEvent read FOnMouseUp write FOnMouseUp;
property OnMouseMove : TMouseMoveEvent read FOnMouseMove write FOnMouseMove;
end;
var
G_Engine : TEngine2D;
implementation
uses
uEngineConfig,uEngine2DObject,uPublic;
{ TEngine2D }
constructor TEngine2D.Create(AOwner : TComponent);
begin
Inherited;
FEngineTimer := TTimer.Create(nil);
FEngineTimer.Interval := DRAW_INTERVAL;
FEngineTimer.OnTimer := Draw;
FEngineTimer.Enabled := false;
FEngineModel := TEngine2DModel.Create;
FBackground := TBitmap.Create;
FDrawBuffer := TBitmap.Create;
// FCurrentInvadedName := '';
//FThread := TEngineThread.Create(true);
end;
destructor TEngine2D.Destroy;
begin
FEngineTimer.DisposeOf;
FEngineModel.DisposeOf;
FBackground.DisposeOf;
FDrawBuffer.DisposeOf;
//FThread.Terminate;
inherited;
end;
procedure TEngine2D.Draw(Sender: TObject);
var
LMatrix, Matrix : TMatrix;
i, J: Integer;
LCount : Integer;
TimeDur : Integer;
tmpP : TPointF;
begin
// draw sprite
TimeDur := Round(abs(MilliSecondSpan(FTime, Now)));
FTime := Now;
UpdateSpriteBitmap;
With FDrawBuffer do
begin
Canvas.BeginScene();
try
Canvas.Clear($00000000);
LMatrix := Canvas.Matrix;
Canvas.DrawBitmap(FBackground,
RectF(0,0,FBackground.Width,FBackground.Height),
RectF(0,0,FWidth,FHeight),1, true);
LCount := FEngineModel.SpriteCount;
if LCount > 0 then
begin
for i := 0 to LCount-1 do
begin
if FEngineModel.SpriteList.Items[i].Visible then
begin
FEngineModel.SpriteList.Items[i].Repaint(TimeDur);
end;
end;
end;
// draw star
LCount := FEngineModel.StarSpriteCount;
if LCount > 0 then
begin
for i := 0 to LCount-1 do
begin
if FEngineModel.StarSpriteList.Items[i].Visible then
begin
FEngineModel.StarSpriteList.Items[i].Repaint(TimeDur);
end;
end;
end;
Canvas.SetMatrix(LMatrix);
// 将可入侵区域画出来,这样可以测试的时候用一下...
// if FEngineModel.InvadeManager.FConvexPolygon.ItemCount > 0 then
// begin
// for I := 0 to FEngineModel.InvadeManager.FConvexPolygon.ItemCount-1 do
// begin
// if 'ID2' = FEngineModel.InvadeManager.FConvexPolygon.Items[I].Name then
// begin
// Canvas.Stroke.Color := TAlphaColors.Red;
// Canvas.Fill.Color := TAlphaColors.Red;
// end else
// begin
// Canvas.Stroke.Color := TAlphaColors.Black;
// Canvas.Fill.Color := TAlphaColors.Black;
// end;
// for J := 0 to High(FEngineModel.InvadeManager.FConvexPolygon.Items[i].AllPoints) do
// begin
// tmpP := FEngineModel.InvadeManager.FConvexPolygon.Items[i].AllPoints[j];
// //Canvas.DrawEllipse(RectF(tmpP.X-2, tmpP.Y - 2, tmpP.X+2, tmpP.Y+2),1);
// Canvas.FillEllipse(RectF(tmpP.X-2, tmpP.Y - 2, tmpP.X+2, tmpP.Y+2),1);
// end;
// end;
// end;
finally
Canvas.EndScene;
end;
end;
Repaint;
end;
procedure TEngine2D.LoadAnimation(AConfigName:String; AResManager : TEngineResManager);
var
LBackgroundName : String;
// LObject : TJSONObject;
LValue : String;
begin
FResManager := AResManager;
FResManager.UpdateConfig(AConfigName);
LBackgroundName := FResManager.GetJSONValue('Background');
FResManager.LoadResource(FBackground, LBackgroundName);
LValue := FResManager.GetJSONValue('OnMouseDown');
if LValue <> '' then
Self.OnMouseDown := G_CurrentLogic.MouseDownHandler;
LValue := FResManager.GetJSONValue('OnMouseMove');
if LValue <> '' then
Self.OnMouseMove := G_CurrentLogic.MouseMoveHandler;
LValue := FResManager.GetJSONValue('OnMouseUp');
if LValue <> '' then
Self.OnMouseUp := G_CurrentLogic.MouseUpHandler;
// FEngineModel.LoadResource(FBackground, LBackgroundName);
FEngineModel.LoadConfig(FDrawBuffer,AConfigName,AResManager);
FEngineTimer.Enabled := true;
FTime := Now;
G_CurrentLogic.EngineModel := FEngineModel;
//FThread.Start;
end;
procedure TEngine2D.UpdateSpriteBitmap;
begin
FEngineModel.UpdateSpriteBackground;
end;
Procedure TEngine2D.Paint;
begin
beginUpdate;
if assigned(DrawBuffer) then
Canvas.DrawBitmap(DrawBuffer, RectF(0, 0, DrawBuffer.Width,
DrawBuffer.Height), RectF(0, 0, Width, Height), 1);
inherited;
endUpdate;
end;
procedure TEngine2D.MouseDown(Button: TMouseButton;
Shift: TShiftState; x, y: single);
var
LSprite : TEngine2DSprite;
I : Integer;
begin
// 检查鼠标事件的时候,从列表的最后一个开始遍历...
for I := FEngineModel.SpriteList.ItemCount-1 downto 0 do
begin
LSprite := FEngineModel.SpriteList.Items[I];
if LSprite.Visible then
begin
if LSprite.IsMouseDown(Button, Shift, X, Y) then
begin
exit;
end;
end;
end;
if Assigned(FOnMouseDown) then
FOnMouseDown(Self,Button,Shift,x,y);
end;
procedure TEngine2D.MouseMove(Shift: TShiftState; X,
Y: Single);
var
LSprite : TEngine2DSprite;
i: Integer;
S : String;
begin
for I := FEngineModel.SpriteList.ItemCount-1 downto 0 do
begin
LSprite := FEngineModel.SpriteList.Items[I];
if LSprite.Visible then
begin
if LSprite.IsMouseMove(Shift, X, Y) then
begin
exit;
end;
end;
end;
if Assigned(FOnMouseMove) then
FOnMouseMove(Self,Shift,X,Y);
end;
procedure TEngine2D.MouseUp(Button: TMouseButton;
Shift: TShiftState; x, y: single);
var
i: Integer;
LSprite : TEngine2DSprite;
begin
// FCurrentDragSprite := nil;
for I := FEngineModel.SpriteList.ItemCount - 1 downto 0 do
begin
LSprite := FEngineModel.SpriteList.Items[i];
LSprite.IsMouseUp(Button, Shift, X, Y);
end;
if Assigned(FOnMouseUp) then
FOnMouseUp(Self,Button,Shift,x,y);
end;
procedure TEngine2D.Resize(const AWidth, AHeight: Integer);
var
i: Integer;
LObject : TEngine2DSprite;
begin
FWidth := AWidth;
FHeight := AHeight;
FDrawBuffer.Width := AWidth;
FDrawBuffer.Height := AHeight;
for i := 0 to FEngineModel.SpriteList.ItemCount-1 do
begin
LObject := FEngineModel.SpriteList.Items[i];
if LObject.Visible then
begin
LObject.Resize(AWidth, AHeight);
end;
end;
// star
for i := 0 to FEngineModel.StarSpriteList.ItemCount-1 do
begin
LObject := FEngineModel.StarSpriteList.Items[i];
if LObject.Visible then
begin
LObject.Resize(AWidth,AHeight);
end;
end;
end;
Procedure TEngine2D.ThreadWork;
begin
Draw(nil);
end;
procedure TEngine2D.SetHeight(value: Single);
begin
FHeight := value;
end;
procedure TEngine2D.SetImage(const Value: TImage);
begin
end;
end.
|
unit u_SolidWastte_Upload;
interface
uses
Classes, SysUtils, Math, SolidWasteService, Json, StrUtils;
Function SolidWastte_Upload(const Info: String): Integer;
function SolidWastte_Desc(RetCode: Byte): String;
implementation
uses
u_Log;
var
g_Intf: ISolidWasteService;
g_RetPaire: JSon.TJSONObject;
Function SolidWastte_Upload(const Info: String): Integer;
var
Log: IMultiLineLog;
RetStr: String;
begin
try
With MultiLineLog do
begin
AddLine('------------------------------------');
AddLine('数据:'#$D#$A+ Info);
Result:= -1;
if g_Intf = Nil then
begin
g_Intf:= GetISolidWasteService;
end;
if g_RetPaire = Nil then
begin
g_RetPaire:= TJSONObject.Create;
end;
RetStr:= g_Intf.process(Info);
With TJSONObject.ParseJSONValue(Trim(RetStr )) as TJSONObject do
begin
AddLine('返回值:' + RetStr);
RetStr:= (GetValue('obj') as TJSONString).Value;
Result:= StrToIntDef(RetStr, -1);
AddLine('解析值:' + IntToStr(Result));
Free;
end;
AddLine('------------------------------------');
Flush();
end;
except
On E: Exception do
begin
u_Log.Log(Format('发生异常: %s : %s', [E.ClassName, e.Message]));
end;
end;
end;
function SolidWastte_Desc(RetCode: Byte): String;
const
CONST_DESC_ARR: Array[0..7] of String = (
'001:执行成功验证通过',
'002:服务器接口发生异常',
'003:参数不正确',
'004:企业身份标识不合法(平台分配的唯一token)',
'005:电子联单编号不存在',
'006:车牌及驾驶员信息与转移联单信息不一致',
'007:车牌信息与转移联单信息不一致',
'008:驾驶员信息与转移联单信息不一致'
);
begin
if InRange(RetCode - 1, Low(CONST_DESC_ARR), High(CONST_DESC_ARR)) then
begin
Result:= CONST_DESC_ARR[RetCode - 1];
end
else
begin
Result:= Format('%-0.3d: 未定义的返回码', [RetCode]);
end;
end;
initialization
finalization
if g_RetPaire <> NIl then
FreeAndNil(g_RetPaire);
end.
|
unit ForestConsts;
interface
uses
Classes;
const
// Numbers
I_FILE_INDEX = $FFFFFFFF;
I_DEFAULT_COL_WIDTH = 64;
I_COL_COUNT = 68;
I_MIN_HEIGHT = 50;
I_NORMAL_HEIGHT = 300;
I_COLS_TO_FIND_LAST_ROW = 11;
I_WEIGHT_TO_FIND_LAST_ROW = 6;
// Settings and params
S_REG_KEY: AnsiString = 'Software\NeferSky\ForestUtil';
S_FORM_LEFT: AnsiString = 'FormLeft';
S_FORM_TOP: AnsiString = 'FormTop';
S_FORM_HEIGHT: AnsiString = 'FormHeight';
S_FORM_WIDTH: AnsiString = 'FormWidth';
S_EDIT_LEFT: AnsiString = 'EditLeft';
S_EDIT_TOP: AnsiString = 'EditTop';
S_EDIT_HEIGHT: AnsiString = 'EditHeight';
S_EDIT_WIDTH: AnsiString = 'EditWidth';
S_COMPRESS_COLUMNS: AnsiString = 'CompressColumns';
S_MATH_ERRORS: AnsiString = 'LogMathErrors';
S_DUPLICATES: AnsiString = 'LogDuplicates';
S_RELATION_ERRORS: AnsiString = 'LogRelationErrors';
S_DICT_REPLACES: AnsiString = 'LogDictReplaces';
S_EMPTY_RECORDS: AnsiString = 'LogEmptyRecords';
S_PREV_REPORT_SUM: AnsiString = 'LogPrevReportSum';
S_INI_GUI: AnsiString = 'GUI';
S_TRAY_ENABLED: AnsiString = 'TrayEnabled';
S_INI_QUERIES: AnsiString = 'Queries';
S_READING_INDEX: AnsiString = 'ReadingIndex';
S_WRITING_INDEX: AnsiString = 'WritingIndex';
S_ACTUAL_COUNT: AnsiString = 'ActualCount';
S_MAX_QUERIES_COUNT: AnsiString = 'MaxQueriesCount';
S_INI_TEMPLATES: AnsiString = 'Templates';
S_SELECT_TEMPLATE: AnsiString = 'SelectTemplate';
S_INSERT_TEMPLATE: AnsiString = 'InsertTemplate';
S_UPDATE_TEMPLATE: AnsiString = 'UpdateTemplate';
S_DELETE_TEMPLATE: AnsiString = 'DeleteTemplate';
S_INI_DICT_FORMATS: AnsiString = 'DictionaryFormats';
S_INI_DATA: AnsiString = 'Data';
S_DB_DATABASE: AnsiString = 'DatabaseName';
S_DB_SERVER: AnsiString = 'ServerName';
S_DB_PORT: AnsiString = 'Port';
S_DB_UID: AnsiString = 'Login';
S_DB_PASSWORD: AnsiString = 'Password';
// File open
S_EXCEL_PROVIDER4: AnsiString = 'Provider=Microsoft.Jet.OLEDB.4.0';
S_EXCEL_PROVIDER12: AnsiString = 'Provider=Microsoft.ACE.OLEDB.12.0';
S_EXCEL_NO_HEADER: AnsiString = 'Header=False';
S_EXCEL_PASSWORD: AnsiString = 'Password=""';
S_EXCEL_DATASOURCE: AnsiString = 'Data Source=';
S_EXCEL_EXCELFILE: AnsiString = 'Excel File=';
S_EXCEL_USERID: AnsiString = 'User ID=Admin';
S_EXCEL_MODE: AnsiString = 'Mode=Share Deny None';
S_EXCEL_EXTENDED4: AnsiString = 'Extended Properties="Excel 8.0;HDR=No"';
S_EXCEL_EXTENDED12: AnsiString = 'Extended Properties="Excel 12.0 Xml;HDR=No"';
S_EXCEL_JET_DB: AnsiString = 'Jet OLEDB:System database=""';
S_EXCEL_JET_REG: AnsiString = 'Jet OLEDB:Registry Path=""';
S_EXCEL_JET_PASS: AnsiString = 'Jet OLEDB:Database Password=""';
S_EXCEL_JET_ENGINE: AnsiString = 'Jet OLEDB:Engine Type=37';
S_EXCEL_JET_LOCK: AnsiString = 'Jet OLEDB:Database Locking Mode=0';
S_EXCEL_JET_BULK_OPS: AnsiString = 'Jet OLEDB:Global Partial Bulk Ops=2';
S_EXCEL_JET_BULK_TRN: AnsiString = 'Jet OLEDB:Global Bulk Transactions=1';
S_EXCEL_JET_NEWPASS: AnsiString = 'Jet OLEDB:New Database Password=""';
S_EXCEL_JET_CRTDB: AnsiString = 'Jet OLEDB:Create System Database=False';
S_EXCEL_JET_ENC: AnsiString = 'Jet OLEDB:Encrypt Database=False';
S_EXCEL_JET_COPY: AnsiString = 'Jet OLEDB:Don''t Copy Locale on Compact=False';
S_EXCEL_JET_REPL: AnsiString = 'Jet OLEDB:Compact Without Replica Repair=False';
S_EXCEL_JET_SFP: AnsiString = 'Jet OLEDB:SFP=False';
S_EXCEL_JET_COMPLEX: AnsiString = 'Jet OLEDB:Support Complex Data=False';
S_XLS_FORMAT: AnsiString = '%s;%s%s;%s';
S_XLSX_FORMAT: AnsiString = '%s;%s;%s%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s';
// Database open
S_PG_PROVIDER: AnsiString = 'Provider=MSDASQL.1';
S_PG_PASSWORD: AnsiString = 'Password=';
S_PG_SECURITY_INFO: AnsiString = 'Persist Security Info=True';
S_PG_USER_ID: AnsiString = 'User ID=';
S_PG_EXTENDED_PROPS: AnsiString = 'Extended Properties="';
S_PG_DRIVER: AnsiString = 'DRIVER={PostgreSQL ANSI}';
S_PG_DATABASE: AnsiString = 'DATABASE=';
S_PG_SERVER: AnsiString = 'SERVER=';
S_PG_PORT: AnsiString = 'PORT=';
S_PG_UID: AnsiString = 'UID=';
S_PG_PWD: AnsiString = 'PWD=';
S_PG_SSL_MODE: AnsiString = 'SSLmode=disable';
S_PG_READ_ONLY: AnsiString = 'ReadOnly=0';
S_PG_PROTOCOL: AnsiString = 'Protocol=7.4';
S_PG_FAKE_OID_INDEX: AnsiString = 'FakeOidIndex=0';
S_PG_SHOW_OID_COLS: AnsiString = 'ShowOidColumn=0';
S_PG_ROW_VERSIONONG: AnsiString = 'RowVersioning=0';
S_PG_SHOW_SYS_TABLES: AnsiString = 'ShowSystemTables=0';
S_PG_CONN_SETTINGS: AnsiString = 'ConnSettings=';
S_PG_FETCH: AnsiString = 'Fetch=100';
S_PG_SOCKET: AnsiString = 'Socket=4096';
S_PG_UNKNOWN_SIZES: AnsiString = 'UnknownSizes=0';
S_PG_VARCHAR_SIZE: AnsiString = 'MaxVarcharSize=255';
S_PG_LVARCHAR_SIZE: AnsiString = 'MaxLongVarcharSize=8190';
S_PG_DEBUG: AnsiString = 'Debug=0';
S_PG_COMM_LOG: AnsiString = 'CommLog=0';
S_PG_OPTIMIZER: AnsiString = 'Optimizer=0';
S_PG_KSQO: AnsiString = 'Ksqo=1';
S_PG_DECLARE_FETCH: AnsiString = 'UseDeclareFetch=0';
S_PG_TEXT_LVARCHAR: AnsiString = 'TextAsLongVarchar=1';
S_PG_UNKNOWNS_LVARCHAR: AnsiString = 'UnknownsAsLongVarchar=0';
S_PG_BOOLS_AS_CHAR: AnsiString = 'BoolsAsChar=1';
S_PG_PARSE: AnsiString = 'Parse=0';
S_PG_CANCEL_FREE_STMT: AnsiString = 'CancelAsFreeStmt=0';
S_PG_SYS_TABLE_PREFIXES: AnsiString = 'ExtraSysTablePrefixes=dd_;';
S_PG_LF_CONVERSION: AnsiString = 'LFConversion=1';
S_PG_UPD_CURSORS: AnsiString = 'UpdatableCursors=1';
S_PG_DISALLOW_PREMATURE: AnsiString = 'DisallowPremature=0';
S_PG_TRUE_IS_MINUS1: AnsiString = 'TrueIsMinus1=0';
S_PG_BI: AnsiString = 'BI=0';
S_PG_BYTEA_LVARBINARY: AnsiString = 'ByteaAsLongVarBinary=0';
S_PG_SERVERSIDE_PREPARE: AnsiString = 'UseServerSidePrepare=1';
S_PG_LOWERCASE_ID: AnsiString = 'LowerCaseIdentifier=0';
S_PG_GSSAUTH_USE_GSS: AnsiString = 'GssAuthUseGSS=0';
S_PG_XA_OPT: AnsiString = 'XaOpt=1"';
S_PG_INIT_CATALOG: AnsiString = 'Initial Catalog=';
S_POSTGRESQL_FORMAT: AnsiString = '%s;%s%s;%s;%s%s;%s%s;%s%s;%s%s;%s%s;%s%s;%s%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s%s';
// User messages
S_QUERY_TYPE_CONFIRM: AnsiString = 'Похоже, что выбран неверный тип запроса.' + sLineBreak + 'Верно ли указан тип?';
S_STATUS_WAITING_TABLE: AnsiString = 'Ожидание выбора таблицы';
S_STATUS_POSITION_TABLE: AnsiString = 'Позиционирование таблицы';
S_STATUS_READY: AnsiString = 'Готово к работе';
S_STATUS_PROCESSING: AnsiString = 'Выполняется:';
S_STATUS_OFFLINE: AnsiString = 'Отключено';
S_LOG_ONE_MORE_THAN_TWO: AnsiString = '' + sLineBreak + 'Строка %d: Значение в колонке %d больше значения в колонке %d';
S_LOG_SUM_ONE_DIFF_THAN_TWO: AnsiString = '' + sLineBreak + 'Строка %d: Сумма значений в колонках %s не равна значению в колонке %d';
S_LOG_ONE_DIFF_THAN_SUM_TWO: AnsiString = '' + sLineBreak + 'Строка %d: Значение в колонке %d больше суммы значений в колонках %s';
S_LOG_FORMULA_ONE_DIFF_THAN_TWO: AnsiString = '' + sLineBreak + 'Строка %d: Значения в колонках (%s) не равно значению в колонке %d';
S_LOG_EMPTY_ROW: AnsiString = '' + sLineBreak + 'Пустая строка: %d';
S_LOG_DUPLICATE_ROW: AnsiString = '' + sLineBreak + 'Дублирование строк: %d и %d';
S_LOG_REPLACE_FROM_DICTIONARY: AnsiString = '' + sLineBreak + 'Строка %d: значение "%s" из словаря вместо "%s"';
S_LOG_NO_SPECIES_RELATION: AnsiString = '' + sLineBreak + 'Строка %d: Повреждаемая порода не соответствует причине повреждения';
S_LOG_NO_CAUSE_RELATION: AnsiString = '' + sLineBreak + 'Строка %d: Причина повреждения не соответствует году повреждения';
S_LOG_INVALID_SUM_PREV_REPORT: AnsiString = '' + sLineBreak + 'Сумма значений в колонке %d не сходится с суммой из предыдущего отчета';
S_LOG_PREV_REPORT_NOT_FOUND: AnsiString = '' + sLineBreak + 'Предыдущий отчет для сравнения не найден';
S_LOG_COMPLETED: AnsiString = 'Завершено';
S_LOG_FORCE_STOP: AnsiString = 'Экстренное завершение по требованию';
S_LOG_SUCCESSFULLY: AnsiString = 'Проверка пройдена успешно - файл может быть загружен в БД';
S_LOG_EXTRA_INVALID: AnsiString = 'Площадь очага больше площади обследования (см. номера строк и колонок в результатах проверки)';
S_LOG_MAIN_INVALID: AnsiString = 'В таблице присутствуют критические ошибки - необходима проверка или доработка (см. номера строк и колонок в результатах проверки)';
S_LOG_DUPLICATE_INVALID: AnsiString = 'В таблице присутствуют дубликаты строк, необходима проверка';
S_LOG_RELATION_INVALID: AnsiString = 'В таблице присутствуют ошибки соответствия полей';
S_LOG_SKIPPED_LINES: AnsiString = 'Обнаружены пропущенные проверки. Поэтому скрипт для базы данных я Вам не отдам...';
S_IN_PROGRESS: AnsiString = 'Похоже, все еще выполняется предыдущий запрос.';
S_QUERY_EXEC_SUCCESS: AnsiString = 'Успешно!';
S_EDIT_PROMPT: AnsiString = '' + sLineBreak + sLineBreak + 'Значения близких по смыслу колонок:' + sLineBreak;
// Error messages
E_FIND_FIRST_CELL: AnsiString = 'Не удалось распознать первую строку таблицы';
E_FIND_LAST_CELL: AnsiString = 'Не удалось распознать последнюю строку таблицы';
E_WRITE_QUERY: AnsiString = 'Ошибка при попытке запомнить SQL-запрос' + sLineBreak +
'Значения счетчиков:' + sLineBreak +
'MaxQueriesCount: %d, FActualCount: %d, FWritingIndex: %d, FReadingIndex: %d';
E_READ_QUERY: AnsiString = 'Ошибка при попытке прочитать SQL-запрос' + sLineBreak +
'Значения счетчиков:' + sLineBreak +
'MaxQueriesCount: %d, FActualCount: %d, FWritingIndex: %d, FReadingIndex: %d';
E_QUERY_EXEC_ERROR: AnsiString = '!!! Ошибка при выполнении запроса. !!!' + sLineBreak +
'Изменения отменены.';
E_REPORT_ERROR = 'Во время подготовки отчета произошла ошибка.';
// File names
S_DICT_VALID_PREFIX: AnsiString = 'Valid';
S_QUERY_FILE_NAME: AnsiString = 'SQLQueries.lst';
S_SETTINGS_FILE_NAME: AnsiString = 'Settings.ini';
S_LOG_FILE_NAME: AnsiString = 'Validate.log';
// Dict files
S_DICT_FORESTRIES_FILE: AnsiString = 'DictionaryForestry.dic';
S_DICT_LOCAL_FORESTRIES_FILE: AnsiString = 'DictionaryLocalForestry.dic';
S_DICT_LANDUSE_FILE: AnsiString = 'DictionaryLanduse.dic';
S_DICT_PROTECT_CATEGORY_FILE: AnsiString = 'DictionaryProtectCategory.dic';
S_DICT_SPECIES_FILE: AnsiString = 'DictionarySpecies.dic';
S_DICT_DAMAGE_FILE: AnsiString = 'DictionaryDamage.dic';
S_DICT_PEST_FILE: AnsiString = 'DictionaryPest.dic';
// Dictionary captions
S_DICT_FORESTRIES_NAME: AnsiString = 'Лесничество';
S_DICT_LOCAL_FORESTRIES_NAME: AnsiString = 'Участковое лесничество';
S_DICT_LANDUSE_NAME: AnsiString = 'Целевое назначение лесов';
S_DICT_PROTECT_CATEGORY_NAME: AnsiString = 'Категория защитных лесов';
S_DICT_SPECIES_NAME: AnsiString = 'Порода';
S_DICT_DAMAGE_NAME: AnsiString = 'Основная причина ослабления (усыхания)';
S_DICT_PEST_NAME: AnsiString = 'Вид вредного организма';
// Dictionary formats
S_DICT_ID_FORMAT: AnsiString = '$ID$';
S_DICT_NAME_FORMAT: AnsiString = '$NAME$';
S_FORMAT_HELP: AnsiString = 'Подстановка значений для форматирования:' + sLineBreak +
'$NAME$ - текстовое название' + sLineBreak + '$ID$ - идентификатор';
// Settings names
S_SETTINGS_TEMPLATE_SELECT: AnsiString = 'Шаблон SELECT';
S_SETTINGS_TEMPLATE_INSERT: AnsiString = 'Шаблон INSERT';
S_SETTINGS_TEMPLATE_UPDATE: AnsiString = 'Шаблон UPDATE';
S_SETTINGS_TEMPLATE_DELETE: AnsiString = 'Шаблон DELETE';
S_SETTINGS_DB_DATABASE: AnsiString = 'Имя базы данных';
S_SETTINGS_DB_SERVER: AnsiString = 'Имя сервера';
S_SETTINGS_DB_PORT: AnsiString = 'Порт';
S_SETTINGS_DB_LOGIN: AnsiString = 'Имя пользователя';
S_SETTINGS_DB_PASSWORD: AnsiString = 'Пароль БД';
S_SETTINGS_QUERIES_REMEMBERED: AnsiString = 'Запоминать запросов';
S_SETTINGS_HIDE_TO_TRAY: AnsiString = 'Сворачиваться в трей';
S_VERSION: AnsiString = 'Версия: %s';
S_COPYRIGHT: AnsiString = 'Axl NeferSky (AxlNeferSky@gmail.com)';
S_COMMENTS: AnsiString = 'Комментарии излишни';
// Script
S_DB_TABLE_NAME: AnsiString = 'QuarterReports';
S_DB_SCRIPT_HEADER: AnsiString = '';
S_DB_SCRIPT_FOOTER: AnsiString = 'COMMIT;';
S_DB_SCRIPT_LN_HEADER: AnsiString = '';
S_DB_SCRIPT_LN_FOOTER: AnsiString = '' + sLineBreak;
S_DB_DELETE_SCRIPT_FORMAT: AnsiString =
'DELETE FROM %s WHERE (forestry_number = %d) ' +
'AND (report_quarter = %d) ' +
'AND (report_year = %d);';
S_DB_INSERT_SCRIPT_FORMAT_BEGIN: AnsiString = 'INSERT INTO %s (';
S_DB_INSERT_SCRIPT_FORMAT_MIDDLE: AnsiString = ') VALUES (';
S_DB_INSERT_SCRIPT_FORMAT_END: AnsiString = ');';
S_DB_INSERT_SCRIPT_FORMAT_FLD1: AnsiString =
'id, input_date, report_quarter, report_year, forestry_number, local_forestry_number, kv, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD2: AnsiString =
'patch, landuse_purpose_code, defense_category, main_species, damage_species, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD3: AnsiString =
'main_reason, damage_year, damage_cause_group, patch_area, exam_all, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD4: AnsiString =
'exam_fbi, exam_lesn, exam_other, dam_byear, dam_iyear, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD5: AnsiString =
'dam_eyear, dam4, dam4_10, dam10_40, dam40, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD6: AnsiString =
'lost_byear, lost_iyear, lost_eyear, nazn_ssr, nazn_vsr, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD7: AnsiString =
'nazn_und, nazn_etc, nazn_etc_s, ssr_kv, ssr_kv_ar, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD8: AnsiString =
'ssr_year, ssr_year_ar, ssr_stock, ssr_stock_ar, vsr_kv, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD9: AnsiString =
'vsr_kv_ar, vsr_year, vsr_year_ar, vsr_stock, vsr_stock_ar, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD10: AnsiString =
'und_kv, und_kv_ar, und_year, und_year_ar, und_stock, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD11: AnsiString =
'und_stock_ar, etc_event_type, etc_kv, etc_kv_ar, etc_year, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD12: AnsiString =
'etc_year_ar, etc_stock, etc_stock_ar, sost, pest, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD13: AnsiString =
'pest_on_byear, pest_by_year, pest_likv_year, pest_zat_year, pest_eyear, ';
S_DB_INSERT_SCRIPT_FORMAT_FLD14: AnsiString =
'pest_eyear_mer, pest_sl, pest_sr, pest_si, pest_sp';
S_DB_INSERT_SCRIPT_FORMAT_VAL1: AnsiString =
'''%s'', ''%s'', %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, ';
S_DB_INSERT_SCRIPT_FORMAT_VAL2: AnsiString =
'%d, %d, %d, %s, %s, %s, %s, %s, %s, %s, ';
S_DB_INSERT_SCRIPT_FORMAT_VAL3: AnsiString =
'%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, ';
S_DB_INSERT_SCRIPT_FORMAT_VAL4: AnsiString =
'%s, ''%s'', %s, %s, %s, %s, %s, %s, %s, %s, ';
S_DB_INSERT_SCRIPT_FORMAT_VAL5: AnsiString =
'%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, ';
S_DB_INSERT_SCRIPT_FORMAT_VAL6: AnsiString =
'%s, ''%s'', %s, %s, %s, %s, %s, %s, ''%s'', %d, ';
S_DB_INSERT_SCRIPT_FORMAT_VAL7: AnsiString =
'%s, %s, %s, %s, %s, %s, %s, %s, %s, %s';
S_DB_GET_REGION_ID_BY_FORESTRY: AnsiString =
'select region_id from forestries where upper(forestry_name) like ''%s''';
S_DB_GET_FORESTRY_ID: AnsiString =
'select forestry_id from forestries where upper(forestry_name) like ''%s''';
S_DB_GET_REPORT_ROW_COUNT: AnsiString =
'select count(*) from %s where forestry_number = %d and report_quarter = %d and report_year = %d';
S_DB_GET_SPECIES_RELATION: AnsiString =
'select count(*) from species_causes sc join species s on s.species_id = sc.species_code join damage_causes c on c.cause_code = sc.cause_code where Upper(Trim(s.poroda)) like ''%s'' and Upper(c.cause_rus) like ''%s''';
S_DB_GET_PREV_YEAR_SUMS: AnsiString =
'select sum(dam_eyear), sum(lost_eyear), sum(pest_eyear) from %s where forestry_number = %d and report_year = %d - 1 and report_quarter = 4';
S_DB_GET_PREV_QUARTER_SUMS: AnsiString =
'select sum(dam_byear), sum(lost_byear), sum(pest_on_byear) from %s where forestry_number = %d and report_year = %d and report_quarter = %d';
S_SQL_GET_FORESTRIES_DICT: AnsiString =
'select distinct forestry_id, forestry_name, region_id from forestries where region_id in (22, 23) order by forestry_name';
S_SQL_GET_LOCAL_FORESTRIES_DICT: AnsiString =
'select distinct local_forestry_id, local_forestry_name, forestry_id from local_forestries where region_id in (22, 23) order by local_forestry_name';
S_SQL_GET_FORESTRIES_BY_REGION: AnsiString =
'select distinct forestry_name from forestries where region_id = %d order by forestry_name';
S_SQL_GET_LANDUSE_DICT: AnsiString =
'select distinct landuse_purpose_code, landuse_purpose, 0 from landuse_purposes order by landuse_purpose';
S_SQL_GET_PROTECT_CATEGORY_DICT: AnsiString =
'select distinct protect_category_code, protect_category_rus, 0 from protect_category order by protect_category_rus';
S_SQL_GET_SPECIES_DICT: AnsiString =
'select distinct species_id, poroda, 0 from species order by poroda';
S_SQL_GET_DAMAGE_DICT: AnsiString =
'select distinct cause_code, cause_rus, 0 from damage_causes order by cause_rus';
S_SQL_GET_PEST_DICT: AnsiString =
'select distinct pest_code, pest_rus, 0 from pest_dict order by pest_rus';
ARR_FIELD_NAMES: array[1..I_COL_COUNT] of AnsiString = (
'Лесничество',
'Участковое лесничество',
'Квартал',
'Выдел',
'Целевое назначение лесов',
'Категория защитных лесов',
'Преобладающая порода',
'Повреждаемая порода',
'Основная причина ослабления (усыхания)',
'Год повреждения',
'Код группы причин ослабления (усыхания)',
'Площадь выдела',
'Обследовано/всего нарастающим итогом (га)',
'Обследовано/в т.ч. ФБУ "Рослесозащита" (га)',
'Обследовано/в т.ч лесничествами (га)',
'Обследовано/в т.ч. подрядными организациями (га)',
'Площадь повреждения/на начало отчётного года (га)',
'Площадь повреждения/выявлено с начала года (нарастающим итогом) (га)',
'Площадь повреждения/на конец отчётного периода с учётом рубок (га)',
'В том числе по степени повреждения/до 4% (га)',
'В том числе по степени повреждения/4.1-10% (га)',
'В том числе по степени повреждения/10.1-40% (га)',
'В том числе по степени повреждения/более 40% (га)',
'В том числе погибшие насаждения/на начало отчётного года (га)',
'В том числе погибшие насаждения/нарастающим итогом (га)',
'В том числе погибшие насаждения/с начала года оставшиеся на корню на конец отчётного периода (с учётои рубок) (га)',
'Назначено мероприятий/ССР (га)',
'Назначено мероприятий/ВСР (га)',
'Назначено мероприятий/УЗ (га)',
'Назначено мероприятий/Прочие/Вид мероприятия',
'Назначено мероприятий/Прочие/Площадь (га)',
'Проведено мероприятий/ССР/За отчётный период/Всего (га)',
'Проведено мероприятий/ССР/За отчётный период/В т.ч. на арендованных территориях (га)',
'Проведено мероприятий/ССР/Нарастающим итогом с начала года/Всего (га)',
'Проведено мероприятий/ССР/Нарастающим итогом с начала года/В т.ч. на арендованных территориях (га)',
'Проведено мероприятий/ССР/Выбираемый запас/Всего (м3)',
'Проведено мероприятий/ССР/Выбираемый запас/В т.ч. на арендованных территориях (м3)',
'Проведено мероприятий/ВСР/За отчётный период/Всего (га)',
'Проведено мероприятий/ВСР/За отчётный период/В т.ч. на арендованных территориях (га)',
'Проведено мероприятий/ВСР/Нарастающим итогом с начала года/Всего (га)',
'Проведено мероприятий/ВСР/Нарастающим итогом с начала года/В т.ч. на арендованных территориях (га)',
'Проведено мероприятий/ВСР/Выбираемый запас/Всего (м3)',
'Проведено мероприятий/ВСР/Выбираемый запас/В т.ч. на арендованных территориях (м3)',
'Проведено мероприятий/УЗ/За отчётный период/Всего (га)',
'Проведено мероприятий/УЗ/За отчётный период/В т.ч. на арендованных территориях (га)',
'Проведено мероприятий/УЗ/Нарастающим итогом с начала года/Всего (га)',
'Проведено мероприятий/УЗ/Нарастающим итогом с начала года/В т.ч. на арендованных территориях (га)',
'Проведено мероприятий/УЗ/Выбираемый запас/Всего (м3)',
'Проведено мероприятий/УЗ/Выбираемый запас/В т.ч. на арендованных территориях (м3)',
'Проведено мероприятий/Прочие мероприятия/Вид мероприятия',
'Проведено мероприятий/Прочие мероприятия/За отчётный период/Всего (га)',
'Проведено мероприятий/Прочие мероприятия/За отчётный период/В т.ч. на арендованных территориях (га)',
'Проведено мероприятий/Прочие мероприятия/Нарастающим итогом с начала года/Всего (га)',
'Проведено мероприятий/Прочие мероприятия/Нарастающим итогом с начала года/В т.ч. на арендованных территориях (га)',
'Проведено мероприятий/Прочие мероприятия/Выбираемый запас/Всего (м3)',
'Проведено мероприятий/Прочие мероприятия/Выбираемый запас/В т.ч. на арендованных территориях (м3)',
'Информация об очагах вредителей и болезней/Состояние очага',
'Информация об очагах вредителей и болезней/Вид вредного организма',
'Информация об очагах вредителей и болезней/Площадь очага/На начало отчетного года (га)',
'Информация об очагах вредителей и болезней/Площадь очага/Возникло вновь (га)',
'Информация об очагах вредителей и болезней/Площадь очага/Ликвидировано (га)',
'Информация об очагах вредителей и болезней/Площадь очага/Затухло под воздействием естественных факторов (га)',
'Информация об очагах вредителей и болезней/Площадь очага/На конец отчетного квартала/Всего (га)',
'Информация об очагах вредителей и болезней/Площадь очага/На конец отчетного квартала/в т.ч. требует мер борьбы (га)',
'Степень очага/Слабая (га)',
'Степень очага/Средняя (га)',
'Степень очага/Сильная (га)',
'Степень очага/Сплошная (га)'
);
// =)
S_YES = 'True';
S_NO = 'False';
S_FREE_SELECT: AnsiString = 'SELECT';
S_DOTCOMMA_SELECT: AnsiString = ';SELECT';
S_BRACKED1_SELECT: AnsiString = '(SELECT';
S_BRACKED2_SELECT: AnsiString = ')SELECT';
S_EQUAL_SELECT: AnsiString = '=SELECT';
S_COMMA_SELECT: AnsiString = ',SELECT';
S_FILE_SELECT: AnsiString = 'select * from [%s]';
var
SQLSelectTemplate: AnsiString = ' SELECT * FROM @ WHERE @ ORDER BY @ ;';
SQLInsertTemplate: AnsiString = ' INSERT INTO @ VALUES @; ';
SQLUpdateTemplate: AnsiString = ' UPDATE @ SET @ WHERE @; ';
SQLDeleteTemplate: AnsiString = ' DELETE FROM @ WHERE @; ';
PgDatabase: AnsiString = 'DatabaseName';
PgServer: AnsiString = '127.0.0.1';
PgPort: AnsiString = '5432';
PgUID: AnsiString = 'postgres';
PgPassword: AnsiString = '********';
TrayEnabled: Boolean = False;
MaxQueriesCount: Integer = 50;
C_LIST_YESNO: TStringList;
implementation
//---------------------------------------------------------------------------
procedure CreateLists;
begin
C_LIST_YESNO := TStringList.Create;
C_LIST_YESNO.Clear;
C_LIST_YESNO.Add(S_NO);
C_LIST_YESNO.Add(S_YES);
end;
//---------------------------------------------------------------------------
procedure DestroyLists;
begin
C_LIST_YESNO.Clear;
C_LIST_YESNO.Free;
end;
//---------------------------------------------------------------------------
initialization
CreateLists();
finalization
DestroyLists();
end.
|
unit osLogin;
interface
uses
Windows, SysUtils, osSQLDataSet, acCustomSQLMainDataUn, Controls, Dialogs,
osCustomLoginFormUn;
type
TLoginUsuario = class
private
FDefaultUserName: string;
FNome: string;
FIDUsuario: integer;
FStatus: string;
FApelido: string;
function GetSystemUserName: string;
function isGrupo(nomeColuna: string; caption: string): boolean;
public
property IDUsuario: integer read FIDUsuario;
property Apelido: string read FApelido;
property Nome: string read FNome;
property Status: string read FStatus;
property DefaultUserName: string read FDefaultUserName write FDefaultUserName;
procedure getInfoUsuarioLogadoSistema;
function Login(caption: string): boolean; overload;
function Login(caption: string; loginFormClass: TLoginFormClass): boolean; overload;
procedure Logout;
function isTesoureiro: boolean;
function isCaixa: boolean;
constructor create;
end;
implementation
uses DB, osMD5;
constructor TLoginUsuario.create;
begin
FApelido := '';
FStatus := '';
FNome := '';
FIDUsuario := -1;
end;
procedure TLoginUsuario.getInfoUsuarioLogadoSistema;
var
query: TosSQLDataSet;
begin
query := TosSQLDataSet.Create(nil);
try
query.SQLConnection := acCustomSQLMainData.SQLConnection;
query.commandText := 'SELECT IDUsuario, Apelido, Nome, Status FROM Usuario ' +
' where UPPER(Apelido)= ' + QuotedStr(UpperCase(acCustomSQLMainData.ApelidoUsuario));
query.Open;
FIDUsuario := query.fieldByName('IDUsuario').AsInteger;
FNome := query.fieldByName('Nome').AsString;
FApelido := query.fieldByName('Apelido').AsString;
FStatus := query.fieldByName('Status').AsString;
finally
FreeAndNil(query);
end;
end;
function TLoginUsuario.GetSystemUserName: string;
const
MaxUNSize = 20;
var
BufSize: Cardinal;
UserName: array [0..MaxUNSize] of char;
begin
BufSize := MaxUNSize + 1;
if not GetUserName(@UserName, BufSize) then
Exception.Create('Năo foi possível obter o nome do usuário do sistema. Co'
+ 'ntate o administrador.');
Result := Copy(UserName, 0, BufSize - 1);
end;
function TLoginUsuario.isCaixa: boolean;
begin
result := isGrupo('IDGrupoCaixa', 'Login do Caixa');
end;
function TLoginUsuario.isGrupo(nomeColuna: string; caption: string): boolean;
var
query: TosSQLDataSet;
begin
query := TosSQLDataSet.Create(nil);
try
query.SQLConnection := acCustomSQLMainData.SQLConnection;
query.CommandText := 'SELECT ' +
' Apelido '+
' FROM ' +
' usuario u ' +
' JOIN grupousuario gu ' +
' ON gu.idusuario=u.idusuario ' +
' JOIN ParametroSistema ps ' +
' ON ps.' + nomeColuna + '=gu.idGrupo ' +
'WHERE '+
' u.Apelido=' + QuotedStr(FApelido);
query.Open;
result := not(query.eof);
finally
FreeAndNil(query);
end;
end;
function TLoginUsuario.isTesoureiro: boolean;
begin
result := isGrupo('IDGrupoTesoureiro','Login do Tesoureiro');
end;
function TLoginUsuario.Login(caption: string): boolean;
begin
result := login(caption, TosCustomLoginForm);
end;
function TLoginUsuario.Login(caption: string;
loginFormClass: TLoginFormClass): boolean;
const
MaxErrorCount = 3;
var
LoginForm: TosCustomLoginForm;
query: TosSQLDataSet;
ErrorCount: integer;
LoginCorrect: boolean;
begin
LoginForm := loginFormClass.Create(nil);
LoginForm.Caption := caption;
query := TosSQLDataSet.Create(nil);
try
{$IFDEF DESENV}
LoginForm.UsernameEdit.Text := 'Desenvolvedor';
LoginForm.PasswordEdit.Text := 'Desenv';
{$ELSE}
if FDefaultUserName<>'' then
LoginForm.UsernameEdit.Text := FDefaultUserName
else
LoginForm.UsernameEdit.Text := GetSystemUserName;
LoginForm.PasswordEdit.Text := '';
{$ENDIF}
LoginForm.FocusedControl := LoginForm.UsernameEdit;
ErrorCount := 0;
LoginCorrect := False;
while (not LoginCorrect) and (ErrorCount < MaxErrorCount)
and (mrCancel <> LoginForm.ShowModal) do
begin
query.SQLConnection := acCustomSQLMainData.SQLConnection;
query.CommandText := 'SELECT idusuario, apelido, nome, senha, status FROM USUARIO' +
' WHERE lower(apelido) = ' + quotedStr(LowerCase(LoginForm.UsernameEdit.Text));
query.Open;
try
if query.RecordCount = 0 then
begin
MessageDlg('Usuário inexistente.', mtError, [mbOK], 0);
LoginForm.FocusedControl := LoginForm.UsernameEdit;
Inc(ErrorCount);
end
else if (query.FieldByName('Senha').Value <> MD5Digest(LoginForm.PasswordEdit.Text))
and (not query.FieldByName('Senha').IsNull or (LoginForm.PasswordEdit.Text <> '')) then
begin
MessageDlg('Senha incorreta.', mtError, [mbOK], 0);
LoginForm.FocusedControl := LoginForm.PasswordEdit;
Inc(ErrorCount);
end
else
begin
FIDUsuario := query.fieldByName('IDUsuario').AsInteger;
FApelido := query.fieldByName('Apelido').AsString;
FNome := query.fieldByName('Nome').AsString;
FStatus := query.fieldByName('Status').AsString;
LoginCorrect := True;
end;
finally
query.Close;
end;
end;
finally
FreeAndNil(query);
FreeAndNil(LoginForm);
end;
Result := LoginCorrect;
end;
procedure TLoginUsuario.Logout;
begin
FApelido := '';
FStatus := '';
FNome := '';
FIDUsuario := -1;
end;
end.
|
unit ClearStorehouseProductsQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseFDQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, RepositoryDataModule;
type
TQryClearStoreHouseProducts = class(TQryBase)
private
{ Private declarations }
public
class procedure ExecSQL; static;
{ Public declarations }
end;
implementation
{$R *.dfm}
class procedure TQryClearStoreHouseProducts.ExecSQL;
var
Q: TQryClearStoreHouseProducts;
begin
Q := TQryClearStoreHouseProducts.Create(nil);
try
Assert(DMRepository <> nil);
Q.FDQuery.ExecSQL;
finally
FreeAndNil(Q);
end;
end;
end.
|
//****************************************************************//
//****** Author - Kucher Alexander <a7exander@gmail.com> *********//
//************************* (С) 2018 *****************************//
//****************************************************************//
unit A7Rep;
interface
uses
SysUtils, Classes, Variants, ComObj, StdCtrls, Forms;
const
// --------------- Excel constants ----------------------------
xlFormulas = $FFFFEFE5;
xlComments = $FFFFEFD0;
xlValues = $FFFFEFBD;
xlNone = -4142;
xlSolid = 1;
xlAutomatic = -4105;
type
// progress-form
TA7Progress = class
private
F: TForm;
L1: TLabel;
L2: TLabel;
L3: TLabel;
protected
public
procedure Line(p: integer);
constructor Create(AOwner: TComponent);
destructor Destroy; override;
end;
TA7Rep = class(TComponent)
private
Progress: TA7Progress;
protected
public
CurrentLine: integer;
Excel, TemplateSheet: Variant;
MaxBandColumns : integer ; // Max band width in excel-columns
isVisible : boolean;
FirstBandLine, LastBandLine : Integer;
procedure OpenTemplate(FileName: string); overload;
procedure OpenTemplate(FileName: string; Visible : boolean); overload;
procedure OpenWorkSheet(Name: string);
procedure PasteBand(BandName: string);
procedure SetValue(VarName: string; Value: Variant); overload;
procedure SetValue(X,Y: Integer; Value: Variant); overload;
procedure SetValueF(VarName: string; Value: Variant);
procedure SetSumFormula(VarName: string; FirstLine, LastLine: Integer); overload;
procedure SetSumFormula(VarName: string; BandName: string); overload;
procedure SetValueAsText(varName: string; Value: string); overload;
procedure SetValueAsText(X,Y: Integer; Value: string); overload;
procedure SetComment(VarName: string; Value: Variant);
procedure SetColor(VarName: string; Color: Variant);
function GetComment(VarName: string): string;
function GetAndClearComment(VarName: string): string; overload;
function GetAndClearComment(X,Y: Integer): string; overload;
function GetCellName(aCol, aRow : Integer): string;
procedure ExcelFind(const Value: string; var aCol, aRow : Integer; Where:Integer);
procedure Show;
destructor Destroy; override;
published
end;
procedure Register;
implementation
const
MaxBandLines = 300; // max template lines count
procedure Register;
begin
RegisterComponents('A7rexcel', [TA7Rep]);
end;
{ TWcReport }
destructor TA7Rep.Destroy;
begin
inherited;
end;
function TA7Rep.GetCellName(aCol, aRow : Integer): string;
var
c1, c2 : Integer;
begin
if aCol<27 then begin
Result := chr(64 + aCol)+IntToStr(aRow);
end else begin
c1 := (aCol-1) div 26;
c2 := aCol - c1*26;
Result := chr(64 + c1)+chr(64 + c2)+IntToStr(aRow);
end;
end;
procedure TA7Rep.ExcelFind(const Value: string; var aCol, aRow : Integer; Where:Integer);
// Where: the search type (xlFormulas, xlComments, xlValues)
var
R: Variant;
begin
R := TemplateSheet.Rows[IntToStr(FirstBandLine) + ':' + IntToStr(LastBandLine)];
R:=R.Find(What:=Value,LookIn:=Where);
if VarIsClear(R) then begin
aCol := -1;
aRow := -1;
end else begin
aCol:=R.Column;
aRow:=R.Row;
end;
end;
function TA7Rep.GetAndClearComment(VarName: string): string;
var
v : Variant;
x , y : Integer;
begin
Result := '';
ExcelFind(VarName, x, y, xlValues);
if x<0 then Exit;
v := Variant(TemplateSheet.Cells[y, x].Value);
if ((varType(v) = varOleStr)) then
if Pos(VarName,v)>0 then begin
Result := TemplateSheet.Cells[y, x].Comment.Text;
TemplateSheet.Cells[y, x].ClearComments;
end;
end;
function TA7Rep.GetAndClearComment(X, Y: Integer): string;
var
v : Variant;
begin
Result := '';
if x<0 then Exit;
v := Variant(TemplateSheet.Cells[y, x].Value);
if ((varType(v) = varOleStr)) then begin
Result := TemplateSheet.Cells[y, x].Comment.Text;
TemplateSheet.Cells[y, x].ClearComments;
end;
end;
function TA7Rep.GetComment(VarName: string): string;
var
v : Variant;
x , y : Integer;
begin
Result := '';
ExcelFind(VarName, x, y, xlValues);
if x<0 then Exit;
v := Variant(TemplateSheet.Cells[y, x].Value);
if ((varType(v) = varOleStr)) then
if Pos(VarName,v)>0 then begin
Result := TemplateSheet.Cells[y, x].Comment.Text;
end;
end;
procedure TA7Rep.OpenTemplate(FileName: string);
begin // По умолчанию не показываем Excel
OpenTemplate(FileName, false);
end;
procedure TA7Rep.OpenTemplate(FileName: string; Visible: boolean);
begin
Excel := CreateOleObject('Excel.Application');
Excel.Workbooks.Open(FileName, True, True);
Excel.DisplayAlerts := False; // for prevent error in SetValue procedure, where VarName not fount for replace
Excel.Visible := Visible;
isVisible := Visible;
if isVisible=False then
Progress := TA7Progress.Create(Self); // show progress-window
Application.ProcessMessages;
TemplateSheet := Excel.Workbooks[1].Sheets[1];
CurrentLine := 1;
MaxBandColumns := TemplateSheet.UsedRange.Columns.Count;
if Assigned(Progress) then Progress.L3.Caption := 'Sheet: 1';
end;
procedure TA7Rep.PasteBand(BandName: string);
var
i: integer;
v, Range: Variant;
begin
// find band in template
FirstBandLine := 0; LastBandLine := 0;
i := CurrentLine;
while ((LastBandLine = 0) and (i < CurrentLine + MaxBandLines)) do begin
v := Variant(TemplateSheet.Cells[i, 1].Value);
if (varType(v) = varOleStr) and (FirstBandLine = 0) then begin
if v = BandName then begin // the start of band
FirstBandLine := i;
end;
end;
if (FirstBandLine <> 0) then begin
if not ((varType(v) = varOleStr) and (v = BandName)) then LastBandLine := i - 1;
end;
inc(i);
end;
if LastBandLine>0 then begin // if BandName found
Range := TemplateSheet.Rows[IntToStr(FirstBandLine) + ':' + IntToStr(LastBandLine)];
Range.Copy;
Range := TemplateSheet.Rows[IntToStr(CurrentLine) + ':' + IntToStr(CurrentLine)];
Range.Insert;
{ // delete band name from result lines
for i := CurrentLine to CurrentLine + (LastBandLine - FirstBandLine) do begin
TemplateSheet.Cells[i, 1].Value := '';
end;}
CurrentLine := CurrentLine + (LastBandLine - FirstBandLine) + 1;
// new band position in report
FirstBandLine := CurrentLine - (LastBandLine - FirstBandLine) - 1;
LastBandLine := CurrentLine - 1;
if isVisible=false then
Progress.Line(CurrentLine);
end;
end;
procedure TA7Rep.SetComment(VarName: string; Value: Variant);
// VarName - tag in cell, for setting comment
var
x, y : Integer;
begin
ExcelFind(VarName, x, y, xlValues);
if x>0 then begin
TemplateSheet.Cells[y, x].AddComment(Value);
end;
end;
procedure TA7Rep.SetValue(VarName: string; Value: Variant);
var Range: Variant;
begin
Range := TemplateSheet.Rows[IntToStr(FirstBandLine) + ':' + IntToStr(LastBandLine)];
if Value=null then
Range.Replace(VarName, '')
else
Range.Replace(VarName, VarToStr(Value));
end;
procedure TA7Rep.SetValue(X, Y: Integer; Value: Variant);
begin
if Value=null then
TemplateSheet.Cells[y, x].Value := ''
else
TemplateSheet.Cells[y, x].Value := Value;
end;
// Edited by cyrax1000, 2017-08-11
// Set value to cell with formatted string
procedure TA7Rep.SetValueF(VarName: string; Value: Variant);
var
x, y, p: Integer;
begin
x:= 0;
while x >= 0 do
begin
ExcelFind(VarName, x, y, xlValues);
if x > 0 then
begin
TemplateSheet.Cells[y, x].Select;
p:= Pos(VarName, TemplateSheet.Cells[y, x]);
if p > 0 then
if Value = Null then
Excel.ActiveCell.Characters[Start:= p, Length:= Length('')].Insert(Value)
else
Excel.ActiveCell.Characters[Start:= p, Length:= Length(VarName)].Insert(Value);
end;
end;
end;
procedure TA7Rep.SetValueAsText(varName, Value: string);
var y, x: integer;
v: Variant;
begin
for y := FirstBandLine to LastBandLine do begin
for x := 2 to MaxBandColumns do begin
v := Variant(TemplateSheet.Cells[y, x].Value);
if ((varType(v) = varOleStr)) then
if v = VarName then begin
TemplateSheet.Cells[y, x].NumberFormat:= '@';
TemplateSheet.Cells[y, x].Value := Value;
end;
end;
end;
end;
procedure TA7Rep.SetValueAsText(X, Y: Integer; Value: string);
begin
TemplateSheet.Cells[y, x].NumberFormat:= '@';
TemplateSheet.Cells[y, x].Value := Value;
end;
procedure TA7Rep.Show;
var
Range: Variant;
begin
// delete the template from result report
Range := TemplateSheet.Rows[IntToStr(CurrentLine) + ':' + IntToStr(CurrentLine + MaxBandLines)];
Range.Delete;
Excel.Visible := true;
if isVisible=false then
Progress.Free;
Range := Unassigned;
TemplateSheet := Unassigned;
Excel := Unassigned;
end;
{ TA7ProgressForm }
constructor TA7Progress.Create(AOwner: TComponent);
begin
F := TForm.Create(nil);
F.Width := 150;
F.Height := 90;
F.Position := poScreenCenter;
F.BorderStyle := bsNone;
F.FormStyle := fsStayOnTop;
F.Color := $FFFFFF;
L1 := TLabel.Create(F);
L1.Parent := F;
L1.Left := 15;
L1.Width := 100;
L1.Alignment := taCenter;
L1.Top := 20;
L1.Caption := 'Building report';
// Line
L2 := TLabel.Create(F);
L2.Parent := F;
L2.Left := 30;
L2.Width := 100;
L2.Alignment := taCenter;
L2.Top := 40;
// Sheet
L3 := TLabel.Create(F);
L3.Parent := F;
L3.Left := 30;
L3.Width := 100;
L3.Alignment := taCenter;
L3.Top := 60;
F.Show;
end;
destructor TA7Progress.Destroy;
begin
L1.Free;
L2.Free;
F.Free;
end;
procedure TA7Progress.Line(p: integer);
begin
L2.Caption := 'Line: ' + IntToStr(p);
Application.ProcessMessages;
end;
// for using multi-sheet reports
// if Name='' then open first worksheet
procedure TA7Rep.OpenWorkSheet(Name: string);
var
Range: Variant;
begin
// delete band templates
Range := TemplateSheet.Rows[IntToStr(CurrentLine) + ':' + IntToStr(CurrentLine + MaxBandLines)];
Range.Delete;
if Name='' then
TemplateSheet := Excel.Workbooks[1].Sheets[1]
else
TemplateSheet := Excel.Workbooks[1].Sheets[Name];
CurrentLine := 1;
MaxBandColumns := TemplateSheet.UsedRange.Columns.Count;
if Assigned(Progress) then Progress.L3.Caption := 'Sheet: '+Name;
end;
procedure TA7Rep.SetSumFormula(VarName: string; FirstLine, LastLine: Integer);
var
x, y : Integer;
begin
ExcelFind(VarName, x, y, xlValues);
if x>0 then begin
if LastLine<>CurrentLine then
TemplateSheet.Cells[y, x].Value := '=SUM('+GetCellName(x,FirstLine)+':'+GetCellName(x,LastLine)+')'
else
TemplateSheet.Cells[y, x].Value := '';
end;
end;
procedure TA7Rep.SetSumFormula(VarName, BandName: string);
var
x, y, i : Integer;
c, s : string;
begin
ExcelFind(VarName, x, y, xlValues);
s := '';
if x>0 then begin
for i := 1 to CurrentLine-1 do begin
c := TemplateSheet.Cells[i, 1].Value;
if c=BandName then begin
if s<>'' then s := s + '+';
s := s + GetCellName(x,i);
end;
end;
if s<>'' then begin
TemplateSheet.Cells[y, x].Value := '='+s+'';
end else begin
TemplateSheet.Cells[y, x].Value := '';
end;
end;
end;
procedure TA7Rep.SetColor(VarName: string; Color: Variant);
var
x, y : Integer;
begin
ExcelFind(VarName, x, y, xlValues);
if Color=null then begin
TemplateSheet.Cells[y, x].Interior.Pattern := xlNone;
end else begin
TemplateSheet.Cells[y, x].Interior.Pattern := xlSolid;
TemplateSheet.Cells[y, x].Interior.PatternColorIndex := xlAutomatic;
TemplateSheet.Cells[y, x].Interior.Color := Color;
end;
end;
end.
|
unit MasterMind.ConsoleUtils.Tests;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
interface
uses
Classes, SysUtils, fpcunit, testregistry, MasterMind.API;
type
TTestMasterMindConsoleUtils = class(TTestCase)
published
procedure TestTryStringToCodeWithInvalidCode;
procedure TestTryStringToCodeWithValidCode;
end;
implementation
uses
MasterMind.ConsoleUtils, MasterMind.TestHelper, EnumHelper;
procedure TTestMasterMindConsoleUtils.TestTryStringToCodeWithInvalidCode;
var
Code: TMasterMindCode;
begin
CheckFalse(TryStringToCode('invalid', Code));
end;
procedure TTestMasterMindConsoleUtils.TestTryStringToCodeWithValidCode;
var
Code: TMasterMindCode;
begin
CheckTrue(TryStringToCode('robw', Code));
TEnumHelper<TMasterMindCodeColor>.CheckArraysEqual(MakeCode([mmcRed, mmcOrange, mmcBrown, mmcWhite]), Code);
end;
initialization
RegisterTest(TTestMasterMindConsoleUtils);
end. |
unit GenericDao;
interface
Uses Db, StrUtils, Rtti, AttributeEntity, TypInfo, SysUtils, Dados.Firebird, Generics.Collections,FireDAC.Comp.Client, FireDAC.Comp.DataSet;
type
TGenericDAO = class
private
class function GetTableName<T: class>(Obj: T): String;
public
class function Insert<T: class>(Obj: T):boolean;
class function Update<T: class>(Obj: T):boolean;
class function GetAll<T: class>(Obj: T): TDataSet;
class function GetPesquisa<T: class>(Obj: T; aValorPk: integer): TDataSet;
class function GetID<T: class>(Obj: T; aCAmpo : String): integer;
class function GetDescricao<T: class>(Obj: T; aValorPk: integer): String;
class function DeleteSlaveTable<T: class>(Obj: T; aValorFk : integer): boolean;
end;
implementation
class function TGenericDAO.GetDescricao<T>(Obj: T; aValorPk: integer): String;
var
Contexto: TRttiContext;
TypObj: TRttiType;
Prop: TRttiProperty;
strInsert, strFields, strValues: String;
Atributo: TCustomAttribute;
aDataSet : TFDQuery;
aSql, aVlrRet : string;
begin
result := '';
aSql := '';
aDataSet := TFDQuery.Create(nil);
aDataSet.ConnectioN := DadosFirebird.FDdaDOS;
strInsert := GetTableName(Obj);
Contexto := TRttiContext.Create;
TypObj := Contexto.GetType(TObject(Obj).ClassInfo);
aSql := 'SELECT T1.* ' +' FROM ' + GetTableName(Obj) + ' T1 ';
for Prop in TypObj.GetProperties do
begin
for Atributo in Prop.GetAttributes do
begin
if Atributo is KeyField then
aSql := aSql +' WHERE T1.'+FieldName(Atributo).Name+' = ';
if FieldName(Atributo).Name = 'DESCRICAO' then
aSql := aSql +IntToStr(aValorPK);
end;
end;
DadosFirebird.OpenDataSet(aSql, aDataSet);
if not aDataSet.IsEmpty then
aVlrRet := aDataSet.FieldByName(FieldName(Atributo).Name).AsString;
result := aVlrRet;
end;
class function TGenericDAO.GetID<T>(Obj: T; aCAmpo: String): integer;
begin
result := DadosFirebird.getMax(GetTableName(Obj),aCampo);
end;
class function TGenericDAO.GetPesquisa<T>(Obj: T; aValorPk: integer): TDataSet;
var
aContexto: TRttiContext;
aTypObj: TRttiType;
aProp: TRttiProperty;
aNomeTabela, aSql: String;
aAtributo: TCustomAttribute;
aDataSet : TDataset;
begin
result := nil;
aSql := '';
aDataSet := TDataset.Create(nil);
aContexto := TRttiContext.Create;
aTypObj := aContexto.GetType(TObject(Obj).ClassInfo);
aSql := 'SELECT T1.* ' +' FROM ' + GetTableName(Obj) + ' T1 ';
for aProp in aTypObj.GetProperties do
begin
for aAtributo in aProp.GetAttributes do
begin
if aAtributo is KeyField then
aSql := aSql +' WHERE T1.'+FieldName(aAtributo).Name+' = ';
end;
end;
aSql := aSql + IntToStr(aValorPk);
aDataSet := DadosFirebird.getDataSet(aSql);
if not aDataSet.IsEmpty then
result := aDataSet;
end;
class function TGenericDAO.GetTableName<T>(Obj: T): String;
var
Contexto: TRttiContext;
TypObj: TRttiType;
Atributo: TCustomAttribute;
strTable: String;
begin
Contexto := TRttiContext.Create;
TypObj := Contexto.GetType(TObject(Obj).ClassInfo);
for Atributo in TypObj.GetAttributes do
begin
if Atributo is TableName then
Exit(TableName(Atributo).Name);
end;
end;
class function TGenericDAO.Insert<T>(Obj: T):boolean;
var
Contexto: TRttiContext;
TypObj: TRttiType;
Prop: TRttiProperty;
strInsert, strFields, strValues: String;
Atributo: TCustomAttribute;
begin
strInsert := '';
strFields := '';
strValues := '';
strInsert := 'INSERT INTO ' + GetTableName(Obj);
Contexto := TRttiContext.Create;
TypObj := Contexto.GetType(TObject(Obj).ClassInfo);
for Prop in TypObj.GetProperties do
begin
for Atributo in Prop.GetAttributes do
begin
if Atributo is FieldName then
begin
strFields := strFields + FieldName(Atributo).Name + ',';
case Prop.GetValue(TObject(Obj)).Kind of
tkWChar, tkLString, tkWString, tkString,
tkChar, tkUString:
strValues := strValues +
QuotedStr(Prop.GetValue(TObject(Obj)).AsString) + ',';
tkInteger, tkInt64:
strValues := strValues +
IntToStr(Prop.GetValue(TObject(Obj)).AsInteger) + ',';
tkFloat:
strValues := strValues +
FloatToStr(Prop.GetValue(TObject(Obj)).AsExtended) + ',';
else
raise Exception.Create('Type not Supported');
end;
end;
end;
end;
strFields := Copy(strFields, 1, Length(strFields) - 1);
strValues := Copy(strValues, 1, Length(strValues) - 1);
strInsert := strInsert + ' ( ' + strFields + ' ) VALUES ( ' + strValues + ' )';
result := DadosFirebird.ExecuteSql(strInsert);
end;
class function TGenericDAO.Update<T>(Obj: T): boolean;
var
aContexto: TRttiContext;
TypObj: TRttiType;
Prop: TRttiProperty;
aPKey, strUpdate, strFields, strWhere: String;
aAtributo: TCustomAttribute;
begin
aPKey := '';
strUpdate := '';
strFields := '';
strUpdate := 'UPDATE ' + GetTableName(Obj)+' SET ';
strWhere := ' WHERE 1=1 ';
aContexto := TRttiContext.Create;
TypObj := aContexto.GetType(TObject(Obj).ClassInfo);
for Prop in TypObj.GetProperties do
begin
for aAtributo in Prop.GetAttributes do
begin
if aAtributo is KeyField then
begin
aPKey := aPKey + FieldName(aAtributo).Name;
strWhere := strWhere + ' AND '+FieldName(aAtributo).Name + ' = ';
case Prop.GetValue(TObject(Obj)).Kind of
tkWChar, tkLString, tkWString, tkString,
tkChar, tkUString:
strWhere := strWhere + QuotedStr(Prop.GetValue(TObject(Obj)).AsString) + ',';
tkInteger, tkInt64:
strWhere := strWhere + IntToStr(Prop.GetValue(TObject(Obj)).AsInteger) + ',';
tkFloat:
strWhere := strWhere + FloatToStr(Prop.GetValue(TObject(Obj)).AsExtended) + ',';
else
raise Exception.Create('Type not Supported');
end;
end
else
begin
if Pos(FieldName(aAtributo).Name, aPkey) = 0 then
begin
strFields := strFields + FieldName(aAtributo).Name + ' = ';
case Prop.GetValue(TObject(Obj)).Kind of
tkWChar, tkLString, tkWString, tkString,
tkChar, tkUString:
strFields := strFields + QuotedStr(Prop.GetValue(TObject(Obj)).AsString) + ',';
tkInteger, tkInt64:
strFields := strFields + IntToStr(Prop.GetValue(TObject(Obj)).AsInteger) + ',';
tkFloat:
strFields := strFields + FloatToStr(Prop.GetValue(TObject(Obj)).AsExtended) + ',';
else
raise Exception.Create('Type not Supported');
end;
end;
end;
end;
end;
strFields := Copy(strFields, 1, Length(strFields) - 1);
strWhere := Copy(strWhere, 1, Length(strWhere) - 1);
strUpdate := strUpdate + strFields + strWhere;
result := DadosFirebird.ExecuteSql(strUpdate);
end;
class function TGenericDAO.DeleteSlaveTable<T>(Obj: T; aValorFk: integer): boolean;
var
aContexto: TRttiContext;
aTypObj: TRttiType;
aProp: TRttiProperty;
aNomeTabela, aSql: String;
aAtributo: TCustomAttribute;
aDataSet : TFDQuery;
begin
result := false;
aSql := '';
aDataSet := TFDQuery.Create(nil);
aContexto := TRttiContext.Create;
aTypObj := aContexto.GetType(TObject(Obj).ClassInfo);
aSql := 'DELETE FROM ' + GetTableName(Obj);
for aProp in aTypObj.GetProperties do
begin
for aAtributo in aProp.GetAttributes do
begin
if aAtributo is KeyField then
aSql := aSql +' WHERE '+FieldName(aAtributo).Name+' = ';
end;
end;
aSql := aSql + IntToStr(aValorFk);
result := DadosFirebird.ExecuteSql(aSql);
end;
class function TGenericDAO.GetAll<T>(Obj: T): TDataSet;
begin
result := DadosFirebird.getDataSet('SELECT T1.* ' +
' FROM ' + GetTableName(Obj) + ' T1 ' );
end;
end.
|
{***************************************************************************
*
* Orion-project.org Lazarus Helper Library
* Copyright (C) 2016-2017 by Nikolay Chunosov
*
* This file is part of the Orion-project.org Lazarus Helper Library
* https://github.com/Chunosov/orion-lazarus
*
* This Library is free software: you can redistribute it and/or modify it
* under the terms of the MIT License. See enclosed LICENSE.txt for details.
*
***************************************************************************}
unit OriGraphics;
{$mode objfpc}{$H+}
interface
uses
Graphics;
function Lighten(Color: TColor; Amount: Integer): TColor;
function Blend(Color1, Color2: TColor; W1: Integer): TColor;
function MixColors(Color1, Color2: TColor; W1: Integer): TColor;
const
{%region 'Web colors'}
// Reds
clIndianRed = TColor($5C5CCD);
clLightCoral = TColor($8080F0);
clSalmon = TColor($7280FA);
clDarkSalmon = TColor($7A96E9);
clLightSalmon = TColor($7AA0FF);
clCrimson = TColor($3C14DC);
clFireBrick = TColor($2222B2);
clDarkRed = TColor($00008B);
// Pinks
clPink = TColor($CBC0FF);
clLightPink = TColor($C1B6FF);
clHotPink = TColor($B469FF);
clDeepPink = TColor($9314FF);
clMediumVioletRed = TColor($8515C7);
clPaleVioletRed = TColor($9370DB);
// Oranges
clCoral = TColor($507FFF);
clTomato = TColor($4763FF);
clOrangeRed = TColor($0045FF);
clDarkOrange = TColor($008CFF);
clOrange = TColor($00A5FF);
// Yellows
clGold = TColor($00D7FF);
clYellow = TColor($00FFFF);
clLightYellow = TColor($E0FFFF);
clLemonChiffon = TColor($CDFAFF);
clLightGoldenrodYellow = TColor($D2FAFA);
clPapayaWhip = TColor($D5EFFF);
clMoccasin = TColor($B5E4FF);
clPeachPuff = TColor($B9DAFF);
clPaleGoldenrod = TColor($AAE8EE);
clKhaki = TColor($8CE6F0);
clDarkKhaki = TColor($6BB7BD);
// Violets
clLavender = TColor($FAE6E6);
clThistle = TColor($D8BFD8);
clPlum = TColor($DDA0DD);
clViolet = TColor($EE82EE);
clOrchid = TColor($D670DA);
clMagenta = TColor($FF00FF);
clMediumOrchid = TColor($D355BA);
clMediumPurple = TColor($DB7093);
clBlueViolet = TColor($E22B8A);
clDarkViolet = TColor($D30094);
clDarkOrchid = TColor($CC3299);
clDarkMagenta = TColor($8B008B);
clPurple = TColor($800080);
clIndigo = TColor($82004B);
clSlateBlue = TColor($CD5A6A);
clDarkSlateBlue = TColor($8B3D48);
// Greens
clGreenYellow = TColor($2FFFAD);
clChartreuse = TColor($00FF7F);
clLawnGreen = TColor($00FC7C);
clLimeGreen = TColor($32CD32);
clPaleGreen = TColor($98FB98);
clLightGreen = TColor($90EE90);
clMediumSpringGreen = TColor($9AFA00);
clSpringGreen = TColor($7FFF00);
clMediumSeaGreen = TColor($71B33C);
clSeaGreen = TColor($578B2E);
clForestGreen = TColor($228B22);
clDarkGreen = TColor($006400);
clYellowGreen = TColor($32CD9A);
clOliveDrab = TColor($238E6B);
clDarkOliveGreen = TColor($2F6B55);
clMediumAquamarine = TColor($AACD66);
clDarkSeaGreen = TColor($8FBC8F);
clLightSeaGreen = TColor($AAB220);
clDarkCyan = TColor($8B8B00);
// Bules
clLightCyan = TColor($FFFFE0);
clPaleTurquoise = TColor($EEEEAF);
clAquamarine = TColor($D4FF7F);
clTurquoise = TColor($D0E040);
clMediumTurquoise = TColor($CCD148);
clDarkTurquoise = TColor($D1CE00);
clCadetBlue = TColor($A09E5F);
clSteelBlue = TColor($B48246);
clLightSteelBlue = TColor($DEC4B0);
clPowderBlue = TColor($E6E0B0);
clLightBlue = TColor($E6D8AD);
clSkyBlue = TColor($EBCE87);
clLightSkyBlue = TColor($FACE87);
clDeepSkyBlue = TColor($FFBF00);
clDodgerBlue = TColor($FF901E);
clCornflowerBlue = TColor($ED9564);
clMediumSlateBlue = TColor($EE687B);
clRoyalBlue = TColor($E16941);
clMediumBlue = TColor($CD0000);
clDarkBlue = TColor($8B0000);
clMidnightBlue = TColor($701919);
// Browns
clCornsilk = TColor($DCF8FF);
clBlanchedAlmond = TColor($CDEBFF);
clBisque = TColor($C4E4FF);
clNavajoWhite = TColor($ADDEFF);
clWheat = TColor($B3DEF5);
clBurlyWood = TColor($87B8DE);
clTan = TColor($8CB4D2);
clRosyBrown = TColor($8F8FBC);
clSandyBrown = TColor($60A4F4);
clGoldenrod = TColor($20A5DA);
clDarkGoldenrod = TColor($0B86B8);
clPeru = TColor($3F85CD);
clChocolate = TColor($1E69D2);
clSaddleBrown = TColor($13458B);
clSienna = TColor($2D52A0);
clBrown = TColor($2A2AA5);
// Whites
clSnow = TColor($FAFAFF);
clHoneydew = TColor($F0FFF0);
clMintCream = TColor($FAFFF5);
clAzure = TColor($FFFFF0);
clAliceBlue = TColor($FFF8F0);
clGhostWhite = TColor($FFF8F8);
clWhiteSmoke = TColor($F5F5F5);
clSeashell = TColor($EEF5FF);
clBeige = TColor($DCF5F5);
clOldLace = TColor($E6F5FD);
clFloralWhite = TColor($F0FAFF);
clIvory = TColor($F0FFFF);
clAntiqueWhite = TColor($D7EBFA);
clLinen = TColor($E6F0FA);
clLavenderBlush = TColor($F5F0FF);
clMistyRose = TColor($E1E4FF);
// Grays
clGainsboro = TColor($DCDCDC);
clLightGray = TColor($D3D3D3);
clDarkGray = TColor($A9A9A9);
clDimGray = TColor($696969);
clLightSlateGray = TColor($998877);
clSlateGray = TColor($908070);
clDarkSlateGray = TColor($4F4F2F);
{%endregion}
implementation
uses
Classes;
{%region Color methods}
function Lighten(Color: TColor; Amount: Integer): TColor;
var
C, R, G, B: Integer;
begin
C := ColorToRGB(Color);
R := C and $FF + Amount;
G := C shr 8 and $FF + Amount;
B := C shr 16 and $FF + Amount;
if R < 0 then R := 0 else if R > 255 then R := 255;
if G < 0 then G := 0 else if G > 255 then G := 255;
if B < 0 then B := 0 else if B > 255 then B := 255;
Result := R or (G shl 8) or (B shl 16);
end;
function Blend(Color1, Color2: TColor; W1: Integer): TColor;
var
W2, A1, A2, D, F, G, C1, C2: Integer;
begin
C1 := ColorToRGB(Color1);
C2 := ColorToRGB(Color2);
if W1 >= 100 then D := 1000
else D := 100;
W2 := D - W1;
F := D div 2;
A2 := C2 shr 16 * W2;
A1 := C1 shr 16 * W1;
G := (A1 + A2 + F) div D and $FF;
Result := G shl 16;
A2 := (C2 shr 8 and $FF) * W2;
A1 := (C1 shr 8 and $FF) * W1;
G := (A1 + A2 + F) div D and $FF;
Result := Result or G shl 8;
A2 := (C2 and $FF) * W2;
A1 := (C1 and $FF) * W1;
G := (A1 + A2 + F) div D and $FF;
Result := Result or G;
end;
function MixColors(Color1, Color2: TColor; W1: Integer): TColor;
var
W2, C1, C2: Cardinal;
begin
Assert(W1 in [0..255]);
W2 := W1 xor 255;
C1 := ColorToRGB(Color1);
C2 := ColorToRGB(Color2);
Result := Integer(
((Cardinal(C1) and $FF00FF) * Cardinal(W1) +
(Cardinal(C2) and $FF00FF) * W2) and $FF00FF00 +
((Cardinal(C1) and $00FF00) * Cardinal(W1) +
(Cardinal(C2) and $00FF00) * W2) and $00FF0000) shr 8;
end;
{%endregion}
end.
|
unit Vigilante.Build.Observer.Impl;
interface
uses
System.TypInfo, System.Generics.Collections, Vigilante.Build.Model,
Vigilante.Build.Observer;
type
TBuildSubject = class(TInterfacedObject, IBuildSubject)
private
FObservadores: TList<IBuildObserver>;
public
constructor Create;
destructor Destroy; override;
procedure Adicionar(const ABuildObserver: IBuildObserver);
procedure Notificar(const ABuild: IBuildModel);
procedure Remover(const ABuildObserver: IBuildObserver);
end;
implementation
uses
System.SysUtils, System.Threading, System.Classes;
constructor TBuildSubject.Create;
begin
FObservadores := TList<IBuildObserver>.Create;
end;
destructor TBuildSubject.Destroy;
begin
FreeAndNil(FObservadores);
inherited;
end;
procedure TBuildSubject.Adicionar(const ABuildObserver: IBuildObserver);
begin
if FObservadores.Contains(ABuildObserver) then
Exit;
FObservadores.Add(ABuildObserver);
end;
procedure TBuildSubject.Notificar(const ABuild: IBuildModel);
begin
if FObservadores.Count = 0 then
Exit;
TParallel.For(0, Pred(FObservadores.Count),
procedure(i: integer)
begin
TThread.Queue(TThread.CurrentThread,
procedure
begin
FObservadores.Items[i].NovaAtualizacao(ABuild);
end);
end);
end;
procedure TBuildSubject.Remover(
const ABuildObserver: IBuildObserver);
begin
FObservadores.Remove(ABuildObserver);
end;
end.
|
unit Ths.Erp.Database.Table.MusteriTemsilciGrubu;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TMusteriTemsilciGrubu = class(TTable)
private
FTemsilciGrupAdi: TFieldDB;
FGecmisOcak: TFieldDB;
FGecmisSubat: TFieldDB;
FGecmisMart: TFieldDB;
FGecmisNisan: TFieldDB;
FGecmisMayis: TFieldDB;
FGecmisHaziran: TFieldDB;
FGecmisTemmuz: TFieldDB;
FGecmisAgustos: TFieldDB;
FGecmisEylul: TFieldDB;
FGecmisEkim: TFieldDB;
FGecmisKasim: TFieldDB;
FGecmisAralik: TFieldDB;
FHedefOcak: TFieldDB;
FHedefSubat: TFieldDB;
FHedefMart: TFieldDB;
FHedefNisan: TFieldDB;
FHedefMayis: TFieldDB;
FHedefHaziran: TFieldDB;
FHedefTemmuz: TFieldDB;
FHedefAgustos: TFieldDB;
FHedefEylul: TFieldDB;
FHedefEkim: TFieldDB;
FHedefKasim: TFieldDB;
FHedefAralik: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property TemsilciGrupAdi: TFieldDB read FTemsilciGrupAdi write FTemsilciGrupAdi;
Property GecmisOcak: TFieldDB read FGecmisOcak write FGecmisOcak;
Property GecmisSubat: TFieldDB read FGecmisSubat write FGecmisSubat;
Property GecmisMart: TFieldDB read FGecmisMart write FGecmisMart;
Property GecmisNisan: TFieldDB read FGecmisNisan write FGecmisNisan;
Property GecmisMayis: TFieldDB read FGecmisMayis write FGecmisMayis;
Property GecmisHaziran: TFieldDB read FGecmisHaziran write FGecmisHaziran;
Property GecmisTemmuz: TFieldDB read FGecmisTemmuz write FGecmisTemmuz;
Property GecmisAgustos: TFieldDB read FGecmisAgustos write FGecmisAgustos;
Property GecmisEylul: TFieldDB read FGecmisEylul write FGecmisEylul;
Property GecmisEkim: TFieldDB read FGecmisEkim write FGecmisEkim;
Property GecmisKasim: TFieldDB read FGecmisKasim write FGecmisKasim;
Property GecmisAralik: TFieldDB read FGecmisAralik write FGecmisAralik;
Property HedefOcak: TFieldDB read FHedefOcak write FHedefOcak;
Property HedefSubat: TFieldDB read FHedefSubat write FHedefSubat;
Property HedefMart: TFieldDB read FHedefMart write FHedefMart;
Property HedefNisan: TFieldDB read FHedefNisan write FHedefNisan;
Property HedefMayis: TFieldDB read FHedefMayis write FHedefMayis;
Property HedefHaziran: TFieldDB read FHedefHaziran write FHedefHaziran;
Property HedefTemmuz: TFieldDB read FHedefTemmuz write FHedefTemmuz;
Property HedefAgustos: TFieldDB read FHedefAgustos write FHedefAgustos;
Property HedefEylul: TFieldDB read FHedefEylul write FHedefEylul;
Property HedefEkim: TFieldDB read FHedefEkim write FHedefEkim;
Property HedefKasim: TFieldDB read FHedefKasim write FHedefKasim;
Property HedefAralik: TFieldDB read FHedefAralik write FHedefAralik;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TMusteriTemsilciGrubu.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'musteri_temsilci_grubu';
SourceCode := '1000';
FTemsilciGrupAdi := TFieldDB.Create('temsilci_grup_adi', ftString, '');
FGecmisOcak := TFieldDB.Create('gecmis_ocak', ftFloat, 0);
FGecmisSubat := TFieldDB.Create('gecmis_subat', ftFloat, 0);
FGecmisMart := TFieldDB.Create('gecmis_mart', ftFloat, 0);
FGecmisNisan := TFieldDB.Create('gecmis_nisan', ftFloat, 0);
FGecmisMayis := TFieldDB.Create('gecmis_mayis', ftFloat, 0);
FGecmisHaziran := TFieldDB.Create('gecmis_haziran', ftFloat, 0);
FGecmisTemmuz := TFieldDB.Create('gecmis_temmuz', ftFloat, 0);
FGecmisAgustos := TFieldDB.Create('gecmis_agustos', ftFloat, 0);
FGecmisEylul := TFieldDB.Create('gecmis_eylul', ftFloat, 0);
FGecmisEkim := TFieldDB.Create('gecmis_ekim', ftFloat, 0);
FGecmisKasim := TFieldDB.Create('gecmis_kasim', ftFloat, 0);
FGecmisAralik := TFieldDB.Create('gecmis_aralik', ftFloat, 0);
FHedefOcak := TFieldDB.Create('hedef_ocak', ftFloat, 0);
FHedefSubat := TFieldDB.Create('hedef_subat', ftFloat, 0);
FHedefMart := TFieldDB.Create('hedef_mart', ftFloat, 0);
FHedefNisan := TFieldDB.Create('hedef_nisan', ftFloat, 0);
FHedefMayis := TFieldDB.Create('hedef_mayis', ftFloat, 0);
FHedefHaziran := TFieldDB.Create('hedef_haziran', ftFloat, 0);
FHedefTemmuz := TFieldDB.Create('hedef_temmuz', ftFloat, 0);
FHedefAgustos := TFieldDB.Create('hedef_agustos', ftFloat, 0);
FHedefEylul := TFieldDB.Create('hedef_eylul', ftFloat, 0);
FHedefEkim := TFieldDB.Create('hedef_ekim', ftFloat, 0);
FHedefKasim := TFieldDB.Create('hedef_kasim', ftFloat, 0);
FHedefAralik := TFieldDB.Create('hedef_aralik', ftFloat, 0);
end;
procedure TMusteriTemsilciGrubu.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FTemsilciGrupAdi.FieldName,
TableName + '.' + FGecmisOcak.FieldName,
TableName + '.' + FGecmisSubat.FieldName,
TableName + '.' + FGecmisMart.FieldName,
TableName + '.' + FGecmisNisan.FieldName,
TableName + '.' + FGecmisMayis.FieldName,
TableName + '.' + FGecmisHaziran.FieldName,
TableName + '.' + FGecmisTemmuz.FieldName,
TableName + '.' + FGecmisAgustos.FieldName,
TableName + '.' + FGecmisEylul.FieldName,
TableName + '.' + FGecmisEkim.FieldName,
TableName + '.' + FGecmisKasim.FieldName,
TableName + '.' + FGecmisAralik.FieldName,
TableName + '.' + FHedefOcak.FieldName,
TableName + '.' + FHedefSubat.FieldName,
TableName + '.' + FHedefMart.FieldName,
TableName + '.' + FHedefNisan.FieldName,
TableName + '.' + FHedefMayis.FieldName,
TableName + '.' + FHedefHaziran.FieldName,
TableName + '.' + FHedefTemmuz.FieldName,
TableName + '.' + FHedefAgustos.FieldName,
TableName + '.' + FHedefEylul.FieldName,
TableName + '.' + FHedefEkim.FieldName,
TableName + '.' + FHedefKasim.FieldName,
TableName + '.' + FHedefAralik.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FTemsilciGrupAdi.FieldName).DisplayLabel := 'Temsilci Grup Adı';
Self.DataSource.DataSet.FindField(FGecmisOcak.FieldName).DisplayLabel := 'Geçmiş Ocak';
Self.DataSource.DataSet.FindField(FGecmisSubat.FieldName).DisplayLabel := 'Geçmiş Şubat';
Self.DataSource.DataSet.FindField(FGecmisMart.FieldName).DisplayLabel := 'Geçmiş Mart';
Self.DataSource.DataSet.FindField(FGecmisNisan.FieldName).DisplayLabel := 'Geçmiş Nisan';
Self.DataSource.DataSet.FindField(FGecmisMayis.FieldName).DisplayLabel := 'Geçmiş Mayıs';
Self.DataSource.DataSet.FindField(FGecmisHaziran.FieldName).DisplayLabel := 'Geçmiş Haziran';
Self.DataSource.DataSet.FindField(FGecmisTemmuz.FieldName).DisplayLabel := 'Geçmiş Temmuz';
Self.DataSource.DataSet.FindField(FGecmisAgustos.FieldName).DisplayLabel := 'Geçmiş Ağustos';
Self.DataSource.DataSet.FindField(FGecmisEylul.FieldName).DisplayLabel := 'Geçmiş Eylül';
Self.DataSource.DataSet.FindField(FGecmisEkim.FieldName).DisplayLabel := 'Geçmiş Ekim';
Self.DataSource.DataSet.FindField(FGecmisKasim.FieldName).DisplayLabel := 'Geçmiş Kasım';
Self.DataSource.DataSet.FindField(FGecmisAralik.FieldName).DisplayLabel := 'Geçmiş Aralık';
Self.DataSource.DataSet.FindField(FHedefOcak.FieldName).DisplayLabel := 'Hedef Ocak';
Self.DataSource.DataSet.FindField(FHedefSubat.FieldName).DisplayLabel := 'Hedef Şubat';
Self.DataSource.DataSet.FindField(FHedefMart.FieldName).DisplayLabel := 'Hedef Mart';
Self.DataSource.DataSet.FindField(FHedefNisan.FieldName).DisplayLabel := 'Hedef Nisan';
Self.DataSource.DataSet.FindField(FHedefMayis.FieldName).DisplayLabel := 'Hedef Mayıs';
Self.DataSource.DataSet.FindField(FHedefHaziran.FieldName).DisplayLabel := 'Hedef Haziran';
Self.DataSource.DataSet.FindField(FHedefTemmuz.FieldName).DisplayLabel := 'Hedef Temmuz';
Self.DataSource.DataSet.FindField(FHedefAgustos.FieldName).DisplayLabel := 'Hedef Ağustos';
Self.DataSource.DataSet.FindField(FHedefEylul.FieldName).DisplayLabel := 'Hedef Eylül';
Self.DataSource.DataSet.FindField(FHedefEkim.FieldName).DisplayLabel := 'Hedef Ekim';
Self.DataSource.DataSet.FindField(FHedefKasim.FieldName).DisplayLabel := 'Hedef Kasım';
Self.DataSource.DataSet.FindField(FHedefAralik.FieldName).DisplayLabel := 'Hedef Aralık';
end;
end;
end;
procedure TMusteriTemsilciGrubu.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FTemsilciGrupAdi.FieldName,
TableName + '.' + FGecmisOcak.FieldName,
TableName + '.' + FGecmisSubat.FieldName,
TableName + '.' + FGecmisMart.FieldName,
TableName + '.' + FGecmisNisan.FieldName,
TableName + '.' + FGecmisMayis.FieldName,
TableName + '.' + FGecmisHaziran.FieldName,
TableName + '.' + FGecmisTemmuz.FieldName,
TableName + '.' + FGecmisAgustos.FieldName,
TableName + '.' + FGecmisEylul.FieldName,
TableName + '.' + FGecmisEkim.FieldName,
TableName + '.' + FGecmisKasim.FieldName,
TableName + '.' + FGecmisAralik.FieldName,
TableName + '.' + FHedefOcak.FieldName,
TableName + '.' + FHedefSubat.FieldName,
TableName + '.' + FHedefMart.FieldName,
TableName + '.' + FHedefNisan.FieldName,
TableName + '.' + FHedefMayis.FieldName,
TableName + '.' + FHedefHaziran.FieldName,
TableName + '.' + FHedefTemmuz.FieldName,
TableName + '.' + FHedefAgustos.FieldName,
TableName + '.' + FHedefEylul.FieldName,
TableName + '.' + FHedefEkim.FieldName,
TableName + '.' + FHedefKasim.FieldName,
TableName + '.' + FHedefAralik.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FTemsilciGrupAdi.Value := FormatedVariantVal(FieldByName(FTemsilciGrupAdi.FieldName).DataType, FieldByName(FTemsilciGrupAdi.FieldName).Value);
FGecmisOcak.Value := FormatedVariantVal(FieldByName(FGecmisOcak.FieldName).DataType, FieldByName(FGecmisOcak.FieldName).Value);
FGecmisSubat.Value := FormatedVariantVal(FieldByName(FGecmisSubat.FieldName).DataType, FieldByName(FGecmisSubat.FieldName).Value);
FGecmisMart.Value := FormatedVariantVal(FieldByName(FGecmisMart.FieldName).DataType, FieldByName(FGecmisMart.FieldName).Value);
FGecmisNisan.Value := FormatedVariantVal(FieldByName(FGecmisNisan.FieldName).DataType, FieldByName(FGecmisNisan.FieldName).Value);
FGecmisMayis.Value := FormatedVariantVal(FieldByName(FGecmisMayis.FieldName).DataType, FieldByName(FGecmisMayis.FieldName).Value);
FGecmisHaziran.Value := FormatedVariantVal(FieldByName(FGecmisHaziran.FieldName).DataType, FieldByName(FGecmisHaziran.FieldName).Value);
FGecmisTemmuz.Value := FormatedVariantVal(FieldByName(FGecmisTemmuz.FieldName).DataType, FieldByName(FGecmisTemmuz.FieldName).Value);
FGecmisAgustos.Value := FormatedVariantVal(FieldByName(FGecmisAgustos.FieldName).DataType, FieldByName(FGecmisAgustos.FieldName).Value);
FGecmisEylul.Value := FormatedVariantVal(FieldByName(FGecmisEylul.FieldName).DataType, FieldByName(FGecmisEylul.FieldName).Value);
FGecmisEkim.Value := FormatedVariantVal(FieldByName(FGecmisEkim.FieldName).DataType, FieldByName(FGecmisEkim.FieldName).Value);
FGecmisKasim.Value := FormatedVariantVal(FieldByName(FGecmisKasim.FieldName).DataType, FieldByName(FGecmisKasim.FieldName).Value);
FGecmisAralik.Value := FormatedVariantVal(FieldByName(FGecmisAralik.FieldName).DataType, FieldByName(FGecmisAralik.FieldName).Value);
FHedefOcak.Value := FormatedVariantVal(FieldByName(FHedefOcak.FieldName).DataType, FieldByName(FHedefOcak.FieldName).Value);
FHedefSubat.Value := FormatedVariantVal(FieldByName(FHedefSubat.FieldName).DataType, FieldByName(FHedefSubat.FieldName).Value);
FHedefMart.Value := FormatedVariantVal(FieldByName(FHedefMart.FieldName).DataType, FieldByName(FHedefMart.FieldName).Value);
FHedefNisan.Value := FormatedVariantVal(FieldByName(FHedefNisan.FieldName).DataType, FieldByName(FHedefNisan.FieldName).Value);
FHedefMayis.Value := FormatedVariantVal(FieldByName(FHedefMayis.FieldName).DataType, FieldByName(FHedefMayis.FieldName).Value);
FHedefHaziran.Value := FormatedVariantVal(FieldByName(FHedefHaziran.FieldName).DataType, FieldByName(FHedefHaziran.FieldName).Value);
FHedefTemmuz.Value := FormatedVariantVal(FieldByName(FHedefTemmuz.FieldName).DataType, FieldByName(FHedefTemmuz.FieldName).Value);
FHedefAgustos.Value := FormatedVariantVal(FieldByName(FHedefAgustos.FieldName).DataType, FieldByName(FHedefAgustos.FieldName).Value);
FHedefEylul.Value := FormatedVariantVal(FieldByName(FHedefEylul.FieldName).DataType, FieldByName(FHedefEylul.FieldName).Value);
FHedefEkim.Value := FormatedVariantVal(FieldByName(FHedefEkim.FieldName).DataType, FieldByName(FHedefEkim.FieldName).Value);
FHedefKasim.Value := FormatedVariantVal(FieldByName(FHedefKasim.FieldName).DataType, FieldByName(FHedefKasim.FieldName).Value);
FHedefAralik.Value := FormatedVariantVal(FieldByName(FHedefAralik.FieldName).DataType, FieldByName(FHedefAralik.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TMusteriTemsilciGrubu.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FTemsilciGrupAdi.FieldName,
FGecmisOcak.FieldName,
FGecmisSubat.FieldName,
FGecmisMart.FieldName,
FGecmisNisan.FieldName,
FGecmisMayis.FieldName,
FGecmisHaziran.FieldName,
FGecmisTemmuz.FieldName,
FGecmisAgustos.FieldName,
FGecmisEylul.FieldName,
FGecmisEkim.FieldName,
FGecmisKasim.FieldName,
FGecmisAralik.FieldName,
FHedefOcak.FieldName,
FHedefSubat.FieldName,
FHedefMart.FieldName,
FHedefNisan.FieldName,
FHedefMayis.FieldName,
FHedefHaziran.FieldName,
FHedefTemmuz.FieldName,
FHedefAgustos.FieldName,
FHedefEylul.FieldName,
FHedefEkim.FieldName,
FHedefKasim.FieldName,
FHedefAralik.FieldName
]);
NewParamForQuery(QueryOfInsert, FTemsilciGrupAdi);
NewParamForQuery(QueryOfInsert, FGecmisOcak);
NewParamForQuery(QueryOfInsert, FGecmisSubat);
NewParamForQuery(QueryOfInsert, FGecmisMart);
NewParamForQuery(QueryOfInsert, FGecmisNisan);
NewParamForQuery(QueryOfInsert, FGecmisMayis);
NewParamForQuery(QueryOfInsert, FGecmisHaziran);
NewParamForQuery(QueryOfInsert, FGecmisTemmuz);
NewParamForQuery(QueryOfInsert, FGecmisAgustos);
NewParamForQuery(QueryOfInsert, FGecmisEylul);
NewParamForQuery(QueryOfInsert, FGecmisEkim);
NewParamForQuery(QueryOfInsert, FGecmisKasim);
NewParamForQuery(QueryOfInsert, FGecmisAralik);
NewParamForQuery(QueryOfInsert, FHedefOcak);
NewParamForQuery(QueryOfInsert, FHedefSubat);
NewParamForQuery(QueryOfInsert, FHedefMart);
NewParamForQuery(QueryOfInsert, FHedefNisan);
NewParamForQuery(QueryOfInsert, FHedefMayis);
NewParamForQuery(QueryOfInsert, FHedefHaziran);
NewParamForQuery(QueryOfInsert, FHedefTemmuz);
NewParamForQuery(QueryOfInsert, FHedefAgustos);
NewParamForQuery(QueryOfInsert, FHedefEylul);
NewParamForQuery(QueryOfInsert, FHedefEkim);
NewParamForQuery(QueryOfInsert, FHedefKasim);
NewParamForQuery(QueryOfInsert, FHedefAralik);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TMusteriTemsilciGrubu.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FTemsilciGrupAdi.FieldName,
FGecmisOcak.FieldName,
FGecmisSubat.FieldName,
FGecmisMart.FieldName,
FGecmisNisan.FieldName,
FGecmisMayis.FieldName,
FGecmisHaziran.FieldName,
FGecmisTemmuz.FieldName,
FGecmisAgustos.FieldName,
FGecmisEylul.FieldName,
FGecmisEkim.FieldName,
FGecmisKasim.FieldName,
FGecmisAralik.FieldName,
FHedefOcak.FieldName,
FHedefSubat.FieldName,
FHedefMart.FieldName,
FHedefNisan.FieldName,
FHedefMayis.FieldName,
FHedefHaziran.FieldName,
FHedefTemmuz.FieldName,
FHedefAgustos.FieldName,
FHedefEylul.FieldName,
FHedefEkim.FieldName,
FHedefKasim.FieldName,
FHedefAralik.FieldName
]);
NewParamForQuery(QueryOfUpdate, FTemsilciGrupAdi);
NewParamForQuery(QueryOfUpdate, FGecmisOcak);
NewParamForQuery(QueryOfUpdate, FGecmisSubat);
NewParamForQuery(QueryOfUpdate, FGecmisMart);
NewParamForQuery(QueryOfUpdate, FGecmisNisan);
NewParamForQuery(QueryOfUpdate, FGecmisMayis);
NewParamForQuery(QueryOfUpdate, FGecmisHaziran);
NewParamForQuery(QueryOfUpdate, FGecmisTemmuz);
NewParamForQuery(QueryOfUpdate, FGecmisAgustos);
NewParamForQuery(QueryOfUpdate, FGecmisEylul);
NewParamForQuery(QueryOfUpdate, FGecmisEkim);
NewParamForQuery(QueryOfUpdate, FGecmisKasim);
NewParamForQuery(QueryOfUpdate, FGecmisAralik);
NewParamForQuery(QueryOfUpdate, FHedefOcak);
NewParamForQuery(QueryOfUpdate, FHedefSubat);
NewParamForQuery(QueryOfUpdate, FHedefMart);
NewParamForQuery(QueryOfUpdate, FHedefNisan);
NewParamForQuery(QueryOfUpdate, FHedefMayis);
NewParamForQuery(QueryOfUpdate, FHedefHaziran);
NewParamForQuery(QueryOfUpdate, FHedefTemmuz);
NewParamForQuery(QueryOfUpdate, FHedefAgustos);
NewParamForQuery(QueryOfUpdate, FHedefEylul);
NewParamForQuery(QueryOfUpdate, FHedefEkim);
NewParamForQuery(QueryOfUpdate, FHedefKasim);
NewParamForQuery(QueryOfUpdate, FHedefAralik);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TMusteriTemsilciGrubu.Clone():TTable;
begin
Result := TMusteriTemsilciGrubu.Create(Database);
Self.Id.Clone(TMusteriTemsilciGrubu(Result).Id);
FTemsilciGrupAdi.Clone(TMusteriTemsilciGrubu(Result).FTemsilciGrupAdi);
FGecmisOcak.Clone(TMusteriTemsilciGrubu(Result).FGecmisOcak);
FGecmisSubat.Clone(TMusteriTemsilciGrubu(Result).FGecmisSubat);
FGecmisMart.Clone(TMusteriTemsilciGrubu(Result).FGecmisMart);
FGecmisNisan.Clone(TMusteriTemsilciGrubu(Result).FGecmisNisan);
FGecmisMayis.Clone(TMusteriTemsilciGrubu(Result).FGecmisMayis);
FGecmisHaziran.Clone(TMusteriTemsilciGrubu(Result).FGecmisHaziran);
FGecmisTemmuz.Clone(TMusteriTemsilciGrubu(Result).FGecmisTemmuz);
FGecmisAgustos.Clone(TMusteriTemsilciGrubu(Result).FGecmisAgustos);
FGecmisEylul.Clone(TMusteriTemsilciGrubu(Result).FGecmisEylul);
FGecmisEkim.Clone(TMusteriTemsilciGrubu(Result).FGecmisEkim);
FGecmisKasim.Clone(TMusteriTemsilciGrubu(Result).FGecmisKasim);
FGecmisAralik.Clone(TMusteriTemsilciGrubu(Result).FGecmisAralik);
FHedefOcak.Clone(TMusteriTemsilciGrubu(Result).FHedefOcak);
FHedefSubat.Clone(TMusteriTemsilciGrubu(Result).FHedefSubat);
FHedefMart.Clone(TMusteriTemsilciGrubu(Result).FHedefMart);
FHedefNisan.Clone(TMusteriTemsilciGrubu(Result).FHedefNisan);
FHedefMayis.Clone(TMusteriTemsilciGrubu(Result).FHedefMayis);
FHedefHaziran.Clone(TMusteriTemsilciGrubu(Result).FHedefHaziran);
FHedefTemmuz.Clone(TMusteriTemsilciGrubu(Result).FHedefTemmuz);
FHedefAgustos.Clone(TMusteriTemsilciGrubu(Result).FHedefAgustos);
FHedefEylul.Clone(TMusteriTemsilciGrubu(Result).FHedefEylul);
FHedefEkim.Clone(TMusteriTemsilciGrubu(Result).FHedefEkim);
FHedefKasim.Clone(TMusteriTemsilciGrubu(Result).FHedefKasim);
FHedefAralik.Clone(TMusteriTemsilciGrubu(Result).FHedefAralik);
end;
end.
|
unit h_Checks;
interface
uses SysUtils, Variants, h_Functions, system.Math;
Type
TChecks = class(TObject)
public
class function CPF(const CPF: string): string; //
class function CNPJ(const CNPJ: string): string; //
class function CanStrToNumber(const strValue: string): boolean; // Valor contém apenas números
class function Negative(const Value: Extended): boolean; // Valor < 0
class function Positive(const Value: Extended): boolean; // Valor > 0
class function Zero(const Value: Extended): boolean; // Valor = 0
class function Equals(const Value: Extended; const ValueToCompare: Extended): boolean; // Valor1 = Valor2
class function Greater(const Value: Extended; const ValueToCompare: Extended): boolean; // Valor1 > Valor2
class function GreaterEquals(const Value: Extended; const ValueToCompare: Extended): boolean; // Valor1 >= Valor2
class function Less(const Value: Extended; const ValueToCompare: Extended): boolean; // Valor1 < Valor2
class function LessEquals(const Value: Extended; const ValueToCompare: Extended): boolean; // Valor1 <= Valor2
class function dateIsNull(const Value: TDate): boolean;
end;
implementation
class function TChecks.CanStrToNumber(const strValue: string): boolean;
var
__var_type: Extended;
begin
result := TryStrToFloat(strValue, __var_type);
end;
class function TChecks.Equals(const Value, ValueToCompare: Extended): boolean;
begin
result := (comparevalue(Value, ValueToCompare) = 0);
end;
class function TChecks.Greater(const Value, ValueToCompare: Extended): boolean;
begin
result := (comparevalue(Value, ValueToCompare) = 1);
end;
class function TChecks.GreaterEquals(const Value, ValueToCompare: Extended): boolean;
begin
result := (Greater(Value, ValueToCompare) or Equals(Value, ValueToCompare));
end;
class function TChecks.dateIsNull(const Value: TDate): boolean;
begin
result := (formatdatetime('dd/mm/yyyy', Value) = '00/00/0000') or (formatdatetime('dd/mm/yyyy', Value) = '30/12/1899');
end;
class function TChecks.Negative(const Value: Extended): boolean;
begin
result := (comparevalue(Value, 0) = -1);
end;
class function TChecks.Positive(const Value: Extended): boolean;
begin
result := (comparevalue(Value, 0) = 1);
end;
class function TChecks.Zero(const Value: Extended): boolean;
begin
result := (comparevalue(Value, 0) = 0);
end;
class function TChecks.Less(const Value, ValueToCompare: Extended): boolean;
begin
result := (comparevalue(Value, ValueToCompare) = -1);
end;
class function TChecks.LessEquals(const Value, ValueToCompare: Extended): boolean;
begin
result := (Less(Value, ValueToCompare) or Equals(Value, ValueToCompare));
end;
class function TChecks.CNPJ(const CNPJ: string): string;
var
__cnpj: string;
begin
result := '';
__cnpj := TFunctions.CleanSpecialChars(CNPJ);
if length(__cnpj) <> 14 then
raise Exception.Create('Campo de CNPJ deve ter 14 dígitos!')
else
begin
if not CanStrToNumber(__cnpj) then
raise Exception.Create('Campo de CNPJ deve ser composto apenas por números!')
else
result := __cnpj;
end
end;
class function TChecks.CPF(const CPF: string): string;
var
__cpf: string;
begin
result := '';
__cpf := TFunctions.CleanSpecialChars(CPF);
if length(__cpf) <> 11 then
raise Exception.Create('Campo de CPF deve ter 11 dígitos!')
else
begin
if not CanStrToNumber(__cpf) then
raise Exception.Create('Campo de CPF deve ser composto apenas por números!')
else
result := __cpf;
end
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.