text stringlengths 14 6.51M |
|---|
{$i deltics.unicode.inc}
unit Deltics.Unicode.Transcode.CodepointToUtf8;
interface
uses
Deltics.Unicode.Types;
procedure _CodepointToUtf8(const aCodepoint: Codepoint; var aUtf8: PUtf8Char; var aMaxChars: Integer);
implementation
uses
Deltics.Unicode;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure _CodepointToUtf8(const aCodepoint: Codepoint;
var aUtf8: PUtf8Char;
var aMaxChars: Integer);
var
numContinuationBytes: Integer;
begin
case aCodepoint of
$00..$7f : begin
aUtf8^ := Utf8Char(aCodepoint);
Inc(aUtf8);
Dec(aMaxChars);
EXIT;
end;
$80..$7ff : begin
numContinuationBytes := 1;
aUtf8^ := Utf8Char($c0 or ((aCodepoint shr 6) and $1f));
end;
$800..$ffff : begin
numContinuationBytes := 2;
aUtf8^ := Utf8Char($e0 or ((aCodepoint shr 12) and $0f));
end;
$10000..$10ffff : begin
numContinuationBytes := 3;
aUtf8^ := Utf8Char($f0 or ((aCodepoint shr 18) and $07));
end;
else
raise EInvalidCodepoint.Create(aCodepoint);
end;
if numContinuationBytes > aMaxChars then
raise EUnicode.Create('Codepoint %s requires %d bytes to encode in Utf8 (capacity in buffer is %d)', [
Unicode.Ref(aCodepoint),
numContinuationBytes + 1,
aMaxChars]);
Inc(aUtf8);
Dec(aMaxChars);
while numContinuationBytes > 0 do
begin
Dec(numContinuationBytes);
aUtf8^ := Utf8Char($80 or ((aCodepoint shr (numContinuationBytes * 6)) and $3f));
Inc(aUtf8);
Dec(aMaxChars);
end;
end;
end.
|
unit obsws;
{$mode objfpc}{$H+}
interface
uses
{$IFDEF UNIX}cthreads,{$ENDIF} Classes, SysUtils,log_core,wsutils,wsmessages,wsstream,ssockets,WebsocketsClient,fpjson, jsonparser, StdCtrls;
type
{ treceiverthread }
treceiverthread = class(TThread)
private
ws_com: TWebsocketCommunincator;
protected
procedure Execute; override;
public
constructor create(_comm: TWebsocketCommunincator);
end;
type
{ twsmessage }
twsmessage=class
private
data:ansistring;
sender:ansistring;
public
readed:boolean;
constructor create(_data,_sender:ansistring);
function get_data:ansistring;
function get_sender:ansistring;
end;
type
{ twsclient }
twsclient=class
private
errorlist:tstringlist;
receiver: TReceiverThread; //Thread for Reciving Msg
ws_com: TWebsocketCommunincator; //Handels connection
ws_client:twebsocketclient;
new_msgl:tlist;
l:tlog;
procedure recieve_msg(Sender: TObject);
procedure stream_closed(Sender: TObject);
function submit_error(_error_txt:ansistring):integer;
public
constructor create(_host:ansistring;_port:integer;_path:ansistring);
procedure assign_log(memo:tmemo);
function connect():integer;
function get_error(_error_id:integer):ansistring; //remove that useless feature
function disconnect():integer;
function send(_msg:string):integer;
function get_new_messages():tlist;
end;
implementation
{ twsmessage }
constructor twsmessage.create(_data, _sender: ansistring);
begin
data:=_data;
sender:=_sender;
readed:=false;
end;
function twsmessage.get_data: ansistring;
begin
result:=data;
readed:=true;
end;
function twsmessage.get_sender: ansistring;
begin
result:=sender;
end;
{ treceiverthread }
procedure treceiverthread.Execute;
begin
while not Terminated and ws_com.Open do begin
ws_com.RecieveMessage;
Sleep(100); //polling of messages every 100ms 1/10s //maybe change to make it faster
end;
end;
constructor treceiverthread.create(_comm: TWebsocketCommunincator);
begin
ws_com:= _comm; //Communicator (Verbindungs Handler ) wird durchgereicht
inherited Create(False); //create wird von tthread geerbt
end;
{ twsclient }
procedure twsclient.recieve_msg(Sender: TObject);
var msgl: TWebsocketMessageOwnerList;
m: TWebsocketMessage;
msg:twsmessage;
begin
msgl:=TWebsocketMessageOwnerList.Create(True);
try
ws_com.GetUnprocessedMessages(msgl); //Nachrichten abrufen
if not assigned(new_msgl) then new_msgl:=tlist.create();
for m in msgl do
if m is TWebsocketStringMessage then begin
msg:=twsmessage.create(TWebsocketStringMessage(m).Data,ws_com.SocketStream.RemoteAddress.Address);
new_msgl.Add(msg);
//l.inp('Message from '+ FCommunicator.SocketStream.RemoteAddress.Address+ ': '+ TWebsocketStringMessage(m).Data);
end;
finally
//msgl.Free; //Destroys MsgList (better: freeandnil() )
freeandnil(msgl);
end;
end;
procedure twsclient.stream_closed(Sender: TObject);
begin
//todo
end;
function twsclient.submit_error(_error_txt: ansistring): integer;
begin
result:=errorlist.Add(_error_txt);
end;
constructor twsclient.create(_host: ansistring; _port: integer;
_path: ansistring);
begin
errorlist:=tstringlist.Create;
ws_client:=twebsocketclient.Create(_host,_port,_path);
end;
procedure twsclient.assign_log(memo: tmemo);
begin
l:=tlog.create(2,memo);
end;
function twsclient.connect(): integer;
begin
try
ws_com:=ws_client.Connect(TSocketHandler.Create);
ws_com.OnClose:=@stream_closed;
ws_com.OnRecieveMessage:=@recieve_msg;
receiver:=treceiverthread.create(ws_com);
result:=0; //0= Connection established
except
result:=1; //1= Connection error
end;
end;
function twsclient.get_error(_error_id: integer): ansistring;
begin
if _error_id>=errorlist.Count then result:=''
else result:=errorlist.Strings[_error_id];
end;
function twsclient.disconnect(): integer;
begin
if assigned(ws_com) then begin
if ws_com.Open then ws_com.Close();
while ws_com.Open do sleep(100);
end;
if ws_com.Open then result:=1
else result:=0;
end;
function twsclient.send(_msg: string): integer;
begin
result:=0;
if ws_com.Open then begin
//if not ws_com.Open then Exit;
try
//test
_msg:='hi server';
l.outp('SEND STR: '+_msg);
ws_com.WriteMessage(wmtString,Word.maxvalue).Write(_msg,length(_msg));
l.outp('SENDED!');
//ws_com.WriteMessage.WriteRaw('{"request-type":"GetSceneList","message-id":"1"}');
result:=1;
finally
ws_com.WriteMessage.Free;
end;
end;
end;
function twsclient.get_new_messages(): tlist;
begin
if not assigned(new_msgl) then new_msgl:=tlist.create();
result:=new_msgl;
new_msgl:=tlist.create();
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit ItemEdit;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, DsnConst;
const
UM_TREEEDIT = WM_USER;
type
TItemInfo = class(TObject)
private
FSubItems: TStringList;
FSubItemImages: TList;
FCaption: string;
FImageIndex: Integer;
FStateIndex: Integer;
FGroupID: Integer;
public
constructor Create(Item: TListItem);
destructor Destroy; override;
end;
TListViewItems = class(TForm)
GroupBox1: TGroupBox;
PropGroupBox: TGroupBox;
New: TButton;
Delete: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
TreeView: TTreeView;
NewSub: TButton;
CaptionEdit: TEdit;
Image: TEdit;
StateImage: TEdit;
OkButton: TButton;
Cancel: TButton;
Apply: TButton;
Button7: TButton;
Label4: TLabel;
cbGroupID: TComboBox;
procedure NewClick(Sender: TObject);
procedure NewSubClick(Sender: TObject);
procedure DeleteClick(Sender: TObject);
procedure ValueChange(Sender: TObject);
procedure CaptionEditExit(Sender: TObject);
procedure ImageExit(Sender: TObject);
procedure StateImageExit(Sender: TObject);
procedure ApplyClick(Sender: TObject);
procedure TreeViewChange(Sender: TObject; Node: TTreeNode);
procedure TreeViewChanging(Sender: TObject; Node: TTreeNode;
var AllowChange: Boolean);
procedure TreeViewDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure TreeViewDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure TreeViewEdited(Sender: TObject; Node: TTreeNode;
var S: string);
procedure Button7Click(Sender: TObject);
procedure TreeViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure TreeViewEditing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure cbGroupIDChange(Sender: TObject);
private
FItems: TListItems;
FDropping: Boolean;
procedure FlushControls;
procedure GetItem(ItemInfo: TItemInfo; Value: TListItem);
procedure SetItem(Value: TItemInfo);
procedure SetStates;
procedure SetSubItem(const S: string; ImageIndex: Integer);
procedure UMTreeEdit(var M: TMessage); message UM_TREEEDIT;
public
property Items: TListItems read FItems;
end;
function EditListViewItems(AItems: TListItems): Boolean;
implementation
uses CommCtrl;
{$R *.dfm}
var
SavedWidth, SavedHeight, SavedLeft, SavedTop: Integer;
function EditListViewItems(AItems: TListItems): Boolean;
var
I, J: Integer;
Node: TTreeNode;
ItemInfo: TItemInfo;
ListView: TListView;
begin
with TListViewItems.Create(Application)do
try
FItems := AItems;
for I := 0 to Items.Count - 1 do
begin
ItemInfo := TItemInfo.Create(Items[I]);
Node := TreeView.Items.AddObject(nil, ItemInfo.FCaption, ItemInfo);
for J := 0 to ItemInfo.FSubItems.Count - 1 do
ItemInfo.FSubItems.Objects[J] := TreeView.Items.AddChild(Node,
ItemInfo.FSubItems[J]);
end;
ListView := TListView(FItems.Owner);
cbGroupID.AddItem(SItemEditNoGroupID, nil);
for I := 0 to ListView.Groups.Count - 1 do
cbGroupID.AddItem(Format(SItemEditGroupIDStr, [ListView.Groups[I].GroupID, ListView.Groups[I].Header]), ListView.Groups[I]);
with TreeView do
if Items.Count > 0 then
begin
Selected := Items.GetFirstNode;
TreeViewChange(nil, Selected);
end;
SetStates;
Result := ShowModal = mrOK;
if Result and Apply.Enabled then ApplyClick(nil);
finally
Free;
end;
end;
procedure ConvertError(Value: TEdit);
begin
with Value do
begin
SetFocus;
SelectAll;
end;
end;
{ TItemInfo }
constructor TItemInfo.Create(Item: TListItem);
var
I: Integer;
begin
inherited Create;
FSubItems := TStringList.Create;
FSubItemImages := TList.Create;
FStateIndex := -1;
FGroupID := -1;
if Item <> nil then
with Item do
begin
FCaption := Caption;
FImageIndex := ImageIndex;
FStateIndex := StateIndex;
FGroupID := GroupID;
FSubItems.Assign(SubItems);
for I := 0 to SubItems.Count-1 do
FSubItemImages.Add(Pointer(SubItemImages[I]));
end;
end;
destructor TItemInfo.Destroy;
begin
FSubItems.Free;
FSubItemImages.Free;
inherited Destroy;
end;
{ TListViewItems }
procedure TListViewItems.SetStates;
begin
Delete.Enabled := TreeView.Items.Count > 0;
PropGroupBox.Enabled := Delete.Enabled;
Apply.Enabled := False;
NewSub.Enabled := TreeView.Selected <> nil;
end;
procedure TListViewItems.GetItem(ItemInfo: TItemInfo; Value: TListItem);
var
I: Integer;
begin
with Value do
begin
Caption := ItemInfo.FCaption;
ImageIndex := ItemInfo.FImageIndex;
StateIndex := ItemInfo.FStateIndex;
GroupID := ItemInfo.FGroupID;
SubItems.Assign(ItemInfo.FSubItems);
for I := 0 to ItemInfo.FSubItems.Count - 1 do
SubItemImages[I] := Integer(ItemInfo.FSubItemImages[I]);
end;
end;
procedure TListViewItems.SetSubItem(const S: string; ImageIndex: Integer);
begin
StateImage.Enabled := False;
cbGroupID.Enabled := False;
Image.Text := IntToStr(ImageIndex);
CaptionEdit.Text := S;
end;
procedure TListViewItems.SetItem(Value: TItemInfo);
var
I: Integer;
begin
Image.Enabled := True;
StateImage.Enabled := True;
cbGroupID.Enabled := True;
if Value <> nil then
with Value do
begin
CaptionEdit.Text := FCaption;
Image.Text := IntToStr(FImageIndex);
StateImage.Text := IntToStr(FStateIndex);
if FGroupID < 0 then
cbGroupID.ItemIndex := 0
else
begin
for I := 1 to cbGroupID.Items.Count - 1 do
begin
if TListGroup(cbGroupID.Items.Objects[I]).GroupID = FGroupID then
begin
cbGroupID.ItemIndex := I;
break;
end;
end;
end;
end
else begin
CaptionEdit.Text := '';
Image.Text := '';
StateImage.Text := '';
end;
end;
procedure TListViewItems.FlushControls;
begin
CaptionEditExit(nil);
ImageExit(nil);
StateImageExit(nil);
end;
procedure TListViewItems.TreeViewChanging(Sender: TObject; Node: TTreeNode;
var AllowChange: Boolean);
begin
if not FDropping then FlushControls;
end;
procedure TListViewItems.TreeViewChange(Sender: TObject; Node: TTreeNode);
var
TempEnabled: Boolean;
ItemInfoSubs: TStrings;
Index: Integer;
begin
TempEnabled := Apply.Enabled;
if Node <> nil then
begin
SetStates;
if Node.Data <> nil then
SetItem(TItemInfo(Node.Data))
else begin
ItemInfoSubs := TItemInfo(Node.Parent.Data).FSubItems;
Index := ItemInfoSubs.IndexOfObject(Node);
SetSubItem(ItemInfoSubs[Index], Integer(TItemInfo(Node.Parent.Data).FSubItemImages[Index]));
end;
end
else SetItem(nil);
Apply.Enabled := TempEnabled;
end;
procedure TListViewItems.NewClick(Sender: TObject);
var
Node: TTreeNode;
begin
Node := TreeView.Items.AddObject(nil, '', TItemInfo.Create(nil));
Node.MakeVisible;
TreeView.Selected := Node;
CaptionEdit.SetFocus;
Apply.Enabled := True;
end;
procedure TListViewItems.NewSubClick(Sender: TObject);
var
Node, NewNode: TTreeNode;
begin
with TreeView do
begin
Node := Selected;
if Node <> nil then
begin
if Node.Data <> nil then
begin
NewNode := Node.Owner.AddChild(Node, '');
TItemInfo(Node.Data).FSubItems.AddObject('', NewNode);
TItemInfo(Node.Data).FSubItemImages.Add(Pointer(-1));
end
else begin
NewNode := Node.Owner.Add(Node, '');
TItemInfo(Node.Parent.Data).FSubItems.AddObject('', NewNode);
TItemInfo(Node.Parent.Data).FSubItemImages.Add(Pointer(-1));
end;
NewNode.MakeVisible;
Selected := NewNode;
end;
end;
CaptionEdit.SetFocus;
Apply.Enabled := True;
end;
procedure TListViewItems.DeleteClick(Sender: TObject);
var
Node: TTreeNode;
Index: Integer;
begin
Node := TreeView.Selected;
if Node <> nil then
begin
if Node.Data = nil then
begin
Index := TItemInfo(Node.Parent.Data).FSubItems.IndexOfObject(Node);
TItemInfo(Node.Parent.Data).FSubItems.Delete(Index);
TItemInfo(Node.Parent.Data).FSubItemImages.Delete(Index);
end
else TItemInfo(Node.Data).Free;
Node.Free;
end;
if TreeView.Items.Count = 0 then SetItem(nil);
SetStates;
Apply.Enabled := True;
end;
procedure TListViewItems.ValueChange(Sender: TObject);
begin
Apply.Enabled := True;
if Sender = CaptionEdit then CaptionEditExit(Sender);
end;
procedure TListViewItems.CaptionEditExit(Sender: TObject);
var
Node: TTreeNode;
ItemInfoSubs: TStrings;
begin
Node := TreeView.Selected;
if Node <> nil then
begin
if Node.Data = nil then
begin
ItemInfoSubs := TItemInfo(Node.Parent.Data).FSubItems;
ItemInfoSubs[ItemInfoSubs.IndexOfObject(Node)] := CaptionEdit.Text;
end
else TItemInfo(Node.Data).FCaption := CaptionEdit.Text;
Node.Text := CaptionEdit.Text;
end;
end;
procedure TListViewItems.cbGroupIDChange(Sender: TObject);
var
Node: TTreeNode;
begin
ValueChange(Sender);
Node := TreeView.Selected;
if (Node <> nil) and (Node.Data <> nil) then
begin
if cbGroupID.ItemIndex = 0 then
begin
TItemInfo(Node.Data).FGroupID := -1;
end
else
begin
TItemInfo(Node.Data).FGroupID := TListGroup(cbGroupID.Items.Objects[cbGroupID.ItemIndex]).GroupID;
end;
end;
end;
procedure TListViewItems.ImageExit(Sender: TObject);
var
Node: TTreeNode;
Index: Integer;
begin
if ActiveControl <> Cancel then
try
Node := TreeView.Selected;
if (Node <> nil) then
begin
if (Node.Data <> nil) then
TItemInfo(Node.Data).FImageIndex := StrToInt(Image.Text)
else begin
Index := TItemInfo(Node.Parent.Data).FSubItems.IndexOfObject(Node);
TItemInfo(Node.Parent.Data).FSubItemImages[Index] := Pointer(StrToInt(Image.Text));
end;
end;
except
ConvertError(Image);
raise;
end;
end;
procedure TListViewItems.StateImageExit(Sender: TObject);
var
Node: TTreeNode;
begin
if ActiveControl <> Cancel then
try
Node := TreeView.Selected;
if (Node <> nil) and (Node.Data <> nil) then
TItemInfo(Node.Data).FStateIndex := StrToInt(StateImage.Text);
except
ConvertError(StateImage);
raise;
end;
end;
procedure TListViewItems.ApplyClick(Sender: TObject);
var
Node: TTreeNode;
ListItem: TListItem;
begin
FlushControls;
Items.Clear;
if TreeView.Items.Count > 0 then Node := TreeView.Items[0]
else Node := nil;
while Node <> nil do
begin
if Node.Data <> nil then
begin
ListItem := Items.Add;
GetItem(TItemInfo(Node.Data), ListItem);
Node := Node.GetNextSibling;
end
end;
with TListView(Items.Owner) do UpdateItems(0, Items.Count -1);
Apply.Enabled := False;
end;
procedure TListViewItems.TreeViewDragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
var
Node, SelNode: TTreeNode;
Child: Boolean;
begin
Child := GetKeyState(VK_SHIFT) < 0;
SelNode := TreeView.Selected;
Node := TreeView.GetNodeAt(X, Y);
if Node = nil then Node := TreeView.DropTarget;
if Node = nil then
Accept := False
else
Accept := (SelNode <> Node) and not (Child and SelNode.HasAsParent(Node))
and not Node.HasAsParent(SelNode)
and not (SelNode.HasChildren and (Node.Data = nil))
and not (Child and (Node.Data <> nil) and SelNode.HasChildren);
end;
procedure TListViewItems.TreeViewDragDrop(Sender, Source: TObject; X,
Y: Integer);
var
Node, SelNode: TTreeNode;
Child: Boolean;
procedure AddItem(Source, Dest: TTreeNode);
var
ItemInfoSubs: TStrings;
begin
// dropping from child to child
if (Source.Data = nil) and (Dest.Data = nil) then
begin
// remove child from parent list
ItemInfoSubs := TItemInfo(Source.Parent.Data).FSubItems;
ItemInfoSubs.Delete(ItemInfoSubs.IndexOfObject(Source));
// move child to new parent
Source.MoveTo(Dest, naAdd);
// add child to new parent list
TItemInfo(Dest.Parent.Data).FSubItems.AddObject(Source.Text, Source);
end
// dropping from a parent to a parent
else if (Source.Data <> nil) and (Dest.Data <> nil) then
begin
if not Child then
Source.MoveTo(Dest, naInsert)
else begin
TItemInfo(Source.Data).Free;
Source.Data := nil;
// make Source a child of Dest
Source.MoveTo(Dest, naAddChild);
// add child to new parent list
TItemInfo(Dest.Data).FSubItems.AddObject(Source.Text, Source);
end;
end
// dropping from parent to child
else if (Source.Data <> nil) and (Dest.Data = nil) then
begin
// remove Source's parent node data
TItemInfo(Source.Data).Free;
Source.Data := nil;
// make Source a child of Dest
Source.MoveTo(Dest, naAdd);
// add child to new parent list
TItemInfo(Dest.Parent.Data).FSubItems.AddObject(Source.Text, Source);
end
// dropping from child to parent
else if (Source.Data = nil) and (Dest.Data <> nil) then
begin
// remove child from parent list
ItemInfoSubs := TItemInfo(Source.Parent.Data).FSubItems;
ItemInfoSubs.Delete(ItemInfoSubs.IndexOfObject(Source));
if Child then
begin
// move child to new parent
Source.MoveTo(Dest, naAddChild);
// add child to new parent list
TItemInfo(Dest.Data).FSubItems.AddObject(Source.Text, Source);
end
else begin
// move child to be sibling of Dest
Source.MoveTo(Dest, naInsert);
// create Parent node item info for Source
Source.Data := TItemInfo.Create(nil);
end;
end;
end;
begin
with TreeView do
begin
SelNode := Selected;
if (SelNode <> nil) then
begin
Child := GetKeyState(VK_SHIFT) < 0;
Node := TreeView.DropTarget; //GetNodeAt(X, Y);
if Node = nil then
begin
Node := Items[Items.Count - 1];
while (Node <> nil) and not Node.IsVisible do
Node := Node.GetPrev;
end;
if Node <> nil then
try
if Child and (Node.Parent <> nil) then Node := Node.Parent;
FDropping := True;
AddItem(SelNode, Node);
SelNode.Selected := True;
Apply.Enabled := True;
finally
FDropping := False;
end;
end;
end;
end;
procedure TListViewItems.TreeViewEdited(Sender: TObject; Node: TTreeNode;
var S: string);
begin
CaptionEdit.Text := S;
CaptionEditExit(nil);
New.Default := True;
end;
procedure TListViewItems.Button7Click(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TListViewItems.TreeViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
PostMessage(Handle, UM_TREEEDIT, Key, Longint(Self));
end;
procedure TListViewItems.UMTreeEdit(var M: TMessage);
var
ItemInfoSubs: TStrings;
TextBuf: array[0..255] of char;
EditNode: TTreeNode;
EditHand: HWnd;
begin
if TreeView.IsEditing then
begin
EditNode := TreeView.Selected;
EditHand := TreeView_GetEditControl(TreeView.Handle);
if (EditHand = 0) or (EditNode = nil) then Exit;
GetWindowText(EditHand, TextBuf, SizeOf(TextBuf));
if EditNode.Data = nil then
begin
ItemInfoSubs := TItemInfo(EditNode.Parent.Data).FSubItems;
ItemInfoSubs[ItemInfoSubs.IndexOfObject(EditNode)] := TextBuf;
end
else
TItemInfo(EditNode.Data).FCaption := TextBuf;
CaptionEdit.Text := TextBuf;
end;
end;
procedure TListViewItems.TreeViewEditing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
begin
New.Default := False;
end;
procedure TListViewItems.FormCreate(Sender: TObject);
begin
if SavedWidth <> 0 then
Width := SavedWidth;
if SavedHeight <> 0 then
Height := SavedHeight;
if SavedLeft <> 0 then
Left := SavedLeft
else
Left := (Screen.Width - Width) div 2;
if SavedTop <> 0 then
Top := SavedTop
else
Top := (Screen.Height - Height) div 2;
end;
procedure TListViewItems.FormDestroy(Sender: TObject);
begin
SavedWidth := Width;
SavedHeight := Height;
SavedLeft := Left;
SavedTop := Top;
end;
end.
|
unit AccountTitle;
interface
type
TCostTypes = (ctNone,ctOperating,ctCapital);
TAccountTitle = class
private
FName: string;
FCode: string;
FCostType: TCostTypes;
public
property Code: string read FCode write FCode;
property Name: string read FName write FName;
property CostType: TCostTypes read FCostType write FCostType;
end;
implementation
end.
|
unit uToolZip;
{$mode objfpc}{$H+}
interface
uses
Classes, uBuildFile, processutils, sysutils, FileUtil, LazFileUtils;
type
TBuildToolZip = class(TBuildTool)
function Execute(const aOrder: TStringList): Integer; override;
end;
implementation
uses
dynlibs;
type
TpfnCreateHardlinkW = function (lpFileName, lpExistingFileName: Pwidechar;
lpSecurityAttributes: Pointer): LongBool; stdcall;
var
pfnCreateHardLinkW: TpfnCreateHardlinkW = nil;
const
FileCopyFlags = [cffPreserveTime];
{ TCopyDirTree for CopyDirTree function }
type
TCopyDirTree = class(TFileSearcher)
private
FSourceDir: string;
FTargetDir: string;
FFlags: TCopyFileFlags;
FCopyFailedCount: integer;
FCopyAsHardlinks: boolean;
protected
procedure DoFileFound; override;
procedure DoDirectoryFound; override;
end;
procedure TCopyDirTree.DoFileFound;
var
NewLoc, NewF: string;
begin
// ToDo: make sure StringReplace works in all situations !
NewLoc := StringReplace(FileName, FSourceDir, FTargetDir, []);
NewF := StringReplace(FileName, FSourceDir, '', []);
WriteLn(' ',newf);
if FCopyAsHardlinks then begin
if pfnCreateHardLinkW(PWideChar(UnicodeString(NewLoc)), PWideChar(UnicodeString(FileName)), nil) then
exit
else
FCopyAsHardlinks:= false;
end;
if not CopyFile(FileName, NewLoc, FFlags) then
Inc(FCopyFailedCount);
end;
procedure TCopyDirTree.DoDirectoryFound;
var
NewPath: string;
begin
NewPath := StringReplace(FileName, FSourceDir, FTargetDir, []);
// ToDo: make directories also respect cffPreserveTime flag.
if not LazFileUtils.DirectoryExistsUTF8(NewPath) then
if not LazFileUtils.ForceDirectoriesUTF8(NewPath) then
Inc(FCopyFailedCount);
end;
function DeepCopy(const SourceFind, TargetDir: string; Flags: TCopyFileFlags = []): boolean;
var
Searcher: TCopyDirTree;
RelPath, SourceDir, SourceMask: string;
B: boolean;
begin
Result := False;
Searcher := TCopyDirTree.Create;
try
SourceDir:= ExtractFilePath(SourceFind);
SourceMask:= ExtractFileName(SourceFind);
// Destination directories are always created. User setting has no effect!
Flags := Flags + [cffCreateDestDirectory];
Searcher.FFlags := Flags;
Searcher.FCopyFailedCount := 0;
Searcher.FSourceDir := LazFileUtils.TrimFilename(SetDirSeparators(SourceDir));
Searcher.FTargetDir := LazFileUtils.TrimFilename(SetDirSeparators(TargetDir));
Searcher.FCopyAsHardlinks:= Assigned(pfnCreateHardLinkW);
// Don't even try to copy to a subdirectory of SourceDir.
B := TryCreateRelativePath(LazFileUtils.ExpandFilenameUtf8(Searcher.FSourceDir),
LazFileUtils.ExpandFilenameUtf8(Searcher.FTargetDir), False, True, RelPath);
if B and ((Copy(RelPath, 1, 2) = '..') or (RelPath = '')) then
Exit;
Searcher.Search(SourceDir, SourceMask);
Result := Searcher.FCopyFailedCount = 0;
finally
Searcher.Free;
end;
end;
{ TBuildToolZip }
function TBuildToolZip.Execute(const aOrder: TStringList): Integer;
function JoinExcludes(delim: string): string;
var
i: integer;
begin
Result:= '';
for i:= 0 to aOrder.Count-1 do
if AnsiSameText('EXCLUDE', aOrder.Names[i]) then begin
if Result > '' then Result += ' ';
Result+= delim+aOrder.ValueFromIndex[i];
end;
end;
var
ofn, fls, td, tn, sn, tdn, zip: string;
files: TStringList;
i: integer;
level: integer;
begin
Result := 0;
ofn := ExpandFileName(aOrder.Values['FILENAME']);
if ofn = '' then begin
WriteLn(ErrOutput, 'Task ', Owner.CurrentTask, ': FileName specifier missing.');
Exit(ERROR_TASK_PARAMETER);
end;
fls := aOrder.Values['FILES'];
if fls = '' then begin
WriteLn(ErrOutput, 'Task ', Owner.CurrentTask, ': Files specifier missing.');
Exit(ERROR_TASK_PARAMETER);
end;
level:= StrToIntDef(aOrder.Values['LEVEL'], 5);
if not (level in [0..9]) then begin
WriteLn(ErrOutput, 'Task ', Owner.CurrentTask, ': Invalid compression level ',level,': not in 0..9.');
Exit(ERROR_TASK_PARAMETER);
end;
files:= Owner.GetSection(fls);
try
Owner.ProcessVariables(files);
td := Owner.GetTempName;
ForceDirectories(td);
try
for i := 0 to files.Count - 1 do begin
sn := files.Names[i];
sn := ExpandFileName(sn);
if Pos('*', ExtractFileName(sn)) > 0 then begin
// copy with mask, target is always a directory
tn := ConcatPaths([files.ValueFromIndex[i], '']);
tdn := ConcatPaths([td, tn]);
WriteLn(sn, ' -> ', tn);
if not DeepCopy(sn, tdn, FileCopyFlags) then begin
WriteLn(ErrOutput, 'Task ', Owner.CurrentTask, ': Copy failed in ', sn, '.');
Exit(ERROR_TASK_PROCESS);
end;
end
else
begin
// copy single file, check if we keep the name or change it
if ExtractFileName(files.ValueFromIndex[i]) = '' then
tn := ConcatPaths([files.ValueFromIndex[i], ExtractFileName(sn)])
else
tn := files.ValueFromIndex[i];
tdn := ConcatPaths([td, tn]);
WriteLn(sn, ' -> ', tn);
if not CopyFile(sn, tdn, [cffCreateDestDirectory] + FileCopyFlags) then begin
WriteLn(ErrOutput, 'Task ', Owner.CurrentTask, ': Cannot copy file ', sn, '.');
Exit(ERROR_TASK_PROCESS);
end;
end;
end;
if FileExists(ofn) then
DeleteFile(ofn);
if Owner.TryGetGlobal('PROGRAM_7ZIP',zip) then
Result := ExecuteCommandInDir(format('"%s" a "%s" %s * -r -mx=%d', [zip, ofn, JoinExcludes('-xr!'), level]), td, True)
else
Result := ExecuteCommandInDir(format('"%s" -o -%d -r -S "%s" %s *', [Owner.GetGlobal('PROGRAM_ZIP'), level, ofn, JoinExcludes('-x ')]), td, True);
finally
DeleteDirectory(td, False);
end;
finally
FreeAndNil(files);
end;
end;
initialization
{$IFDEF MSWINDOWS}
Pointer(pfnCreateHardLinkW):= GetProcAddress(SafeLoadLibrary(KernelDLL), 'CreateHardLinkW');
{$ENDIF}
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Menus;
{$I FMX.Defines.inc}
interface
uses
System.Classes, System.Types, System.UITypes,
FMX.Types, FMX.Forms, FMX.Controls;
type
{ Menus }
TMenuItem = class;
IMenuView = interface(IControl)
['{C211C5EA-789A-48C3-9739-900782101C51}']
function GetLoop: Boolean;
procedure SetLoop(const Value: Boolean);
function GetParentView: IMenuView;
procedure SetParentView(const Value: IMenuView);
function GetChildView: IMenuView;
procedure SetChildView(const Value: IMenuView);
function GetSelected: TMenuItem;
procedure SetSelected(const Value: TMenuItem);
function GetIsMenuBar: Boolean;
{ access }
property IsMenuBar: Boolean read GetIsMenuBar;
property Loop: Boolean read GetLoop write SetLoop;
property ParentView: IMenuView read GetParentView write SetParentView;
property ChildView: IMenuView read GetChildView write SetChildView;
property Selected: TMenuItem read GetSelected write SetSelected;
end;
{ TMenuItem }
TMenuItem = class(TTextControl, IItemsContainer)
private
FContent: TContent;
FIsSelected: Boolean;
FPopupTimer: TTimer;
FShortCut: TShortCut;
FShortCutObject: TFmxObject;
FSubmarkObject: TFmxObject;
FCheckmarkObject: TFmxObject;
FGlyphObject: TFmxObject;
FBitmapObject: TFmxObject;
FHandle: TFmxHandle;
FIsChecked: Boolean;
FBitmap: TBitmap;
FAutoCheck: Boolean;
FRadioItem: Boolean;
FGroupIndex: Byte;
procedure SetIsSelected(const Value: Boolean);
function GetMenuView: IMenuView;
procedure DoPopupTimer(Sender: TObject);
procedure SetShortCut(const Value: TShortCut);
procedure SetIsChecked(const Value: Boolean);
procedure SetBitmap(const Value: TBitmap);
procedure TurnSiblingsOff;
procedure SetGroupIndex(const Value: Byte);
procedure SetRadioItem(const Value: Boolean);
protected
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure DialogKey(var Key: Word; Shift: TShiftState); override;
procedure Click; override;
procedure SetText(const Value: string); override;
function EnterChildren(AObject: TControl): Boolean; override;
{ IItemContainer }
function GetItemsCount: Integer;
function GetItem(const AIndex: Integer): TFmxObject;
procedure SetVisible(const AValue: Boolean); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddObject(AObject: TFmxObject); override;
{ menu }
function CalcSize: TPointF;
{ TStyledControl }
procedure ApplyStyle; override;
procedure FreeStyle; override;
{ Menus }
procedure Popup;
procedure NeedPopup;
function HavePopup: Boolean;
property View: IMenuView read GetMenuView;
{ OS Menu }
property Handle: TFmxHandle read FHandle write FHandle;
property Font;
published
property Align stored False;
property AutoCheck: Boolean read FAutoCheck write FAutoCheck default False;
property Bitmap: TBitmap read FBitmap write SetBitmap;
property IsChecked: Boolean read FIsChecked write SetIsChecked default False;
property IsSelected: Boolean read FIsSelected write SetIsSelected stored False;
property GroupIndex: Byte read FGroupIndex write SetGroupIndex default 0;
// property Font; RAID 282684
property StyleLookup;
property RadioItem: Boolean read FRadioItem write SetRadioItem default False;
property ShortCut: TShortCut read FShortCut write SetShortCut;
property TextAlign default TTextAlign.taLeading;
property Text;
property WordWrap default False;
end;
{ TPopupMenu }
TPopupMenu = class(TCustomPopupMenu, IItemsContainer)
private
FPopupPoint: TPoint;
{ IItemContainer }
function GetItemsCount: Integer;
function GetItem(const AIndex: Integer): TFmxObject;
function GetObject: TFmxObject;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CloseMenu; inline;
procedure Popup(X, Y: Single); override;
property PopupPoint: TPoint read FPopupPoint;
procedure DialogKey(var Key: Word; Shift: TShiftState);
end;
{ TMenuBar }
TMenuBar = class(TStyledControl, IMenuView, IItemsContainer)
private
{ IMenuView }
FLoop: Boolean;
FParentView: IMenuView;
FChildView: IMenuView;
FSelected: TMenuItem;
FUseOSMenu: Boolean;
function GetLoop: Boolean;
procedure SetLoop(const Value: Boolean);
function GetParentView: IMenuView;
procedure SetParentView(const Value: IMenuView);
function GetChildView: IMenuView;
procedure SetChildView(const Value: IMenuView);
function GetSelected: TMenuItem;
procedure SetSelected(const Value: TMenuItem);
function GetIsMenuBar: Boolean;
procedure SetUseOSMenu(const Value: Boolean);
protected
FContent: TControl;
procedure Realign; override;
procedure DialogKey(var Key: Word; Shift: TShiftState); override;
{ TComponent }
procedure Loaded; override;
{ TStyledControl }
procedure ApplyStyle; override;
procedure FreeStyle; override;
{ IItemContainer }
function GetItemsCount: Integer;
function GetItem(const AIndex: Integer): TFmxObject;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddObject(AObject: TFmxObject); override;
procedure StartMenuLoop;
published
property UseOSMenu: Boolean read FUseOSMenu write SetUseOSMenu default False;
end;
{ TMainMenu }
TMainMenu = class(TFmxObject, IItemsContainer)
private
{ IItemContainer }
function GetItemsCount: Integer;
function GetItem(const AIndex: Integer): TFmxObject;
function GetObject: TFmxObject;
protected
{ TComponent }
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddObject(AObject: TFmxObject); override;
//added to enable the shortcut functionality of main menu items
procedure DialogKey(var Key: Word; Shift: TShiftState);
end;
{ TPopupBox }
TPopupBox = class(TCustomButton)
private
FItems: TStrings;
FItemIndex: Integer;
FPopup: TPopupMenu;
FOnChange: TNotifyEvent;
procedure SetItems(const Value: TStrings);
procedure SetItemIndex(const Value: Integer);
protected
procedure ApplyStyle; override;
procedure Click; override;
procedure DoItemsChanged(Sender: TObject); virtual;
procedure DoItemClick(Sender: TObject);
procedure DoPopup; virtual;
function GetData: Variant; override;
procedure SetData(const Value: Variant); override;
procedure SetText(const Value: string); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property BindingSource;
property CanFocus default True;
property DisableFocusEffect;
property TabOrder;
property Text stored False;
property Items: TStrings read FItems write SetItems;
property ItemIndex: Integer read FItemIndex write SetItemIndex;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
function TextToShortcut(Text: string): integer;
implementation
uses System.SysUtils, System.Variants, FMX.Platform, FMX.Objects;
type
{ TMenuView }
TMenuView = class(TStyledControl, IMenuView)
private
{ IMenuView }
FLoop: Boolean;
FParentView, FChildView: IMenuView;
FSelected: TMenuItem;
function GetLoop: Boolean;
procedure SetLoop(const Value: Boolean);
function GetParentView: IMenuView;
procedure SetParentView(const Value: IMenuView);
function GetChildView: IMenuView;
procedure SetChildView(const Value: IMenuView);
function GetSelected: TMenuItem;
procedure SetSelected(const Value: TMenuItem);
function GetIsMenuBar: Boolean;
protected
FContent: TControl;
procedure Realign; override;
{ TStyledControl }
procedure ApplyStyle; override;
procedure FreeStyle; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
end;
{ TMenuItem }
constructor TMenuItem.Create(AOwner: TComponent);
begin
inherited;
TextAlign := TTextAlign.taLeading;
WordWrap := False;
FBitmap := TBitmap.Create(0, 0);
FContent := TContent.Create(Self);
FContent.Parent := Self;
FContent.Stored := False;
FContent.Locked := True;
FContent.HitTest := False;
FContent.Visible := False;
end;
destructor TMenuItem.Destroy;
begin
FBitmap.Free;
FContent := nil;
inherited;
end;
procedure TMenuItem.DialogKey(var Key: Word; Shift: TShiftState);
var
k: word;
SState: TShiftState;
P: TFMXObject;
begin
//getting key from item's defined shortcut
Platform.ShortCutToKey(ShortCut, k, SState);
//checking if the key from Shortcut is the same with the typed one and has the same Shift state
if (Key = k) and (Shift = SState) then
begin
if Assigned(OnClick) then
begin
OnClick(Self);
{$IFDEF MACOS}
//avoid insertion of the leter from shortcut on a editable component with focus on it
Key:=0;
{$ENDIF}
end;
end
else
inherited DialogKey(Key, Shift);
end;
function TMenuItem.EnterChildren(AObject: TControl): Boolean;
begin
Result := inherited EnterChildren(AObject);
IsSelected := True;
Result := True;
end;
function TMenuItem.GetMenuView: IMenuView;
var
View: IMenuView;
begin
Result := nil;
if (Parent <> nil) and (IInterface(Parent).QueryInterface(IMenuView, View) = S_OK) then
Result := View;
end;
function TMenuItem.HavePopup: Boolean;
begin
Result := GetItemsCount > 0;
end;
procedure TMenuItem.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
if Button = TMouseButton.mbLeft then
begin
NeedPopup;
end;
end;
procedure TMenuItem.DoPopupTimer(Sender: TObject);
begin
FPopupTimer.Enabled := False;
Popup;
end;
procedure TMenuItem.NeedPopup;
begin
if not HavePopup then Exit;
if FPopupTimer = nil then
FPopupTimer := TTimer.Create(nil);
FPopupTimer.Parent := Self;
FPopupTimer.Interval := 1;
FPopupTimer.OnTimer := DoPopupTimer;
FPopupTimer.Enabled := True;
end;
procedure TMenuItem.SetBitmap(const Value: TBitmap);
begin
FBitmap.Assign(Value);
end;
procedure TMenuItem.SetGroupIndex(const Value: Byte);
begin
if FGroupIndex <> Value then
begin
FGroupIndex := Value;
if FIsChecked and FRadioItem then
TurnSiblingsOff;
end;
end;
procedure TMenuItem.TurnSiblingsOff;
var
I: Integer;
Item: TMenuItem;
begin
if FParent <> nil then
for I := 0 to FParent.ChildrenCount - 1 do
begin
if FParent.Children[I] is TMenuItem then
begin
Item := TMenuItem(FParent.Children[I]);
if (Item <> Self) and Item.FRadioItem and (Item.GroupIndex = GroupIndex) then
Item.SetIsChecked(False);
end;
end;
end;
procedure TMenuItem.SetIsChecked(const Value: Boolean);
begin
if FIsChecked <> Value then
begin
FIsChecked := Value;
if Value and FRadioItem then
TurnSiblingsOff;
if IsHandleValid(Handle) then
Platform.UpdateMenuItem(Self)
else
begin
StartTriggerAnimation(Self, 'IsChecked');
ApplyTriggerEffect(Self, 'IsChecked');
end;
end;
end;
procedure TMenuItem.SetIsSelected(const Value: Boolean);
begin
if FIsSelected <> Value then
begin
FIsSelected := Value;
StartTriggerAnimation(Self, 'IsSelected');
ApplyTriggerEffect(Self, 'IsSelected');
if View <> nil then
begin
View.Selected := Self;
end;
end;
end;
procedure TMenuItem.SetRadioItem(const Value: Boolean);
begin
if FRadioItem <> Value then
begin
FRadioItem := Value;
if FIsChecked and FRadioItem then
TurnSiblingsOff;
end;
end;
procedure TMenuItem.SetShortCut(const Value: TShortCut);
begin
if FShortCut <> Value then
begin
FShortCut := Value;
if IsHandleValid(Handle) then
Platform.UpdateMenuItem(Self)
end;
end;
procedure TMenuItem.SetText(const Value: string);
begin
if FText <> Value then
begin
inherited;
if IsHandleValid(Handle) then
Platform.UpdateMenuItem(Self)
else
begin
if (Parent is TMenuBar) then
TMenuBar(Parent).Realign;
end;
end;
end;
procedure TMenuItem.SetVisible(const AValue: Boolean);
begin
inherited;
if Parent is TMenuBar then
TMenuBar(Parent).Realign;
if IsHandleValid(Handle) then
Platform.UpdateMenuItem(Self);
end;
procedure TMenuItem.AddObject(AObject: TFmxObject);
begin
if (FContent <> nil) and (AObject is TMenuItem) then
begin
TMenuItem(AObject).Locked := True;
FContent.AddObject(AObject);
if IsHandleValid(Handle) then
Platform.UpdateMenuItem(Self)
end
else
inherited;
end;
procedure TMenuItem.ApplyStyle;
var
O: TFmxObject;
begin
inherited;
O := FindStyleResource('glyph');
if (O <> nil) and (O is TControl) then
begin
FGlyphObject := O;
TControl(FGlyphObject).Visible := not (FBitmap.IsEmpty) or ((View <> nil) and not View.GetIsMenuBar);
end;
O := FindStyleResource('checkmark');
if (O <> nil) and (O is TControl) then
begin
FCheckmarkObject := O;
if (View <> nil) and not View.GetIsMenuBar and IsChecked then
begin
ApplyTriggerEffect(Self, 'IsChecked');
StartTriggerAnimation(Self, 'IsChecked');
end;
TControl(FCheckmarkObject).Visible := True;
end;
O := FindStyleResource('bitmap');
if (O <> nil) and (O is TControl) then
begin
FBitmapObject := O;
if FBitmapObject is TImage then
TImage(FBitmapObject).Bitmap.Assign(FBitmap);
TControl(FBitmapObject).Visible := not (FBitmap.IsEmpty);
end;
O := FindStyleResource('shortcut');
if (O <> nil) then
begin
FShortCutObject := O;
if (FShortCutObject <> nil) and (FShortCutObject is TText) then
begin
TText(FShortCutObject).Text := Platform.ShortCutToText(FShortcut);
TText(FShortCutObject).WordWrap := False;
TText(FShortCutObject).Visible := (((View <> nil) and not View.GetIsMenuBar));
end;
end;
O := FindStyleResource('submark');
if (O <> nil) and (O is TControl) then
begin
FSubmarkObject := O;
TControl(FSubmarkObject).Visible := (View <> nil) and not View.GetIsMenuBar and (GetItemsCount > 0);
end;
end;
procedure TMenuItem.FreeStyle;
begin
inherited;
FCheckmarkObject := nil;
FShortCutObject := nil;
FGlyphObject := nil;
FSubmarkObject := nil;
end;
function TMenuItem.CalcSize: TPointF;
var
C: TCanvas;
begin
if Text = '-' then
begin
StyleLookup := 'menuseparatorstyle';
Result := PointF(0, 8);
Exit;
end;
if Canvas = nil then
begin
C := GetMeasureBitmap.Canvas;
end
else
C := Canvas;
ApplyStyleLookup;
Result := PointF(0, 23);
if (FGlyphObject <> nil) and (FGlyphObject is TControl) and (TControl(FGlyphObject).Visible) then
begin
Result.X := Result.X + TControl(FGlyphObject).Width + TControl(FGlyphObject).Padding.Left + TControl(FGlyphObject).Padding.Right;
end;
if (FTextObject <> nil) and (FTextObject is TText) then
begin
C.Font.Assign(TText(FTextObject).Font);
TText(FTextObject).Width := C.TextWidth(Text);
Result.X := Result.X + TText(FTextObject).Width + TControl(FTextObject).Padding.Left + TControl(FTextObject).Padding.Right;
end;
if (FShortCutObject <> nil) and (FShortCutObject is TText) and (TControl(FShortCutObject).Visible) then
begin
C.Font.Assign(TText(FShortCutObject).Font);
TText(FShortCutObject).Width := C.TextWidth(Platform.ShortCutToText(FShortcut));
Result.X := Result.X + TText(FShortCutObject).Width + TControl(FShortCutObject).Padding.Left + TControl(FShortCutObject).Padding.Right;
end;
if (FSubmarkObject <> nil) and (FSubmarkObject is TControl) and (TControl(FSubmarkObject).Visible) then
begin
Result.X := Result.X + TControl(FSubmarkObject).Width + TControl(FSubmarkObject).Padding.Left + TControl(FSubmarkObject).Padding.Right;
end;
end;
procedure TMenuItem.Click;
begin
DoMouseLeave;
if AutoCheck then
IsChecked := not IsChecked;
inherited;
end;
procedure TMenuItem.Popup;
var
Popup: TPopup;
Menu: TMenuView;
Item: TMenuItem;
i: Integer;
begin
if FContent = nil then Exit;
if FContent.ChildrenCount = 0 then Exit;
IsSelected := True;
Popup := TPopup.Create(nil);
Menu := TMenuView.Create(nil);
try
if View <> nil then
begin
View.ChildView := Menu;
Menu.FParentView := View;
end;
// set style
if (Scene <> nil) and (Scene.StyleBook <> nil) then
Popup.StyleBook := Scene.StyleBook;
// create popup
Popup.PlacementTarget := Self;
if Parent is TMenuBar then
Popup.Placement := TPlacement.plBottom
else
Popup.Placement := TPlacement.plRight;
// create menu
Menu.Parent := Popup;
// copy items to menu
Menu.BeginUpdate;
for i := FContent.ChildrenCount - 1 downto 0 do
if (FContent.Children[i] is TMenuItem) and TMenuItem(FContent.Children[i]).Visible then
begin
Item := TMenuItem(FContent.Children[i]);
Item.Parent := Menu;
Item.Index := 0;
end;
Menu.EndUpdate;
// calc size
Popup.BoundsRect := RectF(0, 0, Menu.Width, Menu.Height);
// show
Popup.Popup;
// style
if Menu.Scene <> nil then
Menu.Scene.UpdateStyle;
// correct size
if (Popup.Parent <> nil) and (Popup.Parent is TCommonCustomForm) then
begin
Menu.Realign;
TCommonCustomForm(Popup.Parent).ClientWidth := round(Menu.Width);
TCommonCustomForm(Popup.Parent).ClientHeight := round(Menu.Height);
end;
// start loop
Platform.StartMenuLoop(Menu);
// copy back
FContent.BeginUpdate;
for i := Menu.ChildrenCount - 1 downto 0 do
if (Menu.Children[i] is TMenuItem) and TMenuItem(Menu.Children[i]).Visible then
begin
Item := TMenuItem(Menu.Children[i]);
Item.Parent := FContent;
Item.Index := 0;
end;
FContent.EndUpdate;
finally
// hide popup
Popup.ClosePopup;
// hide
if View <> nil then
begin
View.Selected := nil;
View.ChildView := nil;
Menu.FParentView := nil;
end;
Menu.Visible := False;
Menu.Free;
IsSelected := False;
Popup.Free;
end;
end;
{ IItemContainer }
function TMenuItem.GetItem(const AIndex: Integer): TFmxObject;
var
i, C: Integer;
begin
Result := nil;
C := 0;
for i := 0 to FContent.ChildrenCount - 1 do
if FContent.Children[i] is TMenuItem then
begin
if C = AIndex then
begin
Result := FContent.Children[i];
Break;
end;
C := C + 1;
end;
end;
function TMenuItem.GetItemsCount: Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to FContent.ChildrenCount - 1 do
if (FContent.Children[i] is TMenuItem){ and TMenuItem(FContent.Children[I]).Visible} then
Result := Result + 1;
end;
{ TMenuView }
constructor TMenuView.Create(AOwner: TComponent);
begin
inherited;
Width := 200;
Height := 200;
end;
destructor TMenuView.Destroy;
begin
inherited;
end;
procedure TMenuView.ApplyStyle;
var
O: TFmxObject;
begin
inherited;
O := FindStyleResource('content');
if (O <> nil) and (O is TControl) then
begin
FContent := TControl(O);
end;
end;
procedure TMenuView.FreeStyle;
begin
inherited;
FContent := nil;
end;
function TMenuView.GetChildView: IMenuView;
begin
Result := FChildView;
end;
function TMenuView.GetIsMenuBar: Boolean;
begin
Result := False;
end;
function TMenuView.GetLoop: Boolean;
begin
Result := FLoop;
end;
function TMenuView.GetParentView: IMenuView;
begin
Result := FParentView;
end;
function TMenuView.GetSelected: TMenuItem;
begin
Result := FSelected;
end;
procedure TMenuView.Realign;
var
MarginR, ContentR, R: TRectF;
P: TPointF;
i: Integer;
Size: TPointF;
S: TPointF;
begin
inherited ;
if FUpdating > 0 then
Exit;
if csLoading in ComponentState then
Exit;
if FDisableAlign then
Exit;
FDisableAlign := True;
try
ApplyStyleLookup;
if (FContent <> nil) and (FResourceLink <> nil) then
begin
TControl(FResourceLink).BoundsRect := RectF(0, 0, Width, Height);
ContentR.TopLeft := AbsoluteToLocal(FContent.LocalToAbsolute(PointF(0, 0)));
with AbsoluteToLocal(FContent.LocalToAbsolute(PointF(FContent.Width, FContent.Height))) do
ContentR.BottomRight := PointF(Self.Width - X, Self.Height - Y);
end
else
ContentR := RectF(0, 0, 0, 0);
if FResourceLink <> nil then
with TControl(FResourceLink) do
MarginR := RectF(Margins.Left, Margins.Top, Margins.Bottom, Margins.Right)
else
MarginR := RectF(0, 0, 0, 0);
{ calc items size }
Size := PointF(0, 0);
if ChildrenCount > 0 then
for i := 0 to ChildrenCount - 1 do
begin
if Children[i] is TMenuItem then
with TMenuItem(Children[i]) do
begin
P := CalcSize;
Size.Y := Size.Y + P.Y + Padding.Top + Padding.Bottom;
if P.X + Padding.Left + Padding.Right > Size.X then
Size.X := P.X + Padding.Left + Padding.Right;
end;
end;
SetBounds(Position.X, Position.Y, Size.X + ContentR.Left + ContentR.Right,
Size.Y + ContentR.Top + ContentR.Bottom);
if FResourceLink <> nil then
with TControl(FResourceLink) do
SetBounds(MarginR.Left, MarginR.Top, Self.Width - MarginR.Left - MarginR.Right,
Self.Height - MarginR.Top - MarginR.Bottom);
{ align }
Size := PointF(0, 0);
if ChildrenCount > 0 then
for i := 0 to (ChildrenCount - 1) do
begin
if Children[i] is TMenuItem then
with TMenuItem(Children[i]) do
begin
P := CalcSize;
SetBounds(ContentR.Left + Padding.Left, ContentR.Top + Size.Y, Self.Width - Padding.Left - Padding.Right - ContentR.Left - ContentR.Right, P.Y - Padding.Top - Padding.Bottom);
Size.Y := Size.Y + Height + Padding.Top + Padding.Bottom;
end;
end;
finally
FDisableAlign := False;
end;
end;
procedure TMenuView.SetChildView(const Value: IMenuView);
begin
FChildView := Value;
end;
procedure TMenuView.SetLoop(const Value: Boolean);
begin
FLoop := Value;
Repaint;
end;
procedure TMenuView.SetParentView(const Value: IMenuView);
begin
FParentView := Value;
end;
procedure TMenuView.SetSelected(const Value: TMenuItem);
begin
if FSelected <> Value then
begin
if FSelected <> nil then
FSelected.IsSelected := False;
FSelected := Value;
if FSelected <> nil then
FSelected.IsSelected := True;
end;
end;
{ TPopupMenu }
constructor TPopupMenu.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TPopupMenu.Destroy;
begin
inherited;
end;
procedure TPopupMenu.DialogKey(var Key: Word; Shift: TShiftState);
var
I: integer;
MItem: TMenuItem;
begin
for I := GetItemsCount - 1 downto 0 do
begin
MItem:= TMenuItem(GetItem(I));
MItem.DialogKey(Key, Shift);
end;
end;
{ IItemContainer }
function TPopupMenu.GetItem(const AIndex: Integer): TFmxObject;
var
i, C: Integer;
begin
Result := nil;
C := 0;
for i := 0 to ChildrenCount - 1 do
if Children[i] is TMenuItem then
begin
if C = AIndex then
begin
Result := Children[i];
Break;
end;
C := C + 1;
end;
end;
function TPopupMenu.GetItemsCount: Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to ChildrenCount - 1 do
if Children[i] is TMenuItem then
Result := Result + 1;
end;
function TPopupMenu.GetObject: TFmxObject;
begin
Result := Self;
end;
procedure TPopupMenu.CloseMenu;
begin
end;
procedure TPopupMenu.Popup(X, Y: Single);
var
Popup: TPopup;
Menu: TMenuView;
Item: TMenuItem;
i: Integer;
begin
Popup := TPopup.Create(nil);
Menu := TMenuView.Create(nil);
try
// create popup
Popup.Parent := Parent;
if Parent is TMenuBar then
Popup.Placement := TPlacement.plBottom
else
Popup.Placement := TPlacement.plRight;
// create menu
Menu.Parent := Popup;
// copy items to menu
Menu.BeginUpdate;
for i := ChildrenCount - 1 downto 0 do
if Children[i] is TMenuItem then
if TMenuItem(Children[i]).Visible then
begin
Item := TMenuItem(Children[i]);
Item.Parent := Menu;
Item.Index := 0;
end;
Menu.EndUpdate;
// calc size
Popup.BoundsRect := RectF(0, 0, Menu.Width * Popup.AbsoluteMatrix.m11, Menu.Height * Popup.AbsoluteMatrix.m11);
Popup.PlacementRectangle.Left := X;
Popup.PlacementRectangle.Top := Y;
Popup.Placement := TPlacement.plAbsolute;
// Popup.PlacementTarget := Self;
// show
Popup.Popup;
// correct size
if (Popup.Parent <> nil) and (Popup.Parent is TCommonCustomForm) then
begin
Menu.Realign;
TCommonCustomForm(Popup.Parent).ClientWidth := round(Menu.Width * Popup.AbsoluteMatrix.m11);
TCommonCustomForm(Popup.Parent).ClientHeight := round(Menu.Height * Popup.AbsoluteMatrix.m11);
end;
// start loop
Platform.StartMenuLoop(Menu);
// copy back
for i := Menu.ChildrenCount - 1 downto 0 do
if Menu.Children[i] is TMenuItem then
begin
Item := TMenuItem(Menu.Children[i]);
Item.Parent := Self;
Item.Index := 0;
end;
finally
// hide popup
Popup.ClosePopup;
Menu.Visible := False;
Menu.Free;
Popup.Free;
end;
end;
{ TMenuBar }
constructor TMenuBar.Create(AOwner: TComponent);
begin
inherited;
FStyleLookup := 'menubarstyle';
Width := 500;
Height := 40;
SetAcceptsControls(False);
end;
destructor TMenuBar.Destroy;
begin
inherited;
end;
procedure TMenuBar.DialogKey(var Key: Word; Shift: TShiftState);
begin
inherited DialogKey(Key, Shift);
end;
procedure TMenuBar.AddObject(AObject: TFmxObject);
begin
inherited;
if AObject is TMenuItem then
begin
if FUseOSMenu and not (csDesigning in ComponentState) then
begin
if (Root <> nil) and (Root.GetObject is TCommonCustomForm) then
Platform.CreateOSMenu(TCommonCustomForm(Root.GetObject), Self);
end
else
Realign;
end;
end;
procedure TMenuBar.ApplyStyle;
var
O: TFmxObject;
begin
inherited;
O := FindStyleResource('content');
if (O <> nil) and (O is TControl) then
begin
FContent := TControl(O);
end;
end;
procedure TMenuBar.FreeStyle;
begin
inherited;
FContent := nil;
end;
function TMenuBar.GetChildView: IMenuView;
begin
Result := FChildView;
end;
function TMenuBar.GetIsMenuBar: Boolean;
begin
Result := True;
end;
function TMenuBar.GetItem(const AIndex: Integer): TFmxObject;
var
i, C: Integer;
begin
Result := nil;
C := 0;
for i := 0 to ChildrenCount - 1 do
if Children[i] is TMenuItem then
begin
if C = AIndex then
begin
Result := Children[i];
Break;
end;
C := C + 1;
end;
end;
function TMenuBar.GetItemsCount: Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to ChildrenCount - 1 do
if Children[i] is TMenuItem then
Result := Result + 1;
end;
function TMenuBar.GetLoop: Boolean;
begin
Result := FLoop;
end;
procedure TMenuBar.SetChildView(const Value: IMenuView);
begin
FChildView := Value;
end;
procedure TMenuBar.SetLoop(const Value: Boolean);
begin
FLoop := Value;
Repaint;
end;
procedure TMenuBar.SetParentView(const Value: IMenuView);
begin
FParentView := Value;
end;
procedure TMenuBar.SetSelected(const Value: TMenuItem);
begin
if FSelected <> Value then
begin
if FSelected <> nil then
FSelected.IsSelected := False;
FSelected := Value;
if FSelected <> nil then
FSelected.IsSelected := True;
end;
end;
procedure TMenuBar.SetUseOSMenu(const Value: Boolean);
begin
if FUseOSMenu <> Value then
begin
FUseOSMenu := Value;
if not (csLoading in ComponentState) and not (csDesigning in ComponentState) then
begin
if FUseOSMenu then
begin
Visible := False;
if Root.GetObject is TCommonCustomForm then
Platform.CreateOSMenu(TCommonCustomForm(Root.GetObject), Self);
end
else
begin
Visible := True;
if Root.GetObject is TCommonCustomForm then
Platform.CreateOSMenu(TCommonCustomForm(Root.GetObject), nil);
end;
end;
end;
end;
procedure TMenuBar.StartMenuLoop;
begin
if not UseOSMenu then
Platform.StartMenuLoop(Self);
end;
function TMenuBar.GetParentView: IMenuView;
begin
Result := FParentView;
end;
function TMenuBar.GetSelected: TMenuItem;
begin
Result := FSelected;
end;
procedure TMenuBar.Loaded;
begin
inherited;
if FUseOSMenu and not (csDesigning in ComponentState) then
begin
Visible := False;
if (Root <> nil) and (Root.GetObject is TCommonCustomForm) then
Platform.CreateOSMenu(TCommonCustomForm(Root.GetObject), Self);
end;
end;
procedure TMenuBar.Realign;
var
R, ContentR: TRectF;
P: TPointF;
i: Integer;
CurX: Single;
begin
inherited ;
if FUpdating > 0 then
Exit;
if csLoading in ComponentState then
Exit;
if FDisableAlign then
Exit;
FDisableAlign := True;
try
ApplyStyleLookup;
if (FContent <> nil) and (FResourceLink <> nil) then
begin
TControl(FResourceLink).BoundsRect := RectF(0, 0, Width, Height);
ContentR.TopLeft := AbsoluteToLocal(FContent.LocalToAbsolute(PointF(0, 0)));
with AbsoluteToLocal(FContent.LocalToAbsolute(PointF(FContent.Width, FContent.Height))) do
ContentR.BottomRight := PointF(Self.Width - X, Self.Height - Y);
end
else
ContentR := RectF(0, 0, 0, 0);
CurX := 0;
if ChildrenCount > 0 then
for i := 0 to (ChildrenCount - 1) do
begin
if (Children[i] is TMenuItem) and (TMenuItem(Children[i]).Visible) then
with TMenuItem(Children[i]) do
begin
P := CalcSize;
SetBounds(ContentR.Left + CurX, ContentR.Top + Padding.Top, P.X - Padding.Left - Padding.Right,
Self.Height - Padding.Top - Padding.Bottom - ContentR.Top - ContentR.Bottom);
CurX := CurX + Width + Padding.Left + Padding.Right;
end;
end;
finally
FDisableAlign := False;
end;
end;
{ TMainMenu }
constructor TMainMenu.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TMainMenu.Destroy;
begin
inherited;
end;
procedure TMainMenu.DialogKey(var Key: Word; Shift: TShiftState);
var
I: integer;
MItem: TMenuItem;
begin
for I := GetItemsCount - 1 downto 0 do
begin
MItem:= TMenuItem(GetItem(I));
MItem.DialogKey(Key, Shift);
end;
end;
procedure TMainMenu.Loaded;
begin
inherited;
if not (csDesigning in ComponentState) then
begin
if Assigned(Root) and (Root.GetObject is TCommonCustomForm) then
Platform.CreateOSMenu(TCommonCustomForm(Root.GetObject), Self);
end;
end;
procedure TMainMenu.AddObject(AObject: TFmxObject);
begin
inherited;
if (AObject is TMenuItem) and not (csDesigning in ComponentState) then
begin
if Assigned(Root) and (Root.GetObject is TCommonCustomForm) then
Platform.CreateOSMenu(TCommonCustomForm(Root.GetObject), Self);
end;
end;
{ IItemContainer }
function TMainMenu.GetItem(const AIndex: Integer): TFmxObject;
var
i, C: Integer;
begin
Result := nil;
C := 0;
for i := 0 to ChildrenCount - 1 do
if Children[i] is TMenuItem then
begin
if C = AIndex then
begin
Result := Children[i];
Break;
end;
C := C + 1;
end;
end;
function TMainMenu.GetItemsCount: Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to ChildrenCount - 1 do
if Children[i] is TMenuItem then
Result := Result + 1;
end;
function TMainMenu.GetObject: TFmxObject;
begin
Result := Self;
end;
{ TPopupBox }
constructor TPopupBox.Create(AOwner: TComponent);
begin
inherited;
CanFocus := True;
Height := 21;
FItems := TStringList.Create;;
TStringList(FItems).OnChange := DoItemsChanged;
FPopup := TPopupMenu.Create(nil);
FPopup.Stored := False;
FPopup.Parent := Self;
FItemIndex := -1;
FText := '';
end;
destructor TPopupBox.Destroy;
begin
FreeAndNil(FPopup);
FreeAndNil(FItems);
inherited;
end;
function TPopupBox.GetData: Variant;
begin
Result := Text;
end;
procedure TPopupBox.SetData(const Value: Variant);
var
S: string;
begin
if VarIsNull(Value) then
ItemIndex := -1
else if VarIsEvent(Value) then
OnChange := VariantToEvent(Value)
else if VarIsNumeric(Value) then
ItemIndex := Value
else if VarIsStr(Value) then
begin
S := VarToWideStr(Value);
if FItems.IndexOf(S) < 0 then
Text := S
else
ItemIndex := FItems.IndexOf(S);
end;
end;
procedure TPopupBox.ApplyStyle;
begin
inherited;
end;
procedure TPopupBox.Click;
begin
inherited;
DoPopup;
end;
procedure TPopupBox.DoPopup;
var
Item: TMenuItem;
VP: TPointF;
i: Integer;
begin
FPopup.DeleteChildren;
for i := 0 to FItems.Count - 1 do
begin
Item := TMenuItem.Create(Self);
Item.Parent := FPopup;
Item.Text := FItems[i];
Item.RadioItem := True;
Item.AutoCheck := True;
Item.IsChecked := i = FItemIndex;
Item.OnClick := DoItemClick;
Item.Tag := i;
end;
if Scene <> nil then
begin
VP := LocalToAbsolute(PointF(0, trunc((Height / 2) - ((FItems.Count * 20) div 2))));
VP := Scene.LocalToScreen(VP);
FPopup.Popup(Round(VP.X), Round(VP.Y));
end;
end;
procedure TPopupBox.DoItemClick(Sender: TObject);
begin
ItemIndex := TMenuItem(Sender).Tag;
end;
procedure TPopupBox.DoItemsChanged(Sender: TObject);
begin
Repaint;
end;
procedure TPopupBox.SetItemIndex(const Value: Integer);
begin
if FItemIndex <> Value then
begin
FItemIndex := Value;
if (FItemIndex >= 0) and (Items.Count > 0) then
Text := Items[FItemIndex]
else
begin
Text := '';
FItemIndex := -1;
end;
if Assigned(FOnChange) then
FOnChange(Self);
end;
end;
procedure TPopupBox.SetText(const Value: string);
begin
if FItems.Count > 0 then
begin
FItemIndex := Items.IndexOf(Value);
if FItemIndex >= 0 then
inherited SetText(Value)
else
inherited SetText('')
end
else
begin
FItemIndex := -1;
inherited SetText('')
end;
end;
procedure TPopupBox.SetItems(const Value: TStrings);
begin
FItems.Assign(Value);
end;
function TextToShortcut(Text: string): integer;
begin
Result:= Platform.TextToShortCut(Text);
end;
initialization
RegisterFmxClasses([TMenuItem, TMenuView, TPopupMenu, TMenuBar, TPopupBox]);
end.
|
Unit MainForm;
Interface
Uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls;
Type
TMainFrm = Class (TForm)
MainPanel: TPanel;
DomainEdit: TEdit;
UserEdit: TEdit;
PasswordEdit: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
ShutdownButton: TButton;
RebootButton: TButton;
ForceCheckBox: TCheckBox;
procedure ActionButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
Private
Procedure ErrorMessage(AFormat:WideString; AArgs:Array Of Const);
end;
Var
MainFrm: TMainFrm;
Implementation
Function CreateProcessWithLogonW(AUserName:PWideChar; ADomain:PWideChar; APassword:PWideChar; ALogonFlags:Cardinal; AApplicationName:PWideChar; ACommandLine:PWideChar; ACreationFlags:Cardinal; AEnvironment:Pointer; ACurrentDirectory:PWideChar; Var AStartupInfo:STARTUPINFOW; Var AProcessInfo:PROCESS_INFORMATION):LongBool; StdCall; External 'advapi32.dll';
{$R *.DFM}
Procedure TMainFrm.ErrorMessage(AFormat:WideString; AArgs:Array Of Const);
Var
wholeMsg : WideString;
begin
wholeMsg := Format(AFormat, AArgs);
MessageBoxW(0, PWideChar(wholeMsg), 'Error', MB_OK Or MB_ICONERROR);
end;
Procedure TMainFrm.ActionButtonClick(Sender: TObject);
Var
b : TButton;
command : WideString;
si : STARTUPINFOW;
pi : PROCESS_INFORMATION;
err : Cardinal;
begin
command := 'shutdown /t 1';
b := Sender As TButton;
Case b.Tag Of
0 : command := command + ' /r';
1 : command := command + ' /s';
end;
If ForceCheckBox.Checked Then
command := command + ' /f';
Zeromemory(@si, SizeOf(si));
si.cb := SizeOf(si);
ZeroMemory(@pi, SizeOf(pi));
If CreateProcessWithLogonW(
PWideChar(UserEdit.Text),
PWideChar(DomainEdit.Text),
PWideChar(PasswordEdit.Text),
0, Nil, PWideChar(command), 0, Nil, Nil, si, pi) Then
begin
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
end
Else begin
err := GetLastError;
ErrorMessage('Error %u'#13#10'%s', [err, SysErrorMessage(err)]);
end;
end;
procedure TMainFrm.FormCreate(Sender: TObject);
Var
size : Cardinal;
cnBuffer : Array [0..MAX_PATH - 1] Of WideChar;
begin
ZeroMemory(@cnBuffer, SizeOf(cnBuffer));
size := SizeOf(cnBuffer) Div SizeOf(WideChar);
If GetComputerNameW(cnBuffer, size) Then
DomainEdit.Text := WideCharToString(cnBuffer);
end;
End.
|
// NIM/Nama : 16518189/M Mirza Fathan Al Arsyad
// Tanggal : 22 Maret 2019
Program ProsesLingkaran;
{ Input: 2 buah Lingkaran }
{ Output: luas, keliling, dan hubungan lingkaran A dan B }
{ KAMUS }
const
PI : real = 3.1415;
type
{ Definisi Type Koordinat }
Koordinat = record
x,y : integer;
end;
{ Definisi Type Lingkaran }
Lingkaran = record
c : Koordinat; { titik pusat lingkaran }
r : real; { jari-jari, > 0 }
end;
var
A, B : Lingkaran; { variabel untuk lingkaran A dan B }
{ FUNGSI DAN PROSEDUR }
function isValid (r : real) : boolean;
begin
if(r>0) then
begin
isValid := True;
end else
begin
isValid := False;
end;
end;
procedure InputLingkaran (var A : Lingkaran);
begin
readln(((A.c).x),((A.c).y));
readln(A.r);
while(not isValid(A.r)) do
begin
writeln('Jari-jari harus > 0');
readln(A.r);
end;
end;
function KelilingLingkaran (A : Lingkaran) : real;
begin
KelilingLingkaran := 2 * PI * A.r;
end;
function LuasLingkaran (A : Lingkaran) : real;
begin
LuasLingkaran := PI * A.r * A.r;
end;
function Jarak (P1, P2 : Koordinat) : real;
begin
Jarak := sqrt((P2.x-P1.x)*(P2.x-P1.x)+(P2.y-P1.y)*(P2.y-P1.y));
end;
function HubunganLingkaran (A, B : Lingkaran) : integer;
begin
if (Jarak(A.c,B.c)=0) then
begin
if (A.r=B.r) then
begin
HubunganLingkaran := 1;
end else
begin
HubunganLingkaran := 2;
end;
end else if (Jarak(A.c,B.c)<((A.r)+(B.r))) then
begin
HubunganLingkaran := 3;
end else if (Jarak(A.c,B.c)=((A.r)+(B.r))) then
begin
HubunganLingkaran := 4;
end else
begin
HubunganLingkaran := 5;
end;
end;
{ ALGORITMA PROGRAM UTAMA }
begin
writeln('Masukkan lingkaran A:');
InputLingkaran(A);
writeln('Masukkan lingkaran B:');
InputLingkaran(B);
writeln('Keliling lingkaran A = ', KelilingLingkaran(A):4:2);
writeln('Luas lingkaran A = ', LuasLingkaran(A):4:2);
writeln('Keliling lingkaran B = ', KelilingLingkaran(B):4:2);
writeln('Luas lingkaran B = ', LuasLingkaran(B):4:2);
write('A dan B adalah ');
if(HubunganLingkaran(A,B)=1) then
begin
writeln('sama');
end else if (HubunganLingkaran(A,B)=2) then
begin
writeln('berimpit');
end else if (HubunganLingkaran(A,B)=3) then
begin
writeln('beririsan');
end else if (HubunganLingkaran(A,B)=4) then
begin
writeln('bersentuhan');
end else
begin
writeln('saling lepas');
end;
end .
|
unit ImgFile;
interface
uses Graph;
TYPE
ImgData = ARRAY[0..$8888] OF BYTE;
ImgRec = RECORD
ImgPtr : ^ImgData;
LastColor : BYTE;
Location : WORD;
RunCount : SHORTINT;
InRepeat : BOOLEAN;
END;
PROCEDURE StartImage( VAR img : ImgRec; rows, cols : WORD);
PROCEDURE AddToImage (VAR img : ImgRec; Color : BYTE);
{ simple byte run encoding }
PROCEDURE SaveImage(filename : string; img : ImgRec);
PROCEDURE RetrieveImage(filename : string; VAR img : ImgRec);
PROCEDURE DisplayImage(img : ImgRec);
implementation
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
PROCEDURE StartImage( VAR img : ImgRec; rows, cols : WORD);
BEGIN
WITH img DO
BEGIN
ImgPtr^[0] := rows;
ImgPtr^[1] := cols;
Location := 2;
InRepeat := FALSE;
RunCount := 0;
LastColor := 0;
END;
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
PROCEDURE AddToImage (VAR img : ImgRec; Color : BYTE);
{ simple byte run encoding }
VAR
Offset : WORD;
InRepeat : BOOLEAN;
BEGIN
WITH Img DO
BEGIN
IF (Color = LastColor) THEN
IF InREPEAT THEN
INC(RunCount)
ELSE BEGIN
{ end literal copy, start repeat }
ImgPtr^[Location] := RunCount; { put run count into img array }
{adding 1 to Runcount before div ensures BYTE alignment}
INC(Location,1 + (RunCount+1) div 2);
RunCount := 0;
InRepeat := True;
END
ELSE
IF InREPEAT THEN BEGIN
{stop repeat, start literal copy}
ImgPtr^[Location] := -RunCount; {neg run is a repeat }
ImgPtr^[Location + 1] := LastColor; { put repeat color into array }
INC(Location,2);
RunCount := 0;
InRepeat := FALSE; END
ELSE BEGIN
Offset := Location + (RunCount div 2);
{ just another color }
IF RunCount MOD 2 = 0 THEN
ImgPtr^[Offset] := Color shl 4
ELSE
ImgPtr^[Offset] := ImgPtr^[Offset] OR Color;
INC(RunCount);
END;
LastColor := Color;
END; {With }
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
PROCEDURE SaveImage(filename : string; img : ImgRec);
VAR
n : LONGINT;
Outfile : FILE OF BYTE;
BEGIN
Assign(outfile,filename);
Rewrite(outfile);
FOR n := 0 TO img.Location DO
Write(outfile,img.ImgPtr^[n]);
Close(outfile);
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
PROCEDURE RetrieveImage(filename : string; VAR img : ImgRec);
VAR
infile : FILE OF BYTE;
BEGIN
Assign(infile,filename);
Reset(infile);
img.Location := 0;
WHILE NOT EOF(infile) DO
BEGIN
Read(infile,img.ImgPtr^[img.Location]);
INC(img.Location);
END;
Close(infile);
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
PROCEDURE DisplayImage(img : ImgRec);
VAR
Color, HighLocation, n,
rows, cols, x,y : WORD;
PROCEDURE DoPixel;
BEGIN
PutPixel(x,y,color);
INC(x);
IF x > cols THEN
BEGIN
INC(y);
x := 0;
END;
END; { DoPixel }
BEGIN {displayimage}
WITH img DO
BEGIN
rows := imgptr^[0];
cols := imgptr^[1];
x := 0;
y := 0;
HighLocation := Location;
Location := 2;
REPEAT
RunCount := imgptr^[Location];
IF RunCount < 0 THEN {repeat} BEGIN
color := imgptr^[Location + 1];
FOR n := 0 to -RunCount - 1 DO DoPixel;
INC(Location,2); END
ELSE BEGIN
INC(Location);
FOR n := 0 to RunCount - 1 DO
BEGIN
IF n MOD 2 = 0 THEN
Color := imgptr^[Location + n div 2] shr 4
ELSE
Color := imgptr^[Location + n div 2] AND $FF;
DoPixel;
END;
END;
UNTIL Location > HighLocation
END; { with }
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
BEGIN
END. |
unit uScsi;
interface
uses Windows, Sysutils;
function GetSCSISerial(Drive: Char): String;
implementation
function GetDeviceHandle( sDeviceName : String ) : THandle;
begin
Result := CreateFile( PChar('\\.\'+sDeviceName), GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0 )
end;
//-------------------------------------------------------------
function ScsiHddSerialNumber( DeviceHandle : THandle ) : String;
{$ALIGN ON}
type
TScsiPassThrough = record
Length : Word;
ScsiStatus : Byte;
PathId : Byte;
TargetId : Byte;
Lun : Byte;
CdbLength : Byte;
SenseInfoLength : Byte;
DataIn : Byte;
DataTransferLength : ULONG;
TimeOutValue : ULONG;
DataBufferOffset : DWORD;
SenseInfoOffset : ULONG;
Cdb : Array[0..15] of Byte;
end;
TScsiPassThroughWithBuffers = record
spt : TScsiPassThrough;
bSenseBuf : Array[0..31] of Byte;
bDataBuf : Array[0..191] of Byte;
end;
{ALIGN OFF}
var dwReturned : DWORD;
len : DWORD;
Buffer : Array[0..SizeOf(TScsiPassThroughWithBuffers)+SizeOf(TScsiPassThrough)-1] of Byte;
sptwb : TScsiPassThroughWithBuffers absolute Buffer;
begin
{$I crypt_start.inc}
Result := '';
FillChar(Buffer,SizeOf(Buffer),#0);
with sptwb.spt do
begin
Length := SizeOf(TScsiPassThrough);
CdbLength := 6; // CDB6GENERIC_LENGTH
SenseInfoLength := 24;
DataIn := 1; // SCSI_IOCTL_DATA_IN
DataTransferLength := 192;
TimeOutValue := 2;
DataBufferOffset := PChar(@sptwb.bDataBuf)-PChar(@sptwb);
SenseInfoOffset := PChar(@sptwb.bSenseBuf)-PChar(@sptwb);
Cdb[0] := $12; // OperationCode := SCSIOP_INQUIRY;
Cdb[1] := $01; // Flags := CDB_INQUIRY_EVPD; Vital product data
Cdb[2] := $80; // PageCode Unit serial number
Cdb[4] := 192; // AllocationLength
end;
len := sptwb.spt.DataBufferOffset+sptwb.spt.DataTransferLength;
if DeviceIoControl( DeviceHandle, $0004d004, @sptwb, SizeOf(TScsiPassThrough), @sptwb, len, dwReturned, nil )
and ((PChar(@sptwb.bDataBuf)+1)^=#$80)
then SetString( Result, PChar(@sptwb.bDataBuf)+4, Ord((PChar(@sptwb.bDataBuf)+3)^) );
{$I crypt_end.inc}
end;
//=============================================================
function GetSCSISerial(Drive: Char): String;
var
hDevice : THandle;
sSerNum : String;
begin
Result := '';
hDevice := GetDeviceHandle( Drive);
if hDevice<>INVALID_HANDLE_VALUE then
try
Result := ScsiHddSerialNumber(hDevice);
finally
CloseHandle(hDevice);
end;
end;
end.
|
{
ID:asiapea1
PROG:kimbits
LANG:PASCAL
}
program kimbits;
const maxn=31;
var f:array[0..maxn+1,0..maxn+1] of int64;
i,j,n,l:longint;
k:int64;
procedure opf;
begin
assign(input,'kimbits.in'); reset(input);
assign(output,'kimbits.out'); rewrite(output);
end;
procedure clf;
begin
close(input);
close(output);
end;
procedure init;
begin
readln(n,l,k);
for i:=0 to n do
begin
f[i,0]:=1;
f[0,i]:=1;
end;
end;
procedure main;
begin
for i:=1 to n do
for j:=1 to n do
if j>i then f[i,j]:=f[i,i] else f[i,j]:=f[i-1,j]+f[i-1,j-1];
for i:=n-1 downto 0 do
if f[i,l]<k then
begin
write(1);
dec(k,f[i,l]);
dec(l);
end
else write(0);
writeln;
end;
begin
opf;
init;
main;
clf;
end. |
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2012-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.Editor.Items;
interface
uses
DesignEditors, DesignMenus, DesignIntf, Classes, Vcl.Menus, System.Generics.Collections, FMX.Types, FmxDsnConst,
FMX.Design.Items, FMX.SearchBox;
const
EDITOR_OPEN_DESIGNER = 0;
EDITOR_CREATE_ITEM = 1;
EDITOR_NEW_ITEM = 2;
type
{ TItemsEditor }
/// <summary>
/// Items Editor Base Classes for controls, which haves list of items.
/// It allows to create list of member of different classes.
/// </summary>
TItemsEditor = class(TComponentEditor)
private
class var FListOfLastItems: TDictionary<string, Integer>;
protected
FAllowChild: Boolean;
FItemsClasses: array of TItemClassDesc;
procedure DoCreateItem(Sender: TObject); virtual;
function GetIndexOfItemClass: Integer;
procedure SetIndexOfItemClass(const Value: Integer);
protected
function CanShow: Boolean; virtual;
property IndexOfItemClass: Integer read GetIndexOfItemClass write SetIndexOfItemClass;
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
procedure PrepareItem(Index: Integer; const AItem: IMenuItem); override;
procedure Edit; override;
end;
{ TMenuEditor }
TMenuEditor = class(TItemsEditor)
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
end;
{ TListBoxEditor }
TListBoxEditor = class(TItemsEditor)
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
end;
{ TTreeViewEditor }
TTreeViewEditor = class(TItemsEditor)
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
end;
{ THeaderEditor }
THeaderEditor = class(TItemsEditor)
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
end;
{ TTabControlEditor }
TTabControlEditor = class(TItemsEditor)
private
FEditorNextTab: Integer;
FEditorPrevTab: Integer;
FEditorDeleteTab: Integer;
FVerbCount: Integer;
function GetTabIndex: Integer;
protected
procedure DoCreateItem(Sender: TObject); override;
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
procedure PrepareItem(Index: Integer; const AItem: IMenuItem); override;
end;
{ TActiveTabProperty }
TActiveTabProperty = class (TComponentProperty)
private
FCurrentControl: TComponent;
FNewValue: string;
FNewControl: TComponent;
procedure CheckValue(const S: string);
procedure EnumerateItems(const VisibleOnly: Boolean; Proc: TGetStrProc);
procedure CheckControl(const S: string);
public
procedure GetValues(Proc: TGetStrProc); override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
function GetAttributes: TPropertyAttributes; override;
end;
{ TBrushKindProperty }
TBrushKindProperty = class (TEnumProperty)
public
procedure SetValue(const Value: string); override;
end;
{ TGridEditor }
TGridEditor = class(TItemsEditor)
protected
function CanShow: Boolean; override;
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
end;
{ TStringGridEditor }
TStringGridEditor = class(TItemsEditor)
protected
function CanShow: Boolean; override;
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
end;
{ TEditEditor }
TEditEditor = class(TItemsEditor)
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
end;
implementation
uses
System.SysUtils, FMX.Consts, FMX.Forms, FMX.TreeView, FMX.Header, FMX.Grid, FMX.ListBox, FMX.TabControl, FMX.Menus,
Vcl.Dialogs, Vcl.Controls, Windows, FMX.Platform.Win, FMX.Design.Lang, ActnEdit, FMX.ActnList, DsnConst,
FMX.Controls, FMX.Edit;
{$REGION 'TItemsEditor'}
function TItemsEditor.CanShow: Boolean;
begin
Result := True;
end;
procedure TItemsEditor.DoCreateItem(Sender: TObject);
var
MenuItem: Vcl.Menus.TMenuItem;
begin
if Sender is Vcl.Menus.TMenuItem then
begin
MenuItem := Sender as Vcl.Menus.TMenuItem;
if MenuItem.Tag >= 0 then
IndexOfItemClass := MenuItem.Tag;
end;
if (Component is TFmxObject) and (IndexOfItemClass >= 0) and (IndexOfItemClass < Length(FItemsClasses)) then
Designer.CreateChild(FItemsClasses[IndexOfItemClass].ItemClass, Component);
end;
procedure TItemsEditor.Edit;
begin
if CanShow then
ExecuteVerb(EDITOR_OPEN_DESIGNER);
end;
procedure TItemsEditor.ExecuteVerb(Index: Integer);
var
Container: IItemsContainer;
begin
case Index of
EDITOR_OPEN_DESIGNER:
begin
if Assigned(DesignItemsForm) then
FreeAndNil(DesignItemsForm);
DesignItemsForm := TDesignItemsForm.Create(Application);
if Supports(Component, IItemsContainer, Container) then
begin
DesignItemsForm.btnAddChild.Visible := FAllowChild;
DesignItemsForm.Caption := GetVerb(Index).TrimRight([' ', '.']);
DesignItemsForm.Designer := Designer;
DesignItemsForm.SetItemClasses(Container, FItemsClasses);
DesignItemsForm.Show;
end;
end;
EDITOR_NEW_ITEM:
DoCreateItem(nil);
end;
end;
function TItemsEditor.GetVerb(Index: Integer): string;
begin
case Index of
EDITOR_OPEN_DESIGNER:
Result := SItemsEditor;
EDITOR_CREATE_ITEM:
Result := SNewItem;
EDITOR_NEW_ITEM:
begin
if (IndexOfItemClass >= 0) and (IndexOfItemClass < Length(FItemsClasses)) then
Result := Format(SNewLastItem, [FItemsClasses[IndexOfItemClass].ItemClass.ClassName])
else
Result := Format(SNewLastItem, [IntToStr(IndexOfItemClass)]);
end;
else
Result := Format(SItems + ' %d', [Index]);
end;
end;
function TItemsEditor.GetVerbCount: Integer;
begin
if CanShow then
Result := 3
else
Result := 0;
end;
function TItemsEditor.GetIndexOfItemClass: Integer;
var
I: Integer;
begin
Result := 0;
if (FListOfLastItems <> nil) and FListOfLastItems.TryGetValue(ClassType.QualifiedClassName, I) then
Result := I;
end;
procedure TItemsEditor.SetIndexOfItemClass(const Value: Integer);
var
I: Integer;
begin
if FListOfLastItems = nil then
begin
FListOfLastItems := TDictionary<string, Integer>.Create;
end;
if FListOfLastItems.TryGetValue(ClassType.QualifiedClassName, I) then
FListOfLastItems[ClassType.QualifiedClassName] := Value
else
FListOfLastItems.Add(ClassType.QualifiedClassName, Value);
end;
procedure TItemsEditor.PrepareItem(Index: Integer; const AItem: IMenuItem);
var
I: Integer;
MenuItem: IMenuItem;
begin
inherited PrepareItem(Index, AItem);
case Index of
EDITOR_CREATE_ITEM:
begin
if Length(FItemsClasses) > 1 then
begin
AItem.Visible := True;
for I := 0 to High(FItemsClasses) do
begin
MenuItem := AItem.AddItem(FItemsClasses[I].ItemClass.ClassName, 0, False, True, DoCreateItem);
MenuItem.Tag := I;
MenuItem := nil;
end;
end
else
AItem.Visible := False;
end;
EDITOR_NEW_ITEM:
begin
AItem.Visible := (IndexOfItemClass >= 0) and (IndexOfItemClass < Length(FItemsClasses));
AItem.Tag := -1;
end;
end;
end;
{$ENDREGION}
{$REGION 'TMenuEditor'}
constructor TMenuEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
begin
inherited Create(AComponent, ADesigner);
FAllowChild := true;
SetLength(FItemsClasses, 1);
FItemsClasses[0] := TItemClassDesc.Create(FMX.Menus.TMenuItem, True);
end;
{$ENDREGION}
{$REGION 'TListBoxEditor'}
constructor TListBoxEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
begin
inherited Create(AComponent, ADesigner);
FAllowChild := false;
SetLength(FItemsClasses, 6);
FItemsClasses[0] := TItemClassDesc.Create(TListBoxItem);
FItemsClasses[1] := TItemClassDesc.Create(TMetropolisUIListBoxItem);
FItemsClasses[2] := TItemClassDesc.Create(TListBoxHeader, False, True);
FItemsClasses[3] := TItemClassDesc.Create(TSearchBox, False, True);
FItemsClasses[4] := TItemClassDesc.Create(TListBoxGroupHeader);
FItemsClasses[5] := TItemClassDesc.Create(TListBoxGroupFooter);
end;
{$ENDREGION}
{$REGION 'TTreeViewEditor'}
constructor TTreeViewEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
begin
inherited Create(AComponent, ADesigner);
FAllowChild := true;
SetLength(FItemsClasses, 1);
FItemsClasses[0] := TItemClassDesc.Create(TTreeViewItem, True);
end;
{$ENDREGION}
{$REGION 'THeaderEditor'}
constructor THeaderEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
begin
inherited Create(AComponent, ADesigner);
FAllowChild := false;
SetLength(FItemsClasses, 1);
FItemsClasses[0] := TItemClassDesc.Create(THeaderItem);
end;
{$ENDREGION}
{$REGION 'TTabControlEditor'}
constructor TTabControlEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
begin
inherited Create(AComponent, ADesigner);
FEditorNextTab := inherited GetVerbCount;
FEditorPrevTab := FEditorNextTab + 1;
FEditorDeleteTab := FEditorNextTab + 2;
FVerbCount := FEditorNextTab + 3;
FAllowChild := False;
SetLength(FItemsClasses, 1);
FItemsClasses[0] := TItemClassDesc.Create(TTabItem);
end;
procedure TTabControlEditor.DoCreateItem(Sender: TObject);
begin
inherited;
if (Component is TTabControl) then
TTabControl(Component).TabIndex := TTabControl(Component).TabCount - 1;
end;
function TTabControlEditor.GetTabIndex: Integer;
begin
if (Component is TTabControl) and (TTabControl(Component).TabIndex >= 0) and
(TTabControl(Component).TabIndex < TTabControl(Component).TabCount) then
Result := TTabControl(Component).TabIndex
else
Result := -1;
end;
procedure TTabControlEditor.ExecuteVerb(Index: Integer);
var
Obj: TFmxObject;
LTabIndex: Integer;
LControl: TTabControl;
procedure SelectTab(I: Integer);
begin
if I >= LControl.TabCount then
I := LControl.TabCount - 1;
if I < 0 then
I := -1;
LControl.TabIndex := I;
if I >= 0 then
Designer.SelectComponent(LControl.Tabs[I])
else
Designer.SelectComponent(Component);
end;
begin
inherited;
if Component is TTabControl then
begin
LTabIndex := GetTabIndex;
LControl := TTabControl(Component);
if Index = FEditorNextTab then
SelectTab(LTabIndex + 1)
else if Index = FEditorPrevTab then
SelectTab(LTabIndex - 1)
else if (Index = FEditorDeleteTab) and (LTabIndex >= 0) then
begin
Obj := (LControl as IItemsContainer).GetItem(LTabIndex);
FreeAndNil(Obj);
SelectTab(LTabIndex);
end;
end;
end;
function TTabControlEditor.GetVerb(Index: Integer): string;
var
S: string;
begin
Result := Inherited GetVerb(Index);
if Component is TTabControl then
if Index = FEditorNextTab then
Result := SNextTab
else if Index = FEditorPrevTab then
Result := SPrevTab
else if Index = FEditorDeleteTab then
begin
if GetTabIndex >= 0 then
begin
S := TTabControl(Component).Tabs[GetTabIndex].Name;
if S = '' then
S := Format(SUnnamedTab, [GetTabIndex, TTabControl(Component).Tabs[GetTabIndex].ClassName])
else
S := QuotedStr(S);
Result := Format(SDeleteItem, [S]);
end
else
Result := Format(SDeleteItem, ['']);
end;
end;
function TTabControlEditor.GetVerbCount: Integer;
begin
Result := FVerbCount;
end;
procedure TTabControlEditor.PrepareItem(Index: Integer; const AItem: IMenuItem);
begin
inherited;
if Component is TTabControl then
begin
if Index = FEditorNextTab then
AItem.Enabled := GetTabIndex < TTabControl(Component).TabCount - 1
else if Index = FEditorPrevTab then
AItem.Enabled := GetTabIndex > 0
else if Index = FEditorDeleteTab then
AItem.Enabled := GetTabIndex >= 0;
end
else
AItem.Visible := False;
end;
{$ENDREGION}
{$REGION 'TBrushKindProperty'}
{ TBrushKindProperty }
procedure TBrushKindProperty.SetValue(const Value: string);
begin
if WideSameText(Value, GetValue) or not WideSameText(Value, 'Bitmap') or
(Vcl.Dialogs.MessageDlg(SBitmapBrushWindowsOnly, mtWarning, [mbOK, mbCancel], 0) = mrOk) then
inherited;
end;
{$ENDREGION}
{$REGION 'TActiveTabProperty'}
{ TActiveTabProperty }
function TActiveTabProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited - [paMultiSelect, paSortList];
end;
procedure TActiveTabProperty.EnumerateItems(const VisibleOnly: Boolean; Proc: TGetStrProc);
var
Persistent: TPersistent;
Container: IItemsContainer;
I: Integer;
Obj: TFmxObject;
S: TComponentName;
begin
if PropCount = 1 then
begin
Persistent := GetComponent(0);
if (Persistent is TComponent) and Persistent.GetInterface(IItemsContainer, Container) then
for I := 0 to Container.GetItemsCount - 1 do
begin
Obj := Container.GetItem(I);
if (Obj is TControl) and (not VisibleOnly or TControl(Obj).Visible) then
begin
FCurrentControl := Obj;
S := TControl(Obj).Name;
if S = '' then
S := Format(SUnnamedTab, [I, Obj.ClassName]);
Proc(S);
end;
end;
end;
end;
procedure TActiveTabProperty.CheckValue(const S: string);
begin
if WideSameText(S, FNewValue) then
FNewControl := FCurrentControl;
end;
procedure TActiveTabProperty.CheckControl(const S: string);
begin
if GetOrdValue = NativeInt(FCurrentControl) then
FNewValue := S;
end;
procedure TActiveTabProperty.SetValue(const Value: string);
begin
FCurrentControl := nil;
FNewControl := nil;
FNewValue := Value;
EnumerateItems(False, CheckValue);
SetOrdValue(NativeInt(FNewControl));
end;
function TActiveTabProperty.GetValue: string;
begin
FCurrentControl := nil;
FNewControl := nil;
FNewValue := '';
EnumerateItems(False, CheckControl);
Result := FNewValue;
end;
procedure TActiveTabProperty.GetValues(Proc: TGetStrProc);
begin
EnumerateItems(True, Proc);
end;
{$ENDREGION}
{$REGION 'TGridEditor'}
function GridItemsEditorEnabled(const Grid: TCustomGrid): Boolean;
var
I: Integer;
begin
Result := Grid <> nil;
if Result and (Grid.ColumnCount > 0) then
begin
for I := 0 to Grid.ColumnCount - 1 do
if not Grid.Columns[I].Locked then
Exit;
Result := False;
end;
end;
constructor TGridEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
var
List: TArray<TColumnClass>;
I: Integer;
begin
inherited Create(AComponent, ADesigner);
FAllowChild := False;
SetLength(FItemsClasses, Length(FItemsClasses) + 1);
FItemsClasses[Length(FItemsClasses) - 1] := TItemClassDesc.Create(TColumn);
List := TColumnClasses.RegisteredColumns;
for I := Low(List) to High(List) do
if List[I].ClassName <> TColumn.ClassName then
begin
SetLength(FItemsClasses, Length(FItemsClasses) + 1);
FItemsClasses[Length(FItemsClasses) - 1] := TItemClassDesc.Create(TFmxObjectClass(List[I]));
end;
end;
function TGridEditor.CanShow: Boolean;
begin
Result := inherited and (Component is TCustomGrid) and GridItemsEditorEnabled(TCustomGrid(Component));
end;
{$ENDREGION}
{$REGION 'TStringGridEditor'}
function TStringGridEditor.CanShow: Boolean;
begin
Result := inherited and (Component is TCustomGrid) and GridItemsEditorEnabled(TCustomGrid(Component));
end;
constructor TStringGridEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
var
List: TArray<TColumnClass>;
I: Integer;
begin
inherited Create(AComponent, ADesigner);
FAllowChild := False;
SetLength(FItemsClasses, Length(FItemsClasses) + 1);
FItemsClasses[Length(FItemsClasses) - 1] := TItemClassDesc.Create(TStringColumn);
List := TColumnClasses.RegisteredColumns;
for I := Low(List) to High(List) do
if (List[I].ClassName <> TStringColumn.ClassName) and not List[I].InheritsFrom(TImageColumn) then
begin
SetLength(FItemsClasses, Length(FItemsClasses) + 1);
FItemsClasses[Length(FItemsClasses) - 1] := TItemClassDesc.Create(TFmxObjectClass(List[I]));
end;
end;
{$ENDREGION}
{$REGION 'TEditEditor'}
constructor TEditEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
begin
inherited Create(AComponent, ADesigner);
FAllowChild := False;
SetLength(FItemsClasses, 7);
FItemsClasses[0] := TItemClassDesc.Create(TEditButton);
FItemsClasses[1] := TItemClassDesc.Create(TClearEditButton);
FItemsClasses[2] := TItemClassDesc.Create(TPasswordEditButton);
FItemsClasses[3] := TItemClassDesc.Create(TSearchEditButton);
FItemsClasses[4] := TItemClassDesc.Create(TEllipsesEditButton);
FItemsClasses[5] := TItemClassDesc.Create(TDropDownEditButton);
FItemsClasses[6] := TItemClassDesc.Create(TSpinEditButton);
end;
{$ENDREGION}
initialization
finalization
FreeandNil(TItemsEditor.FListOfLastItems);
end.
|
{**********************************************}
{ TAxisIncrement Dialog Editor }
{ Copyright (c) 1996-2004 David Berneda }
{**********************************************}
unit TeeAxisIncr;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
{$ENDIF}
Chart, TeEngine, TeeProcs, TeCanvas;
type
TAxisIncrement = class(TForm)
RadioGroup1: TRadioGroup;
CBSteps: TComboFlat;
ECustom: TEdit;
BOk: TButton;
BCancel: TButton;
Label1: TLabel;
CBExact: TCheckBox;
procedure FormShow(Sender: TObject);
procedure RadioGroup1Click(Sender: TObject);
procedure BOkClick(Sender: TObject);
procedure CBExactClick(Sender: TObject);
procedure CBStepsChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
Procedure SetEditText;
public
{ Public declarations }
IsDateTime : Boolean;
IsExact : Boolean;
Increment : Double;
IStep : TDateTimeStep;
end;
Function GetIncrementText( AOwner:TComponent;
Const Increment:Double;
IsDateTime,
ExactDateTime:Boolean;
Const AFormat:String):String;
{ Show message to user, with "Incorrect" text }
Procedure TeeShowIncorrect(Const Message:String);
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeeConst;
Procedure TeeShowIncorrect(Const Message:String);
begin
ShowMessage(Format(TeeMsg_IncorrectMaxMinValue,[Message]));
end;
procedure TAxisIncrement.FormShow(Sender: TObject);
var tmpDif:Integer;
begin
CBExact.Visible:=IsDateTime;
CBExact.Enabled:=RadioGroup1.ItemIndex=0;
CBExact.Checked:=IsExact;
if IsDateTime then
begin
ECustom.Hint:=TeeMsg_EnterDateTime;
SetEditText;
if IsExact and (IStep<>dtNone) then
Begin
RadioGroup1.ItemIndex:=0;
CBSteps.ItemIndex:=Ord(IStep);
ECustom.Text:='';
ECustom.Enabled:=False;
CBSteps.SetFocus;
end
else
begin
RadioGroup1.ItemIndex:=1;
CBSteps.ItemIndex:=-1;
end;
end
else
begin
CBSteps.Visible:=False;
RadioGroup1.Visible:=False;
RadioGroup1.ItemIndex:=1;
ECustom.Hint:='';
ECustom.Text:=FloatToStr(Increment);
tmpDif:=ECustom.Top-Label1.Top;
ECustom.Top:=BOK.Top;
Label1.Top:=ECustom.Top-tmpDif;
ECustom.SetFocus;
end;
end;
Procedure TAxisIncrement.SetEditText;
Begin
if Increment<=0 then ECustom.Text:=TimeToStr(DateTimeStep[dtOneSecond])
else
if Increment>=1 then
Begin
ECustom.Text:=FloatToStr(Int(Increment));
if Frac(Increment)<>0 then
ECustom.Text:=ECustom.Text+' '+TimeToStr(Frac(Increment));
end
else ECustom.Text:=TimeToStr(Increment);
end;
procedure TAxisIncrement.RadioGroup1Click(Sender: TObject);
Procedure DoEnableControls(Value:Boolean);
begin
ECustom.Enabled:=not Value;
CBExact.Checked:=Value;
IsExact:=Value;
CBExact.Enabled:=Value;
CBSteps.Enabled:=Value;
end;
begin
Case RadioGroup1.ItemIndex of
0: Begin
DoEnableControls(True);
if IStep<>dtNone then
CBSteps.ItemIndex:=Ord(IStep)
else
CBSteps.ItemIndex:=0;
CBSteps.SetFocus;
end;
1: Begin
DoEnableControls(False);
SetEditText;
ECustom.SetFocus;
end;
end;
end;
procedure TAxisIncrement.BOkClick(Sender: TObject);
const tmpSpace:String=' ';
var i : Integer;
Code : Integer;
tmp : Double;
begin
try
if IsDateTime then
Begin
if RadioGroup1.ItemIndex=0 then
Increment:=DateTimeStep[TDateTimeStep(CBSteps.ItemIndex)]
else
With ECustom do
Begin
i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(tmpSpace,Text);
if i=0 then
try
Val(Text,tmp,Code);
if Code=0 then Increment:=tmp
else Increment:=StrToTime(Text);
except
on Exception do Increment:=StrToFloat(Text);
end
else Increment:=StrToFloat(Copy(Text,1,i-1))+
StrToTime(Copy(Text,i+1,255));
end;
end
else Increment:=StrToFloat(ECustom.Text);
ModalResult:=mrOk;
except
on E:Exception do TeeShowIncorrect(E.Message);
end;
end;
procedure TAxisIncrement.CBExactClick(Sender: TObject);
begin
IsExact:=CBExact.Checked;
if not IsExact then
begin
RadioGroup1.ItemIndex:=1;
ECustom.Enabled:=True;
SetEditText;
ECustom.SetFocus;
end;
end;
procedure TAxisIncrement.CBStepsChange(Sender: TObject);
begin
IStep:=TDateTimeStep(CBSteps.ItemIndex);
end;
Function GetIncrementText( AOwner:TComponent;
Const Increment:Double;
IsDateTime,
ExactDateTime:Boolean;
Const AFormat:String):String;
Function GetDateTimeStepText(tmp:TDateTimeStep):String;
begin
result:='';
With TAxisIncrement.Create(AOwner) do
try
result:=CBSteps.Items[Ord(tmp)];
finally
Free;
end;
end;
var tmp : TDateTimeStep;
begin
if IsDateTime then
begin
tmp:=FindDateTimeStep(Increment);
if ExactDateTime and (tmp<>dtNone) then result:=GetDateTimeStepText(tmp)
else
if Increment<=0 then result:=TimeToStr(DateTimeStep[dtOneSecond])
else
if Increment<=1 then result:=TimeToStr(Increment)
else
Begin
result:=FloatToStr(Int(Increment));
if Frac(Increment)<>0 then result:=result+' '+TimeToStr(Frac(Increment));
end;
end
else result:=FormatFloat(AFormat,Increment);
end;
procedure TAxisIncrement.FormCreate(Sender: TObject);
begin
BorderStyle:=TeeBorderStyle;
end;
end.
|
unit ClassMHDclient;
interface
uses Classes, ScktComp, Controls, Konstanty;
type TStatus = ( csNone,
csConnecting,
csSendingInfo,
csAcceptingSession,
csAcceptSession,
csGettingFile,
csFileOK,
csFinish,
csTransferError );
TSessionInfo = record
Rozvrhy : integer;
Listky : integer;
Zastavky : integer;
NewUpdate : string;
end;
TFileType = (ftNone,ftRozvrh,ftListok,ftZastavky);
TRecievedFile = record
FileType : TFileType;
Data : WideString;
end;
TStatusEvent = procedure( Status : TStatus; StatusText : string ) of object;
TSessionEvent = procedure( SessionInfo : TSessionInfo ) of object;
TItemEvent = procedure( Typ : integer; Popis, Stav : string ) of object;
TMHDclient = class
private
Client : TClientSocket;
LongFile : boolean;
LongData : WideString;
RecievedFile : TRecievedFile;
StatusText : string;
SessionInfo : TSessionInfo;
FStatus : TStatus;
FOnStatusChange : TStatusEvent;
FOnSessionBegin : TSessionEvent;
FOnItemChange : TItemEvent;
procedure SetStatus( Value : TStatus );
procedure Connect( Sender: TObject; Socket: TCustomWinSocket );
procedure MyRead( Sender: TObject; Socket: TCustomWinSocket );
procedure MyWrite( Sender: TObject; Socket: TCustomWinSocket );
procedure Error( Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer );
procedure GetInfo;
procedure SendInfo;
procedure GetSessionInfo;
procedure SendAcceptSession;
procedure GetFile;
procedure SaveFile;
procedure SaveRozvrh( Data : WideString );
procedure SaveListok( Data : WideString );
procedure SaveZastavky( Data : WideString );
procedure SendFileOK;
procedure SaveLastUpdate;
property Status : TStatus read FStatus write SetStatus;
public
constructor Create;
destructor Destroy; override;
property OnStatusChange : TStatusEvent read FOnStatusChange write FOnStatusChange;
property OnSessionBegin : TSessionEvent read FOnSessionBegin write FOnSessionBegin;
property OnItemChange : TItemEvent read FOnItemChange write FOnItemChange;
end;
var MHDclient : TMHDclient;
implementation
uses SysUtils, Registry, Windows;
//==============================================================================
//==============================================================================
//
// C L I E N T
//
//==============================================================================
//==============================================================================
constructor TMHDclient.Create;
begin
inherited;
Client := TClientSocket.Create( nil );
with Client do
begin
Address := '';
ClientType := ctNonBlocking;
Host := SERVERINFO.Host;
Port := SERVERINFO.Port;
Service := '';
OnConnect := Connect;
OnRead := MyRead;
OnWrite := MyWrite;
OnError := Error;
Active := True;
end;
end;
//==============================================================================
// Destructor
//==============================================================================
destructor TMHDclient.Destroy;
begin
Client.Active := False;
Client.Free;
inherited;
end;
//==============================================================================
// Properties
//==============================================================================
procedure TMHDClient.SetStatus( Value : TStatus );
begin
if (Value = FStatus) then exit;
FStatus := Value;
case FStatus of
csNone : StatusText := 'Neznámy stav';
csConnecting : StatusText := 'Pripájanie ...';
csSendingInfo : StatusText := 'Posielanie informácii ...';
csAcceptingSession : StatusText := 'Prijímanie zoznamu súborov ...';
csAcceptSession : StatusText := 'Začiatok prenosu ...';
csGettingFile : StatusText := 'Prijímanie súboru ...';
csFileOK : StatusText := 'Súbor prijatý';
csFinish : StatusText := 'Aktualizácia dokončená';
csTransferError : StatusText := 'Chyba!';
end;
if (FStatus = csFinish) then SaveLastUpdate;
if (Assigned( OnStatusChange )) then OnStatusChange( Status , StatusText );
case FStatus of
csSendingInfo : SendInfo;
csAcceptSession : SendAcceptSession;
csFileOK : SaveFile;
end;
end;
//==============================================================================
// Events
//==============================================================================
procedure TMHDClient.Connect( Sender: TObject; Socket: TCustomWinSocket );
begin
Status := csConnecting;
end;
procedure TMHDClient.MyRead( Sender: TObject; Socket: TCustomWinSocket );
begin
case Status of
csConnecting : GetInfo;
csSendingInfo : GetSessionInfo;
csGettingFile : GetFile;
end;
end;
procedure TMHDClient.MyWrite( Sender: TObject; Socket: TCustomWinSocket );
begin
case Status of
csFileOK : SendFileOK;
end;
end;
procedure TMHDClient.Error( Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer );
begin
ErrorCode := 0;
Status := csTransferError;
end;
//==============================================================================
// Reading / Writing
//==============================================================================
procedure TMHDClient.GetInfo;
var Data : string;
begin
Data := Client.Socket.ReceiveText;
if (Data = 'CLIENTINFO') then Status := csSendingInfo
else Status := csTransferError;
end;
procedure TMHDClient.SendInfo;
var Data : string;
begin
Data := 'CLIENTINFOBEGIN';
Data := Data+CLIENTINFO.Name+'|';
Data := Data+CLIENTINFO.Company+'|';
Data := Data+CLIENTINFO.Serial+'|';
Data := Data+CLIENTINFO.LastUpdate+'|';
Data := Data+'CLIENTINFOEND';
Client.Socket.SendText( Data );
end;
procedure TMHDClient.GetSessionInfo;
var Data : string;
Zac, Kon : integer;
I : integer;
S : string;
begin
Status := csAcceptingSession;
Data := Client.Socket.ReceiveText;
if (Data = 'FINISH') then
begin
SessionInfo.NewUpdate := CLIENTINFO.LastUpdate;
Status := csFinish;
exit;
end;
Zac := Pos( 'SESSIONBEGIN' , Data );
Kon := Pos( 'SESSIONEND' , Data );
if (Zac = 0) or
(Kon = 0) then
begin
Status := csTransferError;
exit;
end;
try
I := Zac + Length( 'SESSIONBEGIN' );
S := '';
while Data[I] <> '|' do
begin
S := S + Data[I];
Inc( I );
end;
SessionInfo.Rozvrhy := StrToInt( S );
Inc( I );
S := '';
while Data[I] <> '|' do
begin
S := S + Data[I];
Inc( I );
end;
SessionInfo.Listky := StrToInt( S );
Inc( I );
S := '';
while Data[I] <> '|' do
begin
S := S + Data[I];
Inc( I );
end;
SessionInfo.Zastavky := StrToInt( S );
Inc( I );
S := '';
while Data[I] <> '|' do
begin
S := S + Data[I];
Inc( I );
end;
SessionInfo.NewUpdate := S;
except
Status := csTransferError;
exit;
end;
if (Assigned( OnSessionBegin )) then OnSessionBegin( SessionInfo );
Status := csAcceptSession;
end;
procedure TMHDClient.SendAcceptSession;
var Data : string;
begin
Data := 'SESSIONOK';
Client.Socket.SendText( Data );
LongFile := False;
LongData := '';
Status := csGettingFile;
end;
procedure TMHDClient.GetFile;
var Data : WideString;
Zac, Kon : integer;
I : integer;
FileType : string;
begin
Data := Client.Socket.ReceiveText;
if (Data = 'FINISH') then
begin
Status := csFinish;
exit;
end;
Zac := Pos( 'FILEBEGIN' , Data );
Kon := Pos( 'FILEEND' , Data );
if (Zac = 0) and
(not LongFile) then
begin
Status := csTransferError;
exit;
end;
if (Kon = 0) then
begin
LongFile := True;
LongData := LongData + Data;
exit;
end;
if (LongFile) then
begin
Data := LongData + Data;
LongFile := False;
end;
I := Length( 'FILEBEGIN' )+1;
FileType := '';
while Data[I] <> '|' do
begin
FileType := FileType + Data[I];
Inc( I );
end;
RecievedFile.FileType := ftNone;
if (FileType = 'rozvrh') then RecievedFile.FileType := ftRozvrh;
if (FileType = 'listok') then RecievedFile.FileType := ftListok;
if (FileType = 'zastavky') then RecievedFile.FileType := ftZastavky;
if (RecievedFile.FileType = ftNone) then
begin
Status := csTransferError;
exit;
end;
Delete( Data , Pos( 'FILEEND' , Data ) , Length( 'FILEEND' ) );
RecievedFile.Data := Copy( Data , I+1 , Length( Data ) );
Status := csFileOK;
end;
procedure TMHDClient.SaveRozvrh( Data : WideString );
var FileName : string;
I : integer;
F : textfile;
begin
I := Pos( '|' , Data );
FileName := Copy( Data , 1 , I-1 );
Delete( Data , 1 , I );
Delete( Data , Pos( '|' , Data ) , 1 );
AssignFile( F , ROZVRHY_DIR+'\'+FileName );
{$I-}
Rewrite( F );
{$I+}
if (IOResult <> 0) or
(Data = 'ERROR') then
begin
if (Assigned( OnItemChange )) then OnItemChange( 0 , ROZVRHY_DIR+'\'+FileName , 'ERROR' );
exit;
end;
Write( F , String( Data ) );
CloseFile( F );
if (Assigned( OnItemChange )) then OnItemChange( 0 , ROZVRHY_DIR+'\'+FileName , 'OK' );
end;
procedure TMHDClient.SaveListok( Data : WideString );
var Reg : TRegistry;
Min, Norm, Zlav : string;
I : integer;
begin
Min := '';
Norm := '';
Zlav := '';
I := 1;
while (Data[I] <> '|') do
begin
Min := Min + Data[I];
Inc( I );
end;
Inc( I );
while (Data[I] <> '|') do
begin
Norm := Norm + Data[I];
Inc( I );
end;
Inc( I );
while (Data[I] <> '|') do
begin
Zlav := Zlav + Data[I];
Inc( I );
end;
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKey( '\Software\MHDClient\Tickets\Default' , False );
Reg.WriteString( Min , Norm+';'+Zlav );
finally
Reg.Free;
end;
if (Assigned( OnItemChange )) then OnItemChange( 1 , 'Dĺka : '+Min+' Normálny : '+Norm+' Zžavnený : '+Zlav , 'OK' );
end;
procedure TMHDClient.SaveZastavky( Data : WideString );
var F : textfile;
begin
Delete( Data , Pos( '|' , Data ) , 1 );
AssignFile( F , ZASTAVKY_FILE );
{$I-}
Rewrite( F );
{$I+}
if (IOResult <> 0) or
(Data = 'ERROR') then
begin
if (Assigned( OnItemChange )) then OnItemChange( 2 , ZASTAVKY_FILE , 'ERROR' );
exit;
end;
Write( F , String( Data ) );
CloseFile( F );
if (Assigned( OnItemChange )) then OnItemChange( 2 , ZASTAVKY_FILE , 'OK' );
end;
procedure TMHDClient.SaveFile;
begin
case RecievedFile.FileType of
ftRozvrh : SaveRozvrh( RecievedFile.Data );
ftListok : SaveListok( RecievedFile.Data );
ftZastavky : SaveZastavky( RecievedFile.Data );
end;
Client.Socket.Write( Client.Socket.SocketHandle );
end;
procedure TMHDClient.SendFileOK;
var Data : string;
begin
Data := 'FILEOK';
Client.Socket.SendText( Data );
Status := csGettingFile;
end;
procedure TMHDClient.SaveLastUpdate;
begin
CLIENTINFO.LastUpdate := SessionInfo.NewUpdate;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSAzureTableRowDialog;
interface
uses
Vcl.Buttons, System.Classes, Vcl.Controls, DSAzureTableDialog, Vcl.ExtCtrls, Vcl.Forms, Vcl.Graphics,
Vcl.StdCtrls;
type
/// <summary>
/// Dialog for modifying a single cell of a single row in an Azure table. The table column passed
/// in contains the name of the column, the value for the column and its data type. If the column info
/// passed in is nil then this dialog assumes a new one is being created.
/// </summary>
TTAzureTableRowDialog = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Bevel1: TBevel;
nameField: TEdit;
valueField: TEdit;
datatypeCombo: TComboBox;
nameLabel: TLabel;
valueLabel: TLabel;
datatypeLabel: TLabel;
errorLabel: TLabel;
procedure datatypeComboChange(Sender: TObject);
procedure valueFieldChange(Sender: TObject);
procedure nameFieldChange(Sender: TObject);
private
FColumnInfo: TAzureTableColumn;
FRow: TAzureTableRow;
function IsAlphaNumeric(const Value: String; CantStartWithNumber: Boolean = False): Boolean;
function IsValidNameFormat: Boolean;
procedure UpdateOKButtonEnablement;
function GetName: String;
function GetValue: String;
function GetColumnDataType: TPropertyDataType;
public
/// <summary> Constructor which takes in an optional column and a required row. If the column given
/// is nil then a new one will be created when calling 'PersistChanges'.
/// </summary>
constructor Create(AOwner: TComponent; ColumnInfo: TAzureTableColumn; Row: TAzureTableRow); reintroduce;
/// <summary> Returns the given instance (or a new instance if none was provided) of TAzureTableColumn
/// which holds the new values specified by this dialog.
/// </summary>
function PersistChanges: TAzureTableColumn;
/// <summary> Returns the name as typed into the name field of the Dialog </summary>
property Name: String read GetName;
/// <summary> Returns the value as typed into the value field of the Dialog </summary>
property Value: String read GetValue;
/// <summary> Returns the datatype as chosen in the drop-down menu of the Dialog </summary>
property DataType: TPropertyDataType read GetColumnDataType;
end;
implementation
{$R *.dfm}
uses Data.DBXClientResStrs, System.SysUtils;
constructor TTAzureTableRowDialog.Create(AOwner: TComponent; ColumnInfo: TAzureTableColumn; Row: TAzureTableRow);
var
PartiallyEnabled: Boolean;
BeginIndex: Integer;
NameEvent: TNotifyEvent;
ValueEvent: TNotifyEvent;
begin
inherited Create(AOwner);
FColumnInfo := ColumnInfo;
Assert(Row <> nil);
FRow := Row;
if ColumnInfo <> nil then
begin
BeginIndex :=
datatypeCombo.Items.IndexOf(Copy(GetDataType(ColumnInfo.DataType), Length(DT_XML_PREFIX) + 1));
if BeginIndex < 0 then
BeginIndex := 0;
datatypeCombo.ItemIndex := BeginIndex;
NameEvent := nameField.OnChange;
ValueEvent := valueField.OnChange;
nameField.OnChange := nil;
valueField.OnChange := nil;
nameField.Text := ColumnInfo.Name;
valueField.Text := ColumnInfo.Value;
nameField.OnChange := NameEvent;
valueField.OnChange := ValueEvent;
PartiallyEnabled := (ColumnInfo.Name = XML_ROWKEY) or (ColumnInfo.Name = XML_PARTITION);
nameField.Enabled := not PartiallyEnabled;
datatypeCombo.Enabled := not PartiallyEnabled;
end
else
datatypeCombo.ItemIndex := 0;
end;
function TTAzureTableRowDialog.GetColumnDataType: TPropertyDataType;
begin
if (datatypeCombo.Text = EmptyStr) then
Exit(azdtUnknown);
Result := GetDataType(datatypeCombo.Text);
end;
function TTAzureTableRowDialog.GetName: String;
begin
Result := Trim(nameField.Text);
end;
function TTAzureTableRowDialog.GetValue: String;
begin
Result := valueField.Text;
end;
function TTAzureTableRowDialog.IsAlphaNumeric(const Value: String; CantStartWithNumber: Boolean): Boolean;
var
I: Integer;
Len: Integer;
c: Char;
begin
Result := True;
Len := Length(Value);
for I := 1 to Len do
begin
c := Value[I];
//can't start with number
if CantStartWithNumber and (I = 1) and CharInSet(c, ['0'..'9']) then
Exit(False);
if not CharInSet(c, ['0'..'9', 'A'..'Z', 'a'..'z', '_']) then
Exit(False);
end;
end;
function TTAzureTableRowDialog.IsValidNameFormat: Boolean;
var
Num: String;
begin
Result := True;
Num := Name;
//Name can't be empty
if Num = EmptyStr then
Exit(False)
//name must be only numbers, letters and '_'... and can't start with a number
else if not IsAlphaNumeric(Num, True) then
Exit(False)
end;
procedure TTAzureTableRowDialog.UpdateOKButtonEnablement;
begin
if (FColumnInfo <> nil) and (Name = FColumnInfo.Name) and
(Value = FColumnInfo.Value) and
(DataType = FColumnInfo.DataType) then
begin
OKBtn.Enabled := False;
errorLabel.Caption := EmptyStr;
end
else if (AnsiLowerCase(Name) = AnsiLowerCase(XML_TIMESTAMP)) or
(NameField.Enabled and ((AnsiLowerCase(Name) = AnsiLowerCase(XML_ROWKEY)) or
(AnsiLowerCase(Name) = AnsiLowerCase(XML_PARTITION)))) then
begin
OKBtn.Enabled := False;
errorLabel.Caption := SBadColumnName;
end
else if not ValidateValueForDataType(Value, DataType) then
begin
OKBtn.Enabled := False;
errorLabel.Caption := Format(SInvalidDataType, [dataTypeCombo.Text]);
end
else if not IsValidNameFormat then
begin
OKBtn.Enabled := False;
if Name = EmptyStr then
errorLabel.Caption := EmptyStr
else
errorLabel.Caption := SInvalidColumnName;
end
else
begin
//If it is possible the given name may conflict with another column name, verify this
if (FColumnInfo = nil) or ((FColumnInfo <> nil) and (Name <> FColumnInfo.Name)) then
begin
if FRow.GetColumn(Name, True) <> nil then
begin
OKBtn.Enabled := False;
errorLabel.Caption := SColumnNameInUse;
Exit;
end;
end;
OKBtn.Enabled := True;
errorLabel.Caption := EmptyStr;
end;
end;
procedure TTAzureTableRowDialog.nameFieldChange(Sender: TObject);
begin
UpdateOKButtonEnablement;
end;
function TTAzureTableRowDialog.PersistChanges: TAzureTableColumn;
begin
if FColumnInfo = nil then
FColumnInfo := TAzureTableColumn.Create;
FColumnInfo.Name := Name;
FColumnInfo.Value := Value;
FColumnInfo.DataType := DataType;
Result := FColumnInfo;
end;
procedure TTAzureTableRowDialog.datatypeComboChange(Sender: TObject);
begin
UpdateOKButtonEnablement;
end;
procedure TTAzureTableRowDialog.valueFieldChange(Sender: TObject);
begin
UpdateOKButtonEnablement;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXMetaDataProvider;
interface
uses
Data.DBXCommonTable,
Data.DBXMetaDataReader,
Data.DBXMetaDataWriter,
Data.DBXTypedTableStorage;
type
TDBXMetaDataColumn = class;
TDBXMetaDataTable = class;
TDBXSqlExecution = class;
TDBXMetaDataColumnArray = array of TDBXMetaDataColumn;
TDBXMetaDataColumn = class
public
constructor Create; overload;
constructor Create(const Column: TDBXMetaDataColumn); overload;
procedure CopyColumnToTableStorage(const Columns: TDBXColumnsTableStorage);
private
FColumnName: UnicodeString;
FDefaultValue: UnicodeString;
FDataType: Integer;
FPrecision: Integer;
FScale: Integer;
FMaxInline: Integer;
FUnsigned: Boolean;
FAutoIncrement: Boolean;
FNullable: Boolean;
FFixedLength: Boolean;
FUnicodeString: Boolean;
FBlob: Boolean;
public
property AutoIncrement: Boolean read FAutoIncrement write FAutoIncrement;
property ColumnName: UnicodeString read FColumnName write FColumnName;
property DefaultValue: UnicodeString read FDefaultValue write FDefaultValue;
property FixedLength: Boolean read FFixedLength write FFixedLength;
property MaxInline: Integer read FMaxInline write FMaxInline;
property Nullable: Boolean read FNullable write FNullable;
property Long: Boolean read FBlob write FBlob;
property Precision: Integer read FPrecision write FPrecision;
property Scale: Integer read FScale write FScale;
property DataType: Integer read FDataType write FDataType;
property UnicodeString: Boolean read FUnicodeString;
property UnicodeChar: Boolean write FUnicodeString;
property Unsigned: Boolean read FUnsigned write FUnsigned;
end;
TDBXInt8Column = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXInt64Column = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXInt32Column = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXInt16Column = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXDoubleColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXDecimalColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString; const InPrecision: Integer; const InScale: Integer);
end;
TDBXDateColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXBooleanColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXBinaryLongColumn = class(TDBXMetaDataColumn)
public
constructor Create(const Name: UnicodeString);
end;
TDBXBinaryColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString; const InPrecision: Integer);
end;
TDBXAnsiVarCharColumn = class(TDBXMetaDataColumn)
public
constructor Create(const Name: UnicodeString; const InPrecision: Integer);
end;
TDBXAnsiLongColumn = class(TDBXMetaDataColumn)
public
constructor Create(const Name: UnicodeString);
end;
TDBXAnsiCharColumn = class(TDBXMetaDataColumn)
public
constructor Create(const Name: UnicodeString; const InPrecision: Integer);
end;
TDBXMetaDataForeignKey = class
public
constructor Create; overload;
destructor Destroy; override;
constructor Create(const InForeignTableName: UnicodeString; const InPrimaryTableName: UnicodeString; const InForeignKeyName: UnicodeString; References: array of UnicodeString); overload;
procedure AddReference(const ColumnName: UnicodeString; const ColumnNameInPrimaryTable: UnicodeString);
protected
function GetForeignKeyColumnsStorage: TDBXForeignKeyColumnsTableStorage;
function GetCatalogName: UnicodeString;
procedure SetCatalogName(const CatalogName: UnicodeString);
function GetSchemaName: UnicodeString;
procedure SetSchemaName(const SchemaName: UnicodeString);
function GetTableName: UnicodeString;
procedure SetTableName(const TableName: UnicodeString);
function GetForeignKeyName: UnicodeString;
procedure SetForeignKeyName(const ForeignKeyName: UnicodeString);
private
FForeignkey: TDBXForeignKeysTableStorage;
FColumns: TDBXForeignKeyColumnsTableStorage;
FPrimaryCatalogName: UnicodeString;
FPrimarySchemaName: UnicodeString;
FPrimaryTableName: UnicodeString;
FColumnCount: Integer;
public
property ForeignKeysStorage: TDBXForeignKeysTableStorage read FForeignkey;
property ForeignKeyColumnsStorage: TDBXForeignKeyColumnsTableStorage read GetForeignKeyColumnsStorage;
property CatalogName: UnicodeString read GetCatalogName write SetCatalogName;
property SchemaName: UnicodeString read GetSchemaName write SetSchemaName;
property TableName: UnicodeString read GetTableName write SetTableName;
property ForeignKeyName: UnicodeString read GetForeignKeyName write SetForeignKeyName;
property PrimaryCatalogName: UnicodeString read FPrimaryCatalogName write FPrimaryCatalogName;
property PrimarySchemaName: UnicodeString read FPrimarySchemaName write FPrimarySchemaName;
property PrimaryTableName: UnicodeString read FPrimaryTableName write FPrimaryTableName;
end;
TDBXMetaDataIndex = class
public
constructor Create; overload;
destructor Destroy; override;
constructor Create(const InTableName: UnicodeString; const InIndexName: UnicodeString; Columns: array of UnicodeString); overload;
procedure AddColumn(const ColumnName: UnicodeString); overload;
procedure AddColumn(const ColumnName: UnicodeString; const Ascending: Boolean); overload;
protected
function GetCatalogName: UnicodeString;
procedure SetCatalogName(const CatalogName: UnicodeString);
function GetSchemaName: UnicodeString;
procedure SetSchemaName(const SchemaName: UnicodeString);
function GetTableName: UnicodeString;
procedure SetTableName(const TableName: UnicodeString);
function GetIndexName: UnicodeString;
procedure SetIndexName(const IndexName: UnicodeString);
function IsUnique: Boolean;
procedure SetUnique(const Unique: Boolean);
private
FIndexes: TDBXIndexesTableStorage;
FColumns: TDBXIndexColumnsTableStorage;
FColumnCount: Integer;
public
property IndexesStorage: TDBXIndexesTableStorage read FIndexes;
property IndexColumnsStorage: TDBXIndexColumnsTableStorage read FColumns;
property CatalogName: UnicodeString read GetCatalogName write SetCatalogName;
property SchemaName: UnicodeString read GetSchemaName write SetSchemaName;
property TableName: UnicodeString read GetTableName write SetTableName;
property IndexName: UnicodeString read GetIndexName write SetIndexName;
property Unique: Boolean read IsUnique write SetUnique;
end;
TDBXMetaDataProvider = class
public
constructor Create;
destructor Destroy; override;
function CheckColumnSupported(const Column: TDBXMetaDataColumn): Boolean;
procedure Execute(const Sql: UnicodeString);
procedure CreateTable(const Table: TDBXMetaDataTable);
function DropTable(const SchemaName: UnicodeString; const TableName: UnicodeString): Boolean; overload;
function DropTable(const TableName: UnicodeString): Boolean; overload;
procedure CreatePrimaryKey(const Index: TDBXMetaDataIndex);
procedure CreateUniqueIndex(const Index: TDBXMetaDataIndex);
procedure CreateIndex(const Index: TDBXMetaDataIndex);
function DropIndex(const TableName: UnicodeString; const IndexName: UnicodeString): Boolean; overload;
function DropIndex(const SchemaName: UnicodeString; const TableName: UnicodeString; const IndexName: UnicodeString): Boolean; overload;
procedure CreateForeignKey(const Foreignkey: TDBXMetaDataForeignKey);
function DropForeignKey(const TableName: UnicodeString; const ForeignKey: UnicodeString): Boolean; overload;
function DropForeignKey(const SchemaName: UnicodeString; const TableName: UnicodeString; const ForeignKey: UnicodeString): Boolean; overload;
function QuoteIdentifierIfNeeded(const Identifier: UnicodeString): UnicodeString;
function GetCollection(const MetaDataCommand: UnicodeString): TDBXTable;
procedure ToMemoryStorage(const Table: TDBXDelegateTable);
function MakeCreateTableSql(const Table: TDBXTablesTableStorage; const Columns: TDBXColumnsTableStorage): UnicodeString;
function MakeAlterTableSql(const Table: TDBXTablesTableStorage; const Columns: TDBXColumnsTableStorage): UnicodeString; overload;
function MakeDropTableSql(const Table: TDBXTablesTableStorage): UnicodeString;
function MakeCreateIndexSql(const Indexes: TDBXIndexesTableStorage; const Columns: TDBXIndexColumnsTableStorage): UnicodeString;
function MakeDropIndexSql(const Indexes: TDBXIndexesTableStorage): UnicodeString;
function MakeCreateForeignKeySql(const ForeignKeys: TDBXForeignKeysTableStorage; const Columns: TDBXForeignKeyColumnsTableStorage): UnicodeString;
function MakeDropForeignKeySql(const ForeignKey: TDBXForeignKeysTableStorage): UnicodeString;
function MakeAlterTableSql(const Indexes: TDBXIndexesTableStorage; const Columns: TDBXIndexColumnsTableStorage): UnicodeString; overload;
function IsCatalogsSupported: Boolean;
function IsSchemasSupported: Boolean;
function IsMultipleStatementsSupported: Boolean;
function IsDescendingIndexSupported: Boolean;
function IsDescendingIndexColumnsSupported: Boolean;
function IsMixedDDLAndDMLSupported: Boolean;
function IsDDLTransactionsSupported: Boolean;
protected
procedure SetWriter(const Writer: TDBXMetaDataWriter); virtual;
function GetWriter: TDBXMetaDataWriter; virtual;
function GetVendor: UnicodeString;
function GetDatabaseProduct: UnicodeString;
function GetDatabaseVersion: UnicodeString;
function GetIdentifierQuotePrefix: UnicodeString;
function GetIdentifierQuoteSuffix: UnicodeString;
private
FWriter: TDBXMetaDataWriter;
FExecuter: TDBXSqlExecution;
public
property Vendor: UnicodeString read GetVendor;
property DatabaseProduct: UnicodeString read GetDatabaseProduct;
property DatabaseVersion: UnicodeString read GetDatabaseVersion;
property IdentifierQuotePrefix: UnicodeString read GetIdentifierQuotePrefix;
property IdentifierQuoteSuffix: UnicodeString read GetIdentifierQuoteSuffix;
protected
property Writer: TDBXMetaDataWriter read GetWriter write SetWriter;
end;
TDBXMetaDataTable = class
public
constructor Create;
destructor Destroy; override;
procedure AddColumn(const Column: TDBXMetaDataColumn);
function GetColumn(const Ordinal: Integer): TDBXMetaDataColumn;
protected
function GetCatalogName: UnicodeString;
procedure SetCatalogName(const CatalogName: UnicodeString);
function GetSchemaName: UnicodeString;
procedure SetSchemaName(const SchemaName: UnicodeString);
function GetTableName: UnicodeString;
procedure SetTableName(const TableName: UnicodeString);
private
FTable: TDBXTablesTableStorage;
FColumns: TDBXColumnsTableStorage;
FColumnCount: Integer;
FMetaDataColumns: TDBXMetaDataColumnArray;
public
property TableStorage: TDBXTablesTableStorage read FTable;
property ColumnsStorage: TDBXColumnsTableStorage read FColumns;
property CatalogName: UnicodeString read GetCatalogName write SetCatalogName;
property SchemaName: UnicodeString read GetSchemaName write SetSchemaName;
property TableName: UnicodeString read GetTableName write SetTableName;
end;
TDBXObjectColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXProductNames = class
public
const DatasnapProduct = 'Datasnap';
const Db2_Product = 'Db2';
const FirebirdProduct = 'Firebird';
const InformixProduct = 'Informix Dynamic Server';
const InterbaseProduct = 'InterBase';
const MsSqlProduct = 'Microsoft SQL Server';
const MySqlProduct = 'MySQL';
const OracleProduct = 'Oracle';
const SybaseAsaProduct = 'Adaptive Server Anywhere';
const SybaseAseProduct = 'Sybase SQL Server';
end;
TDBXSingleColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXSqlExecution = class
public
constructor Create(const Writer: TDBXMetaDataWriter);
procedure Execute(const Sql: UnicodeString); virtual;
private
FContext: TDBXProviderContext;
end;
TDBXTimeColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXTimestampColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXUInt16Column = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXUInt32Column = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXUInt64Column = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXUInt8Column = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString);
end;
TDBXUnicodeCharColumn = class(TDBXMetaDataColumn)
public
constructor Create(const Name: UnicodeString; const InPrecision: Integer);
end;
TDBXUnicodeLongColumn = class(TDBXMetaDataColumn)
public
constructor Create(const Name: UnicodeString);
end;
TDBXUnicodeVarCharColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString; const InPrecision: Integer);
end;
TDBXVarBinaryColumn = class(TDBXMetaDataColumn)
public
constructor Create(const InName: UnicodeString; const InPrecision: Integer);
end;
TDBXWideVarCharColumn = class(TDBXMetaDataColumn)
public
constructor Create(const Name: UnicodeString; const InPrecision: Integer);
end;
implementation
uses
Data.DBXCommon,
Data.DBXPlatform,
Data.DBXMetaDataNames,
Data.DBXTableFactory,
System.SysUtils;
constructor TDBXMetaDataColumn.Create;
begin
inherited Create;
FNullable := True;
end;
constructor TDBXMetaDataColumn.Create(const Column: TDBXMetaDataColumn);
begin
inherited Create;
self.FColumnName := Column.FColumnName;
self.FDefaultValue := Column.FDefaultValue;
self.FDataType := Column.FDataType;
self.FPrecision := Column.FPrecision;
self.FScale := Column.FScale;
self.FMaxInline := Column.FMaxInline;
self.FUnsigned := Column.FUnsigned;
self.FAutoIncrement := Column.FAutoIncrement;
self.FNullable := Column.FNullable;
self.FFixedLength := Column.FFixedLength;
self.FUnicodeString := Column.FUnicodeString;
self.FBlob := Column.FBlob;
end;
procedure TDBXMetaDataColumn.CopyColumnToTableStorage(const Columns: TDBXColumnsTableStorage);
begin
Columns.ColumnName := FColumnName;
Columns.Precision := FPrecision;
Columns.Scale := FScale;
Columns.DefaultValue := FDefaultValue;
Columns.Long := FBlob;
Columns.Nullable := FNullable;
Columns.AutoIncrement := FAutoIncrement;
Columns.MaxInline := FMaxInline;
Columns.DbxDataType := FDataType;
Columns.FixedLength := FFixedLength;
Columns.Unicode := FUnicodeString;
Columns.Unsigned := FUnsigned;
end;
constructor TDBXInt8Column.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.Int8Type;
ColumnName := InName;
end;
constructor TDBXInt64Column.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.Int64Type;
ColumnName := InName;
end;
constructor TDBXInt32Column.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.Int32Type;
ColumnName := InName;
end;
constructor TDBXInt16Column.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.Int16Type;
ColumnName := InName;
end;
constructor TDBXDoubleColumn.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.DoubleType;
ColumnName := InName;
end;
constructor TDBXDecimalColumn.Create(const InName: UnicodeString; const InPrecision: Integer; const InScale: Integer);
begin
inherited Create;
DataType := TDBXDataTypes.BcdType;
ColumnName := InName;
Precision := InPrecision;
Scale := InScale;
end;
constructor TDBXDateColumn.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.DateType;
ColumnName := InName;
end;
constructor TDBXBooleanColumn.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.BooleanType;
ColumnName := InName;
end;
constructor TDBXBinaryLongColumn.Create(const Name: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.BlobType;
Long := True;
ColumnName := Name;
Precision := 80000;
end;
constructor TDBXBinaryColumn.Create(const InName: UnicodeString; const InPrecision: Integer);
begin
inherited Create;
DataType := TDBXDataTypes.BytesType;
FixedLength := True;
ColumnName := InName;
Precision := InPrecision;
FixedLength := True;
end;
constructor TDBXAnsiVarCharColumn.Create(const Name: UnicodeString; const InPrecision: Integer);
begin
inherited Create;
DataType := TDBXDataTypes.AnsiStringType;
Long := False;
FixedLength := False;
ColumnName := Name;
Precision := InPrecision;
end;
constructor TDBXAnsiLongColumn.Create(const Name: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.AnsiStringType;
Long := True;
ColumnName := Name;
Precision := 80000;
end;
constructor TDBXAnsiCharColumn.Create(const Name: UnicodeString; const InPrecision: Integer);
begin
inherited Create;
DataType := TDBXDataTypes.AnsiStringType;
Long := False;
FixedLength := True;
ColumnName := Name;
Precision := InPrecision;
end;
constructor TDBXMetaDataForeignKey.Create;
begin
inherited Create;
FForeignkey := TDBXForeignKeysTableStorage.Create;
FColumns := TDBXForeignKeyColumnsTableStorage.Create;
FForeignkey.Insert;
FForeignkey.Post;
end;
destructor TDBXMetaDataForeignKey.Destroy;
begin
FreeAndNil(FForeignkey);
FreeAndNil(FColumns);
inherited Destroy;
end;
constructor TDBXMetaDataForeignKey.Create(const InForeignTableName: UnicodeString; const InPrimaryTableName: UnicodeString; const InForeignKeyName: UnicodeString; References: array of UnicodeString);
var
Index: Integer;
begin
Create;
TableName := InForeignTableName;
PrimaryTableName := InPrimaryTableName;
ForeignKeyName := InForeignKeyName;
Index := 0;
while Index < Length(References) do
begin
AddReference(References[Index], References[Index + 1]);
Index := Index + 2;
end;
end;
function TDBXMetaDataForeignKey.GetForeignKeyColumnsStorage: TDBXForeignKeyColumnsTableStorage;
begin
FColumns.First;
while FColumns.InBounds do
begin
FColumns.PrimaryCatalogName := FPrimaryCatalogName;
FColumns.PrimarySchemaName := FPrimarySchemaName;
FColumns.PrimaryTableName := FPrimaryTableName;
FColumns.Next;
end;
Result := FColumns;
end;
function TDBXMetaDataForeignKey.GetCatalogName: UnicodeString;
begin
Result := FForeignkey.CatalogName;
end;
procedure TDBXMetaDataForeignKey.SetCatalogName(const CatalogName: UnicodeString);
begin
FForeignkey.CatalogName := CatalogName;
end;
function TDBXMetaDataForeignKey.GetSchemaName: UnicodeString;
begin
Result := FForeignkey.SchemaName;
end;
procedure TDBXMetaDataForeignKey.SetSchemaName(const SchemaName: UnicodeString);
begin
FForeignkey.SchemaName := SchemaName;
end;
function TDBXMetaDataForeignKey.GetTableName: UnicodeString;
begin
Result := FForeignkey.TableName;
end;
procedure TDBXMetaDataForeignKey.SetTableName(const TableName: UnicodeString);
begin
FForeignkey.TableName := TableName;
end;
function TDBXMetaDataForeignKey.GetForeignKeyName: UnicodeString;
begin
Result := FForeignkey.ForeignKeyName;
end;
procedure TDBXMetaDataForeignKey.SetForeignKeyName(const ForeignKeyName: UnicodeString);
begin
FForeignkey.ForeignKeyName := ForeignKeyName;
end;
procedure TDBXMetaDataForeignKey.AddReference(const ColumnName: UnicodeString; const ColumnNameInPrimaryTable: UnicodeString);
begin
IncrAfter(FColumnCount);
FColumns.Insert;
FColumns.ColumnOrdinal := FColumnCount;
FColumns.ColumnName := ColumnName;
FColumns.PrimaryColumnName := ColumnNameInPrimaryTable;
FColumns.Post;
end;
constructor TDBXMetaDataIndex.Create;
begin
inherited Create;
FIndexes := TDBXIndexesTableStorage.Create;
FColumns := TDBXIndexColumnsTableStorage.Create;
FIndexes.Insert;
FIndexes.Post;
end;
destructor TDBXMetaDataIndex.Destroy;
begin
FreeAndNil(FIndexes);
FreeAndNil(FColumns);
inherited Destroy;
end;
constructor TDBXMetaDataIndex.Create(const InTableName: UnicodeString; const InIndexName: UnicodeString; Columns: array of UnicodeString);
var
Index: Integer;
begin
Create;
TableName := InTableName;
IndexName := InIndexName;
for Index := 0 to Length(Columns) - 1 do
AddColumn(Columns[Index]);
end;
function TDBXMetaDataIndex.GetCatalogName: UnicodeString;
begin
Result := FIndexes.CatalogName;
end;
procedure TDBXMetaDataIndex.SetCatalogName(const CatalogName: UnicodeString);
begin
FIndexes.CatalogName := CatalogName;
end;
function TDBXMetaDataIndex.GetSchemaName: UnicodeString;
begin
Result := FIndexes.SchemaName;
end;
procedure TDBXMetaDataIndex.SetSchemaName(const SchemaName: UnicodeString);
begin
FIndexes.SchemaName := SchemaName;
end;
function TDBXMetaDataIndex.GetTableName: UnicodeString;
begin
Result := FIndexes.TableName;
end;
procedure TDBXMetaDataIndex.SetTableName(const TableName: UnicodeString);
begin
FIndexes.TableName := TableName;
end;
function TDBXMetaDataIndex.GetIndexName: UnicodeString;
begin
Result := FIndexes.IndexName;
end;
procedure TDBXMetaDataIndex.SetIndexName(const IndexName: UnicodeString);
begin
FIndexes.IndexName := IndexName;
end;
function TDBXMetaDataIndex.IsUnique: Boolean;
begin
Result := FIndexes.Unique;
end;
procedure TDBXMetaDataIndex.SetUnique(const Unique: Boolean);
begin
FIndexes.Unique := Unique;
end;
procedure TDBXMetaDataIndex.AddColumn(const ColumnName: UnicodeString);
begin
AddColumn(ColumnName, True);
end;
procedure TDBXMetaDataIndex.AddColumn(const ColumnName: UnicodeString; const Ascending: Boolean);
begin
IncrAfter(FColumnCount);
FColumns.Insert;
FColumns.ColumnOrdinal := FColumnCount;
FColumns.ColumnName := ColumnName;
FColumns.Ascending := Ascending;
FColumns.Post;
end;
constructor TDBXMetaDataProvider.Create;
begin
inherited Create;
end;
destructor TDBXMetaDataProvider.Destroy;
begin
FreeAndNil(FExecuter);
FreeAndNil(FWriter);
inherited Destroy;
end;
procedure TDBXMetaDataProvider.SetWriter(const Writer: TDBXMetaDataWriter);
begin
self.FWriter := Writer;
self.FExecuter := TDBXSqlExecution.Create(Writer);
end;
function TDBXMetaDataProvider.GetWriter: TDBXMetaDataWriter;
begin
Result := self.FWriter;
end;
function TDBXMetaDataProvider.GetVendor: UnicodeString;
begin
Result := FWriter.MetaDataReader.ProductName;
end;
function TDBXMetaDataProvider.CheckColumnSupported(const Column: TDBXMetaDataColumn): Boolean;
var
Storage: TDBXColumnsTableStorage;
Supported: Boolean;
begin
Storage := TDBXColumnsTableStorage.Create;
try
Storage.Insert;
Column.CopyColumnToTableStorage(Storage);
Storage.Post;
Supported := FWriter.CheckColumnSupported(Storage);
finally
FreeAndNil(Storage);
end;
Result := Supported;
end;
procedure TDBXMetaDataProvider.Execute(const Sql: UnicodeString);
begin
FExecuter.Execute(Sql);
end;
procedure TDBXMetaDataProvider.CreateTable(const Table: TDBXMetaDataTable);
var
Sql: UnicodeString;
begin
Sql := MakeCreateTableSql(Table.TableStorage, Table.ColumnsStorage);
FExecuter.Execute(Sql);
end;
function TDBXMetaDataProvider.DropTable(const SchemaName: UnicodeString; const TableName: UnicodeString): Boolean;
var
Storage: TDBXTable;
Builder: TDBXStringBuffer;
Success: Boolean;
Tables: TDBXTablesTableStorage;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
Success := False;
Builder.Append('GetTables ');
if not StringIsNil(SchemaName) then
begin
FWriter.MakeSqlIdentifier(Builder, SchemaName);
Builder.Append('.');
end;
FWriter.MakeSqlIdentifier(Builder, TableName);
Storage := GetCollection(Builder.ToString);
try
Tables := TDBXTablesTableStorage(Storage);
ToMemoryStorage(Tables);
if Tables.First and not Tables.Next then
begin
if Tables.First then
begin
Sql := MakeDropTableSql(Tables);
Execute(Sql);
Success := True;
end;
end;
Result := Success;
finally
Storage.Free;
end;
finally
Builder.Free;
end;
end;
function TDBXMetaDataProvider.DropTable(const TableName: UnicodeString): Boolean;
begin
Result := DropTable(NullString, TableName);
end;
procedure TDBXMetaDataProvider.CreatePrimaryKey(const Index: TDBXMetaDataIndex);
var
Indexes: TDBXIndexesTableStorage;
begin
Index.Unique := True;
Indexes := Index.IndexesStorage;
Indexes.Primary := True;
CreateIndex(Index);
end;
procedure TDBXMetaDataProvider.CreateUniqueIndex(const Index: TDBXMetaDataIndex);
begin
Index.Unique := True;
CreateIndex(Index);
end;
procedure TDBXMetaDataProvider.CreateIndex(const Index: TDBXMetaDataIndex);
var
Sql: UnicodeString;
begin
Sql := MakeCreateIndexSql(Index.IndexesStorage, Index.IndexColumnsStorage);
FExecuter.Execute(Sql);
end;
function TDBXMetaDataProvider.DropIndex(const TableName: UnicodeString; const IndexName: UnicodeString): Boolean;
begin
Result := DropIndex(NullString, TableName, IndexName);
end;
function TDBXMetaDataProvider.DropIndex(const SchemaName: UnicodeString; const TableName: UnicodeString; const IndexName: UnicodeString): Boolean;
var
Storage: TDBXTable;
Builder: TDBXStringBuffer;
Success: Boolean;
Indexes: TDBXIndexesTableStorage;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
Success := False;
Builder.Append('GetIndexes ');
if not StringIsNil(SchemaName) then
begin
FWriter.MakeSqlIdentifier(Builder, SchemaName);
Builder.Append('.');
end;
FWriter.MakeSqlIdentifier(Builder, TableName);
Storage := GetCollection(Builder.ToString);
try
Indexes := TDBXIndexesTableStorage(Storage);
ToMemoryStorage(Indexes);
Indexes.First;
while Indexes.InBounds do
begin
if (not StringIsNil(IndexName)) and (IndexName = Indexes.IndexName) then
begin
Sql := MakeDropIndexSql(Indexes);
Execute(Sql);
Success := True;
end;
Indexes.Next;
end;
Result := Success;
finally
Storage.Free;
end;
finally
Builder.Free;
end;
end;
procedure TDBXMetaDataProvider.CreateForeignKey(const Foreignkey: TDBXMetaDataForeignKey);
var
Sql: UnicodeString;
begin
Sql := MakeCreateForeignKeySql(Foreignkey.ForeignKeysStorage, Foreignkey.ForeignKeyColumnsStorage);
FExecuter.Execute(Sql);
end;
function TDBXMetaDataProvider.DropForeignKey(const TableName: UnicodeString; const ForeignKey: UnicodeString): Boolean;
begin
Result := DropForeignKey(NullString, TableName, ForeignKey);
end;
function TDBXMetaDataProvider.DropForeignKey(const SchemaName: UnicodeString; const TableName: UnicodeString; const ForeignKey: UnicodeString): Boolean;
var
Storage: TDBXTable;
Builder: TDBXStringBuffer;
Success: Boolean;
ForeignKeys: TDBXForeignKeysTableStorage;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
Success := False;
Builder.Append('GetForeignKeys ');
if not StringIsNil(SchemaName) then
begin
FWriter.MakeSqlIdentifier(Builder, SchemaName);
Builder.Append('.');
end;
FWriter.MakeSqlIdentifier(Builder, TableName);
Storage := GetCollection(Builder.ToString);
try
ForeignKeys := TDBXForeignKeysTableStorage(Storage);
ToMemoryStorage(ForeignKeys);
if (not StringIsNil(ForeignKey)) or (ForeignKeys.First and not ForeignKeys.Next) then
begin
ForeignKeys.First;
while ForeignKeys.InBounds do
begin
if (StringIsNil(ForeignKey)) or (ForeignKey = ForeignKeys.ForeignKeyName) then
begin
Sql := MakeDropForeignKeySql(ForeignKeys);
Execute(Sql);
Success := True;
end;
ForeignKeys.Next;
end;
end;
Result := Success;
finally
Storage.Free;
end;
finally
Builder.Free;
end;
end;
function TDBXMetaDataProvider.QuoteIdentifierIfNeeded(const Identifier: UnicodeString): UnicodeString;
var
Builder: TDBXStringBuffer;
Id: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
FWriter.MakeSqlIdentifier(Builder, Identifier);
Id := Builder.ToString;
finally
FreeAndNil(Builder);
end;
Result := Id;
end;
function TDBXMetaDataProvider.GetCollection(const MetaDataCommand: UnicodeString): TDBXTable;
var
Table: TDBXTable;
Name: UnicodeString;
begin
Table := FWriter.MetaDataReader.FetchCollection(MetaDataCommand);
if Table = nil then
Exit(nil);
Name := Table.DBXTableName;
if (Name = TDBXMetaDataCollectionName.DataTypes) then
Exit(TDBXDataTypesTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Catalogs) then
Exit(TDBXCatalogsTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Schemas) then
Exit(TDBXSchemasTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Tables) then
Exit(TDBXTablesTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Views) then
Exit(TDBXViewsTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Synonyms) then
Exit(TDBXSynonymsTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Columns) then
Exit(TDBXColumnsTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Indexes) then
Exit(TDBXIndexesTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.IndexColumns) then
Exit(TDBXIndexColumnsTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.ForeignKeys) then
Exit(TDBXForeignKeysTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.ForeignKeyColumns) then
Exit(TDBXForeignKeyColumnsTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Procedures) then
Exit(TDBXProceduresTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.ProcedureSources) then
Exit(TDBXProcedureSourcesTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.ProcedureParameters) then
Exit(TDBXProcedureParametersTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Packages) then
Exit(TDBXPackagesTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.PackageSources) then
Exit(TDBXPackageSourcesTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Users) then
Exit(TDBXUsersTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.Roles) then
Exit(TDBXRolesTableStorage.Create(Table));
if (Name = TDBXMetaDataCollectionName.ReservedWords) then
Exit(TDBXReservedWordsTableStorage.Create(Table));
Result := nil;
end;
procedure TDBXMetaDataProvider.ToMemoryStorage(const Table: TDBXDelegateTable);
var
Storage: TDBXTable;
begin
if Table.Storage = nil then
begin
Storage := TDBXTableFactory.CreateDBXTable;
Storage.DBXTableName := Table.DBXTableName;
Storage.Columns := Table.CopyColumns;
Storage.CopyFrom(Table);
Storage.AcceptChanges;
Storage := Table.ReplaceStorage(Storage);
Storage.Close;
FreeAndNil(Storage);
end;
end;
function TDBXMetaDataProvider.MakeCreateTableSql(const Table: TDBXTablesTableStorage; const Columns: TDBXColumnsTableStorage): UnicodeString;
var
Builder: TDBXStringBuffer;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
FWriter.MakeSqlCreate(Builder, Table, Columns);
Sql := Builder.ToString;
finally
FreeAndNil(Builder);
end;
Result := Sql;
end;
function TDBXMetaDataProvider.MakeAlterTableSql(const Table: TDBXTablesTableStorage; const Columns: TDBXColumnsTableStorage): UnicodeString;
var
Builder: TDBXStringBuffer;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
FWriter.MakeSqlAlter(Builder, Table, Columns);
Sql := Builder.ToString;
finally
FreeAndNil(Builder);
end;
Result := Sql;
end;
function TDBXMetaDataProvider.MakeDropTableSql(const Table: TDBXTablesTableStorage): UnicodeString;
var
Builder: TDBXStringBuffer;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
FWriter.MakeSqlDrop(Builder, Table);
Sql := Builder.ToString;
finally
FreeAndNil(Builder);
end;
Result := Sql;
end;
function TDBXMetaDataProvider.MakeCreateIndexSql(const Indexes: TDBXIndexesTableStorage; const Columns: TDBXIndexColumnsTableStorage): UnicodeString;
var
Builder: TDBXStringBuffer;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
FWriter.MakeSqlCreate(Builder, Indexes, Columns);
Sql := Builder.ToString;
finally
FreeAndNil(Builder);
end;
Result := Sql;
end;
function TDBXMetaDataProvider.MakeDropIndexSql(const Indexes: TDBXIndexesTableStorage): UnicodeString;
var
Builder: TDBXStringBuffer;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
FWriter.MakeSqlDrop(Builder, Indexes);
Sql := Builder.ToString;
finally
FreeAndNil(Builder);
end;
Result := Sql;
end;
function TDBXMetaDataProvider.MakeCreateForeignKeySql(const ForeignKeys: TDBXForeignKeysTableStorage; const Columns: TDBXForeignKeyColumnsTableStorage): UnicodeString;
var
Builder: TDBXStringBuffer;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
FWriter.MakeSqlCreate(Builder, ForeignKeys, Columns);
Sql := Builder.ToString;
finally
FreeAndNil(Builder);
end;
Result := Sql;
end;
function TDBXMetaDataProvider.MakeDropForeignKeySql(const ForeignKey: TDBXForeignKeysTableStorage): UnicodeString;
var
Builder: TDBXStringBuffer;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
FWriter.MakeSqlDrop(Builder, ForeignKey);
Sql := Builder.ToString;
finally
FreeAndNil(Builder);
end;
Result := Sql;
end;
function TDBXMetaDataProvider.MakeAlterTableSql(const Indexes: TDBXIndexesTableStorage; const Columns: TDBXIndexColumnsTableStorage): UnicodeString;
var
Builder: TDBXStringBuffer;
Sql: UnicodeString;
begin
Builder := TDBXStringBuffer.Create;
try
FWriter.MakeSqlAlter(Builder, Indexes, Columns);
Sql := Builder.ToString;
finally
FreeAndNil(Builder);
end;
Result := Sql;
end;
function TDBXMetaDataProvider.GetDatabaseProduct: UnicodeString;
begin
Result := FWriter.MetaDataReader.ProductName;
end;
function TDBXMetaDataProvider.GetDatabaseVersion: UnicodeString;
begin
Result := FWriter.MetaDataReader.Version;
end;
function TDBXMetaDataProvider.GetIdentifierQuotePrefix: UnicodeString;
begin
Result := FWriter.MetaDataReader.SqlIdentifierQuotePrefix;
end;
function TDBXMetaDataProvider.GetIdentifierQuoteSuffix: UnicodeString;
begin
Result := FWriter.MetaDataReader.SqlIdentifierQuoteSuffix;
end;
function TDBXMetaDataProvider.IsCatalogsSupported: Boolean;
begin
Result := FWriter.CatalogsSupported;
end;
function TDBXMetaDataProvider.IsSchemasSupported: Boolean;
begin
Result := FWriter.SchemasSupported;
end;
function TDBXMetaDataProvider.IsMultipleStatementsSupported: Boolean;
begin
Result := FWriter.MultipleStatementsSupported;
end;
function TDBXMetaDataProvider.IsDescendingIndexSupported: Boolean;
begin
Result := FWriter.MetaDataReader.DescendingIndexSupported;
end;
function TDBXMetaDataProvider.IsDescendingIndexColumnsSupported: Boolean;
begin
Result := FWriter.MetaDataReader.DescendingIndexColumnsSupported;
end;
function TDBXMetaDataProvider.IsMixedDDLAndDMLSupported: Boolean;
begin
Result := FWriter.Mixed_DDL_DML_Supported;
end;
function TDBXMetaDataProvider.IsDDLTransactionsSupported: Boolean;
begin
Result := FWriter.DDLTransactionsSupported;
end;
constructor TDBXMetaDataTable.Create;
begin
inherited Create;
FTable := TDBXTablesTableStorage.Create;
FColumns := TDBXColumnsTableStorage.Create;
FTable.Insert;
FTable.Post;
end;
destructor TDBXMetaDataTable.Destroy;
var
Index: Integer;
begin
if FMetaDataColumns <> nil then
for Index := 0 to Length(FMetaDataColumns) - 1 do
FreeAndNil(FMetaDataColumns[Index]);
FMetaDataColumns := nil;
FreeAndNil(FTable);
FreeAndNil(FColumns);
inherited Destroy;
end;
function TDBXMetaDataTable.GetCatalogName: UnicodeString;
begin
Result := FTable.CatalogName;
end;
procedure TDBXMetaDataTable.SetCatalogName(const CatalogName: UnicodeString);
begin
FTable.CatalogName := CatalogName;
end;
function TDBXMetaDataTable.GetSchemaName: UnicodeString;
begin
Result := FTable.SchemaName;
end;
procedure TDBXMetaDataTable.SetSchemaName(const SchemaName: UnicodeString);
begin
FTable.SchemaName := SchemaName;
end;
function TDBXMetaDataTable.GetTableName: UnicodeString;
begin
Result := FTable.TableName;
end;
procedure TDBXMetaDataTable.SetTableName(const TableName: UnicodeString);
begin
FTable.TableName := TableName;
end;
procedure TDBXMetaDataTable.AddColumn(const Column: TDBXMetaDataColumn);
var
Temp: TDBXMetaDataColumnArray;
Index: Integer;
begin
FColumns.Insert;
Inc(FColumnCount);
FColumns.ColumnOrdinal := FColumnCount;
Column.CopyColumnToTableStorage(FColumns);
FColumns.Post;
if FColumns = nil then
SetLength(FMetaDataColumns,1)
else
begin
SetLength(Temp,Length(FMetaDataColumns) + 1);
for Index := 0 to Length(FMetaDataColumns) - 1 do
Temp[Index] := FMetaDataColumns[Index];
FMetaDataColumns := Temp;
end;
FMetaDataColumns[Length(FMetaDataColumns) - 1] := Column;
end;
function TDBXMetaDataTable.GetColumn(const Ordinal: Integer): TDBXMetaDataColumn;
begin
if FMetaDataColumns = nil then
Exit(nil);
Result := FMetaDataColumns[Ordinal];
end;
constructor TDBXObjectColumn.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.ObjectType;
ColumnName := InName;
end;
constructor TDBXSingleColumn.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.SingleType;
ColumnName := InName;
end;
constructor TDBXSqlExecution.Create(const Writer: TDBXMetaDataWriter);
begin
inherited Create;
self.FContext := Writer.Context;
end;
procedure TDBXSqlExecution.Execute(const Sql: UnicodeString);
var
Statement: UnicodeString;
Start: Integer;
Index: Integer;
Storage: TDBXTable;
begin
Statement := NullString;
Start := 0;
Index := StringIndexOf(Sql,';');
while Index >= 0 do
begin
Statement := Copy(Sql,Start+1,Index-(Start));
Statement := Trim(Statement);
if Length(Statement) > 0 then
begin
Storage := FContext.ExecuteQuery(Statement, nil, nil);
FreeAndNil(Storage);
end;
Start := Index + 1;
Index := StringIndexOf(Sql,';',Start);
end;
Statement := Copy(Sql,Start+1,Length(Sql)-(Start));
Statement := Trim(Statement);
if Length(Statement) > 0 then
FContext.ExecuteQuery(Statement, nil, nil);
end;
constructor TDBXTimeColumn.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.TimeType;
ColumnName := InName;
end;
constructor TDBXTimestampColumn.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.TimeStampType;
ColumnName := InName;
end;
constructor TDBXUInt16Column.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.UInt16Type;
ColumnName := InName;
Unsigned := True;
end;
constructor TDBXUInt32Column.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.UInt32Type;
ColumnName := InName;
Unsigned := True;
end;
constructor TDBXUInt64Column.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.UInt64Type;
ColumnName := InName;
Unsigned := True;
end;
constructor TDBXUInt8Column.Create(const InName: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.UInt8Type;
ColumnName := InName;
Unsigned := True;
end;
constructor TDBXUnicodeCharColumn.Create(const Name: UnicodeString; const InPrecision: Integer);
begin
inherited Create;
DataType := TDBXDataTypes.WideStringType;
Long := False;
FixedLength := True;
ColumnName := Name;
UnicodeChar := True;
Precision := InPrecision;
end;
constructor TDBXUnicodeLongColumn.Create(const Name: UnicodeString);
begin
inherited Create;
DataType := TDBXDataTypes.WideStringType;
Long := True;
UnicodeChar := True;
ColumnName := Name;
Precision := 80000;
end;
constructor TDBXUnicodeVarCharColumn.Create(const InName: UnicodeString; const InPrecision: Integer);
begin
inherited Create;
DataType := TDBXDataTypes.WideStringType;
Long := False;
FixedLength := False;
ColumnName := InName;
UnicodeChar := True;
Precision := InPrecision;
end;
constructor TDBXVarBinaryColumn.Create(const InName: UnicodeString; const InPrecision: Integer);
begin
inherited Create;
DataType := TDBXDataTypes.VarBytesType;
ColumnName := InName;
Precision := InPrecision;
end;
constructor TDBXWideVarCharColumn.Create(const Name: UnicodeString; const InPrecision: Integer);
begin
inherited Create;
DataType := TDBXDataTypes.WideStringType;
Long := False;
FixedLength := False;
ColumnName := Name;
Precision := InPrecision;
end;
end.
|
unit clsTUsuario;
interface
uses
System.SysUtils,
System.Classes,
System.JSON,
REST.JSON,
DBXJSON,
DBXJSONReflect;
type
TUsuarioDTO = class(TPersistent)
private
FNasc: TDateTime;
FNome: String;
FID: Integer;
FEmail: String;
FAlterado: Boolean;
procedure SetNasc(const Value: TDateTime);
procedure SetNome(const Value: String);
procedure SetID(const Value: Integer);
procedure SetEmail(const Value: String);
function GetAlterado: Boolean;
procedure SetAlterado(const Value: Boolean);
public
constructor Create;
published
property ID: Integer read FID write SetID;
property Nome: String read FNome write SetNome;
property Nasc: TDateTime read FNasc write SetNasc;
property Email: String read FEmail write SetEmail;
property Alterado: Boolean read GetAlterado write SetAlterado;
end;
TUsuario = class(TPersistent)
private
FMarshal: TJSONMarshal;
FUnMarshal: TJSONUnMarshal;
FDTO: TUsuarioDTO;
procedure RegisterConverters;
procedure RegisterReverters;
procedure SetDTO(const Value: TUsuarioDTO);
function GetDTO: TUsuarioDTO;
public
constructor Create; overload;
constructor Create(pNome, pEmail: String; pNasc: TDateTIme); overload;
constructor Create(pID: Integer; pNome, pEmail: String; pNasc: TDateTIme); overload;
constructor Create(JSON: String); overload;
published
destructor Destroy; override;
property DTO: TUsuarioDTO read GetDTO write SetDTO;
function ToJSON: String;
end;
implementation
{ TUsuarioDTO }
constructor TUsuarioDTO.Create;
begin
Self.FAlterado := False;
end;
function TUsuarioDTO.GetAlterado: Boolean;
begin
Result := Self.FAlterado;
end;
procedure TUsuarioDTO.SetAlterado(const Value: Boolean);
begin
end;
procedure TUsuarioDTO.SetEmail(const Value: String);
begin
if Self.FEmail <> Value then
Self.FAlterado := True;
Self.FEmail := Value;
end;
procedure TUsuarioDTO.SetID(const Value: Integer);
begin
if Self.FID <> Value then
Self.FAlterado := True;
Self.FID := Value;
end;
procedure TUsuarioDTO.SetNasc(const Value: TDateTime);
begin
if Self.FNasc <> Value then
Self.FAlterado := True;
Self.FNasc := Value;
end;
procedure TUsuarioDTO.SetNome(const Value: String);
begin
if Self.FNome <> Value then
Self.FAlterado := True;
Self.FNome := Value;
end;
{ TUsuario }
procedure TUsuario.RegisterConverters;
begin
end;
procedure TUsuario.RegisterReverters;
begin
end;
constructor TUsuario.Create(pNome, pEmail: String; pNasc: TDateTIme);
begin
Self.FDTO.Nome := pNome;
Self.FDTO.Nasc := pNasc;
Self.FDTO.Email := pEmail;
end;
constructor TUsuario.Create;
begin
Self.FDTO := TUsuarioDTO.Create;
Self.FMarshal := TJSONMarshal.Create;
Self.FUnMarshal := TJSONUnMarshal.Create;
Self.RegisterConverters;
Self.RegisterReverters;
end;
constructor TUsuario.Create(JSON: String);
begin
Self.FMarshal := TJSONMarshal.Create;
Self.FUnMarshal := TJSONUnMarshal.Create;
Self.RegisterConverters;
Self.RegisterReverters;
Self.FDTO := Self.FUnMarshal.Unmarshal(TJSONObject.ParseJSONValue(JSON)) as TUsuarioDTO;
end;
destructor TUsuario.Destroy;
begin
Self.FDTO.Destroy;
Self.FMarshal.Destroy;
Self.FUnMarshal.Destroy;
inherited;
end;
procedure TUsuario.SetDTO(const Value: TUsuarioDTO);
begin
Self.FDTO := Value;
end;
constructor TUsuario.Create(pID: Integer; pNome, pEmail: String; pNasc: TDateTIme);
begin
Self.FDTO := TUsuarioDTO.Create;
Self.FDTO.Nome := pNome;
Self.FDTO.Nasc := pNasc;
Self.FDTO.Email := pEmail;
Self.FDTO.ID := pID;
end;
function TUsuario.GetDTO: TUsuarioDTO;
begin
Result := Self.FDTO;
end;
function TUsuario.ToJSON: String;
begin
Result := Self.FMarshal.Marshal(Self.DTO).ToJSON;
end;
end.
|
unit FizzBuzzExamples;
interface
procedure FizzBuzzExample1;
procedure FizzBuzzExample2;
procedure FizzBuzzExample3(const pFizz, pBuzz:Integer; const pRangeStart, pRangeEnd:Integer);
procedure FizzBuzzExample4(const pFizz, pBuzz:Integer; const pRangeStart, pRangeEnd:Integer);
procedure FizzBuzzExample_UseCase;
procedure FizzBuzzExample_UseDictionary;
implementation
uses
SysUtils,
Math,
Generics.Collections;
// First instinct - code exactly as requested. (Wrong)
procedure FizzBuzzExample1;
var
i:Integer;
begin
for i := 1 to 100 do
begin
if i mod 3 = 0 then
begin
WriteLn('Fizz');
end
else if i mod 5 = 0 then
begin
WriteLn('Buzz');
end
else if (i mod 3 = 0) and (i mod 5 = 0) then
begin
WriteLn('FizzBuzz');
end
else
begin
WriteLn(IntToStr(i));
end;
end;
end;
// corrects the FizzBuzz output
procedure FizzBuzzExample2;
var
i:Integer;
begin
for i := 1 to 100 do
begin
if (i mod 3 = 0) and (i mod 5 = 0) then
begin
WriteLn('FizzBuzz');
end
else if i mod 3 = 0 then
begin
WriteLn('Fizz');
end
else if i mod 5 = 0 then
begin
WriteLn('Buzz');
end
else
begin
WriteLn(IntToStr(i));
end;
end;
end;
// Possible refactor: Add parameters
procedure FizzBuzzExample3(const pFizz, pBuzz:Integer; const pRangeStart, pRangeEnd:Integer);
var
i:Integer;
begin
for i := pRangeStart to pRangeEnd do
begin
if (i mod pFizz = 0) and (i mod pBuzz = 0) then
begin
WriteLn('FizzBuzz');
end
else if i mod pFizz = 0 then
begin
WriteLn('Fizz');
end
else if i mod pBuzz = 0 then
begin
WriteLn('Buzz');
end
else
begin
WriteLn(IntToStr(i));
end;
end;
end;
// Possible refactor: math/logic reduction
procedure FizzBuzzExample4(const pFizz, pBuzz:Integer; const pRangeStart, pRangeEnd:Integer);
function IsMultiple(const x, y:Integer):Boolean;
begin
Result := (x mod y = 0);
end;
var
i:Integer;
vOutput:string;
begin
for i := pRangeStart to pRangeEnd do
begin
vOutput := '';
if IsMultiple(i, pFizz) then
begin
vOutput := 'Fizz';
end;
if IsMultiple(i, pBuzz) then
begin
vOutput := vOutput + 'Buzz';
end;
if vOutput = '' then
begin
vOutput := IntToStr(i);
end;
WriteLn(vOutput);
end;
end;
// Example requiring the use of Case statement
procedure FizzBuzzExample_UseCase;
var
i:Integer;
begin
for i := 1 to 100 do
begin
case i mod 15 of
3, 6, 9, 12:
WriteLn('Fizz');
5, 10:
WriteLn('Buzz');
0:
WriteLn('FizzBuzz');
else
WriteLn(IntToStr(i));
end;
end;
end;
// Example requiring the use of Dictionary
procedure FizzBuzzExample_UseDictionary;
var
i:Integer;
vValue:string;
vDict:TDictionary<Integer, string>;
begin
vDict := TDictionary<Integer, string>.Create;
try
vDict.Add(0, 'FizzBuzz');
vDict.Add(3, 'Fizz');
vDict.Add(5, 'Buzz');
vDict.Add(6, 'Fizz');
vDict.Add(9, 'Fizz');
vDict.Add(10, 'Buzz');
vDict.Add(12, 'Fizz');
for i := 1 to 100 do
begin
if vDict.TryGetValue(i mod 15, vValue) then
begin
WriteLn(vValue);
end
else
begin
WriteLn(IntToStr(i));
end;
end;
finally
vDict.Free();
end;
end;
end.
|
unit GameType;
interface
uses
Windows;
type
TGameRec = record
UpdateTime, RenderTime: Real;
end;
PRect = ^TRect;
TRect = packed record
case Integer of
0: (Left, Top, Right, Bottom: Longint);
1: (TopLeft, BottomRight: TPoint);
end;
TRGB = record
R, G, B: Byte;
end;
TRGBA = record
R, G, B, A: Byte;
end;
TScreenMode = record
X, Y, BPP, Freg: Integer;
end;
TWrapRGB = array[0..0] of TRGB;
TWrapRGBA = array[0..0] of TRGBA;
const
clRed: TRGBA = (R: 255; G: 0; B: 0; A: 255);
clLime: TRGBA = (R: 0; G: 255; B: 0; A: 255);
clBlue: TRGBA = (R: 0; G: 0; B: 255; A: 255);
clWhite: TRGBA = (R: 255; G: 255; B: 255; A: 255);
clBlack: TRGBA = (R: 0; G: 0; B: 0; A: 255);
clYellow: TRGBA = (R: 255; G: 255; B: 0; A: 255);
function RGBA(R, G, B, A: Byte): TRGBA;
function RGB(R, G, B: Byte): TRGB;
function Rect(Left, Top, Right, Bottom: Integer): TRect;
function GetScreenMode: TScreenMode;
implementation
uses
ASDHeader;
function Rect(Left, Top, Right, Bottom: Integer): TRect;
begin
Result.Left := Left;
Result.Top := Top;
Result.Right := Right;
Result.Bottom := Bottom;
end;
function RGBA(R, G, B, A: Byte): TRGBA;
begin
Result.R := R;
Result.G := G;
Result.B := B;
Result.A := A;
end;
function RGB(R, G, B: Byte): TRGB;
begin
Result.R := R;
Result.G := G;
Result.B := B;
end;
function EqulRGBA(const V1, V2: TRGBA): Boolean;
begin
Result := Integer(V1) = Integer(V2);
end;
function GetScreenMode: TScreenMode;
var
DC: HDC;
begin
DC := GetDC(Window.Handle);
Result.X := GetDeviceCaps(DC, HORZRES);
Result.Y := GetDeviceCaps(DC, VERTRES);
Result.BPP := GetDeviceCaps(DC, BITSPIXEL);
Result.Freg := GetDeviceCaps(DC, VREFRESH);
end;
end.
|
unit Demo.CoffeMachine;
interface
uses
Classes,
Rtti;
procedure ExecuteDemoCoffeeMachine;
implementation
uses
Delphi.Mocks,
Model.CoffeMachine;
type
TDemoCoffeeMachine = class
class var fCoffeeMachine: TCoffeeMachine;
class procedure S01_BasicSample;
class procedure S02_Veryfication;
end;
class procedure TDemoCoffeeMachine.S01_BasicSample;
var
aMachineTester: TStub<IMachineTester>;
aCoffee: TCoffee;
begin
aMachineTester := TStub<IMachineTester>.Create;
aMachineTester.Setup.WillReturn(True).When.IsReadyToBrewCoffee;
fCoffeeMachine := TCoffeeMachine.Create(
{} TMock<IBrewingUnit>.Create,
{} TMock<IGrinder>.Create,
{} TMock<IUserPanel>.Create,
{} aMachineTester);
aCoffee := fCoffeeMachine.BrewCoffee(csEspresso);
writeln(aCoffee.ToString);
fCoffeeMachine.Free;
end;
class procedure TDemoCoffeeMachine.S02_Veryfication;
var
aBrewingUnit: TMock<IBrewingUnit>;
aGrinder: TMock<IGrinder>;
aUserPanel: TMock<IUserPanel>;
aMachineTester: TMock<IMachineTester>;
aCoffee: TCoffee;
begin
aBrewingUnit := TMock<IBrewingUnit>.Create;
aGrinder := TMock<IGrinder>.Create;
aUserPanel := TMock<IUserPanel>.Create;
aMachineTester := TMock<IMachineTester>.Create;
aMachineTester.Setup.WillReturn(True).When.IsReadyToBrewCoffee;
aMachineTester.Setup.Expect.Once.When.IsReadyToBrewCoffee;
aGrinder.Setup.Expect.Once.When.SetGrindSize(gsFine);
aGrinder.Setup.Expect.Once.When.GrindCoffeeBeans(8.0 {mg coffee});
aBrewingUnit.Setup.Expect.Once.When.PressCoffe;
aBrewingUnit.Setup.Expect.Once.When.BrewWater(30.0 {ml water});
aBrewingUnit.Setup.Expect.Once.When.PressWater(9.0 {bar});
aBrewingUnit.Setup.Expect.Once.When.TrashCoffe;
aUserPanel.Setup.Expect.Exactly(1).When.CoffeeInProgress(True);
aUserPanel.Setup.Expect.Exactly(1).When.CoffeeInProgress(False);
fCoffeeMachine := TCoffeeMachine.Create(
{} aBrewingUnit,
{} aGrinder,
{} aUserPanel,
{} aMachineTester);
aCoffee := fCoffeeMachine.BrewCoffee(csEspresso);
writeln(aCoffee.ToString);
aMachineTester.Verify;
aGrinder.Verify;
aBrewingUnit.Verify;
aUserPanel.Verify;
fCoffeeMachine.Free;
end;
procedure ExecuteDemoCoffeeMachine;
begin
TDemoCoffeeMachine.S02_Veryfication;
writeln('Done ... hit Enter to finish ...');
end;
end.
|
unit ContextM;
interface
uses
Windows, ActiveX, ComObj, ShlObj, Dialogs;
type
TContextMenu = class(TComObject, IShellExtInit, IContextMenu)
private
FFileName: array[0..MAX_PATH] of Char;
protected
{ IShellExtInit }
function IShellExtInit.Initialize = SEIInitialize; // Avoid compiler warning
function SEIInitialize(pidlFolder: PItemIDList; lpdobj: IDataObject;
hKeyProgID: HKEY): HResult; stdcall;
{ IContextMenu }
function QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst, idCmdLast,
uFlags: UINT): HResult; stdcall;
function InvokeCommand(var lpici: TCMInvokeCommandInfo): HResult; stdcall;
function GetCommandString(idCmd, uType: UINT; pwReserved: PUINT;
pszName: LPSTR; cchMax: UINT): HResult; stdcall;
end;
const
Class_ContextMenu: TGUID = '{EBDF1F20-C829-11D1-8233-0020AF3E97A9}';
implementation
uses ComServ, SysUtils, ShellApi, Registry;
function TContextMenu.SEIInitialize(pidlFolder: PItemIDList; lpdobj: IDataObject;
hKeyProgID: HKEY): HResult;
var
StgMedium: TStgMedium;
FormatEtc: TFormatEtc;
begin
// Fail the call if lpdobj is Nil.
if (lpdobj = nil) then begin
Result := E_INVALIDARG;
Exit;
end;
with FormatEtc do begin
cfFormat := CF_HDROP;
ptd := nil;
dwAspect := DVASPECT_CONTENT;
lindex := -1;
tymed := TYMED_HGLOBAL;
end;
// Render the data referenced by the IDataObject pointer to an HGLOBAL
// storage medium in CF_HDROP format.
Result := lpdobj.GetData(FormatEtc, StgMedium);
if Failed(Result) then
Exit;
// If only one file is selected, retrieve the file name and store it in
// FFileName. Otherwise fail the call.
if (DragQueryFile(StgMedium.hGlobal, $FFFFFFFF, nil, 0) = 1) then begin
DragQueryFile(StgMedium.hGlobal, 0, FFileName, SizeOf(FFileName));
Result := NOERROR;
end
else begin
FFileName[0] := #0;
Result := E_FAIL;
end;
ReleaseStgMedium(StgMedium);
end;
function TContextMenu.QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst,
idCmdLast, uFlags: UINT): HResult;
begin
Result := 0; // or use MakeResult(SEVERITY_SUCCESS, FACILITY_NULL, 0);
if ((uFlags and $0000000F) = CMF_NORMAL) or
((uFlags and CMF_EXPLORE) <> 0) then begin
// Add one menu item to context menu
InsertMenu(Menu, indexMenu, MF_STRING or MF_BYPOSITION, idCmdFirst,
'Compile...');
// Return number of menu items added
Result := 1; // or use MakeResult(SEVERITY_SUCCESS, FACILITY_NULL, 1)
end;
end;
function GetCompilerPath: string;
// Returns string containing path to Delphi command line compiler
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
with Reg do begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\SOFTWARE\Borland\Delphi\6.0', False);
Result := ExpandFileName(ReadString('RootDir') + '\bin\dcc32.exe');
end;
if AnsiPos(' ', Result) <> 0 then
Result := ExtractShortPathName(Result);
Result := Result + ' "%s"';
finally
Reg.Free;
end;
end;
function TContextMenu.InvokeCommand(var lpici: TCMInvokeCommandInfo): HResult;
resourcestring
sPathError = 'Error setting current directory';
var
H: THandle;
PrevDir: string;
begin
Result := E_FAIL;
// Make sure we are not being called by an application
if (HiWord(Integer(lpici.lpVerb)) <> 0) then
begin
Exit;
end;
// Make sure we aren't being passed an invalid argument number
if (LoWord(lpici.lpVerb) <> 0) then begin
Result := E_INVALIDARG;
Exit;
end;
// Execute the command specified by lpici.lpVerb
// by invoking the Delphi command line compiler.
PrevDir := GetCurrentDir;
try
if not SetCurrentDir(ExtractFilePath(FFileName)) then
raise Exception.CreateRes(@sPathError);
H := WinExec(PChar(Format(GetCompilerPath, [FFileName])), lpici.nShow);
if (H < 32) then
MessageBox(lpici.hWnd, 'Error executing Delphi compiler.', 'Error',
MB_ICONERROR or MB_OK);
Result := NOERROR;
finally
SetCurrentDir(PrevDir);
end;
end;
function TContextMenu.GetCommandString(idCmd, uType: UINT; pwReserved: PUINT;
pszName: LPSTR; cchMax: UINT): HRESULT;
begin
if (idCmd = 0) then begin
if (uType = GCS_HELPTEXT) then
// return help string for menu item
StrCopy(pszName, 'Compile the selected Delphi project');
Result := NOERROR;
end
else
Result := E_INVALIDARG;
end;
type
TContextMenuFactory = class(TComObjectFactory)
public
procedure UpdateRegistry(Register: Boolean); override;
end;
procedure TContextMenuFactory.UpdateRegistry(Register: Boolean);
var
ClassID: string;
begin
if Register then begin
inherited UpdateRegistry(Register);
ClassID := GUIDToString(Class_ContextMenu);
CreateRegKey('DelphiProject\shellex', '', '');
CreateRegKey('DelphiProject\shellex\ContextMenuHandlers', '', '');
CreateRegKey('DelphiProject\shellex\ContextMenuHandlers\ContMenu', '', ClassID);
if (Win32Platform = VER_PLATFORM_WIN32_NT) then
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions', True);
OpenKey('Approved', True);
WriteString(ClassID, 'Delphi Context Menu Shell Extension Example');
finally
Free;
end;
end
else begin
DeleteRegKey('DelphiProject\shellex\ContextMenuHandlers\ContMenu');
DeleteRegKey('DelphiProject\shellex\ContextMenuHandlers');
DeleteRegKey('DelphiProject\shellex');
inherited UpdateRegistry(Register);
end;
end;
initialization
TContextMenuFactory.Create(ComServer, TContextMenu, Class_ContextMenu,
'', 'Delphi Context Menu Shell Extension Example', ciMultiInstance,
tmApartment);
end.
|
unit Hilighter;
interface
uses
Windows, KOL, KOLHilightEdit;
type
THilightStyle = (hsDefault, hsKeyword, hsPreprocessor, hsComment, hsString, hsNumber);
THilightStyles = array[THilightStyle] of TTokenAttrs;
PCHilighter=^TCHilighter;
TCHilighter = object(TObj)
private
FStyles: THilightStyles;
FDefStart: Integer;
public
procedure Init; virtual;
destructor Destroy; virtual;
function ScanToken(Sender: PControl; const FromPos: TPoint; var Attrs: TTokenAttrs): Integer;
property Styles: THilightStyles read FStyles write FStyles;
end;
const
StyleNames: array[THilightStyle] of string =
('Default', 'Keyword', 'Preprocessor', 'Comment', 'String', 'Number');
DefStyles: THilightStyles = (
(fontstyle: []; fontcolor: clBlack; backcolor: clWhite),
(fontstyle: [fsBold]; fontcolor: clNavy; backcolor: clWhite),
(fontstyle: []; fontcolor: clGreen; backcolor: clWhite),
(fontstyle: [fsItalic]; fontcolor: clTeal; backcolor: clWhite),
(fontstyle: []; fontcolor: clBlue; backcolor: clWhite),
(fontstyle: []; fontcolor: clMaroon; backcolor: clWhite));
implementation
const
Keywords: array[0..34] of string = ('sizeof', 'typedef', 'auto', 'register', 'extern', 'static',
'char', 'short', 'int', 'long', 'signed', 'unsigned', 'float', 'double', 'void',
'struct', 'enum', 'union', 'do', 'for', 'while', 'if', 'else', 'switch', 'case', 'default',
'break', 'continue', 'goto', 'return', 'inline', 'restrict', '_Bool', '_Complex', '_Imaginary');
Letters: set of Char = ['_', 'a'..'z', 'A'..'Z', '0'..'9'];
Digits: set of Char = ['0'..'9', 'a'..'f', 'x', 'b', '.', 'L', 'f'];
procedure TCHilighter.Init;
begin
inherited;
FDefStart := -2;
FStyles := DefStyles;
end;
destructor TCHilighter.Destroy;
begin
inherited;
end;
function TCHilighter.ScanToken(Sender: PControl; const FromPos: TPoint; var Attrs: TTokenAttrs ): Integer;
var
Text: string;
i: Integer;
begin
Attrs := FStyles[hsDefault];
Text := PHilightMemo(Sender).Edit.Lines[FromPos.Y];
Delete(Text, 1, FromPos.X);
if Text = '' then
begin
Result := 0;
end
else if FromPos.Y = FDefStart + 1 then
begin
Result := Length(Text);
Attrs := FStyles[hsPreprocessor];
if Text[Length(Text)] = '\' then
FDefStart := FromPos.Y;
end
else if Text[1] <= ' ' then
begin
i := 1;
while (i < Length(Text) - 1) and (Text[i] <= ' ') do
Inc(i);
Result := i - 1;
end
else if Text[1] in ['0'..'9'] then
begin
i := 2;
while (i < Length(Text)) and (Text[i] in Digits) do
Inc(i);
Result := i - 1;
Attrs := FStyles[hsNumber];
end
else if Text[1] in Letters then
begin
i := 1;
while (i < Length(Text) - 1) and (Text[i] in Letters) do
Inc(i);
Result := i - 1;
Text := Copy(Text, 1, Result);
for i := 0 to High(Keywords) do
if Text = Keywords[i] then
begin
Attrs := FStyles[hsKeyword];
Break;
end;
end
else if Text[1] = '#' then
begin
Result := Length(Text);
Attrs := FStyles[hsPreprocessor];
if (Copy(Text, 1, 7) = '#define') and (Text[Length(Text)] = '\') then
FDefStart := FromPos.Y;
end
else if Text[1] in ['''', '"'] then
begin
Result := Pos(Text[1], Copy(Text, 2, MaxInt)) + 1;
Attrs := FStyles[hsString];
end
else if Copy(Text, 1, 2) = '//' then
begin
Result := Length(Text);
Attrs := FStyles[hsComment];
end
else Result := 1;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{ Copyright and license exceptions noted in source }
{ }
{*******************************************************}
unit System.StrUtils;
interface
{$IFDEF CPUX86}
{$DEFINE X86ASM}
{$ELSE !CPUX86}
{$DEFINE PUREPASCAL}
{$ENDIF !CPUX86}
{$HPPEMIT LEGACYHPP}
uses
System.Types, System.SysUtils;
{$WARN WIDECHAR_REDUCED OFF}
{ AnsiResemblesText returns true if the two strings are similar (using a
Soundex algorithm or something similar) }
function ResemblesText(const AText, AOther: string): Boolean; overload;
function AnsiResemblesText(const AText, AOther: string): Boolean; overload;
{ AnsiContainsText returns true if the subtext is found, without
case-sensitivity, in the given text }
function ContainsText(const AText, ASubText: string): Boolean; inline; overload;
function AnsiContainsText(const AText, ASubText: string): Boolean; overload;
{ AnsiStartsText & AnsiEndText return true if the leading or trailing part
of the given text matches, without case-sensitivity, the subtext }
function StartsText(const ASubText, AText: string): Boolean; inline; overload;
function AnsiStartsText(const ASubText, AText: string): Boolean; overload;
function EndsText(const ASubText, AText: string): Boolean; inline; overload;
function AnsiEndsText(const ASubText, AText: string): Boolean; inline; overload;
{ AnsiReplaceText will replace all occurrences of a substring, without
case-sensitivity, with another substring (recursion substring replacement
is not supported) }
function ReplaceText(const AText, AFromText, AToText: string): string; inline; overload;
function AnsiReplaceText(const AText, AFromText, AToText: string): string; overload;
{ AnsiMatchText & AnsiIndexText provide case like function for dealing with
strings }
function MatchText(const AText: string; const AValues: array of string): Boolean; overload;
function AnsiMatchText(const AText: string; const AValues: array of string): Boolean; overload;
function IndexText(const AText: string; const AValues: array of string): Integer; overload;
function AnsiIndexText(const AText: string; const AValues: array of string): Integer; overload;
{ These function are similar to some of the above but are case-sensitive }
function ContainsStr(const AText, ASubText: string): Boolean; inline; overload;
function AnsiContainsStr(const AText, ASubText: string): Boolean; overload;
function StartsStr(const ASubText, AText: string): Boolean; inline; overload;
function AnsiStartsStr(const ASubText, AText: string): Boolean; overload;
function EndsStr(const ASubText, AText: string): Boolean; inline; overload;
function AnsiEndsStr(const ASubText, AText: string): Boolean; overload;
function ReplaceStr(const AText, AFromText, AToText: string): string; inline; overload;
function AnsiReplaceStr(const AText, AFromText, AToText: string): string; overload;
function MatchStr(const AText: string; const AValues: array of string): Boolean; overload;
function AnsiMatchStr(const AText: string; const AValues: array of string): Boolean; overload;
function IndexStr(const AText: string; const AValues: array of string): Integer; overload;
function AnsiIndexStr(const AText: string; const AValues: array of string): Integer; overload;
{ DupeString will return N copies of the given string }
function DupeString(const AText: string; ACount: Integer): string; overload;
{ ReverseString simply reverses the given string }
function ReverseString(const AText: string): string; overload;
function AnsiReverseString(const AText: string): string; overload;
{ StuffString replaces a segment of a string with another one }
function StuffString(const AText: string; AStart, ALength: Cardinal;
const ASubText: string): string; overload;
{ RandomFrom will randomly return one of the given strings }
function RandomFrom(const AValues: array of string): string; overload;
{ IfThen will return the true string if the value passed in is true, else
it will return the false string }
function IfThen(AValue: Boolean; const ATrue: string;
AFalse: string = ''): string; overload; inline;
{ SplitString splits a string into different parts delimited by the
specified delimiter characters }
function SplitString(const S, Delimiters: string): TStringDynArray;
{ Basic-like functions / Left, Right, Mid }
{$IFNDEF NEXTGEN}
function LeftStr(const AText: AnsiString; const ACount: Integer): AnsiString; overload; deprecated 'Moved to the AnsiStrings unit';
function RightStr(const AText: AnsiString; const ACount: Integer): AnsiString; overload; deprecated 'Moved to the AnsiStrings unit';
function MidStr(const AText: AnsiString; const AStart, ACount: Integer): AnsiString; overload; deprecated 'Moved to the AnsiStrings unit';
{ Basic-like functions / LeftB, RightB, MidB
these functions don't care locale information.}
function LeftBStr(const AText: AnsiString; const AByteCount: Integer): AnsiString; deprecated 'Moved to the AnsiStrings unit';
function RightBStr(const AText: AnsiString; const AByteCount: Integer): AnsiString; deprecated 'Moved to the AnsiStrings unit';
function MidBStr(const AText: AnsiString; const AByteStart, AByteCount: Integer): AnsiString; deprecated 'Moved to the AnsiStrings unit';
{$ENDIF !NEXTGEN}
function LeftStr(const AText: string; const ACount: Integer): string; overload;
function RightStr(const AText: string; const ACount: Integer): string; overload;
function MidStr(const AText: string; const AStart, ACount: Integer): string; overload;
{ Basic-like functions / Delphi style function name }
function AnsiLeftStr(const AText: string; const ACount: Integer): string; overload;
function AnsiRightStr(const AText: string; const ACount: Integer): string; overload;
function AnsiMidStr(const AText: string; const AStart, ACount: Integer): string; overload;
type
TStringSeachOption = (soDown, soMatchCase, soWholeWord);
TStringSearchOptions = set of TStringSeachOption;
{ SearchBuf is a search routine for arbitrary text buffers. If a match is
found, the function returns a pointer to the start of the matching
string in the buffer. If no match is found, the function returns nil.
If soDown is specified, a forward search is performed otherwise the function
searches backwards through the text. Use SelStart and SelLength to skip
"selected" text; this will cause the search to start before or after (soDown)
the specified text. }
const
{ Default word delimiters are any character except the core alphanumerics. }
WordDelimiters: set of Byte = [0..255] -
[Ord('a')..Ord('z'), Ord('A')..Ord('Z'), Ord('1')..Ord('9'), Ord('0')];
{$IFNDEF NEXTGEN}
function SearchBuf(Buf: PAnsiChar; BufLen: Integer; SelStart, SelLength: Integer;
SearchString: AnsiString; Options: TStringSearchOptions = [soDown]): PAnsiChar; overload; deprecated 'Moved to the AnsiStrings unit';
{$ENDIF}
{$IFDEF UNICODE}
function SearchBuf(Buf: PChar; BufLen: Integer; SelStart, SelLength: Integer;
SearchString: String; Options: TStringSearchOptions = [soDown]): PChar; overload;
{$ENDIF}
{ PosEx searches for SubStr in S and returns the index position of
SubStr if found and 0 otherwise. If Offset is not given then the result is
the same as calling Pos. If Offset is specified and > 1 then the search
starts at position Offset within S. If Offset is larger than Length(S)
then PosEx returns 0. By default, Offset equals 1. }
function PosEx(const SubStr, S: string; Offset: Integer = 1): Integer; inline; overload;
{ Soundex function returns the Soundex code for the given string. Unlike
the original Soundex routine this function can return codes of varying
lengths. This function is loosely based on SoundBts which was written
by John Midwinter. For more information about Soundex see:
http://www.nara.gov/genealogy/coding.html
The general theory behind this function was originally patented way back in
1918 (US1261167 & US1435663) but are now in the public domain.
NOTE: This function does not attempt to deal with 'names with prefixes'
issue.
}
type
TSoundexLength = 1..MaxInt;
function Soundex(const AText: string; ALength: TSoundexLength = 4): string;
{ SoundexInt uses Soundex but returns the resulting Soundex code encoded
into an integer. However, due to limits on the size of an integer, this
function is limited to Soundex codes of eight characters or less.
DecodeSoundexInt is designed to decode the results of SoundexInt back to
a normal Soundex code. Length is not required since it was encoded into
the results of SoundexInt. }
type
TSoundexIntLength = 1..8;
function SoundexInt(const AText: string; ALength: TSoundexIntLength = 4): Integer;
function DecodeSoundexInt(AValue: Integer): string;
{ SoundexWord is a special case version of SoundexInt that returns the
Soundex code encoded into a word. However, due to limits on the size of a
word, this function uses a four character Soundex code.
DecodeSoundexWord is designed to decode the results of SoundexWord back to
a normal Soundex code. }
function SoundexWord(const AText: string): Word;
function DecodeSoundexWord(AValue: Word): string;
{ SoundexSimilar and SoundexCompare are simple comparison functions that use
the Soundex encoding function. }
function SoundexSimilar(const AText, AOther: string;
ALength: TSoundexLength = 4): Boolean;
function SoundexCompare(const AText, AOther: string;
ALength: TSoundexLength = 4): Integer;
{ Default entry point for AnsiResemblesText }
function SoundexProc(const AText, AOther: string): Boolean;
type
TCompareTextProc = function(const AText, AOther: string): Boolean;
{ If the default behavior of AnsiResemblesText (using Soundex) is not suitable
for your situation, you can redirect it to a function of your own choosing }
var
ResemblesProc: TCompareTextProc = SoundexProc;
AnsiResemblesProc: TCompareTextProc = SoundexProc;
implementation
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF MSWINDOWS}
System.Character;
function ResemblesText(const AText, AOther: string): Boolean;
begin
Result := False;
if Assigned(ResemblesProc) then
Result := ResemblesProc(AText, AOther);
end;
function AnsiResemblesText(const AText, AOther: string): Boolean;
begin
Result := False;
if Assigned(AnsiResemblesProc) then
Result := AnsiResemblesProc(AText, AOther);
end;
function ContainsText(const AText, ASubText: string): Boolean;
begin
Result := AnsiContainsText(AText, ASubText);
end;
function AnsiContainsText(const AText, ASubText: string): Boolean;
begin
Result := AnsiPos(AnsiUppercase(ASubText), AnsiUppercase(AText)) > 0;
end;
function StartsText(const ASubText, AText: string): Boolean;
begin
Result := AnsiStartsText(ASubText, AText);
end;
function AnsiStartsText(const ASubText, AText: string): Boolean;
var
{$IFDEF MSWINDOWS}
P: PChar;
{$ENDIF}
L, L2: Integer;
begin
{$IFDEF MSWINDOWS}
P := PChar(AText);
{$ENDIF}
L := Length(ASubText);
L2 := Length(AText);
if L > L2 then
Result := False
else
{$IFDEF MSWINDOWS}
Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE,
P, L, PChar(ASubText), L) = 2;
{$ENDIF}
{$IFDEF POSIX}
Result := SameText(ASubText, Copy(AText, 1, L));
{$ENDIF}
end;
function EndsText(const ASubText, AText: string): Boolean;
begin
Result := AnsiEndsText(ASubText, AText);
end;
function AnsiEndsText(const ASubText, AText: string): Boolean;
begin
Result := string.EndsText(ASubTExt, AText);
end;
function ReplaceStr(const AText, AFromText, AToText: string): string;
begin
Result := AnsiReplaceStr(AText, AFromText, AToText);
end;
function AnsiReplaceStr(const AText, AFromText, AToText: string): string;
begin
Result := StringReplace(AText, AFromText, AToText, [rfReplaceAll]);
end;
function ReplaceText(const AText, AFromText, AToText: string): string;
begin
Result := AnsiReplaceText(AText, AFromText, AToText);
end;
function AnsiReplaceText(const AText, AFromText, AToText: string): string;
begin
Result := StringReplace(AText, AFromText, AToText, [rfReplaceAll, rfIgnoreCase]);
end;
function MatchText(const AText: string; const AValues: array of string): Boolean;
begin
Result := AnsiMatchText(AText, AValues);
end;
function AnsiMatchText(const AText: string; const AValues: array of string): Boolean;
begin
Result := AnsiIndexText(AText, AValues) <> -1;
end;
function IndexText(const AText: string; const AValues: array of string): Integer;
begin
Result := AnsiIndexText(AText, AValues);
end;
function AnsiIndexText(const AText: string; const AValues: array of string): Integer;
var
I: Integer;
begin
Result := -1;
for I := Low(AValues) to High(AValues) do
if AnsiSameText(AText, AValues[I]) then
begin
Result := I;
Break;
end;
end;
function ContainsStr(const AText, ASubText: string): Boolean;
begin
Result := AnsiContainsStr(AText, ASubText);
end;
function AnsiContainsStr(const AText, ASubText: string): Boolean;
begin
Result := AnsiPos(ASubText, AText) > 0;
end;
function StartsStr(const ASubText, AText: string): Boolean;
begin
Result := AnsiStartsStr(ASubText, AText);
end;
function AnsiStartsStr(const ASubText, AText: string): Boolean;
begin
Result := AnsiSameStr(ASubText, Copy(AText, 1, Length(ASubText)));
end;
function EndsStr(const ASubText, AText: string): Boolean;
begin
Result := AText.EndsWith(ASubText);
end;
function AnsiEndsStr(const ASubText, AText: string): Boolean;
const
StrAdjust = 1 - Low(string);
var
SubTextLocation: Integer;
begin
SubTextLocation := Length(AText) - Length(ASubText) + 1;
if (SubTextLocation > 0) and (ASubText <> '') and
(ByteType(AText, SubTextLocation) <> mbTrailByte) then
Result := AnsiStrComp(PChar(ASubText), PChar(@AText[SubTextLocation - StrAdjust])) = 0
else
Result := False;
end;
function MatchStr(const AText: string; const AValues: array of string): Boolean;
begin
Result := AnsiMatchStr(AText, AValues);
end;
function AnsiMatchStr(const AText: string; const AValues: array of string): Boolean;
begin
Result := AnsiIndexStr(AText, AValues) <> -1;
end;
function IndexStr(const AText: string; const AValues: array of string): Integer;
begin
Result := AnsiIndexStr(AText, AValues);
end;
function AnsiIndexStr(const AText: string; const AValues: array of string): Integer;
var
I: Integer;
begin
Result := -1;
for I := Low(AValues) to High(AValues) do
if AnsiSameStr(AText, AValues[I]) then
begin
Result := I;
Break;
end;
end;
function DupeString(const AText: string; ACount: Integer): string;
var
P: PChar;
C: Integer;
begin
C := Length(AText);
SetLength(Result, C * ACount);
P := Pointer(Result);
if P = nil then Exit;
while ACount > 0 do
begin
Move(Pointer(AText)^, P^, C * SizeOf(Char));
Inc(P, C);
Dec(ACount);
end;
end;
function ReverseString(const AText: string): string;
var
I: Integer;
P: PChar;
begin
SetLength(Result, Length(AText));
P := PChar(Result);
for I := High(AText) downto Low(AText) do
begin
P^ := AText[I];
Inc(P);
end;
end;
function AnsiReverseString(const AText: string): string;
var
I: Integer;
Len, CharLen: Integer;
P, R, Tail: PWideChar;
begin
Result := '';
Len := Length(AText);
if Len > 0 then
begin
SetLength(Result, Len);
P := PWideChar(AText);
R := PWideChar(Result) + Len;
Tail := P + Len;
while P < Tail do
begin
CharLen := 1;
if IsLeadChar(P^) then
CharLen := StrNextChar(P) - P;
Dec(R, CharLen);
for I := 0 to CharLen - 1 do
R[I] := P[I];
Inc(P, CharLen);
end;
end;
end;
function StuffString(const AText: string; AStart, ALength: Cardinal;
const ASubText: string): string;
begin
Result := Copy(AText, 1, AStart - 1) +
ASubText +
Copy(AText, AStart + ALength, MaxInt);
end;
function RandomFrom(const AValues: array of string): string;
begin
Result := AValues[Random(High(AValues) + 1)];
end;
function IfThen(AValue: Boolean; const ATrue: string;
AFalse: string = ''): string;
begin
if AValue then
Result := ATrue
else
Result := AFalse;
end;
function SplitString(const S, Delimiters: string): TStringDynArray;
var
StartIdx: Integer;
FoundIdx: Integer;
SplitPoints: Integer;
CurrentSplit: Integer;
i: Integer;
begin
Result := nil;
if S <> '' then
begin
{ Determine the length of the resulting array }
SplitPoints := 0;
for i := 1 to S.Length do
if IsDelimiter(Delimiters, S, i) then
Inc(SplitPoints);
SetLength(Result, SplitPoints + 1);
{ Split the string and fill the resulting array }
StartIdx := 1;
CurrentSplit := 0;
repeat
FoundIdx := FindDelimiter(Delimiters, S, StartIdx);
if FoundIdx <> 0 then
begin
Result[CurrentSplit] := Copy(S, StartIdx, FoundIdx - StartIdx);
Inc(CurrentSplit);
StartIdx := FoundIdx + 1;
end;
until CurrentSplit = SplitPoints;
// copy the remaining part in case the string does not end in a delimiter
Result[SplitPoints] := Copy(S, StartIdx, S.Length - StartIdx + 1);
end;
end;
{$IFNDEF NEXTGEN}
function LeftStr(const AText: AnsiString; const ACount: Integer): AnsiString; overload;
begin
Result := Copy(AText, 1, ACount);
end;
function RightStr(const AText: AnsiString; const ACount: Integer): AnsiString; overload;
begin
Result := Copy(AText, Length(AText) + 1 - ACount, ACount);
end;
function MidStr(const AText: AnsiString; const AStart, ACount: Integer): AnsiString; overload;
begin
Result := Copy(AText, AStart, ACount);
end;
function LeftBStr(const AText: AnsiString; const AByteCount: Integer): AnsiString;
begin
Result := Copy(AText, 1, AByteCount);
end;
function RightBStr(const AText: AnsiString; const AByteCount: Integer): AnsiString;
begin
Result := Copy(AText, Length(AText) + 1 - AByteCount, AByteCount);
end;
function MidBStr(const AText: AnsiString; const AByteStart, AByteCount: Integer): AnsiString;
begin
Result := Copy(AText, AByteStart, AByteCount);
end;
{$ENDIF}
function LeftStr(const AText: string; const ACount: Integer): string; overload;
begin
Result := Copy(AText, 1, ACount);
end;
function RightStr(const AText: string; const ACount: Integer): string; overload;
begin
Result := Copy(AText, Length(AText) + 1 - ACount, ACount);
end;
function MidStr(const AText: string; const AStart, ACount: Integer): string; overload;
begin
Result := Copy(AText, AStart, ACount);
end;
function AnsiCountElems(const AText: UnicodeString; AStartIndex, ACharCount: Integer): Integer;
var
S, P: PWideChar;
Len, CharLen: Integer;
begin
Result := 0;
if AStartIndex <= 0 then
AStartIndex := 1;
Len := Length(AText) - AStartIndex + 1;
if Len > 0 then
begin
P := PWideChar(AText) + AStartIndex - 1;
S := P;
while (Len > 0) and (ACharCount > 0) do
begin
CharLen := 1;
if IsLeadChar(P^) then
CharLen := StrNextChar(P) - P;
if CharLen > Len then
CharLen := Len;
Inc(P, CharLen);
Dec(Len, CharLen);
Dec(ACharCount);
end;
Result := P - S;
end;
end;
function AnsiCountChars(const AText: UnicodeString): Integer;
var
P: PWideChar;
Len, CharLen: Integer;
begin
Result := 0;
Len := Length(AText);
if Len > 0 then
begin
P := PWideChar(AText);
while Len > 0 do
begin
CharLen := 1;
if IsLeadChar(P^) then
CharLen := StrNextChar(P) - P;
if CharLen > Len then
CharLen := Len;
Inc(P, CharLen);
Dec(Len, CharLen);
Inc(Result);
end;
end;
end;
function AnsiLeftStr(const AText: string; const ACount: Integer): string;
var
Count: Integer;
begin
Result := '';
if (ACount > 0) and (Length(AText) > 0) then
begin
Count := AnsiCountElems(AText, 1, ACount);
Result := Copy(AText, 1, Count);
end;
end;
function AnsiRightStr(const AText: string; const ACount: Integer): string;
var
CharCount: Integer;
begin
Result := '';
CharCount := AnsiCountChars(AText);
if CharCount > 0 then
Result := AnsiMidStr(AText, CharCount - ACount + 1, ACount);
end;
function AnsiMidStr(const AText: string; const AStart, ACount: Integer): string;
var
Len, Start, Count: Integer;
begin
Result := '';
if ACount > 0 then
begin
Len := Length(AText);
if Len > 0 then
begin
Start := 1;
if AStart > 0 then
Start := AnsiCountElems(AText, 1, AStart - 1) + 1;
if Len >= Start then
begin
Count := AnsiCountElems(AText, Start, ACount);
Result := Copy(AText, Start, Count);
end;
end;
end;
end;
{$IFNDEF NEXTGEN}
function SearchBuf(Buf: PAnsiChar; BufLen: Integer; SelStart, SelLength: Integer;
SearchString: AnsiString; Options: TStringSearchOptions): PAnsiChar;
var
SearchCount, I: Integer;
C: AnsiChar;
Direction: Shortint;
ShadowMap: array[0..256] of AnsiChar;
CharMap: array [AnsiChar] of AnsiChar absolute ShadowMap;
function FindNextWordStart(var BufPtr: PAnsiChar): Boolean;
begin { (True XOR N) is equivalent to (not N) }
{ (False XOR N) is equivalent to (N) }
{ When Direction is forward (1), skip non delimiters, then skip delimiters. }
{ When Direction is backward (-1), skip delims, then skip non delims }
while (SearchCount > 0) and
((Direction = 1) xor (Byte(BufPtr^) in WordDelimiters)) do
begin
Inc(BufPtr, Direction);
Dec(SearchCount);
end;
while (SearchCount > 0) and
((Direction = -1) xor (Byte(BufPtr^) in WordDelimiters)) do
begin
Inc(BufPtr, Direction);
Dec(SearchCount);
end;
Result := SearchCount > 0;
if Direction = -1 then
begin { back up one char, to leave ptr on first non delim }
Dec(BufPtr, Direction);
Inc(SearchCount);
end;
end;
begin
Result := nil;
if BufLen <= 0 then Exit;
if soDown in Options then
begin
Direction := 1;
Inc(SelStart, SelLength); { start search past end of selection }
SearchCount := BufLen - SelStart - Length(SearchString) + 1;
if SearchCount < 0 then Exit;
if Longint(SelStart) + SearchCount > BufLen then Exit;
end
else
begin
Direction := -1;
Dec(SelStart, Length(SearchString));
SearchCount := SelStart + 1;
end;
if (SelStart < 0) or (SelStart > BufLen) then Exit;
Result := @Buf[SelStart];
{ Using a Char map array is faster than calling AnsiUpper on every character }
for C := Low(CharMap) to High(CharMap) do
CharMap[(C)] := (C);
{ Since CharMap is overlayed onto the ShadowMap and ShadowMap is 1 byte longer,
we can use that extra byte as a guard NULL }
ShadowMap[256] := #0;
if not (soMatchCase in Options) then
begin
{$IFDEF MSWINDOWS}
CharUpperBuffA(PAnsiChar(@CharMap), Length(CharMap));
CharUpperBuffA(@SearchString[1], Length(SearchString));
{$ENDIF}
{$IFDEF POSIX}
AnsiStrUpper(PAnsiChar(@CharMap[#1]));
AnsiStrUpper(PAnsIChar(@SearchString[1]));
{$ENDIF POSIX}
end;
while SearchCount > 0 do
begin
if (soWholeWord in Options) and (Result <> @Buf[SelStart]) then
if not FindNextWordStart(Result) then Break;
I := 0;
while (CharMap[(Result[I])] = (SearchString[I+1])) do
begin
Inc(I);
if I >= Length(SearchString) then
begin
if (not (soWholeWord in Options)) or
(SearchCount = 0) or
((Byte(Result[I])) in WordDelimiters) then
Exit;
Break;
end;
end;
Inc(Result, Direction);
Dec(SearchCount);
end;
Result := nil;
end;
{$ENDIF !NEXTGEN}
{$IFDEF UNICODE}
function SearchBuf(Buf: PChar; BufLen: Integer; SelStart, SelLength: Integer;
SearchString: string; Options: TStringSearchOptions): PChar;
var
SearchCount, I: Integer;
Direction: Shortint;
function FindNextWordStart(var BufPtr: PChar): Boolean;
begin { (True XOR N) is equivalent to (not N) }
{ (False XOR N) is equivalent to (N) }
{ When Direction is forward (1), skip non delimiters, then skip delimiters. }
{ When Direction is backward (-1), skip delims, then skip non delims }
while (SearchCount > 0) and
((Direction = 1) xor (not BufPtr^.IsLetterOrDigit)) do
begin
Inc(BufPtr, Direction);
Dec(SearchCount);
end;
while (SearchCount > 0) and
((Direction = -1) xor (not BufPtr^.IsLetterOrDigit)) do
begin
Inc(BufPtr, Direction);
Dec(SearchCount);
end;
Result := SearchCount > 0;
if Direction = -1 then
begin { back up one WideChar, to leave ptr on first non delim }
Dec(BufPtr, Direction);
Inc(SearchCount);
end;
end;
function NextChar(S: PChar): Char;
begin
if not (soMatchCase in Options) then
Result := Char(S[I]).ToUpper
else
Result := S[I];
end;
begin
Result := nil;
if BufLen <= 0 then Exit;
if soDown in Options then
begin
Direction := 1;
Inc(SelStart, SelLength); { start search past end of selection }
SearchCount := BufLen - SelStart - SearchString.Length + 1;
if SearchCount < 0 then Exit;
if Longint(SelStart) + SearchCount > BufLen then Exit;
end
else
begin
Direction := -1;
Dec(SelStart, SearchString.Length);
SearchCount := SelStart + 1;
end;
if (SelStart < 0) or (SelStart > BufLen) then Exit;
Result := @Buf[SelStart];
if not (soMatchCase in Options) then
SearchString := Char.ToUpper(SearchString);
while SearchCount > 0 do
begin
if (soWholeWord in Options) and (Result <> @Buf[SelStart]) then
if not FindNextWordStart(Result) then Break;
I := 0;
while NextChar(Result) = SearchString[I+Low(string)] do
begin
Inc(I);
if I >= Length(SearchString) then
begin
if (not (soWholeWord in Options)) or
(SearchCount = 0) or
(not Char(Result[I]).IsLetterOrDigit) then
Exit;
Break;
end;
end;
Inc(Result, Direction);
Dec(SearchCount);
end;
Result := nil;
end;
{$ENDIF}
function PosEx(const SubStr, S: string; Offset: Integer): Integer;
begin
Result := System.Pos(SubStr, S, Offset);
end;
{ This function is loosely based on SoundBts which was written by John Midwinter }
function Soundex(const AText: string; ALength: TSoundexLength): string;
const
// This table gives the Soundex score for all characters upper- and lower-
// case hence no need to convert. This is faster than doing an UpCase on the
// whole input string. The 5 non characters in middle are just given 0.
CSoundexTable: array[65..122] of Integer =
// A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
(0, 1, 2, 3, 0, 1, 2, -1, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, -1, 2, 0, 2,
// [ / ] ^ _ '
0, 0, 0, 0, 0, 0,
// a b c d e f g h i j k l m n o p q r s t u v w x y z
0, 1, 2, 3, 0, 1, 2, -1, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, -1, 2, 0, 2);
function Score(AChar: Integer): Integer;
begin
Result := 0;
if (AChar >= Low(CSoundexTable)) and (AChar <= High(CSoundexTable)) then
Result := CSoundexTable[AChar];
end;
var
I, LScore, LPrevScore: Integer;
Str: PChar;
begin
Result := '';
if AText <> '' then
begin
Str := PChar(@AText[Low(string)+1]);
Result := Upcase(AText[Low(string)]);
LPrevScore := Score(Integer(AText[Low(string)]));
for I := 2 to AText.Length do
begin
LScore := Score(Integer(Str^));
if (LScore > 0) and (LScore <> LPrevScore) then
begin
Result := Result + IntToStr(LScore);
if Result.Length = ALength then
Break;
end;
if LScore <> -1 then
LPrevScore := LScore;
Inc(Str);
end;
if Result.Length < ALength then
Result := Copy(Result + DupeString('0', ALength), 1, ALength);
end;
end;
function SoundexInt(const AText: string; ALength: TSoundexIntLength): Integer;
var
LResult: string;
I: Integer;
begin
Result := 0;
if AText <> '' then
begin
LResult := Soundex(AText, ALength);
Result := Ord(LResult.Chars[0]) - Ord('A');
if ALength > 1 then
begin
Result := Result * 26 + StrToInt(LResult.Chars[1]);
for I := 3 to ALength do
Result := Result * 7 + StrToInt(LResult.Chars[I-1]);
end;
Result := Result * 9 + ALength;
end;
end;
function DecodeSoundexInt(AValue: Integer): string;
var
I, LLength: Integer;
begin
Result := '';
LLength := AValue mod 9;
AValue := AValue div 9;
for I := LLength downto 3 do
begin
Result := IntToStr(AValue mod 7) + Result;
AValue := AValue div 7;
end;
if LLength > 2 then
Result := IntToStr(AValue mod 26) + Result;
AValue := AValue div 26;
Result := Chr(AValue + Ord('A')) + Result;
end;
function SoundexWord(const AText: string): Word;
var
LResult: string;
begin
LResult := Soundex(AText, 4);
Result := Ord(LResult.Chars[0]) - Ord('A');
Result := Result * 26 + StrToInt(LResult.Chars[1]);
Result := Result * 7 + StrToInt(LResult.Chars[2]);
Result := Result * 7 + StrToInt(LResult.Chars[3]);
end;
function DecodeSoundexWord(AValue: Word): string;
begin
Result := IntToStr(AValue mod 7) + Result;
AValue := AValue div 7;
Result := IntToStr(AValue mod 7) + Result;
AValue := AValue div 7;
Result := IntToStr(AValue mod 26) + Result;
AValue := AValue div 26;
Result := Chr(AValue + Ord('A')) + Result;
end;
function SoundexSimilar(const AText, AOther: string; ALength: TSoundexLength): Boolean;
begin
Result := Soundex(AText, ALength) = Soundex(AOther, ALength);
end;
function SoundexCompare(const AText, AOther: string; ALength: TSoundexLength): Integer;
begin
Result := AnsiCompareStr(Soundex(AText, ALength), Soundex(AOther, ALength));
end;
function SoundexProc(const AText, AOther: string): Boolean;
begin
Result := SoundexSimilar(AText, AOther);
end;
end.
|
unit PwdDataFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TPwdDataFormData = record
Password: string;
Note: string;
end;
TPwdDataForm = class(TForm)
GroupBox1: TGroupBox;
NoteMemo: TMemo;
GroupBox2: TGroupBox;
PasswordEdit: TEdit;
OkButton: TButton;
CancelButton: TButton;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
{ Private declarations }
function CheckValid: Boolean;
public
{ Public declarations }
procedure SetData(Value: TPwdDataFormData);
procedure GetData(var Value: TPwdDataFormData);
end;
var
PwdDataForm: TPwdDataForm;
function ShowPwdDataForm(var Value: TPwdDataFormData): Boolean;
implementation
{$R *.DFM}
function ShowPwdDataForm(var Value: TPwdDataFormData): Boolean;
var
Frm: TPwdDataForm;
begin
Frm := TPwdDataForm.Create(Application);
Frm.SetData(Value);
Result := (Frm.ShowModal = mrOk);
if Result then Frm.GetData(Value);
Frm.Free;
end;
procedure TPwdDataForm.GetData(var Value: TPwdDataFormData);
begin
Value.Password := PasswordEdit.Text;
Value.Note := NoteMemo.Lines.Text;
end;
procedure TPwdDataForm.SetData(Value: TPwdDataFormData);
begin
PasswordEdit.Text := Value.Password;
NoteMemo.Lines.Text := Value.Note;
end;
function TPwdDataForm.CheckValid: Boolean;
begin
Result := True;
end;
procedure TPwdDataForm.OkButtonClick(Sender: TObject);
begin
if CheckValid then
ModalResult := mrOk;
end;
procedure TPwdDataForm.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
end.
|
program divsumts;
{Программа проверяет правильность ответа на задачу divsum}
Const
nmax = 10000;
Type
list = array[1..nmax] of integer;
Var
a : list;
b : integer; {число из файла с результатами теста}
n : integer; {количество чисел в исходном файле}
k : integer; {количество чисел в файле с результатами теста}
i : integer; {номер числа в исходном списке}
j : integer; {номер числа в списке результата теста}
infile : text; {файл с входными данными}
tstfile : text; {файл с результатами тестирования}
sum : longint;
numexist : boolean; {признак существования числа в исходном списке}
Begin
Writeln('Начало работы тестирующей программы');
Assign(infile,'input.txt');
Reset(infile);
Assign(tstfile,'output.txt');
reset(tstfile);
sum := 0;
Readln(infile,n);
for i := 1 to n do
readln(infile,a[i]);
Readln(tstfile,k);
If k <= 0 then
Begin
Writeln('Неверное количество чисел в результате теста');
Halt(4)
End;
j := 1;
numexist := true;
While (j <= k) and numexist do
Begin
if eof(tstfile) then
Begin
Writeln('Неожиданный конец файла');
Halt(3)
End;
Readln(tstfile,b);
if b <= 0 then
Begin
Writeln('Число ',b,' отсутствует во входных данных.');
Halt(1)
End;
i := 1;
While (i <= n) and (a[i] <> b) do
inc(i);
if i > n then
Begin
Writeln('Число ',b,' отсутствует во входных данных.');
Halt(1)
End
Else
Begin
Sum := Sum + b;
a[i] := -1
End;
inc(j)
End;
if (sum mod n) <> 0 then
Begin
Writeln('Ошибочная сумма');
Halt(2)
End
Else
Begin
Writeln('Тест пройден успешно');
halt(0)
End
End. |
{
Copyright (C) 2007 Laurent Jacques
This source is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This code is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
A copy of the GNU General Public License is available on the World Wide Web
at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing
to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
}
unit ColorProgress;
{$MODE objfpc}{$H+}
interface
uses
LResources, Classes, SysUtils, Controls, Graphics, FPCanvas;
type
TColorProgressKind = (ckText, ckHorizontalBar, ckHorRoundBar, ckVerticalBar,
ckVerRoundBar, ckPie, ckBitmap);
{ TColorProgress }
TColorProgress = class(TGraphicControl)
private
{ Private declarations }
FBackColor: TColor;
FBorderStyle: TBorderStyle;
FCurValue: longint;
FForeColor: TColor;
FForeStyle: TFPBrushStyle;
FForeImage: TBitmap;
FKind: TColorProgressKind;
FMaxValue: longint;
FMinValue: longint;
FShowText: boolean;
FGetForeImage: boolean;
procedure DrawRoundBar;
procedure DrawBar;
procedure DrawText;
procedure DrawPie;
procedure DrawBitmap;
function GetPercentDone: longint;
procedure SetBackColor(AValue: TColor);
procedure SetForeColor(AValue: TColor);
procedure SetForeStyle(AValue: TFPBrushStyle);
procedure SetForeImage(AValue: TBitmap);
procedure SetGaugeKind(const AValue: TColorProgressKind);
procedure SetMaxValue(AValue: longint);
procedure SetMinValue(AValue: longint);
procedure SetProgress(AValue: longint);
procedure SetShowText(AValue: boolean);
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure AddProgress(AValue: longint);
procedure Paint; override;
property PercentDone: longint Read GetPercentDone;
published
{ Published declarations }
property Align;
property Anchors;
property BackColor: TColor Read FBackColor Write SetBackColor default clWhite;
property Color;
property Constraints;
property Enabled;
property ForeColor: TColor Read FForeColor Write SetForeColor default clBlack;
property ForeStyle: TFPBrushStyle Read FForeStyle Write SetForeStyle default bsSolid;
property ForeImage: TBitmap Read FForeImage Write SetForeImage;
property Font;
property Kind: TColorProgressKind Read FKind Write SetGaugeKind default
ckHorizontalBar;
property MinValue: longint Read FMinValue Write SetMinValue default 0;
property MaxValue: longint Read FMaxValue Write SetMaxValue default 100;
property ParentColor;
property ParentFont;
property ParentShowHint;
property Progress: longint Read FCurValue Write SetProgress;
property ShowHint;
property ShowText: boolean Read FShowText Write SetShowText default True;
property Visible;
end;
procedure Register;
implementation
uses Math;
procedure Register;
begin
RegisterComponents('Wile64', [TColorProgress]);
end;
constructor TColorProgress.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
ControlStyle := ControlStyle + [csReplicatable];
FMinValue := 0;
FMaxValue := 100;
FCurValue := 0;
FBorderStyle := bsSingle;
FForeColor := clBlack;
FBackColor := clWhite;
FShowText := True;
FKind := ckHorizontalBar;
Width := 100;
Height := 20;
FForeImage := TBitmap.Create;
FGetForeImage:=false;
end;
destructor TColorProgress.Destroy;
begin
FForeImage.Free;
inherited Destroy;
end;
procedure TColorProgress.Paint;
begin
case Kind of
ckText: DrawText;
ckHorizontalBar,
ckVerticalBar: DrawBar;
ckHorRoundBar,
ckVerRoundBar: DrawroundBar;
ckPie: DrawPie;
ckBitmap: DrawBitmap;
end;
if ShowText and (Kind <> ckText) then
DrawText;
inherited Paint;
end;
procedure TColorProgress.SetForeColor(AValue: TColor);
begin
if AValue <> FForeColor then
begin
FForeColor := AValue;
Refresh;
end;
end;
procedure TColorProgress.DrawRoundBar;
var
FillSize: longint;
MinSize: longint;
begin
with Canvas do
begin
Brush.Color := BackColor;
Brush.Style := bsSolid;
MinSize := Min(self.Width, self.Height);
Pen.Color := cl3DLight;
RoundRect(1, 1, self.Width, self.Height, MinSize div 4, MinSize div 4);
Brush.Style := bsClear;
Pen.Color := cl3DDkShadow;
RoundRect(0, 0, self.Width - 1, self.Height - 1, MinSize div 4, MinSize div 4);
Brush.Style := ForeStyle;
Brush.Color := ForeColor;
Pen.Color := BackColor;
if percentdone > 0 then
case Kind of
ckHorRoundBar:
begin
FillSize := Trunc((self.Width - 2) * (PercentDone / 100));
RoundRect(Rect(2, 2, FillSize, self.Height - 2), MinSize div
4, MinSize div 4);
end;
ckVerRoundBar:
begin
FillSize := Trunc((self.Height - 2) * (PercentDone / 100));
RoundRect(Rect(2, Self.Height - 2 - FillSize, Self.Width - 2, Self.Height - 3),
MinSize div 4, MinSize div 4);
end;
end;
end;
end;
procedure TColorProgress.DrawBar;
var
FillSize: longint;
begin
with Canvas do
begin
Brush.Color := BackColor;
Pen.Color := cl3DLight;
Rectangle(1, 1, self.Width, self.Height);
Brush.Style := bsClear;
Pen.Color := cl3DDkShadow;
Rectangle(0, 0, self.Width-1, self.Height-1);
Brush.Style := ForeStyle;
Brush.Color := ForeColor;
if percentdone > 0 then
case Kind of
ckHorizontalBar:
begin
FillSize := Trunc((self.Width - 4) * (PercentDone / 100));
FillRect(Rect(2, 2, FillSize + 2, self.Height - 2));
end;
ckVerticalBar:
begin
FillSize := Trunc((self.Height - 4) * (PercentDone / 100));
FillRect(Rect(2, Self.Height - 2 - FillSize, Self.Width - 2, Self.Height - 2));
end;
end;
end;
end;
procedure TColorProgress.DrawText;
var
X, Y: integer;
S: string;
begin
with Canvas do
begin
if Kind = ckText then
begin
Brush.Color := BackColor;
Brush.Style := bsSolid;
Pen.Color := clGray;
Rectangle(0, 0, self.Width, self.Height);
Pen.Color := clSilver;
Rectangle(1, 1, self.Width - 1, self.Height - 1);
end;
Font := Self.Font;
S := format('%d%%', [PercentDone]);
Y := (self.Height div 2) - (TextHeight(S) div 2);
X := (self.Width div 2) - (TextWidth(S) div 2);
TextRect(self.ClientRect, X, Y-1, S);
end;
end;
procedure TColorProgress.DrawPie;
var
MiddleX, MiddleY: integer;
Angle: double;
begin
with Canvas do
begin
Brush.Color := BackColor;
Brush.Style := bsSolid;
Pen.Color := cl3DLight;
Ellipse(1, 1, self.Width, self.Height);
Pen.Color := cl3DDkShadow;
Ellipse(0, 0, self.Width - 1, self.Height - 1);
Brush.Style := ForeStyle;
Brush.Color := ForeColor;
if PercentDone > 0 then
begin
MiddleX := (self.Width - 2) div 2;
MiddleY := (self.Height - 2) div 2;
Angle := (Pi * ((PercentDone / 50) + 0.5));
Pie(2, 2, self.Width - 3, self.Height - 3,
integer(Round(MiddleX * (1 - Cos(Angle)))),
integer(Round(MiddleY * (1 - Sin(Angle)))), MiddleX + 1, 1);
end;
end;
end;
procedure TColorProgress.DrawBitmap;
var
FillSize: longint;
MinSize: longint;
SrcRect, DstRect: TRect;
bmp: TBitmap;
begin
with Canvas do
begin
if not FGetForeImage then
begin
bmp := TBitmap.Create;
Bmp.Width := self.Width;
Bmp.Height := Self.Height;
Bmp.Canvas.StretchDraw(rect(0, 0, self.Width, self.Height), FForeImage);
FForeImage.Assign(Bmp);
bmp.Free;
FGetForeImage:=true;
end;
MinSize := Min(self.Width + 2, self.Height + 2);
FillSize := Trunc((self.Width - 4) * (PercentDone / 100));
DstRect := Rect(2, 2, FillSize + 2, self.Height -2);
Brush.Color := BackColor;
Brush.Style := bsSolid;
Pen.Color := cl3DLight;
CopyMode := cmSrcCopy;
RoundRect(1, 1, self.Width, self.Height, MinSize div 4, MinSize div 4);
CopyRect(DstRect, FForeImage.Canvas, DstRect);
Brush.Style := bsclear;
RoundRect(1, 1, self.Width, self.Height, MinSize div 4, MinSize div 4);
Pen.Color := cl3DDkShadow;
RoundRect(0, 0, self.Width - 1, self.Height - 1, MinSize div 4, MinSize div 4);
end;
end;
function TColorProgress.GetPercentDone: longint;
begin
Result := trunc(100.0 * (FCurValue / FMaxValue));
end;
procedure TColorProgress.SetBackColor(AValue: TColor);
begin
if AValue <> FBackColor then
begin
FBackColor := AValue;
Refresh;
end;
end;
procedure TColorProgress.SetMinValue(AValue: longint);
begin
if AValue <> FMinValue then
begin
FMinValue := AValue;
Refresh;
end;
end;
procedure TColorProgress.SetMaxValue(AValue: longint);
begin
if AValue <> FMaxValue then
begin
FMaxValue := AValue;
Refresh;
end;
end;
procedure TColorProgress.SetShowText(AValue: boolean);
begin
if AValue <> FShowText then
begin
FShowText := AValue;
Refresh;
end;
end;
procedure TColorProgress.SetForeStyle(AValue: TFPBrushStyle);
begin
if AValue <> FForeStyle then
begin
FForeStyle := AValue;
Refresh;
end;
end;
procedure TColorProgress.SetForeImage(AValue: TBitmap);
var
NewBitmap: TBitmap;
begin
if AValue <> FForeImage then
begin
NewBitmap := TBitmap.Create;
NewBitmap.Assign(AValue);
FForeImage.Height := self.Height;
FForeImage.Width := self.Width;
FForeImage.Canvas.StretchDraw(Rect(0, 0, Width, Height-1), NewBitmap);
NewBitmap.Free;
Refresh;
end;
end;
procedure TColorProgress.SetGaugeKind(const AValue: TColorProgressKind);
begin
if AValue <> FKind then
begin
FKind := AValue;
Refresh;
end;
end;
procedure TColorProgress.SetProgress(AValue: longint);
begin
if AValue < FMinValue then
AValue := FMinValue
else if AValue > FMaxValue then
AValue := FMaxValue;
if FCurValue <> AValue then
begin
FCurValue := AValue;
Refresh;
end;
end;
procedure TColorProgress.AddProgress(AValue: longint);
begin
Progress := FCurValue + AValue;
Refresh;
end;
initialization
{$I colorprogress.lrs}
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the GNU General Public License
Version 2.0 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.gnu.org/copyleft/gpl.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Initial Developer of the Original Code is Michael Elsdörfer.
All Rights Reserved.
$Id$
You may retrieve the latest version of this file at the Corporeal
Website, located at http://www.elsdoerfer.info/corporeal
Known Issues:
-----------------------------------------------------------------------------}
unit AboutFormUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, pngimage, JvExControls, ShellApi, Credits,
gnugettext;
type
TAboutForm = class(TForm)
ScrollingCredits: TScrollingCredits;
BottomPanel: TPanel;
OKButton: TButton;
Panel1: TPanel;
WebsiteLink: TLabel;
VersionLabel: TLabel;
procedure FormCreate(Sender: TObject);
procedure WebsiteLinkClick(Sender: TObject);
procedure WebsiteLinkMouseLeave(Sender: TObject);
procedure WebsiteLinkMouseEnter(Sender: TObject);
end;
var
AboutForm: TAboutForm;
implementation
uses
Core, VistaCompat, VersionInfo;
const
CreditsString =
'&b&uCorporeal Password Store'#13#10+
'Version %VERSION%'#13#10+
''#13#10+
'2007-2011 by Michael Elsd'#246'rfer'#13#10+
'<michael@elsdoerfer.com>'#13#10+
''#13#10+
''#13#10+
''#13#10+
'&bBuilt in Delphi'#13#10+
''#13#10+
''#13#10+
''#13#10+
'&b&uComponents && Libraries'#13#10+
''#13#10+
'&iIn no particular order'#13#10+
''#13#10+
'&bToolbar2000'#13#10+
'By Jordan Russell'#13#10+
'&ijrsoftware.org'#13#10+
''#13#10+
'&bSpTBX'#13#10+
'By Robert Lee'#13#10+
'Licensed under MPL'#13#10+
'&iclub.telepolis.com/silverpointdev'#13#10+
''#13#10+
'&bVirtualTreeView'#13#10+
'By Mike Lischke and contributors'#13#10+
'Licensed under MPL'#13#10+
'&idelphi-gems.com'#13#10+
''#13#10+
'&bDCPCiphers'#13#10+
'By David Barton'#13#10+
'&icityinthesky.co.uk'#13#10+
''#13#10+
'&bJCL/JVCL'#13#10+
'Licensed under MPL'#13#10+
'&idelphi-jedi.org'#13#10+
''#13#10+
'&bPngComponents'#13#10+
'By Martijn Saly'#13#10+
'&ithany.org'#13#10+
''#13#10+
'&bOpenXML'#13#10+
'By Dieter Köhler'#13#10+
'Licensed under MPL'#13#10+
'&iphilo.de'#13#10+
''#13#10+
'&bEurekaLog'#13#10+
'By Fabio Dell''Aria'#13#10+
'&ieurekalog.com'#13#10+
''#13#10+
'&bTMS TaskDialog'#13#10+
'By TMS Software'#13#10+
'&itmssoftware.com'#13#10+
''#13#10+
''#13#10+
''#13#10+
''#13#10+
'&b&uInspired by'#13#10+
''#13#10+
'KeePass Password Store'#13#10+
''#13#10+
''#13#10+
''#13#10+
''#13#10+
'&b&uApplication Toolbar Icons'#13#10+
''#13#10+
'iconaholic.com'#13#10+
''#13#10+
''#13#10+
''#13#10+
'&b&uShoutouts'#13#10+
''#13#10+
'&iOther great software used'#13#10+
'&iduring this production'#13#10+
''#13#10+
'FinalBuilder'#13#10+
'InnoSetup'#13#10+
'SmartInspect'#13#10+
''#13#10+
''#13#10+
''#13#10+
''#13#10+
''#13#10+
''#13#10+
''#13#10+
''#13#10+
'&iI saved Latin. What did you ever do?';
{$R *.dfm}
procedure TAboutForm.FormCreate(Sender: TObject);
var
C: string;
begin
// localize
TP_GlobalIgnoreClass(TScrollingCredits);
TranslateComponent(Self);
// use font setting of os (mainly intended for new vista font)
SetDesktopIconFonts(Self.Font);
ScrollingCredits.CreditsFont.Assign(Self.Font);
// init gui
Self.Caption := Format(_('About %s'), [AppShortName]);
VersionLabel.Caption := Format(_('Version %s'), [MakeVersionString(vsfFull)]);
WebsiteLink.Caption := 'elsdoerfer.com/corporeal';
// Prepare credits string (replace version number etc)
C := CreditsString;
C := StringReplace(C, '%VERSION%', AppVersion, [rfIgnoreCase, rfReplaceAll]);
ScrollingCredits.Credits.Text := C;
ScrollingCredits.Animate := True;
end;
procedure TAboutForm.WebsiteLinkClick(Sender: TObject);
begin
ShellExecute(Application.Handle, '', AppWebsiteUrl, '', '', SW_SHOWNORMAL);
end;
procedure TAboutForm.WebsiteLinkMouseEnter(Sender: TObject);
begin
with WebsiteLink.Font do Style := Style + [fsUnderline];
end;
procedure TAboutForm.WebsiteLinkMouseLeave(Sender: TObject);
begin
with WebsiteLink.Font do Style := Style - [fsUnderline];
end;
end.
|
unit ncaFrmConfigPosVenda;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ncaFrmBaseOpcaoImgTxtCheckBox, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Menus, StdCtrls,
cxRadioGroup, cxButtons, cxLabel, cxCheckBox, PngImage, ExtCtrls, LMDControl,
LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel,
frxClass;
type
TFrmConfigPosVenda = class(TFrmBaseOpcaoImgTxtCheckBox)
rgNada: TcxRadioButton;
rgOk: TcxRadioButton;
rgNovaVenda: TcxRadioButton;
procedure CBClick(Sender: TObject);
private
function GetBtnDef: Byte;
procedure SetBtnDef(const Value: Byte);
{ Private declarations }
public
procedure Ler; override;
procedure Salvar; override;
function Alterou: Boolean; override;
procedure Renumera; override;
function NumItens: Integer; override;
procedure EnableDisable;
property BtnDef: Byte
read GetBtnDef write SetBtnDef;
{ Public declarations }
end;
var
FrmConfigPosVenda: TFrmConfigPosVenda;
implementation
uses ncClassesBase;
{$R *.dfm}
{ TFrmConfigPosVenda }
function TFrmConfigPosVenda.Alterou: Boolean;
begin
Result := (CB.Checked <> gConfig.TelaPosVenda_Mostrar) or (BtnDef <> gConfig.TelaPosVenda_BtnDef);
end;
procedure TFrmConfigPosVenda.CBClick(Sender: TObject);
begin
inherited;
EnableDisable;
end;
procedure TFrmConfigPosVenda.EnableDisable;
begin
rgNovaVenda.Enabled := CB.Checked;
rgOk.Enabled := CB.Checked;
rgNada.Enabled := CB.Checked;
end;
function TFrmConfigPosVenda.GetBtnDef: Byte;
begin
if rgNovaVenda.Checked then
Result := 1
else
if rgOk.Checked then
Result := 2
else
Result := 0;
end;
procedure TFrmConfigPosVenda.Ler;
begin
inherited;
CB.Checked := gConfig.TelaPosVenda_Mostrar;
BtnDef := gConfig.TelaPosVenda_BtnDef;
EnableDisable;
end;
function TFrmConfigPosVenda.NumItens: Integer;
begin
Result := 4;
end;
procedure TFrmConfigPosVenda.Renumera;
begin
inherited;
RenumRB(rgNovaVenda, 1);
RenumRB(rgOk, 2);
RenumRB(rgNada, 3);
end;
procedure TFrmConfigPosVenda.Salvar;
begin
inherited;
gConfig.TelaPosVenda_Mostrar := CB.Checked;
gConfig.TelaPosVenda_BtnDef := BtnDef;
end;
procedure TFrmConfigPosVenda.SetBtnDef(const Value: Byte);
begin
case Value of
1 : rgNovaVenda.Checked := True;
2 : rgOk.Checked := True;
else
rgNada.Checked := True;
end;
end;
end.
|
unit UGameDataBase;
interface
uses
Windows,Classes,SyncObjs;
const
C_WORLD_DATA = 2000;
C_ITEM_DATA = 2001;
C_HERO_DATA = 2002;
C_ACT_DATA_DEL = 10;
C_ACT_DATA_SUCC = 20;
C_ACT_DATA_ERR = 30;
type
FActionItemCallBack = function (ItemIndex:Integer;pNode:Pointer):Integer of object;
TGameDataBase = class
private
mDataName:string;
mDataType:Cardinal;
mList:TList;
mCri:TCriticalSection;
function GetDataCount: Cardinal;
public
constructor Create(_DataName:string;_DataType:Cardinal);
destructor Destroy; override;
{添加对象}
function AddItem(P:Pointer):Integer;
{操作对象,使用回调函数实现,如果要删除对象,则回调返回C_ACT_DATA_DEL即可}
function ActionItem(ActionItemCallBack:FActionItemCallBack):Integer;
{清空对象列表}
procedure Clear();
{数据类型}
property DataType:Cardinal read mDataType;
{数据数量}
property DataCount:Cardinal read GetDataCount;
end;
implementation
{ TGameDataBase }
function TGameDataBase.ActionItem(ActionItemCallBack: FActionItemCallBack): Integer;
var
i:Integer;
Res:Integer;
begin
Result:= C_ACT_DATA_ERR;
try
try
if mList.Count > 0 then
begin
for i := mList.Count - 1 downto 0 do
begin
if Assigned(ActionItemCallBack) then
begin
Res:=ActionItemCallBack(i,mList[i]);
case Res of
C_ACT_DATA_DEL:begin
TObject(mList[i]).Free;
mList.Delete(i);
Result:=C_ACT_DATA_SUCC;
end;
else
Result:=C_ACT_DATA_SUCC;
end;
end;
end;
end;
except
Result:=-1;
end;
finally
mCri.Leave;
end;
end;
function TGameDataBase.AddItem(P: Pointer): Integer;
begin
mCri.Enter;
Result:=mList.Add(p);
mCri.Leave;
end;
procedure TGameDataBase.Clear;
var
i:Integer;
begin
mCri.Enter;
if mList.Count > 0 then
begin
for I := 0 to mList.Count - 1 do
begin
TObject(mList[i]).Free;
end;
mList.Clear;
end;
mCri.Leave;
end;
constructor TGameDataBase.Create(_DataName:string;_DataType:Cardinal);
begin
mDataType:=_DataType;
mDataName:=_DataName;
mList:=TList.Create;
mCri:=TCriticalSection.Create;
end;
destructor TGameDataBase.Destroy;
begin
inherited;
Clear;
mList.Free;
mCri.Free;
end;
function TGameDataBase.GetDataCount: Cardinal;
begin
Result:= mList.Count;
end;
end.
|
{***************************************************************
*
* Project : Proxy
* Unit Name: Main
* Purpose : Demonstrates using mapped port component to create a simple proxy server
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:54:50
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit Main;
interface
uses
{$IFDEF Linux}
QControls, QStdCtrls, QGraphics, QForms, QDialogs,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, stdctrls,
{$ENDIF}
SysUtils, Classes, IdBaseComponent, IdComponent, IdTCPServer, IdMappedPortTCP;
type
TForm1 = class(TForm)
Memo1: TMemo;
IdMappedPortTCP1 : TIdMappedPortTCP;
private
public
end;
var
Form1: TForm1;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
end.
|
unit IdIntercept;
interface
uses
Classes,
IdBaseComponent, IdSocketHandle;
type
TIdConnectionIntercept = class(TIdBaseComponent)
protected
FBinding: TIdSocketHandle;
FOnConnect: TNotifyEvent;
FRecvHandling: Boolean;
FSendHandling: Boolean;
FIsClient: Boolean;
public
procedure Connect(ABinding: TIdSocketHandle); virtual;
procedure DataReceived(var ABuffer; const AByteCount: integer); virtual;
procedure DataSent(var ABuffer; const AByteCount: integer); virtual;
procedure Disconnect; virtual;
function Recv(var ABuf; ALen: Integer): Integer; virtual;
function Send(var ABuf; ALen: Integer): Integer; virtual;
property Binding: TIdSocketHandle read FBinding;
property IsClient: Boolean read FIsClient;
property RecvHandling: boolean read FRecvHandling;
property SendHandling: boolean read FSendHandling;
published
property OnConnect: TNotifyEvent read FOnConnect write FOnConnect;
end;
TIdServerIntercept = class(TIdBaseComponent)
public
procedure Init; virtual; abstract;
function Accept(ABinding: TIdSocketHandle): TIdConnectionIntercept; virtual;
abstract;
end;
implementation
procedure TIdConnectionIntercept.Disconnect;
begin
FBinding := nil;
end;
procedure TIdConnectionIntercept.DataReceived(var ABuffer; const AByteCount:
integer);
begin
end;
function TIdConnectionIntercept.Recv(var ABuf; ALen: Integer): Integer;
begin
result := 0;
end;
function TIdConnectionIntercept.Send(var ABuf; ALen: Integer): Integer;
begin
result := 0;
end;
procedure TIdConnectionIntercept.DataSent(var ABuffer; const AByteCount:
integer);
begin
end;
procedure TIdConnectionIntercept.Connect(ABinding: TIdSocketHandle);
begin
FBinding := ABinding;
if assigned(FOnConnect) then
begin
FOnConnect(Self);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC ADO Local SQL adapter }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.ADO.LocalSQL;
interface
implementation
uses
System.SysUtils, Winapi.OleDB, Winapi.ADOInt, Data.Win.ADODB,
FireDAC.Stan.Factory,
FireDAC.Phys.Intf;
type
TFDADOLocalSQLAdapter = class (TFDObject, IFDPhysLocalSQLAdapter)
private
FDataSet: TCustomADODataSet;
FTxSupported: Integer;
protected
// private
function GetFeatures: TFDPhysLocalSQLAdapterFeatures;
function GetCachedUpdates: Boolean;
procedure SetCachedUpdates(const AValue: Boolean);
function GetSavePoint: Int64;
procedure SetSavePoint(const AValue: Int64);
function GetIndexFieldNames: String;
procedure SetIndexFieldNames(const AValue: String);
function GetDataSet: TObject;
procedure SetDataSet(ADataSet: TObject);
function GetConn: NativeUInt;
// public
function ApplyUpdates(AMaxErrors: Integer = -1): Integer;
procedure CommitUpdates;
procedure CancelUpdates;
procedure SetRange(const AStartValues, AEndValues: array of const;
AStartExclusive: Boolean = False; AEndExclusive: Boolean = False);
procedure CancelRange;
function IsPKViolation(AExc: Exception): Boolean;
end;
{-------------------------------------------------------------------------------}
{ TFDADOLocalSQLAdapter }
{-------------------------------------------------------------------------------}
// General
function TFDADOLocalSQLAdapter.GetFeatures: TFDPhysLocalSQLAdapterFeatures;
procedure UpdateTxSup;
begin
if (FDataSet.Connection <> nil) and FDataSet.Connection.Connected and
(FDataSet.Connection.Properties['Transaction DDL'].Value > DBPROPVAL_TC_NONE) then
FTxSupported := 1
else
FTxSupported := 0;
end;
begin
Result := [afCachedUpdates, afIndexFieldNames, afFilters];
if FTxSupported = -1 then
UpdateTxSup;
if FTxSupported <> 0 then
Include(Result, afTransactions);
end;
{-------------------------------------------------------------------------------}
function TFDADOLocalSQLAdapter.GetDataSet: TObject;
begin
Result := FDataSet;
end;
{-------------------------------------------------------------------------------}
procedure TFDADOLocalSQLAdapter.SetDataSet(ADataSet: TObject);
begin
FDataSet := ADataSet as TCustomADODataSet;
FTxSupported := -1;
end;
{-------------------------------------------------------------------------------}
function TFDADOLocalSQLAdapter.GetConn: NativeUInt;
begin
Result := NativeUInt(FDataSet.Connection);
end;
{-------------------------------------------------------------------------------}
function TFDADOLocalSQLAdapter.IsPKViolation(AExc: Exception): Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
// Cached Updates management
function TFDADOLocalSQLAdapter.GetCachedUpdates: Boolean;
begin
Result := (FDataSet.CursorLocation = clUseClient) and
(FDataSet.CursorType in [ctKeySet, ctStatic]) and
(FDataSet.LockType = ltBatchOptimistic);
end;
{-------------------------------------------------------------------------------}
procedure TFDADOLocalSQLAdapter.SetCachedUpdates(const AValue: Boolean);
begin
if AValue then begin
FDataSet.CursorLocation := clUseClient;
FDataSet.CursorType := ctKeySet;
FDataSet.LockType := ltBatchOptimistic;
end
else
FDataSet.LockType := ltOptimistic;
end;
{-------------------------------------------------------------------------------}
function TFDADOLocalSQLAdapter.ApplyUpdates(AMaxErrors: Integer): Integer;
begin
try
Result := 0;
FDataSet.UpdateBatch(arAll);
except
Result := 1;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDADOLocalSQLAdapter.CommitUpdates;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDADOLocalSQLAdapter.CancelUpdates;
begin
FDataSet.CancelBatch(arAll);
end;
{-------------------------------------------------------------------------------}
function TFDADOLocalSQLAdapter.GetSavePoint: Int64;
begin
// nothing
Result := -1;
end;
{-------------------------------------------------------------------------------}
procedure TFDADOLocalSQLAdapter.SetSavePoint(const AValue: Int64);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
// Ranges
procedure TFDADOLocalSQLAdapter.SetRange(const AStartValues, AEndValues: array of const;
AStartExclusive, AEndExclusive: Boolean);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDADOLocalSQLAdapter.CancelRange;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
// Indexes
type
__TCustomADODataSet = class(TCustomADODataSet);
function TFDADOLocalSQLAdapter.GetIndexFieldNames: String;
begin
Result := StringReplace(StringReplace(__TCustomADODataSet(FDataSet).IndexFieldNames,
' DESC', ':D', [rfReplaceAll]), ' ASC', ':A', [rfReplaceAll]);
end;
{-------------------------------------------------------------------------------}
procedure TFDADOLocalSQLAdapter.SetIndexFieldNames(const AValue: String);
begin
__TCustomADODataSet(FDataSet).IndexFieldNames := StringReplace(StringReplace(AValue,
':D', ' DESC', [rfReplaceAll]), ':A', ' ASC', [rfReplaceAll]);
end;
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
initialization
oFact := TFDMultyInstanceFactory.Create(TFDADOLocalSQLAdapter,
IFDPhysLocalSQLAdapter, 'TCustomADODataSet');
finalization
FDReleaseFactory(oFact);
end.
|
{$MODE OBJFPC}
program MaxNumber;
const
InputFile = 'NUMBER.INP';
OutputFile = 'NUMBER.OUT';
max = 1001;
type
TStr = AnsiString;
TLine = array[0..max] of TStr;
PLine = ^TLine;
var
a, b: TStr;
m, n: Integer;
L1, L2: TLine;
Current, Next: PLine;
procedure Enter;
var
f: TextFile;
i: Integer;
begin
AssignFile(f, InputFile); Reset(f);
Readln(f, a);
m := Length(a);
Readln(f, b);
n := Length(b);
CloseFile(f);
for i := 1 to m do
begin
L1[i] := '';
L2[i] := '';
end;
Current := @L1;
Next := @L2;
end;
procedure Refine(var s: TStr);
var
i: Integer;
begin
i := 1;
while (i < Length(s)) and (s[i] = '0') do Inc(i);
Delete(s, 1, i - 1);
end;
function AddChar(const s: TStr; Digit: Char): TStr;
begin
if (Digit <> '0') or (s <> '') then Result := s + Digit
else Result := '';
end;
function Compare(const a, b: TStr): Integer;
begin
if Length(a) > Length(b) then Exit(1)
else if Length(a) < Length(b) then Exit(-1);
if a > b then Exit(1)
else if a < b then Exit(-1);
Result := 0;
end;
function GetMax(const s1, s2: TStr): TStr;
begin
if Compare(s1, s2) > 0 then Result := s1
else Result := s2;
end;
procedure Optimize;
var
t, i, j: Integer;
temp: PLine;
begin
for j := 0 to n do Current^[j] := '';
Next^[0] := '';
for i := 1 to m do
begin
for j := 1 to n do
if a[i] = b[j] then
Next^[j] := AddChar(Current^[j - 1], b[j])
else
Next^[j] := GetMax(Next^[j - 1], Current^[j]);
temp := Current; Current := Next; Next := temp;
end;
end;
procedure PrintResult;
var
s: TStr;
i: Integer;
f: TextFile;
begin
s := Current^[n];
Refine(s);
if s = '' then s := '0';
AssignFile(f, OutputFile); Rewrite(f);
try
Writeln(f, s);
finally
CloseFile(f);
end;
end;
begin
Enter;
Optimize;
PrintResult;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Datasnap.DSProxyUtils;
interface
uses
System.SysUtils;
type
EDSProxyException = class(Exception)
end;
TDSProxyUtils = class sealed
class function CompressDirectory(const DirectoryName: String; OutputFileName: String): boolean;
class function IsValidZipFile(FileName: String): boolean;
end;
implementation
uses
System.Zip;
{ TDSProxyUtils }
class function TDSProxyUtils.CompressDirectory(const DirectoryName: String;
OutputFileName: String): boolean;
begin
TZipFile.ZipDirectoryContents(OutputFileName, DirectoryName);
Result := True;
end;
class function TDSProxyUtils.IsValidZipFile(FileName: String): boolean;
begin
Result := TZipFile.IsValid(FileName);
end;
end.
|
//Written for TU Berlin
//Compiled with fpc
Program yingyang;
Uses Math;
const
scale_x=2;
scale_y=1;
black='#';
white='.';
clear=' ';
function inCircle(centre_x:Integer;centre_y:Integer;radius:Integer;x:Integer;y:Integer):Boolean ;
begin
inCircle:=power(x-centre_x,2)+power(y-centre_y,2)<=power(radius,2);
end;
function bigCircle(radius:Integer;x:Integer;y:Integer):Boolean ;
begin
bigCircle:=inCircle(0,0,radius,x,y);
end;
function whiteSemiCircle(radius:Integer;x:Integer;y:Integer):Boolean ;
begin
whiteSemiCircle:=inCircle(0,radius div 2 ,radius div 2,x,y);
end;
function smallBlackCircle(radius:Integer;x:Integer;y:Integer):Boolean ;
begin
smallBlackCircle:=inCircle(0,radius div 2 ,radius div 6,x,y);
end;
function blackSemiCircle(radius:Integer;x:Integer;y:Integer):Boolean ;
begin
blackSemiCircle:=inCircle(0,-radius div 2 ,radius div 2,x,y);
end;
function smallWhiteCircle(radius:Integer;x:Integer;y:Integer):Boolean ;
begin
smallWhiteCircle:=inCircle(0,-radius div 2 ,radius div 6,x,y);
end;
var
radius,sy,sx,x,y:Integer;
begin
writeln('Please type a radius:');
readln(radius);
if radius<3 then begin writeln('A radius bigger than 3');halt end;
sy:=round(radius*scale_y);
while(sy>=-round(radius*scale_y)) do begin
sx:=-round(radius*scale_x);
while(sx<=round(radius*scale_x)) do begin
x:=sx div scale_x;
y:=sy div scale_y;
if bigCircle(radius,x,y) then begin
if (whiteSemiCircle(radius,x,y)) then if smallblackCircle(radius,x,y) then write(black) else write(white) else if blackSemiCircle(radius,x,y) then if smallWhiteCircle(radius,x,y) then write(white) else write(black) else if x>0 then write(white) else write(black);
end
else write(clear);
sx:=sx+1
end;
writeln;
sy:=sy-1;
end;
end.
|
unit UnitFormMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, Psock, NMFtp, ComCtrls, Grids, Outline, FileCtrl, StdCtrls;
type
PPath = ^TPath;
TPath = string;
TFormMain = class(TForm)
MainMenu: TMainMenu;
MainConnect: TMenuItem;
NMFTP: TNMFTP;
StatusBar: TStatusBar;
GroupBox1: TGroupBox;
DriveComboBox: TDriveComboBox;
DirectoryListBox: TDirectoryListBox;
FileListBox: TFileListBox;
ListView: TListView;
GroupBox2: TGroupBox;
ButtonStart: TButton;
TreeView: TTreeView;
ButtonGetAllFiles: TButton;
PopupMenu1: TPopupMenu;
Delete: TMenuItem;
procedure MainConnectClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ButtonGetAllFilesClick(Sender: TObject);
procedure NMFTPDisconnect(Sender: TObject);
procedure NMFTPConnect(Sender: TObject);
procedure NMFTPPacketRecvd(Sender: TObject);
procedure NMFTPPacketSent(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure NMFTPError(Sender: TComponent; Errno: Word; Errmsg: String);
procedure PopupMenu1Popup(Sender: TObject);
procedure TreeViewDeletion(Sender: TObject; Node: TTreeNode);
procedure DeleteClick(Sender: TObject);
procedure ButtonStartClick(Sender: TObject);
private
{ Private declarations }
DelFile, DelDir : TStringList;
procedure VytvorStrom( ToNode : TTreeNode; Path : string );
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
uses UnitFormConnect;
{$R *.DFM}
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
procedure TFormMain.FormCreate(Sender: TObject);
var PNewPath : PPath;
begin
DelFile := TStringList.Create;
DelDir := TStringList.Create;
New( PNewPath );
PNewPath^ := 'C:\Rado\www\x';
TreeView.Items.AddChildObject( TreeView.Items[0] , 'NEW' , PNewPath );
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
procedure TFormMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// if NMFTP.Connected then Action := caNone;
Action := caFree;
DelFile.Free;
DelDir.Free;
end;
//==============================================================================
//==============================================================================
//
// Main Menu
//
//==============================================================================
//==============================================================================
procedure TFormMain.MainConnectClick(Sender: TObject);
begin
if not NMFTP.Connected then FormConnect.MyShowModal( NMFTP )
else NMFTP.Disconnect;
end;
//==============================================================================
//==============================================================================
//
// NMFTP
//
//==============================================================================
//==============================================================================
procedure TFormMain.NMFTPConnect(Sender: TObject);
begin
DelFile.Clear;
DelDir.Clear;
StatusBar.Panels[0].Text := 'Connected';
MainConnect.Caption := '&Disconnect';
ButtonGetAllFiles.Enabled := True;
ListView.Items.Clear;
TreeView.Items.Clear;
TreeView.Items.Add( nil , NMFTP.Host );
end;
procedure TFormMain.NMFTPDisconnect(Sender: TObject);
begin
StatusBar.Panels[0].Text := 'Disconnected';
MainConnect.Caption := '&Connect';
ButtonGetAllFiles.Enabled := False;
end;
procedure TFormMain.NMFTPPacketRecvd(Sender: TObject);
begin
StatusBar.Panels[3].Text := 'Bytes recieved : '+IntToStr( NMFTP.BytesRecvd );
end;
procedure TFormMain.NMFTPPacketSent(Sender: TObject);
begin
StatusBar.Panels[2].Text := 'Bytes sent : '+IntToStr( NMFTP.BytesSent );
end;
procedure TFormMain.NMFTPError(Sender: TComponent; Errno: Word;
Errmsg: String);
begin
MessageDlg( 'Stala sa dáka chyba : '+Errmsg+' '+IntToStr( Errno ) , mtError , [mbOK] , 0 );
end;
//==============================================================================
//==============================================================================
//
// Tree view
//
//==============================================================================
//==============================================================================
procedure TFormMain.VytvorStrom( ToNode : TTreeNode; Path : string );
var ActualDir : string;
I : integer;
Files, Dirs : TStringList;
PNewPath : PPath;
begin
ActualDir := NMFTP.CurrentDir;
if Path <> '' then
begin
NMFTP.ChangeDir( Path );
Path := Path + '/';
end;
NMFTP.List;
Files := TStringList.Create;
Dirs := TStringList.Create;
for I := 0 to NMFTP.FTPDirectoryList.name.Count-1 do
case NMFTP.FTPDirectoryList.Attribute[I][1] of
'd' : Dirs.Add( NMFTP.FTPDirectoryList.name[I] );
'-' : Files.Add( NMFTP.FTPDirectoryList.name[I] );
end;
for I := 0 to Dirs.Count-1 do
begin
New( PNewPath );
PNewPath^ := ActualDir+'/'+Path+Dirs[I];
VytvorStrom( TreeView.Items.AddChildObject( ToNode , Dirs[I] , PNewPath ) , Dirs[I] );
end;
for I := 0 to Files.Count-1 do
begin
New( PNewPath );
PNewPath^ := ActualDir+'/'+Path+Files[I];
TreeView.Items.AddChildObject( ToNode , Files[I] , PNewPath );
end;
TreeView.Update;
NMFTP.ChangeDir( ActualDir );
Files.Free;
Dirs.Free;
end;
procedure TFormMain.PopupMenu1Popup(Sender: TObject);
begin
if TreeView.Selected = nil then exit;
TreeView.Selected.Selected := True;
end;
procedure TFormMain.TreeViewDeletion(Sender: TObject; Node: TTreeNode);
begin
if Node.Data <> nil then
Dispose( PPath( Node.Data ) );
end;
//==============================================================================
//==============================================================================
//
// Ostatné komponenty
//
//==============================================================================
//==============================================================================
procedure TFormMain.ButtonGetAllFilesClick(Sender: TObject);
begin
ButtonGetAllFiles.Enabled := False;
StatusBar.Panels[1].Text := 'Getting file structure ...';
MainConnect.Enabled := False;
with NMFTP do
begin
ParseList := True;
VytvorStrom( TreeView.Items[0] , '' );
end;
MainConnect.Enabled := True;
StatusBar.Panels[1].Text := 'File structure got';
end;
procedure TFormMain.DeleteClick(Sender: TObject);
var NewListItem : TListItem;
begin
if TreeView.Selected.Data = nil then exit;
NewListItem := ListView.Items.Add;
NewListItem.Caption := TPath( TreeView.Selected.Data^ );
NewListItem.SubItems.Add( 'DELETE' );
if TreeView.Selected.Count = 0 then DelFile.Add( TPath( TreeView.Selected.Data^ ) )
else DelDir.Add( TPath( TreeView.Selected.Data^ ) );
end;
procedure TFormMain.ButtonStartClick(Sender: TObject);
var I : integer;
begin
for I := 0 to DelDir.Count-1 do
NMFTP.RemoveDir( DelDir[I] );
for I := 0 to DelFile.Count-1 do
NMFTP.Delete( DelFile[I] );
ListView.Items.Clear;
DelFile.Clear;
DelDir.Clear;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC SQL Server driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Phys.MSSQL;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Error,
FireDAC.Phys, FireDAC.Phys.ODBCCli, FireDAC.Phys.ODBCWrapper, FireDAC.Phys.ODBCBase;
type
TFDMSSQLError = class;
EMSSQLNativeException = class;
TFDPhysMSSQLDriverLink = class;
TFDMSSQLError = class(TFDODBCNativeError)
private
FLine: Integer;
FMessageState: Integer;
FSeverity: Integer;
FProcName: String;
FServerName: String;
protected
procedure Assign(ASrc: TFDDBError); override;
procedure LoadFromStorage(const AStorage: IFDStanStorage); override;
procedure SaveToStorage(const AStorage: IFDStanStorage); override;
public
property Line: Integer read FLine;
property MessageState: Integer read FMessageState;
property Severity: Integer read FSeverity;
property ProcName: String read FProcName;
property ServerName: String read FServerName;
end;
EMSSQLNativeException = class(EODBCNativeException)
private
function GetErrors(AIndex: Integer): TFDMSSQLError;
protected
function GetErrorClass: TFDDBErrorClass; override;
public
function AppendError(AHandle: TODBCHandle; ARecNum: SQLSmallint;
const ASQLState: String; ANativeError: SQLInteger; const ADiagMessage,
AResultMessage, ACommandText, AObject: String;
AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError; override;
property Errors[Index: Integer]: TFDMSSQLError read GetErrors; default;
end;
[ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidLinux)]
TFDPhysMSSQLDriverLink = class(TFDPhysODBCBaseDriverLink)
private
FListServers: Boolean;
protected
function GetBaseDriverID: String; override;
public
constructor Create(AOwner: TComponent); override;
function GetServers(AList: TStrings; ARefresh: Boolean = False; AAsync: Boolean = False): Boolean;
published
property ListServers: Boolean read FListServers write FListServers default True;
end;
{-------------------------------------------------------------------------------}
implementation
uses
System.SysUtils,
{$IFDEF MSWINDOWS}
System.Win.ComObj,
{$ENDIF}
System.StrUtils, System.Variants, System.Threading, Data.DB,
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Factory, FireDAC.Stan.ResStrs,
FireDAC.Stan.Param, FireDAC.Stan.Option,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Phys.MSSQLMeta,
FireDAC.Phys.MSSQLCli, FireDAC.Phys.MSSQLWrapper, FireDAC.Phys.MSSQLDef;
const
C_2017_ODBC = 'ODBC DRIVER 17 FOR SQL SERVER';
C_2016_ODBC = 'ODBC DRIVER 13 FOR SQL SERVER';
C_2012_ODBC = 'ODBC DRIVER 11 FOR SQL SERVER';
{$IFDEF POSIX}
C_FreeTDS = 'FreeTDS';
C_FreeTDSLib = 'libtdsodbc.so';
{$ENDIF}
{$IFDEF MSWINDOWS}
C_2012_NC = 'SQL SERVER NATIVE CLIENT 11.0';
C_2008 = 'SQL SERVER NATIVE CLIENT 10.0';
C_2005 = 'SQL NATIVE CLIENT';
C_2000 = 'SQL SERVER';
{$ENDIF}
C_String = 'String';
C_Binary = 'Binary';
C_Choose = 'Choose';
type
TFDPhysMSSQLDriver = class;
TFDPhysMSSQLConnection = class;
TFDPhysMSSQLEventAlerter = class;
TFDPhysMSSQLCommand = class;
IFDPhysMSSQLDriver = interface
['{A52C2247-E07C-4BEB-821B-6DF097828ED1}']
// public
function GetServers(AList: TStrings; ARefresh, AAsync: Boolean): Boolean;
end;
TFDPhysMSSQLDriver = class(TFDPhysODBCDriverBase, IFDPhysMSSQLDriver)
private
FServers: TStringList;
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
procedure InternalLoad; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
procedure GetODBCConnectStringKeywords(AKeywords: TStrings); override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
// IFDPhysMSSQLDriver
function GetServers(AList: TStrings; ARefresh, AAsync: Boolean): Boolean;
public
constructor Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); override;
destructor Destroy; override;
function BuildODBCConnectString(const AConnectionDef: IFDStanConnectionDef): String; override;
end;
TFDPhysMSSQLConnection = class(TFDPhysODBCConnectionBase)
private
FCatalogCaseSensitive: Boolean;
FExtendedMetadata: Boolean;
FToolLib: TMSSQLToolLib;
FFileStreamSerialID: LongWord;
FFileStreamTxContext: TFDByteString;
FCompatibilityLevel: Integer;
procedure CheckPasswordChange;
protected
function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override;
function InternalCreateCommand: TFDPhysCommand; override;
function InternalCreateCommandGenerator(const ACommand:
IFDPhysCommand): TFDPhysCommandGenerator; override;
function InternalCreateMetadata: TObject; override;
procedure GetStrsMaxSizes(AStrDataType: SQLSmallint; AFixedLen: Boolean;
out ACharSize, AByteSize: Integer); override;
function GetExceptionClass: EODBCNativeExceptionClass; override;
procedure InternalSetMeta; override;
procedure InternalConnect; override;
procedure InternalDisconnect; override;
procedure SetupConnection; override;
procedure InternalChangePassword(const AUserName, AOldPassword,
ANewPassword: String); override;
procedure InternalAnalyzeSession(AMessages: TStrings); override;
function GetFileStream(const ABlobPath: String; AMode: TFDStreamMode;
AOptions: LongWord; AOwningObj: TObject): TStream;
end;
TFDPhysMSSQLEventAlerter = class (TFDPhysEventAlerter)
private
FWaitConnection: IFDPhysConnection;
FWaitCommand: IFDPhysCommand;
FMessageTab: TFDDatSTable;
FWaitThread: TThread;
FServiceName, FQueueName, FEventTabName: String;
FDropService, FDropQueue, FEventTab: Boolean;
function ProcessNotifications: Boolean;
procedure RegisterQuery(AStmt: TODBCCommandStatement; const AEventName: String);
procedure RegisterNotifications;
protected
procedure InternalAllocHandle; override;
procedure InternalRegister; override;
procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override;
procedure InternalAbortJob; override;
procedure InternalUnregister; override;
procedure InternalReleaseHandle; override;
procedure InternalSignal(const AEvent: String; const AArgument: Variant); override;
procedure InternalChangeHandlerModified(const AHandler: IFDPhysChangeHandler;
const AEventName: String; AOperation: TOperation); override;
end;
TFDPhysMSSQLCommand = class(TFDPhysODBCCommand)
private
FEventAlerter: TFDPhysMSSQLEventAlerter;
FEventName: String;
protected
// TFDPhysCommand
procedure InternalPrepare; override;
// TFDPhysODBCCommand
procedure CreateParamColumns(AParam: TFDParam); override;
procedure CreateParamColumnInfos(ApInfo: PFDODBCParInfoRec; AParam: TFDParam); override;
function GetIsCustomParam(ADataType: TFDDataType): Boolean; override;
procedure SetCustomParamValue(ADataType: TFDDataType; AVar: TODBCVariable;
AParam: TFDParam; AVarIndex, AParIndex: Integer); override;
procedure GetCustomParamValue(ADataType: TFDDataType; AVar: TODBCVariable;
AParam: TFDParam; AVarIndex, AParIndex: Integer); override;
end;
{-------------------------------------------------------------------------------}
{ TFDMSSQLError }
{-------------------------------------------------------------------------------}
procedure TFDMSSQLError.Assign(ASrc: TFDDBError);
begin
inherited Assign(ASrc);
if ASrc is TFDMSSQLError then begin
FLine := TFDMSSQLError(ASrc).FLine;
FMessageState := TFDMSSQLError(ASrc).FMessageState;
FSeverity := TFDMSSQLError(ASrc).FSeverity;
FProcName := TFDMSSQLError(ASrc).FProcName;
FServerName := TFDMSSQLError(ASrc).FServerName;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDMSSQLError.LoadFromStorage(const AStorage: IFDStanStorage);
begin
inherited LoadFromStorage(AStorage);
FLine := AStorage.ReadInteger('Line', 0);
FMessageState := AStorage.ReadInteger('MessageState', 0);
FSeverity := AStorage.ReadInteger('Severity', 0);
FProcName := AStorage.ReadString('ProcName', '');
FServerName := AStorage.ReadString('ServerName', '');
end;
{-------------------------------------------------------------------------------}
procedure TFDMSSQLError.SaveToStorage(const AStorage: IFDStanStorage);
begin
inherited SaveToStorage(AStorage);
AStorage.WriteInteger('Line', Line, 0);
AStorage.WriteInteger('MessageState', MessageState, 0);
AStorage.WriteInteger('Severity', Severity, 0);
AStorage.WriteString('ProcName', ProcName, '');
AStorage.WriteString('ServerName', ServerName, '');
end;
{-------------------------------------------------------------------------------}
{ EMSSQLNativeException }
{-------------------------------------------------------------------------------}
function EMSSQLNativeException.AppendError(AHandle: TODBCHandle;
ARecNum: SQLSmallint; const ASQLState: String; ANativeError: SQLInteger;
const ADiagMessage, AResultMessage, ACommandText, AObject: String;
AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError;
var
sObj, sUDiagMessage, sRes: String;
i, j: Integer;
oErr: TFDMSSQLError;
oStmt: TODBCStatementBase;
procedure ExtractObjName;
var
i1, i2: Integer;
begin
i1 := Pos('''', ADiagMessage);
if i1 <> 0 then begin
i2 := Pos('''', ADiagMessage, i1 + 1);
if i2 <> 0 then
sObj := Copy(ADiagMessage, i1 + 1, i2 - i1 - 1);
end;
end;
begin
// following is not supported by MSSQL:
// ekNoDataFound
// ekUserPwdWillExpire
sObj := AObject;
sRes := AResultMessage;
case ANativeError of
1204,
1205,
1222:
AKind := ekRecordLocked;
2601,
2627:
begin
AKind := ekUKViolated;
// first 'xxxx' - constraint name
// second 'xxxx' - table name
ExtractObjName;
end;
547:
begin
sUDiagMessage := UpperCase(ADiagMessage);
if (Pos('COLUMN FOREIGN KEY', sUDiagMessage) <> 0) or
(Pos('CONFLICTED', sUDiagMessage) <> 0) and
(Pos('REFERENCE', sUDiagMessage) <> 0) and
(Pos('CONSTRAINT', sUDiagMessage) <> 0) then begin
AKind := ekFKViolated;
// first 'xxxx' - constraint name
// next 3 'xxxx' - full column name (database, table, column)
ExtractObjName;
end;
end;
208,
3701:
begin
AKind := ekObjNotExists;
// first 'xxxx' - object name
ExtractObjName;
end;
18456,
18463,
18464,
18465,
18466,
18467,
18468:
AKind := ekUserPwdInvalid;
18487,
18488:
AKind := ekUserPwdExpired;
170:
// strange "incorrect syntax near '{'" at Array INSERT execute,
// for example on PKSP_Merge DOCS_OUT table
if (Pos('''{''', UpperCase(ADiagMessage)) <> 0) and (Pos('{', ACommandText) = 0) and
(AHandle is TODBCCommandStatement) and (TODBCCommandStatement(AHandle).PARAMSET_SIZE > 1) then
AKind := ekArrExecMalfunc;
0:
if ASQLState = '01000' then begin
AKind := ekServerOutput;
i := 0;
for j := 1 to 3 do
i := Pos(']', sRes, i + 1);
if i <> 0 then
sRes := Copy(sRes, i + 1, Length(sRes));
end
else if ASQLState = 'HY000' then begin
if Pos('Connection may have been terminated by the server', ADiagMessage) <> 0 then
AKind := ekServerGone;
end
// strange errors at Array DML:
// - "Invalid character value for cast specification", 22018.
// GS has provided the bug report for 22018.
// - "Invalid cursor state", 24000.
// FDQA fails on Batch execute -> Error handling on MSSQL 2005 with 24000 state.
// - "String data, length mismatch", 22026
// Insert into VARBINARY(MAX) on MSSQL 2008 may give 22026.
else if ((ASQLState = '22018') or (ASQLState = '24000') or (ASQLState = '22026')) and
(AHandle is TODBCCommandStatement) and (TODBCCommandStatement(AHandle).PARAMSET_SIZE > 1) then
AKind := ekArrExecMalfunc;
201,
8144:
AKind := ekInvalidParams;
end;
Result := inherited AppendError(AHandle, ARecNum, ASQLState, ANativeError,
ADiagMessage, sRes, ACommandText, sObj, AKind, ACmdOffset, ARowIndex);
if AHandle is TODBCStatementBase then begin
oErr := TFDMSSQLError(Result);
oStmt := TODBCStatementBase(AHandle);
try
oStmt.IgnoreErrors := True;
oErr.FLine := oStmt.DIAG_SS_LINE[ARecNum];
oErr.FMessageState := oStmt.DIAG_SS_MSGSTATE[ARecNum];
oErr.FSeverity := oStmt.DIAG_SS_SEVERITY[ARecNum];
oErr.FProcName := oStmt.DIAG_SS_PROCNAME[ARecNum];
if oErr.ObjName = '' then
oErr.ObjName := oErr.FProcName;
oErr.FServerName := oStmt.DIAG_SS_SRVNAME[ARecNum];
finally
oStmt.IgnoreErrors := False;
end;
end;
end;
{-------------------------------------------------------------------------------}
function EMSSQLNativeException.GetErrorClass: TFDDBErrorClass;
begin
Result := TFDMSSQLError;
end;
{-------------------------------------------------------------------------------}
function EMSSQLNativeException.GetErrors(AIndex: Integer): TFDMSSQLError;
begin
Result := inherited Errors[AIndex] as TFDMSSQLError;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSSQLDriverLink }
{-------------------------------------------------------------------------------}
constructor TFDPhysMSSQLDriverLink.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FListServers := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLDriverLink.GetBaseDriverID: String;
begin
Result := S_FD_MSSQLId;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLDriverLink.GetServers(AList: TStrings; ARefresh: Boolean = False;
AAsync: Boolean = False): Boolean;
var
oDrv: IFDPhysMSSQLDriver;
begin
if FDPhysManager.State = dmsInactive then
FDPhysManager.Open;
DriverIntf.Employ;
try
Supports(DriverIntf, IFDPhysMSSQLDriver, oDrv);
Result := oDrv.GetServers(AList, ARefresh, AAsync);
finally
oDrv := nil;
DriverIntf.Vacate;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSSQLDriver }
{-------------------------------------------------------------------------------}
constructor TFDPhysMSSQLDriver.Create(AManager: TFDPhysManager;
const ADriverDef: IFDStanDefinition);
begin
inherited Create(AManager, ADriverDef);
FServers := TFDStringList.Create;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysMSSQLDriver.Destroy;
begin
FDFreeAndNil(FServers);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMSSQLDriver.GetBaseDriverID: String;
begin
Result := S_FD_MSSQLId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMSSQLDriver.GetBaseDriverDesc: String;
begin
Result := 'Microsoft SQL Server';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMSSQLDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.MSSQL;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMSSQLDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysMSSQLConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLDriver.InternalLoad;
begin
inherited InternalLoad;
if ODBCDriver = '' then
ODBCDriver := FindBestDriver(
{$IFDEF MSWINDOWS} [C_2012_NC, C_2016_ODBC, C_2012_ODBC, C_2017_ODBC, C_2008, C_2005, C_2000] {$ENDIF}
{$IFDEF POSIX} [C_2016_ODBC, C_2012_ODBC, C_2017_ODBC, C_FreeTDS], C_FreeTDSLib {$ENDIF}
);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLDriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysMSSQLConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLDriver.GetODBCConnectStringKeywords(AKeywords: TStrings);
begin
inherited GetODBCConnectStringKeywords(AKeywords);
AKeywords.Values[S_FD_ConnParam_Common_Password] := 'PWD';
AKeywords.Add(S_FD_ConnParam_Common_Server);
AKeywords.Add(S_FD_ConnParam_Common_Database);
AKeywords.Add(S_FD_ConnParam_MSSQL_Language);
AKeywords.Add(S_FD_ConnParam_MSSQL_Address);
AKeywords.Add(S_FD_ConnParam_MSSQL_Workstation + '=WSID');
{$IFDEF POSIX}
AKeywords.Add(S_FD_ConnParam_Common_Port);
{$ENDIF}
{$IFDEF MSWINDOWS}
AKeywords.Add(S_FD_ConnParam_MSSQL_Network);
AKeywords.Add(S_FD_ConnParam_Common_OSAuthent + '=Trusted_Connection');
AKeywords.Add(S_FD_ConnParam_MSSQL_MARS + '=MARS_Connection');
AKeywords.Add(S_FD_ConnParam_MSSQL_Encrypt);
{$ENDIF}
AKeywords.Add(S_FD_ConnParam_Common_ApplicationName + '=APP');
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLDriver.BuildODBCConnectString(const AConnectionDef: IFDStanConnectionDef): string;
begin
Result := inherited BuildODBCConnectString(AConnectionDef);
if ((CompareText(ODBCDriver, C_2012_ODBC) = 0) or
(CompareText(ODBCDriver, C_2016_ODBC) = 0)
{$IFDEF MSWINDOWS}
or (CompareText(ODBCDriver, C_2012_NC) = 0) or
(CompareText(ODBCDriver, C_2005) = 0) or
(CompareText(ODBCDriver, C_2008) = 0)
{$ENDIF}
) and
not (AConnectionDef.HasValue('DSN') or AConnectionDef.HasValue('FIL')) and
(Pos('MARS_CONNECTION=', UpperCase(Result)) = 0) then
Result := Result + ';MARS_Connection=yes'
{$IFDEF POSIX}
else if ((CompareText(ODBCDriver, C_FreeTDS) = 0) or
(CompareText(ODBCDriver, C_FreeTDSLib) = 0)) and
not (AConnectionDef.HasValue('DSN') or AConnectionDef.HasValue('FIL')) and
(Pos('TDS_VERSION=', UpperCase(Result)) = 0) then
Result := Result + ';TDS_VERSION=8.0';
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
oList: TFDStringList;
s: String;
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;
oList := TFDStringList.Create(#0, ';');
try
GetServers(oList, False, True);
s := oList.DelimitedText;
if s = '' then
s := '@S';
finally
FDFree(oList);
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, s, '', S_FD_ConnParam_Common_Server, 3]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSSQL_Network, '@S', '', S_FD_ConnParam_MSSQL_Network, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSSQL_Address, '@S', '', S_FD_ConnParam_MSSQL_Address, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_OSAuthent, '@Y', '', S_FD_ConnParam_Common_OSAuthent, 2]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSSQL_MARS, '@Y', S_FD_Yes, S_FD_ConnParam_MSSQL_MARS, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSSQL_Workstation, '@S', '', S_FD_ConnParam_MSSQL_Workstation, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSSQL_Language, '@S', '', S_FD_ConnParam_MSSQL_Language, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSSQL_Encrypt, '@Y', '', S_FD_ConnParam_MSSQL_Encrypt, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSSQL_VariantFormat, C_String + ';' + C_Binary, C_String, S_FD_ConnParam_MSSQL_VariantFormat, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_ExtendedMetadata, '@L', S_FD_False, S_FD_ConnParam_Common_ExtendedMetadata, -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]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCaseIns, '@L', S_FD_False, S_FD_ConnParam_Common_MetaCaseIns, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSSQL_MetaCaseInsCat, C_Choose + ';' + S_FD_False + ';' + S_FD_True, C_Choose, S_FD_ConnParam_MSSQL_MetaCaseInsCat, -1]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLDriver.GetServers(AList: TStrings; ARefresh, AAsync: Boolean): Boolean;
var
oConn: TODBCConnection;
oLnk: TFDPhysDriverLink;
oTask: ITask;
begin
oLnk := Manager.FindDriverLink(DriverID);
if ((oLnk = nil) or not (oLnk is TFDPhysMSSQLDriverLink) or TFDPhysMSSQLDriverLink(oLnk).ListServers) and
(FServers.Delimiter = ',') or ARefresh then begin
FServers.Delimiter := '.';
oTask := TTask.Run(procedure
begin
Employ;
oConn := TODBCConnection.Create(ODBCEnvironment);
try
oConn.SS_BROWSE_CONNECT := SQL_MORE_INFO_YES;
oConn.ListServers('DRIVER=' + TODBCLib.DecorateKeyValue(ODBCDriver), FServers);
finally
FDFree(oConn);
Vacate;
FServers.Delimiter := '*';
end;
end);
if not AAsync then
oTask.Wait();
end;
Result := FServers.Delimiter <> '.';
if Result then
AList.SetStrings(FServers)
else begin
AList.Clear;
AList.Add('<discovering ...>');
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSSQLConnection }
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
CreateMetadata(oConnMeta);
if (oConnMeta.ServerVersion >= svMSSQL2005) and
(ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc]) and
(CompareText(AEventKind, S_FD_EventKind_MSSQL_Events) = 0) then
Result := TFDPhysMSSQLEventAlerter.Create(Self, AEventKind)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnection.InternalCreateCommand: TFDPhysCommand;
begin
Result := TFDPhysMSSQLCommand.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
if ACommand <> nil then
Result := TFDPhysMSSQLCommandGenerator.Create(ACommand)
else
Result := TFDPhysMSSQLCommandGenerator.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnection.InternalCreateMetadata: TObject;
var
iSrvVer, iClntVer: TFDVersion;
iCase: SQLUSmallint;
begin
if ODBCConnection <> nil then begin
GetVersions(iSrvVer, iClntVer);
iCase := ODBCConnection.IDENTIFIER_CASE;
Result := TFDPhysMSSQLMetadata.Create(Self, FCatalogCaseSensitive,
iCase in [SQL_IC_SENSITIVE, SQL_IC_MIXED], iCase in [SQL_IC_MIXED],
ODBCConnection.IDENTIFIER_QUOTE_CHAR = '"',
ODBCConnection.DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc], iSrvVer, iClntVer,
FExtendedMetadata);
end
else
Result := TFDPhysMSSQLMetadata.Create(Self, False, True, True, True, False,
0, 0, FExtendedMetadata);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnection.GetStrsMaxSizes(AStrDataType: SQLSmallint;
AFixedLen: Boolean; out ACharSize, AByteSize: Integer);
begin
AByteSize := 8000;
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_MSSQLId]);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnection.GetExceptionClass: EODBCNativeExceptionClass;
begin
Result := EMSSQLNativeException;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnection.CheckPasswordChange;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
if not ODBCConnection.Connected then
Exit;
CreateMetadata(oConnMeta);
if not ((oConnMeta.ServerVersion >= svMSSQL2005) and
(ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc])) then
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_MSSQLId]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnection.InternalConnect;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
inherited InternalConnect;
CreateMetadata(oConnMeta);
if (oConnMeta.ClientVersion >= svMSSQL2008) and
(ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc]) then begin
FToolLib := TMSSQLToolLib.Create(Self);
FToolLib.Load(ODBCConnection.DRIVER_NAME);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnection.SetupConnection;
var
oPrevChanging: TNotifyEvent;
oParams: TFDPhysMSSQLConnectionDefParams;
begin
oParams := ConnectionDef.Params as TFDPhysMSSQLConnectionDefParams;
if oParams.NewPassword <> '' then begin
CheckPasswordChange;
ODBCConnection.SS_OLDPWD := oParams.Password;
oPrevChanging := ConnectionDef.OnChanging;
ConnectionDef.OnChanging := nil;
oParams.Password := oParams.NewPassword;
oParams.NewPassword := '';
ConnectionDef.OnChanging := oPrevChanging;
end;
inherited SetupConnection;
ODBCConnection.MSSQLVariantBinary := oParams.VariantFormat = vfBinary;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnection.InternalDisconnect;
begin
FDFreeAndNil(FToolLib);
inherited InternalDisconnect;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnection.InternalSetMeta;
var
oStmt: TODBCCommandStatement;
oCol1, oCol2, oCol3, oCol4: TODBCColumn;
oConnMeta: IFDPhysConnectionMetadata;
iCount: SQLLen;
sCollPropSvr, sCollPropDB, sCurCatalog, sCompatLvl, sSchema: String;
oPars: TFDPhysMSSQLConnectionDefParams;
iSize: SQLLen;
pData: Pointer;
begin
inherited InternalSetMeta;
oStmt := TODBCCommandStatement.Create(ODBCConnection, Self);
try
CreateMetadata(oConnMeta);
if FCurrentCatalog <> '' then
sCurCatalog := FCurrentCatalog
else
sCurCatalog := InternalGetCurrentCatalog;
sCollPropSvr := 'SERVERPROPERTY(''COLLATION'')';
if sCurCatalog <> '' then begin
sCurCatalog := AnsiQuotedStr(sCurCatalog, '''');
if oConnMeta.ServerVersion >= svMSSQL2005 then
sCollPropDB := 'DATABASEPROPERTYEX('
else
sCollPropDB := 'DATABASEPROPERTY(';
sCollPropDB := sCollPropDB + sCurCatalog + ', ''COLLATION'')';
if oConnMeta.ServerVersion >= svMSSQL2005 then
sCompatLvl := '(SELECT compatibility_level FROM sys.databases WHERE LOWER(name) = ' +
AnsiLowerCase(sCurCatalog) + ')'
else if oConnMeta.ServerVersion >= svMSSQL2000 then
sCompatLvl := '80'
else if oConnMeta.ServerVersion >= svMSSQL7 then
sCompatLvl := '70'
else
sCompatLvl := '60';
end
else begin
sCollPropDB := sCollPropSvr;
sCompatLvl := '0';
end;
if oConnMeta.ServerVersion >= svMSSQL2005 then
sSchema := 'SCHEMA_NAME()'
else
sSchema := 'USER_NAME()';
oStmt.Open(1, 'SELECT ' + sSchema + ', ' + sCollPropSvr + ', ' + sCollPropDB + ',' + sCompatLvl);
oCol1 := oStmt.AddCol(1, SQL_WVARCHAR, SQL_C_WCHAR, 128);
oCol2 := oStmt.AddCol(2, SQL_WVARCHAR, SQL_C_WCHAR, 128);
oCol3 := oStmt.AddCol(3, SQL_WVARCHAR, SQL_C_WCHAR, 128);
oCol4 := oStmt.AddCol(4, SQL_INTEGER, SQL_C_LONG, 0);
oStmt.Fetch(1);
if FCurrentSchema = '' then begin
FCurrentSchema := oCol1.AsStrings[0];
// Under MSSQL 2005 the SCHEMA_NAME() may return NULL
if FCurrentSchema = '' then
FCurrentSchema := 'dbo';
end;
oPars := TFDPhysMSSQLConnectionDefParams(ConnectionDef.Params);
if oPars.MetaCaseInsCat = mciChoose then
FCatalogCaseSensitive := (Pos('_CI_', UpperCase(oCol2.AsStrings[0])) = 0) or
(Pos('_CI_', UpperCase(oCol3.AsStrings[0])) = 0)
else
FCatalogCaseSensitive := oPars.MetaCaseInsCat = mciFalse;
pData := @FCompatibilityLevel;
oCol4.GetData(0, pData, iSize);
FExtendedMetadata := oPars.ExtendedMetadata;
if FExtendedMetadata then begin
oStmt.Unprepare;
oStmt.Execute(1, 0, iCount, False, 'SET NO_BROWSETABLE ON');
end;
finally
FDFree(oStmt);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnection.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.Password := ANewPassword;
oConn := TODBCConnection.Create(ODBCEnvironment, Self);
try
oConn.SS_OLDPWD := AOldPassword;
oConn.Connect(TFDPhysODBCDriverBase(DriverObj).BuildODBCConnectString(oConnDef));
finally
FDFree(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnection.InternalAnalyzeSession(AMessages: TStrings);
var
oConnMeta: IFDPhysConnectionMetadata;
begin
inherited InternalAnalyzeSession(AMessages);
CreateMetadata(oConnMeta);
// 2. "SQL Server" ODBC driver is outdated
if CompareText(ODBCConnection.DRIVER_NAME, 'SQLSRV32.DLL') = 0 then
AMessages.Add(S_FD_MSSQLWarnSQLSRV);
// 3. SQLNC 2008 fails with SQL2000 on some tests
if (oConnMeta.ServerVersion >= svMSSQL2000) and (oConnMeta.ServerVersion < svMSSQL2005) and
(oConnMeta.ClientVersion >= svMSSQL2008) then
AMessages.Add(S_FD_MSSQLWarnNC2008);
// 4. MS ODBC 11 and higher does not support SQL_VARIANT
if CompareText(Copy(ODBCConnection.DRIVER_NAME, 1, 9), 'MSODBCSQL') = 0 then
AMessages.Add(S_FD_MSSQLWarnODBC11);
// 5. SQL Server 2016 and compatibility level >= 130 may lead to DATETIME comparision failure
if (oConnMeta.ServerVersion >= svMSSQL2016) and
(FCompatibilityLevel >= 130) then
AMessages.Add(S_FD_MSSQLWarn2106Dt);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnection.GetFileStream(const ABlobPath: String;
AMode: TFDStreamMode; AOptions: LongWord; AOwningObj: TObject): TStream;
var
pData: SQLPointer;
iLen: SQLLen;
oStmt: TODBCCommandStatement;
begin
if FToolLib = nil then
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_MSSQLId]);
if ABlobPath = '' then
FDException(Self, [S_FD_LPhys, S_FD_MSSQLId], er_FD_MSSQLFSNoPath, []);
if (Length(FFileStreamTxContext) = 0) or
(GetTransaction.SerialID <> FFileStreamSerialID) then begin
oStmt := TODBCCommandStatement.Create(ODBCConnection, Self);
try
oStmt.Open(1, 'SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()');
oStmt.AddCol(1, SQL_VARBINARY, SQL_C_BINARY, MaxInt);
oStmt.Fetch(1);
if not oStmt.ColumnList[0].GetData(0, pData, iLen, True) or (iLen = 0) then
FDException(Self, [S_FD_LPhys, S_FD_MSSQLId], er_FD_MSSQLFSNoTx, []);
SetLength(FFileStreamTxContext, iLen);
Move(pData^, PByte(FFileStreamTxContext)^, iLen);
finally
FDFree(oStmt);
end;
FFileStreamSerialID := GetTransaction.SerialID;
end;
Result := TMSSQLFileStream.Create(FToolLib, ABlobPath, FFileStreamTxContext,
AMode, AOptions, AOwningObj);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSSQLEventThread }
{-------------------------------------------------------------------------------}
type
TFDPhysMSSQLEventThread = class(TThread)
private
[weak] FAlerter: TFDPhysMSSQLEventAlerter;
protected
procedure Execute; override;
public
constructor Create(AAlerter: TFDPhysMSSQLEventAlerter);
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysMSSQLEventThread.Create(AAlerter: TFDPhysMSSQLEventAlerter);
begin
inherited Create(False);
FAlerter := AAlerter;
FreeOnTerminate := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysMSSQLEventThread.Destroy;
begin
FAlerter.FWaitThread := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLEventThread.Execute;
begin
FAlerter.RegisterNotifications();
while not Terminated and FAlerter.IsRunning do
try
if FAlerter.FMessageTab.Columns.Count = 0 then
FAlerter.FWaitCommand.Define(FAlerter.FMessageTab);
FAlerter.FWaitCommand.Open();
if not Terminated then begin
FAlerter.FWaitCommand.Fetch(FAlerter.FMessageTab, True);
if (FAlerter.FMessageTab.Rows.Count > 0) and
FAlerter.ProcessNotifications() then
FAlerter.RegisterNotifications();
end;
except
on E: EFDDBEngineException do begin
Terminate;
if not (E.Kind in [ekCmdAborted, ekServerGone]) then
FAlerter.AbortJob;
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSSQLEventMessage }
{-------------------------------------------------------------------------------}
type
TFDPhysMSSQLEventMessage = class(TFDPhysEventMessage)
private
FName,
FType,
FSource,
FInfo: String;
public
constructor Create(const AName, AType, ASource, AInfo: String);
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysMSSQLEventMessage.Create(const AName, AType, ASource, AInfo: String);
begin
inherited Create;
FName := AName;
FType := AType;
FSource := ASource;
FInfo := AInfo;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSSQLEventAlerter }
{-------------------------------------------------------------------------------}
// See:
// 1) http://msdn.microsoft.com/en-us/library/ms181122.aspx
// Creating a Query for Notification - supported SELECT's, connection settings, etc
// 2) http://msdn.microsoft.com/en-us/library/ms188323.aspx
// Understanding When Query Notifications Occur
// 3) http://www.code-magazine.com/article.aspx?quickid=0605061&page=1
// SQL Server 2005 Query Notifications Tell .NET 2.0 Apps When Critical Data Changes
// SERVICE=<service>
// QUEUE=<queue>
// CHANGE1=<message>;<SELECT>
// ...
// CHANGEn=<message>;<SELECT>
// <EV1>=<message>
// ...
// <EVn>=<message>
const
C_Service = 'SERVICE';
C_Queue = 'QUEUE';
C_Change = 'CHANGE';
C_Events = 'EVENTS';
{-------------------------------------------------------------------------------}
{$IFDEF POSIX}
function CreateClassID: String;
begin
Format('%.4x%.4x-%.4x-%.4x-%.4x-%.4x%.4x%.4x', [
Random($FFFF), Random($FFFF), // Generates a 64-bit Hex number
Random($FFFF), // Generates a 32-bit Hex number
((Random($FFFF) and $0FFF) or $4000), // Generates a 32-bit Hex number of the form 4xxx (4 indicates the UUID version)
Random($FFFF) mod $3FFF + $8000, // Generates a 32-bit Hex number in the range [0x8000, 0xbfff]
Random($FFFF), Random($FFFF), Random($FFFF)]);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLEventAlerter.InternalAllocHandle;
var
i: Integer;
sName, sVal: String;
begin
FWaitConnection := GetConnection.Clone;
if FWaitConnection.State = csDisconnected then
FWaitConnection.Open;
FWaitConnection.CreateCommand(FWaitCommand);
SetupCommand(FWaitCommand);
FMessageTab := TFDDatSTable.Create;
FServiceName := C_FD_SysNamePrefix + C_Service;
FQueueName := C_FD_SysNamePrefix + C_Queue;
FEventTabName := C_FD_SysNamePrefix + C_Events;
FDropService := False;
FDropQueue := False;
FEventTab := False;
for i := 0 to GetNames.Count - 1 do begin
sName := GetNames().KeyNames[i];
sVal := GetNames().ValueFromIndex[i];
if CompareText(sName, C_Service) = 0 then
if sVal = '?' then begin
FServiceName := C_FD_SysNamePrefix + C_Service + CreateClassID;
FDropService := True;
end
else
FServiceName := sVal
else if CompareText(sName, C_Queue) = 0 then
if sVal = '?' then begin
FQueueName := C_FD_SysNamePrefix + C_Queue + CreateClassID;
FDropQueue := True;
end
else
FQueueName := sVal
else if StrLIComp(PChar(sName), PChar(C_Change), Length(C_Change)) <> 0 then
FEventTab := True;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLEventAlerter.InternalRegister;
var
sSQL: String;
begin
sSQL :=
'IF OBJECT_ID(''' + FQueueName + ''') IS NULL BEGIN ' +
' CREATE QUEUE [' + FQueueName + ']; ' +
'END; ' +
'IF (SELECT COUNT(*) FROM sys.services WHERE NAME = ''' + FServiceName + ''') = 0 BEGIN ' +
' CREATE SERVICE [' + FServiceName + '] ON QUEUE [' + FQueueName + '] ' +
' ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]); ' +
' IF (SELECT COUNT(*) FROM sys.database_principals WHERE name = ''sql_dependency_subscriber'' AND type = ''R'') <> 0 BEGIN ' +
' GRANT SEND ON SERVICE::[' + FServiceName + '] TO sql_dependency_subscriber; ' +
' END; ' +
'END;';
if FEventTab then
sSQL := sSQL +
'IF OBJECT_ID(''' + FEventTabName + ''') IS NULL BEGIN ' +
' CREATE TABLE [' + FEventTabName + '] (Name NVARCHAR(128) NOT NULL PRIMARY KEY CLUSTERED, Value BIGINT); ' +
'END; ';
FWaitCommand.Prepare(sSQL);
FWaitCommand.Execute;
FWaitThread := TFDPhysMSSQLEventThread.Create(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLEventAlerter.RegisterQuery(AStmt: TODBCCommandStatement;
const AEventName: String);
begin
if GetOptions.Timeout div MSecsPerSec > 0 then
AStmt.SS_QUERYNOTIFICATION_TIMEOUT := GetOptions.Timeout div MSecsPerSec;
AStmt.SS_QUERYNOTIFICATION_MSGTEXT := AEventName;
AStmt.SS_QUERYNOTIFICATION_OPTIONS := 'SERVICE=' + FServiceName +
';LOCAL DATABASE=' + GetConnection.ConnectionDef.Params.ExpandedDatabase;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLEventAlerter.RegisterNotifications;
var
i, j: Integer;
oStmt: TODBCCommandStatement;
sName, sVal: String;
sMsg, sSQL: String;
begin
for i := 0 to GetNames.Count - 1 do begin
sName := GetNames().KeyNames[i];
sVal := GetNames().ValueFromIndex[i];
if not ((CompareText(sName, C_Service) = 0) or (CompareText(sName, C_Queue) = 0)) then begin
if StrLIComp(PChar(sName), PChar(C_Change), Length(C_Change)) = 0 then begin
j := Pos(';', sVal);
sMsg := Copy(sVal, 1, j - 1);
sSQL := Copy(sVal, j + 1, MAXINT);
end
else begin
sName := QuotedStr(sName);
try
FWaitCommand.Prepare('INSERT INTO [' + FEventTabName + '] VALUES(' + sName + ', 0)');
FWaitCommand.Execute();
except
on E: EMSSQLNativeException do
if E.Kind <> ekUKViolated then
raise;
end;
sSQL := 'SELECT Value FROM [' + FEventTabName + '] WHERE Name = ' + sName;
end;
FWaitCommand.Prepare(sSQL);
oStmt := TODBCCommandStatement(FWaitCommand.CliObj);
RegisterQuery(oStmt, sMsg);
FWaitCommand.Define(FMessageTab);
FWaitCommand.Open;
FWaitCommand.Disconnect;
FMessageTab.Reset;
end;
end;
sSQL := 'WAITFOR (RECEIVE message_body FROM [' + FQueueName + '])';
if GetOptions.Timeout > 0 then
sSQL := sSQL + ', TIMEOUT ' + IntToStr(GetOptions.Timeout);
FWaitCommand.Prepare(sSQL);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLEventAlerter.ProcessNotifications: Boolean;
var
i: Integer;
sMsg, sType, sSrc, sInfo, sVal: String;
function GetAttr(const AName: String): String;
var
i1, i2: Integer;
begin
Result := '';
i1 := Pos(AName + '="', sMsg);
if i1 > 0 then begin
i2 := Pos('"', sMsg, i1 + Length(AName) + 2);
if i2 > 0 then begin
i1 := i1 + Length(AName) + 2;
i2 := i2 - 1;
Result := Copy(sMsg, i1, i2 - i1 + 1);
end;
end;
end;
function GetValue(const AName: String): String;
var
i1, i2: Integer;
begin
i1 := Pos('<' + AName + '>', sMsg);
i2 := Pos('</' + AName + '>', sMsg);
if (i1 > 0) and (i2 > 0) then begin
i1 := i1 + Length(AName) + 2;
i2 := i2 - 1;
Result := Copy(sMsg, i1, i2 - i1 + 1);
end
else
Result := '';
end;
begin
// http://technet.microsoft.com/en-us/library/ms189308(v=sql.105).aspx
// Query Notification Messages format
Result := True;
for i := 0 to FMessageTab.Rows.Count - 1 do begin
sMsg := FMessageTab.Rows[i].AsString['message_body'];
sType := GetAttr('type');
sSrc := GetAttr('source');
Result := CompareText(sType, 'subscribe') <> 0;
if (CompareText(sType, 'change') = 0) and (CompareText(sSrc, 'timeout') <> 0) or
not Result then begin
sInfo := GetAttr('info');
sVal := GetValue('qn:Message');
FMsgThread.EnqueueMsg(TFDPhysMSSQLEventMessage.Create(sVal, sType, sSrc, sInfo));
end;
end;
FMessageTab.Clear;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLEventAlerter.InternalHandle(AEventMessage: TFDPhysEventMessage);
var
oMsg: TFDPhysMSSQLEventMessage;
i: Integer;
oHnlr: IFDPhysChangeHandler;
oCmd: TFDPhysMSSQLCommand;
begin
oMsg := TFDPhysMSSQLEventMessage(AEventMessage);
if CompareText(oMsg.FType, 'subscribe') = 0 then
try
FDException(Self, [S_FD_LPhys, S_FD_MSSQLId], er_FD_MSSQLQNSubError, [oMsg.FInfo])
except
ApplicationHandleException(nil);
end
else begin
InternalHandleEvent(oMsg.FName, VarArrayOf([oMsg.FSource, oMsg.FInfo]));
i := FChangeHandlerNames.IndexOf(oMsg.FName);
if i >= 0 then begin
oHnlr := FChangeHandlers[i] as IFDPhysChangeHandler;
// If content is modified here, then Refresh was not performed.
// So, reexecute query here to reregister change notification.
// Otherwise, it is reregistered at Refresh call.
if oHnlr.ContentModified then begin
oCmd := oHnlr.TrackCommand as TFDPhysMSSQLCommand;
if (oCmd.FEventAlerter = Self) and (oCmd.FEventName <> '') and
(oCmd.ODBCStatement <> nil) and (oCmd.ODBCStatement is TODBCCommandStatement) then begin
RegisterQuery(TODBCCommandStatement(oCmd.ODBCStatement), oCmd.FEventName);
oCmd.CloseAll;
oCmd.Open;
end;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLEventAlerter.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 TFDPhysMSSQLEventAlerter.InternalUnregister;
var
sSQL: String;
begin
FWaitThread := nil;
sSQL := '';
if FDropService then
sSQL := sSQL +
'IF (SELECT COUNT(*) FROM sys.services WHERE NAME = ''' + FServiceName + ''') <> 0 BEGIN ' +
' DROP SERVICE [' + FServiceName + ']; ' +
'END; ';
if FDropQueue then
sSQL := sSQL +
'IF OBJECT_ID(''' + FQueueName + ''') IS NOT NULL BEGIN ' +
' DROP QUEUE [' + FQueueName + ']; ' +
'END; ';
if sSQL <> '' then begin
FWaitCommand.Prepare(sSQL);
FWaitCommand.Execute;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLEventAlerter.InternalReleaseHandle;
begin
FWaitCommand := nil;
FWaitConnection := nil;
FDFreeAndNil(FMessageTab);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLEventAlerter.InternalSignal(const AEvent: String;
const AArgument: Variant);
var
oCmd: IFDPhysCommand;
begin
if FEventTab then begin
GetConnection.CreateCommand(oCmd);
SetupCommand(oCmd);
oCmd.Prepare('UPDATE [' + FEventTabName + '] SET Value = Value + 1 WHERE Name = ' + QuotedStr(AEvent));
oCmd.Execute();
end
else
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_MSSQLId]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLEventAlerter.InternalChangeHandlerModified(
const AHandler: IFDPhysChangeHandler; const AEventName: String;
AOperation: TOperation);
var
oCmd: TFDPhysMSSQLCommand;
begin
oCmd := AHandler.TrackCommand as TFDPhysMSSQLCommand;
case AOperation of
opInsert:
begin
oCmd.FEventAlerter := Self;
oCmd.FEventName := AEventName;
end;
opRemove:
begin
oCmd.FEventAlerter := nil;
oCmd.FEventName := '';
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSSQLCommand }
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLCommand.InternalPrepare;
begin
inherited InternalPrepare;
if (FEventAlerter <> nil) and (FEventName <> '') and
(ODBCStatement <> nil) and (ODBCStatement is TODBCCommandStatement) then
FEventAlerter.RegisterQuery(TODBCCommandStatement(ODBCStatement), FEventName);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLCommand.CreateParamColumns(AParam: TFDParam);
var
oConnMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
oView: TFDDatSView;
oTab: TFDDatSTable;
i: Integer;
ui: LongWord;
oCol: TFDDatSColumn;
oRow: TFDDatSRow;
begin
GetConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(AParam.DataTypeName, rName, nil, [doUnquote]);
oView := oConnMeta.GetTableTypeFields(rName.FCatalog, rName.FSchema, rName.FObject, '');
oTab := TFDDatSTable.Create;
try
oTab.Name := AParam.Name;
for i := 0 to oView.Rows.Count - 1 do begin
oCol := TFDDatSColumn.Create;
oRow := oView.Rows[i];
oCol.Name := oRow.GetData(4);
oCol.DataType := TFDDataType(oRow.GetData(6));
oCol.SourceDataTypeName := oRow.GetData(7);
ui := oRow.GetData(8);
oCol.Attributes := TFDDataAttributes(Pointer(@ui)^);
oCol.Precision := oRow.GetData(9);
oCol.Scale := oRow.GetData(10);
oCol.Size := oRow.GetData(11);
oTab.Columns.Add(oCol);
end;
AParam.SetObjectValue(oTab, ftDataSet, True, -1);
except
FDFree(oTab);
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLCommand.CreateParamColumnInfos(ApInfo: PFDODBCParInfoRec;
AParam: TFDParam);
var
oDS: TDataSet;
i: Integer;
oFld: TField;
pInfo: PFDODBCParInfoRec;
oFmtOpts: TFDFormatOptions;
iPrec: Integer;
iScale: Integer;
eDestFldType: TFieldType;
iDestSize: LongWord;
lFixedLen: Boolean;
eAttrs: TFDDataAttributes;
iLen: LongWord;
oVar: TODBCParameter;
begin
oFmtOpts := FOptions.FormatOptions;
oDS := AParam.AsDataSet;
SetLength(ApInfo.FSubInfos, oDS.FieldCount);
for i := 0 to oDS.FieldCount - 1 do begin
oFld := oDS.Fields[i];
pInfo := @ApInfo.FSubInfos[i];
pInfo^.FName := '';
pInfo^.FPos := oFld.FieldNo;
pInfo^.FParamIndex := oFld.Index;
pInfo^.FParamType := AParam.ParamType;
pInfo^.FDataType := oFld.DataType;
if oFld is TBCDField then begin
iPrec := TBCDField(oFld).Precision;
iScale := TBCDField(oFld).Size;
end
else if oFld is TFMTBCDField then begin
iPrec := TFMTBCDField(oFld).Precision;
iScale := TBCDField(oFld).Size;
end
else begin
iPrec := 0;
iScale := 0;
end;
oFmtOpts.ResolveFieldType(oFld.FieldName, '', oFld.DataType, dtUnknown,
oFld.Size, iPrec, iScale, eDestFldType, iDestSize, pInfo^.FColSize,
pInfo^.FScale, pInfo^.FSrcDataType, pInfo^.FDestDataType, False);
lFixedLen := pInfo^.FDataType in [ftFixedChar, ftBytes, ftFixedWideChar];
pInfo^.FSrcSQLDataType := FD2SQLDataType(pInfo^.FSrcDataType, lFixedLen,
iPrec, iScale);
pInfo^.FOutSQLDataType := FD2SQLDataType(pInfo^.FDestDataType, lFixedLen,
pInfo^.FColSize, pInfo^.FScale);
if pInfo^.FOutSQLDataType = SQL_UNKNOWN_TYPE then
ParTypeMapError(AParam);
eAttrs := [];
SQL2FDColInfo(pInfo^.FOutSQLDataType, False, '', pInfo^.FColSize, pInfo^.FScale,
pInfo^.FOutDataType, eAttrs, iLen, iPrec, iScale);
if (pInfo^.FDestDataType = dtBCD) and (pInfo^.FOutDataType = dtFmtBCD) then
pInfo^.FOutDataType := dtBCD;
pInfo^.FVar := TODBCParameter(ApInfo^.FVar).ColumnList.Add(TODBCParameter.Create);
oVar := TODBCParameter(pInfo^.FVar);
oVar.ParamType := FD2SQLParamType(pInfo^.FParamType);
oVar.Position := SQLSmallint(pInfo^.FPos);
oVar.Name := pInfo^.FName;
oVar.ColumnSize := pInfo^.FColSize;
oVar.Scale := pInfo^.FScale;
oVar.SQLDataType := pInfo^.FOutSQLDataType;
oVar.CDataType := FD2CDataType(pInfo^.FOutDataType, True);
oVar.UpdateFlags;
// Set Scale value to specified 0 instead of default scale, excluding date/time
// data types. Otherwise exception is raised "Datetime field overflow. Fractional
// second precision exceeds the scale specified in the parameter binding"
if not ((oVar.CDataType = SQL_C_TYPE_TIMESTAMP) or (oVar.CDataType = SQL_C_TIMESTAMP) or
(oVar.CDataType = SQL_C_TYPE_DATE) or
(oVar.CDataType >= SQL_C_INTERVAL_YEAR) and (oVar.CDataType <= SQL_C_INTERVAL_MINUTE_TO_SECOND)) then
oVar.Scale := pInfo^.FScale;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommand.GetIsCustomParam(ADataType: TFDDataType): Boolean;
begin
Result := ADataType = dtHBFile;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLCommand.SetCustomParamValue(ADataType: TFDDataType;
AVar: TODBCVariable; AParam: TFDParam; AVarIndex, AParIndex: Integer);
begin
if ADataType = dtHBFile then
AVar.SetData(AVarIndex, nil, 0)
else
inherited SetCustomParamValue(ADataType, AVar, AParam, AVarIndex, AParIndex);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLCommand.GetCustomParamValue(ADataType: TFDDataType;
AVar: TODBCVariable; AParam: TFDParam; AVarIndex, AParIndex: Integer);
var
sPath: String;
oExtStr, oIntStr: TStream;
pBuffer: PByte;
iDataSize: LongWord;
lFree: Boolean;
lExtStream: Boolean;
begin
if ADataType = dtHBFile then begin
oExtStr := AParam.AsStreams[AParIndex];
lExtStream := (oExtStr <> nil) and
not ((oExtStr is TMSSQLFileStream) and (TMSSQLFileStream(oExtStr).OwningObj = Self));
sPath := AVar.AsStrings[AVarIndex];
if (AParam.StreamMode in [smOpenRead, smOpenReadWrite]) and (sPath = '') then begin
if lExtStream then
oExtStr.Size := 0;
AParam.Clear(AParIndex);
Exit;
end;
oIntStr := TFDPhysMSSQLConnection(ODBCConnection).GetFileStream(
sPath, AParam.StreamMode, SQL_FILESTREAM_OPEN_NONE, Self);
lFree := True;
try
try
// Store SQL Server stream into FD parameter
if not lExtStream and (AParam.DataType = ftStream) then begin
AParam.AsStreams[AParIndex] := oIntStr;
lFree := False;
end
// Write FD parameter into SQL Server stream
else if AParam.StreamMode = smOpenWrite then
if lExtStream then
oIntStr.CopyFrom(oExtStr, -1)
else if AParam.IsNulls[AParIndex] then
oIntStr.Size := 0
else begin
AParam.GetBlobRawData(iDataSize, pBuffer, AParIndex);
if AParam.IsUnicode then
iDataSize := iDataSize * SizeOf(WideChar);
oIntStr.WriteBuffer(pBuffer^, iDataSize);
end
// Read SQL Server stream into FD parameter
else
if lExtStream then begin
oExtStr.Position := 0;
oExtStr.CopyFrom(oIntStr, -1);
end
else begin
iDataSize := oIntStr.Size;
FBuffer.Check(iDataSize);
oIntStr.ReadBuffer(FBuffer.FBuffer^, iDataSize);
if AParam.IsUnicode then
iDataSize := iDataSize div SizeOf(WideChar);
AParam.SetBlobRawData(iDataSize, FBuffer.FBuffer, AParIndex);
end;
except
on E: EStreamError do
FDException(Self, [S_FD_LPhys, S_FD_MSSQLId], er_FD_MSSQLFSIOError,
[FDLastSystemErrorMsg]);
end;
finally
if lFree then
FDFree(oIntStr);
end;
end
else
inherited GetCustomParamValue(ADataType, AVar, AParam, AVarIndex, AParIndex);
end;
{-------------------------------------------------------------------------------}
function MSSQLNativeExceptionLoad(const AStorage: IFDStanStorage): TObject;
begin
Result := EMSSQLNativeException.Create;
EMSSQLNativeException(Result).LoadFromStorage(AStorage);
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysMSSQLDriver);
FDStorageManager().RegisterClass(EMSSQLNativeException, 'MSSQLNativeException',
@MSSQLNativeExceptionLoad, @FDExceptionSave);
finalization
FDUnregisterDriverClass(TFDPhysMSSQLDriver);
end.
|
{
DStun
Description:
A delphi librry for stun(rfc3489).
License:
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/
Contact Details:
EMail: heroyin@gmail.com
unit:
stun socket
Change log:
(2007-6-11):
- First version by heroyin@gmail.com.
}
unit DSSocket;
interface
uses
SysUtils, WinSock;
function GetSocketAddr(h: ansistring; p: Integer): TSockAddr;
function WaitForData(H: THandle; ATimeOut: Integer): Boolean;
implementation
var
WSAData: TWSAData;
procedure Startup;
var
ErrorCode: Integer;
begin
ErrorCode := WSAStartup($0101, WSAData);
if ErrorCode <> 0 then
raise Exception.Create('WSAStartup');
end;
procedure Cleanup;
var
ErrorCode: Integer;
begin
ErrorCode := WSACleanup;
if ErrorCode <> 0 then
raise Exception.Create('WSACleanup');
end;
function GetSocketAddr(h: ansistring; p: Integer): TSockAddr;
function LookupHostAddr(const hn: ansistring): AnsiString;
var
h: PHostEnt;
begin
Result := '';
if hn <> '' then
begin
if hn[1] in ['0'..'9'] then
begin
if inet_addr(pansichar(hn)) <> INADDR_NONE then
Result := hn;
end
else
begin
h := gethostbyname(pansichar(hn));
if h <> nil then
with h^ do
Result := format('%d.%d.%d.%d', [ord(h_addr^[0]), ord(h_addr^[1]),
ord(h_addr^[2]), ord(h_addr^[3])]);
end;
end
else Result := '0.0.0.0';
end;
function LookupPort(const sn: ansistring; pn: PAnsiChar = nil): word;
var
se: PServent;
begin
Result := 0;
if sn <> '' then
begin
se := getservbyname(pansichar(sn), pansichar(pn));
if se <> nil then
Result := ntohs(se^.s_port)
else
Result := StrToInt(sn);
end;
end;
begin
Result.sin_family := AF_INET;
Result.sin_addr.s_addr := inet_addr(pansichar(LookupHostAddr(h)));
Result.sin_port := htons(LookupPort(IntToStr(p)));
end;
function Select(H: THandle; ReadReady, WriteReady, ExceptFlag: PBoolean;
TimeOut: Integer): Boolean;
var
ReadFds: TFDset;
ReadFdsptr: PFDset;
WriteFds: TFDset;
WriteFdsptr: PFDset;
ExceptFds: TFDset;
ExceptFdsptr: PFDset;
tv: timeval;
Timeptr: PTimeval;
begin
if Assigned(ReadReady) then
begin
ReadFdsptr := @ReadFds;
FD_ZERO(ReadFds);
FD_SET(H, ReadFds);
end else
ReadFdsptr := nil;
if Assigned(WriteReady) then
begin
WriteFdsptr := @WriteFds;
FD_ZERO(WriteFds);
FD_SET(H, WriteFds);
end else
WriteFdsptr := nil;
if Assigned(ExceptFlag) then
begin
ExceptFdsptr := @ExceptFds;
FD_ZERO(ExceptFds);
FD_SET(H, ExceptFds);
end else
ExceptFdsptr := nil;
if TimeOut >= 0 then
begin
tv.tv_sec := TimeOut div 1000;
tv.tv_usec := 1000 * (TimeOut mod 1000);
Timeptr := @tv;
end else
Timeptr := nil;
Try
Result := WinSock.select(H + 1, ReadFdsptr, WriteFdsptr, ExceptFdsptr, Timeptr) > 0;
except
Result := False;
end;
if Assigned(ReadReady) then
ReadReady^ := FD_ISSET(H, ReadFds);
if Assigned(WriteReady) then
WriteReady^ := FD_ISSET(H, WriteFds);
if Assigned(ExceptFlag) then
ExceptFlag^ := FD_ISSET(H, ExceptFds);
end;
function WaitForData(H: THandle; ATimeOut: Integer): Boolean;
var
ReadReady, ExceptFlag: Boolean;
begin
Result := False;
if Select(H, @ReadReady, nil, @ExceptFlag, ATimeOut) then
Result := ReadReady and not ExceptFlag;
end;
initialization
Startup;
finalization
Cleanup;
end.
|
Unit Cutters;
Interface
Uses
Objects, Crt, SndObj;
Var
CutterUP_OPEN : Format;
CutterUP_CLOSE : Format;
CutterDOWN_OPEN : Format;
CutterDOWN_CLOSE : Format;
CutterLEFT_CLOSE : Format;
CutterLEFT_OPEN : Format;
CutterRIGHT_CLOSE : Format;
CutterRIGHT_OPEN : Format;
Fr : PFrames;
Type
PCutter = ^TCutter;
TCutter = Object (TObject)
Constructor Init(Sound : PSndObj; SpcWar : PSpace; x, y : Integer);
Procedure Run;
Virtual;
Procedure Move(Dir : Integer);
Virtual;
Procedure Draw;
Virtual;
Destructor Done;
Virtual;
End;
Implementation
CONSTRUCTOR TCutter.Init(Sound : PSndObj; SpcWar : PSpace; x, y : Integer);
Var
i, j : Integer;
Begin
Frames := Fr;
Scores := 0;
TObject.Init(Sound, SpcWar, CUTTER, x, y);
SpaceWar^.Space[x,y] := @Self;
End;
Procedure TCutter.Draw;
Begin
TObject.Draw;
End;
Procedure TCutter.Run;
Begin
If GetDirection = STOP Then Direction := RIGHT;
Move(Direction);
End;
Procedure TCutter.Move(Dir : Integer);
Var
ObjBEFORE : PObject;
ObjRIGHT : PObject;
LimitBEFORE: Boolean;
LimitRIGHT : Boolean;
Begin
LimitBEFORE := False;
LimitRIGHT := False;
ObjRIGHT := Nil;
ObjBEFORE := Nil;
If InMov Then TObject.Move(Direction)
Else
Begin
Case Dir Of
UP :
Begin
If posy > 01 Then
ObjBEFORE := SpaceWar^.Space[posx, posy-1]
Else LimitBEFORE := True;
If posx < 30 Then
ObjRIGHT := SpaceWar^.Space[posx+1, posy]
Else LimitRIGHT := True;
End;
DOWN :
Begin
If posy < 20 Then
ObjBEFORE := SpaceWar^.Space[posx, posy+1]
Else LimitBEFORE := True;
If posx > 01 Then
ObjRIGHT := SpaceWar^.Space[posx-1, posy]
Else LimitRIGHT := True;
End;
LEFT :
Begin
If posx > 01 Then
ObjBEFORE := SpaceWar^.Space[posx-1, posy]
Else LimitBEFORE := True;
If posy > 01 Then
ObjRIGHT := SpaceWar^.Space[posx, posy-1]
Else LimitRIGHT := True;
End;
RIGHT :
Begin
If posx < 30 Then
ObjBEFORE := SpaceWar^.Space[posx+1, posy]
Else LimitBEFORE := True;
If posy < 20 Then
ObjRIGHT := SpaceWar^.Space[posx, posy+1]
Else LimitRIGHT := True;
End;
End;
If LimitRIGHT = True Then {If right is the limit}
Begin
If (LimitBEFORE = True) Then {If front is the limit}
Begin
Case Direction Of {Change direction}
UP : Direction := LEFT;
DOWN : Direction := RIGHT;
RIGHT : Direction := UP;
LEFT : Direction := DOWN;
End;
Draw;
End
Else If ObjBEFORE^.Name = PLETS Then {If PLETS, kill}
Begin
Snd^.Snd(EXPLOITSND);
ObjBEFORE^.Destroy := True;
ObjBEFORE^.Explode := True;
Destroy := True;
Explode := True;
End
Else If ObjBEFORE = Nil Then {If nothing, move}
TObject.Move(Direction)
Else {else change direction}
Begin
Case Direction Of
UP : Direction := LEFT;
DOWN : Direction := RIGHT;
RIGHT : Direction := UP;
LEFT : Direction := DOWN;
End;
Draw;
End;
End
Else If ObjRIGHT^.Name = PLETS Then {If right is PLETS, kill}
Begin
Snd^.Snd(EXPLOITSND);
ObjRIGHT^.Destroy := True;
ObjRIGHT^.Explode := True;
Destroy := True;
Explode := True;
End
Else If ObjRIGHT = Nil Then {if nothing, turn right}
Case Direction Of {and move}
UP : TObject.Move(RIGHT);
DOWN : TObject.Move(LEFT);
RIGHT : TObject.Move(DOWN);
LEFT : TObject.Move(UP);
End
Else
Begin
If (LimitBEFORE = True) Then {If front is the limit}
Begin
Case Direction Of {change direction}
UP : Direction := LEFT;
DOWN : Direction := RIGHT;
RIGHT : Direction := UP;
LEFT : Direction := DOWN;
End;
Draw;
End
Else If ObjBEFORE^.Name = PLETS Then {if PLETS, kill}
Begin
Snd^.Snd(EXPLOITSND);
ObjBEFORE^.Destroy := True;
ObjBEFORE^.Destroy := True;
Destroy := True;
Explode := True;
End
Else If ObjBEFORE = Nil Then {If nothing, move}
TObject.Move(Direction)
Else {else change direction}
Begin
Case Direction Of
UP : Direction := LEFT;
DOWN : Direction := RIGHT;
RIGHT : Direction := UP;
LEFT : Direction := DOWN;
End;
Draw;
End;
End;
End;
End;
DESTRUCTOR TCutter.Done;
Begin
TObject.Done;
End;
{****************************************************************************}
Begin
CutterUP_OPEN[01] := '....................';
CutterUP_OPEN[02] := '....................';
CutterUP_OPEN[03] := '....F............7..';
CutterUP_OPEN[04] := '....FF..........77..';
CutterUP_OPEN[05] := '....FF..........77..';
CutterUP_OPEN[06] := '....FFF........777..';
CutterUP_OPEN[07] := '.....FF........77...';
CutterUP_OPEN[08] := '.....FFF......777...';
CutterUP_OPEN[09] := '......FF......77....';
CutterUP_OPEN[10] := '......FFF....777....';
CutterUP_OPEN[11] := '.......FF....77.....';
CutterUP_OPEN[12] := '.......FFF..777.....';
CutterUP_OPEN[13] := '........FF..77......';
CutterUP_OPEN[14] := '......222.F7.222....';
CutterUP_OPEN[15] := '.....2...2222...2...';
CutterUP_OPEN[16] := '.....2....22....2...';
CutterUP_OPEN[17] := '.....2..22..22..2...';
CutterUP_OPEN[18] := '......222....222....';
CutterUP_OPEN[19] := '....................';
CutterUP_OPEN[20] := '....................';
CutterUP_CLOSE[01] := '....................';
CutterUP_CLOSE[02] := '.........F7.........';
CutterUP_CLOSE[03] := '........FF77........';
CutterUP_CLOSE[04] := '........FF77........';
CutterUP_CLOSE[05] := '........FF77........';
CutterUP_CLOSE[06] := '........FF77........';
CutterUP_CLOSE[07] := '........FF77........';
CutterUP_CLOSE[08] := '........FF77........';
CutterUP_CLOSE[09] := '........FF77........';
CutterUP_CLOSE[10] := '........FF77........';
CutterUP_CLOSE[11] := '........FF77........';
CutterUP_CLOSE[12] := '........FF77........';
CutterUP_CLOSE[13] := '........FF77........';
CutterUP_CLOSE[14] := '.........F7.........';
CutterUP_CLOSE[15] := '......22222222......';
CutterUP_CLOSE[16] := '.....2...22...2.....';
CutterUP_CLOSE[17] := '.....2...22...2.....';
CutterUP_CLOSE[18] := '.....2...22...2.....';
CutterUP_CLOSE[19] := '......222..222......';
CutterUP_CLOSE[20] := '....................';
CutterDOWN_OPEN[01] := '....................';
CutterDOWN_OPEN[02] := '....................';
CutterDOWN_OPEN[03] := '.....222....222.....';
CutterDOWN_OPEN[04] := '....2..222222..2....';
CutterDOWN_OPEN[05] := '....2....22....2....';
CutterDOWN_OPEN[06] := '....2...2222...2....';
CutterDOWN_OPEN[07] := '.....222.F7.222.....';
CutterDOWN_OPEN[08] := '.......FF..77.......';
CutterDOWN_OPEN[09] := '......FFF..777......';
CutterDOWN_OPEN[10] := '......FF....77......';
CutterDOWN_OPEN[11] := '.....FFF....777.....';
CutterDOWN_OPEN[12] := '.....FF......77.....';
CutterDOWN_OPEN[13] := '....FFF......777....';
CutterDOWN_OPEN[14] := '....FF........77....';
CutterDOWN_OPEN[15] := '...FFF........777...';
CutterDOWN_OPEN[16] := '...FF..........77...';
CutterDOWN_OPEN[17] := '..FFF..........777..';
CutterDOWN_OPEN[18] := '..FF............77..';
CutterDOWN_OPEN[19] := '..F..............7..';
CutterDOWN_OPEN[20] := '....................';
CutterDOWN_CLOSE[01] := '....................';
CutterDOWN_CLOSE[02] := '......222..222......';
CutterDOWN_CLOSE[03] := '.....2...22...2.....';
CutterDOWN_CLOSE[04] := '.....2...22...2.....';
CutterDOWN_CLOSE[05] := '.....2...22...2.....';
CutterDOWN_CLOSE[06] := '......22222222......';
CutterDOWN_CLOSE[07] := '.........F7.........';
CutterDOWN_CLOSE[08] := '.........F7.........';
CutterDOWN_CLOSE[09] := '........FF77........';
CutterDOWN_CLOSE[10] := '........FF77........';
CutterDOWN_CLOSE[11] := '........FF77........';
CutterDOWN_CLOSE[12] := '........FF77........';
CutterDOWN_CLOSE[13] := '........FF77........';
CutterDOWN_CLOSE[14] := '........FF77........';
CutterDOWN_CLOSE[15] := '........FF77........';
CutterDOWN_CLOSE[16] := '........FF77........';
CutterDOWN_CLOSE[17] := '........FF77........';
CutterDOWN_CLOSE[18] := '........FF77........';
CutterDOWN_CLOSE[19] := '.........F7.........';
CutterDOWN_CLOSE[20] := '....................';
CutterRIGHT_OPEN[01] := '....................';
CutterRIGHT_OPEN[02] := '....................';
CutterRIGHT_OPEN[03] := '................FFF.';
CutterRIGHT_OPEN[04] := '..............FFFF..';
CutterRIGHT_OPEN[05] := '...222......FFFFF...';
CutterRIGHT_OPEN[06] := '..2...2...FFFFF.....';
CutterRIGHT_OPEN[07] := '..2...2.FFFFF.......';
CutterRIGHT_OPEN[08] := '..22..2FFFF.........';
CutterRIGHT_OPEN[09] := '...2.2.FF...........';
CutterRIGHT_OPEN[10] := '...222F.............';
CutterRIGHT_OPEN[11] := '...2227.............';
CutterRIGHT_OPEN[12] := '...2.2.77...........';
CutterRIGHT_OPEN[13] := '..22..27777.........';
CutterRIGHT_OPEN[14] := '..2...2.77777.......';
CutterRIGHT_OPEN[15] := '..2...2...77777.....';
CutterRIGHT_OPEN[16] := '...222......77777...';
CutterRIGHT_OPEN[17] := '..............7777..';
CutterRIGHT_OPEN[18] := '................777.';
CutterRIGHT_OPEN[19] := '....................';
CutterRIGHT_OPEN[20] := '....................';
CutterRIGHT_CLOSE[01] := '....................';
CutterRIGHT_CLOSE[02] := '....................';
CutterRIGHT_CLOSE[03] := '....................';
CutterRIGHT_CLOSE[04] := '....................';
CutterRIGHT_CLOSE[05] := '....................';
CutterRIGHT_CLOSE[06] := '..222...............';
CutterRIGHT_CLOSE[07] := '.2...2..............';
CutterRIGHT_CLOSE[08] := '.2...2..............';
CutterRIGHT_CLOSE[09] := '.2...2.FFFFFFFFFFF..';
CutterRIGHT_CLOSE[10] := '..2222FFFFFFFFFFFFF.';
CutterRIGHT_CLOSE[11] := '..22227777777777777.';
CutterRIGHT_CLOSE[12] := '.2...2.77777777777..';
CutterRIGHT_CLOSE[13] := '.2...2..............';
CutterRIGHT_CLOSE[14] := '.2...2..............';
CutterRIGHT_CLOSE[15] := '..222...............';
CutterRIGHT_CLOSE[16] := '....................';
CutterRIGHT_CLOSE[17] := '....................';
CutterRIGHT_CLOSE[18] := '....................';
CutterRIGHT_CLOSE[19] := '....................';
CutterRIGHT_CLOSE[20] := '....................';
CutterLEFT_OPEN[01] := '....................';
CutterLEFT_OPEN[02] := '....................';
CutterLEFT_OPEN[03] := '.FFF................';
CutterLEFT_OPEN[04] := '..FFFF..............';
CutterLEFT_OPEN[05] := '...FFFFF......222...';
CutterLEFT_OPEN[06] := '.....FFFFF...2...2..';
CutterLEFT_OPEN[07] := '.......FFFFF.2...2..';
CutterLEFT_OPEN[08] := '.........FFFF2...2..';
CutterLEFT_OPEN[09] := '...........FF.2.22..';
CutterLEFT_OPEN[10] := '.............F222...';
CutterLEFT_OPEN[11] := '.............7222...';
CutterLEFT_OPEN[12] := '...........77.2.2...';
CutterLEFT_OPEN[13] := '.........77772..22..';
CutterLEFT_OPEN[14] := '.......77777.2...2..';
CutterLEFT_OPEN[15] := '.....77777...2...2..';
CutterLEFT_OPEN[16] := '...77777......222...';
CutterLEFT_OPEN[17] := '..7777..............';
CutterLEFT_OPEN[18] := '.777................';
CutterLEFT_OPEN[19] := '....................';
CutterLEFT_OPEN[20] := '....................';
CutterLEFT_CLOSE[01] := '....................';
CutterLEFT_CLOSE[02] := '....................';
CutterLEFT_CLOSE[03] := '....................';
CutterLEFT_CLOSE[04] := '....................';
CutterLEFT_CLOSE[05] := '....................';
CutterLEFT_CLOSE[06] := '...............222..';
CutterLEFT_CLOSE[07] := '..............2...2.';
CutterLEFT_CLOSE[08] := '..............2...2.';
CutterLEFT_CLOSE[09] := '..FFFFFFFFFFF.2...2.';
CutterLEFT_CLOSE[10] := '.FFFFFFFFFFFFF2222..';
CutterLEFT_CLOSE[11] := '.77777777777772222..';
CutterLEFT_CLOSE[12] := '..77777777777.2...2.';
CutterLEFT_CLOSE[13] := '..............2...2.';
CutterLEFT_CLOSE[14] := '..............2...2.';
CutterLEFT_CLOSE[15] := '...............222..';
CutterLEFT_CLOSE[16] := '....................';
CutterLEFT_CLOSE[17] := '....................';
CutterLEFT_CLOSE[18] := '....................';
CutterLEFT_CLOSE[19] := '....................';
CutterLEFT_CLOSE[20] := '....................';
Fr[1][1] := @CutterRIGHT_CLOSE;
Fr[2][1] := @CutterRIGHT_OPEN;
Fr[1][2] := @CutterUP_CLOSE;
Fr[2][2] := @CutterUP_OPEN;
Fr[1][3] := @CutterDOWN_CLOSE;
Fr[2][3] := @CutterDOWN_OPEN;
Fr[1][4] := @CutterRIGHT_CLOSE;
Fr[2][4] := @CutterRIGHT_OPEN;
Fr[1][5] := @CutterLEFT_CLOSE;
Fr[2][5] := @CutterLEFT_OPEN;
End.
|
unit AAlteraEstagioCotacao;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, StdCtrls, Buttons, Localizacao, UnCotacao,
DBKeyViolation;
type
TFAlteraEstagioCotacao = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
BGravar: TBitBtn;
BCancelar: TBitBtn;
EUsuario: TEditLocaliza;
ECodEstagio: TEditLocaliza;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
ConsultaPadrao1: TConsultaPadrao;
Label4: TLabel;
ECotacao: TEditLocaliza;
BCotacao: TSpeedButton;
Label5: TLabel;
Label6: TLabel;
ValidaGravacao1: TValidaGravacao;
EEstagioAtual: TEditLocaliza;
Label7: TLabel;
SpeedButton4: TSpeedButton;
Label8: TLabel;
EMotivo: TMemoColor;
Label9: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BCancelarClick(Sender: TObject);
procedure ECotacaoSelect(Sender: TObject);
procedure EUsuarioChange(Sender: TObject);
procedure BGravarClick(Sender: TObject);
procedure ECodEstagioCadastrar(Sender: TObject);
procedure ECotacaoRetorno(Retorno1, Retorno2: String);
procedure ECodEstagioRetorno(Retorno1, Retorno2: String);
private
{ Private declarations }
VprCotacoes : String;
VprAcao : Boolean;
function DadosValidos : String;
procedure LimpaCampos;
public
{ Public declarations }
function AlteraEstagio :boolean;
function AlteraEstagioCotacoes(VpaCotacoes : String): Boolean;
end;
var
FAlteraEstagioCotacao: TFAlteraEstagioCotacao;
implementation
uses APrincipal, Constantes, ConstMsg, AEstagioProducao, FunObjeto;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFAlteraEstagioCotacao.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
end;
{******************************************************************************}
procedure TFAlteraEstagioCotacao.LimpaCampos;
begin
ECotacao.AInteiro:= 0;
ECotacao.Atualiza;
EEstagioAtual.AInteiro:= 0;
EEstagioAtual.Atualiza;
ECodEstagio.AInteiro:=0;
ECodEstagio.Atualiza;
EMotivo.Clear;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFAlteraEstagioCotacao.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFAlteraEstagioCotacao.BCancelarClick(Sender: TObject);
begin
VprAcao := false;
close;
end;
{******************************************************************************}
procedure TFAlteraEstagioCotacao.ECotacaoSelect(Sender: TObject);
begin
ECotacao.ASelectLocaliza.Text := 'Select CLI.C_NOM_CLI, COT.I_LAN_ORC, COT.I_COD_EST '+
' from CADCLIENTES CLI, CADORCAMENTOS COT '+
' Where CLI.I_COD_CLI = COT.I_COD_CLI '+
' and COT.I_EMP_FIL = '+inttoStr(Varia.CodigoEmpFil)+
' and CLI.C_NOM_CLI LIKE ''@%''';
ECotacao.ASelectValida.Text := 'Select CLI.C_NOM_CLI, COT.I_LAN_ORC, COT.I_COD_EST '+
' from CADCLIENTES CLI, CADORCAMENTOS COT '+
' Where CLI.I_COD_CLI = COT.I_COD_CLI '+
' and COT.I_EMP_FIL = '+inttoStr(Varia.CodigoEmpFil)+
' and COT.I_LAN_ORC = @';
end;
{******************************************************************************}
function TFAlteraEstagioCotacao.DadosValidos : String;
begin
result := '';
if EMotivo.ACampoObrigatorio then
if EMotivo.Lines.Text = '' then
result := 'MOTIVO NÃO PREENCHIDO!!!'#13'É necessário preencher o motivo pelo qual se está mudando de estágio';
end;
{******************************************************************************}
procedure TFAlteraEstagioCotacao.EUsuarioChange(Sender: TObject);
begin
ValidaGravacao1.Execute;
end;
{******************************************************************************}
function TFAlteraEstagioCotacao.AlteraEstagio :boolean;
begin
EUsuario.Ainteiro := varia.CodigoUsuario;
EUsuario.Atualiza;
showmodal;
result := vpracao;
end;
{******************************************************************************}
function TFAlteraEstagioCotacao.AlteraEstagioCotacoes(VpaCotacoes : String): Boolean;
begin
EUsuario.Ainteiro := varia.CodigoUsuario;
EUsuario.Atualiza;
VprCotacoes := VpaCotacoes;
AlterarEnabledDet([ECotacao,BCotacao],false);
ECotacao.ACampoObrigatorio := false;
showmodal;
result := vpracao;
end;
{******************************************************************************}
procedure TFAlteraEstagioCotacao.BGravarClick(Sender: TObject);
Var
VpfResultado : String;
begin
VpfResultado := DadosValidos;
if VpfResultado = '' then
begin
if VprCotacoes = '' then
vpfResultado := FunCotacao.AlteraEstagioCotacao(Varia.CodigoEmpFil,EUsuario.AInteiro,ECotacao.AInteiro,ECodEstagio.AInteiro,EMotivo.Lines.text)
else
VpfResultado := FunCotacao.AlteraEstagioCotacoes(varia.CodigoEmpfil,EUsuario.AInteiro,ECodEstagio.AInteiro,VprCotacoes,EMotivo.lines.text);
end;
if vpfresultado = '' then
begin
VprAcao := true;
LimpaCampos;
// close;
end
else
aviso(VpfResultado);
end;
{******************************************************************************}
procedure TFAlteraEstagioCotacao.ECodEstagioCadastrar(Sender: TObject);
begin
FEstagioProducao := TFEstagioProducao.CriarSDI(application,'', FPrincipal.VerificaPermisao('FEstagioProducao'));
FEstagioProducao.BotaoCadastrar1.Click;
FEstagioProducao.showmodal;
FEstagioProducao.free;
ConsultaPadrao1.AtualizaConsulta;
end;
{******************************************************************************}
procedure TFAlteraEstagioCotacao.ECotacaoRetorno(Retorno1,
Retorno2: String);
begin
if retorno1 <> '' then
EEstagioAtual.Text := Retorno1
else
EEstagioAtual.clear;
EEstagioAtual.Atualiza;
end;
{******************************************************************************}
procedure TFAlteraEstagioCotacao.ECodEstagioRetorno(Retorno1,
Retorno2: String);
begin
EMotivo.ACampoObrigatorio := false;
if retorno1 <> '' then
begin
if Retorno1 = 'S' then
EMotivo.ACampoObrigatorio := true;
end;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFAlteraEstagioCotacao]);
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXCommonIndy;
interface
uses
System.SysUtils,
Data.DBXCommon,
IPPeerAPI
;
type
/// <summary> Indy wrapper implementation of TX500Principal</summary>
TX500PrincipalIndy = class(TX500Principal)
protected
FIdX509Name : IIPX509Name;
FInstanceOwner : Boolean;
public
constructor Create(idX509Name: IIPX509Name; instanceOwner: Boolean = False); virtual;
destructor Destroy; override;
function GetName: String; override;
function GetEncoded: Longint; override;
end;
/// <summary> Indy wrapper implementation of TX509Certificate</summary>
TX509CertificateIndy = class(TX509Certificate)
protected
FIdX509: IIPX509;
FSubjectPrincipal: TX500PrincipalIndy;
FIssuerPrincipal: TX500PrincipalIndy;
FInstanceOwner : Boolean;
public
constructor Create(CertFile: String); overload; virtual;
constructor Create(CertFile: String; const AIPImplementationID: string); overload; virtual;
constructor Create(idX509: IIPX509; instanceOwner: Boolean = False); overload; virtual;
destructor Destroy; override;
{Inherited from the base Certificate class}
function GetEncoded: TBytes; override;
function GetPublicKey: TPublicKey; override;
function Verify(key: TPublicKey): Boolean; override;
{Inherited from the X.509 Certificate class}
procedure CheckValidity; overload; override;
procedure CheckValidity(ADate: TDateTime); overload; override;
function GetNotAfter: TDateTime; override;
function GetNotBefore: TDateTime; override;
function GetBasicConstraints: Integer; override;
function GetSerialNumber: string; override;
function GetVersion: LongInt; override;
function GetSigAlgName: String; override;
function GetSignature: String; override;
function GetIssuerX500Principal: TX500Principal; override;
function GetSubjectX500Principal: TX500Principal; override;
end;
implementation
uses
System.Classes,
Data.DBXClientResStrs
;
{ TX509CertificateIndy }
constructor TX509CertificateIndy.Create(CertFile: String);
begin
Create(CertFile, '');
end;
constructor TX509CertificateIndy.Create(CertFile: String; const AIPImplementationID: string);
var
fileStream: TFileStream;
data: TBytes;
dataPPtr: PPByte;
begin
Assert(FileExists(CertFile));
fileStream := TFileStream.Create(CertFile, fmOpenRead);
try
SetLength(data, fileStream.Size);
fileStream.Read(data[0], fileStream.Size);
dataPPtr := Addr(PByte(data));
Create(PeerFactory.CreatePeer(AIPImplementationID, IIPX509, IPProcs(AIPImplementationID)._d2i_X509(nil, dataPPtr, Length(data)), True) as IIPX509, True);
finally
fileStream.Free;
end;
end;
constructor TX509CertificateIndy.Create(idX509: IIPX509; instanceOwner: Boolean = False);
begin
Assert(idX509 <> nil);
FIdX509 := idX509;
FInstanceOwner := instanceOwner;
end;
destructor TX509CertificateIndy.Destroy;
begin
if FInstanceOwner then
FIdX509 := nil;
FreeAndNil(FSubjectPrincipal);
FreeAndNil(FIssuerPrincipal);
inherited;
end;
procedure TX509CertificateIndy.CheckValidity;
begin
CheckValidity(Now);
end;
procedure TX509CertificateIndy.CheckValidity(ADate: TDateTime);
begin
if ADate > FIdX509.notAfter then
raise ECertificateExpiredException.Create(SCertExpired);
if ADate < FIdX509.notBefore then
raise ECertificateNotYetValidException.Create(SCertNotYetValid);
end;
function TX509CertificateIndy.GetBasicConstraints: Integer;
begin
raise TDBXError.Create(TDBXErrorCodes.NotImplemented, SNotImplemented);
end;
function TX509CertificateIndy.GetEncoded: TBytes;
begin
raise TDBXError.Create(TDBXErrorCodes.NotImplemented, SNotImplemented);
end;
function TX509CertificateIndy.GetIssuerX500Principal: TX500Principal;
begin
if FIssuerPrincipal = nil then
begin
FIssuerPrincipal := TX500PrincipalIndy.Create(FIdX509.Issuer);
end;
Result := FIssuerPrincipal;
end;
function TX509CertificateIndy.GetSubjectX500Principal: TX500Principal;
begin
if FSubjectPrincipal = nil then
begin
FSubjectPrincipal := TX500PrincipalIndy.Create(FIdX509.Subject);
end;
Result := FSubjectPrincipal;
end;
function TX509CertificateIndy.GetNotAfter: TDateTime;
begin
Result := FIdX509.notAfter;
end;
function TX509CertificateIndy.GetNotBefore: TDateTime;
begin
Result := FIdX509.notBefore;
end;
function TX509CertificateIndy.GetPublicKey: TPublicKey;
begin
raise TDBXError.Create(TDBXErrorCodes.NotImplemented, SNotImplemented);
end;
function TX509CertificateIndy.GetSerialNumber: string;
begin
Result := FIdX509.SerialNumber;
end;
function TX509CertificateIndy.GetSigAlgName: String;
begin
Result := FIdX509.SigInfo.SigTypeAsString;
end;
function TX509CertificateIndy.GetSignature: String;
begin
Result := FIdX509.SigInfo.Signature;
end;
function TX509CertificateIndy.GetVersion: LongInt;
begin
Result := FIdX509.Version;
end;
function TX509CertificateIndy.Verify(key: TPublicKey): Boolean;
begin
raise TDBXError.Create(TDBXErrorCodes.NotImplemented, SNotImplemented);
end;
{ TX500PrincipalIndy }
constructor TX500PrincipalIndy.Create(idX509Name: IIPX509Name; instanceOwner: Boolean = False);
begin
Assert(idX509Name <> nil);
FIdX509Name := idX509Name;
FInstanceOwner := instanceOwner;
end;
destructor TX500PrincipalIndy.Destroy;
begin
if FInstanceOwner then
begin
FIdX509Name := nil;
end;
inherited;
end;
function TX500PrincipalIndy.GetEncoded: Longint;
begin
Result := FIdX509Name.Hash.L1;
end;
function TX500PrincipalIndy.GetName: String;
begin
Result := FIdX509Name.OneLine;
end;
end.
|
unit LuaProperties;
interface
Uses Dialogs, Forms, Graphics, Classes, Controls, StdCtrls, TypInfo, LuaPas, Lua;
function LuaListProperties(L: Plua_State): Integer; cdecl;
function LuaGetProperty(L: Plua_State): Integer; cdecl;
function LuaSetProperty(L: Plua_State): Integer; cdecl;
function SetPropertiesFromLuaTable(L: Plua_State; Obj:TObject; Index:Integer):Boolean;
procedure SetProperty(L:Plua_State; Index:Integer; Comp:TObject; PInfo:PPropInfo);
procedure LuaSetControlProperty(L:Plua_State; Comp: TObject; PropName:String; Index:Integer);
procedure lua_pushtable_object(L: Plua_State; Comp:TObject; PropName:String; index: Integer);overload;
procedure lua_pushtable_object(L: Plua_State; Comp:TObject; PInfo:PPropInfo; index: Integer);overload;
procedure lua_pushtable_object(L: Plua_State; Comp:TObject; index: Integer);overload;
// color converter
function ToColor(L: Plua_State; index: Integer):TColor;
implementation
Uses SysUtils, ExtCtrls, Grids, ActnList, LuaActionList, LuaImageList, LuaControl, LCLProc,
LuaStrings,
LuaCanvas,
LuaBitmap,
LuaPicture;
// ****************************************************************
function tabletotext(L:Plua_State; Index:Integer):String;
var n :integer;
begin
result := '';
if lua_istable(L,Index) then begin
n := lua_gettop(L);
lua_pushnil(L);
while (lua_next(L, n) <> 0) do begin
Result := Result + lua_tostring(L, -1) + #10;
lua_pop(L, 1);
end;
end else if lua_isstring(L,Index) then
Result := lua_tostring(L,Index);
Result := AnsiToUTF8(Result); ///QVCL
end;
function ToColor(L: Plua_State; index: Integer):TColor;
begin
result := 0;
if lua_isstring(L,index) then
result := StringToColor(lua_tostring(L,index))
else if lua_isnumber(L,index) then
result := TColor(trunc(lua_tonumber(L,index)));
end;
function SetTStringsProperty( L: Plua_State; Comp:TObject; PropName:String; index:Integer):boolean;
var target: TStrings;
begin
result := false;
target := TStrings( Pointer(GetInt64Prop(Comp,PropName)));
if Assigned(target) then begin
target.Clear;
target.Text := tabletotext(L,index);
result := true;
end;
end;
// ****************************************************************
procedure lua_pushtable_object(L: Plua_State; Comp:TObject; PropName:String; index: Integer);overload;
begin
lua_newtable(L);
LuaSetTableLightUserData(L, index, HandleStr, Pointer(GetInt64Prop(Comp,PropName)));
LuaSetMetaFunction(L, index, '__index', LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', LuaSetProperty);
end;
procedure lua_pushtable_object(L: Plua_State; Comp:TObject; PInfo:PPropInfo; index: Integer); overload;
begin
// check pinfo for TStrings
if (PInfo.PropType^.Name = 'TStrings') then begin
TStringsToTable(L,Comp,PInfo,index);
end else begin
lua_newtable(L);
LuaSetTableLightUserData(L, index, HandleStr, Pointer(GetInt64Prop(Comp, PInfo.Name)));
end;
LuaSetMetaFunction(L, index, '__index', LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', LuaSetProperty);
end;
procedure lua_pushtable_object(L: Plua_State; Comp:TObject; index: Integer);overload;
begin
lua_newtable(L);
LuaSetTableLightUserData(L, index, HandleStr, Comp);
LuaSetMetaFunction(L, index, '__index', LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', LuaSetProperty);
end;
function isVcluaObject(L: Plua_State; index: Integer):boolean;
begin
Result := (LuaGetTableLightUserData(L,Index,'Handle') <> nil);
end;
// ****************************************************************
procedure ListProperty(L: Plua_State; PName:String; PInfo: PPropInfo; idx:Integer);
var
PropType: String;
begin
try
PropType := PInfo^.Proptype^.Name;
if PropType[1] = 'T' then
delete(Proptype,1,1);
lua_pushnumber(L,idx);
lua_newtable(L);
lua_pushstring(L, PChar(PName));
lua_pushstring(L, PChar(PropType));
lua_rawset(L,-3);
lua_rawset(L,-3);
except
end;
end;
procedure ListObjectProperties(L: Plua_State; PObj:TObject);
var subObj, tmpObj:TObject;
Count,Loop:Integer;
PInfo: PPropInfo;
PropInfos: PPropList;
s,t:String;
n:Integer;
begin
Count := GetPropList(PObj.ClassInfo, tkAny, nil);
GetMem(PropInfos, Count * SizeOf(PPropInfo));
GetPropList(PObj.ClassInfo, tkAny, PropInfos, true);
for Loop := 0 to Count - 1 do begin
PInfo := GetPropInfo(PObj.ClassInfo, PropInfos^[Loop]^.Name);
case PInfo^.Proptype^.Kind of
tkClass:
begin
subObj := GetObjectProp(PObj, PInfo);
if subObj<>nil then begin
s := PropInfos^[Loop]^.Name;
t := PInfo^.Proptype^.Name;
lua_pushnumber(L,Loop+1);
lua_newtable(L);
lua_pushstring(L, PChar(s)); // name
lua_pushstring(L, PChar(t)); // type
lua_rawset(L,-3);
// avoid circular reference
if (s<>'Owner') and (s<>'Parent') then begin
if subObj.InheritsFrom(TStrings) then begin
tmpObj := TLuaStrings.Create;
ListObjectProperties(L,tmpObj);
tmpObj.Free;
end else
ListObjectProperties(L,subObj);
end;
lua_rawset(L,-3);
end;
end;
tkMethod:
begin
ListProperty(L, PropInfos^[Loop]^.Name, PInfo, Loop+1);
end
else begin
ListProperty(L, PropInfos^[Loop]^.Name, PInfo, Loop+1);
end
end;
end;
FreeMem(PropInfos);
end;
function LuaListProperties(L: Plua_State): Integer; cdecl;
var
PObj: TObject;
begin
CheckArg(L, 1);
PObj := GetLuaObject(L, 1);
lua_newtable(L);
ListObjectProperties(L, PObj);
Result := 1;
end;
// ****************************************************************
procedure LuaSetControlProperty(L:Plua_State; Comp: TObject; PropName:String; Index:Integer);
var
PInfo: PPropInfo;
begin
PInfo := GetPropInfo(TObject(Comp).ClassInfo, PropName);
SetProperty(L,Index,Comp,PInfo);
end;
procedure SetProperty(L:Plua_State; Index:Integer; Comp:TObject; PInfo:PPropInfo);
Var propVal:String;
LuaFuncPInfo: PPropInfo;
Str: String;
tm: TMethod;
cc: TObject;
// refrence!!!
luafunc, top: Integer;
begin
Str := PInfo^.Proptype^.Name;
// to be safe...
if ((Str = 'TStringList') or (Str = 'TStrings')) and
(SetTStringsProperty( L, Comp, PInfo.Name, index))
// (ComponentStringList(TComponent(Comp), lua_tostring(L, -2), tabletotext(L,-1)))
then else
if (Str = 'SHORTCUT') and (ComponentShortCut(TComponent(Comp),lua_tostring(L, -1))) then
else
case PInfo^.Proptype^.Kind of
tkMethod: begin
// Property Name
Str := lua_tostring(L,index-1);
// omg watchout!
cc := TComponent(Comp).Components[0];
LuaFuncPInfo := GetPropInfo(cc, Str+'_Function');
if LuaFuncPInfo <> nil then begin
// OnXxxx_Function
if lua_isfunction(L,index) then begin
// store luafunc in component by LuaCtl
top := lua_gettop(L);
lua_settop(L,index);
luafunc := luaL_ref(L, LUA_REGISTRYINDEX);
SetOrdProp(cc, LuaFuncPInfo, luafunc);
lua_settop(L,top);
// setup luaeventhandler
LuaFuncPInfo := GetPropInfo(Comp.ClassInfo, Str);
// OnXxxx -->OnLuaXxxx
insert('Lua',Str,3);
if (LuaFuncPInfo<>nil) then begin
tm.Data := Pointer(cc);
tm.Code := cc.MethodAddress(Str);
SetMethodProp(Comp, LuaFuncPInfo, tm);
end
end else begin
// LuaError(L,'Lua function required for event!' , lua_tostring(L,index));
tm.Data:= nil;
tm.Code:= nil;
SetMethodProp(Comp, PInfo, tm);
end
end
else begin
LuaError(L,'Method not found or not supported!' , lua_tostring(L,index));
end
end;
tkSet:
begin
// writeln('SET ', Comp.Classname, StringToSet(PInfo,lua_tostring(L,index)));
SetOrdProp(Comp, PInfo, StringToSet(PInfo,lua_tostring(L,index)));
end;
tkClass:
begin
// not a vclua class
if (not isVcluaObject(L,index)) then begin
// create on runtime
lua_pushtable_object(L, Comp, PInfo, index);
end;
SetInt64Prop(Comp, PInfo, Int64(Pointer(GetLuaObject(L, index))));
end;
tkInteger:
begin
if (Str='TGraphicsColor') and lua_isstring(L, index) then
SetOrdProp(Comp, PInfo, ToColor(L, index))
else
SetOrdProp(Comp, PInfo, Trunc(lua_tonumber(L, index)));
end;
///QVCL change start
tkChar, tkWChar:
begin
Str := AnsiToUTF8(lua_tostring(L, index));
if length(Str)<1 then
SetOrdProp(Comp, PInfo, 0)
else
SetOrdProp(Comp, PInfo, Ord(Str[1]));
end;
///QVCL change end
tkBool:
begin
// writeln(PInfo^.Name, lua_toboolean(L,index));
{$IFDEF UNIX}
propval := BoolToStr(lua_toboolean(L,index));
SetOrdProp(Comp, PInfo, GetEnumValue(PInfo^.PropType, PropVal));
{$ELSE}
SetPropValue(Comp, PInfo^.Name, lua_toboolean(L,index));
{$ENDIF}
end;
tkEnumeration:
begin
if lua_type(L, index) = LUA_TBOOLEAN then
propval := BoolToStr(lua_toboolean(L,index))
else
propVal := lua_tostring(L, index);
// writeln('ENUM ', Comp.Classname, PInfo^.Name, PropVal);
SetOrdProp(Comp, PInfo, GetEnumValue(PInfo^.PropType, PropVal));
end;
tkFloat:
SetFloatProp(Comp, PInfo, lua_tonumber(L, index));
///QVCL change start
tkString, tkLString, tkWString:
begin
Str := lua_tostring(L, index);
SetStrProp(Comp, PInfo, AnsiToUtf8(Str));
end;
tkInt64: begin
SetInt64Prop(Comp, PInfo, Int64(Round(lua_tonumber(L, index))));
end;
else begin
Str := AnsiToUtf8(lua_tostring(L, index));
if (PInfo^.Proptype^.Name='TTranslateString') then
SetStrProp(Comp, PInfo, Str )
else if (PInfo^.Proptype^.Name='AnsiString') then
SetStrProp(Comp, PInfo, Str)
else if (PInfo^.Proptype^.Name='WideString') then
SetStrProp(Comp, PInfo, Str)
///QVCL change end
else
LuaError(L,'Property not supported!' , PInfo^.Proptype^.Name);
end;
end;
end;
procedure CheckAndSetProperty(L: Plua_State; Obj:TObject; PInfo: PPropInfo; PName: String; Index:Integer);
begin
if lua_istable(L,Index) then begin
if (PInfo.PropType.Kind<>TKCLASS) and (PInfo.PropType.Kind<>TKASTRING) and (TObject(GetInt64Prop(Obj,pName))=nil) then
SetPropertiesFromLuaTable(L,TObject(GetInt64Prop(Obj,pName)),Index)
else
// set table properties if the property is not a vclobject
if (PInfo.PropType^.Kind=tkClass) and (not isVcluaObject(L,Index)) then begin
// loader--> items = luatable
if TObject(GetInt64Prop(Obj, PInfo.Name)).InheritsFrom(TStrings) then
SetTStringsProperty( L, Obj, PName, Index)
else
SetPropertiesFromLuaTable(L,TObject(GetInt64Prop(Obj,pName)),Index);
end else
SetProperty(L, Index, TComponent(Obj), PInfo);
end else
SetProperty(L, Index, TComponent(Obj), PInfo);
end;
// ****************************************************************
// Sets Property Values from a Lua table
// ****************************************************************
function SetPropertiesFromLuaTable(L: Plua_State; Obj:TObject; Index:Integer):Boolean;
var n,d: Integer;
PInfo: PPropInfo;
pName: String;
begin
result := false;
// L,1 is the Object self
if lua_istable(L,Index) then begin
n := lua_gettop(L);
lua_pushnil(L);
while (lua_next(L, n) <> 0) do begin
pName := lua_tostring(L, -2);
PInfo := GetPropInfo(Obj.ClassInfo,lua_tostring(L, -2));
if PInfo <> nil then begin
Result:=True;
CheckAndSetProperty(L,Obj,PInfo,PName,-1);
end else begin
if (UpperCase(pName)='SHORTCUT') and (ComponentShortCut(TComponent(Obj),lua_tostring(L, -1))) then
else
if UpperCase(pName) = 'PARENT' then begin
TControl(Obj).Parent := TWinControl(GetLuaObject(L, -1));
end else begin
// lua invalid key raised
LuaError(L,'Property not found! ', Obj.ClassName+'.'+PName);
end;
end;
lua_pop(L, 1);
end;
result := true;
end;
end;
// ****************************************************************
// Sets Property Value
// ****************************************************************
function LuaSetProperty(L: Plua_State): Integer; cdecl;
var
PInfo: PPropInfo;
Comp: TObject;
propname: String;
propType: String;
begin
Result := 0;
Comp := TObject(GetLuaObject(L, 1));
if (Comp=nil) then begin
LuaError(L, 'Can''t set null object property! ' , PropName );
lua_pushnil(L);
Exit;
end;
PropName := lua_tostring(L, 2);
if (UpperCase(PropName)='SHORTCUT') and (ComponentShortCut(TComponent(Comp),lua_tostring(L, -1))) then
else
if (lua_gettop(L)=3) and (lua_istable(L,3)) and ((PropName='_')) then begin
SetPropertiesFromLuaTable(L,Comp,3);
end else begin
// ClassInfo replacement
if Comp.InheritsFrom(TStrings) then
PInfo := GetPropInfo(TLuaStrings.ClassInfo, PropName)
else
PInfo := GetPropInfo(TComponent(Comp).ClassInfo, PropName);
if (PInfo <> nil) and (lua_gettop(L)=3) then begin
CheckAndSetProperty(L,Comp,PInfo,PropName,3);
end else begin
case lua_type(L,3) of
LUA_TNIL: LuaRawSetTableNil(L,1,lua_tostring(L, 2));
LUA_TBOOLEAN: LuaRawSetTableBoolean(L,1,lua_tostring(L, 2),lua_toboolean(L, 3));
LUA_TLIGHTUSERDATA: LuaRawSetTableLightUserData(L,1,lua_tostring(L, 2),lua_touserdata(L, 3));
LUA_TNUMBER: LuaRawSetTableNumber(L,1,lua_tostring(L, 2),lua_tonumber(L, 3));
LUA_TSTRING: LuaRawSetTableString(L,1,lua_tostring(L, 2),lua_tostring(L, 3));
LUA_TTABLE: LuaRawSetTableValue(L,1,lua_tostring(L, 2), 3);
LUA_TFUNCTION: LuaRawSetTableFunction(L,1,lua_tostring(L, 2),lua_CFunction(lua_touserdata(L, 3)));
else
if lowercase(PropName) = 'parent' then begin
TWinControl(Comp).Parent := TWinControl(GetLuaObject(L, 3));
end else
LuaError(L,'Property not found!',PropName);
end;
end;
end;
end;
// ****************************************************************
// Gets Property Value
// ****************************************************************
function LuaGetProperty(L: Plua_State): Integer; cdecl;
var
PInfo, PPInfo: PPropInfo;
proptype: String;
propname: String;
strValue: String;
ordValue: Int64;
Comp, Pcomp: TObject;
P64: Int64;
begin
Result := 1;
Comp := TObject(GetLuaObject(L, 1));
PropName := lua_tostring(L, 2);
if (Comp=nil) then begin
LuaError(L, 'Can''t get null object property!' , '' );
lua_pushnil(L);
Exit;
end;
// ClassInfo replacement
if Comp.InheritsFrom(TStrings) then
PInfo := GetPropInfo(TLuaStrings.ClassInfo, PropName)
else
PInfo := GetPropInfo(Comp.ClassInfo, PropName);
if PInfo <> nil then begin
PropType := PInfo^.Proptype^.Name;
PropName := PInfo^.Name;
if (Comp.ClassName = 'TLuaActionList') and (UpperCase(PropName)='IMAGES') then
TLuaImageList(TLuaActionList(Comp).Images).LuaCtl.ToTable(L,-1,TLuaImageList(TLuaActionList(Comp).Images))
else
begin
case PInfo^.Proptype^.Kind of
tkMethod:
begin
PPInfo := GetPropInfo(Comp.ClassInfo, PropName + '_FunctionName');
if PPInfo <> nil then
lua_pushstring(L,pchar(GetStrProp(Comp, PPInfo)))
else begin
lua_pushnil(L);
end;
end;
tkSet:
lua_pushstring(L,pchar(SetToString(PInfo,GetOrdProp(Comp, PInfo),true)));
tkClass: begin
lua_pushtable_object(L, Comp, PInfo, -1);
end;
tkInteger:
lua_pushnumber(L,GetOrdProp(Comp, PInfo));
tkChar,
tkWChar:
lua_pushnumber(L,GetOrdProp(Comp, PInfo));
tkBool:
begin
strValue := GetEnumName(PInfo^.PropType, GetOrdProp(Comp, PInfo));
if (strValue<>'') then
lua_pushboolean(L,StrToBool(strValue));
end;
tkEnumeration:
lua_pushstring(L,PChar(GetEnumName(PInfo^.PropType, GetOrdProp(Comp, PInfo))));
tkFloat:
lua_pushnumber(L,GetFloatProp(Comp, PInfo));
tkString,
tkLString,
tkWString:
lua_pushstring(L,pchar(UTF8ToAnsi(GetStrProp(Comp, PInfo)))); ///QVCL
tkInt64:
lua_pushnumber(L,GetInt64Prop(Comp, PInfo));
else begin
if (PInfo^.Proptype^.Name='TTranslateString') then begin
lua_pushstring(L,pchar(UTF8ToAnsi(GetStrProp(Comp, PInfo)))); ///QVCL
end else if (PInfo^.Proptype^.Name='AnsiString') then begin
lua_pushstring(L,pchar(UTF8ToAnsi(GetStrProp(Comp, PInfo)))); ///QVCL
end else begin
lua_pushnil(L);
LuaError(L,'Property not supported!', lua_tostring(L,2) + ' ' + PInfo^.Proptype^.Name);
end;
end
end;
end
end else begin
// try to find the property self
if lowercase(lua_tostring(L,2)) = 'classname' then begin
lua_pushstring(L, pchar(AnsiString(Comp.ClassName)));
end else
if lowercase(lua_tostring(L,2)) = 'parent' then begin
lua_pushtable_object(L, TComponent(Comp).Owner, 'Parent', -1);
end else begin
// lua property?
case lua_type(L,1) of
LUA_TBOOLEAN:
lua_pushBoolean(L, LuaRawGetTableBoolean(L,1,lua_tostring(L, 2)));
LUA_TLIGHTUSERDATA:
lua_pushlightuserdata(L,LuaRawGetTableLightUserData(L,1,lua_tostring(L, 2)));
LUA_TNUMBER:
lua_pushnumber(L,LuaRawGetTableNumber(L,1,lua_tostring(L, 2)));
LUA_TSTRING:
lua_pushstring(L,PChar(UTF8ToAnsi(LuaRawGetTableString(L,1,lua_tostring(L, 2))))); ///QVCL
LUA_TTABLE:
begin
LuaRawGetTable(L,1,lua_tostring(L, 2));
end;
LUA_TFUNCTION:
lua_pushcfunction(L,LuaRawGetTableFunction(L,1,lua_tostring(L, 2)));
else begin
lua_pushnil(L);
LuaError(L,'(Lua) Property not found!', lua_tostring(L,2)+' type:'+IntToStr(lua_type(L,1)));
end;
end;
end;
end;
end;
end.
|
unit UMain;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Menus, ExtCtrls, StdCtrls,
Buttons, ComCtrls, Grids, Spin, UVisualTools, UTransformation,
URTTI, Math, UFigures, UEdits, UGraph, USaveLoadToLPF, UEditsStatic, UAbout;
{ TVectorEditMainForm }
type
TVectorEditMainForm = class(TForm)
Big_Left_Panel: TPanel;
FSE_ScaleEdit: TFloatSpinEdit;
Menu_Move_Down: TMenuItem;
Menu_Cut: TMenuItem;
Menu_Move_Up: TMenuItem;
Menu_Delete: TMenuItem;
Menu_Paste: TMenuItem;
Menu_Copy: TMenuItem;
Menu_Edit: TMenuItem;
TB_Open: TToolButton;
TB_Save: TToolButton;
TB_Exit: TToolButton;
TB_Separator1: TToolButton;
TB_Separator2: TToolButton;
TB_Separator3: TToolButton;
TB_Separator4: TToolButton;
TB_OriginalScale: TToolButton;
TB_Separator5: TToolButton;
ToolBar_Main: TToolBar;
Tools_Panel: TPanel;
Edits_Panel: TPanel;
Big_Bottom_Panel: TPanel;
Sh_Background_Color: TShape;
StatusBar_Main: TStatusBar;
Color_DrawGrid: TDrawGrid;
SH_Brush_Color: TShape;
SH_Pen_Color: TShape;
Right_Scroll_Panel: TPanel;
SB_Right: TScrollBar;
Bottom_Scroll_Panel: TPanel;
SB_Bottom: TScrollBar;
Central_Part_Panel: TPanel;
Left_Part_Panel: TPanel;
ToolBar1: TToolBar;
TB_Centering: TToolButton;
TB_Delete: TToolButton;
TB_Move_Up: TToolButton;
TB_Move_Down: TToolButton;
TB_Paste: TToolButton;
TB_Copy: TToolButton;
TB_Cut: TToolButton;
Main_OpenDialog: TOpenDialog;
Main_ColorDialog: TColorDialog;
Main_SaveDialog: TSaveDialog;
Main_ImageList: TImageList;
Main_Menu: TMainMenu;
Menu_SaveAs: TMenuItem;
Menu_Open: TMenuItem;
Menu_File: TMenuItem;
Menu_Help: TMenuItem;
Menu_Exit: TMenuItem;
Menu_About: TMenuItem;
Main_PaintBox: TPaintBox;
procedure Color_DrawGridDblClick(Sender: TObject);
procedure Color_DrawGridDrawCell(Sender: TObject; aCol, aRow: integer;
aRect: TRect; aState: TGridDrawState);
procedure Color_DrawGridMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure FormCreate(Sender: TObject);
procedure FSE_ScaleEditChange(Sender: TObject);
procedure Menu_AboutClick(Sender: TObject);
procedure Main_PaintBoxMouseLeave(Sender: TObject);
procedure Sh_Background_ColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: integer);
procedure SpeedButtonClick(Sender: TObject);
procedure CreateControlEx(ParentClass: TWinControl);
procedure Main_PaintBoxMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure Main_PaintBoxMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
procedure Main_PaintBoxMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure Main_PaintBoxMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: boolean);
procedure Main_PaintBoxMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: boolean);
procedure Main_PaintBoxPaint(Sender: TObject);
procedure SB_BottomChange(Sender: TObject);
procedure SB_RightChange(Sender: TObject);
procedure SH_ColorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure StatusBar_MainResize(Sender: TObject);
procedure TB_CenteringClick(Sender: TObject);
procedure TB_ExitClick(Sender: TObject);
procedure TB_OpenClick(Sender: TObject);
procedure TB_OriginalScaleClick(Sender: TObject);
procedure TB_DeleteClick(Sender: TObject);
procedure TB_Move_UpClick(Sender: TObject);
procedure TB_Move_DownClick(Sender: TObject);
procedure TB_PasteClick(Sender: TObject);
procedure TB_CopyClick(Sender: TObject);
procedure TB_CutClick(Sender: TObject);
procedure TB_SaveClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
VectorEditMainForm: TVectorEditMainForm;
Tools: TToolsClass;
Clipboard: array of TFigure;
CellsColors: array[0..24, 0..1] of
TColor = ((clBlack, clMaroon), (clGreen, clOlive), (clNavy, clPurple),
(clTeal, clGray), (clSilver, clRed), (clLime, clYellow),
(clBlue, clFuchsia), (clAqua, clLtGray), (clDkGray, clWhite),
(clMoneyGreen, clSkyBlue), (clCream, clMedGray), (clNone, clDefault),
(clScrollBar, clBackground), (clActiveCaption, clInactiveCaption),
(clMenu, clWindow), (clWindowFrame, clMenuText),
(clWindowText, clCaptionText), (clActiveBorder, clInactiveBorder),
(clAppWorkspace, clHighlight), (clHighlightText, clBtnFace),
(clBtnShadow, clGrayText), (clBtnText, clInactiveCaptionText),
(clBtnHighlight, cl3DDkShadow), (cl3DLight, clInfoText),
(clInfoBk, clHotLight));
const
BRUSH_COLOR = clWhite;
PEN_COLOR = clBlack;
BACKGROUND_COLOR = clWhite;
implementation
{$R *.lfm}
{ TVectorEditMainForm }
procedure TVectorEditMainForm.SpeedButtonClick(Sender: TObject);
var
I: integer;
begin
Edits_Panel.DestroyComponents;
Tools := ControlTools.Class_Tools_Array[TSpeedButton(Sender).Tag];
Tools.Proper;
GetComponentProperties(FakeFigure, Edits_Panel);
ControlTools.Set_Selected_On_Draw;
ControlTools.MAIN_Invalidate;
end;
procedure TVectorEditMainForm.CreateControlEx(ParentClass: TWinControl);
var
I: integer;
SpBt_New: TSpeedButton;
begin
ParentClass.Height := 8 + 40 * Ceil(Length(ControlTools.Class_Tools_Array) / 3);
for I := 0 to High(ControlTools.Class_Tools_Array) do begin
SpBt_New := TSpeedButton.Create(ParentClass);
with SpBt_New do begin
OnClick := @SpeedButtonClick;
Parent := ParentClass;
Tag := I;
GroupIndex := 1;
SetBounds((I mod 3) * 40 + 8, (I div 3) * 40 + 8, 32, 32);
ShowHint := True;
Hint := ControlTools.Class_Tools_Array[I].GetHint;
Glyph.LoadFromFile(ControlTools.Class_Tools_Array[I].GetGlyph);
if I = 5 then begin
Down := True;
Tools := ControlTools.Class_Tools_Array[I];
end;
end;
end;
end;
procedure TVectorEditMainForm.Main_PaintBoxPaint(Sender: TObject);
begin
ControlTools.Re_Draw_Canvas(Main_PaintBox.Canvas);
end;
procedure TVectorEditMainForm.SB_BottomChange(Sender: TObject);
begin
Trans.OffsetX := SB_Bottom.Position;
Main_PaintBox.Invalidate;
end;
procedure TVectorEditMainForm.SB_RightChange(Sender: TObject);
begin
Trans.OffsetY := SB_Right.Position;
Main_PaintBox.Invalidate;
end;
procedure TVectorEditMainForm.FormCreate(Sender: TObject);
begin
CreateControlEx(Tools_Panel);
ControlTools.MAIN_Invalidate := @Main_PaintBox.Invalidate;
ControlEdits.MAIN_Invalidate := @Main_PaintBox.Invalidate;
ControlEditsNew.MAIN_Invalidate := @Main_PaintBox.Invalidate;
Trans.ScrollBarX := SB_Bottom;
Trans.ScrollBarY := SB_Right;
Trans.FSEScale := FSE_ScaleEdit;
Trans.Scale := FSE_ScaleEdit.Value;
SH_Background_Color.Brush.Color := BACKGROUND_COLOR;
SH_Brush_Color.Brush.Color := BRUSH_COLOR;
SH_Pen_Color.Brush.Color := PEN_COLOR ;
ControlTools.Main_Panel := Edits_Panel;
ControlEditsNew.Register_Controls(VectorEditMainForm.SH_Pen_Color);
ControlEditsNew.Register_Controls(VectorEditMainForm.SH_Brush_Color);
GlobalPenColor := @SH_Pen_Color.Brush.Color;
GlobalBrushColor := @SH_Brush_Color.Brush.Color;
GlobalBackgroundColor := @SH_Background_Color.Brush.Color;
end;
procedure TVectorEditMainForm.FSE_ScaleEditChange(Sender: TObject);
begin
Trans.Scale := FSE_ScaleEdit.Value;
Trans.RefreshScrollBar;
Invalidate;
end;
//------------------------- Муню -----------------------------------------------
procedure TVectorEditMainForm.Menu_AboutClick(Sender: TObject);
begin
About.ShowModal;
end;
//------------------------- Обработка Событий Главного Холста ------------------
procedure TVectorEditMainForm.Main_PaintBoxMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
Tools.MouseUp(Shift, Trans.S2W(Point(X, Y)), Main_PaintBox.Canvas);
end;
procedure TVectorEditMainForm.Main_PaintBoxMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
Tools.MouseDown(Shift, Trans.S2W(Point(X, Y)), Main_PaintBox.Canvas);
end;
procedure TVectorEditMainForm.Main_PaintBoxMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: integer);
var
W_MouseP: TDoublePoint;
begin
W_MouseP := Trans.S2W(Point(X, Y));
with StatusBar_Main.Panels do begin
Items[1].Text := 'Экранные X: ' + IntToStr(X) +
' Y: ' + IntToStr(Y);
Items[2].Text := 'Мировые X: ' + FloatToStrF(W_MouseP.X, ffFixed, 0, 2) +
' Y: ' + FloatToStrF(W_MouseP.Y, ffFixed, 0, 2);
end;
Tools.MouseMove(Shift, W_MouseP, Main_PaintBox.Canvas);
end;
procedure TVectorEditMainForm.Main_PaintBoxMouseLeave(Sender: TObject);
begin
StatusBar_Main.Panels[1].Text := '';
StatusBar_Main.Panels[2].Text := '';
end;
procedure TVectorEditMainForm.Main_PaintBoxMouseWheelDown(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: boolean);
begin
Trans.ScrollReduction(MousePos);
Invalidate;
end;
procedure TVectorEditMainForm.Main_PaintBoxMouseWheelUp(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: boolean);
begin
Trans.ScrollIncrease(MousePos);
Invalidate;
end;
//------------------------- Обработка Цветов Кисти и Заливки -------------------
procedure TVectorEditMainForm.SH_ColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
if Main_ColorDialog.Execute then
TShape(Sender).Brush.Color := Main_ColorDialog.Color;
end;
procedure TVectorEditMainForm.Sh_Background_ColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
if Main_ColorDialog.Execute then begin
Sh_Background_Color.Brush.Color := Main_ColorDialog.Color;
Invalidate;
end;
end;
//------------------------- Панель Состояний -----------------------------------
procedure TVectorEditMainForm.StatusBar_MainResize(Sender: TObject);
begin
StatusBar_Main.Panels.Items[0].Width := StatusBar_Main.Width - 350;
SB_Bottom.PageSize := SB_Bottom.Width;
SB_Right.PageSize := SB_Right.Height;
end;
//------------------------- Верхнее меню ---------------------------------------
procedure Swap(var AObject1, AObject2: TFigure);
var
AObject3: TFigure;
begin
AObject3 := AObject1;
AObject1 := AObject2;
AObject2 := AObject3;
end;
procedure TVectorEditMainForm.TB_CenteringClick(Sender: TObject);
begin
Trans.Scaling(Trans.W2S(Trans.FilledArea));
Trans.Centering(Trans.W2S(Trans.FilledArea));
Trans.RefreshScrollBar;
Invalidate;
end;
procedure TVectorEditMainForm.TB_ExitClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TVectorEditMainForm.TB_OpenClick(Sender: TObject);
begin
if Main_OpenDialog.Execute then
Open(Utf8ToAnsi(Main_OpenDialog.FileName));
end;
procedure TVectorEditMainForm.TB_OriginalScaleClick(Sender: TObject);
begin
Trans.Scale := 1;
Trans.RefreshScrollBar;
end;
procedure TVectorEditMainForm.TB_DeleteClick(Sender: TObject);
var
I, J, ArrayLength: integer;
begin
ArrayLength := 0;
I := 0;
while I <= High(MAIN_FIGURE_ARRAY) - ArrayLength do
if MAIN_FIGURE_ARRAY[I].SelectedFigure = SelectedDrawFigure then
begin
MAIN_FIGURE_ARRAY[I].Free;
Inc(ArrayLength);
for J := I to High(MAIN_FIGURE_ARRAY) - ArrayLength do
Swap(MAIN_FIGURE_ARRAY[J], MAIN_FIGURE_ARRAY[J + 1]);
end
else
Inc(I);
SetLength(MAIN_FIGURE_ARRAY, Length(MAIN_FIGURE_ARRAY) - ArrayLength);
Invalidate;
end;
procedure TVectorEditMainForm.TB_Move_UpClick(Sender: TObject);
var
I, J, ArrayLength: integer;
begin
ArrayLength := 0;
I := 0;
while I <= High(MAIN_FIGURE_ARRAY) - ArrayLength do
if MAIN_FIGURE_ARRAY[I].SelectedFigure = SelectedDrawFigure then begin
Inc(ArrayLength);
for J := I to High(MAIN_FIGURE_ARRAY) - 1 do
Swap(MAIN_FIGURE_ARRAY[J], MAIN_FIGURE_ARRAY[J + 1]);
end
else
Inc(I);
Invalidate;
end;
procedure TVectorEditMainForm.TB_Move_DownClick(Sender: TObject);
var
I, J, ArrayLength: integer;
begin
ArrayLength := 0;
I := High(MAIN_FIGURE_ARRAY);
while I >= ArrayLength do
if MAIN_FIGURE_ARRAY[I].SelectedFigure = SelectedDrawFigure then begin
Inc(ArrayLength);
for J := I downto 1 do
Swap(MAIN_FIGURE_ARRAY[J], MAIN_FIGURE_ARRAY[J - 1]);
end
else
Dec(I);
Invalidate;
end;
procedure TVectorEditMainForm.TB_PasteClick(Sender: TObject);
var
I, ArrayLength: integer;
begin
SetLength(MAIN_FIGURE_ARRAY, Length(MAIN_FIGURE_ARRAY) + Length(Clipboard));
for I := 0 to High(Clipboard) do
MAIN_FIGURE_ARRAY[High(MAIN_FIGURE_ARRAY) - I] := CopyFigure(Clipboard[I]);
Invalidate;
end;
procedure TVectorEditMainForm.TB_CopyClick(Sender: TObject);
var
I, J: integer;
NewInst: TFigure;
begin
for I := 0 to High(Clipboard) do
Clipboard[I].Free;
SetLength(Clipboard, 0);
for I := 0 to High(MAIN_FIGURE_ARRAY) do
if MAIN_FIGURE_ARRAY[I].SelectedFigure = SelectedDrawFigure then begin
SetLength(Clipboard, Length(Clipboard) + 1);
Clipboard[High(Clipboard)] := CopyFigure(MAIN_FIGURE_ARRAY[I]);
end;
end;
procedure TVectorEditMainForm.TB_CutClick(Sender: TObject);
begin
TB_CopyClick(Sender);
TB_DeleteClick(Sender);
end;
procedure TVectorEditMainForm.TB_SaveClick(Sender: TObject);
begin
if Main_SaveDialog.Execute then
Save(Utf8ToAnsi(Main_SaveDialog.FileName));
end;
//------------------------- Палитра --------------------------------------------
procedure TVectorEditMainForm.Color_DrawGridMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
if Button = mbLeft then
SH_Pen_Color.Brush.Color := CellsColors[X div 18, Y div 18];
if Button = mbRight then
SH_Brush_Color.Brush.Color := CellsColors[X div 18, Y div 18];
end;
procedure TVectorEditMainForm.Color_DrawGridDrawCell(Sender: TObject;
aCol, aRow: integer; aRect: TRect; aState: TGridDrawState);
begin
with Color_DrawGrid.Canvas do begin
Brush.Color := CellsColors[aCol, aRow];
FillRect(aRect);
end;
end;
procedure TVectorEditMainForm.Color_DrawGridDblClick(Sender: TObject);
begin
if Main_ColorDialog.Execute then
with Color_DrawGrid, Color_DrawGrid.Canvas do begin
CellsColors[Col, Row] := Main_ColorDialog.Color;
Brush.Color := Main_ColorDialog.Color;
FillRect(CellRect(Col, Row));
end;
end;
initialization
end.
|
unit WinPropEditor;
{$mode objfpc}{$H+}
interface
uses
Forms, Controls, PropEdits, ObjectInspector;
type
{ TWndPropEditor }
TWndPropEditor = class(TForm)
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
private
FObjectInspector: TObjectInspectorDlg;
public
procedure SetSelection(AControl: TControl);
end;
function ShowPropEditor: TWndPropEditor; overload;
procedure ShowPropEditor(AControl: TControl); overload;
implementation
{$R *.lfm}
function ShowPropEditor: TWndPropEditor;
begin
Result := TWndPropEditor.Create(Application.MainForm);
Result.Show;
end;
procedure ShowPropEditor(AControl: TControl);
var
Wnd: TWndPropEditor;
begin
Wnd := ShowPropEditor;
AControl.Parent := Wnd;
AControl.Align := alClient;
Wnd.SetSelection(AControl);
end;
{ TWndPropEditor }
procedure TWndPropEditor.FormCreate(Sender: TObject);
begin
// create the PropertyEditorHook (the interface to the properties)
if not Assigned(GlobalDesignHook) then
GlobalDesignHook := TPropertyEditorHook.Create;
// create the ObjectInspector
FObjectInspector := TObjectInspectorDlg.Create(Application);
FObjectInspector.PropertyEditorHook := GlobalDesignHook;
FObjectInspector.Show;
end;
procedure TWndPropEditor.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
FObjectInspector.Close;
CloseAction := caFree;
end;
procedure TWndPropEditor.SetSelection(AControl: TControl);
var
Selection: TPersistentSelectionList;
begin
GlobalDesignHook.LookupRoot := AControl;
Selection := TPersistentSelectionList.Create;
try
Selection.Add(AControl);
FObjectInspector.Selection := Selection;
finally
Selection.Free;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{$HPPEMIT '#pragma link "Data.DbxOracle"'} {Do not Localize}
unit Data.DbxOracle;
interface
uses
Data.DBXDynalink,
Data.DBXDynalinkNative,
Data.DBXCommon, Data.DbxOracleReadOnlyMetaData, Data.DbxOracleMetaData;
type
TDBXOracleProperties = class(TDBXProperties)
strict private
const StrOSAuthentication = 'OS Authentication';
const StrOracleTransIsolation = 'Oracle TransIsolation';
const StrDecimalSeparator = 'Decimal Separator';
const StrTrimChar = 'Trim Char';
const StrMultipleTransaction = 'Multiple Transaction';
const StrRowsetSize = 'RowsetSize';
function GetHostName: string;
function GetPassword: string;
function GetUserName: string;
function GetBlobSize: Integer;
function GetDatabase: string;
function GetOracleTransIsolation: string;
function GetDecimalSeparator: string;
function GetTrimChar: Boolean;
function GetRowsetSize: Integer;
function GetOSAuthentication: Boolean;
function GetMultipleTransaction: Boolean;
procedure SetMultipleTransaction(const Value: Boolean);
procedure SetOSAuthentication(const Value: Boolean);
procedure SetRowsetSize(const Value: Integer);
procedure SetBlobSize(const Value: Integer);
procedure SetDatabase(const Value: string);
procedure SetOracleTransIsolation(const Value: string);
procedure SetDecimalSeparator(const Value: string);
procedure SetTrimChar(const Value: Boolean);
procedure SetHostName(const Value: string);
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
public
constructor Create(DBXContext: TDBXContext); override;
published
property HostName: string read GetHostName write SetHostName;
property UserName: string read GetUserName write SetUserName;
property Password: string read GetPassword write SetPassword;
property Database: string read GetDatabase write SetDatabase;
property BlobSize: Integer read GetBlobSize write SetBlobSize;
property OracleTransIsolation:string read GetOracleTransIsolation write SetOracleTransIsolation;
property DecimalSeparator: string read GetDecimalSeparator write SetDecimalSeparator;
property OSAuthentication: Boolean read GetOSAuthentication write SetOSAuthentication;
property TrimChar: Boolean read GetTrimChar write SetTrimChar;
property RowsetSize: Integer read GetRowsetSize write SetRowsetSize;
property MultipleTransaction: Boolean read GetMultipleTransaction write SetMultipleTransaction;
end;
TDBXOracleDriver = class(TDBXDynalinkDriverNative)
public
constructor Create(DBXDriverDef: TDBXDriverDef); override;
end;
implementation
uses
Data.DBXPlatform, System.SysUtils;
const
sDriverName = 'Oracle';
{ TDBXOracleDriver }
constructor TDBXOracleDriver.Create(DBXDriverDef: TDBXDriverDef);
var
Props: TDBXOracleProperties;
I, Index: Integer;
begin
Props := TDBXOracleProperties.Create(DBXDriverDef.FDBXContext);
if DBXDriverDef.FDriverProperties <> nil then
begin
for I := 0 to DBXDriverDef.FDriverProperties.Count - 1 do
begin
Index := Props.Properties.IndexOfName(DBXDriverDef.FDriverProperties.Properties.Names[I]);
if Index > -1 then
Props.Properties.Strings[Index] := DBXDriverDef.FDriverProperties.Properties.Strings[I];
end;
Props.AddUniqueProperties(DBXDriverDef.FDriverProperties.Properties);
DBXDriverDef.FDriverProperties.AddUniqueProperties(Props.Properties);
end;
inherited Create(DBXDriverDef, TDBXDynalinkDriverLoader, Props);
rcs;
end;
{ TDBXOracleProperties }
constructor TDBXOracleProperties.Create(DBXContext: TDBXContext);
begin
inherited Create(DBXContext);
Values[TDBXPropertyNames.DriverUnit] := 'Data.DBXOracle';
Values[TDBXPropertyNames.DriverPackageLoader] := 'TDBXDynalinkDriverLoader,DBXOracleDriver160.bpl';
Values[TDBXPropertyNames.DriverAssemblyLoader] := 'Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken;
Values[TDBXPropertyNames.MetaDataPackageLoader] := 'TDBXOracleMetaDataCommandFactory,DbxOracleDriver160.bpl';
Values[TDBXPropertyNames.MetaDataAssemblyLoader] := 'Borland.Data.TDBXOracleMetaDataCommandFactory,Borland.Data.DbxOracleDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken;
Values[TDBXPropertyNames.GetDriverFunc] := 'getSQLDriverORACLE';
Values[TDBXPropertyNames.LibraryName] := 'dbxora.dll';
Values[TDBXPropertyNames.LibraryNameOsx] := 'libsqlora.dylib';
Values[TDBXPropertyNames.VendorLib] := 'oci.dll';
Values[TDBXPropertyNames.VendorLibWin64] := 'oci.dll';
Values[TDBXPropertyNames.VendorLibOsx] := 'libociei.dylib';
Values[TDBXPropertyNames.Database] := 'Database Name';
Values[TDBXPropertyNames.UserName] := 'user';
Values[TDBXPropertyNames.Password] := 'password';
Values[TDBXPropertyNames.MaxBlobSize] := '-1';
Values[TDBXPropertyNames.ErrorResourceFile] := '';
Values[TDBXDynalinkPropertyNames.LocaleCode] := '0000';
Values[TDBXPropertyNames.IsolationLevel] := 'ReadCommitted';
Values['RowSetSize'] := '20';
Values['OSAuthentication'] := 'False';
Values['MultipleTransactions'] := 'False';
Values['TrimChar'] := 'False';
end;
function TDBXOracleProperties.GetBlobSize: Integer;
begin
Result := StrToIntDef(Values[TDBXPropertyNames.MaxBlobSize], -1);
end;
function TDBXOracleProperties.GetDatabase: string;
begin
Result := Values[TDBXPropertyNames.Database];
end;
function TDBXOracleProperties.GetOracleTransIsolation: string;
begin
Result := Values[StrOracleTransIsolation];
end;
function TDBXOracleProperties.GetDecimalSeparator: string;
begin
Result := Values[StrDecimalSeparator];
end;
function TDBXOracleProperties.GetOSAuthentication: Boolean;
begin
Result := StrToBoolDef(Values[StrOSAuthentication], False);
end;
function TDBXOracleProperties.GetTrimChar: Boolean;
begin
Result := StrToBoolDef(Values[StrTrimChar], False);
end;
function TDBXOracleProperties.GetHostName: string;
begin
Result := Values[TDBXPropertyNames.HostName];
end;
function TDBXOracleProperties.GetMultipleTransaction: Boolean;
begin
Result := StrToBoolDef(Values[StrMultipleTransaction], False);
end;
function TDBXOracleProperties.GetPassword: string;
begin
Result := Values[TDBXPropertyNames.Password];
end;
function TDBXOracleProperties.GetRowsetSize: Integer;
begin
Result := StrToIntDef(Values[StrRowsetSize], 20);
end;
function TDBXOracleProperties.GetUserName: string;
begin
Result := Values[TDBXPropertyNames.UserName];
end;
procedure TDBXOracleProperties.SetBlobSize(const Value: Integer);
begin
Values[TDBXPropertyNames.MaxBlobSize] := IntToStr(Value);
end;
procedure TDBXOracleProperties.SetDatabase(const Value: string);
begin
Values[TDBXPropertyNames.Database] := Value;
end;
procedure TDBXOracleProperties.SetOracleTransIsolation(const Value: string);
begin
Values[StrOracleTransisolation] := Value;
end;
procedure TDBXOracleProperties.SetDecimalSeparator(const Value: string);
begin
Values[StrDecimalSeparator] := Value;
end;
procedure TDBXOracleProperties.SetOSAuthentication(const Value: Boolean);
begin
Values[StrOSAuthentication] := BoolToStr(Value, True);
end;
procedure TDBXOracleProperties.SetTrimChar(const Value: Boolean);
begin
Values[StrTrimChar] := BoolToStr(Value, True);
end;
procedure TDBXOracleProperties.SetHostName(const Value: string);
begin
Values[TDBXPropertyNames.HostName] := Value;
end;
procedure TDBXOracleProperties.SetMultipleTransaction(
const Value: Boolean);
begin
Values[StrMultipleTransaction] := BoolToStr(Value, True);
end;
procedure TDBXOracleProperties.SetPassword(const Value: string);
begin
Values[TDBXPropertyNames.Password] := Value;
end;
procedure TDBXOracleProperties.SetRowsetSize(const Value: Integer);
begin
Values[StrRowsetSize] := IntToStr(Value);
end;
procedure TDBXOracleProperties.SetUserName(const Value: string);
begin
Values[TDBXPropertyNames.UserName] := Value;
end;
initialization
TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXOracleDriver);
end.
|
{**********************************************}
{ TeeChart Gallery Dialog }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeeGally;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
{$IFDEF CLX}
QGraphics, QControls, QExtCtrls, QStdCtrls, QComCtrls, QForms,
{$ELSE}
Graphics, Controls, StdCtrls, ExtCtrls, ComCtrls, Forms,
{$ENDIF}
SysUtils, Classes,
TeEngine, Chart, TeeGalleryPanel, TeeProcs;
type
TTeeGallery = class(TForm)
P1: TPanel;
BOk: TButton;
BCancel: TButton;
CB3D: TCheckBox;
TabPages: TTabControl;
TabTypes: TTabControl;
ChartGalleryPanel1: TChartGalleryPanel;
CBSmooth: TCheckBox;
procedure CB3DClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure TabPagesChange(Sender: TObject);
procedure TabTypesChange(Sender: TObject);
procedure ChartGalleryPanel1SelectedChart(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CBSmoothClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Procedure HideButtons;
Procedure HideFunctions;
end;
{ Shows the gallery and asks the user a Series type.
If user double clicks a chart or presses Ok, a new Series
is created and returned. The new Series is owned by AOwner
parameter (usually the Form).
}
Function CreateNewSeriesGallery( AOwner:TComponent;
OldSeries:TChartSeries;
tmpChart:TCustomAxisPanel;
AllowSameType,
CheckSeries:Boolean;
Var SubIndex:Integer ):TChartSeries; overload;
// Same as above but much simpler to use:
Function CreateNewSeriesGallery( AOwner:TComponent;
AChart:TCustomAxisPanel):TChartSeries; overload;
{ Shows the gallery and asks the user a Series type. Then
changes tmpSeries to the new type. }
procedure ChangeSeriesTypeGallery(AOwner:TComponent; Var tmpSeries:TChartSeries);
{ Shows the Gallery Dialog and lets the user choose a Series type.
Returns True if user pressed OK.
The "tmpClass" parameter returns the choosen type.
}
Function GetChartGalleryClass( AOwner:TComponent;
OldSeries:TChartSeries;
ShowFunctions:Boolean;
Var tmpClass:TChartSeriesClass;
Var Show3D:Boolean;
Var tmpFunctionClass:TTeeFunctionClass;
CheckValidSeries:Boolean;
Var SubIndex:Integer):Boolean;
{ Shows the gallery and asks the user a Series type. Then
changes all Series in AChart to the new type. }
procedure ChangeAllSeriesGallery( AOwner:TComponent; AChart:TCustomChart );
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeeLisB, TeeConst, Series, TeCanvas, TeePenDlg, TeeGalleryAlternate;
{ TeeGallery }
Procedure TTeeGallery.HideFunctions;
begin
{$IFDEF CLX}
if TabTypes.Tabs.Count>1 then
{$ENDIF}
TabTypes.Tabs.Delete(1);
ChartGalleryPanel1.FunctionsVisible:=False;
end;
Procedure TTeeGallery.HideButtons;
begin
P1.Visible:=False;
end;
procedure TTeeGallery.CB3DClick(Sender: TObject);
begin
ChartGalleryPanel1.View3D:=CB3D.Checked;
end;
procedure TTeeGallery.FormShow(Sender: TObject);
begin
CBSmooth.Checked:=ChartGalleryPanel1.Smooth;
TabTypes.TabIndex:=0;
TabTypesChange(Self);
TeeTranslateControl(Self);
end;
procedure TTeeGallery.TabPagesChange(Sender: TObject);
begin
With ChartGalleryPanel1 do
begin
FunctionsVisible:=TabTypes.TabIndex=1;
View3D:=CB3D.Checked;
With TabPages do
if TabIndex<>-1 then CreateGalleryPage(Tabs[TabIndex]{$IFDEF CLX}.Caption{$ENDIF})
else Charts.Clear;
end;
end;
procedure TTeeGallery.TabTypesChange(Sender: TObject);
Function TabIndexOf(Const GalleryPage:String):Integer;
{$IFDEF CLX}
var t : Integer;
{$ENDIF}
begin
{$IFDEF CLX}
With TabPages do
for t:=0 to Tabs.Count-1 do
if Tabs[t].Caption=GalleryPage then
begin
result:=t;
exit;
end;
result:=-1;
{$ELSE}
result:=TabPages.Tabs.IndexOf(GalleryPage);
{$ENDIF}
end;
Procedure AddTabPages;
var t : Integer;
tmpPage : String;
begin
TabPages.Tabs.Clear;
With TeeSeriesTypes do
for t:=0 to Count-1 do
With Items[t] do
if NumGallerySeries>0 then
begin
tmpPage:=GalleryPage{$IFNDEF CLR}^{$ENDIF};
{$IFNDEF CLX}
if TabPages.Tabs.IndexOf(tmpPage)=-1 then
{$ELSE}
if TabIndexOf(tmpPage)=-1 then
{$ENDIF}
Case TabTypes.TabIndex of
0: if not Assigned(FunctionClass) then TabPages.Tabs.Add(tmpPage);
1: if Assigned(FunctionClass) then TabPages.Tabs.Add(tmpPage);
end;
end;
end;
var i : Integer;
begin
AddTabPages;
i:=TabIndexOf(TeeMsg_GalleryStandard);
if i>0 then
{$IFDEF CLX}
TabPages.Tabs[i].Index:=0;
{$ELSE}
TabPages.Tabs.Exchange(0,i);
{$ENDIF}
TabPages.TabIndex:=0;
TabPagesChange(Self);
end;
procedure TTeeGallery.ChartGalleryPanel1SelectedChart(Sender: TObject);
begin
ModalResult:=mrOk;
end;
procedure TTeeGallery.FormCreate(Sender: TObject);
begin
with TabTypes.Tabs do
begin
Add(TeeMsg_Series);
Add(TeeMsg_GalleryFunctions);
end;
end;
{ Helper functions }
Function GetChartGalleryClass( AOwner:TComponent;
OldSeries:TChartSeries;
ShowFunctions:Boolean;
Var tmpClass:TChartSeriesClass;
Var Show3D:Boolean;
Var tmpFunctionClass:TTeeFunctionClass;
CheckValidSeries:Boolean;
Var SubIndex:Integer):Boolean;
procedure NormalGallery;
begin
with TTeeGallery.Create(AOwner) do
try
{$IFDEF D5}
if Assigned(Owner) then Position:=poOwnerFormCenter
else
{$ENDIF}
Position:=poScreenCenter;
CB3D.Checked:=Show3D;
ChartGalleryPanel1.SelectedSeries:=OldSeries;
if not ShowFunctions then HideFunctions;
ChartGalleryPanel1.CheckSeries:=CheckValidSeries;
if ShowModal=mrOk then
begin
result:=ChartGalleryPanel1.GetSeriesClass(tmpClass,tmpFunctionClass,SubIndex);
if result then
Show3D:=CB3D.Checked and ChartGalleryPanel1.SelectedChart.View3D;
end;
finally
Free;
end;
end;
procedure AlternateGallery;
var g : TTeeGalleryForm;
begin
g:=TTeeGalleryForm.Create(AOwner);
with g do
try
{$IFDEF D5}
if Assigned(Owner) then Position:=poOwnerFormCenter
else
{$ENDIF}
Position:=poScreenCenter;
CB3D.Checked:=Show3D;
TeeTranslateControl(g);
if ShowModal=mrOk then
begin
result:=ChartGalleryPanel1.GetSeriesClass(tmpClass,tmpFunctionClass,SubIndex);
if result then
Show3D:=CB3D.Checked and ChartGalleryPanel1.SelectedChart.View3D;
end;
finally
Free;
end;
end;
begin
result:=False;
if TChartGalleryPanel.DefaultMode=0 then
NormalGallery
else
AlternateGallery;
end;
Function CreateNewSeriesGallery( AOwner:TComponent;
AChart:TCustomAxisPanel):TChartSeries;
var tmp : Integer;
begin
result:=CreateNewSeriesGallery( AOwner, nil, AChart, True, False, tmp);
end;
type TSeriesAccess=class(TChartSeries);
Function CreateNewSeriesGallery( AOwner:TComponent;
OldSeries:TChartSeries;
tmpChart:TCustomAxisPanel;
AllowSameType,
CheckSeries:Boolean;
Var SubIndex:Integer ):TChartSeries;
var Show3D : Boolean;
tmpClass : TChartSeriesClass;
tmpFunctionClass : TTeeFunctionClass;
begin
result:=nil;
Show3D:=tmpChart.View3D;
if GetChartGalleryClass(AOwner,OldSeries,AllowSameType,tmpClass,Show3D,
tmpFunctionClass,CheckSeries,SubIndex) then
begin
tmpChart.View3D:=Show3D;
if (not Assigned(OldSeries)) or
(AllowSameType or ((tmpClass<>OldSeries.ClassType) or (SubIndex<>-1))) then
begin
if Assigned(OldSeries) then AOwner:=OldSeries.Owner
else AOwner:=tmpChart.Owner;
result:=CreateNewSeries(AOwner,tmpChart,tmpClass,tmpFunctionClass);
if SubIndex<>-1 then TSeriesAccess(result).SetSubGallery(result,SubIndex);
end;
end;
end;
procedure ChangeSeriesTypeGallery(AOwner:TComponent; Var tmpSeries:TChartSeries);
var NewSeries : TChartSeries;
SubIndex : Integer;
begin
NewSeries:=CreateNewSeriesGallery(AOwner,tmpSeries,tmpSeries.ParentChart,False,True,SubIndex);
if Assigned(NewSeries) then
begin
AssignSeries(tmpSeries,NewSeries);
tmpSeries:=NewSeries;
if SubIndex<>-1 then TSeriesAccess(tmpSeries).SetSubGallery(tmpSeries,SubIndex);
end;
end;
procedure ChangeAllSeriesGallery( AOwner:TComponent; AChart:TCustomChart );
var NewSeries : TChartSeries;
tmpSeries : TChartSeries;
SubIndex : Integer;
begin
if AChart.SeriesCount>0 then
begin
tmpSeries:=AChart.Series[0];
NewSeries:=CreateNewSeriesGallery(AOwner,tmpSeries,AChart,False,True,SubIndex);
if Assigned(NewSeries) then
begin
AssignSeries(tmpSeries,NewSeries);
ChangeAllSeriesType(AChart,TChartSeriesClass(NewSeries.ClassType));
end;
end;
end;
Function TeeAddGallery(AOwner:TComponent; Chart:TCustomChart; Series:TChartSeries):TChartSeries;
var SubIndex : Integer;
begin
if Assigned(Chart) then
result:=CreateNewSeriesGallery(AOwner,Series,Chart,True,False,SubIndex)
else
result:=nil;
end;
Function TeeChangeGallery(AOwner:TComponent; var Series: TChartSeries):TChartSeriesClass;
begin
ChangeSeriesTypeGallery(AOwner,Series);
result:=TChartSeriesClass(Series.ClassType);
end;
procedure TTeeGallery.CBSmoothClick(Sender: TObject);
begin
ChartGalleryPanel1.Smooth:=CBSmooth.Checked;
ChartGalleryPanel1.SaveSmooth(ChartGalleryPanel1.Smooth);
end;
initialization
TeeAddGalleryProc:=TeeAddGallery;
TeeChangeGalleryProc:=TeeChangeGallery;
finalization
TeeChangeGalleryProc:=nil;
TeeAddGalleryProc:=nil;
end.
|
unit ncDMCaixa;
{
ResourceString: Dario 12/03/13
}
interface
uses
SysUtils, Classes, DB, nxdb, kbmMemTable, nxllTransport,
nxptBasePooledTransport, nxtwWinsockTransport, nxsdServerEngine,
nxreRemoteServerEngine, nxllComponent, frxClass, frxDBSet, frxExportPDF,
uLogs, uNexTransResourceStrings_PT;
type
{TDadosCaixa = record
dcID : Integer;
dcAbertura : TDateTime;
dcFechamento : TDateTime;
dcSaldoInicial : Currency;
dcUsuario : String;
end;}
TDadosResFin = record
rfFaturamento,
rfDebitado,
rfRecebido,
rfPgDebito : Currency;
end;
TdmCaixa = class(TDataModule)
nxSession: TnxSession;
nxDB: TnxDatabase;
nxRSE: TnxRemoteServerEngine;
nxTCPIP: TnxWinsockTransport;
dsQVC: TDataSource;
qVC: TnxQuery;
tProd: TnxTable;
tProdDescricao: TStringField;
tME: TnxTable;
mtEst: TkbmMemTable;
mtEstSaldoInicial: TFloatField;
mtEstEntradas: TFloatField;
mtEstCompras: TFloatField;
mtEstSaidas: TFloatField;
mtEstVendas: TFloatField;
mtEstValorVendas: TCurrencyField;
mtEstDescricao: TStringField;
mtEstSaldoFinal: TFloatField;
mtEstLucro: TCurrencyField;
dsTot: TDataSource;
dsEst: TDataSource;
mtTot: TkbmMemTable;
mtTotItem: TIntegerField;
mtTotDescricao: TStringField;
mtTotTotal: TCurrencyField;
tProdID: TAutoIncField;
mtEstID: TIntegerField;
tProdCustoUnitario: TCurrencyField;
tProdNaoControlaEstoque: TBooleanField;
qRFFat: TnxQuery;
mtTotFaturamento: TCurrencyField;
mtTotDebitado: TCurrencyField;
mtTotRecebido: TCurrencyField;
mtTotPgDebito: TCurrencyField;
qSS: TnxQuery;
qSSTipo: TWordField;
qSSTotal: TCurrencyField;
qDesc: TnxQuery;
qCanc: TnxQuery;
tCli: TnxTable;
qGratis: TnxQuery;
qVCCategoria: TStringField;
qVCTotal: TCurrencyField;
qVCDesconto: TCurrencyField;
qVCTotFinal: TCurrencyField;
dsGratis: TDataSource;
tMEID: TAutoIncField;
tMETran: TIntegerField;
tMEProduto: TIntegerField;
tMEQuant: TFloatField;
tMEUnitario: TCurrencyField;
tMETotal: TCurrencyField;
tMECustoU: TCurrencyField;
tMEItem: TWordField;
tMEDesconto: TCurrencyField;
tMEPago: TCurrencyField;
tMEPagoPost: TCurrencyField;
tMEDescPost: TCurrencyField;
tMEDataHora: TDateTimeField;
tMEEntrada: TBooleanField;
tMECancelado: TBooleanField;
tMEEstoqueAnt: TFloatField;
tMECliente: TIntegerField;
tMECaixa: TIntegerField;
tMECategoria: TStringField;
tMENaoControlaEstoque: TBooleanField;
tMEITran: TIntegerField;
tMETipoTran: TWordField;
tMESessao: TIntegerField;
tMESaldoFinal: TFloatField;
tCaixa: TnxTable;
tCaixaID: TAutoIncField;
tCaixaAberto: TBooleanField;
tCaixaUsuario: TStringField;
tCaixaAbertura: TDateTimeField;
tCaixaFechamento: TDateTimeField;
tCaixaTotalFinal: TCurrencyField;
tCaixaDescontos: TCurrencyField;
tCaixaCancelamentos: TCurrencyField;
tCaixaSaldoAnt: TCurrencyField;
tCaixaObs: TMemoField;
qFecha: TnxQuery;
qFechaCancelado: TBooleanField;
qFechaTipo: TWordField;
qFechaTotal: TCurrencyField;
qFechaDesconto: TCurrencyField;
qFechaPago: TCurrencyField;
qFechaDebito: TCurrencyField;
tSessao: TnxTable;
PDFexp: TfrxPDFExport;
frdbCaixa: TfrxDBDataset;
frdbTot: TfrxDBDataset;
tCriar: TnxTable;
tCriarID: TAutoIncField;
tCriarTipo: TIntegerField;
tCriarParametros: TMemoField;
tCriarDestino: TMemoField;
qVCQuant: TFloatField;
tCaixaSangria: TCurrencyField;
tCaixaSupr: TCurrencyField;
mtImp: TkbmMemTable;
mtImpTipoImp: TIntegerField;
tTipoImp: TnxTable;
mtImpQuant: TIntegerField;
mtImpValor: TCurrencyField;
dsImp: TDataSource;
tImp: TnxTable;
tImpID: TAutoIncField;
tImpTran: TIntegerField;
tImpCaixa: TIntegerField;
tImpManual: TBooleanField;
tImpDataHora: TDateTimeField;
tImpComputador: TStringField;
tImpMaquina: TWordField;
tImpPaginas: TWordField;
tImpImpressora: TStringField;
tImpDocumento: TMemoField;
tImpSessao: TIntegerField;
tImpResultado: TWordField;
tImpq1: TWordField;
tImpq2: TWordField;
tImpq3: TWordField;
tImpq4: TWordField;
tImpq5: TWordField;
tImpq6: TWordField;
tImpq7: TWordField;
tImpq8: TWordField;
tImpq9: TWordField;
tImpq10: TWordField;
tImpv1: TCurrencyField;
tImpv2: TCurrencyField;
tImpv3: TCurrencyField;
tImpv4: TCurrencyField;
tImpv5: TCurrencyField;
tImpv6: TCurrencyField;
tImpv7: TCurrencyField;
tImpv8: TCurrencyField;
tImpv9: TCurrencyField;
tImpv10: TCurrencyField;
tImpTotal: TCurrencyField;
tImpDesconto: TCurrencyField;
tImpPagoPost: TCurrencyField;
tImpDescPost: TCurrencyField;
tImpPago: TCurrencyField;
tImpFunc: TStringField;
tImpCliente: TIntegerField;
tImpCancelado: TBooleanField;
mtImpNomeTipoImp: TStringField;
tCaixaReproc: TDateTimeField;
qCorr: TnxQuery;
qCorr2: TnxQuery;
qSessao: TnxQuery;
dsSessao: TDataSource;
qSessaoID: TIntegerField;
qSessaoInicio: TDateTimeField;
qSessaoTermino: TDateTimeField;
qSessaoMinutosR: TFloatField;
qSessaoMinutosC: TFloatField;
qSessaoMaq: TWordField;
qSessaoMaqI: TWordField;
qSessaoEncerrou: TBooleanField;
qSessaoCliente: TIntegerField;
qSessaoTransfMaq: TBooleanField;
qSessaoTipoCli: TWordField;
qSessaoCancelado: TBooleanField;
qSessaoTotal: TCurrencyField;
qSessaoDesconto: TCurrencyField;
qSessaoPagoPost: TCurrencyField;
qSessaoDescPost: TCurrencyField;
qSessaoPago: TCurrencyField;
qSessaoNomeCliente: TStringField;
qSessaoFuncI: TStringField;
qSessaoFuncF: TStringField;
qSessaoObs: TMemoField;
qSessaoTipoAcesso: TIntegerField;
qSessaoCaixaI: TIntegerField;
qSessaoCaixaF: TIntegerField;
qSessaoTicksI: TIntegerField;
qSessaoPausado: TBooleanField;
qSessaoInicioPausa: TIntegerField;
qSessaoMinTicksUsados: TIntegerField;
qSessaoMinTicksTotal: TIntegerField;
qSessaoFimTicksUsados: TIntegerField;
qSessaoFimTicksTotal: TIntegerField;
qSessaoStrPausas: TMemoField;
qSessaoStrTransfMaq: TMemoField;
qSessaoStrFechamentoCaixa: TMemoField;
qSessaoMinutosCli: TFloatField;
qSessaoMinutosPrev: TFloatField;
qSessaoMinutosMax: TFloatField;
qSessaoMinutosCliU: TFloatField;
qSessaoValorCli: TCurrencyField;
qSessaoValorCliU: TFloatField;
qSessaoTranI: TIntegerField;
qSessaoTranF: TIntegerField;
qSessaoPermitirDownload: TBooleanField;
qSessaoVersaoRegistro: TIntegerField;
qSessaoCartaoTempo: TBooleanField;
qSessaoHP1: TIntegerField;
qSessaoHP2: TIntegerField;
qSessaoHP3: TIntegerField;
qSessaoHP4: TIntegerField;
qSessaoHP5: TIntegerField;
qSessaoHP6: TIntegerField;
qSessaoHP7: TIntegerField;
qSessaoRG: TStringField;
qSessaoCPF: TStringField;
qSessaoEndereco: TStringField;
qSessaoBairro: TStringField;
qSessaoDataNasc: TDateField;
qSessaoCEP: TStringField;
qSessaoUF: TStringField;
qSessaoTelefone: TStringField;
qSessaoCelular: TStringField;
qSessaoCidade: TStringField;
qSessaoEmail: TStringField;
tTran: TnxTable;
tTranID: TAutoIncField;
tTranDataHora: TDateTimeField;
tTranCliente: TIntegerField;
tTranTipo: TWordField;
tTranFunc: TStringField;
tTranTotal: TCurrencyField;
tTranDesconto: TCurrencyField;
tTranPago: TCurrencyField;
tTranObs: TMemoField;
tTranCancelado: TBooleanField;
tTranCanceladoPor: TStringField;
tTranCanceladoEm: TDateTimeField;
tTranCaixa: TIntegerField;
tTranMaq: TWordField;
tTranNomeCliente: TStringField;
tTranSessao: TIntegerField;
tTranDescr: TStringField;
tTranDebito: TCurrencyField;
tTranQtdTempo: TFloatField;
tTranCredValor: TBooleanField;
tITran: TnxTable;
tITranID: TAutoIncField;
tITranTran: TIntegerField;
tITranCaixa: TIntegerField;
tITranDataHora: TDateTimeField;
tITranTipoTran: TWordField;
tITranTipoItem: TWordField;
tITranSubTipo: TWordField;
tITranItemID: TIntegerField;
tITranSubItemID: TIntegerField;
tITranItemPos: TWordField;
tITranTotal: TCurrencyField;
tITranDesconto: TCurrencyField;
tITranPago: TCurrencyField;
tITranCancelado: TBooleanField;
tITranSessao: TIntegerField;
tITranDebito: TCurrencyField;
tImpx75: TBooleanField;
qSessaoUsername: TStringField;
mtEstFidResg: TFloatField;
tMEFidResgate: TBooleanField;
tMEFidPontos: TFloatField;
qFatPre: TnxQuery;
qFatPos: TnxQuery;
mtFatPrePos: TkbmMemTable;
mtFatPrePosTipo: TStringField;
mtFatPrePosQuant: TIntegerField;
mtFatPrePosValor: TCurrencyField;
tTipoPass: TnxTable;
tTipoPassID: TAutoIncField;
tTipoPassNome: TStringField;
tPacote: TnxTable;
tPacoteID: TAutoIncField;
tPacoteDescr: TStringField;
dsPrePos: TDataSource;
tCaixaEstSessoesQtd: TIntegerField;
tCaixaEstSessoesTempo: TFloatField;
tCaixaEstUrls: TIntegerField;
tCaixaEstSyncOk: TBooleanField;
tCaixaEstBuscasEng: TMemoField;
qEstSearchQtd: TnxQuery;
qEstSearchPag: TnxQuery;
qEstUrl: TnxQuery;
qEstSessoes: TnxQuery;
qEstRes: TnxQuery;
tCaixaEstRes: TMemoField;
qCancQuant: TLargeintField;
qCancTotal: TCurrencyField;
qGratisCliente: TIntegerField;
qGratisQuant: TLargeintField;
qGratisMinutosU: TFloatField;
qGratisMinutosP: TFloatField;
qDescQuant: TLargeintField;
qDescTotal: TCurrencyField;
qFatPosQuant: TLargeintField;
qFatPosValor: TCurrencyField;
qEstSearchPagSearchEng: TStringField;
qEstSearchPagQtd: TLargeintField;
qEstSearchQtdSearchEng: TStringField;
qEstSearchQtdQtd: TLargeintField;
qEstUrlqtd: TLargeintField;
qEstResDisplayWH: TStringField;
qEstResqtd: TLargeintField;
qEstSessoestempo: TFloatField;
qEstSessoesqtd: TLargeintField;
qFatPreTipo: TWordField;
qFatPreIDPacPass: TIntegerField;
qFatPreQuant: TLargeintField;
qFatPreValor: TCurrencyField;
qGratisNomeCliente: TStringField;
qManut: TnxQuery;
qManutFunc: TStringField;
qManutQuant: TLargeintField;
qManutMinutosU: TFloatField;
dsManut: TDataSource;
qSessaoIPs: TnxMemoField;
tCaixaSaldoF: TCurrencyField;
tCaixaQuebra: TCurrencyField;
frdbEst: TfrxDBDataset;
mtEstEntradasTot: TFloatField;
frdbImp: TfrxDBDataset;
frdbTran: TfrxDBDataset;
tRepProd: TnxTable;
tRepProdID: TAutoIncField;
tRepProdCodigo: TStringField;
tRepProdDescricao: TStringField;
tRepProdUnid: TStringField;
tRepProdPreco: TCurrencyField;
tRepProdObs: TnxMemoField;
tRepProdImagem: TGraphicField;
tRepProdCategoria: TStringField;
tRepProdFornecedor: TIntegerField;
tRepProdSubCateg: TStringField;
tRepProdEstoqueAtual: TFloatField;
tRepProdCustoUnitario: TCurrencyField;
tRepProdEstoqueACE: TFloatField;
tRepProdEstoqueACS: TFloatField;
tRepProdPodeAlterarPreco: TBooleanField;
tRepProdNaoControlaEstoque: TBooleanField;
tRepProdEstoqueMin: TFloatField;
tRepProdEstoqueMax: TFloatField;
tRepProdAbaixoMin: TBooleanField;
tRepProdAbaixoMinDesde: TDateTimeField;
tRepProdEstoqueRepor: TFloatField;
tRepProdFidelidade: TBooleanField;
tRepProdFidPontos: TIntegerField;
frdbProd: TfrxDBDataset;
qRepTran: TnxQuery;
qRepTranID: TIntegerField;
qRepTranDataHora: TDateTimeField;
qRepTranCliente: TIntegerField;
qRepTranTipo: TWordField;
qRepTranFunc: TStringField;
qRepTranTotal: TCurrencyField;
qRepTranDesconto: TCurrencyField;
qRepTranTotLiq: TCurrencyField;
qRepTranPago: TCurrencyField;
qRepTranDebito: TCurrencyField;
qRepTranObs: TnxMemoField;
qRepTranCancelado: TBooleanField;
qRepTranCanceladoPor: TStringField;
qRepTranCanceladoEm: TDateTimeField;
qRepTranCaixa: TIntegerField;
qRepTranMaq: TWordField;
qRepTranNomeCliente: TStringField;
qRepTranSessao: TIntegerField;
qRepTranDescr: TStringField;
qRepTranQtdTempo: TFloatField;
qRepTranCredValor: TBooleanField;
qRepTranFidResgate: TBooleanField;
qRepTranNomeTipo: TStringField;
qRepTranCancFid: TStringField;
tCaixaIDLivre: TStringField;
tUsuario: TnxTable;
tUsuarioUsername: TStringField;
tUsuarioNome: TStringField;
tUsuarioAdmin: TBooleanField;
repCaixa: TfrxReport;
tCaixaNomeLoja: TStringField;
qPagEsp: TnxQuery;
qPagEspTotalF: TCurrencyField;
qPagEspTotalValor: TCurrencyField;
qPagEspTotalTroco: TCurrencyField;
qPagEspEspecie: TWordField;
tEsp: TnxTable;
tEspID: TWordField;
tEspNome: TStringField;
tEspImg: TWordField;
qPagEspNomeEspecie: TStringField;
qPagEspImg: TWordField;
qPagEspObs: TStringField;
dsPagEsp: TDataSource;
frdbPagEsp: TfrxDBDataset;
qRFPag: TnxQuery;
qRFFatTipoTran: TWordField;
qRFFatTipoItem: TWordField;
qRFFatTotal: TCurrencyField;
qRFFatDesconto: TCurrencyField;
qRFPagTipoTran: TWordField;
qRFPagTipoItem: TWordField;
qRFPagTotal: TCurrencyField;
qRFPagDesconto: TCurrencyField;
qRFPagPago: TCurrencyField;
qRFPagDebito: TCurrencyField;
qFechaTroco: TCurrencyField;
qCred: TnxQuery;
qCredCredito: TCurrencyField;
procedure qVCCalcFields(DataSet: TDataSet);
procedure tMECalcFields(DataSet: TDataSet);
procedure DataModuleCreate(Sender: TObject);
procedure qFatPosCalcFields(DataSet: TDataSet);
procedure mtEstCalcFields(DataSet: TDataSet);
procedure repCaixaBeforePrint(Sender: TfrxReportComponent);
procedure qRepTranCalcFields(DataSet: TDataSet);
procedure tCaixaCalcFields(DataSet: TDataSet);
procedure qPagEspCalcFields(DataSet: TDataSet);
private
{ Private declarations }
public
drf : Array[0..2] of TDadosResFin;
CaixaI,
CaixaF: Integer;
TemSupSan : Boolean;
FImpTran : Boolean;
TotalTroco : Currency;
procedure AbreConn;
function AbreCaixa(aFunc: String; aSaldo: Currency; aManterSaldo: Boolean; var aNumCx: Integer): Integer;
function FechaCaixa(aFunc: String; aSaldo: Currency; aNumCx: Integer; aReproc: Boolean): Integer;
function Processa(aID: Integer; aPeriodo: Boolean; aDataI, aDataF: TDateTime): Currency;
procedure ExportaCaixa(aID: Integer; aArquivo: String);
procedure ExportaCaixaKite(aID: Integer; aArquivo: String; slPar: tStrings);
{ Public declarations }
end;
var
dmCaixa: TdmCaixa;
implementation
uses
ncClassesBase, ncErros, Graphics, ncDebug;
// START resource string wizard section
{$R *.dfm}
{ TdmCaixa }
resourcestring
rsValorOriginal = 'Valor Original';
rsTroco = 'Troco';
function InitTran(aDB: TnxDatabase;
const aTables : array of TnxTable;
aWith : Boolean): Boolean;
var I : Integer;
begin
Result := False;
if aDB.InTransaction then Exit;
I := 10;
while I > 0 do begin
try
if aWith then
aDB.StartTransactionWith(aTables)
else
aDB.StartTransaction;
I := 0;
except
Dec(I);
Random(500);
end
end;
Result := True;
end;
function TdmCaixa.AbreCaixa(aFunc: String; aSaldo: Currency; aManterSaldo: Boolean; var aNumCx: Integer): Integer;
var SaldoAnt: Currency;
begin
tCaixa.Active := True;
tTran.IndexName := 'IID'; // do not localize
tTran.Open;
tITran.Open;
tImp.Open;
InitTran(nxDB, [tCaixa, tImp, tTran, tITran], True);
try
tCaixa.IndexName := 'IAberto'; // do not localize
try
if tCaixa.FindKey([True]) then begin
nxDB.Rollback;
Result := ncerrJaTemCaixaAberto;
Exit;
end;
finally
tCaixa.IndexName := 'IID'; // do not localize
end;
if aManterSaldo then begin
if tCaixa.IsEmpty then
SaldoAnt := 0
else begin
tCaixa.Last;
SaldoAnt := tCaixaTotalFinal.Value + tCaixaSaldoAnt.Value + tCaixaSupr.Value - tCaixaSangria.Value;
end;
end else
SaldoAnt := aSaldo;
tCaixa.Insert;
tCaixaAbertura.Value := Now;
tCaixaAberto.Value := True;
tCaixaUsuario.Value := aFunc;
if aManterSaldo or gConfig.PedirSaldoI then
tCaixaSaldoAnt.Value := SaldoAnt;
tCaixaEstSyncOk.Value := False;
tCaixa.Post;
aNumCx := tCaixaID.Value;
Result := 0;
tImp.IndexName := 'ICaixaID'; // do not localize
while tImp.FindKey([0]) do begin
tImp.Edit;
if tImpx75.Value then
tImpCaixa.Value := aNumCx else
tImpCaixa.Value := -1;
tImp.Post;
if tImpx75.Value then
if tTran.FindKey([tImpTran.Value]) and (tTranCaixa.Value=0) then begin
if tTranCaixa.Value=0 then
tTran.Edit;
tTranCaixa.Value := aNumCx;
tTran.Post;
tITran.SetRange([tTranID.Value], [tTranID.Value]);
try
tITran.First;
while not tITran.Eof do begin
tITran.Edit;
tITranCaixa.Value := aNumCx;
tITran.Post;
tITran.Next;
end;
finally
tITran.CancelRange;
end;
end;
end;
nxDB.Commit;
except
on e: exception do begin
nxDB.Rollback;
Result := ncerrExcecaoNaoTratada_TdmCaixa_AbreCaixa;
glog.LogCriticalException(self,Result, e);
end;
end;
end;
procedure TdmCaixa.AbreConn;
begin
nxDB.AliasPath := '';
nxDB.AliasName := 'NexCafe'; // do not localize
nxDB.Active := True;
tCli.Open;
tME.Open;
tProd.Open;
tCaixa.Open;
tSessao.Open;
tCriar.Open;
end;
procedure TdmCaixa.DataModuleCreate(Sender: TObject);
begin
TemSupSan := False;
FImpTran := False;
TotalTroco := 0;
end;
procedure TdmCaixa.ExportaCaixa(aID: Integer; aArquivo: String);
begin
ExportaCaixaKite(aID, aArquivo, nil);
end;
procedure TdmCaixa.ExportaCaixaKite(aID: Integer; aArquivo: String;
slPar: tStrings);
var sIdent: String;
begin
DebugMsg('TdmCaixa.ExportaCaixa - aID: ' + IntToStr(aID) + ' - aArquivo: ' + aArquivo); // do not localize
Processa(aID, False, 0, 0);
DebugMsg('TdmCaixa.ExportaCaixa - 2'); // do not localize
tUsuario.Active := True;
if slPar<>nil then begin
slPar.Add('timestamp_de_abertura='+formatDateTime('YYYY-MM-DD HH:NN:SS', tCaixaAbertura.Value)); // do not localize
slPar.Add('timestamp_de_fechamento='+formatDateTime('YYYY-MM-DD HH:NN:SS', tCaixaFechamento.Value)); // do not localize
slPar.Add('username_funcionario='+tCaixaUsuario.Value); // do not localize
slPar.Add('numero_do_caxa='+tCaixaID.AsString); // do not localize
slPar.Add('conta_da_loja='+gConfig.Conta); // do not localize
if tUsuario.FindKey([tCaixaUsuario.Value]) then
slPar.Add('nome_funcionario='+tUsuarioNome.Value) else // do not localize
slPar.Add('nome_funcionario='); // do not localize
if Trim(gConfig.EmailIdent)>'' then
sIdent:= gConfig.EmailIdent + ' - ' else
sIdent:= '';
slPar.Add('subject='+sIdent+'Caixa n.' + tCaixaID.AsString+ // do not localize
' - ' + tCaixaAbertura.AsString +
' a ' + tCaixaFechamento.AsString);
end;
pdfExp.FileName := aArquivo;
DebugMsg('TdmCaixa.ExportaCaixa - 3'); // do not localize
pdfExp.DefaultPath := '';
DebugMsg('TdmCaixa.ExportaCaixa - 4'); // do not localize
repCaixa.PrepareReport;
DebugMsg('TdmCaixa.ExportaCaixa - 5'); // do not localize
repCaixa.Export(PDFexp);
DebugMsg('TdmCaixa.ExportaCaixa - 6'); // do not localize
end;
function TdmCaixa.FechaCaixa(aFunc: String; aSaldo: Currency; aNumCx: Integer; aReproc: Boolean): Integer;
var
SAnt: Currency;
SL : TStrings;
begin
InitTran(nxDB, [], False);
try
tCaixa.IndexName := 'IID'; // do not localize
if not tCaixa.FindKey([aNumCx]) then begin
nxDB.Rollback;
Result := ncerrItemInexistente;
Exit;
end;
SAnt := 0;
if aReproc then begin
if tCaixaAberto.Value then begin
nxDB.Rollback;
Raise ENexCafe.Create(SncDMCaixa_OReprocessamentoDeCaixaSóPodeSer);
end;
if gConfig.ManterSaldoCaixa then begin
tCaixa.Prior;
if (tCaixaID.Value < aNumCx) then
if not tCaixaSaldoF.IsNull then
SAnt := tCaixaSaldoF.Value else
SAnt := tCaixaTotalFinal.Value + tCaixaSaldoAnt.Value + tCaixaSupr.Value - tCaixaSangria.Value;
tCaixa.FindKey([aNumCx]);
end else
SAnt := tCaixaSaldoAnt.Value;
end else
if not tCaixaAberto.Value then begin
nxDB.Rollback;
Result := ncerrCaixaJaFoiFechado;
Exit;
end;
if not aReproc then
if tSessao.FindKey([True, 0]) then begin
nxDB.Rollback;
Result := ncerrAguardaPagto;
Exit;
end;
if aReproc then begin
qCorr.Active := False;
qCorr.ParamByName('Caixa').AsInteger := aNumCx; // do not localize
qCorr.ExecSQL;
qCorr2.Active := False;
qCorr2.SQL.Text := 'update itran '+ // do not localize
'set caixa = ' + IntToStr(aNumCx) + // do not localize
' where tran in (select id from tran where caixa = ' + IntToStr(aNumCx) +')'; // do not localize
qCorr2.ExecSQL;
qCorr2.Active := False;
qCorr2.SQL.Text := 'update movest '+ // do not localize
'set caixa = ' + IntToStr(aNumCx) + // do not localize
' where tran in (select id from tran where caixa = ' + IntToStr(aNumCx) +')'; // do not localize
qCorr2.ExecSQL;
end;
qFecha.ParamByName('Caixa').AsInteger := aNumCx; // do not localize
qFecha.Active := True;
tCaixa.Edit;
tCaixaCancelamentos.Value := 0;
tCaixaDescontos.Value := 0;
tCaixaTotalFinal.Value := 0;
tCaixaSangria.Value := 0;
tCaixaSupr.Value := 0;
qEstSearchPag.Params[0].Value := aNumCx;
qEstSearchQtd.Params[0].Value := aNumCx;
qEstUrl.Params[0].Value := aNumCx;
qEstSessoes.Params[0].Value := aNumCx;
try
qEstSearchPag.Active := True;
qEstSearchQtd.Active := True;
qEstUrl.Active := True;
qEstSessoes.Active := True;
qEstRes.Active := True;
SL := TStringList.Create;
try
qEstSearchPag.First;
while not qEstSearchPag.Eof do begin
SL.Values['p_'+qEstSearchPagSearchEng.Value] := IntToStr(qEstSearchPagQtd.Value);
qEstSearchPag.Next;
end;
qEstSearchQtd.First;
while not qEstSearchQtd.Eof do begin
SL.Values['q_'+qEstSearchQtdSearchEng.Value] := IntToStr(qEstSearchQtdQtd.Value);
qEstSearchQtd.Next;
end;
tCaixaEstBuscasEng.Value := SL.Text;
SL.Text := '';
qEstRes.First;
while not qEstRes.Eof do begin
SL.Values[qEstResDisplayWH.Value] := IntToStr(qEstResQtd.Value);
qEstRes.Next;
end;
tCaixaEstUrls.Value := qEstUrlQtd.Value;
tCaixaEstRes.Value := SL.Text;
tCaixaEstSessoesQtd.Value := qEstSessoesQtd.Value;
tCaixaEstSessoesTempo.Value := qEstSessoesTempo.Value;
finally
SL.Free;
end;
finally
qEstSearchPag.Active := False;
qEstSearchQtd.Active := False;
qEstUrl.Active := False;
qEstSessoes.Active := False;
qEstRes.Active := False;
end;
if aReproc then
tCaixaSaldoAnt.Value := SAnt;
while not qFecha.Eof do begin
if qFechaCancelado.Value then
tCaixaCancelamentos.Value := tCaixaCancelamentos.Value + qFechaTotal.Value
else
case qFechaTipo.Value of
trCaixaEnt : tCaixaSupr.Value := tCaixaSupr.Value + qFechaTotal.Value;
trCaixaSai : tCaixaSangria.Value := tCaixaSangria.Value + qFechaTotal.Value;
trEstCompra,
trEstSaida,
trEstEntrada,
trCorrDataCx : ;
else
tCaixaTotalFinal.Value := tCaixaTotalFinal.Value + (qFechaPago.Value-qFechaTroco.Value);
end;
tCaixaDescontos.Value := tCaixaDescontos.Value + qFechaDesconto.Value;
qFecha.Next;
end;
tCaixaAberto.Value := False;
if aReproc then
tCaixaReproc.Value := Now else
tCaixaFechamento.Value := Now;
tCaixaEstSyncOk.Value := True;
if gConfig.PedirSaldoF then begin
if (not aReproc) then
tCaixaSaldoF.Value := aSaldo;
tCaixaQuebra.Value :=
tCaixaSaldoF.Value -
(tCaixaTotalFinal.Value + tCaixaSaldoAnt.Value + tCaixaSupr.Value - tCaixaSangria.Value);
end;
tCaixa.Post;
Result := 0;
nxDB.Commit;
except
on e: exception do begin
nxDB.Rollback;
Result := ncerrExcecaoNaoTratada_TdmCaixa_FechaCaixa;
glog.LogCriticalException(self,Result, e);
end;
end;
end;
procedure TdmCaixa.mtEstCalcFields(DataSet: TDataSet);
begin
mtEstEntradasTot.Value := mtEstEntradas.Value + mtEstCompras.Value;
end;
function V2Casas(C: Currency): Currency;
begin
Result := Int(C * 100) / 100;
end;
function TdmCaixa.Processa(aID: Integer; aPeriodo: Boolean; aDataI, aDataF: TDateTime): Currency;
var
Q: TnxQuery;
I, Num, IDCli : Integer;
CustoU, TotFinal, PercDesc, Desc, DescT : Double;
drf : Array[0..2] of TDadosResFin;
S: String;
Incluir: Boolean;
PagDet, PagReg : Integer;
ValorI : Currency;
qItem: Integer;
Data: TDateTime;
SaldoI : Double;
const
drfSessao = 0;
drfVendas = 1;
drfImp = 2;
function QImp(Index: Integer): Integer;
begin
case Index of
1 : Result := tImpQ1.Value;
2 : Result := tImpQ2.Value;
3 : Result := tImpQ3.Value;
4 : Result := tImpQ4.Value;
5 : Result := tImpQ5.Value;
6 : Result := tImpQ6.Value;
7 : Result := tImpQ7.Value;
8 : Result := tImpQ8.Value;
9 : Result := tImpQ9.Value;
10 : Result := tImpQ10.Value;
else
Result := 0;
end;
end;
function ValorImp(Index: Integer): Currency;
begin
case Index of
1 : Result := tImpV1.Value * tImpQ1.Value;
2 : Result := tImpV2.Value * tImpQ2.Value;
3 : Result := tImpV3.Value * tImpQ3.Value;
4 : Result := tImpV4.Value * tImpQ4.Value;
5 : Result := tImpV5.Value * tImpQ5.Value;
6 : Result := tImpV6.Value * tImpQ6.Value;
7 : Result := tImpV7.Value * tImpQ7.Value;
8 : Result := tImpV8.Value * tImpQ8.Value;
9 : Result := tImpV9.Value * tImpQ9.Value;
10 : Result := tImpV10.Value * tImpQ10.Value;
else
Result := 0;
end;
end;
function UltimoImp(Index: Integer): Boolean;
var
ind: Integer;
begin
for ind := Index+1 to 10 do
if QImp(Ind)>0 then begin
Result := False;
Exit;
end;
Result := True;
end;
begin
Result := 0;
CaixaI := 0;
CaixaF := 0;
qVC.Active := False;
qManut.Active := False;
qGratis.Active := False;
qSS.Active := False;
qDesc.Active := False;
qCanc.Active := False;
qRFFat.Active := False;
qRFPag.Active := False;
qSessao.Active := False;
qFatPre.Active := False;
qFatPos.Active := False;
// qCliValor.Active := False;
mtEst.Active := False;
mtEst.Active := True;
mtTot.Active := False;
mtTot.Active := True;
mtFatPrePos.Active := False;
mtFatPrePos.Active := True;
FillChar(drf, SizeOf(drf), 0);
Num := aID;
if aPeriodo then begin
Q := TnxQuery.Create(Self);
try
Q.Database := nxDB;
Q.SQL.Add('SELECT MIN(ID) as CaixaI, MAX(ID) as CaixaF FROM CAIXA'); // do not localize
Q.SQL.Add('WHERE (Abertura >= TIMESTAMP ' + QuotedStr(FormatDateTime('yyyy-mm-dd hh:mm:ss', aDataI))+') AND ' + // do not localize
' (Abertura < TIMESTAMP ' + QuotedStr(FormatDateTime('yyyy-mm-dd hh:mm:ss', aDataF+1))+') AND (Aberto = False)'); // do not localize
Q.Open;
CaixaI := Q.FieldByName('CaixaI').AsInteger; // do not localize
CaixaF := Q.FieldByName('CaixaF').AsInteger; // do not localize
finally
Q.Free;
end;
end;
if Num > 0 then begin
tCaixa.Locate('ID', Num, []); // do not localize
CaixaI := Num;
CaixaF := Num;
end;
tRepProd.Open;
tRepProd.SetRange([True], [True]);
qRepTran.Active := False;
qRepTran.SQL.Text := 'select * from Tran'; // do not localize
if gConfig.cce(cceTransacoesCanc) then
S := '(Cancelado=True)' else // do not localize
S := '';
if gConfig.cce(cceTransacoesDesc) then
if S>'' then
S := '(Cancelado=True) or (Desconto>0)' else // do not localize
S := '(Desconto>0)'; // do not localize
if gConfig.cce(cceTransacoesObs) then
if S>'' then
S := S + ' or (Trim(Obs)>'+QuotedStr('')+')' else // do not localize
S := '(Trim(Obs)>'+QuotedStr('')+')'; // do not localize
if (gConfig.EmailEnviarCaixa) and (S>'') then begin
FImpTran := True;
S := 'where (Caixa='+IntToStr(CaixaI)+') and ('+S+') order by ID'; // do not localize
qRepTran.SQL.Text := 'select * from Tran ' + S; // do not localize
qRepTran.Open;
end else begin
// qRepTran.Open;
FImpTran := False;
end;
qSessao.Params[0].AsInteger := CaixaI;
qSessao.Params[1].AsInteger := CaixaF;
{ qSessao.Params[2].AsInteger := CaixaI;
qSessao.Params[3].AsInteger := CaixaF; }
dsSessao.DataSet := nil;
try
qSessao.Open;
finally
dsSessao.Dataset := qSessao;
end;
qFatPre.Params[0].AsInteger := CaixaI;
qFatPre.Params[1].AsInteger := CaixaF;
qFatPos.Params[0].AsInteger := CaixaI;
qFatPos.Params[1].AsInteger := CaixaF;
qPagEsp.Active := False;
qPagEsp.Params[0].AsInteger := CaixaI;
qPagEsp.Params[1].AsInteger := CaixaF;
qPagEsp.Active := True;
qPagEsp.First;
TotalTroco := 0;
while not qPagEsp.Eof do begin
TotalTroco := TotalTroco + qPagEspTotalTroco.Value;
qPagEsp.Next;
end;
qPagEsp.First;
qRFFat.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qRFFat.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qRFFat.Active := True;
qRFFat.First;
qRFPag.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qRFPag.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qRFPag.Active := True;
qRFPag.First;
qCred.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qCred.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qCred.Active := True;
while not qRFFat.Eof do begin
case qRFFatTipoItem.Value of
itSessao, itTempo : I := drfSessao;
itMovEst : I := drfVendas;
itImpressao : I := drfImp;
else
I := -1;
end;
if (I>=0) then
if (qRFFatTipoTran.Value <> trEstCompra) and (qRFFatTipoTran.Value <> trPagDebito) then begin
if (qRFFatTipoItem.Value=itSessao) or (qRFFatTipoTran.Value<>trFimSessao) then
drf[I].rfFaturamento :=
drf[I].rfFaturamento +
(qRFFatTotal.Value - qRFFatDesconto.Value);
end;
qRFFat.Next;
end;
while not qRFPag.Eof do begin
case qRFPagTipoItem.Value of
itSessao, itTempo : I := drfSessao;
itMovEst : I := drfVendas;
itImpressao : I := drfImp;
else
I := -1;
end;
if (I>=0) then
if qRFPagTipoTran.Value = trPagDebito then
drf[I].rfPgDebito := drf[I].rfPgDebito + qRFPagPago.Value
else
if qRFPagTipoTran.Value <> trEstCompra then begin
drf[I].rfRecebido := drf[I].rfRecebido + qRFPagPago.Value;
drf[I].rfDebitado := drf[I].rfDebitado + qRFPagDebito.Value;
end;
qRFPag.Next;
end;
dsEst.Dataset := nil;
try
tProd.First;
while not tProd.Eof do begin
tME.SetRange([tProdID.Value, CaixaI], [tProdID.Value, CaixaF]);
if not (tME.Eof and tME.Bof) then begin
Data := 0;
SaldoI := 0;
mtEst.Append;
mtEstID.Value := tProdID.Value;
mtEstDescricao.Value := tProdDescricao.Value;
tME.First;
while not tME.Eof do begin
if (Data=0) or (tMEDataHora.Value<Data) then begin
Data := tMEDataHora.Value;
SaldoI := tMEEstoqueAnt.Value;
end;
case tMETipoTran.Value of
trEstCompra : mtEstCompras.Value := mtEstCompras.Value + tMEQuant.Value;
trEstEntrada : mtEstEntradas.Value := mtEstEntradas.Value + tMEQuant.Value;
trEstSaida : mtEstSaidas.Value := mtEstSaidas.Value + tMEQuant.Value;
else
if tMEFidResgate.Value then begin
mtEstFidResg.Value := mtEstFidResg.Value + tMEQuant.Value;
end else begin
mtEstVendas.Value := mtEstVendas.Value + tMEQuant.Value;
mtEstValorVendas.Value := mtEstValorVendas.Value + tMETotal.Value - tMEDesconto.Value;
CustoU := tMECustoU.Value;
if (CustoU < 0.00009) then
CustoU := tProdCustoUnitario.Value;
mtEstLucro.Value := mtEstLucro.Value + (tMETotal.Value - (CustoU * tMEQuant.Value) - tMEDesconto.Value);
end;
end;
tME.Next;
end;
mtEstSaldoInicial.Value := SaldoI;
mtEstSaldoFinal.Value := tMESaldoFinal.Value;
mtEst.Post;
end;
tProd.Next;
end;
finally
dsEst.Dataset := mtEst;
end;
PagDet := 0;
PagReg := 0;
ValorI := 0;
mtImp.DisableControls;
dsImp.Dataset := nil;
try
{$IFNDEF LOJA}
tTipoImp.Active := True;
mtImp.Active := True;
mtImp.EmptyTable;
tImp.Active := True;
tImp.SetRange([CaixaI], [CaixaF]);
tImp.First;
while not tImp.Eof do begin
if not tImpCancelado.Value then begin
if (tImpDesconto.Value > 0.009) and (tImpTotal.Value>0.009) then begin
DescT := tImpDesconto.Value;
PercDesc := tImpDesconto.Value / tImpTotal.Value;
end else begin
PercDesc := 0;
DescT := 0;
end;
if not tImpManual.Value then
PagDet := PagDet + tImpPaginas.Value;
for I := 1 to 10 do
if QImp(I)>0 then begin
if mtImp.Locate('TipoImp', I, []) then // do not localize
mtImp.Edit
else begin
mtImp.Insert;
mtImpTipoImp.Value := I;
mtImpNomeTipoImp.AsVariant := tTipoImp.Lookup('ID', I, 'Nome'); // do not localize
end;
mtImpQuant.Value := mtImpQuant.Value + QImp(I);
if UltimoImp(I) then begin
mtImpValor.Value := mtImpValor.Value + ValorImp(I) - DescT;
DescT := 0;
end else
if DescT>0.009 then begin
Desc := V2Casas(ValorImp(I) * PercDesc);
mtImpValor.Value := mtImpValor.Value + ValorImp(I) - Desc;
DescT := DescT - Desc;
end else
mtImpValor.Value := mtImpValor.Value + ValorImp(I);
ValorI := ValorI + (tImpTotal.Value - tImpDesconto.Value);
PagReg := PagReg + QImp(I);
mtImp.Post;
end;
end;
tImp.Next;
end;
finally
mtImp.EnableControls;
dsImp.DataSet := mtImp;
end;
if mtImp.RecordCount>1 then begin
mtImp.Insert;
mtImpTipoImp.Value := 11;
mtImpNomeTipoImp.Value := SncDMCaixa_TOTAL;
mtImpValor.Value := ValorI;
mtImpQuant.Value := PagReg;
mtImp.Post;
end;
if mtImp.RecordCount>0 then begin
mtImp.Insert;
mtImpTipoImp.Value := 12;
mtImpNomeTipoImp.Value := SncDMCaixa_PÁGINASDETECTADASAUTOMATICAMENTE;
mtImpQuant.Value := PagDet;
mtImp.Post;
end;
mtImp.First;
{$ENDIF}
mtTot.Open;
mtTot.EmptyTable;
mtTot.Append;
mtTotItem.Value := 1;
mtTotDescricao.Value := SncDMCaixa_Acessos;
mtTotFaturamento.Value := drf[drfSessao].rfFaturamento;
mtTotDebitado.Value := drf[drfSessao].rfDebitado;
mtTotPgDebito.Value := drf[drfSessao].rfPgDebito;
mtTotRecebido.Value := drf[drfSessao].rfRecebido;
mtTotTotal.Value := drf[drfSessao].rfRecebido + drf[drfSessao].rfPgDebito;
mtTot.Post;
mtTot.Open;
mtTot.Append;
mtTotItem.Value := 2;
mtTotDescricao.Value := SncDMCaixa_Vendas;
mtTotFaturamento.Value := drf[drfVendas].rfFaturamento;
mtTotDebitado.Value := drf[drfVendas].rfDebitado;
mtTotPgDebito.Value := drf[drfVendas].rfPgDebito;
mtTotRecebido.Value := drf[drfVendas].rfRecebido;
mtTotTotal.Value := drf[drfVendas].rfRecebido + drf[drfVendas].rfPgDebito;
mtTot.Post;
qItem := 3;
{$IFNDEF LOJA}
mtTot.Open;
mtTot.Append;
mtTotItem.Value := qItem;
mtTotDescricao.Value := SncDMCaixa_Impressões;
mtTotFaturamento.Value := drf[drfImp].rfFaturamento;
mtTotDebitado.Value := drf[drfImp].rfDebitado;
mtTotPgDebito.Value := drf[drfImp].rfPgDebito;
mtTotRecebido.Value := drf[drfImp].rfRecebido;
mtTotTotal.Value := drf[drfImp].rfRecebido + drf[drfImp].rfPgDebito;
mtTot.Post;
inc(qItem);
{$ENDIF}
mtTot.Open;
mtTot.Append;
mtTotItem.Value := qItem;
mtTotDescricao.Value := SncDMCaixa_TotalDoCaixa;
mtTotFaturamento.Value :=
drf[drfVendas].rfFaturamento +
drf[drfSessao].rfFaturamento +
drf[drfImp].rfFaturamento;
mtTotDebitado.Value :=
drf[drfVendas].rfDebitado +
drf[drfSessao].rfDebitado +
drf[drfImp].rfDebitado;
mtTotPgDebito.Value :=
drf[drfVendas].rfPgDebito +
drf[drfSessao].rfPgDebito +
drf[drfImp].rfPgDebito;
mtTotRecebido.Value :=
drf[drfVendas].rfRecebido +
drf[drfSessao].rfRecebido +
drf[drfImp].rfRecebido;
mtTotTotal.Value :=
drf[drfVendas].rfRecebido + drf[drfVendas].rfPgDebito +
drf[drfSessao].rfRecebido + drf[drfSessao].rfPgDebito +
drf[drfImp ].rfRecebido + drf[drfImp ].rfPgDebito;
TotFinal := mtTotTotal.Value;
mtTot.Post;
qSS.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qSS.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qSS.Active := True;
qCanc.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qCanc.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qCanc.Active := True;
qDesc.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qDesc.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qDesc.Active := True;
qManut.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qManut.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qManut.Active := True;
qVC.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qVC.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qVC.Active := True;
qGratis.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qGratis.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qGratis.Active := True;
qFatPre.Active := True;
qFatPos.Active := True;
mtFatPrePos.Append;
mtFatPrePosTipo.Value := SncDMCaixa_PósPago;
mtFatPrePosQuant.Value := qFatPosQuant.Value;
mtFatPrePosValor.Value := qFatPosValor.Value;
mtFatPrePos.Post;
tPacote.Active := True;
tTipoPass.Active := True;
qFatPre.First;
while not qFatPre.Eof do begin
Incluir := True;
case qFatPreTipo.Value of
tctAvulso : S := SncDMCaixa_CréditoDeTempoAvulso;
tctPacote :
if tPacote.FindKey([qFatPreIDPacPass.Value]) then
S := tPacoteDescr.Value else
S := SncDMCaixa_PacoteNãoExisteMais;
tctCartaoTempo :
if tTipoPass.FindKey([qFatPreIDPacPass.Value]) then
S := SncDMCaixa_CartãoDeTempo+tTipoPassNome.Value else
S := SncDMCaixa_CartãoDeTempoNãoExisteMais;
tctPassaporte :
if tTipoPass.FindKey([qFatPreIDPacPass.Value]) then
S := tTipoPassNome.Value else
S := SncDMCaixa_PassaporteNãoExisteMais;
else
Incluir := False;
end;
if Incluir then begin
mtFatPrePos.Append;
mtFatPrePosTipo.Value := S;
mtFatPrePosQuant.Value := qFatPreQuant.Value;
mtFatPrePosValor.Value := qFatPreValor.Value;
mtFatPrePos.Post;
end;
qFatPre.Next;
end;
TemSupSan := False;
if not aPeriodo then begin
mtTot.Append;
mtTotItem.Value := 5;
mtTotDescricao.Value := SncDMCaixa_SaldoInicial;
mtTotTotal.Value := tCaixaSaldoAnt.Value;
TotFinal := TotFinal + mtTotTotal.Value;
if mtTotTotal.Value>0.0009 then
TemSupSan := True;
mtTot.Post;
end;
mtTot.Append;
mtTotItem.Value := 6;
mtTotDescricao.Value := SncDMCaixa_DinheiroAdicionado;
mtTotTotal.AsVariant := qSS.Lookup('Tipo', trCaixaEnt, 'Total'); // do not localize
if mtTotTotal.IsNull then
mtTotTotal.Value := 0;
TotFinal := TotFinal + mtTotTotal.Value;
if mtTotTotal.Value>0.0009 then
TemSupSan := True;
mtTot.Post;
mtTot.Append;
mtTotItem.Value := 7;
mtTotDescricao.Value := SncDMCaixa_DinheiroRetirado;
mtTotTotal.AsVariant := qSS.Lookup('Tipo', trCaixaSai, 'Total'); // do not localize
if mtTotTotal.IsNull then
mtTotTotal.Value := 0;
TotFinal := TotFinal - mtTotTotal.Value;
if mtTotTotal.Value>0.0009 then
TemSupSan := True;
mtTot.Post;
if qCredCredito.Value>0.001 then begin
mtTot.Append;
mtTotItem.Value := 8;
mtTotDescricao.Value := SncDMCaixa_TrocoCreditado;
mtTotTotal.AsVariant := qCredCredito.Value; // do not localize
if mtTotTotal.IsNull then
mtTotTotal.Value := 0;
TotFinal := TotFinal + qCredCredito.Value;
mtTot.Post;
end;
mtTot.Append;
mtTotItem.Value := 9;
mtTotDescricao.Value := SncDMCaixa_SaldoFinal;
mtTotTotal.Value := TotFinal;
mtTot.Post;
if (not aPeriodo) and (not tCaixaAberto.Value) and gConfig.PedirSaldoF then begin
mtTot.Append;
mtTotItem.Value := 10;
mtTotDescricao.Value := SncDMCaixa_SaldoInformado;
mtTotTotal.Value := tCaixaSaldoF.Value;
if Abs(tCaixaQuebra.Value)>0.009 then begin
mtTot.Append;
mtTotItem.Value := 10;
mtTotDescricao.Value := SncDMCaixa_QuebraDeCaixa;
mtTotTotal.Value := tCaixaQuebra.Value;
end;
end;
Result := TotFinal;
{ mtTot.Append;
mtTotItem.Value := 9;
mtTotDescricao.Value := '';
mtTot.Post;}
if qDescQuant.Value>0 then begin
mtTot.Append;
mtTotItem.Value := 11;
mtTotDescricao.Value := qDescQuant.AsString + SncDMCaixa_DescontoS;
mtTotTotal.Value := qDescTotal.Value;
mtTot.Post;
end;
if qCancQuant.Value>0 then begin
mtTot.Append;
mtTotItem.Value := 12;
mtTotDescricao.Value := qCancQuant.AsString + SncDMCaixa_CancelamentoS;
mtTotTotal.Value := qCancTotal.Value;
mtTot.Post;
end;
end;
procedure TdmCaixa.qFatPosCalcFields(DataSet: TDataSet);
begin
qFatPosQuant.Value := 1;
end;
procedure TdmCaixa.qPagEspCalcFields(DataSet: TDataSet);
begin
if (qPagEspEspecie.Value=1) then begin
qPagEspTotalF.Value := qPagEspTotalValor.Value - TotalTroco;
qPagEspObs.Value := rsValorOriginal + '=' + CurrencyToStr(qPagEspTotalValor.Value) + ' - ' +
rsTroco + '=' + CurrencyToStr(TotalTroco);
end else
qPagEspTotalF.Value := qPagEspTotalValor.Value;
end;
procedure TdmCaixa.qRepTranCalcFields(DataSet: TDataSet);
const BoolStr : Array[Boolean] of String[3] = ('Não', 'Sim');
begin
if qRepTranTipo.Value in [trInicioSessao..trAjustaFid] then
qRepTranNomeTipo.Value := StTipoTransacao[qRepTranTipo.Value];
qRepTranCancFid.Value := BoolStr[qRepTranCancelado.Value] + ' / ' + BoolStr[qRepTranFidResgate.Value];
end;
procedure TdmCaixa.qVCCalcFields(DataSet: TDataSet);
begin
qVCTotFinal.Value := qVCTotal.Value - qVCDesconto.Value;
end;
procedure TdmCaixa.repCaixaBeforePrint(Sender: TfrxReportComponent);
begin
if SameText(Sender.Name, 'srTran') then // do not localize
Sender.Visible := FImpTran;
if SameText(Sender.Name, 'srImpressoes') then // do not localize
Sender.Visible := gConfig.cce(cceImpressoes);
if SameText(Sender.Name, 'srMovEstoque') then // do not localize
Sender.Visible := gConfig.cce(cceMovEstoque);
if SameText(Sender.Name, 'srResumoFin') then // do not localize
Sender.Visible := gConfig.cce(cceResumoFin);
if SameText(Sender.Name, 'srEstoqueAbaixoMin') then // do not localize
Sender.Visible := gConfig.cce(cceEstoqueAbaixoMin);
if SameText(Sender.Name, 'srPagEsp') then // do not localize
Sender.Visible := gConfig.cce(ccePagEsp);
if SameText(Sender.Name, 'Footer2') then // do not localize
Sender.Visible := (Trim(tCaixaObs.Value)>'');
end;
procedure TdmCaixa.tCaixaCalcFields(DataSet: TDataSet);
begin
tCaixaNomeLoja.Value := gConfig.EmailIdent;
end;
procedure TdmCaixa.tMECalcFields(DataSet: TDataSet);
begin
if tMENaoControlaEstoque.Value then
tMESaldoFinal.Value := 0 else
if tMECancelado.Value then
tMESaldoFinal.Value := tMEEstoqueAnt.Value
else
if tMEEntrada.Value then
tMESaldoFinal.Value := tMEEstoqueAnt.Value + tMEQuant.Value else
tMESaldoFinal.Value := tMEEstoqueAnt.Value - tMEQuant.Value;
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
主要实现:
设置数据库连接ADO方式,返回连接字符串
//------------------------------------------------------------------------------}
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1999-2001 Borland Software Corporation }
{ }
{*******************************************************}
unit EasyADOConEditor_Server;
{$R-}
interface
uses Windows, SysUtils, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Buttons, StdCtrls, DB, ADODB, ExtCtrls, Mask, DBClient,
MConnect, SConnect;
//插件导出函数
function ShowBplForm(var AParamList: TStrings): TForm; stdcall; exports ShowBplForm;
type
TStep = (spDefault, spConnSet, spMidasSet);
TfrmEasyADOConEditor = class(TForm)
btnNext: TButton;
nbkMain: TNotebook;
GroupBox1: TGroupBox;
csStyle: TRadioButton;
midasStyle: TRadioButton;
SourceofConnection: TGroupBox;
UseDataLinkFile: TRadioButton;
DataLinkFile: TComboBox;
Browse: TButton;
UseConnectionString: TRadioButton;
ConnectionString: TEdit;
Build: TButton;
GroupBox2: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
edtGUID: TEdit;
Label4: TLabel;
edtServerName: TEdit;
btnPrev: TButton;
Label5: TLabel;
edtIP: TEdit;
edtPort: TEdit;
ADOTest: TADOConnection;
scktTest: TSocketConnection;
procedure FormCreate(Sender: TObject);
procedure HelpButtonClick(Sender: TObject);
procedure BuildClick(Sender: TObject);
procedure BrowseClick(Sender: TObject);
procedure SourceButtonClick(Sender: TObject);
procedure btnNextClick(Sender: TObject);
procedure btnPrevClick(Sender: TObject);
procedure edtPortExit(Sender: TObject);
procedure edtIPKeyPress(Sender: TObject; var Key: Char);
procedure edtPortKeyPress(Sender: TObject; var Key: Char);
private
FStep: TStep;
FAppType,
FHost,
FPort,
FGUID,
FServerName,
FConnectString: string;
function GetDBStep: TStep;
procedure SetDBStep(const Value: TStep);
procedure ChangeNBK(ADBStep: TStep);
procedure LoadConnectString;
public
function Edit(ConnStr: WideString): WideString;
property DBStep: TStep read GetDBStep write SetDBStep;
end;
function EditConnectionString(Component: TComponent): Boolean;
var
frmEasyADOConEditor: TfrmEasyADOConEditor;
implementation
{$R *.dfm}
uses
TypInfo, OleDB, ADOInt, ActiveX, ComObj, untEasyUtilMethod, untEasyUtilConst,
ZLib, ZLibConst;
const
SConnectionString = 'ConnectionString'; { Do not localize }
resourcestring
SEditConnectionStringTitle = '%s%s%s %s';
//引出函数实现
function ShowBplForm(var AParamList: TStrings): TForm;
begin
Result := nil;
frmEasyADOConEditor := TfrmEasyADOConEditor.Create(Application);
frmEasyADOConEditor.ShowModal;
frmEasyADOConEditor.Free;
end;
function EditConnectionString(Component: TComponent): Boolean;
var
PropInfo: PPropInfo;
NewConnStr,
InitialConnStr: WideString;
begin
Result := False;
with TfrmEasyADOConEditor.Create(Application) do
try
Caption := Format(SEditConnectionStringTitle, [Component.Owner.Name, DotSep,
Component.Name, SConnectionString]);
PropInfo := GetPropInfo(Component.ClassInfo, SConnectionString);
InitialConnStr := GetStrProp(Component, PropInfo);
NewConnStr := Edit(InitialConnStr);
if NewConnStr <> InitialConnStr then
begin
SetStrProp(Component, PropInfo, NewConnStr);
Result := True;
end;
finally
Free;
end;
end;
{ TConnEditForm }
function TfrmEasyADOConEditor.Edit(ConnStr: WideString): WideString;
var
FileName: string;
begin
Result := ConnStr;
UseDataLinkFile.Checked := True;
if Pos(CT_FILENAME, ConnStr) = 1 then
begin
FileName := Copy(ConnStr, Length(CT_FILENAME)+1, MAX_PATH);
if ExtractFilePath(FileName) = (DataLinkDir + '\') then
DataLinkFile.Text := ExtractFileName(FileName) else
DataLinkFile.Text := FileName;
end else
begin
ConnectionString.Text := ConnStr;
UseConnectionString.Checked := True;
end;
SourceButtonClick(nil);
if ShowModal = mrOk then
if UseConnectionString.Checked then
Result := ConnectionString.Text
else if DataLinkFile.Text <> '' then
begin
if ExtractFilePath(DataLinkFile.Text) = '' then
Result := CT_FILENAME + DataLinkDir + '\' +DataLinkFile.Text else
Result := CT_FILENAME + DataLinkFile.Text
end
else
Result := '';
end;
{ Event Handlers }
procedure TfrmEasyADOConEditor.FormCreate(Sender: TObject);
begin
HelpContext := 27270; //hcDADOConnEdit;
GetDataLinkFiles(DataLinkFile.Items);
FStep := spDefault;
ChangeNBK(DBStep);
csStyle.Checked := True;
nbkMain.PageIndex := 1;
LoadConnectString;
DBStep := spConnSet;
ConnectionString.Text := FConnectString;
end;
procedure TfrmEasyADOConEditor.HelpButtonClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TfrmEasyADOConEditor.BrowseClick(Sender: TObject);
begin
DataLinkFile.Text := PromptDataLinkFile(Handle, DataLinkFile.Text);
end;
procedure TfrmEasyADOConEditor.BuildClick(Sender: TObject);
begin
ConnectionString.Text := PromptDataSource(Handle, ConnectionString.Text);
end;
procedure TfrmEasyADOConEditor.SourceButtonClick(Sender: TObject);
const
EnabledColor: array[Boolean] of TColor = (clBtnFace, clWindow);
begin
DataLinkFile.Enabled := UseDataLinkFile.Checked;
DataLinkFile.Color := EnabledColor[DataLinkFile.Enabled];
Browse.Enabled := DataLinkFile.Enabled;
ConnectionString.Enabled := UseConnectionString.Checked;
ConnectionString.Color := EnabledColor[ConnectionString.Enabled];
Build.Enabled := ConnectionString.Enabled;
if DataLinkFile.Enabled then
ActiveControl := DataLinkFile else
ActiveControl := ConnectionString;
end;
function TfrmEasyADOConEditor.GetDBStep: TStep;
begin
Result := FStep;
end;
procedure TfrmEasyADOConEditor.SetDBStep(const Value: TStep);
begin
if FStep <> Value then
begin
FStep := Value;
ChangeNBK(Value);
end;
end;
procedure TfrmEasyADOConEditor.ChangeNBK(ADBStep: TStep);
begin
case ADBStep of
spDefault:
begin
nbkMain.PageIndex := 0;
btnNext.Caption := '下一步';
btnPrev.Visible := False;
end;
spConnSet:
begin
nbkMain.PageIndex := 1;
btnNext.Caption := '确定';
btnPrev.Caption := '上一步';
btnPrev.Visible := False;
end;
spMidasSet:
begin
nbkMain.PageIndex := 2;
btnNext.Caption := '确定';
btnPrev.Caption := '上一步';
btnPrev.Visible := False;
end;
end;
end;
procedure TfrmEasyADOConEditor.btnNextClick(Sender: TObject);
var
AList: TStrings;
ATmpMMStream: TMemoryStream;
AFile: string;
begin
case DBStep of
spDefault:
begin
if csStyle.Checked then
begin
DBStep := spConnSet;
ConnectionString.Text := FConnectString;
end else
if midasStyle.Checked then
begin
DBStep := spMidasSet;
edtIP.Text := FHost;
edtPort.Text := FPort;
edtGUID.Text := FGUID;
edtServerName.Text := FServerName;
end;
end;
spConnSet, spMidasSet:
begin
AList := TStringList.Create;
ATmpMMStream := TMemoryStream.Create;
//二层CS 三层CAS
if csStyle.Checked then
begin
if Trim(ConnectionString.Text) = '' then
Exit;
AList.Add('APPTYPE=CS');
AList.Add('CONNECTSTRING=' + ConnectionString.Text);
end else
if midasStyle.Checked then
begin
if (Trim(edtIP.Text) = '') or (Trim(edtPort.Text) = '')
or (Trim(edtServerName.Text) = '') then Exit;
AList.Add('APPTYPE=CAS');
AList.Add('HOST=' + edtIP.Text);
AList.Add('PORT=' + edtPort.Text);
AList.Add('IGUID=' + edtGUID.Text);
AList.Add('SNAME=' + edtServerName.Text);
end;
try
if csStyle.Checked then
begin
ADOTest.LoginPrompt := False;
ADOTest.ConnectionString := ConnectionString.Text;
try
ADOTest.Connected := True;
except on e:Exception do
Application.MessageBox(PChar(e.Message), EASY_SYS_HINT,
MB_OK + MB_ICONINFORMATION);
end;
end else
if midasStyle.Checked then
begin
with scktTest do
begin
Host := edtIP.Text;
Port := StrToInt(edtPort.Text);
InterceptGUID := edtGUID.Text;
ServerName := edtServerName.Text;
end;
try
scktTest.Connected;
except on e:Exception do
Application.MessageBox(PChar(e.Message), EASY_SYS_HINT,
MB_OK + MB_ICONINFORMATION);
end;
end;
AFile := ExtractFilePath(Application.ExeName) + 'ConnectString.dll';
AList.SaveToFile(AFile);
CompressFile_Easy(AFile, ATmpMMStream, clMax);
ATmpMMStream.SaveToFile(AFile);
Application.MessageBox(EASY_DBCONNECT_SUCCESS, EASY_SYS_HINT,
MB_OK + MB_ICONINFORMATION);
finally
AList.Free;
ATmpMMStream.Free;
end;
Close;
end;
end;
end;
procedure TfrmEasyADOConEditor.btnPrevClick(Sender: TObject);
begin
case DBStep of
spConnSet, spMidasSet:
begin
DBStep := spDefault;
end;
end;
end;
procedure TfrmEasyADOConEditor.LoadConnectString;
var
AList: TStrings;
ATmpMMStream,
ADestMMStream: TMemoryStream;
AFile: string;
begin
AFile := ExtractFilePath(Application.ExeName) + 'ConnectString.dll';
AList := TStringList.Create;
if FileExists(AFile) then
begin
ATmpMMStream := TMemoryStream.Create;
ADestMMStream := TMemoryStream.Create;
try
ATmpMMStream.LoadFromFile(AFile);
DeCompressFile_Easy(ATmpMMStream, ADestMMStream, AFile);
AList.LoadFromStream(ADestMMStream);
FAppType := AList.Values['APPTYPE'];
FHost := AList.Values['HOST'];
FPort := AList.Values['PORT'];
FGUID := AList.Values['IGUID'];
FServerName := AList.Values['SNAME'];
FConnectString := AList.Values['CONNECTSTRING'];
finally
ATmpMMStream.Free;
ADestMMStream.Free;
end;
end;
AList.Free;
if FAppType = 'CAS' then
midasStyle.Checked := True
else
csStyle.Checked := True;
end;
procedure TfrmEasyADOConEditor.edtPortExit(Sender: TObject);
var
APort: Integer;
begin
if TryStrToInt(edtPort.Text, APort) then
begin
if (APort > 65535) or (APort < 211) then
edtPort.Text := '211';
end;
end;
procedure TfrmEasyADOConEditor.edtIPKeyPress(Sender: TObject;
var Key: Char);
begin
if not (Key in ['0'..'9', '.']) then
Key := #0;
end;
procedure TfrmEasyADOConEditor.edtPortKeyPress(Sender: TObject;
var Key: Char);
begin
if not (Key in ['0'..'9']) then
Key := #0;
end;
initialization
CoInitialize(nil);
finalization
CoUninitialize;
end.
|
unit CPRSLibTestCases;
interface
uses
TestFramework, ORFn, SysUtils, Classes, Types;
type
TORFnTestCase = class(TTestCase)
published
// Test Date/Time functions
procedure TestDateTimeToFMDateTime;
procedure TestFMDateTimeOffsetBy;
procedure TestFMDateTimeToDateTime;
procedure TestFormatFMDateTime;
procedure TestFormatFMDateTimeStr;
procedure TestIsFMDateTime;
procedure TestMakeFMDateTime;
procedure TestSetListFMDateTime;
// Test Numeric functions
procedure TestHigherOf;
procedure TestLowerOf;
procedure TestRectContains;
procedure TestStrToFloatDef;
end;
implementation
{ TORFnTestCase }
// ** Test Date/Time Functions **
procedure TORFnTestCase.TestDateTimeToFMDateTime;
var
TestDT: TDateTime;
begin
// use 07/20/1969@20:17:39 - Date/Time (UTC) of Apollo 11 Lunar landing
TestDT := EncodeDate(1969, 7, 20) + EncodeTime(20, 17, 39, 0);
Check(FloatToStr(DateTimeToFMDateTime(TestDT)) = '2690720.201739', 'DateTimeToFMDateTime Failed!');
end;
procedure TORFnTestCase.TestFMDateTimeOffsetBy;
var
TestFMDT: TFMDateTime;
begin
TestFMDT := StrToFloat('2690725.201739');
Check(FMDateTimeOffsetBy(StrToFloat('2690720.201739'), 5) = TestFMDT, 'FMDateTimeOffsetBy Failed!');
TestFMDT := StrToFloat('2690629.201739');
Check(FMDateTimeOffsetBy(StrToFloat('2690720.201739'), -21) = TestFMDT, 'FMDateTimeOffsetBy (Negative Offset) Failed!');
end;
procedure TORFnTestCase.TestFMDateTimeToDateTime;
var
TestDT: TDateTime;
begin
TestDT := EncodeDate(1969, 7, 20) + EncodeTime(20, 17, 39, 0);
Check(TestDT = FMDateTimeToDateTime(StrToFloat('2690720.201739')), 'FMDateTimeToDateTime Failed!');
end;
procedure TORFnTestCase.TestFormatFMDateTime;
var
TestFMDT: TFMDateTime;
ExpectedDTString, ActualDTString: String;
begin
TestFMDT := StrToFloat('2690720.201739');
ExpectedDTString := '07/20/1969@20:17:39';
ActualDTString := FormatFMDateTime('mm/dd/yyyy@hh:nn:ss', TestFMDT);
Check(ExpectedDTString = ActualDTString, 'FormatFMDateTime Failed! Expected: ' + ExpectedDTString + ' Actual: ' + ActualDTString);
ExpectedDTString := '19690720.201739';
ActualDTString := FormatFMDateTime('yyyymmdd.hhnnss', TestFMDT);
Check(ExpectedDTString = ActualDTString, 'FormatFMDateTime Failed! Expected: ' + ExpectedDTString + ' Actual: ' + ActualDTString);
ExpectedDTString := '20 Jul 69 20:17';
ActualDTString := FormatFMDateTime('dd mmm yy hh:nn', TestFMDT);
Check(ExpectedDTString = ActualDTString, 'FormatFMDateTime Failed! Expected: ' + ExpectedDTString + ' Actual: ' + ActualDTString);
ExpectedDTString := 'July 20, 1969 20:17';
ActualDTString := FormatFMDateTime('mmmm dd, yyyy hh:nn', TestFMDT);
Check(ExpectedDTString = ActualDTString, 'FormatFMDateTime Failed! Expected: ' + ExpectedDTString + ' Actual: ' + ActualDTString);
end;
procedure TORFnTestCase.TestFormatFMDateTimeStr;
var
TestFMDT: String;
ExpectedDTString, ActualDTString: String;
begin
TestFMDT := '2690720.201739';
ExpectedDTString := '07/20/1969@20:17:39';
ActualDTString := FormatFMDateTimeStr('mm/dd/yyyy@hh:nn:ss', TestFMDT);
Check(ExpectedDTString = ActualDTString, 'FormatFMDateTimeStr Failed! Expected: ' + ExpectedDTString + ' Actual: ' + ActualDTString);
ExpectedDTString := '19690720.201739';
ActualDTString := FormatFMDateTimeStr('yyyymmdd.hhnnss', TestFMDT);
Check(ExpectedDTString = ActualDTString, 'FormatFMDateTime Failed! Expected: ' + ExpectedDTString + ' Actual: ' + ActualDTString);
ExpectedDTString := '20 Jul 69 20:17';
ActualDTString := FormatFMDateTimeStr('dd mmm yy hh:nn', TestFMDT);
Check(ExpectedDTString = ActualDTString, 'FormatFMDateTimeStr Failed! Expected: ' + ExpectedDTString + ' Actual: ' + ActualDTString);
ExpectedDTString := 'July 20, 1969 20:17';
ActualDTString := FormatFMDateTimeStr('mmmm dd, yyyy hh:nn', TestFMDT);
Check(ExpectedDTString = ActualDTString, 'FormatFMDateTimeStr Failed! Expected: ' + ExpectedDTString + ' Actual: ' + ActualDTString);
end;
procedure TORFnTestCase.TestHigherOf;
begin
Check(HigherOf(1024, 2048) = 2048, 'HigherOf(1024, 2048) failed.');
CheckFalse(HigherOf(1024, 2048) = 1024, 'HigherOf(1024, 2048) failed.');
end;
procedure TORFnTestCase.TestIsFMDateTime;
var
TestFMDT: String;
begin
// Test Case where isFMDateTime returns True
TestFMDT := '2690720.201739';
Check(IsFMDateTime(TestFMDT) = True, 'isFMDateTime failed for ' + TestFMDT);
// Test Case where isFMDateTime returns False
TestFMDT := '19690720.201739';
Check(IsFMDateTime(TestFMDT) = False, 'isFMDateTime failed for ' + TestFMDT);
end;
procedure TORFnTestCase.TestLowerOf;
begin
Check(LowerOf(1024, 2048) = 1024, 'LowerOf(1024, 2048) failed.');
CheckFalse(LowerOf(1024, 2048) = 2048, 'LowerOf(1024, 2048) failed.');
end;
procedure TORFnTestCase.TestMakeFMDateTime;
var
TestFMDT: String;
MadeFMDT: Extended;
begin
TestFMDT := '2690720.201739';
MadeFMDT := MakeFMDateTime(TestFMDT);
Check(TestFMDT = FloatToStr(MadeFMDT), 'MakeFMDateTime Failed. Expected: ' + TestFMDT + ' Actual: ' + FloatToStr(MadeFMDT));
TestFMDT := '19690720.201739';
MadeFMDT := MakeFMDateTime(TestFMDT);
Check(-1 = MadeFMDT, 'MakeFMDateTime Failed. Expected: -1 Actual: ' + FloatToStr(MadeFMDT));
end;
procedure TORFnTestCase.TestRectContains;
var
ARect: TRect;
APoint: TPoint;
begin
ARect := Rect(0, 0, 100, 100);
APoint := Point(50, 50);
Check(RectContains(ARect, APoint) = True, 'RectContains([0, 0, 100, 100], [50, 50]) Failed!');
APoint := Point(50, 101);
Check(RectContains(ARect, APoint) = False, 'RectContains([0, 0, 100, 100], [50, 101]) Failed!');
end;
procedure TORFnTestCase.TestSetListFMDateTime;
var
AList: TStringList;
begin
//Load AList with strings analogous to RPC Results
AList := TStringList.Create;
AList.Add('917^3101012.142241^p^ANTICOAG^Consult^^ANTICOAG Cons^14520207^C');
AList.Add('903^3100813.144108^a^NUTRITION ASSESSMENT^Consult^^NUTRITION ASSESSMENT Cons^14519894^C');
AList.Add('902^20100713.124501^c^NUTRITION ASSESSMENT^Consult^*^NUTRITION ASSESSMENT Cons^14519811^C');
AList.Add('899^3100707.093843^p^CARDIOLOGY^Consult^^CARDIOLOGY Cons^14519751^C');
AList.Add('900^31007^p^CARDIOLOGY^Consult^^CARDIOLOGY Cons^14519752^C');
SetListFMDateTime('mm/dd/yyyy@hh:nn:ss', AList, '^', 2);
Check(Piece(AList[0], '^', 2) = '10/12/2010@14:22:41', 'SetListFMDateTime failed: ' + Piece(AList[0], '^', 2));
Check(Piece(AList[1], '^', 2) = '08/13/2010@14:41:08', 'SetListFMDateTime failed: ' + Piece(AList[1], '^', 2));
Check(Piece(AList[2], '^', 2) = '', 'HL7 Date/Time caused: ' + Piece(AList[2], '^', 2));
Check(Piece(AList[3], '^', 2) = '07/07/2010@09:38:43', 'SetListFMDateTime failed: ' + Piece(AList[3], '^', 2));
Check(Piece(AList[4], '^', 2) = '', 'Imprecise Date/Time caused: ' + Piece(AList[4], '^', 2));
AList.Clear;
AList.Add('917^3101012.142241^p^ANTICOAG^Consult^^ANTICOAG Cons^14520207^C');
AList.Add('903^3100813.144108^a^NUTRITION ASSESSMENT^Consult^^NUTRITION ASSESSMENT Cons^14519894^C');
AList.Add('902^20100713.124501^c^NUTRITION ASSESSMENT^Consult^*^NUTRITION ASSESSMENT Cons^14519811^C');
AList.Add('899^3100707.093843^p^CARDIOLOGY^Consult^^CARDIOLOGY Cons^14519751^C');
AList.Add('900^31007^p^CARDIOLOGY^Consult^^CARDIOLOGY Cons^14519752^C');
SetListFMDateTime('mm/dd/yyyy@hh:nn:ss', AList, '^', 2, True);
Check(Piece(AList[0], '^', 2) = '10/12/2010@14:22:41', 'SetListFMDateTime failed: ' + Piece(AList[0], '^', 2));
Check(Piece(AList[1], '^', 2) = '08/13/2010@14:41:08', 'SetListFMDateTime failed: ' + Piece(AList[1], '^', 2));
Check(Piece(AList[2], '^', 2) = '20100713.124501', 'HL7 Date/Time caused: ' + Piece(AList[2], '^', 2));
Check(Piece(AList[3], '^', 2) = '07/07/2010@09:38:43', 'SetListFMDateTime failed: ' + Piece(AList[3], '^', 2));
Check(Piece(AList[4], '^', 2) = '31007', 'Imprecise Date/Time caused: ' + Piece(AList[4], '^', 2));
end;
procedure TORFnTestCase.TestStrToFloatDef;
begin
Check(StrToFloatDef('3.1416', Pi) = 3.1416, 'StrToFloatDef Failed!');
Check(StrToFloatDef('0031416', Pi) = 31416, 'StrToFloatDef Failed!');
Check(StrToFloatDef('NotANumber', Pi) = Pi, 'StrToFloatDef Failed!');
end;
initialization
TestFramework.RegisterTest(TORFnTestCase.Suite);
end.
|
unit FC.Trade.FilterDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogOKCancel_B, ActnList, StdCtrls, ExtendControls, ExtCtrls, JvExControls,
JvComponent, JvEditorCommon, JvEditor, JvHLEditor, RecentlyList, Menus, ActnPopup, Buttons,
PlatformDefaultStyleActnCtrls;
type
TFilterEditorHighlighter = class;
TfmFilterDialog = class(TfmDialogOkCancel_B)
mmAvailableFields: TMemo;
Label1: TLabel;
mmFilter: TJvHLEditor;
rlFilters: TRecentlyList;
Panel1: TPanel;
buRecentlyFilters: TSpeedButton;
pmRecentlyFilters: TPopupActionBar;
procedure rlFiltersRecentlyMenuClick(Sender: TRecentlyList; RecentlyValue: string);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure buRecentlyFiltersClick(Sender: TObject);
procedure mmFilterCompletionIdentifier(Sender: TObject; var Cancel: Boolean);
procedure mmFilterCompletionDrawItem(Control: TWinControl; Index: Integer; Rect: TRect;
State: TOwnerDrawState);
procedure mmFilterCompletionMeasureItem(Control: TWinControl; Index: Integer;
var Height: Integer);
procedure FormShow(Sender: TObject);
private
FHilighter: TFilterEditorHighlighter;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure SetFields(aStrings: TStrings);
end;
TFilterEditorHighlighter = class(TJvEditorHighlighter)
private
FFields: TStrings;
FFunctions: TStrings;
protected
procedure GetAttr(Editor: TJvHLEditor; Lines: TStrings; Line, ColBeg, ColEnd: Integer;
LongToken: TLongTokenType; var LineAttrs: TLineAttrs); override;
procedure ScanLongTokens(Editor: TJvHLEditor; Lines: TStrings; Line: Integer;
var FLong: TLongTokenType); override;
function GetRescanLongKeys(Editor: TJvHLEditor; Action: TModifiedAction;
ACaretX, ACaretY: Integer; const Text: string): Boolean; override;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
function IsFunction(const S: string):boolean;
function IsField(const S: string):boolean;
function IsKeyword(const S: string):boolean;
property Fields: TStrings read FFields;
property Functions: TStrings read FFunctions;
end;
implementation
uses BaseUtils,MemoryDS,JvJCLUtils,Math,Application.Definitions;
{$R *.dfm}
const
FilterReservedWords: array [0..5] of string = ('and','or','xor','div','mod','like');
FilterBuiltInFunctions: array [0..10] of string = ('round','trunc','int','frac','sin','cos','tan','atan','ln','exp','sign');
{ TFilterEditorHighlighter }
constructor TFilterEditorHighlighter.Create(aOwner: TComponent);
var
i: integer;
begin
inherited;
FFields:=TStringList.Create;
FFunctions:=TStringList.Create;
for I := 0 to High(FilterBuiltInFunctions) - 1 do
FFunctions.Add(FilterBuiltInFunctions[i]);
end;
destructor TFilterEditorHighlighter.Destroy;
begin
FreeAndNil(FFields);
FreeAndNil(FFunctions);
inherited;
end;
procedure TFilterEditorHighlighter.GetAttr(Editor: TJvHLEditor; Lines: TStrings; Line, ColBeg,
ColEnd: Integer; LongToken: TLongTokenType; var LineAttrs: TLineAttrs);
var
ps0,ps1, ps2 : pchar;
PrevSymbol: char;
function IsCharBelongsID(aChar: char): boolean;
begin
result:=IsCharAlphaNumeric(aChar) or (aChar='_');
end;
procedure OnToken(const aX1,aX2: pchar);
var
s: string;
j: Integer;
aColor: TJvSymbolColor;
begin
if aX2<=aX1 then
exit;
SetLength(s, aX2-aX1);
StrLCopy(pchar(s), aX1,aX2-aX1);
aColor:=nil;
if (aColor=nil) and IsRealNumericString(s) then
aColor:=Editor.Colors.Number
else if (aColor=nil) and CharInSet(s[1],['''','"']) then
aColor:=Editor.Colors.Strings;
if aColor=nil then
if IsKeyword(s) then
aColor:=Editor.Colors.Reserved;
if aColor=nil then
if IsFunction(s) then
aColor:=Editor.Colors.FunctionCall;
if aColor=nil then
if IsField(s) then
aColor:=Editor.Colors.Identifier;
if aColor<>nil then
begin
for j:= aX1-ps0 to aX2-ps0 do
begin
LineAttrs[j].FC:=aColor.ForeColor;
LineAttrs[j].BC:=aColor.BackColor;
LineAttrs[j].Style:=aColor.Style;
end;
end;
end;
begin
ps0:=pchar(Lines[Line]);
ps1:=ps0;
ps2:=ps1;
PrevSymbol:='a';
while ps2^<>#0 do
begin
if not IsCharBelongsID(ps2^) or not IsCharBelongsID(PrevSymbol)then
begin
OnToken(ps1,ps2);
ps1:=ps2;
end;
//Одинарная строка
if ps2^='''' then
begin
inc(ps2);
while (ps2^<>'''') and (ps2^<>#0) do
inc(ps2);
if (ps2^='''') then inc(ps2);
OnToken(ps1,ps2);
ps1:=ps2;
end
//Двойная строка
else if ps2^='"' then
begin
inc(ps2);
while (ps2^<>'"') and (ps2^<>#0) do
inc(ps2);
if (ps2^='"') then inc(ps2);
OnToken(ps1,ps2);
ps1:=ps2;
end;
if (ps2^=#0) then break;
PrevSymbol:=ps2^;
inc(ps2);
end;
OnToken(ps1,ps2);
end;
function TFilterEditorHighlighter.GetRescanLongKeys(Editor: TJvHLEditor; Action: TModifiedAction;
ACaretX, ACaretY: Integer; const Text: string): Boolean;
begin
result:=true;
end;
function TFilterEditorHighlighter.IsField(const S: string): boolean;
begin
result:=FFields.IndexOf(s)<>-1;
end;
function TFilterEditorHighlighter.IsFunction(const S: string): boolean;
begin
result:=FFunctions.IndexOf(s)<>-1;
end;
function TFilterEditorHighlighter.IsKeyword(const S: string): boolean;
var
i: integer;
begin
result:=false;
for I := 0 to High(FilterReservedWords) - 1 do
if SameText(s,FilterReservedWords[i]) then
begin
result:=true;
break;
end;
end;
procedure TFilterEditorHighlighter.ScanLongTokens(Editor: TJvHLEditor; Lines: TStrings;
Line: Integer; var FLong: TLongTokenType);
begin
inherited;
end;
{ TfmFilterDialog }
procedure TfmFilterDialog.buRecentlyFiltersClick(Sender: TObject);
var
aP: TPoint;
begin
inherited;
aP:=buRecentlyFilters.ClientToScreen(Point(buRecentlyFilters.BoundsRect.Left,buRecentlyFilters.BoundsRect.Bottom));
pmRecentlyFilters.Popup(aP.X,aP.Y);
end;
constructor TfmFilterDialog.Create(aOwner: TComponent);
begin
inherited;
FHilighter:=TFilterEditorHighlighter.Create(mmFilter);
mmFilter.Highlighter:=hlSyntaxHighlighter;
mmFilter.SyntaxHighlighter:=FHilighter;
rlFilters.RegistryKey:=Workspace.MainRegistryKey+'\'+Self.ClassName+'\RecentlyFilters';
buRecentlyFilters.Enabled:=not rlFilters.IsEmpty;
end;
destructor TfmFilterDialog.Destroy;
begin
inherited;
end;
procedure TfmFilterDialog.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
if ModalResult=mrOk then
rlFilters.AddRecently(Trim(mmFilter.Lines.Text));
end;
procedure TfmFilterDialog.FormShow(Sender: TObject);
begin
inherited;
mmFilter.SetFocus;
end;
procedure TfmFilterDialog.mmFilterCompletionDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
const
FuncTitle = 'function';
FieldTitle = 'field';
var
aRect: TRect;
aCanvas : TCanvas;
s: string;
aItem: string;
begin
inherited;
aItem:=TListBox(Control).Items[Index];
aCanvas:=TListBox(Control).Canvas;
aCanvas.FillRect(Rect);
inc(Rect.Left,4);
dec(Rect.Right,4);
aRect:=Rect;
aRect.Right:=max(aCanvas.TextWidth(FuncTitle),aCanvas.TextWidth(FieldTitle));
s:='';
if FHilighter.IsField(aItem) then
s:=FieldTitle
else if FHilighter.IsFunction(aItem) then
s:=FuncTitle;
if not (odSelected in State) then
begin
if FHilighter.IsField(aItem) then
aCanvas.Font.Color:=clGreen
else if FHilighter.IsFunction(aItem) then
aCanvas.Font.Color:=clBlue
else
aCanvas.Font.Color:=clWindowText;
end
else begin
aCanvas.Font.Color:=clHighlightText
end;
aCanvas.TextOut(aRect.Left,aRect.Top,s);
//----------
aRect.Left:=aRect.Right+8;
aRect.Right:=Rect.Right;
if not (odSelected in State) then
aCanvas.Font.Color:=clWindowText
else
aCanvas.Font.Color:=clHighlightText;
aCanvas.TextOut(aRect.Left,aRect.Top,aItem);
end;
procedure TfmFilterDialog.mmFilterCompletionIdentifier(Sender: TObject; var Cancel: Boolean);
var
s: string;
i: integer;
begin
if mmFilter.Lines.Count=0 then
Cancel:=true
else begin
S := Trim(GetWordOnPos(mmFilter.Lines[mmFilter.CaretY], mmFilter.CaretX));
if s='' then
Cancel:=true
else begin
mmFilter.Completion.Identifiers.Clear;
for i := 0 to FHilighter.FFields.Count - 1 do
if StrStartsWithI(FHilighter.Fields[i],s) then
mmFilter.Completion.Identifiers.Add(FHilighter.Fields[i]);
for i := 0 to FHilighter.Functions.Count - 1 do
if StrStartsWithI(FHilighter.Functions[i],s) then
mmFilter.Completion.Identifiers.Add(FHilighter.Functions[i]);
end;
end;
end;
procedure TfmFilterDialog.mmFilterCompletionMeasureItem(Control: TWinControl; Index: Integer;
var Height: Integer);
begin
inherited;
//
end;
procedure TfmFilterDialog.rlFiltersRecentlyMenuClick(Sender: TRecentlyList; RecentlyValue: string);
begin
inherited;
mmFilter.Lines.Text:=RecentlyValue;
end;
procedure TfmFilterDialog.SetFields(aStrings: TStrings);
var
i: integer;
begin
FHilighter.FFields.Assign(aStrings);
mmFilter.Completion.Identifiers.Assign(aStrings);
for i := 0 to FHilighter.FFields.Count - 1 do
mmAvailableFields.Text:=mmAvailableFields.Text+FHilighter.FFields[i]+' ';
end;
end.
|
unit IdIcmpClient;
interface
uses
Classes,
IdGlobal,
IdRawBase,
IdRawClient,
IdStack,
IdStackConsts,
SysUtils;
const
DEF_PACKET_SIZE = 32;
MAX_PACKET_SIZE = 1024;
ICMP_MIN = 8;
const
iDEFAULTPACKETSIZE = 128;
iDEFAULTREPLYBUFSIZE = 1024;
const
Id_TIDICMP_ReceiveTimeout = 5000;
type
TReplyStatusTypes = (rsEcho, rsError, rsTimeOut, rsErrorUnreachable,
rsErrorTTLExceeded);
TReplyStatus = record
BytesReceived: integer;
FromIpAddress: string;
MsgType: byte;
SequenceId: word;
MsRoundTripTime: longword;
TimeToLive: byte;
ReplyStatusType: TReplyStatusTypes;
end;
TCharBuf = array[1..MAX_PACKET_SIZE] of char;
TICMPDataBuffer = array[1..iDEFAULTPACKETSIZE] of byte;
TOnReplyEvent = procedure(ASender: TComponent; const AReplyStatus:
TReplyStatus) of object;
TIdIcmpClient = class(TIdRawClient)
protected
bufReceive: TCharBuf;
bufIcmp: TCharBuf;
wSeqNo: word;
iDataSize: integer;
FReplyStatus: TReplyStatus;
FOnReply: TOnReplyEvent;
function CalcCheckSum: word;
procedure DecodeResponse(BytesRead: integer; var AReplyStatus:
TReplyStatus);
procedure DoReply(const AReplyStatus: TReplyStatus);
procedure GetEchoReply;
procedure PrepareEchoRequest;
procedure SendEchoRequest;
public
constructor Create(AOwner: TComponent); override;
procedure Ping;
function Receive(ATimeOut: Integer): TReplyStatus;
property ReplyStatus: TReplyStatus read FReplyStatus;
published
property ReceiveTimeout default Id_TIDICMP_ReceiveTimeout;
property Host;
property Port;
property Protocol default Id_IPPROTO_ICMP;
property OnReply: TOnReplyEvent read FOnReply write FOnReply;
end;
implementation
uses
IdException
, IdResourceStrings, IdRawHeaders;
constructor TIdIcmpClient.Create(AOwner: TComponent);
begin
inherited;
FProtocol := Id_IPPROTO_ICMP;
wSeqNo := 0;
FReceiveTimeOut := Id_TIDICMP_ReceiveTimeout;
end;
function TIdIcmpClient.CalcCheckSum: word;
type
PWordArray = ^TWordArray;
TWordArray = array[1..512] of word;
var
pwa: PWordarray;
dwChecksum: longword;
i, icWords, iRemainder: integer;
begin
icWords := iDataSize div 2;
iRemainder := iDatasize mod 2;
pwa := PWordArray(@bufIcmp);
dwChecksum := 0;
for i := 1 to icWords do
begin
dwChecksum := dwChecksum + pwa^[i];
end;
if (iRemainder <> 0) then
begin
dwChecksum := dwChecksum + byte(bufIcmp[iDataSize]);
end;
dwCheckSum := (dwCheckSum shr 16) + (dwCheckSum and $FFFF);
dwCheckSum := dwCheckSum + (dwCheckSum shr 16);
Result := word(not dwChecksum);
end;
procedure TIdIcmpClient.PrepareEchoRequest;
var
pih: PIdIcmpHdr;
i: integer;
begin
iDataSize := DEF_PACKET_SIZE + sizeof(TIdIcmpHdr);
FillChar(bufIcmp, sizeof(bufIcmp), 0);
pih := PIdIcmpHdr(@bufIcmp);
with pih^ do
begin
icmp_type := Id_ICMP_ECHO;
icmp_code := 0;
icmp_hun.echo.id := word(CurrentProcessId);
icmp_hun.echo.seq := wSeqNo;
icmp_dun.ts.otime := GetTickcount;
i := Succ(sizeof(TIdIcmpHdr));
while (i <= iDataSize) do
begin
bufIcmp[i] := 'E';
Inc(i);
end;
icmp_sum := CalcCheckSum;
end;
Inc(wSeqNo);
end;
procedure TIdIcmpClient.SendEchoRequest;
begin
Send(Host, Port, bufIcmp, iDataSize);
end;
procedure TIdIcmpClient.DecodeResponse(BytesRead: integer; var AReplyStatus:
TReplyStatus);
var
pip: PIdIPHdr;
picmp: PIdICMPHdr;
iIpHeaderLen: integer;
begin
if BytesRead = 0 then
begin
AReplyStatus.BytesReceived := 0;
AReplyStatus.FromIpAddress := '0.0.0.0';
AReplyStatus.MsgType := 0;
AReplyStatus.SequenceId := wSeqNo;
AReplyStatus.TimeToLive := 0;
AReplyStatus.ReplyStatusType := rsTimeOut;
end
else
begin
AReplyStatus.ReplyStatusType := rsError;
pip := PIdIPHdr(@bufReceive);
iIpHeaderLen := (pip^.ip_verlen and $0F) * 4;
if (BytesRead < iIpHeaderLen + ICMP_MIN) then
begin
raise EIdIcmpException.Create(RSICMPNotEnoughtBytes);
end;
picmp := PIdICMPHdr(@bufReceive[iIpHeaderLen + 1]);
{$IFDEF LINUX}
{$ENDIF}
case picmp^.icmp_type of
Id_ICMP_ECHOREPLY, Id_ICMP_ECHO:
AReplyStatus.ReplyStatusType := rsEcho;
Id_ICMP_UNREACH:
AReplyStatus.ReplyStatusType := rsErrorUnreachable;
Id_ICMP_TIMXCEED:
AReplyStatus.ReplyStatusType := rsErrorTTLExceeded;
else
raise EIdICMPException.Create(RSICMPNonEchoResponse);
end;
with AReplyStatus do
begin
BytesReceived := BytesRead;
FromIpAddress := GStack.TInAddrToString(pip^.ip_src);
MsgType := picmp^.icmp_type;
SequenceId := picmp^.icmp_hun.echo.seq;
MsRoundTripTime := GetTickCount - picmp^.icmp_dun.ts.otime;
TimeToLive := pip^.ip_ttl;
end;
end;
DoReply(AReplyStatus);
end;
procedure TIdIcmpClient.GetEchoReply;
begin
FReplyStatus := Receive(FReceiveTimeout);
end;
procedure TIdIcmpClient.Ping;
begin
PrepareEchoRequest;
SendEchoRequest;
GetEchoReply;
Binding.CloseSocket;
end;
function TIdIcmpClient.Receive(ATimeOut: Integer): TReplyStatus;
var
BytesRead: Integer;
Size: Integer;
begin
FillChar(bufReceive, sizeOf(bufReceive), 0);
Size := sizeof(bufReceive);
BytesRead := ReceiveBuffer(bufReceive, Size);
GStack.CheckForSocketError(BytesRead);
DecodeResponse(BytesRead, Result);
end;
procedure TIdIcmpClient.DoReply(const AReplyStatus: TReplyStatus);
begin
if Assigned(FOnReply) then
begin
FOnReply(Self, AReplyStatus);
end;
end;
end.
|
unit eSocial.Models.DAO.Operacao;
interface
uses
Data.DB,
System.Generics.Collections,
eSocial.Models.DAO.Interfaces,
eSocial.Models.ComplexTypes,
eSocial.Models.Entities.Operacao,
eSocial.Models.Components.Connections.Interfaces,
eSocial.Models.Components.Connections.Factory;
type
TModelDAOOperacao = class(TInterfacedObject, iModelDAOEntity<TOperacao>)
private
FConnection : iModelComponentConnection;
FDataSet : TDataSource;
FEntity : TOperacao;
procedure ReadFields;
public
constructor Create;
destructor Destroy; override;
class function New : iModelDAOEntity<TOperacao>;
function DataSet(aValue : TDataSource) : iModelDAOEntity<TOperacao>;
function Delete : iModelDAOEntity<TOperacao>; virtual; abstract;
function Get : iModelDAOEntity<TOperacao>; overload;
function Get(aID : String) : iModelDAOEntity<TOperacao>; overload;
function Get(aParams : TDictionary<String, String>) : iModelDAOEntity<TOperacao>; overload;
function Get(aParams : TArrayStrings) : iModelDAOEntity<TOperacao>; overload;
function Insert : iModelDAOEntity<TOperacao>; virtual; abstract;
function This : TOperacao;
function Update : iModelDAOEntity<TOperacao>; virtual; abstract;
end;
implementation
uses
System.SysUtils;
{ TModelDAOOperacao }
constructor TModelDAOOperacao.Create;
begin
FConnection := TModelComponentConnectionFactory.Connection;
FDataSet := TDataSource.Create(nil);
FDataSet.DataSet := FConnection.DataSet;
FEntity := TOperacao.Create(Self);
end;
destructor TModelDAOOperacao.Destroy;
begin
if Assigned(FDataSet) then
FDataSet.DisposeOf;
if Assigned(FEntity) then
FEntity.DisposeOf;
inherited;
end;
function TModelDAOOperacao.Get(aParams: TDictionary<String, String>): iModelDAOEntity<TOperacao>;
begin
Result := Self;
try
FConnection
.SQLClear
.SQL('Select')
.SQL(' e.competencia')
// .SQL(' , sum(Case when (e.insercao = ''S'') and (coalesce(pI.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''I'')), 0) > 0) then 1 else 0 end) as insercao ')
// .SQL(' , sum(Case when (e.alteracao = ''S'') and (coalesce(pA.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''A'')), 0) > 0) then 1 else 0 end) as alteracao')
// .SQL(' , sum(Case when (e.exclusao = ''S'') and (coalesce(pE.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''E'')), 0) > 0) then 1 else 0 end) as exclusao ')
.SQL(' , sum(Case when (e.insercao = ''S'') and (coalesce(pI.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pI.operacao)), 0) > 0) then 1 else 0 end) as insercao ')
.SQL(' , sum(Case when (e.alteracao = ''S'') and (coalesce(pA.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pA.operacao)), 0) > 0) then 1 else 0 end) as alteracao')
.SQL(' , sum(Case when (e.exclusao = ''S'') and (coalesce(pE.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pE.operacao)), 0) > 0) then 1 else 0 end) as exclusao ')
.SQL('from ESOCIAL_GERAR_EVENTOS e')
.SQL(' left join ESOCIAL_EVENTO pI on (pI.evento = e.evento and pI.competencia = e.competencia and pI.operacao = ''I'') ')
.SQL(' left join ESOCIAL_EVENTO pA on (pA.evento = e.evento and pA.competencia = e.competencia and pA.operacao = ''A'') ')
.SQL(' left join ESOCIAL_EVENTO pE on (pE.evento = e.evento and pE.competencia = e.competencia and pE.operacao = ''E'') ')
.SQL('where (e.competencia = :competencia)')
.SQL(' and (e.evento = :evento)')
.FetchParams
.AddParam('competencia', aParams.Items['competencia'])
.AddParam('evento', aParams.Items['evento'])
.SQL('group by')
.SQL(' e.competencia')
.Open;
ReadFields;
aParams.DisposeOf;
except
on E : Exception do
raise Exception.Create('Erro ao consultar a operação : ' + #13#13 + E.Message);
end;
end;
class function TModelDAOOperacao.New: iModelDAOEntity<TOperacao>;
begin
Result := Self.Create;
end;
function TModelDAOOperacao.DataSet(aValue: TDataSource): iModelDAOEntity<TOperacao>;
begin
Result := Self;
FDataSet := aValue;
end;
function TModelDAOOperacao.Get(aID: String): iModelDAOEntity<TOperacao>;
begin
Result := Self;
try
FConnection
.SQLClear
.SQL('Select')
.SQL(' e.competencia')
// .SQL(' , sum(Case when (e.insercao = ''S'') and (coalesce(pI.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''I'')), 0) > 0) then 1 else 0 end) as insercao ')
// .SQL(' , sum(Case when (e.alteracao = ''S'') and (coalesce(pA.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''A'')), 0) > 0) then 1 else 0 end) as alteracao')
// .SQL(' , sum(Case when (e.exclusao = ''S'') and (coalesce(pE.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''E'')), 0) > 0) then 1 else 0 end) as exclusao ')
.SQL(' , sum(Case when (e.insercao = ''S'') and (coalesce(pI.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pI.operacao)), 0) > 0) then 1 else 0 end) as insercao ')
.SQL(' , sum(Case when (e.alteracao = ''S'') and (coalesce(pA.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pA.operacao)), 0) > 0) then 1 else 0 end) as alteracao')
.SQL(' , sum(Case when (e.exclusao = ''S'') and (coalesce(pE.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pE.operacao)), 0) > 0) then 1 else 0 end) as exclusao ')
.SQL('from ESOCIAL_GERAR_EVENTOS e')
.SQL(' left join ESOCIAL_EVENTO pI on (pI.evento = e.evento and pI.competencia = e.competencia and pI.operacao = ''I'') ')
.SQL(' left join ESOCIAL_EVENTO pA on (pA.evento = e.evento and pA.competencia = e.competencia and pA.operacao = ''A'') ')
.SQL(' left join ESOCIAL_EVENTO pE on (pE.evento = e.evento and pE.competencia = e.competencia and pE.operacao = ''E'') ');
if not aID.Trim.IsEmpty then
begin
FConnection
.SQL('where (e.competencia = :competencia)')
.FetchParams
.AddParam('competencia', aID);
end;
FConnection
.SQL('group by')
.SQL(' e.competencia')
.Open;
ReadFields;
except
on E : Exception do
raise Exception.Create('Erro ao consultar a operação : ' + #13#13 + E.Message);
end;
end;
function TModelDAOOperacao.Get: iModelDAOEntity<TOperacao>;
begin
Result := Self;
try
FConnection
.SQLClear
.SQL('Select')
.SQL(' e.competencia')
// .SQL(' , sum(Case when (e.insercao = ''S'') and (coalesce(pI.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''I'')), 0) > 0) then 1 else 0 end) as insercao ')
// .SQL(' , sum(Case when (e.alteracao = ''S'') and (coalesce(pA.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''A'')), 0) > 0) then 1 else 0 end) as alteracao')
// .SQL(' , sum(Case when (e.exclusao = ''S'') and (coalesce(pE.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''E'')), 0) > 0) then 1 else 0 end) as exclusao ')
.SQL(' , sum(Case when (e.insercao = ''S'') and (coalesce(pI.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pI.operacao)), 0) > 0) then 1 else 0 end) as insercao ')
.SQL(' , sum(Case when (e.alteracao = ''S'') and (coalesce(pA.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pA.operacao)), 0) > 0) then 1 else 0 end) as alteracao')
.SQL(' , sum(Case when (e.exclusao = ''S'') and (coalesce(pE.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pE.operacao)), 0) > 0) then 1 else 0 end) as exclusao ')
.SQL('from ESOCIAL_GERAR_EVENTOS e')
.SQL(' left join ESOCIAL_EVENTO pI on (pI.evento = e.evento and pI.competencia = e.competencia and pI.operacao = ''I'') ')
.SQL(' left join ESOCIAL_EVENTO pA on (pA.evento = e.evento and pA.competencia = e.competencia and pA.operacao = ''A'') ')
.SQL(' left join ESOCIAL_EVENTO pE on (pE.evento = e.evento and pE.competencia = e.competencia and pE.operacao = ''E'') ')
.SQL('where (e.competencia = :competencia)')
.SQL('group by')
.SQL(' e.competencia')
.FetchParams
.AddParam('competencia', FEntity.Competencia)
.Open;
ReadFields;
except
on E : Exception do
raise Exception.Create('Erro ao consultar a operação : ' + #13#13 + E.Message);
end;
end;
procedure TModelDAOOperacao.ReadFields;
begin
with FDataSet.DataSet do
begin
FEntity
.Competencia( FieldByName('competencia').AsString )
.Insercao( FieldByName('insercao').AsInteger > 0 )
.Alteracao( FieldByName('alteracao').AsInteger > 0 )
.Exclusao( FieldByName('exclusao').AsInteger > 0 );
end;
end;
function TModelDAOOperacao.This: TOperacao;
begin
Result := FEntity;
end;
function TModelDAOOperacao.Get(aParams: TArrayStrings): iModelDAOEntity<TOperacao>;
begin
Result := Self;
try
FConnection
.SQLClear
.SQL('Select')
.SQL(' e.competencia')
// .SQL(' , sum(Case when (e.insercao = ''S'') and (coalesce(pI.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''I'')), 0) > 0) then 1 else 0 end) as insercao ')
// .SQL(' , sum(Case when (e.alteracao = ''S'') and (coalesce(pA.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''A'')), 0) > 0) then 1 else 0 end) as alteracao')
// .SQL(' , sum(Case when (e.exclusao = ''S'') and (coalesce(pE.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, ''E'')), 0) > 0) then 1 else 0 end) as exclusao ')
.SQL(' , sum(Case when (e.insercao = ''S'') and (coalesce(pI.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pI.operacao)), 0) > 0) then 1 else 0 end) as insercao ')
.SQL(' , sum(Case when (e.alteracao = ''S'') and (coalesce(pA.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pA.operacao)), 0) > 0) then 1 else 0 end) as alteracao')
.SQL(' , sum(Case when (e.exclusao = ''S'') and (coalesce(pE.enviado, ''N'') = ''N'') or (coalesce((Select pendencias from GET_ESOCIAL_PENDENCIA(e.evento, pE.operacao)), 0) > 0) then 1 else 0 end) as exclusao ')
.SQL('from ESOCIAL_GERAR_EVENTOS e')
.SQL(' left join ESOCIAL_EVENTO pI on (pI.evento = e.evento and pI.competencia = e.competencia and pI.operacao = ''I'') ')
.SQL(' left join ESOCIAL_EVENTO pA on (pA.evento = e.evento and pA.competencia = e.competencia and pA.operacao = ''A'') ')
.SQL(' left join ESOCIAL_EVENTO pE on (pE.evento = e.evento and pE.competencia = e.competencia and pE.operacao = ''E'') ')
.SQL('where (e.competencia = :competencia)')
.SQL(' and (e.evento = :evento)')
.FetchParams
.AddParam('competencia', aParams[0])
.AddParam('evento', aParams[1]);
if (aParams[2] = 'I') then
FConnection
.SQL(' and (e.insercao = ''S'')')
else
if (aParams[2] = 'A') then
FConnection
.SQL(' and (e.alteracao = ''S'')')
else
if (aParams[2] = 'E') then
FConnection
.SQL(' and (e.exclusao = ''S'')');
FConnection
.SQL('group by')
.SQL(' e.competencia')
.Open;
ReadFields;
except
on E : Exception do
raise Exception.Create('Erro ao consultar a operação : ' + #13#13 + E.Message);
end;
end;
end.
|
unit Kafka.Interfaces;
interface
uses
System.SysUtils,
Kafka.Lib;
type
IKafkaInterface = interface
['{B2F30971-1971-45D7-8694-7C946E5D91E8}']
end;
IKafkaProducer = interface(IKafkaInterface)
['{DCED73C8-0F12-4E82-876C-ACF90940D2C2}']
function GetProducedCount: Int64;
function GetKafkaHandle: prd_kafka_t;
function Produce(const Topic: String; const Payload: Pointer; const PayloadLength: NativeUInt; const Key: Pointer = nil; const KeyLen: NativeUInt = 0; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
function Produce(const Topic: String; const Payloads: TArray<Pointer>; const PayloadLengths: TArray<Integer>; const Key: Pointer = nil; const KeyLen: NativeUInt = 0; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
function Produce(const Topic: String; const Payload: String; const Key: String; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
function Produce(const Topic: String; const Payloads: TArray<String>; const Key: String; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
function Produce(const Topic: String; const Payload: String; const Key: String; const Encoding: TEncoding; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
function Produce(const Topic: String; const Payloads: TArray<String>; const Key: String; const Encoding: TEncoding; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
property KafkaHandle: prd_kafka_t read GetKafkaHandle;
property ProducedCount: Int64 read GetProducedCount;
end;
IKafkaConsumer = interface(IKafkaInterface)
['{7C124CC8-B64D-45EE-B3D4-99DA5653349C}']
function GetConsumedCount: Int64;
property ConsumedCount: Int64 read GetConsumedCount;
end;
implementation
end.
|
unit State;
interface
type
TWork = class;
//工作状态基类
TState = class
public
procedure WriteProgram(W: TWork); virtual; abstract;
end;
//上午工作状态
TForenoonState = class(TState)
public
procedure WriteProgram(W: TWork); override;
end;
//中午工作状态
TNoonState = class(TState)
public
procedure WriteProgram(W: TWork); override;
end;
//下午和傍晚工作状态
TAfternoonState = class(TState)
public
procedure WriteProgram(W: TWork); override;
end;
//晚间工作状态
TEveningState = class(TState)
public
procedure WriteProgram(W: TWork); override;
end;
//睡眠工作状态
TSleepingState = class(TState)
public
procedure WriteProgram(W: TWork); override;
end;
//下班休息状态
TRestState = class(TState)
public
procedure WriteProgram(W: TWork); override;
end;
TWork = class
private
FState: TState;
FHour: Double;
FFinish: Boolean;
public
constructor Create;
destructor Destroy; override;
procedure WriteProgram;
property State: TState read FState write FState;
property Hour: Double read FHour write FHour;
property Finish: Boolean read FFinish write FFinish;
end;
implementation
uses
SysUtils, Dialogs;
{ TForenoonState }
procedure TForenoonState.WriteProgram(W: TWork);
var
S: string;
begin
if W.Hour < 12 then
begin
S := Format('当前时间:%f点上午工作,精神百倍。', [W.Hour]);
ShowMessage(S);
end else
begin
//如果这里根据条件 释放和创建任何类就可以变化成各种时间段的状态,节约内存很好,比如界面Tab页程序。
W.State.Free;
W.State := TNoonState.Create;
W.WriteProgram;
end;
end;
{ TNoonState }
procedure TNoonState.WriteProgram(W: TWork);
var
S: string;
begin
if W.Hour < 13 then
begin
S := Format('当前时间:%f点饿了,午饭;犯困,午休。', [W.Hour]);
ShowMessage(S);
end else
begin
W.State.Free;
W.State := TAfternoonState.Create;
W.WriteProgram;
end;
end;
{ TAfternoonState }
procedure TAfternoonState.WriteProgram(W: TWork);
var
S: string;
begin
if W.Hour < 17 then
begin
S := Format('当前时间:%f点下午状态还不错,继续努力。', [W.Hour]);
ShowMessage(S);
end else
begin
W.State.Free;
W.State := TEveningState.Create;
W.WriteProgram;
end;
end;
{ TEveningState }
procedure TEveningState.WriteProgram(W: TWork);
var
S: string;
begin
if W.Finish then
begin
W.State := TRestState.Create;
W.WriteProgram;
end else
begin
if W.Hour < 21 then
begin
S := Format('当前时间:%f点加班哦,疲累之极。', [W.Hour]);
ShowMessage(S);
end else
begin
W.State.Free;
W.State := TSleepingState.Create;
W.WriteProgram;
end;
end;
end;
{ TSleepingState }
procedure TSleepingState.WriteProgram(W: TWork);
var
S: string;
begin
S := Format('当前时间:%f点不行了,睡着了。', [W.Hour]);
ShowMessage(S);
end;
{ TRestState }
procedure TRestState.WriteProgram(W: TWork);
var
S: string;
begin
S := Format('当前时间:%f点下班回家了。', [W.Hour]);
ShowMessage(S);
end;
{ TWork }
constructor TWork.Create;
begin
FState := TForenoonState.Create;
end;
destructor TWork.Destroy;
begin
FState.Free;
inherited;
end;
procedure TWork.WriteProgram;
begin
FState.WriteProgram(Self);
end;
end.
|
unit BrickCamp.Repositories.IUser;
interface
uses
System.JSON,
BrickCamp.Model.TUser;
type
IUserRepository = interface(IInterface)
['{9477B244-BFF7-4FBB-86EA-AC6ADAB82833}']
function GetOne(const Id: Integer): TUser;
function GetOneByName(const Name: string): TUser;
function GetList: TJSONArray;
procedure Insert(const User: TUser);
procedure Update(const User: TUser);
procedure Delete(const Id: Integer);
end;
implementation
end.
|
unit untEasyDBToolObject;
interface
uses
Classes;
type
TEasyDataBase = class
private
FName,
Fdbid,
Fsid,
Fcrdate,
Ffilename,
Fversion : string;
public
property Name: string read FName write FName;
property dbid: string read Fdbid write Fdbid;
property sid: string read Fsid write Fsid;
property crdate: string read Fcrdate write Fcrdate;
property filename: string read Ffilename write Ffilename;
property version: string read Fversion write Fversion;
end;
TEasyTableField = class
private
FTableName: string;
FFieldOrder: Integer;
FFieldName,
FFlag : string;
FPrimaryKey: Boolean;
FDataType : string;
FDataByte,
FDataLong,
FDataPercimcal : Integer;
FAllowNULL: Boolean;
FDefaultValue,
FFieldRemark : string;
FIsLoad: Boolean; //判断此表的字段是否已经获取过 如果获取过就不再获取
public
property TableName: string read FTableName write FTableName;
property FieldOrder: Integer read FFieldOrder write FFieldOrder;
property FieldName: string read FFieldName write FFieldName;
property Flag: string read FFlag write FFlag;
property PrimaryKey: Boolean read FPrimaryKey write FPrimaryKey;
property DataType: string read FDataType write FDataType;
property DataByte: Integer read FDataByte write FDataByte;
property DataLong: Integer read FDataLong write FDataLong;
property DataPercimcal: Integer read FDataPercimcal write FDataPercimcal;
property AllowNULL: Boolean read FAllowNULL write FAllowNULL;
property DefaultValue: string read FDefaultValue write FDefaultValue;
property FieldRemark: string read FFieldRemark write FFieldRemark;
property IsLoad: Boolean read FIsLoad write FIsLoad;
end;
implementation
end.
|
unit FIToolkit.CommandLine.Consts;
interface
uses
FIToolkit.Localization;
const
{ Command-line option }
STR_CLI_OPTION_PREFIX = '--';
STR_CLI_OPTION_DELIMITER = '=';
STR_CLI_OPTIONS_DELIMITER = ' ';
{ Supported command-line options }
STR_CLI_OPTION_GENERATE_CONFIG = 'generate-config';
STR_CLI_OPTION_HELP = 'help';
STR_CLI_OPTION_LOG_FILE = 'log-file';
STR_CLI_OPTION_NO_EXIT = 'no-exit';
STR_CLI_OPTION_SET_CONFIG = 'set-config';
STR_CLI_OPTION_VERSION = 'version';
resourcestring
{$IF LANGUAGE = LANG_EN_US}
{$INCLUDE 'Locales\en-US.inc'}
{$ELSEIF LANGUAGE = LANG_RU_RU}
{$INCLUDE 'Locales\ru-RU.inc'}
{$ELSE}
{$MESSAGE FATAL 'No language defined!'}
{$ENDIF}
implementation
end.
|
unit SoccerTests.RuleChooserTests;
interface
uses
System.SysUtils,
System.Generics.Collections,
DUnitX.TestFramework,
Soccer.Exceptions,
Soccer.Voting.AbstractRule,
Soccer.Voting.Preferences,
Soccer.Voting.RulePreferenceList,
Soccer.Voting.RuleChooser;
type
[TestFixture]
TRuleChooserTests = class(TObject)
public
[Test]
procedure NoRuleImportedTest;
[Test]
procedure NoRuleFoundTest;
end;
TUnusefulRule = class(TInterfacedObject, ISoccerVotingRule)
public
function ExecuteOn(AProfile: TSoccerVotingVotersPreferences;
out Winners: System.Generics.Collections.
TList<string>): Boolean;
function GetName: string;
end;
implementation
{ TRuleChooserTests }
procedure TRuleChooserTests.NoRuleFoundTest;
var
LRuleChooser: TSoccerRuleChooser;
LProfile: TSoccerVotingVotersPreferences;
LList: TSoccerVotingRulePreferenceList;
begin
LRuleChooser := TSoccerRuleChooser.Create;
LList := TSoccerVotingRulePreferenceList.Create
('..\..\testdata\empty.soccfg');
LList.Add(TUnusefulRule.Create);
LProfile := TSoccerVotingVotersPreferences.Create;
Assert.WillRaise(
procedure
begin
LRuleChooser.ChooseRuleFindWinners(LProfile, LList);
end, ESoccerParserException);
FreeAndNil(LProfile);
FreeAndNil(LList);
FreeAndNil(LRuleChooser);
end;
procedure TRuleChooserTests.NoRuleImportedTest;
var
LRuleChooser: TSoccerRuleChooser;
LProfile: TSoccerVotingVotersPreferences;
LList: TSoccerVotingRulePreferenceList;
begin
LRuleChooser := TSoccerRuleChooser.Create;
LList := TSoccerVotingRulePreferenceList.Create
('..\..\testdata\empty.soccfg');
LProfile := TSoccerVotingVotersPreferences.Create;
Assert.WillRaise(
procedure
begin
LRuleChooser.ChooseRuleFindWinners(LProfile, LList);
end, ESoccerParserException, 'No rule was imported');
FreeAndNil(LList);
FreeAndNil(LProfile);
FreeAndNil(LRuleChooser);
end;
{ TUnusefulRule }
function TUnusefulRule.ExecuteOn(AProfile: TSoccerVotingVotersPreferences;
out Winners: System.Generics.Collections.TList<string>): Boolean;
begin
Winners := TList<string>.Create;
Winners.Add('LOL');
Result := false;
end;
function TUnusefulRule.GetName: string;
begin
Result := 'unuseful';
end;
initialization
TDUnitX.RegisterTestFixture(TRuleChooserTests);
end.
|
unit ClassTree;
interface
const IS_WORD_FLAG = 32;
LAST_FLAG = 64;
HAS_CHILD_FLAG = 128;
type TTree = class
public
FData : char;
FWord : boolean;
FLeaves : array of TTree;
constructor Create( Data : char; Word : boolean );
destructor Destroy; override;
procedure AddTree( Leave : TTree );
function GetTreeByData( Data : char ) : TTree;
procedure SetWord( Data : char );
function Pack : byte;
end;
implementation
//==============================================================================
// Constructor/destructor
//==============================================================================
constructor TTree.Create( Data : char; Word : boolean );
begin
inherited Create;
FData := Data;
FWord := Word;
SetLength( FLeaves , 0 );
end;
destructor TTree.Destroy;
var I : integer;
begin
for I := Low( FLeaves ) to High( FLeaves ) do
FLeaves[I].Free;
SetLength( FLeaves , 0 );
inherited;
end;
//==============================================================================
// P U B L I C
//==============================================================================
procedure TTree.AddTree( Leave : TTree );
begin
SetLength( FLeaves , Length( Fleaves )+1 );
FLeaves[High( FLeaves )] := Leave;
end;
function TTree.GetTreeByData( Data : char ) : TTree;
var I : integer;
begin
Result := nil;
for I := Low( FLeaves ) to High( FLeaves ) do
if (FLeaves[I].FData = Data) then
begin
Result := FLeaves[I];
exit;
end;
end;
procedure TTree.SetWord( Data : char );
var I : integer;
begin
for I := Low( FLeaves ) to High( FLeaves ) do
if (FLeaves[I].FData = Data) then
begin
FLeaves[I].FWord := true;
exit;
end;
end;
function TTree.Pack : byte;
begin
Result := Ord( FData ) - Ord( 'a' );
if (FWord) then
Result := Result or IS_WORD_FLAG;
if (Length( FLeaves ) > 0) then
Result := Result or HAS_CHILD_FLAG;
end;
end.
|
unit DecoratorAdicionais;
interface
uses
Bebida, System.SysUtils;
type
TAdicionais = class(TBebida)
public
FBebida : TBebida;
function GetDescricao: String; override;
function Custo: Currency; override;
constructor Create(Bebida : TBebida);
destructor Destroy; override;
end;
implementation
{ TAdicionais }
constructor TAdicionais.Create(Bebida: TBebida);
begin
FBebida := Bebida;
end;
function TAdicionais.Custo: Currency;
begin
Result := FBebida.Custo
end;
destructor TAdicionais.Destroy;
begin
FBebida.Free;
inherited;
end;
function TAdicionais.GetDescricao: String;
begin
Result := FBebida.GetDescricao;
end;
end.
|
{ Invokable implementation File for TClientsTalking which implements IClientsTalking }
unit uClientsTalkingImpl;
interface
uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd,
System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes,
System.Variants,
FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr, uClientsTalkingIntf;
type
{ TClientsTalking }
TClientsTalking = class(TInvokableClass, IClientsTalking)
private
function CreateDb: Tsqlconnection;
public
procedure Update(Item: TClientServ);
procedure Delete(id: string);
function LoadClients: ClientsArray;
procedure DeleteDataFromTable;
procedure AddClientInBd(Item: TClientServ);
procedure UpdateOrInsert(Item: TClientServ);
function LogIn(name, password: string): Boolean;
procedure Autorisation(name, password: string);
function CheckUser(name: string): Boolean;
function SelectUser(id: string): Boolean;
end;
implementation
{ TClientsTalking }
procedure TClientsTalking.AddClientInBd(Item: TClientServ);
const
cInsertQuery =
'INSERT INTO clients (Cl_id,FIO,Phone,Adress,Photo) VALUES (:id,:FIO,:Phone,:Adress,:Photo)';
var
connect: Tsqlconnection;
Params: Tparams;
begin
connect := CreateDb;
Params := Tparams.Create;
Params.CreateParam(TFieldType.ftString, 'id', ptInput);
Params.ParamByName('id').AsString := Item.id;
Params.CreateParam(TFieldType.ftString, 'FIO', ptInput);
Params.ParamByName('FIO').AsString := Item.FIO;
Params.CreateParam(TFieldType.ftString, 'Phone', ptInput);
Params.ParamByName('Phone').AsString := Item.Phone;
Params.CreateParam(TFieldType.ftString, 'Adress', ptInput);
Params.ParamByName('Adress').AsString := Item.Adress;
Params.CreateParam(TFieldType.ftString, 'Photo', ptInput);
Params.ParamByName('Photo').AsString := Item.Photo;
connect.Execute(cInsertQuery, Params);
end;
procedure TClientsTalking.Autorisation(name, password: string);
const
cInsertQuery = 'INSERT INTO users (Login,Password) VALUES (:Login,:Password)';
var
Params: Tparams;
connect: Tsqlconnection;
begin
connect := CreateDb;
connect := CreateDb;
Params := Tparams.Create;
Params.CreateParam(TFieldType.ftString, 'Login', ptInput);
Params.ParamByName('Login').AsString := name;
Params.CreateParam(TFieldType.ftString, 'Password', ptInput);
Params.ParamByName('Password').AsString := password;
connect.Execute(cInsertQuery, Params);
end;
function TClientsTalking.CheckUser(name: string): Boolean;
var
connect: Tsqlconnection;
query: tsqlquery;
begin
connect := CreateDb;
query := tsqlquery.Create(nil);
query.SQLConnection := connect;
query.SQL.Text := 'select Login from users where Login = "' + name + '"';
query.Open;
if query.Eof then
begin
result := false;
connect.Close;
end
else
begin
result := true;
connect.Close;
end;
end;
function TClientsTalking.CreateDb: Tsqlconnection;
var
ASQLConnection: Tsqlconnection;
begin
ASQLConnection := Tsqlconnection.Create(nil);
ASQLConnection.ConnectionName := 'SQLITECONNECTION';
ASQLConnection.DriverName := 'Sqlite';
ASQLConnection.LoginPrompt := false;
ASQLConnection.Params.Values['Host'] := 'localhost';
ASQLConnection.Params.Values['FailIfMissing'] := 'False';
ASQLConnection.Params.Values['ColumnMetaDataSupported'] := 'False';
ASQLConnection.Params.Values['Database'] := 'clients.db';
ASQLConnection.Execute('CREATE TABLE if not exists clients(' + 'Cl_id TEXT,' +
'FIO TEXT,' + 'Phone TEXT,' + 'Adress TEXT,' + 'Photo TEXT,' +
'DataTime TEXT' + ');', nil);
ASQLConnection.Open;
ASQLConnection.Close;
ASQLConnection.Execute('CREATE TABLE if not exists users(' + 'Login TEXT,' +
'Password TEXT' + ');', nil);
ASQLConnection.Open;
result := ASQLConnection;
end;
procedure TClientsTalking.Delete(id: string);
var
query: tsqlquery;
connect: Tsqlconnection;
begin
connect := CreateDb;
query := tsqlquery.Create(nil);
query.SQLConnection := connect;
query.SQL.Text := 'DELETE FROM clients WHERE Cl_id = "' + id + '"';
query.ExecSQL();
freeandnil(query);
freeandnil(connect);
end;
procedure TClientsTalking.DeleteDataFromTable;
const
cInsertQuery = 'DELETE From clients';
var
connect: Tsqlconnection;
begin
connect := CreateDb;
connect.Execute(cInsertQuery, nil);
connect.Open;
freeandnil(connect);
end;
function TClientsTalking.LoadClients: ClientsArray;
var
connect: Tsqlconnection;
client: ClientsArray;
i: integer;
rs: Tdataset;
begin
connect := CreateDb;
connect.Execute
('select Cl_id,FIO,Phone,Adress,Photo,DataTime from clients', nil, rs);
connect.Open;
i := 0;
while not rs.Eof do
begin
setlength(client, i + 1);
client[i] := TClientServ.Create;
client[i].id := rs.FieldByName('Cl_id').Value;
client[i].FIO := rs.FieldByName('FIO').Value;
client[i].Phone := rs.FieldByName('Phone').Value;
client[i].Adress := rs.FieldByName('Adress').Value;
client[i].Photo := rs.FieldByName('Photo').Value;
client[i].DataTime := rs.FieldByName('DataTime').Value;
rs.Next;
inc(i);
end;
result := client;
end;
function TClientsTalking.LogIn(name, password: string): Boolean;
var
ASQLConnection: Tsqlconnection;
connect: tsqlquery;
query: string;
i, j: integer;
begin
i := 0;
j := 0;
connect := tsqlquery.Create(nil);
connect.SQLConnection := CreateDb;
connect.SQL.Text := 'select Login from users where Login = "' + name + '"';
connect.Open;
if not connect.Eof then
i := 1;
connect.Close;
connect.SQL.Text := 'select Password from users where Password = "' +
password + '"';
connect.Open;
if not connect.Eof then
j := 1;
connect.Close;
if (i + j) = 2 then
result := true
else
result := false;
end;
function TClientsTalking.SelectUser(id: string): Boolean;
var
query: tsqlquery;
connect: Tsqlconnection;
begin
connect := CreateDb;
try
query := tsqlquery.Create(nil);
query.SQL.Text := 'select CL_id from clients where Cl_id = "' + id + '"';
query.Open;
if not query.Eof then
result := true
else
result := false;
finally
freeandnil(query);
end;
end;
procedure TClientsTalking.Update(Item: TClientServ);
const
cInsertQuery =
'UPDATE clients SET `FIO` =:FIO, `Phone`= :Phone, `Adress` = :Adress, `Photo` = :Photo, `DataTime` = :DataTime WHERE Cl_id="%s"';
var
connect: Tsqlconnection;
querity: tsqlquery;
query: string;
begin
connect := CreateDb;
querity := tsqlquery.Create(nil);
querity.SQLConnection := connect;
query := Format(cInsertQuery, [Item.id]);
querity.Params.CreateParam(TFieldType.ftString, 'FIO', ptInput);
querity.Params.ParamByName('FIO').AsString := Item.FIO;
querity.Params.CreateParam(TFieldType.ftString, 'DataTime', ptInput);
querity.Params.ParamByName('DataTime').AsString := Item.DataTime;
querity.Params.CreateParam(TFieldType.ftString, 'Phone', ptInput);
querity.Params.ParamByName('Phone').AsString := Item.Phone;
querity.Params.CreateParam(TFieldType.ftString, 'Adress', ptInput);
querity.Params.ParamByName('Adress').AsString := Item.Adress;
querity.Params.CreateParam(TFieldType.ftString, 'Photo', ptInput);
querity.Params.ParamByName('Photo').AsString := Item.Photo;
querity.SQL.Text := query;
querity.ExecSQL();
end;
procedure TClientsTalking.UpdateOrInsert(Item: TClientServ);
const
cInsertQuery =
'UPDATE clients SET `FIO` =:FIO, `Phone`= :Phone, `Adress` = :Adress, `DataTime` = :DataTime WHERE Cl_id="%s"';
var
connect: tsqlquery;
connection: Tsqlconnection;
query: string;
begin
connection := CreateDb;
connect := tsqlquery.Create(nil);
try
connect.SQLConnection := connection;
connect.SQL.Text := 'select CL_id from clients where Cl_id = "' +
Item.id + '"';
connect.Open;
if not connect.Eof then
begin
query := Format(cInsertQuery, [Item.id]);
connect.Params.CreateParam(TFieldType.ftString, 'FIO', ptInput);
connect.Params.ParamByName('FIO').AsString := Item.FIO;
connect.Params.CreateParam(TFieldType.ftString, 'Phone', ptInput);
connect.Params.ParamByName('Phone').AsString := Item.Phone;
connect.Params.CreateParam(TFieldType.ftString, 'Adress', ptInput);
connect.Params.ParamByName('Adress').AsString := Item.Adress;
connect.Params.CreateParam(TFieldType.ftString, 'DataTime', ptInput);
connect.Params.ParamByName('DataTime').AsString := Item.DataTime;
connect.SQL.Text := query;
connect.ExecSQL();
end
else
begin
query := 'INSERT INTO clients (Cl_id,FIO,Phone,Adress,Photo,DataTime) VALUES (:id,:FIO,:Phone,:Adress,:Photo,:DataTime)';
connect.Params.CreateParam(TFieldType.ftString, 'id', ptInput);
connect.Params.ParamByName('id').AsString := Item.id;
connect.Params.CreateParam(TFieldType.ftString, 'FIO', ptInput);
connect.Params.ParamByName('FIO').AsString := Item.FIO;
connect.Params.CreateParam(TFieldType.ftString, 'Phone', ptInput);
connect.Params.ParamByName('Phone').AsString := Item.Phone;
connect.Params.CreateParam(TFieldType.ftString, 'Adress', ptInput);
connect.Params.ParamByName('Adress').AsString := Item.Adress;
connect.Params.CreateParam(TFieldType.ftString, 'Photo', ptInput);
connect.Params.ParamByName('Photo').AsString := Item.Photo;
connect.Params.CreateParam(TFieldType.ftString, 'DataTime', ptInput);
connect.Params.ParamByName('DataTime').AsString := Item.DataTime;
connect.SQL.Text := query;
connect.ExecSQL();
end;
finally
freeandnil(connect);
end;
freeandnil(connection);
end;
initialization
{ Invokable classes must be registered }
InvRegistry.RegisterInvokableClass(TClientsTalking);
end.
|
unit uWebBrowser;
interface
uses
SysUtils, Forms, Graphics, Windows, Classes, ShDocVw, MSHTML, ActiveX,
IntfDocHostUIHandler, UContainer;
function doURLEncode(const S: string; const InQueryString: Boolean = true): string;
function ColorToHTML(const Color: TColor): string;
type
TOnGetExternalProc = function(out ppDispatch: IDispatch): HResult of object; stdcall;
{$M+}
TWBWrapper = class(TWBContainer, IDocHostUIHandler, IOleClientSite)
private
fOnGetExternal: TOnGetExternalProc;
protected
function GetExternal(out ppDispatch: IDispatch): HResult; stdcall;
public
procedure ExecJS(const javascript: String);
procedure FocusWebBrowser(WB: TWebBrowser);
procedure LoadHTML(const aHTMLCode: String; const aSetLocationAsLocalhost: Boolean = false);
published
property OnGetExternal: TOnGetExternalProc read fOnGetExternal write fOnGetExternal;
end;
implementation
function doURLEncode(const S: string; const InQueryString: Boolean = true): string;
var
Idx: Integer; // loops thru characters in string
begin
Result := '';
for Idx := 1 to Length(S) do
begin
case S[Idx] of
'A'..'Z', 'a'..'z', '0'..'9', '-', '_', '.', ',':
Result := Result + S[Idx];
' ':
if InQueryString then
Result := Result + '+'
else
Result := Result + '%20';
else
Result := Result + '%' + SysUtils.IntToHex(Ord(S[Idx]), 2);
end;
end;
end;
function ColorToHTML(const Color: TColor): string;
var
ColorRGB: Integer;
begin
ColorRGB := ColorToRGB(Color);
Result := Format('#%0.2X%0.2X%0.2X', [GetRValue(ColorRGB), GetGValue(ColorRGB), GetBValue(ColorRGB)]);
end;
procedure TWBWrapper.ExecJS(const javascript: String);
var
aHTMLDocument2: IHTMLDocument2;
begin
if Supports(HostedBrowser.Document, IHTMLDocument2, aHTMLDocument2) then
aHTMLDocument2.parentWindow.execScript(javascript, 'JavaScript');
end;
procedure TWBWrapper.FocusWebBrowser(WB: TWebBrowser);
var
aHTMLDocument2: IHTMLDocument2;
begin
if Supports(HostedBrowser.Document, IHTMLDocument2, aHTMLDocument2) then
aHTMLDocument2.parentWindow.focus;
end;
function TWBWrapper.GetExternal(out ppDispatch: IDispatch): HResult;
begin
ppDispatch := nil;
Result := E_FAIL;
if Assigned (fOnGetExternal) then
Result := fOnGetExternal(ppDispatch);
end;
procedure TWBWrapper.LoadHTML(const aHTMLCode: String; const aSetLocationAsLocalhost: Boolean = false);
var
aPersistStreamInit: IPersistStreamInit;
sl: TStringList;
ms: TMemoryStream;
begin
HostedBrowser.Navigate('about:blank');
// pretend we're at localhost, so google doesn't complain about the API key
if aSetLocationAsLocalhost then
(HostedBrowser.Document as IHTMLDocument2).URL := 'http://localhost';
while HostedBrowser.ReadyState < READYSTATE_INTERACTIVE do
Forms.Application.ProcessMessages;
sl := TStringList.Create;
try
ms := TMemoryStream.Create;
try
sl.Text := aHTMLCode;
sl.SaveToStream(ms);
ms.Seek(0, 0);
if Supports(HostedBrowser.Document, IPersistStreamInit, aPersistStreamInit) then
begin
if Succeeded(aPersistStreamInit.InitNew) then /// without calling InitNew, I was getting intermittent error windows
aPersistStreamInit.Load(TStreamAdapter.Create(ms)); /// popping up, complaining something about Objects not existing in
end; /// for some windows dns error file
finally
ms.Free;
end;
finally
sl.Free;
end;
end;
end.
|
{ ****************************************************************************** }
{ * Audio Fingerprint * }
{ * written by QQ 600585@qq.com * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit AudioPrint;
{$INCLUDE zDefine.inc}
interface
uses CoreClasses, PascalStrings, DoStatusIO, UnicodeMixedLib, LearnTypes, Learn;
type
TInt16 = SmallInt;
TUInt32 = Cardinal;
TU32Vec = array of TUInt32;
TI16Vec = array of TInt16;
TBytes_ = array of Byte;
TAudioprintAlgorithm = (Audioprint_ALGORITHM1, Audioprint_ALGORITHM2, Audioprint_ALGORITHM3, Audioprint_ALGORITHM4);
TAudioprint = class(TInterfacedObject)
private type
TAudioprintContext = record
algorithm: TAudioprintAlgorithm;
Engine: TObject;
fingerprint: TU32Vec;
end;
public
ctx: TAudioprintContext;
constructor Create;
destructor Destroy; override;
function NewAlgorithm(algorithm: TAudioprintAlgorithm): boolean;
function GetAlgorithm: TAudioprintAlgorithm;
function SetOption(const Name: TPascalString; Value: TLInt): boolean;
function Start(Sample_Rate: TLInt; NumChannels: TLInt): boolean;
function Feed(Data: TI16Vec; len: TLInt): boolean;
function Finish: boolean;
function GetFingerprint(var fingerprint: TPascalString): boolean;
function GetCompressionFingerprint(var fingerprint: TPascalString): boolean;
function GetRawFingerprint(var fingerprint: TU32Vec; var Size: TLInt): boolean;
procedure EnocdeFingerprint(RawFP: TU32Vec; algorithm: TLInt; var EncodedFP: TPascalString; var EncodedSize: TLInt; Base64: boolean);
procedure DecodeFingerprint(encoded: TPascalString; var uncompressed: TU32Vec; var algorithm: TLInt; Base64: boolean);
end;
implementation
uses Math;
const
FILTER_SHIFT = 15;
WINDOW_TYPE = 9;
kMinSampleRate = 1000;
kMaxBufferSize = 1024 * 16;
// Resampler configuration
kResampleFilterLength = 16;
kResamplePhaseCount = 10;
kResampleLinear = 0;
kResampleCutoff = 0.8;
NUM_BANDS = 12;
cSAMPLE_RATE = 11025;
cFRAME_SIZE = 4096;
cOVERLAP = cFRAME_SIZE - cFRAME_SIZE div 3;
cMIN_FREQ = 28;
cMAX_FREQ = 3520;
Math_Pi: TLFloat = 3.1415926535897931;
TwoMath_Pi: TLFloat = 6.2831853071795862;
CODES: array [0 .. 3] of Byte = (0, 1, 3, 2);
kMaxNormalValue = 7;
kNormalBits = 3;
kExceptionBits = 5;
kChromaFilterSize = 5;
kSilenceWindow = 55; // 5 ms as 11025 Hz
function FreqToOctave(freq, base: TLFloat): TLFloat; {$IFDEF INLINE_ASM} inline; {$ENDIF}
begin
Result := log10(freq / base) / log10(2.0); // logarithmus dualis
end;
function IndexToFreq(i, frame_size, Sample_Rate: TLInt): TLFloat; {$IFDEF INLINE_ASM} inline; {$ENDIF}
begin
Result := i * Sample_Rate / frame_size;
end;
function FreqToIndex(freq: TLFloat; frame_size, Sample_Rate: TLInt): TLInt; {$IFDEF INLINE_ASM} inline; {$ENDIF}
begin
Result := round(frame_size * freq / Sample_Rate);
end;
procedure NormalizeVector(var vector: TLVec; norm: TLFloat; Threshold: TLFloat); {$IFDEF INLINE_ASM} inline; {$ENDIF}
var
i: TLInt;
begin
if (norm < Threshold) then
LSetVec(vector, 0.0)
else
for i := 0 to Length(vector) - 1 do
LDiv(vector[i], norm);
end;
function EuclideanNorm(vector: TLVec): TLFloat; {$IFDEF INLINE_ASM} inline; {$ENDIF}
var
squares, Value: TLFloat;
i: TLInt;
begin
squares := 0;
for i := 0 to Length(vector) - 1 do
begin
Value := vector[i];
squares := squares + Value * Value;
end;
if squares > 0 then
Result := Sqrt(squares)
else
Result := 0;
end;
procedure PrepareHammingWindow(var Data: TLVec); {$IFDEF INLINE_ASM} inline; {$ENDIF}
var
i, n: TLInt;
scale: TLFloat;
begin
n := Length(Data);
scale := TwoMath_Pi / (n - 1);
for i := 0 to n - 1 do
Data[i] := 0.54 - 0.46 * cos(scale * i);
end;
procedure ApplyWindow(var Data: TLVec; window: TLVec; Size: TLInt; scale: TLFloat); {$IFDEF INLINE_ASM} inline; {$ENDIF}
var
i: TLInt;
begin
i := 0;
while (i < Size) do
begin
Data[i] := Data[i] * window[i] * scale;
Inc(i);
end;
end;
type
TAudioConsumer = class(TCoreClassObject)
public
procedure Consume(Input: TI16Vec; AOffset: TLInt; ALength: TLInt); virtual; abstract;
end;
TAudioBuffer = class(TAudioConsumer)
public
FData: TI16Vec;
constructor Create;
destructor Destroy; override;
procedure Consume(Input: TI16Vec; AOffset: TLInt; ALength: TLInt); override;
function Data: TI16Vec;
procedure Reset;
end;
TAVResampleContext = record
public
rFilterBank: TI16Vec;
rFilterLength: TLInt;
rIdealDstIncr: TLInt;
rDstIncr: TLInt;
rIndex: TLInt;
rFrac: TLInt;
rSrcIncr: TLInt;
rCompensationDistance: TLInt;
rPhaseShift: TLInt;
rPhaseMask: TLInt;
rLinear: TLInt;
procedure Clear;
procedure Init(out_rate, in_rate, filter_size, APhaseShift: TLInt; ALinear: TLInt; cutoff: TLFloat);
function Resample(dst: TI16Vec; src: TI16Vec; var consumed: TLInt; src_size: TLInt; dst_size: TLInt; update_ctx: TLInt): TLInt;
end;
PAVResampleContext = ^TAVResampleContext;
TBitStringWriter = class(TCoreClassObject)
public
FValue: TPascalString;
FBuffer: TUInt32;
FBufferSize: TLInt;
constructor Create;
destructor Destroy; override;
procedure Flush;
procedure Write(x: TUInt32; bits: TLInt);
end;
TBitStringReader = class(TCoreClassObject)
public
FValue: TPascalString;
FValueIter: TLInt;
FBuffer: TUInt32;
FBufferSize: TLInt;
FEOF: boolean;
function GetAvailableBits: TLInt;
property EOF: boolean read FEOF;
property AvailableBits: TLInt read GetAvailableBits;
constructor Create(Input: TPascalString);
destructor Destroy; override;
procedure Reset;
function Read(bits: TLInt): TUInt32;
end;
TCPImage = class(TCoreClassObject)
public
FColumns: TLInt;
FRows: TLInt;
FData: TLMatrix;
property NumRows: TLInt read FRows;
property NumColumns: TLInt read FColumns;
constructor Create(columns: TLInt; rows: TLInt = 0);
destructor Destroy; override;
procedure AddRow(Row: TLVec);
function GetData(Row, Column: TLInt): TLFloat;
procedure SetData(Row, Column: TLInt; Value: TLFloat);
end;
TIntegralImage = class(TCoreClassObject)
public
FImage: TCPImage;
procedure Transform;
{ Construct the integral image. Note that will modify the original image in-place, so it will not be usable afterwards. }
constructor Create(Image: TCPImage);
destructor Destroy; override;
function Area(x1, y1, x2, y2: TLInt): TLFloat;
function NumColumns: TLInt;
function NumRows: TLInt;
function GetData(Row, Column: TLInt): TLFloat;
end;
TComparator = function(a, b: TLFloat): TLFloat;
TFilter = class(TCoreClassObject)
public
FType: TLInt;
FY: TLInt;
FHeight: TLInt;
FWidth: TLInt;
constructor Create(AType: TLInt; Y: TLInt; Height: TLInt; Width: TLInt);
function Apply(Image: TIntegralImage; offset: TLInt): TLFloat;
end;
TQuantizer = class(TCoreClassObject)
public
FT0, FT1, FT2: TLFloat;
constructor Create(t0: TLFloat = 0.0; t1: TLFloat = 0.0; t2: TLFloat = 0.0);
function Quantize(Value: TLFloat): TLInt;
end;
TClassifier = class(TCoreClassObject)
public
FFilter: TFilter;
FQuantizer: TQuantizer;
constructor Create(Filter: TFilter = nil; Quantizer: TQuantizer = nil);
destructor Destroy; override;
function Classify(Image: TIntegralImage; offset: TLInt): TLInt;
end;
TClassifierArray = array of TClassifier;
TCombinedBuffer = class(TCoreClassObject)
public
FOffset: TLInt;
FBuffer1, FBuffer2: TI16Vec;
FSize1, FSize2: TLInt;
constructor Create(const Buffer1: TI16Vec; Size1: TLInt; const Buffer2: TI16Vec; Size2: TLInt);
destructor Destroy; override;
function Size: TLInt;
function GetValue(i: TLInt): TInt16;
function Shift(Value: TLInt): TLInt;
function Read(var Buffer: TI16Vec; offset: TLInt; Count: TLInt): TLInt;
procedure Flush(var Buffer: TI16Vec);
end;
TFFTFrame = class(TCoreClassObject)
public
FSize: TLInt;
Data: TLVec;
constructor Create(Size: TLInt);
destructor Destroy; override;
function Magnitude(i: TLInt): TLFloat;
function Energy(i: TLInt): TLFloat;
end;
TFFTFrameConsumer = class(TCoreClassObject)
public
procedure Consume(frame: TFFTFrame); virtual; abstract;
end;
TFFTLib = class(TCoreClassObject)
public
FWindow: TLVec;
FFrameSize: TLInt;
FFrameSizeH: TLInt;
constructor Create(frame_size: TLInt; window: TLVec);
destructor Destroy; override;
procedure ComputeFrame(Input: TI16Vec; var frame: TFFTFrame); virtual; abstract;
end;
TFFT = class(TAudioConsumer)
public
FBufferOffset: TLInt;
FWindow: TLVec;
FFFTBuffer: TI16Vec;
FFrame: TFFTFrame;
FFrameSize: TLInt;
FIncrement: TLInt;
FLib: TFFTLib;
FConsumer: TFFTFrameConsumer;
constructor Create(frame_size: TLInt; overlap: TLInt; consumer: TFFTFrameConsumer);
destructor Destroy; override;
procedure Reset;
procedure Consume(Input: TI16Vec; AOffset: TLInt; lLength: TLInt); override;
function overlap: TLInt;
end;
TFFTLomont = class(TFFTLib)
public
FInput: TLVec;
ForwardCos: TLVec;
ForwardSin: TLVec;
procedure ComputeTable(Size: TLInt);
procedure FFT(var Data: TLVec);
procedure RealFFT(var Data: TLVec);
constructor Create(frame_size: TLInt; window: TLVec);
destructor Destroy; override;
procedure ComputeFrame(Input: TI16Vec; var frame: TFFTFrame); override;
end;
TFeatureVectorConsumer = class(TCoreClassObject)
public
constructor Create;
destructor Destroy; override;
procedure Consume(var features: TLVec); virtual; abstract;
end;
TImageBuilder = class(TFeatureVectorConsumer)
public
FImage: TCPImage;
constructor Create(Image: TCPImage = nil);
destructor Destroy; override;
procedure Reset(Image: TCPImage);
procedure Consume(var features: TLVec); override;
end;
TChromaFilter = class(TFeatureVectorConsumer)
public
FBufferOffset: TLInt;
FBufferSize: TLInt;
FConsumer: TFeatureVectorConsumer;
FCoefficients: TLVec;
FLength: TLInt;
FBuffer: TLMatrix;
FResult: TLVec;
constructor Create(coefficients: TLVec; ALength: TLInt; consumer: TFeatureVectorConsumer);
destructor Destroy; override;
procedure Reset;
procedure Consume(var features: TLVec); override;
end;
TChromaNormalizer = class(TFeatureVectorConsumer)
public
FConsumer: TFeatureVectorConsumer;
constructor Create(consumer: TFeatureVectorConsumer);
destructor Destroy; override;
procedure Reset;
procedure Consume(var features: TLVec); override;
end;
TChromaResampler = class(TFeatureVectorConsumer)
public
FResult: TLVec;
FConsumer: TFeatureVectorConsumer;
FIteration: TLInt;
FFactor: TLInt;
constructor Create(factor: TLInt; consumer: TFeatureVectorConsumer);
destructor Destroy; override;
procedure Reset;
procedure Consume(var features: TLVec); override;
end;
TFingerprintCalculator = class(TCoreClassObject)
public
FMaxFilterWidth: TLInt;
FClassifiers: TClassifierArray;
constructor Create(classifiers: TClassifierArray);
destructor Destroy; override;
function Calculate(Image: TCPImage): TU32Vec;
function CalculateSubfingerprint(Image: TIntegralImage; offset: TLInt): TUInt32;
end;
TFingerprintCompressor = class(TCoreClassObject)
public
FResult: TPascalString;
FBits: TBytes_;
procedure WriteNormalBits();
procedure WriteExceptionBits();
procedure ProcessSubfingerprint(x: TUInt32);
constructor Create;
function Compress(var fingerprint: TU32Vec; algorithm: TLInt = 0): TPascalString;
end;
TFingerprintDecompressor = class(TCoreClassObject)
public
FResult: TU32Vec;
FBits: TBytes_;
function ReadNormalBits(reader: TBitStringReader): boolean;
function ReadExceptionBits(reader: TBitStringReader): boolean;
procedure UnpackBits();
constructor Create;
function Decompress(fingerprint: TPascalString; var algorithm: TLInt): TU32Vec;
end;
TFingerprinterConfiguration = class(TCoreClassObject)
public
FNumClassifiers: TLInt;
FClassifiers: TClassifierArray;
FNumFilterCoefficients: TLInt;
FFilterCoefficients: TLVec;
FInterpolate: boolean;
FRemoveSilence: boolean;
FSilenceThreshold: TLInt;
kChromaFilterCoefficients: TLVec;
constructor Create;
destructor Destroy; override;
procedure SetClassifiers(classifiers: TClassifierArray);
procedure SetFilterCoefficients(FilterCoefficients: TLVec);
end;
// Trained on a randomly selected test data
TFingerprinterConfigurationTest1 = class(TFingerprinterConfiguration)
public
constructor Create;
destructor Destroy; override;
end;
// Trained on 60k pairs based on eMusic samples (mp3)
TFingerprinterConfigurationTest2 = class(TFingerprinterConfiguration)
public
constructor Create;
destructor Destroy; override;
end;
// Trained on 60k pairs based on eMusic samples with interpolation enabled (mp3)
TFingerprinterConfigurationTest3 = class(TFingerprinterConfiguration)
public
constructor Create;
destructor Destroy; override;
end;
// Same as v2, but trims leading silence
TFingerprinterConfigurationTest4 = class(TFingerprinterConfigurationTest2)
public
constructor Create;
destructor Destroy; override;
end;
TMovingAverage = class(TCoreClassObject)
public
FBuffer: TI16Vec;
FSize: TLInt;
FOffset: TLInt;
FSum: TLInt;
FCount: TLInt;
constructor Create(Size: TLInt);
destructor Destroy; override;
procedure AddValue(const x: TInt16);
function GetAverage: TInt16;
end;
TSilenceRemover = class(TAudioConsumer)
public
FThreshold: TLInt;
FStart: boolean;
FConsumer: TAudioConsumer;
FAverage: TMovingAverage;
constructor Create(consumer: TAudioConsumer; Threshold: TLInt = 0);
destructor Destroy; override;
function Reset(Sample_Rate, NumChannels: TLInt): boolean;
procedure Flush;
procedure Consume(Input: TI16Vec; AOffset: TLInt; Length: TLInt); override;
end;
TAudioProcessor = class(TAudioConsumer)
public
FBufferOffset: TLInt;
FBufferSize: TLInt;
FTargetSampleRate: TLInt;
FNumChannels: TLInt;
FResampleCTX: PAVResampleContext;
FConsumer: TAudioConsumer;
FBuffer: TI16Vec;
FResampleBuffer: TI16Vec;
procedure Resample;
function Load(Input: TI16Vec; offset: TLInt; ALength: TLInt): TLInt;
procedure LoadMono(Input: TI16Vec; offset: TLInt; ALength: TLInt);
procedure LoadStereo(Input: TI16Vec; offset: TLInt; ALength: TLInt);
procedure LoadMultiChannel(Input: TI16Vec; offset: TLInt; ALength: TLInt);
constructor Create(SampleRate: TLInt; consumer: TAudioConsumer);
destructor Destroy; override;
function Reset(SampleRate, NumChannels: TLInt): boolean;
procedure Flush;
procedure Consume(Input: TI16Vec; AOffset: TLInt; ALength: TLInt); override;
end;
TChroma = class(TFFTFrameConsumer)
public
FInterpolate: boolean;
FMinIndex: TLInt;
FMaxIndex: TLInt;
FNotes: TBytes_;
FNotesFrac: TLVec;
FFeatures: TLVec;
FConsumer: TFeatureVectorConsumer;
procedure PrepareNotes(min_freq, max_freq, frame_size, Sample_Rate: TLInt);
constructor Create(min_freq, max_freq, frame_size, Sample_Rate: TLInt; consumer: TFeatureVectorConsumer);
destructor Destroy; override;
procedure Reset;
procedure Consume(frame: TFFTFrame); override;
end;
TFingerprinter = class(TAudioConsumer)
public
FSilenceRemover: TSilenceRemover;
FImage: TCPImage;
FImageBuilder: TImageBuilder;
FChroma: TChroma;
FChromaNormalizer: TChromaNormalizer;
FChromaFilter: TChromaFilter;
FFFT: TFFT;
FAudioProcessor: TAudioProcessor;
FFingerprintCalculator: TFingerprintCalculator;
FConfig: TFingerprinterConfiguration;
constructor Create(config: TFingerprinterConfiguration = nil);
destructor Destroy; override;
function SetOption(const Name: TPascalString; Value: TLInt): boolean;
function Start(Sample_Rate, NumChannels: TLInt): boolean;
function Finish: TU32Vec;
procedure Consume(Input: TI16Vec; AOffset: TLInt; len: TLInt); override;
end;
function CompressFingerprint(Data: TU32Vec; algorithm: TLInt = 0): TPascalString; forward;
function DecompressFingerprint(Data: TPascalString; var algorithm: TLInt): TU32Vec; forward;
function CreateFingerprinterConfiguration(algorithm: TAudioprintAlgorithm): TFingerprinterConfiguration; forward;
constructor TAudioBuffer.Create;
begin
inherited Create;
SetLength(FData, 0);
end;
destructor TAudioBuffer.Destroy;
begin
SetLength(FData, 0);
inherited Destroy;
end;
procedure TAudioBuffer.Consume(Input: TI16Vec; AOffset: TLInt; ALength: TLInt);
var
i, n: TLInt;
begin
n := Length(FData);
SetLength(FData, n + ALength - AOffset);
for i := AOffset to ALength - 1 do
begin
FData[n + i - AOffset] := Input[i];
end;
end;
function TAudioBuffer.Data: TI16Vec;
begin
Result := FData;
end;
procedure TAudioBuffer.Reset;
begin
SetLength(FData, 0);
end;
function BuildFilter(var Filter: TI16Vec; factor: TLFloat; tap_count: TLInt; phase_count, scale, _Type: TLInt): boolean; {$IFDEF INLINE_ASM} inline; {$ENDIF}
{ 0th order modified bessel function of the first kind. }
function bessel(x: TLFloat): TLFloat; inline;
var
v, lastv, t, lx: TLFloat;
i: TLInt;
begin
v := 1;
lastv := 0;
t := 1;
lx := x * x / 4;
i := 1;
while v <> lastv do
begin
lastv := v;
t := t * lx / (i * i);
v := v + t;
Inc(i);
end;
Result := v;
end;
function Clip16(a: TLInt; amin, amax: TInt16): TInt16; inline;
begin
if (a < amin) then
Result := amin
else if (a > amax) then
Result := amax
else
Result := TInt16(a);
end;
var
ph, i, center: TLInt;
x, Y, w: TLFloat;
tab: array of TLFloat;
norm: TLFloat;
d: TLFloat;
ex: TLInt;
begin
SetLength(tab, tap_count);
center := (tap_count - 1) div 2;
// if upsampling, only need to interpolate, no filter
if (factor > 1.0) then
factor := 1.0;
for ph := 0 to phase_count - 1 do
begin
norm := 0;
for i := 0 to tap_count - 1 do
begin
x := Math_Pi * ((i - center) - ph / phase_count) * factor;
if (x = 0) then
Y := 1.0
else
Y := Sin(x) / x;
case (_Type) of
0:
begin
d := -0.5; // first order derivative = -0.5
x := Abs(((i - center) - ph / phase_count) * factor);
if (x < 1.0) then
Y := 1 - 3 * x * x + 2 * x * x * x + d * (-x * x + x * x * x)
else
Y := d * (-4 + 8 * x - 5 * x * x + x * x * x);
end;
1:
begin
w := 2.0 * x / (factor * tap_count) + Math_Pi;
Y := Y * (0.3635819 - 0.4891775 * cos(w) + 0.1365995 * cos(2 * w) - 0.0106411 * cos(3 * w));
end;
else
begin
w := 2.0 * x / (factor * tap_count * Math_Pi);
Y := Y * (bessel(_Type * Sqrt(Max(1 - w * w, 0))));
end;
end;
tab[i] := Y;
norm := norm + Y;
end;
// normalize so that an uniform color remains the same
for i := 0 to tap_count - 1 do
begin
ex := floor(tab[i] * scale / norm + 0.50000);
Filter[ph * tap_count + i] := Clip16(ex, -32768, 32767);
end;
end;
Result := True;
end;
procedure TAVResampleContext.Clear;
begin
SetLength(rFilterBank, 0);
rFilterLength := 0;
rIdealDstIncr := 0;
rDstIncr := 0;
rIndex := 0;
rFrac := 0;
rSrcIncr := 0;
rCompensationDistance := 0;
rPhaseShift := 0;
rPhaseMask := 0;
rLinear := 0;
end;
procedure TAVResampleContext.Init(out_rate, in_rate, filter_size, APhaseShift: TLInt; ALinear: TLInt; cutoff: TLFloat);
var
factor: TLFloat;
phase_count: TLInt;
r: boolean;
begin
factor := min(out_rate * cutoff / in_rate, 1.0);
phase_count := 1 shl APhaseShift;
rPhaseShift := APhaseShift;
rPhaseMask := phase_count - 1;
rLinear := ALinear;
rFilterLength := Max(ceil(filter_size / factor), 1);
SetLength(rFilterBank, rFilterLength * (phase_count + 1));
begin
r := BuildFilter(rFilterBank, factor, rFilterLength, phase_count, (1 shl FILTER_SHIFT), WINDOW_TYPE);
if (r) then
begin
CopyPtr(@rFilterBank[0], @rFilterBank[rFilterLength * phase_count + 1], (rFilterLength - 1) * sizeof(TInt16));
rFilterBank[rFilterLength * phase_count] := rFilterBank[rFilterLength - 1];
rSrcIncr := out_rate;
rDstIncr := in_rate * phase_count;
rIdealDstIncr := rDstIncr;
rIndex := -phase_count * ((rFilterLength - 1) div 2);
end;
end;
end;
function TAVResampleContext.Resample(dst: TI16Vec; src: TI16Vec; var consumed: TLInt; src_size: TLInt; dst_size: TLInt; update_ctx: TLInt): TLInt;
var
dst_index, i: TLInt;
lIndex, lFrac, ldst_incr_frac, lDst_incr, lCompensationDistance: TLInt;
lIndex2, lIncr: int64;
lFilterOffset: TLInt;
lSampleIndex, lVal, lV2: TLInt;
lr: TLInt;
lTempSrcIdx: TLInt;
begin
lIndex := self.rIndex;
lFrac := self.rFrac;
ldst_incr_frac := self.rDstIncr mod self.rSrcIncr;
lDst_incr := self.rDstIncr div self.rSrcIncr;
lCompensationDistance := self.rCompensationDistance;
if (lCompensationDistance = 0) and (self.rFilterLength = 1) and (self.rPhaseShift = 0) then
begin
lIndex2 := int64(lIndex) shl 32; // pascal is pain
lIncr := (int64(1) shl 32) * self.rDstIncr div self.rSrcIncr;
dst_size := min(dst_size, (src_size - 1 - lIndex) * self.rSrcIncr div self.rDstIncr);
dst_index := 0;
while dst_index < dst_size do
begin
dst[dst_index] := src[lIndex2 shr 32];
Inc(lIndex2, lIncr);
Inc(dst_index);
end;
Inc(lFrac, dst_size * ldst_incr_frac);
Inc(lIndex, dst_size * lDst_incr + lFrac div self.rSrcIncr);
lFrac := lFrac mod self.rSrcIncr;
end
else
begin
for dst_index := 0 to dst_size - 1 do
begin
lFilterOffset := self.rFilterLength * (lIndex and self.rPhaseMask);
lr := Integer(int64(lIndex) shr self.rPhaseShift);
lSampleIndex := lr;
lVal := 0;
if (lSampleIndex < 0) then
begin
for i := 0 to self.rFilterLength - 1 do
begin
lTempSrcIdx := Abs(lSampleIndex + i) mod src_size;
Inc(lVal, (src[lTempSrcIdx] * self.rFilterBank[lFilterOffset + i]));
end;
end
else if (lSampleIndex + self.rFilterLength > src_size) then
begin
break;
end
else if (self.rLinear = 1) then
begin
lV2 := 0;
for i := 0 to self.rFilterLength - 1 do
begin
Inc(lVal, src[lSampleIndex + i] * self.rFilterBank[lFilterOffset + i]);
Inc(lV2, src[lSampleIndex + i] * self.rFilterBank[lFilterOffset + i + self.rFilterLength]);
end;
Inc(lVal, ((lV2 - lVal) * (lFrac div self.rSrcIncr)));
end
else
begin
for i := 0 to self.rFilterLength - 1 do
begin
Inc(lVal, (src[lSampleIndex + i] * self.rFilterBank[lFilterOffset + i]));
end;
end;
lVal := (lVal + (1 shl (FILTER_SHIFT - 1))) shr FILTER_SHIFT;
if (lVal + 32768) > 65535 then // Pascal is pain
dst[dst_index] := (lVal shr 31) xor 32767
else
dst[dst_index] := lVal;
Inc(lFrac, ldst_incr_frac);
Inc(lIndex, lDst_incr);
if (lFrac >= self.rSrcIncr) then
begin
dec(lFrac, self.rSrcIncr);
Inc(lIndex);
end;
if (dst_index + 1 = lCompensationDistance) then
begin
lCompensationDistance := 0;
ldst_incr_frac := self.rIdealDstIncr mod self.rSrcIncr;
lDst_incr := self.rIdealDstIncr div self.rSrcIncr;
end;
end;
end;
consumed := Max(lIndex, 0) shr self.rPhaseShift;
if (lIndex >= 0) then
lIndex := lIndex and self.rPhaseMask;
if (lCompensationDistance <> 0) then
begin
lCompensationDistance := lCompensationDistance - dst_index;
end;
if (update_ctx = 1) then
begin
self.rFrac := lFrac;
self.rIndex := lIndex;
self.rDstIncr := ldst_incr_frac + self.rSrcIncr * lDst_incr;
self.rCompensationDistance := lCompensationDistance;
end;
Result := dst_index;
end;
constructor TBitStringWriter.Create;
begin
inherited Create;
FBuffer := 0;
FBufferSize := 0;
FValue := '';
end;
destructor TBitStringWriter.Destroy;
begin
inherited Destroy;
end;
procedure TBitStringWriter.Flush;
begin
while (FBufferSize > 0) do
begin
FValue.Append(chr(FBuffer and 255));
FBuffer := FBuffer shr 8;
FBufferSize := FBufferSize - 8;
end;
FBufferSize := 0;
end;
procedure TBitStringWriter.Write(x: TUInt32; bits: TLInt);
begin
FBuffer := FBuffer or (x shl FBufferSize);
FBufferSize := FBufferSize + bits;
while (FBufferSize >= 8) do
begin
FValue.Append(chr(FBuffer and 255));
FBuffer := FBuffer shr 8;
FBufferSize := FBufferSize - 8;
end;
end;
function TBitStringReader.GetAvailableBits: TLInt;
begin
if FEOF then
Result := 0
else
begin
Result := FBufferSize + 8 * (FValue.len - FValueIter + 1);
end;
end;
constructor TBitStringReader.Create(Input: TPascalString);
begin
inherited Create;
FValue := Input;
FBuffer := 0;
FBufferSize := 0;
FEOF := False;
FValueIter := 1;
end;
destructor TBitStringReader.Destroy;
begin
inherited Destroy;
end;
procedure TBitStringReader.Reset;
begin
FBuffer := 0;
FBufferSize := 0;
end;
function TBitStringReader.Read(bits: TLInt): TUInt32;
var
lValueByte: Byte;
begin
if (FBufferSize < bits) then
begin
if (FValueIter <= FValue.len) then
begin
lValueByte := Ord(FValue[FValueIter]);
FBuffer := FBuffer or (lValueByte shl FBufferSize);
Inc(FValueIter);
FBufferSize := FBufferSize + 8;
end
else
begin
FEOF := True;
end;
end;
Result := FBuffer and ((1 shl bits) - 1);
FBuffer := FBuffer shr bits;
FBufferSize := FBufferSize - bits;
if (FBufferSize <= 0) and (FValueIter > FValue.len) then
begin
FEOF := True;
end;
end;
constructor TCPImage.Create(columns: TLInt; rows: TLInt = 0);
var
i: TLInt;
begin
inherited Create;
FColumns := columns; // 12 columns 0...x rows (variabel);
FRows := rows;
// dim the array correctly
SetLength(FData, FRows);
if FRows > 0 then
begin
for i := 0 to FRows - 1 do
begin
SetLength(FData[i], FColumns);
end;
end;
end;
destructor TCPImage.Destroy;
var
i: TLInt;
begin
for i := 0 to FRows - 1 do
begin
SetLength(FData[i], 0);
end;
SetLength(FData, 0);
inherited Destroy;
end;
procedure TCPImage.AddRow(Row: TLVec);
var
i: TLInt;
begin
// add a row and copy the values
Inc(FRows);
SetLength(FData, FRows);
SetLength(FData[FRows - 1], FColumns);
for i := 0 to FColumns - 1 do
begin
FData[FRows - 1, i] := Row[i];
end;
end;
function TCPImage.GetData(Row, Column: TLInt): TLFloat;
begin
Result := FData[Row][Column];
end;
procedure TCPImage.SetData(Row, Column: TLInt; Value: TLFloat);
begin
FData[Row][Column] := Value;
end;
procedure TIntegralImage.Transform;
var
lColumns, lRows: TLInt;
m, n: TLInt;
begin
// in Pascal you know what you're doing
lColumns := FImage.NumColumns;
lRows := FImage.NumRows;
for m := 1 to lColumns - 1 do
begin
// First column - add value on top
FImage.SetData(0, m, FImage.GetData(0, m) + FImage.GetData(0, m - 1));
end;
for n := 1 to lRows - 1 do
begin
// First row - add value on left
FImage.SetData(n, 0, FImage.GetData(n, 0) + FImage.GetData(n - 1, 0));
for m := 1 to lColumns - 1 do
begin
FImage.SetData(n, m, FImage.GetData(n, m) + FImage.GetData(n - 1, m) + FImage.GetData(n, m - 1) - FImage.GetData(n - 1, m - 1));
end;
end;
end;
constructor TIntegralImage.Create(Image: TCPImage);
begin
inherited Create;
FImage := Image;
Transform;
end;
destructor TIntegralImage.Destroy;
begin
FImage := nil;
inherited Destroy;
end;
function TIntegralImage.GetData(Row, Column: TLInt): TLFloat;
begin
Result := FImage.GetData(Row, Column);
end;
function TIntegralImage.Area(x1, y1, x2, y2: TLInt): TLFloat;
var
lArea: TLFloat;
begin
if (x2 < x1) or (y2 < y1) then
begin
Result := 0.0;
Exit;
end;
lArea := FImage.GetData(x2, y2);
if (x1 > 0) then
begin
lArea := lArea - FImage.GetData(x1 - 1, y2);
if (y1 > 0) then
begin
lArea := lArea + FImage.GetData(x1 - 1, y1 - 1);
end;
end;
if (y1 > 0) then
begin
lArea := lArea - FImage.GetData(x2, y1 - 1);
end;
Result := lArea;
end;
function TIntegralImage.NumColumns: TLInt;
begin
Result := FImage.NumColumns;
end;
function TIntegralImage.NumRows: TLInt;
begin
Result := FImage.NumRows;
end;
function Subtract(a, b: TLFloat): TLFloat;
begin
Result := a - b;
end;
function SubtractLog(a, b: TLFloat): TLFloat;
var
r: TLFloat;
begin
r := ln(1.0 + a) - ln(1.0 + b);
// assert(!IsNaN(r));
Result := r;
end;
// oooooooooooooooo
// oooooooooooooooo
// oooooooooooooooo
// oooooooooooooooo
function Filter0(Image: TIntegralImage; x, Y, w, h: TLInt; cmp: TComparator): TLFloat;
var
a, b: TLFloat;
begin
a := Image.Area(x, Y, x + w - 1, Y + h - 1);
b := 0;
Result := cmp(a, b);
end;
// ................
// ................
// oooooooooooooooo
// oooooooooooooooo
function Filter1(Image: TIntegralImage; x, Y, w, h: TLInt; cmp: TComparator): TLFloat;
var
a, b: TLFloat;
h_2: TLInt;
begin
h_2 := h div 2;
a := Image.Area(x, Y + h_2, x + w - 1, Y + h - 1);
b := Image.Area(x, Y, x + w - 1, Y + h_2 - 1);
Result := cmp(a, b);
end;
// .......ooooooooo
// .......ooooooooo
// .......ooooooooo
// .......ooooooooo
function Filter2(Image: TIntegralImage; x, Y, w, h: TLInt; cmp: TComparator): TLFloat;
var
a, b: TLFloat;
w_2: TLInt;
begin
w_2 := w div 2;
a := Image.Area(x + w_2, Y, x + w - 1, Y + h - 1);
b := Image.Area(x, Y, x + w_2 - 1, Y + h - 1);
Result := cmp(a, b);
end;
// .......ooooooooo
// .......ooooooooo
// ooooooo.........
// ooooooo.........
function Filter3(Image: TIntegralImage; x, Y, w, h: TLInt; cmp: TComparator): TLFloat;
var
a, b: TLFloat;
w_2, h_2: TLInt;
begin
w_2 := w div 2;
h_2 := h div 2;
a := Image.Area(x, Y + h_2, x + w_2 - 1, Y + h - 1) + Image.Area(x + w_2, Y, x + w - 1, Y + h_2 - 1);
b := Image.Area(x, Y, x + w_2 - 1, Y + h_2 - 1) + Image.Area(x + w_2, Y + h_2, x + w - 1, Y + h - 1);
Result := cmp(a, b);
end;
// ................
// oooooooooooooooo
// ................
function Filter4(Image: TIntegralImage; x, Y, w, h: TLInt; cmp: TComparator): TLFloat;
var
a, b: TLFloat;
h_3: TLInt;
begin
h_3 := h div 3;
a := Image.Area(x, Y + h_3, x + w - 1, Y + 2 * h_3 - 1);
b := Image.Area(x, Y, x + w - 1, Y + h_3 - 1) + Image.Area(x, Y + 2 * h_3, x + w - 1, Y + h - 1);
Result := cmp(a, b);
end;
// .....oooooo.....
// .....oooooo.....
// .....oooooo.....
// .....oooooo.....
function Filter5(Image: TIntegralImage; x, Y, w, h: TLInt; cmp: TComparator): TLFloat;
var
a, b: TLFloat;
w_3: TLInt;
begin
w_3 := w div 3;
a := Image.Area(x + w_3, Y, x + 2 * w_3 - 1, Y + h - 1);
b := Image.Area(x, Y, x + w_3 - 1, Y + h - 1) + Image.Area(x + 2 * w_3, Y, x + w - 1, Y + h - 1);
Result := cmp(a, b);
end;
constructor TFilter.Create(AType: TLInt; Y: TLInt; Height: TLInt; Width: TLInt);
begin
inherited Create;
FType := AType;
FY := Y;
FHeight := Height;
FWidth := Width;
end;
function TFilter.Apply(Image: TIntegralImage; offset: TLInt): TLFloat;
begin
case (FType) of
0: Result := Filter0(Image, offset, FY, FWidth, FHeight, {$IFDEF FPC}@{$ENDIF FPC}SubtractLog);
1: Result := Filter1(Image, offset, FY, FWidth, FHeight, {$IFDEF FPC}@{$ENDIF FPC}SubtractLog);
2: Result := Filter2(Image, offset, FY, FWidth, FHeight, {$IFDEF FPC}@{$ENDIF FPC}SubtractLog);
3: Result := Filter3(Image, offset, FY, FWidth, FHeight, {$IFDEF FPC}@{$ENDIF FPC}SubtractLog);
4: Result := Filter4(Image, offset, FY, FWidth, FHeight, {$IFDEF FPC}@{$ENDIF FPC}SubtractLog);
5: Result := Filter5(Image, offset, FY, FWidth, FHeight, {$IFDEF FPC}@{$ENDIF FPC}SubtractLog);
else
Result := 0.0;
end;
end;
constructor TQuantizer.Create(t0: TLFloat; t1: TLFloat; t2: TLFloat);
begin
inherited Create;
FT0 := t0;
FT1 := t1;
FT2 := t2;
end;
function TQuantizer.Quantize(Value: TLFloat): TLInt;
begin
if (Value < FT1) then
begin
if (Value < FT0) then
Result := 0
else
Result := 1;
end
else
begin
if (Value < FT2) then
Result := 2
else
Result := 3;
end;
end;
constructor TClassifier.Create(Filter: TFilter; Quantizer: TQuantizer);
begin
inherited Create;
if Filter <> nil then
FFilter := Filter
else
FFilter := TFilter.Create(0, 0, 0, 0);
if Quantizer <> nil then
FQuantizer := Quantizer
else
FQuantizer := TQuantizer.Create;
end;
destructor TClassifier.Destroy;
begin
DisposeObject(FFilter);
DisposeObject(FQuantizer);
inherited Destroy;
end;
function TClassifier.Classify(Image: TIntegralImage; offset: TLInt): TLInt;
var
Value: TLFloat;
begin
Value := FFilter.Apply(Image, offset);
Result := FQuantizer.Quantize(Value);
end;
constructor TCombinedBuffer.Create(const Buffer1: TI16Vec; Size1: TLInt; const Buffer2: TI16Vec; Size2: TLInt);
begin
inherited Create;
FOffset := 0;
FBuffer1 := Buffer1;
FBuffer2 := Buffer2;
FSize1 := Size1;
FSize2 := Size2;
end;
destructor TCombinedBuffer.Destroy;
begin
inherited Destroy;
end;
// Gets the size of the combined buffer.
function TCombinedBuffer.Size: TLInt;
begin
Result := FSize1 + FSize2 - FOffset;
end;
// Gets the element at given position.
function TCombinedBuffer.GetValue(i: TLInt): TInt16;
var
k: TLInt;
begin
k := i + FOffset;
if k < FSize1 then
Result := FBuffer1[k]
else
begin
k := k - FSize1;
Result := FBuffer2[k];
end;
end;
// Shift the buffer offset.
function TCombinedBuffer.Shift(Value: TLInt): TLInt;
begin
FOffset := FOffset + Value;
Result := FOffset;
end;
function TCombinedBuffer.Read(var Buffer: TI16Vec; offset, Count: TLInt): TLInt;
var
n: TLInt;
pos: TLInt;
lSplit: TLInt;
begin
pos := FOffset + offset;
if (pos < FSize1) and (pos + Count > FSize1) then
begin
{ read from first and seconde buffer }
// Number of shorts to be read from first buffer
lSplit := FSize1 - pos;
// Number of shorts to be read from second buffer
n := Math.min(Count - lSplit, FSize2);
// Copy from both buffers
CopyPtr(@FBuffer1[pos], @Buffer[0], lSplit * sizeof(TInt16));
CopyPtr(@FBuffer2[0], @Buffer[lSplit], n * sizeof(TInt16));
// Correct total length
n := n + lSplit;
end
else
begin
if pos > FSize1 then
begin
{ read from seconde buffer }
pos := pos - FSize1;
// Number of shorts to be read from second buffer
n := Math.min(Count, FSize2 - pos);
// Read from second buffer
CopyPtr(@FBuffer2[pos], @Buffer[0], n * sizeof(TInt16));
end
else
begin
n := Math.min(Count, FSize1 - pos); // here not safe in C++ and C#
CopyPtr(@FBuffer1[pos], @Buffer[0], n * sizeof(TInt16));
end;
end;
Result := n;
end;
// Read all remaining values from the buffer.
procedure TCombinedBuffer.Flush(var Buffer: TI16Vec);
var
lSize: TLInt;
begin
// Read the whole buffer (offset will be taken care of).
lSize := Size;
if lSize > 0 then
begin
Read(Buffer, 0, lSize);
end;
end;
constructor TFFTFrame.Create(Size: TLInt);
begin
inherited Create;
FSize := Size;
SetLength(Data, FSize);
end;
destructor TFFTFrame.Destroy;
begin
SetLength(Data, 0);
inherited Destroy;
end;
function TFFTFrame.Magnitude(i: TLInt): TLFloat;
begin
Result := Sqrt(Data[i]);
end;
function TFFTFrame.Energy(i: TLInt): TLFloat;
begin
Result := Data[i];
end;
constructor TFFT.Create(frame_size: TLInt; overlap: TLInt; consumer: TFFTFrameConsumer);
var
i: TLInt;
begin
inherited Create;
SetLength(FWindow, frame_size);
FBufferOffset := 0;
SetLength(FFFTBuffer, frame_size);
FFrame := TFFTFrame.Create(frame_size);
FFrameSize := frame_size;
FIncrement := frame_size - overlap;
FConsumer := consumer;
PrepareHammingWindow(FWindow);
for i := 0 to frame_size - 1 do
begin
FWindow[i] := FWindow[i] / $7FFF;
end;
FLib := TFFTLomont.Create(frame_size, FWindow);
end;
destructor TFFT.Destroy;
begin
DisposeObject(FFrame);
DisposeObject(FLib);
SetLength(FFFTBuffer, 0);
SetLength(FWindow, 0);
inherited Destroy;
end;
function TFFT.overlap: TLInt;
begin
Result := FFrameSize - FIncrement;
end;
procedure TFFT.Reset;
begin
FBufferOffset := 0;
end;
procedure TFFT.Consume(Input: TI16Vec; AOffset: TLInt; lLength: TLInt);
var
lCombinedBuffer: TCombinedBuffer;
lBuffer: TI16Vec;
begin
// Special case, just pre-filling the buffer
if (FBufferOffset + lLength < FFrameSize) then
begin
CopyPtr(@Input[0], @FFFTBuffer[FBufferOffset], lLength * sizeof(TInt16));
FBufferOffset := FBufferOffset + lLength;
Exit;
end;
// Apply FFT on the available data
lCombinedBuffer := TCombinedBuffer.Create(FFFTBuffer, FBufferOffset, Input, lLength);
while (lCombinedBuffer.Size >= FFrameSize) do
begin
SetLength(lBuffer, FFrameSize);
lCombinedBuffer.Read(lBuffer, 0, FFrameSize);
FLib.ComputeFrame(lBuffer, FFrame);
FConsumer.Consume(FFrame);
lCombinedBuffer.Shift(FIncrement);
SetLength(lBuffer, 0);
end;
// Copy the remaining input data to the internal buffer
lCombinedBuffer.Flush(FFFTBuffer);
FBufferOffset := lCombinedBuffer.Size();
DisposeObject(lCombinedBuffer);
end;
constructor TFFTLib.Create(frame_size: TLInt; window: TLVec);
begin
inherited Create;
end;
destructor TFFTLib.Destroy;
begin
inherited Destroy;
end;
// Call this with the size before using the FFT
// Fills in tables for speed
procedure TFFTLomont.ComputeTable(Size: TLInt);
var
i, n, mmax, istep, m: TLInt;
theta, wr, wpr, wpi, wi, t: TLFloat;
begin
SetLength(ForwardCos, Size);
SetLength(ForwardSin, Size);
// forward pass
i := 0;
n := Size;
mmax := 1;
while (n > mmax) do
begin
istep := 2 * mmax;
theta := Math_Pi / mmax;
wr := 1;
wi := 0;
wpr := cos(theta);
wpi := Sin(theta);
m := 0;
while m < istep do
begin
ForwardCos[i] := wr;
ForwardSin[i] := wi;
Inc(i);
t := wr;
wr := wr * wpr - wi * wpi;
wi := wi * wpr + t * wpi;
m := m + 2;
end;
mmax := istep;
end;
end;
constructor TFFTLomont.Create(frame_size: TLInt; window: TLVec);
begin
inherited Create(frame_size, window);
FFrameSize := frame_size;
FFrameSizeH := frame_size div 2;
FWindow := window;
SetLength(FInput, frame_size);
ComputeTable(frame_size);
end;
destructor TFFTLomont.Destroy;
begin
SetLength(FInput, 0);
SetLength(FWindow, 0);
SetLength(ForwardCos, 0);
SetLength(ForwardSin, 0);
inherited Destroy;
end;
// Compute the forward or inverse FFT of data, which is
// complex valued items, stored in alternating real and
// imaginary real numbers. The length must be a power of 2.
procedure TFFTLomont.FFT(var Data: TLVec);
var
n, j, top, k, h: TLInt;
t: TLFloat;
mmax, tptr, istep, m: TLInt;
wr, wi, tempr, tempi: TLFloat;
begin
n := Length(Data);
// check all are valid
// checks n is a power of 2 in 2's complement format
if ((n and (n - 1)) <> 0) then
begin
// throw new Exception("data length " + n + " in FFT is not a power of 2");
Exit;
end;
n := n div 2;
// bit reverse the indices. This is exercise 5 in section 7.2.1.1 of Knuth's TAOCP
// the idea is a binary counter in k and one with bits reversed in j
// see also Alan H. Karp, "Bit Reversals on Uniprocessors", SIAM Review, vol. 38, #1, 1--26, March (1996)
// nn = number of samples, 2* this is length of data?
j := 0;
k := 0; // Knuth R1: initialize
top := n div 2; // this is Knuth's 2^(n-1)
while (True) do
begin
// Knuth R2: swap
// swap j+1 and k+2^(n-1) - both have two entries
t := Data[j + 2];
Data[j + 2] := Data[k + n];
Data[k + n] := t;
t := Data[j + 3];
Data[j + 3] := Data[k + n + 1];
Data[k + n + 1] := t;
if (j > k) then
begin // swap two more
// j and k
t := Data[j];
Data[j] := Data[k];
Data[k] := t;
t := Data[j + 1];
Data[j + 1] := Data[k + 1];
Data[k + 1] := t;
// j + top + 1 and k+top + 1
t := Data[j + n + 2];
Data[j + n + 2] := Data[k + n + 2];
Data[k + n + 2] := t;
t := Data[j + n + 3];
Data[j + n + 3] := Data[k + n + 3];
Data[k + n + 3] := t;
end;
// Knuth R3: advance k
k := k + 4;
if (k >= n) then
break;
// Knuth R4: advance j
h := top;
while (j >= h) do
begin
j := j - h;
h := h div 2;
end;
j := j + h;
end; // bit reverse loop
// do transform by doing float transforms, then doubles, fours, etc.
mmax := 1;
tptr := 0;
while (n > mmax) do
begin
istep := 2 * mmax;
m := 0;
while m < istep do
begin
wr := ForwardCos[tptr];
wi := ForwardSin[tptr];
Inc(tptr);
k := m;
while (k < 2 * n) do
begin
j := k + istep;
tempr := wr * Data[j] - wi * Data[j + 1];
tempi := wi * Data[j] + wr * Data[j + 1];
Data[j] := Data[k] - tempr;
Data[j + 1] := Data[k + 1] - tempi;
Data[k] := Data[k] + tempr;
Data[k + 1] := Data[k + 1] + tempi;
k := k + 2 * istep;
end;
Inc(m, 2);
end;
mmax := istep;
end;
end;
// Computes the real FFT.
procedure TFFTLomont.RealFFT(var Data: TLVec);
var
n, j, k: TLInt;
temp, theta, wpr, wpi, wjr, wji: TLFloat;
tnr, tni, tjr, tji: TLFloat;
a, b, c, d, e, f: TLFloat;
begin
FFT(Data); // do packed FFT
n := Length(Data); // number of real input points, which is 1/2 the complex length
theta := 2 * Math_Pi / n;
wpr := cos(theta);
wpi := Sin(theta);
wjr := wpr;
wji := wpi;
for j := 1 to (n div 4) do
begin
k := n div 2 - j;
tnr := Data[2 * k];
tni := Data[2 * k + 1];
tjr := Data[2 * j];
tji := Data[2 * j + 1];
e := (tjr + tnr);
f := (tji - tni);
a := (tjr - tnr) * wji;
d := (tji + tni) * wji;
b := (tji + tni) * wjr;
c := (tjr - tnr) * wjr;
// compute entry y[j]
Data[2 * j] := 0.5 * (e + (a + b));
Data[2 * j + 1] := 0.5 * (f - (c - d));
// compute entry y[k]
Data[2 * k] := 0.5 * (e - (a + b));
Data[2 * k + 1] := 0.5 * ((-c + d) - f);
temp := wjr;
wjr := wjr * wpr - wji * wpi;
wji := temp * wpi + wji * wpr;
end;
// compute final y0 and y_{N/2} ones, place into data[0] and data[1]
temp := Data[0];
Data[0] := Data[0] + Data[1];
Data[1] := temp - Data[1];
end;
procedure TFFTLomont.ComputeFrame(Input: TI16Vec; var frame: TFFTFrame);
var
i: TLInt;
begin
for i := 0 to FFrameSize - 1 do
begin
FInput[i] := Input[i] * FWindow[i] * 1.0;
end;
RealFFT(FInput);
// FInput will now contain the FFT values
// r0, r(n/2), r1, i1, r2, i2 ...
// Compute energy
frame.Data[0] := FInput[0] * FInput[0];
frame.Data[FFrameSizeH] := FInput[1] * FInput[1];
for i := 1 to FFrameSizeH - 1 do
begin
frame.Data[i] := FInput[2 * i] * FInput[2 * i] + FInput[2 * i + 1] * FInput[2 * i + 1];
end;
end;
constructor TChromaFilter.Create(coefficients: TLVec; ALength: TLInt; consumer: TFeatureVectorConsumer);
begin
inherited Create;
SetLength(FResult, 12);
FCoefficients := coefficients;
FLength := ALength;
SetLength(FBuffer, 8);
FBufferOffset := 0;
FBufferSize := 1;
FConsumer := consumer;
end;
destructor TChromaFilter.Destroy;
begin
SetLength(FResult, 0);
FConsumer := nil;
SetLength(FCoefficients, 0);
inherited Destroy;
end;
procedure TChromaFilter.Reset;
begin
FBufferSize := 1;
FBufferOffset := 0;
end;
procedure TChromaFilter.Consume(var features: TLVec);
var
offset: TLInt;
i, j: TLInt;
begin
SetLength(FBuffer[FBufferOffset], Length(features));
for i := 0 to Length(features) - 1 do
begin
FBuffer[FBufferOffset, i] := features[i];
end;
FBufferOffset := (FBufferOffset + 1) mod 8;
if (FBufferSize >= FLength) then
begin
offset := (FBufferOffset + 8 - FLength) mod 8;
for i := 0 to Length(FResult) - 1 do
begin
FResult[i] := 0.0;
end;
for i := 0 to 11 do
begin
for j := 0 to FLength - 1 do
begin
FResult[i] := FResult[i] + FBuffer[(offset + j) mod 8, i] * FCoefficients[j];
end;
end;
FConsumer.Consume(FResult);
end
else
begin
Inc(FBufferSize);
end;
end;
constructor TFeatureVectorConsumer.Create;
begin
inherited Create;
end;
destructor TFeatureVectorConsumer.Destroy;
begin
inherited Destroy;
end;
constructor TImageBuilder.Create(Image: TCPImage);
begin
inherited Create;
FImage := Image;
end;
destructor TImageBuilder.Destroy;
begin
FImage := nil;
inherited Destroy;
end;
procedure TImageBuilder.Reset(Image: TCPImage);
begin
FImage := Image;
end;
procedure TImageBuilder.Consume(var features: TLVec);
begin
FImage.AddRow(features);
end;
constructor TChromaNormalizer.Create(consumer: TFeatureVectorConsumer);
begin
inherited Create;
FConsumer := consumer;
end;
destructor TChromaNormalizer.Destroy;
begin
FConsumer := nil;
inherited Destroy;
end;
procedure TChromaNormalizer.Reset;
begin
end;
procedure TChromaNormalizer.Consume(var features: TLVec);
var
norm: TLFloat;
begin
norm := EuclideanNorm(features);
NormalizeVector(features, norm, 0.01);
FConsumer.Consume(features);
end;
constructor TChromaResampler.Create(factor: TLInt; consumer: TFeatureVectorConsumer);
begin
inherited Create;
SetLength(FResult, 12);
Reset;
FFactor := factor;
FConsumer := consumer;
end;
destructor TChromaResampler.Destroy;
begin
SetLength(FResult, 0);
inherited Destroy;
end;
procedure TChromaResampler.Reset;
var
i: TLInt;
begin
FIteration := 0;
for i := 0 to Length(FResult) - 1 do
begin
FResult[i] := 0.0;
end;
end;
procedure TChromaResampler.Consume(var features: TLVec);
var
i: TLInt;
begin
for i := 0 to 11 do
LAdd(FResult[i], features[i]);
Inc(FIteration);
if (FIteration = FFactor) then
begin
for i := 0 to 11 do
LDiv(FResult[i], FFactor);
FConsumer.Consume(FResult);
Reset();
end;
end;
constructor TFingerprintCalculator.Create(classifiers: TClassifierArray);
var
i: TLInt;
n: TLInt;
begin
inherited Create;
FClassifiers := classifiers;
n := Length(FClassifiers);
FMaxFilterWidth := 0;
for i := 0 to n - 1 do
begin
FMaxFilterWidth := Math.Max(FMaxFilterWidth, FClassifiers[i].FFilter.FWidth);
end;
end;
destructor TFingerprintCalculator.Destroy;
begin
inherited Destroy;
end;
function TFingerprintCalculator.Calculate(Image: TCPImage): TU32Vec;
var
lLength: TLInt;
i: TLInt;
lIntegralImage: TIntegralImage;
begin
lLength := Image.NumRows - FMaxFilterWidth + 1;
if (lLength <= 0) then
begin
Result := nil;
Exit;
end;
lIntegralImage := TIntegralImage.Create(Image);
SetLength(Result, lLength);
for i := 0 to lLength - 1 do
begin
Result[i] := CalculateSubfingerprint(lIntegralImage, i);
end;
DisposeObject(lIntegralImage);
end;
function TFingerprintCalculator.CalculateSubfingerprint(Image: TIntegralImage; offset: TLInt): TUInt32;
var
bits: TUInt32;
i: TLInt;
n: TLInt;
begin
bits := 0;
n := Length(FClassifiers);
for i := 0 to n - 1 do
begin
bits := (bits shl 2) or CODES[TClassifierArray(FClassifiers)[i].Classify(Image, offset)];
end;
Result := bits;
end;
function CompressFingerprint(Data: TU32Vec; algorithm: TLInt = 0): TPascalString;
var
compressor: TFingerprintCompressor;
begin
compressor := TFingerprintCompressor.Create;
try
Result := compressor.Compress(Data, algorithm);
finally
DisposeObject(compressor);
end;
end;
function DecompressFingerprint(Data: TPascalString; var algorithm: TLInt): TU32Vec;
var
decompressor: TFingerprintDecompressor;
begin
decompressor := TFingerprintDecompressor.Create;
try
Result := decompressor.Decompress(Data, algorithm);
finally
DisposeObject(decompressor);
end;
end;
constructor TFingerprintCompressor.Create;
begin
inherited Create;
end;
procedure TFingerprintCompressor.ProcessSubfingerprint(x: TUInt32);
var
bit, last_bit, n: TLInt;
begin
bit := 1;
last_bit := 0;
while (x <> 0) do
begin
if ((x and 1) <> 0) then
begin
n := Length(FBits);
SetLength(FBits, n + 1);
FBits[n] := (bit - last_bit);
last_bit := bit;
end;
x := x shr 1;
Inc(bit);
end;
n := Length(FBits);
SetLength(FBits, n + 1);
FBits[n] := 0;
end;
procedure TFingerprintCompressor.WriteExceptionBits;
var
writer: TBitStringWriter;
i: TLInt;
begin
writer := TBitStringWriter.Create;
for i := 0 to Length(FBits) - 1 do
if (FBits[i] >= kMaxNormalValue) then
writer.Write(FBits[i] - kMaxNormalValue, kExceptionBits);
writer.Flush();
FResult.Append(writer.FValue);
DisposeObject(writer);
end;
procedure TFingerprintCompressor.WriteNormalBits;
var
writer: TBitStringWriter;
i: TLInt;
begin
writer := TBitStringWriter.Create;
for i := 0 to Length(FBits) - 1 do
writer.Write(Math.min(FBits[i], kMaxNormalValue), kNormalBits);
writer.Flush();
FResult.Append(writer.FValue);
DisposeObject(writer);
end;
function TFingerprintCompressor.Compress(var fingerprint: TU32Vec; algorithm: TLInt = 0): TPascalString;
var
i, n: TLInt;
begin
n := Length(fingerprint);
if n > 0 then
begin
ProcessSubfingerprint(fingerprint[0]);
for i := 1 to n - 1 do
ProcessSubfingerprint(fingerprint[i] xor fingerprint[i - 1]);
end;
FResult := chr(algorithm and 255);
FResult.Append(chr((n shr 16) and 255));
FResult.Append(chr((n shr 8) and 255));
FResult.Append(chr(n and 255));
WriteNormalBits();
WriteExceptionBits();
Result := FResult;
end;
constructor TFingerprintDecompressor.Create;
begin
inherited Create;
end;
function TFingerprintDecompressor.Decompress(fingerprint: TPascalString; var algorithm: TLInt): TU32Vec;
var
n: TLInt;
reader: TBitStringReader;
begin
SetLength(Result, 0);
if fingerprint.len < 4 then
begin
DoStatus('FingerprintDecompressor::Decompress() -- Invalid fingerprint (shorter than 4 bytes)');
Exit;
end;
if algorithm <> 0 then
algorithm := Ord(fingerprint[1]);
n := (Ord(fingerprint[2]) shl 16) or (Ord(fingerprint[3]) shl 8) or (Ord(fingerprint[4]));
reader := TBitStringReader.Create(fingerprint);
reader.Read(8);
reader.Read(8);
reader.Read(8);
reader.Read(8);
if (reader.AvailableBits < n * kNormalBits) then
begin
DoStatus('FingerprintDecompressor::Decompress() -- Invalid fingerprint (too short)');
DisposeObject(reader);
Exit;
end;
SetLength(FResult, n);
reader.Reset();
if (not ReadNormalBits(reader)) then
begin
DisposeObject(reader);
Exit;
end;
reader.Reset();
if (not ReadExceptionBits(reader)) then
begin
DisposeObject(reader);
Exit;
end;
UnpackBits();
Result := FResult;
end;
function TFingerprintDecompressor.ReadExceptionBits(reader: TBitStringReader): boolean;
var
i: TLInt;
begin
for i := 0 to Length(FBits) - 1 do
begin
if (FBits[i] = kMaxNormalValue) then
begin
if (reader.EOF) then
begin
DoStatus('FingerprintDecompressor.ReadExceptionBits() -- Invalid fingerprint (reached EOF while reading exception bits)');
Result := False;
Exit;
end;
FBits[i] := FBits[i] + reader.Read(kExceptionBits);
end;
end;
Result := True;
end;
function TFingerprintDecompressor.ReadNormalBits(reader: TBitStringReader): boolean;
var
i, bit, n: TLInt;
begin
i := 0;
while (i < Length(FResult)) do
begin
bit := reader.Read(kNormalBits);
if (bit = 0) then
Inc(i);
n := Length(FBits);
SetLength(FBits, n + 1);
FBits[n] := bit;
end;
Result := True;
end;
procedure TFingerprintDecompressor.UnpackBits;
var
i, last_bit, j, bit: TLInt;
Value: TUInt32;
begin
i := 0;
last_bit := 0;
Value := 0;
for j := 0 to Length(FBits) - 1 do
begin
bit := FBits[j];
if (bit = 0) then
begin
if (i > 0) then
FResult[i] := Value xor FResult[i - 1]
else
FResult[i] := Value;
Value := 0;
last_bit := 0;
Inc(i);
continue;
end;
bit := bit + last_bit;
last_bit := bit;
Value := Value or (1 shl (bit - 1));
end;
end;
function CreateFingerprinterConfiguration(algorithm: TAudioprintAlgorithm): TFingerprinterConfiguration;
begin
case (algorithm) of
Audioprint_ALGORITHM1: Result := TFingerprinterConfigurationTest1.Create;
Audioprint_ALGORITHM2: Result := TFingerprinterConfigurationTest2.Create;
Audioprint_ALGORITHM3: Result := TFingerprinterConfigurationTest3.Create;
Audioprint_ALGORITHM4: Result := TFingerprinterConfigurationTest4.Create;
else
Result := nil;
end;
end;
constructor TFingerprinterConfigurationTest4.Create;
begin
inherited Create;
FRemoveSilence := True;
FSilenceThreshold := 50;
end;
destructor TFingerprinterConfigurationTest4.Destroy;
begin
inherited Destroy;
end;
constructor TFingerprinterConfigurationTest3.Create;
var
kClassifiersTest: TClassifierArray;
begin
inherited Create;
SetLength(kClassifiersTest, 16);
kClassifiersTest[0] := TClassifier.Create(TFilter.Create(0, 4, 3, 15), TQuantizer.Create(1.98215, 2.35817, 2.63523));
kClassifiersTest[1] := TClassifier.Create(TFilter.Create(4, 4, 6, 15), TQuantizer.Create(-1.03809, -0.651211, -0.282167));
kClassifiersTest[2] := TClassifier.Create(TFilter.Create(1, 0, 4, 16), TQuantizer.Create(-0.298702, 0.119262, 0.558497));
kClassifiersTest[3] := TClassifier.Create(TFilter.Create(3, 8, 2, 12), TQuantizer.Create(-0.105439, 0.0153946, 0.135898));
kClassifiersTest[4] := TClassifier.Create(TFilter.Create(3, 4, 4, 8), TQuantizer.Create(-0.142891, 0.0258736, 0.200632));
kClassifiersTest[5] := TClassifier.Create(TFilter.Create(4, 0, 3, 5), TQuantizer.Create(-0.826319, -0.590612, -0.368214));
kClassifiersTest[6] := TClassifier.Create(TFilter.Create(1, 2, 2, 9), TQuantizer.Create(-0.557409, -0.233035, 0.0534525));
kClassifiersTest[7] := TClassifier.Create(TFilter.Create(2, 7, 3, 4), TQuantizer.Create(-0.0646826, 0.00620476, 0.0784847));
kClassifiersTest[8] := TClassifier.Create(TFilter.Create(2, 6, 2, 16), TQuantizer.Create(-0.192387, -0.029699, 0.215855));
kClassifiersTest[9] := TClassifier.Create(TFilter.Create(2, 1, 3, 2), TQuantizer.Create(-0.0397818, -0.00568076, 0.0292026));
kClassifiersTest[10] := TClassifier.Create(TFilter.Create(5, 10, 1, 15), TQuantizer.Create(-0.53823, -0.369934, -0.190235));
kClassifiersTest[11] := TClassifier.Create(TFilter.Create(3, 6, 2, 10), TQuantizer.Create(-0.124877, 0.0296483, 0.139239));
kClassifiersTest[12] := TClassifier.Create(TFilter.Create(2, 1, 1, 14), TQuantizer.Create(-0.101475, 0.0225617, 0.231971));
kClassifiersTest[13] := TClassifier.Create(TFilter.Create(3, 5, 6, 4), TQuantizer.Create(-0.0799915, -0.00729616, 0.063262));
kClassifiersTest[14] := TClassifier.Create(TFilter.Create(1, 9, 2, 12), TQuantizer.Create(-0.272556, 0.019424, 0.302559));
kClassifiersTest[15] := TClassifier.Create(TFilter.Create(3, 4, 2, 14), TQuantizer.Create(-0.164292, -0.0321188, 0.0846339));
SetClassifiers(kClassifiersTest);
SetFilterCoefficients(kChromaFilterCoefficients);
FInterpolate := True;
end;
destructor TFingerprinterConfigurationTest3.Destroy;
begin
inherited Destroy;
end;
constructor TFingerprinterConfigurationTest2.Create;
var
kClassifiersTest: TClassifierArray;
begin
inherited Create;
SetLength(kClassifiersTest, 16);
kClassifiersTest[0] := TClassifier.Create(TFilter.Create(0, 4, 3, 15), TQuantizer.Create(1.98215, 2.35817, 2.63523));
kClassifiersTest[1] := TClassifier.Create(TFilter.Create(4, 4, 6, 15), TQuantizer.Create(-1.03809, -0.651211, -0.282167));
kClassifiersTest[2] := TClassifier.Create(TFilter.Create(1, 0, 4, 16), TQuantizer.Create(-0.298702, 0.119262, 0.558497));
kClassifiersTest[3] := TClassifier.Create(TFilter.Create(3, 8, 2, 12), TQuantizer.Create(-0.105439, 0.0153946, 0.135898));
kClassifiersTest[4] := TClassifier.Create(TFilter.Create(3, 4, 4, 8), TQuantizer.Create(-0.142891, 0.0258736, 0.200632));
kClassifiersTest[5] := TClassifier.Create(TFilter.Create(4, 0, 3, 5), TQuantizer.Create(-0.826319, -0.590612, -0.368214));
kClassifiersTest[6] := TClassifier.Create(TFilter.Create(1, 2, 2, 9), TQuantizer.Create(-0.557409, -0.233035, 0.0534525));
kClassifiersTest[7] := TClassifier.Create(TFilter.Create(2, 7, 3, 4), TQuantizer.Create(-0.0646826, 0.00620476, 0.0784847));
kClassifiersTest[8] := TClassifier.Create(TFilter.Create(2, 6, 2, 16), TQuantizer.Create(-0.192387, -0.029699, 0.215855));
kClassifiersTest[9] := TClassifier.Create(TFilter.Create(2, 1, 3, 2), TQuantizer.Create(-0.0397818, -0.00568076, 0.0292026));
kClassifiersTest[10] := TClassifier.Create(TFilter.Create(5, 10, 1, 15), TQuantizer.Create(-0.53823, -0.369934, -0.190235));
kClassifiersTest[11] := TClassifier.Create(TFilter.Create(3, 6, 2, 10), TQuantizer.Create(-0.124877, 0.0296483, 0.139239));
kClassifiersTest[12] := TClassifier.Create(TFilter.Create(2, 1, 1, 14), TQuantizer.Create(-0.101475, 0.0225617, 0.231971));
kClassifiersTest[13] := TClassifier.Create(TFilter.Create(3, 5, 6, 4), TQuantizer.Create(-0.0799915, -0.00729616, 0.063262));
kClassifiersTest[14] := TClassifier.Create(TFilter.Create(1, 9, 2, 12), TQuantizer.Create(-0.272556, 0.019424, 0.302559));
kClassifiersTest[15] := TClassifier.Create(TFilter.Create(3, 4, 2, 14), TQuantizer.Create(-0.164292, -0.0321188, 0.0846339));
SetClassifiers(kClassifiersTest);
SetFilterCoefficients(kChromaFilterCoefficients);
FInterpolate := False;
end;
destructor TFingerprinterConfigurationTest2.Destroy;
begin
inherited Destroy;
end;
constructor TFingerprinterConfigurationTest1.Create;
var
kClassifiersTest: TClassifierArray;
begin
inherited Create;
SetLength(kClassifiersTest, 16);
kClassifiersTest[0] := TClassifier.Create(TFilter.Create(0, 0, 3, 15), TQuantizer.Create(2.10543, 2.45354, 2.69414));
kClassifiersTest[1] := TClassifier.Create(TFilter.Create(1, 0, 4, 14), TQuantizer.Create(-0.345922, 0.0463746, 0.446251));
kClassifiersTest[2] := TClassifier.Create(TFilter.Create(1, 4, 4, 11), TQuantizer.Create(-0.392132, 0.0291077, 0.443391));
kClassifiersTest[3] := TClassifier.Create(TFilter.Create(3, 0, 4, 14), TQuantizer.Create(-0.192851, 0.00583535, 0.204053));
kClassifiersTest[4] := TClassifier.Create(TFilter.Create(2, 8, 2, 4), TQuantizer.Create(-0.0771619, -0.00991999, 0.0575406));
kClassifiersTest[5] := TClassifier.Create(TFilter.Create(5, 6, 2, 15), TQuantizer.Create(-0.710437, -0.518954, -0.330402));
kClassifiersTest[6] := TClassifier.Create(TFilter.Create(1, 9, 2, 16), TQuantizer.Create(-0.353724, -0.0189719, 0.289768));
kClassifiersTest[7] := TClassifier.Create(TFilter.Create(3, 4, 2, 10), TQuantizer.Create(-0.128418, -0.0285697, 0.0591791));
kClassifiersTest[8] := TClassifier.Create(TFilter.Create(3, 9, 2, 16), TQuantizer.Create(-0.139052, -0.0228468, 0.0879723));
kClassifiersTest[9] := TClassifier.Create(TFilter.Create(2, 1, 3, 6), TQuantizer.Create(-0.133562, 0.00669205, 0.155012));
kClassifiersTest[10] := TClassifier.Create(TFilter.Create(3, 3, 6, 2), TQuantizer.Create(-0.0267, 0.00804829, 0.0459773));
kClassifiersTest[11] := TClassifier.Create(TFilter.Create(2, 8, 1, 10), TQuantizer.Create(-0.0972417, 0.0152227, 0.129003));
kClassifiersTest[12] := TClassifier.Create(TFilter.Create(3, 4, 4, 14), TQuantizer.Create(-0.141434, 0.00374515, 0.149935));
kClassifiersTest[13] := TClassifier.Create(TFilter.Create(5, 4, 2, 15), TQuantizer.Create(-0.64035, -0.466999, -0.285493));
kClassifiersTest[14] := TClassifier.Create(TFilter.Create(5, 9, 2, 3), TQuantizer.Create(-0.322792, -0.254258, -0.174278));
kClassifiersTest[15] := TClassifier.Create(TFilter.Create(2, 1, 8, 4), TQuantizer.Create(-0.0741375, -0.00590933, 0.0600357));
SetClassifiers(kClassifiersTest);
SetFilterCoefficients(kChromaFilterCoefficients);
FInterpolate := False;
end;
destructor TFingerprinterConfigurationTest1.Destroy;
begin
inherited Destroy;
end;
constructor TFingerprinterConfiguration.Create;
begin
FNumClassifiers := 0;
FClassifiers := nil;
FRemoveSilence := False;
FSilenceThreshold := 0;
SetLength(kChromaFilterCoefficients, kChromaFilterSize);
kChromaFilterCoefficients[0] := 0.25;
kChromaFilterCoefficients[1] := 0.75;
kChromaFilterCoefficients[2] := 1.0;
kChromaFilterCoefficients[3] := 0.75;
kChromaFilterCoefficients[4] := 0.25;
end;
destructor TFingerprinterConfiguration.Destroy;
var
i: TLInt;
begin
for i := 0 to Length(FClassifiers) - 1 do
begin
DisposeObject(FClassifiers[i]);
end;
inherited Destroy;
end;
procedure TFingerprinterConfiguration.SetClassifiers(classifiers: TClassifierArray);
begin
FClassifiers := classifiers;
FNumClassifiers := Length(classifiers);
end;
procedure TFingerprinterConfiguration.SetFilterCoefficients(FilterCoefficients: TLVec);
begin
FFilterCoefficients := FilterCoefficients;
FNumFilterCoefficients := Length(FilterCoefficients);
end;
constructor TMovingAverage.Create(Size: TLInt);
var
i: TLInt;
begin
FSize := Size;
FOffset := 0;
FSum := 0;
FCount := 0;
SetLength(FBuffer, FSize);
for i := 0 to FSize - 1 do
begin
FBuffer[i] := 0;
end;
end;
destructor TMovingAverage.Destroy;
begin
SetLength(FBuffer, 0);
inherited Destroy;
end;
procedure TMovingAverage.AddValue(const x: TInt16);
begin
FSum := FSum + x;
FSum := FSum - FBuffer[FOffset];
if (FCount < FSize) then
begin
Inc(FCount);
end;
FBuffer[FOffset] := x;
FOffset := (FOffset + 1) mod FSize;
end;
function TMovingAverage.GetAverage: TInt16;
begin
if (FCount = 0) then
begin
Result := 0;
Exit;
end;
Result := FSum div FCount;
end;
constructor TSilenceRemover.Create(consumer: TAudioConsumer; Threshold: TLInt);
begin
FStart := True;
FThreshold := Threshold;
FAverage := TMovingAverage.Create(kSilenceWindow);
FConsumer := consumer;
end;
destructor TSilenceRemover.Destroy;
begin
DisposeObject(FAverage);
inherited Destroy;
end;
function TSilenceRemover.Reset(Sample_Rate, NumChannels: TLInt): boolean;
begin
if NumChannels <> 1 then
begin
Result := False;
Exit;
end;
FStart := True;
Result := True;
end;
procedure TSilenceRemover.Flush;
begin
end;
procedure TSilenceRemover.Consume(Input: TI16Vec; AOffset: TLInt; Length: TLInt);
var
offset, n: TLInt;
begin
offset := 0;
n := Length;
if (FStart) then
begin
while (n > 0) do
begin
FAverage.AddValue(Abs(Input[offset]));
if (FAverage.GetAverage() > FThreshold) then
begin
FStart := False;
break;
end;
Inc(offset);
dec(n);
end;
end;
if (n > 0) then
begin
FConsumer.Consume(Input, offset, Length);
end;
end;
procedure TAudioProcessor.Resample;
var
consumed, lLength: TLInt;
remaining: TLInt;
begin
// coding C++ is a pain
if (FResampleCTX = nil) then
begin
FConsumer.Consume(FBuffer, 0, FBufferOffset);
FBufferOffset := 0;
Exit;
end;
consumed := 0;
lLength := FResampleCTX^.Resample(FResampleBuffer, FBuffer, consumed, FBufferOffset, kMaxBufferSize, 1);
if (lLength > kMaxBufferSize) then
begin
DoStatus('Audioprint::AudioProcessor::Resample() -- Resampling overwrote output buffer.');
lLength := kMaxBufferSize;
end;
FConsumer.Consume(FResampleBuffer, 0, lLength); // do the FFT now
remaining := FBufferOffset - consumed;
if (remaining > 0) then
begin
CopyPtr(@FBuffer[consumed], @FBuffer[0], remaining * sizeof(TInt16));
end
else if (remaining < 0) then
begin
DoStatus('Audioprint::AudioProcessor::Resample() -- Resampling overread input buffer.');
remaining := 0;
end;
FBufferOffset := remaining;
end;
function TAudioProcessor.Load(Input: TI16Vec; offset: TLInt; ALength: TLInt): TLInt;
var
lLength: TLInt;
begin
lLength := Math.min(ALength, FBufferSize - FBufferOffset);
case (FNumChannels) of
1: LoadMono(Input, offset, lLength);
2: LoadStereo(Input, offset, lLength);
else
LoadMultiChannel(Input, offset, lLength);
end;
FBufferOffset := FBufferOffset + lLength;
Result := lLength;
end;
procedure TAudioProcessor.LoadMono(Input: TI16Vec; offset: TLInt; ALength: TLInt);
var
i: TLInt;
begin
i := FBufferOffset;
while ALength > 0 do
begin
FBuffer[i] := Input[offset];
Inc(offset);
Inc(i);
dec(ALength);
end;
end;
procedure TAudioProcessor.LoadStereo(Input: TI16Vec; offset: TLInt; ALength: TLInt);
var
i: TLInt;
begin
i := FBufferOffset;
while (ALength > 0) do
begin
FBuffer[i] := (Input[offset] + Input[offset + 1]) div 2;
Inc(i);
Inc(offset, 2);
dec(ALength);
end;
end;
procedure TAudioProcessor.LoadMultiChannel(Input: TI16Vec; offset: TLInt; ALength: TLInt);
var
sum: TLInt;
i, j: TLInt;
begin
i := FBufferOffset;
while ALength > 0 do
begin
sum := 0;
for j := 0 to FNumChannels - 1 do
begin
sum := sum + Input[offset];
Inc(offset);
end;
FBuffer[i] := sum div FNumChannels;
Inc(i);
dec(ALength);
end;
end;
constructor TAudioProcessor.Create(SampleRate: TLInt; consumer: TAudioConsumer);
begin
FBufferSize := kMaxBufferSize;
FTargetSampleRate := SampleRate;
FConsumer := consumer;
FResampleCTX := nil;
SetLength(FBuffer, kMaxBufferSize);
FBufferOffset := 0;
SetLength(FResampleBuffer, kMaxBufferSize);
end;
destructor TAudioProcessor.Destroy;
begin
if FResampleCTX <> nil then
Dispose(FResampleCTX);
SetLength(FBuffer, 0);
SetLength(FResampleBuffer, 0);
inherited Destroy;
end;
function TAudioProcessor.Reset(SampleRate, NumChannels: TLInt): boolean;
begin
if (NumChannels <= 0) then
begin
DoStatus('Audioprint::AudioProcessor::Reset() -- No audio channels.');
Result := False;
Exit;
end;
if (SampleRate <= kMinSampleRate) then
begin
DoStatus('Audioprint::AudioProcessor::Reset() -- Sample rate less than 0 1, kMinSampleRate, sample_rate');
Result := False;
Exit;
end;
FBufferOffset := 0;
if (FResampleCTX <> nil) then
begin
Dispose(FResampleCTX);
FResampleCTX := nil;
end;
if (SampleRate <> FTargetSampleRate) then
begin
FResampleCTX := New(PAVResampleContext);
FResampleCTX^.Clear;
FResampleCTX^.Init(FTargetSampleRate, SampleRate, kResampleFilterLength, kResamplePhaseCount, kResampleLinear, kResampleCutoff);
end;
FNumChannels := NumChannels;
Result := True;
end;
procedure TAudioProcessor.Flush;
begin
if (FBufferOffset <> 0) then
Resample();
end;
procedure TAudioProcessor.Consume(Input: TI16Vec; AOffset: TLInt; ALength: TLInt);
var
offset, consumed: TLInt;
lLength: TLInt;
begin
lLength := ALength div FNumChannels;
offset := 0;
while (lLength > 0) do
begin
consumed := Load(Input, offset, lLength);
offset := offset + consumed * FNumChannels;
lLength := lLength - consumed;
if (FBufferSize = FBufferOffset) then
begin
Resample();
if (FBufferSize = FBufferOffset) then
begin
// DEBUG("Audioprint::AudioProcessor::Consume() -- Resampling failed?");
Exit;
end;
end;
end;
end;
procedure TChroma.PrepareNotes(min_freq, max_freq, frame_size, Sample_Rate: TLInt);
var
i: TLInt;
freq, octave, note: TLFloat;
cn: Byte;
begin
FMinIndex := Math.Max(1, FreqToIndex(min_freq, frame_size, Sample_Rate));
FMaxIndex := Math.min(frame_size div 2, FreqToIndex(max_freq, frame_size, Sample_Rate));
for i := FMinIndex to FMaxIndex - 1 do
begin
freq := IndexToFreq(i, frame_size, Sample_Rate);
octave := FreqToOctave(freq, 440.0 / 16.0);
note := NUM_BANDS * (octave - floor(octave));
cn := Byte(trunc(note));
FNotes[i] := cn;
FNotesFrac[i] := note - FNotes[i];
end;
end;
constructor TChroma.Create(min_freq, max_freq, frame_size, Sample_Rate: TLInt; consumer: TFeatureVectorConsumer);
begin
FInterpolate := False;
SetLength(FNotes, frame_size);
SetLength(FNotesFrac, frame_size);
SetLength(FFeatures, NUM_BANDS);
FConsumer := consumer;
PrepareNotes(min_freq, max_freq, frame_size, Sample_Rate);
end;
destructor TChroma.Destroy;
begin
SetLength(FNotes, 0);
SetLength(FNotesFrac, 0);
SetLength(FFeatures, 0);
FConsumer := nil;
inherited Destroy;
end;
procedure TChroma.Reset;
begin
end;
procedure TChroma.Consume(frame: TFFTFrame);
var
lNote, i, lNote2, n: TLInt;
lEnergy, a: TLFloat;
begin
n := Length(FFeatures);
for i := 0 to n - 1 do
begin
FFeatures[i] := 0.0;
end;
for i := FMinIndex to FMaxIndex - 1 do
begin
lNote := FNotes[i];
lEnergy := frame.Energy(i);
if (FInterpolate) then
begin
lNote2 := lNote;
a := 1.0;
if (FNotesFrac[i] < 0.5) then
begin
lNote2 := (lNote + NUM_BANDS - 1) mod NUM_BANDS;
a := 0.5 + FNotesFrac[i];
end;
if (FNotesFrac[i] > 0.5) then
begin
lNote2 := (lNote + 1) mod NUM_BANDS;
a := 1.5 - FNotesFrac[i];
end;
FFeatures[lNote] := FFeatures[lNote] + lEnergy * a;
FFeatures[lNote2] := FFeatures[lNote2] + lEnergy * (1.0 - a);
end
else
begin
FFeatures[lNote] := FFeatures[lNote] + lEnergy;
end;
end;
FConsumer.Consume(FFeatures);
end;
constructor TFingerprinter.Create(config: TFingerprinterConfiguration);
begin
FImage := TCPImage.Create(12, 0);
if (config = nil) then
config := TFingerprinterConfigurationTest1.Create;
FImageBuilder := TImageBuilder.Create(FImage);
FChromaNormalizer := TChromaNormalizer.Create(FImageBuilder);
FChromaFilter := TChromaFilter.Create(config.FFilterCoefficients, config.FNumFilterCoefficients, FChromaNormalizer);
FChroma := TChroma.Create(cMIN_FREQ, cMAX_FREQ, cFRAME_SIZE, cSAMPLE_RATE, FChromaFilter);
FFFT := TFFT.Create(cFRAME_SIZE, cOVERLAP, FChroma);
if (config.FRemoveSilence) then
begin
FSilenceRemover := TSilenceRemover.Create(FFFT);
FSilenceRemover.FThreshold := config.FSilenceThreshold;
FAudioProcessor := TAudioProcessor.Create(cSAMPLE_RATE, FSilenceRemover);
end
else
begin
FSilenceRemover := nil;
FAudioProcessor := TAudioProcessor.Create(cSAMPLE_RATE, FFFT);
end;
FFingerprintCalculator := TFingerprintCalculator.Create(config.FClassifiers);
FConfig := config;
end;
destructor TFingerprinter.Destroy;
begin
DisposeObject(FConfig);
DisposeObject(FFingerprintCalculator);
DisposeObject(FAudioProcessor);
if (FSilenceRemover <> nil) then
DisposeObject(FSilenceRemover);
DisposeObject(FFFT);
DisposeObject(FChroma);
DisposeObject(FChromaFilter);
DisposeObject(FChromaNormalizer);
DisposeObject(FImageBuilder);
DisposeObject(FImage);
inherited Destroy;
end;
function TFingerprinter.SetOption(const Name: TPascalString; Value: TLInt): boolean;
begin
Result := False;
if Name.Same('silence_threshold') then
begin
if (FSilenceRemover <> nil) then
begin
FSilenceRemover.FThreshold := Value;
Result := True;
end;
end;
end;
function TFingerprinter.Start(Sample_Rate, NumChannels: TLInt): boolean;
begin
if (not FAudioProcessor.Reset(Sample_Rate, NumChannels)) then
begin
// FIXME save error message somewhere
Result := False;
Exit;
end;
FFFT.Reset();
FChroma.Reset();
FChromaFilter.Reset();
FChromaNormalizer.Reset();
if FImage <> nil then
DisposeObject(FImage);
FImage := TCPImage.Create(12);
FImageBuilder.Reset(FImage);
Result := True;
end;
function TFingerprinter.Finish: TU32Vec;
begin
FAudioProcessor.Flush();
Result := FFingerprintCalculator.Calculate(FImage);
end;
procedure TFingerprinter.Consume(Input: TI16Vec; AOffset: TLInt; len: TLInt);
begin
FAudioProcessor.Consume(Input, AOffset, len);
end;
constructor TAudioprint.Create;
begin
inherited Create;
end;
destructor TAudioprint.Destroy;
begin
SetLength(ctx.fingerprint, 0);
if ctx.Engine <> nil then
DisposeObject(ctx.Engine);
inherited Destroy;
end;
function TAudioprint.NewAlgorithm(algorithm: TAudioprintAlgorithm): boolean;
begin
SetLength(ctx.fingerprint, 0);
ctx.algorithm := algorithm;
if ctx.Engine <> nil then
DisposeObject(ctx.Engine);
ctx.Engine := TFingerprinter.Create(CreateFingerprinterConfiguration(ctx.algorithm));
Result := ctx.Engine <> nil;
end;
function TAudioprint.GetAlgorithm: TAudioprintAlgorithm;
begin
Result := ctx.algorithm;
end;
function TAudioprint.SetOption(const Name: TPascalString; Value: TLInt): boolean;
begin
Result := TFingerprinter(ctx.Engine).SetOption(Name, Value);
end;
function TAudioprint.Start(Sample_Rate: TLInt; NumChannels: TLInt): boolean;
begin
Result := TFingerprinter(ctx.Engine).Start(Sample_Rate, NumChannels);
end;
function TAudioprint.Feed(Data: TI16Vec; len: TLInt): boolean;
begin
// data: raw audio data, should point to an array of 16-bit signed integers in native byte-order
TFingerprinter(ctx.Engine).Consume(Data, 0, len);
Result := True;
end;
function TAudioprint.Finish: boolean;
begin
ctx.fingerprint := TFingerprinter(ctx.Engine).Finish;
Result := True;
end;
function TAudioprint.GetFingerprint(var fingerprint: TPascalString): boolean;
begin
umlEncodeLineBASE64(CompressFingerprint(ctx.fingerprint, Ord(ctx.algorithm)), fingerprint);
Result := True;
end;
function TAudioprint.GetCompressionFingerprint(var fingerprint: TPascalString): boolean;
begin
fingerprint := CompressFingerprint(ctx.fingerprint, Ord(ctx.algorithm));
Result := True;
end;
function TAudioprint.GetRawFingerprint(var fingerprint: TU32Vec; var Size: TLInt): boolean;
begin
SetLength(fingerprint, Length(ctx.fingerprint));
CopyPtr(@ctx.fingerprint[0], @fingerprint[0], sizeof(TUInt32) * Length(ctx.fingerprint));
Size := Length(ctx.fingerprint);
Result := True;
end;
procedure TAudioprint.EnocdeFingerprint(RawFP: TU32Vec; algorithm: TLInt; var EncodedFP: TPascalString; var EncodedSize: TLInt; Base64: boolean);
var
compressed: TPascalString;
begin
compressed := CompressFingerprint(RawFP, algorithm);
if not Base64 then
begin
EncodedFP := compressed;
EncodedSize := EncodedFP.len;
end
else
begin
umlEncodeLineBASE64(compressed, EncodedFP);
EncodedSize := EncodedFP.len;
end;
end;
procedure TAudioprint.DecodeFingerprint(encoded: TPascalString; var uncompressed: TU32Vec; var algorithm: TLInt; Base64: boolean);
var
lCompressed: TPascalString;
begin
if Base64 then
umlDecodeLineBASE64(encoded, lCompressed)
else
lCompressed := encoded;
uncompressed := DecompressFingerprint(lCompressed, algorithm);
end;
end.
|
{ ********************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ Component and Property Editor Source }
{ }
{ Copyright (C) 2000, 2001 Borland Software Corporation }
{ All Rights Reserved. }
{ }
{ ********************************************************************** }
unit ClxItemEdit;
interface
uses
SysUtils, Classes, QGraphics, QForms, QDialogs,
LibHelp, DesignIntf, DesignEditors, DsnConst, QStdCtrls, QComCtrls, QControls;
type
TItemInfo = class(TObject)
private
FSubItems: TStringList;
FSubItemImages: TList;
FCaption: string;
FImageIndex: Integer;
FStateIndex: Integer;
public
constructor Create(Item: TListItem);
destructor Destroy; override;
end;
TClxListViewItems = class(TForm)
GroupBox1: TGroupBox;
PropGroupBox: TGroupBox;
New: TButton;
Delete: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
TreeView: TTreeView;
NewSub: TButton;
Text: TEdit;
Image: TEdit;
StateImage: TEdit;
Button4: TButton;
Cancel: TButton;
Apply: TButton;
Button7: TButton;
procedure NewClick(Sender: TObject);
procedure NewSubClick(Sender: TObject);
procedure DeleteClick(Sender: TObject);
procedure ValueChange(Sender: TObject);
procedure TextExit(Sender: TObject);
procedure ImageExit(Sender: TObject);
procedure StateImageExit(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ApplyClick(Sender: TObject);
procedure TreeViewChange(Sender: TObject; Node: TTreeNode);
procedure TreeViewChanging(Sender: TObject; Node: TTreeNode;
var AllowChange: Boolean);
procedure TreeViewDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure TreeViewDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure TreeViewEdited(Sender: TObject; Node: TTreeNode;
var S: WideString);
procedure Button7Click(Sender: TObject);
procedure TreeViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure TreeViewEditing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
private
FItems: TListItems;
FDropping: Boolean;
procedure FlushControls;
procedure GetItem(ItemInfo: TItemInfo; Value: TListItem);
procedure SetItem(Value: TItemInfo);
procedure SetStates;
procedure SetSubItem(const S: string; ImageIndex: Integer);
public
property Items: TListItems read FItems;
end;
{ TListViewEditor }
type
TEditInvoker = class
private
FDesigner: IDesigner;
FComponent: TComponent;
procedure InvokeEdit;
public
constructor Create(ADesigner: IDesigner; AComponent: TComponent);
end;
TListViewEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TListViewColumnsProperty = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
TListViewItemsProperty = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
function EditListViewItems(AItems: TListItems): Boolean;
implementation
{$IFDEF MSWINDOWS}
uses Qt, ColnEdit;
{$ENDIF}
{$IFDEF LINUX}
uses Qt, ColnEdit, Libc;
{$ENDIF}
{$R *.xfm}
function EditListViewItems(AItems: TListItems): Boolean;
var
I, J: Integer;
Node: TTreeNode;
ItemInfo: TItemInfo;
begin
with TClxListViewItems.Create(Application) do
try
FItems := AItems;
for I := 0 to Items.Count - 1 do
begin
ItemInfo := TItemInfo.Create(Items[I]);
Node := TreeView.Items.AddObject(nil, ItemInfo.FCaption, ItemInfo);
for J := 0 to ItemInfo.FSubItems.Count - 1 do
ItemInfo.FSubItems.Objects[J] := TreeView.Items.AddChild(Node,
ItemInfo.FSubItems[J]);
end;
with TreeView do
if Items.Count > 0 then
begin
Selected := Items.GetFirstNode;
TreeViewChange(nil, Selected);
end;
SetStates;
Result := ShowModal = mrOK;
if Result and Apply.Enabled then
ApplyClick(nil);
finally
Free;
end;
end;
procedure ConvertError(Value: TEdit);
begin
with Value do
begin
SetFocus;
SelectAll;
end;
end;
{ TItemInfo }
constructor TItemInfo.Create(Item: TListItem);
var
I: Integer;
begin
inherited Create;
FSubItems := TStringList.Create;
FSubItemImages := TList.Create;
FStateIndex := -1;
FImageIndex := -1;
if Assigned(Item) then
begin
FCaption := Item.Caption;
FImageIndex := Item.ImageIndex;
// FStateIndex := StateIndex;
FSubItems.Assign(Item.SubItems);
for I := 0 to Item.SubItems.Count-1 do
FSubItemImages.Add(Pointer(Item.SubItemImages[I]));
end;
end;
destructor TItemInfo.Destroy;
begin
FSubItems.Free;
FSubItemImages.Free;
inherited Destroy;
end;
{ TClxListViewItems }
procedure TClxListViewItems.SetStates;
begin
Delete.Enabled := TreeView.Items.Count > 0;
PropGroupBox.Enabled := Delete.Enabled;
Apply.Enabled := False;
NewSub.Enabled := TreeView.Selected <> nil;
end;
procedure TClxListViewItems.GetItem(ItemInfo: TItemInfo; Value: TListItem);
var
I: Integer;
begin
with Value do
begin
Caption := ItemInfo.FCaption;
ImageIndex := ItemInfo.FImageIndex;
// StateIndex := ItemInfo.FStateIndex;
SubItems.Assign(ItemInfo.FSubItems);
for I := 0 to ItemInfo.FSubItems.Count - 1 do
SubItemImages[I] := Integer(ItemInfo.FSubItemImages[I]);
end;
end;
procedure TClxListViewItems.SetSubItem(const S: string; ImageIndex: Integer);
begin
StateImage.Enabled := False;
Image.Text := IntToStr(ImageIndex);
Text.Text := S;
end;
procedure TClxListViewItems.SetItem(Value: TItemInfo);
begin
Image.Enabled := True;
StateImage.Enabled := True;
if Value <> nil then
with Value do
begin
Text.Text := FCaption;
Image.Text := IntToStr(FImageIndex);
// StateImage.Text := IntToStr(FStateIndex);
end
else begin
Text.Text := '';
Image.Text := '';
StateImage.Text := '';
end;
end;
procedure TClxListViewItems.FlushControls;
begin
TextExit(nil);
ImageExit(nil);
StateImageExit(nil);
end;
procedure TClxListViewItems.TreeViewChanging(Sender: TObject; Node: TTreeNode;
var AllowChange: Boolean);
begin
if not FDropping then
FlushControls;
end;
procedure TClxListViewItems.TreeViewChange(Sender: TObject; Node: TTreeNode);
var
TempEnabled: Boolean;
ItemInfoSubs: TStrings;
Index: Integer;
begin
TempEnabled := Apply.Enabled;
if Node <> nil then
begin
SetStates;
if Node.Data <> nil then
SetItem(TItemInfo(Node.Data))
else begin
ItemInfoSubs := TItemInfo(Node.Parent.Data).FSubItems;
Index := ItemInfoSubs.IndexOfObject(Node);
if Index <> -1 then
SetSubItem(ItemInfoSubs[Index],
Integer(TItemInfo(Node.Parent.Data).FSubItemImages[Index]))
else
SetSubItem('', -1);
end;
end
else SetItem(nil);
Apply.Enabled := TempEnabled;
end;
procedure TClxListViewItems.NewClick(Sender: TObject);
var
Node: TTreeNode;
begin
Node := TreeView.Items.AddObject(nil, '', TItemInfo.Create(nil));
Node.MakeVisible;
TreeView.Selected := Node;
Text.SetFocus;
Apply.Enabled := True;
end;
procedure TClxListViewItems.NewSubClick(Sender: TObject);
var
Node, NewNode: TTreeNode;
begin
with TreeView do
begin
Node := Selected;
if Node <> nil then
begin
if Node.Data <> nil then
begin
NewNode := Node.Owner.AddChild(Node, '');
TItemInfo(Node.Data).FSubItems.AddObject('', NewNode);
TItemInfo(Node.Data).FSubItemImages.Add(Pointer(-1));
end
else begin
NewNode := Node.Owner.Add(Node, '');
TItemInfo(Node.Parent.Data).FSubItems.AddObject('', NewNode);
TItemInfo(Node.Parent.Data).FSubItemImages.Add(Pointer(-1));
end;
NewNode.MakeVisible;
Selected := NewNode;
end;
end;
Text.SetFocus;
Apply.Enabled := True;
end;
procedure TClxListViewItems.DeleteClick(Sender: TObject);
var
Node: TTreeNode;
Index: Integer;
begin
Node := TreeView.Selected;
if Node <> nil then
begin
if Node.Data = nil then
begin
Index := TItemInfo(Node.Parent.Data).FSubItems.IndexOfObject(Node);
if Index <> -1 then
begin
TItemInfo(Node.Parent.Data).FSubItems.Delete(Index);
TItemInfo(Node.Parent.Data).FSubItemImages.Delete(Index);
end;
end
else
TItemInfo(Node.Data).Free;
Node.Free;
end;
if TreeView.Items.Count = 0 then SetItem(nil);
SetStates;
Apply.Enabled := True;
end;
procedure TClxListViewItems.ValueChange(Sender: TObject);
begin
Apply.Enabled := True;
if Sender = Text then TextExit(Sender);
end;
procedure TClxListViewItems.TextExit(Sender: TObject);
var
Node: TTreeNode;
ItemInfoSubs: TStrings;
Index: Integer;
begin
Node := TreeView.Selected;
if Assigned(Node) then
begin
if not Assigned(Node.Data) then
begin
ItemInfoSubs := TItemInfo(Node.Parent.Data).FSubItems;
Index := ItemInfoSubs.IndexOfObject(Node);
if Index <> -1 then
ItemInfoSubs[Index] := Text.Text;
end
else
TItemInfo(Node.Data).FCaption := Text.Text;
Node.Text := Text.Text;
end;
end;
procedure TClxListViewItems.ImageExit(Sender: TObject);
var
Node: TTreeNode;
Index: Integer;
begin
if ActiveControl <> Cancel then
try
Node := TreeView.Selected;
if (Node <> nil) then
begin
if (Node.Data <> nil) then
TItemInfo(Node.Data).FImageIndex := StrToInt(Image.Text)
else begin
Index := TItemInfo(Node.Parent.Data).FSubItems.IndexOfObject(Node);
TItemInfo(Node.Parent.Data).FSubItemImages[Index] := Pointer(StrToInt(Image.Text));
end;
end;
except
ConvertError(Image);
raise;
end;
end;
procedure TClxListViewItems.StateImageExit(Sender: TObject);
var
Node: TTreeNode;
begin
if ActiveControl <> Cancel then
try
Node := TreeView.Selected;
if (Node <> nil) and (Node.Data <> nil) then
; // TItemInfo(Node.Data).FStateIndex := StrToInt(StateImage.Text);
except
ConvertError(StateImage);
raise;
end;
end;
procedure TClxListViewItems.FormCreate(Sender: TObject);
begin
HelpContext := hcDListViewItemEdit;
end;
procedure TClxListViewItems.ApplyClick(Sender: TObject);
var
Node: TTreeNode;
ListItem: TListItem;
begin
FlushControls;
Items.Clear;
if TreeView.Items.Count > 0 then
Node := TreeView.Items[0]
else
Node := nil;
while Node <> nil do
begin
if Node.Data <> nil then
begin
ListItem := Items.Add;
GetItem(TItemInfo(Node.Data), ListItem);
Node := Node.GetNextSibling;
end
end;
with TListView(Items.Owner) do
UpdateItems(0, Items.Count -1);
Apply.Enabled := False;
end;
procedure TClxListViewItems.TreeViewDragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
{var
Node, SelNode: TTreeNode;
Child: Boolean;}
begin
{
Child := GetKeyState(VK_SHIFT) < 0;
SelNode := TreeView.Selected;
Node := TreeView.GetNodeAt(X, Y);
if Node = nil then Node := TreeView.DropTarget;
if Node = nil then
Accept := False
else
Accept := (SelNode <> Node) and not (Child and SelNode.HasAsParent(Node))
and not Node.HasAsParent(SelNode)
and not (SelNode.HasChildren and (Node.Data = nil))
and not (Child and (Node.Data <> nil) and SelNode.HasChildren);\
}
end;
procedure TClxListViewItems.TreeViewDragDrop(Sender, Source: TObject; X,
Y: Integer);
var
{Node, }SelNode: TTreeNode;
Child: Boolean;
procedure AddItem(Source, Dest: TTreeNode);
var
ItemInfoSubs: TStrings;
begin
// dropping from child to child
if (Source.Data = nil) and (Dest.Data = nil) then
begin
// remove child from parent list
ItemInfoSubs := TItemInfo(Source.Parent.Data).FSubItems;
ItemInfoSubs.Delete(ItemInfoSubs.IndexOfObject(Source));
// move child to new parent
Source.MoveTo(Dest, naAdd);
// add child to new parent list
TItemInfo(Dest.Parent.Data).FSubItems.AddObject(Source.Text, Source);
end
// dropping from a parent to a parent
else if (Source.Data <> nil) and (Dest.Data <> nil) then
begin
if not Child then
Source.MoveTo(Dest, naInsert)
else begin
TItemInfo(Source.Data).Free;
Source.Data := nil;
// make Source a child of Dest
Source.MoveTo(Dest, naAddChild);
// add child to new parent list
TItemInfo(Dest.Data).FSubItems.AddObject(Source.Text, Source);
end;
end
// dropping from parent to child
else if (Source.Data <> nil) and (Dest.Data = nil) then
begin
// remove Source's parent node data
TItemInfo(Source.Data).Free;
Source.Data := nil;
// make Source a child of Dest
Source.MoveTo(Dest, naAdd);
// add child to new parent list
TItemInfo(Dest.Parent.Data).FSubItems.AddObject(Source.Text, Source);
end
// dropping from child to parent
else if (Source.Data = nil) and (Dest.Data <> nil) then
begin
// remove child from parent list
ItemInfoSubs := TItemInfo(Source.Parent.Data).FSubItems;
ItemInfoSubs.Delete(ItemInfoSubs.IndexOfObject(Source));
if Child then
begin
// move child to new parent
Source.MoveTo(Dest, naAddChild);
// add child to new parent list
TItemInfo(Dest.Data).FSubItems.AddObject(Source.Text, Source);
end
else begin
// move child to be sibling of Dest
Source.MoveTo(Dest, naInsert);
// create Parent node item info for Source
Source.Data := TItemInfo.Create(nil);
end;
end;
end;
begin
with TreeView do
begin
SelNode := Selected;
if (SelNode <> nil) then
begin
{
Child := GetKeyState(VK_SHIFT) < 0;
Node := TreeView.DropTarget; //GetNodeAt(X, Y);
if Node = nil then
begin
Node := Items[Items.Count - 1];
while (Node <> nil) and not Node.IsVisible do
Node := Node.GetPrev;
end;
if Node <> nil then
try
if Child and (Node.Parent <> nil) then Node := Node.Parent;
FDropping := True;
AddItem(SelNode, Node);
SelNode.Selected := True;
Apply.Enabled := True;
finally
FDropping := False;
end;
}
end;
end;
end;
procedure TClxListViewItems.TreeViewEdited(Sender: TObject; Node: TTreeNode;
var S: WideString);
begin
Text.Text := S;
TextExit(nil);
New.Default := True;
end;
procedure TClxListViewItems.Button7Click(Sender: TObject);
begin
InvokeHelp;
end;
procedure TClxListViewItems.TreeViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// PostMessage(Handle, UM_TREEEDIT, Key, Longint(Self));
end;
procedure TClxListViewItems.TreeViewEditing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
begin
New.Default := False;
end;
{ TEditInvoker }
constructor TEditInvoker.Create(ADesigner: IDesigner; AComponent: TComponent);
begin
inherited Create;
FDesigner := ADesigner;
FComponent := AComponent;
end;
procedure TEditInvoker.InvokeEdit;
begin
ShowCollectionEditor(FDesigner, FComponent, TListView(FComponent).Columns, 'Columns');
Free;
end;
{ TListViewEditor }
procedure TListViewEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: with TEditInvoker.Create(Designer, Component) do
InvokeEdit;
1: if EditListViewItems(TListView(Component).Items) and
Assigned(Designer) then
Designer.Modified;
end;
end;
function TListViewEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := SListColumnsEditor;
1: Result := SListItemsEditor;
end;
end;
function TListViewEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
{ TListViewColumnsProperty }
procedure TListViewColumnsProperty.Edit;
var
Component: TComponent;
begin
Component := TComponent(GetComponent(0));
if not Assigned(Component) then
Exit;
ShowCollectionEditor(Designer, Component, TListView(Component).Columns, 'Columns');
end;
function TListViewColumnsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paMultiSelect, paRevertable, paVCL];
end;
{ TListViewItemsProperty }
procedure TListViewItemsProperty.Edit;
var
Component: TComponent;
begin
Component := TComponent(GetComponent(0));
if not Assigned(Component) then
Exit;
if EditListViewItems(TListView(Component).Items) and
Assigned(Designer) then
Designer.Modified;
end;
function TListViewItemsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paMultiSelect, paRevertable];
end;
end.
|
unit ServData;
{ This Datamodule is the CoClass for the IEmpServer interface. It was
created using the File | New | Remote Data Module menu option }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComServ, ComObj, VCLCom, StdVcl, DataBkr, Provider, Db, DBTables,
Serv_TLB;
type
TEmpServer = class(TRemoteDataModule, IEmpServer)
EmpQuery: TQuery;
EmpQueryProvider: TDataSetProvider;
procedure EmpQueryAfterOpen(DataSet: TDataSet);
procedure EmpServerCreate(Sender: TObject);
procedure EmpServerDestroy(Sender: TObject);
end;
var
EmpServer: TEmpServer;
implementation
{$R *.DFM}
uses ServMain;
{ This rest of this code just demonstrates how you might monitor client
activity from the server. None of this is required to develop an
application server. }
procedure TEmpServer.EmpQueryAfterOpen(DataSet: TDataSet);
begin
{ Update the query counter }
MainForm.IncQueryCount;
end;
procedure TEmpServer.EmpServerCreate(Sender: TObject);
begin
{ Update the client counter }
MainForm.UpdateClientCount(1);
end;
procedure TEmpServer.EmpServerDestroy(Sender: TObject);
begin
{ Update the client counter }
MainForm.UpdateClientCount(-1);
end;
initialization
{ This creates the class factory for us. This code is generated automatically }
TComponentFactory.Create(ComServer, TEmpServer, Class_EmpServer,
ciMultiInstance);
end.
|
program formato;
uses unitmsc2;
const
MAX_PALABRA=40;
MAX_TEXTO=132;
type
texto_palabra=array[1..MAX_PALABRA] of char;
texto_linea=array[1..MAX_TEXTO] of char;
palabra=record
pal:texto_palabra;
tamano:integer;
finparrafo:boolean;
end;
linea=record
lin:texto_linea;
num_palabras:integer;
esparrafo:boolean;
end;
var
margen:integer;
ancho_texto:integer;
ok:boolean;
entrada:string;
salida:string;
ascii:string;
sec_in:msc2;
sec_out:msc2;
linea_in:linea;
linea_aux:linea;
palabra_in:palabra;
(*------------------------------------------------------------------------------*)
(*---- procedimientos y funciones ------*)
(*------------------------------------------------------------------------------*)
function ascii2integer(ascii:string):integer;
var
k,multiplicador,numero:integer;
begin
numero:=0;
multiplicador:=1;
k:=length(ascii);
while k<>0 do
begin
numero:=numero+(multiplicador*((ord(ascii[k]))-48));
multiplicador:=multiplicador*10;
dec(k);
end;
ascii2integer:=numero;
end;
(*------------------------------------------------------------------------------*)
procedure sacarparametros(var ok:boolean; var entrada:string; var salida:string; var margen:integer; var ancho_texto:integer);
begin
ok:=true;
if paramcount<>4 then
begin
ok:=false;
writeln('error introduciendo el numero de parametros.');
writeln('el formato correcto es: formato.exe entrada.txt salida.txt margen ancho_texto');
end
else
entrada:=paramstr(1);
salida:=paramstr(2);
ascii:=paramstr(3);
margen:=ascii2integer(ascii);
if (margen>MAX_PALABRA)or(margen<0) then
begin
ok:=false;
writeln('margen izquierdo incorrecto.');
end;
ascii:=paramstr(4);
ancho_texto:=ascii2integer(ascii);
if (ancho_texto>MAX_TEXTO)or(ancho_texto<0) then
begin
ok:=false;
writeln('ancho de texto incorrecto.');
end;
end;
(*------------------------------------------------------------------------------*)
procedure darpalabra(var sec_in:msc2;var palabra_in:palabra);
var
i:integer;
begin
for i:=1 to MAX_PALABRA do
begin
palabra_in.pal[i]:=' ';
end;
palabra_in.tamano:=1;
palabra_in.finparrafo:=false;
while (not esultimo_msc2(sec_in)) and (ea_msc2(sec_in)<>' ') and (ea_msc2(sec_in)<>msc2_marcafinlinea) do
begin
palabra_in.pal[palabra_in.tamano]:=ea_msc2(sec_in);
inc(palabra_in.tamano);
if (not esultimo_msc2(sec_in)) then
begin
avanzar_msc2(sec_in);
end;
end;
if not esultimo_msc2(sec_in) then
begin
case ea_msc2(sec_in) of
' ' : begin
avanzar_msc2(sec_in);
palabra_in.finparrafo:=false;
end;
msc2_marcafinlinea : begin
avanzar_msc2(sec_in);
if ea_msc2(sec_in)=msc2_marcafinlinea then
begin
palabra_in.finparrafo:=true;
avanzar_msc2(sec_in);
end
else
palabra_in.finparrafo:=false;
end;
end;
end;
dec(palabra_in.tamano);
end;
(*------------------------------------------------------------------------------*)
procedure darlinea (var sec_in:msc2;var palabra_in:palabra;ancho_texto:integer;var linea_in:linea);
var
resto:integer;
indice_p,indice_l:integer;
begin
for indice_l:=1 to MAX_TEXTO do
begin
linea_in.lin[indice_l]:=' ';
end;
indice_l:=1;
linea_in.num_palabras:=0;
resto:=ancho_texto;
repeat
if palabra_in.tamano=0 then
begin
darpalabra(sec_in,palabra_in);
end;
linea_in.esparrafo:=palabra_in.finparrafo;
for indice_p:=1 to palabra_in.tamano do
begin
linea_in.lin[indice_l]:=palabra_in.pal[indice_p];
indice_l:=indice_l+1;
end;
linea_in.num_palabras:=linea_in.num_palabras+1;
linea_in.lin[indice_l]:=' ';
indice_l:=indice_l+1;
resto:=(resto - (palabra_in.tamano+1)); {la primera palabra SIEMPRE entra}
palabra_in.tamano:=0;
if not linea_in.esparrafo then
begin
darpalabra(sec_in,palabra_in);
end;
until (linea_in.esparrafo) or (resto<palabra_in.tamano) or esultimo_msc2(sec_in);
if resto>palabra_in.tamano then
begin
for indice_p:=1 to palabra_in.tamano do
begin
linea_in.lin[indice_l]:=palabra_in.pal[indice_p];
indice_l:=indice_l+1;
end;
linea_in.num_palabras:=linea_in.num_palabras+1;
palabra_in.tamano:=0;
end;
if linea_in.esparrafo then
begin
linea_in.num_palabras:=(linea_in.num_palabras-1);
end;
end;
(*------------------------------------------------------------------------------*)
procedure darespacios(linea_in:linea; var linea_aux:linea; ancho_texto:integer);
var
i,indice_in,indice_aux:integer;
esp_div,esp_mod,esp_total:integer;
begin
linea_aux.esparrafo:=linea_in.esparrafo;
esp_total:=0;
for indice_aux:=1 to MAX_TEXTO do
begin
linea_aux.lin[indice_aux]:=' ';
end;
for indice_in:=1 to ancho_texto do
begin
if linea_in.lin[indice_in]=' ' then
begin
esp_total:=esp_total+1;
end;
end;
esp_div:=esp_total DIV (linea_in.num_palabras-1);
esp_mod:=esp_total MOD (linea_in.num_palabras-1);
indice_aux:=1;
indice_in:=1;
while indice_aux<=ancho_texto do
begin
if linea_in.lin[indice_in]<>' ' then
begin
linea_aux.lin[indice_aux]:=linea_in.lin[indice_in];
inc(indice_aux);
inc(indice_in);
end
else
begin
inc(indice_in);
for i:=1 to esp_div do
begin
linea_aux.lin[indice_aux]:=' ';
inc(indice_aux);
end;
if esp_mod<>0 then
begin
linea_aux.lin[indice_aux]:=' ';
dec(esp_mod);
inc(indice_aux);
end;
end;
end;
end;
(*------------------------------------------------------------------------------*)
procedure guardararchivo(var sec_out:msc2;linea_aux:linea;ancho_texto:integer;margen:integer);
var
i:integer;
begin
for i:=1 to margen do
begin
registrar_msc2(sec_out,' ');
end;
for i:=1 to ancho_texto do
begin
registrar_msc2(sec_out,linea_aux.lin[i]);
end;
registrar_msc2(sec_out,msc2_marcafinlinea);
if linea_aux.esparrafo then
begin
registrar_msc2(sec_out,msc2_marcafinlinea);
end;
end;
(*------------------------------------------------------------------------------*)
(*---- programa principal ------*)
(*------------------------------------------------------------------------------*)
begin
sacarparametros(ok,entrada,salida,margen,ancho_texto);
if ok then
begin
tratamientoinicial_msc2(sec_in);
cargar_fichero_msc2(sec_in,entrada);
inicacceso_msc2(sec_in);
avanzar_msc2(sec_in);
tratamientoinicial_msc2(sec_out);
arrancar_msc2(sec_out);
palabra_in.tamano:=0;
while not esultimo_msc2(sec_in) do
begin
darlinea(sec_in,palabra_in,ancho_texto,linea_in);
if linea_in.num_palabras<>1 then
begin
darespacios(linea_in,linea_aux,ancho_texto);
guardararchivo(sec_out,linea_aux,ancho_texto,margen);
end
else
guardararchivo(sec_out,linea_in,ancho_texto,margen); {si solo tiene una palabra no hace falta organizar la linea}
end;
end;
if palabra_in.tamano<>0 then {puede ocurrir que quede una palabra suelta, ahora es momento de tratarla}
begin
darlinea(sec_in,palabra_in,ancho_texto,linea_in);
guardararchivo(sec_out,linea_in,ancho_texto,margen);
end;
salvar_fichero_msc2(sec_out,salida);
end. |
unit DBServerClientUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DBXpress, DB, SqlExpr, FMTBcd, SOAPLinked, InvokeRegistry,
StdCtrls, DBClient, Grids, DBGrids, DBCtrls, XSBuiltIns, SoapDBServerUnit,
ExtCtrls;
type
TClientForm = class(TForm)
Edit1: TEdit;
ClientDataSet1: TClientDataSet;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
Button3: TButton;
Label1: TLabel;
DBNavigator1: TDBNavigator;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ClientDataSet1AfterPost(DataSet: TDataSet);
procedure ClientDataSet1AfterInsert(DataSet: TDataSet);
procedure ClientDataSet1AfterEdit(DataSet: TDataSet);
procedure ClientDataSet1AfterDelete(DataSet: TDataSet);
procedure Edit1KeyPress(Sender: TObject; var Key: Char);
procedure Button3Click(Sender: TObject);
private
NoEvents: Boolean;
FUpdateInfo: TUpdateInfo;
FUpdateType: TUpdateType;
RIO: TLinkedRIO;
WebServicesDS: IWebServicesDataSet;
SoapDataPacket: TSoapDataPacket;
Delta: TSoapDataPacket;
FUpdateErrors: TDBErrorArray;
procedure ClearDeletedFromPacket;
procedure UpdateChanges;
procedure GetIssuesData;
// function InPacket(RowArray: TRowArray; ErrorArray: TErrorIds): Boolean;
// function ShowUpdateErrors(Error: TIssueError): Boolean;
procedure RefreshDelta;
(* procedure UpdateDelta(NewIssue: Tissue; OldID: Integer);
procedure UpdateDataset(DataSet: TDataSet; NewIssue: Tissue; OldID: Integer);
procedure UpdateDatasets(NewIssue: Tissue; OldID: Integer); *)
{ Private declarations }
public
{ Public declarations }
end;
var
ClientForm: TClientForm;
implementation
{$R *.dfm}
uses DSIntf;
procedure TClientForm.FormCreate(Sender: TObject);
begin
RIO := TLinkedRIO.Create(Nil);
WebServicesDS := Rio As IWebServicesDataSet;
FUpdateInfo := TUpdateInfo.Create;
FUpdateInfo.UseIndexMetadata := True;
end;
procedure TClientForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(FUpdateInfo);
end;
procedure TClientForm.GetIssuesData;
begin
WebServicesDS.RetrieveDataSet(Edit1.Text, SoapDataPacket, FUpdateInfo);
if FUpdateInfo.ErrorCount > 0 then
begin
ShowMessage(FUpdateInfo.ErrorMessage);
exit;
end;
ClientDataSet1.Close;
ClientDataSet1.Data := NULL;
DataSetFromColumnDescArray(SoapDataPacket.ColDescArray, ClientDataSet1, True);
ClientDataSet1.CreateDataSet;
DataSetFromRowArray(ClientDataSet1, SoapDataPacket.RowArray);
RefreshDelta;
end;
procedure TClientForm.ClearDeletedFromPacket;
var
I: Integer;
begin
for I := 0 to Length(Delta.RowArray) -1 do
begin
if Delta.RowArray[I].UpdateType = utUpdateDelete then
SoapDataPacket.ClearRowByRowID(Delta.RowArray[I].rowid);
end;
end;
procedure TClientForm.RefreshDelta;
begin
if Assigned(Delta) then
begin
ClearDeletedFromPacket;
if Length(FUpdateErrors) = 0 then
Delta.ClearRows;
end else
Delta := SoapDataPacket.CloneStructure;
end;
(*procedure TClientForm.UpdateDelta(NewIssue: Tissue; OldID: Integer);
var
I: Integer;
begin
for I := 0 to Length(Delta) -1 do
begin
if Delta[I].ID = OldID then
begin
Delta[I].DateOpened := NewIssue.DateOpened;
Delta[I].Owner := NewIssue.Owner;
Delta[I].ID := NewIssue.ID;
break
end;
end;
end;
procedure TClientForm.UpdateDataset(DataSet: TDataSet; NewIssue: Tissue; OldID: Integer);
begin
DataSet.First;
while not DataSet.eof do
begin
if DataSet.Fields[0].Value = OldID then
begin
DataSet.Edit;
DataSet.Fields[2].Value := NewIssue.DateOpened.AsDateTime;
DataSet.Fields[1].Value := NewIssue.Owner;
DataSet.Fields[0].Value := NewIssue.ID;
DataSet.Post;
break;
end;
DataSet.Next;
end;
DataSet.First;
end;
procedure TClientForm.UpdateDatasets(NewIssue: Tissue; OldID: Integer);
begin
NoEvents := True;
UpdateDelta(NewIssue, OldId);
UpdateDataSet(ClientDataSet1, NewIssue, OldId);
NoEvents := False;
end;
function TClientForm.ShowUpdateErrors(Error: TIssueError): Boolean;
var
DlgRslt, OldId: Integer;
begin
OldId := Error.FailedRecord.ID;
UpdateErrorDlg.issue := Error.FailedRecord;
UpdateErrorDlg.Edit1.Text := IntToStr(Error.FailedRecord.ID);
UpdateErrorDlg.Edit2.Text := Error.FailedRecord.Owner;
UpdateErrorDlg.Edit3.Text := DateToStr(Error.FailedRecord.DateOpened.AsDateTime);
UpdateErrorDlg.DataSet := ClientDataSet1;
// UpdateErrorDlg.Delta := Delta;
UpdateErrorDlg.Memo1.Lines.Clear;
UpdateErrorDlg.Memo1.Lines.Add(Error.ErrorMsg);
DlgRslt := UpdateErrorDlg.ShowModal;
SetDlgReadOnly;
if DlgRslt <> mrCancel then
UpdateDataSets(UpdateErrorDlg.Issue, OldId);
if DlgRslt = mrRetry then
UpdateChanges;
Result := DlgRslt <> mrCancel;
end; *)
(*function TClientForm.InPacket(RowArray: TRowArray; ErrorArray: TErrorIds): Boolean;
var
I: Integer;
begin
Result := True;
for I := 0 to Length(ErrorArray) -1 do
if ID = ErrorArray[I] then
exit;
Result := False;
end; *)
procedure TClientForm.UpdateChanges;
var
Errors: Integer;
begin
if not Assigned(Delta) then exit;
if Length(Delta.RowArray) > 0 then
begin
Errors := WebServicesDS.UpdateDataSet(Delta, FUpdateInfo, FUpdateErrors);
RefreshDelta;
end;
end;
function CompareValues(Value: Variant; Field: TField): Boolean;
var
DT: TDateTime;
Dbl: Double;
begin
if Field.DataType = ftTimeStamp then
Result := (Field.AsDateTime = Value)
else if Field.DataType = ftFMTBcd then
Result := (Field.AsCurrency = Value)
else
Result := (Value = Field.Value);
end;
procedure TClientForm.ClientDataSet1AfterPost(DataSet: TDataSet);
var
I, Current, PacketCurrent: Integer;
begin
if NoEvents then exit;
PacketCurrent := ClientDataSet1.RecNo-1;
Current := -1;
for I := 0 to Length(Delta.RowArray) -1 do
begin
if Delta.RowArray[I].RowID = ClientDataSet1.RecNo then
begin
Current := I;
break;
end;
end;
if Current = -1 then
begin
if FUpdateType = utUpdateInsert then
PacketCurrent := SoapDataPacket.IncRowSize -1;
Current := Delta.IncRowSize -1;
Delta.RowArray[Current] := SoapDataPacket.RowArray[PacketCurrent].Clone;
if FUpdateType = utUpdateInsert then
Delta.RowArray[Current].ClearValues;
end;
Delta.RowArray[Current].UpdateType := FUpdateType;
for I := 0 to Length(Delta.RowArray[Current].FieldValueArray) -1 do
begin
if (FUpdateType = utUpdateInsert) or
not (CompareValues(Delta.RowArray[Current].FieldValueArray[I].Value, ClientDataSet1.Fields[I])) then
begin
Delta.RowArray[Current].FieldValueArray[I].Changed := True;
if VarIsNull(Delta.RowArray[Current].FieldValueArray[I].OldValue) then
Delta.RowArray[Current].FieldValueArray[I].OldValue :=
SoapDataPacket.RowArray[PacketCurrent].FieldValueArray[I].Value;
Delta.RowArray[Current].FieldValueArray[I].Value := ClientDataSet1.Fields[I].Value;
end;
end;
end;
procedure TClientForm.ClientDataSet1AfterInsert(DataSet: TDataSet);
begin
if not NoEvents then
FUpdateType := utUpdateInsert;
end;
procedure TClientForm.ClientDataSet1AfterEdit(DataSet: TDataSet);
begin
if not NoEvents then
FUpdateType := utUpdateUpdate;
end;
procedure TClientForm.ClientDataSet1AfterDelete(DataSet: TDataSet);
begin
if not NoEvents then
begin
FUpdateType := utUpdateDelete;
ClientDataSet1AfterPost(DataSet);
end;
end;
procedure TClientForm.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if Key in [#13, #9] then
begin
NoEvents := True;
GetIssuesData;
NoEvents := False;
DBGrid1.SetFocus;
end;
end;
procedure TClientForm.Button3Click(Sender: TObject);
begin
UpdateChanges;
end;
end.
|
unit AccountingAuxData;
interface
uses
System.SysUtils, System.Classes, Data.DB, Data.Win.ADODB;
type
TdmAccountingAux = class(TDataModule)
dstAccountClass: TADODataSet;
dscAccountClass: TDataSource;
dstLineItems: TADODataSet;
dscLineItems: TDataSource;
dstAccountTitles: TADODataSet;
dscAccountTitles: TDataSource;
dstSubsidiaryTypes: TADODataSet;
dscSubsidiaryTypes: TDataSource;
dstSubsidiaries: TADODataSet;
dscSubsidiaries: TDataSource;
procedure dstAccountClassBeforePost(DataSet: TDataSet);
procedure dstLineItemsBeforePost(DataSet: TDataSet);
procedure dstLineItemsAfterPost(DataSet: TDataSet);
procedure dstAccountTitlesAfterPost(DataSet: TDataSet);
procedure dstSubsidiariesBeforePost(DataSet: TDataSet);
procedure dstSubsidiariesAfterPost(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dmAccountingAux: TdmAccountingAux;
implementation
uses
AppData, DBUtil;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TdmAccountingAux.dstAccountClassBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
begin
DataSet.FieldByName('acct_class').AsInteger := GetAccountClassId;
end;
end;
procedure TdmAccountingAux.dstLineItemsAfterPost(DataSet: TDataSet);
begin
// Use RefreshDataSet method in the DBUtil unit
DataSet.Close;
DataSet.Open;
end;
procedure TdmAccountingAux.dstLineItemsBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
begin
DataSet.FieldByName('line_item').AsInteger := GetAccountGroupId;
end;
end;
procedure TdmAccountingAux.dstSubsidiariesAfterPost(DataSet: TDataSet);
begin
// Use RefreshDataSet method in the DBUtil unit
DataSet.Close;
DataSet.Open;
end;
procedure TdmAccountingAux.dstSubsidiariesBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
begin
DataSet.FieldByName('subsidiary_id').AsString := GetSubsidiaryId;
end;
end;
procedure TdmAccountingAux.dstAccountTitlesAfterPost(DataSet: TDataSet);
begin
DataSet.Close;
DataSet.Open;
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Generics.Collections, Vcl.StdCtrls;
type
TCity = record
State: String;
Country: String;
Name: String;
end;
TfmMain = class(TForm)
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
CitiesList: TDictionary<String, TCity>;
public
{ Public declarations }
end;
var
fmMain: TfmMain;
implementation
{$R *.dfm}
procedure TfmMain.Button1Click(Sender: TObject);
var City: TCity;
begin
City.State := 'SC';
City.Country := 'Brazil';
City.Name := 'Concórdia';
CitiesList.Add(City.Name, City);
City.State := 'SC';
City.Country := 'Brazil';
City.Name := 'Chapecó';
CitiesList.Add(City.Name, City);
City.State := 'SC';
City.Country := 'Brazil';
City.Name := 'Arabutã';
CitiesList.Add(City.Name, City);
end;
procedure TfmMain.Button2Click(Sender: TObject);
var City: TCity;
begin
if CitiesList.TryGetValue('Concórdia', City) then
Memo1.Lines.Add(City.Name+' - '+City.State+' - '+City.Country)
else
Memo1.Lines.Add('City not found.')
end;
procedure TfmMain.Button3Click(Sender: TObject);
var City: TCity;
begin
CitiesList.Remove('Arabutã');
if not CitiesList.TryGetValue('Arabutã', City) then
Memo1.Lines.Add('Removed');
end;
procedure TfmMain.FormCreate(Sender: TObject);
begin
CitiesList := TDictionary<String, TCity>.Create;
end;
end.
|
unit Code02.Ongakw.Czas_Zmiana;
interface
uses
System.SysUtils;
type
THistoria_Zapytan_r_wsk = ^THistoria_Zapytan_r;
THistoria_Zapytan_r = record
rok : word;
czas__zmiana,
czas__zmiana__koniec__ustawione,
czas__zmiana__poczatek__ustawione,
czas__zmiana__ustawione
: boolean;
czas__zmiana__koniec,
czas__zmiana__poczatek
: TDateTime;
miejsce : string;
end;
//---//THistoria_Zapytan_r
TCzas_Zmiana = class
private
zapytania_ilosc_g : integer;
czas_blok_g : string;
historia_zapytan_r_t_g : array of THistoria_Zapytan_r;
function Czas_Blok_Zmiany_Znajdz( napis_f : string; const czy_blok_poczatku_f : boolean ) : TDateTime;
public
procedure Inicjuj();
procedure Zakoncz();
function IsDaylightSaving( const area : string; year : word ) : boolean;
function GetDaylightStart( const area : string; year : word ) : TDateTime;
function GetDaylightEnd( const area : string; year : word ) : TDateTime;
function Historia_Zapytan_Zarzadzaj( const miejsce_f : string; rok_f : word ) : THistoria_Zapytan_r_wsk;
function Zapytania_Ilosc_Odczytaj() : integer;
end;
//---//TCzas_Zmiana
const
strona_adres_c : string = 'https://www.timeanddate.com/time/change/';
strona_adres__rok_c : string = '?year=';
znacznik_zmiana__brak_c : string = 'Daylight Saving Time (DST) Not Observed';
znacznik_zmiana__poczatek_c : string = 'Daylight Saving Time Start';
znacznik_zmiana__koniec_c : string = 'Daylight Saving Time End';
implementation
uses
Code02.HttpGet;
//Funkcja Inicjuj().
procedure TCzas_Zmiana.Inicjuj();
begin
Self.zapytania_ilosc_g := 0;
Self.czas_blok_g := '';
SetLength( Self.historia_zapytan_r_t_g, 0 );
end;//---//Funkcja Inicjuj().
//Funkcja Zakoncz().
procedure TCzas_Zmiana.Zakoncz();
begin
Self.Inicjuj();
end;//---//Funkcja Zako�cz().
//Funkcja Czas_Blok_Zmiany_Znajdn().
function TCzas_Zmiana.Czas_Blok_Zmiany_Znajdz( napis_f : string; const czy_blok_poczatku_f : boolean ) : TDateTime;
//Funkcja Data_Dekoduj_Z_Napisu() w Czas_Blok_Zmiany_Znajd�().
function Data_Dekoduj_Z_Napisu( data_s_f : string ) : TDate;
var
zts_l,
dzien_s_l,
miesiac_s_l
: string;
zti_l,
dzien_l,
miesiac_l,
rok_l
: integer;
begin
//
// Funkcja zamienia napis na datę.
//
// Zwraca datę i czas.
//
// Parametry:
// napis_f - w postaci dd mmmmm rrrr
//
Result := 0;
zti_l := Pos( ' ', data_s_f ) - 1;
dzien_s_l := Copy( data_s_f, 1, zti_l );
Delete( data_s_f, 1, zti_l + 1 );
zti_l := Pos( ' ', data_s_f ) - 1;
miesiac_s_l := AnsiLowerCase( Copy( data_s_f, 1, zti_l ) );
Delete( data_s_f, 1, zti_l + 1 );
try
dzien_l := StrToInt( dzien_s_l );
except
dzien_l := -1;
end;
//---//try
try
rok_l := StrToInt( data_s_f );
except
rok_l := -1;
end;
//---//try
{$region 'Dekoduje miesiąc.'}
if ( miesiac_s_l = 'styczeń' )
or ( miesiac_s_l = 'styczen' )
or ( miesiac_s_l = '1' )
or ( miesiac_s_l = '01' )
or ( miesiac_s_l = 'january' ) then
miesiac_l := 1
else
if ( miesiac_s_l = 'luty' )
or ( miesiac_s_l = '2' )
or ( miesiac_s_l = '02' )
or ( miesiac_s_l = 'february' ) then
miesiac_l := 2
else
if ( miesiac_s_l = 'marzec' )
or ( miesiac_s_l = '3' )
or ( miesiac_s_l = '03' )
or ( miesiac_s_l = 'march' ) then
miesiac_l := 3
else
if ( miesiac_s_l = 'kwiecień' )
or ( miesiac_s_l = 'kwiecien' )
or ( miesiac_s_l = '4' )
or ( miesiac_s_l = '04' )
or ( miesiac_s_l = 'april' ) then
miesiac_l := 4
else
if ( miesiac_s_l = 'maj' )
or ( miesiac_s_l = '5' )
or ( miesiac_s_l = '05' )
or ( miesiac_s_l = 'may' ) then
miesiac_l := 5
else
if ( miesiac_s_l = 'czerwiec' )
or ( miesiac_s_l = '6' )
or ( miesiac_s_l = '06' )
or ( miesiac_s_l = 'june' ) then
miesiac_l := 6
else
if ( miesiac_s_l = 'lipiec' )
or ( miesiac_s_l = '7' )
or ( miesiac_s_l = '07' )
or ( miesiac_s_l = 'july' ) then
miesiac_l := 7
else
if ( miesiac_s_l = 'sierpień' )
or ( miesiac_s_l = 'sierpien' )
or ( miesiac_s_l = '8' )
or ( miesiac_s_l = '08' )
or ( miesiac_s_l = 'august' ) then
miesiac_l := 8
else
if ( miesiac_s_l = 'wrzesień' )
or ( miesiac_s_l = 'wrzesien' )
or ( miesiac_s_l = '9' )
or ( miesiac_s_l = '09' )
or ( miesiac_s_l = 'september' ) then
miesiac_l := 9
else
if ( miesiac_s_l = 'październik' )
or ( miesiac_s_l = 'pazdziernik' )
or ( miesiac_s_l = '10' )
or ( miesiac_s_l = 'october' ) then
miesiac_l := 10
else
if ( miesiac_s_l = 'listopad' )
or ( miesiac_s_l = '11' )
or ( miesiac_s_l = 'november' ) then
miesiac_l := 11
else
if ( miesiac_s_l = 'grudzień' )
or ( miesiac_s_l = 'grudzien' )
or ( miesiac_s_l = '12' )
or ( miesiac_s_l = 'december' ) then
miesiac_l := 12
else
miesiac_l := -1;
{$endregion 'Dekoduje miesi�c.'}
if ( dzien_l <= 0 )
or ( miesiac_l <= 0 )
or ( rok_l <= 0 ) then
Exit;
Result := EncodeDate( rok_l, miesiac_l, dzien_l );
end;//---//Funkcja Data_Dekoduj_Z_Napisu() w Czas_Blok_Zmiany_Znajd�().
var
zti : integer;
zts,
data_l,
czas_l
: string;
ztt : TTime;
ztd : TDate;
begin//Funkcja Czas_Blok_Zmiany_Znajdn().
//
// Funkcja wyszukuje blok danych z informacjami o dacie zmiany czasu.
//
// Zwraca blok danych z informacjami o dacie zmiany czasu.
//
// Parametry:
// napis_f
// czy_blok_poczatku_f:
// false - szuka daty początku zmiany czasu.
// true - szuka daty końca zmiany czasu.
//
Result := 0;
if czy_blok_poczatku_f then
zti := Pos( znacznik_zmiana__poczatek_c, napis_f )
else//if czy_blok_początku_f then
zti := Pos( znacznik_zmiana__koniec_c, napis_f );
if zti <= 0 then
Exit;
Delete( napis_f, 1, zti );
zts := '<br>';
zti := Pos( zts, AnsiLowerCase( napis_f ) );
Delete( napis_f, 1, zti + Length( zts ) - 1 );
zts := ' ';
zti := Pos( zts, AnsiLowerCase( napis_f ) );
Delete( napis_f, 1, zti + Length( zts ) - 1 );
zti := Pos( ',', napis_f ) - 1;
data_l := Copy( napis_f, 1, zti );
zts := '<strong>';
zti := Pos( zts, AnsiLowerCase( napis_f ) );
Delete( napis_f, 1, zti + Length( zts ) - 1 );
zti := Pos( AnsiLowerCase( '</strong>' ), napis_f ) - 1;
czas_l := Copy( napis_f, 1, zti );
ztd := Data_Dekoduj_Z_Napisu( data_l );
try
ztt := StrToTime( czas_l );
except
on E: Exception do
begin
ztt := 0;
//Application.MessageBox( PChar( E.Message + ' ' + IntToStr( E.HelpContext ) ), 'B��d', MB_OK + MB_ICONEXCLAMATION );
end;
//---//on E: Exception do
end;
//---//try
Result := ztd + ztt;
end;//---//Funkcja Czas_Blok_Zmiany_Znajdn().
//Funkcja IsDaylightSaving().
function TCzas_Zmiana.IsDaylightSaving( const area : string; year : word ) : boolean;
var
zt_historia_zapytan_r_wsk_l : THistoria_Zapytan_r_wsk;
begin
//https://www.timeanddate.com/time/change/poland/warsaw?year=2015
// Zmiana czasu.
//
//<div class="nine columns"><h2 class='mgt0'>29 mar 2015 - Daylight Saving Time Started</h2><p>When local standard time was about to reach<br>niedziela 29 marzec 2015, <strong>02:00:00</strong> clocks were turned <strong>forward</strong> 1 hour to <br>niedziela 29 marzec 2015, <strong>03:00:00</strong> local daylight time instead.</p>
//
//<div class="nine columns">
//<h2 class='mgt0'>29 mar 2015 - Daylight Saving Time Started</h2>
// albo
// <h2 class='mgt0'>14 mar 2021 - Daylight Saving Time Starts</h2>
//<p>When local standard time was about to reach<br>
//niedziela 29 marzec 2015,
//<strong>02:00:00</strong>
// clocks were turned <strong>forward</strong> 1 hour to <br>niedziela 29 marzec 2015, <strong>03:00:00</strong> local daylight time instead.</p>
//
//<div class="nine columns"><h2 class='mgt0'>25 paz 2015 - Daylight Saving Time Ended</h2><p>When local daylight time was about to reach<br>niedziela 25 pazdziernik 2015, <strong>03:00:00</strong> clocks were turned <strong>backward</strong> 1 hour to <br>niedziela 25 pazdziernik 2015, <strong>02:00:00</strong> local standard time instead.</p>
//
//<div class="nine columns">
//<h2 class='mgt0'>25 paz 2015 - Daylight Saving Time Ended</h2>
// albo
// <h2 class='mgt0'>7 lis 2021 - Daylight Saving Time Ends</h2>
//<p>When local daylight time was about to reach<br>
//niedziela 25 pazdziernik 2015,
//<strong>03:00:00</strong>
// clocks were turned <strong>backward</strong> 1 hour to <br>niedziela 25 pazdziernik 2015, <strong>02:00:00</strong> local standard time instead.</p>
// Bez zmiany czasu.
//
//<h3>Daylight Saving Time (DST) Not Observed in Year 1995</h3>
Result := false;
zt_historia_zapytan_r_wsk_l := Self.Historia_Zapytan_Zarzadzaj( area, year );
if zt_historia_zapytan_r_wsk_l.czas__zmiana__ustawione then
begin
Result := zt_historia_zapytan_r_wsk_l.czas__zmiana;
Exit;
end;
//---//if zt_historia_zapytan_r_wsk_l.czas__zmiana__ustawione then
inc( Self.zapytania_ilosc_g );
czas_blok_g := Code02.HttpGet.TMyHttpGet.GetWebsiteContent( strona_adres_c + area + strona_adres__rok_c + IntToStr( year ) );
if Pos( znacznik_zmiana__brak_c, czas_blok_g ) > 0 then
begin
zt_historia_zapytan_r_wsk_l.czas__zmiana := Result;
zt_historia_zapytan_r_wsk_l.czas__zmiana__ustawione := true;
zt_historia_zapytan_r_wsk_l.czas__zmiana__koniec__ustawione := true;
zt_historia_zapytan_r_wsk_l.czas__zmiana__poczatek__ustawione := true;
Exit;
end;
//---//if Pos( znacznik_zmiana__brak_c, czas_blok_g ) > 0 then
if ( Pos( znacznik_zmiana__poczatek_c, czas_blok_g ) > 0 )
and ( Pos( znacznik_zmiana__koniec_c, czas_blok_g ) > 0 ) then
begin
Result := true;
zt_historia_zapytan_r_wsk_l.czas__zmiana := Result;
zt_historia_zapytan_r_wsk_l.czas__zmiana__ustawione := true;
// Od razu przeliczy pozostałe wartości (opcjonalnie). //???
if not zt_historia_zapytan_r_wsk_l.czas__zmiana__koniec__ustawione then
begin
zt_historia_zapytan_r_wsk_l.czas__zmiana__koniec := Self.Czas_Blok_Zmiany_Znajdz( Self.czas_blok_g, false );
zt_historia_zapytan_r_wsk_l.czas__zmiana__koniec__ustawione := true;
end;
//---//if not zt_historia_zapytan_r_wsk_l.czas__zmiana__koniec__ustawione then
if not zt_historia_zapytan_r_wsk_l.czas__zmiana__poczatek__ustawione then
begin
zt_historia_zapytan_r_wsk_l.czas__zmiana__poczatek := Self.Czas_Blok_Zmiany_Znajdz( Self.czas_blok_g, true );
zt_historia_zapytan_r_wsk_l.czas__zmiana__poczatek__ustawione := true;
end;
//---//if not zt_historia_zapytan_r_wsk_l.czas__zmiana__pocz�tek__ustawione then
//---// Od razu przeliczy pozostałe wartości (opcjonalnie). //???.
Exit;
end;
//---//if ( Pos( znacznik_zmiana__pocz�tek_c, czas_blok_g ) > 0 ) (...)
//else
// Błąd. //???
end;//---//Funkcja IsDaylightSaving().
//Funkcja GetDaylightStart().
function TCzas_Zmiana.GetDaylightStart( const area : string; year : word ) : TDateTime;
var
zts : string;
zt_historia_zapytan_r_wsk_l : THistoria_Zapytan_r_wsk;
begin
Result := 0;
zt_historia_zapytan_r_wsk_l := Self.Historia_Zapytan_Zarzadzaj( area, year );
if zt_historia_zapytan_r_wsk_l.czas__zmiana__poczatek__ustawione then
begin
Result := zt_historia_zapytan_r_wsk_l.czas__zmiana__poczatek;
Exit;
end;
//---//if zt_historia_zapytan_r_wsk_l.czas__zmiana__pocz�tek__ustawione then
if not IsDaylightSaving( area, year ) then
begin
zt_historia_zapytan_r_wsk_l.czas__zmiana__poczatek__ustawione := true;
Exit;
end;
//---//if not IsDaylightSaving( area, year ) then
if Trim( Self.czas_blok_g ) = '' then
Exit;
Result := Self.Czas_Blok_Zmiany_Znajdz( Self.czas_blok_g, true );
zt_historia_zapytan_r_wsk_l.czas__zmiana__poczatek := Result;
zt_historia_zapytan_r_wsk_l.czas__zmiana__poczatek__ustawione := true;
end;//---//Funkcja GetDaylightStart().
//Funkcja GetDaylightEnd().
function TCzas_Zmiana.GetDaylightEnd( const area : string; year : word ) : TDateTime;
var
zts : string;
zt_historia_zapytan_r_wsk_l : THistoria_Zapytan_r_wsk;
begin
Result := 0;
zt_historia_zapytan_r_wsk_l := Self.Historia_Zapytan_Zarzadzaj( area, year );
if zt_historia_zapytan_r_wsk_l.czas__zmiana__koniec__ustawione then
begin
Result := zt_historia_zapytan_r_wsk_l.czas__zmiana__koniec;
Exit;
end;
//---//if zt_historia_zapyta�_r_wsk_l.czas__zmiana__koniec__ustawione then
if not IsDaylightSaving( area, year ) then
begin
zt_historia_zapytan_r_wsk_l.czas__zmiana__koniec__ustawione := true;
Exit;
end;
//---//if not IsDaylightSaving( area, year ) then
if Trim( Self.czas_blok_g ) = '' then
Exit;
Result := Self.Czas_Blok_Zmiany_Znajdz( Self.czas_blok_g, false );
zt_historia_zapytan_r_wsk_l.czas__zmiana__koniec := Result;
zt_historia_zapytan_r_wsk_l.czas__zmiana__koniec__ustawione := true;
end;//---//Funkcja GetDaylightEnd().
//Funkcja Historia_Zapytan_Zarzadzaj().
function TCzas_Zmiana.Historia_Zapytan_Zarzadzaj( const miejsce_f : string; rok_f : word ) : THistoria_Zapytan_r_wsk;
var
i : integer;
zts : string;
begin
//
// Funkcja sprawdza czy jest zapamiętane zapytanie o podane miejsce i rok.
//
// Zwraca rekord historii zapytań
// gdy nie ma w historii zapytania wartość Result.historia_brak równa się false.
//
// Parametry:
// miejsce_f
// rok_f:
//
for i := 0 to Length( Self.historia_zapytan_r_t_g ) - 1 do
if ( Self.historia_zapytan_r_t_g[ i ].miejsce = miejsce_f )
and ( Self.historia_zapytan_r_t_g[ i ].rok = rok_f ) then
begin
Result := @Self.historia_zapytan_r_t_g[ i ];
Exit;
end;
//---//if ( Self.historia_zapyta�_r_t_g[ i ].miejsce = miejsce_f ) (...)
// Dodaje nowy wpis historii zapytan i zeruje wartości.
i := Length( Self.historia_zapytan_r_t_g );
SetLength( Self.historia_zapytan_r_t_g, i + 1 );
Self.historia_zapytan_r_t_g[ i ].rok := rok_f;
Self.historia_zapytan_r_t_g[ i ].miejsce := miejsce_f;
Self.historia_zapytan_r_t_g[ i ].czas__zmiana__koniec__ustawione := false;
Self.historia_zapytan_r_t_g[ i ].czas__zmiana__poczatek__ustawione := false;
Self.historia_zapytan_r_t_g[ i ].czas__zmiana__ustawione := false;
Self.historia_zapytan_r_t_g[ i ].czas__zmiana := false;
Self.historia_zapytan_r_t_g[ i ].czas__zmiana__koniec := 0;
Self.historia_zapytan_r_t_g[ i ].czas__zmiana__poczatek := 0;
//---// Dodaje nowy wpis historii zapyta� i zeruje warto�ci.
Result := @Self.historia_zapytan_r_t_g[ i ];
end;//---//Funkcja Historia_Zapyta�_Zarz�dzaj().
//Funkcja Historia_Zapyta�_Zarz�dzaj().
function TCzas_Zmiana.Zapytania_Ilosc_Odczytaj() : integer;
begin
Result := Self.zapytania_ilosc_g;
end;//---//Funkcja Historia_Zapyta�_Zarz�dzaj().
end.
|
{A benchmark demonstrating that never downsizing memory blocks can lead to
problems.}
unit DownsizeTestUnit;
interface
uses BenchmarkClassUnit, Math;
type
TDownsizeTest = class(TFastcodeMMBenchmark)
protected
FStrings: array of string;
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetSpeedWeight: Double; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
{ TDownsizeTest }
class function TDownsizeTest.GetBenchmarkDescription: string;
begin
Result := 'Allocates large blocks and immediately resizes them to a '
+ 'much smaller size. This checks whether the memory manager downsizes '
+ 'memory blocks correctly. '
+ 'Benchmark submitted by Pierre le Riche.';
end;
class function TDownsizeTest.GetBenchmarkName: string;
begin
Result := 'Block downsize';
end;
class function TDownsizeTest.GetCategory: TBenchmarkCategory;
begin
Result := bmSingleThreadRealloc;
end;
class function TDownsizeTest.GetSpeedWeight: Double;
begin
{Speed is not important here. It is just to check that the behaviour of the
MM is acceptable.}
Result := 0.2;
end;
procedure TDownsizeTest.RunBenchmark;
var
i, n, LOffset: integer;
begin
inherited;
//for n := 1 to 50 do // loop added to have more than 1000 MTicks for this benchmark
begin
{Allocate a lot of strings}
SetLength(FStrings, 3000000);
for i := 0 to high(FStrings) do
begin
{Grab a 20K block}
SetLength(FStrings[i], 20000);
{Touch memory}
LOffset := 1;
while LOffset <= 20000 do
begin
FStrings[i][LOffset] := #1;
Inc(LOffset, 4096);
end;
{Reduce the size to 1 byte}
SetLength(FStrings[i], 1);
end;
{Update the peak address space usage}
UpdateUsageStatistics;
end;
end;
end.
|
unit uObjectPanel;
interface
uses Forms, Graphics, Math, Windows, SysUtils, Types, uObjectFeature, uObjectFeatureList, uFeaCombo, uMyTypes,
uConfig, Classes, uOtherObjects, uObjectCombo, uObjectComboList, IniFiles, StrUtils, uObjectGuideList;
type
TPanelObject = class(TObject)
private
objID: integer; // ID pridelene po nahrati na web
objVersion: integer; // ked nahravam panely zo suborov zo starsich verzii, tak aby som mal prehlad, akou verziou bol vytvoreny
objSirka: Double;
objVyska: Double;
objHrubka: Double;
objRadius: Double;
objGrid: Double;
objPovrch: string;
objHranaStyl: string;
objHranaRozmer: Double;
objHranaObrobenaBottom: boolean;
objHranaObrobenaRight: boolean;
objHranaObrobenaTop: boolean;
objHranaObrobenaLeft: boolean;
objMaterialVlastny: boolean;
objFeatures: TFeaList; // tu budu ulozene vsetky features
objCombos: TComboList; // tu budu ulozene vsetky comba
objGuides: TGuideList; // tu budu ulozene vsetky guide-liney
objFonty: TStringList; // zoznam nahratych fontov
objNewFeatureId: integer; // number of next created feature
objNextComboId : integer; // number of next created combo
objBgndCol: TColor;
objSurfCol: TColor;
objBordCol: TColor;
objZoom: Double; // pomer mm/px (uz zahrna aj objZoomFactor)
objZoomFactor: double; // udava zoom nastaveny uzivatelom
objSideZeroes: array[1..9] of byte; // pole nul.bodov (na poz.1 je nul.bod strany 1...)
objCurrentSide: byte; // cislo aktivneho nuloveho bodu (v poli nulovych bodov)
objDrawOffsetX: integer;
objDrawOffsetY: integer;
objZoomOffsetX: integer;
objZoomOffsetY: integer;
objFileName: string;
objHasChanged: boolean;
objRoh_c1: TMyPoint;
objSelCombosDrawn: string; // kym nenajdem lepsie riesenie: na oznacenie, ci vyselectovanemu combu uz bol vykresleny vyberovy obdlznik
objStranaVisible: byte;
objUndoList2: TMyUndoList_v2;
objNextUndoStepID: integer;
objIndexOfNextUndoStep: integer;
objGridPointsX: array of Integer; // spocitame px suradnice gridu, sem sa to ulozi a potom sa uz len podla tohto pola vykresluje grid
objGridPointsY: array of Integer; // --- " ---
procedure SetSirka(val: Double);
procedure SetVyska(val: Double);
function GetCenterPos: byte;
procedure SetCenterPos(newVal: byte);
procedure SetCurrentSide(newVal: Byte);
procedure SetRoh_c1;
procedure KresliZrazenyRoh(c_rohu: byte; x_zrazeneho_rohu_mm, y_zrazeneho_rohu_mm: double; horizontal, vertikal: boolean);
procedure SetHasChanged(val: Boolean);
procedure RedrawSurrounding;
published
constructor Create;
destructor Destroy;
property ID: integer read objID write objID;
property Version: integer read objVersion;
property Features: TFeaList read objFeatures;
property Combos: TComboList read objCombos;
property Guides: TGuideList read objGuides;
property Sirka: Double read objSirka write SetSirka;
property Vyska: Double read objVyska write SetVyska;
property Hrubka: Double read objHrubka write objHrubka;
property Radius: Double read objRadius write objRadius;
property Grid: Double read objGrid write objGrid;
property Povrch: string read objPovrch write objPovrch;
property HranaStyl: string read objHranaStyl write objHranaStyl;
property HranaRozmer: Double read objHranaRozmer write objHranaRozmer;
property HranaObrobenaBottom: boolean read objHranaObrobenaBottom write objHranaObrobenaBottom;
property HranaObrobenaRight: boolean read objHranaObrobenaRight write objHranaObrobenaRight;
property HranaObrobenaTop: boolean read objHranaObrobenaTop write objHranaObrobenaTop;
property HranaObrobenaLeft: boolean read objHranaObrobenaLeft write objHranaObrobenaLeft;
property MaterialVlastny: boolean read objMaterialVlastny write objMaterialVlastny;
property CenterPos: byte read GetCenterPos write SetCenterPos;
property CurrentSide: byte read objCurrentSide write SetCurrentSide;
property HasChanged: boolean read objHasChanged write SetHasChanged;
property BgndCol: TColor read objBgndCol write objBgndCol;
property SurfCol: TColor read objSurfCol write objSurfCol;
property BordCol: TColor read objBordCol write objBordCol;
property DrwOffX: integer read objDrawOffsetX write objDrawOffsetX;
property DrwOffY: integer read objDrawOffsetY write objDrawOffsetY;
property Zoom: Double read objZoom write objZoom;
property ZoomOffX: integer read objZoomOffsetX write objZoomOffsetX;
property ZoomOffY: integer read objZoomOffsetY write objZoomOffsetY;
property StranaVisible: byte read objStranaVisible write objStranaVisible;
property FileName: string read objFileName write objFileName;
property Roh_c1: TMyPoint read objRoh_c1;
property SelCombosDrawn: string read objSelCombosDrawn write objSelCombosDrawn;
property UndoList2: TMyUndoList_v2 read objUndoList2 write objUndoList2;
property Fonty: TStringList read objFonty write objFonty;
procedure LoadFromFile_old(panelfile: string);
procedure LoadFromFile(panelfile: string);
procedure SaveToFile(panelfile: string);
function GetFeatureByID(fid: integer): TFeatureObject;
function GetFeaturesAt(var poleNajdenych: TPoleIntegerov; bod_x, bod_y: integer): boolean;
function GetGuidelinesAt(bod_x, bod_y: integer): TMyInt2x;
function GetSelectedFeaturesNum: TMyInt2x;
function GetFeatureIndex(fid: integer):integer;
procedure MoveSelected(byXmm, byYmm: double);
procedure SelectAll;
procedure SelectAllInRect(obdlz: TRect; ciastocne: boolean = false);
procedure DeselectAll;
procedure DelSelected;
procedure DelFeatureByID(fid: integer);
procedure Draw(copyCanvas: Boolean = True);
procedure DrawHighlightedOnly(copyCanvas: Boolean = True);
procedure GetFullInfo(target: string = 'debug');
procedure SetZoom(zoomVal: Double = 1; curX: integer = 0; curY: integer = 0);
function GetCenterPosBack: byte;
function GetCenterPosByNum(num: Byte): Byte;
procedure SetCenterPosByNum(newVal: Byte; cenPosNumber: byte = 0);
procedure LoadFont(fontfilename: string);
// combo veci
function AddCombo(id: integer = -1): integer;
function MakeCombo: integer;
function ComboExists(comboId: integer): boolean;
procedure GetComboFeatures(var poleObjektov: TPoleIntegerov; comboID: integer);
function GetComboBoundingBox(comboID: integer): TMyRect;
function GetComboByID(cid: integer): TComboObject;
procedure SelectCombo(comboID: integer; sel_state: boolean = true);
procedure ExplodeCombo(comboID: integer);
// GuideLine-y
function AddGuideLine(typ: string; param_1: double; param_2: double = 0; param_3: double = 0; side: byte = 1): TGuideObject;
function GetGuideLineById(gid: integer): TGuideObject;
procedure DelGuideLineById(gid: integer);
procedure DeselectAllGuidelines;
// undo
procedure PrepareUndoStep;
procedure CreateUndoStep(undoType: string; subjectType: string; subjectID: integer);
procedure Undo;
function GetNumberOfUndoSteps: integer;
public
function AddFeature(ftype: integer): integer; overload;
function AddFeature(ftype: string): integer; overload;
end;
implementation
uses uMain, uPanelSett, uDebug, uTranslate, uDrawLib, uObjectFeaturePolyLine,
uObjectFont, uObjectFontZnak, uFeaEngrave, uGuides;
constructor TPanelObject.Create;
begin
inherited Create;
objFeatures := TFeaList.Create;
objCombos := TComboList.Create;
objGuides := TGuideList.Create;
objFonty := TStringList.Create;
LoadFont('din17i_cp1250.font');
objID := -1;
objNewFeatureId := 1;
objNextComboId := 1;
objSideZeroes[1] := cpLB;
objSideZeroes[2] := cpLB;
objRoh_c1 := MyPoint(0,0);
objDrawOffsetX := 5;
objDrawOffsetY := fMain.ToolBar1.Height + 5;
objZoomOffsetX := 0;
objZoomOffsetY := 0;
objGrid := 0.5;
objZoom := 9999;
objZoomFactor := 1;
objStranaVisible := 1; // ktora strana je prave viditelna (1=predna strana, 2=zadna strana)
objCurrentSide := objStranaVisible;
objHasChanged := false;
SetLength(objUndoList2, 100);
objNextUndoStepID := 0;
objIndexOfNextUndoStep := 0;
objMaterialVlastny := false;
objHranaStyl := '0';
objHranaRozmer := 0;
objHranaObrobenaBottom := false;
objHranaObrobenaRight := false;
objHranaObrobenaTop := false;
objHranaObrobenaLeft := false;
end;
destructor TPanelObject.Destroy;
begin
FreeAndNil(objFeatures);
inherited Destroy;
end;
procedure TPanelObject.SetSirka(val: Double);
begin
objSirka := val;
SetRoh_c1;
fPanelSett.edSirka.Text := FloatToStr(val);
SetZoom;
objHasChanged := true;
end;
procedure TPanelObject.SetVyska(val: Double);
begin
objVyska := val;
SetRoh_c1;
fPanelSett.edVyska.Text := FloatToStr(val);
SetZoom;
objHasChanged := true;
end;
function TPanelObject.GetCenterPos: byte;
begin
result := objSideZeroes[objCurrentSide];
end;
procedure TPanelObject.SetCenterPos(newVal: byte);
begin
SetCenterPosByNum(newVal);
end;
procedure TPanelObject.SetCenterPosByNum(newVal: Byte; cenPosNumber: byte = 0);
var
oldC, newC, diff: TMyPoint;
i: integer;
guide: TGuideObject;
begin
if cenPosNumber = 0 then cenPosNumber := objCurrentSide;
// ked sa zmeni poloha pociatku sur.sys., prekotuje vsetky features
// najprv si absolutne zakotujeme stary aj novy center (pevna nula je vlavo dole)
if objSideZeroes[cenPosNumber] = cpLT then begin oldC.X := 0; oldC.Y := objVyska; end;
if objSideZeroes[cenPosNumber] = cpLB then begin oldC.X := 0; oldC.Y := 0; end;
if objSideZeroes[cenPosNumber] = cpRT then begin oldC.X := objSirka; oldC.Y := objVyska; end;
if objSideZeroes[cenPosNumber] = cpRB then begin oldC.X := objSirka; oldC.Y := 0; end;
if objSideZeroes[cenPosNumber] = cpCEN then begin oldC.X := objSirka/2; oldC.Y := objVyska/2; end;
if newVal = cpLT then begin newC.X := 0; newC.Y := objVyska; end;
if newVal = cpLB then begin newC.X := 0; newC.Y := 0; end;
if newVal = cpRT then begin newC.X := objSirka; newC.Y := objVyska; end;
if newVal = cpRB then begin newC.X := objSirka; newC.Y := 0; end;
if newVal = cpCEN then begin newC.X := objSirka/2; newC.Y := objVyska/2; end;
// teraz si vycislime rozdiel medzi starym a novym centrom
diff.X := newC.X - oldC.X;
diff.Y := newC.Y - oldC.Y;
// a teraz "posunieme" vsetky feature
for i:=0 to objFeatures.Count-1 do
if Assigned( objFeatures[i] ) AND (objFeatures[i].Strana = cenPosNumber) then begin
objFeatures[i].X := objFeatures[i].X - diff.X;
objFeatures[i].Y := objFeatures[i].Y - diff.Y;
// ak je to polyline, musime prekotovat kazdy vertex
if objFeatures[i].Typ = ftPolyLineGrav then begin
(objFeatures[i] as TFeaturePolyLineObject).MovePolylineBy(-diff.X, -diff.Y);
end;
end;
// aj vsetky combo objekty
for i:=0 to objCombos.Count-1 do
if Assigned( objCombos[i] ) AND (objFeatures[i].Strana = cenPosNumber) then begin
objCombos[i].X := objCombos[i].X - diff.X;
objCombos[i].Y := objCombos[i].Y - diff.Y;
end;
// aj vsetky guide lines treba prekotovat
for i:=0 to objGuides.Count-1 do begin
guide := objGuides[i];
if Assigned(guide) then begin
if guide.Typ = 'V' then guide.Param1 := guide.Param1 - diff.X;
if guide.Typ = 'H' then guide.Param1 := guide.Param1 - diff.Y;
end;
end;
objSideZeroes[cenPosNumber] := newVal;
SetRoh_c1;
end;
procedure TPanelObject.SetCurrentSide(newVal: Byte);
begin
objCurrentSide := newVal;
SetRoh_c1;
end;
procedure TPanelObject.SetHasChanged(val: Boolean);
var
sZnacka: string;
begin
if (objHasChanged <> val) then begin // len ak sa prave teraz meni hodnota, tak to vyznacime v title bare
sZnacka := ' (*)';
if not objHasChanged then begin
fMain.Caption := fMain.Caption + sZnacka;
end else begin
fMain.Caption := Copy( fMain.Caption, 1, Length(fMain.Caption) - Length(sZnacka));
end;
objHasChanged := val;
end;
end;
procedure TPanelObject.SetRoh_c1;
begin
if objSideZeroes[objCurrentSide] = cpLB then objRoh_c1 := MyPoint(0,0);
if objSideZeroes[objCurrentSide] = cpRB then objRoh_c1 := MyPoint(-objSirka, 0);
if objSideZeroes[objCurrentSide] = cpRT then objRoh_c1 := MyPoint(-objSirka, -objVyska);
if objSideZeroes[objCurrentSide] = cpLT then objRoh_c1 := MyPoint(0, -objVyska);
if objSideZeroes[objCurrentSide] = cpCEN then objRoh_c1 := MyPoint((-objSirka/2), (-objVyska/2));
end;
function TPanelObject.AddFeature(ftype: string): integer;
begin
result := AddFeature( StrToInt(ftype) );
end;
procedure TPanelObject.RedrawSurrounding;
var
r: TRect;
begin
// "osekneme" zobrazenie objektov mimo panela (napr. kapsa, co presahuje mimo panel)
with BackPlane.Canvas do begin
Pen.Color := objBgndCol;
Brush.Color := objBgndCol;
// nalavo
r.Left := 0;
r.Right := PX(objRoh_c1.x, 'x');
r.Top := 0;
r.Bottom := fMain.ClientHeight;
Rectangle(r);
// napravo
r.Left := PX(objRoh_c1.X + objSirka, 'x');
r.Right := fMain.ClientWidth;
r.Top := 0;
r.Bottom := fMain.ClientHeight;
Rectangle(r);
// hore
r.Left := 0;
r.Right := fMain.ClientWidth;
r.Top := 0;
r.Bottom := PX(objRoh_c1.Y + objVyska, 'y');
Rectangle(r);
// dolu
r.Left := 0;
r.Right := fMain.ClientWidth;
r.Top := PX(objRoh_c1.Y, 'y');
r.Bottom := fMain.ClientHeight;
Rectangle(r);
end;
end;
function TPanelObject.AddFeature(ftype: integer): integer;
var
new_index: integer;
begin
result := -1;
try
// vytvori novu feature a vrati jej ID
if ftype <= 0 then Exit;
if ftype = ftPolyLineGrav then
new_index := objFeatures.Add(TFeaturePolyLineObject.Create(Self))
else
new_index := objFeatures.Add(TFeatureObject.Create(Self, -1, ftype));
objFeatures[new_index].ID := objNewFeatureId;
// objFeatures[new_index].Param5 := 'din17i_cp1250.font'; // default
Inc(objNewFeatureId);
objHasChanged := true;
result := objFeatures[new_index].ID;
except
MessageBox(0, PChar(TransTxt('Couldn''t create new object')), PChar(TransTxt('Error')), MB_ICONERROR);
end;
end;
function TPanelObject.AddCombo(id: integer = -1): integer;
var
new_index: integer;
begin
// inicializuje nove combo v poli, priradi mu spravne ID
// samotne features na paneli donho neprida
// combo z prvkov na paneli vytvarat cez metodu MAKECOMBO
result := -1;
try
new_index := objCombos.Add(TComboObject.Create);
// ak je zadany parameter, tak vytvori nove combo presne s takym IDckom
// ak nie, najde najblizsi nepouzity a vytvori combo
if (id > -1) then begin
objCombos[new_index].ID := id;
// ak zadane ID pre nove combo bolo vyssie, nez je automaticky zvolene ID pre nove comba, zvysi ho
if (objNextComboId <= id) then objNextComboId := id+1;
end else begin
objCombos[new_index].ID := objNextComboId;
Inc(objNextComboId);
end;
objHasChanged := true;
result := objCombos[new_index].ID;
except
MessageBox(0, PChar(TransTxt('Couldn''t create new combo')), PChar(TransTxt('Error')), MB_ICONERROR);
end;
end;
function TPanelObject.MakeCombo: integer;
var
i, newComboID: integer;
tmp_rect: TMyRect;
tmp_bod: TMyPoint;
begin
{ z prave vyselectovanych prvkov vytvori combo otvor,
de facto len zgrupne prvky do jedneho tym, ze im nastavi ComboID
a vratime cislo vytvoreneho comba }
result := -1;
if GetSelectedFeaturesNum.i1 <= 0 then
Exit;
// vytvori nove combo a ulozi si jeho ID
newComboID := _PNL.AddCombo;
for i:=0 to objFeatures.Count-1 do
if Assigned(objFeatures[i]) then
if objFeatures[i].Selected then
objFeatures[i].ComboID := newComboID;
// standardne bude combo, ktore sa vytvori, polohovane na svoj stred
tmp_rect := _PNL.GetComboBoundingBox(newComboID);
tmp_bod.X := tmp_rect.TopL.X + ((tmp_rect.BtmR.X-tmp_rect.TopL.X)/2);
tmp_bod.Y := tmp_rect.TopL.Y + ((tmp_rect.BtmR.Y-tmp_rect.TopL.Y)/2);
_PNL.GetComboByID(newComboID).PolohaObject := -1;
_PNL.GetComboByID(newComboID).Poloha := tmp_bod;
_PNL.GetComboByID(newComboID).Velkost := MyPoint( Abs(tmp_rect.BtmR.X-tmp_rect.TopL.X) , Abs(tmp_rect.TopL.Y-tmp_rect.BtmR.Y));
result := newComboID;
end;
function TPanelObject.ComboExists(comboId: integer): boolean;
var
i: integer;
begin
// zistuje, ci combo s danym IDckom uz existuje
result := false;
for i:=0 to objCombos.Count-1 do
if Assigned(objCombos[i]) then
if objCombos[i].ID = comboId then
result := true;
end;
function TPanelObject.GetFeatureByID(fid: integer): TFeatureObject;
var
i: integer;
begin
result := nil;
for i:=0 to objFeatures.Count-1 do
if objFeatures[i].ID = fid then begin
result := objFeatures[i];
Break;
end;
end;
function TPanelObject.GetFeaturesAt(var poleNajdenych: TPoleIntegerov; bod_x, bod_y: integer): boolean;
var
i: integer;
bod_mm: TMyPoint;
najdeneComba: TStringList;
begin
najdeneComba := TStringList.Create;
bod_mm := MyPoint( MM(bod_x, 'x'), MM(bod_y, 'y') );
SetLength(poleNajdenych, 0);
for i:=0 to objFeatures.Count-1 do
if Assigned(objFeatures[i]) then
if (not objFeatures[i].Locked) AND (objFeatures[i].IsOnPoint(bod_mm)) AND (objFeatures[i].Strana = _PNL.StranaVisible) then begin
if objFeatures[i].ComboID = -1 then begin
// Ak sa objekt nachadza na bode kliknutia, zvacsi pole najdenych o jedna
// a tento objekt do toho pola prida.
SetLength(poleNajdenych, Length(poleNajdenych)+1 ); // zvacsime pole
poleNajdenych[ Length(poleNajdenych)-1 ] := objFeatures[i].ID; // a pridame najdene ID do pola
end else begin
// Ak je objekt sucastou comba, pozrie sa do pola najdenych combo objektov
// a ak este to combo nezapocital do najdenych, prida ho
// ale pri dalsom objekte z toho comba ho uz nezapocita
if najdeneComba.IndexOf(IntToStr(objFeatures[i].ComboID)) = -1 then begin
najdeneComba.Add( IntToStr(objFeatures[i].ComboID) );
SetLength(poleNajdenych, Length(poleNajdenych)+1 ); // zvacsime pole
poleNajdenych[ Length(poleNajdenych)-1 ] := objFeatures[i].ID; // a pridame najdene ID do pola
end;
end;
end;
result := (Length(poleNajdenych) > 0); // este nastavime navratovu hodnotu (TRUE = nasiel sa aspon jeden)
najdeneComba.Free;
end;
procedure TPanelObject.GetComboFeatures(var poleObjektov: TPoleIntegerov; comboID: integer);
var
i: integer;
begin
// naplni dodane pole ID-ckami vsetkych objektov, ktore patria do daneho comba
SetLength(poleObjektov, 0);
for i:=0 to objFeatures.Count-1 do
if Assigned(objFeatures[i]) then
if objFeatures[i].ComboID = comboID then begin
SetLength(poleObjektov, Length(poleObjektov)+1 ); // zvacsime pole
poleObjektov[ Length(poleObjektov)-1 ] := objFeatures[i].ID; // a pridame najdene ID do pola
end;
end;
function TPanelObject.GetCenterPosBack: byte;
begin
if objStranaVisible = 1 then
result := objSideZeroes[2]
else
result := objSideZeroes[1];
end;
function TPanelObject.GetCenterPosByNum(num: Byte): Byte;
begin
Result := objSideZeroes[num];
end;
function TPanelObject.GetComboBoundingBox(comboID: integer): TMyRect;
var
poleComboObj: TPoleIntegerov;
i: integer;
tmp_box: TMyRect;
begin
GetComboFeatures( poleComboObj, comboID );
for i:=0 to High(poleComboObj) do begin
// pri prvom prvku dame jeho box cely ako je do vysledku
if i=0 then result := GetFeatureByID(poleComboObj[i]).BoundingBox
else begin
// pri kazdom dalsom budeme tento box rozsirovat (ak je treba)
tmp_box := GetFeatureByID(poleComboObj[i]).BoundingBox;
result.TopL.X := Min( result.TopL.X , tmp_box.TopL.X );
result.TopL.Y := Max( result.TopL.Y , tmp_box.TopL.Y );
result.BtmR.X := Max( result.BtmR.X , tmp_box.BtmR.X );
result.BtmR.Y := Min( result.BtmR.Y , tmp_box.BtmR.Y );
end;
end;
end;
function TPanelObject.GetComboByID(cid: integer): TComboObject;
var
i: integer;
begin
result := nil;
for i := 0 to objCombos.Count-1 do begin
if (objCombos[i].ID = cid) then
result := objCombos[i];
end;
end;
procedure TPanelObject.DelSelected;
var
i: integer;
ids: TPoleIntegerov;
begin
PrepareUndoStep;
// skopirujeme ficre-na-zmazanie do undo pola (kym este maju pridelene comboID)
for i := 0 to objFeatures.Count-1 do
if objFeatures[i].Selected then begin
CreateUndoStep('DEL', 'FEA', objFeatures[i].ID);
// odlozime si ID vsetkych, co treba vymazat
SetLength( ids, Length(ids)+1 );
ids[ Length(ids)-1 ] := objFeatures[i].ID;
end;
// zmazeme vsetky comba (vyselectovane)
for i := 0 to objFeatures.Count-1 do
if (objFeatures[i].Selected) AND (objFeatures[i].ComboID > -1) then begin
CreateUndoStep('DEL', 'COM', objFeatures[i].ComboID);
ExplodeCombo(objFeatures[i].ComboID);
end;
//a zmazeme aj vsetky ficre
for i := 0 to High(ids) do
DelFeatureByID( ids[i] );
end;
procedure TPanelObject.ExplodeCombo(comboID: integer);
var
i: integer;
delIndex: integer;
begin
if comboID < 0 then Exit;
for i:=0 to objFeatures.Count-1 do
if (Assigned(objFeatures[i])) AND (objFeatures[i].ComboID = comboID) then begin
objFeatures[i].ComboID := -1;
end;
delIndex := -1;
for i:=0 to objCombos.Count-1 do
if (Assigned(objCombos[i])) AND (objCombos[i].ID = comboID) then
delIndex := i;
// nemozem ho odstranit priamo v slucke FOR, lebo ona by potom pokracovala az po uz neexistujuci index
if delIndex > -1 then begin
objCombos.Delete(delIndex);
objCombos.Capacity := objCombos.Count;
end;
end;
procedure TPanelObject.DelFeatureByID(fid: integer);
var
i: integer;
begin
for i:=0 to objFeatures.Count-1 do
if (Assigned(objFeatures[i])) AND (objFeatures[i].id = fid) then begin
objFeatures.Delete(i);
objHasChanged := true;
break;
end;
end;
procedure TPanelObject.KresliZrazenyRoh(c_rohu: byte; x_zrazeneho_rohu_mm, y_zrazeneho_rohu_mm: double; horizontal, vertikal: boolean);
var
roh, zraz_roh: TPoint;
priemer_px, polomer_px: integer;
begin
zraz_roh := Point( PX2(x_zrazeneho_rohu_mm,'x') , PX2(y_zrazeneho_rohu_mm,'y') );
case c_rohu of
1: roh := Point( PX2(0,'x') , PX2(0,'y') );
2: roh := Point( PX2(objSirka,'x') , PX2(0,'y') );
3: roh := Point( PX2(objSirka,'x') , PX2(objVyska,'y') );
4: roh := Point( PX2(0,'x') , PX2(objVyska,'y') );
end;
with BackPlane.Canvas do begin
priemer_px := PX((objRadius-objHranaRozmer)*2);
polomer_px := PX((objRadius-objHranaRozmer));
if horizontal AND vertikal then
if (objHranaRozmer < objRadius) then begin
case c_rohu of
1: Arc(zraz_roh.X, zraz_roh.Y, zraz_roh.X+priemer_px+1, zraz_roh.Y-priemer_px-1, -9999, zraz_roh.Y-polomer_px, zraz_roh.X+polomer_px, 9999);
2: Arc(zraz_roh.X, zraz_roh.Y, zraz_roh.X-priemer_px-1, zraz_roh.Y-priemer_px-1, zraz_roh.x-polomer_px, 9999, 9999, zraz_roh.Y-polomer_px);
3: Arc(zraz_roh.X, zraz_roh.Y, zraz_roh.X-priemer_px-1, zraz_roh.Y+priemer_px+1, 9999, zraz_roh.Y+polomer_px, zraz_roh.X-polomer_px, -9999);
4: Arc(zraz_roh.X, zraz_roh.Y, zraz_roh.X+priemer_px+1, zraz_roh.Y+priemer_px+1, zraz_roh.X+polomer_px, -9999, -9999, zraz_roh.Y+polomer_px);
end;
end
else
if (objRadius = 0) then begin // ak je roh bez radiusu, nakreslime diagonal ciaru
MoveTo( roh.X, roh.Y );
LineTo( zraz_roh.X, zraz_roh.Y );
end
else
else begin
if (objRadius = 0) then polomer_px := PX(objHranaRozmer);
if horizontal then
if (c_rohu = 1) OR (c_rohu = 4) then begin
MoveTo( roh.X, zraz_roh.Y );
LineTo( zraz_roh.X+polomer_px+1, zraz_roh.Y );
end else begin
MoveTo( roh.X, zraz_roh.Y );
LineTo( zraz_roh.X-polomer_px-1, zraz_roh.Y );
end;
if vertikal then
if (c_rohu = 1) OR (c_rohu = 2) then begin
MoveTo( zraz_roh.X, roh.Y );
LineTo( zraz_roh.X, zraz_roh.Y-polomer_px-1 );
end else begin
MoveTo( zraz_roh.X, roh.Y );
LineTo( zraz_roh.X, zraz_roh.Y+polomer_px+1 );
end;
end;
end;
end;
procedure TPanelObject.Draw(copyCanvas: Boolean = True);
var
i, j: integer;
center: TPoint;
center_radius: integer;
rect: TRect;
hranaStart: double;
gridStepPx: Integer;
gridStepMm: Single;
gridOffset: TMyPoint;
rPX: Integer;
rohC1PX: array [0..1] of integer;
rozmeryPX: array [0..1] of Integer;
{$IFDEF DEBUG}
CPUTimestampStart, CPUTimestampEnd: Int64;
FPS: Double;
{$ENDIF}
begin
if not Assigned(BackPlane) then EXIT;
{$IFDEF DEBUG}
QueryPerformanceCounter(CPUTimestampStart);
{$ENDIF}
SetZoom;
if (objPovrch = 'elprirodny') then begin
objBgndCol := farbaBgndTmavy;
objSurfCol := farbaPovrchEloxNatural;
end else if (objPovrch = 'elcierny') then begin
objBgndCol := farbaBgndSvetly;
objSurfCol := farbaPovrchEloxBlack;
end else if (objPovrch = 'surovy') OR (objPovrch = 'bruseny') then begin
objBgndCol := farbaBgndTmavy;
objSurfCol := farbaPovrchSurovy;
end;
objBordCol := clGray;
with BackPlane.Canvas do begin
// zmazanie platna
Pen.Width := 1;
Pen.Style := psSolid;
Pen.Mode := pmCopy;
Brush.Style := bsSolid;
// pozadie uz nemusim vykreslovat osobitne, lebo sa vykresluje panel a 4 pruhy pozadia okolo neho (neskor)
Pen.Color := objBgndCol;
Brush.Color := objBgndCol;
// Rectangle(0,fmain.ToolBar1.Height, fMain.ClientWidth,fMain.ClientHeight);
// vykreslenie samotneho panela
// najprv celu plochu panela vyplnim pozadim, aby pri paneli so zaoblenymi rohmi bola farba v zaoblenych rohoch farba pozadia
if objRadius > 0 then begin
rPX := PX(objRadius); // rozmer zaoblenia v PX
rohC1PX[0] := PX(objRoh_c1.X, 'x');
rohC1PX[1] := PX(objRoh_c1.Y, 'y');
rozmeryPX[0] := PX(objSirka);
rozmeryPX[1] := PX(objVyska);
// vykreslenie pozadia rohov
// #1
rect.Left := rohC1PX[0];
rect.Top := rohC1PX[1];
rect.Width := rPX;
rect.Height := -rPX;
Rectangle(rect);
// #2
rect.Left := rohC1PX[0] + rozmeryPX[0];
rect.Top := rohC1PX[1];
rect.Width := -rPX;
rect.Height := -rPX;
Rectangle(rect);
// #3
rect.Left := rohC1PX[0] + rozmeryPX[0];
rect.Top := rohC1PX[1] - rozmeryPX[1];
rect.Width := -rPX;
rect.Height := rPX;
Rectangle(rect);
// #4
rect.Left := rohC1PX[0];
rect.Top := rohC1PX[1] - rozmeryPX[1];
rect.Width := rPX;
rect.Height := rPX;
Rectangle(rect);
end;
// teraz uz panel
Pen.Color := objBordCol;
Brush.Color := objSurfCol;
RoundRect( objDrawOffsetX + objZoomOffsetX,
objDrawOffsetY + objZoomOffsetY,
objDrawOffsetX + objZoomOffsetX + Px(objSirka) + 1,
objDrawOffsetY + objZoomOffsetY + Px(objVyska) + 1,
Px(objRadius*2), Px(objRadius*2)
);
// snapping grid
// pre vykreslenie v 'XOR' rezime sa hodia tieto rezimy (pre bielu farbu): Not, Maskpennot, Notmask, Xor
if fGuides.comShowGrid.ItemIndex > gridNone then begin
// prevencia prehusteneho gridu
gridStepPx := PX(objGrid);
gridStepMm := objGrid;
if gridStepPx < 1 then gridStepPx := 1; // moze sa stat, ze je to nula ked grid je 0.5mm a Zoom je 0.998 tak 0.5 * 0.998 je po zaokruhleni nula !
while gridStepPx < 10 do begin
gridStepPx := gridStepPx * 2;
gridStepMm := gridStepMm * 2;
end;
{ TODO -oenovacek -c : upravit tak, aby sa polia nastavovali a pocitali len pre viditelnu cast panela }
SetLength(objGridPointsX, Round(objSirka / gridStepMm));
SetLength(objGridPointsY, Round(objVyska / gridStepMm));
// offset vykreslovania gridu pri roznych nul.bodoch
SetRoh_c1;
gridOffset := objRoh_c1;
for i := 0 to High(objGridPointsX) do
objGridPointsX[i] := PX( (gridStepMm * i) + gridOffset.X , 'x');
for i := 0 to High(objGridPointsY) do
objGridPointsY[i] := PX( (gridStepMm * i) + gridOffset.Y , 'y');
if fGuides.comShowGrid.ItemIndex = gridDots then begin
Pen.Color := objBgndCol;
for i := 0 to High(objGridPointsX) do begin
if (objGridPointsX[i] > 0) AND (objGridPointsX[i] < fMain.ClientWidth) then
for j := 0 to High(objGridPointsY) do begin
if (objGridPointsY[j] > 20) AND (objGridPointsY[j] < fMain.ClientHeight) then begin
MoveTo( objGridPointsX[i] , objGridPointsY[j] );
LineTo( objGridPointsX[i]+1 , objGridPointsY[j] );
end;
end;
end;
end;
if fGuides.comShowGrid.ItemIndex = gridLines then begin
Pen.Color := objBordCol;
Pen.Style := psDot;
for i := 0 to High(objGridPointsX) do begin
if (objGridPointsX[i] > 0) AND (objGridPointsX[i] < fMain.ClientWidth) then begin
MoveTo( objGridPointsX[i] , PX(gridOffset.Y, 'y') );
LineTo( objGridPointsX[i] , PX(objVyska + gridOffset.Y, 'y'));
end;
end;
for j := 0 to High(objGridPointsY) do begin
if (objGridPointsY[j] > 20) AND (objGridPointsY[j] < fMain.ClientHeight) then begin
MoveTo( PX(gridOffset.X, 'x') , objGridPointsY[j] );
LineTo( PX(objSirka + gridOffset.X, 'x') , objGridPointsY[j] );
end;
end;
end;
end;
// vykreslenie pripadnej zrazenej hrany
if (objHranaStyl = 'cham45') then begin
if objStranaVisible = 1 then begin
Pen.Color := clOlive;
Pen.Style := psSolid;
end else begin
Pen.Color := clGreen;
Pen.Style := psDash;
end;
Brush.Style := bsClear;
hranaStart := Max(objRadius,objHranaRozmer);
// spodna hrana
if objHranaObrobenaBottom then begin
MoveTo( PX2(hranaStart,'x') , PX2(objHranaRozmer,'y'));
LineTo( PX2(objSirka - hranaStart,'x') , PX2(objHranaRozmer,'y'));
end;
// prava hrana
if objHranaObrobenaRight then begin
MoveTo( PX2(objSirka-objHranaRozmer,'x') , PX2(hranaStart,'y'));
LineTo( PX2(objSirka-objHranaRozmer,'x') , PX2(objVyska - hranaStart,'y'));
end;
// vrchna hrana
if objHranaObrobenaTop then begin
MoveTo( PX2(objSirka-hranaStart,'x') , PX2(objVyska-objHranaRozmer,'y'));
LineTo( PX2(hranaStart,'x') , PX2(objVyska-objHranaRozmer,'y'));
end;
// lava hrana
if objHranaObrobenaLeft then begin
MoveTo( PX2(objHranaRozmer,'x') , PX2(objVyska - hranaStart,'y'));
LineTo( PX2(objHranaRozmer,'x') , PX2(hranaStart,'y'));
end;
// roh c.1
KresliZrazenyRoh(1, objHranaRozmer, objHranaRozmer, objHranaObrobenaBottom, objHranaObrobenaLeft);
KresliZrazenyRoh(2, objSirka-objHranaRozmer, objHranaRozmer, objHranaObrobenaBottom, objHranaObrobenaRight);
KresliZrazenyRoh(3, objSirka-objHranaRozmer, objVyska-objHranaRozmer, objHranaObrobenaTop, objHranaObrobenaRight);
KresliZrazenyRoh(4, objHranaRozmer, objVyska-objHranaRozmer, objHranaObrobenaTop, objHranaObrobenaLeft);
end;
end;
// kresli cosmetic prvky, ktore maju byt prekryte ostatnymi (napr. zrazenie hran)
for i:=0 to objFeatures.Count-1 do
objFeatures[i].Draw_CosmeticLowPriority;
// kresli prvky, ktore nie su skrz (kapsy napr.)
for i:=0 to objFeatures.Count-1 do
if (objFeatures[i].Typ = ftPolyLineGrav) then
(objFeatures[i] as TFeaturePolyLineObject).Draw // mozno trochu nestandardne - ale v Class Polyline neviem volat Draw() automatizovane, tak takto rucne ju volam - gravirovane objekty
else
objFeatures[i].Draw_Blind;
// najprv objekty, ktore nejdu skrz
// for i:=0 to objFeatures.Count-1 do
// if (objFeatures[i].Hlbka1 < 9999) then
// if (objFeatures[i].Typ = ftPolyLineGrav) then
// (objFeatures[i] as TFeaturePolyLineObject).Draw // mozno trochu nestandardne - ale v Class Polyline neviem volat Draw() automatizovane, tak takto rucne ju volam - gravirovane objekty
// else
// objFeatures[i].Draw_Through;
// kresli objekty, ak su skrz
for i:=0 to objFeatures.Count-1 do
objFeatures[i].Draw_Through;
// kresli cosmetic prvky objektov (napr. 3/4 kruh na zavite)
for i:=0 to objFeatures.Count-1 do
objFeatures[i].Draw_Cosmetic;
// teraz "osekneme" zobrazenie objektov mimo panela (napr. kapsa, co presahuje mimo panel)
RedrawSurrounding;
// kresli cosmetic prvky - tie sa zobrazuju aj mimo panela
for i:=0 to objFeatures.Count-1 do
objFeatures[i].Draw_CosmeticHighPriority;
// ten co je highlightovany - zvycajne len 1 objekt
DrawHighlightedOnly(false);
// a este raz - tie, co su vyselectovane - tak ich selectovaci ramik
objSelCombosDrawn := ''; // (pre vysvetlenie pozri deklaraciu)
for i:=0 to objFeatures.Count-1 do
objFeatures[i].DrawSelected;
// a nakoniec este guideliney
if cfg_ShowGuides then
for i:=0 to objGuides.Count-1 do
objGuides[i].Draw;
objCurrentSide := objStranaVisible;
// vykreslenie pociatku suradneho systemu
case objSideZeroes[objStranaVisible] of
cpLT : center := Point(
objDrawOffsetX + objZoomOffsetX,
objDrawOffsetY + objZoomOffsetY
);
cpLB : center := Point(
objDrawOffsetX + objZoomOffsetX,
objDrawOffsetY + objZoomOffsetY + Px(objVyska)
);
cpRT : center := Point(
objDrawOffsetX + objZoomOffsetX + Px(objSirka),
objDrawOffsetY + objZoomOffsetY
);
cpRB : center := Point(
objDrawOffsetX + objZoomOffsetX + Px(objSirka),
objDrawOffsetY + objZoomOffsetY + Px(objVyska)
);
cpCEN : center := Point(
objDrawOffsetX + objZoomOffsetX + Px(objSirka/2),
objDrawOffsetY + objZoomOffsetY + Px(objVyska/2)
);
end;
{
************** ak sa panel zrkadli, treba to takto: *******************
if objCenterPos = 'TL' then
center := Point(
objDrawOffsetX + objZoomOffsetX + Px(SirkaPolovica - objMirrorX*SirkaPolovica),
objDrawOffsetY + objZoomOffsetY + Px(VyskaPolovica - objMirrorY*VyskaPolovica)
);
if objCenterPos = 'BL' then
center := Point(
objDrawOffsetX + objZoomOffsetX + Px(SirkaPolovica - objMirrorX*SirkaPolovica),
objDrawOffsetY + objZoomOffsetY + Px(VyskaPolovica + objMirrorY*VyskaPolovica)
);
if objCenterPos = 'TR' then
center := Point(
objDrawOffsetX + objZoomOffsetX + Px(SirkaPolovica + objMirrorX*SirkaPolovica),
objDrawOffsetY + objZoomOffsetY + Px(VyskaPolovica - objMirrorY*VyskaPolovica)
);
if objCenterPos = 'BR' then
center := Point(
objDrawOffsetX + objZoomOffsetX + Px(SirkaPolovica + objMirrorX*SirkaPolovica),
objDrawOffsetY + objZoomOffsetY + Px(VyskaPolovica + objMirrorY*VyskaPolovica)
);
if objCenterPos = 'C' then
center := Point(
objDrawOffsetX + objZoomOffsetX + Px(SirkaPolovica),
objDrawOffsetY + objZoomOffsetY + Px(VyskaPolovica)
);
}
center_radius := 5;
with BackPlane.Canvas do begin
Pen.Width := 1;
Pen.Color := clBlack;
Pen.Style := psSolid;
Pen.Mode := pmCopy;
Brush.Style := bsSolid;
Brush.Color := clYellow;
Rectangle( center.X, center.Y-1, center.X+center_radius+10, center.Y+2 );
Rectangle( center.X-1, center.Y, center.X+2, center.Y-center_radius-10 );
{
************** ak sa panel zrkadli, treba to takto: *******************
Rectangle( center.X, center.Y-1, center.X+(center_radius+10)*objMirrorX, center.Y+2 );
Rectangle( center.X-1, center.Y, center.X+2, center.Y-(center_radius+10)*objMirrorY );
}
Ellipse( center.X-center_radius, center.Y-center_radius, center.X+center_radius, center.Y+center_radius );
Font.Size := 8;
Font.Color := clYellow;
Font.Name := 'Tahoma';
Pen.Color := clYellow;
Brush.Color := clBlack;
TextOut( center.X + center_radius + 15 , center.Y-6 , 'X' );
TextOut( center.X-3 , center.Y - center_radius - 24 , 'Y' );
{
************** ak sa panel zrkadli, treba to takto: *******************
TextOut( center.X+((center_radius+15)*objMirrorX)-3, center.Y-6, 'X' );
TextOut( center.X-3, center.Y-((center_radius+18)*objMirrorY)-6, 'Y' );
}
{$IFDEF DEBUG}
QueryPerformanceCounter(CPUTimestampEnd);
FPS := CPUTimestampFrequency / (CPUTimestampEnd - CPUTimestampStart);
Font.Size := 20;
TextOut( 10, 70, 'FPS: ' + FloatToStr(FPS));
TextOut( 10, 100, 'avg: ' + FloatToStr(FPSavg));
FPSsum := FPSsum + FPS;
Inc(FPSsumCount);
if FPSsumCount = 100 then begin
FPSavg := RoundTo(FPSsum / FPSsumCount, -2);
FPSsum := 0;
FPSsumCount := 0;
end;
{$ENDIF}
end;
if multiselectShowing then MultiselectTlacitka.Draw(false);
// na zaver sa cely vykresleny panel skopiruje na viditelnu canvas
if (copyCanvas) then begin
rect := fMain.Canvas.ClipRect;
fMain.Canvas.CopyRect(rect, BackPlane.Canvas, rect);
end;
end;
procedure TPanelObject.DrawHighlightedOnly(copyCanvas: Boolean = True);
var
i: Integer;
rect: TRect;
begin
// ten co je highlightovany - zvycajne len 1 objekt
for i:=0 to objFeatures.Count-1 do
if objFeatures[i].Highlighted then
if (objFeatures[i].Typ = ftPolyLineGrav) then
(objFeatures[i] as TFeaturePolyLineObject).DrawHighlighted
else
objFeatures[i].DrawHighlighted;
// na zaver sa skopiruje na viditelnu canvas
if (copyCanvas) then begin
rect := fMain.Canvas.ClipRect;
fMain.Canvas.CopyRect(rect, BackPlane.Canvas, rect);
end;
end;
procedure TPanelObject.SetZoom(zoomVal: Double = 1; curX: integer = 0; curY: integer = 0);
var
zoomx,zoomy: Double;
edgeDistPX_x_old: integer;
edgeDistPX_x_new: integer;
edgeDistMM_x_old: Double;
edgeDistPX_y_old: integer;
edgeDistPX_y_new: integer;
edgeDistMM_y_old: Double;
begin
// ochrana pred delenim nulou (pri volani procedury pocas startu)
if (objSirka = 0) OR (objVyska = 0) then begin
objZoom := 1;
Exit;
end;
// hranice zoomovania
if ((zoomVal > 1) AND (objZoom < 50)) OR
((zoomVal < 1) AND (objZoom > 1)) then
objZoomFactor := objZoomFactor * zoomVal; // zoomuje len ak platia tieto 2 podmienky
// ak bola funkcia zavolana s parametrom ZoomVal = 0, resetne uzivatelsky zoom
if (zoomVal = 0) then
objZoomFactor := 1;
// ak bola funkcia zavolana s parametrami CurX/CurY = -1, resetne uzivatelsky offset
if (curX = -1) AND (curY = -1) then begin
objZoomOffsetX := 0;
objZoomOffsetY := 0;
end;
// ulozime si vzdialenost k hrane este pri starom zoome
edgeDistPX_x_old := curX - objDrawOffsetX - objZoomOffsetX;
edgeDistPX_y_old := curY - objDrawOffsetY - objZoomOffsetY;
edgeDistMM_x_old := MM( edgeDistPX_x_old );
edgeDistMM_y_old := MM( edgeDistPX_y_old );
// nastavenie zoomu (ak nie je zadany parameter zoomVal, nazoomuje cely panel)
zoomx := (fMain.ClientWidth - 10) / objSirka;
zoomy := (fMain.ClientHeight - fMain.ToolBar1.Height - 10 - 20 {status bar}) / objVyska;
objZoom := Min(zoomx, zoomy) * objZoomFactor;
if (curX > 0) AND (curY > 0) then begin // ochrana pred znicenim hodnoty v objZoomOffsetX(Y) ked sa procedura zavola bez pozicie kurzora
// este nastavime posunutie celeho vykreslovania - aby mys aj po prezoomovani
// ostavala nad tym istym miestom panela
edgeDistPX_x_new := PX( edgeDistMM_x_old );
edgeDistPX_y_new := PX( edgeDistMM_y_old );
objZoomOffsetX := objZoomOffsetX + ((edgeDistPX_x_old) - (edgeDistPX_x_new));
objZoomOffsetY := objZoomOffsetY + ((edgeDistPX_y_old) - (edgeDistPX_y_new));
end;
end;
procedure TPanelObject.SaveToFile(panelfile: string);
var
pisar: TStreamWriter;
i, v: integer;
vertex: TMyPoint;
tempStr: string;
fea: TFeatureObject;
combo: TComboObject;
guide: TGuideObject;
minX, minY, maxX, maxY: double;
objektMimoPanela: boolean;
mimoPanelMazat: SmallInt;
begin
// najprv povodny subor zazalohujeme
if FileExists(panelfile) then begin
DeleteFile(panelfile+'.bak');
RenameFile(panelfile, panelfile+'.bak');
end;
pisar := TStreamWriter.Create(panelfile, false, TEncoding.UTF8);
// panel sa musi ukladat pri zapnutej strane "A"
// (kym nie je poriadne urobene prepocitavanie suradnic)
if objStranaVisible = 2 then
fMain.btnSideSwitch.Click;
try
// zapiseme hlavicku
pisar.WriteLine('{>header}');
pisar.WriteLine('filetype=quickpanel:panel');
pisar.WriteLine('filever=' + IntToStr((cfg_swVersion1*10000)+(cfg_swVersion2*100)+cfg_swVersion3));
pisar.WriteLine('units=mm');
pisar.WriteLine('sizex=' + FloatToStr(RoundTo(objSirka , -4)));
pisar.WriteLine('sizey=' + FloatToStr(RoundTo(objVyska , -4)));
pisar.WriteLine('thickness=' + FloatToStr(RoundTo(objHrubka , -4)));
pisar.WriteLine('radius1=' + FloatToStr(RoundTo(objRadius , -4)));
pisar.WriteLine('shape=rect');
pisar.WriteLine('gridsize=' + FloatToStr(RoundTo(objGrid, -4)));
pisar.WriteLine('surface=' + objPovrch);
objCurrentSide := 1;
pisar.WriteLine('zeropos1=' + IntToStr(GetCenterPos));
objCurrentSide := 2;
pisar.WriteLine('zeropos2=' + IntToStr(GetCenterPos));
pisar.WriteLine('custommater=' + BoolToStr(objMaterialVlastny, true));
pisar.WriteLine('edgestyle=' + objHranaStyl);
pisar.WriteLine('edgesize=' + FloatToStr(RoundTo(objHranaRozmer, -4)));
pisar.WriteLine('edgebottom=' + BoolToStr(objHranaObrobenaBottom, true));
pisar.WriteLine('edgeright=' + BoolToStr(objHranaObrobenaRight, true));
pisar.WriteLine('edgetop=' + BoolToStr(objHranaObrobenaTop, true));
pisar.WriteLine('edgeleft=' + BoolToStr(objHranaObrobenaLeft, true));
pisar.WriteLine('structfeatures=id,type,comboid,posx,posy,size1,size2,size3,size4,size5,depth,param1,param2,param3,param4,param5,side,locked,vertexarray,name,color'); // MUSIA byt oddelene ciarkami LoadFromFile sa na nich spolieha
pisar.WriteLine('structcombos=id,posref,posx,posy');
pisar.WriteLine('structguides=type,param1,param2,param3,side');
pisar.WriteLine('{/header}');
// zapiseme combo objekty - musia byt pred ficrami lebo combo moze byt polohovane podla nejakeho svojho objektu - takze pri Loadovani suboru si tu poodkladame vsetky Feature.ID, ktore neskor musime sledovat a podla nich polohovat combo (pri Loadovani sa feature.ID generuje nove)
pisar.WriteLine('{>combos}');
for i:=0 to Combos.Count-1 do begin
combo := Combos[i];
if Assigned(combo) then begin
pisar.WriteLine(IntToStr(combo.ID));
if (combo.PolohaObject = -1) then
pisar.WriteLine('-1')
else
// ak je combo polohovane na nejaky svoj komponent, zapiseme jeho INDEX nie ID (lebo ID sa po OpenFile pomenia)
pisar.WriteLine(IntToStr(combo.PolohaObject));
pisar.WriteLine(FloatToStr(RoundTo(combo.X , -4)));
pisar.WriteLine(FloatToStr(RoundTo(combo.Y , -4)));
end;
end;
pisar.WriteLine('{/combos}');
// ficre
pisar.WriteLine('{>features}');
// skontrolujeme, ci bounding box nejakeho ficru nelezi mimo panela
// a dame na vyber, ci taketo objekty zmazat
mimoPanelMazat := -1; // -1 = este sme sa ho nepytali , 0 = odpovedal NIE , 1 = odpovedal ANO
i := 0;
while i < objfeatures.Count do begin // cez WHILE a nie FOR lebo v cykle menime pocet ficrov (tie mimo panela mozeme mazat)
fea := objFeatures[i];
if objSideZeroes[fea.Strana] = cpLB then begin
minX := 0;
minY := 0;
maxX := objSirka;
maxY := objVyska;
end;
if objSideZeroes[fea.Strana] = cpRB then begin
minX := -objSirka;
minY := 0;
maxX := 0;
maxY := objVyska;
end;
if objSideZeroes[fea.Strana] = cpRT then begin
minX := -objSirka;
minY := -objVyska;
maxX := 0;
maxY := 0;
end;
if objSideZeroes[fea.Strana] = cpLT then begin
minX := 0;
minY := -objVyska;
maxX := objSirka;
maxY := 0;
end;
if objSideZeroes[fea.Strana] = cpCEN then begin
minX := -objSirka/2;
minY := -objVyska/2;
maxX := objSirka/2;
maxY := objVyska/2;
end;
if (fea.BoundingBox.TopL.X > maxX)
OR (fea.BoundingBox.TopL.Y < minY)
OR (fea.BoundingBox.BtmR.X < minX)
OR (fea.BoundingBox.BtmR.Y > maxY)
then begin
objektMimoPanela := true;
if (mimoPanelMazat = -1) then begin
case MessageBox(fmain.Handle, PChar(TransTxt('Feature placed out of panel surface has been found.')+#13+TransTxt('Delete such features?')), PChar(TransTxt('Warning')), MB_ICONWARNING OR MB_YESNO OR MB_DEFBUTTON2) of
ID_YES: mimoPanelMazat := 1;
ID_NO: mimoPanelMazat := 0;
else
mimoPanelMazat := 0;
end;
end;
end else
objektMimoPanela := false;
if objektMimoPanela AND (mimoPanelMazat = 1) then begin
Self.DelFeatureByID(fea.ID);
Continue;
end;
if Assigned(fea) then begin
pisar.WriteLine(IntToStr(fea.ID)); // po nahrati sa ID vygeneruju nove, toto ukladame, len pre zachovanie spojenia s combo objektami
pisar.WriteLine(IntToStr(fea.Typ));
pisar.WriteLine(IntToStr(fea.ComboID));
pisar.WriteLine(FloatToStr(RoundTo(fea.X , -4)));
pisar.WriteLine(FloatToStr(RoundTo(fea.Y , -4)));
pisar.WriteLine(FloatToStr(RoundTo(fea.Rozmer1 , -4)));
pisar.WriteLine(FloatToStr(RoundTo(fea.Rozmer2 , -4)));
pisar.WriteLine(FloatToStr(RoundTo(fea.Rozmer3 , -4)));
pisar.WriteLine(FloatToStr(RoundTo(fea.Rozmer4 , -4)));
pisar.WriteLine(FloatToStr(RoundTo(fea.Rozmer5 , -4)));
pisar.WriteLine(FloatToStr(RoundTo(fea.Hlbka1 , -4)));
pisar.WriteLine(fea.Param1);
pisar.WriteLine(fea.Param2);
pisar.WriteLine(fea.Param3);
pisar.WriteLine(fea.Param4);
pisar.WriteLine(fea.Param5);
pisar.WriteLine(IntToStr(fea.Strana));
pisar.WriteLine(BoolToStr(fea.Locked, true));
// polyline vertexes
if (fea.Typ <> ftPolyLineGrav) then
pisar.WriteLine('')
else begin
tempStr := '';
for v := 0 to (fea as TFeaturePolyLineObject).VertexCount-1 do begin
vertex := (fea as TFeaturePolyLineObject).GetVertex(v);
tempStr := tempStr + FormatFloat('0.0###',vertex.X)+','+FormatFloat('0.0###',vertex.Y)+separChar;
end;
tempStr := Copy(tempStr, 0, Length(tempStr)-1 ); // odstranime posledny separchar
pisar.WriteLine(tempStr);
end;
pisar.WriteLine(fea.Nazov);
pisar.WriteLine(ColorToString(fea.Farba));
end;
Inc(i);
end;
pisar.WriteLine('{/features}');
// ostatne - guideline-y a pod.
pisar.WriteLine('{>guides}');
for i:=0 to _PNL.Guides.Count-1 do begin
guide := _PNL.Guides[i];
pisar.WriteLine(guide.Typ);
pisar.WriteLine(FloatToStr(RoundTo(guide.Param1 , -4)));
pisar.WriteLine(FloatToStr(RoundTo(guide.Param2 , -4)));
pisar.WriteLine(FloatToStr(RoundTo(guide.Param3 , -4)));
pisar.WriteLine(IntToStr(guide.Strana));
// end;
end;
pisar.WriteLine('{/guides}');
objHasChanged := false;
objFileName := panelfile;
finally
pisar.Free;
end;
// ak vsetko prebehlo OK, mozeme zmazat zalozny subor
if FileExists(panelfile+'.bak') then DeleteFile(panelfile+'.bak');
// ak sme pocas ukladania aj mazali nejake ficre mimo panela, prekreslime panel
if objektMimoPanela then Self.Draw;
end;
procedure TPanelObject.SelectAll;
var
i: integer;
begin
for i:=0 to objFeatures.Count-1 do
if Assigned(objFeatures[i]) then
if (objFeatures[i].Strana = objStranaVisible) then
objFeatures[i].Selected := true;
end;
procedure TPanelObject.SelectAllInRect(obdlz: TRect; ciastocne: boolean = false);
var
i, tmp: integer;
myrectMM, comboRectMM: TMyRect;
myrectPX, comboRectPX: TRect;
begin
for i:=0 to objFeatures.Count-1 do
if Assigned(objFeatures[i]) then begin
// ak je lavy viac vpravo ako pravy :) tak ich vymenime a to iste aj o hornom/spodnom
if obdlz.Left > obdlz.Right then begin
tmp := obdlz.Left;
obdlz.Left := obdlz.Right;
obdlz.Right := tmp;
end;
if obdlz.Bottom < obdlz.Top then begin
tmp := obdlz.Bottom;
obdlz.Bottom := obdlz.Top;
obdlz.Top := tmp;
end;
myrectMM := objFeatures[i].BoundingBox;
myrectPX.Left := PX(myrectMM.TopL.X, 'x');
myrectPX.Right := PX(myrectMM.BtmR.X, 'x');
myrectPX.Top := PX(myrectMM.TopL.Y, 'y');
myrectPX.Bottom:= PX(myrectMM.BtmR.Y, 'y');
if (myrectPX.Left > obdlz.Left) AND (myrectPX.Right < obdlz.Right) AND
(myrectPX.Top > obdlz.Top) AND (myrectPX.Bottom < obdlz.Bottom) AND
(objFeatures[i].Strana = objStranaVisible) then
if (objFeatures[i].ComboID = -1) then
// ak objekt nie je sucastou ziadneho comba, jednoducho ho vyselectujeme
objFeatures[i].Selected := true
else begin
// ak je sucastou nejakeho comba, zistime ci aj ostatne objekty
// comba lezia vo vyberovom obdlzniku a ak ano, vyberieme cele combo
comboRectMM := GetComboBoundingBox( objFeatures[i].ComboID );
comboRectPX.Left := PX(comboRectMM.TopL.X, 'x');
comboRectPX.Right := PX(comboRectMM.BtmR.X, 'x');
comboRectPX.Top := PX(comboRectMM.TopL.Y, 'y');
comboRectPX.Bottom:= PX(comboRectMM.BtmR.Y, 'y');
if (comboRectPX.Left > obdlz.Left) AND (comboRectPX.Right < obdlz.Right) AND
(comboRectPX.Top > obdlz.Top) AND (comboRectPX.Bottom < obdlz.Bottom) then
SelectCombo( objFeatures[i].ComboID );
end;
// ak treba vybrat aj len pretate, otestujeme aj tuto podmienku
if (ciastocne) then begin
if (obdlz.Right > myrectPX.Left) AND (obdlz.Left < myrectPX.Right) AND
(obdlz.Top < myrectPX.Bottom) AND (obdlz.Bottom > myrectPX.Top) AND
(objFeatures[i].Strana = objStranaVisible) then
if (objFeatures[i].ComboID = -1) then begin
// ak objekt nie je sucastou ziadneho comba, jednoducho ho vyselectujeme
objFeatures[i].Selected := true;
end else begin
SelectCombo( objFeatures[i].ComboID );
end;
end; // if (ciastocne) then
end;
end;
procedure TPanelObject.SelectCombo(comboID: integer; sel_state: boolean = true);
var
i: integer;
begin
// ak nie je uvedeny 2. parameter, vyselectuje combo
// ak je ale explicitne "false", tak ho deselectuje
if comboID > -1 then
for i:=0 to objFeatures.Count-1 do
if Assigned(objFeatures[i]) then
if (objFeatures[i].ComboID = comboID) AND (not objFeatures[i].Locked) then
objFeatures[i].Selected := sel_state;
end;
procedure TPanelObject.DeselectAll;
var
i: integer;
begin
for i:=0 to objFeatures.Count-1 do
if Assigned(objFeatures[i]) then
objFeatures[i].Selected := false;
end;
function TPanelObject.GetSelectedFeaturesNum: TMyInt2x;
var
i: integer;
tmp_str: string; // akesi pole na ukladanie cisel vyselectovanych combo prvkov, napr: '1#3#120#9#'
begin
result.i1 := 0; // pocet vyselectovanych featurov (kazde combo je za 1)
result.i2 := 0; // pocet vyselectovanych LEN combo featurov
tmp_str := '';
for i:=0 to objFeatures.Count-1 do
if (Assigned(objFeatures[i]) AND objFeatures[i].Selected ) then
// ak je v combe, zistime, ci sme uz toto combo zapocitali
if (objFeatures[i].ComboID > -1) then begin
if ( Pos(IntToStr(objFeatures[i].ComboID)+'#',tmp_str) = 0) then begin
// ak je v combe a toto combo sme este neriesili, ulozime jeho cislo do "pola" a zapocitame ho
tmp_str := tmp_str + IntToStr(objFeatures[i].ComboID) + '#';
Inc(result.i2);
end;
end else begin
Inc(result.i1);
end;
end;
procedure TPanelObject.LoadFont(fontfilename: string);
var
rider: TStreamReader;
lajna: string;
i, indexZnaku, fontIndex: integer;
strPoints, strPointData: TStringList;
NahravanyFont: TMyFont;
NahravanyZnak: TMyZnak;
begin
// najprv zistime, ci dany font uz nie je nahraty vo fontoch - ak ano, tak rovno exit
fontIndex := objFonty.IndexOf(fontfilename);
if fontIndex > -1 then
Exit
else begin
if not FileExists(ExtractFilePath(Application.ExeName)+'\\'+fontfilename) then begin
fMain.Log('Font file not found: '+ExtractFilePath(Application.ExeName)+'\\'+fontfilename);
MessageBox(0, PChar(TransTxt('Font file not found:')+' '+fontfilename), PChar(TransTxt('Error')), MB_ICONERROR);
Exit;
end;
fontIndex := objFonty.AddObject(fontfilename, TMyFont.Create() );
end;
// placeholder pre font, ktory nahravam
NahravanyFont := TMyFont(objFonty.Objects[fontIndex]);
// nahratie dat pre dany font zo suboru
FormatSettings.DecimalSeparator := '.';
strPoints := TStringList.Create;
strPointData := TStringList.Create;
rider := TStreamReader.Create( ExtractFilePath(Application.ExeName)+'\\'+fontfilename, TEncoding.Unicode );
try
// kontrola spravneho formatu suboru
while (lajna <> '{/header}') do begin
lajna := rider.ReadLine;
if (Pos('filetype',lajna) > 0) AND (Pos('quickpanel:font', lajna) = 0 ) then begin
strPoints.Free;
strPointData.Free;
rider.Free;
Exit;
end;
end;
// nacitavanie samotnych pismeniek do pola
while not rider.EndOfStream do begin
if Pos('=', lajna) > 0 then begin
// nasiel sa riadok s definiciou pismenka, tak ho podme nacitat
if Pos('=', lajna) = 7 then // "rovnasa" znak sa neda klasickym sposobom, takze je (v subore fontu) nahradeny slovom "equals" a separator "=" je teda az na 7. pozicii
indexZnaku := Ord(Char('='))
else
indexZnaku := Ord(Char(lajna[1]));
NahravanyZnak := NahravanyFont.PridajZnak(indexZnaku);
//....nacitanie samotneho znaku (rozparsovat lajnu)....
strPoints.Clear;
ExplodeStringSL( Copy(lajna, Pos('=', lajna)+1 ), '#', strPoints);
NahravanyZnak.NastavPocetBodov(strPoints.Count);
NahravanyZnak.SirkaZnaku := 0;
for i := 0 to strPoints.Count-1 do begin
strPointData.Clear;
ExplodeStringSL(strPoints[i], ',', strPointData);
NahravanyZnak.Points[i].kresli := (strPointData[0] = '1');
NahravanyZnak.Points[i].bod.X := StrToFloat(strPointData[1]);
NahravanyZnak.Points[i].bod.Y := StrToFloat(strPointData[2]);
NahravanyZnak.SirkaZnaku := Max(NahravanyZnak.SirkaZnaku , NahravanyZnak.Points[i].bod.X);
end;
// este nacitame sirku medzery za znakom (hned z nasledujuceho riadku v subore)
lajna := rider.ReadLine;
NahravanyZnak.SirkaMedzery := StrToFloat(lajna);
end;
lajna := rider.ReadLine;
end;
finally
rider.Free;
strPoints.Free;
strPointData.Free;
end;
// pre vsetky znaky, ktore sa v subore fontu nenasli a su prazdne nastavime ako default velku sirku znaku,
// aby ked user zada taky znak, tak to hned zbadal tak, ze bude mat na jeho mieste v texte velku medzeru
// for i := 0 to High(fontDin17i_cp1250) do
// if Length(fontDin17i_cp1250[i].body) = 0 then
// fontDin17i_cp1250[i].sirkaZnaku := sirkaNeznamehoZnaku;
end;
procedure TPanelObject.LoadFromFile(panelfile: string);
type
comboMap = record
id: integer;
pos_ref: integer;
end;
var
comboMapping: array of comboMap;
rider: TStreamReader;
lajn: string;
hlavicka, paramsList: TStringList;
currSoftVersion, I, J: integer;
newfea: TFeatureObject;
newcombo: TComboObject;
poleParams, poleVertexy: TPoleTextov;
vertex: TMyPoint;
lastSucessfulOperation: string;
lineNumber: integer;
begin
if not FileExists(panelfile) then begin
MessageBox(Application.ActiveFormHandle, PChar(TransTxt('File not found: ')+panelfile), PChar(TransTxt('Error')), MB_ICONERROR);
Exit;
end;
objHasChanged := true;
// detekcia stareho formatu suboru (do 0.3.10)
rider := TStreamReader.Create(panelfile, TEncoding.UTF8);
lajn := rider.ReadLine; Inc(lineNumber);
rider.Free;
if (lajn = '[Panel]') then begin
objVersion := 310;
LoadFromFile_old(panelfile);
Exit;
end;
// nahravanie noveho formatu suboru
hlavicka := TStringList.Create;
rider := TStreamReader.Create(panelfile, TEncoding.UTF8);
try
lajn := rider.ReadLine; Inc(lineNumber);
if (lajn = '{>header}') then begin // 1.riadok musi byt zaciatok hlavicky
// najprv nacitanie hlavicky
while (lajn <> '{/header}') do begin
lajn := rider.ReadLine; Inc(lineNumber);
if (Pos('=', lajn) > 0) then begin
hlavicka.Add(lajn);
end; // if (Pos('=', lajn) > 0)
end; // while (lajn <> '{/header}')
// kontrola, ci sa skutocne jedna o subor panela
if hlavicka.Values['filetype'] <> 'quickpanel:panel' then begin
raise Exception.Create( PChar(TransTxt('File is not a QuickPanel file.') + ' ('+hlavicka.Values['filetype']+')') );
end;
// spracovanie hlavicky - kontrola verzie suboru
currSoftVersion := (cfg_swVersion1*10000)+(cfg_swVersion2*100)+cfg_swVersion3;
objVersion := StrToInt(hlavicka.Values['filever']);
{$IFNDEF DEBUG}
if (objVersion > currSoftVersion) then begin
MessageBox(Application.ActiveFormHandle, PChar(TransTxt('File was saved by newer version of the QuickPanel. It might not open correctly.')), PChar(TransTxt('Warning')), MB_ICONWARNING);
end;
{$ELSE}
// nech ma pri debugovani neotravuje (v debugu je verzia softu = 1.0.0)
{$ENDIF}
lastSucessfulOperation := 'hlavicka nacitana do stringlistu';
// spracovanie hlavicky - udaje o samotnom paneli
objFileName := panelfile;
objSirka := StrToFloat(hlavicka.Values['sizex']);
objVyska := StrToFloat(hlavicka.Values['sizey']);
objHrubka := StrToFloat(hlavicka.Values['thickness']);
objRadius := StrToFloat(hlavicka.Values['radius1']);
objPovrch := hlavicka.Values['surface'];
objHranaStyl := hlavicka.Values['edgestyle']; if objHranaStyl='' then objHranaStyl := '0';
objHranaRozmer := StrToFloat(hlavicka.Values['edgesize']);
objHranaObrobenaBottom := StrToBool(hlavicka.Values['edgebottom']);
objHranaObrobenaRight := StrToBool(hlavicka.Values['edgeright']);
objHranaObrobenaTop := StrToBool(hlavicka.Values['edgetop']);
objHranaObrobenaLeft := StrToBool(hlavicka.Values['edgeleft']);
objGrid := StrToFloat(hlavicka.Values['gridsize']);
SetCenterPosByNum( StrToInt(hlavicka.Values['zeropos1']), 1);
SetCenterPosByNum( StrToInt(hlavicka.Values['zeropos2']), 2);
CurrentSide := 1;
MaterialVlastny := StrToBool(hlavicka.Values['custommater']);
if not StrToBool( uConfig.Config_ReadValue('material_custom_available') ) then MaterialVlastny := false;
SetZoom(0, -1, -1);
end else begin // if lajn = '{>header}'
raise Exception.Create(PChar(TransTxt('File is corrupted.')));
end;
lastSucessfulOperation := 'hlavicka uspesne nacitana & spracovana';
paramsList := TStringList.Create;
// ********************* nacitanie combo objektov **************************
while (lajn <> '{>combos}') AND (not rider.EndOfStream) do begin
// presun na zaciatok sekcie COMBOS
lajn := rider.ReadLine;
Inc(lineNumber);
end;
if lajn <> '{>combos}' then raise Exception.Create(PChar(TransTxt('File is corrupted.')));
paramsList.Clear; // init
SetLength(poleParams, 0); // init
ExplodeString( hlavicka.Values['structcombos'], ',', poleParams); // do pola naplnime zaradom parametre v poradi ako su zapisane do fajlu
lajn := rider.ReadLine; Inc(lineNumber); // nacitame dalsi riadok, aby sme vedeli, ci je sekcia prazdna (riadok = uzatvaracia znacka) alebo je tam nejaky objekt
lastSucessfulOperation := 'zacinam citat combos';
while (lajn <> '{/combos}') do begin
paramsList.Values[ poleParams[0] ] := lajn; // kedze sme splnili podmienku, ze (lajn <> uzatvaracia znacka), znamena to ze v "lajn" uz mame nacitany 1.parameter objektu combo takze ho tu hned ulozime do pola a zvysne parametre objektu nacitame v nasledujucej slucke
for I := 1 to Length(poleParams)-1 do begin // tu nacitavame N-1 parametrov objektu (prvy sme nacitali uz v predchadzajucom riadku)
lajn := rider.ReadLine; Inc(lineNumber);
paramsList.Values[ poleParams[I] ] := lajn; // vytvorime asociativne pole s hodnotami jednotlivych parametrov priradenymi nazvom parametrov
end;
newcombo := GetComboByID( AddCombo( StrToInt( paramsList.Values['id'] ) )); // vytvorime nove combo na paneli s takym ID ako malo pri ulozeni (nemusia ist po poradi a mozu byt niektore ID vynechane, lebo user pred ulozenim panela mohol nejake comba aj vymazat)
try
if not(newcombo = nil) then begin
newcombo.PolohaObject := StrToInt( paramsList.Values['posref']);
newcombo.X := StrToFloat(paramsList.Values['posx']);
newcombo.Y := StrToFloat(paramsList.Values['posy']);
end;
SetLength( comboMapping, Length(comboMapping)+1 ); // pridame dalsiu polozku do pola mapovania comba
comboMapping[ Length(comboMapping)-1 ].id := newcombo.ID; // do posledneho prvku pola ukladame parametre aktualne vytvaraneho comba
comboMapping[ Length(comboMapping)-1 ].pos_ref := StrToInt( paramsList.Values['posref']);// do posledneho prvku pola ukladame parametre aktualne vytvaraneho comba
lajn := rider.ReadLine; Inc(lineNumber);
except
on E:exception do begin
fMain.Log('Error while opening file on line:'+IntToStr(lineNumber)+', Error:'+E.Message+'. Line in combo section:'+#13+lajn);
MessageBox(0, PChar(TransTxt('Error while opening file.')), PChar('Error'), MB_ICONERROR OR MB_OK);
end;
end;
end;
lastSucessfulOperation := 'combos uspesne nacitane & spracovane';
// *********************** nacitanie ficrov ********************************
while (lajn <> '{>features}') AND (not rider.EndOfStream) do begin
lajn := rider.ReadLine;
Inc(lineNumber);
end;
if lajn <> '{>features}' then raise Exception.Create(PChar(TransTxt('File is corrupted.')));
paramsList.Clear;
SetLength(poleParams, 0);
ExplodeString( hlavicka.Values['structfeatures'], ',', poleParams); // vysvetlivky kodu - vid sekciu combos
lajn := rider.ReadLine; Inc(lineNumber);
lastSucessfulOperation := 'idem citat features';
while lajn <> '{/features}' do begin
paramsList.Values[ poleParams[0] ] := lajn;
for I := 1 to Length(poleParams)-1 do begin // su indexovane od 0 ale na pozicii 0 je ID ficra a to nepotrebujeme
lajn := rider.ReadLine; Inc(lineNumber);
paramsList.Values[ poleParams[I] ] := lajn;
end;
{$IFDEF DEBUG}
lastSucessfulOperation := 'idem vytvorit feature: '+
paramsList.Values['type'] + ';' +
paramsList.Values['side'] + ';' +
paramsList.Values['locked'] + ';' +
paramsList.Values['comboid'] + ';' +
paramsList.Values['posx'] + ';' +
paramsList.Values['posy'] + ';' +
paramsList.Values['size1'] + ';' +
paramsList.Values['size2'] + ';' +
paramsList.Values['size3'] + ';' +
paramsList.Values['size4'] + ';' +
paramsList.Values['size5'] + ';' +
paramsList.Values['depth'] + ';' +
paramsList.Values['param1'] + ';' +
paramsList.Values['param2'] + ';' +
paramsList.Values['param3'] + ';' +
paramsList.Values['param4'] + ';' +
paramsList.Values['param5'] + '; (END)'
;
{$ENDIF}
newfea := GetFeatureByID( AddFeature( paramsList.Values['type'] ) );
try
newfea.Strana := StrToInt(paramsList.Values['side']);
newfea.Locked := StrToBool(paramsList.Values['locked']);
newfea.ComboID := StrToInt( paramsList.Values['comboid'] );
newfea.Poloha := MyPoint( StrToFloat(paramsList.Values['posx']) , StrToFloat(paramsList.Values['posy']) );
newfea.Rozmer1 := StrToFloat(paramsList.Values['size1']);
newfea.Rozmer2 := StrToFloat(paramsList.Values['size2']);
newfea.Rozmer3 := StrToFloat(paramsList.Values['size3']);
newfea.Rozmer4 := StrToFloat(paramsList.Values['size4']);
newfea.Rozmer5 := StrToFloat(paramsList.Values['size5']);
newfea.Hlbka1 := StrToFloat(paramsList.Values['depth']);
except
on E:exception do begin
fMain.Log('Error while opening file on line:'+IntToStr(lineNumber)+', Error:'+E.Message+'. Line in feature(1) section:'+#13+lajn);
MessageBox(0, PChar(TransTxt('Error while opening file.')), PChar('Error'), MB_ICONERROR OR MB_OK);
end;
end;
newfea.Param1 := paramsList.Values['param1'];
newfea.Param2 := paramsList.Values['param2'];
newfea.Param3 := paramsList.Values['param3'];
newfea.Param4 := paramsList.Values['param4'];
newFea.Param5 := paramsList.Values['param5'];
newfea.Nazov := paramsList.Values['name'];
if (paramsList.Values['color'] = '') OR (paramsList.Values['color'] = '-1') then
newfea.Farba := -1
else
newfea.Farba := StringToColor(paramsList.Values['color']);
if (newfea.Typ = ftTxtGrav) then begin
if (newfea.Rozmer2 = -1) then newfea.Rozmer2 := 0; // rozmer2 = natocenie textu. V starych verziach sa tam vzdy ukladalo -1 lebo parameter nebol vyuzity. Od verzie 1.0.16 bude ale default = 0
if (newfea.Param5 = '') then newfea.Param5 := fFeaEngraving.comTextFontValue.Items[0];
end;
// ak v paneli nie je nahraty taky font, aky ma priradeny nacitavana ficurka, tak ju ani nevytvorime
if (newfea.Typ = ftTxtGrav) AND (Fonty.IndexOf(newfea.Param5) = -1) then begin
fMain.Log('Font not loaded in panel: '+newfea.Param5);
MessageBox(0, PChar(TransTxt('Font file not found:')+' '+newfea.Param5), PChar(TransTxt('Error')), MB_ICONERROR);
DelFeatureByID(newfea.ID); // rovno zmazeme ficr
end else begin
try
// ak je to text, musime prepocitat boundingbox lebo tento zavisi od Param1 .. Param4 a ked sa tie nahravaju do ficra, tak tam sa uz AdjustBoundingBox nevola (automaticky sa to vola len pri nastavovani Size1 .. Size5)
if newfea.Typ = ftTxtGrav then
newfea.AdjustBoundingBox;
// ak je to polyline, nacitame vertexy
if (newfea.Typ = ftPolyLineGrav) AND (paramsList.Values['vertexarray'] <> '' ) then begin
ExplodeString(paramsList.Values['vertexarray'], separChar, poleVertexy);
if ((Length(poleVertexy) > 0) AND (poleVertexy[0] <> '')) then // ochrana ak riadok co ma obsahovat vertexy je prazdny (pole bude mat vtedy len jeden prvok - prazdny text)
for I := 0 to Length(poleVertexy)-1 do begin
vertex.X := StrToFloat( Copy(poleVertexy[I], 0, Pos(',', poleVertexy[I])-1 ) );
vertex.Y := StrToFloat( Copy(poleVertexy[I], Pos(',', poleVertexy[I])+1 ) );
(newfea as TFeaturePolyLineObject).AddVertex(vertex);
end;
end;
// pre vsetky, kde sa uplatnuje farba vyplne zrusime vypln ak nie je v konfigu povolena
if (newfea.Typ >= ftTxtGrav) AND (newfea.Typ < ftThread) then begin
if not StrToBool( uConfig.Config_ReadValue('engraving_colorinfill_available') ) then newfea.Param4 := 'NOFILL';
end;
// este skontrolujeme combo - ak bolo combo polohovane na FICR, tak musime v combe aktualizovat ID toho ficru,
// pretoze pri nahravani panela zo suboru sa ficrom vygeneruju nove IDcka
if newfea.ComboID > -1 then begin
for I := 0 to Length(comboMapping)-1 do begin
if (comboMapping[I].pos_ref = StrToInt(paramsList.Values['id'])) then begin
GetComboByID(comboMapping[I].id).PolohaObject := newfea.ID;
end;
end;
end;
except
on E:exception do begin
fMain.Log('Error while opening file on line: '+IntToStr(lineNumber)+', Error: '+E.Message+'. Line in feature(2) section:'+#13+lajn);
MessageBox(0, PChar(TransTxt('Error while opening file.')), PChar('Error'), MB_ICONERROR OR MB_OK);
end;
end;
newfea.Inicializuj;
// polyline s nulovym poctom vertexov ani nebudem drzat na paneli, lebo to navysuje cenovu ponuku
if ((newfea.Typ = ftPolyLineGrav) and
((newfea as TFeaturePolyLineObject).GetVertexCount <= 1)) then
DelFeatureByID(newfea.ID);
end;
lajn := rider.ReadLine; Inc(lineNumber);
end;
lastSucessfulOperation := 'features uspesne nacitane & spracovane';
// *********************** nacitanie guideov *******************************
while (lajn <> '{>guides}') AND (not rider.EndOfStream) do begin
lajn := rider.ReadLine;
Inc(lineNumber);
end;
if lajn <> '{>guides}' then raise Exception.Create(PChar(TransTxt('File is corrupted.')));
paramsList.Clear;
SetLength(poleParams, 0);
ExplodeString( hlavicka.Values['structguides'], ',', poleParams); // vysvetlivky kodu - vid sekciu combos
lajn := rider.ReadLine; Inc(lineNumber);
lastSucessfulOperation := 'idem citat guides';
while lajn <> '{/guides}' do begin
paramsList.Values[ poleParams[0] ] := lajn;
for I := 1 to Length(poleParams)-1 do begin
lajn := rider.ReadLine; Inc(lineNumber);
paramsList.Values[ poleParams[I] ] := lajn;
end;
try
lastSucessfulOperation := 'idem vytvorit guide: '+paramsList.Values['type']+';'+paramsList.Values['param1']+';'+paramslist.Values['param2']+';'+paramslist.Values['param3']+';'+paramslist.Values['side']+'; (END)';
AddGuideLine(
paramsList.Values['type'],
StrToFloat(paramsList.Values['param1']),
StrToFloat(paramsList.Values['param2']),
StrToFloat(paramsList.Values['param3']),
StrToInt (paramsList.Values['side'])
);
except
on E:exception do begin
fMain.Log('Error while opening file on line: '+IntToStr(lineNumber)+', Error: '+E.Message+'. Line in guide section:'+#13+lajn);
MessageBox(0, PChar(TransTxt('Error while opening file.')), PChar('Error'), MB_ICONERROR OR MB_OK);
end;
end;
lajn := rider.ReadLine; Inc(lineNumber);
end;
objHasChanged := false;
lastSucessfulOperation := 'all done';
finally
hlavicka.Free;
paramsList.Free;
rider.Free;
fMain.Log('Load panel from file (last successful operation): ' + lastSucessfulOperation);
end;
end;
procedure TPanelObject.LoadFromFile_old(panelfile: string);
var
myini: TIniFile;
currSoftVersion: integer;
i, newfeaID: integer;
iass: string; // i as string
newfea : TFeatureObject;
newcmb : TComboObject;
begin
try
myini := TIniFile.Create(panelfile);
// kontrola, ci neotvarame subor ulozeny novsou verziou
currSoftVersion := (cfg_swVersion1*10000)+(cfg_swVersion2*100)+cfg_swVersion3;
if myini.ReadInteger('Panel','FileVer', 0) > currSoftVersion then begin
MessageBox(Application.ActiveFormHandle, PChar(TransTxt('File was saved by newer version of the QuickPanel. It might not open correctly.')), PChar(TransTxt('Warning')), MB_ICONWARNING);
end;
objFileName := panelfile;
objSirka := myini.ReadFloat('Panel','SizeX',10);
objVyska := myini.ReadFloat('Panel','SizeY',10);
objRadius := myini.ReadFloat('Panel','Radius1',0);
objGrid := myini.ReadFloat('Panel','GridSize',0.5);
objHrubka := myini.ReadFloat('Panel','Thickness',3);
objPovrch := myini.ReadString('Panel','SurfaceFinish','surovy');
objHranaStyl := myini.ReadString('Panel','EdgeStyle','0'); if objHranaStyl='' then objHranaStyl := '0';
objHranaRozmer := myini.ReadFloat('Panel','EdgeSize',0);
objHranaObrobenaBottom := myini.ReadBool('Panel','EdgeBottom',false);
objHranaObrobenaRight := myini.ReadBool('Panel','EdgeRight',false);
objHranaObrobenaTop := myini.ReadBool('Panel','EdgeTop',false);
objHranaObrobenaLeft := myini.ReadBool('Panel','EdgeLeft',false);
CurrentSide := 1;
CenterPos := myini.ReadInteger('Panel','ZeroPosition', cpLB);
CurrentSide := 2;
CenterPos := myini.ReadInteger('Panel','ZeroPosition2', cpLB);
CurrentSide := 1;
MaterialVlastny := myini.ReadBool('Panel','CustomMaterial', false);
SetZoom(0, -1, -1);
for i:=1 to myini.ReadInteger('Panel','FeaNumber',0) do begin
iass := IntToStr(i);
newfeaID := AddFeature( myini.ReadInteger('Features','FeaType_'+iass, 0) );
if newfeaID > 0 then begin
newfea := GetFeatureByID(newfeaID);
// ako prve sa nacitaju Params, lebo pri grav.textoch to musi tak byt
// (inak by pri nastavovani polohy a pocitani BoundingRect zahlasil vynimku)
newfea.Param1 := myini.ReadString('Features','Param1_'+iass, '');
newfea.Param2 := myini.ReadString('Features','Param2_'+iass, '');
newfea.Param3 := myini.ReadString('Features','Param3_'+iass, '');
newfea.Param4 := myini.ReadString('Features','Param4_'+iass, '');
if newfea.Typ = ftTxtGrav then begin
newfea.Param5 := fFeaEngraving.comTextFontValue.Text; // deafaultne priradime prvy font
end;
newfea.Rozmer1 := myini.ReadFloat('Features','Size1_'+iass, 0);
newfea.Rozmer2 := myini.ReadFloat('Features','Size2_'+iass, 0);
newfea.Rozmer3 := myini.ReadFloat('Features','Size3_'+iass, 0);
newfea.Rozmer4 := myini.ReadFloat('Features','Size4_'+iass, 0);
newfea.Rozmer5 := myini.ReadFloat('Features','Size5_'+iass, 0);
if newfea.Typ = ftTxtGrav then begin
newfea.Rozmer2 := 0; // stary format suboru este rotaciu textov nepodporoval a bola tam ulozena hodnota -1, co by bolo chybne interpretovane ako uhol = -1 stupnov
end;
newfea.Poloha := MyPoint( myini.ReadFloat('Features','PosX_'+iass, 0) ,
myini.ReadFloat('Features','PosY_'+iass, 0));
newfea.Hlbka1 := myini.ReadFloat('Features','Depth_'+iass, 0);
newfea.Strana := myini.ReadInteger('Features','Side_'+iass, 1);
if newfea.Strana = 0 then newfea.Strana := 1;
// spatna kompatibilita pre verzie pod 0.3.3. (hrubka gravirovania)
if (newfea.Typ >= 30) AND (newfea.Typ <= 39) AND ((newfea.Rozmer3 = 0) OR (newfea.Rozmer3 = -1)) then
newfea.Rozmer3 := 0.2;
// spatna kompatibilita pre verzie pod 0.3.7. (farba gravirovania)
if (newfea.Typ >= 30) AND (newfea.Typ <= 39) AND (newfea.Param4 = '') then
newfea.Param4 := 'NOFILL';
// spatna kompatibilita pre verzie pod 0.3.11. (radiusy grav obdlznika)
if (newfea.Typ = 33) AND (newfea.Rozmer4 < 0) then
newfea.Rozmer4 := 0;
newfea.ComboID := myini.ReadInteger('Features','ComboID_'+iass, -1);
// ak objekt patri do nejakeho comba (a take este neexistuje), vytvori to combo aj v poli combo objektov
if (newfea.ComboID > -1) AND (not ComboExists(newfea.ComboID)) then
AddCombo(newfea.ComboID);
newfea.Inicializuj;
end;
end;
// nahratie combo featurov
for i:=1 to myini.ReadInteger('Panel','ComboNumber', 0) do begin
iass := IntToStr(i);
newcmb := GetComboByID( myini.ReadInteger('Combos','ComboID_'+iass, -1) );
if not(newcmb = nil) then begin
newcmb.PolohaObject := myini.ReadInteger('Combos','PosRef_'+iass, -1);
newcmb.X := myini.ReadFloat('Combos','PosX_'+iass, 0);
newcmb.Y := myini.ReadFloat('Combos','PosY_'+iass, 0);
end;
end;
// nahratie guidelineov
for i:=1 to myini.ReadInteger('Panel','GuideNumber', 0) do begin
iass := IntToStr(i);
AddGuideLine(
myini.ReadString('GuideLines', 'GuideType_'+iass, ''),
myini.ReadFloat('GuideLines', 'Param1_'+iass, -1),
myini.ReadFloat('GuideLines', 'Param2_'+iass, -1),
myini.ReadFloat('GuideLines', 'Param3_'+iass, 0),
myini.ReadInteger('GuideLines', 'Side_'+iass, 1)
);
end;
finally
FreeAndNil(myini);
end;
HasChanged := false;
end;
function TPanelObject.GetFeatureIndex(fid: integer):integer;
var
i: integer;
begin
result := -1;
for i:=0 to objFeatures.Count-1 do
if (Assigned(objFeatures[i]) AND (objFeatures[i].ID=fid) ) then
result := i;
end;
procedure TPanelObject.MoveSelected(byXmm, byYmm: double);
var
i, v: integer;
tmp_str: string;
b: TMyPoint;
begin
tmp_str := '';
// posunie objekty, ktore su vyselectovane o danu vzdialenost
for i:=0 to objFeatures.Count-1 do
if (Assigned(objFeatures[i]) AND objFeatures[i].Selected ) then begin
if objFeatures[i].Typ = ftPolyLineGrav then begin
for v := 0 to (objFeatures[i] as TFeaturePolyLineObject).VertexCount - 1 do begin
b := (objFeatures[i] as TFeaturePolyLineObject).GetVertex(v);
(objFeatures[i] as TFeaturePolyLineObject).SetVertex(v , b.X+byXmm , b.Y+byYmm);
end;
end else begin
objFeatures[i].X := objFeatures[i].X + byXmm;
objFeatures[i].Y := objFeatures[i].Y + byYmm;
end;
objHasChanged := true;
// ak je objekt sucastou komba a to kombo nie je polohovane vzhladom na nejaky svoj prvok, prepise polohu v samotnom objekte combo
if (objFeatures[i].ComboID > -1) AND (_PNL.GetComboByID(objFeatures[i].ComboID).PolohaObject = -1) then begin
// ak sme este toto combo neposuvali
if ( Pos(IntToStr(objFeatures[i].ComboID)+'#' , tmp_str) = 0 ) then begin
_PNL.GetComboByID( objFeatures[i].ComboID ).X := _PNL.GetComboByID( objFeatures[i].ComboID ).X + byXmm;
_PNL.GetComboByID( objFeatures[i].ComboID ).Y := _PNL.GetComboByID( objFeatures[i].ComboID ).Y + byYmm;
tmp_str := tmp_str + IntToStr(objFeatures[i].ComboID) + '#';
end;
end; // ak je objekt sucastou komba...
end; // if
end;
procedure TPanelObject.GetFullInfo(target: string = 'debug');
var
i : integer;
s: string;
begin
if target='debug' then begin
fMain.Log('====== FEATURES ======');
fMain.Log('count:'+IntToStr(objFeatures.Count));
fMain.Log('=i=|=ID=|SEL|TYP|SIDE|COMBO|===X===|==Y===|==R1==|==R2==|==R3==|==R4==|==R5==|==H==|==P1==|==P2==|==P3==|==P4==|==P5==|==BoundBox==|');
for i:=0 to objFeatures.Count-1 do
if Assigned(objFeatures[i]) then begin
s := FormatFloat('000 ',i);
s := s + FormatFloat('000 ',objFeatures[i].ID);
if (objFeatures[i].Selected) then
s := s + '[x]'
else
s := s + '[ ]';
s := s + FormatFloat(' 000 ', objFeatures[i].Typ );
s := s + FormatFloat(' 0 ', objFeatures[i].Strana );
s := s + FormatFloat(' 000 ', objFeatures[i].ComboID );
s := s + FormatFloat('000.00 ', objFeatures[i].Poloha.X );
s := s + FormatFloat('000.00 ', objFeatures[i].Poloha.Y );
s := s + FormatFloat('000.00 ', objFeatures[i].Rozmer1 );
s := s + FormatFloat('000.00 ', objFeatures[i].Rozmer2 );
s := s + FormatFloat('000.00 ', objFeatures[i].Rozmer3 );
s := s + FormatFloat('000.00 ', objFeatures[i].Rozmer4 );
s := s + FormatFloat('000.00 ', objFeatures[i].Rozmer5 );
s := s + FormatFloat('000.00 ', objFeatures[i].Hlbka1 );
s := s + objFeatures[i].Param1 + ', ' + objFeatures[i].Param2 + ', ' + objFeatures[i].Param3 + ', ' + objFeatures[i].Param4 + ', ' + objFeatures[i].Param5;
s := s + '['+MyRectToStr(objFeatures[i].BoundingBox)+']';
fMain.Log(s);
end else
fMain.Log( FormatFloat('000 ',i) + '...' );
fMain.Log('');
fMain.Log('====== COMBOS ======');
fMain.Log('=i=|=ID=|=Angle=|==Position==|=Pos.object=|');
for i:=0 to objCombos.Count-1 do
if Assigned(objCombos[i]) then begin
s := FormatFloat('000 ',i);
s := s + FormatFloat('000 ',objCombos[i].ID);
s := s + FormatFloat(' 000 ', objCombos[i].Rotation );
s := s + MyPointToStr( objCombos[i].Poloha ) + ' ';
s := s + IntToStr( objCombos[i].PolohaObject );
fMain.Log(s);
end else
fMain.Log( FormatFloat('000 ',i) + '...' );
fMain.Log('');
fMain.Log('====== FONTS ======');
for i := 0 to objFonty.Count-1 do
fMain.Log(objFonty[i]);
fMain.Log('');
fMain.Log('====== PANEL ======');
fMain.Log(FloatToStr(objSirka)+'x'+FloatToStr(objVyska)+'x'+FloatToStr(objHrubka)+'mm , '+objPovrch+' , matros vlastny:'+BoolToStr(objMaterialVlastny, true));
objCurrentSide := 1;
fMain.Log('CSYS1:'+inttostr(_PNL.CenterPos));
objCurrentSide := 2;
fMain.Log('CSYS2:'+inttostr(_PNL.CenterPos));
fMain.Log('_____________________________________________________________');
end;
end;
function TPanelObject.AddGuideLine(typ: string; param_1: double; param_2: double = 0; param_3: double = 0; side: byte = 1): TGuideObject;
var
newid, newindex: integer;
begin
newindex := objGuides.Add( TGuideObject.Create(typ) );
// vytvorime nove ID - nemoze to byt index objektu v objektliste, lebo index sa meni ked vymazem nejaky objekt zo stredu objektlistu
if (objGuides.Count = 1) then
newid := 1
else
newid := objGuides[ objGuides.Count-2 ].ID + 1;
with objGuides[newindex] do begin
ID := newid;
Param1 := param_1;
Param2 := param_2;
Param3 := param_3;
Strana := side;
end;
result := objGuides[newindex];
objHasChanged := true;
end;
function TPanelObject.GetGuideLineById(gid: integer): TGuideObject;
var
i: Integer;
begin
for i := 0 to objGuides.Count-1 do
if objGuides[i].ID = gid then begin
result := objGuides[i];
Break;
end;
end;
{
Vrati premennu typu TMyInt2x s maximalne 2 ID-ckami najdenych guidelineov.
Pripadne s 1 alebo ziadnym ID-ckom (ak nic nenajde, budu obidva integery nastavene na 0)
}
function TPanelObject.GetGuidelinesAt(bod_x, bod_y: integer): TMyInt2x;
var
i: integer;
bod_mm: TMyPoint;
currentGuide: TGuideObject;
distAbs: Double;
foundDistances: record
V: Double;
H: Double;
end;
begin
foundDistances.V := MM(10); // hladame guidey, ktore su od mysi blizsie nie X mm ale X pixlov - nech je to pri kazdom zoome rovnake
foundDistances.H := foundDistances.V;
Result.i1 := 0;
Result.i2 := 0;
bod_mm := MyPoint( MM(bod_x, 'x'), MM(bod_y, 'y') );
for i:=0 to objGuides.Count-1 do
if (Assigned(objGuides[i])) AND (objGuides[i].Strana = _PNL.StranaVisible) then begin
currentGuide := objGuides[i];
if (currentGuide.Typ = 'V') then begin
distAbs := Abs(bod_mm.X - currentGuide.Param1);
if (distAbs < foundDistances.V) then begin
foundDistances.V := distAbs;
Result.i1 := currentGuide.ID;
end;
end;
if (currentGuide.Typ = 'H') then begin
distAbs := Abs(bod_mm.Y - currentGuide.Param1);
if (distAbs < foundDistances.H) then begin
foundDistances.H := distAbs;
Result.i2 := currentGuide.ID;
end;
end;
end;
end;
procedure TPanelObject.DelGuideLineById(gid: integer);
var
i: integer;
begin
for i := 0 to objGuides.Count-1 do
if objGuides[i].ID = gid then begin
objGuides.Delete(i);
Break;
end;
objHasChanged := true;
end;
procedure TPanelObject.DeselectAllGuidelines;
var
i: Integer;
begin
for i := 0 to objGuides.Count-1 do
objGuides[i].Selected := false;
end;
procedure TPanelObject.PrepareUndoStep;
var
i: integer;
posledne_ID_pouzite: boolean;
begin
// ak sa nevyuzilo predchadzajuce ID (nema ho ziadny undostep), tak ID nebudeme zvysovat
posledne_ID_pouzite := false;
for i := 0 to High(objUndoList2) do
if (objUndoList2[i].step_ID = objNextUndoStepID) then
posledne_ID_pouzite := true;
// zvysime ID - priradime ho neskor najblizsiemu undostepu
if (posledne_ID_pouzite) then
Inc(objNextUndoStepID);
end;
procedure TPanelObject.CreateUndoStep(undoType: string; subjectType: string; subjectID: integer);
begin
// Undo moze byt typu: Create, Modify, Delete CRT, MOD, DEL
// Subjekt moze byt typu: Panel, Feature, Combo, Guidline PNL, FEA, COM, GUI
objUndoList2[objIndexOfNextUndoStep].step_type := undoType;
objUndoList2[objIndexOfNextUndoStep].step_subject := subjectType;
objUndoList2[objIndexOfNextUndoStep].step_ID := objNextUndoStepID;
objUndoList2[objIndexOfNextUndoStep].step_side := objStranaVisible;
if (subjectType = 'PNL') then begin
objUndoList2[objIndexOfNextUndoStep].obj := TPanelObject.Create;
if (undoType = 'MOD') then begin
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objSirka := objSirka;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objVyska := objVyska;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objHrubka := objHrubka;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objMaterialVlastny := objMaterialVlastny;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objRadius := objRadius;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objPovrch := objPovrch;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objSideZeroes := objSideZeroes;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objHranaStyl := objHranaStyl;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objHranaRozmer := objHranaRozmer;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objHranaObrobenaBottom := objHranaObrobenaBottom;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objHranaObrobenaRight := objHranaObrobenaRight;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objHranaObrobenaTop := objHranaObrobenaTop;
(objUndoList2[objIndexOfNextUndoStep].obj as TPanelObject).objHranaObrobenaLeft := objHranaObrobenaLeft;
end;
end; // PNL
if (subjectType = 'FEA') then begin
if TFeatureObject( GetFeatureByID(subjectID)).Typ = ftPolyLineGrav then
objUndoList2[objIndexOfNextUndoStep].obj := TFeaturePolyLineObject.Create(Self)
else
objUndoList2[objIndexOfNextUndoStep].obj := TFeatureObject.Create(Self);
if (undoType = 'CRT') then
(objUndoList2[objIndexOfNextUndoStep].obj as TFeatureObject).ID := subjectID;
if (undoType = 'MOD')
OR (undoType = 'DEL') then begin
(objUndoList2[objIndexOfNextUndoStep].obj as TFeatureObject).ID := subjectID;
if TFeatureObject( GetFeatureByID(subjectID)).Typ = ftPolyLineGrav then
(objUndoList2[objIndexOfNextUndoStep].obj as TFeaturePolyLineObject).CopyFrom( TFeaturePolyLineObject( GetFeatureByID(subjectID)) )
else
(objUndoList2[objIndexOfNextUndoStep].obj as TFeatureObject).CopyFrom( GetFeatureByID(subjectID) );
end;
end; // FEA
if (subjectType = 'COM') then begin
objUndoList2[objIndexOfNextUndoStep].obj := TComboObject.Create;
if (undoType = 'CRT') then
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).ID := subjectID;
if (undoType = 'MOD') then begin
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).ID := subjectID;
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).Poloha := GetComboByID(subjectID).Poloha;
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).PolohaObject := GetComboByID(subjectID).PolohaObject;
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).Name := GetComboByID(subjectID).Name;
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).Rotation := GetComboByID(subjectID).Rotation;
end;
if (undoType = 'DEL') then begin
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).ID := subjectID;
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).Poloha := GetComboByID(subjectID).Poloha;
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).PolohaObject := GetComboByID(subjectID).PolohaObject;
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).Name := GetComboByID(subjectID).Name;
(objUndoList2[objIndexOfNextUndoStep].obj as TComboObject).Rotation := GetComboByID(subjectID).Rotation;
end;
end; // COM
if (subjectType = 'GUI') then begin
objUndoList2[objIndexOfNextUndoStep].obj := TGuideObject.Create( GetGuideLineById(subjectID).Typ );
if (undoType = 'CRT') then begin
(objUndoList2[objIndexOfNextUndoStep].obj as TGuideObject).ID := subjectID;
end;
if (undoType = 'MOD')
OR (undoType = 'DEL') then begin
(objUndoList2[objIndexOfNextUndoStep].obj as TGuideObject).Param1 := GetGuideLineById(subjectID).Param1;
(objUndoList2[objIndexOfNextUndoStep].obj as TGuideObject).Param2 := GetGuideLineById(subjectID).Param2;
(objUndoList2[objIndexOfNextUndoStep].obj as TGuideObject).Param3 := GetGuideLineById(subjectID).Param3;
end;
end; // GUI
// pre dalsie vlozenie undostepu pripravime spravne index-cislo
Inc(objIndexOfNextUndoStep);
// ak sa ma najblizsi undostep davat uz na poslednu poziciu pola, pole sa navysi o dalsich 100 prvkov
if (objIndexOfNextUndoStep >= High(objUndoList2) ) then
SetLength(objUndoList2, Length(objUndoList2)+100 );
end;
procedure TPanelObject.Undo;
var
i, j: integer;
original_id, reborn_id: integer;
currUndoStep: TMyUndoStep_v2;
begin
for i := High(objUndoList2) downto 0 do
// vratime spat len tie kroky, ktore maju najvyssi STEP_ID
if (objUndoList2[i].step_ID = objNextUndoStepID) then begin
currUndoStep := objUndoList2[i];
// ak vraciame operacie, ktore clovek urobil na opacnej strane panela (a potom ho prevratil), najprv sa prepneme na tu stranu
if (objStranaVisible <> currUndoStep.step_side) then
fMain.btnSideSwitch.Click;
if (currUndoStep.step_subject = 'PNL') then begin
if (currUndoStep.step_type = 'MOD') then begin
objSirka := (currUndoStep.obj as TPanelObject).Sirka;
objVyska := (currUndoStep.obj as TPanelObject).Vyska;
objHrubka := (currUndoStep.obj as TPanelObject).Hrubka;
objMaterialVlastny := (currUndoStep.obj as TPanelObject).MaterialVlastny;
objRadius := (currUndoStep.obj as TPanelObject).Radius;
objPovrch := (currUndoStep.obj as TPanelObject).Povrch;
SetCenterPosByNum( (currUndoStep.obj as TPanelObject).GetCenterPosByNum(1) , 1);
SetCenterPosByNum( (currUndoStep.obj as TPanelObject).GetCenterPosByNum(2) , 2);
objHranaStyl := (currUndoStep.obj as TPanelObject).HranaStyl;
objHranaRozmer := (currUndoStep.obj as TPanelObject).HranaRozmer;
objHranaObrobenaBottom := (currUndoStep.obj as TPanelObject).HranaObrobenaBottom;
objHranaObrobenaRight := (currUndoStep.obj as TPanelObject).HranaObrobenaRight;
objHranaObrobenaTop := (currUndoStep.obj as TPanelObject).HranaObrobenaTop;
objHranaObrobenaLeft := (currUndoStep.obj as TPanelObject).HranaObrobenaLeft;
end;
end; // PNL
if (currUndoStep.step_subject = 'FEA') then begin
if (currUndoStep.step_type = 'CRT') then begin
DelFeatureByID( (currUndoStep.obj as TFeatureObject).ID );
end;
if (currUndoStep.step_type = 'MOD') then begin
if GetFeatureByID( (currUndoStep.obj as TFeatureObject).ID ).Typ = ftPolyLineGrav then
TFeaturePolyLineObject( GetFeatureByID( (currUndoStep.obj as TFeatureObject).ID )).CopyFrom( (currUndoStep.obj as TFeaturePolyLineObject) )
else
GetFeatureByID( (currUndoStep.obj as TFeatureObject).ID ).CopyFrom( (currUndoStep.obj as TFeatureObject) );
end;
if (currUndoStep.step_type = 'DEL') then begin
// ulozime si aj povodne ID, aj nove ID (musime vytvorit novy objekt, ked robime undo po zmazani)
original_id := (currUndoStep.obj as TFeatureObject).ID;
reborn_id := AddFeature( (currUndoStep.obj as TFeatureObject).Typ );
GetFeatureByID( reborn_id ).CopyFrom( (currUndoStep.obj as TFeatureObject) );
// ked sme nanovo vytvorili objekt, uz nema take ID ako pred zmazanim,
// takze aj v zaznamoch undolistu musime opravit ID objektu
for j := 0 to High(objUndoList2) do begin
if Assigned(objUndoList2[j].obj) then begin
if (objUndoList2[j].step_subject = 'FEA') AND ((objUndoList2[j].obj as TFeatureObject).ID = original_id) then
(objUndoList2[j].obj as TFeatureObject).ID := reborn_id;
end;
end;
end;
end; // FEA
if (currUndoStep.step_subject = 'COM') then begin
if (currUndoStep.step_type = 'CRT') then begin
ExplodeCombo( (currUndoStep.obj as TComboObject).ID );
end;
if (currUndoStep.step_type = 'MOD') then begin
GetComboByID( (currUndoStep.obj as TComboObject).ID ).Poloha := (currUndoStep.obj as TComboObject).Poloha;
GetComboByID( (currUndoStep.obj as TComboObject).ID ).PolohaObject := (currUndoStep.obj as TComboObject).PolohaObject;
GetComboByID( (currUndoStep.obj as TComboObject).ID ).Name := (currUndoStep.obj as TComboObject).Name;
GetComboByID( (currUndoStep.obj as TComboObject).ID ).Rotation := (currUndoStep.obj as TComboObject).Rotation;
end;
if (currUndoStep.step_type = 'DEL') then begin
// ulozime si aj povodne ID, aj nove ID (musime vytvorit novy objekt, ked robime undo po zmazani)
original_id := (currUndoStep.obj as TComboObject).ID;
reborn_id := AddCombo;
GetComboByID(reborn_id).Rotation := (currUndoStep.obj as TComboObject).Rotation;
GetComboByID(reborn_id).Poloha := (currUndoStep.obj as TComboObject).Poloha;
GetComboByID(reborn_id).PolohaObject := (currUndoStep.obj as TComboObject).PolohaObject;
// ked sme nanovo vytvorili objekt, uz nema take ID ako pred zmazanim,
// takze aj v zaznamoch undolistu musime opravit ID objektu
for j := 0 to High(objUndoList2) do begin
if Assigned(objUndoList2[j].obj) then begin
if (objUndoList2[j].step_subject = 'FEA')
AND ((objUndoList2[j].obj as TFeatureObject).ComboID = original_id) then
(objUndoList2[j].obj as TFeatureObject).ComboID := reborn_id;
if (objUndoList2[j].step_subject = 'COM')
AND ((objUndoList2[j].obj as TComboObject).ID = original_id) then
(objUndoList2[j].obj as TComboObject).ID := reborn_id;
end;
end;
end;
end; // COM
if (currUndoStep.step_subject = 'GUI') then begin
if (currUndoStep.step_type = 'CRT') then begin
DelGuideLineById( (currUndoStep.obj as TGuideObject).ID );
end;
if (currUndoStep.step_type = 'DEL') then begin
AddGuideLine(
(currUndoStep.obj as TGuideObject).Typ,
(currUndoStep.obj as TGuideObject).Param1,
(currUndoStep.obj as TGuideObject).Param2,
(currUndoStep.obj as TGuideObject).Param3
);
end;
end; // GUI
// nie je to nutne, ale vymazeme aspon zakladne data zo zaznamu
currUndoStep.step_ID := 0;
currUndoStep.step_type := '';
currUndoStep.step_subject := '';
// aj objekt, nech sa setri pamat
if Assigned(currUndoStep.obj) then
FreeAndNil(currUndoStep.obj);
// nakoniec znizime aj index-cislo, nech je pripravene pre zapis noveho undostepu
Dec(objIndexOfNextUndoStep);
end; //if (currUndoStep.step_ID = objNextUndoStepID)
Dec(objNextUndoStepID);
if (GetNumberOfUndoSteps = 0) then
SetHasChanged(false);
Draw;
end;
function TPanelObject.GetNumberOfUndoSteps: integer;
begin
result := objNextUndoStepID;
end;
end.
|
unit UnitAMapWebAPI;
interface
uses
System.SysUtils, System.Classes, IPPeerClient, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, REST.Response.Adapter, REST.Client, Data.Bind.Components,
Data.Bind.ObjectScope;
type
TDMAMapWebAPI = class(TDataModule)
RESTClient: TRESTClient;
RESTRequest: TRESTRequest;
RESTResponse: TRESTResponse;
RESTResponseDataSetAdapter: TRESTResponseDataSetAdapter;
FDMemTable: TFDMemTable;
FDMemTable2: TFDMemTable;
procedure DataModuleCreate(Sender: TObject);
private
CoordConvertURL: string;
RevGeocodingURL: string;
TruckRouteURL: string;
DistanceURL: string;
WeatherInfoURL: string;
GeofenceMetaURL: string;
GeofenceStatusURL: string;
A38, A44: string;
procedure ClearStatus;
public
WebApiKey: string;
//
function Gps2AMap(const GpsLng, GpsLat: string): string; // 坐标转换API
function RevGeocoding(const AMapLng, AMapLat: string): string; // 根据经纬度获取地址信息
function TruckRoutePlan(const BeginLng, BeginLat, EndLng, EndLat, ADiu, Aheight, Awidth, Aload, Aweight, Aaxis, Aprovince, Anumber, Astrategy,
Asize: string): string; // 货车运输计划数据
function Distance(const BeginLng, BeginLat, EndLng, EndLat, AType: string): string; // 距离量算
function WeatherInfo(const Acity, Aextensions: string): string; // 天气查询
function GeofenceQuery(const Agid: string = ''): string; // 查询围栏
function GeofenceDelete(const Agid: string): string; // 删除围栏
function GeofenceCheckin(const ADiu, AMapLng, AMapLat, Agid: string): string; // 围栏设备监控
end;
var
DMAMapWebAPI: TDMAMapWebAPI;
implementation
uses System.JSON, System.DateUtils, REST.Types;
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
function TDMAMapWebAPI.GeofenceCheckin(const ADiu, AMapLng, AMapLat, Agid: string): string;
var
URL, diu, locations: string;
begin
//
ClearStatus;
URL := Concat(GeofenceStatusURL, 'key=', WebApiKey, A38);
diu := Concat('diu=', ADiu, A38);
locations := Concat('locations=', AMapLng, A44, AMapLat);
URL := Concat(URL, diu, locations, A44, DateTimeToUnix(Now).ToString);
RESTClient.BaseURL := URL;
RESTRequest.Method := TRESTRequestMethod.rmGET;
RESTRequest.Execute;
Result := FDMemTable.FieldByName('errmsg').AsString;
if (Result = 'OK') then
begin
RESTResponse.RootElement := 'data.fencing_event_list';
if (FDMemTable.RecordCount = 1) then
begin
if (FDMemTable.FieldByName('client_status').AsString = 'in') then
begin
RESTResponse.RootElement := 'data.fencing_event_list[0].fence_info';
if Agid = FDMemTable.FieldByName('fence_gid').AsString then
begin
Exit('1');
end
else
begin
Exit('0');
end;
end;
end
else
begin
Exit('0'); // 不在围栏内
end;
end;
end;
function TDMAMapWebAPI.GeofenceDelete(const Agid: string): string;
var
URL, gid: string;
begin
//
ClearStatus;
URL := Concat(GeofenceMetaURL, 'key=', WebApiKey, A38);
gid := Concat('gid=', Agid);
URL := Concat(URL, gid);
RESTClient.BaseURL := URL;
RESTRequest.Method := TRESTRequestMethod.rmDELETE;
RESTRequest.Execute;
Result := FDMemTable.FieldByName('errmsg').AsString;
if (Result = 'OK') then
begin
RESTResponse.RootElement := 'data';
Result := FDMemTable.FieldByName('message').AsString;
end;
end;
function TDMAMapWebAPI.GeofenceQuery(const Agid: string): string;
var
URL, gid: string;
begin
// 返回 Key 所创建的 所有 或 某个 围栏信息 errcode
ClearStatus;
URL := Concat(GeofenceMetaURL, 'key=', WebApiKey, A38);
gid := Concat('gid=', Agid);
URL := Concat(URL, gid);
RESTClient.BaseURL := URL;
RESTRequest.Method := TRESTRequestMethod.rmGET;
RESTRequest.Execute;
Result := FDMemTable.FieldByName('errmsg').AsString;
if (Result = 'OK') then
begin
RESTResponse.RootElement := 'data.rs_list';
end;
end;
function TDMAMapWebAPI.Gps2AMap(const GpsLng, GpsLat: string): string;
var
URL, locations: string;
begin
// 回返 longitude,latitude
ClearStatus;
URL := Concat(CoordConvertURL, 'key=', WebApiKey, A38, 'coordsys=gps', A38);
locations := Concat('locations=', GpsLng, A44, GpsLat);
URL := Concat(URL, locations);
RESTClient.BaseURL := URL;
RESTRequest.Method := TRESTRequestMethod.rmGET;
RESTRequest.Execute;
if (FDMemTable.FieldByName('status').AsInteger = 1) then
begin
Exit(FDMemTable.FieldByName('locations').AsString);
end
else
begin
Exit(FDMemTable.FieldByName('info').AsString);
end;
end;
function TDMAMapWebAPI.TruckRoutePlan(const BeginLng, BeginLat, EndLng, EndLat, ADiu, Aheight, Awidth, Aload, Aweight, Aaxis, Aprovince, Anumber,
Astrategy, Asize: string): string;
var
URL, origin, destination, diu, height, width, load, weight, axis, province, number, strategy, size, showpolyline: string;
begin
{ Astrategy
1---“躲避拥堵”
2---“不走高速”
3---“避免收费”
4---“躲避拥堵&不走高速”
5---“避免收费&不走高速” //3+2
6---“躲避拥堵&避免收费”
7---“躲避拥堵&避免收费&不走高速”
8---“高速优先” //
9---“躲避拥堵&高速优先” //1+8
}
// 回返 获取状态, FDMemTable切换到 data.route.paths
ClearStatus;
URL := Concat(TruckRouteURL, 'key=', WebApiKey, A38);
origin := Concat('origin=', BeginLng, A44, BeginLat, A38);
destination := Concat('destination=', EndLng, A44, EndLat, A38);
diu := Concat('diu=', ADiu, A38);
height := Concat('height=', Aheight, A38);
width := Concat('width=', Awidth, A38);
load := Concat('load=', Aload, A38);
weight := Concat('weight=', Aweight, A38);
axis := Concat('axis=', Aaxis, A38);
province := Concat('province=', Aprovince, A38);
number := Concat('number=', Anumber, A38);
strategy := Concat('strategy=', Astrategy, A38);
size := Concat('size=', Asize, A38);
showpolyline := Concat('showpolyline=', '0');
URL := Concat(URL, origin, destination, diu, height, width, load, weight, axis, province, number, strategy, size, showpolyline);
RESTClient.BaseURL := URL;
RESTRequest.Method := TRESTRequestMethod.rmGET;
RESTRequest.Execute;
Result := FDMemTable.FieldByName('errmsg').AsString;
if Result = 'OK' then
begin
RESTResponse.RootElement := 'data.route.paths';
end;
end;
function TDMAMapWebAPI.WeatherInfo(const Acity, Aextensions: string): string;
var
URL, city, extensions: string;
begin
// 返回 天气信息,切换到 lives 或 forecasts[0].casts
// 可选值:base/all base:返回实况天气 all:返回预报天气
ClearStatus;
URL := Concat(WeatherInfoURL, 'key=', WebApiKey, A38);
city := Concat('city=', Acity, A38);
extensions := Concat('extensions=', Aextensions);
URL := Concat(URL, city, extensions);
RESTClient.BaseURL := URL;
RESTRequest.Method := TRESTRequestMethod.rmGET;
RESTRequest.Execute;
if (FDMemTable.FieldByName('status').AsInteger = 1) then
begin
if LowerCase(Aextensions) = 'base' then
begin
RESTResponse.RootElement := 'lives';
Exit(FDMemTable.FieldByName('weather').AsString);
end
else
begin
RESTResponse.RootElement := 'forecasts[0].casts';
Exit(FDMemTable.FieldByName('dayweather').AsString);
end;
end
else
begin
Exit(FDMemTable.FieldByName('info').AsString);
end;
end;
function TDMAMapWebAPI.RevGeocoding(const AMapLng, AMapLat: string): string;
var
URL, Location: string;
begin
// 回返详细地址, FDMemTable切换到 regeocode.addressComponent
ClearStatus;
URL := Concat(RevGeocodingURL, 'key=', WebApiKey, A38);
Location := Concat('location=', AMapLng, A44, AMapLat);
URL := Concat(URL, Location);
RESTClient.BaseURL := URL;
RESTRequest.Method := TRESTRequestMethod.rmGET;
RESTRequest.Execute;
if (FDMemTable.FieldByName('status').AsInteger = 1) then
begin
RESTResponse.RootElement := 'regeocode';
Result := FDMemTable.FieldByName('formatted_address').AsString;
RESTResponse.RootElement := 'regeocode.addressComponent';
end
else
begin
Exit(FDMemTable.FieldByName('info').AsString);
end;
end;
procedure TDMAMapWebAPI.ClearStatus;
begin
RESTResponse.ResetToDefaults;
RESTResponseDataSetAdapter.ClearDataSet;
RESTResponse.RootElement := EmptyStr;
end;
procedure TDMAMapWebAPI.DataModuleCreate(Sender: TObject);
begin
A38 := #38; // &
A44 := #44; // ,
WebApiKey := '02deb20436dcd7b9fc25a2c9da700db';
CoordConvertURL := 'https://restapi.amap.com/v3/assistant/coordinate/convert?';
RevGeocodingURL := 'https://restapi.amap.com/v3/geocode/regeo?';
TruckRouteURL := 'https://restapi.amap.com/v4/direction/truck?';
DistanceURL := 'https://restapi.amap.com/v3/distance?';
WeatherInfoURL := 'https://restapi.amap.com/v3/weather/weatherInfo?';
GeofenceMetaURL := 'https://restapi.amap.com/v4/geofence/meta?';
GeofenceStatusURL := 'https://restapi.amap.com/v4/geofence/status?';
end;
function TDMAMapWebAPI.Distance(const BeginLng, BeginLat, EndLng, EndLat, AType: string): string;
var
URL, origin, destination: string;
begin
{ AType
0:直线距离
1:驾车导航距离(仅支持国内坐标)
必须指出,当为1时会考虑路况,故在不同时间请求返回结果可能不同。
此策略和驾车路径规划接口的 strategy=4策略基本一致,策略为“ 躲避拥堵的路线,但是可能会存在绕路的情况,耗时可能较长 ”
若需要实现高德地图客户端效果,可以考虑使用驾车路径规划接口
2:公交规划距离(仅支持同城坐标,QPS不可超过1,否则可能导致意外)
3:步行规划距离
}
// 回返距离 m, FDMemTable切换到 results
ClearStatus;
URL := Concat(DistanceURL, 'key=', WebApiKey, A38);
origin := Concat('origins=', BeginLng, A44, BeginLat, A38);
destination := Concat('destination=', EndLng, A44, EndLat, A38); // results
URL := Concat(URL, origin, destination, 'type=', AType);
RESTClient.BaseURL := URL;
RESTRequest.Method := TRESTRequestMethod.rmGET;
RESTRequest.Execute;
if (FDMemTable.FieldByName('status').AsInteger = 1) then
begin
RESTResponse.RootElement := 'results';
Exit(FDMemTable.FieldByName('distance').AsString);
end
else
begin
Exit(FDMemTable.FieldByName('info').AsString);
end;
end;
end.
|
{**********************************************}
{ TMyPointSeries }
{ TBarJoinSeries }
{ Copyright (c) 1997-2004 by David Berneda }
{**********************************************}
unit MyPoint;
{$I TeeDefs.inc}
interface
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, Types,
{$ELSE}
Graphics,
{$ENDIF}
TeEngine, Chart, Series, TeCanvas;
{ This sample Series derives from TPointSeries.
It shows how to override the DrawValue method, which is called
every time every point in the Series should be displayed.
In this sample, one horizontal line and one vertical line are
drawn from the axis to every point.
A new TPen property is published to control the lines attributes.
}
type TMyPointSeries=class(TPointSeries)
private
FLinesPen : TChartPen;
procedure SetLinesPen(Value:TChartPen);
protected
procedure DrawValue(ValueIndex:Integer); override;
class Function GetEditorClass:String; override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
Procedure Assign(Source:TPersistent); override;
published
property LinesPen:TChartPen read FLinesPen write SetLinesPen;
end;
TBarJoinSeries=class(TBarSeries)
private
FJoinPen: TChartPen;
OldBarBounds : TRect;
IFirstPoint : Boolean;
procedure SetJoinPen(const Value: TChartPen);
protected
procedure DoBeforeDrawChart; override;
class Function GetEditorClass:String; override;
Procedure PrepareForGallery(IsEnabled:Boolean); override;
public
Constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
Procedure Assign(Source:TPersistent); override;
Procedure DrawBar(BarIndex,StartPos,EndPos:Integer); override;
Function NumSampleValues:Integer; override;
published
property JoinPen:TChartPen read FJoinPen write SetJoinPen;
end;
implementation
Uses TeeProCo;
{ overrided constructor to change default pointer style and 3D }
Constructor TMyPointSeries.Create(AOwner:TComponent);
begin
inherited;
Pointer.Draw3D:=False;
Pointer.Style:=psDiamond;
FLinesPen:=CreateChartPen; { <-- create new pen property }
FLinesPen.Color:=clRed; { <-- set default color to Red }
end;
Destructor TMyPointSeries.Destroy;
begin
FLinesPen.Free;
inherited;
end;
procedure TMyPointSeries.Assign(Source: TPersistent);
begin
if Source is TMyPointSeries then LinesPen:=TMyPointSeries(Source).LinesPen;
inherited;
end;
{ overrided DrawValue to draw additional lines for each point }
procedure TMyPointSeries.DrawValue(ValueIndex:Integer);
var tmpX : Integer;
tmpY : Integer;
begin
{ calculate the point position }
tmpX:=CalcXPos(ValueIndex);
tmpY:=CalcYPos(ValueIndex);
With ParentChart,Canvas do
begin
{ change brush and pen attributes }
Brush.Style:=bsClear;
BackMode:=cbmTransparent;
AssignVisiblePen(FLinesPen);
{ draw the horizontal and vertical lines }
MoveTo3D(GetVertAxis.PosAxis,tmpY,StartZ);
LineTo3D(tmpX,tmpY,StartZ);
LineTo3D(tmpX,GetHorizAxis.PosAxis,StartZ);
end;
inherited; { <-- draw the point }
end;
procedure TMyPointSeries.SetLinesPen(Value:TChartPen);
begin
FLinesPen.Assign(Value);
end;
class function TMyPointSeries.GetEditorClass: String;
begin
result:='TLinePointEditor';
end;
{ TBarJoinSeries }
Constructor TBarJoinSeries.Create(AOwner: TComponent);
begin
inherited;
FJoinPen:=CreateChartPen;
end;
Destructor TBarJoinSeries.Destroy;
begin
FJoinPen.Free;
inherited;
end;
procedure TBarJoinSeries.Assign(Source: TPersistent);
begin
if Source is TBarJoinSeries then
JoinPen:=TBarJoinSeries(Source).JoinPen;
inherited;
end;
procedure TBarJoinSeries.DoBeforeDrawChart;
begin
inherited;
IFirstPoint:=True;
end;
procedure TBarJoinSeries.DrawBar(BarIndex, StartPos, EndPos: Integer);
var tmpA : Integer;
tmpB : Integer;
tmpTopA : Integer;
tmpTopB : Integer;
begin
inherited;
if not IFirstPoint then
begin
Case BarStyle of
bsPyramid,bsEllipse,bsArrow,bsCone:
begin
tmpA:=(OldBarBounds.Left+OldBarBounds.Right) div 2;
tmpB:=(BarBounds.Left+BarBounds.Right) div 2;
end;
else
begin
tmpA:=OldBarBounds.Right;
tmpB:=BarBounds.Left;
end;
end;
tmpTopA:=OldBarBounds.Top;
tmpTopB:=BarBounds.Top;
if not DrawValuesForward then
begin
tmpA:=BarBounds.Right;
tmpB:=OldBarBounds.Left;
SwapInteger(tmpTopA,tmpTopB);
end;
With ParentChart,Canvas do
begin
AssignVisiblePen(FJoinPen);
if View3D then
begin
MoveTo3D(tmpA,tmpTopA,MiddleZ);
LineTo3D(tmpB,tmpTopB,MiddleZ);
end
else
begin
MoveTo(tmpA,tmpTopA);
LineTo(tmpB,tmpTopB);
end;
end;
end;
IFirstPoint:=False;
OldBarBounds:=BarBounds;
end;
procedure TBarJoinSeries.SetJoinPen(const Value: TChartPen);
begin
FJoinPen.Assign(Value);
end;
function TBarJoinSeries.NumSampleValues: Integer;
begin
result:=3;
end;
procedure TBarJoinSeries.PrepareForGallery(IsEnabled: Boolean);
begin
inherited;
FJoinPen.Color:=clBlue;
FJoinPen.Width:=2;
FillSampleValues(2);
end;
class function TBarJoinSeries.GetEditorClass: String;
begin
result:='TBarJoinEditor';
end;
initialization
RegisterTeeSeries( TMyPointSeries,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryLinePoint,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GallerySamples, 1);
RegisterTeeSeries( TBarJoinSeries,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryBarJoin,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GallerySamples, 1);
finalization
UnRegisterTeeSeries([TMyPointSeries,TBarJoinSeries]);
end.
|
unit fMyDate;
interface
type
TMyDate = class
private
fDate: string[4];
fMonth: byte;
fYear: smallInt;
function DoConvert: string;
function SwitchYearMonth(ADate: string): string;
public
constructor Create;
function Convert(Month: Byte; Year: smallInt): string;
function SetDate(Month: byte; Year: smallInt): byte;
function StepUp: string;
function StepDown: string;
function GetDate: string;
function EarlierThan(ADate: string): boolean;
function LaterThan(ADate: string): boolean;
function Equals(ADate: string): boolean;
end;
implementation
constructor TMyDate.Create;
begin
inherited;
fMonth := 0;
fYear := 0;
fDate := '';
end;
function TMyDate.DoConvert: string;
begin
if fMonth * fYear = 0 then Exit;
Result := Chr(48 + fMonth div 10) + Chr(48 + fMonth mod 10);
Result := Result + Chr(48 + (fYear mod 100) div 10) + Chr(48 + (fYear mod 100) mod 10);
end;
function TMyDate.SwitchYearMonth(ADate: string): string;
begin
try
Result := ADate[3] + ADate[4] + ADate[1] + ADate[2];
except
Result := '';
end;
end;
function TMyDate.Convert(Month: Byte; Year: smallInt): string;
begin
if Month * Year = 0 then Exit;
Result := Chr(48 + Month div 10) + Chr(48 + Month mod 10);
Result := Result + Chr(48 + (Year mod 100) div 10) + Chr(48 + (Year mod 100) mod 10);
end;
function TMyDate.SetDate(Month: byte; Year: smallInt): byte;
begin
Result := 1;
fMonth := 0;
fYear := 0;
if (Month < 13) then fMonth := Month;
if (Year > 1970) and (Year < 2050) then fYear := Year;
if fMonth * fYear <> 0 then
Result := 0;
end;
function TMyDate.StepUp: string;
begin
Inc(fMonth);
if fMonth > 12 then begin
fMonth := 1;
Inc(fYear);
end;
Result := DoConvert;
end;
function TMyDate.StepDown: string;
begin
Dec(fMonth);
if fMonth < 1 then begin
fMonth := 12;
Dec(fYear);
end;
Result := DoConvert;
end;
function TMyDate.GetDate: string;
begin
Result := DoConvert;
end;
function TMyDate.EarlierThan(ADate: string): boolean;
begin
Result := False;
if ADate = '' then Exit;
Result := SwitchYearMonth(GetDate) < SwitchYearMonth(ADate);
end;
function TMyDate.LaterThan(ADate: string): boolean;
begin
Result := False;
if ADate = '' then Exit;
Result := SwitchYearMonth(GetDate) > SwitchYearMonth(ADate);
end;
function TMyDate.Equals(ADate: string): boolean;
begin
Result := False;
if ADate = '' then Exit;
Result := ADate = GetDate;
end;
end.
|
unit g_hud;
interface
uses
OpenGL, Windows, u_winapi, u_math, g_class_gameobject, g_game_objects, Textures, u_consts, u_opengl, u_utils;
type
THudCursor = class (TGameObject)
procedure Move; override;
procedure Render; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
constructor Create;
end;
TCompas = class (TGameObject)
procedure Render; override;
procedure Move; override;
end;
THUD = class
Bg : GLuint;
Cursor : THudCursor;
Compas : TCompas;
Font_FixeSys,
Font_Courier_new : GLuint;
Fade_Trans : Single;
Fade_Status : (fsNone, fsFadeIn, fsFadeOut);
MainLabel : String;
MainLabelTime : Integer;
procedure ReInit;
procedure WriteLn(Font:GLuint; tx,ty:integer; Text: String; r, g, b: Single);
procedure Render;
procedure Move;
procedure SetOrtho;
procedure FadeIn;
procedure FadeOut;
constructor Create;
end;
var
HUD : THUD;
implementation
uses
g_player, g_world;
{ THUD }
constructor THUD.Create;
var
font : HFONT;
begin
ReInit;
Compas := TCompas.Create;
Compas.Pos.x := WINDOW_WIDTH - 60;
Compas.Pos.y := WINDOW_HEIGHT - 60;
LoadTexture('i/space.jpg', Bg, False);
Font_FixeSys := glGenLists(256);
font := CreateFont(23, 12, 0, 0, FW_NORMAL, 0, 0, 0, ANSI_CHARSET, OUT_TT_PRECIS,
CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY , FF_DONTCARE or DEFAULT_PITCH, 'Fixedsys');
SelectObject(DC, font);
wglUseFontBitmaps(DC, 0, 256, Font_FixeSys);
DeleteObject(font);
Font_Courier_new := glGenLists(256);
font := CreateFont(12, 12, 0, 0, FW_NORMAL, 0, 0, 0, ANSI_CHARSET, OUT_TT_PRECIS,
CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY , FF_DONTCARE or DEFAULT_PITCH, 'Courier New');
SelectObject(DC, font);
wglUseFontBitmaps(DC, 0, 256, Font_Courier_new);
DeleteObject(font);
FadeOut;
end;
procedure THUD.FadeIn;
begin
Fade_Status := fsFadeIn;
Fade_Trans := 0.0;
end;
procedure THUD.FadeOut;
begin
Fade_Status := fsFadeOut;
Fade_Trans := 1.0;
end;
procedure THUD.Move;
begin
if Fade_Status = fsFadeIn then
begin
Fade_Trans := Fade_Trans + 0.005;
if Fade_Trans >= 1 then Fade_Status := fsNone;
end else if Fade_Status = fsFadeOut then
begin
Fade_Trans := Fade_Trans - 0.005;
if Fade_Trans <= 0 then Fade_Status := fsNone;
end;
if MainLabelTime > 0 then
dec(MainLabelTime);
Compas.Move;
end;
procedure THUD.ReInit;
begin
Cursor := THudCursor.Create;
ObjectsEngine.AddObject(Cursor);
end;
procedure THUD.Render;
var
i,j:Integer;
begin
glPushMatrix;
glEnable(GL_TEXTURE_2D);
glColor3f(1, 1, 1);
glBindTexture(GL_TEXTURE_2D, Bg);
glBegin(GL_QUADS);
for i := -10 to 10 do for j := -10 to 10 do
begin
glTexCoord2f(0, 0); glVertex3i(i * 30, -1, j * 30);
glTexCoord2f(1, 0); glVertex3i(i * 30 + 30, -1, j * 30);
glTexCoord2f(1, 1); glVertex3i(i * 30 + 30, -1, j*30 +30);
glTexCoord2f(0, 1); glVertex3i(i * 30, -1, j*30 + 30);
end;
glEnd;
glDisable(GL_TEXTURE_2D);
glPopMatrix;
SetOrtho;
Compas.Render;
//if Fade_Status <> fsNone then
//begin
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(0.0, 0.0, 0.0, Fade_Trans);
glBegin(GL_QUADS);
glVertex2i(0, 0);
glVertex2i(WINDOW_WIDTH, 0);
glVertex2i(WINDOW_WIDTH, WINDOW_HEIGHT);
glVertex2i(0, WINDOW_HEIGHT);
glEnd;
glDisable(GL_BLEND);
// end;
{DEBUG}
{WriteLn(Font_Courier_new, 5, 10, 'Objects Drawn : ' + IntToStr(ObjectsEngine.Rendered), 1, 1, 1);
WriteLn(Font_Courier_new, 5, 20, 'PlayerX : ' + FloatToStr(Player.Pos.X), 1, 1, 1);
WriteLn(Font_Courier_new, 5, 30, 'PlayerY : ' + FloatToStr(Player.Pos.Y), 1, 1, 1);
WriteLn(Font_Courier_new, 5, 40, 'PlayerZ : ' + FloatToStr(Player.Pos.Z), 1, 1, 1);
WriteLn(Font_Courier_new, 5, 50, 'Player Angle : ' + FloatToStr(Player.Angle), 1, 1, 1);
WriteLn(Font_Courier_new, 5, 60, 'Player Speed : ' + FloatToStr(Player.Speed), 1, 1, 1);
WriteLn(Font_Courier_new, 5, 70, 'Player.MVector.x : ' + FloatToStr(Player.MVector.x), 1, 1, 1);
WriteLn(Font_Courier_new, 5, 80, 'Player.MVector.y : ' + FloatToStr(Player.MVector.y), 1, 1, 1);
WriteLn(Font_Courier_new, 5, 90, 'Player.MVector.z : ' + FloatToStr(Player.MVector.z), 1, 1, 1);
WriteLn(Font_Courier_new, 5, 100, 'Player.Health : ' + FloatToStr(Player.Health), 1, 1, 1); }
//WriteLn(Font_Courier_new, 5, 110, 'Trans : ' + FloatToStr(Fade_Trans), 1, 1, 1);
{Debug}
if MainLabelTime > 0 then
begin
WriteLn(Font_FixeSys, WINDOW_WIDTH div 2 - (Length(MainLabel) div 2) * 20, WINDOW_HEIGHT div 2, MainLabel, 1, 1, 1);
end;
WriteLn(Font_FixeSys, 5, WINDOW_HEIGHT-60, 'Lifes x ' + IntToStr(World.Lifes) + ' (' + FloatToStr(Player.Health, 0) + '%)', 1, 0.7, 0);
WriteLn(Font_FixeSys, 5, WINDOW_HEIGHT-40, 'Score : ' + IntToStr(World.Score), 1, 0.7, 0);
Writeln(Font_FixeSys, 5, WINDOW_HEIGHT-20, 'Coins : ' + IntToStr(World.Coins_coll) + '/' + IntToStr(World.Coins_Total), 1, 0.7, 0);
end;
procedure THUD.SetOrtho;
begin
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluOrtho2D(0, WINDOW_WIDTH, WINDOW_HEIGHT, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
end;
procedure THUD.WriteLn;
procedure glPutchar(text : PChar);
begin
if (text = '') then Exit;
glListBase(Font);
glCallLists(length(text), GL_UNSIGNED_BYTE, text);
end;
begin
glColor3f(r, g, b);
glRasterPos3f(tx, ty, 1);
glPutchar(PChar(text));
glColor3f(1, 1, 1);
end;
{ THudCursor }
constructor THudCursor.Create;
begin
Health := 100;
Collision := False;
end;
procedure THudCursor.DoCollision(Vector: TGamePos; CoObject: TObject);
begin
end;
procedure THudCursor.Move;
var
TmpV : TGamePos;
begin
Pos.x := Pos.x + Mouse_Dx / 20;
Pos.z := Pos.z + Mouse_Dy / 20;
{ if Distance(Pos, Player.Pos) > 20 then
begin
Pos := AddVector(Player.Pos, MultiplyVectorScalar( NormalizeVector(MinusVctors(Pos, Player.Pos)), 20));
end;}
// Pos := AddVector(Pos, Player.MVector);
end;
procedure THudCursor.Render;
begin
glPushMatrix;
glColor3f(0.0, 0.5, 1.0);
glTranslatef(Player.Pos.x, Player.Pos.y, Player.Pos.z);
glBegin(GL_LINES);
glVertex3f(Pos.x-1, 0, Pos.z);
glVertex3f(Pos.x+1, 0, Pos.z);
glVertex3f(Pos.x, 0, Pos.z+1);
glVertex3f(Pos.x, 0, Pos.z-1);
glEnd;
glPopMatrix;
end;
{ TCompas }
procedure TCompas.Move;
var
CPos : TGamePos;
begin
CPos := ObjectsEngine.GetNearestCoin;
Angle := AngleTo(Player.Pos.x, Player.Pos.z, CPos.x, CPOs.z);
end;
procedure TCompas.Render;
var
a : Integer;
begin
glPushMatrix;
glTranslatef(Pos.x, Pos.y, 0);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINE_LOOP);
for a := 0 to 18 do
begin
glVertex2f(Cosinus(a * 20) * 50, Sinus(a * 20) * 50);
end;
glEnd;
glRotatef(Angle, 0, 0, 1);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POLYGON);
glVertex2f(50, 0);
glVertex2f(0, -5);
glVertex2f( 0, 5);
glEnd;
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(-50, 0);
glVertex2f(0, -5);
glVertex2f( 0, 5);
glEnd;
glPopMatrix;
end;
end.
|
Unit UnAtualizacao;
interface
Uses Classes, DbTables,SysUtils;
Const
CT_VersaoBanco = 353;
CT_VersaoInvalida = 'SISTEMA DESATUALIZADO!!! Este sistema já possui novas versões, essa versão pode não funcionar corretamente, para o bom funcionamento do mesmo é necessário fazer atualização...' ;
CT_SenhaAtual = '9774';
Type
TAtualiza = Class
Private
Aux : TQuery;
DataBase : TDataBase;
procedure AtualizaSenha( Senha : string );
procedure AlteraVersoesSistemas;
public
procedure AtualizaTabela(VpaNumAtualizacao : Integer);
function AtualizaTabela1(VpaNumAtualizacao : Integer): String;
procedure AtualizaBanco;
constructor criar( aowner : TComponent; ADataBase : TDataBase );
end;
implementation
Uses FunSql, ConstMsg, FunNumeros,Registry, Constantes, FunString, funvalida;
{*************************** cria a classe ************************************}
constructor TAtualiza.criar( aowner : TComponent; ADataBase : TDataBase );
begin
inherited Create;
Aux := TQuery.Create(aowner);
DataBase := ADataBase;
Aux.DataBaseName := 'BaseDados';
end;
{*************** atualiza senha na base de dados ***************************** }
procedure TAtualiza.AtualizaSenha( Senha : string );
var
ini : TRegIniFile;
senhaInicial : string;
begin
try
if not DataBase.InTransaction then
DataBase.StartTransaction;
// atualiza regedit
Ini := TRegIniFile.Create('Software\Systec\Sistema');
senhaInicial := Ini.ReadString('SENHAS','BANCODADOS', ''); // guarda senha do banco
Ini.WriteString('SENHAS','BANCODADOS', Criptografa(senha)); // carrega senha do banco
// atualiza base de dados
LimpaSQLTabela(aux);
AdicionaSQLTabela(Aux, 'grant connect, to DBA identified by ''' + senha + '''');
Aux.ExecSQL;
if DataBase.InTransaction then
DataBase.commit;
ini.free;
except
if DataBase.InTransaction then
DataBase.Rollback;
Ini.WriteString('SENHAS','BANCODADOS', senhaInicial);
ini.free;
end;
end;
{*********************** atualiza o banco de dados ****************************}
procedure TAtualiza.AtualizaBanco;
begin
AdicionaSQLAbreTabela(Aux,'Select I_Ult_Alt from Cfg_Geral ');
if Aux.FieldByName('I_Ult_Alt').AsInteger < CT_VersaoBanco Then
AtualizaTabela(Aux.FieldByName('I_Ult_Alt').AsInteger);
end;
{********************* altera as versoes do sistema ***************************}
procedure TAtualiza.AlteraVersoesSistemas;
begin
ExecutaComandoSql(Aux,'Update Cfg_Geral ' +
'set C_Mod_Fat = '''+ VersaoFaturamento + ''',' +
' C_Mod_Pon = '''+ VersaoPontoLoja + ''','+
' C_Mod_Est = ''' + VersaoEstoque + ''',' +
' C_Mod_Fin = ''' + VersaoFinanceiro+''','+
' C_CON_SIS = ''' + VersaoConfiguracaoSistema+'''');
end;
{**************************** atualiza a tabela *******************************}
procedure TAtualiza.AtualizaTabela(VpaNumAtualizacao : Integer);
var
VpfSemErros : Boolean;
VpfErro : String;
begin
VpfSemErros := true;
// FAbertura.painelTempo1.Execute('Atualizando o Banco de Dados. Aguarde...');
repeat
Try
if VpaNumAtualizacao < 1 Then
begin
VpfErro := '1';
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 3');
end;
if VpaNumAtualizacao < 2 Then
begin
VpfErro := '2';
ExecutaComandoSql(Aux,'Alter table CFG_GERAL'
+' ADD C_MOD_TRX CHAR(10) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 2');
ExecutaComandoSql(Aux,'comment on column CFG_GERAL.C_MOD_TRX is ''MODULO DE TRANSFERENCIA DE DADOS''');
end;
if VpaNumAtualizacao < 3 Then
begin
VpfErro := '3';
ExecutaComandoSql(Aux,'Alter table CADUSUARIOS'
+' ADD C_MOD_TRX CHAR(1) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 3');
ExecutaComandoSql(Aux,'comment on column CADUSUARIOS.C_MOD_TRX is ''MODULO DE TRANSFERENCIA DE DADOS''');
end;
if VpaNumAtualizacao < 4 Then
begin
VpfErro := '4';
ExecutaComandoSql(Aux,'alter table movchequeterceiro'
+' add C_TIP_MOV char(1); '
+' '
+' update movchequeterceiro '
+' set C_TIP_MOV = ''T''; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 4');
ExecutaComandoSql(Aux,'comment on column movchequeterceiro.c_tip_mov is ''TIPO DE MOVIMENTACAO, T TERCEIRO, V VARIAS FORMAS''');
end;
if VpaNumAtualizacao < 5 Then
begin
VpfErro := '5';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_MODULO '
+' ADD FLA_SERVICO CHAR(1), '
+' ADD FLA_TEF CHAR(1), '
+' ADD FLA_CODIGOBARRA CHAR(1), '
+' ADD FLA_GAVETA CHAR(1), '
+' ADD FLA_IMPDOCUMENTOS CHAR(1), '
+' ADD FLA_ORCAMENTOVENDA CHAR(1), '
+' ADD FLA_IMP_EXP CHAR(1), '
+' ADD FLA_SENHAGRUPO CHAR(1); ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 5');
end;
if VpaNumAtualizacao < 6 Then
begin
VpfErro := '6';
ExecutaComandoSql(Aux,'alter table cfg_fiscal'
+' ADD I_CLI_DEV INTEGER ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 6');
ExecutaComandoSql(Aux,'comment on column CFG_FISCAL.I_CLI_DEV is ''CLIENTE DE DEVOLUCAO DA NOTA FISCAL''');
end;
if VpaNumAtualizacao < 7 Then
begin
VpfErro := '7';
ExecutaComandoSql(Aux,'alter table cadClientes'
+' add C_ELE_REP char(100) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 7');
ExecutaComandoSql(Aux,'comment on column cadClientes.C_ELE_REP is ''ENDERECO ELETRONICO DO REPRESENTANTE (WWW)''');
end;
if VpaNumAtualizacao < 8 Then
begin
VpfErro := '8';
ExecutaComandoSql(Aux,'alter table cfg_fiscal'
+' add I_NAT_NOT integer, '
+' add I_NOT_CUP integer ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 8');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.I_NAT_NOT is ''NATUREZA PARA DEVOLUCAO DE NOTA FISCAL''');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.I_NOT_CUP is ''NATUREZA DE NOTA FISCAL DE CUPOM''');
end;
if VpaNumAtualizacao < 9 Then
begin
VpfErro := '9';
ExecutaComandoSql(Aux,'alter table MovTef'
+' drop n_aut_tra, '
+' drop t_tim_loc, '
+' drop n_tip_par, '
+' drop n_qtd_par, '
+' drop d_ven_par, '
+' drop n_vlr_par, '
+' drop n_nsu_par, '
+' drop d_pre_dat, '
+' drop c_ima_lin, '
+' drop c_aut_tef, '
+' drop c_nom_adm ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 9');
end;
if VpaNumAtualizacao < 10 Then
begin
VpfErro := '10';
ExecutaComandoSql(Aux,'alter table cfg_fiscal'
+' add C_CLI_CUP char(1) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 10');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.c_cli_cup is ''BOOLEAN - MOSTRAR OU NAO TELA DADOS DO CLIENTE NO CUPOM FISCAL''');
end;
if VpaNumAtualizacao < 11 Then
begin
VpfErro := '11';
ExecutaComandoSql(Aux,'drop table Tabela_Exportacao');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 11');
end;
if VpaNumAtualizacao < 12 Then
begin
VpfErro := '12';
ExecutaComandoSql(Aux,'create table TABELA_EXPORTACAO'
+' ( SEQ_TABELA INTEGER NOT NULL, '
+' NOM_TABELA CHAR(50), '
+' NOM_CHAVE1 CHAR(50), '
+' NOM_CHAVE2 CHAR(50), '
+' NOM_CHAVE3 CHAR(50), '
+' NOM_CHAVE4 CHAR(50), '
+' NOM_CHAVE5 CHAR(50), '
+' NOM_CAMPO_DATA CHAR(50), '
+' PRIMARY KEY(SEQ_TABELA)) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 12');
ExecutaComandoSql(Aux,'comment on table TABELA_EXPORTACAO is ''TABELA DE EXPORTACAO''');
ExecutaComandoSql(Aux,'comment on column TABELA_EXPORTACAO.SEQ_TABELA is ''SEQUENCIAL DE EXPORTACAO DA TABELA''');
ExecutaComandoSql(Aux,'comment on column TABELA_EXPORTACAO.NOM_CHAVE1 is ''NOME DO CAMPO CHAVE 1''');
ExecutaComandoSql(Aux,'comment on column TABELA_EXPORTACAO.NOM_CHAVE2 is ''NOME DO CAMPO CHAVE 2''');
ExecutaComandoSql(Aux,'comment on column TABELA_EXPORTACAO.NOM_CHAVE3 is ''NOME DO CAMPO CHAVE 3''');
ExecutaComandoSql(Aux,'comment on column TABELA_EXPORTACAO.NOM_CHAVE4 is ''NOME DO CAMPO CHAVE 4''');
ExecutaComandoSql(Aux,'comment on column TABELA_EXPORTACAO.NOM_CHAVE5 is ''NOME DO CAMPO CHAVE 5''');
ExecutaComandoSql(Aux,'comment on column TABELA_EXPORTACAO.NOM_CAMPO_DATA is ''NOME DO CAMPO DATA''');
end;
if VpaNumAtualizacao < 13 Then
begin
VpfErro := '13';
ExecutaComandoSql(Aux,'create table GRUPO_TABELA_EXPORTACAO'
+' ( SEQ_TABELA INTEGER NOT NULL, '
+' COD_GRUPO INTEGER NOT NULL, '
+' PRIMARY KEY(SEQ_TABELA,COD_GRUPO)) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 13');
ExecutaComandoSql(Aux,'comment on table GRUPO_TABELA_EXPORTACAO is ''GRUPOS DAS TABELAS DE EXPORTACAO''');
ExecutaComandoSql(Aux,'comment on column GRUPO_TABELA_EXPORTACAO.SEQ_TABELA is ''SEQUENCIAL DA TABELA''');
ExecutaComandoSql(Aux,'comment on column GRUPO_TABELA_EXPORTACAO.COD_GRUPO is ''CODIGO DO GRUPO''');
end;
if VpaNumAtualizacao < 14 Then
begin
VpfErro := '14';
ExecutaComandoSql(Aux,'create unique index GRUPO_TABELA_EXPORTACAO_pk on'
+' GRUPO_TABELA_EXPORTACAO(SEQ_TABELA ASC,COD_GRUPO ASC) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 14');
end;
if VpaNumAtualizacao < 15 Then
begin
VpfErro := '15';
ExecutaComandoSql(Aux,'drop index GRUPO_EXPORTACAO_PK');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 15');
end;
if VpaNumAtualizacao < 16 Then
begin
VpfErro := '16';
ExecutaComandoSql(Aux,'alter table grupo_exportacao'
+' drop primary key ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 16');
end;
if VpaNumAtualizacao < 17 Then
begin
VpfErro := '17';
ExecutaComandoSql(Aux,'alter table grupo_exportacao'
+' drop cod_empresa ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 17');
end;
if VpaNumAtualizacao < 18 Then
begin
VpfErro := '18';
ExecutaComandoSql(Aux,'alter table grupo_exportacao'
+' add primary key(cod_grupo) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 18');
end;
if VpaNumAtualizacao < 19 Then
begin
VpfErro := '19';
ExecutaComandoSql(Aux,'alter table GRUPO_TABELA_EXPORTACAO'
+' add foreign key GRUPO_TABELA_EXPORTACAO_FK101(COD_GRUPO) '
+' references GRUPO_EXPORTACAO(COD_GRUPO) '
+' on update restrict on delete restrict ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 19');
end;
if VpaNumAtualizacao < 20 Then
begin
VpfErro := '20';
ExecutaComandoSql(Aux,'alter table GRUPO_EXPORTACAO'
+' add IDE_TIPO_GRUPO CHAR(1) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 20');
ExecutaComandoSql(Aux,'comment on column GRUPO_EXPORTACAO.IDE_TIPO_GRUPO is ''DEFINE O TIPO DO GRUPO''');
end;
if VpaNumAtualizacao < 21 Then
begin
VpfErro := '21';
ExecutaComandoSql(Aux,'create table CADCARTAO( I_COD_CAR integer,'
+' C_NOM_CAR char(40), '
+' N_PER_COM numeric(17,2), '
+' primary key (I_COD_CAR) ) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 21');
ExecutaComandoSql(Aux,'comment on column CADCARTAO.I_COD_CAR is ''CODIGO DO CARTAO''');
ExecutaComandoSql(Aux,'comment on column CADCARTAO.C_NOM_CAR is ''NOME DA REDE DO CARTAO''');
ExecutaComandoSql(Aux,'comment on column CADCARTAO.N_PER_COM is ''PERCENTUAL DO CARTAO''');
end;
if VpaNumAtualizacao < 22 Then
begin
VpfErro := '22';
ExecutaComandoSql(Aux,'create table CADTIPOTRANSACAO( I_COD_TRA integer,'
+' C_NOM_TRA char(40), '
+' primary key (I_COD_TRA) ) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 22');
ExecutaComandoSql(Aux,'comment on column CADTIPOTRANSACAO.I_COD_TRA is ''CODIGO DO TRANSACAO''');
ExecutaComandoSql(Aux,'comment on column CADTIPOTRANSACAO.C_NOM_TRA is ''NOME DO TIPO DE TRANSACAO DO CARTAO''');
end;
if VpaNumAtualizacao < 23 Then
begin
VpfErro := '23';
ExecutaComandoSql(Aux,'alter table MovContasAReceber'
+' add I_SEQ_TEF integer; '
+' '
+' alter table MovContasAReceber '
+' add foreign key FK_MOVTEF_2020(I_EMP_FIL,I_SEQ_TEF) '
+' references movtef(I_EMP_FIL,I_SEQ_TEF) '
+' on update restrict on delete restrict ; '
+' '
+' create index FK_MOVTEF_56231 on '
+' MovContasAReceber(I_SEQ_TEF ASC, I_EMP_FIL ASC) ; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 23');
ExecutaComandoSql(Aux,'comment on column MovContasAReceber.I_SEQ_TEF is ''SEQUENCIAL DO TEF DISCADO''');
end;
if VpaNumAtualizacao < 24 Then
begin
VpfErro := '24';
ExecutaComandoSql(Aux, ' drop index Ref_125589_FK; '
+'alter table movtef'
+' drop foreign key FK_MOVTEF_REF_12558_MOVCONTA; '
+' '
+' alter table movtef '
+' drop i_lan_rec, '
+' drop i_nro_par; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 24');
end;
if VpaNumAtualizacao < 25 Then
begin
VpfErro := '25';
ExecutaComandoSql(Aux,'create unique index CADTIPOTRANSACAO_pk on'
+' CADTIPOTRANSACAO(I_COD_TRA ASC); '
+' create unique index CADCARTAO_pk on '
+' CADCARTAO(I_COD_CAR ASC); ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 25');
end;
if VpaNumAtualizacao < 26 Then
begin
VpfErro := '26';
ExecutaComandoSql(Aux,' create table CADREGIAOVENDA( I_COD_REG integer,'
+' C_NOM_REG char(40), '
+' primary key (I_COD_REG) ); '
+' create unique index CADREGIAOVENDA_pk on'
+' CADREGIAOVENDA(I_COD_REG ASC); ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 26');
ExecutaComandoSql(Aux,'comment on column CADREGIAOVENDA.I_COD_REG is ''CODIGO DA REGIAO DE VENDA''');
ExecutaComandoSql(Aux,'comment on column CADREGIAOVENDA.C_NOM_REG is ''NOME DA REGIAO DE VENDA''');
end;
if VpaNumAtualizacao < 27 Then
begin
VpfErro := '27';
ExecutaComandoSql(Aux,'alter table CADClientes'
+' add I_COD_REG integer; '
+' '
+' alter table CADClientes '
+' add foreign key FK_CADREGIAOVENDA_7561(I_COD_REG) '
+' references CADREGIAOVENDA(I_COD_REG) '
+' on update restrict on delete restrict ; '
+' '
+' create index FK_CADREGIAOVENDA_14549 on '
+' CADClientes(I_COD_REG ASC); ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 27');
ExecutaComandoSql(Aux,'comment on column CADClientes.I_COD_REG is ''CODIGO DA REGIAO DE VENDA''');
end;
if VpaNumAtualizacao < 28 Then
begin
VpfErro := '28';
ExecutaComandoSql(Aux,' INSERT INTO CADREGIAOVENDA(I_COD_REG, C_NOM_REG) '
+' VALUES(1101,''GERAL''); '
+' update cadClientes '
+' set i_cod_reg = 1101' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 28');
end;
if VpaNumAtualizacao < 29 Then
begin
VpfErro := '29';
ExecutaComandoSql(Aux,'alter table cfg_fiscal'
+' add I_LAY_ECF integer; '
+' '
+' update cfg_fiscal '
+' set I_LAY_ECF = 0; ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 29');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.i_lay_ecf is ''TIPO DE LAYOUT DO ECF''');
end;
if VpaNumAtualizacao < 30 Then
begin
VpfErro := '30';
ExecutaComandoSql(Aux,'alter table cfg_fiscal'
+' add I_FON_ECF integer, '
+' add I_CLI_ECF integer; ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 30');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.I_FON_ECF is ''TAMANHO DA FONTE DO ECF''');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.I_CLI_ECF is ''CLIENTE PADRAO DO ECF''');
end;
if VpaNumAtualizacao < 31 Then
begin
VpfErro := '31';
ExecutaComandoSql(Aux,'alter table cfg_financeiro'
+' add C_PAR_DAT char(1) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 31');
ExecutaComandoSql(Aux,'comment on column cfg_financeiro.c_par_dat is ''BOOLEAN - SE O CAIXA ESTIVER COM DATA RETROATIVA NAUM PERMITE ABRIR PARCIAL''');
end;
if VpaNumAtualizacao < 32 Then
begin
VpfErro := '32';
ExecutaComandoSql(Aux,'alter table cfg_financeiro'
+' add C_ITE_DAT char(1) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 32');
ExecutaComandoSql(Aux,'comment on column cfg_financeiro.c_ite_dat is ''BOOLEAN - PERMITE LANCAR ITENS EM CAIXA COM DATA RETROATIVA''');
end;
if VpaNumAtualizacao < 33 Then
begin
VpfErro := '33';
ExecutaComandoSql(Aux,'alter table movsumarizaestoque'
+' drop c_tip_ope; '
+' alter table movsumarizaestoque '
+' add D_DAT_MES date; ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 33');
ExecutaComandoSql(Aux,'comment on column movsumarizaestoque.d_dat_mes is ''DATA DO FECHAMENTO DO PRODUTO POR MES''');
end;
if VpaNumAtualizacao < 34 Then
begin
VpfErro := '34';
ExecutaComandoSql(Aux,'alter table movnotasfiscais'
+' add N_VLR_IPI numeric(17,3) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 34');
ExecutaComandoSql(Aux,'comment on column movnotasfiscais.N_VLR_IPI is ''VALOR DO IPI''');
end;
if VpaNumAtualizacao < 35 Then
begin
VpfErro := '35';
ExecutaComandoSql(Aux,'alter table cfg_fiscal'
+' drop i_cod_nat, '
+' drop i_nat_not, '
+' drop i_not_cup, '
+' drop i_nat_dev; ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 35');
end;
if VpaNumAtualizacao < 36 Then
begin
VpfErro := '36';
ExecutaComandoSql(Aux,'alter table cfg_fiscal'
+' add C_COD_NAT char(10), '
+' add C_NAT_NOT char(10), '
+' add C_NOT_CUP char(10), '
+' add C_NAT_DEV char(10); ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 36');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.C_COD_NAT is ''CODIGO DA NATUREZA PADRAO''');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.C_NAT_NOT is ''NATUREZA DE DEVOLUCAO DE NOTA FISCAL''');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.C_NOT_CUP is ''NATUREZA DE CUPOM FISCAL''');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.C_NAT_DEV is ''NATUREZA DE DEVOLUCAO DE CUPOM''');
end;
if VpaNumAtualizacao < 37 Then
begin
VpfErro := '37';
ExecutaComandoSql(Aux,'alter table cadnatureza'
+' add C_ENT_SAI char(1) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 37');
ExecutaComandoSql(Aux,'comment on column cadnatureza.C_ENT_SAI is ''TIPO DA NOTA ENTRADA OU SAIDA''');
end;
if VpaNumAtualizacao < 38 Then
begin
VpfErro := '38';
ExecutaComandoSql(Aux,'alter table tabela_exportacao'
+' ADD NOM_CAMPO_FILIAL CHAR(50) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 38');
ExecutaComandoSql(Aux,'comment on column tabela_exportacao.NOM_CAMPO_FILIAL is ''NOME DO CAMPO FILIAL''');
end;
if VpaNumAtualizacao < 39 Then
begin
VpfErro := '39';
ExecutaComandoSql(Aux,'alter table movnatureza'
+' add C_MOS_NOT char(1) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 39');
ExecutaComandoSql(Aux,'comment on column movnatureza.c_mos_not is ''MOSTRAR OPCAO NA NOTA FISCAL''');
end;
if VpaNumAtualizacao < 40 Then
begin
VpfErro := '40';
ExecutaComandoSql(Aux,'alter table CadNotaFiscais'
+' add I_ITE_NAT integer; '
+' '
+' alter table MovNotasFiscaisFor '
+' add I_ITE_NAT integer; ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 40');
ExecutaComandoSql(Aux,'comment on column CadNotaFiscais.i_ite_nat is ''ITEM DO MOVNATUREZA''');
ExecutaComandoSql(Aux,'comment on column MovNotasFiscaisFor.i_ite_nat is ''ITEM DO MOVNATUREZA''');
end;
if VpaNumAtualizacao < 41 Then
begin
VpfErro := '41';
ExecutaComandoSql(Aux,'alter table cfg_fiscal'
+' add I_FRE_NOT integer ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 41');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.i_fre_not is ''TIPO PADRAO DO FRETE DA NOTA 1 - 2 ''');
end;
if VpaNumAtualizacao < 42 Then
begin
VpfErro := '42';
ExecutaComandoSql(Aux,'alter table cfg_fiscal'
+' add C_NRO_NOT CHAR(1) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 42');
ExecutaComandoSql(Aux,'comment on column cfg_fiscal.c_nro_not is ''TRANCA A ALTERAÇÃO DO NRO DA NOTA FISCAL''');
end;
if VpaNumAtualizacao < 43 Then
begin
VpfErro := '43';
ExecutaComandoSql(Aux,'alter table CAD_PAISES'
+' add DAT_ULTIMA_ALTERACAO DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 43');
ExecutaComandoSql(Aux,'comment on column CAD_PAISES.DAT_ULTIMA_ALTERACAO is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 44 Then
begin
VpfErro := '44';
ExecutaComandoSql(Aux,'alter table CAD_ESTADOS'
+' add DAT_ULTIMA_ALTERACAO DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 44');
ExecutaComandoSql(Aux,'comment on column CAD_ESTADOS.DAT_ULTIMA_ALTERACAO is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 45 Then
begin
VpfErro := '45';
ExecutaComandoSql(Aux,'alter table CADREGIAOVENDA'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 45');
ExecutaComandoSql(Aux,'comment on column CADREGIAOVENDA.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 46 Then
begin
VpfErro := '46';
ExecutaComandoSql(Aux,'alter table CADEMPRESAS'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 46');
ExecutaComandoSql(Aux,'comment on column CADEMPRESAS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 47 Then
begin
VpfErro := '47';
ExecutaComandoSql(Aux,'alter table CADFILIAIS'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 47');
ExecutaComandoSql(Aux,'comment on column CADFILIAIS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 48 Then
begin
VpfErro := '48';
ExecutaComandoSql(Aux,'alter table CADCLASSIFICACAO'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 48');
ExecutaComandoSql(Aux,'comment on column CADCLASSIFICACAO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 49 Then
begin
VpfErro := '49';
ExecutaComandoSql(Aux,'alter table CADUNIDADE'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 49');
ExecutaComandoSql(Aux,'comment on column CADUNIDADE.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 50 Then
begin
VpfErro := '50';
ExecutaComandoSql(Aux,'alter table MOVINDICECONVERSAO'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 50');
ExecutaComandoSql(Aux,'comment on column MOVINDICECONVERSAO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 51 Then
begin
VpfErro := '51';
ExecutaComandoSql(Aux,'alter table CADOPERACAOBANCARIA'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 51');
ExecutaComandoSql(Aux,'comment on column CADOPERACAOBANCARIA.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 52 Then
begin
VpfErro := '52';
ExecutaComandoSql(Aux,'alter table MOVCONDICAOPAGTO'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 52');
ExecutaComandoSql(Aux,'comment on column MOVCONDICAOPAGTO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 53 Then
begin
VpfErro := '53';
ExecutaComandoSql(Aux,'alter table CADBANCOS'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 53');
ExecutaComandoSql(Aux,'comment on column CADBANCOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 54 Then
begin
VpfErro := '54';
ExecutaComandoSql(Aux,'alter table MOVMOEDAS'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 54');
ExecutaComandoSql(Aux,'comment on column MOVMOEDAS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 55 Then
begin
VpfErro := '55';
ExecutaComandoSql(Aux,'alter table CADGRUPOS'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 55');
ExecutaComandoSql(Aux,'comment on column CADGRUPOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 56 Then
begin
VpfErro := '56';
ExecutaComandoSql(Aux,'alter table CADUSUARIOS'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 56');
ExecutaComandoSql(Aux,'comment on column CADUSUARIOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 57 Then
begin
VpfErro := '57';
ExecutaComandoSql(Aux,'alter table CAD_CODIGO_BARRA'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 57');
ExecutaComandoSql(Aux,'comment on column CAD_CODIGO_BARRA.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 58 Then
begin
VpfErro := '58';
ExecutaComandoSql(Aux,'ALTER TABLE CAD_BORDERO'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 58');
ExecutaComandoSql(Aux,'comment on column CAD_BORDERO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 59 Then
begin
VpfErro := '59';
ExecutaComandoSql(Aux,'ALTER TABLE MOVKIT'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 59');
ExecutaComandoSql(Aux,'comment on column MOVKIT.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 60 Then
begin
VpfErro := '60';
ExecutaComandoSql(Aux,'ALTER TABLE MOVQDADEPRODUTO'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 60');
ExecutaComandoSql(Aux,'comment on column MOVQDADEPRODUTO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 61 Then
begin
VpfErro := '61';
ExecutaComandoSql(Aux,'alter table MOVTABELAPRECO'
+' add D_ULT_ALT DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 61');
ExecutaComandoSql(Aux,'comment on column MOVTABELAPRECO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 62 Then
begin
VpfErro := '62';
ExecutaComandoSql(Aux,'Alter table cadnatureza'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 62');
ExecutaComandoSql(Aux,'comment on column cadnatureza.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 63 Then
begin
VpfErro := '63';
ExecutaComandoSql(Aux,'create table TEMPORARIAESTOQUE'
+' ( I_EMP_FIL INTEGER NULL, '
+' C_GRU_001 CHAR(20) NULL, '
+' C_GRU_002 CHAR(20) NULL, '
+' C_GRU_003 CHAR(20) NULL, '
+' C_GRU_004 CHAR(20) NULL, '
+' C_GRU_005 CHAR(20) NULL, '
+' C_COD_CLA CHAR(15) NULL, '
+' C_NOM_CLA CHAR(40) NULL, '
+' N_EST_ANT NUMERIC(17,3) NULL, '
+' N_VLR_ANT NUMERIC(17,3) NULL, '
+' N_EST_ATU NUMERIC(17,3) NULL, '
+' N_VLR_ATU NUMERIC(17,3) NULL, '
+' N_QTD_VEN NUMERIC(17,3) NULL, '
+' N_VLR_VEN NUMERIC(17,3) NULL, '
+' N_GIR_EST NUMERIC(17,3) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 63');
end;
if VpaNumAtualizacao < 64 Then
begin
VpfErro := '64';
ExecutaComandoSql(Aux,'Alter table MOVnatureza'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 64');
ExecutaComandoSql(Aux,'comment on column MOVNATUREZA.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 65 Then
begin
VpfErro := '65';
ExecutaComandoSql(Aux,'alter table CADORCAMENTOS'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 65');
ExecutaComandoSql(Aux,'comment on column CADORCAMENTOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 66 Then
begin
VpfErro := '66';
ExecutaComandoSql(Aux,'alter table MOVORCAMENTOS'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 66');
ExecutaComandoSql(Aux,'comment on column CADORCAMENTOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 67 Then
begin
VpfErro := '67';
ExecutaComandoSql(Aux,'alter table MOVSERVICOORCAMENTO'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 67');
ExecutaComandoSql(Aux,'comment on column MOVSERVICOORCAMENTO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 68 Then
begin
VpfErro := '68';
ExecutaComandoSql(Aux,'ALTER TABLE CADICMSESTADOS'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 68');
ExecutaComandoSql(Aux,'comment on column CADICMSESTADOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 69 Then
begin
VpfErro := '69';
ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECOSERVICO'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 69');
ExecutaComandoSql(Aux,'comment on column MOVTABELAPRECOSERVICO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 70 Then
begin
VpfErro := '70';
ExecutaComandoSql(Aux,'DROP TABLE PROXIMO_CODIGO');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 70');
end;
if VpaNumAtualizacao < 71 Then
begin
VpfErro := '71';
ExecutaComandoSql(Aux,'ALTER TABLE CADSERIENOTAS'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 71');
ExecutaComandoSql(Aux,'comment on column CADSERIENOTAS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 72 Then
begin
VpfErro := '72';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 72');
ExecutaComandoSql(Aux,'comment on column CADNOTAFISCAISFOR.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 73 Then
begin
VpfErro := '73';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAISFOR'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 73');
ExecutaComandoSql(Aux,'comment on column MOVNOTASFISCAISFOR.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 74 Then
begin
VpfErro := '74';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 74');
ExecutaComandoSql(Aux,'comment on column CADNOTAFISCAIS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 75 Then
begin
VpfErro := '75';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 75');
ExecutaComandoSql(Aux,'comment on column MOVNOTASFISCAIS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 76 Then
begin
VpfErro := '76';
ExecutaComandoSql(Aux,'ALTER TABLE MOVSERVICONOTA'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 76');
ExecutaComandoSql(Aux,'comment on column MOVSERVICONOTA.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 77 Then
begin
VpfErro := '77';
ExecutaComandoSql(Aux,' alter table CadCartao '
+' add I_DIA_VEN integer nulL, '
+' add I_TIP_VEN integer null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 77');
ExecutaComandoSql(Aux,'comment on column CadCartao.I_DIA_VEN is ''DIA FIXO OU QUANTIDADE DE DIAS PARA O VENCIMENTO''');
ExecutaComandoSql(Aux,'comment on column CadCartao.I_TIP_VEN is ''TIPO DE VENCIMENTO FIXO OU SOMATORIO''');
end;
if VpaNumAtualizacao < 78 Then
begin
VpfErro := '78';
ExecutaComandoSql(Aux,'alter table CADDESPESAS'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 78');
ExecutaComandoSql(Aux,'comment on column CADDESPESAS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 79 Then
begin
VpfErro := '79';
ExecutaComandoSql(Aux,'alter table CADCONTAS'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 79');
ExecutaComandoSql(Aux,'comment on column CADCONTAS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 80 Then
begin
VpfErro := '80';
ExecutaComandoSql(Aux,'alter table cadcartao'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 80');
ExecutaComandoSql(Aux,'comment on column CADCARTAO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO DO REGISTRO''');
end;
if VpaNumAtualizacao < 81 Then
begin
VpfErro := '81';
ExecutaComandoSql(Aux,'alter table CAD_TIPO_OPERA'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 81');
ExecutaComandoSql(Aux,'comment on column CAD_TIPO_OPERA.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO DO REGISTRO''');
end;
if VpaNumAtualizacao < 82 Then
begin
VpfErro := '82';
ExecutaComandoSql(Aux,'alter table CADTIPOTRANSACAO'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 82');
ExecutaComandoSql(Aux,'comment on column CADTIPOTRANSACAO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO DO REGISTRO''');
end;
if VpaNumAtualizacao < 83 Then
begin
VpfErro := '83';
ExecutaComandoSql(Aux,'alter table CADCONTASARECEBER'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 83');
ExecutaComandoSql(Aux,'comment on column CADCONTASARECEBER.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO DO REGISTRO''');
end;
if VpaNumAtualizacao < 84 Then
begin
VpfErro := '84';
ExecutaComandoSql(Aux,'alter table MOVCONTASARECEBER'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 84');
ExecutaComandoSql(Aux,'comment on column MOVCONTASARECEBER.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO DO REGISTRO''');
end;
if VpaNumAtualizacao < 85 Then
begin
VpfErro := '85';
ExecutaComandoSql(Aux,'alter table MOVCONTASAPAGAR'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 85');
ExecutaComandoSql(Aux,'comment on column MOVCONTASAPAGAR.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO DO REGISTRO''');
end;
if VpaNumAtualizacao < 86 Then
begin
VpfErro := '86';
ExecutaComandoSql(Aux,'alter table CADCONTASAPAGAR'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 86');
ExecutaComandoSql(Aux,'comment on column CADCONTASAPAGAR.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO DO REGISTRO''');
end;
if VpaNumAtualizacao < 87 Then
begin
VpfErro := '87';
ExecutaComandoSql(Aux,'alter table MOVFORNECPRODUTOS'
+' ADD D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 87');
ExecutaComandoSql(Aux,'comment on column MOVFORNECPRODUTOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 88 Then
begin
VpfErro := '88';
ExecutaComandoSql(Aux,'alter table MOVBANCOS'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 88');
ExecutaComandoSql(Aux,'comment on column MOVBANCOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 89 Then
begin
VpfErro := '89';
ExecutaComandoSql(Aux,'alter table MOVCOMISSOES'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 89');
ExecutaComandoSql(Aux,'comment on column MOVCOMISSOES.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 90 Then
begin
VpfErro := '90';
ExecutaComandoSql(Aux,'alter table CAD_ALTERACAO'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 90');
ExecutaComandoSql(Aux,'comment on column CAD_ALTERACAO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 91 Then
begin
VpfErro := '91';
ExecutaComandoSql(Aux,'alter table CAD_CAIXA'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 91');
ExecutaComandoSql(Aux,'comment on column CAD_CAIXA.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 92 Then
begin
VpfErro := '92';
ExecutaComandoSql(Aux,'alter table CAD_BOLETO'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 92');
ExecutaComandoSql(Aux,'comment on column CAD_BOLETO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 93 Then
begin
VpfErro := '93';
ExecutaComandoSql(Aux,'alter table MOV_DOC'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 93');
ExecutaComandoSql(Aux,'comment on column MOV_DOC.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 95 Then
begin
VpfErro := '95';
ExecutaComandoSql(Aux,'alter table MOVCHEQUETERCEIRO'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 95');
ExecutaComandoSql(Aux,'comment on column MOVCHEQUETERCEIRO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 96 Then
begin
VpfErro := '96';
ExecutaComandoSql(Aux,'alter table MOV_DIARIO'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 96');
ExecutaComandoSql(Aux,'comment on column MOV_DIARIO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 97 Then
begin
VpfErro := '97';
ExecutaComandoSql(Aux,'alter table ITE_CAIXA'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 97');
ExecutaComandoSql(Aux,'comment on column ITE_CAIXA.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 98 Then
begin
VpfErro := '98';
ExecutaComandoSql(Aux,'alter table CRP_PARCIAL'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 98');
ExecutaComandoSql(Aux,'comment on column CRP_PARCIAL.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 99 Then
begin
VpfErro := '99';
ExecutaComandoSql(Aux,'alter table MOV_ALTERACAO'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 99');
ExecutaComandoSql(Aux,'comment on column MOV_ALTERACAO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 100 Then
begin
VpfErro := '100';
ExecutaComandoSql(Aux,'alter table MOVTEF'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 100');
ExecutaComandoSql(Aux,'comment on column MOVTEF.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 101 Then
begin
VpfErro := '101';
ExecutaComandoSql(Aux,'alter table ITE_FECHAMENTO'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 101');
ExecutaComandoSql(Aux,'comment on column ITE_FECHAMENTO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 102 Then
begin
VpfErro := '102';
ExecutaComandoSql(Aux,'alter table MovTef'
+' add C_CAN_TEF char(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 102');
ExecutaComandoSql(Aux,'comment on column MovTef.C_CAN_TEF is ''CASO O TEF TENHA SIDO CANCELADO''');
end;
if VpaNumAtualizacao < 103 Then
begin
VpfErro := '103';
ExecutaComandoSql(Aux,'alter table CAD_PLANO_CONTA'
+' add D_ULT_ALT DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 103');
ExecutaComandoSql(Aux,'comment on column CAD_PLANO_CONTA.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 104 Then
begin
VpfErro := '104';
AtualizaSenha(CT_SenhaAtual);
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 104');
end;
if VpaNumAtualizacao < 105 Then
begin
VpfErro := '105';
ExecutaComandoSql(Aux,'alter table cadformularios'
+' add C_MOD_TRX CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 105');
ExecutaComandoSql(Aux,'comment on column cadformularios.C_MOD_TRX is ''MODULO DE TRANSFERECIA''');
end;
if VpaNumAtualizacao < 106 Then
begin
VpfErro := '106';
ExecutaComandoSql(Aux,'alter table cadusuarios'
+' add C_MOD_REL char(1) null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 106');
ExecutaComandoSql(Aux,'comment on column cadusuarios.c_mod_rel is ''PERMITE CONSULTAR O MODULO DE RELATORIOS''');
end;
if VpaNumAtualizacao < 107 Then
begin
VpfErro := '107';
ExecutaComandoSql(Aux,'alter table cadformularios'
+' add C_MOD_REL char(1) null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 107');
ExecutaComandoSql(Aux,'comment on column cadformularios.c_mod_rel is ''cadastros de relatorios''');
end;
if VpaNumAtualizacao < 108 Then
begin
VpfErro := '108';
ExecutaComandoSql(Aux,'alter table cfg_geral'
+' add C_MOD_REL char(10) null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 108');
ExecutaComandoSql(Aux,'comment on column CFG_GERAL.C_MOD_REL is ''VERSAO DO MODULO DE RALATORIO''');
end;
if VpaNumAtualizacao < 109 Then
begin
VpfErro := '109';
ExecutaComandoSql(Aux,'alter table cfg_geral'
+' ADD I_DIA_VAL integer NULL, '
+' ADD I_TIP_BAS integer NULL; '
+' update cfg_geral set i_tip_bas = 1');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 109');
ExecutaComandoSql(Aux,'comment on column cfg_geral.I_DIA_VAL is ''DIAS DE VALIDADE DA BASE DEMO''');
ExecutaComandoSql(Aux,'comment on column cfg_geral.I_TIP_BAS is ''TIPO DA BASE DEMO OU OFICIAL 0 OFICIAL 1 DEMO''');
end;
if VpaNumAtualizacao < 110 Then
begin
VpfErro := '110';
ExecutaComandoSql(Aux,'alter table cfg_financeiro'
+' add I_FRM_CAR INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 110');
ExecutaComandoSql(Aux,'comment on column cfg_financeiro.I_FRM_CAR is ''FORMA DE PAGAMENTO EM CARTEIRA''');
end;
if VpaNumAtualizacao < 111 Then
begin
VpfErro := '111';
ExecutaComandoSql(Aux,' create table MOVFORMAS'
+' ( I_EMP_FIL INTEGER NOT NULL, '
+' I_SEQ_MOV INTEGER NOT NULL, '
+' I_NRO_LOT INTEGER NULL, '
+' I_LAN_REC INTEGER NULL, '
+' I_LAN_APG INTEGER NULL, '
+' I_COD_FRM INTEGER NULL, '
+' C_NRO_CHE CHAR(20) NULL, '
+' N_VLR_MOV NUMERIC(17,3) NULL, '
+' C_NRO_CON CHAR(13) NULL, '
+' C_NRO_BOL CHAR(20) NULL, '
+' C_NOM_CHE CHAR(50) NULL, '
+' PRIMARY KEY(I_EMP_FIL, I_SEQ_MOV)) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 111');
ExecutaComandoSql(Aux,'comment on column movformas.I_EMP_FIL is ''CODIGO DA FILIAL''');
ExecutaComandoSql(Aux,'comment on column movformas.I_SEQ_MOV is ''SEQUENCIAL DO MOVIMENTO''');
ExecutaComandoSql(Aux,'comment on column movformas.I_NRO_LOT is ''NUMERO DO LOTE''');
ExecutaComandoSql(Aux,'comment on column movformas.I_LAN_REC is ''LANCAMENTO DO CONTAS A RECEBER''');
ExecutaComandoSql(Aux,'comment on column movformas.I_LAN_APG is ''LANCAMENTO DO CONTAS A PAGAR''');
ExecutaComandoSql(Aux,'comment on column movformas.I_COD_FRM is ''CODIGO DA FORMA DE PAGAMENTO''');
ExecutaComandoSql(Aux,'comment on column movformas.C_NRO_CHE is ''NUMERO DO CHEQUE''');
ExecutaComandoSql(Aux,'comment on column movformas.N_VLR_MOV is ''VALOR DO MOVIMENTO''');
ExecutaComandoSql(Aux,'comment on column movformas.C_NRO_CON is ''NUMERO DA CONTA''');
ExecutaComandoSql(Aux,'comment on column movformas.C_NRO_BOL is ''NUMERO DO BOLETO''');
ExecutaComandoSql(Aux,'comment on column movformas.C_NOM_CHE is ''NOMINAL DO CHEQUE''');
end;
if VpaNumAtualizacao < 112 Then
begin
VpfErro := '112';
ExecutaComandoSql(Aux,'create unique index MOVFORMAS_pk on'
+' MOVFORMAS(I_EMP_FIL, I_SEQ_MOV ASC) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 112');
end;
if VpaNumAtualizacao < 113 Then
begin
VpfErro := '113';
ExecutaComandoSql(Aux,'create table CADHISTORICOCLIENTE'
+' ( I_COD_HIS INTEGER NOT NULL, '
+' C_DES_HIS char(40) NULL, '
+' D_ULT_ALT DATE NULL, '
+' PRIMARY KEY(I_COD_HIS) ) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 113');
ExecutaComandoSql(Aux,'comment on table CADHISTORICOCLIENTE is ''TABELA DO HISTORICO DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column CADHISTORICOCLIENTE.I_COD_HIS is ''CODIGO HISTORICO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column CADHISTORICOCLIENTE.C_DES_HIS is ''DESCRICAO DO HISTORICO DO CLIENTE''');
end;
if VpaNumAtualizacao < 114 Then
begin
VpfErro := '114';
ExecutaComandoSql(Aux,'create table MOVHISTORICOCLIENTE'
+' ( I_SEQ_HIS INTEGER NOT NULL, '
+' I_COD_HIS INTEGER NULL, '
+' I_COD_CLI INTEGER NULL, '
+' I_COD_USU INTEGER NULL, '
+' D_DAT_HIS DATE NULL, '
+' L_HIS_CLI LONG VARCHAR NULL, '
+' D_DAT_AGE DATE NULL, '
+' L_HIS_AGE LONG VARCHAR NULL, '
+' D_ULT_ALT DATE NULL, '
+' PRIMARY KEY(I_SEQ_HIS) ) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 114');
ExecutaComandoSql(Aux,'comment on table MOVHISTORICOCLIENTE is ''TABELA DO HISTORICO DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.I_SEQ_HIS is ''SEQUENCIAL DO MOV HISTORICO''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.I_COD_HIS is ''CODIGO HISTORICO''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.I_COD_CLI is ''CODIGO DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.D_DAT_HIS is ''DATA DO HISTORICO''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.L_HIS_CLI is ''HISTORICO DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.D_DAT_AGE is ''DATA DA AGENDA DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.L_HIS_AGE is ''HISTORICO DA AGENDA''');
end;
if VpaNumAtualizacao < 115 Then
begin
VpfErro := '115';
ExecutaComandoSql(Aux,' alter table MOVHISTORICOCLIENTE '
+' add foreign key CADHISTORICOCLIENTE_FK(I_COD_HIS) '
+' references CADHISTORICOCLIENTE(I_COD_HIS) '
+' on update restrict on delete restrict ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 115');
end;
if VpaNumAtualizacao < 116 Then
begin
VpfErro := '116';
ExecutaComandoSql(Aux,' alter table MOVHISTORICOCLIENTE '
+' add foreign key CADCLIENTE_FK101(I_COD_CLI) '
+' references CADCLIENTES(I_COD_CLI) '
+' on update restrict on delete restrict ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 116');
end;
if VpaNumAtualizacao < 117 Then
begin
VpfErro := '117';
ExecutaComandoSql(Aux,'alter table cfg_geral'
+' add L_ATU_IGN long varchar null; '
+' update cfg_geral '
+' set L_ATU_IGN = null; ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 117');
ExecutaComandoSql(Aux,'comment on column cfg_geral.L_ATU_IGN is ''ATUALIZACOES IGNORADAS''');
end;
if VpaNumAtualizacao < 118 Then
begin
VpfErro := '118';
ExecutaComandoSql(Aux,' alter table movhistoricocliente '
+' add H_HOR_AGE TIME NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 118');
ExecutaComandoSql(Aux,'comment on column movhistoricocliente.H_HOR_AGE is ''HORA AGENDADA''');
end;
if VpaNumAtualizacao < 119 Then
begin
VpfErro := '119';
ExecutaComandoSql(Aux,' alter table movhistoricocliente '
+' add C_SIT_AGE char(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 119');
ExecutaComandoSql(Aux,'comment on column movhistoricocliente.H_HOR_AGE is ''HORA AGENDADA''');
end;
if VpaNumAtualizacao < 120 Then
begin
VpfErro := '120';
ExecutaComandoSql(Aux,' alter table movhistoricocliente '
+' add H_HOR_HIS TIME NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 120');
ExecutaComandoSql(Aux,'comment on column movhistoricocliente.H_HOR_HIS is ''HORA HISTORICO''');
end;
if VpaNumAtualizacao < 121 Then
begin
VpfErro := '121';
ExecutaComandoSql(Aux,' alter table movcontasareceber '
+' add N_VLR_CHE numeric(17,3) NULL, '
+' add C_CON_CHE char(15) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 121');
ExecutaComandoSql(Aux,'comment on column movcontasareceber.N_VLR_CHE is ''VALOR DO CHEQUE''');
ExecutaComandoSql(Aux,'comment on column movcontasareceber.C_CON_CHE is ''CONTA DO CHEQUE''');
end;
if VpaNumAtualizacao < 122 Then
begin
VpfErro := '122';
ExecutaComandoSql(Aux,'create table CADCODIGO'
+' ( I_EMP_FIL INTEGER NULL, '
+' I_LAN_REC INTEGER NULL, '
+' I_LAN_APG INTEGER NULL, '
+' I_LAN_EST INTEGER NULL, '
+' I_LAN_BAC INTEGER NULL, '
+' I_LAN_CON INTEGER NULL ) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 122');
end;
if VpaNumAtualizacao < 123 Then
begin
VpfErro := '123';
ExecutaComandoSql(Aux,'alter table cfg_modulo'
+' add FLA_MALACLIENTE CHAR(1) NULL, '
+' add FLA_AGENDACLIENTE CHAR(1) NULL, '
+' add FLA_PEDIDO CHAR(1) NULL, '
+' add FLA_ORDEMSERVICO CHAR(1) NULL ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 123');
end;
if VpaNumAtualizacao < 124 Then
begin
VpfErro := '124';
ExecutaComandoSql(Aux,'alter table MOVSUMARIZAESTOQUE'
+' ADD C_REL_PRO CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 124');
ExecutaComandoSql(Aux,'comment on column MOVSUMARIZAESTOQUE.C_REL_PRO is ''BOOLEAN - INDICA SE IMPRIME NO RELATORIO DE PRODUTOS OU NAO''');
end;
if VpaNumAtualizacao < 125 Then
begin
VpfErro := '125';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL'
+' ADD N_PER_PIS NUMERIC(6,3) null, '
+' ADD N_PER_COF NUMERIC(6,3) null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 125');
ExecutaComandoSql(Aux,'comment on column CFG_FISCAL.N_PER_PIS is ''PERCENTUAL DO PIS''');
ExecutaComandoSql(Aux,'comment on column CFG_FISCAL.N_PER_COF is ''PERCENTUAL DE COFINS''');
end;
if VpaNumAtualizacao < 126 Then
begin
VpfErro := '126';
ExecutaComandoSql(Aux,'alter table MOVSUMARIZAESTOQUE'
+' ADD N_VLR_VEN_LIQ NUMERIC(17,4) null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 126');
ExecutaComandoSql(Aux,'comment on column MOVSUMARIZAESTOQUE.N_VLR_VEN_LIQ is ''VALOR DE VENDA LIQUIDA''');
end;
if VpaNumAtualizacao < 128 Then
begin
VpfErro := '128';
ExecutaComandoSql(Aux,'alter table MOVSUMARIZAESTOQUE'
+' ADD N_VLR_GIR NUMERIC(5,2) null');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 128');
ExecutaComandoSql(Aux,'comment on column MOVSUMARIZAESTOQUE.N_VAL_GIR is ''VALOR DO GIRO DE ESTOQUE''');
end;
if VpaNumAtualizacao < 129 Then
begin
VpfErro := '129';
ExecutaComandoSql(Aux,'Alter table cadprodutos'
+' add C_FLA_PRO CHAR(1) null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 129');
ExecutaComandoSql(Aux,'comment on column CADPRODUTOS.C_FLA_PRO is ''FLAG SE CONSIDERA O KIT COMO PRODUTO''');
end;
if VpaNumAtualizacao < 130 Then
begin
VpfErro := '130';
ExecutaComandoSql(Aux,'alter table CFG_PRODUTO'
+' ADD C_FLA_IPI CHAR(1) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 130');
ExecutaComandoSql(Aux,'comment on column CFG_PRODUTO.C_FLA_IPI is ''BOOLEAN - SE E PARA UTILIZAR O IPI''');
end;
if VpaNumAtualizacao < 131 Then
begin
VpfErro := '131';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL'
+' ADD C_ALT_VNF CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 131');
end;
if VpaNumAtualizacao < 132 Then
begin
VpfErro := '132';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASAPAGAR'
+' ADD I_FIL_NOT INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 132');
ExecutaComandoSql(Aux,'comment on column CADCONTASAPAGAR.I_FIL_NOT is ''FILIAL DA NOTA FISCAL''');
end;
if VpaNumAtualizacao < 133 Then
begin
VpfErro := '133';
ExecutaComandoSql(Aux,'alter table CFG_FINANCEIRO'
+' ADD I_FIL_CON INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 133');
ExecutaComandoSql(Aux,'comment on column CFG_FINANCEIRO.I_FIL_CON is ''FILIAL CONTROLADORA''');
end;
if VpaNumAtualizacao < 134 Then
begin
VpfErro := '134';
ExecutaComandoSql(Aux,'alter table CFG_FINANCEIRO'
+' ADD C_FIL_CON CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 134');
ExecutaComandoSql(Aux,'comment on column CFG_FINANCEIRO.C_FIL_CON is ''FILIAL CONTROLADORA''');
end;
if VpaNumAtualizacao < 135 Then
begin
VpfErro := '135';
ExecutaComandoSql(Aux,'alter table CFG_FISCAL'
+' ADD C_PLA_VEI CHAR(10) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 135');
ExecutaComandoSql(Aux,'comment on column CFG_FISCAL.C_PLA_VEI is ''PLACA DO VEICULO''');
end;
if VpaNumAtualizacao < 136 Then
begin
VpfErro := '136';
ExecutaComandoSql(Aux,'alter table CADFILIAIS'
+' ADD D_ULT_FEC DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 136');
ExecutaComandoSql(Aux,'comment on column CADFILIAIS.D_ULT_FEC is ''DATA DO ULTIMO FECHAMENTO''');
end;
if VpaNumAtualizacao < 137 Then
begin
VpfErro := '137';
ExecutaComandoSql(Aux,'create table INVENTARIO'
+' (I_EMP_FIL INTEGER NOT NULL, '
+' I_COD_INV INTEGER NOT NULL, '
+' I_NUM_SEQ INTEGER NOT NULL, '
+' I_SEQ_PRO INTEGER, '
+' C_COD_PRO CHAR(20), '
+' I_QTD_ANT Numeric(15,4), '
+' I_QTD_INV Numeric(15,4), '
+' N_CUS_PRO NUMERIC(15,4), '
+' C_COD_UNI CHAR(2),'
+' D_DAT_INV DATE, '
+' PRIMARY KEY(I_EMP_FIL, I_COD_INV,I_NUM_SEQ)) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 137');
end;
if VpaNumAtualizacao < 138 Then
begin
VpfErro := '138';
ExecutaComandoSql(Aux,'create unique index INVENTARIO_PK ON INVENTARIO(I_EMP_FIL,I_COD_INV,I_NUM_SEQ)'
+' ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 138');
end;
if VpaNumAtualizacao < 139 Then
begin
VpfErro := '139';
ExecutaComandoSql(Aux,'alter table CFG_PRODUTO '
+' ADD I_INV_ENT INTEGER NULL, '
+' ADD I_INV_SAI INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 139');
end;
if VpaNumAtualizacao < 140 Then
begin
VpfErro := '140';
ExecutaComandoSql(Aux,'alter table CFG_FISCAL '
+' ADD C_DUP_PNF CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 140');
end;
if VpaNumAtualizacao < 141 Then
begin
VpfErro := '141';
ExecutaComandoSql(Aux,'alter table movnotasfiscais ' +
' modify N_VLR_PRO NUMERIC(17,4)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 141');
end;
if VpaNumAtualizacao < 142 Then
begin
VpfErro := '142';
ExecutaComandoSql(Aux,'alter table MOVORCAMENTOS ' +
' modify N_VLR_PRO NUMERIC(17,4)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 142');
end;
if VpaNumAtualizacao < 143 Then
begin
VpfErro := '143';
ExecutaComandoSql(Aux,'alter table MOVHISTORICOCLIENTE ' +
' modify D_DAT_HIS null');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 143');
end;
if VpaNumAtualizacao < 144 Then
begin
VpfErro := '144';
ExecutaComandoSql(Aux,'alter table MOVHISTORICOCLIENTE ' +
' modify D_DAT_AGE null');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 144');
end;
if VpaNumAtualizacao < 145 Then
begin
VpfErro := '145';
ExecutaComandoSql(Aux,'alter table MOVHISTORICOCLIENTE ' +
' modify L_HIS_CLI null');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 145');
end;
if VpaNumAtualizacao < 146 Then
begin
VpfErro := '146';
ExecutaComandoSql(Aux,'alter table MOVHISTORICOCLIENTE ' +
' modify L_HIS_AGE null');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 146');
end;
if VpaNumAtualizacao < 147 Then
begin
VpfErro := '147';
ExecutaComandoSql(Aux,'alter table CADPRODUTOS ' +
' ADD C_PRA_PRO CHAR(20) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 147');
end;
if VpaNumAtualizacao < 148 Then
begin
VpfErro := '148';
ExecutaComandoSql(Aux,'alter table CADNOTAFISCAIS ' +
' ADD C_ORD_COM CHAR(50) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 148');
end;
if VpaNumAtualizacao < 149 Then
begin
VpfErro := '149';
ExecutaComandoSql(Aux,'alter table CADPRODUTOS ' +
' ADD I_LRG_PRO INTEGER NULL,'+
' ADD I_CMP_PRO INTEGER NULL, '+
' ADD I_CMP_FIG INTEGER NULL,'+
' ADD C_NUM_FIO CHAR(20) NULL, '+
' ADD C_BAT_PRO CHAR(20) NULL,'+
' ADD I_COD_FUN INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 149');
end;
if VpaNumAtualizacao < 150 Then
begin
VpfErro := '150';
ExecutaComandoSql(Aux,'create table CADTIPOFUNDO ' +
' (I_COD_FUN INTEGER NOT NULL,'+
' C_NOM_FUN CHAR(50), '+
' PRIMARY KEY (I_COD_FUN))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 150');
end;
if VpaNumAtualizacao < 151 Then
begin
VpfErro := '151';
ExecutaComandoSql(Aux,'create unique index CADTIPOFUNDO_PK ON CADTIPOFUNDO(I_COD_FUN) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 151');
end;
if VpaNumAtualizacao < 152 Then
begin
VpfErro := '152';
ExecutaComandoSql(Aux,'Alter table CFG_PRODUTO ADD C_IND_ETI CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 152');
end;
if VpaNumAtualizacao < 153 Then
begin
VpfErro := '153';
ExecutaComandoSql(Aux,'update CFG_PRODUTO set C_IND_ETI = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 153');
end;
if VpaNumAtualizacao < 154 Then
begin
VpfErro := '154';
ExecutaComandoSql(Aux,'CREATE TABLE MAQUINA (CODMAQ INTEGER NOT NULL , '+
' NOMMAQ CHAR(50), '+
' QTDFIO INTEGER, '+
' INDATI CHAR(1), '+
' PRIMARY KEY (CODMAQ))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX MAQUINA_PK ON MAQUINA(CODMAQ)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 154');
end;
if VpaNumAtualizacao < 155 Then
begin
VpfErro := '155';
ExecutaComandoSql(Aux,'CREATE TABLE ORDEMPRODUCAOCORPO(EMPFIL INTEGER NOT NULL , '+
' SEQORD INTEGER NOT NULL, '+
' DATEMI DATETIME, '+
' DATENT DATETIME, '+
' DATENP DATETIME, '+
' CODCLI INTEGER, '+
' CODPRO INTEGER, '+
' CODCOM INTEGER, '+
' NUMPED INTEGER, '+
' HORPRO CHAR(8), '+
' CODEST INTEGER, '+
' CODMAQ INTEGER, '+
' TIPPED INTEGER, ' +
' PRIMARY KEY (EMPFIL, SEQORD))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX ORDEMPRODUCAOCORPO_PK ON ORDEMPRODUCAOCORPO(EMPFIL,SEQORD)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 155');
end;
if VpaNumAtualizacao < 156 Then
begin
VpfErro := '156';
ExecutaComandoSql(Aux,'CREATE TABLE ESTAGIOPRODUCAO(CODEST INTEGER NOT NULL , '+
' NOMEST CHAR(50), '+
' CODTIP INTEGER, '+
' PRIMARY KEY (CODEST))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX ESTAGIOPRODUCAO_PK ON ESTAGIOPRODUCAO(CODEST)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 156');
end;
if VpaNumAtualizacao < 157 Then
begin
VpfErro := '157';
ExecutaComandoSql(Aux,'CREATE TABLE TIPOESTAGIOPRODUCAO(CODTIP INTEGER NOT NULL , '+
' NOMTIP CHAR(50), '+
' PRIMARY KEY (CODTIP))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX TIPOESTAGIOPRODUCAO_PK ON TIPOESTAGIOPRODUCAO(CODTIP)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 157');
end;
if VpaNumAtualizacao < 158 Then
begin
VpfErro := '158';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOCORPO ADD SEQPRO INTEGER ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 158');
end;
if VpaNumAtualizacao < 159 Then
begin
VpfErro := '159';
ExecutaComandoSql(Aux,'CREATE INDEX ORDEMPRODUCAOCORPO_FK1 ON ORDEMPRODUCAOCORPO(CODCLI) ');
ExecutaComandoSql(Aux,'CREATE INDEX ORDEMPRODUCAOCORPO_FK2 ON ORDEMPRODUCAOCORPO(CODEST) ');
ExecutaComandoSql(Aux,'CREATE INDEX ORDEMPRODUCAOCORPO_FK3 ON ORDEMPRODUCAOCORPO(SEQPRO) ');
ExecutaComandoSql(Aux,'CREATE INDEX ORDEMPRODUCAOCORPO_FK4 ON ORDEMPRODUCAOCORPO(CODMAQ) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 159');
end;
if VpaNumAtualizacao < 160 Then
begin
VpfErro := '160';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD CODEST INTEGER ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 160');
end;
if VpaNumAtualizacao < 161 Then
begin
VpfErro := '161';
ExecutaComandoSql(Aux,'CREATE TABLE TIPOEMENDA(CODEME INTEGER NOT NULL , '+
' NOMEME CHAR(50), '+
' PRIMARY KEY (CODEME))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX TIPOEMENDA_PK ON TIPOEMENDA(CODEME)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 161');
end;
if VpaNumAtualizacao < 162 Then
begin
VpfErro := '162';
ExecutaComandoSql(Aux,'alter table CADPRODUTOS ' +
' ADD CODEME INTEGER NULL,'+
' ADD INDCAL CHAR(1) NULL,'+
' ADD INDENG CHAR(1) NULL');
ExecutaComandoSql(Aux,'CREATE INDEX PRODUTO_TIPOEMENDA_FK ON CADPRODUTOS(CODEME)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 162');
end;
if VpaNumAtualizacao < 163 Then
begin
VpfErro := '163';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOCORPO ADD METTOT NUMERIC(11,2) NULL,'+
' ADD METFIT NUMERIC(11,2) NULL,'+
' ADD PERACR INTEGER NULL, '+
' ADD VALUNI NUMERIC(12,3) NULL, '+
' ADD QTDFIT INTEGER NULL' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 163');
end;
if VpaNumAtualizacao < 164 Then
begin
VpfErro := '164';
ExecutaComandoSql(Aux,'CREATE TABLE COMBINACAOFIGURA'+
' (SEQPRO INTEGER NOT NULL,'+
' CODCOM INTEGER NOT NULL,'+
' SEQCOR INTEGER NOT NULL, '+
' CODCOR INTEGER NOT NULL, '+
' TITFIO INTEGER NULL,'+
' NUMESP INTEGER NULL, '+
' PRIMARY KEY (SEQPRO, CODCOM,SEQCOR))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX COMBINACAOFIGURA_PK ON COMBINACAOFIGURA(SEQPRO,CODCOM,SEQCOR)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 164');
end;
if VpaNumAtualizacao < 165 Then
begin
VpfErro := '165';
ExecutaComandoSql(Aux,'CREATE TABLE COMBINACAO '+
' (SEQPRO INTEGER NOT NULL,'+
' CODCOM INTEGER NOT NULL,'+
' PRIMARY KEY (SEQPRO, CODCOM))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX COMBINACAO_PK ON COMBINACAO(SEQPRO,CODCOM)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 165');
end;
if VpaNumAtualizacao < 166 Then
begin
VpfErro := '166';
ExecutaComandoSql(Aux,'DELETE FROM COMBINACAO ');
ExecutaComandoSql(Aux,'ALTER TABLE COMBINACAO '+
' ADD CORFU1 INTEGER NOT NULL,'+
' ADD CORFU2 INTEGER NOT NULL,'+
' ADD TITFU1 INTEGER NOT NULL,'+
' ADD TITFU2 INTEGER NOT NULL,'+
' ADD CORCAR INTEGER NOT NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 166');
end;
if VpaNumAtualizacao < 167 Then
begin
VpfErro := '167';
ExecutaComandoSql(Aux,'CREATE TABLE ORDEMPRODUCAOITEM(EMPFIL INTEGER NOT NULL , '+
' SEQORD INTEGER NOT NULL, '+
' SEQITE INTEGER NOT NULL, '+
' CODCOM INTEGER NOT NULL, '+
' CODMAN INTEGER, '+
' QTDCOM INTEGER, '+
' METFIT NUMERIC(8,2), '+
' PRIMARY KEY (EMPFIL, SEQORD,SEQITE))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX ORDEMPRODUCAOITEM_PK ON ORDEMPRODUCAOITEM(EMPFIL,SEQORD,SEQITE)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 167');
end;
if VpaNumAtualizacao < 168 Then
begin
VpfErro := '168';
ExecutaComandoSql(Aux,'ALTER TABLE COMBINACAO '+
' ADD ESPFU1 INTEGER NULL,'+
' ADD ESPFU2 INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 168');
end;
if VpaNumAtualizacao < 169 Then
begin
VpfErro := '169';
ExecutaComandoSql(Aux,'Alter TABLE ORDEMPRODUCAOITEM add QTDFIT INTEGER ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 169');
end;
if VpaNumAtualizacao < 170 Then
begin
VpfErro := '170';
ExecutaComandoSql(Aux,'Alter TABLE CADCLIENTES add I_COD_VEN INTEGER ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 170');
end;
if VpaNumAtualizacao < 171 Then
begin
VpfErro := '171';
ExecutaComandoSql(Aux,'Alter TABLE MAQUINA add CONKWH NUMERIC(8,4)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 171');
end;
if VpaNumAtualizacao < 172 Then
begin
VpfErro := '172';
ExecutaComandoSql(Aux,'Alter table CFG_PRODUTO ADD C_IND_CAR CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 172');
end;
if VpaNumAtualizacao < 173 Then
begin
VpfErro := '173';
ExecutaComandoSql(Aux,'alter table CADPRODUTOS ' +
' ADD CODMAQ INTEGER NULL,'+
' ADD METMIN NUMERIC(7,3) NULL,'+
' ADD ENGPRO CHAR(7) NULL,'+
' ADD IMPPRE CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 173');
end;
if VpaNumAtualizacao < 174 Then
begin
VpfErro := '174';
ExecutaComandoSql(Aux,'ALTER TABLE COMBINACAO '+
' MODIFY TITFU1 CHAR(10) NOT NULL,'+
' MODIFY TITFU2 CHAR(10) NOT NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 174');
end;
if VpaNumAtualizacao < 175 Then
begin
VpfErro := '175';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO '+
' ADD C_PLA_ORC CHAR(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 175');
end;
if VpaNumAtualizacao < 176 Then
begin
VpfErro := '176';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS '+
' ADD N_PER_COM INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 176');
end;
if VpaNumAtualizacao < 177 Then
begin
VpfErro := '177';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS '+
' ADD I_TIP_ORC INTEGER NULL,'+
' ADD C_GER_FIN CHAR(1) NULL,'+
' ADD N_VLR_LIQ NUMERIC(17,4) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 177');
end;
if VpaNumAtualizacao < 178 Then
begin
VpfErro := '178';
ExecutaComandoSql(Aux,'UPDATE CADORCAMENTOS '+
' SET N_VLR_LIQ = N_VLR_TOT');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 178');
end;
if VpaNumAtualizacao < 179 Then
begin
VpfErro := '179';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASARECEBER '+
' ADD C_IND_CAD CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 179');
end;
if VpaNumAtualizacao < 180 Then
begin
VpfErro := '180';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO '+
' ADD I_OPE_ORC INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 180');
end;
if VpaNumAtualizacao < 181 Then
begin
VpfErro := '181';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS '+
' ADD C_DES_COR CHAR(20)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 181');
end;
if VpaNumAtualizacao < 182 Then
begin
VpfErro := '182';
ExecutaComandoSql(Aux,'drop index MOVORCAMENTOS_PK ');
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS drop PRIMARY KEY');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 182');
end;
if VpaNumAtualizacao < 183 Then
begin
VpfErro := '183';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS '+
' ADD I_SEQ_MOV INTEGER NULL');
ExecutaComandoSql(Aux,'UPDATE MOVORCAMENTOS '+
' SET I_SEQ_MOV = I_SEQ_PRO');
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS '+
' MODIFY I_SEQ_MOV NOT NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 183');
end;
if VpaNumAtualizacao < 184 Then
begin
VpfErro := '184';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS '+
' ADD PRIMARY KEY(I_EMP_FIL,I_LAN_ORC,I_SEQ_MOV)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 184');
end;
if VpaNumAtualizacao < 185 Then
begin
VpfErro := '185';
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX MOVORCAMENTOS_PK ON MOVORCAMENTOS(I_EMP_FIL,I_LAN_ORC,I_SEQ_MOV)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 185');
end;
if VpaNumAtualizacao < 186 Then
begin
VpfErro := '186';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD C_ORD_COM CHAR(20) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 186');
end;
if VpaNumAtualizacao < 187 Then
begin
VpfErro := '187';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS '+
' ADD C_DES_COR CHAR(20)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 187');
end;
if VpaNumAtualizacao < 188 Then
begin
VpfErro := '188';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES '+
' ADD I_COD_PAG INTEGER NULL, '+
' ADD I_FRM_PAG INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 188');
end;
if VpaNumAtualizacao < 189 Then
begin
VpfErro := '189';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES '+
' ADD I_PER_COM INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 189');
end;
if VpaNumAtualizacao < 190 Then
begin
VpfErro := '190';
ExecutaComandoSql(Aux,'CREATE TABLE COR '+
' (COD_COR INTEGER NOT NULL, '+
' NOM_COR CHAR(50) , '+
' PRIMARY KEY(COD_COR))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 190');
end;
if VpaNumAtualizacao < 191 Then
begin
VpfErro := '191';
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX COR_PK ON COR(COD_COR) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 191');
end;
if VpaNumAtualizacao < 192 Then
begin
VpfErro := '192';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS ' +
' ADD I_COD_COR INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 192');
end;
if VpaNumAtualizacao < 193 Then
begin
VpfErro := '193';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO '+
' ADD C_EST_COR CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 193');
end;
if VpaNumAtualizacao < 194 Then
begin
VpfErro := '194';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS '+
' ADD I_COD_COR INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 194');
end;
if VpaNumAtualizacao < 195 Then
begin
VpfErro := '195';
ExecutaComandoSql(Aux,'UPDATE CADORCAMENTOS '+
' SET C_FLA_SIT = ''A'''+
' where c_fla_sit <> ''A'''+
' AND C_FLA_SIT <> ''E'''+
' AND C_FLA_SIT <> ''C''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 195');
end;
if VpaNumAtualizacao < 196 Then
begin
VpfErro := '196';
ExecutaComandoSql(Aux,'Alter table MOVNOTASFISCAIS MODIFY C_COD_CST CHAR(3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 196');
end;
if VpaNumAtualizacao < 197 Then
begin
VpfErro := '197';
ExecutaComandoSql(Aux,'Alter table COMBINACAOFIGURA MODIFY TITFIO CHAR(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 197');
end;
if VpaNumAtualizacao < 198 Then
begin
VpfErro := '198';
ExecutaComandoSql(Aux,'Alter table CADNOTAFISCAIS ADD C_FIN_GER CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 198');
end;
if VpaNumAtualizacao < 199 Then
begin
VpfErro := '199';
ExecutaComandoSql(Aux,'UPDATE CADNOTAFISCAIS SET C_FIN_GER = ''N''');
ExecutaComandoSql(Aux,'UPDATE CADNOTAFISCAIS SET C_FIN_GER = ''S'''+
' WHERE C_COD_NAT LIKE ''51%'''+
' OR C_COD_NAT LIKE ''61%''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 199');
end;
if VpaNumAtualizacao < 200 Then
begin
VpfErro := '200';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO '+
' ADD C_LIM_CRE CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 200');
end;
if VpaNumAtualizacao < 201 Then
begin
VpfErro := '201';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO '+
' ADD C_BLO_CAT CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 201');
end;
if VpaNumAtualizacao < 202 Then
begin
VpfErro := '202';
ExecutaComandoSql(Aux,'Update CFG_FINANCEIRO '+
' set C_BLO_CAT = ''F'', C_LIM_CRE = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 202');
end;
if VpaNumAtualizacao < 203 Then
begin
VpfErro := '203';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOCORPO '+
' ADD ORDCLI INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 203');
end;
if VpaNumAtualizacao < 204 Then
begin
VpfErro := '204';
ExecutaComandoSql(Aux,' ALTER TABLE CFG_FISCAL ' +
' ADD C_PED_PRE CHAR(1) ');
ExecutaComandoSql(Aux,' UPDATE CFG_FISCAL ' +
' SET C_PED_PRE = ''F'' ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 204');
end;
if VpaNumAtualizacao < 205 Then
begin
VpfErro := '205';
ExecutaComandoSql(Aux,' ALTER TABLE CFG_FISCAL ' +
' ADD C_MAR_PRO CHAR(50), '+
' ADD I_COD_TRA INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 205');
end;
if VpaNumAtualizacao < 206 Then
begin
VpfErro := '206';
ExecutaComandoSql(Aux,' ALTER TABLE CAD_DOC ' +
' ADD I_MAX_ITE INTEGER NULL ');
ExecutaComandoSql(Aux,' Update CAD_DOC set I_MAX_ITE = 40');
ExecutaComandoSql(Aux,' Update CFG_GERAL set I_Ult_Alt = 206');
end;
if VpaNumAtualizacao < 207 Then
begin
VpfErro := '207';
ExecutaComandoSql(Aux,' ALTER TABLE CFG_FISCAL ' +
' ADD I_PED_PAD INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 207');
end;
if VpaNumAtualizacao < 208 Then
begin
VpfErro := '208';
ExecutaComandoSql(Aux,' alter table CADORCAMENTOS ' +
' ADD I_COD_TRA integer NULL ');
ExecutaComandoSql(Aux,' alter table CADORCAMENTOS ' +
' ADD C_PLA_VEI varchar(10) ');
ExecutaComandoSql(Aux,' alter table CADORCAMENTOS ' +
' ADD C_EST_VEI char(2) ');
ExecutaComandoSql(Aux,' alter table CADORCAMENTOS ' +
' ADD N_QTD_TRA NUMERIC(11,3) ');
ExecutaComandoSql(Aux,' alter table CADORCAMENTOS ' +
' ADD C_ESP_TRA varchar(30) ');
ExecutaComandoSql(Aux,' alter table CADORCAMENTOS ' +
' ADD C_MAR_TRA varchar(30) ');
ExecutaComandoSql(Aux,' alter table CADORCAMENTOS ' +
' ADD I_NRO_TRA integer ');
ExecutaComandoSql(Aux,' alter table CADORCAMENTOS ' +
' ADD N_PES_BRU NUMERIC(11,3) ');
ExecutaComandoSql(Aux,' alter table CADORCAMENTOS ' +
' ADD N_PES_LIQ NUMERIC(11,3) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 208');
end;
if VpaNumAtualizacao < 209 Then
begin
VpfErro := '209';
ExecutaComandoSql(Aux,' ALTER TABLE CFG_FISCAL ' +
' ADD C_TRA_PED CHAR(1) ');
ExecutaComandoSql(Aux,' UPDATE CFG_FISCAL ' +
' SET C_TRA_PED = ''F'' ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 209');
end;
if VpaNumAtualizacao < 210 Then
begin
VpfErro := '210';
ExecutaComandoSql(Aux,' ALTER TABLE CADCLIENTES '+
' MODIFY I_PER_COM NUMERIC(8,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 210');
end;
if VpaNumAtualizacao < 211 Then
begin
VpfErro := '211';
ExecutaComandoSql(Aux,' ALTER TABLE CFG_FISCAL '+
' ADD C_NAT_FOE CHAR(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 211');
end;
if VpaNumAtualizacao < 212 Then
begin
VpfErro := '212';
ExecutaComandoSql(Aux,' ALTER TABLE CADPRODUTOS '+
' ADD N_PES_LIQ NUMERIC(10,5) NULL,'+
' ADD N_PES_BRU NUMERIC(10,5) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 212');
end;
if VpaNumAtualizacao < 213 Then
begin
VpfErro := '213';
ExecutaComandoSql(Aux,' CREATE TABLE CADTIPOORCAMENTO ( '+
' I_COD_TIP INTEGER NOT NULL, '+
' C_NOM_TIP CHAR(50), '+
' C_CLA_PLA CHAR(10), '+
' I_COD_OPE INTEGER, '+
' PRIMARY KEY (I_COD_TIP))');
ExecutaComandoSql(Aux,'Create unique index CADTIPOORCAMENTO_PK on CADTIPOORCAMENTO(I_COD_TIP)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 213');
end;
if VpaNumAtualizacao < 214 Then
begin
VpfErro := '214';
ExecutaComandoSql(Aux,' ALTER TABLE CFG_PRODUTO '+
' DROP I_OPE_ORC ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 214');
end;
if VpaNumAtualizacao < 215 Then
begin
VpfErro := '215';
ExecutaComandoSql(Aux,' ALTER TABLE CFG_FINANCEIRO '+
' DROP C_PLA_ORC ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 215');
end;
if VpaNumAtualizacao < 216 Then
begin
VpfErro := '216';
ExecutaComandoSql(Aux,' CREATE TABLE LOG'+
' (SEQ_LOG INTEGER NOT NULL, '+
' DAT_LOG DATETIME NOT NULL ,'+
' COD_USUARIO INTEGER NOT NULL,'+
' DES_LOG CHAR(20),'+
' NOM_TABELA CHAR(50),'+
' NOM_CAMPO CHAR(50),'+
' VAL_ANTERIOR CHAR(100),'+
' VAL_ATUAL CHAR(100),' +
' NOM_MODULO_SISTEMA CHAR(30), '+
' PRIMARY KEY (SEQ_LOG))');
ExecutaComandoSql(Aux,'Create UNIQUE INDEX LOG_PK on LOG(SEQ_LOG)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 216');
end;
if VpaNumAtualizacao < 217 Then
begin
VpfErro := '217';
ExecutaComandoSql(Aux,' ALTER TABLE CFG_PRODUTO '+
' ADD I_TIP_ORC INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 217');
end;
if VpaNumAtualizacao < 218 Then
begin
VpfErro := '218';
ExecutaComandoSql(Aux,' CREATE TABLE RAMO_ATIVIDADE ('+
' COD_RAMO_ATIVIDADE INTEGER NOT NULL, '+
' NOM_RAMO_ATIVIDADE CHAR(50),'+
' PRIMARY KEY (COD_RAMO_ATIVIDADE))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX RAMO_ATIVIDADE_PK ON RAMO_ATIVIDADE(COD_RAMO_ATIVIDADE)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 218');
end;
if VpaNumAtualizacao < 219 Then
begin
VpfErro := '219';
ExecutaComandoSql(Aux,' ALTER TABLE CADCLIENTES '+
' ADD I_COD_RAM INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 219');
end;
if VpaNumAtualizacao < 220 Then
begin
VpfErro := '220';
ExecutaComandoSql(Aux,' ALTER TABLE MOVCONTASARECEBER '+
' ADD C_DUP_DES CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 220');
end;
if VpaNumAtualizacao < 221 Then
begin
VpfErro := '221';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO ' +
' add C_TIP_BOL char(1) null ');
ExecutaComandoSql(Aux,' update cfg_financeiro set C_TIP_BOL = ''P'' ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 221');
end;
if VpaNumAtualizacao < 222 Then
begin
VpfErro := '222';
ExecutaComandoSql(Aux,' alter table CADORCAMENTOS ' +
' MODIFY N_PER_COM NUMERIC(8,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 222');
end;
if VpaNumAtualizacao < 223 Then
begin
VpfErro := '223';
ExecutaComandoSql(Aux,' alter table CADCONTASARECEBER ' +
' ADD C_IND_CON CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 223');
end;
if VpaNumAtualizacao < 224 Then
begin
VpfErro := '224';
ExecutaComandoSql(Aux,' UPDATE CADORCAMENTOS '+
' SET I_TIP_ORC = 1 '+
' Where I_TIP_ORC is null');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 224');
end;
if VpaNumAtualizacao < 225 Then
begin
VpfErro := '225';
ExecutaComandoSql(Aux,' UPDATE CADORCAMENTOS '+
' SET I_TIP_ORC = 1 '+
' Where I_TIP_ORC = 0');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 225');
end;
if VpaNumAtualizacao < 226 Then
begin
VpfErro := '226';
ExecutaComandoSql(Aux,' ALTER TABLE MOVCONTASARECEBER '+
' ADD N_VLR_BRU NUMERIC(17,2) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 226');
end;
if VpaNumAtualizacao < 227 Then
begin
VpfErro := '227';
ExecutaComandoSql(Aux,' ALTER TABLE CADCLIENTES '+
' ADD C_NOM_FAN CHAR(50) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 227');
end;
if VpaNumAtualizacao < 228 Then
begin
VpfErro := '228';
ExecutaComandoSql(Aux,' ALTER TABLE ORDEMPRODUCAOITEM '+
' modify CODMAN CHAR(15) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 228');
end;
if VpaNumAtualizacao < 229 Then
begin
VpfErro := '229';
ExecutaComandoSql(Aux,' CREATE TABLE MOVCONTACONSOLIDADACR '+
' (I_EMP_FIL INTEGER NOT NULL, '+
' I_REC_PAI INTEGER NOT NULL, '+
' I_LAN_REC INTEGER NOT NULL, '+
' I_NRO_PAR INTEGER NOT NULL,' +
' PRIMARY KEY (I_EMP_FIL, I_REC_PAI, I_LAN_REC, I_NRO_PAR))' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 229');
end;
if VpaNumAtualizacao < 230 Then
begin
VpfErro := '230';
ExecutaComandoSql(Aux,' CREATE UNIQUE INDEX MOVCONTACONSOLIDADACR_PK ON MOVCONTACONSOLIDADACR(I_EMP_FIL,I_REC_PAI,I_LAN_REC, I_NRO_PAR)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 230');
end;
if VpaNumAtualizacao < 231 Then
begin
VpfErro := '231';
ExecutaComandoSql(Aux,' Alter table CFG_GERAL ADD D_CLI_PED Datetime');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 231');
end;
if VpaNumAtualizacao < 232 Then
begin
VpfErro := '232';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASAPAGAR '+
' ADD C_IND_CAD CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 232');
end;
if VpaNumAtualizacao < 233 Then
begin
VpfErro := '233';
ExecutaComandoSql(Aux,'ALTER TABLE CADVENDEDORES '+
' ADD C_IND_ATI CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 233');
end;
if VpaNumAtualizacao < 234 Then
begin
VpfErro := '234';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES '+
' ADD N_COD_EAN NUMERIC(15) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 234');
end;
if VpaNumAtualizacao < 235 Then
begin
VpfErro := '235';
ExecutaComandoSql(Aux,'UPDATE CADVENDEDORES SET C_IND_ATI = ''S''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 235');
end;
if VpaNumAtualizacao < 236 Then
begin
VpfErro := '236';
ExecutaComandoSql(Aux,'ALTER TABLE MAQUINA ADD QTDRPM INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 236');
end;
if VpaNumAtualizacao < 237 Then
begin
VpfErro := '237';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOCORPO ADD DESOBS CHAR(750) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 237');
end;
if VpaNumAtualizacao < 238 Then
begin
VpfErro := '238';
ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECO ADD I_COD_CLI INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 238');
end;
if VpaNumAtualizacao < 239 Then
begin
VpfErro := '239';
ExecutaComandoSql(Aux,'UPDATE MOVTABELAPRECO SET I_COD_CLI = 0');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 239');
end;
if VpaNumAtualizacao < 240 Then
begin
VpfErro := '240';
ExecutaComandoSql(Aux,'DROP INDEX MOVTABELAPRECO_PK');
ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECO DELETE PRIMARY KEY');
ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECO MODIFY I_COD_CLI INTEGER NOT NULL');
ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECO ADD PRIMARY KEY(I_COD_EMP,I_COD_TAB,I_SEQ_PRO,I_COD_CLI)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 240');
end;
if VpaNumAtualizacao < 241 Then
begin
VpfErro := '241';
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX MOVTABELAPRECO_PK ON MOVTABELAPRECO(I_COD_EMP,I_COD_TAB,I_SEQ_PRO,I_COD_CLI)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 241');
end;
if VpaNumAtualizacao < 242 Then
begin
VpfErro := '242';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOCORPO ADD UNMPED CHAR(2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 242');
end;
if VpaNumAtualizacao < 243 Then
begin
VpfErro := '243';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD C_PRC_AUT CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_PRODUTO SET C_PRC_AUT = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 243');
end;
if VpaNumAtualizacao < 244 Then
begin
VpfErro := '244';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOCORPO ADD TIPTEA INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 244');
end;
if VpaNumAtualizacao < 245 Then
begin
VpfErro := '245';
ExecutaComandoSql(Aux,'CREATE TABLE EMBALAGEM ( '+
' COD_EMBALAGEM INTEGER NOT NULL, '+
' NOM_EMBALAGEM CHAR(50),'+
' PRIMARY KEY (COD_EMBALAGEM))');
ExecutaComandoSql(Aux,'Create unique INDEX EMBALAGEM_PK ON EMBALAGEM(COD_EMBALAGEM)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 245');
end;
if VpaNumAtualizacao < 246 Then
begin
VpfErro := '246';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS '+
' ADD I_COD_EMB INTEGER NULL,'+
' ADD C_DES_EMB CHAR(50)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 246');
end;
if VpaNumAtualizacao < 247 Then
begin
VpfErro := '247';
ExecutaComandoSql(Aux,'CREATE TABLE VENDA_PAO_DE_ACUCAR ( '+
' COD_FILIAL NUMERIC(15,0) NOT NULL,'+
' NOM_FILIAL CHAR(50) NULL,' +
' QTD_COMPRADO NUMERIC(15,3),'+
' QTD_VENDIDO NUMERIC(15,3),'+
' PRIMARY KEY (COD_FILIAL))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX VENDA_PAO_DE_ACUCAR_PK ON VENDA_PAO_DE_ACUCAR(COD_FILIAL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 247');
end;
if VpaNumAtualizacao < 248 Then
begin
VpfErro := '248';
ExecutaComandoSql(Aux,'CREATE TABLE VENDA_PAO_DE_ACUCAR_ITEM ( '+
' COD_FILIAL NUMERIC(15,0) NOT NULL,'+
' COD_PRODUTO NUMERIC(15,0) NOT NULL,'+
' NOM_PRODUTO CHAR(50) NULL,' +
' QTD_COMPRADO NUMERIC(15,3),'+
' QTD_VENDIDO NUMERIC(15,3),'+
' PRIMARY KEY (COD_FILIAL,COD_PRODUTO))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX VENDA_PAO_DE_ACUCAR_ITEM_PK ON VENDA_PAO_DE_ACUCAR_ITEM(COD_FILIAL,COD_PRODUTO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 248');
end;
if VpaNumAtualizacao < 249 Then
begin
VpfErro := '249';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS '+
' ADD C_ADM_SIS CHAR(1) NULL,'+
' ADD C_FIN_COM CHAR(1) NULL,'+
' ADD C_EST_COM CHAR(1) NULL,'+
' ADD C_POL_COM CHAR(1) NULL,'+
' ADD C_FAT_COM CHAR(1) NULL,'+
' ADD C_FIN_CCR CHAR(1) NULL,'+
' ADD C_FIN_BCR CHAR(1) NULL,'+
' ADD C_FIN_CCP CHAR(1) NULL,'+
' ADD C_FIN_BCP CHAR(1) NULL,'+
' ADD C_POL_IPP CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 249');
end;
if VpaNumAtualizacao < 250 Then
begin
VpfErro := '250';
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS '+
' SET C_ADM_SIS = ''F'','+
' C_FIN_COM = ''F'','+
' C_EST_COM = ''F'','+
' C_POL_COM = ''F'','+
' C_FAT_COM = ''F'','+
' C_FIN_CCR = ''F'','+
' C_FIN_BCR = ''F'','+
' C_FIN_CCP = ''F'','+
' C_FIN_BCP = ''F'','+
' C_POL_IPP = ''F''');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS '+
' SET C_ADM_SIS = ''T'','+
' C_FIN_COM = ''T'','+
' C_EST_COM = ''T'','+
' C_POL_COM = ''T'','+
' C_FAT_COM = ''T'','+
' C_FIN_CCR = ''T'','+
' C_FIN_BCR = ''T'','+
' C_FIN_CCP = ''T'','+
' C_FIN_BCP = ''T'','+
' C_POL_IPP = ''T'''+
' Where I_COD_GRU = 1');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 250');
end;
if VpaNumAtualizacao < 251 Then
begin
VpfErro := '251';
ExecutaComandoSql(Aux,'DROP TABLE CFG_FAIXA_CADASTRO');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 251');
end;
if VpaNumAtualizacao < 252 Then
begin
VpfErro := '252';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD C_ORP_IMP CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 252');
end;
if VpaNumAtualizacao < 253 Then
begin
VpfErro := '253';
ExecutaComandoSql(Aux,'alter table CADPRODUTOS ' +
' MODIFY METMIN NUMERIC(12,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 253');
end;
if VpaNumAtualizacao < 254 Then
begin
VpfErro := '254';
ExecutaComandoSql(Aux,'CREATE TABLE COLETAOPCORPO( EMPFIL INTEGER NOT NULL, ' +
' SEQORD INTEGER NOT NULL, '+
' SEQCOL INTEGER NOT NULL, '+
' DATCOL DATETIME NOT NULL,'+
' INDFIN CHAR(1) NULL, '+
' INDREP CHAR(1) NULL, '+
' CODUSU INTEGER NOT NULL, '+
' PRIMARY KEY (EMPFIL,SEQORD,SEQCOL))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX COLETAOPCORPO_PK ON COLETAOPCORPO(EMPFIL,SEQORD,SEQCOL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 254');
end;
if VpaNumAtualizacao < 255 Then
begin
VpfErro := '255';
ExecutaComandoSql(Aux,'CREATE TABLE COLETAOPITEM(EMPFIL INTEGER NOT NULL , '+
' SEQORD INTEGER NOT NULL, '+
' SEQCOL INTEGER NOT NULL, '+
' SEQITE INTEGER NOT NULL, '+
' CODCOM INTEGER NOT NULL, '+
' CODMAN INTEGER, '+
' NROFIT INTEGER, '+
' METPRO NUMERIC(14,2), '+
' METCOL NUMERIC(14,2), '+
' METAPR NUMERIC(14,2), '+
' METFAL NUMERIC(14,2), '+
' PRIMARY KEY (EMPFIL, SEQORD,SEQCOL,SEQITE))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX COLETAOPITEM_PK ON COLETAOPITEM(EMPFIL,SEQORD,SEQCOL,SEQITE)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 255');
end;
if VpaNumAtualizacao < 256 Then
begin
VpfErro := '256';
ExecutaComandoSql(Aux,'CREATE TABLE PRODUTO_REFERENCIA(SEQ_PRODUTO INTEGER NOT NULL , '+
' COD_CLIENTE INTEGER NOT NULL , '+
' SEQ_REFERENCIA INTEGER NOT NULL, '+
' COD_COR INTEGER, '+
' DES_REFERENCIA CHAR(50), '+
' COD_PRODUTO CHAR(20), '+
' PRIMARY KEY (SEQ_PRODUTO,COD_CLIENTE,SEQ_REFERENCIA))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX PRODUTO_REFERENCIA_PK ON PRODUTO_REFERENCIA(SEQ_PRODUTO,COD_CLIENTE,SEQ_REFERENCIA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 256');
end;
if VpaNumAtualizacao < 257 Then
begin
VpfErro := '257';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOITEM '+
' ADD QTDPRO NUMERIC(14,2), '+
' ADD QTDFAL NUMERIC(14,2)');
ExecutaComandoSql(Aux,'Update ORDEMPRODUCAOITEM SET QTDFAL = METFIT');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 257');
end;
if VpaNumAtualizacao < 258 Then
begin
VpfErro := '258';
ExecutaComandoSql(Aux,'ALTER TABLE COLETAOPCORPO '+
' ADD QTDTOT NUMERIC(14,2)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 258');
end;
if VpaNumAtualizacao < 259 Then
begin
VpfErro := '259';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS '+
' ADD C_PEN_PRO CHAR(20)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 259');
end;
if VpaNumAtualizacao < 260 Then
begin
VpfErro := '260';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD C_EXI_DAP CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_PRODUTO SET C_EXI_DAP = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 260');
end;
if VpaNumAtualizacao < 261 Then
begin
VpfErro := '261';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS ADD C_PRO_REF CHAR(50) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 261');
end;
if VpaNumAtualizacao < 262 Then
begin
VpfErro := '262';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS ADD C_PRO_REF CHAR(50) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 262');
end;
if VpaNumAtualizacao < 263 Then
begin
VpfErro := '263';
ExecutaComandoSql(Aux,'CREATE TABLE MOVNOTAORCAMENTO ('+
' I_EMP_FIL INTEGER NOT NULL, '+
' I_SEQ_NOT INTEGER NOT NULL,'+
' I_LAN_ORC INTEGER NOT NULL,'+
' PRIMARY KEY(I_EMP_FIL,I_SEQ_NOT,I_LAN_ORC))');
ExecutaComandoSql(Aux,'create unique index MOVNOTAORCAMENTO_PK ON MOVNOTAORCAMENTO(I_EMP_FIL, I_SEQ_NOT,I_LAN_ORC)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 263');
end;
if VpaNumAtualizacao < 264 Then
begin
VpfErro := '264';
ExecutaComandoSql(Aux,' ALTER TABLE COLETAOPITEM '+
' modify CODMAN CHAR(15) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 264');
end;
if VpaNumAtualizacao < 265 Then
begin
VpfErro := '265';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO'
+' ADD C_EXC_CNF CHAR(1) NULL ');
ExecutacomandoSql(Aux,'Update CFG_PRODUTO SET C_EXC_CNF = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 265');
end;
if VpaNumAtualizacao < 266 Then
begin
VpfErro := '266';
ExecutaComandoSql(Aux,'CREATE TABLE ROMANEIOCORPO(EMPFIL INTEGER NOT NULL,'+
' SEQROM INTEGER NOT NULL,'+
' DATINI DATETIME, '+
' DATFIM DATETIME, '+
' NOTGER CHAR(1),'+
' INDIMP CHAR(1),'+
' PRIMARY KEY(EMPFIL, SEQROM))');
ExecutacomandoSql(Aux,'CREATE UNIQUE INDEX ROMANEIOCORPO_PK ON ROMANEIOCORPO(EMPFIL,SEQROM)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 266');
end;
if VpaNumAtualizacao < 267 Then
begin
VpfErro := '267';
ExecutaComandoSql(Aux,'CREATE TABLE ROMANEIOITEM(EMPFIL INTEGER NOT NULL,'+
' SEQROM INTEGER NOT NULL,'+
' SEQORD INTEGER NOT NULL, '+
' SEQCOL INTEGER NOT NULL,'+
' PRIMARY KEY(EMPFIL, SEQROM,SEQORD,SEQCOL))');
ExecutacomandoSql(Aux,'CREATE UNIQUE INDEX ROMANEIOITEM_PK ON ROMANEIOITEM(EMPFIL,SEQROM,SEQORD,SEQCOL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 267');
end;
if VpaNumAtualizacao < 268 Then
begin
VpfErro := '268';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD I_SEQ_ROM INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 268');
end;
if VpaNumAtualizacao < 269 Then
begin
VpfErro := '269';
ExecutaComandoSql(Aux,'ALTER TABLE COLETAOPCORPO ADD INDROM CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update COLETAOPCORPO SET INDROM = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 269');
end;
if VpaNumAtualizacao < 270 Then
begin
VpfErro := '270';
ExecutaComandoSql(Aux,'ALTER TABLE MOVKIT'
+' ADD I_COD_COR INTEGER NULL, '+
' ADD C_COD_UNI CHAR(2) NULL,'+
' ADD I_SEQ_MOV INTEGER NULL');
ExecutaComandoSql(Aux,'Update MOVKIT SET I_SEQ_MOV = 1');
ExecutaComandoSql(Aux,'ALTER TABLE MOVKIT MODIFY I_SEQ_MOV INTEGER NOT NULL');
ExecutaComandoSql(Aux,'DROP INDEX MOVKIT_PK');
ExecutaComandoSql(Aux,'ALTER TABLE MOVKIT drop PRIMARY KEY');
ExecutaComandoSql(Aux,'ALTER TABLE MOVKIT '+
' ADD PRIMARY KEY(I_PRO_KIT,I_SEQ_PRO,I_SEQ_MOV)');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX MOVKIT_PK ON MOVKIT(I_PRO_KIT,I_SEQ_PRO,I_SEQ_MOV)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 270');
ExecutaComandoSql(Aux,'comment on column MOVKIT.I_COD_COR is ''CODIGO DA COR''');
end;
if VpaNumAtualizacao < 271 Then
begin
VpfErro := '271';
ExecutaComandoSql(Aux,'update movkit mov ' +
' set C_COD_UNI = (SELECT C_COD_UNI FROM CADPRODUTOS PRO WHERE PRO.I_SEQ_PRO = MOV.I_SEQ_PRO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 271');
end;
if VpaNumAtualizacao < 272 Then
begin
VpfErro := '272';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAISFOR ADD I_COD_COR INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 272');
end;
if VpaNumAtualizacao < 273 Then
begin
VpfErro := '273';
ExecutaComandoSql(Aux,'ALTER TABLE MOVQDADEPRODUTO'
+' ADD I_COD_COR INTEGER NULL');
ExecutaComandoSql(Aux,'Update MOVQDADEPRODUTO SET I_COD_COR = 0');
ExecutaComandoSql(Aux,'ALTER TABLE MOVQDADEPRODUTO MODIFY I_COD_COR INTEGER NOT NULL');
ExecutaComandoSql(Aux,'DROP INDEX MOVQDADEPRODUTO_PK');
ExecutaComandoSql(Aux,'ALTER TABLE MOVQDADEPRODUTO drop PRIMARY KEY');
ExecutaComandoSql(Aux,'ALTER TABLE MOVQDADEPRODUTO '+
' ADD PRIMARY KEY(I_EMP_FIL,I_SEQ_PRO,I_COD_COR)');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX MOVQDADEPRODUTO_PK ON MOVQDADEPRODUTO(I_EMP_FIL,I_SEQ_PRO,I_COD_COR)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 273');
end;
if VpaNumAtualizacao < 274 Then
begin
VpfErro := '274';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL '
+' ADD C_OPT_SIM CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_FISCAL set C_OPT_SIM = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 274');
end;
if VpaNumAtualizacao < 275 Then
begin
VpfErro := '275';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR '
+' ADD N_PER_DES NUMERIC(15,3) NULL, '+
' ADD C_CLA_PLA CHAR(10) NULL, ' +
' ADD I_COD_FRM INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 275');
end;
if VpaNumAtualizacao < 276 Then
begin
VpfErro := '276';
ExecutaComandoSql(Aux,'DROP INDEX MOVNOTASFISCAISFOR_PK');
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAISFOR drop PRIMARY KEY');
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAISFOR '+
' ADD PRIMARY KEY(I_EMP_FIL,I_SEQ_NOT,I_SEQ_MOV)');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX MOVNOTASFISCAISFOR_PK ON MOVNOTASFISCAISFOR(I_EMP_FIL,I_SEQ_NOT,I_SEQ_MOV)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 276');
end;
if VpaNumAtualizacao < 277 Then
begin
VpfErro := '277';
ExecutaComandoSql(Aux,'delete from CADPRODUTOS Where C_COD_PRO = ''6054218''');
ExecutaComandoSql(Aux,'delete from CADPRODUTOS Where C_COD_PRO = ''6062326''');
ExecutaComandoSql(Aux,'delete from CADPRODUTOS Where C_COD_PRO = ''6062377''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 277');
end;
if VpaNumAtualizacao < 278 Then
begin
VpfErro := '278';
ExecutaComandoSql(Aux,'DROP INDEX MOVQDADEPRODUTO_PK2');
ExecutaComandoSql(Aux,'DROP INDEX MOVQDADEPRODUTO_PK3');
ExecutaComandoSql(Aux,'DROP INDEX MOVQDADEPRODUTO_PK4');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 278');
end;
if VpaNumAtualizacao < 279 Then
begin
VpfErro := '279';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS '+
' DROP N_PER_ACR ');
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS '+
' ADD N_VLR_DES NUMERIC(15,3)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 279');
end;
if VpaNumAtualizacao < 280 Then
begin
VpfErro := '280';
ExecutaComandoSql(Aux,'ALTER TABLE MOVESTOQUEPRODUTOS '+
' ADD I_COD_COR INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 280');
end;
if VpaNumAtualizacao < 281 Then
begin
VpfErro := '281';
ExecutaComandoSql(Aux,'DROP TABLE INVENTARIO');
ExecutaComandoSql(Aux,'DROP TABLE CADINVENTARIO');
ExecutaComandoSql(Aux,'DROP TABLE MOVINVENTARIO');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 281');
end;
if VpaNumAtualizacao < 282 Then
begin
VpfErro := '282';
ExecutaComandoSql(Aux,'CREATE TABLE INVENTARIOCORPO( '+
' COD_FILIAL INTEGER NOT NULL, '+
' SEQ_INVENTARIO INTEGER NOT NULL, '+
' COD_USUARIO INTEGER , '+
' DAT_INICIO DATETIME, '+
' DAT_FIM DATETIME,'+
' PRIMARY KEY(COD_FILIAL,SEQ_INVENTARIO))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX INVENTARIOCORPO_PK ON INVENTARIOCORPO(COD_FILIAL,SEQ_INVENTARIO)');
ExecutaComandoSql(Aux,'CREATE TABLE INVENTARIOITEM( '+
' COD_FILIAL INTEGER NOT NULL, '+
' SEQ_INVENTARIO INTEGER NOT NULL, '+
' SEQ_ITEM INTEGER NOT NULL, '+
' SEQ_PRODUTO INTEGER, '+
' COD_COR INTEGER, '+
' DAT_INVENTARIO DATETIME , '+
' COD_UNIDADE CHAR(2),'+
' QTD_PRODUTO NUMERIC(15,3),'+
' COD_USUARIO INTEGER, '+
' COD_PRODUTO CHAR(20), '+
' PRIMARY KEY(COD_FILIAL,SEQ_INVENTARIO,SEQ_ITEM))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX INVENTARIOITEM_PK ON INVENTARIOITEM(COD_FILIAL,SEQ_INVENTARIO,SEQ_ITEM)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 282');
end;
if VpaNumAtualizacao < 283 Then
begin
VpfErro := '283';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES '+
' ADD N_PER_DES NUMERIC(10,3)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 283');
end;
if VpaNumAtualizacao < 284 Then
begin
VpfErro := '284';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS '+
' ADD I_TAB_GRA INTEGER NULL,'+
' ADD I_TAB_PED INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 284');
end;
if VpaNumAtualizacao < 285 Then
begin
VpfErro := '285';
ExecutaComandoSql(Aux,'CREATE TABLE MOTIVOREPROGRAMACAO( '+
' COD_MOTIVO INTEGER NOT NULL,'+
' NOM_MOTIVO CHAR(50),'+
' PRIMARY KEY (COD_MOTIVO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 285');
end;
if VpaNumAtualizacao < 286 Then
begin
VpfErro := '286';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOCORPO '+
' ADD CODMOT INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 286');
end;
if VpaNumAtualizacao < 287 Then
begin
VpfErro := '287';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL '+
' ADD C_NNF_FIL CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_FISCAL set C_NNF_FIL = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 287');
end;
if VpaNumAtualizacao < 288 Then
begin
VpfErro := '288';
ExecutaComandoSql(Aux,'CREATE TABLE OPITEMCADARCO( '+
' EMPFIL INTEGER NOT NULL, '+
' SEQORD INTEGER NOT NULL, '+
' SEQITE INTEGER NOT NULL, '+
' SEQPRO INTEGER NOT NULL, '+
' CODCOR INTEGER NULL, '+
' GROPRO INTEGER NULL, '+
' QTDFUS INTEGER NULL, '+
' NROFIO INTEGER NULL, '+
' NROMAQ INTEGER NULL, '+
' CODPRO CHAR(20) NULL, '+
' INDALG CHAR(1) NULL, '+
' INDPOL CHAR(1) NULL, '+
' DESENG CHAR(15) NULL, '+
' TITFIO CHAR(15) NULL, '+
' DESENC CHAR(50) NULL, '+
' QTDMET NUMERIC(15,3), '+
' QTDPRO NUMERIC(15,3), '+
' NUMTAB NUMERIC(5,2) , '+
' PRIMARY KEY (EMPFIL,SEQORD,SEQITE))');
ExecutaComandoSql(Aux,'create unique index OPITEMCADARCO_PK ON OPITEMCADARCO(EMPFIL,SEQORD,SEQITE)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 288');
end;
if VpaNumAtualizacao < 289 Then
begin
VpfErro := '289';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOCORPO '+
' ADD CODUSU INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 289');
end;
if VpaNumAtualizacao < 290 Then
begin
VpfErro := '290';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS '+
' ADD I_QTD_FUS INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 290');
end;
if VpaNumAtualizacao < 291 Then
begin
VpfErro := '291';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL '+
' ADD C_VER_DEV CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_FISCAL set C_VER_DEV = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 291');
end;
if VpaNumAtualizacao < 292 Then
begin
VpfErro := '292';
ExecutaComandoSql(Aux,'CREATE TABLE REVISAOOPEXTERNA( EMPFIL INTEGER NOT NULL, ' +
' SEQORD INTEGER NOT NULL, '+
' SEQCOL INTEGER NOT NULL, '+
' CODUSU INTEGER NOT NULL, '+
' DATREV DATETIME NOT NULL,'+
' PRIMARY KEY (EMPFIL,SEQORD,SEQCOL,CODUSU))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX REVISAOOPEXTERNA_PK ON REVISAOOPEXTERNA(EMPFIL,SEQORD,SEQCOL,CODUSU)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 292');
end;
if VpaNumAtualizacao < 293 Then
begin
VpfErro := '293';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS '+
' ADD C_BAT_TEA CHAR(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 293');
end;
if VpaNumAtualizacao < 294 Then
begin
VpfErro := '294';
ExecutaComandoSql(Aux,'ALTER TABLE ROMANEIOCORPO '+
' ADD NRONOT INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 294');
end;
if VpaNumAtualizacao < 295 Then
begin
VpfErro := '295';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS '+
' ADD I_TIP_FRE INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 295');
end;
if VpaNumAtualizacao < 296 Then
begin
VpfErro := '296';
ExecutaComandoSql(Aux,'ALTER TABLE CADEMPRESAS '+
' ADD I_ULT_PRO INTEGER NULL');
ExecutaComandoSql(Aux,'UPDATE CADEMPRESAS SET I_ULT_PRO = 0 ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 296');
end;
if VpaNumAtualizacao < 297 Then
begin
VpfErro := '297';
ExecutaComandoSql(Aux,'ALTER TABLE OPITEMCADARCO '+
' MODIFY GROPRO NUMERIC(8,2) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 297');
end;
if VpaNumAtualizacao < 298 Then
begin
VpfErro := '298';
ExecutaComandoSql(Aux,'CREATE TABLE OPITEMCADARCOMAQUINA( '+
' EMPFIL INTEGER NOT NULL, '+
' SEQORD INTEGER NOT NULL, '+
' SEQITE INTEGER NOT NULL, '+
' SEQMAQ INTEGER NOT NULL, '+
' CODMAQ INTEGER NOT NULL, '+
' QTDMET NUMERIC(15,3) NULL,'+
' QTDHOR CHAR(7) NULL,'+
' DATFIN DATETIME NULL,'+
' PRIMARY KEY(EMPFIL,SEQORD,SEQITE,SEQMAQ))');
ExecutaComandoSql(Aux,'Create unique index OPITEMCADARCOMAQUINA_PK ON OPITEMCADARCOMAQUINA(EMPFIL,SEQORD,SEQITE,SEQMAQ)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 298');
end;
if VpaNumAtualizacao < 299 Then
begin
VpfErro := '299';
ExecutaComandoSql(Aux,'ALTER TABLE MOVESTOQUEPRODUTOS' +
' add N_VLR_CUS NUMERIC(15,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 299');
end;
if VpaNumAtualizacao < 300 Then
begin
VpfErro := '300';
ExecutaComandoSql(Aux,'ALTER TABLE CADVENDEDORES' +
' add C_DES_EMA CHAR(50) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 300');
end;
if VpaNumAtualizacao < 301 Then
begin
VpfErro := '301';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS' +
' ADD N_VLR_DES NUMERIC(12,3) NULL, '+
' ADD N_PER_DES NUMERIC(12,3) NULL, '+
' ADD N_PER_COM NUMERIC(5,2) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 301');
end;
if VpaNumAtualizacao < 302 Then
begin
VpfErro := '302';
ExecutaComandoSql(Aux,'DROP INDEX MOVNOTASFISCAIS_PK');
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS drop PRIMARY KEY');
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS '+
' ADD PRIMARY KEY(I_EMP_FIL,I_SEQ_NOT,I_SEQ_MOV)');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX MOVNOTASFISCAIS_PK ON MOVNOTASFISCAIS(I_EMP_FIL,I_SEQ_NOT,I_SEQ_MOV)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 302');
end;
if VpaNumAtualizacao < 303 Then
begin
VpfErro := '303';
ExecutaComandoSql(Aux,'create index CadNotaFiscais_CP1 on CADNOTAFISCAIS(C_Ser_Not,I_NRO_NOT)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 303');
end;
VpfErro := AtualizaTabela1(VpaNumAtualizacao);
VpfSemErros := true;
except
on E : Exception do
begin
Aux.Sql.text := E.message;
Aux.Sql.SavetoFile('c:\ErroInicio.txt');
if Confirmacao(VpfErro + ' - Existe uma alteração para ser feita no banco de dados mas existem usuários'+
' utilizando o sistema, ou algum outro sistema sendo utilizado no seu computador, é necessário'+
' que todos os usuários saiam do sistema, para'+
' poder continuar. Deseja continuar agora?') then
Begin
VpfSemErros := false;
AdicionaSQLAbreTabela(Aux,'Select I_Ult_Alt from CFG_GERAL ');
VpaNumAtualizacao := Aux.FieldByName('I_Ult_Alt').AsInteger;
end
else
exit;
end;
end;
until VpfSemErros;
// FAbertura.painelTempo1.Fecha;
end;
{******************************************************************************}
function TAtualiza.AtualizaTabela1(VpaNumAtualizacao : Integer): String;
begin
result := '';
if VpaNumAtualizacao < 304 Then
begin
result := '304';
ExecutaComandoSql(Aux,'create index CADORCAMENTOS_CP1 on CADORCAMENTOS(D_DAT_ORC)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 304');
end;
if VpaNumAtualizacao < 305 Then
begin
result := '305';
ExecutaComandoSql(Aux,'ALTER TABLE CAD_DOC ADD C_FLA_FOR CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 305');
end;
if VpaNumAtualizacao < 306 Then
begin
result := '306';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS ADD N_PER_DES NUMERIC(5,2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 306');
end;
if VpaNumAtualizacao < 307 Then
begin
result := '307';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL '+
' ADD C_OBS_PED CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_FISCAL SET C_OBS_PED = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 307');
end;
if VpaNumAtualizacao < 308 Then
begin
result := '308';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS '+
' ADD C_NUM_PED CHAR(40) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 308');
end;
if VpaNumAtualizacao < 309 Then
begin
result := '309';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS '+
' ADD C_GER_COC CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 309');
end;
if VpaNumAtualizacao < 310 Then
begin
result := '310';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL '+
' ADD C_FIN_COT CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_FISCAL set C_FIN_COT = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 310');
end;
if VpaNumAtualizacao < 311 Then
begin
result := '311';
ExecutaComandoSql(Aux,'CREATE INDEX CADNOTAFISCAIS_CP2 ON CADNOTAFISCAIS(D_DAT_EMI)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 311');
end;
if VpaNumAtualizacao < 312 Then
begin
result := '312';
ExecutaComandoSql(Aux,'ALTER TABLE CADICMSESTADOS ADD I_COD_EMP INTEGER NULL');
ExecutaComandoSql(Aux,'UPDATE CADICMSESTADOS SET I_COD_EMP = 1');
ExecutaComandoSql(Aux,'ALTER TABLE CADICMSESTADOS MODIFY I_COD_EMP INTEGER NOT NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 312');
end;
if VpaNumAtualizacao < 313 Then
begin
result := '313';
ExecutaComandoSql(Aux,'drop index CADICMSESTADOS_PK ');
ExecutaComandoSql(Aux,'ALTER TABLE CADICMSESTADOS drop PRIMARY KEY');
ExecutaComandoSql(Aux,'ALTER TABLE CADICMSESTADOS ADD PRIMARY KEY(I_COD_EMP,C_COD_EST)');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX CADICMSESTADOS_PK ON CADICMSESTADOS(I_COD_EMP,C_COD_EST)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 313');
end;
if VpaNumAtualizacao < 314 Then
begin
result := '314';
ExecutaComandoSql(Aux,'alter table CFG_PRODUTO '+
' ADD I_OPE_ESA INTEGER NULL, '+
' ADD I_OPE_EEN INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 314');
end;
if VpaNumAtualizacao < 315 Then
begin
result := '315';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS'+
' ADD C_NOT_GER CHAR(1) NULL' );
ExecutaComandoSql(Aux,'update CADORCAMENTOS SET C_NOT_GER = ''S'' WHERE C_NRO_NOT IS NOT NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 315');
end;
if VpaNumAtualizacao < 316 Then
begin
result := '316';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS'+
' ADD N_VLR_TTD NUMERIC(15,3) NULL' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 316');
end;
if VpaNumAtualizacao < 317 Then
begin
result := '317';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO'+
' ADD C_BAI_CON CHAR(1) NULL' );
ExecutaComandoSql(Aux,'UPDATE CFG_PRODUTO SET C_BAI_CON = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 317');
end;
if VpaNumAtualizacao < 318 Then
begin
result := '318';
ExecutaComandoSql(Aux,'ALTER TABLE CADEMPRESAS'+
' ADD C_PLA_DEC CHAR(10) NULL' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 318');
end;
if VpaNumAtualizacao < 319 Then
begin
result := '319';
ExecutaComandoSql(Aux,'ALTER TABLE MOVINDICECONVERSAO'+
' MODIFY N_IND_COV NUMERIC(16,8)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 319');
end;
if VpaNumAtualizacao < 320 Then
begin
result := '320';
ExecutaComandoSql(Aux,'update MOVINDICECONVERSAO'+
' set N_IND_COV = 100 '+
' where C_UNI_COV = ''mt'''+
' AND C_UNI_ATU = ''cm''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 320');
end;
if VpaNumAtualizacao < 321 Then
begin
result := '321';
ExecutaComandoSql(Aux,'alter table CFG_PRODUTO'+
' ADD C_DES_ICO CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_PRODUTO set C_DES_ICO = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 321');
end;
if VpaNumAtualizacao < 322 Then
begin
result := '322';
ExecutaComandoSql(Aux,'alter table ORDEMPRODUCAOCORPO '+
' ADD INDPNO CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 322');
end;
if VpaNumAtualizacao < 323 Then
begin
result := '323';
ExecutaComandoSql(Aux,'CREATE TABLE TIPOCORTE ('+
' CODCORTE INTEGER NOT NULL, '+
' NOMCORTE CHAR(50) , '+
' PRIMARY KEY(CODCORTE))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX TIPOCORTE_PK ON TIPOCORTE(CODCORTE)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 323');
end;
if VpaNumAtualizacao < 324 Then
begin
result := '324';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS' +
' DROP C_DES_ACR, '+
' DROP C_VLR_PER, '+
' DROP N_DES_ACR, '+
' DROP N_VLR_PER');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 324');
end;
if VpaNumAtualizacao < 325 Then
begin
result := '325';
ExecutaComandoSql(Aux,'CREATE TABLE ORCAMENTOPARCIALCORPO ( ' +
' CODFILIAL INTEGER NOT NULL, '+
' LANORCAMENTO INTEGER NOT NULL, '+
' SEQPARCIAL INTEGER NOT NULL, '+
' DATPARCIAL DATETIME,' +
' PRIMARY KEY(CODFILIAL,LANORCAMENTO,SEQPARCIAL))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX ORCAMENTOPARCIALCORPO_PK ON ORCAMENTOPARCIALCORPO(CODFILIAL,LANORCAMENTO,SEQPARCIAL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 325');
end;
if VpaNumAtualizacao < 326 Then
begin
result := '326';
ExecutaComandoSql(Aux,'CREATE TABLE ORCAMENTOPARCIALITEM ( ' +
' CODFILIAL INTEGER NOT NULL, '+
' LANORCAMENTO INTEGER NOT NULL, '+
' SEQPARCIAL INTEGER NOT NULL, '+
' SEQMOVORCAMENTO INTEGER NOT NULL,' +
' QTDPARCIAL NUMERIC(13,4),'+
' PRIMARY KEY(CODFILIAL,LANORCAMENTO,SEQPARCIAL,SEQMOVORCAMENTO))');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX ORCAMENTOPARCIALITEM_PK ON ORCAMENTOPARCIALITEM(CODFILIAL,LANORCAMENTO,SEQPARCIAL,SEQMOVORCAMENTO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 326');
end;
if VpaNumAtualizacao < 327 Then
begin
result := '327';
ExecutaComandoSql(Aux,'ALTER TABLE CADEMPRESAS' +
' ADD I_BOL_PAD INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 327');
end;
if VpaNumAtualizacao < 328 Then
begin
result := '328';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO' +
' ADD I_OPE_EXE INTEGER NULL,'+
' ADD I_OPE_EXS INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 328');
end;
if VpaNumAtualizacao < 329 Then
begin
result := '329';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOCORPO ' +
' ADD CODCRT INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 329');
end;
if VpaNumAtualizacao < 330 Then
begin
result := '330';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR ' +
' ADD C_COD_NAT CHAR(10) NULL,'+
' ADD I_SEQ_NAT INTEGER NULL, '+
' ADD I_QTD_PAR INTEGER NULL, '+
' ADD I_PRA_DIA INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 330');
end;
if VpaNumAtualizacao < 331 Then
begin
result := '331';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAISFOR ' +
' ADD C_NOM_COR CHAR(50) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 331');
end;
if VpaNumAtualizacao < 332 Then
begin
result := '332';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO ' +
' ADD I_REC_PAD INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 332');
end;
if VpaNumAtualizacao < 333 Then
begin
result := '333';
ExecutaComandoSql(Aux,'ALTER TABLE LOG ' +
' ADD DES_INFORMACOES LONG VARCHAR NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 333');
end;
if VpaNumAtualizacao < 334 Then
begin
result := '334';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS ' +
' MODIFY C_DES_COR CHAR(50) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 334');
end;
if VpaNumAtualizacao < 335 Then
begin
result := '335';
ExecutaComandoSql(Aux,'ALTER TABLE MOVCONTASARECEBER ' +
' ADD C_COB_EXT CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 335');
end;
if VpaNumAtualizacao < 336 Then
begin
result := '336';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ' +
' ADD I_COD_OPE INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 336');
end;
if VpaNumAtualizacao < 337 Then
begin
result := '337';
ExecutaComandoSql(Aux,'UPDATE CADORCAMENTOS ' +
' SET I_COD_OPE = 1101');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 337');
end;
if VpaNumAtualizacao < 338 Then
begin
result := '338';
ExecutaComandoSql(Aux,'CREATE TABLE REL_PRODUTO_VENDIDO_MES ' +
'( SEQ_PRODUTO INTEGER NOT NULL,'+
' QTD_VENDIDA NUMERIC(15,3),'+
' UM_PRODUTO CHAR(2), '+
' PRIMARY KEY (SEQ_PRODUTO))');
ExecutaComandoSql(Aux,'Create unique index REL_PRODUTO_VENDIDO_MES_PK ON REL_PRODUTO_VENDIDO_MES(SEQ_PRODUTO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 338');
end;
if VpaNumAtualizacao < 339 Then
begin
result := '339';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ' +
' ADD C_IMP_NOR CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FISCAL SET C_IMP_NOR = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 339');
end;
if VpaNumAtualizacao < 340 Then
begin
result := '340';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ' +
' ADD C_FIN_COT CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADFILIAIS SET C_FIN_COT = (SELECT C_FIN_COT FROM CFG_FISCAL)');
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ' +
' DROP C_FIN_COT');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 340');
end;
if VpaNumAtualizacao < 341 Then
begin
result := '341';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ' +
' ADD C_EXC_FIC CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADFILIAIS SET C_EXC_FIC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 341');
end;
if VpaNumAtualizacao < 342 Then
begin
result := '342';
ExecutaComandoSql(Aux,'CREATE TABLE METROFATURADOITEM (' +
' EMPFIL INTEGER NOT NULL,'+
' SEQROM INTEGER NOT NULL,'+
' FILNOT INTEGER NOT NULL,'+
' SEQNOT INTEGER NOT NULL,'+
' PRIMARY KEY (EMPFIL,SEQROM,FILNOT,SEQNOT))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 342');
end;
if VpaNumAtualizacao < 343 Then
begin
result := '343';
ExecutaComandoSql(Aux,'Alter Table CFG_PRODUTO ' +
' ADD C_EST_CEN CHAR(1),'+
' ADD I_FIL_EST INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 343');
end;
if VpaNumAtualizacao < 344 Then
begin
result := '344';
ExecutaComandoSql(Aux,'Alter Table CFG_PRODUTO ' +
' DROP C_PAG_PRO');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 344');
end;
if VpaNumAtualizacao < 345 Then
begin
result := '345';
ExecutaComandoSql(Aux,'CREATE INDEX ORDEMPRODUCAOCOPRO_FK5 ON ORDEMPRODUCAOCORPO(DATENP) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 345');
end;
if VpaNumAtualizacao < 346 Then
begin
result := '346';
ExecutaComandoSql(Aux,'Alter table CADPRODUTOS ADD I_TAB_TRA INTEGER NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 346');
end;
if VpaNumAtualizacao < 347 Then
begin
result := '347';
ExecutaComandoSql(Aux,'Alter table CADPRODUTOS ADD C_TIT_FIO CHAR(15) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 347');
end;
if VpaNumAtualizacao < 348 Then
begin
result := '348';
ExecutaComandoSql(Aux,'Alter table CADFILIAIS ADD C_JUN_COM CHAR(50) NULL, '+
' ADD C_CPF_RES CHAR(20) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 348');
end;
if VpaNumAtualizacao < 349 Then
begin
result := '349';
ExecutaComandoSql(Aux,'Alter table ORDEMPRODUCAOCORPO ADD DATFIM DATETIME NULL, '+
' ADD DATPCO DATETIME NULL, '+
' ADD DATFAT DATETIME NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 349');
end;
if VpaNumAtualizacao < 350 Then
begin
result := '350';
ExecutaComandoSql(Aux,'UPDATE ORDEMPRODUCAOCORPO OP '+
' SET DATPCO = ''2005/01/01'''+
' WHERE EXISTS (SELECT * FROM COLETAOPCORPO COL '+
' WHERE OP.EMPFIL = COL.EMPFIL '+
' AND OP.SEQORD = COL.SEQORD)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 350');
end;
if VpaNumAtualizacao < 351 Then
begin
result := '351';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL '+
' ADD I_FOR_EXP INTEGER ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 351');
end;
if VpaNumAtualizacao < 352 Then
begin
result := '352';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASARECEBER '+
' ADD I_SEQ_PAR INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 352');
end;
if VpaNumAtualizacao < 353 Then
begin
result := '353';
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOPARCIALCORPO '+
' ADD VALTOTAL NUMERIC(15,3) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 353');
end;
end;
end.
|
unit uLocalization;
interface
uses
Windows, Dialogs, Forms, IniFiles, SysUtils;
function LongFileName(ShortName: String): String;
function GetCurrentLocaleID: LCID;
function LoadNewResourceModules(ALocaleId: LCId): Longint;
function GetLocaleNameById(LocaleId: LCID): String; //! Возможно не поддерживается в Windows 7 и выше
implementation
function LongFileName(ShortName: String): String;
var
SR: TSearchRec;
Begin
Result := '';
If (pos ('\\', ShortName) + pos ('*', ShortName) +
pos ('?', ShortName) <> 0) Or Not FileExists(ShortName) Then
Begin
{ ignore NetBIOS name, joker chars and invalid file names }
Exit;
End;
While FindFirst(ShortName, faAnyFile, SR) = 0 Do
Begin
{ next part as prefix }
Result := '\' + SR.Name + Result;
SysUtils.FindClose(SR); { the SysUtils, not the WinProcs procedure! }
{ directory up (cut before '\') }
ShortName := ExtractFileDir (ShortName);
If length (ShortName) <= 2 Then
Begin
Break; { ShortName contains drive letter followed by ':' }
End;
End;
Result := ExtractFileDrive (ShortName) + Result;
end;
function GetCurrentLocaleID: LCID;
var
IniFileName: String;
IniFile: TIniFile;
Begin
Result := 25;
IniFileName := ExtractFilePath(Application.ExeName) + 'locale.ini';
if FileExists(IniFileName) then
begin
IniFile := TIniFile.Create(IniFileName);
try
Result := IniFile.ReadInteger('LOCALE', 'current_locale_id', 25);
finally
IniFile.Free;
end;
end;
End;
function LoadNewResourceModules(ALocaleId: LCId): Longint;
var
LocaleName: WideString;
LocaleFilesPath: WideString;
CurModule: PLibModule;
CurFileName: WideString;
CurResFileName: WideString;
// locale: LCID;
NewInst: Longint;
Begin
Result := 0;
// locale := GetCurrentLocaleID;
if ALocaleId > 0 then
begin
SetLength(LocaleName, 3);
GetLocaleInfoW(ALocaleId, LOCALE_SABBREVLANGNAME, @LocaleName[1], Length(LocaleName) * 2);
if LocaleName[1] <> #0 then
begin
LocaleFilesPath := ExtractFilePath(ParamStr(0)) + LocaleName + '\';
CurModule := LibModuleList;
while CurModule <> nil do
begin
CurFileName := LongFileName(GetModuleName(CurModule.Instance));
CurResFileName := LocaleFilesPath + ChangeFileExt(ExtractFileName(CurFileName), '.' + LocaleName);
if FileExists(CurResFileName) then
begin
NewInst := LoadLibraryExW(PWideChar(CurResFileName), 0, LOAD_LIBRARY_AS_DATAFILE);
if NewInst <> 0 then
begin
if CurModule.ResInstance <> CurModule.Instance then
FreeLibrary(CurModule.ResInstance);
CurModule.ResInstance := NewInst;
end;
end;
CurModule := CurModule.Next;
end;
end;
end;
End;
function GetLocaleNameById(LocaleId: LCID): String; //! Возможно не поддерживается в Windows 7 и выше
var
LocaleName: String;
begin
SetLength(LocaleName, GetLocaleInfo(LocaleId, LOCALE_SLANGUAGE, nil, 0));
GetLocaleInfo(LocaleId, LOCALE_SLANGUAGE, @LocaleName[1], Length(LocaleName));
Result := Trim(LocaleName);
end;
END.
|
{$mode objfpc}{$H+}{$J-}
{$R+}
program snakeProgram;
uses
ncurses,
sysutils;
const
SNAKE_CHAR = 'X';
FOOD_CHAR = 'O';
type
TPos = array [ 0..1 ] of integer;
snakeArray = array of TPos;
TDir = (drUp, drRight, drDown, drLeft);
operator = (pos1, pos2 : TPos) b : boolean;
begin
Result := (pos1[0] = pos2[0]) and (pos1[1] = pos2[1]);
end;
procedure initGame;
begin
Randomize;
initscr();
timeout(1);
raw();
keypad(stdscr, true);
attroff(A_INVIS);
curs_set(0);
noecho();
end;
function initSnake (const snakeLength: Integer): snakeArray;
var
I: Integer;
begin
setlength(Result, snakeLength);
for I := 0 to snakeLength - 1 do
begin
Result[I][0] := 10 - I;
Result[I][1] := 5;
end;
end;
procedure setSnakeDir(const ch: LongInt; var snakeDir: TDir);
begin
case ch of
KEY_UP: snakeDir := drUp;
KEY_DOWN: snakeDir := drDown;
KEY_LEFT: snakeDir := drLeft;
KEY_RIGHT: snakeDir := drRight;
end; // TODO : prevent player from being able to turn around
end;
procedure moveSnake(var snake: snakeArray; const snakeLength: Integer; const snakeDir: TDir);
var
I: Integer;
begin
I := snakeLength - 1;
while I > 0 do
begin
snake[I] := snake[I - 1];
I := I - 1;
end;
case snakeDir of
drUp: snake[0][1] := snake[0][1] - 1;
drDown: snake[0][1] := snake[0][1] + 1;
drLeft: snake[0][0] := snake[0][0] - 1;
drRight: snake[0][0] := snake[0][0] + 1;
end;
end;
function checkForDeath (const snake: snakeArray; const snakeLength: Integer) : Bool;
var
I: Integer;
begin
for I := 1 to snakeLength - 1 do
if snake[I] = snake[0] then
Exit(true);
Exit(false);
end;
procedure drawSnake(const snake: array of TPos);
var
snkBlock: TPos;
begin
for snkBlock in snake do
mvprintw(snkBlock[1], snkBlock[0], SNAKE_CHAR);
end;
function getRandomPos : TPos;
begin
Result[0] := Random(34); // TODO : needs to use map coordinates
Result[1] := Random(34);
end;
var
snake: snakeArray;
snakeLength: Integer;
snakeDir: TDir;
foodPos: TPos;
ch: LongInt;
begin
snakeLength := 6;
snakeDir := drRight;
initGame();
snake := initSnake(snakeLength);
foodPos := getRandomPos();
repeat
ch := getch();
setSnakeDir(ch, snakeDir);
if (snake[0] = foodPos) then
begin
snakeLength := snakeLength + 1;
setlength(snake, snakeLength);
foodPos := getRandomPos();
end;
if checkForDeath(snake, snakeLength) = True then
break;
moveSnake(snake, snakeLength, snakeDir);
drawSnake(snake);
mvprintw(foodPos[1], foodPos[0], FOOD_CHAR);
refresh();
Clear();
Sleep(100); // TODO : change, for obvious reasons
until (ch = KEY_NPAGE);
endwin();
end.
|
unit HKSqlStringGrid;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Grids,
ZDataset;
type
{ THKSqlStringGrid }
TOnWriteCell=Procedure(aSender:TObject; aFieldName, aValue:String; var aResult:String) of object;
THKSqlStringGrid = class(TStringGrid)
private
FEvenColor: TColor;
FOddColor: TColor;
FOnWriteCell: TOnWriteCell;
FzQuery: TZQuery;
procedure SetEvenColor(AValue: TColor);
procedure SetOddColor(AValue: TColor);
procedure SetOnWriteCell(AValue: TOnWriteCell);
procedure SetzQuery(AValue: TZQuery);
protected
Function DoPrepareField:TStringArray;
Function DoWriteCell(aFieldName, aValue:String):String;
procedure DoPrepareCanvas(aCol, aRow: Integer; aState: TGridDrawState);
override;
public
procedure Refresh;
constructor Create(AOwner: TComponent); override;
published
property OddColor:TColor read FOddColor write SetOddColor;
property EvenColor:TColor read FEvenColor write SetEvenColor;
property zQuery:TZQuery read FzQuery write SetzQuery;
property OnWriteCell:TOnWriteCell read FOnWriteCell write SetOnWriteCell;
end;
procedure Register;
implementation
procedure Register;
begin
{$I hksqlstringgrid_icon.lrs}
RegisterComponents('HKCompPacks',[THKSqlStringGrid]);
end;
{ THKSqlStringGrid }
procedure THKSqlStringGrid.SetzQuery(AValue: TZQuery);
begin
if FzQuery=AValue then Exit;
FzQuery:=AValue;
end;
procedure THKSqlStringGrid.SetOnWriteCell(AValue: TOnWriteCell);
begin
if FOnWriteCell=AValue then Exit;
FOnWriteCell:=AValue;
end;
procedure THKSqlStringGrid.SetEvenColor(AValue: TColor);
begin
if FEvenColor=AValue then Exit;
FEvenColor:=AValue;
end;
procedure THKSqlStringGrid.SetOddColor(AValue: TColor);
begin
if FOddColor=AValue then Exit;
FOddColor:=AValue;
end;
function THKSqlStringGrid.DoPrepareField: TStringArray;
var
aaa: Integer;
str: String;
begin
RowCount:=1;
FixedCols:=1;
FixedRows:=1;
ColCount:=zQuery.FieldCount+1;
SetLength(Result, ColCount);
Cells[0, 0]:='#';
for aaa:=0 to zQuery.FieldCount-1 do
begin
str:=zQuery.Fields[aaa].FieldName;
Cells[aaa+1, 0]:=str;
Result[aaa]:=str;
end;
AutoFillColumns:=True;
//Options:=;
end;
function THKSqlStringGrid.DoWriteCell(aFieldName, aValue: String): String;
begin
Result:=aValue;
if Assigned(OnWriteCell)then OnWriteCell(Self, aFieldName, aValue, Result);
end;
procedure THKSqlStringGrid.DoPrepareCanvas(aCol, aRow: Integer;
aState: TGridDrawState);
var //isNegative:Boolean;
aaa: Integer;
begin
inherited DoPrepareCanvas(aCol, aRow, aState);
if aRow=0 then exit;
Canvas.Font.Color:=clBlack;
if (aRow mod 2)=1 then
begin
Canvas.Brush.Color:=OddColor;
end
else
begin
Canvas.Brush.Color:=EvenColor;
end;
end;
procedure THKSqlStringGrid.Refresh;
var
aaa, bbb: Integer;
colNames: TStringArray;
str, vname: String;
begin
RowCount:=1;
if Assigned(zQuery) then
begin
with zQuery do
begin
if Active then Close;
Open;
colNames:=DoPrepareField;
aaa:=1;
while not EOF do
begin
RowCount:=RowCount+1;
Cells[0, aaa]:=RecNo.ToString;
for bbb:=0 to Length(colNames)-1 do
begin
if colNames[bbb]='' then Continue;
vname:=colNames[bbb];
str:=FieldByName(vname).AsString;
Cells[bbb+1, aaa]:=DoWriteCell(vname, str);
end;
Inc(aaa);
Next;
end;
end;
end;
end;
constructor THKSqlStringGrid.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
OddColor:=$00FEFEFE;
EvenColor:=$00EFEFEF;
end;
end.
|
unit rhlELF;
interface
uses
rhlCore;
type
{ TrhlELF }
TrhlELF = class(TrhlHash)
private
m_hash: DWord;
protected
procedure UpdateBytes(const ABuffer; ASize: LongWord); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlELF }
procedure TrhlELF.UpdateBytes(const ABuffer; ASize: LongWord);
var
b: PByte;
g: DWord;
begin
b := @ABuffer;
while ASize > 0 do
begin
m_hash := (m_hash shl 4) + b^;
g := m_hash and $f0000000;
if (g <> 0) then
m_hash := m_hash xor (g shr 24);
m_hash := m_hash and (not g);
Inc(b);
Dec(ASize);
end;
end;
constructor TrhlELF.Create;
begin
HashSize := 4;
BlockSize := 1;
end;
procedure TrhlELF.Init;
begin
inherited Init;
m_hash := 0;
end;
procedure TrhlELF.Final(var ADigest);
begin
Move(m_hash, ADigest, 4);
end;
end.
|
unit Auxiliary;
interface
uses
Graphics;
function ColorNameToColor(AString: String): TColor;
function ColorToColorName(AColor: TColor): String;
implementation
type
TPair =
record
N: String;
C: TColor;
end;
const
ColorTable: array[0..15] of TPair =
( (N: 'clAqua' ; C: clAqua)
, (N: 'clBlack' ; C: clBlack)
, (N: 'clBlue' ; C: clBlue)
, (N: 'clCream' ; C: clCream)
, (N: 'clFuchsia' ; C: clFuchsia)
, (N: 'clGreen' ; C: clGreen)
, (N: 'clLime' ; C: clLime)
, (N: 'clMaroon' ; C: clMaroon)
, (N: 'clMoneyGreen'; C: clMoneyGreen)
, (N: 'clNavy' ; C: clNavy)
, (N: 'clOlive' ; C: clOlive)
, (N: 'clPurple' ; C: clPurple)
, (N: 'clRed' ; C: clRed)
, (N: 'clTeal' ; C: clTeal)
, (N: 'clYellow' ; C: clYellow)
, (N: 'clWhite' ; C: clWhite)
);
clDefaultColor = clBlack;
clDefaultName = 'clBlack';
function ColorNameToColor(AString: String): TColor;
var
I: Integer;
begin
Result := clDefaultColor;
for I := 0 to 15 do
if ColorTable[I].N = AString
then Result := ColorTable[I].C;
end;
function ColorToColorName(AColor: TColor): String;
var
I: Integer;
begin
Result := clDefaultName;
for I := 0 to 15 do
if ColorTable[I].C = AColor
then Result := ColorTable[I].N;
end;
end.
|
Program BalancedParentheses;
const
MAX = 100;
var
arr : Array[1..MAX] of boolean; { 0 = '(' 1 = ')' }
length : integer;
pairs : integer;
procedure print();
var
i : integer;
begin
for i := 1 to pairs*2 do
if arr[i] then
write(')')
else
write('(');
writeln();
end;
procedure recc(open, closed, i: integer);
begin
if (open = pairs) and (closed = pairs) then
print()
else begin
if open < pairs then begin
arr[i] := False;
recc(open+1, closed, i+1);
end;
if closed < open then begin
arr[i] := True;
recc(open, closed+1, i+1);
end;
end;
end;
begin
read(length);
pairs := length div 2;
recc(0,0,1);
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Медиа-сервер }
{ }
{ <Область> 16:Медиа-контроль }
{ }
{ <Задача> Медиа-источник, предоставляющий возможность объединять данные }
{ из нескольких других источников }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 14.01.2011 }
{ }
{ <Примечание> Нет примечаний. }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaServer.Stream.Source.InPointsRetransmitter;
interface
uses Windows, SysUtils, Classes, SyncObjs, Types,
MediaServer.Stream.Source,
MediaProcessing.Definitions,MediaServer.Definitions, MediaServer.InPoint;
type
//Класс, выполняющий непосредственно получение данных (видеопотока) из камеры
TMediaServerSourceInPointsRetransmitter = class (TMediaServerSource)
private
FInPoint: TMediaServerInPoint;
FOpened: boolean;
procedure OnFrameReceived(const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize:cardinal;
aInfo: pointer; aInfoSize: cardinal);
procedure OnConnectionOkHandler(aSender: TMediaServerInPoint);
procedure OnConnectionFailedHandler (aSender: TMediaServerInPoint; aError: Exception);
protected
function GetStreamType(aMediaType: TMediaType): TStreamType; override;
public
constructor Create(aInPoint: TMediaServerInPoint); overload;
destructor Destroy; override;
procedure DoOpen(aSync: boolean); override;
procedure DoClose; override;
procedure WaitWhileConnecting(aTimeout: integer); override;
function Opened: Boolean; override;
function Connecting: boolean; override;
function Name: string; override;
function DeviceType: string; override;
function ConnectionString: string; override;
function StreamInfo: TBytes; override;
function PtzSupported: boolean; override;
property InPoint: TMediaServerInPoint read FInPoint;
end;
implementation
uses Math,Forms,MediaServer.Workspace,uTrace,uBaseUtils, MediaStream.FramerFactory;
type
TMediaStreamDataSink = class (TInterfacedObject,IMediaStreamDataSink)
private
FOwner: TMediaServerSourceInPointsRetransmitter;
FInPoint:TMediaServerInPoint;
FChannel: integer;
public
constructor Create(aOwner: TMediaServerSourceInPointsRetransmitter; aInPoint:TMediaServerInPoint; aChannel: integer);
destructor Destroy; override;
procedure OnData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal);
end;
{ TMediaServerSourceInPointsRetransmitter }
constructor TMediaServerSourceInPointsRetransmitter.Create(aInPoint: TMediaServerInPoint);
var
aSink: IMediaStreamDataSink;
begin
Create(-1);
//UsePrebuffer:=false;
FInPoint:=aInPoint;
aSink:=TMediaStreamDataSink.Create(self,FInPoint,0);
FInPoint.DataSinks.AddSink(aSink);
end;
destructor TMediaServerSourceInPointsRetransmitter.Destroy;
begin
inherited;
FInPoint:=nil;
//FInPointSinks:=nil;
end;
function TMediaServerSourceInPointsRetransmitter.DeviceType: string;
begin
result:='Мультиплексор';
end;
function TMediaServerSourceInPointsRetransmitter.Name: string;
begin
result:='Input Point Retransmitter';
end;
procedure TMediaServerSourceInPointsRetransmitter.OnConnectionFailedHandler(
aSender: TMediaServerInPoint; aError: Exception);
begin
DoConnectionFailed(aError);
end;
procedure TMediaServerSourceInPointsRetransmitter.OnConnectionOkHandler(
aSender: TMediaServerInPoint);
begin
DoConnectionOK;
end;
procedure TMediaServerSourceInPointsRetransmitter.OnFrameReceived(
const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize:cardinal;
aInfo: pointer; aInfoSize: cardinal);
begin
DoDataReceived(aFormat, aData,aDataSize, aInfo,aInfoSize);
end;
procedure TMediaServerSourceInPointsRetransmitter.DoOpen(aSync: boolean);
begin
if Opened then
exit;
FInPoint.OnConnectionOk2:=OnConnectionOkHandler;
FInPoint.OnConnectionFailed2:=OnConnectionFailedHandler;
FOpened:=true;
if not FInPoint.Opened then
begin
FInPoint.Open(aSync);
end
else begin
DoConnectionOK;
end;
end;
procedure TMediaServerSourceInPointsRetransmitter.DoClose;
begin
FInPoint.OnConnectionOk2:=nil;
FInPoint.OnConnectionFailed2:=nil;
FOpened:=false;
end;
function TMediaServerSourceInPointsRetransmitter.GetStreamType(aMediaType: TMediaType): TStreamType;
begin
result:=FInPoint.StreamTypes[aMediaType];
end;
function TMediaServerSourceInPointsRetransmitter.Connecting: boolean;
begin
result:=FOpened and FInPoint.Source.Connecting;
end;
function TMediaServerSourceInPointsRetransmitter.ConnectionString: string;
begin
result:=FInPoint.Name;
end;
function TMediaServerSourceInPointsRetransmitter.Opened: Boolean;
begin
result:=FOpened and FInPoint.Opened;
end;
function TMediaServerSourceInPointsRetransmitter.StreamInfo: TBytes;
begin
result:=nil;
end;
function TMediaServerSourceInPointsRetransmitter.PtzSupported: boolean;
begin
result:=FInPoint.Source.PtzSupported;
end;
procedure TMediaServerSourceInPointsRetransmitter.WaitWhileConnecting(aTimeout: integer);
begin
inherited;
FInPoint.WaitWhileConnecting;
end;
{ TMediaStreamDataSink }
constructor TMediaStreamDataSink.Create(aOwner: TMediaServerSourceInPointsRetransmitter; aInPoint: TMediaServerInPoint; aChannel: integer);
begin
inherited Create;
FOwner:=aOwner;
FInPoint:=aInPoint;
FChannel:=aChannel;
end;
destructor TMediaStreamDataSink.Destroy;
begin
FOwner:=nil;
FInPoint:=nil;
inherited;
end;
procedure TMediaStreamDataSink.OnData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal);
var
aFormat2: TMediaStreamDataHeader;
begin
if FOwner<>nil then
if FInPoint<>nil then
begin
aFormat2:=aFormat;
aFormat2.Channel:=FChannel;
if FOwner.FOpened then
FOwner.OnFrameReceived(aFormat2,aData,aDataSize,aInfo,aInfoSize);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC physical layer base classes }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Phys;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.Classes, System.SysUtils, System.SyncObjs, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Util,
FireDAC.Stan.Error, FireDAC.Stan.Factory,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator,
FireDAC.UI.Intf;
type
TFDPhysManager = class;
TFDPhysDriver = class;
TFDPhysDriverLink = class;
TFDPhysDriverService = class;
TFDPhysConnectionHost = class;
TFDPhysConnection = class;
TFDPhysTransaction = class;
TFDPhysEventThread = class;
TFDPhysEventMessage = class;
TFDPhysEventStartMessage = class;
TFDPhysEventStopMessage = class;
TFDPhysEventAlerter = class;
TFDPhysCommand = class;
TFDPhysDriverClass = class of TFDPhysDriver;
TFDPhysConnectionClass = class of TFDPhysConnection;
TFDPhysCliHandles = record
FDriverCliHandles: Pointer;
FTxSerialID: LongWord;
FDriverID: array [0 .. 10] of Char;
end;
PFDPhysCliHandles = ^TFDPhysCliHandles;
TFDPhysFindObjMode = (fomNone, fomMBActive, fomMBNotInactive, fomIfActive);
TFDPhysRecoveryFlags = set of (rfInRecovery, rfEmergencyClose);
TFDPhysManager = class(TFDObject,
{$IFNDEF FireDAC_SkipIUnk} IUnknown, {$ENDIF}
IFDStanObject, IFDStanOptions, IFDPhysManager, IFDPhysManagerMetadata)
private
FLock: TCriticalSection;
FDriverDefs: IFDStanDefinitions;
FDriverIDs: TFDStringList;
FRDBMSNames: TFDStringList;
FDriverClasses: TFDClassList;
FDriverList: TFDPtrList;
FDriverLinkList: TFDObjList;
FState: TFDPhysManagerState;
FConnectionDefs: IFDStanConnectionDefs;
FUpdateDriverIDs: Boolean;
procedure CheckActive;
procedure CheckActiveOrStoping;
procedure CleanupDrivers;
procedure CleanupManager;
function FindDriverClass(const ADriverID: String): TFDPhysDriverClass;
function DriverByID(const ADriverID: String;
AMode: TFDPhysFindObjMode; ARequired: Boolean): TFDPhysDriver;
procedure InternalClose(ATerminate, AWaitForClose: Boolean);
procedure Shutdown;
procedure ErrorDriverNotReg(const ADriverID, ABaseDriverID: String);
procedure UpdateDriverIDs;
procedure CheckUpdateDriverIDs;
protected
FOptions: IFDStanOptions;
// IUnknown
function _Release: Integer; stdcall;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
// IFDStanObject
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
// IFDStanOptions
property Options: IFDStanOptions read FOptions implements IFDStanOptions;
// IFDPhysManager
procedure CreateDriver(const ADriverID: String;
out ADrv: IFDPhysDriver; AIntfRequired: Boolean = True);
procedure CreateConnection(const AConnectionDef: IFDStanConnectionDef;
out AConn: IFDPhysConnection; AIntfRequired: Boolean = True); overload;
procedure CreateConnection(const AConDefName: String;
out AConn: IFDPhysConnection; AIntfRequired: Boolean = True); overload;
procedure CreateMetadata(out AMeta: IFDPhysManagerMetadata);
procedure CreateDefaultConnectionMetadata(out AConMeta: IFDPhysConnectionMetadata);
procedure Open;
procedure Close(AWait: Boolean = False);
procedure CloseConnectionDef(const AConnectionDef: IFDStanConnectionDef);
procedure RefreshMetadataCache;
function DriverIDFromSharedCliHandle(ASharedCliHandle: Pointer): String;
procedure RegisterRDBMSKind(AKind: TFDRDBMSKind; const AName: String);
procedure RegisterDriverClass(ADriverClass: TClass);
procedure UnregisterDriverClass(ADriverClass: TClass);
function GetDriverDefs: IFDStanDefinitions;
function GetConnectionDefs: IFDStanConnectionDefs;
function GetOptions: IFDStanOptions;
function GetState: TFDPhysManagerState;
// IFDPhysManagerMetadata
function GetDriverCount: Integer;
function GetDriverID(AIndex: Integer): String;
function GetBaseDriverID(AIndex: Integer): String; overload;
function GetBaseDriverID(const ADriverID: String): String; overload;
function GetBaseDriverClass(const ADriverID: String): TClass;
function GetRDBMSKind(const ADriverID: String): TFDRDBMSKind;
function GetRDBMSName(AKind: TFDRDBMSKind): String;
procedure GetRDBMSNames(ANames: TStrings);
procedure CreateDriverMetadata(const ADriverID: String; out AMeta: IFDPhysDriverMetadata);
public
procedure Initialize; override;
destructor Destroy; override;
function FindDriverLink(const ADriverID: String): TFDPhysDriverLink;
end;
TFDPhysDriver = class(TInterfacedObject,
IFDStanObject, IFDPhysDriver, IFDPhysDriverMetadata)
private
FLock: TCriticalSection;
FDriverID: String;
FParams: IFDStanDefinition;
FState: TFDPhysDriverState;
FManager: TFDPhysManager;
FConnHostList: TFDPtrList;
FConnectionList: TFDPtrList;
FMessages: TFDLog;
FUsageCount: Integer;
procedure Stop;
procedure Shutdown;
function FindConnectionHost(
const AConnectionDef: IFDStanConnectionDef): TFDPhysConnectionHost;
protected
// IFDStanObject
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
// IFDPhysDriver
function GetDriverID: String;
function GetBaseDrvID: String;
function GetDbKind: TFDRDBMSKind;
function GetCliObj: Pointer; virtual;
function GetMessages: TStrings;
procedure Load;
procedure Unload;
procedure Employ;
procedure Vacate;
procedure CreateConnection(const AConnectionDef: IFDStanConnectionDef;
out AConn: IFDPhysConnection);
procedure CloseConnectionDef(const AConnectionDef: IFDStanConnectionDef);
procedure CreateMetadata(out ADrvMeta: IFDPhysDriverMetadata);
procedure CreateConnectionWizard(out AWizard: IFDPhysDriverConnectionWizard);
function GetConnectionCount: Integer;
function GetConnections(AIndex: Integer): IFDPhysConnection;
function GetState: TFDPhysDriverState;
// IFDPhysDriverMetadata
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; virtual;
function GetBaseDrvDesc: String;
// overridable by descendants
class function GetBaseDriverID: String; virtual;
class function GetBaseDriverDesc: String; virtual;
/// <summary> Returns database kind of this driver. The descendant classes must override this method. </summary>
class function GetRDBMSKind: TFDRDBMSKind; virtual;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; virtual;
procedure InternalLoad; virtual; abstract;
procedure InternalUnload; virtual; abstract;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; virtual; abstract;
procedure GetVendorParams(out AHome, ALib: String);
public
constructor Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); virtual;
destructor Destroy; override;
property DriverID: String read FDriverID;
property BaseDriverID: String read GetBaseDrvID;
/// <summary> Returns database kind of this driver. </summary>
property RDBMSKind: TFDRDBMSKind read GetDbKind;
property State: TFDPhysDriverState read FState;
property Manager: TFDPhysManager read FManager;
property Params: IFDStanDefinition read FParams;
property Messages: TFDLog read FMessages;
end;
TFDPhysDriverLink = class(TFDComponent)
private
FDriverID: String;
FVendorHome: String;
FVendorLib: String;
FOnDriverDestroying: TNotifyEvent;
FOnDriverCreated: TNotifyEvent;
FServiceList: TFDObjList;
procedure SetDriverID(const AValue: String);
function GetDriverIntf: IFDPhysDriver;
function GetDriverState: TFDPhysDriverState;
function GetServices(AIndex: Integer): TFDPhysDriverService;
function GetServicesCount: Integer;
procedure SetupDef(const AParams: IFDStanDefinition);
procedure SetUpdateDriverIDs;
protected
function GetActualDriverID: String; virtual;
function GetBaseDriverID: String; virtual;
function IsConfigured: Boolean; virtual;
procedure ApplyTo(const AParams: IFDStanDefinition); virtual;
procedure DoDriverCreated; virtual;
procedure DoDriverDestroying; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Release;
property DriverState: TFDPhysDriverState read GetDriverState;
property DriverIntf: IFDPhysDriver read GetDriverIntf;
property ActualDriverID: String read GetActualDriverID;
property ServicesCount: Integer read GetServicesCount;
property Services[AIndex: Integer]: TFDPhysDriverService read GetServices;
published
property BaseDriverID: String read GetBaseDriverID;
property DriverID: String read FDriverID write SetDriverID;
property VendorHome: String read FVendorHome write FVendorHome;
property VendorLib: String read FVendorLib write FVendorLib;
property OnDriverCreated: TNotifyEvent read FOnDriverCreated write FOnDriverCreated;
property OnDriverDestroying: TNotifyEvent read FOnDriverDestroying write FOnDriverDestroying;
end;
TFDPhysServiceProgressEvent = procedure (ASender: TFDPhysDriverService; const AMessage: String) of object;
TFDPhysDriverService = class (TFDComponent, IFDStanErrorHandler)
private
FDriverLink: TFDPhysDriverLink;
FActive: Boolean;
FOnError: TFDErrorEvent;
FStreamingActive: Boolean;
FBeforeExecute: TNotifyEvent;
FAfterExecute: TNotifyEvent;
procedure SetActive(const AValue: Boolean);
procedure SetDriverLink(const AValue: TFDPhysDriverLink);
function GetCliObj: TObject;
protected
// TComponent
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Loaded; override;
// introduced
function GetActualActive: Boolean; virtual;
procedure CheckActive(AAutoActivate, ANeedActivation: Boolean); virtual;
procedure InternalUninstall; virtual;
procedure InternalInstall; virtual;
procedure InternalExecute; virtual;
procedure DoBeforeExecute; virtual;
procedure DoAfterExecute; virtual;
// IFDStanErrorHandler
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
// must be strong-typed by descendants
property DriverLink: TFDPhysDriverLink read FDriverLink write SetDriverLink;
// for static services
property ActualActive: Boolean read GetActualActive;
property Active: Boolean read FActive write SetActive default False;
// for dynamic services
procedure Execute;
public
destructor Destroy; override;
property CliObj: TObject read GetCliObj;
published
property OnError: TFDErrorEvent read FOnError write FOnError;
property BeforeExecute: TNotifyEvent read FBeforeExecute write FBeforeExecute;
property AfterExecute: TNotifyEvent read FAfterExecute write FAfterExecute;
end;
TFDPhysConnectionHost = class(TInterfacedObject,
{$IFNDEF FireDAC_SkipIUnk} IUnknown, {$ENDIF}
IFDStanObjectHost)
private
[Weak] FDriverObj: TFDPhysDriver;
FConnectionDef: IFDStanConnectionDef;
FConnectionCount: Integer;
FPool: IFDStanObjectFactory;
FPassCode: LongWord;
{$IFDEF FireDAC_MONITOR}
FMonitor: IFDMoniClient;
FInitialTracing: Boolean;
procedure AddMoniClient;
{$ENDIF}
procedure Employ;
procedure Vacate;
protected
// IUnknown
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
// IFDStanObjectHost
function GetObjectKindName: TComponentName;
procedure CreateObject(out AObject: IFDStanObject);
// other
public
constructor Create(ADriver: TFDPhysDriver; const AConnectionDef: IFDStanConnectionDef);
destructor Destroy; override;
procedure CreateConnection(out AConn: IFDPhysConnection);
property ConnectionDef: IFDStanConnectionDef read FConnectionDef;
end;
TFDPhysConnection = class(TInterfacedObject,
{$IFNDEF FireDAC_SkipIUnk} IUnknown, {$ENDIF}
IFDMoniAdapter, IFDStanObject, IFDStanOptions, IFDStanErrorHandler,
IFDPhysConnection)
private
FDriver: IFDPhysDriver;
[Weak] FDriverObj: TFDPhysDriver;
FConnHost: TFDPhysConnectionHost;
FLock: TCriticalSection;
FErrorHandler: IFDStanErrorHandler;
FRecoveryHandler: IFDPhysConnectionRecoveryHandler;
FMetadata: TObject;
FLogin: IFDGUIxLoginDialog;
FLoginPrompt: Boolean;
FPreparedCommands: Integer;
FInternalConnectionDef: IFDStanConnectionDef;
FPoolManaged: Boolean;
FMoniAdapterHelper: TFDMoniAdapterHelper;
FSharedHandle: PFDPhysCliHandles;
FTransaction: IFDPhysTransaction;
[Weak] FTransactionObj: TFDPhysTransaction;
FRecoveryFlags: TFDPhysRecoveryFlags;
FCliHandles: TFDPhysCliHandles;
{$IFDEF FireDAC_MONITOR}
procedure UpdateMonitor;
{$ENDIF}
procedure CheckInactive;
procedure CheckActive(ADisconnectingAllowed: Boolean = False);
procedure IncPrepared(ACommand: TFDPhysCommand);
procedure DecPrepared;
procedure ConnectBase;
procedure DoConnect;
procedure DoLogin;
procedure CheckTransaction;
procedure AllocTransactionHandles;
procedure ReleaseTransactionHandles;
procedure DisconnectTransactions;
procedure DisconnectCommands;
function GetDriverID: String;
procedure DisconnectEvents;
procedure RecoverConnection(const AInitiator: IFDStanObject; AOnLogin: Boolean);
public
// IUnknown
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
protected
FOptions: IFDStanOptions;
{$IFDEF FireDAC_MONITOR}
FMonitor: IFDMoniClient;
FTracing: Boolean;
{$ENDIF}
// IFDMoniAdapter
function GetHandle: LongWord;
function GetItemCount: Integer; virtual;
procedure GetItem(AIndex: Integer; out AName: String; out AValue: Variant;
out AKind: TFDMoniAdapterItemKind); virtual;
function GetSupportItems: TFDMoniAdapterItemKinds; virtual;
// IFDStanObject
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
// IFDStanOptions
property Options: IFDStanOptions read FOptions implements IFDStanOptions;
procedure GetParentOptions(var AOpts: IFDStanOptions);
// IFDStanErrorHandler
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
// IFDPhysConnection
function GetDriver: IFDPhysDriver;
function GetState: TFDPhysConnectionState;
function GetOptions: IFDStanOptions;
function GetCommandCount: Integer;
function GetCommands(AIndex: Integer): IFDPhysCommand;
function GetErrorHandler: IFDStanErrorHandler;
function GetRecoveryHandler: IFDPhysConnectionRecoveryHandler;
function GetLogin: IFDGUIxLoginDialog;
function GetLoginPrompt: Boolean;
function GetConnectionDef: IFDStanConnectionDef;
function GetMessages: EFDDBEngineException; virtual;
function GetCliObj: Pointer; virtual;
function GetCliHandle: Pointer;
function GetSharedCliHandle: Pointer;
function GetTransaction: IFDPhysTransaction;
function GetTransactionCount: Integer;
function GetTransactions(AIndex: Integer): IFDPhysTransaction;
function GetCurrentCatalog: String;
function GetCurrentSchema: String;
function GetEventCount: Integer;
function GetEvents(AIndex: Integer): IFDPhysEventAlerter;
procedure SetOptions(const AValue: IFDStanOptions);
procedure SetErrorHandler(const AValue: IFDStanErrorHandler);
procedure SetRecoveryHandler(const AValue: IFDPhysConnectionRecoveryHandler);
procedure SetLogin(const AValue: IFDGUIxLoginDialog);
procedure SetLoginPrompt(const AValue: Boolean);
procedure SetSharedCliHandle(AValue: Pointer);
procedure SetTransaction(const AValue: IFDPhysTransaction);
procedure SetCurrentCatalog(const AValue: String);
procedure SetCurrentSchema(const AValue: String);
procedure CreateMetadata(out AConnMeta: IFDPhysConnectionMetadata);
procedure CreateCommandGenerator(out AGen: IFDPhysCommandGenerator;
const ACommand: IFDPhysCommand);
procedure CreateCommand(out ACmd: IFDPhysCommand);
procedure CreateMetaInfoCommand(out AMetaCmd: IFDPhysMetaInfoCommand);
procedure CreateTransaction(out ATx: IFDPhysTransaction);
procedure CreateEvent(const AEventKind: String; out AEvent: IFDPhysEventAlerter);
procedure Open;
procedure Close;
procedure ForceDisconnect;
function Ping: Boolean;
procedure ChangePassword(const ANewPassword: String);
function GetLastAutoGenValue(const AName: String = ''): Variant; virtual;
procedure SaveLastAutoGenValue(const AValue: Variant);
function Clone: IFDPhysConnection;
procedure AnalyzeSession(AMessages: TStrings); virtual;
{$IFDEF FireDAC_MONITOR}
procedure TracingChanged;
function GetTracing: Boolean;
procedure SetTracing(AValue: Boolean);
function GetMonitor: IFDMoniClient;
procedure TraceList(AList: TStrings; const AName: String);
procedure TraceConnInfo(AKind: TFDMoniAdapterItemKind; const AName: String);
{$ENDIF}
protected
// overridable by descendants
procedure InternalConnect; virtual; abstract;
procedure InternalSetMeta; virtual;
procedure InternalDisconnect; virtual; abstract;
procedure InternalPing; virtual;
function InternalCreateMetadata: TObject; virtual; abstract;
function InternalCreateTransaction: TFDPhysTransaction; virtual; abstract;
function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; virtual;
function InternalCreateCommand: TFDPhysCommand; virtual; abstract;
function InternalCreateMetaInfoCommand: TFDPhysCommand; virtual;
function InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; virtual; abstract;
procedure InternalChangePassword(
const AUserName, AOldPassword, ANewPassword: String); virtual;
{$IFDEF FireDAC_MONITOR}
procedure InternalTracingChanged; virtual;
{$ENDIF}
procedure InternalOverrideNameByCommand(
var AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand); virtual;
procedure InternalExecuteDirect(
const ASQL: String; ATransaction: TFDPhysTransaction); virtual; abstract;
function InternalGetCurrentCatalog: String; virtual;
function InternalGetCurrentSchema: String; virtual;
function InternalGetCliHandle: Pointer; virtual;
function InternalGetSharedCliHandle: Pointer; virtual;
procedure InternalAnalyzeSession(AMessages: TStrings); virtual;
protected
FState: TFDPhysConnectionState;
FCommandList: TFDPtrList;
FTransactionList: TFDPtrList;
FEventList: TFDPtrList;
FDefaultSchema,
FDefaultCatalog,
FCurrentCatalog,
FCurrentSchema: String;
FAvoidImplicitMeta,
FRemoveDefaultMeta: TFDPhysNameParts;
FLastAutoGenValue: Variant;
{$IFDEF FireDAC_MONITOR}
procedure Trace(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep;
const AMsg: String; const AArgs: array of const);
{$ENDIF}
public
constructor Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); virtual;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
property DriverObj: TFDPhysDriver read FDriverObj;
property TransactionObj: TFDPhysTransaction read FTransactionObj;
property ConnectionDef: IFDStanConnectionDef read GetConnectionDef;
property CliObj: Pointer read GetCliObj;
property DefaultSchema: String read FDefaultSchema;
property DefaultCatalog: String read FDefaultCatalog;
property AvoidImplicitMeta: TFDPhysNameParts read FAvoidImplicitMeta;
property RemoveDefaultMeta: TFDPhysNameParts read FRemoveDefaultMeta;
property DriverID: String read GetDriverID;
end;
TFDPhysTxNotification = (
cpBeforeCmdPrepare, cpAfterCmdPrepareSuccess, cpAfterCmdPrepareFailure,
cpAfterCmdUnprepare,
cpBeforeCmdExecute, cpAfterCmdExecuteSuccess, cpAfterCmdExecuteFailure);
TFDPhysTransaction = class(TInterfacedObject,
IFDMoniAdapter, IFDStanObject, IFDStanErrorHandler,
IFDPhysTransaction)
private
FConnection: IFDPhysConnection;
[Weak] FConnectionObj: TFDPhysConnection;
FOptions,
FExternalOptions: TFDTxOptions;
FSavepoints: TFDStringList;
FSerialID: LongWord;
FMoniAdapterHelper: TFDMoniAdapterHelper;
FRetaining: Boolean;
FCommandList: TFDPtrList;
FState: TFDPhysTransactionState;
FStateHandlerList: TInterfaceList;
FPrevAutoStop: Boolean;
FExplicitActive: Boolean;
FLockAutoStopCount: Integer;
FNotifyCount: Integer;
FSharedActive: Boolean;
{$IFDEF FireDAC_MONITOR}
procedure UpdateMonitor;
{$ENDIF}
function GetCLIAutoCommit: Boolean;
function GetDriverID: String;
procedure TxOperation(AOperation: TFDPhysTransactionState;
ABefore: Boolean);
protected
// IFDMoniAdapter
function GetHandle: LongWord;
function GetItemCount: Integer; virtual;
procedure GetItem(AIndex: Integer; out AName: String; out AValue: Variant;
out AKind: TFDMoniAdapterItemKind); virtual;
function GetSupportItems: TFDMoniAdapterItemKinds; virtual;
// IFDStanObject
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
// IFDStanErrorHandler
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
// IFDPhysTransaction
function GetOptions: TFDTxOptions;
function GetActive: Boolean;
function GetTopSerialID: LongWord;
function GetSerialID: LongWord;
function GetNestingLevel: LongWord;
function GetConnection: IFDPhysConnection;
function GetCliObj: Pointer; virtual;
function GetState: TFDPhysTransactionState;
procedure SetOptions(const AValue: TFDTxOptions);
function StartTransaction: LongWord;
procedure Commit;
procedure CommitRetaining;
procedure Rollback;
procedure RollbackRetaining;
procedure LockAutoStop;
procedure UnlockAutoStop(ASuccess, AAllowStop: Boolean);
procedure AddStateHandler(const AHandler: IFDPhysTransactionStateHandler);
procedure RemoveStateHandler(const AHandler: IFDPhysTransactionStateHandler);
procedure Disconnect;
protected
FIDAutoCommit: LongWord;
// overridable by descendants
procedure InternalStartTransaction(AID: LongWord); virtual; abstract;
procedure InternalCommit(AID: LongWord); virtual; abstract;
procedure InternalRollback(AID: LongWord); virtual; abstract;
procedure InternalSetSavepoint(const AName: String); virtual;
procedure InternalRollbackToSavepoint(const AName: String); virtual;
procedure InternalCommitSavepoint(const AName: String); virtual;
procedure InternalChanged; virtual;
procedure InternalAllocHandle; virtual;
procedure InternalReleaseHandle; virtual;
procedure InternalSelect; virtual;
procedure InternalUnSelect; virtual;
procedure InternalNotify(ANotification: TFDPhysTxNotification;
ACommandObj: TFDPhysCommand); virtual;
procedure InternalCheckState(ACommandObj: TFDPhysCommand; ASuccess: Boolean); virtual;
// other
procedure Update;
procedure DisconnectCommands(AFilter: TFDPhysDisconnectFilter;
AMode: TFDPhysDisconnectMode);
procedure Stop(ASuccess: Boolean);
procedure CheckStoping(AAllowUnprepare, AForce, ASuccess: Boolean);
procedure Notify(ANotification: TFDPhysTxNotification;
ACommandObj: TFDPhysCommand);
procedure TransactionFinished;
procedure TransactionStarted;
procedure ReleaseHandleBase;
public
constructor Create(AConnection: TFDPhysConnection); virtual;
destructor Destroy; override;
property ConnectionObj: TFDPhysConnection read FConnectionObj;
property Retaining: Boolean read FRetaining;
property CLIAutoCommit: Boolean read GetCLIAutoCommit;
property DriverID: String read GetDriverID;
end;
TFDPhysEventThread = class(TFDThread)
private
FAlerter: TFDPhysEventAlerter;
protected
procedure DoTimeout; override;
class function GetStartMsgClass: TFDThreadMsgClass; override;
class function GetStopMsgClass: TFDThreadMsgClass; override;
public
constructor Create(AAlerter: TFDPhysEventAlerter);
end;
TFDPhysEventMessage = class(TFDThreadMsgBase)
private
FMsgThread: TFDPhysEventThread;
procedure BasePerform;
public
function Perform(AThread: TFDThread): Boolean; override;
end;
TFDPhysEventStartMessage = class(TFDThreadStartMsg)
public
function Perform(AThread: TFDThread): Boolean; override;
end;
TFDPhysEventStopMessage = class(TFDThreadStopMsg)
public
function Perform(AThread: TFDThread): Boolean; override;
end;
TFDPhysEventAlerter = class(TInterfacedObject,
IFDMoniAdapter, IFDStanObject, IFDStanErrorHandler,
IFDPhysEventAlerter)
private
FConnection: IFDPhysConnection;
[Weak] FConnectionObj: TFDPhysConnection;
FKind: String;
FState: TFDPhysEventAlerterState;
FNames: TFDStringList;
FSubscriptionName: String;
FHandler: IFDPhysEventHandler;
FOptions,
FExternalOptions: TFDEventAlerterOptions;
FMoniAdapterHelper: TFDMoniAdapterHelper;
function GetDriverID: String;
procedure DoNamesChanging(ASender: TObject);
procedure DoTimeout;
procedure MarkChangeHandlers(const AHandler: IFDPhysChangeHandler;
AModified: Boolean);
function AreChangeHandlersModified: Boolean;
{$IFDEF FireDAC_MONITOR}
procedure UpdateMonitor;
{$ENDIF}
protected
FMsgThread: TFDThread;
/// <summary> The list of associated IFDPhysChangeHandler change handlers. </summary>
FChangeHandlers: TInterfaceList;
/// <summary> The list of associated IFDPhysChangeHandler change handler names. </summary>
FChangeHandlerNames: TFDStringList;
function IsRunning: Boolean;
procedure SetupCommand(const ACmd: IFDPhysCommand);
// IFDMoniAdapter
function GetHandle: LongWord;
function GetItemCount: Integer; virtual;
procedure GetItem(AIndex: Integer; out AName: String; out AValue: Variant;
out AKind: TFDMoniAdapterItemKind); virtual;
function GetSupportItems: TFDMoniAdapterItemKinds; virtual;
// IFDStanObject
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
// IFDStanErrorHandler
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
// IFDPhysEventAlerter
function GetConnection: IFDPhysConnection;
function GetState: TFDPhysEventAlerterState;
function GetKind: String;
function GetOptions: TFDEventAlerterOptions;
function GetNames: TStrings;
function GetSubscriptionName: String;
function GetHandler: IFDPhysEventHandler;
procedure SetOptions(const AValue: TFDEventAlerterOptions);
procedure SetNames(const AValue: TStrings);
procedure SetSubscriptionName(const AValue: String);
procedure SetHandler(const AValue: IFDPhysEventHandler);
procedure Register;
procedure Unregister;
procedure Signal(const AEvent: String; const AArgument: Variant);
procedure Refresh(const AHandler: IFDPhysChangeHandler; AForce: Boolean);
procedure AddChangeHandler(const AHandler: IFDPhysChangeHandler);
procedure RemoveChangeHandler(const AHandler: IFDPhysChangeHandler);
procedure AbortJob;
// overridable by descendants
procedure InternalAllocHandle; virtual;
procedure InternalReleaseHandle; virtual;
procedure InternalHandle(AEventMessage: TFDPhysEventMessage); virtual; abstract;
procedure InternalAbortJob; virtual;
procedure InternalRegister; virtual;
procedure InternalUnregister; virtual;
procedure InternalSignal(const AEvent: String; const AArgument: Variant); virtual; abstract;
/// <summary> Implements driver specific refreshing of a change handler. Is called
/// from Refresh method as result of direct method call or a change notification. </summary>
procedure InternalRefresh(const AHandler: IFDPhysChangeHandler); virtual;
/// <summary> Implements driver specific event notification handling. Is called
/// as result of processing of the change notifications queue. </summary>
procedure InternalHandleEvent(const AEventName: String; const AArgument: Variant); virtual;
/// <summary> Implements driver specific timeout handling. Is called
/// as result of timeout processing of the change notifications queue. </summary>
procedure InternalHandleTimeout(var AContinue: Boolean); virtual;
/// <summary> Implements driver specific change handler registration. Is called
/// from AddChangeHandler / RemoveChangeHandler methods. </summary>
procedure InternalChangeHandlerModified(const AHandler: IFDPhysChangeHandler;
const AEventName: String; AOperation: TOperation); virtual;
public
constructor Create(AConnection: TFDPhysConnection; const AKind: String); virtual;
destructor Destroy; override;
property ConnectionObj: TFDPhysConnection read FConnectionObj;
property DriverID: String read GetDriverID;
end;
TFDPhysDataTableInfo = record
FSourceName: String;
FSourceID: Integer;
FOriginName: String;
FArraySize: Integer;
end;
TFDPhysDataColumnInfo = record
FParentTableSourceID: Integer;
FTableSourceID: Integer;
FSourceName: String;
FSourceID: Integer;
FSourceTypeName: String;
FSourceType: TFDDataType;
FOriginTabName: TFDPhysParsedName;
FOriginColName: String;
FType: TFDDataType;
FLen: LongWord;
FPrec: Integer;
FScale: Integer;
FAttrs: TFDDataAttributes;
FForceAddOpts,
FForceRemOpts: TFDDataOptions;
end;
TFDPhysCommand = class(TInterfacedObject,
{$IFNDEF FireDAC_SkipIUnk} IUnknown, {$ENDIF}
IFDMoniAdapter, IFDStanObject, IFDStanOptions, IFDStanErrorHandler,
IFDPhysCommand, IFDPhysMetaInfoCommand)
private
FBaseObjectName: String;
FSchemaName: String;
FCatalogName: string;
FCommandText: String;
FCommandKind: TFDPhysCommandKind;
FFixedCommandKind: Boolean;
FMacros: TFDMacros;
FParams: TFDParams;
FObjectScopes: TFDPhysObjectScopes;
FTableKinds: TFDPhysTableKinds;
FWildcard: String;
FExecutor: IFDStanAsyncExecutor;
FState: TFDPhysCommandState;
FThreadID: TThreadID;
FSourceObjectName: String;
FSourceRecordSetName: String;
FRecordSetIndex: Integer;
FOverload: Word;
FEof: Boolean;
FFirstFetch: Boolean;
FNextRecordSet: Boolean;
FErrorHandler: IFDStanErrorHandler;
FExecuteCount: Integer;
FStateHandler: IFDPhysCommandStateHandler;
FRowsAffected: TFDCounter;
FRowsAffectedReal: Boolean;
FErrorAction: TFDErrorAction;
FMappingHandler: IFDPhysMappingHandler;
FMoniAdapterHelper: TFDMoniAdapterHelper;
FLimitOptions: TFDPhysLimitOptions;
{$IFDEF FireDAC_MONITOR}
procedure UpdateMonitor;
{$ENDIF}
procedure CheckState(ARequiredState: TFDPhysCommandState);
function DoDefineDataTable(ADatSManager: TFDDatSManager; ATable: TFDDatSTable;
ARootID: Integer; const ARootName: String; AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode): TFDDatSTable;
procedure PreprocessCommand(ACreateParams, ACreateMacros,
AExpandParams, AExpandMacros, AExpandEscapes, AParseSQL: Boolean);
function CheckMetaAvailability: Boolean;
procedure OpenBase;
procedure FetchBase(ATable: TFDDatSTable; AAll: Boolean);
procedure ExecuteBase(ATimes, AOffset: Integer);
procedure BeginDefine;
function GetParamsOwner: TPersistent;
function GetDriverID: String;
procedure CheckPreprocessCommand(ACreateParams: Boolean);
procedure ExecuteTask(const AOperation: IFDStanAsyncOperation;
const AHandler: IFDStanAsyncHandler; ABlocked: Boolean);
protected
FOptions: IFDStanOptions;
// IFDStanObject
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
// IFDStanErrorHandler
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
// IFDStanOptions
property Options: IFDStanOptions read FOptions implements IFDStanOptions;
procedure GetParentOptions(var AOpts: IFDStanOptions);
// IFDMoniAdapter
function GetHandle: LongWord;
function GetItemCount: Integer; virtual;
procedure GetItem(AIndex: Integer; out AName: String; out AValue: Variant;
out AKind: TFDMoniAdapterItemKind); virtual;
function GetSupportItems: TFDMoniAdapterItemKinds; virtual;
// IFDPhysCommand
function GetSchemaName: String;
function GetCatalogName: String;
function GetBaseObjectName: String;
function GetConnection: IFDPhysConnection;
function GetOptions: IFDStanOptions;
function GetState: TFDPhysCommandState;
function GetCommandText: String;
function GetCommandKind: TFDPhysCommandKind;
function GetParams: TFDParams;
function GetOverload: Word;
function GetNextRecordSet: Boolean;
function GetErrorHandler: IFDStanErrorHandler;
function GetSourceObjectName: String;
function GetSourceRecordSetName: String;
function GetMacros: TFDMacros;
function GetRowsAffected: TFDCounter;
function GetRowsAffectedReal: Boolean;
function GetErrorAction: TFDErrorAction;
function GetMappingHandler: IFDPhysMappingHandler;
function GetSQLOrderByPos: Integer;
function GetCliObj: Pointer; virtual;
function GetTransaction: IFDPhysTransaction;
function GetSQLText: String;
function GetStateHandler: IFDPhysCommandStateHandler;
procedure SetSchemaName(const AValue: String);
procedure SetCatalogName(const AValue: String);
procedure SetBaseObjectName(const AValue: String);
procedure SetOptions(const AValue: IFDStanOptions);
procedure SetCommandText(const AValue: String);
procedure SetCommandKind(const AValue: TFDPhysCommandKind);
procedure SetSourceObjectName(const AValue: String);
procedure SetSourceRecordSetName(const AValue: String);
procedure SetNextRecordSet(const AValue: Boolean);
procedure SetErrorHandler(const AValue: IFDStanErrorHandler);
procedure SetOverload(const AValue: Word);
procedure SetMappingHandler(const AValue: IFDPhysMappingHandler);
procedure SetState(const AValue: TFDPhysCommandState);
procedure SetTransaction(const AValue: IFDPhysTransaction);
procedure SetStateHandler(const AValue: IFDPhysCommandStateHandler);
procedure SetMacros(AValue: TFDMacros);
procedure SetParams(AValue: TFDParams);
procedure AbortJob(const AWait: Boolean = False);
function Define(ADatSManager: TFDDatSManager; ATable: TFDDatSTable = nil;
AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode = mmReset): TFDDatSTable; overload;
function Define(ATable: TFDDatSTable;
AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode = mmReset): TFDDatSTable; overload;
procedure Execute(ATimes: Integer = 0; AOffset: Integer = 0;
ABlocked: Boolean = False);
procedure Fetch(ATable: TFDDatSTable; AAll: Boolean = True;
ABlocked: Boolean = False); overload;
procedure Fetch(ADatSManager: TFDDatSManager;
AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode = mmReset); overload;
procedure CloseStreams;
procedure Preprocess;
procedure Prepare(const ACommandText: String = ''; ACreateParams: Boolean = True);
procedure Unprepare;
procedure Open(ABlocked: Boolean = False);
procedure Close;
procedure CloseAll;
procedure Disconnect;
procedure CheckAsyncProgress;
// IFDPhysMetaInfoCommand
function GetMetaInfoKind: TFDPhysMetaInfoKind;
procedure SetMetaInfoKind(AValue: TFDPhysMetaInfoKind);
function GetTableKinds: TFDPhysTableKinds;
procedure SetTableKinds(AValue: TFDPhysTableKinds);
function GetWildcard: String;
procedure SetWildcard(const AValue: String);
function GetObjectScopes: TFDPhysObjectScopes;
procedure SetObjectScopes(AValue: TFDPhysObjectScopes);
protected
[Weak] FConnectionObj: TFDPhysConnection;
FConnection: IFDPhysConnection;
[Weak] FTransactionObj: TFDPhysTransaction;
FTransaction: IFDPhysTransaction;
FDbCommandText: String;
FMetaInfoKind: TFDPhysMetaInfoKind;
FBuffer: TFDBuffer;
FSQLValuesPos: Integer;
FSQLValuesPosEnd: Integer;
FSQLOrderByPos: Integer;
FSQLLimitSkip,
FSQLLimitRows: Integer;
FRecordsFetched: Integer;
// utils
function GetTraceCommandText(const ACmd: String = ''): String;
{$IFDEF FireDAC_MONITOR}
procedure Trace(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep;
const AMsg: String; const AArgs: array of const);
function EnterTrace(AConnObj: TFDPhysConnection): Boolean;
function ExitTrace(AConnObj: TFDPhysConnection; var AUpdateMonitor: Boolean): Boolean;
{$ENDIF}
function CheckFetchColumn(ADataType: TFDDataType; AAttributes: TFDDataAttributes): Boolean; overload;
procedure CheckParamMatching(AParam: TFDParam;
ADataType: TFieldType; AParamType: TParamType; APrec: Integer);
procedure CreateCommandGenerator(out AGen: IFDPhysCommandGenerator);
function OpenBlocked: Boolean;
procedure GenerateStoredProcParams(const AName: TFDPhysParsedName);
procedure GenerateStoredProcCall(const AName: TFDPhysParsedName;
ASPUsage: TFDPhysCommandKind);
procedure GetSelectMetaInfoParams(out AName: TFDPhysParsedName);
procedure GenerateSelectMetaInfo(const AName: TFDPhysParsedName);
procedure GenerateLimitSelect();
procedure GenerateParamMarkers();
procedure ParTypeMapError(AParam: TFDParam);
procedure ParTypeUnknownError(AParam: TFDParam);
procedure ParDefChangedError(ADataType: TFieldType; AParam: TFDParam);
procedure ParSetChangedError(AExpected, AActual: Integer);
procedure UnsupParamObjError(AParam: TFDParam);
procedure CheckMetaInfoParams(const AName: TFDPhysParsedName);
procedure CheckExact(AUseRecsMax: Boolean; ATimes, AOffset: Integer;
AValue: TFDCounter; AFetch: Boolean);
procedure CheckArrayDMLWithIntStr(AHasIntStreams: Boolean;
ATimes, AOffset: Integer);
procedure InitRowsAffected;
procedure UpdateRowsAffected(AValue: TFDCounter);
// overridables
procedure InternalAbort; virtual;
procedure InternalPrepare; virtual; abstract;
procedure InternalUnprepare; virtual; abstract;
function InternalOpen(var ACount: TFDCounter): Boolean; virtual; abstract;
function InternalNextRecordSet: Boolean; virtual; abstract;
procedure InternalClose; virtual; abstract;
procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); virtual; abstract;
procedure InternalCloseStreams; virtual;
function InternalUseStandardMetadata: Boolean; virtual;
function InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean; virtual; abstract;
function InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean; virtual; abstract;
function InternalFetchRowSet(ATable: TFDDatSTable; AParentRow: TFDDatSRow;
ARowsetSize: LongWord): LongWord; virtual; abstract;
public
constructor Create(AConnection: TFDPhysConnection);
destructor Destroy; override;
property DriverID: String read GetDriverID;
end;
var
FDPhysManagerObj: TFDPhysManager;
implementation
uses
System.Variants, System.Generics.Defaults, System.Generics.Collections,
System.Types,
FireDAC.Stan.Consts, FireDAC.Stan.ResStrs,
FireDAC.Phys.SQLPreprocessor, FireDAC.Phys.Meta;
const
CFOMs: array[Boolean] of TFDPhysFindObjMode = (fomIfActive, fomMBActive);
{ ----------------------------------------------------------------------------- }
{ TFDPhysManager }
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.Initialize;
begin
inherited Initialize;
FLock := TCriticalSection.Create;
FDPhysManagerObj := Self;
FOptions := TFDOptionsContainer.Create(nil, TFDFetchOptions,
TFDUpdateOptions, TFDTopResourceOptions, nil);
FDriverIDs := TFDStringList.Create;
FRDBMSNames := TFDStringList.Create(dupError, True, False);
RegisterRDBMSKind(TFDRDBMSKinds.Other, S_FD_Other_RDBMS);
FDriverClasses := TFDClassList.Create;
FDriverList := TFDPtrList.Create;
FDriverLinkList := TFDObjList.Create;
end;
{ ----------------------------------------------------------------------------- }
destructor TFDPhysManager.Destroy;
begin
CleanupManager;
FDriverDefs := nil;
FConnectionDefs := nil;
FDFreeAndNil(FDriverList);
FDFreeAndNil(FDriverLinkList);
FDFreeAndNil(FDriverClasses);
FDFreeAndNil(FDriverIDs);
FDFreeAndNil(FRDBMSNames);
_AddRef;
FOptions := nil;
inherited Destroy;
FDPhysManagerObj := nil;
FDFreeAndNil(FLock);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager._Release: Integer;
begin
Result := FDDecRef;
if Result = 0 then
Shutdown;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
Result := inherited QueryInterface(IID, Obj);
CheckUpdateDriverIDs;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetOptions: IFDStanOptions;
begin
Result := Self as IFDStanOptions;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetConnectionDefs: IFDStanConnectionDefs;
begin
FLock.Enter;
try
if FConnectionDefs = nil then
FDCreateInterface(IFDStanConnectionDefs, FConnectionDefs);
Result := FConnectionDefs;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetDriverDefs: IFDStanDefinitions;
begin
FLock.Enter;
try
if FDriverDefs = nil then begin
FDCreateInterface(IFDStanDefinitions, FDriverDefs);
FDriverDefs.Name := S_FD_DefDrvFileName;
FDriverDefs.Storage.DefaultFileName := S_FD_DefDrvFileName;
FDriverDefs.Storage.GlobalFileName := FDReadRegValue(S_FD_DrvValName);
end;
Result := FDriverDefs;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetState: TFDPhysManagerState;
begin
Result := FState;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CheckActive;
begin
if FState <> dmsActive then
FDException(Self, [S_FD_LPhys], er_FD_AccDrvMngrMB, ['Active']);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CheckActiveOrStoping;
begin
if not (FState in [dmsActive, dmsStoping, dmsTerminating]) then
FDException(Self, [S_FD_LPhys], er_FD_AccDrvMngrMB, ['Active or Stoping']);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.RegisterRDBMSKind(AKind: TFDRDBMSKind; const AName: String);
begin
if FRDBMSNames.IndexOf(AName) = -1 then
FRDBMSNames.AddInt(AName, AKind);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.RegisterDriverClass(ADriverClass: TClass);
begin
if FDriverClasses.IndexOf(ADriverClass) = -1 then begin
FDriverClasses.Add(TFDPhysDriverClass(ADriverClass));
FUpdateDriverIDs := True;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.UnregisterDriverClass(ADriverClass: TClass);
begin
if FDriverClasses.Remove(ADriverClass) < 0 then
FUpdateDriverIDs := True;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.Open;
begin
GetConnectionDefs;
GetDriverDefs;
FState := dmsActive;
FUpdateDriverIDs := True;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CleanupDrivers;
var
i: Integer;
[Weak] oDrv: TFDPhysDriver;
begin
FLock.Enter;
try
for i := FDriverList.Count - 1 downto 0 do begin
oDrv := TFDPhysDriver(FDriverList[i]);
if oDrv.FState in [drsRegistered, drsLoaded, drsActive] then
oDrv.Shutdown;
end;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CleanupManager;
begin
FLock.Enter;
try
if FDriverDefs <> nil then
FDriverDefs.Clear;
if FConnectionDefs <> nil then
FConnectionDefs.Clear;
FState := dmsInactive;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.InternalClose(ATerminate, AWaitForClose: Boolean);
var
i: Integer;
lStop, lTimeOut, lFree: Boolean;
iStartTime: Cardinal;
begin
lStop := False;
lFree := False;
lTimeOut := False;
try
FLock.Enter;
try
if (FState = dmsInactive) and not ATerminate then
Exit;
if ATerminate and (FState in [dmsStoping, dmsInactive]) then begin
lFree := (FState = dmsInactive) and (RefCount = 0);
FState := dmsTerminating;
end
else begin
if FState <> dmsInactive then begin
CheckActive;
lStop := True;
end;
if ATerminate then
FState := dmsTerminating
else
FState := dmsStoping;
end;
if lStop then
for i := 0 to FDriverList.Count - 1 do
TFDPhysDriver(FDriverList[i]).Stop;
finally
FLock.Leave;
end;
finally
iStartTime := TThread.GetTickCount();
while not lTimeOut and (FDriverList.Count > 0) do begin
lTimeOut := FDTimeout(iStartTime, C_FD_PhysManagerShutdownTimeout);
CleanupDrivers;
Sleep(1);
end;
if FDriverList.Count = 0 then
if FState = dmsTerminating then
lFree := True
else if FState = dmsStoping then
CleanupManager;
if lTimeOut then
FDException(nil, [S_FD_LPhys], er_FD_AccShutdownTO, []);
if lFree then
FDFree(Self);
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.Close(AWait: Boolean);
begin
InternalClose(False, AWait);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.Shutdown;
begin
InternalClose(True, True);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.ErrorDriverNotReg(const ADriverID, ABaseDriverID: String);
var
sDrvID, s: String;
begin
if ABaseDriverID <> '' then
sDrvID := ABaseDriverID
else
sDrvID := ADriverID;
if (CompareText(sDrvID, S_FD_TDBXId) = 0) or
(CompareText(sDrvID, S_FD_ODBCId) = 0) or
(CompareText(sDrvID, S_FD_MSSQLId) = 0) or
(CompareText(sDrvID, S_FD_MSAccId) = 0) or
(CompareText(sDrvID, S_FD_DB2Id) = 0) or
(CompareText(sDrvID, S_FD_MySQLId) = 0) or
(CompareText(sDrvID, S_FD_OraId) = 0) or
(CompareText(sDrvID, S_FD_ASAId) = 0) or
(CompareText(sDrvID, S_FD_ADSId) = 0) or
(CompareText(sDrvID, S_FD_IBId) = 0) or
(CompareText(sDrvID, S_FD_IBLiteId) = 0) or
(CompareText(sDrvID, S_FD_FBId) = 0) or
(CompareText(sDrvID, S_FD_PGId) = 0) or
(CompareText(sDrvID, S_FD_SQLiteId) = 0) or
(CompareText(sDrvID, S_FD_DSId) = 0) or
(CompareText(sDrvID, S_FD_InfxId) = 0) or
(CompareText(sDrvID, S_FD_TDataId) = 0) or
(CompareText(sDrvID, S_FD_MongoId) = 0) then
s := Format(S_FD_AccSrcNotFoundExists, [UpperCase(ABaseDriverID)])
else
s := Format(S_FD_AccSrcNotFoundNotExists, [UpperCase(ADriverID), S_FD_DefDrvFileName]);
FDException(Self, [S_FD_LPhys], er_FD_AccSrvNotFound, [ADriverID, s]);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.FindDriverClass(const ADriverID: String): TFDPhysDriverClass;
var
i: Integer;
begin
Result := nil;
for i := 0 to FDriverClasses.Count - 1 do
if CompareText(TFDPhysDriverClass(FDriverClasses[i]).GetBaseDriverID, ADriverID) = 0 then begin
Result := TFDPhysDriverClass(FDriverClasses[i]);
Break;
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.FindDriverLink(const ADriverID: String): TFDPhysDriverLink;
var
i: Integer;
begin
Result := nil;
FLock.Enter;
try
for i := 0 to FDriverLinkList.Count - 1 do
if CompareText(TFDPhysDriverLink(FDriverLinkList[i]).ActualDriverID, ADriverID) = 0 then begin
Result := TFDPhysDriverLink(FDriverLinkList[i]);
Exit;
end;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.DriverByID(const ADriverID: String;
AMode: TFDPhysFindObjMode; ARequired: Boolean): TFDPhysDriver;
var
oDef: IFDStanDefinition;
oDrvClass: TFDPhysDriverClass;
oLink: TFDPhysDriverLink;
sBaseDriverID: String;
i: Integer;
begin
if ADriverID = '' then
FDException(Self, [S_FD_LPhys], er_FD_AccSrvNotDefined, []);
sBaseDriverID := '';
FLock.Enter;
try
case AMode of
fomNone:
;
fomMBActive:
CheckActive;
fomMBNotInactive:
CheckActiveOrStoping;
fomIfActive:
if FState <> dmsActive then begin
Result := nil;
Exit;
end;
end;
Result := nil;
for i := 0 to FDriverList.Count - 1 do
if CompareText(TFDPhysDriver(FDriverList[i]).FDriverID, ADriverID) = 0 then begin
Result := TFDPhysDriver(FDriverList[i]);
Break;
end;
if (Result = nil) and ARequired then begin
oDef := GetDriverDefs.FindDefinition(ADriverID);
if oDef = nil then begin
oDef := GetDriverDefs.Add;
oDef.Name := ADriverID;
end;
oLink := FindDriverLink(ADriverID);
if oLink <> nil then
oLink.SetupDef(oDef);
sBaseDriverID := oDef.AsString[C_FD_DrvBaseId];
if sBaseDriverID = '' then
sBaseDriverID := oDef.Name;
oDrvClass := FindDriverClass(sBaseDriverID);
if oDrvClass <> nil then
Result := oDrvClass.Create(Self, oDef);
end;
finally
FLock.Leave;
end;
if Result = nil then begin
if ARequired then
ErrorDriverNotReg(ADriverID, sBaseDriverID);
end
else
Result.FLock.Enter;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CreateDriver(const ADriverID: String;
out ADrv: IFDPhysDriver; AIntfRequired: Boolean);
var
oDrv: TFDPhysDriver;
begin
ADrv := nil;
oDrv := DriverByID(ADriverID, CFOMs[AIntfRequired], True);
if oDrv <> nil then begin
ADrv := oDrv as IFDPhysDriver;
oDrv.FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CreateConnection(const AConnectionDef: IFDStanConnectionDef;
out AConn: IFDPhysConnection; AIntfRequired: Boolean);
var
oDrv: TFDPhysDriver;
begin
ASSERT(AConnectionDef <> nil);
AConn := nil;
GetConnectionDefs.BeginRead;
try
oDrv := DriverByID(AConnectionDef.Params.DriverID, CFOMs[AIntfRequired], True);
if oDrv <> nil then
try
oDrv.CreateConnection(AConnectionDef, AConn);
finally
oDrv.FLock.Leave;
end;
finally
GetConnectionDefs.EndRead;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CreateConnection(const AConDefName: String;
out AConn: IFDPhysConnection; AIntfRequired: Boolean);
var
oDef: IFDStanConnectionDef;
begin
if Pos('=', AConDefName) <> 0 then begin
oDef := GetConnectionDefs.AddTemporary as IFDStanConnectionDef;
oDef.ParseString(AConDefName);
end
else
oDef := GetConnectionDefs.ConnectionDefByName(AConDefName);
CreateConnection(oDef, AConn, AIntfRequired);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CreateMetadata(out AMeta: IFDPhysManagerMetadata);
begin
Supports(TObject(Self), IFDPhysManagerMetadata, AMeta);
ASSERT(Assigned(AMeta));
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CreateDefaultConnectionMetadata(
out AConMeta: IFDPhysConnectionMetadata);
begin
AConMeta := TFDPhysConnectionMetadata.Create(nil, 0, 0, False) as IFDPhysConnectionMetadata;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CreateDriverMetadata(const ADriverID: String;
out AMeta: IFDPhysDriverMetadata);
var
oDrv: IFDPhysDriver;
begin
CreateDriver(ADriverID, oDrv);
oDrv.CreateMetadata(AMeta);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.RefreshMetadataCache;
var
i, j: Integer;
oDrv: TFDPhysDriver;
oConnMeta: IFDPhysConnectionMetadata;
begin
FLock.Enter;
try
for i := 0 to FDriverList.Count - 1 do begin
oDrv := TFDPhysDriver(FDriverList[i]);
for j := 0 to oDrv.GetConnectionCount - 1 do
if Supports(oDrv.GetConnections(j), IFDPhysConnectionMetadata, oConnMeta) then
oConnMeta.RefreshMetadataCache;
end;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.DriverIDFromSharedCliHandle(ASharedCliHandle: Pointer): String;
begin
if ASharedCliHandle = nil then
Result := ''
else
Result := String(PFDPhysCliHandles(ASharedCliHandle)^.FDriverID);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.CloseConnectionDef(const AConnectionDef: IFDStanConnectionDef);
var
oDrv: TFDPhysDriver;
begin
ASSERT(AConnectionDef <> nil);
oDrv := DriverByID(AConnectionDef.Params.DriverID, fomIfActive, False);
if oDrv <> nil then
try
oDrv.CloseConnectionDef(AConnectionDef);
finally
oDrv.FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
// IFDPhysManagerMetadata
procedure TFDPhysManager.CheckUpdateDriverIDs;
begin
FLock.Enter;
try
if FUpdateDriverIDs then begin
FUpdateDriverIDs := False;
UpdateDriverIDs;
end;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.UpdateDriverIDs;
var
i: Integer;
oDef: IFDStanDefinition;
oLink: TFDPhysDriverLink;
sID, sBaseID: String;
begin
FDriverIDs.Clear;
FDriverIDs.Sorted := True;
FDriverIDs.Duplicates := dupIgnore;
for i := 0 to GetDriverDefs.Count - 1 do
FDriverIDs.Add(GetDriverDefs[i].Name);
for i := 0 to FDriverLinkList.Count - 1 do
FDriverIDs.Add(TFDPhysDriverLink(FDriverLinkList[i]).ActualDriverID);
for i := 0 to FDriverClasses.Count - 1 do
FDriverIDs.Add(TFDPhysDriverClass(FDriverClasses[i]).GetBaseDriverID);
FDriverIDs.Sorted := False;
for i := FDriverIDs.Count - 1 downto 0 do begin
sID := FDriverIDs[i];
sBaseID := '';
oDef := GetDriverDefs.FindDefinition(sID);
if oDef <> nil then
sBaseID := oDef.AsString[C_FD_DrvBaseId]
else begin
oLink := FindDriverLink(sID);
if oLink <> nil then
sBaseID := oLink.BaseDriverID;
end;
if sBaseID = '' then
sBaseID := sID;
if FindDriverClass(sBaseID) = nil then
FDriverIDs.Delete(i)
else
FDriverIDs[i] := sID + '=' + sBaseID;
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetDriverCount: Integer;
begin
Result := FDriverIDs.Count;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetDriverID(AIndex: Integer): String;
begin
Result := FDriverIDs.KeyNames[AIndex];
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetBaseDriverID(AIndex: Integer): String;
begin
Result := FDriverIDs.ValueFromIndex[AIndex];
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetBaseDriverID(const ADriverID: String): String;
var
i: Integer;
begin
Result := '';
FLock.Enter;
try
for i := 0 to FDriverIDs.Count - 1 do
if CompareText(GetDriverID(i), ADriverID) = 0 then begin
Result := GetBaseDriverID(i);
Break;
end;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetBaseDriverClass(const ADriverID: String): TClass;
var
sId: String;
begin
sId := GetBaseDriverID(ADriverID);
if sId <> '' then
Result := FindDriverClass(sId)
else
Result := nil;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetRDBMSKind(const ADriverID: String): TFDRDBMSKind;
var
oDrvClass: TFDPhysDriverClass;
i: Integer;
begin
Result := TFDRDBMSKinds.Unknown;
oDrvClass := TFDPhysDriverClass(GetBaseDriverClass(ADriverID));
if oDrvClass <> nil then
Result := oDrvClass.GetRDBMSKind
else begin
i := FRDBMSNames.IndexOf(ADriverID);
if i <> -1 then
Result := TFDRDBMSKind(FRDBMSNames.Ints[i]);
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetRDBMSName(AKind: TFDRDBMSKind): String;
var
i: Integer;
begin
Result := '';
for i := 0 to FRDBMSNames.Count - 1 do
if TFDRDBMSKind(FRDBMSNames.Ints[i]) = AKind then begin
Result := FRDBMSNames[i];
Break;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.GetRDBMSNames(ANames: TStrings);
begin
ANames.SetStrings(FRDBMSNames);
end;
{ ----------------------------------------------------------------------------- }
// IFDStanObject
function TFDPhysManager.GetName: TComponentName;
begin
Result := ClassName;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysManager.GetParent: IFDStanObject;
begin
Result := nil;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.AfterReuse;
begin
// nothing
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.BeforeReuse;
begin
// nothing
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysManager.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
// nothing
end;
{ ----------------------------------------------------------------------------- }
{ TFDPhysConnectionDefParams }
{ ----------------------------------------------------------------------------- }
type
TFDPhysConnectionDefParams = class(TInterfacedObject, IFDStanConnectionDefParams)
private
FClass: TFDConnectionDefParamsClass;
protected
// IFDStanConnectionDefParams
function CreateParams(const ADef: IFDStanDefinition): TObject;
public
constructor Create(AClass: TFDConnectionDefParamsClass);
end;
{ ----------------------------------------------------------------------------- }
constructor TFDPhysConnectionDefParams.Create(AClass: TFDConnectionDefParamsClass);
begin
inherited Create;
FClass := AClass;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnectionDefParams.CreateParams(const ADef: IFDStanDefinition): TObject;
begin
Result := FClass.Create(ADef);
end;
{ ----------------------------------------------------------------------------- }
{ TFDPhysConnectionDefParamsFactory }
{ ----------------------------------------------------------------------------- }
type
TFDPhysConnectionDefParamsFactory = class(TFDMultyInstanceFactory)
protected
function CreateObject(const AProvider: String): TObject; override;
function Match(const AIID: TGUID; const AProvider: String;
AValidate: Boolean): Boolean; override;
public
constructor Create;
end;
{ ----------------------------------------------------------------------------- }
constructor TFDPhysConnectionDefParamsFactory.Create;
begin
inherited Create(nil, IFDStanConnectionDefParams);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnectionDefParamsFactory.CreateObject(const AProvider: String): TObject;
var
oMeta: IFDPhysManagerMetadata;
begin
Supports(FDPhysManager, IFDPhysManagerMetadata, oMeta);
Result := TFDPhysConnectionDefParams.Create(
TFDPhysDriverClass(oMeta.GetBaseDriverClass(AProvider)).GetConnectionDefParamsClass);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnectionDefParamsFactory.Match(const AIID: TGUID;
const AProvider: String; AValidate: Boolean): Boolean;
var
oMeta: IFDPhysManagerMetadata;
begin
Result := IsEqualGUID(AIID, IFDStanConnectionDefParams) and
Supports(FDPhysManager, IFDPhysManagerMetadata, oMeta) and
(oMeta.GetBaseDriverClass(AProvider) <> nil);
end;
{ ----------------------------------------------------------------------------- }
{ TFDPhysDriver }
{ ----------------------------------------------------------------------------- }
constructor TFDPhysDriver.Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition);
var
oParentDef: IFDStanDefinition;
sBaseDriverID: String;
begin
inherited Create;
// Pins the driver in the manager
_AddRef;
FState := drsUnknown;
FManager := AManager;
FManager.FLock.Enter;
FManager.FDriverList.Add(Self);
FManager.FLock.Leave;
FLock := TCriticalSection.Create;
FDriverID := ADriverDef.Name;
sBaseDriverID := ADriverDef.AsString[C_FD_DrvBaseId];
if (sBaseDriverID <> '') and (sBaseDriverID <> FDriverID) then begin
if ADriverDef.ParentDefinition = nil then begin
oParentDef := AManager.GetDriverDefs.FindDefinition(sBaseDriverID);
if (oParentDef <> nil) and (ADriverDef <> oParentDef) then
ADriverDef.ParentDefinition := oParentDef;
end;
end;
FParams := ADriverDef;
FState := drsRegistered;
FConnHostList := TFDPtrList.Create;
FConnectionList := TFDPtrList.Create;
FMessages := TFDLog.Create;
end;
{ ----------------------------------------------------------------------------- }
destructor TFDPhysDriver.Destroy;
var
i: Integer;
begin
Shutdown;
for i := FConnHostList.Count - 1 downto 0 do
FDFree(TFDPhysConnectionHost(FConnHostList[i]));
FDFreeAndNil(FConnHostList);
FDFreeAndNil(FConnectionList);
FManager.FLock.Enter;
FManager.FDriverList.Remove(Self);
FManager.FLock.Leave;
FState := drsUnknown;
FParams := nil;
FManager := nil;
FDFreeAndNil(FLock);
FDFreeAndNil(FMessages);
inherited Destroy;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.GetDriverID: String;
begin
Result := FDriverID;
end;
{ ----------------------------------------------------------------------------- }
class function TFDPhysDriver.GetBaseDriverID: String;
begin
Result := '';
ASSERT(False);
end;
{ ----------------------------------------------------------------------------- }
class function TFDPhysDriver.GetBaseDriverDesc: String;
begin
Result := '';
ASSERT(False);
end;
{ ----------------------------------------------------------------------------- }
class function TFDPhysDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.Unknown;
ASSERT(False);
end;
{ ----------------------------------------------------------------------------- }
class function TFDPhysDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := nil;
ASSERT(False);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.GetBaseDrvID: String;
begin
Result := GetBaseDriverID;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.GetBaseDrvDesc: String;
begin
Result := GetBaseDriverDesc;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.GetDbKind: TFDRDBMSKind;
begin
Result := GetRDBMSKind;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.GetState: TFDPhysDriverState;
begin
Result := FState;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.GetCliObj: Pointer;
begin
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDriver.GetMessages: TStrings;
begin
Result := Messages;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.GetConnectionCount: Integer;
begin
Result := FConnectionList.Count;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.GetConnections(AIndex: Integer): IFDPhysConnection;
begin
FLock.Enter;
try
Result := TFDPhysConnection(FConnectionList[AIndex]) as IFDPhysConnection;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.Stop;
var
i: Integer;
oConnHost: TFDPhysConnectionHost;
begin
FLock.Enter;
try
for i := 0 to FConnHostList.Count - 1 do begin
oConnHost := TFDPhysConnectionHost(FConnHostList[i]);
if oConnHost.FPool <> nil then
oConnHost.FPool.Close;
end;
if FState <> drsActive then
Exit;
if FRefCount <= 1 then begin
FState := drsLoaded;
Exit;
end;
FState := drsStoping;
for i := FConnectionList.Count - 1 downto 0 do
TFDPhysConnection(FConnectionList[i]).ForceDisconnect;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.Unload;
var
oLink: TFDPhysDriverLink;
begin
FLock.Enter;
try
if FState <> drsLoaded then
Exit;
oLink := FManager.FindDriverLink(FDriverID);
if oLink <> nil then
oLink.DoDriverDestroying;
try
InternalUnload;
except
// not visible
end;
FState := drsRegistered;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.Shutdown;
var
lLeave: Boolean;
begin
lLeave := True;
FLock.Enter;
try
Stop;
Unload;
if (FState = drsRegistered) and (FRefCount = 1) then
lLeave := _Release > 0;
finally
if lLeave then
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.Load;
var
oLink: TFDPhysDriverLink;
begin
FLock.Enter;
try
if FState <> drsRegistered then
Exit;
oLink := FManager.FindDriverLink(FDriverID);
FMessages.Clear;
FMessages.Start('Loading driver ' + FDriverID);
try
try
FState := drsLoading;
if oLink <> nil then
oLink.SetupDef(FParams);
InternalLoad;
FState := drsLoaded;
except
on E: Exception do begin
FState := drsRegistered;
FMessages.Msg('Error: ' + E.Message);
raise;
end;
end;
finally
FMessages.Stop;
end;
if oLink <> nil then
oLink.DoDriverCreated;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.Employ;
begin
FLock.Enter;
try
Load;
if AtomicIncrement(FUsageCount) = 1 then
if FState = drsLoaded then
FState := drsActive;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.Vacate;
begin
FLock.Enter;
try
if AtomicDecrement(FUsageCount) = 0 then
if FState in [drsActive, drsStoping] then
FState := drsLoaded;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.GetVendorParams(out AHome, ALib: String);
begin
if Params <> nil then begin
AHome := Params.AsXString[S_FD_DrvVendorHome];
ALib := Params.AsXString[S_FD_DrvVendorLib];
end
else begin
AHome := '';
ALib := '';
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.FindConnectionHost(
const AConnectionDef: IFDStanConnectionDef): TFDPhysConnectionHost;
var
i: Integer;
begin
Result := nil;
for i := 0 to FConnHostList.Count - 1 do
if TFDPhysConnectionHost(FConnHostList[i]).FConnectionDef = AConnectionDef then begin
Result := TFDPhysConnectionHost(FConnHostList[i]);
Break;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.CreateConnection(const AConnectionDef: IFDStanConnectionDef;
out AConn: IFDPhysConnection);
var
oConnHost: TFDPhysConnectionHost;
begin
ASSERT(AConnectionDef <> nil);
FLock.Enter;
try
oConnHost := FindConnectionHost(AConnectionDef);
if oConnHost = nil then
oConnHost := TFDPhysConnectionHost.Create(Self, AConnectionDef);
oConnHost.CreateConnection(AConn);
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.CloseConnectionDef(const AConnectionDef: IFDStanConnectionDef);
var
oConnHost: TFDPhysConnectionHost;
begin
ASSERT(AConnectionDef <> nil);
FLock.Enter;
try
oConnHost := FindConnectionHost(AConnectionDef);
if oConnHost <> nil then begin
if oConnHost.FPool <> nil then
oConnHost.FPool.Close;
FDFree(oConnHost);
end;
finally
FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.CreateMetadata(out ADrvMeta: IFDPhysDriverMetadata);
begin
Supports(TObject(Self), IFDPhysDriverMetadata, ADrvMeta);
ASSERT(Assigned(ADrvMeta));
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.CreateConnectionWizard(
out AWizard: IFDPhysDriverConnectionWizard);
begin
Supports(TObject(Self), IFDPhysDriverConnectionWizard, AWizard);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
i: Integer;
s: String;
begin
if AParams = nil then begin
AParams := TFDDatSTable.Create;
AParams.Columns.Add('ID', dtInt32).AutoIncrement := True;
AParams.Columns.Add('Name', dtWideString).Size := C_FD_DefStrSize;
AParams.Columns.Add('Type', dtWideString).Size := C_FD_DefMaxStrSize;
AParams.Columns.Add('DefVal', dtWideString).Size := C_FD_DefStrSize;
AParams.Columns.Add('Caption', dtWideString).Size := C_FD_DefStrSize;
AParams.Columns.Add('LoginIndex', dtInt32);
end;
Result := AParams;
s := '';
for i := 0 to FManager.FDriverList.Count - 1 do begin
if s <> '' then
s := s + ';';
s := s + TFDPhysDriver(FManager.FDriverList[i]).DriverID;
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_DriverID, s, GetDriverID, S_FD_ConnParam_Common_DriverID, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Pooled, '@L', S_FD_False, S_FD_ConnParam_Common_Pooled, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Database, '@S', '', S_FD_ConnParam_Common_Database, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_UserName, '@S', '', S_FD_ConnParam_Common_BDEStyleUserName, 0]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Password, '@P', '', S_FD_ConnParam_Common_Password, 1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MonitorBy, S_FD_MoniFlatFile + ';' + S_FD_MoniRemote + ';' + S_FD_MoniCustom, '', S_FD_ConnParam_Common_MonitorBy, -1]);
if (AKeys <> nil) and
(CompareText(AKeys.Values[S_FD_ConnParam_Common_Pooled], S_FD_True) = 0) then begin
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Pool_CleanupTimeout, '@I', IntToStr(C_FD_PoolCleanupTimeout), S_FD_ConnParam_Common_Pool_CleanupTimeout, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Pool_ExpireTimeout, '@I', IntToStr(C_FD_PoolExpireTimeout), S_FD_ConnParam_Common_Pool_ExpireTimeout, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Pool_MaximumItems, '@I', IntToStr(C_FD_PoolMaximumItems), S_FD_ConnParam_Common_Pool_MaximumItems, -1]);
end;
end;
{ ----------------------------------------------------------------------------- }
// IFDStanObject
function TFDPhysDriver.GetName: TComponentName;
begin
Result := GetDriverID;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriver.GetParent: IFDStanObject;
begin
Supports(FDPhysManager, IFDStanObject, Result);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.AfterReuse;
begin
// nothing
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.BeforeReuse;
begin
// nothing
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriver.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
// nothing
end;
{ ----------------------------------------------------------------------------- }
{ TFDPhysDriverLink }
{ ----------------------------------------------------------------------------- }
constructor TFDPhysDriverLink.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDPhysManager();
FDPhysManagerObj.FLock.Enter;
FDPhysManagerObj.FDriverLinkList.Add(Self);
FDPhysManagerObj.FLock.Leave;
FServiceList := TFDObjList.Create;
SetUpdateDriverIDs;
end;
{ ----------------------------------------------------------------------------- }
destructor TFDPhysDriverLink.Destroy;
var
i: Integer;
begin
for i := FServiceList.Count - 1 downto 0 do
TFDPhysDriverService(FServiceList[i]).DriverLink := nil;
if FDPhysManagerObj <> nil then begin
FDPhysManagerObj.FLock.Enter;
FDPhysManagerObj.FDriverLinkList.Remove(Self);
FDPhysManagerObj.FLock.Leave;
end;
FDFreeAndNil(FServiceList);
SetUpdateDriverIDs;
inherited Destroy;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverLink.SetDriverID(const AValue: String);
begin
if FDriverID <> AValue then begin
FDriverID := AValue;
SetUpdateDriverIDs;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverLink.SetUpdateDriverIDs;
begin
if FDPhysManagerObj <> nil then
FDPhysManagerObj.FUpdateDriverIDs := True;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriverLink.GetBaseDriverID: String;
begin
ASSERT(False);
Result := '';
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriverLink.GetActualDriverID: String;
begin
if DriverID = '' then
Result := BaseDriverID
else
Result := DriverID;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriverLink.GetDriverIntf: IFDPhysDriver;
begin
FDPhysManager.CreateDriver(ActualDriverID, Result, True);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriverLink.GetDriverState: TFDPhysDriverState;
var
oDrv: TFDPhysDriver;
begin
Result := drsUnknown;
if FDPhysManagerObj <> nil then begin
oDrv := FDPhysManagerObj.DriverByID(ActualDriverID, fomIfActive, False);
if oDrv <> nil then begin
Result := oDrv.State;
oDrv.FLock.Leave;
end;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverLink.Release;
var
oDrv: TFDPhysDriver;
begin
if FDPhysManagerObj <> nil then begin
oDrv := FDPhysManagerObj.DriverByID(ActualDriverID, fomIfActive, False);
if oDrv <> nil then
try
if oDrv.GetConnectionCount > 0 then
FDException(Self, [S_FD_LPhys], er_FD_AccCannotReleaseDrv, [ActualDriverID]);
finally
if oDrv._Release > 0 then
oDrv.FLock.Leave;
end;
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriverLink.IsConfigured: Boolean;
begin
Result := (FVendorHome <> '') or (FVendorLib <> '') or (FDriverID <> '');
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverLink.ApplyTo(const AParams: IFDStanDefinition);
begin
if FVendorHome <> '' then
AParams.AsString[S_FD_DrvVendorHome] := FVendorHome;
if FVendorLib <> '' then
AParams.AsString[S_FD_DrvVendorLib] := FVendorLib;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverLink.SetupDef(const AParams: IFDStanDefinition);
begin
SetUpdateDriverIDs;
AParams.AsString[C_FD_DrvBaseId] := BaseDriverID;
if IsConfigured then
ApplyTo(AParams);
AParams.MarkUnchanged;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriverLink.GetServices(AIndex: Integer): TFDPhysDriverService;
begin
Result := TFDPhysDriverService(FServiceList[AIndex]);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriverLink.GetServicesCount: Integer;
begin
Result := FServiceList.Count;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverLink.DoDriverCreated;
var
i: Integer;
oSvc: TFDPhysDriverService;
begin
if Assigned(FOnDriverCreated) then
FOnDriverCreated(Self);
for i := 0 to FServiceList.Count - 1 do begin
oSvc := TFDPhysDriverService(FServiceList[i]);
if oSvc.ActualActive then
oSvc.InternalInstall;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverLink.DoDriverDestroying;
var
i: Integer;
oSvc: TFDPhysDriverService;
begin
for i := 0 to FServiceList.Count - 1 do begin
oSvc := TFDPhysDriverService(FServiceList[i]);
if oSvc.ActualActive then
oSvc.InternalUnInstall;
end;
if Assigned(FOnDriverDestroying) then
FOnDriverDestroying(Self);
end;
{ ----------------------------------------------------------------------------- }
{ TFDPhysDriverService }
{ ----------------------------------------------------------------------------- }
destructor TFDPhysDriverService.Destroy;
begin
Active := False;
DriverLink := nil;
inherited Destroy;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
if AComponent = DriverLink then
DriverLink := nil;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriverService.GetActualActive: Boolean;
begin
Result := (DriverLink <> nil) and Active;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.CheckActive(AAutoActivate, ANeedActivation: Boolean);
begin
if DriverLink = nil then
FDException(Self, [S_FD_LPhys], er_FD_SvcLinkMBSet, []);
if AAutoActivate and not Active then
Active := True;
if ANeedActivation and not Active then
FDException(Self, [S_FD_LPhys, DriverLink.ActualDriverID], er_FD_SvcMBActive, []);
if FDPhysManager().State = dmsInactive then
FDPhysManager().Open;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.SetActive(const AValue: Boolean);
begin
if FActive <> AValue then
if csReading in ComponentState then
FStreamingActive := AValue
else begin
FActive := AValue;
if DriverLink <> nil then
if AValue then begin
if DriverLink.DriverState in [drsLoaded, drsActive] then
InternalInstall;
end
else
InternalUninstall;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.Loaded;
begin
inherited Loaded;
if FStreamingActive then
Active := True;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.SetDriverLink(const AValue: TFDPhysDriverLink);
begin
if FDriverLink <> AValue then begin
Active := False;
if FDriverLink <> nil then
FDriverLink.FServiceList.Remove(Self);
FDriverLink := AValue;
if FDriverLink <> nil then
FDriverLink.FServiceList.Add(Self);
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysDriverService.GetCliObj: TObject;
begin
Result := DriverLink.DriverIntf.CliObj;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
begin
if Assigned(FOnError) then
FOnError(Self, AInitiator as TObject, AException);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.Execute;
var
oDrv: IFDPhysDriver;
oWait: IFDGUIxWaitCursor;
begin
FDCreateInterface(IFDGUIxWaitCursor, oWait);
oWait.StartWait;
try
DoBeforeExecute;
CheckActive(False, False);
oDrv := DriverLink.DriverIntf;
try
oDrv.Employ;
try
InternalExecute;
finally
oDrv.Vacate;
end;
finally
oDrv := nil;
end;
DoAfterExecute;
finally
oWait.StopWait;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.InternalInstall;
begin
// nothing
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.InternalUninstall;
begin
// nothing
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.InternalExecute;
begin
// nothing
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.DoBeforeExecute;
begin
if Assigned(BeforeExecute) then
BeforeExecute(Self);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysDriverService.DoAfterExecute;
begin
if Assigned(AfterExecute) then
AfterExecute(Self);
end;
{ ----------------------------------------------------------------------------- }
{ TFDPhysConnectionHost }
{ ----------------------------------------------------------------------------- }
constructor TFDPhysConnectionHost.Create(ADriver: TFDPhysDriver;
const AConnectionDef: IFDStanConnectionDef);
begin
inherited Create;
FDriverObj := ADriver;
FDriverObj.FLock.Enter;
FDriverObj.FConnHostList.Add(Self);
FDriverObj.FLock.Leave;
FPassCode := Random($7FFFFFFF);
FConnectionDef := AConnectionDef;
{$IFDEF FireDAC_MONITOR}
FInitialTracing := True;
if FConnectionDef.Params.MonitorBy <> mbNone then
AddMoniClient;
{$ENDIF}
if FConnectionDef.Params.Pooled and not FDIsDesignTime then begin
if FConnectionDef.Style <> atTemporary then
FConnectionDef.ToggleUpdates(FPassCode, True, True);
FDCreateInterface(IFDStanObjectFactory, FPool);
FPool.Open(Self, FConnectionDef);
end
else
if FConnectionDef.Style <> atTemporary then
FConnectionDef.ToggleUpdates(FPassCode, True, False);
end;
{ ----------------------------------------------------------------------------- }
destructor TFDPhysConnectionHost.Destroy;
begin
ASSERT(FConnectionCount = 0);
FDriverObj.FLock.Enter;
FDriverObj.FConnHostList.Remove(Self);
FDriverObj.FLock.Leave;
if FConnectionDef.Style = atTemporary then begin
if FConnectionDef.ParentDefinition <> nil then
FConnectionDef.ParentDefinition := nil;
end
else
FConnectionDef.ToggleUpdates(FPassCode, False, False);
FPassCode := 0;
FDriverObj := nil;
FConnectionDef := nil;
FPool := nil;
{$IFDEF FireDAC_MONITOR}
FMonitor := nil;
{$ENDIF}
inherited Destroy;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnectionHost._AddRef: Integer;
begin
Result := -1;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnectionHost._Release: Integer;
begin
Result := -1;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnectionHost.Employ;
begin
if AtomicIncrement(FConnectionCount) = 1 then
if FConnectionDef.Style <> atTemporary then
FConnectionDef.ToggleUpdates(FPassCode, True, True);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnectionHost.Vacate;
begin
if AtomicDecrement(FConnectionCount) = 0 then
if FConnectionDef.Style <> atTemporary then
FConnectionDef.ToggleUpdates(FPassCode, True, False)
else if not FConnectionDef.Params.Pooled then
FDFree(Self);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnectionHost.GetObjectKindName: TComponentName;
begin
Result := 'connection';
if (FConnectionDef <> nil) and (FConnectionDef.Name <> '') then
Result := Result + ' ' + FConnectionDef.Name;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnectionHost.CreateObject(out AObject: IFDStanObject);
begin
AObject := FDriverObj.InternalCreateConnection(Self) as IFDStanObject;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnectionHost.CreateConnection(out AConn: IFDPhysConnection);
var
oObj: IFDStanObject;
begin
if FConnectionDef.Params.Pooled and not FDIsDesignTime then begin
FPool.Acquire(oObj);
Supports(oObj, IFDPhysConnection, AConn);
end
else
AConn := FDriverObj.InternalCreateConnection(Self) as IFDPhysConnection;
end;
{ ----------------------------------------------------------------------------- }
{$IFDEF FireDAC_MONITOR}
procedure TFDPhysConnectionHost.AddMoniClient;
var
rGUID: TGUID;
oClnt: IUnknown;
begin
FMonitor := nil;
case FConnectionDef.Params.MonitorBy of
mbFlatFile: rGUID := IFDMoniFlatFileClient;
mbRemote: rGUID := IFDMoniRemoteClient;
mbCustom: rGUID := IFDMoniCustomClient;
else Exit;
end;
FInitialTracing := FConnectionDef.Params.MonitorByInitial;
FDCreateInterface(rGUID, oClnt);
FMonitor := oClnt as IFDMoniClient;
end;
{$ENDIF}
{ ----------------------------------------------------------------------------- }
{ TFDPhysConnection }
{ ----------------------------------------------------------------------------- }
constructor TFDPhysConnection.Create(ADriverObj: TFDPhysDriver;
AConnHost: TFDPhysConnectionHost);
begin
FDriver := ADriverObj as IFDPhysDriver;
FDriverObj := ADriverObj;
FDriverObj.FLock.Enter;
try
FMoniAdapterHelper := TFDMoniAdapterHelper.Create(Self, FDriverObj);
{$IFDEF FireDAC_MONITOR}
FMonitor := AConnHost.FMonitor;
if FMonitor <> nil then begin
FTracing := AConnHost.FInitialTracing;
TracingChanged;
end;
if GetTracing then
FMonitor.Notify(ekLiveCycle, esProgress, Self, 'CreateConnection',
['ConnectionDef', AConnHost.ConnectionDef.Name]);
{$ENDIF}
inherited Create;
FState := csDisconnected;
FPoolManaged := (AConnHost.FPool <> nil);
FLoginPrompt := False;
FDriverObj.FConnectionList.Add(Self);
FConnHost := AConnHost;
FConnHost.Employ;
if FConnHost.FConnectionDef.Style <> atTemporary then begin
FDCreateInterface(IFDStanConnectionDef, FInternalConnectionDef);
FInternalConnectionDef.ParentDefinition := FConnHost.ConnectionDef;
end;
FLock := TCriticalSection.Create;
FCommandList := TFDPtrList.Create;
FTransactionList := TFDPtrList.Create;
FEventList := TFDPtrList.Create;
SetOptions(nil);
ConnectionDef.ReadOptions(FOptions.FormatOptions, FOptions.UpdateOptions,
FOptions.FetchOptions, FOptions.ResourceOptions);
CheckTransaction;
finally
FDriverObj.FLock.Leave;
end;
end;
{ ----------------------------------------------------------------------------- }
destructor TFDPhysConnection.Destroy;
begin
{$IFNDEF AUTOREFCOUNT}
FDHighRefCounter(FRefCount);
{$ENDIF}
FDriverObj.FLock.Enter;
try
{$IFDEF FireDAC_MONITOR}
if GetTracing then
FMonitor.Notify(ekLiveCycle, esProgress, Self, 'DestroyConnection',
['ConnectionDef', ConnectionDef.Name]);
{$ENDIF}
try
if FCommandList <> nil then
ForceDisconnect;
FDriverObj.FConnectionList.Remove(Self);
FTransactionObj := nil;
FTransaction := nil;
SetErrorHandler(nil);
SetLogin(nil);
FDFreeAndNil(FMetadata);
FDFreeAndNil(FCommandList);
FDFreeAndNil(FTransactionList);
FDFreeAndNil(FEventList);
FOptions := nil;
FDFreeAndNil(FLock);
inherited Destroy;
finally
FDFree(FMoniAdapterHelper);
FMoniAdapterHelper := nil;
{$IFDEF FireDAC_MONITOR}
SetTracing(False);
FMonitor := nil;
{$ENDIF}
end;
finally
FDriverObj.FLock.Leave;
if FConnHost <> nil then
FConnHost.Vacate;
FConnHost := nil;
FInternalConnectionDef := nil;
FDriverObj := nil;
FDriver := nil;
{$IFNDEF AUTOREFCOUNT}
FRefCount := 0;
{$ENDIF}
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.Lock;
begin
FLock.Enter;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.Unlock;
begin
FLock.Leave;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection._AddRef: Integer;
begin
Result := inherited _AddRef;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection._Release: Integer;
procedure ReleaseToPool;
var
oPoolItem: IFDStanObject;
begin
Lock;
try
if not FPoolManaged then begin
Supports(TObject(Self), IFDStanObject, oPoolItem);
FConnHost.FPool.Release(oPoolItem);
AtomicDecrement(FRefCount);
Pointer(oPoolItem) := nil;
end;
finally
UnLock;
end;
end;
begin
Result := AtomicDecrement(FRefCount);
if Result <= 1 then
if (Result = 1) and (FConnHost <> nil) and (FConnHost.FPool <> nil) then
ReleaseToPool
else if Result = 0 then
FDFree(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.GetState: TFDPhysConnectionState;
begin
Result := FState;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetDriverID: String;
begin
if FDriverObj <> nil then
Result := FDriverObj.FDriverID
else
Result := '';
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
// Tracing
procedure TFDPhysConnection.Trace(AKind: TFDMoniEventKind;
AStep: TFDMoniEventStep; const AMsg: String; const AArgs: array of const);
begin
if GetTracing then
FMonitor.Notify(AKind, AStep, Self, AMsg, AArgs);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetTracing: Boolean;
begin
Result := FTracing and (FMonitor <> nil) and FMonitor.Tracing;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.SetTracing(AValue: Boolean);
var
lPrevTracing: Boolean;
begin
lPrevTracing := GetTracing;
if AValue <> FTracing then begin
FTracing := AValue;
if lPrevTracing <> GetTracing then
TracingChanged;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.TracingChanged;
begin
InternalTracingChanged;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.InternalTracingChanged;
begin
// nothing
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetMonitor: IFDMoniClient;
begin
Result := FMonitor;
end;
{$ENDIF}
{ ----------------------------------------------------------------------------- }
// Get interfaces
function TFDPhysConnection.GetDriver: IFDPhysDriver;
begin
Result := FDriver;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.CreateCommandGenerator(out AGen: IFDPhysCommandGenerator;
const ACommand: IFDPhysCommand);
begin
AGen := InternalCreateCommandGenerator(ACommand) as IFDPhysCommandGenerator;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.CreateMetadata(out AConnMeta: IFDPhysConnectionMetadata);
begin
if FMetadata = nil then
FMetadata := InternalCreateMetadata;
Supports(FMetadata, IFDPhysConnectionMetadata, AConnMeta);
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetCliObj: Pointer;
begin
Result := nil;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.InternalGetCliHandle: Pointer;
begin
Result := nil;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetCliHandle: Pointer;
begin
FCliHandles.FDriverCliHandles := InternalGetCliHandle;
if (GetTransaction <> nil) and GetTransaction.Active then
FCliHandles.FTxSerialID := NativeUInt(GetTransaction.SerialID)
else
FCliHandles.FTxSerialID := 0;
StrCopy(@FCliHandles.FDriverID, PChar(GetDriverID));
Result := @FCliHandles;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.InternalGetSharedCliHandle: Pointer;
begin
if FSharedHandle <> nil then
Result := FSharedHandle^.FDriverCliHandles
else
Result := nil;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetSharedCliHandle: Pointer;
begin
Result := FSharedHandle;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.SetSharedCliHandle(AValue: Pointer);
begin
CheckInactive;
FSharedHandle := PFDPhysCliHandles(AValue);
end;
{ ----------------------------------------------------------------------------- }
// Options interface
procedure TFDPhysConnection.GetParentOptions(var AOpts: IFDStanOptions);
begin
AOpts := FDriverObj.FManager.GetOptions;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetOptions: IFDStanOptions;
begin
Result := Self as IFDStanOptions;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.SetOptions(const AValue: IFDStanOptions);
begin
if (FOptions <> AValue) or (FMetadata = nil) then begin
FOptions := AValue;
if FOptions = nil then
FOptions := TFDOptionsContainer.Create(nil, TFDFetchOptions,
TFDUpdateOptions, TFDTopResourceOptions, GetParentOptions);
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetConnectionDef: IFDStanConnectionDef;
begin
if FInternalConnectionDef <> nil then
Result := FInternalConnectionDef
else
Result := FConnHost.ConnectionDef;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetMessages: EFDDBEngineException;
begin
Result := nil;
end;
{ ----------------------------------------------------------------------------- }
// Transactions
function TFDPhysConnection.GetTransactionCount: Integer;
begin
Result := FTransactionList.Count;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetTransactions(AIndex: Integer): IFDPhysTransaction;
begin
Lock;
try
Result := TFDPhysTransaction(FTransactionList[AIndex]) as IFDPhysTransaction;
finally
Unlock;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.CreateTransaction(out ATx: IFDPhysTransaction);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekLiveCycle, esProgress, 'CreateTransaction', ['ConnectionDef', ConnectionDef.Name]);
end;
{$ENDIF}
var
oTxObj: TFDPhysTransaction;
oConnMeta: IFDPhysConnectionMetadata;
lCreate: Boolean;
begin
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace1;
{$ENDIF}
lCreate := FTransactionList.Count = 0;
if not lCreate then begin
CreateMetadata(oConnMeta);
lCreate := oConnMeta.TxMultiple;
end;
if lCreate then begin
oTxObj := InternalCreateTransaction;
if GetState = csConnected then
oTxObj.InternalAllocHandle;
end
else
oTxObj := TFDPhysTransaction(FTransactionList[0]);
ATx := oTxObj as IFDPhysTransaction;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetTransaction: IFDPhysTransaction;
begin
Result := FTransaction;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.SetTransaction(const AValue: IFDPhysTransaction);
var
oTxObj: TFDPhysTransaction;
begin
if AValue <> FTransaction then begin
if FTransactionObj <> nil then begin
if GetState in [csConnecting, csConnected] then
FTransactionObj.InternalUnselect;
FTransactionObj.FConnection := FTransactionObj.FConnectionObj as IFDPhysConnection;
end;
FTransaction := nil;
FTransactionObj := nil;
if AValue <> nil then begin
oTxObj := AValue as TFDPhysTransaction;
if oTxObj.FConnectionObj <> Self then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccCantAssignTxIntf, []);
FTransaction := AValue;
FTransactionObj := oTxObj;
if GetState in [csConnecting, csConnected] then
FTransactionObj.InternalSelect;
FTransactionObj.FConnection := nil;
end;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.CheckTransaction;
var
oTx: IFDPhysTransaction;
begin
if FTransaction = nil then begin
CreateTransaction(oTx);
SetTransaction(oTx);
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.AllocTransactionHandles;
var
i: Integer;
oTran: TFDPhysTransaction;
begin
if (FTransactionList.Count > 0) and
(GetSharedCliHandle() <> nil) and (FSharedHandle^.FTxSerialID > 0) then begin
oTran := TFDPhysTransaction(FTransactionList[0]);
oTran.FSerialID := FSharedHandle^.FTxSerialID;
FSharedHandle^.FTxSerialID := 0;
oTran.FSharedActive := True;
oTran.TransactionStarted;
end;
for i := 0 to FTransactionList.Count - 1 do
TFDPhysTransaction(FTransactionList[i]).InternalAllocHandle;
if (GetState in [csConnecting, csConnected]) and (FTransactionObj <> nil) then
FTransactionObj.InternalSelect;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.ReleaseTransactionHandles;
var
i: Integer;
begin
if (GetState in [csConnecting, csConnected]) and (FTransactionObj <> nil) then
FTransactionObj.InternalUnSelect;
for i := 0 to FTransactionList.Count - 1 do
TFDPhysTransaction(FTransactionList[i]).ReleaseHandleBase;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.DisconnectTransactions;
var
i: Integer;
begin
for i := 0 to FTransactionList.Count - 1 do
TFDPhysTransaction(FTransactionList[i]).Disconnect;
end;
{ ----------------------------------------------------------------------------- }
// Events
function TFDPhysConnection.GetEventCount: Integer;
begin
Result := FEventList.Count;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetEvents(AIndex: Integer): IFDPhysEventAlerter;
begin
Lock;
try
Result := TFDPhysEventAlerter(FEventList[AIndex]) as IFDPhysEventAlerter;
finally
Unlock;
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter;
begin
Result := nil;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.CreateEvent(const AEventKind: String; out AEvent: IFDPhysEventAlerter);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekLiveCycle, esProgress, 'CreateEvent', ['EventKind', AEventKind,
'ConnectionDef', ConnectionDef.Name]);
end;
{$ENDIF}
var
oEventObj: TFDPhysEventAlerter;
oMeta: IFDPhysConnectionMetadata;
sEvent: String;
i: Integer;
begin
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace1;
{$ENDIF}
CreateMetadata(oMeta);
if not oMeta.EventSupported then
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
if AEventKind <> '' then
sEvent := AEventKind
else begin
i := 1;
sEvent := FDExtractFieldName(oMeta.EventKinds, i);
end;
oEventObj := InternalCreateEvent(sEvent);
if oEventObj = nil then
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
AEvent := oEventObj as IFDPhysEventAlerter;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.DisconnectEvents;
var
i: Integer;
begin
for i := 0 to FEventList.Count - 1 do
TFDPhysEventAlerter(FEventList[i]).Unregister;
end;
{ ----------------------------------------------------------------------------- }
// Commands
function TFDPhysConnection.GetCommandCount: Integer;
begin
Result := FCommandList.Count;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetCommands(AIndex: Integer): IFDPhysCommand;
begin
Lock;
try
Result := TFDPhysCommand(FCommandList[AIndex]) as IFDPhysCommand;
finally
UnLock;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.CreateCommand(out ACmd: IFDPhysCommand);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekLiveCycle, esProgress, 'CreateCommand', ['ConnectionDef', ConnectionDef.Name]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace1;
{$ENDIF}
ACmd := InternalCreateCommand as IFDPhysCommand;
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.InternalCreateMetaInfoCommand: TFDPhysCommand;
begin
Result := InternalCreateCommand;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.CreateMetaInfoCommand(out AMetaCmd: IFDPhysMetaInfoCommand);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekLiveCycle, esProgress, 'CreateMetaInfoCommand', ['ConnectionDef', ConnectionDef.Name]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace1;
{$ENDIF}
AMetaCmd := InternalCreateMetaInfoCommand as IFDPhysMetaInfoCommand;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.InternalOverrideNameByCommand(
var AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand);
var
oConnMeta: IFDPhysConnectionMetadata;
begin
CreateMetadata(oConnMeta);
if (AParsedName.FCatalog = '') and (npCatalog in oConnMeta.NameParts) and
not (npCatalog in FAvoidImplicitMeta) then
AParsedName.FCatalog := GetCurrentCatalog;
if (AParsedName.FSchema = '') and (npSchema in oConnMeta.NameParts) and
not (npSchema in FAvoidImplicitMeta) then
AParsedName.FSchema := GetCurrentSchema;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.DisconnectCommands;
var
i: Integer;
oCmd: TFDPhysCommand;
begin
for i := FCommandList.Count - 1 downto 0 do begin
oCmd := TFDPhysCommand(FCommandList[i]);
if GetState = csRecovering then
oCmd.AbortJob(True);
oCmd.Disconnect;
end;
end;
{ ----------------------------------------------------------------------------- }
// Exception handling
function TFDPhysConnection.GetErrorHandler: IFDStanErrorHandler;
begin
Result := FErrorHandler;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.SetErrorHandler(const AValue: IFDStanErrorHandler);
begin
FErrorHandler := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
begin
{$IFDEF FireDAC_MONITOR}
if not (AException is EFDDBEngineException) and GetTracing then
Trace(ekError, esProgress, AException.Message, []);
{$ENDIF}
if Assigned(GetErrorHandler()) then
GetErrorHandler().HandleException(AInitiator, AException);
end;
{-------------------------------------------------------------------------------}
// Connection management
procedure TFDPhysConnection.CheckActive(ADisconnectingAllowed: Boolean = False);
begin
if not ADisconnectingAllowed and not (FState in [csConnected, csRecovering]) or
ADisconnectingAllowed and not (FState in [csConnected, csDisconnecting, csRecovering]) then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccSrvMBConnected, []);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.CheckInactive;
begin
if FState <> csDisconnected then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccSrvMBDisConnected, []);
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.GetLogin: IFDGUIxLoginDialog;
begin
Result := FLogin;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.SetLogin(const AValue: IFDGUIxLoginDialog);
begin
if FLogin <> nil then
FLogin.ConnectionDef := nil;
FLogin := AValue;
if FLogin <> nil then
FLogin.ConnectionDef := ConnectionDef;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysConnection.GetLoginPrompt: Boolean;
begin
Result := FLoginPrompt;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.SetLoginPrompt(const AValue: Boolean);
begin
FLoginPrompt := AValue;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.BeforeReuse;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekLiveCycle, esProgress, 'BeforeReuse', ['ConnectionDef', ConnectionDef.Name]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace1;
{$ENDIF}
FPoolManaged := False;
// The connecting / pinging moved out of here to Open. This enables
// automatic connection recovery for pooled connections. Because at this
// moment TFDConnection recovery handler and options are not yet set.
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.AfterReuse;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekLiveCycle, esProgress, 'AfterReuse', ['ConnectionDef', ConnectionDef.Name]);
end;
{$ENDIF}
var
i: Integer;
begin
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace1;
{$ENDIF}
FPoolManaged := True;
DisconnectCommands;
DisconnectEvents;
DisconnectTransactions;
for i := 0 to FTransactionList.Count - 1 do
TFDPhysTransaction(FTransactionList[i]).SetOptions(nil);
SetOptions(nil);
SetErrorHandler(nil);
SetOwner(nil, '');
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.ForceDisconnect;
var
i: Integer;
oCmd: TFDPhysCommand;
begin
Lock;
try
for i := FCommandList.Count - 1 downto 0 do
try
oCmd := TFDPhysCommand(FCommandList[i]);
if oCmd.GetState in [csExecuting, csFetching] then
oCmd.AbortJob(True);
oCmd.Disconnect;
except
// hide exceptions
end;
if GetState = csConnected then
Close;
finally
UnLock;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.ConnectBase;
begin
FDriver.Employ;
try
InternalConnect;
try
AllocTransactionHandles;
InternalSetMeta;
except
ReleaseTransactionHandles;
raise;
end;
except
try
InternalDisconnect;
finally
FDriver.Vacate;
end;
raise;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.DoConnect;
var
lConnected: Boolean;
begin
lConnected := False;
repeat
try
ConnectBase;
lConnected := True;
except
on E: EFDDBEngineException do
if E.Kind = ekServerGone then
RecoverConnection(Self, True)
else
raise;
end;
until lConnected;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.DoLogin;
procedure LoginAborted;
var
s: String;
begin
s := ConnectionDef.Name;
if s = '' then
s := S_FD_Unnamed;
FDException(Self, [S_FD_LPhys, DriverID], er_FD_ClntDbLoginAborted, [s]);
end;
var
oDlg: IFDGUIxLoginDialog;
begin
if not Assigned(FLogin) then begin
FDCreateInterface(IFDGUIxLoginDialog, oDlg, False);
if oDlg = nil then begin
DoConnect;
Exit;
end;
oDlg.ConnectionDef := ConnectionDef;
end
else
oDlg := FLogin;
try
if not oDlg.Execute(DoConnect) then
LoginAborted;
finally
if not Assigned(FLogin) then
oDlg.ConnectionDef := nil;
end;
end;
{ ----------------------------------------------------------------------------- }
{$IFDEF FireDAC_MONITOR}
procedure TFDPhysConnection.TraceList(AList: TStrings; const AName: String);
var
i: Integer;
begin
if AList.Count > 0 then begin
Trace(ekConnConnect, esStart, AName, []);
for i := 0 to AList.Count - 1 do
Trace(ekConnConnect, esProgress, AList[i], []);
Trace(ekConnConnect, esEnd, AName, []);
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.TraceConnInfo(AKind: TFDMoniAdapterItemKind;
const AName: String);
var
i: Integer;
sName: String;
vVal: Variant;
eKind: TFDMoniAdapterItemKind;
oList: TFDStringList;
begin
oList := TFDStringList.Create;
try
FTracing := False;
try
for i := 0 to GetItemCount - 1 do begin
sName := '';
vVal := Unassigned;
eKind := ikStat;
GetItem(i, sName, vVal, eKind);
if eKind = AKind then
oList.Add(sName + '=' + VarToStr(vVal));
end;
finally
FTracing := True;
end;
TraceList(oList, AName);
finally
FDFree(oList);
end;
end;
{$ENDIF}
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.InternalSetMeta;
var
oConnDef: IFDStanConnectionDef;
procedure SetParam(var AParam: String; const AName: String;
var AFlags: TFDPhysNameParts; AFlag: TFDPhysNamePart);
begin
if oConnDef.HasValue(AName) then
AParam := oConnDef.AsString[AName];
if AParam = '*' then begin
Include(AFlags, AFlag);
AParam := '';
end;
end;
begin
oConnDef := ConnectionDef;
// get user specified default schema and catalog names
SetParam(FDefaultCatalog, S_FD_ConnParam_Common_MetaDefCatalog, FRemoveDefaultMeta, npCatalog);
SetParam(FDefaultSchema, S_FD_ConnParam_Common_MetaDefSchema, FRemoveDefaultMeta, npSchema);
// get user specified current schema and catalog names
SetParam(FCurrentCatalog, S_FD_ConnParam_Common_MetaCurCatalog, FAvoidImplicitMeta, npCatalog);
SetParam(FCurrentSchema, S_FD_ConnParam_Common_MetaCurSchema, FAvoidImplicitMeta, npSchema);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.Open;
var
oConnDef: IFDStanConnectionDef;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
if not FMoniAdapterHelper.IsRegistered then
FMoniAdapterHelper.RegisterClient(GetMonitor);
Trace(ekConnConnect, esStart, 'Open', ['ConnectionDef', oConnDef.Name]);
oConnDef.Trace(FMonitor);
TraceConnInfo(ikFireDACInfo, C_FD_Product + ' info');
end;
procedure Trace2;
begin
if FDriver.Messages <> nil then
TraceList(FDriver.Messages, 'Driver log');
TraceConnInfo(ikClientInfo, 'Client info');
if FState = csConnected then begin
UpdateMonitor;
TraceConnInfo(ikSessionInfo, 'Session info');
end;
Trace(ekConnConnect, esEnd, 'Open', ['ConnectionDef', oConnDef.Name]);
end;
{$ENDIF}
begin
oConnDef := ConnectionDef;
if oConnDef.Params.Pooled and (GetState = csConnected) then begin
if (GetOptions.ResourceOptions as TFDTopResourceOptions).AutoReconnect then
Ping;
Exit;
end;
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace1;
try
{$ENDIF}
Lock;
try
CheckInactive;
FState := csConnecting;
FDefaultCatalog := '';
FDefaultSchema := '';
FCurrentCatalog := '';
FCurrentSchema := '';
FRemoveDefaultMeta := [];
FAvoidImplicitMeta := [];
try
{$IFDEF FireDAC_MONITOR}
SetTracing((oConnDef.Params.MonitorBy <> mbNone) and FConnHost.FInitialTracing);
{$ENDIF}
if GetLoginPrompt and not oConnDef.Params.Pooled and not FDGUIxSilent() and
(GetSharedCliHandle() = nil) then
DoLogin
else
DoConnect;
// following is required to "refresh" metadata after connecting server
FDFreeAndNil(FMetadata);
FState := csConnected;
except
FState := csDisconnected;
raise;
end;
finally
UnLock;
end;
{$IFDEF FireDAC_MONITOR}
finally
if GetTracing then Trace2;
end;
{$ENDIF}
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.Close;
var
oConnDef: IFDStanConnectionDef;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekConnConnect, esStart, 'Close', ['ConnectionDef', oConnDef.Name]);
end;
procedure Trace2;
begin
Trace(ekConnConnect, esEnd, 'Close', ['ConnectionDef', oConnDef.Name]);
end;
{$ENDIF}
begin
oConnDef := ConnectionDef;
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace1;
try
{$ENDIF}
Lock;
try
CheckActive;
// If the state will be csDisconnecting, but the connection is broken
// and there were active transactions, then DisconnectTransactions will
// rollback them. That will lead to errors. So, leave csRecovering -
// means the connection is broken.
if FState <> csRecovering then
FState := csDisconnecting;
DisconnectCommands;
DisconnectEvents;
DisconnectTransactions;
ReleaseTransactionHandles;
InternalDisconnect;
// TFDPhysCommand.DoDefineDataTable, etc keep a reference to a metadata.
// If connection is failed and closed then AV will be raised at exiting
// from DoDefineDataTable, etc, because metadata reference is invalid.
// FDFreeAndNil(FMetadata);
finally
FDriver.Vacate;
FState := csDisconnected;
UnLock;
end;
{$IFDEF FireDAC_MONITOR}
finally
if GetTracing then Trace2;
end;
{$ENDIF}
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.ChangePassword(const ANewPassword: String);
begin
FDriver.Employ;
try
InternalChangePassword(ConnectionDef.Params.UserName, ConnectionDef.Params.Password,
ANewPassword);
finally
FDriver.Vacate;
end;
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.InternalChangePassword(const AUserName,
AOldPassword, ANewPassword: String);
begin
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
end;
{ ----------------------------------------------------------------------------- }
procedure TFDPhysConnection.DecPrepared;
begin
Lock;
Dec(FPreparedCommands);
UnLock;
end;
{ ----------------------------------------------------------------------------- }
function SortOnUsage(Item1, Item2: Pointer): Integer;
var
oCmdObj1, oCmdObj2: TFDPhysCommand;
begin
oCmdObj1 := TFDPhysCommand(Item1);
oCmdObj2 := TFDPhysCommand(Item2);
if oCmdObj1.FExecuteCount > oCmdObj2.FExecuteCount then
Result := -1
else if oCmdObj1.FExecuteCount < oCmdObj2.FExecuteCount then
Result := 1
else
Result := 0;
end;
{$IFDEF AUTOREFCOUNT}
type
TFDPhysCommandComparer = class(TInterfacedObject, IComparer<Pointer>)
function Compare(const Left, Right: Pointer): Integer;
end;
function TFDPhysCommandComparer.Compare(const Left, Right: Pointer): Integer;
begin
Result := SortOnUsage(Left, Right);
end;
{$ENDIF}
procedure TFDPhysConnection.IncPrepared(ACommand: TFDPhysCommand);
var
j, i, n: Integer;
oCmdObj: TFDPhysCommand;
oResOpts: TFDTopResourceOptions;
begin
Lock;
try
oResOpts := FOptions.ResourceOptions as TFDTopResourceOptions;
if (oResOpts.MaxCursors > 0) and
(FPreparedCommands + 1 > oResOpts.MaxCursors) then begin
FCommandList.Sort({$IFDEF AUTOREFCOUNT} TFDPhysCommandComparer.Create {$ELSE} SortOnUsage {$ENDIF});
n := (oResOpts.MaxCursors * C_FD_CrsPctClose) div 100;
i := 0;
for j := FCommandList.Count - 1 downto 0 do begin
oCmdObj := TFDPhysCommand(FCommandList[j]);
if oCmdObj <> ACommand then begin
oCmdObj.Disconnect;
Inc(i);
if i >= n then
Break;
end;
end;
end;
Inc(FPreparedCommands);
finally
UnLock;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.GetLastAutoGenValue(const AName: String = ''): Variant;
var
oCmd: IFDPhysCommand;
oGen: IFDPhysCommandGenerator;
oTab: TFDDatSTable;
oFtch: TFDFetchOptions;
oRes: TFDResourceOptions;
begin
if not VarIsNull(FLastAutoGenValue) and not VarIsEmpty(FLastAutoGenValue) then begin
Result := FLastAutoGenValue;
Exit;
end;
CreateCommand(oCmd);
CreateCommandGenerator(oGen, nil);
oFtch := oCmd.Options.FetchOptions;
oFtch.RowsetSize := 1;
oFtch.Items := oFtch.Items - [fiMeta];
oFtch.RecordCountMode := cmVisible;
oFtch.Mode := fmOnDemand;
oFtch.AutoFetchAll := afAll;
oRes := oCmd.Options.ResourceOptions;
if oRes.CmdExecMode = amAsync then
oRes.CmdExecMode := amBlocking;
oRes.DirectExecute := True;
oRes.Persistent := False;
oCmd.CommandText := oGen.GenerateReadGenerator(AName, '', False, True);
oCmd.CommandKind := oGen.CommandKind;
oTab := TFDDatSTable.Create;
try
oCmd.Define(oTab);
oCmd.Open;
oCmd.Fetch(oTab);
if oTab.Rows.Count > 0 then
Result := oTab.Rows[0].GetData(0)
else
Result := Null;
finally
FDFree(oTab);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.SaveLastAutoGenValue(const AValue: Variant);
begin
FLastAutoGenValue := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.Clone: IFDPhysConnection;
begin
FDriverObj.FManager.CreateConnection(ConnectionDef, Result);
Result.Options := GetOptions;
Result.ErrorHandler := GetErrorHandler;
Result.RecoveryHandler := GetRecoveryHandler;
Result.CurrentCatalog := GetCurrentCatalog;
Result.CurrentSchema := GetCurrentSchema;
if GetSharedCliHandle <> nil then begin
if Result.State in [csConnected, csRecovering] then
Result.Close;
Result.SharedCliHandle := GetSharedCliHandle;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.InternalAnalyzeSession(AMessages: TStrings);
var
oConnMeta: IFDPhysConnectionMetadata;
iVer: TFDVersion;
begin
CreateMetadata(oConnMeta);
// 1. Diff between clnt and srv versions must be <= 1 major version
iVer := oConnMeta.ServerVersion div 100000000 - oConnMeta.ClientVersion div 100000000;
if iVer < 0 then
iVer := -iVer;
if iVer > 1 then
AMessages.Add(Format(S_FD_PhysWarnMajVerDiff,
[FDVerInt2Str(oConnMeta.ClientVersion), FDVerInt2Str(oConnMeta.ServerVersion)]));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.AnalyzeSession(AMessages: TStrings);
begin
CheckActive(False);
AMessages.BeginUpdate;
try
AMessages.Clear;
InternalAnalyzeSession(AMessages);
finally
AMessages.EndUpdate;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.InternalGetCurrentCatalog: String;
begin
Result := ConnectionDef.Params.ExpandedDatabase;
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.GetCurrentCatalog: String;
var
oConnMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
begin
CreateMetadata(oConnMeta);
if npCatalog in oConnMeta.NameParts then begin
if FCurrentCatalog <> '' then
rName.FCatalog := FCurrentCatalog
else
rName.FCatalog := InternalGetCurrentCatalog;
Result := oConnMeta.EncodeObjName(rName, nil, [eoNormalize]);
end
else
Result := '';
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.SetCurrentCatalog(const AValue: String);
begin
FCurrentCatalog := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.InternalGetCurrentSchema: String;
begin
Result := ConnectionDef.AsString[S_FD_ConnParam_Common_UserName];
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.GetCurrentSchema: String;
var
oConnMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
begin
CreateMetadata(oConnMeta);
if npSchema in oConnMeta.NameParts then begin
if FCurrentSchema <> '' then
rName.FSchema := FCurrentSchema
else
rName.FSchema := InternalGetCurrentSchema;
Result := oConnMeta.EncodeObjName(rName, nil, [eoNormalize]);
end
else
Result := '';
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.SetCurrentSchema(const AValue: String);
begin
FCurrentSchema := AValue;
end;
{-------------------------------------------------------------------------------}
// Connection recovery
function TFDPhysConnection.GetRecoveryHandler: IFDPhysConnectionRecoveryHandler;
begin
Result := FRecoveryHandler;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.SetRecoveryHandler(const AValue: IFDPhysConnectionRecoveryHandler);
begin
FRecoveryHandler := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.RecoverConnection(const AInitiator: IFDStanObject; AOnLogin: Boolean);
var
oExc: TObject;
eAction: TFDPhysConnectionRecoverAction;
lDone, lAutoRetry, lRaised: Boolean;
i, iTrials: Integer;
oCmdList: TFDObjList;
oEvtList: TFDObjList;
oParsList: TFDObjList;
oCmd: TFDPhysCommand;
oPars: TFDParams;
oPrevMeta: TObject;
{$IFDEF FireDAC_MONITOR}
sDefName: String;
{$ENDIF}
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekConnConnect, esStart, 'RecoverConnection', ['ConnectionDef', sDefName]);
end;
procedure Trace2;
begin
Trace(ekConnConnect, esEnd, 'RecoverConnection', ['ConnectionDef', sDefName]);
end;
procedure Trace3;
begin
Trace(ekConnConnect, esProgress, 'HandleConnectionRecover', ['ConnectionDef', sDefName]);
end;
procedure Trace4;
begin
Trace(ekConnConnect, esProgress, 'HandleConnectionRestored', ['ConnectionDef', sDefName]);
end;
procedure Trace5;
begin
Trace(ekConnConnect, esProgress, 'HandleConnectionLost', ['ConnectionDef', sDefName]);
end;
{$ENDIF}
procedure ConnectionRecover(AExitState: TFDPhysConnectionState);
var
E: Exception;
begin
if not AOnLogin then
FState := csRecovering;
try
if Assigned(GetRecoveryHandler()) then begin
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace3;
{$ENDIF}
E := nil;
if oExc is Exception then
E := Exception(oExc);
GetRecoveryHandler().HandleConnectionRecover(AInitiator, E, eAction);
end;
finally
if not AOnLogin and (FState = csRecovering) then
FState := AExitState;
end;
end;
procedure ConnectionRestored(AExitState: TFDPhysConnectionState);
begin
FState := AExitState;
if Assigned(GetRecoveryHandler()) then begin
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace4;
{$ENDIF}
GetRecoveryHandler().HandleConnectionRestored();
end;
end;
procedure ConnectionLost(AExitState: TFDPhysConnectionState);
begin
if not AOnLogin and (FState = csRecovering) then
FState := csConnected;
try
if Assigned(GetRecoveryHandler()) then begin
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace4;
{$ENDIF}
GetRecoveryHandler().HandleConnectionLost();
end;
finally
if not AOnLogin and (FState = csRecovering) then
FState := AExitState;
end;
end;
begin
oExc := AcquireExceptionObject;
lRaised := False;
try
if not (rfInRecovery in FRecoveryFlags) and
(oExc is EFDDBEngineException) and (EFDDBEngineException(oExc).Kind = ekServerGone) and
(AOnLogin or (GetState = csConnected)) then begin
{$IFDEF FireDAC_MONITOR}
sDefName := ConnectionDef.Name;
if GetTracing then Trace1;
try
{$ENDIF}
Lock;
Include(FRecoveryFlags, rfInRecovery);
try
lDone := False;
lAutoRetry := False;
iTrials := 1;
eAction := faDefault;
ConnectionRecover(csConnected);
oCmdList := TFDObjList.Create;
oParsList := TFDObjList.Create;
oEvtList := TFDObjList.Create;
if not AOnLogin then begin
// TFDPhysCommand.DoDefineDataTable, etc keep a reference to a metadata.
// If connection is failed and restored then AV will be raised at exiting
// from DoDefineDataTable, etc, because metadata reference is invalid.
oPrevMeta := FMetadata;
FMetadata := nil;
end
else
oPrevMeta := nil;
try
for i := 0 to FCommandList.Count - 1 do begin
oCmd := TFDPhysCommand(FCommandList[i]);
if oCmd.GetState <> csInactive then begin
oCmdList.Add(oCmd);
if (oCmd.GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs]) and
(fiMeta in oCmd.GetOptions.FetchOptions.Items) then begin
oPars := TFDParams.Create;
oParsList.Add(oPars);
oPars.Assign(oCmd.GetParams);
end
else
oParsList.Add(nil);
end;
end;
for i := 0 to FEventList.Count - 1 do
if TFDPhysEventAlerter(FEventList[i]).GetState <> esInactive then
oEvtList.Add(FEventList[i]);
// Prohibit to call state handlers, otherwise datasets will be disconnected.
// But only Phys commands must be reprepared.
Include(FRecoveryFlags, rfEmergencyClose);
try
ForceDisconnect;
finally
Exclude(FRecoveryFlags, rfEmergencyClose);
end;
if eAction = faDefault then
if (FOptions.ResourceOptions as TFDTopResourceOptions).AutoReconnect then begin
eAction := faRetry;
lAutoRetry := True;
end
else
eAction := faFail;
repeat
case eAction of
faFail:
begin
ConnectionLost(csDisconnected);
lRaised := True;
raise oExc;
end;
faRetry:
begin
// if first trial, do not wait, may be DBMS is already available
if lAutoRetry and (iTrials > 1) then
Sleep(C_FD_PhysConnRetryDelay);
FState := csConnecting;
try
ConnectBase;
ConnectionRestored(csConnected);
lDone := True;
except
on EFDDBEngineException do begin
FState := csDisconnected;
FDFree(oExc);
if ExceptObject is Exception then
oExc := AcquireExceptionObject
else
oExc := nil;
ConnectionRecover(csDisconnected);
end;
end;
end;
faCloseAbort,
faOfflineAbort:
begin
ConnectionLost(csDisconnected);
Abort;
end;
end;
Inc(iTrials);
if (eAction = faRetry) and lAutoRetry and (iTrials > C_FD_PhysConnRetryCount) then begin
ConnectionLost(csDisconnected);
lRaised := True;
raise oExc;
end;
until lDone;
finally
if not AOnLogin then begin
FDFreeAndNil(FMetadata);
FMetadata := oPrevMeta;
end;
if GetState = csConnected then begin
for i := 0 to oCmdList.Count - 1 do begin
TFDPhysCommand(oCmdList[i]).Prepare();
if oParsList[i] <> nil then begin
TFDPhysCommand(oCmdList[i]).GetParams.AssignValues(TFDParams(oParsList[i]), [ptInput, ptInputOutput]);
FDFree(TFDParams(oParsList[i]));
end;
end;
for i := 0 to oEvtList.Count - 1 do
TFDPhysEventAlerter(oEvtList[i]).Register();
end;
FDFree(oCmdList);
FDFree(oParsList);
FDFree(oEvtList);
end;
finally
UnLock;
Exclude(FRecoveryFlags, rfInRecovery);
end;
{$IFDEF FireDAC_MONITOR}
finally
if GetTracing then Trace2;
end;
{$ENDIF}
end
else begin
lRaised := True;
raise oExc;
end;
finally
if not lRaised then
FDFree(oExc);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.Ping: Boolean;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekConnConnect, esStart, 'Ping', ['ConnectionDef', ConnectionDef.Name]);
end;
procedure Trace2;
begin
Trace(ekConnConnect, esEnd, 'Ping', ['ConnectionDef', ConnectionDef.Name]);
end;
{$ENDIF}
begin
Result := False;
if GetState in [csDisconnecting, csConnecting, csRecovering] then
Exit;
_AddRef;
try
{$IFDEF FireDAC_MONITOR}
if GetTracing then Trace1;
try
{$ENDIF}
case GetState of
csConnected:
try
InternalPing;
Result := True;
except
on E: EFDDBEngineException do
if E.Kind = ekServerGone then begin
RecoverConnection(Self, False);
Result := GetState = csConnected;
end;
end;
csDisconnected:
Open;
end;
{$IFDEF FireDAC_MONITOR}
finally
if GetTracing then Trace2;
end;
{$ENDIF}
finally
_Release;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.InternalPing;
var
oGen: IFDPhysCommandGenerator;
s: String;
begin
CreateCommandGenerator(oGen, nil);
s := oGen.GeneratePing;
if s <> '' then
InternalExecuteDirect(s, TransactionObj);
end;
{-------------------------------------------------------------------------------}
// IFDStanObject
function TFDPhysConnection.GetName: TComponentName;
begin
if FMoniAdapterHelper <> nil then
Result := FMoniAdapterHelper.Name
else
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.GetParent: IFDStanObject;
begin
if FMoniAdapterHelper <> nil then
Result := FMoniAdapterHelper.Parent
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
FMoniAdapterHelper.SetOwner(AOwner, ARole);
{$IFDEF FireDAC_MONITOR}
FMoniAdapterHelper.UnRegisterClient;
FMoniAdapterHelper.RegisterClient(GetMonitor);
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
// IFDMoniAdapter
function TFDPhysConnection.GetHandle: LongWord;
begin
if FMoniAdapterHelper = nil then
Result := 0
else
Result := FMoniAdapterHelper.Handle;
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.GetSupportItems: TFDMoniAdapterItemKinds;
begin
Result := [ikStat, ikFireDACInfo, ikClientInfo, ikSessionInfo];
end;
{-------------------------------------------------------------------------------}
function TFDPhysConnection.GetItemCount: Integer;
begin
Result := 6;
if GetState <> csDisconnected then
Inc(Result, 2);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysConnection.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
var
s: String;
iLen: Integer;
procedure Add(const AStr: String);
begin
if iLen + Length(AStr) + 1 > 50 then begin
s := s + C_FD_EOL + ' ';
iLen := 0;
end;
s := s + AStr + ';';
Inc(iLen, Length(AStr) + 1);
end;
begin
case AIndex of
0:
begin
AName := 'Commands';
AValue := FCommandList.Count;
AKind := ikStat;
end;
1:
begin
AName := 'Transactions';
AValue := FTransactionList.Count;
AKind := ikStat;
end;
2:
begin
AName := 'Tool';
AValue := C_FD_ToolName;
AKind := ikFireDACInfo;
end;
3:
begin
AName := C_FD_Product;
AValue := C_FD_Version;
AKind := ikFireDACInfo;
end;
4:
begin
AName := 'Platform';
AValue :=
{$IFDEF MSWINDOWS}
'Windows'
{$ENDIF}
{$IFDEF ANDROID}
'Android'
{$ENDIF}
{$IFDEF LINUX}
'Linux'
{$ENDIF}
{$IFDEF MACOS}
{$IFDEF IOS}
{$IFDEF CPUARM}
'iOS Device'
{$ELSE}
'iOS Emulator'
{$ENDIF}
{$ELSE}
'OS X'
{$ENDIF}
{$ENDIF}
{$IFDEF FireDAC_64}
+ ' 64 bit'
{$ENDIF}
{$IFDEF FireDAC_32}
+ ' 32 bit'
{$ENDIF}
;
AKind := ikFireDACInfo;
end;
5:
begin
AName := 'Defines';
s := '';
iLen := 0;
{$IFDEF FireDAC_NOLOCALE_DATA}
Add('FireDAC_NOLOCALE_DATA');
{$ENDIF}
{$IFDEF FireDAC_NOLOCALE_META}
Add('FireDAC_NOLOCALE_META');
{$ENDIF}
{$IFDEF FireDAC_MONITOR}
Add('FireDAC_MONITOR');
{$ENDIF}
{$IFDEF FireDAC_DEBUG}
Add('FireDAC_DEBUG');
{$ENDIF}
{$IFDEF FireDAC_SynEdit}
Add('FireDAC_SynEdit');
{$ENDIF}
{$IFDEF FireDAC_MOBILE}
Add('FireDAC_MOBILE');
{$ENDIF}
AValue := Copy(s, 1, Length(s) - 1);
AKind := ikFireDACInfo;
end;
6:
begin
AName := 'Current catalog';
AValue := FCurrentCatalog;
AKind := ikSessionInfo;
end;
7:
begin
AName := 'Current schema';
AValue := FCurrentSchema;
AKind := ikSessionInfo;
end;
end;
end;
{-------------------------------------------------------------------------------}
{$IFDEF FireDAC_MONITOR}
procedure TFDPhysConnection.UpdateMonitor;
begin
if GetTracing then
FMonitor.AdapterChanged(Self as IFDMoniAdapter);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TFDPhysTransaction }
{-------------------------------------------------------------------------------}
constructor TFDPhysTransaction.Create(AConnection: TFDPhysConnection);
begin
inherited Create;
FState := tsInactive;
FConnection := AConnection as IFDPhysConnection;
FConnectionObj := AConnection;
FConnectionObj.Lock;
FConnectionObj.FTransactionList.Add(Self);
FConnectionObj.UnLock;
FSavepoints := TFDStringList.Create;
SetOptions(nil);
FMoniAdapterHelper := TFDMoniAdapterHelper.Create(Self, AConnection);
FCommandList := TFDPtrList.Create;
FStateHandlerList := TInterfaceList.Create;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysTransaction.Destroy;
begin
Disconnect;
{$IFNDEF AUTOREFCOUNT}
FDHighRefCounter(FRefCount);
{$ENDIF}
try
if FConnectionObj.FTransactionObj = Self then
FConnectionObj.SetTransaction(nil);
FConnectionObj.Lock;
FConnectionObj.FTransactionList.Remove(Self);
FConnectionObj.UnLock;
InternalReleaseHandle;
FDFreeAndNil(FSavepoints);
FExternalOptions := nil;
FDFreeAndNil(FOptions);
FDFree(FMoniAdapterHelper);
FMoniAdapterHelper := nil;
FDFreeAndNil(FCommandList);
FDFreeAndNil(FStateHandlerList);
inherited Destroy;
finally
{$IFNDEF AUTOREFCOUNT}
FRefCount := 0;
{$ENDIF}
FConnectionObj := nil;
FConnection := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.Disconnect;
begin
if not (GetState in [tsCommiting, tsRollingback]) and
not (rfEmergencyClose in FConnectionObj.FRecoveryFlags) and
not FSharedActive then
case GetOptions.DisconnectAction of
xdCommit:
while GetActive do
Commit;
xdRollback:
while GetActive do
Rollback;
end;
TransactionFinished;
end;
{-------------------------------------------------------------------------------}
// Get/Set
function TFDPhysTransaction.GetActive: Boolean;
begin
Result := FSavepoints.Count > 0;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetOptions: TFDTxOptions;
begin
if FExternalOptions <> nil then
Result := FExternalOptions
else
Result := FOptions;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetSerialID: LongWord;
begin
if FSavepoints.Count > 0 then
Result := FSavepoints.Ints[FSavepoints.Count - 1]
else
Result := 0;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetTopSerialID: LongWord;
begin
if FSavepoints.Count > 0 then
Result := FSavepoints.Ints[0]
else
Result := 0;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetNestingLevel: LongWord;
begin
Result := FSavepoints.Count;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetConnection: IFDPhysConnection;
begin
Result := FConnectionObj as IFDPhysConnection;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetCliObj: Pointer;
begin
// nothing
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.SetOptions(const AValue: TFDTxOptions);
begin
if (FExternalOptions <> AValue) or (FCommandList = nil) then begin
FExternalOptions := AValue;
if FExternalOptions = nil then
FOptions := TFDTxOptions.Create
else
FDFreeAndNil(FOptions);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetState: TFDPhysTransactionState;
begin
Result := FState;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetDriverID: String;
begin
if FConnectionObj <> nil then
Result := FConnectionObj.DriverID
else
Result := '';
end;
{-------------------------------------------------------------------------------}
// Commands management
procedure TFDPhysTransaction.DisconnectCommands(AFilter: TFDPhysDisconnectFilter;
AMode: TFDPhysDisconnectMode);
var
i: Integer;
oCmd: TFDPhysCommand;
begin
if not (rfEmergencyClose in FConnectionObj.FRecoveryFlags) then
for i := FStateHandlerList.Count - 1 downto 0 do
IFDPhysTransactionStateHandler(FStateHandlerList[i]).HandleDisconnectCommands(AFilter, AMode);
for i := FCommandList.Count - 1 downto 0 do
if i < FCommandList.Count then begin
oCmd := TFDPhysCommand(FCommandList[i]);
if (oCmd.GetState <> csInactive) and (not Assigned(AFilter) or AFilter(oCmd.GetCliObj)) then begin
if oCmd.GetState in [csExecuting, csFetching, csAborting] then
oCmd.AbortJob(True);
case AMode of
dmOffline: oCmd.Disconnect;
dmRelease: oCmd.CloseAll;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.Stop(ASuccess: Boolean);
begin
if not (GetState in [tsCommiting, tsRollingback]) and
not (rfEmergencyClose in FConnectionObj.FRecoveryFlags) then
while GetActive do
try
if xoFinishRetaining in GetOptions.StopOptions then begin
if ASuccess then
CommitRetaining
else
RollbackRetaining;
if FSavepoints.Count <= 1 then
Exit;
end
else
if ASuccess then
Commit
else
Rollback;
except
on E: EFDDBEngineException do begin
if ASuccess and (E.Kind <> ekServerGone) then
Stop(False);
raise;
end;
end;
TransactionFinished;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.CheckStoping(AAllowUnprepare, AForce, ASuccess: Boolean);
var
i: Integer;
oCmd: TFDPhysCommand;
lStop: Boolean;
begin
lStop := True;
if not AForce then
for i := FCommandList.Count - 1 downto 0 do begin
oCmd := TFDPhysCommand(FCommandList[i]);
case oCmd.GetState of
csInactive:
;
csPrepared:
if not AAllowUnprepare or
(oCmd.GetOptions.FetchOptions.AutoFetchAll = afDisable) then begin
lStop := False;
Break;
end;
csExecuting,
csOpen,
csFetching,
csAborting:
begin
lStop := False;
Break;
end;
end;
end;
if lStop then
Stop(ASuccess);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.InternalCheckState(ACommandObj: TFDPhysCommand;
ASuccess: Boolean);
begin
if ASuccess then
case ACommandObj.GetCommandKind of
skStartTransaction: TransactionStarted;
skCommit: TransactionFinished;
skRollback: TransactionFinished;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.Notify(ANotification: TFDPhysTxNotification;
ACommandObj: TFDPhysCommand);
begin
if not (FState in [tsInactive, tsActive]) then
Exit;
// As result of InternalNotify, a transaction may be marked as finished,
// then the associated commands belonging to components will be destroyed,
// and Self may be destroyed (FRefCount = 0) earlier, then all processing
// will be finished. So, temporary increment a reference.
_AddRef;
Inc(FNotifyCount);
try
InternalNotify(ANotification, ACommandObj);
finally
Dec(FNotifyCount);
_Release;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.InternalNotify(ANotification: TFDPhysTxNotification;
ACommandObj: TFDPhysCommand);
var
oMeta: IFDPhysConnectionMetadata;
begin
if ANotification in [cpBeforeCmdPrepare, cpAfterCmdPrepareSuccess,
cpAfterCmdPrepareFailure, cpAfterCmdUnprepare] then
Exit;
FConnectionObj.CreateMetadata(oMeta);
if oMeta.TxSupported then begin
FConnectionObj.Lock;
try
if oMeta.TxAutoCommit then
case ANotification of
cpBeforeCmdExecute:
if not GetActive then
Update;
cpAfterCmdExecuteSuccess,
cpAfterCmdExecuteFailure:
InternalCheckState(ACommandObj, ANotification = cpAfterCmdExecuteSuccess);
end
else
case ANotification of
cpBeforeCmdExecute:
if not (ACommandObj.GetCommandKind in [skStartTransaction, skCommit, skRollback]) then
if GetOptions.AutoStart and not GetActive then begin
StartTransaction;
FIDAutoCommit := GetSerialID;
end;
cpAfterCmdExecuteSuccess,
cpAfterCmdExecuteFailure:
if not (ACommandObj.GetCommandKind in [skStartTransaction, skCommit, skRollback]) then begin
if GetOptions.AutoStop and GetActive and
(not (xoIfAutoStarted in GetOptions.StopOptions) or
(FIDAutoCommit <> 0) and (FIDAutoCommit = GetSerialID)) then
CheckStoping(True, True, ANotification <> cpAfterCmdExecuteFailure);
end
else
InternalCheckState(ACommandObj, ANotification = cpAfterCmdExecuteSuccess);
end;
finally
FConnectionObj.UnLock;
end;
end;
end;
{-------------------------------------------------------------------------------}
// TX management
procedure TFDPhysTransaction.TxOperation(AOperation: TFDPhysTransactionState;
ABefore: Boolean);
var
i: Integer;
begin
for i := FStateHandlerList.Count - 1 downto 0 do
IFDPhysTransactionStateHandler(FStateHandlerList[i]).
HandleTxOperation(AOperation, ABefore);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.TransactionStarted;
var
ePrevState: TFDPhysTransactionState;
begin
ePrevState := FState;
FSavepoints.Clear;
FIDAutoCommit := 0;
Inc(FSerialID);
FSavepoints.AddInt(IntToStr(FSerialID), FSerialID);
FState := tsActive;
if ePrevState = tsInactive then
TxOperation(tsActive, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.TransactionFinished;
var
ePrevState: TFDPhysTransactionState;
begin
ePrevState := FState;
FSavepoints.Clear;
FIDAutoCommit := 0;
FState := tsInactive;
if ePrevState = tsActive then
TxOperation(tsCommiting, False);
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.StartTransaction: LongWord;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
if not FMoniAdapterHelper.IsRegistered then
FMoniAdapterHelper.RegisterClient(FConnectionObj.GetMonitor);
FConnectionObj.Trace(ekConnTransact, esStart, 'StartTransaction',
['ConnectionDef', FConnectionObj.ConnectionDef.Name]);
end;
procedure Trace2;
begin
UpdateMonitor;
FConnectionObj.Trace(ekConnTransact, esEnd, 'StartTransaction',
['ConnectionDef', FConnectionObj.ConnectionDef.Name]);
end;
{$ENDIF}
var
s: String;
oMeta: IFDPhysConnectionMetadata;
lExecuted: Boolean;
iLastSerialID: LongWord;
begin
TxOperation(tsActive, True);
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace1;
try
{$ENDIF}
Result := 0;
FConnectionObj.CheckActive;
FConnectionObj.CreateMetadata(oMeta);
if not oMeta.TxSupported then
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
FConnectionObj.Lock;
if FSavepoints.Count = 0 then
FState := tsStarting;
try
lExecuted := False;
repeat
try
Result := FSerialID + 1;
if (FSavepoints.Count > 0) and not GetOptions.EnableNested then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccTxMBInActive, [ClassName]);
if (FSavepoints.Count = 0) or oMeta.TxNested then begin
Update;
s := IntToStr(Result);
InternalStartTransaction(Result);
end
else begin
if not oMeta.TxSavepoints then
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
s := C_FD_SysSavepointPrefix + IntToStr(Result);
InternalSetSavepoint(s);
end;
Inc(FSerialID);
FSavepoints.AddInt(s, FSerialID);
FState := tsActive;
lExecuted := True;
if (FNotifyCount = 0) and (FSavepoints.Count = 1) then
FExplicitActive := True;
except
on E: EFDDBEngineException do
if E.Kind = ekServerGone then begin
iLastSerialID := FSerialID;
FConnectionObj.RecoverConnection(Self, False);
if iLastSerialID = FSerialID then
TransactionFinished;
end
else
raise;
end;
until lExecuted;
finally
// FConnectionObj is nil when connection recovery is aborted
if FConnectionObj <> nil then begin
if FSavepoints.Count = 0 then
FState := tsInactive
else
FState := tsActive;
FConnectionObj.UnLock;
end;
end;
{$IFDEF FireDAC_MONITOR}
finally
if (FConnectionObj <> nil) and FConnectionObj.GetTracing then Trace2;
end;
{$ENDIF}
TxOperation(tsActive, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.InternalSetSavepoint(const AName: String);
var
oGen: IFDPhysCommandGenerator;
s: String;
begin
ConnectionObj.CreateCommandGenerator(oGen, nil);
s := oGen.GenerateSavepoint(AName);
if s <> '' then
ConnectionObj.InternalExecuteDirect(s, Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.InternalRollbackToSavepoint(const AName: String);
var
oGen: IFDPhysCommandGenerator;
s: String;
begin
ConnectionObj.CreateCommandGenerator(oGen, nil);
s := oGen.GenerateRollbackToSavepoint(AName);
if s <> '' then
ConnectionObj.InternalExecuteDirect(s, Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.InternalCommitSavepoint(const AName: String);
var
oGen: IFDPhysCommandGenerator;
s: String;
begin
ConnectionObj.CreateCommandGenerator(oGen, nil);
s := oGen.GenerateCommitSavepoint(AName);
if s <> '' then
ConnectionObj.InternalExecuteDirect(s, Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.Commit;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
FConnectionObj.Trace(ekConnTransact, esStart, 'Commit',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'Retaining', FRetaining]);
end;
procedure Trace2;
begin
UpdateMonitor;
FConnectionObj.Trace(ekConnTransact, esEnd, 'Commit',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'Retaining', FRetaining]);
end;
{$ENDIF}
var
oMeta: IFDPhysConnectionMetadata;
s: String;
iLastSerialID: LongWord;
begin
if not ((FState = tsActive) or not GetOptions.AutoStop) then
Exit;
TxOperation(tsCommiting, True);
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace1;
{$ENDIF}
FConnectionObj.Lock;
FState := tsCommiting;
try
FConnectionObj.CheckActive(True);
FConnectionObj.CreateMetadata(oMeta);
if not oMeta.TxSupported then
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
if not (GetActive or not GetOptions.AutoStop) then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccTxMBActive, [ClassName]);
try
if (FSavepoints.Count <= 1) or
(FSavepoints.Count > 1) and oMeta.TxNested then
InternalCommit(GetSerialID)
else begin
s := FSavepoints[FSavepoints.Count - 1];
InternalCommitSavepoint(s);
if FRetaining then
InternalSetSavepoint(s);
end;
if not FRetaining and (FSavepoints.Count > 0) then
FSavepoints.Delete(FSavepoints.Count - 1);
except
on E: EFDDBEngineException do
if E.Kind = ekServerGone then begin
iLastSerialID := FSerialID;
FConnectionObj.RecoverConnection(Self, False);
if iLastSerialID = FSerialID then
TransactionFinished;
end
else
raise;
end;
finally
// FConnectionObj is nil when connection recovery is aborted
if FConnectionObj <> nil then begin
if FSavepoints.Count = 0 then begin
FState := tsInactive;
FExplicitActive := False;
end
else
FState := tsActive;
FConnectionObj.UnLock;
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace2;
{$ENDIF}
end;
end;
TxOperation(tsCommiting, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.CommitRetaining;
begin
FRetaining := True;
try
Commit;
finally
FRetaining := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.Rollback;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
FConnectionObj.Trace(ekConnTransact, esStart, 'Rollback',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'Retaining', FRetaining]);
end;
procedure Trace2;
begin
UpdateMonitor;
FConnectionObj.Trace(ekConnTransact, esEnd, 'Rollback',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'Retaining', FRetaining]);
end;
{$ENDIF}
var
oMeta: IFDPhysConnectionMetadata;
s: String;
iLastSerialID: LongWord;
begin
if not ((FState = tsActive) or not GetOptions.AutoStop) then
Exit;
TxOperation(tsRollingback, True);
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace1;
{$ENDIF}
FConnectionObj.Lock;
FState := tsRollingback;
try
FConnectionObj.CheckActive(True);
FConnectionObj.CreateMetadata(oMeta);
if not oMeta.TxSupported then
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
if not (GetActive or not GetOptions.AutoStop) then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccTxMBActive, []);
try
if (FSavepoints.Count <= 1) or
(FSavepoints.Count > 1) and oMeta.TxNested then
InternalRollback(GetSerialID)
else begin
s := FSavepoints[FSavepoints.Count - 1];
InternalRollbackToSavepoint(s);
if FRetaining then
InternalSetSavepoint(s);
end;
if not FRetaining and (FSavepoints.Count > 0) then
FSavepoints.Delete(FSavepoints.Count - 1);
except
on E: EFDDBEngineException do
if E.Kind = ekServerGone then begin
iLastSerialID := FSerialID;
FConnectionObj.RecoverConnection(Self, False);
if iLastSerialID = FSerialID then
TransactionFinished;
end
else
raise;
end;
finally
// FConnectionObj is nil when connection recovery is aborted
if FConnectionObj <> nil then begin
if FSavepoints.Count = 0 then begin
FState := tsInactive;
FExplicitActive := False;
end
else
FState := tsActive;
FConnectionObj.UnLock;
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace2;
{$ENDIF}
end;
end;
TxOperation(tsRollingback, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.RollbackRetaining;
begin
FRetaining := True;
try
Rollback;
finally
FRetaining := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.LockAutoStop;
var
oTx: TFDTxOptions;
begin
if FLockAutoStopCount = 0 then begin
oTx := GetOptions;
FPrevAutoStop := oTx.AutoStop;
oTx.AutoStop := False;
// Driver should not update CLI autocommit mode, so just clear xoAutoCommit.
oTx.Changed := oTx.Changed - [xoAutoCommit, xoAutoStop];
end;
Inc(FLockAutoStopCount);
if FLockAutoStopCount = 1 then
FExplicitActive := GetActive and (FIDAutoCommit <> GetSerialID);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.UnlockAutoStop(ASuccess, AAllowStop: Boolean);
var
oTx: TFDTxOptions;
begin
if FLockAutoStopCount > 0 then begin
Dec(FLockAutoStopCount);
if FLockAutoStopCount = 0 then begin
oTx := GetOptions;
oTx.AutoStop := FPrevAutoStop;
// Driver should not update CLI autocommit mode, so just clear xoAutoCommit.
oTx.Changed := oTx.Changed - [xoAutoCommit, xoAutoStop];
if not FExplicitActive and FPrevAutoStop and AAllowStop then
Stop(ASuccess);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.AddStateHandler(const AHandler: IFDPhysTransactionStateHandler);
begin
FStateHandlerList.Add(AHandler);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.RemoveStateHandler(const AHandler: IFDPhysTransactionStateHandler);
begin
FStateHandlerList.Remove(AHandler);
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetCLIAutoCommit: Boolean;
var
oTx: TFDTxOptions;
begin
oTx := GetOptions;
if FLockAutoStopCount = 0 then
Result := oTx.AutoCommit
else
Result := oTx.AutoStart and FPrevAutoStop and
(xoIfAutoStarted in oTx.StopOptions) and (xoIfCmdsInactive in oTx.StopOptions);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.InternalChanged;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.Update;
var
lExecuted: Boolean;
begin
if GetOptions.Changed <> [] then begin
FConnectionObj.Lock;
try
lExecuted := False;
repeat
try
InternalChanged;
lExecuted := True;
except
on E: EFDDBEngineException do
if E.Kind = ekServerGone then
FConnectionObj.RecoverConnection(Self, False)
else
raise;
end;
until lExecuted;
GetOptions.ClearChanged;
finally
FConnectionObj.UnLock;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.ReleaseHandleBase;
begin
GetOptions.ResetChanged;
InternalReleaseHandle;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.InternalAllocHandle;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.InternalReleaseHandle;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.InternalSelect;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.InternalUnSelect;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
// IFDStanErrorHandler
procedure TFDPhysTransaction.HandleException(
const AInitiator: IFDStanObject; var AException: Exception);
begin
FConnectionObj.HandleException(AInitiator, AException);
end;
{-------------------------------------------------------------------------------}
// IFDStanObject
function TFDPhysTransaction.GetName: TComponentName;
begin
Result := FMoniAdapterHelper.Name;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetParent: IFDStanObject;
begin
Result := FMoniAdapterHelper.Parent;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
FMoniAdapterHelper.SetOwner(AOwner, ARole);
{$IFDEF FireDAC_MONITOR}
FMoniAdapterHelper.UnRegisterClient;
FMoniAdapterHelper.RegisterClient(FConnectionObj.GetMonitor);
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.BeforeReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.AfterReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
// IFDMoniAdapter
function TFDPhysTransaction.GetHandle: LongWord;
begin
if FMoniAdapterHelper = nil then
Result := 0
else
Result := FMoniAdapterHelper.Handle;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetSupportItems: TFDMoniAdapterItemKinds;
begin
Result := [ikStat];
end;
{-------------------------------------------------------------------------------}
function TFDPhysTransaction.GetItemCount: Integer;
begin
Result := 3;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTransaction.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
const
C_States: array [TFDPhysTransactionState] of String = ('Inactive', 'Active',
'Starting', 'Commiting', 'Rolling back');
begin
case AIndex of
0:
begin
AName := 'Commands';
AValue := FCommandList.Count;
AKind := ikStat;
end;
1:
begin
AName := 'Start count';
AValue := FSerialID;
AKind := ikStat;
end;
2:
begin
AName := 'State';
AValue := C_States[FState];
AKind := ikStat;
end;
end;
end;
{-------------------------------------------------------------------------------}
{$IFDEF FireDAC_MONITOR}
procedure TFDPhysTransaction.UpdateMonitor;
begin
if FConnectionObj.GetTracing then
FConnectionObj.FMonitor.AdapterChanged(Self as IFDMoniAdapter);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TFDPhysEventThread }
{-------------------------------------------------------------------------------}
constructor TFDPhysEventThread.Create(AAlerter: TFDPhysEventAlerter);
begin
inherited Create;
FAlerter := AAlerter;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventThread.DoTimeout;
begin
if Active and (FAlerter.GetOptions.Timeout > -1) then
if FAlerter.GetOptions.Synchronize then
TFDThread.Queue(nil, FAlerter.DoTimeout)
else
FAlerter.DoTimeout;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysEventThread.GetStartMsgClass: TFDThreadMsgClass;
begin
Result := TFDPhysEventStartMessage;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysEventThread.GetStopMsgClass: TFDThreadMsgClass;
begin
Result := TFDPhysEventStopMessage;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventStartMessage.Perform(AThread: TFDThread): Boolean;
begin
(AThread as TFDPhysEventThread).FAlerter.InternalRegister;
Result := inherited Perform(AThread);
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventStopMessage.Perform(AThread: TFDThread): Boolean;
begin
(AThread as TFDPhysEventThread).FAlerter.InternalUnregister;
Result := inherited Perform(AThread);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventMessage.BasePerform;
begin
FMsgThread.FAlerter.InternalHandle(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventMessage.Perform(AThread: TFDThread): Boolean;
begin
FMsgThread := AThread as TFDPhysEventThread;
if FMsgThread.Active then begin
if FMsgThread.FAlerter.GetOptions.Synchronize then
TFDThread.Synchronize(BasePerform)
else
BasePerform;
end;
Result := True;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysEventAlerter }
{-------------------------------------------------------------------------------}
constructor TFDPhysEventAlerter.Create(AConnection: TFDPhysConnection;
const AKind: String);
begin
inherited Create;
FConnection := AConnection as IFDPhysConnection;
FConnectionObj := AConnection;
FConnectionObj.Lock;
FConnectionObj.FEventList.Add(Self);
FConnectionObj.UnLock;
FKind := AKind;
FState := esInactive;
FNames := TFDStringList.Create(dupError, False, False);
FNames.OnChanging := DoNamesChanging;
FChangeHandlers := TInterfaceList.Create;
FChangeHandlerNames := TFDStringList.Create(dupAccept, False, False);
SetOptions(nil);
FMoniAdapterHelper := TFDMoniAdapterHelper.Create(Self, AConnection);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysEventAlerter.Destroy;
begin
Unregister;
{$IFNDEF AUTOREFCOUNT}
FDHighRefCounter(FRefCount);
{$ENDIF}
try
FConnectionObj.Lock;
FConnectionObj.FEventList.Remove(Self);
FConnectionObj.UnLock;
FExternalOptions := nil;
FDFreeAndNil(FNames);
FDFreeAndNil(FOptions);
FDFreeAndNil(FChangeHandlers);
FDFreeAndNil(FChangeHandlerNames);
FDFree(FMoniAdapterHelper);
FMoniAdapterHelper := nil;
inherited Destroy;
finally
{$IFNDEF AUTOREFCOUNT}
FRefCount := 0;
{$ENDIF}
FConnectionObj := nil;
FConnection := nil;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetConnection: IFDPhysConnection;
begin
Result := FConnectionObj as IFDPhysConnection;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetHandler: IFDPhysEventHandler;
begin
Result := FHandler;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetNames: TStrings;
begin
Result := FNames;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetSubscriptionName: String;
begin
Result := FSubscriptionName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetOptions: TFDEventAlerterOptions;
begin
if FExternalOptions <> nil then
Result := FExternalOptions
else
Result := FOptions;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetState: TFDPhysEventAlerterState;
begin
Result := FState;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetKind: String;
begin
Result := FKind;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetDriverID: String;
begin
if FConnectionObj <> nil then
Result := FConnectionObj.DriverID
else
Result := '';
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.SetHandler(const AValue: IFDPhysEventHandler);
begin
FHandler := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.SetNames(const AValue: TStrings);
begin
if FNames <> AValue then begin
Unregister;
FNames.SetStrings(AValue);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.SetSubscriptionName(const AValue: String);
begin
if FSubscriptionName <> AValue then begin
Unregister;
FSubscriptionName := AValue;
if AValue <> '' then
GetOptions.Synchronize := True;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.SetOptions(const AValue: TFDEventAlerterOptions);
begin
if (FExternalOptions <> AValue) or (FMoniAdapterHelper = nil) then begin
FExternalOptions := AValue;
if FExternalOptions = nil then
FOptions := TFDEventAlerterOptions.Create
else
FDFreeAndNil(FOptions);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.DoTimeout;
var
lContinue: Boolean;
begin
if (FState in [esRegistered, esFiring]) and (GetOptions.Timeout > 0) then begin
lContinue := True;
InternalHandleTimeout(lContinue);
if not lContinue then
AbortJob;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.DoNamesChanging(ASender: TObject);
begin
Unregister;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.Register;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
if not FMoniAdapterHelper.IsRegistered then
FMoniAdapterHelper.RegisterClient(FConnectionObj.GetMonitor);
FConnectionObj.Trace(ekConnService, esStart, 'RegisterEvent',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'Kind', GetKind]);
end;
procedure Trace2;
begin
UpdateMonitor;
FConnectionObj.Trace(ekConnService, esEnd, 'RegisterEvent',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'Kind', GetKind]);
end;
{$ENDIF}
begin
if FState <> esInactive then
Exit;
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace1;
try
{$ENDIF}
FConnectionObj.CheckActive;
FState := esRegistering;
try
InternalAllocHandle;
FMsgThread := TFDPhysEventThread.Create(Self);
if GetOptions.Timeout > 0 then
FMsgThread.IdleTimeout := GetOptions.Timeout;
FMsgThread.Active := True;
FState := esRegistered;
except
InternalReleaseHandle;
if FMsgThread <> nil then begin
FMsgThread.Shutdown(True);
FMsgThread := nil;
end;
FState := esInactive;
raise;
end;
{$IFDEF FireDAC_MONITOR}
finally
if FConnectionObj.GetTracing then Trace2;
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.Unregister;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
FConnectionObj.Trace(ekConnService, esStart, 'UnregisterEvent',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'Kind', GetKind]);
end;
procedure Trace2;
begin
UpdateMonitor;
FConnectionObj.Trace(ekConnService, esEnd, 'UnregisterEvent',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'Kind', GetKind]);
end;
{$ENDIF}
begin
if FState <> esRegistered then
Exit;
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace1;
try
{$ENDIF}
FConnectionObj.CheckActive(True);
FState := esUnregistering;
try
AbortJob;
FMsgThread.Shutdown(True);
InternalReleaseHandle;
finally
FMsgThread := nil;
FState := esInactive;
MarkChangeHandlers(nil, False);
end;
{$IFDEF FireDAC_MONITOR}
finally
if FConnectionObj.GetTracing then Trace2;
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.Signal(const AEvent: String;
const AArgument: Variant);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
FConnectionObj.Trace(ekConnService, esStart, 'SignalEvent',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'Event', AEvent]);
end;
procedure Trace2;
begin
FConnectionObj.Trace(ekConnService, esEnd, 'SignalEvent',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'Event', AEvent]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace1;
try
{$ENDIF}
FConnectionObj.CheckActive;
InternalSignal(AEvent, AArgument);
{$IFDEF FireDAC_MONITOR}
finally
if FConnectionObj.GetTracing then Trace2;
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.Refresh(const AHandler: IFDPhysChangeHandler;
AForce: Boolean);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
FConnectionObj.Trace(ekConnService, esStart, 'Refresh',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'SubscriptionName', FSubscriptionName]);
end;
procedure Trace2;
begin
FConnectionObj.Trace(ekConnService, esEnd, 'Refresh',
['ConnectionDef', FConnectionObj.ConnectionDef.Name,
'SubscriptionName', FSubscriptionName]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace1;
try
{$ENDIF}
try
FConnectionObj.CheckActive;
if IsRunning then begin
if AForce then
MarkChangeHandlers(AHandler, True);
InternalRefresh(AHandler);
end;
finally
MarkChangeHandlers(AHandler, False);
end;
{$IFDEF FireDAC_MONITOR}
finally
if FConnectionObj.GetTracing then Trace2;
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.AddChangeHandler(const AHandler: IFDPhysChangeHandler);
var
oConnMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
s: String;
begin
if FChangeHandlers.IndexOf(AHandler) = -1 then begin
GetConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(AHandler.TrackEventName, rName, nil,
[doNormalize, doUnquote]);
s := rName.FObject;
FChangeHandlers.Add(AHandler);
FChangeHandlerNames.Add(s);
try
InternalChangeHandlerModified(AHandler, s, opInsert);
except
RemoveChangeHandler(AHandler);
raise;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.RemoveChangeHandler(const AHandler: IFDPhysChangeHandler);
var
s: String;
i: Integer;
begin
i := FChangeHandlers.IndexOf(AHandler);
if i >= 0 then begin
s := FChangeHandlerNames[i];
try
InternalChangeHandlerModified(AHandler, s, opRemove);
finally
FChangeHandlers.Delete(i);
FChangeHandlerNames.Delete(i);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.AbortJob;
begin
try
InternalAbortJob;
FMsgThread.Active := False;
except
// not visible
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.IsRunning: Boolean;
begin
Result := (FMsgThread <> nil) and FMsgThread.Active and not FMsgThread.Finished and
(FState <> esInactive);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.SetupCommand(const ACmd: IFDPhysCommand);
var
oRes: TFDResourceOptions;
oFtch: TFDFetchOptions;
begin
oRes := ACmd.Options.ResourceOptions;
oRes.PreprocessCmdText := True;
oRes.CmdExecMode := amBlocking;
oRes.CmdExecTimeout := $FFFFFFFF;
oRes.DirectExecute := True;
oFtch := ACmd.Options.FetchOptions;
oFtch.AutoClose := True;
oFtch.RecsSkip := -1;
oFtch.RecsMax := -1;
oFtch.Items := oFtch.Items - [fiMeta];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.MarkChangeHandlers(
const AHandler: IFDPhysChangeHandler; AModified: Boolean);
var
i: Integer;
begin
if AHandler = nil then
for i := FChangeHandlers.Count - 1 downto 0 do
(FChangeHandlers[i] as IFDPhysChangeHandler).ContentModified := AModified
else
AHandler.ContentModified := AModified;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.AreChangeHandlersModified: Boolean;
var
i: Integer;
begin
Result := False;
for i := FChangeHandlers.Count - 1 downto 0 do
if (FChangeHandlers[i] as IFDPhysChangeHandler).ContentModified then begin
Result := True;
Break;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.InternalAllocHandle;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.InternalRegister;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.InternalUnregister;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.InternalReleaseHandle;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.InternalAbortJob;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.InternalRefresh(const AHandler: IFDPhysChangeHandler);
var
i: Integer;
oHnlr: IFDPhysChangeHandler;
begin
if AHandler = nil then
for i := FChangeHandlers.Count - 1 downto 0 do begin
oHnlr := FChangeHandlers[i] as IFDPhysChangeHandler;
if oHnlr.ContentModified then
oHnlr.RefreshContent;
end
else
if AHandler.ContentModified then
AHandler.RefreshContent;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.InternalHandleEvent(const AEventName: String;
const AArgument: Variant);
var
i: Integer;
oHnlr: IFDPhysChangeHandler;
begin
if GetSubscriptionName <> '' then begin
i := FChangeHandlerNames.IndexOf(AEventName);
if i >= 0 then
oHnlr := FChangeHandlers[i] as IFDPhysChangeHandler
else
oHnlr := nil;
MarkChangeHandlers(oHnlr, True);
if (GetOptions.AutoRefresh = afAlert) and (TThread.CurrentThread.ThreadID = MainThreadID) then
Refresh(oHnlr, False);
end;
if GetHandler <> nil then
GetHandler.HandleEvent(AEventName, AArgument);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.InternalHandleTimeout(var AContinue: Boolean);
begin
if (GetSubscriptionName <> '') and
(GetOptions.AutoRefresh = afTimeout) and (TThread.CurrentThread.ThreadID = MainThreadID) and
AreChangeHandlersModified then
Refresh(nil, False);
if GetHandler <> nil then
GetHandler.HandleTimeout(AContinue);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.InternalChangeHandlerModified(
const AHandler: IFDPhysChangeHandler; const AEventName: String;
AOperation: TOperation);
var
i: Integer;
begin
case AOperation of
opInsert:
if (AEventName <> '') and (GetNames.IndexOf(AEventName) = -1) then
GetNames.Add(AEventName);
opRemove:
if AEventName <> '' then begin
i := GetNames.IndexOf(AEventName);
if i <> -1 then
GetNames.Delete(i);
end;
end;
end;
{-------------------------------------------------------------------------------}
// IFDStanErrorHandler
procedure TFDPhysEventAlerter.HandleException(
const AInitiator: IFDStanObject; var AException: Exception);
begin
FConnectionObj.HandleException(AInitiator, AException);
end;
{-------------------------------------------------------------------------------}
// IFDStanObject
function TFDPhysEventAlerter.GetName: TComponentName;
begin
Result := FMoniAdapterHelper.Name;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetParent: IFDStanObject;
begin
Result := FMoniAdapterHelper.Parent;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
FMoniAdapterHelper.SetOwner(AOwner, ARole);
{$IFDEF FireDAC_MONITOR}
FMoniAdapterHelper.UnRegisterClient;
FMoniAdapterHelper.RegisterClient(FConnectionObj.GetMonitor);
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.BeforeReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.AfterReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
// IFDMoniAdapter
function TFDPhysEventAlerter.GetHandle: LongWord;
begin
if FMoniAdapterHelper = nil then
Result := 0
else
Result := FMoniAdapterHelper.Handle;
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetSupportItems: TFDMoniAdapterItemKinds;
begin
Result := [ikStat];
end;
{-------------------------------------------------------------------------------}
function TFDPhysEventAlerter.GetItemCount: Integer;
begin
Result := 1;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysEventAlerter.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
const
C_States: array [TFDPhysEventAlerterState] of String = ('Inactive', 'Registering',
'Registered', 'Unregistering', 'Fired');
begin
case AIndex of
0:
begin
AName := 'State';
AValue := C_States[FState];
AKind := ikStat;
end;
end;
end;
{-------------------------------------------------------------------------------}
{$IFDEF FireDAC_MONITOR}
procedure TFDPhysEventAlerter.UpdateMonitor;
begin
if FConnectionObj.GetTracing then
FConnectionObj.FMonitor.AdapterChanged(Self as IFDMoniAdapter);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TFDPhysCommandAsyncOperation }
{-------------------------------------------------------------------------------}
type
TFDPhysCommandAsyncOperation = class(TInterfacedObject, IFDStanAsyncOperation)
protected
FCommand: TFDPhysCommand;
// IFDStanAsyncOperation
procedure Execute; virtual; abstract;
procedure AbortJob;
function AbortSupported: Boolean;
public
constructor Create(ACmd: TFDPhysCommand);
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysCommandAsyncOperation.Create(ACmd: TFDPhysCommand);
begin
inherited Create;
FCommand := ACmd;
{$IFNDEF NEXTGEN}
FCommand._AddRef;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysCommandAsyncOperation.Destroy;
begin
{$IFNDEF NEXTGEN}
FCommand._Release;
{$ENDIF}
FCommand := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandAsyncOperation.AbortJob;
begin
FCommand.AbortJob;
while FCommand.GetState = csAborting do
Sleep(1);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandAsyncOperation.AbortSupported: Boolean;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
FCommand.GetConnection.CreateMetadata(oConnMeta);
Result := oConnMeta.AsyncAbortSupported;
end;
{ ----------------------------------------------------------------------------- }
{ TFDPhysCommand }
{ ----------------------------------------------------------------------------- }
// Constructors
constructor TFDPhysCommand.Create(AConnection: TFDPhysConnection);
begin
inherited Create;
FConnection := AConnection as IFDPhysConnection;
FConnectionObj := AConnection;
FConnectionObj.Lock;
FConnectionObj.FCommandList.Add(Self);
FConnectionObj.UnLock;
FParams := TFDParams.CreateRefCounted(GetParamsOwner);
FMacros := TFDMacros.CreateRefCounted(GetParamsOwner);
SetOptions(nil);
FObjectScopes := [osMy];
FTableKinds := [tkSynonym, tkTable, tkView];
FBuffer := TFDBuffer.Create;
FMoniAdapterHelper := TFDMoniAdapterHelper.Create(Self, FConnectionObj);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysCommand.Destroy;
begin
{$IFNDEF AUTOREFCOUNT}
FDHighRefCounter(FRefCount);
{$ENDIF}
Disconnect;
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then
FConnectionObj.FMonitor.Notify(ekLiveCycle, esProgress, Self, 'Destroy',
['Command', GetTraceCommandText]);
{$ENDIF}
try
SetTransaction(nil);
FConnectionObj.Lock;
FConnectionObj.FCommandList.Remove(Self);
FConnectionObj.UnLock;
FParams.RemRef;
FParams := nil;
FMacros.RemRef;
FMacros := nil;
FOptions := nil;
FDFreeAndNil(FBuffer);
inherited Destroy;
finally
FDFree(FMoniAdapterHelper);
FMoniAdapterHelper := nil;
FTransactionObj := nil;
FTransaction := nil;
FConnectionObj := nil;
FConnection := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.CreateCommandGenerator(out AGen: IFDPhysCommandGenerator);
begin
FConnection.CreateCommandGenerator(AGen, Self);
AGen.Params := GetParams;
AGen.Options := Self as IFDStanOptions;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetParamsOwner: TPersistent;
begin
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetDriverID: String;
begin
if FConnectionObj <> nil then
Result := FConnectionObj.DriverID
else
Result := '';
end;
{-------------------------------------------------------------------------------}
// Tracing
function TFDPhysCommand.GetTraceCommandText(const ACmd: String): String;
function GetLoc: String;
begin
Result := '';
if GetCatalogName <> '' then
Result := Result + GetCatalogName + '.';
if GetSchemaName <> '' then
Result := Result + GetSchemaName + '.';
if GetBaseObjectName <> '' then
Result := Result + GetBaseObjectName + '.';
end;
var
sCmd: String;
begin
if ACmd <> '' then
sCmd := ACmd
else
sCmd := FCommandText;
if FMetaInfoKind = mkNone then begin
if FCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs] then begin
Result := GetLoc + sCmd;
if FOverload <> 0 then
Result := Result + ';' + IntTostr(FOverload);
end
else
Result := sCmd;
end
else begin
sCmd := TrimRight(sCmd);
case FMetaInfoKind of
mkCatalogs: Result := 'Catalog List';
mkSchemas: Result := 'Schemas List';
mkTables: Result := 'Table List';
mkTableFields: Result := 'Table Fields (' + GetLoc + sCmd + ')';
mkIndexes: Result := 'Table Indexes (' + GetLoc + sCmd + ')';
mkIndexFields: Result := 'Table Index Fields (' + GetLoc + FBaseObjectName + ', ' + sCmd + ')';
mkPrimaryKey: Result := 'Table PKeys (' + GetLoc + sCmd + ')';
mkPrimaryKeyFields: Result := 'Table PKey Fields (' + GetLoc + FBaseObjectName + ')';
mkForeignKeys: Result := 'Table FKeys (' + GetLoc + sCmd + ')';
mkForeignKeyFields: Result := 'Table FKey Fields (' + GetLoc + FBaseObjectName + ', ' + sCmd + ')';
mkPackages: Result := 'Packages(' + GetLoc + ')';
mkProcs: Result := 'Procedures (' + GetLoc + FBaseObjectName + ')';
mkProcArgs: Result := 'Procedure Args (' + GetLoc + FBaseObjectName + ', ' + sCmd + ')';
mkGenerators: Result := 'Generator List';
mkResultSetFields: Result := 'ResultSet Fields (' + sCmd + ')';
mkTableTypeFields: Result := 'Table Type Fields (' + GetLoc + sCmd + ')';
end;
end;
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.Trace(AKind: TFDMoniEventKind;
AStep: TFDMoniEventStep; const AMsg: String; const AArgs: array of const);
begin
if FConnectionObj.GetTracing then
FConnectionObj.FMonitor.Notify(AKind, AStep, Self, AMsg, AArgs);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.EnterTrace(AConnObj: TFDPhysConnection): Boolean;
begin
// _AddRef / _Release will preserve command from distruction before esEnd
// trace call: esStart try ... finally esEnd end. Otherwise to many times
// will be required to handle this situation.
_AddRef;
Result := AConnObj.GetTracing;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.ExitTrace(AConnObj: TFDPhysConnection; var AUpdateMonitor: Boolean): Boolean;
begin
Result := AConnObj.GetTracing;
AUpdateMonitor := _Release > 0;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
// Options
function TFDPhysCommand.GetOptions: IFDStanOptions;
begin
Result := Self as IFDStanOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.GetParentOptions(var AOpts: IFDStanOptions);
begin
AOpts := FConnectionObj as IFDStanOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetOptions(const AValue: IFDStanOptions);
begin
if (FOptions <> AValue) or (FBuffer = nil) then begin
FOptions := AValue;
if FOptions = nil then
FOptions := TFDOptionsContainer.Create(nil, TFDFetchOptions,
TFDBottomUpdateOptions, TFDBottomResourceOptions, GetParentOptions);
end;
end;
{-------------------------------------------------------------------------------}
// Exception handling
function TFDPhysCommand.GetErrorHandler: IFDStanErrorHandler;
begin
Result := FErrorHandler;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetErrorHandler(const AValue: IFDStanErrorHandler);
begin
FErrorHandler := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
begin
{$IFDEF FireDAC_MONITOR}
if not (AException is EFDDBEngineException) and FConnectionObj.GetTracing then
Trace(ekError, esProgress, AException.Message, []);
{$ENDIF}
if Assigned(GetErrorHandler()) then
GetErrorHandler().HandleException(AInitiator, AException);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.ParTypeUnknownError(AParam: TFDParam);
begin
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccParTypeUnknown, [AParam.Name]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.ParTypeMapError(AParam: TFDParam);
begin
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccParDataMapNotSup, [AParam.Name]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.ParDefChangedError(ADataType: TFieldType; AParam: TFDParam);
begin
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccParDefChanged,
[AParam.Name, FieldTypeNames[ADataType], FieldTypeNames[AParam.DataType]]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.ParSetChangedError(AExpected, AActual: Integer);
begin
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccParSetChanged, [AExpected, AActual]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.UnsupParamObjError(AParam: TFDParam);
begin
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccUnsupParamObjValue,
[AParam.SQLName, FieldTypeNames[AParam.DataType]]);
end;
{-------------------------------------------------------------------------------}
// Get/set props
function TFDPhysCommand.GetState: TFDPhysCommandState;
begin
Result := FState;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetState(const AValue: TFDPhysCommandState);
begin
FState := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetConnection: IFDPhysConnection;
begin
Result := FConnection;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetCommandText: String;
begin
Result := FCommandText;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetCommandText(const AValue: String);
begin
if FCommandText <> AValue then begin
Disconnect;
FCommandText := AValue;
Preprocess;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetParams: TFDParams;
begin
Result := FParams;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetMacros: TFDMacros;
begin
Result := FMacros;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetParams(AValue: TFDParams);
begin
if AValue = FParams then
Exit;
if FParams <> nil then
if FParams.IsRefCounted then
FParams.RemRef
else
FDFree(FParams);
FParams := AValue;
if FParams <> nil then begin
if FParams.IsRefCounted then
FParams.AddRef;
end
else
FParams := TFDParams.CreateRefCounted(GetParamsOwner);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetMacros(AValue: TFDMacros);
begin
if AValue = FMacros then
Exit;
if FMacros <> nil then
if FMacros.IsRefCounted then
FMacros.RemRef
else
FDFree(FMacros);
FMacros := AValue;
if FMacros <> nil then begin
if FMacros.IsRefCounted then
FMacros.AddRef;
end
else
FMacros := TFDMacros.CreateRefCounted(GetParamsOwner);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetCommandKind: TFDPhysCommandKind;
begin
Result := FCommandKind;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetCommandKind(const AValue: TFDPhysCommandKind);
begin
FCommandKind := AValue;
FFixedCommandKind := (AValue <> skUnknown);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetSourceObjectName: String;
begin
Result := FSourceObjectName;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetSourceObjectName(const AValue: String);
begin
FSourceObjectName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetSourceRecordSetName: String;
begin
Result := FSourceRecordSetName;
if Result = '' then
Result := GetSourceObjectName
else if FRecordSetIndex > 0 then
Result := Result + '#' + IntToStr(FRecordSetIndex);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetSourceRecordSetName(const AValue: String);
begin
FSourceRecordSetName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetOverload: Word;
begin
Result := FOverload;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetOverload(const AValue: Word);
begin
if AValue <> FOverload then begin
Disconnect;
FOverload := AValue;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetBaseObjectName: String;
begin
Result := FBaseObjectName;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetBaseObjectName(const AValue: String);
begin
if AValue <> FBaseObjectName then begin
Disconnect;
FBaseObjectName := AValue;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetSchemaName: String;
begin
Result := FSchemaName;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetSchemaName(const AValue: String);
begin
if AValue <> FSchemaName then begin
Disconnect;
FSchemaName := AValue;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetCatalogName: String;
begin
Result := FCatalogName;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetCatalogName(const AValue: String);
begin
if AValue <> FCatalogName then begin
Disconnect;
FCatalogName := AValue;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetNextRecordSet: Boolean;
begin
Result := FNextRecordSet;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetNextRecordSet(const AValue: Boolean);
begin
FNextRecordSet := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetMappingHandler: IFDPhysMappingHandler;
begin
Result := FMappingHandler;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetMappingHandler(const AValue: IFDPhysMappingHandler);
begin
FMappingHandler := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetSQLOrderByPos: Integer;
begin
Result := FSQLOrderByPos;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysCommand.GetCliObj: Pointer;
begin
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetSQLText: String;
begin
Result := FDbCommandText;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetTransaction: IFDPhysTransaction;
begin
Result := FTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetTransaction(const AValue: IFDPhysTransaction);
var
oTxObj: TFDPhysTransaction;
begin
CheckState(csInactive);
if AValue <> FTransaction then begin
if FTransactionObj <> nil then begin
{$IFDEF FireDAC_MONITOR}
if FMoniAdapterHelper.IsRegistered and
(FMoniAdapterHelper.Parent = IFDStanObject(FTransactionObj)) then begin
FMoniAdapterHelper.UnRegisterClient;
FMoniAdapterHelper.SetOwner(FConnectionObj, '');
end;
{$ENDIF}
FConnectionObj.Lock;
FTransactionObj.FCommandList.Remove(Self);
FConnectionObj.UnLock;
FTransaction := nil;
FTransactionObj := nil;
end;
if AValue <> nil then begin
oTxObj := AValue as TFDPhysTransaction;
if oTxObj.FConnectionObj <> FConnectionObj then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccCantAssignTxIntf, []);
FTransaction := AValue;
FTransactionObj := oTxObj;
FConnectionObj.Lock;
FTransactionObj.FCommandList.Add(Self);
FConnectionObj.UnLock;
{$IFDEF FireDAC_MONITOR}
if FMoniAdapterHelper.Parent = IFDStanObject(FConnectionObj) then begin
if FMoniAdapterHelper.IsRegistered then
FMoniAdapterHelper.UnRegisterClient;
FMoniAdapterHelper.SetOwner(FTransactionObj, '');
end;
{$ENDIF}
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetStateHandler: IFDPhysCommandStateHandler;
begin
Result := FStateHandler;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetStateHandler(const AValue: IFDPhysCommandStateHandler);
begin
FStateHandler := AValue;
end;
{-------------------------------------------------------------------------------}
// Metainfo get/set
function TFDPhysCommand.GetMetaInfoKind: TFDPhysMetaInfoKind;
begin
Result := FMetaInfoKind;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetMetaInfoKind(AValue: TFDPhysMetaInfoKind);
begin
if AValue <> FMetaInfoKind then begin
Disconnect;
FMetaInfoKind := AValue;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetTableKinds: TFDPhysTableKinds;
begin
Result := FTableKinds;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetTableKinds(AValue: TFDPhysTableKinds);
begin
if AValue <> FTableKinds then begin
Disconnect;
FTableKinds := AValue;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetWildcard: String;
begin
Result := FWildcard;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetWildcard(const AValue: String);
begin
if AValue <> FWildcard then begin
Disconnect;
FWildcard := AValue;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetObjectScopes: TFDPhysObjectScopes;
begin
Result := FObjectScopes;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetObjectScopes(AValue: TFDPhysObjectScopes);
begin
if AValue <> FObjectScopes then begin
Disconnect;
FObjectScopes := AValue;
end;
end;
{-------------------------------------------------------------------------------}
// Runtime cycle
procedure TFDPhysCommand.ExecuteTask(const AOperation: IFDStanAsyncOperation;
const AHandler: IFDStanAsyncHandler; ABlocked: Boolean);
var
eMode: TFDStanAsyncMode;
oRes: TFDResourceOptions;
oConnMeta: IFDPhysConnectionMetadata;
iTimeout: LongWord;
begin
oRes := FOptions.ResourceOptions;
eMode := oRes.CmdExecMode;
if ABlocked and (eMode = amAsync) then
eMode := amBlocking;
FConnection.CreateMetadata(oConnMeta);
if oConnMeta.AsyncNativeTimeout and (eMode = amBlocking) then
iTimeout := $FFFFFFFF
else
iTimeout := oRes.CmdExecTimeout;
try
if FExecutor = nil then
FDCreateInterface(IFDStanAsyncExecutor, FExecutor);
FExecutor.Setup(AOperation, eMode, iTimeout, AHandler, oRes.ActualSilentMode);
except
on E: Exception do begin
if AHandler <> nil then
AHandler.HandleFinished(Self, asFailed, E);
raise;
end;
end;
FExecutor.Run;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.Disconnect;
begin
CheckAsyncProgress;
if GetState = csOpen then
CloseAll;
if GetState = csPrepared then
Unprepare;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.CheckAsyncProgress;
begin
if GetState in [csExecuting, csFetching] then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccAsyncOperInProgress, []);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.CheckState(ARequiredState: TFDPhysCommandState);
begin
if GetState <> ARequiredState then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccCantChngCommandState, []);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.AbortJob(const AWait: Boolean = False);
var
oConnMeta: IFDPhysConnectionMetadata;
begin
if (FThreadID <> 0) and (FThreadID = TThread.CurrentThread.ThreadID) then begin
if FState = csFetching then
FState := csOpen
else if FState = csExecuting then
FState := csPrepared;
Exit;
end;
_AddRef;
try
FConnection.CreateMetadata(oConnMeta);
if oConnMeta.AsyncAbortSupported and (GetState in [csExecuting, csFetching]) then
try
FState := csAborting;
InternalAbort;
except
on E: EFDDBEngineException do
if (E.Kind = ekServerGone) and (GetState = csAborting) then
FState := csPrepared;
end;
if AWait then begin
while (GetState in [csExecuting, csFetching, csAborting]) or
(FThreadID <> 0) do
Sleep(1);
if (FExecutor <> nil) and (FExecutor.Operation <> nil) then begin
Sleep(1);
if TThread.CurrentThread.ThreadID = MainThreadID then
CheckSynchronize();
end;
end;
finally
_Release;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.InternalAbort;
begin
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.PreprocessCommand(ACreateParams, ACreateMacros,
AExpandParams, AExpandMacros, AExpandEscapes, AParseSQL: Boolean);
var
oPP: TFDPhysPreprocessor;
oPList: TFDParams;
oMList: TFDMacros;
oConnMeta: IFDPhysConnectionMetadata;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekCmdPrepare, esProgress, 'Preprocessed', ['CMD', FDbCommandText,
'FROM', oPP.SQLFromValue, 'VP', oPP.SQLValuesPos, 'VPE', oPP.SQLValuesPosEnd,
'OBP', oPP.SQLOrderByPos, 'CK', Integer(oPP.SQLCommandKind)]);
end;
{$ENDIF}
begin
if not (ACreateParams or ACreateMacros or AExpandParams or AExpandMacros or
AExpandEscapes or AParseSQL) then
Exit;
oPList := nil;
oMList := nil;
oPP := TFDPhysPreprocessor.Create;
oPP.Instrs := [];
if AExpandParams then begin
oPP.Instrs := oPP.Instrs + [piExpandParams];
oPList := GetParams;
end;
if AExpandMacros then begin
oPP.Instrs := oPP.Instrs + [piExpandMacros];
oMList := GetMacros;
end;
if AExpandEscapes then
oPP.Instrs := oPP.Instrs + [piExpandEscapes];
if AParseSQL then
oPP.Instrs := oPP.Instrs + [piParseSQL, piTransformEOLs];
if ACreateParams then begin
oPList := TFDParams.CreateRefCounted(GetParamsOwner);
oPList.BindMode := GetParams.BindMode;
oPP.Instrs := oPP.Instrs + [piCreateParams];
end;
if ACreateMacros then begin
oMList := TFDMacros.CreateRefCounted(GetParamsOwner);
oPP.Instrs := oPP.Instrs + [piCreateMacros];
end;
try
FConnection.CreateMetadata(oConnMeta);
oPP.ConnMetadata := oConnMeta;
oPP.Source := FCommandText;
oPP.Params := oPList;
oPP.MacrosRead := GetMacros;
oPP.MacrosUpd := oMList;
oPP.Execute;
if AParseSQL then begin
FDbCommandText := oPP.Destination;
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace1;
{$ENDIF}
if not FFixedCommandKind and (GetCommandKind = skUnknown) then begin
SetCommandKind(oPP.SQLCommandKind);
FFixedCommandKind := False;
end;
SetSourceObjectName(oPP.SQLFromValue);
FSQLValuesPos := oPP.SQLValuesPos;
FSQLValuesPosEnd := oPP.SQLValuesPosEnd;
FSQLOrderByPos := oPP.SQLOrderByPos;
FSQLLimitSkip := oPP.SQLLimitSkip;
FSQLLimitRows := oPP.SQLLimitRows;
end;
if ACreateParams then begin
oPList.AssignValues(GetParams);
GetParams.Assign(oPList);
end;
if ACreateMacros then begin
oMList.AssignValues(GetMacros);
GetMacros.TempLockUpdate;
GetMacros.Assign(oMList);
end;
finally
if ACreateParams then
oPList.RemRef;
if ACreateMacros then
oMList.RemRef;
FDFree(oPP);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.CheckPreprocessCommand(ACreateParams: Boolean);
var
oRes: TFDResourceOptions;
begin
if not (GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs]) and
(GetMetaInfoKind = mkNone) then begin
oRes := FOptions.ResourceOptions;
PreprocessCommand(oRes.ParamCreate and ACreateParams, oRes.MacroCreate and ACreateParams,
oRes.ParamExpand, oRes.MacroExpand, oRes.EscapeExpand, True);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.Preprocess;
begin
CheckPreprocessCommand(True);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.Prepare(const ACommandText: String = ''; ACreateParams: Boolean = True);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
if not FMoniAdapterHelper.IsRegistered then
FMoniAdapterHelper.RegisterClient(FConnectionObj.GetMonitor);
Trace(ekCmdPrepare, esStart, 'Prepare', ['Command', GetTraceCommandText(ACommandText)]);
end;
procedure Trace2(AUpdateMonitor: Boolean);
begin
if AUpdateMonitor then UpdateMonitor;
Trace(ekCmdPrepare, esEnd, 'Prepare', ['Command', GetTraceCommandText]);
end;
{$ENDIF}
var
lPrepared: Boolean;
{$IFDEF FireDAC_MONITOR}
lUpdateMonitor: Boolean;
{$ENDIF}
begin
if (GetState <> csInactive) and (ACommandText = '') then
Exit;
{$IFDEF FireDAC_MONITOR}
if EnterTrace(FConnectionObj) then Trace1;
try
{$ENDIF}
Disconnect;
ASSERT(FConnection <> nil);
if FTransaction = nil then begin
SetTransaction(FConnection.Transaction);
ASSERT(FTransaction <> nil);
end;
FConnectionObj.CheckActive(True);
if ACommandText <> '' then
FCommandText := ACommandText;
if (GetMetaInfoKind = mkNone) and (GetCommandText = '') then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccCommandMBFilled, [GetName]);
FSQLLimitSkip := -1;
FSQLLimitRows := -1;
FLimitOptions := [];
CheckPreprocessCommand((ACommandText <> '') and ACreateParams);
GetParams.Prepare(GetOptions.FormatOptions.DefaultParamDataType,
GetOptions.ResourceOptions.DefaultParamType);
FBuffer.Release;
FRecordSetIndex := -1;
FConnectionObj.IncPrepared(Self);
try
lPrepared := False;
repeat
try
FTransactionObj.Notify(cpBeforeCmdPrepare, Self);
if (GetMetaInfoKind = FireDAC.Phys.Intf.mkNone) or CheckMetaAvailability then
InternalPrepare;
lPrepared := True;
except
on E: Exception do begin
InternalUnprepare;
if (E is EFDDBEngineException) and (EFDDBEngineException(E).Kind = ekServerGone) then
FConnectionObj.RecoverConnection(Self, False)
else
raise;
end;
end;
until lPrepared;
FTransactionObj.Notify(cpAfterCmdPrepareSuccess, Self);
except
GetParams.Markers.Clear;
FConnectionObj.DecPrepared;
FTransactionObj.Notify(cpAfterCmdPrepareFailure, Self);
raise;
end;
FState := csPrepared;
{$IFDEF FireDAC_MONITOR}
finally
if ExitTrace(FConnectionObj, lUpdateMonitor) then Trace2(lUpdateMonitor);
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.Unprepare;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekCmdPrepare, esStart, 'Unprepare', ['Command', GetTraceCommandText]);
end;
procedure Trace2(AUpdateMonitor: Boolean);
begin
if AUpdateMonitor then UpdateMonitor;
Trace(ekCmdPrepare, esEnd, 'Unprepare', ['Command', GetTraceCommandText]);
end;
{$ENDIF}
var
lDestroyed: Boolean;
{$IFDEF FireDAC_MONITOR}
oConn: TFDPhysConnection;
lUpdateMonitor: Boolean;
{$ENDIF}
begin
if GetState = csInactive then
Exit;
if (GetStateHandler <> nil) and not (rfEmergencyClose in FConnectionObj.FRecoveryFlags) then begin
CheckAsyncProgress;
_AddRef;
try
GetStateHandler.HandleUnprepare;
finally
lDestroyed := _Release = 0;
end;
if lDestroyed or (GetState = csInactive) then
Exit;
end;
{$IFDEF FireDAC_MONITOR}
oConn := FConnectionObj;
if EnterTrace(oConn) then Trace1;
try
{$ENDIF}
CheckAsyncProgress;
if GetState = csOpen then
CloseAll;
if GetState = csInactive then
Exit;
CheckState(csPrepared);
FBuffer.Release;
try
InternalUnprepare;
except
on E: EFDDBEngineException do
if E.Kind <> ekServerGone then
raise;
end;
GetParams.Unprepare;
FConnectionObj.DecPrepared;
FExecuteCount := 0;
FRecordsFetched := 0;
if not FFixedCommandKind then
SetCommandKind(skUnknown);
SetSourceObjectName('');
FExecutor := nil;
FState := csInactive;
FTransactionObj.Notify(cpAfterCmdUnprepare, Self);
{$IFDEF FireDAC_MONITOR}
finally
if ExitTrace(oConn, lUpdateMonitor) then Trace2(lUpdateMonitor);
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.GenerateStoredProcParams(const AName: TFDPhysParsedName);
var
oGen: IFDPhysCommandGenerator;
begin
CreateCommandGenerator(oGen);
FDbCommandText := oGen.GenerateStoredProcParams(AName.FCatalog, AName.FSchema,
AName.FBaseObject, AName.FObject, AName.OverInd);
if GetCommandKind = skStoredProc then
SetCommandKind(oGen.CommandKind);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.GenerateStoredProcCall(const AName: TFDPhysParsedName;
ASPUsage: TFDPhysCommandKind);
var
oGen: IFDPhysCommandGenerator;
begin
CreateCommandGenerator(oGen);
FDbCommandText := oGen.GenerateStoredProcCall(AName.FCatalog, AName.FSchema,
AName.FBaseObject, AName.FObject, AName.OverInd, ASPUsage);
SetCommandKind(oGen.CommandKind);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.CheckMetaAvailability: Boolean;
var
rName1, rName2: TFDPhysParsedName;
oGen: IFDPhysCommandGenerator;
oConnMeta: IFDPhysConnectionMetadata;
begin
// 1) Special single row tables have no indexes and constraints.
// Avoiding querying metainfo for them optimizes execution.
// 2) MySQL: "SHOW INDEX FOR dual" always returns an error.
// 3) Informix: "select DBINFO('sqlca.sqlerrd1') from SYSMASTER:"informix".SYSDUAL"
// with fiMeta will always return 0, because mkPrimaryKeyFields execution clears
// sqlca.sqlerrd1 content.
Result := True;
if (GetMetaInfoKind in [mkIndexes, mkIndexFields,
mkPrimaryKey, mkPrimaryKeyFields,
mkForeignKeys, mkForeignKeyFields]) then begin
FConnection.CreateCommandGenerator(oGen, Self);
if oGen.SingleRowTable <> '' then begin
FConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(oGen.SingleRowTable, rName2, nil,
[doNormalize, doUnquote]);
GetSelectMetaInfoParams(rName1);
if CompareText(rName1.FBaseObject, rName2.FObject) = 0 then
Result := False;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.GetSelectMetaInfoParams(out AName: TFDPhysParsedName);
var
sCmd: String;
oConnMeta: IFDPhysConnectionMetadata;
begin
sCmd := Trim(GetCommandText());
if GetMetaInfoKind() = mkResultSetFields then
AName.FObject := sCmd
else if (GetMetaInfoKind() in [mkCatalogs, mkSchemas, mkTables, mkPackages, mkGenerators]) or
(GetMetaInfoKind() = mkProcs) and (GetBaseObjectName = '') then begin
AName.FCatalog := GetCatalogName;
AName.FSchema := GetSchemaName;
end
else begin
FConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(sCmd, AName, Self, [doNormalize, doUnquote, doMetaParams]);
end;
CheckMetaInfoParams(AName);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.GenerateSelectMetaInfo(const AName: TFDPhysParsedName);
var
oGen: IFDPhysCommandGenerator;
i: Integer;
oPar: TFDParam;
begin
GetMacros.Clear;
GetParams.Clear;
CreateCommandGenerator(oGen);
FDbCommandText := oGen.GenerateSelectMetaInfo(GetMetaInfoKind(),
AName.FCatalog, AName.FSchema, AName.FBaseObject, AName.FObject,
GetWildcard(), GetObjectScopes(), GetTableKinds(), GetOverload());
SetCommandKind(oGen.CommandKind);
for i := 0 to GetParams.Count - 1 do begin
oPar := GetParams[i];
if CompareText(oPar.Name, 'CAT') = 0 then
oPar.Value := AName.FCatalog
else if CompareText(oPar.Name, 'SCH') = 0 then
oPar.Value := AName.FSchema
else if CompareText(oPar.Name, 'BAS') = 0 then
oPar.Value := AName.FBaseObject
else if CompareText(oPar.Name, 'OBJ') = 0 then
oPar.Value := AName.FObject
else if CompareText(oPar.Name, 'WIL') = 0 then
oPar.Value := GetWildcard()
else if CompareText(oPar.Name, 'OVE') = 0 then
oPar.Value := GetOverload();
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.GenerateLimitSelect();
var
oFtchOpts: TFDFetchOptions;
procedure DoGenerate(ASkip, ARows: Integer);
var
oGen: IFDPhysCommandGenerator;
oConnMeta: IFDPhysConnectionMetadata;
begin
CreateCommandGenerator(oGen);
FConnection.CreateMetadata(oConnMeta);
FLimitOptions := oConnMeta.LimitOptions;
FDbCommandText := oGen.GenerateLimitSelect(ASkip, ARows,
(oFtchOpts.Mode = fmExactRecsMax) and (ARows >= 0), FLimitOptions);
FSQLOrderByPos := oGen.SQLOrderByPos;
end;
begin
oFtchOpts := FOptions.FetchOptions;
if (FSQLLimitSkip <> -1) or (FSQLLimitRows <> -1) then
DoGenerate(FSQLLimitSkip, FSQLLimitRows)
else if (oFtchOpts.RecsSkip <> -1) or
(oFtchOpts.RecsMax <> -1) and (oFtchOpts.Mode <> fmExactRecsMax) then
DoGenerate(oFtchOpts.RecsSkip, oFtchOpts.RecsMax);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.GenerateParamMarkers();
var
i: Integer;
oPars: TFDParams;
begin
oPars := GetParams();
if (oPars.Markers.Count = 0) and (oPars.Count > 0) then
for i := 0 to oPars.Count - 1 do
oPars.Markers.Add(oPars[i].Name);
end;
{-------------------------------------------------------------------------------}
// Query open / close
type
TFDPhysCommandAsyncOpen = class(TFDPhysCommandAsyncOperation)
protected
procedure Execute; override;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandAsyncOpen.Execute;
begin
FCommand.OpenBase;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.CheckMetaInfoParams(const AName: TFDPhysParsedName);
procedure CheckRequired(const AValue, ASubMsg: String);
begin
if AValue = '' then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccMetaInfoNotDefined, [ASubMsg]);
end;
const
STabName: String = 'table name';
SProcName: String = 'procedure name';
SIndexName: String = 'index name';
SFKName: String = 'foreign key name';
STabTypeName: String = 'table type name';
begin
case GetMetaInfoKind of
mkCatalogs,
mkSchemas,
mkTables:
;
mkTableFields:
CheckRequired(AName.FObject, STabName);
mkIndexes:
CheckRequired(AName.FObject, STabName);
mkIndexFields:
begin
CheckRequired(AName.FBaseObject, STabName);
CheckRequired(AName.FObject, SIndexName);
end;
mkPrimaryKey:
CheckRequired(AName.FObject, STabName);
mkPrimaryKeyFields:
CheckRequired(AName.FBaseObject, STabName);
mkForeignKeys:
CheckRequired(AName.FObject, STabName);
mkForeignKeyFields:
begin
CheckRequired(AName.FBaseObject, STabName);
CheckRequired(AName.FObject, SFKName);
end;
mkPackages,
mkProcs:
;
mkProcArgs:
CheckRequired(AName.FObject, SProcName);
mkGenerators,
mkResultSetFields:
;
mkTableTypeFields:
CheckRequired(AName.FObject, STabTypeName);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.OpenBase;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekCmdExecute, esStart, 'Open', ['Command', GetTraceCommandText]);
end;
procedure Trace2(AUpdateMonitor: Boolean);
begin
if AUpdateMonitor then UpdateMonitor;
Trace(ekCmdExecute, esEnd, 'Open', ['Command', GetTraceCommandText]);
end;
{$ENDIF}
var
lOpened: Boolean;
lExecuted: Boolean;
iCount: TFDCounter;
{$IFDEF FireDAC_MONITOR}
lUpdateMonitor: Boolean;
{$ENDIF}
begin
if GetState = csOpen then
Exit
else if GetState = csAborting then begin
FState := csPrepared;
Exit;
end;
{$IFDEF FireDAC_MONITOR}
if EnterTrace(FConnectionObj) then Trace1;
{$ENDIF}
try
InitRowsAffected;
iCount := 0;
if not GetNextRecordSet then
FConnectionObj.SaveLastAutoGenValue(Null);
CheckAsyncProgress;
if GetState = csInactive then
Prepare;
CheckState(csPrepared);
FState := csExecuting;
FThreadID := TThread.CurrentThread.ThreadID;
FExecutor.Launched;
lOpened := False;
try
try
lExecuted := False;
repeat
if not GetNextRecordSet then
FTransactionObj.Notify(cpBeforeCmdExecute, Self);
try
if not GetNextRecordSet then
lOpened := InternalOpen(iCount)
else
lOpened := InternalNextRecordSet;
lExecuted := True;
except
on E: EFDDBEngineException do begin
if E.Kind = ekServerGone then begin
FConnectionObj.RecoverConnection(Self, False);
if GetNextRecordSet then begin
lOpened := False;
lExecuted := True;
end
end
else
raise;
end;
end;
until lExecuted;
finally
UpdateRowsAffected(iCount);
if FState = csAborting then begin
lOpened := False;
InternalClose;
end;
if lOpened then begin
FState := csOpen;
FBuffer.Check;
FEof := False;
FFirstFetch := True;
FRecordsFetched := 0;
Inc(FExecuteCount);
Inc(FRecordSetIndex);
end
else if GetState <> csInactive then
FState := csPrepared;
end;
except
if not GetNextRecordSet then
FTransactionObj.Notify(cpAfterCmdExecuteFailure, Self);
raise;
end;
if not lOpened then
FTransactionObj.Notify(cpAfterCmdExecuteSuccess, Self);
finally
FThreadID := 0;
{$IFDEF FireDAC_MONITOR}
if ExitTrace(FConnectionObj, lUpdateMonitor) then Trace2(lUpdateMonitor);
{$ENDIF}
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.OpenBlocked: Boolean;
begin
if GetState <> csOpen then
Open(True);
Result := (GetState = csOpen);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.Open(ABlocked: Boolean = False);
var
oOper: IFDStanAsyncOperation;
begin
oOper := TFDPhysCommandAsyncOpen.Create(Self) as IFDStanAsyncOperation;
ExecuteTask(oOper, GetStateHandler, ABlocked);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.Close;
{$IFDEF FireDAC_MONITOR}
var
oConn: TFDPhysConnection;
lUpdateMonitor: Boolean;
sCmdText: String;
procedure Trace1;
begin
sCmdText := GetTraceCommandText;
Trace(ekCmdExecute, esStart, 'Close', ['Command', sCmdText]);
end;
procedure Trace2(AUpdateMonitor: Boolean);
begin
if AUpdateMonitor then UpdateMonitor;
oConn.Trace(ekCmdExecute, esEnd, 'Close', ['Command', sCmdText]);
end;
{$ENDIF}
begin
if GetState in [csInactive, csPrepared] then
Exit;
{$IFDEF FireDAC_MONITOR}
oConn := FConnectionObj;
if EnterTrace(oConn) then Trace1;
try
{$ENDIF}
CheckAsyncProgress;
if GetState = csOpen then
try
try
InternalClose;
except
on E: EFDDBEngineException do
if E.Kind <> ekServerGone then
raise;
end;
finally
if GetState <> csInactive then
FState := csPrepared;
FRecordSetIndex := -1;
if not GetNextRecordSet then
FTransactionObj.Notify(cpAfterCmdExecuteSuccess, Self);
end;
{$IFDEF FireDAC_MONITOR}
finally
if ExitTrace(oConn, lUpdateMonitor) then Trace2(lUpdateMonitor);
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.CloseAll;
begin
GetParams.Close;
SetNextRecordSet(False);
Close;
end;
{-------------------------------------------------------------------------------}
// Defining
function TFDPhysCommand.InternalUseStandardMetadata: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.DoDefineDataTable(ADatSManager: TFDDatSManager;
ATable: TFDDatSTable; ARootID: Integer; const ARootName: String;
AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode): TFDDatSTable;
var
i, j: Integer;
oFmtOpts: TFDFormatOptions;
oUpdOpts: TFDBottomUpdateOptions;
rTabInfo: TFDPhysDataTableInfo;
rColInfo: TFDPhysDataColumnInfo;
oChildTab: TFDDatSTable;
oCol, oChildTabRelCol, oROWIDCol: TFDDatSColumn;
oRel: TFDDatSRelation;
lTabCreated, lColCreated, lInUpdate: Boolean;
oCreatedList: TFDObjList;
oOriginCols: TFDStringList;
sName, sTabName, sFirstOriginTabName: String;
lDefPK, lPKDefined, lNoRowSet, lExtAttrs: Boolean;
oConnMeta: IFDPhysConnectionMetadata;
oPKFieldsView: TFDDatSView;
rMappedTab: TFDPhysMappingName;
eLocalMetaInfoMergeMode: TFDPhysMetaInfoMergeMode;
rName, rName1, rName2: TFDPhysParsedName;
lOriginProvided, lUpdBaseFieldsOnly, lOriginUseful: Boolean;
iArrayItem: Integer;
lTabIsArray: Boolean;
function EnsureTabExistance(ADatSManager: TFDDatSManager; var ASourceID: Integer;
var ASourceName, ADatSName: String; var ATabCreated: Boolean): TFDDatSTable;
var
i: Integer;
eMapResult: TFDPhysMappingResult;
sTmp: String;
oTab: TFDDatSTable;
begin
if ATable <> nil then
Result := ATable
else
Result := nil;
ATabCreated := False;
ADatSName := '';
eMapResult := mrDefault;
sTmp := '';
oTab := nil;
rMappedTab := TFDPhysMappingName.Create(0, nkDefault);
if ((ADatSManager = nil) or (AMetaInfoMergeMode <> mmRely)) and
(GetMappingHandler <> nil) then begin
if ASourceID >= 0 then
eMapResult := GetMappingHandler.MapRecordSet(TFDPhysMappingName.Create(ASourceID, nkID),
ASourceID, ASourceName, ADatSName, sTmp, oTab);
if eMapResult = mrMapped then
rMappedTab := TFDPhysMappingName.Create(ASourceID, nkID)
else begin
eMapResult := GetMappingHandler.MapRecordSet(TFDPhysMappingName.Create(ASourceName, nkSource),
ASourceID, ASourceName, ADatSName, sTmp, oTab);
if eMapResult = mrMapped then
rMappedTab := TFDPhysMappingName.Create(ASourceName, nkSource);
end;
if (eMapResult = mrMapped) and (ATable = nil) then
Result := oTab
end;
if eMapResult = mrDefault then
if (ADatSManager <> nil) and (ATable = nil) then begin
if eLocalMetaInfoMergeMode <> mmReset then begin
if ASourceName <> '' then
i := ADatSManager.Tables.IndexOfSourceName(ASourceName)
else
i := -1;
if (i = -1) and (ASourceID >= 0) then
i := ADatSManager.Tables.IndexOfSourceID(ASourceID);
if i <> -1 then
Result := ADatSManager.Tables[i];
end;
end;
if Result = nil then begin
if (eLocalMetaInfoMergeMode <> mmRely) and ((ARootID <> -1) or (eMapResult <> mrNotMapped)) then begin
Result := TFDDatSTable.Create;
Result.CountRef(0);
oCreatedList.Add(Result);
ATabCreated := True;
end;
end
else
if (eLocalMetaInfoMergeMode = mmRely) and (ATable <> nil) and (ATable <> Result) then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccMetaInfoMismatch, []);
if Result <> nil then
Result.Setup(FOptions);
end;
function EnsureColExistance(ATable: TFDDatSTable; var ASourceID: Integer;
var ASourceName, ADatSName: String; var AColCreated: Boolean): TFDDatSColumn;
var
i: Integer;
eMapResult: TFDPhysMappingResult;
sTmp: String;
oCol: TFDDatSColumn;
begin
Result := nil;
AColCreated := False;
ADatSName := '';
sTmp := '';
oCol := nil;
eMapResult := mrDefault;
if ((ATable = nil) or (AMetaInfoMergeMode <> mmRely)) and
(GetMappingHandler <> nil) and (rMappedTab.FKind <> nkDefault) then begin
if ASourceID >= 0 then
eMapResult := GetMappingHandler.MapRecordSetColumn(rMappedTab,
TFDPhysMappingName.Create(ASourceID, nkID),
ASourceID, ASourceName, ADatSName, sTmp, oCol);
if eMapResult <> mrMapped then
eMapResult := GetMappingHandler.MapRecordSetColumn(rMappedTab,
TFDPhysMappingName.Create(ASourceName, nkSource),
ASourceID, ASourceName, ADatSName, sTmp, oCol);
if (oCol <> nil) and (oCol.Table = ATable) and (eMapResult = mrMapped) then
Result := oCol;
end;
if eMapResult = mrDefault then
if eLocalMetaInfoMergeMode <> mmReset then begin
if ASourceName <> '' then
i := ATable.Columns.IndexOfSourceName(ASourceName)
else
i := -1;
if (i = -1) and (ASourceID >= 0) then
i := ATable.Columns.IndexOfSourceID(ASourceID);
if i <> -1 then
Result := ATable.Columns[i];
end;
if Result = nil then
if (eLocalMetaInfoMergeMode <> mmRely) and (eMapResult <> mrNotMapped) then begin
Result := TFDDatSColumn.Create;
oCreatedList.Add(Result);
AColCreated := True;
end;
end;
procedure CheckColMatching(AColumn: TFDDatSColumn; const AInfo: TFDPhysDataColumnInfo);
begin
if not ((AColumn.SourceDataType = AInfo.FSourceType) and
(AnsiCompareText(AColumn.SourceName, AInfo.FSourceName) = 0) and
(AColumn.SourceID = AInfo.FSourceID)) then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccMetaInfoMismatch, []);
end;
function GetDatSManager: TFDDatSManager;
begin
if ADatSManager <> nil then
Result := ADatSManager
else if ATable <> nil then
Result := ATable.Manager
else
Result := nil;
end;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekCmdPrepare, esProgress, 'Col add (ref)',
['Index', ATable.Columns.Count, 'Name', oCol.SourceName,
'@Type', C_FD_DataTypeNames[oCol.SourceDataType], 'TypeName',
oCol.SourceDataTypeName]);
end;
procedure Trace2;
begin
Trace(ekCmdPrepare, esProgress, 'Col add',
['Index', ATable.Columns.Count, 'SrcName', oCol.SourceName,
'@SrcType', C_FD_DataTypeNames[oCol.SourceDataType],
'SrcSize', oCol.SourceSize, 'SrcPrec', oCol.SourcePrecision,
'SrcScale', oCol.SourceScale, '@Type', C_FD_DataTypeNames[oCol.DataType],
'Size', oCol.Size, 'Prec', oCol.Precision, 'Scale', oCol.Scale,
'OrigTabName', oCol.OriginTabName, 'OrigColName', oCol.OriginColName]);
end;
procedure Trace3;
begin
Trace(ekCmdPrepare, esProgress, 'Primary key',
['Cols', oPKFieldsView.Rows.GetValuesList('COLUMN_NAME', ';', '')]);
end;
{$ENDIF}
begin
FConnection.CreateMetadata(oConnMeta);
rName.FCatalog := '';
rName.FSchema := '';
rName.FBaseObject := '';
rName.FLink := '';
eLocalMetaInfoMergeMode := AMetaInfoMergeMode;
if GetMetaInfoKind <> mkNone then begin
if eLocalMetaInfoMergeMode <> mmReset then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccMetaInfoReset, []);
Result := ATable;
if Result = nil then begin
Result := TFDDatSTable.Create;
Result.CountRef(0);
Result.Setup(FOptions);
Result.Name := oConnMeta.DefineMetadataTableName(GetMetaInfoKind);
if GetDatSManager <> nil then
GetDatSManager.Tables.Add(Result);
end
else
Result.Reset;
oConnMeta.DefineMetadataStructure(Result, GetMetaInfoKind);
Exit;
end;
oFmtOpts := FOptions.FormatOptions;
oUpdOpts := FOptions.UpdateOptions as TFDBottomUpdateOptions;
if oUpdOpts.UpdateTableName <> '' then
sTabName := oUpdOpts.UpdateTableName
else
sTabName := GetSourceObjectName;
oROWIDCol := nil;
oPKFieldsView := nil;
if (oUpdOpts.KeyFields <> '') or not InternalUseStandardMetadata then begin
lDefPK := False;
lPKDefined := False;
end
else begin
lDefPK := (ARootID = -1) and (fiMeta in FOptions.FetchOptions.Items) and (sTabName <> '') and
not ((sTabName[1] = '(') and (sTabName[Length(sTabName)] = ')')) and
(Pos('''', sTabName) = 0);
lPKDefined := False;
end;
lNoRowSet := False;
lTabCreated := False;
lExtAttrs := False;
lTabIsArray := False;
sName := '';
sFirstOriginTabName := '';
lOriginProvided := False;
lOriginUseful := True;
oCreatedList := TFDObjList.Create;
oOriginCols := TFDStringList.Create(dupIgnore, True, False);
try
try
if lDefPK then
oPKFieldsView := oConnMeta.GetTablePrimaryKeyFields(GetCatalogName,
GetSchemaName, sTabName, '');
rTabInfo.FSourceID := ARootID;
rTabInfo.FArraySize := -1;
if not InternalColInfoStart(rTabInfo) then begin
lNoRowSet := True;
ATable := nil;
end
else begin
if ARootID = -1 then
rTabInfo.FSourceName := GetSourceRecordSetName
else
rTabInfo.FSourceName := ARootName + '.' + rTabInfo.FOriginName;
lTabIsArray := rTabInfo.FArraySize >= 0;
ATable := EnsureTabExistance(ADatSManager, rTabInfo.FSourceID,
rTabInfo.FSourceName, sName, lTabCreated);
if ATable <> nil then begin
if (eLocalMetaInfoMergeMode = mmOverride) and lTabCreated then
eLocalMetaInfoMergeMode := mmReset
else if (eLocalMetaInfoMergeMode = mmReset) and not lTabCreated then
ATable.Reset;
if (eLocalMetaInfoMergeMode <> mmRely) or lTabCreated then begin
if sName <> '' then
ATable.Name := sName
else if GetDatSManager <> nil then
ATable.Name := GetDatSManager.Tables.BuildUniqueName(rTabInfo.FSourceName)
else
ATable.Name := rTabInfo.FSourceName;
ATable.SourceName := rTabInfo.FSourceName;
ATable.SourceID := rTabInfo.FSourceID;
ATable.MinimumCapacity := FOptions.FetchOptions.ActualRowsetSize;
if (GetDatSManager <> nil) and (ATable.Manager <> GetDatSManager) then begin
if ATable.Manager <> nil then
ATable.Manager.Tables.Remove(ATable, True);
GetDatSManager.Tables.Add(ATable);
end;
end;
end;
end;
if ATable <> nil then begin
FillChar(rColInfo, SizeOf(TFDPhysDataColumnInfo), 0);
rColInfo.FParentTableSourceID := ARootID;
rColInfo.FTableSourceID := rTabInfo.FSourceID;
iArrayItem := 0;
while (iArrayItem = 0) and InternalColInfoGet(rColInfo) or
lTabIsArray and (iArrayItem < rTabInfo.FArraySize) do begin
if lTabIsArray then begin
rColInfo.FSourceName := Format('%s[%d]', [rTabInfo.FOriginName, iArrayItem]);
rColInfo.FSourceID := iArrayItem;
end
else if rColInfo.FSourceName = '' then begin
Include(rColInfo.FAttrs, caUnnamed);
rColInfo.FSourceName := S_FD_Unnamed + IntToStr(rColInfo.FSourceID);
end
else if StrLIComp(PChar(rColInfo.FSourceName),
PChar(C_FD_SysColumnPrefix),
Length(C_FD_SysColumnPrefix)) = 0 then begin
Include(rColInfo.FAttrs, caInternal);
if not (caROWID in rColInfo.FAttrs) then
Include(rColInfo.FAttrs, caReadOnly);
rColInfo.FSourceName := Copy(rColInfo.FSourceName,
Length(C_FD_SysColumnPrefix) + 1, MAXINT);
if rColInfo.FOriginColName = '' then
rColInfo.FOriginColName := rColInfo.FSourceName;
end;
lColCreated := False;
if rColInfo.FType in [dtRowSetRef, dtCursorRef, dtRowRef, dtArrayRef] then begin
if GetDatSManager <> nil then begin
oChildTab := DoDefineDataTable(GetDatSManager, nil, rColInfo.FSourceID,
rTabInfo.FSourceName, AMetaInfoMergeMode);
if oChildTab <> nil then begin
oCol := EnsureColExistance(ATable, rColInfo.FSourceID,
rColInfo.FSourceName, sName, lColCreated);
if (oCol <> nil) and (eLocalMetaInfoMergeMode <> mmRely) or lColCreated then begin
if lColCreated or (oCol.Name = '') then
if sName <> '' then
oCol.Name := sName
else
oCol.Name := ATable.Columns.BuildUniqueName(rColInfo.FSourceName);
oCol.DataType := rColInfo.FType;
oCol.SourceName := rColInfo.FSourceName;
oCol.SourceID := rColInfo.FSourceID;
oCol.SourceDataType := rColInfo.FSourceType;
oCol.SourceDataTypeName := rColInfo.FSourceTypeName;
oCol.OriginTabName := oConnMeta.EncodeObjName(rColInfo.FOriginTabName, nil, [eoBeautify]);
rName.FObject := rColInfo.FOriginColName;
oCol.OriginColName := oConnMeta.EncodeObjName(rName, nil, [eoBeautify]);
oCol.Attributes := rColInfo.FAttrs - [caSearchable];
oCol.Options := oCol.Options + rColInfo.FForceAddOpts - rColInfo.FForceRemOpts;
if lColCreated then
ATable.Columns.Add(oCol);
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace1;
{$ENDIF}
if lColCreated then begin
oChildTabRelCol := TFDDatSColumn.Create;
oCreatedList.Add(oChildTabRelCol);
oChildTabRelCol.Name := oChildTab.Columns.BuildUniqueName(
C_FD_SysNamePrefix + '#' + ATable.Name);
oChildTabRelCol.DataType := dtParentRowRef;
oChildTabRelCol.SourceDataType := dtUnknown;
oChildTabRelCol.SourceID := -1;
oChildTabRelCol.Attributes := oCol.Attributes + [caInternal] - [caSearchable];
oChildTab.Columns.Add(oChildTabRelCol);
oRel := TFDDatSRelation.Create;
oCreatedList.Add(oRel);
oRel.Nested := True;
oRel.Name := GetDatSManager.Relations.BuildUniqueName(
C_FD_SysNamePrefix + '#' + ATable.Name + '#' + oChildTab.Name);
oRel.ParentTable := ATable;
oRel.ParentColumnNames := oCol.Name;
oRel.ChildTable := oChildTab;
oRel.ChildColumnNames := oChildTabRelCol.Name;
GetDatSManager.Relations.Add(oRel);
end;
end;
end;
end;
end
else begin
oCol := EnsureColExistance(ATable, rColInfo.FSourceID,
rColInfo.FSourceName, sName, lColCreated);
if (oCol <> nil) and (eLocalMetaInfoMergeMode <> mmRely) or lColCreated then begin
if lColCreated or (oCol.Name = '') then
if sName <> '' then
oCol.Name := sName
else
oCol.Name := ATable.Columns.BuildUniqueName(rColInfo.FSourceName);
oCol.SourceName := rColInfo.FSourceName;
oCol.SourceID := rColInfo.FSourceID;
oCol.SourceDataType := rColInfo.FSourceType;
oCol.SourceDataTypeName := rColInfo.FSourceTypeName;
oCol.SourcePrecision := rColInfo.FPrec;
oCol.SourceScale := rColInfo.FScale;
oCol.SourceSize := rColInfo.FLen;
oCol.OriginTabName := oConnMeta.EncodeObjName(rColInfo.FOriginTabName, nil, [eoBeautify]);
if sFirstOriginTabName = '' then begin
sFirstOriginTabName := oCol.OriginTabName;
if (GetSourceObjectName <> '') and (sFirstOriginTabName <> '') and
(oUpdOpts.UpdateTableName = '') then begin
oConnMeta.DecodeObjName(GetSourceObjectName, rName1, nil, [doUnquote]);
oConnMeta.DecodeObjName(sFirstOriginTabName, rName2, nil, [doUnquote]);
if CompareText(rName1.FObject, rName2.FObject) <> 0 then
lOriginUseful := False;
end;
end;
rName.FObject := rColInfo.FOriginColName;
oCol.OriginColName := oConnMeta.EncodeObjName(rName, nil, [eoBeautify]);
oCol.Attributes := rColInfo.FAttrs;
if caROWID in oCol.Attributes then
oROWIDCol := oCol;
oCol.DataType := rColInfo.FType;
case oCol.DataType of
dtAnsiString,
dtWideString,
dtByteString:
if rColInfo.FLen <> LongWord(-1) then
oCol.Size := rColInfo.FLen;
dtSByte,
dtInt16,
dtInt32,
dtInt64,
dtByte,
dtUInt16,
dtUInt32,
dtUInt64:
oCol.Precision := rColInfo.FPrec;
dtSingle,
dtDouble,
dtExtended,
dtCurrency,
dtBCD,
dtFmtBCD:
begin
if oFmtOpts.DataSnapCompatibility and (rColInfo.FPrec > 32) then begin
if rColInfo.FPrec = rColInfo.FScale then
rColInfo.FScale := rColInfo.FPrec div 3;
rColInfo.FPrec := 32;
end;
oCol.Precision := rColInfo.FPrec;
oCol.Scale := rColInfo.FScale;
end;
dtDateTime,
dtDateTimeStamp,
dtTime:
oCol.Scale := rColInfo.FScale;
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS:
begin
oCol.Precision := rColInfo.FPrec;
oCol.Scale := rColInfo.FScale;
end;
dtUnknown:
begin
oCol.DataType := dtAnsiString;
oCol.Size := 1;
oCol.Attributes := oCol.Attributes + [caAllowNull, caReadOnly];
rColInfo.FForceAddOpts := [coAllowNull, coReadOnly];
rColInfo.FForceRemOpts := [coInUpdate, coInWhere, coInKey, coAfterInsChanged, coAfterUpdChanged];
end;
end;
if caDefault in oCol.Attributes then
Include(rColInfo.FForceAddOpts, coAllowNull);
oCol.Options := oCol.Options + rColInfo.FForceAddOpts - rColInfo.FForceRemOpts;
lExtAttrs := lExtAttrs or (oCol.Attributes * [caBase, caExpr] <> []);
if lColCreated then
ATable.Columns.Add(oCol);
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace2;
{$ENDIF}
end;
end;
if lTabIsArray then
Inc(iArrayItem);
end;
if not lTabIsArray and (ARootID = -1) then begin
lOriginProvided := lOriginUseful and (oConnMeta.ColumnOriginProvided or (sFirstOriginTabName <> ''));
lUpdBaseFieldsOnly := lOriginProvided and not oUpdOpts.UpdateNonBaseFields;
for i := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns.ItemsI[i];
if not lOriginUseful or (oCol.OriginColName = '') then begin
oCol.OriginTabName := '';
rName.FObject := oCol.SourceName;
oCol.OriginColName := oConnMeta.EncodeObjName(rName, nil, [eoBeautify]);
end;
if not lExtAttrs then
if not lOriginProvided then
oCol.Attributes := oCol.Attributes + [caBase]
else if (oCol.OriginTabName = '') and not (caBase in oCol.Attributes) then
oCol.Attributes := oCol.Attributes + [caExpr, caReadOnly] - [caDefault]
else if (oCol.OriginTabName <> '') and (CompareText(sFirstOriginTabName, oCol.OriginTabName) = 0) then
oCol.Attributes := oCol.Attributes + [caBase];
// SELECT F1 AS A, F1 AS B -> excluded extra occurences of F1 from updates
// to avoid "Column Xxx cannot be repeated in UPDATE statement"
if lUpdBaseFieldsOnly and (caBase in oCol.Attributes) then begin
if oCol.OriginTabName <> '' then
sName := oCol.OriginTabName + '.'
else
sName := '';
sName := sName + oCol.OriginColName;
if sName <> '' then begin
if oOriginCols.IndexOf(sName) >= 0 then
oCol.Options := oCol.Options - [coInUpdate, coInWhere, coInKey] +
[coAfterInsChanged, coAfterUpdChanged];
oOriginCols.Add(sName);
end;
end;
// Server side calculated fields has to be excluded from updates
if [caCalculated, caReadOnly] * oCol.Attributes = [caCalculated, caReadOnly] then
oCol.Options := oCol.Options - [coInUpdate, coInWhere, coInKey] +
[coReadOnly, coAfterInsChanged, coAfterUpdChanged];
// Set key fields and auto-inc fields only for base fields
if not lUpdBaseFieldsOnly or (caBase in oCol.Attributes) then begin
if oUpdOpts.KeyFields <> '' then
if FDFieldInFieldNames(oUpdOpts.KeyFields, oCol.SourceName) then
oCol.Options := oCol.Options + [coInKey]
else
oCol.Options := oCol.Options - [coInKey];
if coInKey in oCol.Options then
lPKDefined := True;
lInUpdate := coInUpdate in oCol.Options;
if caAutoInc in oCol.Attributes then
if oCol.IsAutoIncrementType(oCol.DataType) then begin
oCol.ServerAutoIncrement := True;
if oConnMeta.GeneratorSupported and not oConnMeta.InlineRefresh and lInUpdate then
oCol.Options := oCol.Options + [coInUpdate];
end
else
// Non-numeric fields with caAutoInc has to be converted to caROWID
oCol.Attributes := oCol.Attributes - [caAutoInc] + [caROWID]
else if (oUpdOpts.AutoIncFields <> '') and
FDFieldInFieldNames(oUpdOpts.AutoIncFields, oCol.SourceName) then begin
oCol.ServerAutoIncrement := True;
if oConnMeta.GeneratorSupported and lInUpdate then
oCol.Options := oCol.Options + [coInUpdate];
end;
end;
// Exclude non-base fields from editing
if [caROWID, caRowVersion, caInternal, caCalculated, caBase] * oCol.Attributes = [] then begin
if lUpdBaseFieldsOnly then begin
oCol.Attributes := oCol.Attributes - [caAutoInc];
oCol.Options := oCol.Options - [coInUpdate, coInWhere, coInKey] +
[coReadOnly, coAllowNull];
end
else if not lExtAttrs and (caExpr in oCol.Attributes) then
oCol.Options := oCol.Options - [coReadOnly];
if lOriginProvided then
oCol.Options := oCol.Options - [coInKey];
oCol.Options := oCol.Options + [coAfterInsChanged, coAfterUpdChanged];
end;
end;
end;
if lDefPK and not lPKDefined then begin
{$IFDEF FireDAC_MONITOR}
if FConnectionObj.GetTracing then Trace3;
{$ENDIF}
for i := 0 to oPKFieldsView.Rows.Count - 1 do begin
j := ATable.Columns.IndexOfName(oPKFieldsView.Rows.ItemsI[i].GetData('COLUMN_NAME'));
if j <> -1 then begin
oCol := ATable.Columns.ItemsI[j];
oCol.Options := oCol.Options + [coInKey];
lPKDefined := True;
end;
end;
end;
if not lPKDefined and (oROWIDCol <> nil) then
oROWIDCol.Options := oROWIDCol.Options + [coInKey];
if lOriginProvided and (GetSourceObjectName = '') and (sFirstOriginTabName <> '') then
SetSourceObjectName(sFirstOriginTabName);
end;
except
for i := oCreatedList.Count - 1 downto 0 do
FDFree(TObject(oCreatedList[i]));
raise;
end;
finally
if (oPKFieldsView <> nil) and (FConnection.State <> csDisconnected) then
FDClearMetaView(oPKFieldsView, FOptions.FetchOptions);
FDFree(oCreatedList);
FDFree(oOriginCols);
end;
Result := ATable;
if lNoRowSet then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccCmdMHRowSet, []);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.BeginDefine;
begin
CheckAsyncProgress;
if GetState = csInactive then
Prepare;
if GetState = csInactive then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccCmdMBPrepared, []);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.Define(ADatSManager: TFDDatSManager;
ATable: TFDDatSTable; AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode): TFDDatSTable;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
var
sTabName: String;
begin
if ATable <> nil then sTabName := ATable.Name else sTabName := '<nil>';
Trace(ekCmdPrepare, esStart, 'Define(TFDDatSManager)',
['ADatSManager', ADatSManager.Name, 'ATable', sTabName, 'Command', GetTraceCommandText]);
end;
procedure Trace2;
var
sTabName: String;
begin
if ATable <> nil then sTabName := ATable.Name else sTabName := '<nil>';
Trace(ekCmdPrepare, esEnd, 'Define(TFDDatSManager)',
['ADatSManager', ADatSManager.Name, 'ATable', sTabName, 'Command', GetTraceCommandText]);
end;
var
lUpdateMonitor: Boolean;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if EnterTrace(FConnectionObj) then Trace1;
try
{$ENDIF}
BeginDefine;
if AMetaInfoMergeMode = mmReset then begin
if GetMetaInfoKind = mkNone then begin
if ATable <> nil then
ATable.Reset;
AMetaInfoMergeMode := mmOverride;
end
else if ADatSManager <> nil then
ADatSManager.Reset;
end;
Result := DoDefineDataTable(ADatSManager, ATable, -1, '', AMetaInfoMergeMode);
{$IFDEF FireDAC_MONITOR}
finally
if ExitTrace(FConnectionObj, lUpdateMonitor) then Trace2;
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.Define(ATable: TFDDatSTable;
AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode): TFDDatSTable;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
var
sTabName: String;
begin
if ATable <> nil then sTabName := ATable.Name else sTabName := '<nil>';
Trace(ekCmdPrepare, esStart, 'Define(TFDDatSTable)',
['ATable', sTabName, 'Command', GetTraceCommandText]);
end;
procedure Trace2;
var
sTabName: String;
begin
if ATable <> nil then sTabName := ATable.Name else sTabName := '<nil>';
Trace(ekCmdPrepare, esEnd, 'Define(TFDDatSTable)',
['ATable', sTabName, 'Command', GetTraceCommandText]);
end;
var
lUpdateMonitor: Boolean;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if EnterTrace(FConnectionObj) then Trace1;
try
{$ENDIF}
BeginDefine;
Result := DoDefineDataTable(nil, ATable, -1, '', AMetaInfoMergeMode);
{$IFDEF FireDAC_MONITOR}
finally
if ExitTrace(FConnectionObj, lUpdateMonitor) then Trace2;
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
// Executing
type
TFDPhysCommandAsyncExecute = class(TFDPhysCommandAsyncOperation)
private
FTimes: Integer;
FOffset: Integer;
protected
// IFDStanAsyncOperation
procedure Execute; override;
public
constructor Create(ACmd: TFDPhysCommand; ATimes, AOffset: Integer);
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysCommandAsyncExecute.Create(ACmd: TFDPhysCommand;
ATimes, AOffset: Integer);
begin
inherited Create(ACmd);
FTimes := ATimes;
FOffset := AOffset;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandAsyncExecute.Execute;
begin
FCommand.ExecuteBase(FTimes, FOffset);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.CheckExact(AUseRecsMax: Boolean; ATimes, AOffset: Integer;
AValue: TFDCounter; AFetch: Boolean);
procedure Error;
var
sPref, sMsg, sOper: String;
eKind: TFDCommandExceptionKind;
oExc: EFDDBEngineException;
begin
if AFetch then
sOper := 'fetch returned'
else
sOper := 'update affected';
sPref := FDExceptionLayers([S_FD_LPhys, DriverID]) + '-' +
IntToStr(er_FD_AccExactMismatch) + '. ';
sMsg := Format(FDGetErrorMessage(er_FD_AccExactMismatch, []),
[sOper, AValue, ATimes - AOffset]);
if AValue < ATimes - AOffset then
eKind := ekNoDataFound
else
eKind := ekTooManyRows;
oExc := EFDDBEngineException.Create(er_FD_AccExactMismatch, sPref + sMsg);
oExc.AppendError(1, er_FD_AccExactMismatch, sMsg, '', eKind, -1, -1);
FDException(Self, oExc {$IFDEF FireDAC_Monitor}, FConnectionObj.GetTracing {$ENDIF});
end;
var
oFO: TFDFetchOptions;
begin
oFO := FOptions.FetchOptions;
if oFO.Mode = fmExactRecsMax then begin
if AUseRecsMax then begin
AOffset := 0;
ATimes := oFO.RecsMax;
end;
if (AValue <> ATimes - AOffset) and
(AValue >= 0) and (ATimes - AOffset >= 0) then
Error;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.CheckArrayDMLWithIntStr(AHasIntStreams: Boolean;
ATimes, AOffset: Integer);
begin
if AHasIntStreams and ((AOffset > 0) or (ATimes > 1)) then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccArrayDMLWithIntStr, []);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.InitRowsAffected;
begin
FRowsAffected := 0;
FRowsAffectedReal := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.UpdateRowsAffected(AValue: TFDCounter);
begin
if AValue <= -1 then begin
FRowsAffected := 0;
FRowsAffectedReal := False;
end
else if FRowsAffectedReal then begin
Inc(FRowsAffected, AValue);
Inc(FExecuteCount, AValue);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.ExecuteBase(ATimes, AOffset: Integer);
var
eMode: TFDPhysArrayExecMode;
lAtomic: Boolean;
lSavepoint: Boolean;
i: Integer;
{$IFDEF FireDAC_MONITOR}
lUpdateMonitor: Boolean;
{$ENDIF}
procedure SetMeta;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
FConnection.CreateMetadata(oConnMeta);
eMode := oConnMeta.ArrayExecMode;
lAtomic := (FTransactionObj <> nil) and FTransactionObj.GetActive and oConnMeta.TxAtomic;
lSavepoint := lAtomic and (oConnMeta.TxNested or oConnMeta.TxSavepoints);
oConnMeta := nil;
end;
function Process_HandleSystemFailure(ATimes, AOffset: Integer; out ACount: TFDCounter;
AArrayDML: Boolean): Boolean;
var
lExecuted: Boolean;
begin
Result := True;
FErrorAction := eaExitSuccess;
lExecuted := False;
repeat
ACount := 0;
if lSavepoint then
FTransactionObj.StartTransaction;
try
InternalExecute(ATimes, AOffset, ACount);
CheckExact(not AArrayDML, ATimes, AOffset, ACount, False);
lExecuted := True;
if lSavepoint then
FTransactionObj.Commit;
except
on E: EFDDBEngineException do begin
if lSavepoint then
FTransactionObj.Rollback;
case E.Kind of
ekServerGone:
begin
lSavepoint := False;
FConnectionObj.RecoverConnection(Self, False);
end;
ekArrExecMalfunc:
begin
Result := False;
Exit;
end;
else
raise;
end;
end;
end;
until lExecuted;
UpdateRowsAffected(ACount);
end;
procedure Process_SingleRow;
var
iCount: TFDCounter;
iRetryLevel: Integer;
oErr: Exception;
begin
iRetryLevel := 0;
repeat
try
Process_HandleSystemFailure(1, 0, iCount, False);
except
on E: EFDDBEngineException do begin
UpdateRowsAffected(iCount);
FErrorAction := eaFail;
if Assigned(GetErrorHandler()) then begin
Inc(iRetryLevel);
oErr := EFDDBArrayExecuteError.Create(1, 0, E, iRetryLevel);
try
GetErrorHandler().HandleException(nil, oErr);
if oErr <> nil then
FErrorAction := EFDDBArrayExecuteError(oErr).Action;
finally
FDFree(oErr);
end;
end;
case FErrorAction of
eaApplied,
eaSkip:
FErrorAction := eaExitSuccess;
eaRetry:
;
eaFail,
eaDefault:
raise;
end;
end;
end;
until FErrorAction in [eaExitSuccess, eaExitFailure];
end;
procedure Process_UntilFirstError(AUndoAll: Boolean);
var
iCount: TFDCounter;
iLastTimes, iLastOffset, iRetryLevel: Integer;
iCurTimes, iCurOffset, iArraySize: Integer;
oErr: Exception;
begin
iLastTimes := 0;
iLastOffset := 0;
iRetryLevel := 0;
iArraySize := FOptions.ResourceOptions.ArrayDMLSize;
if iArraySize > ATimes - AOffset then
iArraySize := ATimes - AOffset;
iCurOffset := AOffset;
iCurTimes := AOffset + iArraySize;
repeat
try
while iCurOffset < ATimes do begin
if iCurTimes > ATimes then
iCurTimes := ATimes;
if not Process_HandleSystemFailure(iCurTimes, iCurOffset, iCount, True) then begin
iArraySize := 1;
iCurTimes := iCurOffset + 1;
FErrorAction := eaRetry;
Continue;
end;
Inc(iCurOffset, iArraySize);
Inc(iCurTimes, iArraySize);
end;
except
on E: EFDDBEngineException do begin
UpdateRowsAffected(iCount);
if iCount > 0 then
iCurOffset := iCurOffset + Integer(iCount);
if AUndoAll then
if lAtomic and not lSavepoint then begin
FErrorAction := eaFail;
FRowsAffected := 0;
raise;
end
else if (iArraySize > 1) and not (E.Kind in [ekNoDataFound, ekTooManyRows]) then begin
iArraySize := 1;
iCurTimes := iCurOffset + 1;
FErrorAction := eaRetry;
Continue;
end;
FErrorAction := eaFail;
if Assigned(GetErrorHandler()) then begin
if (iLastTimes = iCurTimes) and (iLastOffset = iCurOffset) then
Inc(iRetryLevel)
else begin
iLastTimes := iCurTimes;
iLastOffset := iCurOffset;
iRetryLevel := 0;
end;
oErr := EFDDBArrayExecuteError.Create(iCurTimes, iCurOffset, E, iRetryLevel);
try
GetErrorHandler().HandleException(nil, oErr);
if oErr <> nil then
FErrorAction := EFDDBArrayExecuteError(oErr).Action;
finally
FDFree(oErr);
end;
end;
case FErrorAction of
eaApplied,
eaSkip:
begin
Inc(iCurOffset);
if iCurOffset >= iCurTimes then
Inc(iCurTimes, iArraySize);
if FErrorAction = eaApplied then
if FRowsAffected >= 0 then
Inc(FRowsAffected);
end;
eaRetry:
;
eaFail,
eaDefault:
raise;
end;
end;
end;
if (iCurOffset >= ATimes) and (FErrorAction <> eaExitFailure) then
FErrorAction := eaExitSuccess;
until FErrorAction in [eaExitSuccess, eaExitFailure];
end;
procedure RemoveCurrentRowErrors(E: EFDDBEngineException; ACurRow: Integer);
begin
repeat
FDFree(E[0]);
E.Remove(E[0]);
until (E.ErrorCount = 0) or (ACurRow <> E[0].RowIndex);
end;
procedure Process_CollectErrors;
var
iCount: TFDCounter;
iLastTimes, iLastOffset, iRetryLevel: Integer;
iCurTimes, iCurOffset, iArraySize: Integer;
oErr: Exception;
begin
iLastTimes := 0;
iLastOffset := 0;
iRetryLevel := 0;
iArraySize := FOptions.ResourceOptions.ArrayDMLSize;
if iArraySize > ATimes - AOffset then
iArraySize := ATimes - AOffset;
iCurOffset := AOffset;
iCurTimes := AOffset + iArraySize;
while iCurOffset < ATimes do begin
if iCurTimes > ATimes then
iCurTimes := ATimes;
try
if not Process_HandleSystemFailure(iCurTimes, iCurOffset, iCount, True) then begin
iArraySize := 1;
iCurTimes := iCurOffset + 1;
FErrorAction := eaRetry;
Continue;
end;
except
on E: EFDDBEngineException do begin
UpdateRowsAffected(iCount);
repeat
FErrorAction := eaFail;
AOffset := E[0].RowIndex;
if Assigned(GetErrorHandler()) then begin
if (iLastTimes = ATimes) and (iLastOffset = AOffset) then
Inc(iRetryLevel)
else begin
iLastTimes := ATimes;
iLastOffset := AOffset;
iRetryLevel := 0;
end;
oErr := EFDDBArrayExecuteError.Create(ATimes, AOffset, E, iRetryLevel);
try
GetErrorHandler().HandleException(nil, oErr);
if oErr <> nil then
FErrorAction := EFDDBArrayExecuteError(oErr).Action;
finally
FDFree(oErr);
end;
end;
case FErrorAction of
eaApplied,
eaSkip:
begin
RemoveCurrentRowErrors(E, AOffset);
if FErrorAction = eaApplied then
if FRowsAffected >= 0 then
Inc(FRowsAffected);
end;
eaRetry:
try
try
InternalExecute(AOffset + 1, AOffset, iCount);
CheckExact(False, AOffset + 1, AOffset, iCount, False);
finally
UpdateRowsAffected(iCount);
RemoveCurrentRowErrors(E, AOffset);
end;
except
on E2: EFDDBEngineException do begin
E.Merge(E2, 0);
FErrorAction := eaRetry;
end;
end;
eaFail,
eaDefault:
raise;
end;
if (E.ErrorCount = 0) and (FErrorAction <> eaExitFailure) then
FErrorAction := eaExitSuccess;
until (E.ErrorCount = 0) or (FErrorAction in [eaExitSuccess, eaExitFailure]);
end;
end;
Inc(iCurOffset, iArraySize);
Inc(iCurTimes, iArraySize);
end;
end;
procedure MBPrepared;
begin
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccCmdMBPrepared, []);
end;
procedure CantExec;
begin
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccCantExecCmdWithRowSet, []);
end;
procedure ParamArrMismatch(AParam: TFDParam);
begin
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccParamArrayMismatch,
[AParam.Name, AParam.ArraySize, ATimes]);
end;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekCmdExecute, esStart, 'Execute', ['Command', GetTraceCommandText,
'ATimes', ATimes, 'AOffset', AOffset]);
end;
procedure Trace2(AUpdateMonitor: Boolean);
begin
if AUpdateMonitor then UpdateMonitor;
Trace(ekCmdExecute, esEnd, 'Execute', ['Command', GetTraceCommandText,
'ATimes', ATimes, 'AOffset', AOffset, 'RowsAffected', FRowsAffected,
'RowsAffectedReal', FRowsAffectedReal, 'ErrorAction', Integer(FErrorAction)]);
end;
{$ENDIF}
begin
if GetState = csAborting then begin
FState := csPrepared;
Exit;
end;
{$IFDEF FireDAC_MONITOR}
if EnterTrace(FConnectionObj) then Trace1;
{$ENDIF}
try
InitRowsAffected;
FErrorAction := eaExitFailure;
if not GetNextRecordSet then
FConnectionObj.SaveLastAutoGenValue(Null);
CheckAsyncProgress;
if GetState = csInactive then
Prepare;
if GetState <> csPrepared then
MBPrepared;
if (GetCommandKind in [skSelect, skSelectForLock, skSelectForUnLock]) or
(GetMetaInfoKind <> mkNone) then
CantExec;
for i := 0 to GetParams.Count - 1 do
if GetParams[i].ArraySize < ATimes then
ParamArrMismatch(GetParams[i]);
FErrorAction := eaExitSuccess;
if ATimes <= 0 then
ATimes := 1;
if AOffset < 0 then
AOffset := 0;
if AOffset >= ATimes then
Exit;
lAtomic := False;
lSavepoint := False;
FState := csExecuting;
FThreadID := TThread.CurrentThread.ThreadID;
FExecutor.Launched;
try
try
FTransactionObj.Notify(cpBeforeCmdExecute, Self);
if (ATimes = 1) and (AOffset = 0) then
Process_SingleRow
else begin
SetMeta;
case eMode of
aeOnErrorUndoAll:
Process_UntilFirstError(True);
aeUpToFirstError:
Process_UntilFirstError(False);
aeCollectAllErrors:
Process_CollectErrors;
aeNotSupported:
if (ATimes <> 1) or (AOffset <> 0) then
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID])
else
Process_UntilFirstError(False);
end;
end;
finally
if GetState <> csInactive then
FState := csPrepared;
end;
except
FTransactionObj.Notify(cpAfterCmdExecuteFailure, Self);
raise;
end;
case FErrorAction of
eaExitSuccess:
FTransactionObj.Notify(cpAfterCmdExecuteSuccess, Self);
eaExitFailure:
FTransactionObj.Notify(cpAfterCmdExecuteFailure, Self);
else
ASSERT(False);
end;
finally
FThreadID := 0;
{$IFDEF FireDAC_MONITOR}
if ExitTrace(FConnectionObj, lUpdateMonitor) then Trace2(lUpdateMonitor);
{$ENDIF}
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.Execute(ATimes: Integer = 0; AOffset: Integer = 0;
ABlocked: Boolean = False);
var
oOper: IFDStanAsyncOperation;
begin
oOper := TFDPhysCommandAsyncExecute.Create(Self, ATimes, AOffset) as IFDStanAsyncOperation;
ExecuteTask(oOper, GetStateHandler, ABlocked);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetErrorAction: TFDErrorAction;
begin
Result := FErrorAction;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetRowsAffected: TFDCounter;
begin
Result := FRowsAffected;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetRowsAffectedReal: Boolean;
begin
Result := FRowsAffectedReal;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.InternalCloseStreams;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.CloseStreams;
begin
CheckAsyncProgress;
if GetState <> csPrepared then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccCmdMBPrepared, []);
try
InternalCloseStreams;
finally
GetParams.Close;
end;
end;
{-------------------------------------------------------------------------------}
// Fetching
type
TFDPhysCommandAsyncFetch = class(TFDPhysCommandAsyncOperation, IFDStanAsyncHandler)
private
FTable: TFDDatSTable;
FAll: Boolean;
protected
// IFDStanAsyncOperation
procedure Execute; override;
// IFDStanAsyncHandler
procedure HandleFinished(const AInitiator: IFDStanObject;
AState: TFDStanAsyncState; AException: Exception);
public
constructor Create(ACmd: TFDPhysCommand; ATable: TFDDatSTable; AAll: Boolean);
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysCommandAsyncFetch.Create(ACmd: TFDPhysCommand;
ATable: TFDDatSTable; AAll: Boolean);
begin
inherited Create(ACmd);
FTable := ATable;
FAll := AAll;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandAsyncFetch.Execute;
begin
FCommand.FetchBase(FTable, FAll);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandAsyncFetch.HandleFinished(const AInitiator: IFDStanObject;
AState: TFDStanAsyncState; AException: Exception);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
FCommand.Trace(ekCmdExecute, esProgress, 'Eof reached',
['ATable', FTable.SourceName, 'Command', FCommand.GetTraceCommandText]);
end;
{$ENDIF}
var
oHnlr: IFDPhysCommandStateHandler;
begin
// StartTransaction calls FConnectionObj.Lock and on MSSQL calls Fetch(True).
// On Eof the command is closing. That calls TFDPhysTransaction.InternalNotify,
// which is calling FConnectionObj.Lock. With async fetching that leads to
// deadlock, so call Close in the calling thread.
oHnlr := FCommand.GetStateHandler;
if FCommand.FEof then begin
{$IFDEF FireDAC_MONITOR}
if FCommand.FConnectionObj.GetTracing then Trace1;
{$ENDIF}
if FCommand.FOptions.FetchOptions.AutoClose then
FCommand.Close;
end;
if oHnlr <> nil then
oHnlr.HandleFinished(AInitiator, AState, AException);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.FetchBase(ATable: TFDDatSTable; AAll: Boolean);
function DoFetch(ARowsSkip, ARowsCount, ARowsetSize: Integer; AMaxLimited: Boolean): Integer;
var
iLastFetch, iThrowRows: Integer;
begin
Result := 0;
repeat
iLastFetch := 0;
if FRecordsFetched + ARowsetSize > ARowsCount then
ARowsetSize := ARowsCount - FRecordsFetched;
if ARowsetSize > 0 then begin
try
iLastFetch := InternalFetchRowSet(ATable, nil, ARowsetSize);
except
on E: EFDDBEngineException do
if E.Kind = ekServerGone then
FConnectionObj.RecoverConnection(Self, False)
else
raise;
end;
if ARowsSkip > 0 then begin
if ARowsSkip >= iLastFetch then
iThrowRows := iLastFetch
else
iThrowRows := ARowsSkip;
Inc(FRecordsFetched, iLastFetch - iThrowRows);
Inc(Result, iLastFetch - iThrowRows);
Dec(ARowsSkip, iThrowRows);
while iThrowRows > 0 do begin
ATable.Rows.RemoveAt(0);
Dec(iThrowRows);
end;
end
else begin
Inc(FRecordsFetched, iLastFetch);
Inc(Result, iLastFetch);
end;
end;
until (FState <> csFetching) or (iLastFetch <> ARowsetSize) or (FRecordsFetched >= ARowsCount);
FEof := (iLastFetch <> ARowsetSize) or AMaxLimited and (FRecordsFetched >= ARowsCount);
end;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekCmdExecute, esStart, 'Fetch',
['ATable', ATable.SourceName, 'Command', GetTraceCommandText]);
end;
procedure Trace2(AUpdateMonitor: Boolean);
begin
if AUpdateMonitor then UpdateMonitor;
Trace(ekCmdExecute, esEnd, 'Fetch',
['ATable', ATable.SourceName, 'Command', GetTraceCommandText,
'RowsAffected', FRowsAffected]);
end;
{$ENDIF}
var
oFO: TFDFetchOptions;
eMode: TFDFetchMode;
iRowsetSize, iRecsSkip, iRecsMax: Integer;
rState: TFDDatSLoadState;
lErase: Boolean;
{$IFDEF FireDAC_MONITOR}
lUpdateMonitor: Boolean;
{$ENDIF}
begin
if GetState = csAborting then begin
FState := csOpen;
Exit;
end;
{$IFDEF FireDAC_MONITOR}
if EnterTrace(FConnectionObj) then Trace1;
{$ENDIF}
try
InitRowsAffected;
if FEof then
Exit;
ASSERT(ATable <> nil);
CheckAsyncProgress;
if GetState <> csOpen then
FDException(Self, [S_FD_LPhys, DriverID], er_FD_AccCmdMBOpen4Fetch, []);
FState := csFetching;
FThreadID := TThread.CurrentThread.ThreadID;
FExecutor.Launched;
oFO := FOptions.FetchOptions;
if not FFirstFetch and not AAll then
eMode := fmOnDemand
else if AAll then
eMode := fmAll
else
eMode := oFO.Mode;
iRowsetSize := oFO.ActualRowsetSize;
iRecsSkip := 0;
if FFirstFetch and (not (loSkip in FLimitOptions) or (GetCommandKind <> skSelect)) then
if FSQLLimitSkip >= 0 then
iRecsSkip := FSQLLimitSkip
else
iRecsSkip := oFO.RecsSkip;
iRecsMax := oFO.RecsMax;
lErase := False;
if (eMode in [fmAll, fmExactRecsMax]) or (iRecsSkip > 0) then
ATable.BeginLoadData(rState, lmHavyFetching)
else
ATable.BeginLoadData(rState, lmFetching);
try
try
case eMode of
fmAll:
if iRecsMax > 0 then
FRowsAffected := DoFetch(iRecsSkip, iRecsMax, iRowsetSize, True)
else
FRowsAffected := DoFetch(iRecsSkip, MAXINT, iRowsetSize, False);
fmExactRecsMax:
begin
FRowsAffected := DoFetch(iRecsSkip, iRowsetSize + 1, iRowsetSize, True);
if FRowsAffected <> iRowsetSize then begin
lErase := (FRowsAffected = ATable.Rows.Count);
CheckExact(False, iRowsetSize, 0, FRowsAffected, True);
end;
end;
fmManual, fmOnDemand:
if (iRecsMax > 0) and (FRecordsFetched + iRowsetSize > iRecsMax) then
FRowsAffected := DoFetch(iRecsSkip, iRecsMax, iRowsetSize, True)
else
FRowsAffected := DoFetch(iRecsSkip, FRecordsFetched + iRowsetSize, iRowsetSize, False);
end;
finally
// If command is part of TFDQuery, the connection is lost,
// then query will be closed and ATable destroyed.
if ATable.DataHandleMode <> lmDestroying then
ATable.EndLoadData(rState);
end;
finally
FFirstFetch := False;
if GetState <> csInactive then
case FState of
csFetching:
FState := csOpen;
csAborting:
begin
FState := csOpen;
FEof := True;
end;
end;
if lErase then begin
FRowsAffected := 0;
ATable.Clear;
end;
end;
finally
FThreadID := 0;
{$IFDEF FireDAC_MONITOR}
if ExitTrace(FConnectionObj, lUpdateMonitor) then Trace2(lUpdateMonitor);
{$ENDIF}
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.Fetch(ATable: TFDDatSTable; AAll: Boolean = True;
ABlocked: Boolean = False);
var
oFetch: TFDPhysCommandAsyncFetch;
begin
oFetch := TFDPhysCommandAsyncFetch.Create(Self, ATable, AAll);
ExecuteTask(oFetch as IFDStanAsyncOperation, oFetch as IFDStanAsyncHandler, ABlocked);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.Fetch(ADatSManager: TFDDatSManager;
AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode = mmReset);
var
eMode: TFDPhysMetaInfoMergeMode;
oTab: TFDDatSTable;
iRows: Integer;
begin
iRows := 0;
try
CheckAsyncProgress;
if GetState = csInactive then
Prepare;
eMode := AMetaInfoMergeMode;
if eMode = mmReset then begin
ADatSManager.Reset;
eMode := mmOverride;
end;
while True do begin
if GetState = csPrepared then
OpenBlocked;
if GetState <> csOpen then
Break;
oTab := Define(ADatSManager, nil, eMode);
Fetch(oTab, True, True);
Inc(iRows, FRowsAffected);
SetNextRecordSet(True);
end;
if (GetState = csOpen) and FOptions.FetchOptions.AutoClose then
Close;
finally
FRowsAffected := iRows;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.CheckFetchColumn(ADataType: TFDDataType;
AAttributes: TFDDataAttributes): Boolean;
begin
Result := (ADataType <> dtUnknown) and (
not (
(ADataType in [dtRowSetRef, dtCursorRef]) and
not (fiDetails in FOptions.FetchOptions.Items) or
(ADataType in C_FD_BlobTypes) and
not (fiBlobs in FOptions.FetchOptions.Items)
) or (
GetMetaInfoKind() <> mkNone
)
);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.CheckParamMatching(AParam: TFDParam;
ADataType: TFieldType; AParamType: TParamType; APrec: Integer);
begin
if not ((AParamType = AParam.ParamType) or
(ptUnknown = AParam.ParamType) and (AParamType = ptInput)) or
not ((ADataType = AParam.DataType) or
(ADataType in [ftFixedChar, ftString]) and
(AParam.DataType in [ftFixedChar, ftString]) or
(ADataType in [ftFixedWideChar, ftWideString]) and
(AParam.DataType in [ftFixedWideChar, ftWideString]) or
(ADataType in [ftInteger, ftAutoInc, ftLongWord]) and
(AParam.DataType in [ftInteger, ftAutoInc, ftLongWord]) or
(ADataType in [ftFmtMemo, ftWideMemo]) and
(AParam.DataType in [ftFmtMemo, ftWideMemo]) or
(ADataType in [ftParadoxOle, ftOraInterval]) and
(AParam.DataType in [ftParadoxOle, ftOraInterval])) or
not ((APrec = 0) or (APrec = AParam.Precision)) then
ParDefChangedError(ADataType, AParam);
end;
{-------------------------------------------------------------------------------}
// IFDStanObject
function TFDPhysCommand.GetName: TComponentName;
begin
Result := FMoniAdapterHelper.Name;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetParent: IFDStanObject;
begin
Result := FMoniAdapterHelper.Parent;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
FMoniAdapterHelper.SetOwner(AOwner, ARole);
{$IFDEF FireDAC_MONITOR}
FMoniAdapterHelper.UnRegisterClient;
FMoniAdapterHelper.RegisterClient(FConnectionObj.GetMonitor);
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.AfterReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.BeforeReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
// IFDMoniAdapter
function TFDPhysCommand.GetHandle: LongWord;
begin
if FMoniAdapterHelper = nil then
Result := 0
else
Result := FMoniAdapterHelper.Handle;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetSupportItems: TFDMoniAdapterItemKinds;
begin
Result := [ikStat, ikSQL, ikParam];
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommand.GetItemCount: Integer;
begin
Result := 5 + GetParams.Count + GetMacros.Count;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommand.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
const
C_States: array [TFDPhysCommandState] of String = ('Inactive', 'Prepared',
'Executing', 'Open', 'Fetching', 'Aborting');
var
oPar: TFDParam;
oMac: TFDMacro;
begin
case AIndex of
0:
begin
AName := 'ExecuteCount';
AValue := FExecuteCount;
AKind := ikStat;
end;
1:
begin
AName := 'RowsAffected';
AValue := FRowsAffected;
AKind := ikStat;
end;
2:
begin
AName := 'RecordsFetched';
AValue := FRecordsFetched;
AKind := ikStat;
end;
3:
begin
AName := 'Status';
AValue := C_States[GetState];
if (GetState = csOpen) and FEof then
AValue := AValue + ', Eof';
AKind := ikStat;
end;
4:
begin
AName := '@CommandText';
AValue := GetTraceCommandText;
AKind := ikSQL;
end;
else
if AIndex - 5 < GetParams.Count then begin
oPar := GetParams[AIndex - 5];
AName := oPar.Name;
if oPar.ArrayType <> atScalar then
AValue := '<array>'
else
AValue := oPar.Value;
AKind := ikParam;
end
else begin
oMac := GetMacros[AIndex - 5 - GetParams.Count];
AName := oMac.Name;
AValue := oMac.Value;
AKind := ikParam;
end;
end;
end;
{-------------------------------------------------------------------------------}
{$IFDEF FireDAC_MONITOR}
procedure TFDPhysCommand.UpdateMonitor;
begin
if FConnection.Tracing then
FConnection.Monitor.AdapterChanged(Self);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
initialization
TFDSingletonFactory.Create(TFDPhysManager, IFDPhysManager);
oFact := TFDPhysConnectionDefParamsFactory.Create;
finalization
FDReleaseFactory(oFact);
end.
|
unit rhlSHA256Base;
interface
uses
rhlCore, sysutils;
type
{ TrhlSHA256Base }
TrhlSHA256Base = class abstract(TrhlHash)
private
const s_K: array[0..63] of DWord = (
$428a2f98, $71374491, $b5c0fbcf, $e9b5dba5, $3956c25b, $59f111f1, $923f82a4, $ab1c5ed5,
$d807aa98, $12835b01, $243185be, $550c7dc3, $72be5d74, $80deb1fe, $9bdc06a7, $c19bf174,
$e49b69c1, $efbe4786, $0fc19dc6, $240ca1cc, $2de92c6f, $4a7484aa, $5cb0a9dc, $76f988da,
$983e5152, $a831c66d, $b00327c8, $bf597fc7, $c6e00bf3, $d5a79147, $06ca6351, $14292967,
$27b70a85, $2e1b2138, $4d2c6dfc, $53380d13, $650a7354, $766a0abb, $81c2c92e, $92722c85,
$a2bfe8a1, $a81a664b, $c24b8b70, $c76c51a3, $d192e819, $d6990624, $f40e3585, $106aa070,
$19a4c116, $1e376c08, $2748774c, $34b0bcb5, $391c0cb3, $4ed8aa4a, $5b9cca4f, $682e6ff3,
$748f82ee, $78a5636f, $84c87814, $8cc70208, $90befffa, $a4506ceb, $bef9a3f7, $c67178f2);
protected
m_state: array[0..7] of DWord;
procedure UpdateBlock(const AData); override;
public
constructor Create; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlSHA256Base }
procedure TrhlSHA256Base.UpdateBlock(const AData);
var
A, B, C, D, E, F, G, H, T, T2: DWord;
data: array[0..63] of DWord;
r: Integer;
begin
ConvertBytesToDWordsSwapOrder(AData, BlockSize, data);
A := m_state[0];
B := m_state[1];
C := m_state[2];
D := m_state[3];
E := m_state[4];
F := m_state[5];
G := m_state[6];
H := m_state[7];
for r := 16 to 63 do
begin
T := data[r - 2];
T2 := data[r - 15];
data[r] := (((T shr 17) or (T shl 15)) xor ((T shr 19) or (T shl 13)) xor (T shr 10)) + data[r - 7] +
(((T2 shr 7) or (T2 shl 25)) xor ((T2 shr 18) or (T2 shl 14)) xor (T2 shr 3)) + data[r - 16];
end;
for r := 0 to 63 do
begin
T := s_K[r] + data[r] + H + (((E shr 6) or (E shl 26)) xor ((E shr 11) or (E shl 21)) xor ((E shr 25) or
(E shl 7))) + ((E and F) xor (not E and G));
T2 := (((A shr 2) or (A shl 30)) xor ((A shr 13) or (A shl 19)) xor
((A shr 22) or (A shl 10))) + ((A and B) xor (A and C) xor (B and C));
H := G;
G := F;
F := E;
E := D + T;
D := C;
C := B;
B := A;
A := T + T2;
end;
Inc(m_state[0], A);
Inc(m_state[1], B);
Inc(m_state[2], C);
Inc(m_state[3], D);
Inc(m_state[4], E);
Inc(m_state[5], F);
Inc(m_state[6], G);
Inc(m_state[7], H);
end;
constructor TrhlSHA256Base.Create;
begin
BlockSize := 64;
end;
procedure TrhlSHA256Base.Final(var ADigest);
var
bits: QWord;
pad: TBytes;
padIndex: QWord;
begin
bits := QWord(FProcessedBytes) * 8;
if FBuffer.Pos < 56 then
padIndex := 56 - FBuffer.Pos
else
padIndex := 120 - FBuffer.Pos;
SetLength(pad, padIndex + 8);
FillChar(pad[0], Length(pad), 0);
pad[0] := $80;
bits := SwapEndian(bits);
Move(bits, pad[padIndex], SizeOf(bits));
Inc(padIndex, 8);
UpdateBytes(pad[0], padIndex);
ConvertDWordsToBytesSwapOrder(m_state, HashSize div SizeOf(DWord), ADigest);
end;
end.
|
{ *************************************************************************** }
{ }
{ Kylix and Delphi Cross-Platform Visual Component Library }
{ Internet Application Runtime }
{ }
{ Copyright (C) 1997, 2001 Borland Software Corporation }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
{ Need denypackage unit because of threadvar }
{$DENYPACKAGEUNIT}
unit WebReq;
interface
uses SyncObjs, SysUtils, Classes, HTTPApp, Contnrs, WebCntxt;
type
TRequestNotification = (rnActivateModule, rnDeactivateModule, rnCreateModule, rnFreeModule,
rnStartRequest, rnFinishRequest);
TWebModuleList = class;
TWebModuleFactoryList = class(TObject)
private
FAppModuleFactory: TAbstractWebModuleFactory;
FList: TObjectList;
function GetItemCount: Integer;
protected
function GetItem(I: Integer): TAbstractWebModuleFactory;
public
constructor Create;
destructor Destroy; override;
procedure AddFactory(AFactory: TAbstractWebModuleFactory);
property AppModuleFactory: TAbstractWebModuleFactory read FAppModuleFactory;
property Items[I: Integer]: TAbstractWebModuleFactory read GetItem;
property ItemCount: Integer read GetItemCount;
end;
TWebRequestHandler = class(TComponent)
private
FCriticalSection: TCriticalSection;
FActiveWebModules: TList;
FAddingActiveModules: Integer;
FInactiveWebModules: TList;
FMaxConnections: Integer;
FCacheConnections: Boolean;
FWebModuleFactories: TWebModuleFactoryList;
FWebModuleClass: TComponentClass;
FRequestNotifies: TComponentList;
function GetActiveCount: Integer;
function GetInactiveCount: Integer;
procedure SetCacheConnections(Value: Boolean);
function GetWebModuleFactory(I: Integer): TAbstractWebModuleFactory;
function GetWebModuleFactoryCount: Integer;
protected
function ActivateWebModules: TWebModuleList;
procedure DeactivateWebModules(WebModules: TWebModuleList);
function HandleRequest(Request: TWebRequest; Response: TWebResponse): Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure HandleException(Sender: TObject);
property WebModuleClass: TComponentClass read FWebModuleClass write FWebModuleClass;
procedure AddWebModuleFactory(AFactory: TAbstractWebModuleFactory);
property ActiveCount: Integer read GetActiveCount;
property CacheConnections: Boolean read FCacheConnections write SetCacheConnections;
property InactiveCount: Integer read GetInactiveCount;
property MaxConnections: Integer read FMaxConnections write FMaxConnections;
property WebModuleFactoryCount: Integer read GetWebModuleFactoryCount;
property WebModuleFactory[I: Integer]: TAbstractWebModuleFactory read GetWebModuleFactory;
end;
TWebModuleList = class(TAbstractWebModuleList)
private
FFactories: TWebModuleFactoryList;
FList: TComponentList;
FFixupLevel: Integer;
FSaveIsUniqueGlobalComponentName: TIsUniqueGlobalComponentName;
FUnresolvedNames: TStrings;
FModuleAddedProc: TModuleAddedProc;
procedure EndFixup;
procedure StartFixup;
procedure RecordUnresolvedName(const AName: string);
procedure PromoteFactoryClass(const AName: string);
protected
function GetItem(I: Integer): TComponent; override;
function GetItemCount: Integer; override;
function GetOnModuleAdded: TModuleAddedProc; override;
function GetFactoryCount: Integer; override;
function GetFactory(I: Integer): TAbstractWebModuleFactory; override;
procedure SetOnModuleAdded(AProc: TModuleAddedProc); override;
property Factories: TWebModuleFactoryList read FFactories;
public
constructor Create(const AFactories: TWebModuleFactoryList);
destructor Destroy; override;
function FindModuleClass(AClass: TComponentClass): TComponent; override;
function FindModuleName(const AName: string): TComponent; override;
function AddModuleClass(AClass: TComponentClass): TComponent; override;
function AddModuleName(const AName: string): TComponent; override;
procedure AddModule(AComponent: TComponent);
procedure AutoCreateModules;
procedure AutoDestroyModules;
end;
function WebRequestHandler: TWebRequestHandler;
var
WebRequestHandlerProc: function: TWebRequestHandler = nil;
implementation
{$IFDEF MSWINDOWS}
uses Windows, BrkrConst, WebConst;
{$ENDIF}
{$IFDEF LINUX}
uses BrkrConst, WebComp, WebConst;
{$ENDIF}
threadvar WebContext: TAbstractWebContext;
type
TDefaultWebModuleFactory = class(TAbstractWebModuleFactory)
private
FComponentClass: TComponentClass;
protected
procedure PreventDestruction; override;
function GetModuleName: string; override;
function GetIsAppModule: Boolean; override;
function GetCreateMode: TWebModuleCreateMode; override;
function GetCacheMode: TWebModuleCacheMode; override;
function GetComponentClass: TComponentClass; override;
public
constructor Create(AComponentClass: TComponentClass);
function GetModule: TComponent; override;
end;
{ TDefaultWebModuleFactory }
constructor TDefaultWebModuleFactory.Create(AComponentClass: TComponentClass);
begin
inherited Create;
FComponentClass := AComponentClass;
end;
function TDefaultWebModuleFactory.GetCacheMode: TWebModuleCacheMode;
begin
Result := caCache;
end;
function TDefaultWebModuleFactory.GetComponentClass: TComponentClass;
begin
Result := FComponentClass;
end;
function TDefaultWebModuleFactory.GetCreateMode: TWebModuleCreateMode;
begin
Result := crAlways
end;
function TDefaultWebModuleFactory.GetIsAppModule: Boolean;
begin
Result := True;
end;
function TDefaultWebModuleFactory.GetModule: TComponent;
begin
Result := FComponentClass.Create(nil);
end;
function TDefaultWebModuleFactory.GetModuleName: string;
begin
Result := Copy(FComponentClass.ClassName, 2, MaxInt);
end;
function GetWebContext: TAbstractWebContext;
begin
Result := WebContext;
end;
procedure SetWebContext(AWebContext: TAbstractWebContext);
begin
WebContext := AWebContext;
end;
function WebRequestHandler: TWebRequestHandler;
begin
if Assigned(WebRequestHandlerProc) then
Result := WebRequestHandlerProc
else
Result := nil;
end;
procedure TDefaultWebModuleFactory.PreventDestruction;
begin
// Do nothing. Cache mode is always caCache
end;
{ TWebRequestHandler }
constructor TWebRequestHandler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCriticalSection := TCriticalSection.Create;
FActiveWebModules := TList.Create;
FInactiveWebModules := TList.Create;
FWebModuleFactories := TWebModuleFactoryList.Create;
FMaxConnections := 32;
FCacheConnections := True;
end;
destructor TWebRequestHandler.Destroy;
begin
FCriticalSection.Free;
FActiveWebModules.Free;
FInactiveWebModules.Free;
FRequestNotifies.Free;
FWebModuleFactories.Free;
inherited Destroy;
end;
threadvar AvailableWebModules: TWebModuleList;
function FindWebModuleComponent(const Name: string): TComponent;
begin
if AvailableWebModules <> nil then
begin
// Global components references are supported by SiteExpress
Result := AvailableWebModules.FindModuleName(Name);
if Result = nil then
AvailableWebModules.RecordUnresolvedName(Name);
end
else
// Global component references are not supported by standard WebBroker
Result := nil;
end;
function IsUniqueGlobalWebComponentName(const Name: string): Boolean;
begin
// Prevent rename of data modules
Result := True;
end;
function TWebRequestHandler.ActivateWebModules: TWebModuleList;
begin
if (FMaxConnections > 0) and (FAddingActiveModules >= FMaxConnections) then
raise Exception.CreateRes(@sTooManyActiveConnections);
FCriticalSection.Enter;
try
FAddingActiveModules := FActiveWebModules.Count + 1;
try
Result := nil;
if (FMaxConnections > 0) and (FActiveWebModules.Count >= FMaxConnections) then
raise Exception.CreateRes(@sTooManyActiveConnections);
if FInactiveWebModules.Count > 0 then
begin
Result := FInactiveWebModules[0];
Result.OnModuleAdded := nil;
FInactiveWebModules.Delete(0);
FActiveWebModules.Add(Result);
end
else
begin
if FWebModuleFactories.ItemCount = 0 then
if WebModuleClass <> nil then
FWebModuleFactories.AddFactory(TDefaultWebModuleFactory.Create(WebModuleClass));
if FWebModuleFactories.ItemCount > 0 then
begin
Result := TWebModuleList.Create(FWebModuleFactories);
FActiveWebModules.Add(Result);
end
else
raise Exception.CreateRes(@sNoDataModulesRegistered);
end;
finally
FAddingActiveModules := 0;
end;
finally
FCriticalSection.Leave;
end;
Result.AutoCreateModules;
end;
procedure TWebRequestHandler.DeactivateWebModules(WebModules: TWebModuleList);
begin
FCriticalSection.Enter;
try
FActiveWebModules.Remove(WebModules);
WebModules.AutoDestroyModules;
if FCacheConnections and (WebModules.GetItemCount > 0) then
FInactiveWebModules.Add(WebModules)
else
begin
WebModules.Free;
end;
finally
FCriticalSection.Leave;
end;
end;
function TWebRequestHandler.GetActiveCount: Integer;
begin
FCriticalSection.Enter;
try
Result := FActiveWebModules.Count;
finally
FCriticalSection.Leave;
end;
end;
function TWebRequestHandler.GetInactiveCount: Integer;
begin
FCriticalSection.Enter;
try
Result := FInactiveWebModules.Count;
finally
FCriticalSection.Leave;
end;
end;
function TWebRequestHandler.HandleRequest(Request: TWebRequest;
Response: TWebResponse): Boolean;
var
I: Integer;
WebModules: TWebModuleList;
WebModule: TComponent;
WebAppServices: IWebAppServices;
GetWebAppServices: IGetWebAppServices;
begin
Result := False;
WebModules := ActivateWebModules;
if Assigned(WebModules) then
try
if WebModules.ItemCount = 0 then
raise Exception.CreateRes(@sNoWebModulesActivated);
try
// Look at modules for a web application
for I := 0 to WebModules.ItemCount - 1 do
begin
WebModule := WebModules[I];
if Supports(IInterface(WebModule), IGetWebAppServices, GetWebAppServices) then
WebAppServices := GetWebAppServices.GetWebAppServices;
if WebAppServices <> nil then break;
end;
if WebAppServices = nil then
WebAppServices := TDefaultWebAppServices.Create(nil);
WebAppServices.InitContext(WebModules, Request, Response);
try
try
Result := WebAppServices.HandleRequest;
except
ApplicationHandleException(WebAppServices.ExceptionHandler);
end;
finally
WebAppServices.FinishContext;
end;
if Result and not Response.Sent then
Response.SendResponse;
except
ApplicationHandleException(nil);
end;
finally
DeactivateWebModules(WebModules);
end;
end;
procedure TWebRequestHandler.SetCacheConnections(Value: Boolean);
var
I: Integer;
begin
if Value <> FCacheConnections then
begin
FCacheConnections := Value;
if not Value then
begin
FCriticalSection.Enter;
try
for I := 0 to FInactiveWebModules.Count - 1 do
TComponent(FInactiveWebModules[I]).Free;
FInactiveWebModules.Clear;
finally
FCriticalSection.Leave;
end;
end;
end;
end;
procedure TWebRequestHandler.AddWebModuleFactory(
AFactory: TAbstractWebModuleFactory);
begin
if Assigned(FWebModuleFactories) then
FWebModuleFactories.AddFactory(AFactory);
end;
function TWebRequestHandler.GetWebModuleFactory(
I: Integer): TAbstractWebModuleFactory;
begin
if Assigned(FWebModuleFactories) then
Result := FWebModuleFactories.Items[I]
else
Result := nil;
end;
function TWebRequestHandler.GetWebModuleFactoryCount: Integer;
begin
if Assigned(FWebModuleFactories) then
Result := FWebModuleFactories.ItemCount
else
Result := 0;
end;
procedure TWebRequestHandler.HandleException(Sender: TObject);
var
Handled: Boolean;
Intf: IWebExceptionHandler;
begin
Handled := False;
if (ExceptObject is Exception) and
not (ExceptObject is EAbort) and
Supports(Sender, IWebExceptionHandler, Intf) then
Intf.HandleException(Exception(ExceptObject), Handled);
if not Handled then
SysUtils.ShowException(ExceptObject, ExceptAddr);
end;
{ TWebModuleList }
constructor TWebModuleList.Create(const AFactories: TWebModuleFactoryList);
begin
inherited Create;
FUnresolvedNames := TStringList.Create;
FList := TComponentList.Create;
FFactories := AFactories;
end;
destructor TWebModuleList.Destroy;
begin
inherited;
FList.Free;
FUnresolvedNames.Free;
end;
function TWebModuleList.GetItem(I: Integer): TComponent;
begin
Result := FList[I];
end;
function TWebModuleList.GetItemCount: Integer;
begin
Result := FList.Count;
end;
function TWebModuleList.AddModuleClass(
AClass: TComponentClass): TComponent;
var
I: Integer;
Factory: TAbstractWebModuleFactory;
begin
Result := nil;
Assert(FindModuleClass(AClass) = nil);
for I := 0 to Factories.ItemCount - 1 do
begin
Factory := Factories.Items[I];
if AClass = Factory.ComponentClass then
begin
StartFixup;
try
Result := Factory.GetModule;
AddModule(Result);
finally
EndFixup;
end;
end;
end;
end;
function TWebModuleList.AddModuleName(const AName: string): TComponent;
var
I: Integer;
Factory: TAbstractWebModuleFactory;
begin
Result := nil;
Assert(FindModuleName(AName) = nil);
for I := 0 to Factories.ItemCount - 1 do
begin
Factory := Factories.Items[I];
if CompareText(AName, Factory.ModuleName) = 0 then
begin
StartFixup;
try
Result := Factory.GetModule;
AddModule(Result);
break;
finally
EndFixup;
end;
end;
end;
end;
function TWebModuleList.FindModuleClass(
AClass: TComponentClass): TComponent;
var
I: Integer;
begin
for I := 0 to ItemCount - 1 do
begin
Result := Items[I];
if Result.ClassType = AClass then
Exit;
end;
Result := nil;
end;
function TWebModuleList.FindModuleName(const AName: string): TComponent;
var
I: Integer;
begin
for I := 0 to ItemCount - 1 do
begin
Result := Items[I];
if CompareText(Result.Name, AName) = 0 then
Exit;
end;
Result := nil;
end;
procedure TWebModuleList.AddModule(AComponent: TComponent);
begin
Assert(FFixupLevel >= 1, 'Module created outside of fixup block'); { Do not localize }
FList.Add(AComponent);
if Assigned(FModuleAddedProc) then
FModuleAddedProc(AComponent);
end;
procedure TWebModuleList.StartFixup;
begin
Inc(FFixupLevel);
if FFixupLevel = 1 then
begin
AvailableWebModules := Self;
FSaveIsUniqueGlobalComponentName := Classes.IsUniqueGlobalComponentNameProc;
Classes.RegisterFindGlobalComponentProc(FindWebModuleComponent);
Classes.IsUniqueGlobalComponentNameProc := IsUniqueGlobalWebComponentName;
end;
end;
procedure TWebModuleList.EndFixup;
var
Name: string;
begin
Dec(FFixupLevel);
try
if FFixupLevel = 0 then
while FUnresolvedNames.Count > 0 do
begin
Name := FUnresolvedNames[0];
FUnresolvedNames.Delete(0);
if (FindModuleName(Name) <> nil) or (AddModuleName(Name) <> nil) then
begin
PromoteFactoryClass(Name);
GlobalFixupReferences;
end
end;
finally
if FFixupLevel = 0 then
begin
AvailableWebModules := nil;
// Once set, the hooks stay in place for this application
//Classes.UnregisterFindGlobalComponentProc(FindWebModuleComponent);
//Classes.IsUniqueGlobalComponentNameProc := FSaveIsUniqueGlobalComponentName;
end;
end;
end;
procedure TWebModuleList.AutoCreateModules;
var
I: Integer;
Factory: TAbstractWebModuleFactory;
begin
StartFixup;
try
for I := 0 to Factories.ItemCount - 1 do
begin
Factory := Factories.Items[I];
if Factory.CreateMode = crAlways then
if FindModuleClass(Factory.ComponentClass) = nil then
AddModule(Factory.GetModule);
end;
finally
EndFixup;
end;
end;
procedure TWebModuleList.AutoDestroyModules;
var
I: Integer;
Factory: TAbstractWebModuleFactory;
Component: TComponent;
begin
for I := 0 to Factories.ItemCount - 1 do
begin
Factory := Factories.Items[I];
if Factory.CacheMode = caDestroy then
begin
Component := FindModuleClass(Factory.ComponentClass);
if Assigned(Component) then
Component.Free;
end;
end;
end;
procedure TWebModuleList.RecordUnresolvedName(const AName: string);
begin
if FUnresolvedNames.IndexOf(AName) < 0 then
FUnresolvedNames.Add(AName);
end;
function TWebModuleList.GetOnModuleAdded: TModuleAddedProc;
begin
Result := FModuleAddedProc;
end;
procedure TWebModuleList.SetOnModuleAdded(AProc: TModuleAddedProc);
begin
FModuleAddedProc := AProc;
end;
// Prevent modules referenced by other modules from being destroyed
procedure TWebModuleList.PromoteFactoryClass(const AName: string);
var
I: Integer;
Factory: TAbstractWebModuleFactory;
begin
for I := 0 to Factories.ItemCount - 1 do
begin
Factory := Factories.Items[I];
if CompareText(AName, Factory.ModuleName) = 0 then
begin
if Factory.CacheMode = caDestroy then
Factory.PreventDestruction;
end;
end;
end;
function TWebModuleList.GetFactory(I: Integer): TAbstractWebModuleFactory;
begin
Result := Factories.Items[I];
end;
function TWebModuleList.GetFactoryCount: Integer;
begin
Result := Factories.ItemCount;
end;
{ TWebModuleFactoryList }
procedure TWebModuleFactoryList.AddFactory(AFactory: TAbstractWebModuleFactory);
begin
if FList.IndexOf(AFactory) <> -1 then
raise Exception.Create(sFactoryAlreadyRegistered);
if AFactory.IsAppModule then
begin
if Self.AppModuleFactory <> nil then
raise Exception.Create(sAppFactoryAlreadyRegistered);
Self.FAppModuleFactory := AFactory;
end;
FList.Add(AFactory);
end;
constructor TWebModuleFactoryList.Create;
begin
FList := TObjectList.Create;
end;
destructor TWebModuleFactoryList.Destroy;
begin
inherited;
FList.Free;
end;
function TWebModuleFactoryList.GetItem(
I: Integer): TAbstractWebModuleFactory;
begin
Result := TAbstractWebModuleFactory(FList[I]);
end;
function TWebModuleFactoryList.GetItemCount: Integer;
begin
Result := FList.Count;
end;
function ImplGetModuleFileName: string;
var
ModuleName: array[0..255] of Char;
begin
{$IFDEF MSWINDOWS}
GetModuleFileName(hinstance, ModuleName, sizeof(ModuleName));
{$ENDIF}
{$IFDEF LINUX}
GetModuleFileName(MainInstance, ModuleName, sizeof(ModuleName));
{$ENDIF}
Result := ModuleName;
end;
initialization
GetWebContextProc := GetWebContext;
SetWebContextProc := SetWebContext;
GetModuleFileNameProc := ImplGetModuleFileName;
end.
|
unit DeleteFileOnCloseUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
type
TDeleteFilesOnCloseForm = class(TForm)
DeleteFilesLabel: TLabel;
DeleteFileTimer: TTimer;
procedure FormCreate(Sender: TObject);
procedure DeleteFileTimerTimer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
DeleteFileName, DeleteFileDirectory, LabelCaption : String;
end;
var
DeleteFilesOnCloseForm: TDeleteFilesOnCloseForm;
implementation
{$R *.DFM}
{================================================}
Procedure TDeleteFilesOnCloseForm.FormCreate(Sender: TObject);
var
I, EqualsPos : Integer;
begin
For I := 1 to ParamCount do
begin
If (Pos('FILENAME', ANSIUppercase(ParamStr(I))) > 0)
then
begin
EqualsPos := Pos('=', ParamStr(I));
DeleteFileName := Copy(ParamStr(I), (EqualsPos + 1), 200);
DeleteFileName := Trim(DeleteFileName);
end; {If (Pos('FILENAME', ANSIUppercase(ParamStr(I))) > 0)}
If (Pos('FILEDIRECTORY', ANSIUppercase(ParamStr(I))) > 0)
then
begin
EqualsPos := Pos('=', ParamStr(I));
DeleteFileDirectory := Copy(ParamStr(I), (EqualsPos + 1), 200);
DeleteFileDirectory := Trim(DeleteFileDirectory);
DeleteFileDirectory := StringReplace(DeleteFileDirectory,
'"', '', [rfReplaceAll]);
end; {If (Pos('FILEDIRECTORY', ANSIUppercase(ParamStr(I))) > 0)}
If (Pos('LABEL', ANSIUppercase(ParamStr(I))) > 0)
then
begin
EqualsPos := Pos('=', ParamStr(I));
LabelCaption := Copy(ParamStr(I), (EqualsPos + 1), 200);
DeleteFilesLabel.Caption := Trim(LabelCaption);
end; {If (Pos('LABEL', ANSIUppercase(ParamStr(I))) > 0)}
end; {For I := 1 to ParamCount do}
DeleteFileTimer.Enabled := True;
end; {FormCreate}
{================================================}
Procedure TDeleteFilesOnCloseForm.DeleteFileTimerTimer(Sender: TObject);
var
Return : Integer;
Done, FirstTimeThrough : Boolean;
SearchRec : TSearchRec;
begin
DeleteFileTimer.Enabled := False;
Done := False;
Return := 0;
FirstTimeThrough := True;
FindFirst(DeleteFileDirectory + DeleteFileName + '.*', faAnyFile, SearchRec);
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else Return := FindNext(SearchRec);
If (Return <> 0)
then Done := True;
If ((not Done) and
(SearchRec.Name <> '.') and
(SearchRec.Name <> '..'))
then
try
DeleteFile(DeleteFileDirectory + SearchRec.Name);
except
end;
until Done;
Close;
end; {DeleteFileTimerTimer}
end.
|
{**********************************************************}
{ }
{ This unit is a sample of custom encryption algothrim. }
{ As a sample, the algorithm is very simple . }
{ }
{**********************************************************}
unit MyEncAlgo;
interface
uses
Classes, Windows, SysUtils, TinyDB;
type
//TMyEncAlgo must derive from class TEncryptAlgo.
TMyEncAlgo = class(TEncryptAlgo)
private
FKey: string;
procedure XorBuffer(const Source; var Dest; DataSize: Integer);
public
procedure InitKey(const Key: string); override;
procedure EncodeBuffer(const Source; var Dest; DataSize: Integer); override;
procedure DecodeBuffer(const Source; var Dest; DataSize: Integer); override;
end;
implementation
//-----------------------------------------------------------------------------
//Init password
//-----------------------------------------------------------------------------
procedure TMyEncAlgo.InitKey(const Key: string);
begin
//Hash original key, and assign result to FKey.
//NOTE: HashSHA is a routine in TinyDatabase, it used SHA algorithm.
FKey := HashSHA(Key);
end;
//-----------------------------------------------------------------------------
//Use XOR to encode & decode the buffer.
//This algorithm is very simple.
//-----------------------------------------------------------------------------
procedure TMyEncAlgo.XorBuffer(const Source; var Dest; DataSize: Integer);
var
I, J, KeyLen: Integer;
Ptr: PChar;
begin
Move(Source, Dest, DataSize);
Ptr := PChar(@Dest);
KeyLen := Length(FKey);
J := 1;
for I := 0 to DataSize - 1 do
begin
Ptr[I] := Chr(Ord(Ptr[I]) xor Ord(FKey[J]));
Inc(J);
if J > KeyLen then J := 1;
end;
end;
//-----------------------------------------------------------------------------
//Encrypt the buffer.
//THE PROCEDURE MUST BE OVERRIDED!
//Parameters:
// Source -- Source buffer
// Dest -- Destination buffer
// DataSize -- The size of buffer will be encrypted
//-----------------------------------------------------------------------------
procedure TMyEncAlgo.EncodeBuffer(const Source; var Dest; DataSize: Integer);
begin
XorBuffer(Source, Dest, DataSize);
end;
//-----------------------------------------------------------------------------
//Decrypt the buffer.
//THE PROCEDURE MUST BE OVERRIDED!
//Parameters:
// Source -- Source buffer
// Dest -- Destination buffer
// DataSize -- The size of buffer will be decrypted
//-----------------------------------------------------------------------------
procedure TMyEncAlgo.DecodeBuffer(const Source; var Dest; DataSize: Integer);
begin
XorBuffer(Source, Dest, DataSize);
end;
//-----------------------------------------------------------------------------
//At last, register the encryption algorithm class!
//
//procedure RegisterEncryptClass(AClass: TEncryptAlgoClass; AlgoName: string);
//Parameters:
// AClass -- The encryption algorithm class
// AlgoName -- Give a nickname for this encryption algorithm
//-----------------------------------------------------------------------------
initialization
RegisterEncryptClass(TMyEncAlgo, 'MyEncAlgo');
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.Bindings.Expression;
interface
uses
System.SysUtils, System.Classes, System.Rtti, System.Generics.Collections,
System.Bindings.EvalProtocol, System.Bindings.EvalSys, System.Bindings.Outputs;
type
/// <summary>Thrown when errors occur in the behaviour of a binding expression.</summary>
EBindingExpressionError = class(Exception);
/// <summary>
/// Stores an association between a Delphi object and a expression object. </summary>
TBindingAssociation = record
public
/// <summary>The Delphi object in the association.</summary>
RealObject: TObject;
/// <summary>The expression object in the association </summary>
ScriptObject: String;
/// <summary>Constructs the association using the given Delphi and expression objects.</summary>
/// <param name="ARealObject">The Delphi object of the association.</param>
/// <param name="AScriptObject">The expression object of the association.</param>
constructor Create(ARealObject: TObject; const AScriptObject: String);
end;
/// <summary>
/// Stores an association between an Interface and an expression object.</summary>
TBidiAssociation = record
public
/// <summary>The interface reference that is part of the association.</summary>
BidiInterface: IInterface;
/// <summary>The expression object that is part of the association.</summary>
BidiName: string;
/// <summary>Constructs the association using the given interface reference and
/// the given expression object.</summary>
/// <param name="ABidiInterface">The interface reference of the association.</param>
/// <param name="ABidiName">The expression object of the association.</param>
constructor Create(ABidiInterface: IInterface; const ABidiName: string);
end;
/// <summary>
/// Every expression parsed and evaluated must descend from this class.</summary>
TBindingExpression = class abstract(TObject)
public
type
TAssociationPair = TPair<TObject, String>;
TAssociations = TDictionary<TObject, String>;
private
FSource: String;
FAssociations: TAssociations;
FBindingOutput: TBindingOutput;
FOutputValue: TValue;
FEvalErrorEvent: TBindingEvalErrorEvent;
protected
/// <summary>Scopes that are chained up and used by the compiler to search
/// for global symbols used in the expression. These scopes are set by
/// the Compile methods that use scopes among their input parameters.</summary>
FScopes: Array of IScope;
function GetCompiled: Boolean; virtual; abstract;
function GetSource: String; virtual;
procedure SetSource(const Value: String); virtual;
function GetOutputValue: TValue; virtual;
procedure SetOutputValue(const Value: TValue); virtual;
procedure SetOutputs(const ValueFunc: TBindOutValueFunc); virtual;
/// <summary>Realizes the actual compilation of the expression based on the
/// script and real objects Associations</summary>
procedure Compile; overload; virtual; abstract;
function GetIsManaged: Boolean; virtual; abstract;
function GetAssigningValueEvent: TBindingAssigningValueEvent;
procedure SetAssigningValueEvent(AssigningValueEvent: TBindingAssigningValueEvent);
function GetAssignedValueEvent: TBindingAssignedValueEvent;
procedure SetAssignedValueEvent(AssignedValueEvent: TBindingAssignedValueEvent);
procedure SetEvalErrorEvent(EvalErrorEvent: TBindingEvalErrorEvent);
public
/// <summary>Creates an instance of a binding expression.</summary>
constructor Create;
/// <summary>Destroyes an instance of a binding expression.</summary>
destructor Destroy; override;
/// <summary>Compiles an expression and makes the relationship between
/// the Delphi components and the expression objects based on the component names.
/// There cannot be two components with the same name, nor with empty names.</summary>
/// <param name="Objects">These components and their properties are used in the expression.
/// The names of the components must match those of the expression objects.</param>
procedure Compile(const Objects: array of TComponent); overload;
/// <summary>Compiles the expression based on the associations between
/// Delphi objects and expression objects.</summary>
/// <param name="Assocs">An array of associations between Delphi objects and
/// the corresponding expression objects used in the source of the expression.</param>
procedure Compile(const Assocs: array of TBindingAssociation); overload;
/// <summary>Compiles the expression based on the provided IScope.</summary>
/// <param name="AScope">The scope used by the compiler and the evaluator
/// to resolve the object names and to determine their values.</param>
procedure Compile(const AScope: IScope); overload;
/// <summary>Compiles the expression based on the provided array of scopes.</summary>
/// <param name="AScopes">The array of scopes used by the compiler and the
/// evaluator to resolve object names and to determine their actual values.</param>
procedure Compile(const AScopes: array of IScope); overload;
/// <summary>Compiles the expression using all the parameters to determine
/// the relationships between Delphi objects and the expression objects. This
/// version of the method gives the user the possibility to specifiy associations
/// between Delphi objects and expression objects by all means possible.
/// The compiler will use information in all the parameters.</summary>
/// <param name="Objects">These components and their properties are used in the expression.
/// The names of the components must match those of the expression objects.</param>
/// <param name="Assocs">An array of associations between Delphi objects and
/// the corresponding expression objects used in the source of the expression.</param>
/// <param name="Scopes">The array of scopes used by the compiler and the
/// evaluator to resolve object names and to determine their actual values.</param>
procedure Compile(const Objects: array of TComponent; const Assocs: array of TBindingAssociation; const Scopes: array of IScope); overload;
/// <summary>Recompiles the expression using the last binding associations
/// between the Delphi objects and the expression objects.</summary>
procedure Recompile; inline;
/// <summary>Evaluates the expression and returns value</summary>
/// <returns>A value wrapper that wraps the actual calculated value. The value
/// wrapper may also be a location, which means that the wrapper supports
/// to change the resulting value within the wrapper.</returns>
function Evaluate: IValue; virtual; abstract;
/// <summary>Assigns the expression value to outputs</summary>
/// <returns>A value wrapper that wraps the actual calculated value. The value
/// wrapper may also be a location, which means that the wrapper supports
/// to change the resulting value within the wrapper.</returns>
procedure EvaluateOutputs; virtual; abstract;
/// <summary>Clears the current compilation data.</summary>
procedure Clear; virtual;
/// <summary>The source code of the expression.</summary>
property Source: String read GetSource write SetSource;
/// <summary>Indicates whether the expression has been compiled. An expression
/// cannot be evaluated if it hasn't been compiled. </summary>
property Compiled: Boolean read GetCompiled;
/// <summary>Container for the outputs that receive the value resulting from
/// the expression evaluation.</summary>
property Outputs: TBindingOutput read FBindingOutput;
/// <summary>Sets and gets the computed output value</summary>
property OutputValue: TValue read GetOutputValue write SetOutputValue;
/// <summary>Denotes the current associations between the Delphi objects and
/// the expression objects used by the expression to recompile or evaluate.
/// Here you put the input objects/properties for the expression.</summary>
property Associations: TAssociations read FAssociations;
/// <summary>Indicates whether the expression is managed. Managed expressions are associated with
/// a TBindingManager and participate in the notification system.</summary>
property IsManaged: Boolean read GetIsManaged;
/// <summary>Issued when an output has a new value assigned to it as a result of
/// the evaluation of the expression</summary>
property OnAssigningValueEvent: TBindingAssigningValueEvent read GetAssigningValueEvent write SetAssigningValueEvent;
/// <summary>Event called whenever an evaluation error occurs.</summary>
property OnEvalErrorEvent: TBindingEvalErrorEvent read FEvalErrorEvent write SetEvalErrorEvent;
property OnAssignedValueEvent: TBindingAssignedValueEvent read GetAssignedValueEvent write SetAssignedValueEvent;
end;
/// <summary>
/// Facilitates grouping and naming binding expressions. The group has a name
/// itself. Each binding expression object stored in the group can be identified
/// using its assigned name.</summary>
TBindExprDict = class
private
FName: string;
FPersistBindings: Boolean;
FExpressions: TObjectDictionary<string,TBindingExpression>;
function GetValues: TDictionary<string,TBindingExpression>.TValueCollection;
public
/// <summary>Adds a binding expression along with its name to the group.</summary>
/// <param name="ExpressionStr">Specifies the name of the binding expression.</param>
/// <param name="BindingExpression">Identifies the binding expression object.</param>
procedure Add(const ExpressionStr: string; BindingExpression: TBindingExpression);
/// <summary>Permits manipulation of the stored binding expression objects.</summary>
property Expressions: TObjectDictionary<string,TBindingExpression> read FExpressions;
/// <summary>Gives access to the collection containing only the binding expression objects,
/// without their associated names.</summary>
property Values: TDictionary<string,TBindingExpression>.TValueCollection read GetValues;
/// <summary>The name of the group.</summary>
property Name: string read FName;
property PersistBindings: Boolean read FPersistBindings write FPersistBindings;
/// <summary>Creates an instance of a group of binding expressions.</summary>
/// <param name="GroupName">Specifies the name of the group.</param>
constructor Create(const GroupName: string);
/// <summary>Destroys the instance of a group of binding expressions.</summary>
destructor Destroy; override;
end;
/// <summary>Provides an easier way to create associations between Delphi objects
/// and the expression objects. This is essentially a record constructor, but
/// permits shorter syntax.</summary>
/// <param name="RealObject">Denotes the Delphi object implied in the association.</param>
/// <param name="ScriptObject">Denotes the expression object implied in the association.</param>
/// <returns>The association generated from the given objects.</returns>
function Associate(RealObject: TObject; const ScriptObject: String): TBindingAssociation;
/// <summary>Provides an easier way to create associations between interface references
/// and the expression objects. This is essentially a record constructor, but
/// permits shorter syntax.</summary>
/// <param name="BidiInterface">Denotes the interface reference implied in the association.</param>
/// <param name="BidiName">Denotes the expression object implied in the association.</param>
/// <returns>The association generated from the given interface reference and expression object.</returns>
function BidiAssociate(BidiInterface: IInterface; const BidiName: string): TBidiAssociation;
implementation
uses
System.Bindings.Factories, System.Bindings.NotifierContracts;
function BidiAssociate(BidiInterface: IInterface; const BidiName: string): TBidiAssociation;
begin
Result.BidiInterface := BidiInterface;
Result.BidiName := BidiName;
end;
function Associate(RealObject: TObject; const ScriptObject: String): TBindingAssociation;
begin
Result.RealObject := RealObject;
Result.ScriptObject := ScriptObject;
end;
{ TBindingExpression }
procedure TBindingExpression.Compile(
const Assocs: array of TBindingAssociation);
var
i: Integer;
begin
Clear;
for i := Low(Assocs) to High(Assocs) do
Associations.Add(Assocs[i].RealObject, Assocs[i].ScriptObject);
Compile;
end;
procedure TBindingExpression.Compile(const Objects: array of TComponent);
var
i: Integer;
begin
Clear;
for i := Low(Objects) to High(Objects) do
Associations.Add(Objects[i], Objects[i].Name);
Compile;
end;
procedure TBindingExpression.Clear;
begin
Associations.Clear;
end;
constructor TBindingExpression.Create;
begin
inherited;
FOutputValue := TValue.Empty;
if IsManaged then
FBindingOutput := TBindingOutput.Create(Self, [opNotify])
else
FBindingOutput := TBindingOutput.Create(Self, []);
FAssociations := TAssociations.Create;
SetLength(FScopes, 0);
// FDataChangeEvent := nil;
end;
destructor TBindingExpression.Destroy;
begin
Clear;
FBindingOutput.Free;
FAssociations.Free;
inherited;
end;
procedure TBindingExpression.SetEvalErrorEvent(
EvalErrorEvent: TBindingEvalErrorEvent);
begin
FEvalErrorEvent := EvalErrorEvent;
Outputs.OnEvalErrorEvent := EvalErrorEvent;
end;
procedure TBindingExpression.SetAssigningValueEvent(
AssigningValueEvent: TBindingAssigningValueEvent);
begin
Outputs.OnAssigningValue := AssigningValueEvent;
end;
procedure TBindingExpression.SetAssignedValueEvent(
AssignedValueEvent: TBindingAssignedValueEvent);
begin
Outputs.OnAssignedValue := AssignedValueEvent;
end;
function TBindingExpression.GetAssigningValueEvent: TBindingAssigningValueEvent;
begin
Result := Outputs.OnAssigningValue;
end;
function TBindingExpression.GetAssignedValueEvent: TBindingAssignedValueEvent;
begin
Result := Outputs.OnAssignedValue;
end;
procedure TBindingExpression.SetOutputs(const ValueFunc: TBindOutValueFunc);
begin
assert(Assigned(ValueFunc));
Outputs.SetValue(Self, ValueFunc);
end;
function TBindingExpression.GetOutputValue: TValue;
begin
Result := FOutputValue;
end;
procedure TBindingExpression.SetOutputValue(const Value: TValue);
begin
FOutputValue := Value;
end;
function TBindingExpression.GetSource: String;
begin
Result := FSource;
end;
procedure TBindingExpression.Recompile;
begin
Compile;
end;
procedure TBindingExpression.SetSource(const Value: String);
begin
if FSource <> Value then
begin
FSource := Value;
//Clear; //seems to kill the usefulness of Recompile() assuming Input/Output assocaitions haven't changed
end;
end;
procedure TBindingExpression.Compile(const AScope: IScope);
begin
SetLength(FScopes, 1);
FScopes[0] := AScope;
Compile;
end;
procedure TBindingExpression.Compile(const AScopes: array of IScope);
var
I: Integer;
begin
SetLength(FScopes, Length(AScopes));
for I := Low(AScopes) to High(AScopes) do
FScopes[I] := AScopes[I];
Compile;
end;
procedure TBindingExpression.Compile(const Objects: array of TComponent;
const Assocs: array of TBindingAssociation; const Scopes: array of IScope);
var
I: Integer;
begin
Clear;
for i := Low(Assocs) to High(Assocs) do
Associations.Add(Assocs[i].RealObject, Assocs[i].ScriptObject);
for i := Low(Objects) to High(Objects) do
Associations.Add(Objects[i], Objects[i].Name);
SetLength(FScopes, Length(Scopes));
for I := Low(Scopes) to High(Scopes) do
FScopes[I] := Scopes[I];
Compile;
end;
{ TBindExprDict }
procedure TBindExprDict.Add(const ExpressionStr: string;
BindingExpression: TBindingExpression);
begin
Expressions.Add(ExpressionStr, BindingExpression);
end;
constructor TBindExprDict.Create(const GroupName: string);
begin
FExpressions := TObjectDictionary<string,TBindingExpression>.Create;
FPersistBindings := False;
FName := GroupName;
end;
destructor TBindExprDict.Destroy;
//var
// BE: TBindingExpression;
begin
// if not PersistBindings then
// for BE in Expressions.Values do
// TBindings.RemoveBinding(BE);
FExpressions.Free;
end;
function TBindExprDict.GetValues: TDictionary<string,TBindingExpression>.TValueCollection;
begin
Result := FExpressions.Values;
end;
{ TBindingAssociation }
constructor TBindingAssociation.Create(ARealObject: TObject;
const AScriptObject: String);
begin
RealObject := ARealObject;
ScriptObject := AScriptObject;
end;
{ TBidiAssociation }
constructor TBidiAssociation.Create(ABidiInterface: IInterface;
const ABidiName: string);
begin
BidiInterface := ABidiInterface;
BidiName := ABidiName;
end;
end.
|
unit Frmviews;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
StdCtrls, Forms, DBCtrls, DB, DBGrids, Buttons, DBTables, Grids, ExtCtrls;
type
TFrmViewDemo = class(TForm)
DBGrid1: TDBGrid;
DBNavigator: TDBNavigator;
Panel1: TPanel;
VaryingTableSource: TDataSource;
Panel2: TPanel;
VaryingTable: TTable;
BitBtn1: TBitBtn;
BtnShowEmployee: TSpeedButton;
BtnShowPhoneList: TSpeedButton;
procedure BtnShowEmployeeClick(Sender: TObject);
procedure BtnShowPhoneListClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ private declarations }
procedure ShowTable(ATable: string);
public
{ public declarations }
end;
var
FrmViewDemo: TFrmViewDemo;
implementation
{$R *.DFM}
procedure TFrmViewDemo.ShowTable( ATable: string );
begin
Screen.Cursor := crHourglass; { show user something's happening }
VaryingTable.DisableControls; { hide data changes from user }
VaryingTable.Active := FALSE; { close the table }
VaryingTable.TableName := ATable; { update the name }
VaryingTable.Open; { open the table }
VaryingTable.EnableControls; { paint the changes }
Screen.Cursor := crDefault; { reset the pointer }
end;
procedure TFrmViewDemo.FormShow(Sender: TObject);
begin
VaryingTable.Open;
end;
procedure TFrmViewDemo.BtnShowEmployeeClick(Sender: TObject);
begin
ShowTable('EMPLOYEE');
end;
procedure TFrmViewDemo.BtnShowPhoneListClick(Sender: TObject);
begin
ShowTable('PHONE_LIST');
end;
end.
|
(*
Name: kpuninstallfont
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 14 Sep 2006
Modified Date: 3 Feb 2015
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 14 Sep 2006 - mcdurdin - If unable to get font details, add a warning rather than exception
30 May 2007 - mcdurdin - I850 - Fix font uninstall in Vista
28 Feb 2011 - mcdurdin - I2751 - When a font is in use, a strange error can be displayed during package uninstall
03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
01 May 2014 - mcdurdin - I4181 - V9.0 - Stop using DeleteFileAlways, MOVEFILE_DELAY_UNTIL_REBOOT
03 Feb 2015 - mcdurdin - I4574 - V9.0 - If any files are read-only, they need the read-only flag removed on install
*)
unit kpuninstallfont;
interface
uses kpbase;
type
TKPUninstallFont = class(TKPBase)
procedure Execute(const src_filename: string; FIsAdmin: Boolean);
end;
implementation
uses
windows, sysutils, shellapi, shlobj, ttinfo,
utildir, utilsystem,
ErrorControlledRegistry, registrykeys, getosversion, keymanerrorcodes, Variants;
procedure TKPUninstallFont.Execute(const src_FileName: string; FIsAdmin: Boolean);
var
filename, fontnm: string;
begin
if not FIsAdmin then // I2751
begin
if not RemoveFontResource(PChar(src_FileName)) then
WarnFmt(KMN_W_UninstallFont_FontInUse, VarArrayOf([fontnm]));
end
else
begin
filename := GetFolderPath(CSIDL_FONTS) + ExtractFileName(src_filename);
try
with TTTInfo.Create(FileName, [tfNames]) do
try
fontnm := FullName;
finally
Free;
end;
except
on E:Exception do
begin
WarnFmt(KMN_W_UninstallFileNotFound, VarArrayOf([FileName]));
Exit;
end;
end;
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKey(SRegKey_NTFontList, False) and ValueExists(fontnm + ' (TrueType)') then
begin
if LowerCase(ReadString(fontnm + ' (TrueType)')) = LowerCase(ExtractFileName(FileName)) then
begin
DeleteValue(fontnm + ' (TrueType)');
if not RemoveFontResource(PChar(FileName)) then // I2751
begin
WarnFmt(KMN_W_UninstallFont_FontInUse, VarArrayOf([fontnm]));
end;
if not DeleteFileCleanAttr(filename) then // I4574
begin
WarnFmt(KMN_W_UninstallFont_FontInUse, VarArrayOf([fontnm])); // I4181
end;
end;
end;
finally
Free;
end;
end;
end;
end.
|
unit Component.SSDLabel;
interface
uses
Classes, Controls, SysUtils, Windows, StdCtrls,
MeasureUnit.DataSize, Getter.PhysicalDrive.PartitionList, Device.PhysicalDrive;
type
TSSDLabel = class(TLabel)
private
type
TPartitionPosition = (First, Last, Mid);
procedure AppendCurrentPartitionToCaption(Position: TPartitionPosition;
const Letter: String);
procedure AppendPartitionListToCaption(PartitionList: TPartitionList);
procedure SetCaption;
procedure SetCaptionAsModelAndDiskSizeInMB;
procedure SetCaptionByPartitionList(PartitionList: TPartitionList);
procedure SetCursorAsHandPoint;
procedure SetEvent;
procedure SetFontAsInherited;
procedure SetParentAsgSSDSel;
procedure SetPhysicalDrive(PhysicalDriveToReplicate: IPhysicalDrive);
procedure SetProperty;
procedure AppendFirst(PartitionList: TPartitionList);
public
PhysicalDrive: IPhysicalDrive;
constructor Create(PhysicalDriveToReplicate: IPhysicalDrive); reintroduce;
destructor Destroy; override;
end;
implementation
uses Form.Main;
destructor TSSDLabel.Destroy;
begin
inherited;
end;
constructor TSSDLabel.Create(PhysicalDriveToReplicate: IPhysicalDrive);
begin
inherited Create(fMain.gSSDSel);
SetPhysicalDrive(PhysicalDriveToReplicate);
SetProperty;
SetEvent;
SetCaption;
end;
procedure TSSDLabel.SetPhysicalDrive(PhysicalDriveToReplicate: IPhysicalDrive);
begin
PhysicalDrive := PhysicalDriveToReplicate;
end;
procedure TSSDLabel.SetFontAsInherited;
begin
Font.Name := fMain.Font.Name;
Font.Size := fMain.SSDSelLbl.Font.Size;
end;
procedure TSSDLabel.SetParentAsgSSDSel;
begin
Parent := fMain.gSSDSel;
end;
procedure TSSDLabel.SetCursorAsHandPoint;
begin
Cursor := crHandPoint;
end;
procedure TSSDLabel.SetProperty;
begin
SetParentAsgSSDSel;
SetFontAsInherited;
SetCursorAsHandPoint;
end;
procedure TSSDLabel.SetEvent;
begin
OnClick := fMain.SSDLabelClick;
OnMouseEnter := fMain.SSDSelLblMouseEnter;
OnMouseLeave := fMain.SSDSelLblMouseLeave;
end;
function DenaryByteToMB(SizeInByte: Double): Double;
var
DenaryByteToMB: TDatasizeUnitChangeSetting;
begin
DenaryByteToMB.FNumeralSystem := Denary;
DenaryByteToMB.FFromUnit := ByteUnit;
DenaryByteToMB.FToUnit := MegaUnit;
result :=
ChangeDatasizeUnit(SizeInByte, DenaryByteToMB);
end;
function FormatSizeInMBAsDenaryInteger(SizeInDenaryFloat: Double): String;
var
DenaryInteger: TFormatSizeSetting;
begin
DenaryInteger.FNumeralSystem := Denary;
DenaryInteger.FPrecision := 0;
result := FormatSizeInMB(SizeInDenaryFloat, DenaryInteger);
end;
procedure TSSDLabel.SetCaptionAsModelAndDiskSizeInMB;
var
DiskSizeInMB: Double;
begin
DiskSizeInMB := DenaryByteToMB(PhysicalDrive.DiskSizeInByte);
Caption :=
PhysicalDrive.IdentifyDeviceResult.Model + ' ' +
FormatSizeInMBAsDenaryInteger(DiskSizeInMB);
end;
procedure TSSDLabel.AppendCurrentPartitionToCaption(
Position: TPartitionPosition; const Letter: String);
begin
Caption := Caption + Letter;
if Position = TPartitionPosition.Mid then
Caption := Caption + ', '
else
Caption := Caption + ') ';
end;
procedure TSSDLabel.AppendFirst(PartitionList: TPartitionList);
begin
if PartitionList.Count > 0 then
Caption := Caption + '(';
end;
procedure TSSDLabel.AppendPartitionListToCaption(PartitionList: TPartitionList);
var
PartitionEntryNumber: Integer;
begin
AppendFirst(PartitionList);
for PartitionEntryNumber := 0 to (PartitionList.Count - 1) do
if PartitionEntryNumber = (PartitionList.Count - 1) then
AppendCurrentPartitionToCaption(TPartitionPosition.Last,
PartitionList[PartitionEntryNumber].Letter)
else
AppendCurrentPartitionToCaption(TPartitionPosition.Mid,
PartitionList[PartitionEntryNumber].Letter);
end;
procedure TSSDLabel.SetCaptionByPartitionList(PartitionList: TPartitionList);
begin
SetCaptionAsModelAndDiskSizeInMB;
AppendPartitionListToCaption(PartitionList);
end;
procedure TSSDLabel.SetCaption;
var
PartitionList: TPartitionList;
begin
PartitionList := PhysicalDrive.GetPartitionList;
SetCaptionByPartitionList(PartitionList);
FreeAndNil(PartitionList);
end;
end. |
unit Points;
interface
type
float = single;
Point = record case boolean of true: (x,y,z:float); false: (c: array [0..2] of float) end;
function ToPoint (x,y,z: float): Point;
function Dot (const p1,p2: Point): float;
function Cross (const p1,p2: Point): Point;
function Volume (const p1,p2,p3: Point): float;
function LengthP (const p: Point): float;
function Add (const p1,p2: Point): Point;
function Sub (const p1,p2: Point): Point;
function Scale (const p: Point; s: float): Point;
function Mid (const p1: Point; f1: float; const p2: Point; f2: float) : Point;
function Atan2(y,x:float):float;
type
Matrix = array [0..3] of Point;
procedure SetID (var M: Matrix);
procedure Translate (var M: Matrix; const P: Point);
procedure Rotate (var M: Matrix; coord : integer; a :float);
procedure ScaleM (var M: Matrix; S : Point);
function RotateP (const M: Matrix; const P: Point; OnlyRot : boolean = false) : Point;
implementation
uses Math;
function ToPoint (x,y,z: float): Point;
begin
Result.x := x;
Result.y := y;
Result.z := z;
end;
function Dot (const p1,p2: Point): float;
begin
Result := p1.x*p2.x + p1.y*p2.y + p1.z*p2.z;
end;
function Cross (const p1,p2: Point): Point;
begin
Result.x := p1.y*p2.z - p1.z*p2.y;
Result.y := p1.z*p2.x - p1.x*p2.z;
Result.z := p1.x*p2.y - p1.y*p2.x;
end;
function Volume (const p1,p2,p3: Point): float;
begin
Result := Dot(Cross(p1,p2),p3);
end;
function LengthP (const p: Point): float;
begin
Result := sqrt(sqr(p.x)+sqr(p.y)+sqr(p.z));
end;
function Add (const p1,p2: Point): Point;
begin
Result.x := p1.x+p2.x;
Result.y := p1.y+p2.y;
Result.z := p1.z+p2.z;
end;
function Sub (const p1,p2: Point): Point;
begin
Result.x := p1.x-p2.x;
Result.y := p1.y-p2.y;
Result.z := p1.z-p2.z;
end;
function Scale (const p: Point; s: float): Point;
begin
Result.x := p.x*s;
Result.y := p.y*s;
Result.z := p.z*s;
end;
function Mid (const p1: Point; f1: float; const p2: Point; f2: float) : Point;
begin
Result := Add(p1, Scale(Sub(p2,p1), f1/(f1+f2)));
end;
procedure SetID (var M: Matrix);
begin
M[0] := ToPoint(1,0,0);
M[1] := ToPoint(0,1,0);
M[2] := ToPoint(0,0,1);
M[3] := ToPoint(0,0,0);
end;
procedure Translate (var M: Matrix; const P: Point);
begin
M[3] := Add(M[3], P);
end;
procedure Rotate (var M: Matrix; coord : integer; a :float);
// умножение справа
var
c,s,t: float;
i : integer;
c1,c2 : integer;
begin
c := cos(a);
s := sin(a);
c1 := (coord+1) mod 3;
c2 := (coord+2) mod 3;
for i := 0 to 3 do begin
t := M[i].c[c1]*c - M[i].c[c2]*s;
M[i].c[c2] := M[i].c[c2]*c + M[i].c[c1]*s;
M[i].c[c1] := t;
end;
end;
procedure ScaleM (var M: Matrix; S : Point);
var
j, i : integer;
begin
for j := 0 to 2 do
for i := 0 to 3 do
M[i].c[j] := M[i].c[j] * S.c[j];
end;
function RotateP (const M: Matrix; const P: Point; OnlyRot : boolean = false) : Point;
var
i : integer;
begin
if OnlyRot then begin
for i := 0 to 2 do
Result.c[i] := M[0].c[i]*P.c[0] + M[1].c[i]*P.c[1] + M[2].c[i]*P.c[2];
end else begin
for i := 0 to 2 do
Result.c[i] := M[0].c[i]*P.c[0] + M[1].c[i]*P.c[1] + M[2].c[i]*P.c[2] + M[3].c[i];
end;
end;
function Atan2(y,x:float):float;
asm
FLD Y
FLD X
FPATAN
FWAIT
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
/// ///
/// MAP FILE PARSER UNIT ///
/// ///
/// -DESCRIPTION ///
/// This unit is responsible for parsing out he map file ///
/// and searching for the map info from provided addresses ///
/// ///
/// ///
/// ///
/// ///
/// -IMPLEMNTATION ///
/// This can be ran in the main thread or is multithreaded ///
/// for an increase in performance ///
/// ///
////////////////////////////////////////////////////////////////////////////////
unit uMapParser;
interface
uses
System.Classes, Vcl.Forms, System.SysUtils, System.IniFiles, UStopWatch, Vcl.Dialogs, Winapi.Windows, UThreadPool,
System.Generics.Defaults, System.Generics.Collections;
type
/// <summary>custom Weight function used for the binary searching</summary>
/// <param name="aTarget">The search criteria</param>
/// <param name="aLine">The direction to move</param>
/// <returns>The direction to move</returns>
TWeight = function(aTarget, aLine: String): Integer;
/// <summary>Function to be called by the thread</summary>
/// <param name="aMasterList">The main list to move through</param>
/// <param name="aResultList">The results list</param>
/// <param name="aExtList">Additonal list that can be filled out</param>
TWorkThreadFunc = procedure(aMasterList, aResultList: TStringList; aExtList: TStringList = nil);
/// <summary>Additional methodes for the TStringList object</summary>
TStringsHelper = class helper for TStrings
public
/// <summary>Finds the index of the string while stripping the spaces</summary>
/// <param name="S">Substring that we want to find (should not have spaces)</param>
/// <param name="OffSet">defines our starting position for the search</param>
/// <returns>The index of the string or -1 if not found</returns>
function IndexOfStrippedString(const S: string; OffSet: Integer = 0): Integer;
/// <summary>Finds the index where a specific substring exist</summary>
/// <param name="S">Substring to search for</param>
/// <param name="OffSet">The starting point to begin the search</param>
/// <returns>The first index where the substring was found</returns>
function IndexOfPiece(const S: string; OffSet: Integer = 0): Integer;
/// <summary>Retrieves a set of strings from a specific index on</summary>
/// <param name="ReturnList">Reutnr list where the strings should be placed</param>
/// <param name="OffSet">Index to start processing at</param>
/// <param name="Linecnt">How many lines to go past the Offset</param>
Procedure StringsByNum(ReturnList: TStringList; OffSet: Integer = 0; Linecnt: Integer = 1);
end;
// * Thread Types *
// <table>
// Type Name Meaning
// ------------- -------------
// TYPE_UNIT Processing the unit section
// TYPE_METHOD Processing the Method section
// TYPE_LINES Processing the Lines section
//</table>
tThreadType = (TYPE_UNIT, TYPE_METHOD, TYPE_LINES);
TWorker = class
FWorkerID: Integer;
fThreadType: tThreadType;
fMasterList: TStringList;
fResultList: TStringList;
fExtList: TStringList;
fThreadFunc: TWorkThreadFunc;
fHandler: TThreadPool;
private
procedure TakeAction(Sender: TObject);
public
constructor Create(const Handler: TThreadPool; aThreadType: tThreadType; const aMasterList: TStringList; const aWrokerID: Integer);
destructor Destroy(); override;
procedure FireThread;
property ResultList: TStringList read fResultList;
property ExtList: TStringList read fExtList;
Property ThreadFunction: TWorkThreadFunc read fThreadFunc write fThreadFunc;
property ThreadType: tThreadType read fThreadType write fThreadType;
Property WorkerID: Integer read FWorkerID write FWorkerID;
end;
tMapParser = class(TObject)
private
fMapLoaded: Boolean;
fMapFile: TStringList;
fUnitSection: TStringList;
fMethodSection: TStringList;
fLinesSections: TStringList;
fLines: TStringList;
fFileName: String;
FUnitMax: THashedStringList;
// fStopWatch: TStopWatch;
fworkerArray: TObjectList<TWorker>;
fThreadPool: TThreadPool;
Function LoadMapFile: Boolean;
Function LoadUnits: Boolean;
Function LoadMethods: Boolean;
Function LoadLines: Boolean;
Function LineSearch(const LookUpAddr: LongWord; const UnitName: String): Integer;
function GetUnitName(const LookUpAddr: LongWord): string;
function GetMethodName(const LookUpAddr: LongWord): string;
function GetLineNum(const LookUpAddr: LongWord; const UnitName: string): string;
public
constructor Create; overload;
constructor Create(ThreadOnDemand: Boolean = true); overload;
procedure CreateThreaded(Const ThreadOnDemand: Boolean);
destructor Destroy; override;
procedure LookupInMap(const LookUpAddr: LongWord; out aUnit, aMethod, aLineNumber: String);
Property FileName: string read fFileName;
property MapLoaded: Boolean read fMapLoaded;
property _UnitName[const LookUpAddr: LongWord]: string read GetUnitName;
property _MethodName[const LookUpAddr: LongWord]: string read GetMethodName;
end;
Procedure LoadUnitsThreaded(aMasterList, aResultList: TStringList; aExtList: TStringList = nil);
Procedure LoadMethodsThreaded(aMasterList, aResultList: TStringList; aExtList: TStringList = nil);
Procedure LoadLinesThreaded(aMasterList, aResultList: TStringList; aExtList: TStringList = nil);
implementation
uses
System.StrUtils, Vcl.Controls, System.Math;
const
UnitPrefix = ' M=';
SegmentMap = 'Detailedmapofsegments';
PublicsByValue = 'AddressPublicsbyValue';
BoundResource = 'Boundresourcefiles';
UnitSection = 'Line numbers for ';
LookUpErrorNum = -3;
{$REGION 'Utils'}
function Piece(const S: string; Delim: char; PieceNum: Integer): string;
{ returns the Nth piece (PieceNum) of a string delimited by Delim }
var
i: Integer;
Strt, Next: PChar;
begin
i := 1;
Strt := PChar(S);
Next := StrScan(Strt, Delim);
while (i < PieceNum) and (Next <> nil) do
begin
Inc(i);
Strt := Next + 1;
Next := StrScan(Strt, Delim);
end;
if Next = nil then
Next := StrEnd(Strt);
if i < PieceNum then
Result := ''
else
SetString(Result, Strt, Next - Strt);
end;
function Piece2(input: string; schar: char; S: Integer): string;
var
c: array of Integer;
b, t: Integer;
begin
Result := '';
// Dec(s, 2); // for compatibility with very old & slow split function
if Trim(input) = '' then
Exit;
S := S - 1; // zero based
t := 0; // variable T needs to be initialized...
setlength(c, Length(input));
for b := 0 to pred(High(c)) do
begin
c[b + 1] := posex(schar, input, succ(c[b]));
// BREAK LOOP if posex looped (position before previous)
// or wanted position reached..
if (c[b + 1] < c[b]) or (S < t) then
break
else
Inc(t);
end;
if (S < Length(c)) and (c[S + 1] <> 0) then
Result := Copy(input, succ(c[S]), pred(c[S + 1] - c[S]))
else
Result := Copy(input, succ(c[S]), Length(input))
end;
function Piece3(const S: string; Delim: char; PieceNum: Integer): string;
var
tmp: TStringList;
begin
Result := '';
if S = '' then
Exit;
tmp := TStringList.Create;
try
ExtractStrings([Delim], [], PChar(S), tmp);
if PieceNum <= tmp.Count then
Result := tmp[PieceNum - 1];
finally
tmp.Free;
end;
end;
function PieceByString(Value, Delimiter: string; StartPiece, EndPiece: Integer): string;
var
dlen, i, pnum: Integer;
buf: String;
begin
Result := '';
Value := Uppercase(Value);
Delimiter := Uppercase(Delimiter);
if (Value <> '') And (StartPiece > 0) And (EndPiece >= StartPiece) then
begin
dlen := Length(Delimiter);
i := Pos(Delimiter, Value) - 1;
if i >= 0 then
begin
buf := Value;
pnum := 1;
repeat
if pnum > EndPiece then
break;
if i < 0 then
i := Length(buf);
if pnum = StartPiece then
Result := Copy(buf, 1, i)
else if pnum > StartPiece then
Result := Result + Delimiter + Copy(buf, 1, i);
Delete(buf, 1, i + dlen);
i := Pos(Delimiter, buf) - 1;
Inc(pnum);
until (i < 0) And (buf = '');
end
else if StartPiece = 1 then
Result := Value;
end;
end;
procedure SetPiece(var x: string; Delim: char; PieceNum: Integer; const NewPiece: string);
{ sets the Nth piece (PieceNum) of a string to NewPiece, adding delimiters as necessary }
var
i: Integer;
Strt, Next: PChar;
begin
i := 1;
Strt := PChar(x);
Next := StrScan(Strt, Delim);
while (i < PieceNum) and (Next <> nil) do
begin
Inc(i);
Strt := Next + 1;
Next := StrScan(Strt, Delim);
end;
if Next = nil then
Next := StrEnd(Strt);
if i < PieceNum then
x := x + StringOfChar(Delim, PieceNum - i) + NewPiece
else
x := Copy(x, 1, Strt - PChar(x)) + NewPiece + StrPas(Next);
end;
procedure SetPieces(var x: string; Delim: char; Pieces: Array of Integer; FromString: string);
var
i: Integer;
begin
for i := low(Pieces) to high(Pieces) do
SetPiece(x, Delim, Pieces[i], Piece(FromString, Delim, Pieces[i]));
end;
function MapWeightAddress(aTarget: String; aLine: String): Integer;
Function StrToLongWord(var aLngWrd: LongWord; aStr: String; aAdjustment: Integer = 0): Boolean;
var
aInt: Integer;
begin
Result := false;
aInt := StrToIntDef(aStr, -1) + aAdjustment;
if aInt >= 0 then
begin
Result := true;
aLngWrd := aInt;
end;
end;
var
_Target, _min, _max: LongWord;
_Error: Boolean;
begin
_Target := 0;
_Error := not StrToLongWord(_Target, aTarget);
if not _Error then
_Error := not StrToLongWord(_min, Piece(aLine, '^', 1));
if not _Error then
_Error := not StrToLongWord(_max, Piece(aLine, '^', 2), -1);
if not _Error then
begin
if _Target < _min then
Result := -1
else if _Target <= _max then
Result := 0
else
Result := 1;
end else
Result := LookUpErrorNum;
end;
function findPosition(aList: TStrings; aTarget: String; aStartPos, aEndPos: Integer; aWeight: TWeight): Integer;
var
S: string;
Pos, step, dir: Integer;
Found: Boolean;
CacheLookup: TStringList;
begin
Result := -1;
if not assigned(aList) then
Exit;
if aList.Count < 1 then
Exit;
Found := true;
Pos := 0;
step := aList.Count - 1;
dir := aWeight(aTarget, aList[0]);
if dir = LookUpErrorNum then
begin
Result := -2;
exit;
end;
case dir of
- 1:
Exit;
0:
Result := 0;
else
Found := false;
end;
if not Found then
begin
CacheLookup := TStringList.Create;
try
while not Found do
begin
step := step div 2;
if step < 1 then
step := 1;
Pos := Pos + dir * step;
if (Pos < aStartPos) or (Pos > aEndPos) then
Exit;
// logging positions to avoid cycling when there are gaps in the map
S := IntToStr(Pos);
if CacheLookup.IndexOf(S) > 0 then
begin
Result := -2;
Exit;
end
else
CacheLookup.Add(S);
dir := aWeight(aTarget, aList[Pos]);
if dir = LookUpErrorNum then
begin
Result := -2;
exit;
end;
Found := dir = 0;
if Found then
Result := Pos;
end;
Finally
FreeAndNil(CacheLookup);
end;
end;
end;
function DelimCount(const Str, Delim: string): Integer;
var
i, dlen, slen: Integer;
begin
Result := 0;
i := 1;
dlen := Length(Delim);
slen := Length(Str) - dlen + 1;
while (i <= slen) do
begin
if (Copy(Str, i, dlen) = Delim) then
begin
Inc(Result);
Inc(i, dlen);
end
else
Inc(i);
end;
end;
procedure Replace(Var InString: String; WhatToReplace, WhatToReplaceWith: String);
{
does a search and replace within InString. Replaces all occurrences
of "WhatToReplace" with "WhatToReplaceWith".
Instring: The string we are going to modify
WhatToReplace: The part of Instring that we are going to replace
WhatToReplaceWith: The string we will replace WhatToReplace with.
You can use this routine to delete characters by simply setting
WhatToReplaceWith:='';
}
var
ReplacePosition: Integer;
begin
if WhatToReplace = WhatToReplaceWith then
Exit;
ReplacePosition := Pos(WhatToReplace, InString);
if ReplacePosition <> 0 then
begin
repeat
Delete(InString, ReplacePosition, Length(WhatToReplace));
Insert(WhatToReplaceWith, InString, ReplacePosition);
// ReplacePosition:=PosEx(WhatToReplace,InString,ReplacePosition);
ReplacePosition := Pos(WhatToReplace, InString); // Remarkably, Pos is faster than PosEX, despite the ReplacePosition parameter in PosEx
until ReplacePosition = 0;
end; // if
end; // procedure
{$ENDREGION}
{$REGION 'tMapParser'}
{$REGION 'Threaded'}
procedure tMapParser.CreateThreaded(Const ThreadOnDemand: Boolean);
const
MaxLineCnt = 3; // Number of lines to process for each thread
var
CoreCnt: Integer;
CanContinue: Boolean;
RtnCursor: Integer;
function PreLoadWorkers(StrtStr: String; WorkerType: tThreadType; EndStr: string = ''): Boolean;
var
i, FromIdx, ToIdx, LastPos, SegmentCnt, LoopCnt: Integer;
tmpStrLst: TStringList;
aObj: TWorker;
begin
Result := false;
// find the start and end point of the file
FromIdx := fMapFile.IndexOfStrippedString(StrtStr);
if WorkerType = TYPE_LINES then
FromIdx := fMapFile.IndexOfPiece(UnitSection, FromIdx);
ToIdx := fMapFile.IndexOfStrippedString(EndStr, FromIdx + 2);
// Ensure that we have our points
if (FromIdx = -1) or (ToIdx = -1) then
Exit;
// Find how much to break up the text
SegmentCnt := Ceil((ToIdx - FromIdx) / CoreCnt);
LoopCnt := CoreCnt;
tmpStrLst := TStringList.Create;
try
LastPos := FromIdx;
// for each core grab the "chunk" of text
for i := 1 to LoopCnt do
begin
// Get the remaining if at the end
if i = LoopCnt then
SegmentCnt := ToIdx - LastPos;
// Grab the text
tmpStrLst.Clear;
fMapFile.StringsByNum(tmpStrLst, LastPos, SegmentCnt);
// Create the worker
aObj := TWorker.Create(fThreadPool, WorkerType, tmpStrLst, fworkerArray.Count + 1);
// set the callback
case WorkerType of
TYPE_UNIT:
aObj.ThreadFunction := LoadUnitsThreaded;
TYPE_METHOD:
aObj.ThreadFunction := LoadMethodsThreaded;
TYPE_LINES:
aObj.ThreadFunction := LoadLinesThreaded;
end;
fworkerArray.Add(aObj);
// This will start the new thread (can be called after all have been setup too)
if ThreadOnDemand then
aObj.FireThread;
// Update so we know where we left off
Inc(LastPos, SegmentCnt + 1);
end;
finally
tmpStrLst.Free;
end;
Result := true;
end;
procedure FireOffThreads;
var
aObj: TWorker;
begin
// Will loop throgh and start the threads
for aObj in fworkerArray do
aObj.FireThread;
end;
procedure LoadResults;
var
i: Integer;
Comp: IComparer<TWorker>;
LAddrStr, NewText: String;
aObj: TWorker;
begin
// Sort the array by it's type and thread id
Comp := TComparer<TWorker>.Construct(
function(const Left, Right: TWorker): Integer
begin
Result := TComparer<tThreadType>.Default.Compare(Left.ThreadType, Right.ThreadType);
if Result = 0 then
Result := TComparer<Integer>.Default.Compare(Left.WorkerID, Right.WorkerID);
end);
// Sort the data array
fworkerArray.Sort(Comp);
// Need to grad the last addrss from methods and add it to the start of the first (for the next part)
for aObj in fworkerArray do
begin
case aObj.ThreadType of
TYPE_UNIT:
begin
fUnitSection.AddStrings(aObj.ResultList);
FUnitMax.AddStrings(aObj.ExtList);
end;
TYPE_METHOD:
begin
// With it sorted we need to peice some data together
if fMethodSection.Count > 0 then
begin
// Grab the last address
LAddrStr := Piece(aObj.ResultList.Strings[0], '^', 1);
// Need to tack this on to the new line
NewText := fMethodSection[fMethodSection.Count - 1];
SetPiece(NewText, '^', 2, LAddrStr);
fMethodSection[fMethodSection.Count - 1] := NewText;
end;
// Add these results to the list
fMethodSection.AddStrings(aObj.ResultList);
end;
TYPE_LINES:
begin
// Need to adjust the extlist line values by the current length (if already added)
if fLinesSections.Count > 0 then
begin
for i := 0 to aObj.ExtList.Count - 1 do
aObj.ExtList.ValueFromIndex[i] := IntToStr(StrToIntDef(aObj.ExtList.ValueFromIndex[i], -1) + (fLines.Count));
end;
fLines.AddStrings(aObj.ResultList);
fLinesSections.AddStrings(aObj.ExtList);
end;
end;
end;
fUnitSection.Sort;
fMethodSection.Sort;
end;
begin
RtnCursor := Screen.Cursor;
Screen.Cursor := crhourGlass;
try
// Assume we can load it
fMapLoaded := LoadMapFile;
// Init our variables
fworkerArray := TObjectList<TWorker>.Create;
try
CoreCnt := CPUCount - 1;
fThreadPool := TThreadPool.Create(CoreCnt);
// Run our setup
CanContinue := PreLoadWorkers(SegmentMap, TYPE_UNIT);
if CanContinue then
CanContinue := PreLoadWorkers(PublicsByValue, TYPE_METHOD);
if CanContinue then
CanContinue := PreLoadWorkers(PublicsByValue, TYPE_LINES, BoundResource);
if not CanContinue then
begin
fMapLoaded := false;
Exit;
end;
if not ThreadOnDemand then
FireOffThreads;
// Wait while we run
While Not(fThreadPool.AllTasksFinished) Do
Sleep(0);
fUnitSection := TStringList.Create;
FUnitMax := THashedStringList.Create;
fMethodSection := TStringList.Create;
fLines := TStringList.Create;
fLinesSections := THashedStringList.Create;
LoadResults;
finally
FreeAndNil(fworkerArray);
end;
Finally
Screen.Cursor := RtnCursor;
end;
end;
procedure LoadUnitsThreaded(aMasterList, aResultList: TStringList; aExtList: TStringList = nil);
var
idx: Integer;
line, tmpStr, _UnitName: string;
addr, Next, len: LongWord;
begin
for idx := 0 to aMasterList.Count - 1 do
begin
line := aMasterList[idx];
if (Piece(line, ' ', 4) = 'C=CODE') then
begin
tmpStr := Piece(line, ':', 2);
addr := StrToInt('$' + Piece(tmpStr, ' ', 1));
len := StrToInt('$' + Piece(tmpStr, ' ', 2));
Next := addr + len;
_UnitName := '';
_UnitName := Piece(PieceByString(line, UnitPrefix, 2, 2), ' ', 1);
aResultList.Add(Format('%.*d', [8, addr]) + '^' + Format('%.*d', [8, Next]) + '^' + _UnitName);
aExtList.Add(_UnitName + '=' + IntToStr(Next));
end;
end;
end;
Procedure LoadMethodsThreaded(aMasterList, aResultList: TStringList; aExtList: TStringList = nil);
var
idx: Integer;
line, tmpStr, tmpStr2: string;
LAddr, addr1: LongWord;
begin
for idx := 0 to aMasterList.Count - 1 do
begin
line := aMasterList[idx];
if (Trim(Piece(line, ':', 1)) = '0001') then
begin
tmpStr := Piece(line, ':', 2);
addr1 := StrToInt('$' + Piece(tmpStr, ' ', 1));
LAddr := 0;
if (idx + 1) <= aMasterList.Count - 1 then
begin
if (aMasterList[idx + 1] <> '') then
begin
tmpStr2 := Piece(aMasterList[idx + 1], ':', 2);
LAddr := StrToInt('$' + Piece(tmpStr2, ' ', 1));
end;
end;
// Chop of the address
tmpStr := Copy(tmpStr, Pos(' ', tmpStr), Length(tmpStr));
aResultList.Add(Format('%.*d', [8, addr1]) + '^' + Format('%.*d', [8, LAddr]) + '^' + Trim(tmpStr));
end;
end;
end;
Procedure LoadLinesThreaded(aMasterList, aResultList: TStringList; aExtList: TStringList = nil);
var
idx, AddLineNum: Integer;
line, tmpStr: string;
insertLastLine: Boolean;
begin
insertLastLine := false;
for idx := 0 to aMasterList.Count - 1 do
begin
line := aMasterList[idx];
if Pos(UnitSection, line) > 0 then
begin
tmpStr := Piece(line, '(', 1);
AddLineNum := aResultList.Add(line);
aExtList.Add(Piece(tmpStr, ' ', 4) + '=' + IntToStr(AddLineNum));
insertLastLine := true;
end;
if (line = '') and insertLastLine then
begin
// aResultList.Add(' XXX 0001:' + IntToHex(FUnitMax, 8));
insertLastLine := false;
end;
if Pos('0001:', line) > 0 then
aResultList.Add(line);
end;
end;
constructor tMapParser.Create(ThreadOnDemand: Boolean = true);
begin
inherited Create;
// fStopWatch := TStopWatch.Create(nil, true);
// try
// fStopWatch.Start;
// try
CreateThreaded(ThreadOnDemand);
// finally
// fStopWatch.Stop;
// ShowMessage('Load of the map file: ' + fStopWatch.Elapsed);
// end;
// finally
// fStopWatch.Free;
// end;
end;
{$ENDREGION}
{$REGION 'Non Threaded'}
constructor tMapParser.Create();
begin
inherited;
// fStopWatch := TStopWatch.Create(nil, true);
// try
// fStopWatch.Start;
// try
// Assume we can load it
fMapLoaded := LoadMapFile;
// No need to waste time if we are missing some info
if fMapLoaded then
fMapLoaded := LoadUnits;
if fMapLoaded then
fMapLoaded := LoadMethods;
if fMapLoaded then
fMapLoaded := LoadLines;
// finally
// fStopWatch.Stop;
// ShowMessage('Load of the map file: ' + fStopWatch.Elapsed);
// end;
// finally
// fStopWatch.Free;
// end;
end;
Function tMapParser.LoadMapFile: Boolean;
const
MapFileExt = '.map';
begin
fMapFile := TStringList.Create;
fFileName := ExtractFileName(Application.exename);
fFileName := ChangeFileExt(fFileName, MapFileExt);
if FileExists(fFileName) then
begin
fMapFile.LoadFromFile(fFileName);
Result := true;
end
else
Result := false;
end;
destructor tMapParser.Destroy;
begin
fMapFile.Free;
fUnitSection.Free;
fMethodSection.Free;
fLinesSections.Free;
fLines.Free;
FUnitMax.Free;
if assigned(fThreadPool) then
FreeAndNil(fThreadPool);
inherited;
end;
Function tMapParser.LoadUnits: Boolean;
Function FindStartLoc: Integer;
begin
Result := fMapFile.IndexOfStrippedString(SegmentMap);
end;
var
idx: Integer;
line, tmpStr, _UnitName: string;
addr, Next, len: LongWord;
tmpLst: TStringList;
begin
fUnitSection := TStringList.Create;
idx := FindStartLoc;
// if not found then we have an error
if idx < 0 then
begin
Result := false;
Exit;
end
else
Result := true;
// Move down 2 lines
try
tmpLst := TStringList.Create;
try
Inc(idx, 2);
repeat
line := fMapFile[idx];
if (Piece(line, ' ', 4) = 'C=CODE') then
begin
tmpStr := Piece(line, ':', 2);
addr := StrToInt('$' + Piece(tmpStr, ' ', 1));
len := StrToInt('$' + Piece(tmpStr, ' ', 2));
Next := addr + len;
_UnitName := '';
_UnitName := Piece(PieceByString(line, UnitPrefix, 2, 2), ' ', 1);
fUnitSection.Add(Format('%.*d', [8, addr]) + '^' + Format('%.*d', [8, Next]) + '^' + _UnitName);
tmpLst.Add(_UnitName + '=' + IntToStr(Next));
end;
Inc(idx, 1);
until (line = '');
fUnitSection.Sort;
finally
if tmpLst.Count > 0 then
begin
FUnitMax := THashedStringList.Create;
FUnitMax.Assign(tmpLst);
end;
tmpLst.Free;
end;
except
Result := false;
end;
end;
// Last Address^ current Address^ Method
Function tMapParser.LoadMethods: Boolean;
Function FindStartLoc: Integer;
const
Val1 = 'AddressPublicsbyValue';
begin
Result := fMapFile.IndexOfStrippedString(Val1);
end;
var
idx: Integer;
line, tmpStr, tmpStr2: string;
LAddr, addr1: LongWord;
begin
fMethodSection := TStringList.Create;
idx := FindStartLoc;
// if not found then we have an error
if idx < 0 then
begin
Result := false;
Exit;
end
else
Result := true;
// Move down 2 lines
try
Inc(idx, 2);
repeat
line := fMapFile[idx];
if (Trim(Piece(line, ':', 1)) = '0001') then
begin
tmpStr := Piece(line, ':', 2);
addr1 := StrToInt('$' + Piece(tmpStr, ' ', 1));
LAddr := 0;
if (fMapFile[idx + 1] <> '') then
begin
tmpStr2 := Piece(fMapFile[idx + 1], ':', 2);
LAddr := StrToInt('$' + Piece(tmpStr2, ' ', 1));
end;
tmpStr := Copy(tmpStr, Pos(' ', tmpStr), Length(tmpStr));
fMethodSection.Add(Format('%.*d', [8, addr1]) + '^' + Format('%.*d', [8, LAddr]) + '^' + Trim(tmpStr));
end;
Inc(idx, 1);
until (line = '');
fMethodSection.Sort;
except
Result := false;
end;
end;
Function tMapParser.LoadLines: Boolean;
const
BoundResourceFiles = 'Bound resource files';
UnitSection = 'Line numbers for ';
Function FindStartLoc: Integer;
const
Val1 = 'AddressPublicsbyValue';
begin
Result := fMapFile.IndexOfStrippedString(Val1);
end;
Function FindEndLoc(OffSet: Integer): Integer;
const
Val1 = 'Boundresourcefiles';
begin
Result := fMapFile.IndexOfStrippedString(Val1, OffSet);
end;
var
idx, EndIdx, AddLineNum: Integer;
line, tmpStr: string;
insertLastLine: Boolean;
i: Integer;
begin
fLinesSections := TStringList.Create;
fLines := TStringList.Create;
insertLastLine := false;
idx := FindStartLoc;
EndIdx := FindEndLoc(idx);
// if not found then we have an error
if idx < 0 then
begin
Result := false;
Exit;
end
else
Result := true;
// Need to move past all the methods
// while Pos(UnitSection, fMapFile[idx]) = 0 do
// Inc(idx);
Inc(idx, 2);
while fMapFile[idx] <> '' do
Inc(idx);
// Move down 2 lines
try
Inc(idx, 2);
for i := idx to EndIdx do
begin
line := fMapFile[i];
if ContainsText(line, UnitSection) then
begin
tmpStr := Piece(line, '(', 1);
AddLineNum := fLines.Add(line);
fLinesSections.Add(Piece(tmpStr, ' ', 4) + '=' + IntToStr(AddLineNum));
insertLastLine := true;
end;
if (line = '') and insertLastLine then
begin
// fLines.Add(' XXX 0001:' + IntToHex(FUnitMax, 8));
insertLastLine := false;
end;
if ContainsText(line, '0001:') then
fLines.Add(line);
end;
except
Result := false;
end;
end;
procedure tMapParser.LookupInMap(const LookUpAddr: LongWord; out aUnit, aMethod, aLineNumber: String);
begin
aUnit := GetUnitName(LookUpAddr);
if (aUnit = 'NA') then
Exit;
aMethod := GetMethodName(LookUpAddr);
aLineNumber := GetLineNum(LookUpAddr, aUnit);
end;
function tMapParser.GetUnitName(const LookUpAddr: LongWord): string;
var
UnitLineNum: Integer;
begin
Result := 'NA';
UnitLineNum := findPosition(fUnitSection, Format('%.*d', [8, LookUpAddr]), 0, fUnitSection.Count - 1, MapWeightAddress);
//UnitLineNum := findPosition(fUnitSection, IntToStr(LookUpAddr), 0, fUnitSection.Count - 1, MapWeightAddress);
if UnitLineNum > -1 then
Result := Piece(fUnitSection[UnitLineNum], '^', 3);
end;
function tMapParser.GetMethodName(const LookUpAddr: LongWord): string;
var
MethodLineNum: Integer;
begin
Result := '*** Unknown ***';
MethodLineNum := findPosition(fMethodSection, Format('%.*d', [8, LookUpAddr]), 0, fMethodSection.Count - 1, MapWeightAddress);
// MethodLineNum := findPosition(fMethodSection, IntToStr(LookUpAddr), 0, fMethodSection.Count - 1, MapWeightAddress);
// MethodLineNum := BinaryMethodSearch(LookUpAddr);
if MethodLineNum = -1 then
Exit;
Result := Trim(Piece(fMethodSection[MethodLineNum], '^', 3));
end;
function tMapParser.GetLineNum(const LookUpAddr: LongWord; const UnitName: string): string;
begin
Result := '*** Unknown ***';
Result := IntToStr(LineSearch(LookUpAddr, UnitName));
end;
Function tMapParser.LineSearch(const LookUpAddr: LongWord; const UnitName: String): Integer;
var
idx, i, UnitIdx: Integer;
lastAddr, addr: LongWord;
line, lineNum, LastLineNum: string;
Found, insertLastLine: Boolean;
begin
Result := -1;
UnitIdx := 0;
Found := false;
UnitIdx := fLinesSections.IndexOfPiece(UnitName, UnitIdx);
while (UnitIdx > 0) and not Found do
begin
// find the starting point
idx := StrToIntDef(fLinesSections.ValueFromIndex[UnitIdx], -1);
if idx = -1 then
Exit;
insertLastLine := true;
Inc(idx, 2);
lastAddr := 0;
LastLineNum := '-1';
repeat
line := fLines[idx];
Inc(idx);
if idx < fLines.Count - 1 then
begin
if ((fLines[idx] = '') or (Pos(UnitSection, fLines[idx]) > 0)) and (fLinesSections.IndexOfPiece(UnitName, UnitIdx + 1) < 0) and insertLastLine then
begin
fLines.Insert(idx, ' XXX 0001:' + IntToHex(StrToIntDef(FUnitMax.Values[UnitName], 0), 8));
insertLastLine := false;
end;
end;
repeat
i := Pos('0001:', line);
if (i > 0) then
begin
addr := StrToInt('$' + Copy(line, i + 5, 8));
lineNum := Trim(Copy(line, 1, i - 1));
line := Copy(line, i + 13, MaxInt) + ' ';
if (LookUpAddr >= lastAddr) and (LookUpAddr < addr) then
begin
Result := StrToInt(LastLineNum);
line := '';
Found := true;
end;
LastLineNum := lineNum;
lastAddr := addr;
end;
until (i = 0) or Found;
until ((line = '') or (Pos(UnitSection, fLines[idx]) > 0)) or Found;
UnitIdx := fLinesSections.IndexOfPiece(UnitName, UnitIdx + 1);
end;
end;
{$ENDREGION}
{$ENDREGION}
{$REGION 'TStringsHelper'}
function TStringsHelper.IndexOfStrippedString(const S: string; OffSet: Integer = 0): Integer;
var
tmpStr: String;
begin
Result := -1;
if OffSet > GetCount - 1 then
Exit;
for Result := OffSet to GetCount - 1 do
begin
tmpStr := Strings[Result];
Replace(tmpStr, ' ', '');
if CompareStr(tmpStr, S) = 0 then
Exit;
end;
Result := -1;
end;
function TStringsHelper.IndexOfPiece(const S: string; OffSet: Integer = 0): Integer;
begin
Result := -1;
if OffSet > GetCount - 1 then
Exit;
for Result := OffSet to GetCount - 1 do
if Pos(Uppercase(S), Uppercase(Strings[Result])) > 0 then
Exit;
Result := -1;
end;
Procedure TStringsHelper.StringsByNum(ReturnList: TStringList; OffSet: Integer = 0; Linecnt: Integer = 1);
var
i: Integer;
begin
for i := OffSet to OffSet + Linecnt do
ReturnList.Add(Strings[i]);
end;
{$ENDREGION}
{$REGION 'TWorker'}
constructor TWorker.Create(const Handler: TThreadPool; aThreadType: tThreadType; const aMasterList: TStringList; const aWrokerID: Integer);
begin
FWorkerID := aWrokerID;
fMasterList := TStringList.Create;
fResultList := TStringList.Create;
fThreadType := aThreadType;
fMasterList.Assign(aMasterList);
case aThreadType of
TYPE_UNIT, TYPE_LINES:
fExtList := TStringList.Create;
end;
fHandler := Handler;
end;
destructor TWorker.Destroy();
begin
FreeAndNil(fMasterList);
FreeAndNil(fResultList);
if assigned(fExtList) then
FreeAndNil(fExtList);
inherited;
end;
procedure TWorker.TakeAction(Sender: TObject);
begin
if assigned(fThreadFunc) then
fThreadFunc(fMasterList, fResultList, fExtList);
end;
procedure TWorker.FireThread;
begin
fHandler.AddTask(TakeAction, nil);
end;
{$ENDREGION}
end.
|
unit plugin.ImportMapData;
interface
uses
plugin,infra.Classes,infra.Geometry,infra.Peds,infra.Types,infra.Trackage,Forms,uGeodata,
Generics.Collections,infra.Manipulation, EuklidMath,infra.E2Visualizer,plugin.Peds;
type
TPluginImportMapData = class(TEditorPlugin)
strict private
FImportMapData : TFrame;
FXmlPath : String;
FExistOsmOrigin : Boolean;
FElevation : Double;
aListofNodes : TList<TNode>;
aListofWays : TList<TWay>;
aListofRelations : TList<TRelation>;
aListofHandles : TDictionary<Int64,TGeometricEntity>;
aListofNodeHandles : TDictionary<Int64,TGeometricEntity>;
aListofTrackNodes : TDictionary<Int64,TOsmElements>;
aListofCommonNodes : TDictionary<Int64,TNode>;
aListofOsmElements : TList<TOsmElements>;
aMinLat : Double;
aMinLon : Double;
aMaxLat : Double;
aMaxLon : Double;
countNodes:Integer;
point : TGE_Point;
segment : TGE_Segment;
spline : TGE_Spline;
polygon : TGE_Polygon;
vectorList : TVector3List;
nodes : TList<TGE_Node>;
function GetInfrastructure: TInfrastructure; inline;
public
property Infrastructure:TInfrastructure read GetInfrastructure;
class function GetCaption (): String; override;
procedure InitializePlugin; override;
procedure ReleasePlugin; override;
function IntegrateToIDE: Boolean; override;
destructor Destroy; override;
procedure setBoundingBox(paMinLat,paMinLon,paMaxLat,paMaxLon :Double);
function getMinLat():Double;
function getMinLon():Double;
function getMaxLat():Double;
function getMaxLon():Double;
function isSpline(paOsmElement: TOsmElements):Boolean;
function existOsmOrigin():Boolean;
procedure setRailways();
procedure loadOsmOrigin();
procedure loadHandles();
procedure OsmVisualize();
procedure XMLParser();
procedure FindInfrastructure(paKey,paValue,paData:String);
procedure setListOfOsmElements(paIndex:Integer;paOsmElement:TOsmElements);
procedure setElevation(paElefvation:double);
procedure setXmlPath(paPath : String);
function StringToCaseSelect(Selector : string;CaseList:array of string): Integer;
function StrToFloat_Decimal(const AStr:String):Double;
function DistanceLatLong(lat1,lon1,lat2,lon2:double):Double;
function Xcoordinate(lon:Double):double;
function Ycoordinate(lat:Double):double;
function getVector(Lon,Lat:TE2Float): TVector3;
function getEle(jsonString:string):string;
function getZ(lat,lon:TE2Float):TE2Float;
procedure cleanStuff;
end;
TED_OsmOrigin = class (TEntityData)
strict private
aLat : Double;
aLon : Double;
private
public
function getLat(): Double;
function getLon(): Double;
procedure setCoordinate(paLat,paLon:Double);
class function CanBeLinkedWithEntity (const Entity: TGeneralEntity; const ReportMessages: Boolean): Boolean; override;
class function GetElementType (): TInfraElement; override;
constructor DirectCreate (const AEntity: TGeneralEntity); override;
end;
implementation
uses
System.SysUtils,frImportMapData,infra.Data,OmniXML,OmniXMLUtils,System.Math,msg,frWebBrowser,
System.Enviroment,REST.Json,System.JSON,plugin.Peds.Visualizator,infra.Colors;
resourcestring
rsPluginImportMapDataCaption = 'Import MapData';
{ TPluginImportMapData }
class function TPluginImportMapData.GetCaption: String;
begin
Result := rsPluginImportMapDataCaption;
end;
function TPluginImportMapData.getEle(jsonString: string): string;
var
text:string;
vJSONScenario: TJSONObject;
begin
vJSONScenario:= TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(jsonString), 0)as TJSONObject;
Result:=vJSONScenario.Values['ele'].Value;
FreeAndNil(vJSONScenario);
end;
function TPluginImportMapData.GetInfrastructure: TInfrastructure;
begin
Result := Editor.GetInfra;
end;
function TPluginImportMapData.getMaxLat: Double;
begin
Result := aMaxLat;
end;
function TPluginImportMapData.getMaxLon: Double;
begin
Result := aMaxLon;
end;
function TPluginImportMapData.getMinLat: Double;
begin
Result := aMinLat;
end;
function TPluginImportMapData.getMinLon: Double;
begin
Result := aMinLon;
end;
function TPluginImportMapData.getVector(Lon, Lat: TE2Float): TVector3;
var
vector : TVector3;
aX : TE2Float;
aY : TE2Float;
aZ : TE2Float;
begin
aX := DistanceLatLong(getMinLat,getMinLon,getMinLat,Lon);
aY := DistanceLatLong(getMinLat,getMinLon,Lat,getMinLon);
//aZ := getZ(Lon,Lat);
aZ := FElevation;
if(Lat < getMinLat )then
begin
aY:=aY*(-1);
end;
if(lon < getMinLon)then
begin
aX:=aX*(-1);
end;
vector := TVector3.Create(aX,aY,aZ);
inc(CountNodes);
Result := vector;
end;
function TPluginImportMapData.getZ(lat,lon:TE2Float): TE2Float;
var
SourceString,DestinationString,jsonString:string;
elevationFile : TextFile;
aZ:TE2Float;
begin
SourceString := 'http://www.freemap.sk/api/0.1/elevation/'+
FloatToStr(lat)+'%7C'+FloatToStr(lon);
DestinationString := GetCommonDataFolder(True)+'importMapData/elevation.txt';
if(frOpenStreetMapForm.DownloadFile(SourceString,DestinationString))then
begin
DestinationString := GetCommonDataFolder(True)+'importMapData/elevation.txt';
AssignFile(elevationFile,DestinationString);
FileMode := fmOpenRead;
Reset(elevationFile);
ReadLn(elevationFile,jsonString);
aZ:=StrToFloat_Decimal(getEle(jsonString));
CloseFile(elevationFile);
DeleteFile(DestinationString);
end;
Result:=aZ;
end;
procedure TPluginImportMapData.InitializePlugin;
begin
inherited;
FImportMapData := TImportMapDataFrame.Create(nil);
aListofNodes := TList<TNode>.Create;
aListofWays := TList<TWay>.Create;
aListofRelations := TList<TRelation>.Create;
aListofOsmElements := TList<TOsmElements>.Create;
countNodes:=0;
end;
function TPluginImportMapData.IntegrateToIDE: Boolean;
begin
(FImportMapData as TImportMapDataFrame).Init(Self);
// put toolbar to main form
(FImportMapData as TImportMapDataFrame).sptbxToolbarMap.CurrentDock := Editor.GetToolbarDock();
// set toolbar position
(FImportMapData as TImportMapDataFrame).sptbxToolbarMap.DockRow := 1;
(FImportMapData as TImportMapDataFrame).sptbxToolbarMap.DockPos := 8;
end;
function TPluginImportMapData.isSpline(paOsmElement: TOsmElements): Boolean;
begin
if (paOsmElement.getData = 'TED_Track')or
(paOsmElement.getData = 'TED_Building')or
(paOsmElement.getData = 'TED_Road')or
(paOsmElement.getData = 'TED_PedWallSpline')
then
Result := True
else
Result := False;
end;
procedure TPluginImportMapData.loadHandles;
var
i:Integer;
key : Int64;
value : TGeometricEntity;
begin
aListofNodeHandles := TDictionary<Int64,TGeometricEntity>.Create;
if(existOsmOrigin)then
begin
aListofHandles := TDictionary<Int64,TGeometricEntity>.Create;
for I := 0 to Infrastructure.Entities.Count - 1 do
begin
if(Infrastructure.Entities[i] is TGE_Spline)and((Infrastructure.Entities[i] as TGE_Spline).DXFHandle <> 0)then
begin
key := (Infrastructure.Entities[i] as TGE_Spline).DXFHandle;
value := (Infrastructure.Entities[i] as TGE_Spline);
if (not(aListofHandles.ContainsKey(key))) then
aListofHandles.Add(key,value);
end;
if(Infrastructure.Entities[i] is TGE_Polygon)and((Infrastructure.Entities[i] as TGE_Polygon).DXFHandle <> 0)then
begin
key := (Infrastructure.Entities[i] as TGE_Polygon).DXFHandle;
value := (Infrastructure.Entities[i] as TGE_Polygon);
aListofHandles.Add(key,value);
end;
if(Infrastructure.Entities[i] is TGE_Node)and((Infrastructure.Entities[i] as TGE_Node).DXFHandle <> 0)then
begin
key := (Infrastructure.Entities[i] as TGE_Node).DXFHandle;
value := (Infrastructure.Entities[i] as TGE_Node);
aListofNodeHandles.Add(key,value);
end;
end;
end;
end;
procedure TPluginImportMapData.loadOsmOrigin;
var
i : integer;
Lat : Double;
Lon : Double;
begin
for I := 0 to Infrastructure.Entities.Count - 1 do
begin
if(Infrastructure.Entities[i] is TGE_Point)then
begin
if(Infrastructure.Entities[i].Data is TED_OsmOrigin)then
begin
Lat := (Infrastructure.Entities[i].Data as TED_OsmOrigin).getLat;
Lon := (Infrastructure.Entities[i].Data as TED_OsmOrigin).getLon;
setBoundingBox(Lat,Lon,aMaxLat,aMaxLon);
end;
end;
end;
end;
procedure TPluginImportMapData.ReleasePlugin;
var
i:integer;
begin
inherited;
// release toolbar from main form
(FImportMapData as TImportMapDataFrame).sptbxToolbarMap.CurrentDock := (FImportMapData as TImportMapDataFrame).sptbxDockMapsData;
// release source frame
(FImportMapData as TImportMapDataFrame).Finalize;
FreeAndNil(FImportMapData);
if((frOpenStreetMapForm<>nil) and (frOpenStreetMapForm.WebBrowserOsm <>nil))then
FreeAndNil(frOpenStreetMapForm);
if(aListofNodes.Count > 0)then
begin
for i := 0 to aListofNodes.Count - 1 do
aListofNodes.Items[i].Free;
end;
if(aListofWays.Count > 0) then
begin
for i := 0 to aListofWays.Count - 1 do
aListofWays.Items[i].Free;
end;
if (aListofRelations.Count > 0) then
begin
for i := 0 to aListofRelations.Count - 1 do
aListofRelations.Items[i].Free;
end;
if aListofOsmElements.Count > 0 then
begin
for i := 0 to aListofOsmElements.Count - 1 do
aListofOsmElements.Items[i].Free;
end;
aListofNodes.Free;
aListofWays.Free;
aListofRelations.Free;
aListofOsmElements.Free;
end;
procedure TPluginImportMapData.setBoundingBox(paMinLat, paMinLon, paMaxLat,
paMaxLon: Double);
begin
aMinLat := paMinLat;
aMinLon := paMinLon;
aMaxLat := paMaxLat;
aMaxLon := paMaxLon;
end;
procedure TPluginImportMapData.setElevation(paElefvation: double);
begin
if(paElefvation > 0)then
FElevation:= paElefvation
else
FElevation:=0;
end;
procedure TPluginImportMapData.setXmlPath(paPath: String);
begin
FXmlPath := paPath;
end;
procedure TPluginImportMapData.OsmVisualize;
var
Lon : TE2Float;
Lat : TE2Float;
vector : TVector3;
entities : TGeneralEntityList;
visualizeList : TGeneralEntityList;
node : TGE_Node;
i,j: Integer;
paOsmElement : TOsmElements;
begin
(FImportMapData as TImportMapDataFrame).Init(Self);
entities := TGeneralEntityList.Create;
visualizeList := TGeneralEntityList.Create;
for i := 0 to aListofOsmElements.Count - 1 do
begin
vectorList := TVector3List.Create;
nodes := TList<TGE_Node>.Create;
paOsmElement := aListofOsmElements.Items[i];
for j := 0 to paOsmElement.sizeofNodes - 1 do
begin
Lat := StrToFloat_Decimal(paOsmElement.getNodeItem(j).getLat);
Lon := StrToFloat_Decimal(paOsmElement.getNodeItem(j).getLon);
vector := getVector(Lon,Lat);
vectorList.Add(vector);
if(isSpline(paOsmElement))then
begin
if(aListofNodeHandles.ContainsKey(StrToInt64(paOsmElement.getNodeItem(j).getID)))
then
begin
node := ((aListofNodeHandles.Items[StrToInt64(paOsmElement.getNodeItem(j).getID)])as TGE_Node);
nodes.Add(node);
end
else
begin
node := TGE_Node.DirectCreate(Infrastructure);
node.Position:= vector;
TED_Node.DirectCreate(node);
node.DXFHandle :=StrToInt64(paOsmElement.getNodeItem(j).getID);
node.Insert;
aListofNodeHandles.Add(node.DXFHandle,node);
nodes.Add(node);
end;
end;
end;
if(paOsmElement.getData = 'TED_Road' )then
begin
if(FExistOsmOrigin)then
begin
if not(aListofHandles.ContainsKey(StrToInt64(paOsmElement.getID))) then
begin
spline := CreateInfraSpline(Infrastructure,nodes,TED_RoadSegment,TED_Road);
spline.DXFHandle := StrToInt64(paOsmElement.getID);
entities.Add(spline);
end;
end
else
begin
spline := CreateInfraSpline(Infrastructure,nodes,TED_RoadSegment,TED_Road);
spline.DXFHandle := StrToInt64(paOsmElement.getID);
entities.Add(spline);
end;
nodes.Free;
vectorList.Free;
end;
if(paOsmElement.getData = 'TED_PedStair' )then
begin
if(FExistOsmOrigin)then
begin
if not(aListofHandles.ContainsKey(StrToInt64(paOsmElement.getID))) then
begin
spline := CreateInfraSpline(Infrastructure,vectorList,TED_PedStairNode,TED_PedStairSegment,TED_PedStair);
spline.DXFHandle:= StrToInt64(paOsmElement.getID);
entities.Add(spline);
end;
end
else
begin
spline := CreateInfraSpline(Infrastructure,vectorList,TED_PedStairNode,TED_PedStairSegment,TED_PedStair);
spline.DXFHandle:= StrToInt64(paOsmElement.getID);
entities.Add(spline);
end;
nodes.Free;
vectorList.Free;
end;
if(paOsmElement.getData = 'TED_Building' )then
begin
if(FExistOsmOrigin)then
begin
if not(aListofHandles.ContainsKey(StrToInt64(paOsmElement.getID))) then
begin
spline := CreateInfraSpline(Infrastructure,nodes,TED_BuildingSegment,TED_Building);
spline.DXFHandle:= StrToInt64(paOsmElement.getID);
entities.Add(spline);
end;
end
else
begin
spline := CreateInfraSpline(Infrastructure,nodes,TED_BuildingSegment,TED_Building);
spline.DXFHandle:= StrToInt64(paOsmElement.getID);
entities.Add(spline);
end;
nodes.Free;
vectorList.Free;
end;
if(paOsmElement.getData = 'TED_PedWall' )then
begin
if(FExistOsmOrigin)then
begin
if not(aListofHandles.ContainsKey(StrToInt64(paOsmElement.getID))) then
begin
polygon := CreateInfraPolygon(Infrastructure,vectorList,TED_Node,TED_PedWallSegment,TED_PedWallSpline,TED_PedWall);
polygon.DXFHandle := StrToInt64(paOsmElement.getID);
entities.Add(polygon);
end;
end
else
begin
polygon := CreateInfraPolygon(Infrastructure,vectorList,TED_Node,TED_PedWallSegment,TED_PedWallSpline,TED_PedWall);
polygon.DXFHandle := StrToInt64(paOsmElement.getID);
entities.Add(polygon);
end;
nodes.Free;
vectorList.Free;
end;
if(paOsmElement.getData = 'TED_Track')then
begin
if(FExistOsmOrigin)then
begin
if not(aListofHandles.ContainsKey(StrToInt64(paOsmElement.getID))) then
begin
spline := CreateInfraSpline(Infrastructure,nodes,TED_TrackSegment,TED_Track);
spline.DXFHandle := StrToInt64(paOsmElement.getID);
entities.Add(spline);
end;
end else
begin
spline := CreateInfraSpline(Infrastructure,nodes,TED_TrackSegment,TED_Track);
spline.DXFHandle := StrToInt64(paOsmElement.getID);
entities.Add(spline);
end;
nodes.Free;
vectorList.Free;
end;
if(paOsmElement.getData = 'TED_PedWallSpline' )then
begin
if(FExistOsmOrigin)then
begin
if not(aListofHandles.ContainsKey(StrToInt64(paOsmElement.getID))) then
begin
spline := CreateInfraSpline(Infrastructure,nodes,TED_PedWallSegment,TED_PedWallSpline);
spline.DXFHandle := StrToInt64(paOsmElement.getID);
entities.Add(spline);
end;
end
else
begin
spline := CreateInfraSpline(Infrastructure,nodes,TED_PedWallSegment,TED_PedWallSpline);
spline.DXFHandle := StrToInt64(paOsmElement.getID);
entities.Add(spline);
end;
nodes.Free;
vectorList.Free;
end;
end;
TE2InfrastructureVisualizer.ExpandListForVisualization(entities,visualizeList);
Editor.GetVisualizer.PerformOnEntities(visualizeList);
entities.Free;
visualizeList.Free;
aListofHandles.Free;
aListofNodeHandles.Free;
if(not(FExistOsmOrigin))then
begin
vector := getVector(aMinLon,aMinLat);
point := TGE_Point.DirectCreateWithVector(Infrastructure,vector);
TED_OsmOrigin.DirectCreate(point);
if (point.Data is TED_OsmOrigin)then
(point.Data as TED_OsmOrigin).setCoordinate(getMinLat,getMinLon);
Lat:= (point.Data as TED_OsmOrigin).getLat;
Lon:= (point.Data as TED_OsmOrigin).getLon;
point.Insert;
end;
end;
procedure TPluginImportMapData.XMLParser;
var
xmlDoc : IXMLDocument;
element : IXMLNode;
element2 : IXMLNode;
countOfNodes : integer;
i,j,k,l : integer;
node : TNode;
way : TWay;
relation : TRelation;
tag : TTag;
nd : TNd;
member : TMember;
countOfWays : Integer;
countOfRelation:Integer;
NodesCount : Integer;
minlat:Double;
minlon:Double;
maxlat:Double;
maxlon:Double;
begin
countOfWays :=0;
countOfRelation :=0;
NodesCount :=0;
xmlDoc := CreateXMLDoc;
xmlDoc.Load(FXmlPath);
if(FileExists(GetCommonDataFolder(True)+'importMapData/osm.xml'))then
DeleteFile(GetCommonDataFolder(True)+'importMapData/osm.xml');
minlat := StrToFloat_Decimal(xmlDoc.DocumentElement.ChildNodes.FindNode('bounds').Attributes.GetNamedItem('minlat').Value);
minlon := StrToFloat_Decimal(xmlDoc.DocumentElement.ChildNodes.FindNode('bounds').Attributes.GetNamedItem('minlon').Value);
maxlat := StrToFloat_Decimal(xmlDoc.DocumentElement.ChildNodes.FindNode('bounds').Attributes.GetNamedItem('maxlat').Value);
maxlon := StrToFloat_Decimal(xmlDoc.DocumentElement.ChildNodes.FindNode('bounds').Attributes.GetNamedItem('maxlon').Value);
setBoundingBox(minlat,minlon,maxlat,maxlon);
if(FExistOsmOrigin)then
loadOsmOrigin;
countOfNodes := xmlDoc.DocumentElement.ChildNodes.Count;
for I := 1 to countOfNodes-1 do
begin
element := xmlDoc.DocumentElement.ChildNodes.Get(i);
case StringToCaseSelect(xmlDoc.DocumentElement.ChildNodes.Get(i).NodeName,['node','way','relation']) of
0:
begin
node := TNode.Create(element.Attributes.GetNamedItem('id').Value,
element.Attributes.GetNamedItem('lon').Value,
element.Attributes.GetNamedItem('lat').Value);
aListofNodes.Add(node);
inc(NodesCount);
end;
1:
begin
way := TWay.Create(element.Attributes.GetNamedItem('id').Value);
aListofWays.Add(way);
inc(countOfWays);
end;
2:
begin
relation := TRelation.Create(element.Attributes.GetNamedItem('id').Value);
aListofRelations.Add(relation);
inc(countOfRelation);
end;
end;
if(xmlDoc.DocumentElement.ChildNodes.Get(i).HasChildNodes)then
begin
case StringToCaseSelect(xmlDoc.DocumentElement.ChildNodes.Get(i).NodeName,['node','way','relation']) of
0 : begin
for j := 0 to xmlDoc.DocumentElement.ChildNodes.Get(i).ChildNodes.Count - 1 do
begin
element2 := xmlDoc.DocumentElement.ChildNodes.Get(i).ChildNodes.Get(j);
tag := TTag.Create(element2.Attributes.GetNamedItem('k').Value,
element2.Attributes.GetNamedItem('v').Value);
aListofNodes[NodesCount-1].AddTagItem(tag);
end;
end;
1 : begin
for k := 0 to xmlDoc.DocumentElement.ChildNodes.Get(i).ChildNodes.Count - 1 do
begin
if(xmlDoc.DocumentElement.ChildNodes.Get(i).ChildNodes.Get(k).NodeName='tag')
then
begin
element2 := xmlDoc.DocumentElement.ChildNodes.Get(i).ChildNodes.Get(k);
tag := TTag.Create(element2.Attributes.GetNamedItem('k').Value,
element2.Attributes.GetNamedItem('v').Value);
aListofWays[countOfWays-1].AddTagItem(tag);
end
else
begin
element2 := xmlDoc.DocumentElement.ChildNodes.Get(i).ChildNodes.Get(k);
nd := TNd.Create(element2.Attributes.GetNamedItem('ref').Value);
aListofWays[countOfWays-1].AddNdItem(nd);
end;
end;
end;
2 : begin
for l := 0 to xmlDoc.DocumentElement.ChildNodes.Get(i).ChildNodes.Count - 1 do
begin
if(xmlDoc.DocumentElement.ChildNodes.Get(i).ChildNodes.Get(l).NodeName='tag')
then
begin
element2 := xmlDoc.DocumentElement.ChildNodes.Get(i).ChildNodes.Get(l);
tag := TTag.Create(element2.Attributes.GetNamedItem('k').Value,
element2.Attributes.GetNamedItem('v').Value);
aListofRelations[countOfRelation-1].AddTagItem(tag);
end
else
begin
element2 := xmlDoc.DocumentElement.ChildNodes.Get(i).ChildNodes.Get(l);
member := TMember.Create(element2.Attributes.GetNamedItem('type').Value,
element2.Attributes.GetNamedItem('ref').Value,
element2.Attributes.GetNamedItem('role').Value);
aListofRelations[countOfRelation-1].AddMemberItem(member);
end;
end;
end;
end;
end;
end;
xmlDoc:=nil;
end;
function TPluginImportMapData.Xcoordinate(lon:double): double;
var
minlat:Double;
minlon:Double;
begin
minlat := getMinLat;
minlon := getMinLon;
Result := DistanceLatLong(minlat,minlon,minlat,lon);
end;
function TPluginImportMapData.Ycoordinate(lat:double): double;
var
minlat:Double;
minLon:Double;
begin
minlat := getMinLat;
minLon := getMinLon;
Result := DistanceLatLong(minlat,minLon,lat,minlon);
end;
procedure TPluginImportMapData.cleanStuff;
var
i:integer;
begin
if(aListofNodes.Count > 0)then
begin
for i := 0 to aListofNodes.Count - 1 do
aListofNodes.Items[i].Free;
end;
if(aListofWays.Count > 0) then
begin
for i := 0 to aListofWays.Count - 1 do
aListofWays.Items[i].Free;
end;
if (aListofRelations.Count > 0) then
begin
for i := 0 to aListofRelations.Count - 1 do
aListofRelations.Items[i].Free;
end;
if aListofOsmElements.Count > 0 then
begin
for i := 0 to aListofOsmElements.Count - 1 do
aListofOsmElements.Items[i].Free;
end;
aListofNodes.Free;
aListofWays.Free;
aListofRelations.Free;
aListofOsmElements.Free;
aListofNodes := TList<TNode>.Create;
aListofWays := TList<TWay>.Create;
aListofRelations := TList<TRelation>.Create;
aListofOsmElements := TList<TOsmElements>.Create;
end;
destructor TPluginImportMapData.Destroy;
begin
inherited;
end;
procedure TPluginImportMapData.setRailways;
var
i:Integer;
FAktualElement: TOsmElements;
FEnteredElement: TOsmElements;
FNewElement : TOsmElements;
j,l,k,m,n: Integer;
indexFirst:Integer;
commonNode: TNode;
begin
aListofTrackNodes := TDictionary<Int64,TOsmElements>.Create;
aListofCommonNodes:= TDictionary<Int64,TNode>.Create;
// for I := 0 to aListofOsmElements.Count - 1 do
m:= aListofOsmElements.Count;
while (i < (m)) do
begin
if (aListofOsmElements.Items[i].getData = 'TED_Track') then
begin
FAktualElement:= aListofOsmElements.Items[i];
for j := 0 to FAktualElement.sizeofNodes - 1 do
begin
if(aListofTrackNodes.ContainsKey(StrToInt64(FAktualElement.getNodeItem(j).getID)))then
begin
FEnteredElement := aListofTrackNodes.Items[StrToInt64(FAktualElement.getNodeItem(j).getID)];
if((not (FAktualElement.isEdgeNode(FAktualElement.getNodeItem(j)))) and (FEnteredElement.isEdgeNode(FAktualElement.getNodeItem(j)))) then
begin
FNewElement := TOsmElements.Create(FAktualElement.getCaption,FAktualElement.getValue,FAktualElement.getData);
FNewElement.setID(FAktualElement.getID);
for l := 0 to FAktualElement.sizeofNodes - 1 do
begin
if(FAktualElement.getNodeItem(l).getID = FAktualElement.getNodeItem(j).getID)then
begin
if not(aListofCommonNodes.ContainsKey(StrtoInt64(FAktualElement.getNodeItem(j).getID)))then
aListofCommonNodes.Add(StrtoInt64(FAktualElement.getNodeItem(l).getID),FAktualElement.getNodeItem(l));
for k := l to FAktualElement.sizeofNodes - 1 do
begin
FNewElement.AddNodeItem(FAktualElement.getNodeItem(k));
if(k=l)then
begin
aListofTrackNodes.Remove(StrToInt64(FAktualElement.getNodeItem(k).getID));
aListofTrackNodes.Add(StrToInt64(FAktualElement.getNodeItem(k).getID),FNewElement);
end;
end;
aListofOsmElements.Add(FNewElement);
FAktualElement.removeNodesFrom(l+1,FAktualElement.sizeofNodes -(l+1));
Inc(m);
Break;
end;
end;
if not (aListofOsmElements.Contains(FNewElement)) then
FNewElement.Free;
end;
if(((FAktualElement.isEdgeNode(FAktualElement.getNodeItem(j)))) and (not (FEnteredElement.isEdgeNode(FAktualElement.getNodeItem(j))))) then
begin
FNewElement := TOsmElements.Create(FEnteredElement.getCaption,FEnteredElement.getValue,FEnteredElement.getData);
FNewElement.setID(FEnteredElement.getID);
for l := 0 to FEnteredElement.sizeofNodes - 1 do
begin
if not(aListofCommonNodes.ContainsKey(StrtoInt64(FAktualElement.getNodeItem(j).getID)))then
aListofCommonNodes.Add(StrtoInt64(FAktualElement.getNodeItem(j).getID),FAktualElement.getNodeItem(l));
if(FEnteredElement.getNodeItem(l).getID = FAktualElement.getNodeItem(j).getID)then
begin
for k := l to FEnteredElement.sizeofNodes - 1 do
begin
FNewElement.AddNodeItem(FEnteredElement.getNodeItem(k));
aListofTrackNodes.Remove(StrToInt64(FEnteredElement.getNodeItem(k).getID));
aListofTrackNodes.Add(StrToInt64(FEnteredElement.getNodeItem(k).getID),FNewElement);
end;
aListofOsmElements.Add(FNewElement);
FEnteredElement.removeNodesFrom(l+1,FEnteredElement.sizeofNodes -(l+1));
Inc(m);
Break;
end;
end;
if not (aListofOsmElements.Contains(FNewElement)) then
FNewElement.Free;
end;
if((not(FAktualElement.isEdgeNode(FAktualElement.getNodeItem(j)))) and (not(FEnteredElement.isEdgeNode(FAktualElement.getNodeItem(j))))) then
begin
FNewElement := TOsmElements.Create(FEnteredElement.getCaption,FEnteredElement.getValue,FEnteredElement.getData);
FNewElement.setID(FEnteredElement.getID);
for l := 0 to FEnteredElement.sizeofNodes - 1 do
begin
if not(aListofCommonNodes.ContainsKey(StrtoInt64(FAktualElement.getNodeItem(j).getID)))then
aListofCommonNodes.Add(StrtoInt64(FAktualElement.getNodeItem(j).getID),FAktualElement.getNodeItem(j));
if(FEnteredElement.getNodeItem(l).getID = FAktualElement.getNodeItem(j).getID)then
begin
for k := l to FEnteredElement.sizeofNodes - 1 do
begin
FNewElement.AddNodeItem(FEnteredElement.getNodeItem(k));
aListofTrackNodes.Remove(StrToInt64(FEnteredElement.getNodeItem(k).getID));
aListofTrackNodes.Add(StrToInt64(FEnteredElement.getNodeItem(k).getID),FNewElement);
end;
aListofOsmElements.Add(FNewElement);
FEnteredElement.removeNodesFrom(l+1,FEnteredElement.sizeofNodes -(l+1));
inc(m);
Break;
end;
end;
if not (aListofOsmElements.Contains(FNewElement)) then
FNewElement.Free;
FNewElement := TOsmElements.Create(FAktualElement.getCaption,FAktualElement.getValue,FAktualElement.getData);
FNewElement.setID(FAktualElement.getID);
for l := 0 to FAktualElement.sizeofNodes - 1 do
begin
if not(aListofCommonNodes.ContainsKey(StrtoInt64(FAktualElement.getNodeItem(l).getID)))then
aListofCommonNodes.Add(StrtoInt64(FAktualElement.getNodeItem(l).getID),FAktualElement.getNodeItem(l));
if (FAktualElement.getNodeItem(l).getID = FAktualElement.getNodeItem(j).getID)then
begin
for k := l to FAktualElement.sizeofNodes - 1 do
begin
FNewElement.AddNodeItem(FAktualElement.getNodeItem(k));
if(k=l)then
begin
aListofTrackNodes.Remove(StrToInt64(FAktualElement.getNodeItem(k).getID));
aListofTrackNodes.Add(StrToInt64(FAktualElement.getNodeItem(k).getID),FNewElement);
end;
end;
aListofOsmElements.Add(FNewElement);
FAktualElement.removeNodesFrom(l+1,FAktualElement.sizeofNodes -(l+1));
Inc(m);
Break;
end;
end;
if not (aListofOsmElements.Contains(FNewElement)) then
FNewElement.Free;
end;
Break;
end else
begin
aListofTrackNodes.Add(StrToInt64(FAktualElement.getNodeItem(j).getID),FAktualElement);
end;
end;
end;
Inc(i);
end;
aListofCommonNodes.Free;
aListofTrackNodes.Free;
end;
procedure TPluginImportMapData.setListOfOsmElements(paIndex: Integer;
paOsmElement: TOsmElements);
var
j,l:Integer;
begin
if (aListofWays.Items[paIndex].OwnsNd)then
begin
for j := 0 to aListofWays.Items[paIndex].sizeofNd -1 do
begin
for l := 0 to aListofNodes.Count - 1 do
begin
if(aListofNodes.Items[l].getID = aListofWays.Items[paIndex].getNd(j).getRef)then
begin
paOsmElement.AddNodeItem(aListofNodes.Items[l]);
end;
end;
end;
end;
aListofOsmElements.Add(paOsmElement);
end;
procedure TPluginImportMapData.FindInfrastructure(paKey,paValue,paData : String);
var
j,k,l,i : Integer;
FOsmElement : TOsmElements;
FTag : TTag;
begin
if (aListofWays.Count >0)then
begin
for i := 0 to aListofWays.Count -1 do
begin
if(aListofWays.Items[i].OwnsTag)then
begin
for k := 0 to aListofWays.Items[i].sizeofTags -1 do
begin
FTag:= aListofWays.Items[i].getTag(k);
if((paKey ='highway') and (FTag.getKey = paKey) and (FTag.getValue = paValue))then
begin
FOsmElement := TOsmElements.Create(paKey,paValue,paData);
FOsmElement.setID(aListofWays.Items[i].getID);
setListOfOsmElements(i,FOsmElement);
end
else if (paKey = 'building')and(FTag.getKey = paKey)and(FTag.getValue = paValue)then
begin
FOsmElement := TOsmElements.Create(paKey,paValue,paData);
FOsmElement.setID(aListofWays.Items[i].getID);
setListOfOsmElements(i,FOsmElement);
end
else if (paKey = 'railway')and(FTag.getKey = paKey)and(FTag.getValue = paValue) then
begin
FOsmElement := TOsmElements.Create(paKey,paValue,paData);
FOsmElement.setID(aListofWays.Items[i].getID);
setListOfOsmElements(i,FOsmElement);
end
else if (paKey = 'barrier')and(FTag.getKey = paKey)and(FTag.getValue = paValue) then
begin
FOsmElement := TOsmElements.Create(paKey,paValue,paData);
FOsmElement.setID(aListofWays.Items[i].getID);
setListOfOsmElements(i,FOsmElement);
end;
end;
end;
end;
end;
end;
function TPluginImportMapData.StringToCaseSelect(Selector: string;
CaseList: array of string): Integer;
var cnt: integer;
begin
Result:=-1;
for cnt:=0 to Length(CaseList)-1 do
begin
if CompareText(Selector, CaseList[cnt]) = 0 then
begin
Result:=cnt;
Break;
end;
end;
end;
function TPluginImportMapData.StrToFloat_Decimal(const AStr: String): Double;
var
FS: TFormatSettings;
begin
FS.Create('en-UK');
FS.DecimalSeparator :='.';
Result:= StrToFloat(AStr, FS);
end;
function TPluginImportMapData.DistanceLatLong(lat1, lon1, lat2,
lon2: double): Double;
var
dLat, dLon, a, c, radius: double;
begin
radius := 6378.137;
dLat := DegToRad(lat2 - lat1);
dLon := DegToRad(lon2 - lon1);
a := sin(dLat / 2) * sin(dLat / 2) + cos(DegToRad(lat1)) * cos(DegToRad(lat2)) * sin(dLon / 2) * sin(dLon / 2);
c := 2 * Arcsin(Sqrt(a));
Result := radius * c * 1000;
end;
function TPluginImportMapData.existOsmOrigin: Boolean;
var
i:Integer;
begin
for I := 0 to Infrastructure.Entities.Count - 1 do
begin
if(Infrastructure.Entities[i] is TGE_Point)then
begin
if(Infrastructure.Entities[i].Data is TED_OsmOrigin)then
begin
Result := True;
FExistOsmOrigin:=True;
Exit;
end;
end;
end;
FExistOsmOrigin:=False;
Result := False;
end;
{ TED_OsmOrigin }
class function TED_OsmOrigin.CanBeLinkedWithEntity(const Entity: TGeneralEntity;
const ReportMessages: Boolean): Boolean;
begin
Result := (Entity is TGE_Point);
if (not Result) and ReportMessages then
ReportMessage('OsmOrigin nemoze byt linkovany s objektom "' + Entity.ClassName + '"!')
end;
constructor TED_OsmOrigin.DirectCreate(const AEntity: TGeneralEntity);
begin
inherited;
end;
class function TED_OsmOrigin.GetElementType: TInfraElement;
begin
Result := ieOsmOrigin;
end;
function TED_OsmOrigin.getLat: Double;
begin
Result := aLat;
end;
function TED_OsmOrigin.getLon: Double;
begin
Result := aLon;
end;
procedure TED_OsmOrigin.setCoordinate(paLat, paLon: Double);
begin
aLat := paLat;
aLon := paLon;
end;
end.
|
UNIT Animation;
{$MODE Delphi}
INTERFACE
TYPE TAnimation = CLASS
PUBLIC
CONSTRUCTOR create(_offset, _frames, _duration : INTEGER; _loops : BOOLEAN);
PROCEDURE advance();
FUNCTION start() : TAnimation;
FUNCTION resume(other : TAnimation) : TAnimation;
FUNCTION isOver() : BOOLEAN;
FUNCTION getSpriteId() : INTEGER;
PRIVATE
loops : BOOLEAN;
current_frame : INTEGER;
sprite_offset : INTEGER;
total_frames : INTEGER;
total_duration : INTEGER;
END;
IMPLEMENTATION
CONSTRUCTOR TAnimation.create(_offset, _frames, _duration : INTEGER; _loops : BOOLEAN);
BEGIN
sprite_offset := _offset;
total_frames := _frames;
total_duration := _duration;
current_frame := 0;
loops := _loops;
END;
PROCEDURE TAnimation.advance();
BEGIN
IF loops THEN
current_frame := (current_frame+1) MOD (total_frames*total_duration)
ELSE
IF current_frame < total_frames*total_duration-1 THEN
current_frame := current_frame + 1;
END;
FUNCTION TAnimation.start() : TAnimation;
BEGIN
current_frame := 0;
start := self;
END;
FUNCTION TAnimation.resume(other : TAnimation) : TAnimation;
BEGIN
current_frame := (other.current_frame) MOD (total_frames*total_duration);
resume := self;
END;
FUNCTION TAnimation.isOver() : BOOLEAN;
BEGIN
isOver := (NOT loops) AND (current_frame = total_frames*total_duration-1);
END;
FUNCTION TAnimation.getSpriteId() : INTEGER;
BEGIN
getSpriteId := sprite_offset + current_frame DIV total_duration;
END;
END.
|
unit UServerMethods;
interface
uses
SysUtils, Classes, DSServer, WideStrings, ADODB, DB, Provider, DBClient,
IniFiles, Variants;
type
TServerMethods = class(TDSServerModule)
dspPublic: TDataSetProvider;
ConMain: TADOConnection;
QryPublic: TADOQuery;
QryExecute: TADOQuery;
procedure DSServerModuleCreate(Sender: TObject);
procedure DSServerModuleDestroy(Sender: TObject);
private
FErrorCode: Integer;
FErrorText: string;
procedure InitErrorMsg;
// 事务控制
function BeginTrans: Boolean;
function CommitTrans: Boolean;
function InTransaction: Boolean;
function RollbackTrans: Boolean;
function ConnectDB: Boolean;
public
function EchoString(Value: string): string;
// 获取服务器信息函数
function GetServerDateTime(var Value: TDateTime): Boolean;
procedure GetServerLastError(var ErrorCode: Integer; var ErrorText: string);
// 数据操作(DML)语句
function ReadDataSet(AStrSql: string; var AData: OleVariant): Boolean;
function ReadMultipleDataSets(ASqlArr: OleVariant; var ADataArr: OleVariant): Boolean;
function ReadTableHead(TableName: string; var Data: OleVariant): Boolean;
function QueryData(AStrSql: string; APageSize, APageNo: Integer;
var AData: OleVariant): Boolean;
function GetSQLStringValue(const AStrSql: string; var Value: string): Boolean;
function GetSQLIntegerValue(const AStrSql: string; var Value: Integer): Boolean;
// function GetBillCode(TableName, KeyFieldName, Prefix: string;
// ALength: Integer; var NewBillCode: string): Boolean;
function DataSetIsEmpty(const AStrSql: string): Integer;
function ApplyUpdates(const TableName: string; Delta: OleVariant;
var ErrorCount: Integer): Boolean;
function ExecuteSQL(AStrSql: string): Boolean;
function ExecuteBatchSQL(AList: TStream): Boolean;
// 实现传递参数列表
procedure ParamsMethod(InParams: TParams; out OutParams: TParams);
end;
implementation
uses UGlobalVar, UErrorConst;
{$R *.dfm}
function TServerMethods.ApplyUpdates(const TableName: string; Delta: OleVariant;
var ErrorCount: Integer): Boolean;
begin
InitErrorMsg;
try
QryPublic.Close;
try
QryPublic.SQL.Text := Format('select * from %s where 1=0', [TableName]);
QryPublic.Open;
dspPublic.ApplyUpdates(Delta, 0, ErrorCount);
Result := ErrorCount = 0;
finally
QryPublic.Close;
end;
except
on E: Exception do
begin
Result := False;
FErrorCode := ERRCODE_SERVER_ApplyUpdates;
FErrorText := E.Message;
end;
end;
end;
function TServerMethods.BeginTrans: Boolean;
begin
try
if not InTransaction then
ConMain.BeginTrans;
Result := True;
except
Result := False;
end;
end;
function TServerMethods.CommitTrans: Boolean;
begin
try
if InTransaction then
ConMain.CommitTrans;
Result := True;
except
Result := False;
end;
end;
function TServerMethods.InTransaction: Boolean;
begin
Result := ConMain.InTransaction;
end;
/// <summary>
/// 分页查询数据
/// </summary>
/// <param name="AStrSql">查询数据的SQL</param>
/// <param name="APageSize">每页数据条数</param>
/// <param name="APageNo">页号</param>
/// <param name="AData">返回的数据容器</param>
/// <returns>执行成功返回True,失败False</returns>
function TServerMethods.QueryData(AStrSql: string; APageSize, APageNo: Integer;
var AData: OleVariant): Boolean;
begin
Result := False;
if (APageSize = 0) or (APageNo = 0) then
Result := ReadDataSet(AStrSql, AData)
else
begin
try
except
end;
end;
end;
function TServerMethods.RollbackTrans: Boolean;
begin
try
if InTransaction then
ConMain.RollbackTrans;
Result := True;
except
Result := False;
end;
end;
/// <summary>
/// 获取服务器时间:1本机时间;2读取数据库服务器时间
/// </summary>
/// <param name="Value">返回获取到的服务器时间</param>
/// <returns></returns>
function TServerMethods.GetServerDateTime(var Value: TDateTime): Boolean;
begin
try
Value := Now;
Result := True;
except
on E: Exception do
begin
Result := False;
FErrorCode := ERRCODE_SERVER_GetServerDateTime;
FErrorText := E.Message;
end;
end;
end;
/// <summary>
/// 根据传入的SQL判断数据集是否为空
/// </summary>
/// <param name="AStrSql">传入的SQL语句</param>
/// <returns>1:数据集为空;0数据集不为空;-1出现异常</returns>
function TServerMethods.DataSetIsEmpty(const AStrSql: string): Integer;
begin
InitErrorMsg;
try
QryPublic.Close;
try
QryPublic.SQL.Text := AStrSql;
QryPublic.Open;
if QryPublic.IsEmpty then
Result := 1
else
Result := 0;
finally
QryPublic.Close;
end;
except
on E: Exception do
begin
Result := -1;
FErrorCode := ERRCODE_SERVER_DataSetIsEmpty;
FErrorText := E.Message;
end;
end;
end;
function TServerMethods.ConnectDB: Boolean;
const
DBConnectString = 'Provider=SQLOLEDB.1;Password=%s;' +
'Persist Security Info=True;User ID=%s;Initial Catalog=%s;Data Source=%s';
var
Ini: TIniFile;
lServer, lUser, lPass, lDBName: string;
begin
Ini := TIniFile.Create(GLB.AppPath + 'config\database.ini');
try
lServer := Ini.ReadString('DBLink', 'Server', '');
lUser := Ini.ReadString('DBLink', 'User', '');
lPass := Ini.ReadString('DBLink', 'Pass', '');
lDBName := Ini.ReadString('DBLink', 'DBName', '');
finally
Ini.Free;
end;
ConMain.Connected := False;
ConMain.ConnectionString := Format(DBConnectString, [lPass, lUser,
lDBName, lServer]);
try
ConMain.Connected := True;
Result := ConMain.Connected;
except
on E: Exception do
begin
Result := False;
FErrorCode := ERRCODE_SERVER_ConnectDB;
FErrorText := E.Message;
end;
end;
end;
procedure TServerMethods.DSServerModuleCreate(Sender: TObject);
begin
ConnectDB;
end;
procedure TServerMethods.DSServerModuleDestroy(Sender: TObject);
begin
ConMain.Connected := False;
end;
function TServerMethods.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods.ExecuteBatchSQL(AList: TStream): Boolean;
var
I: Integer;
lList: TStringList;
begin
InitErrorMsg;
ConMain.BeginTrans;
try
lList := TStringList.Create;
try
AList.Position := 0;
lList.LoadFromStream(AList);
for I := 0 to lList.Count - 1 do
begin
QryExecute.Close;
QryExecute.SQL.Text := lList[I];
QryExecute.ExecSQL;
end;
ConMain.CommitTrans;
Result := True;
finally
lList.Free;
end;
except
on E: Exception do
begin
ConMain.RollbackTrans;
Result := False;
FErrorCode := ERRCODE_SERVER_ExecuteBatchSQL;
FErrorText := E.Message;
end;
end;
end;
function TServerMethods.ExecuteSQL(AStrSql: string): Boolean;
begin
InitErrorMsg;
try
QryExecute.Close;
QryExecute.SQL.Text := AStrSql;
QryExecute.ExecSQL;
Result := True;
except
on E: Exception do
begin
Result := False;
FErrorCode := ERRCODE_SERVER_ExecuteSQL;
FErrorText := E.Message;
end;
end;
end;
procedure TServerMethods.GetServerLastError(var ErrorCode: Integer; var ErrorText: string);
begin
ErrorCode := FErrorCode;
ErrorText := FErrorText;
InitErrorMsg;
end;
/// <summary>
/// 根据传入的SQL获取整形返回值
/// </summary>
/// <param name="AStrSql">传入的SQL</param>
/// <param name="Value">获取到的整形返回值</param>
/// <returns>异常时返回False</returns>
function TServerMethods.GetSQLIntegerValue(const AStrSql: string;
var Value: Integer): Boolean;
begin
InitErrorMsg;
try
QryPublic.Close;
try
QryPublic.SQL.Text := AStrSql;
QryPublic.Open;
if QryPublic.IsEmpty or QryPublic.Fields[0].IsNull then
Value := 0
else
Value := QryPublic.Fields[0].AsInteger;
Result := True;
finally
QryPublic.Close;
end;
except
on E: Exception do
begin
Result := False;
FErrorCode := ERRCODE_SERVER_GetSQLIntegerValue;
FErrorText := E.Message;
end;
end;
end;
/// <summary>
/// 根据传入的SQL获取字符串返回值
/// </summary>
/// <param name="AStrSql">传入的SQL</param>
/// <param name="Value">获取到的字符串返回值</param>
/// <returns>异常时返回False</returns>
function TServerMethods.GetSQLStringValue(const AStrSql: string;
var Value: string): Boolean;
begin
InitErrorMsg;
try
QryPublic.Close;
try
QryPublic.SQL.Text := AStrSql;
QryPublic.Open;
if QryPublic.IsEmpty or QryPublic.Fields[0].IsNull then
Value := ''
else
Value := QryPublic.Fields[0].AsString;
Result := True;
finally
QryPublic.Close;
end;
except
on E: Exception do
begin
Result := False;
FErrorCode := ERRCODE_SERVER_GetSQLStringValue;
FErrorText := E.Message;
end;
end;
end;
procedure TServerMethods.InitErrorMsg;
begin
FErrorCode := ERRCODE_SERVER;
FErrorText := '';
end;
/// <summary>
/// 根据传入的SQL,返回获取到的数据集数据
/// </summary>
/// <param name="AStrSql">传入的SQL</param>
/// <param name="AData">数据集数据</param>
/// <returns>执行成功返回True,失败返回False</returns>
function TServerMethods.ReadDataSet(AStrSql: string; var AData: OleVariant): Boolean;
begin
InitErrorMsg;
try
QryPublic.Close;
try
QryPublic.SQL.Text := AStrSql;
QryPublic.Open;
AData := dspPublic.Data;
Result := True;
finally
QryPublic.Close;
end;
except
on E: Exception do
begin
Result := False;
FErrorCode := ERRCODE_SERVER_ReadDataSet;
FErrorText := E.Message;
end;
end;
end;
/// <summary>
/// 根绝传入的SQL列表,返回多数据集
/// </summary>
/// <param name="AStrSql">SQL数组</param>
/// <param name="AData">返回的多数据集组</param>
/// <returns></returns>
function TServerMethods.ReadMultipleDataSets(ASqlArr: OleVariant;
var ADataArr: OleVariant): Boolean;
var
I, iCount: Integer;
begin
Result := False;
InitErrorMsg;
if VarIsEmpty(ASqlArr) or (not VarIsArray(ASqlArr)) then
begin
FErrorCode := ERRCODE_SERVER_ReadMultipleDataSets;
FErrorText := '请求执行的脚本列表为空';
Exit;
end;
iCount := VarArrayHighBound(ASqlArr, 1) - VarArrayLowBound(ASqlArr, 1);
try
ADataArr := VarArrayCreate([0, iCount], varVariant);
for I := 0 to iCount do
begin
QryPublic.Close;
QryPublic.SQL.Text := ASqlArr[I];
QryPublic.Open;
ADataArr[I] := dspPublic.Data;
QryPublic.Close;
end;
Result := True;
except
on E: Exception do
begin
FErrorCode := ERRCODE_SERVER_ReadMultipleDataSets;
FErrorText := E.Message;
end;
end;
end;
/// <summary>
/// 获取数据表头,根据传入的表名称返回空数据集即可
/// </summary>
/// <param name="TableName">表名</param>
/// <param name="Data">包含数据表头的变体类型</param>
/// <returns>成功True,失败False</returns>
function TServerMethods.ReadTableHead(TableName: string;
var Data: OleVariant): Boolean;
begin
InitErrorMsg;
try
QryPublic.Close;
try
QryPublic.SQL.Text := Format('select * from %s where 1=0', [TableName]);
QryPublic.Open;
Data := dspPublic.Data;
Result := True;
finally
QryPublic.Close;
end;
except
on E: Exception do
begin
Result := False;
FErrorCode := ERRCODE_SERVER_ReadTableHead;
FErrorText := E.Message;
end;
end;
end;
/// <summary>
/// 根据传递的参数列表处理
/// </summary>
/// <param name="InParams">传入参数列表</param>
/// <param name="OutParams">返回参数列表</param>
procedure TServerMethods.ParamsMethod(InParams: TParams;
out OutParams: TParams);
begin
OutParams := TParams.Create(nil);
end;
end.
|
//==============================================================//
// ParserTuanYon //
//--------------------------------------------------------------//
// Unit yang menangani parsing tipe data untuk unit-unit lain //
//==============================================================//
unit parsertuanyon;
interface
function StrToInt (str : string) : integer;
{Menghasilkan str dalam tipe integer}
function StrToBool (str : string) : boolean;
{Menghasilkan str dalam tipe boolean}
function IntToHex (number : Int64 ; digits : integer) : string;
{Menghasilkan int dalam bentuk hexadecimal bertipe string}
{Sumber Ide : https://www.geeksforgeeks.org/program-decimal-hexadecimal-conversion/}
implementation
function StrToInt (str : string) : integer;
{Menghasilkan str dalam tipe integer}
{ KAMUS LOKAL }
var
i, int : integer;
{ ALGORITMA }
begin
int := 0;
for i := 1 to Length(str) do
begin
int := (int * 10) + ord(str[i]) - 48;
end;
StrToInt := int;
end;
function StrToBool (str : string) : boolean;
{Menghasilkan str dalam tipe boolean}
{ ALGORITMA }
begin
if (str = 'TRUE') then
begin
StrToBool := true;
end else if (str = 'FALSE') then
begin
StrToBool := false;
end;
end;
function IntToHex (number : Int64; digits : integer) : string;
{Menghasilkan int dalam bentuk hexadecimal bertipe string}
{Sumber Ide : https://www.geeksforgeeks.org/program-decimal-hexadecimal-conversion/}
{ KAMUS LOKAL }
var
remainder: Int64;
i, counter : integer;
{ ALGORITMA }
begin
IntToHex := '';
counter := 0;
while (number <> 0) do
begin
remainder := number mod 16;
if (remainder < 10) then
begin
IntToHex := chr(remainder + 48) + IntToHex;
end else
begin
IntToHex := chr(remainder + 55) + IntToHex;
end;
counter := counter + 1;
number := number div 16;
end;
for i := 1 to (digits-counter) do
begin
IntToHex := '0' + IntToHex;
end;
end;
end. |
unit ProducersGroupUnit2;
interface
uses
QueryGroupUnit2, System.Classes, NotifyEvents, ProducersQuery,
ProducerTypesQuery, System.Generics.Collections, ProducersExcelDataModule;
resourcestring
// Категория производителей которые добавляются на склад в ручную или из Excel Файла
sWareHouseDefaultProducerType = 'Склад';
type
TProducersGroup2 = class(TQueryGroup2)
private
FqProducers: TQueryProducers;
FqProducerTypes: TQueryProducerTypes;
function GetqProducers: TQueryProducers;
function GetqProducerTypes: TQueryProducerTypes;
procedure SetqProducers(const Value: TQueryProducers);
protected
procedure DoAfterDelete(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
function Find(const AProducer: string): TArray<String>;
procedure LoadDataFromExcelTable(AProducersExcelTable
: TProducersExcelTable);
procedure LocateOrAppend(AValue: string; const AProducerType: String);
property qProducers: TQueryProducers read GetqProducers write SetqProducers;
property qProducerTypes: TQueryProducerTypes read GetqProducerTypes;
end;
implementation
uses
System.SysUtils, Data.DB, FireDAC.Comp.DataSet;
constructor TProducersGroup2.Create(AOwner: TComponent);
begin
inherited;
QList.Add(qProducerTypes);
QList.Add(qProducers);
// Для каскадного удаления
TNotifyEventWrap.Create(qProducerTypes.W.AfterDelete, DoAfterDelete,
EventList);
end;
procedure TProducersGroup2.DoAfterDelete(Sender: TObject);
begin
Assert(qProducerTypes.W.DeletedPKValue > 0);
// На сервере типы производителей уже каскадно удалились
// Каскадно удаляем производителей с клиента
qProducers.W.CascadeDelete(qProducerTypes.W.DeletedPKValue,
qProducers.W.ProducerTypeID.FieldName, True);
end;
function TProducersGroup2.Find(const AProducer: string): TArray<String>;
var
L: TList<String>;
begin
L := TList<String>.Create();
try
// Пытаемся искать среди производителей по наименованию
if qProducers.W.Name.Locate(AProducer, [lxoCaseInsensitive, lxoPartialKey])
then
begin
qProducerTypes.W.LocateByPK(qProducers.W.ProducerTypeID.F.Value, True);
// запоминаем что надо искать на первом уровне
L.Add(qProducerTypes.W.ProducerType.F.AsString);
// запоминаем что надо искать на втором уровне
L.Add(AProducer);
end
else
// Пытаемся искать среди типов производителей
if qProducerTypes.W.ProducerType.Locate(AProducer,
[lxoCaseInsensitive, lxoPartialKey]) then
begin
L.Add(AProducer);
end;
Result := L.ToArray;
finally
FreeAndNil(L);
end;
end;
function TProducersGroup2.GetqProducers: TQueryProducers;
begin
if FqProducers = nil then
FqProducers := TQueryProducers.Create(Self);
Result := FqProducers;
end;
function TProducersGroup2.GetqProducerTypes: TQueryProducerTypes;
begin
if FqProducerTypes = nil then
FqProducerTypes := TQueryProducerTypes.Create(Self);
Result := FqProducerTypes;
end;
procedure TProducersGroup2.LoadDataFromExcelTable(AProducersExcelTable
: TProducersExcelTable);
var
AField: TField;
I: Integer;
begin
qProducerTypes.FDQuery.DisableControls;
qProducers.FDQuery.DisableControls;
try
// Цикл по всем записям, которые будем добавлять
AProducersExcelTable.First;
AProducersExcelTable.CallOnProcessEvent;
while not AProducersExcelTable.Eof do
begin
qProducerTypes.LocateOrAppend
(AProducersExcelTable.ProducerType.AsString.Trim);
// Если производитель с таким именем уже есть
if qProducers.Locate(AProducersExcelTable.Name.AsString.Trim) then
qProducers.W.TryEdit
else
qProducers.W.TryAppend;
// Связываем производителя с его типом
qProducers.W.ProducerTypeID.F.AsInteger := qProducerTypes.W.PK.AsInteger;
for I := 0 to AProducersExcelTable.FieldCount - 1 do
begin
AField := qProducers.FDQuery.FindField(AProducersExcelTable.Fields[I]
.FieldName);
if AField <> nil then
AField.Value := AProducersExcelTable.Fields[I].Value;
end;
qProducers.W.TryPost;
AProducersExcelTable.Next;
AProducersExcelTable.CallOnProcessEvent;
end;
finally
qProducers.FDQuery.EnableControls;
qProducerTypes.FDQuery.EnableControls;
end;
end;
procedure TProducersGroup2.LocateOrAppend(AValue: string;
const AProducerType: String);
var
OK: Boolean;
begin
OK := qProducers.Locate(AValue);
if OK then
Exit;
qProducerTypes.LocateOrAppend(AProducerType);
qProducers.W.AddNewValue(AValue, qProducerTypes.W.PK.AsInteger);
end;
procedure TProducersGroup2.SetqProducers(const Value: TQueryProducers);
begin
FqProducers := Value;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.