text stringlengths 14 6.51M |
|---|
unit UMessages;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls, Grids;
type
TfmMess = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
btSend: TBitBtn;
BitBtn2: TBitBtn;
pn: TPanel;
sgMess: TStringGrid;
procedure FormCreate(Sender: TObject);
procedure sgMessDblClick(Sender: TObject);
private
{ Private declarations }
public
procedure FillMessages;
procedure LocateToId(ID: Integer);
function GetId: string;
end;
var
fmMess: TfmMess;
implementation
{$R *.DFM}
procedure TfmMess.FillMessages;
begin
Caption:='Messages';
sgMess.ColWidths[0]:=200;
sgMess.ColWidths[1]:=80;
sgMess.Cells[0,0]:='Message Name';
sgMess.Cells[1,0]:='Message Id';
sgMess.RowCount:=2;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NULL';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NULL,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CREATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CREATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DESTROY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DESTROY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MOVE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MOVE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SIZE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SIZE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_ACTIVATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_ACTIVATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SETFOCUS';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SETFOCUS,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_KILLFOCUS';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_KILLFOCUS,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_ENABLE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_ENABLE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SETREDRAW';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SETREDRAW,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SETTEXT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SETTEXT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_GETTEXT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_GETTEXT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_GETTEXTLENGTH';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_GETTEXTLENGTH,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PAINT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PAINT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CLOSE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CLOSE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_QUERYENDSESSION';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_QUERYENDSESSION,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_QUIT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_QUIT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_QUERYOPEN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_QUERYOPEN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_ERASEBKGND';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_ERASEBKGND,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SYSCOLORCHANGE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SYSCOLORCHANGE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_ENDSESSION';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_ENDSESSION,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SYSTEMERROR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SYSTEMERROR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SHOWWINDOW';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SHOWWINDOW,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CTLCOLOR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CTLCOLOR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_WININICHANGE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_WININICHANGE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SETTINGCHANGE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SETTINGCHANGE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DEVMODECHANGE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DEVMODECHANGE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_ACTIVATEAPP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_ACTIVATEAPP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_FONTCHANGE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_FONTCHANGE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_TIMECHANGE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_TIMECHANGE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CANCELMODE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CANCELMODE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SETCURSOR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SETCURSOR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MOUSEACTIVATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MOUSEACTIVATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CHILDACTIVATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CHILDACTIVATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_QUEUESYNC';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_QUEUESYNC,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_GETMINMAXINFO';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_GETMINMAXINFO,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PAINTICON';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PAINTICON,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_ICONERASEBKGND';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_ICONERASEBKGND,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NEXTDLGCTL';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NEXTDLGCTL,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SPOOLERSTATUS';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SPOOLERSTATUS,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DRAWITEM';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DRAWITEM,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MEASUREITEM';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MEASUREITEM,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DELETEITEM';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DELETEITEM,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_VKEYTOITEM';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_VKEYTOITEM,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CHARTOITEM';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CHARTOITEM,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SETFONT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SETFONT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_GETFONT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_GETFONT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SETHOTKEY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SETHOTKEY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_GETHOTKEY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_GETHOTKEY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_QUERYDRAGICON';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_QUERYDRAGICON,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_COMPAREITEM';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_COMPAREITEM,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_GETOBJECT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_GETOBJECT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_COMPACTING';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_COMPACTING,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_COMMNOTIFY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_COMMNOTIFY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_WINDOWPOSCHANGING';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_WINDOWPOSCHANGING,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_WINDOWPOSCHANGED';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_WINDOWPOSCHANGED,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_POWER';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_POWER,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_COPYDATA';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_COPYDATA,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CANCELJOURNAL';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CANCELJOURNAL,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NOTIFY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NOTIFY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_INPUTLANGCHANGEREQUEST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_INPUTLANGCHANGEREQUEST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_INPUTLANGCHANGE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_INPUTLANGCHANGE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_TCARD';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_TCARD,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_HELP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_HELP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_USERCHANGED';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_USERCHANGED,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NOTIFYFORMAT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NOTIFYFORMAT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CONTEXTMENU';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CONTEXTMENU,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_STYLECHANGING';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_STYLECHANGING,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_STYLECHANGED';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_STYLECHANGED,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DISPLAYCHANGE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DISPLAYCHANGE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_GETICON';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_GETICON,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SETICON';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SETICON,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCCREATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCCREATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCDESTROY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCDESTROY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCCALCSIZE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCCALCSIZE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCHITTEST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCHITTEST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCPAINT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCPAINT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCACTIVATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCACTIVATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_GETDLGCODE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_GETDLGCODE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCMOUSEMOVE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCMOUSEMOVE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCLBUTTONDOWN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCLBUTTONDOWN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCLBUTTONUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCLBUTTONUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCLBUTTONDBLCLK';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCLBUTTONDBLCLK,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCRBUTTONDOWN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCRBUTTONDOWN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCRBUTTONUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCRBUTTONUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCRBUTTONDBLCLK';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCRBUTTONDBLCLK,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCMBUTTONDOWN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCMBUTTONDOWN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCMBUTTONUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCMBUTTONUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NCMBUTTONDBLCLK';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NCMBUTTONDBLCLK,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_KEYFIRST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_KEYFIRST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_KEYDOWN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_KEYDOWN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_KEYUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_KEYUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CHAR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CHAR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DEADCHAR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DEADCHAR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SYSKEYDOWN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SYSKEYDOWN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SYSKEYUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SYSKEYUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SYSCHAR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SYSCHAR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SYSDEADCHAR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SYSDEADCHAR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_KEYLAST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_KEYLAST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_INITDIALOG';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_INITDIALOG,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_COMMAND';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_COMMAND,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SYSCOMMAND';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SYSCOMMAND,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_TIMER';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_TIMER,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_HSCROLL';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_HSCROLL,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_VSCROLL';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_VSCROLL,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_INITMENU';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_INITMENU,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_INITMENUPOPUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_INITMENUPOPUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MENUSELECT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MENUSELECT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MENUCHAR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MENUCHAR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_ENTERIDLE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_ENTERIDLE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MENURBUTTONUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MENURBUTTONUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MENUDRAG';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MENUDRAG,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MENUGETOBJECT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MENUGETOBJECT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_UNINITMENUPOPUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_UNINITMENUPOPUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MENUCOMMAND';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MENUCOMMAND,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CHANGEUISTATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CHANGEUISTATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_UPDATEUISTATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_UPDATEUISTATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_QUERYUISTATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_QUERYUISTATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CTLCOLORMSGBOX';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CTLCOLORMSGBOX,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CTLCOLOREDIT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CTLCOLOREDIT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CTLCOLORLISTBOX';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CTLCOLORLISTBOX,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CTLCOLORBTN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CTLCOLORBTN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CTLCOLORDLG';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CTLCOLORDLG,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CTLCOLORSCROLLBAR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CTLCOLORSCROLLBAR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CTLCOLORSTATIC';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CTLCOLORSTATIC,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MOUSEFIRST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MOUSEFIRST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MOUSEMOVE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MOUSEMOVE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_LBUTTONDOWN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_LBUTTONDOWN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_LBUTTONUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_LBUTTONUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_LBUTTONDBLCLK';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_LBUTTONDBLCLK,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_RBUTTONDOWN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_RBUTTONDOWN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_RBUTTONUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_RBUTTONUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_RBUTTONDBLCLK';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_RBUTTONDBLCLK,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MBUTTONDOWN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MBUTTONDOWN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MBUTTONUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MBUTTONUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MBUTTONDBLCLK';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MBUTTONDBLCLK,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MOUSEWHEEL';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MOUSEWHEEL,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MOUSELAST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MOUSELAST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PARENTNOTIFY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PARENTNOTIFY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_ENTERMENULOOP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_ENTERMENULOOP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_EXITMENULOOP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_EXITMENULOOP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_NEXTMENU';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_NEXTMENU,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SIZING';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SIZING,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CAPTURECHANGED';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CAPTURECHANGED,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MOVING';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MOVING,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_POWERBROADCAST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_POWERBROADCAST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DEVICECHANGE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DEVICECHANGE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_STARTCOMPOSITION';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_STARTCOMPOSITION,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_ENDCOMPOSITION';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_ENDCOMPOSITION,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_COMPOSITION';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_COMPOSITION,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_KEYLAST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_KEYLAST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_SETCONTEXT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_SETCONTEXT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_NOTIFY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_NOTIFY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_CONTROL';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_CONTROL,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_COMPOSITIONFULL';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_COMPOSITIONFULL,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_SELECT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_SELECT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_CHAR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_CHAR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_REQUEST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_REQUEST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_KEYDOWN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_KEYDOWN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_IME_KEYUP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_IME_KEYUP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDICREATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDICREATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDIDESTROY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDIDESTROY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDIACTIVATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDIACTIVATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDIRESTORE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDIRESTORE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDINEXT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDINEXT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDIMAXIMIZE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDIMAXIMIZE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDITILE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDITILE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDICASCADE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDICASCADE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDIICONARRANGE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDIICONARRANGE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDIGETACTIVE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDIGETACTIVE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDISETMENU';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDISETMENU,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_ENTERSIZEMOVE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_ENTERSIZEMOVE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_EXITSIZEMOVE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_EXITSIZEMOVE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DROPFILES';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DROPFILES,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MDIREFRESHMENU';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MDIREFRESHMENU,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MOUSEHOVER';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MOUSEHOVER,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_MOUSELEAVE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_MOUSELEAVE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CUT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CUT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_COPY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_COPY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PASTE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PASTE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CLEAR';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CLEAR,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_UNDO';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_UNDO,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_RENDERFORMAT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_RENDERFORMAT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_RENDERALLFORMATS';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_RENDERALLFORMATS,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DESTROYCLIPBOARD';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DESTROYCLIPBOARD,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DRAWCLIPBOARD';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DRAWCLIPBOARD,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PAINTCLIPBOARD';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PAINTCLIPBOARD,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_VSCROLLCLIPBOARD';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_VSCROLLCLIPBOARD,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_SIZECLIPBOARD';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_SIZECLIPBOARD,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_ASKCBFORMATNAME';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_ASKCBFORMATNAME,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_CHANGECBCHAIN';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_CHANGECBCHAIN,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_HSCROLLCLIPBOARD';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_HSCROLLCLIPBOARD,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_QUERYNEWPALETTE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_QUERYNEWPALETTE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PALETTEISCHANGING';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PALETTEISCHANGING,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PALETTECHANGED';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PALETTECHANGED,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_HOTKEY';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_HOTKEY,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PRINT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PRINT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PRINTCLIENT';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PRINTCLIENT,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_HANDHELDFIRST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_HANDHELDFIRST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_HANDHELDLAST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_HANDHELDLAST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PENWINFIRST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PENWINFIRST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_PENWINLAST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_PENWINLAST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_COALESCE_FIRST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_COALESCE_FIRST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_COALESCE_LAST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_COALESCE_LAST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_FIRST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_FIRST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_INITIATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_INITIATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_TERMINATE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_TERMINATE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_ADVISE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_ADVISE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_UNADVISE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_UNADVISE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_ACK';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_ACK,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_DATA';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_DATA,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_REQUEST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_REQUEST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_POKE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_POKE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_EXECUTE';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_EXECUTE,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_DDE_LAST';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_DDE_LAST,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_APP';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_APP,8);
sgMess.RowCount:=sgMess.RowCount+1;
sgMess.Cells[0,sgMess.RowCount-1]:='WM_USER';
sgMess.Cells[1,sgMess.RowCount-1]:=inttohex(WM_USER,8);
end;
procedure TfmMess.FormCreate(Sender: TObject);
begin
sgMess.InplaceEditor.ReadOnly:=true;
end;
procedure TfmMess.sgMessDblClick(Sender: TObject);
begin
ModalResult:=mrOk;
end;
procedure TfmMess.LocateToId(ID: Integer);
var
i: Integer;
begin
for i:=1 to sgMess.RowCount-1 do begin
if strtoint('$'+sgMess.Cells[1,i])=Id then begin
sgMess.row:=i;
exit;
end;
end;
end;
function TfmMess.GetId: string;
begin
result:=sgMess.Cells[1,sgMess.Row];
end;
end.
|
unit XDebugFile;
interface
uses Classes, XDebugItem;
type
TXFileProgressEvent = procedure(Sender: TObject; const Position: Cardinal; const Total: Cardinal) of object;
XFile = class
private
FProgressEvent: TXFileProgressEvent;
FRoot: PXItem;
FTerminated: boolean;
Stream: TFileStream;
FLastMemory: Integer;
function ParseLine(const Line: string; ItemParent: PXItem): PXItem;
public
constructor Create(Filename: string);
destructor Destroy(); override;
procedure Parse();
procedure Terminate();
property OnProgress: TXFileProgressEvent read FProgressEvent write FProgressEvent;
property Root: PXItem read FRoot;
property Terminated: boolean read FTerminated;
end;
implementation
uses SysUtils, Math,Stream;
function Split(const Subject: String; const Delimiter: Char; const MaxCount: Integer = 0): TStringArray;
var Pos, Ex, L, R, C: integer;
P: PChar;
begin
R := Max(MaxCount, 10);
SetLength(Result, R);
C := 0;
L := Length(Subject);
P := Pointer(Subject);
Pos := 1;
Ex := Pos;
while Pos <= L do begin
if C = MaxCount - 1 then
Break;
if P^ = Delimiter then begin
if C = R - 1 then begin
Inc(R, 10);
SetLength(Result, R);
end;
Result[C] := Copy(Subject, Ex, Pos - Ex);
Inc(C);
Ex := Pos + 1;
end;
Inc(P);
Inc(Pos);
end;
if Pos <= L + 1 then begin
Result[C] := Copy(Subject, Ex, L);
Inc(C);
end;
if R < MaxCount then begin
SetLength(Result, MaxCount);
for L := C to MaxCount - 1 do
Result[L] := '';
end else if C < R - 1 then
SetLength(Result, C);
end;
procedure Replace(const Subject: String; const Search: Char; const Replace: Char);
var Pos, L: integer;
P: PChar;
begin
L := Length(Subject);
P := Pointer(Subject);
Pos := 1;
while Pos <= L do begin
if P^ = Search then
P^ := Replace;
Inc(Pos);
Inc(P);
end;
end;
constructor XFile.Create(Filename: string);
begin
inherited Create;
FTerminated := false;
if not FileExists(Filename) then
raise Exception.Create(Format('File %s does not exist.', [filename]));
try
Stream := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite);
except on E: Exception do
raise Exception.Create(Format('File %s could not be opened: %s.', [Filename, E.Message]));
end;
New(FRoot);
FRoot^ := TXItem.Create(0);
end;
destructor XFile.Destroy;
begin
if Assigned(Stream) then
Stream.Free;
if Assigned(FRoot) then begin
FRoot.Free;
Dispose(FRoot);
end;
end;
procedure XFile.Parse;
var Parent: PXItem;
Line: String;
TextStream: TTextStream;
begin
Parent := Root;
FLastMemory := -1;
Stream.Seek(0, soFromBeginning);
TextStream := TTextStream.Create(Stream);
try
while TextStream.ReadLn(Line) and not FTerminated do begin
if (Length(Line) > 0) and (Ord(Line[1]) in [48..57]) then
Parent := parseLine(Line, Parent);
if Assigned(FProgressEvent) then
FProgressEvent(self, Stream.Position, Stream.Size);
end;
finally
TextStream.Free;
end;
FRoot.Freeze;
end;
function XFile.ParseLine(const Line: string; ItemParent: PXItem): PXItem;
var Items: TStringArray;
L, ItemLevel: Integer;
begin
Items := Split(Line, #9, 12);
Replace(Items[3], '.', ',');
L := Length(Items);
if not L in [5, 12] then
raise Exception.Create(Format('Invalid items count, 5 or 12 expected, %d given', [L]));
ItemLevel := StrToInt(Items[0]);
if ItemLevel < 1 then
raise Exception.Create(Format('Invalid call level definition: %d', [ItemLevel]));
if L = 5 then begin
// Call end
while ItemParent^.Level > ItemLevel do begin
ItemParent := ItemParent^.Parent;
if not Assigned(ItemParent) then
raise Exception.Create('Could not find element parent');
end;
ItemParent^.Finish(Items);
Result := ItemParent;
FLastMemory := Result^.MemoryEnd;
end else if L = 12 then begin
// Call start
while ItemParent^.Level >= ItemLevel do begin
ItemParent := ItemParent^.Parent;
if not Assigned(ItemParent) then
raise Exception.Create('Could not find element parent');
end;
New(Result);
Result^ := TXItem.Create(Items, ItemParent, Stream);
ItemParent.AddChild(Result);
// XDebug user friendly output seems to calculate memory usage this way.
// The end result seems more logic, but I can't understand the programming logic.
if FLastMemory >= 0 then
Result^.DebugMemoryUsage := Result^.MemoryStart - FLastMemory
else
Result^.DebugMemoryUsage := 0;
FLastMemory := Result^.MemoryStart;
end;
end;
procedure XFile.Terminate;
begin
FTerminated := true;
end;
end.
|
unit uDlgStreetEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBASE_DialogForm, Menus, cxLookAndFeelPainters, StdCtrls,
cxButtons, ExtCtrls, cxGraphics, cxDBEdit, cxControls, cxContainer,
cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, DB, ADODB;
type
TdlgStreetEdit = class(TBASE_DialogForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
lcSettlement: TcxDBLookupComboBox;
lcStreetType: TcxDBLookupComboBox;
teNameShort: TcxDBTextEdit;
DataSource: TDataSource;
Query: TADOQuery;
dsSettlement: TDataSource;
qrySettlement: TADOQuery;
dsStreetType: TDataSource;
qryStreetType: TADOQuery;
lcRegion: TcxDBLookupComboBox;
dsRegion: TDataSource;
qryRegion: TADOQuery;
procedure lcSettlementPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure lcRegionPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
FPrimaryKey: integer;
procedure SetPrimaryKey(const Value: integer);
{ Private declarations }
public
property PrimaryKey: integer read FPrimaryKey write SetPrimaryKey;
constructor Create(AOwner: TComponent); override;
end;
var
dlgStreetEdit: TdlgStreetEdit;
implementation
uses uMain, uAccess, uUserBook;
{$R *.dfm}
{ TdlgStreetEdit }
procedure TdlgStreetEdit.SetPrimaryKey(const Value: integer);
begin
FPrimaryKey:=Value;
Query.Close;
Query.SQL.Text:='[sp_Улица_получить] @код_Улица = '+IntToStr(Value);
Query.Open;
end;
procedure TdlgStreetEdit.lcSettlementPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
a: TAccessBook;
lc: TcxDBLookupComboBox;
qry: TAdoQuery;
begin
inherited;
if AButtonIndex=2 then begin
a:=TAccessBook.Create;
try
lc:=Sender as TcxDBLookupComboBox;
a.ObjectID:=lc.Tag;
qry:=lc.Properties.ListSource.DataSet as TAdoQuery;
if a.ShowModal(qry[qry.Fields[0].FieldName], false, false)<>mrOK then exit;
qry.Close;
qry.Open;
lc.DataBinding.StoredValue:=(a.UserBook as TUserBook).PrimaryKeyValue;
lc.DataBinding.UpdateDisplayValue;
finally
a.Free;
end;
end;
if AButtonIndex=1 then begin
(Sender as TcxDBLookupComboBox).DataBinding.StoredValue:=null;
(Sender as TcxDBLookupComboBox).DataBinding.DisplayValue:=null;
end
end;
constructor TdlgStreetEdit.Create(AOwner: TComponent);
begin
inherited;
self.qrySettlement.Open;
self.qryStreetType.Open;
self.qryRegion.Open;
end;
procedure TdlgStreetEdit.lcRegionPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
a: TAccessBook;
lc: TcxDBLookupComboBox;
qry: TAdoQuery;
begin
inherited;
if AButtonIndex=2 then begin
a:=TAccessBook.Create;
try
lc:=Sender as TcxDBLookupComboBox;
a.ObjectID:=lc.Tag;
qry:=lc.Properties.ListSource.DataSet as TAdoQuery;
if a.ShowModal(qry[qry.Fields[0].FieldName], false, false)<>mrOK then exit;
qry.Close;
qry.Open;
lc.DataBinding.StoredValue:=(a.UserBook as TUserBook).PrimaryKeyValue;
lc.DataBinding.UpdateDisplayValue;
finally
a.Free;
end;
end;
if AButtonIndex=1 then begin
(Sender as TcxDBLookupComboBox).DataBinding.StoredValue:=null;
(Sender as TcxDBLookupComboBox).DataBinding.DisplayValue:=null;
end
end;
end.
|
(*
FreePascalGraphicsModes.pas
Not originally part of SWAG, adapted from
https://www.freepascal.org/docs-html/rtl/graph/modes.html
Added by Nacho, 2017
*)
(*
In FreePascal, The following drivers are defined:
D1bit = 11;
D2bit = 12;
D4bit = 13;
D6bit = 14; { 64 colors Half-brite mode - Amiga }
D8bit = 15;
D12bit = 16; { 4096 color modes HAM mode - Amiga }
D15bit = 17;
D16bit = 18;
D24bit = 19; { not yet supported }
D32bit = 20; { not yet supported }
D64bit = 21; { not yet supported }
lowNewDriver = 11;
highNewDriver = 21;
Each of these drivers specifies a desired color-depth.
The following modes have been defined:
detectMode = 30000;
m320x200 = 30001;
m320x256 = 30002; { amiga resolution (PAL) }
m320x400 = 30003; { amiga/atari resolution }
m512x384 = 30004; { mac resolution }
m640x200 = 30005; { vga resolution }
m640x256 = 30006; { amiga resolution (PAL) }
m640x350 = 30007; { vga resolution }
m640x400 = 30008;
m640x480 = 30009;
m800x600 = 30010;
m832x624 = 30011; { mac resolution }
m1024x768 = 30012;
m1280x1024 = 30013;
m1600x1200 = 30014;
m2048x1536 = 30015;
lowNewMode = 30001;
highNewMode = 30015;
*)
Program FreePascalGraphicsModes;
{ Program to demonstrate static graphics mode selection }
uses graph, wincrt;
const
TheLine = 'We are now in 640 x 480 x 256 colors!'+
' (press <Return> to continue)';
var
gd, gm, lo, hi, error,tw,th: integer;
found: boolean;
begin
{ We want an 8 bit mode }
gd := D8bit;
gm := m640x480;
initgraph(gd,gm,'');
{ Make sure you always check graphresult! }
error := graphResult;
if (error <> grOk) Then
begin
writeln('640x480x256 is not supported!');
halt(1)
end;
{ We are now in 640x480x256 }
setColor(cyan);
rectangle(0,0,getmaxx,getmaxy);
{ Write a nice message in the center of the screen }
setTextStyle(defaultFont,horizDir,1);
tw:=TextWidth(TheLine);
th:=TextHeight(TheLine);
outTextXY((getMaxX - TW) div 2,
(getMaxY - TH) div 2,TheLine);
{ Wait for a key press }
readkey;
{ Back to text mode }
closegraph;
end.
|
unit AnidbConnection;
//Single-threaded usage only!
interface
uses SysUtils, DateUtils, WinSock, Windows, AnidbConsts, StrUtils, UniStrUtils;
//Use UTF8 instead of ANSI+HTML_encoding
{$DEFINE ENC_UTF8}
type
{$IFDEF ENC_UTF8}
RawString = UnicodeString; //convert to UTF8 at the latest moment
RawChar = WideChar;
{$ELSE}
RawString = AnsiString;
RawChar = AnsiChar;
{$ENDIF}
PRawChar = ^RawChar;
type
ESocketError = class(Exception)
public
constructor Create(hr: integer); overload;
constructor Create(hr: integer; op: string); overload;
end;
ENoAnswerFromServer = class(Exception);
//Exceptions of this kind stop the execution no matter what.
ECritical = class(Exception);
const
INFINITE = cardinal(-1);
ANIDB_REQUEST_PAUSE: TDatetime = 2 * OneSecond + 500 * OneMillisecond;
ANIDB_BUSY_PAUSE: cardinal = 5000; //milliseconds
type
TUdpConnection = class
protected
WsaData: TWsaData;
FSocket: TSocket;
FHostAddr: in_addr;
FPort: word;
FLocalPort: word;
function GetLocalPort: word;
procedure SetLocalPort(Value: word);
//Speed-up hacks
protected
//Used for select()
fdRead: TFdSet;
function HostnameToAddr(name: AnsiString; out addr: in_addr): boolean;
private
//Buffers for reading things out
buf: pbyte;
bufsz: integer;
procedure FreeBuffers;
protected
function PendingDataSize: integer;
procedure FlushInput;
public
constructor Create;
destructor Destroy; override;
procedure Connect(AHost: AnsiString; APort: word);
procedure Disconnect;
function Connected: boolean;
procedure Send(s: RawString);
function Recv(out s: RawString; Timeout: cardinal = INFINITE): boolean;
function Exchange(inp: RawString; Timeout: cardinal = INFINITE; RetryCount: integer = 1): RawString;
property HostAddr: in_addr read FHostAddr;
property Port: word read FPort;
property LocalPort: word read GetLocalPort write SetLocalPort;
end;
type
TRawStringArray=array of RawString;
PRawStringArray=^TRawStringArray;
TAnidbResult = record
code: integer;
msg: string;
function ToString: string;
end;
PAnidbResult = ^TAnidbResult;
EAnidbError = class(Exception)
public
constructor Create(res: TAnidbResult);
end;
TAnidbMylistStats = record
cAnimes: integer;
cEps: integer;
cFiles: integer;
cSizeOfFiles: integer;
cAddedAnimes: integer;
cAddedEps: integer;
cAddedFiles: integer;
cAddedGroups: integer;
pcLeech: integer;
pcGlory: integer;
pcViewedOfDb: integer;
pcMylistOfDb: integer;
pcViewedOfMylist: integer;
cViewedEps: integer;
cVotes: integer;
cReviews: integer;
end;
PAnidbMylistStats = ^TAnidbMylistStats;
TAnidbConnection = class;
TShortTimeoutEvent = procedure(Sender: TAnidbConnection; Time: cardinal) of object;
TServerBusyEvent = procedure(Sender: TAnidbConnection; WaitTime: cardinal) of object;
TNoAnswerEvent = procedure(Sender: TAnidbConnection; WaitTime: cardinal) of object;
TAnidbConnection = class(TUdpConnection)
protected
FTimeout: cardinal;
FRetryCount: integer;
FSessionKey: AnsiString;
//Date and time when last command was issued.
FLastCommandTime: TDatetime;
FOnShortTimeout: TShortTimeoutEvent;
FOnServerBusy: TServerBusyEvent;
FOnNoAnswer: TNoAnswerEvent;
function Exchange_int(cmd, params: RawString; var outp: TRawStringArray): TAnidbResult;
public
constructor Create;
function Exchange(cmd, params: RawString; var outp: TRawStringArray): TAnidbResult;
function SessionExchange(cmd, params: RawString; var outp: TRawStringArray): TAnidbResult;
property Timeout: cardinal read FTimeout write FTimeout;
property RetryCount: integer read FRetryCount write FRetryCount;
//Session-related cookies
property SessionKey: AnsiString read FSessionKey write FSessionKey;
property LastCommandTime: TDatetime read FLastCommandTime write FLastCommandTime;
property OnShortTimeout: TShortTimeoutEvent read FOnShortTimeout write FOnShortTimeout;
property OnServerBusy: TServerBusyEvent read FOnServerBusy write FOnServerBusy;
property OnNoAnswer: TNoAnswerEvent read FOnNoAnswer write FOnNoAnswer;
protected //Login
FClient: AnsiString;
FClientVer: AnsiString;
FProtoVer: AnsiString;
public
function Login(AUser: AnsiString; APass: AnsiString): TAnidbResult;
procedure Logout;
function LoggedIn: boolean;
property Client: AnsiString read FClient write FClient;
property ClientVer: AnsiString read FClientVer write FClientVer;
property ProtoVer: AnsiString read FProtoVer write FProtoVer;
public //Commands
function MyListAdd(size: int64; ed2k: AnsiString; state: TAnidbFileState; edit: boolean): TAnidbResult;
function MyListStats(out Stats: TAnidbMylistStats): TAnidbResult;
end;
implementation
constructor ESocketError.Create(hr: integer);
begin
inherited Create('Socket error '+IntToStr(hr));
end;
constructor ESocketError.Create(hr: integer; op: string);
begin
inherited Create('Socket error '+IntToStr(hr)+' on '+op);
end;
constructor TUdpConnection.Create;
begin
inherited;
FSocket := INVALID_SOCKET;
FLocalPort := 0; //random local port
buf := nil;
bufsz := 0;
end;
destructor TUdpConnection.Destroy;
begin
if Connected then
Disconnect;
FreeBuffers;
inherited;
end;
procedure TUdpConnection.FreeBuffers;
begin
if Assigned(buf) then
FreeMem(buf);
buf := nil;
bufsz := 0;
end;
function TUdpConnection.HostnameToAddr(name: AnsiString; out addr: in_addr): boolean;
var host_ent: PHostEnt;
begin
//Try to decode host address and port
addr.S_addr := inet_addr(PAnsiChar(name));
if (FHostAddr.S_addr <> integer(INADDR_NONE)) then begin
Result := true;
exit;
end;
//Else we can just try to use this as host name
host_ent := gethostbyname(PAnsiChar(name));
if (host_ent = nil) or (host_ent.h_addrtype <> AF_INET) then begin
Result := false;
exit;
end;
addr.S_addr := pinteger(host_ent^.h_addr^)^;
Result := true;
end;
procedure TUdpConnection.Connect(AHost: AnsiString; APort: word);
var hr: integer;
addr: sockaddr_in;
begin
//Initialize WinSock
hr := WsaStartup($0202, WsaData);
if (hr <> 0) then
raise ESocketError.Create(hr, 'WsaStartup');
//Try to decode host name and addr
FPort := htons(APort);
if not HostnameToAddr(AHost, FHostAddr) then begin
WsaCleanup;
raise ESocketError.Create('Cannot decode hostname/find host '+string(AHost)+'.');
end;
//Create socket
FSocket := socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (FSocket = INVALID_SOCKET) then begin
hr := WsaGetLastError;
WsaCleanup;
raise ESocketError.Create(hr, 'socket()');
end;
//Bind local socket randomly (but to specified port)
addr.sin_family := AF_INET;
addr.sin_port := htons(FLocalPort);
addr.sin_addr.S_addr := 0;
if (bind(FSocket, addr, SizeOf(addr)) <> 0) then begin
hr := WsaGetLastError;
closesocket(FSocket);
FSocket := INVALID_SOCKET;
WsaCleanup;
raise ESocketError.Create(hr, 'local bind()');
end;
//Connect socket
addr.sin_family := AF_INET;
addr.sin_port := FPort;
addr.sin_addr := FHostAddr;
if (WinSock.connect(FSocket, addr, SizeOf(addr)) <> 0) then begin
hr := WsaGetLastError;
closesocket(FSocket);
FSocket := INVALID_SOCKET;
WsaCleanup;
raise ESocketError.Create(hr, 'connect()');
end;
fdRead.fd_count := 1;
fdRead.fd_array[0] := FSocket;
end;
procedure TUdpConnection.Disconnect;
begin
//Purge hacks
fdRead.fd_count := 0;
//Close socket (this terminates everything and unbinds it)
closesocket(FSocket);
FSocket := INVALID_SOCKET;
//Deinit WinSock
WsaCleanup;
end;
function TUdpConnection.Connected: boolean;
begin
Result := (FSocket <> INVALID_SOCKET);
end;
function TUdpConnection.GetLocalPort: word;
var addr: sockaddr_in;
addr_sz: integer;
begin
if not Connected then
Result := FLocalPort
else begin
addr_sz := sizeof(addr);
if (getsockname(FSocket, addr, addr_sz) <> 0) then
raise ESocketError.Create(WsaGetLastError, 'getsockname()');
Result := ntohs(addr.sin_port);
end;
end;
procedure TUdpConnection.SetLocalPort(Value: word);
begin
//We can't change active port if we're connected, so we just plan to use new port in the future.
FLocalPort := Value;
end;
procedure TUdpConnection.Send(s: RawString);
{$IFDEF ENC_UTF8}
var u: UTF8String;
{$ENDIF}
begin
{$IFDEF ENC_UTF8}
u := UTF8String(s);
if not (WinSock.send(FSocket, u[1], Length(u), 0)=Length(u)) then
{$ELSE}
if not (WinSock.send(FSocket, s[1], Length(s), 0)=Length(s)) then
{$ENDIF}
raise ESocketError.Create(WsaGetLastError, 'send()');
end;
function TUdpConnection.Recv(out s: RawString; Timeout: cardinal): boolean;
var sel: integer;
tm: Timeval;
sz: integer;
{$IFDEF ENC_UTF8}
u: UTF8String;
{$ENDIF}
begin
//Timeout-wait for data
fdread.fd_count := 1;
fdread.fd_array[0] := FSocket;
if Timeout <> INFINITE then begin
tm.tv_sec := Timeout div 1000;
tm.tv_usec := Timeout mod 1000;
sel := select(0, @fdRead, nil, nil, @tm);
end else begin
sel := select(0, @fdRead, nil, nil, nil);
end;
if (sel=SOCKET_ERROR) then
raise ESocketError.Create(WsaGetLastError, 'select()');
if (sel<=0) then begin
s := '';
Result := false;
exit;
end;
//Retrieve the amount of data available (>= than the size of first packet)
if(ioctlsocket(FSocket, FIONREAD, sz) <> 0) then
raise ESocketError.Create(WsaGetLastError, 'ioctlsocket()');
{$IFDEF ENC_UTF8}
SetLength(u, sz);
sz := WinSock.Recv(FSocket, u[1], sz, 0);
{$ELSE}
SetLength(s, sz);
sz := WinSock.Recv(FSocket, s[1], sz, 0);
{$ENDIF}
if sz < 0 then
raise ESocketError.Create(WsaGetLastError, 'recv()');
{$IFDEF ENC_UTF8}
SetLength(u, sz);
s := string(u);
{$ELSE}
SetLength(s, sz);
{$ENDIF}
Result := true;
end;
//Returns the size of the data pending in the input buffer. This may differ
//from how much winsock will actually return on recv. See docs for FIONREAD.
function TUdpConnection.PendingDataSize: integer;
begin
if ioctlsocket(FSocket, FIONREAD, Result) <> 0 then
raise ESocketError.Create(WsaGetLastError, 'ioctlsocket()');
end;
//Reads out everything in the input buffer. Use to clean up and minimize
//the chances of getting the answer to the previous question.
procedure TUdpConnection.FlushInput;
var sz: integer;
begin
sz := PendingDataSize;
while sz > 0 do begin
if bufsz < sz then begin
bufsz := sz;
ReallocMem(buf, bufsz);
end;
if WinSock.recv(FSocket, buf^, sz, 0) < 0 then
raise ESocketError.Create(WsaGetLastError, 'recv()');
sz := PendingDataSize;
end;
end;
function TUdpConnection.Exchange(inp: RawString; Timeout: cardinal; RetryCount: integer): RawString;
var i: integer;
done: boolean;
begin
i := 0;
repeat
FlushInput();
Send(inp);
done := Recv(Result, Timeout);
Inc(i);
until done or (i >= RetryCount);
if not done then
raise ENoAnswerFromServer.Create('No answer from server');
end;
////////////////////////////////////////////////////////////////////////////////
function TAnidbResult.ToString: string;
begin
Result := IntToStr(code) + ' ' + string(msg);
end;
constructor EAnidbError.Create(res: TAnidbResult);
begin
//We do not use res.ToString here since we want special treatment.
inherited Create('Anidb error '+IntToStr(res.code) + ': ' + string(res.msg));
end;
function SplitStr(s: RawString; sep: RawChar): TRawStringArray;
var sepcnt, i: integer;
last_sep: integer;
begin
//Count the occurences of char
sepcnt := 0;
for i := 1 to Length(s) do
if s[i]=sep then Inc(sepcnt);
//Allocate memory
SetLength(Result, sepcnt+1);
//Parse string;
last_sep := 0;
sepcnt := 0;
for i := 1 to Length(s) do
if s[i]=sep then begin
SetLength(Result[sepcnt], i-last_sep-1);
Move(s[last_sep+1], Result[sepcnt][1], (i-last_sep-1)*sizeof(s[1]));
last_sep := i;
Inc(sepcnt);
end;
//Last block
SetLength(Result[sepcnt], Length(s)-last_sep);
Move(s[last_sep+1], Result[sepcnt][1], (Length(s)-last_sep)*sizeof(s[last_sep+1]));
end;
constructor TAnidbConnection.Create;
begin
inherited;
FLastCommandTime := 0;
end;
function TAnidbConnection.Exchange_int(cmd, params: RawString; var outp: TRawStringArray): TAnidbResult;
var str: RawString;
tm: cardinal;
i: integer;
begin
while now - LastCommandTime < ANIDB_REQUEST_PAUSE do begin
//If not yet allowed to send, sleep the remaining time
tm := Trunc(MilliSecondSpan(now, LastCommandTime + ANIDB_REQUEST_PAUSE));
if Assigned(FOnShortTimeout) then FOnShortTimeout(Self, tm);
Sleep(tm);
end;
str := inherited Exchange(cmd + ' ' + params, Timeout, 1); //make one try
LastCommandTime := now;
//Split result string;
outp := SplitStr(str, #10);
if Length(outp) <= 0 then
raise ESocketError.Create('Illegal answer from server');
str := outp[0];
//At least the code should be there
if (Length(str) < 3)
or not TryStrToInt(string(str[1] + str[2] + str[3]), Result.code) then
raise ESocketError.Create('Illegal answer from server');
if (Result.Code=LOGIN_ACCEPTED)
or (Result.Code=LOGIN_ACCEPTED_NEW_VER) then begin
//Test if the code is there (at least one byte of it)
if (Length(str) < 5) or (str[4] <> ' ') then
raise ESocketError.Create('Illegal LOGIN_ACCEPTED answer from server');
//Retrieve new session id
FSessionKey := '';
i := 5;
while (i <= Length(str)) and (str[i] <> ' ') do begin
FSessionKey := FSessionKey + AnsiChar(str[i]);
Inc(i);
end;
//The remainder is the message
if (i <= Length(str)) then
//str[i] is the separator
Result.msg := string(PRawChar(@str[i+1]))
else
Result.msg := '';
end else
//Default mode: everything to the right is message
if Length(str) > 4 then
Result.msg := string(PRawChar(@str[5]))
else
Result.msg := '';
end;
//Automatically retries on SERVER_BUSY or on no answer.
function TAnidbConnection.Exchange(cmd, params: RawString; var outp: TRawStringArray): TAnidbResult;
var retries_left: integer;
wait_interval: integer;
begin
retries_left := RetryCount;
wait_interval := ANIDB_BUSY_PAUSE;
while retries_left > 0 do try
Result := Exchange_int(cmd, params, outp);
//Out of service
if Result.Code = ANIDB_OUT_OF_SERVICE then
raise ECritical.Create('AniDB is out of service - try again no earlier than 30 minutes later.');
if (Result.Code = ILLEGAL_INPUT_OR_ACCESS_DENIED)
or (Result.Code = ACCESS_DENIED)
or (Result.Code = UNKNOWN_COMMAND)
or (Result.Code = INTERNAL_SERVER_ERROR) then
raise ECritical.Create('AniDB error '+Result.ToString+'. Unrecoverable.');
if (Result.Code = BANNED) then
raise ECritical.Create('You were banned from anidb. Investigate the case before retrying.');
//Other results
if Result.code <> SERVER_BUSY then exit;
//Busy
Dec(retries_left);
if retries_left > 0 then begin
if Assigned(FOnServerBusy) then FOnServerBusy(Self, wait_interval);
Sleep(wait_interval);
Inc(wait_interval, ANIDB_BUSY_PAUSE);
end;
except
//No answer
on ENoAnswerFromServer do begin
Dec(retries_left);
if retries_left > 0 then begin
if Assigned(FOnNoAnswer) then FOnNoAnswer(Self, wait_interval);
Sleep(wait_interval);
Inc(wait_interval, ANIDB_BUSY_PAUSE);
end;
end;
end;
raise ECritical.Create('Anidb server is not accessible. Impossible to continue.');
end;
function TAnidbConnection.SessionExchange(cmd, params: RawString; var outp: TRawStringArray): TAnidbResult;
begin
if params <> '' then
params := params + '&s=' + RawString(FSessionKey)
else
params := 's='+RawString(FSessionKey);
Result := Exchange(cmd, params, outp);
end;
function TAnidbConnection.Login(AUser: AnsiString; APass: AnsiString): TAnidbResult;
var ans: TRawStringArray;
begin
Result := Exchange('AUTH',
'user='+RawString(AUser)+'&'+
'pass='+RawString(APass)+'&'+
'protover='+RawString(ProtoVer)+'&'+
{$IFDEF ENC_UTF8}
'enc=utf8&'+
{$ENDIF}
'client='+RawString(Client)+'&'+
'clientver='+RawString(ClientVer),
ans);
if (Result.code <> LOGIN_ACCEPTED)
and (Result.code <> LOGIN_ACCEPTED_NEW_VER) then
raise EAnidbError.Create(Result);
end;
procedure TAnidbConnection.Logout;
var ans: TRawStringArray;
res: TAnidbResult;
begin
res := SessionExchange('LOGOUT', '', ans);
if (res.code <> LOGGED_OUT) then
raise EAnidbError.Create(res);
FSessionKey := '';
end;
function TAnidbConnection.LoggedIn: boolean;
begin
Result := (FSessionKey <> '');
end;
//Boolean in andb
function AnidbBool(value: boolean): RawString; inline;
begin
if value then
Result := '1'
else
Result := '0';
end;
const
// Sets UnixStartDate to TDateTime of 01/01/1970
UnixStartDate: TDateTime = 25569.0;
function DateTimeToUnix(ConvDate: TDateTime): Longint;
begin
Result := Round((ConvDate - UnixStartDate) * 86400);
end;
function UnixToDateTime(USec: Longint): TDateTime;
begin
Result := (Usec / 86400) + UnixStartDate;
end;
//Datetime in anidb: string representation of integer
function AnidbDatetime(dt: TDatetime): RawString;
begin
Result := RawString(IntToStr(DatetimeToUnix(dt)));
end;
function RawReplaceStr(const AText, AFromText, AToText: RawString): RawString; inline;
begin
{$IFDEF ENC_UTF8}
Result := UniReplaceStr(AText, AFromText, AToText);
{$ELSE}
Result := AnsiReplaceStr(AText, AFromText, AToText);
{$ENDIF}
end;
type
TAnidbStringOption = (
asoNoNewlines //remove all newlines instead of replacing them with "<br />"
);
TAnidbStringOptions = set of TAnidbStringOption;
//Strings in anidb: html encoded
function AnidbString(s: string; opt: TAnidbStringOptions=[]): RawString;
var r: RawString;
begin
{
Anidb uses some kind of a strange encoding scheme.
They declare it as "form encoding scheme" and ¶m=value+value would
have been logical but it doesn't work. Neither does value%20value.
& works but other %#321; codes don't.
Newlines are replaced with <br />s per documentation, but not allowed
in some cases.
}
//First we either escape HTML tags or HTML tags+all non-unicode chars,
//depending on encoding scheme used
{$IFDEF ENC_UTF8}
r := HtmlEscape(s);
{$ELSE}
r := HtmlEscapeToAnsi(s);
{$ENDIF}
//Next we escape Anidb-specific stuff
{ Slow, can be made faster }
if asoNoNewlines in opt then begin
r := RawReplaceStr(r, #13, '');
r := RawReplaceStr(r, #10, '');
end else begin
r := RawReplaceStr(r, #13#10, '<br />');
r := RawReplaceStr(r, #13, '<br />');
r := RawReplaceStr(r, #10, '<br />');
end;
Result := r;
end;
function TAnidbConnection.MyListAdd(size: int64; ed2k: AnsiString;
state: TAnidbFileState; edit: boolean): TAnidbResult;
var ans: TRawStringArray;
s: RawString;
begin
s := 'size='+RawString(IntToStr(size))+'&ed2k='+RawString(ed2k)+'&edit='+AnidbBool(edit);
if state.State_set then
s := s + '&state='+RawString(IntToStr(state.State));
if state.Viewed_set then
s := s + '&viewed='+AnidbBool(state.Viewed);
if state.ViewDate_set then
s := s + '&viewdate='+AnidbDatetime(state.ViewDate);
if state.Source_set then
s := s + '&source='+AnidbString(state.Source);
if state.Storage_set then
s := s + '&storage='+AnidbString(state.Storage);
if state.Other_set then
s := s + '&other='+AnidbString(state.Other);
Result := SessionExchange('MYLISTADD', s, ans);
end;
function TAnidbConnection.MyListStats(out Stats: TAnidbMylistStats): TAnidbResult;
var ans: TRawStringArray;
vals: TStringArray;
begin
Result := SessionExchange('MYLISTSTATS', '', ans);
if Result.code = MYLIST_STATS then begin
//The answer should have at least one string
if Length(ans) < 2 then
raise Exception.Create('Illegal answer from server: no data.');
ZeroMemory(@Stats, SizeOf(Stats));
vals := SepSplit(string(ans[1]), '|');
if (Length(vals) < 16)
or not TryStrToInt(vals[00], Stats.cAnimes)
or not TryStrToInt(vals[01], Stats.cEps)
or not TryStrToInt(vals[02], Stats.cFiles)
or not TryStrToInt(vals[03], Stats.cSizeOfFiles)
or not TryStrToInt(vals[04], Stats.cAddedAnimes)
or not TryStrToInt(vals[05], Stats.cAddedEps)
or not TryStrToInt(vals[06], Stats.cAddedFiles)
or not TryStrToInt(vals[07], Stats.cAddedGroups)
or not TryStrToInt(vals[08], Stats.pcLeech)
or not TryStrToInt(vals[09], Stats.pcGlory)
or not TryStrToInt(vals[10], Stats.pcViewedOfDb)
or not TryStrToInt(vals[11], Stats.pcMylistOfDb)
or not TryStrToInt(vals[12], Stats.pcViewedOfMylist)
or not TryStrToInt(vals[13], Stats.cViewedEps)
or not TryStrToInt(vals[14], Stats.cVotes)
or not TryStrToInt(vals[15], Stats.cReviews)
then
raise Exception.Create('Invalid answer format.');
end;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Editor for Gui skin.
}
unit FGuiSkinEditor;
interface
uses
System.Messaging,
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
System.Math.Vectors,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.StdCtrls,
FMX.Layouts,
FMX.ListBox,
FMX.Objects,
FMX.Controls.Presentation,
FMX.Edit,
FMX.Controls3D,
VXS.Gui,
VXS.Texture,
VXS.BaseClasses,
VXS.Material;
type
TGUISkinEditor = class(TForm)
PanElements: TPanel;
StatusBar: TStatusBar;
PanBottom: TPanel;
Label1: TLabel;
btnAdd: TButton;
btnDelete: TButton;
LBElements: TListBox;
Label2: TLabel;
ComboBox1: TComboBox;
PanImageProperties: TPanel;
PanZoomImage: TPanel;
SBarHorizontal: TScrollBar;
SBarVertical: TScrollBar;
ImgFull: TImage;
ButtonOK: TButton;
ImageOK: TImage;
ButtonCancel: TButton;
ImageCancel: TImage;
Panel1: TPanel;
ImgPreview: TImage;
Panel2: TPanel;
Label3: TLabel;
CheckBox1: TCheckBox;
Label4: TLabel;
Label5: TLabel;
EditWidth: TEdit;
EditHeight: TEdit;
GLCamera1: TCamera;
GLPanel1: TPanel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FOriginalWndProc: TWndMethod;
FFocusRect: TRect;
VisibleRect: TRect;
PreviewMousePoint: TPoint;
PreviewWidth,
PreviewHeight: Integer;
FullMousePoint: TPoint;
MouseDown: Boolean;
procedure ImageWndProc(var Message: TMessage);
procedure DrawImageFocusRect(ARect: TRect);
procedure AlignZoomPanel;
procedure UpdateRegionEdits;
procedure SetEditState(Parent: TControl; Enabled: Boolean);
procedure AddElement(Index: Integer);
procedure DrawCrossair(Point: TPoint);
public
TheGuiComponent: TVXGuiElementList;
SelectedElement: TVXGUIElement;
Tex: TVXTexture;
Zoom: Single;
Width: Integer;
Height: Integer;
function Edit(GuiComponent: TVXGuiElementList): Boolean;
procedure Render;
procedure SetMax(Scrollbar: TScrollbar; Val: Integer);
end;
var
GUISkinEditor: TGUISkinEditor;
function GUIComponentDialog(GuiComponent: TVXGuiElementList): Boolean;
//--------------------------------------------------------------------
//--------------------------------------------------------------------
//--------------------------------------------------------------------
implementation
//--------------------------------------------------------------------
//--------------------------------------------------------------------
//--------------------------------------------------------------------
{$R *.fmx}
function GUIComponentDialog(GuiComponent: TVXGuiElementList): Boolean;
var
Editor: TGUISkinEditor;
begin
Editor := TGUISkinEditor.Create(nil);
Result := Editor.Edit(GuiComponent);
Editor.Free;
end;
procedure TGUISkinEditor.FormCreate(Sender: TObject);
begin
//override original WndProc to capture image mouse leave message
//with FMX tools
(*
FOriginalWndProc := ImgFull.WindowProc;
imgFull.WindowProc := ImageWndProc;
Tex := TVXTexture.Create(Self);
Tex.SetImageClassName('TVXPersistentImage');
GLPanel1.RedrawAtOnce := True;
StatusBar.Panels[0].Text := 'X : 0';
StatusBar.Panels[1].Text := 'Y : 0';
AlignZoomPanel;
UpdateRegionEdits;
DoubleBuffered := True;
FullMousePoint := Point(-1, -1);
//this Delphi bug shows all panels transparent
//the code below is to avoid this bug in XP
panElements.ParentBackground := False;
panElements.ParentBackground := True;
panElements.ParentBackground := False;
panImageProperties.ParentBackground := False;
panImageProperties.ParentBackground := True;
panImageProperties.ParentBackground := False;
panBottom.ParentBackground := False;
panBottom.ParentBackground := True;
panBottom.ParentBackground := False;
panZoomImage.ParentBackground := False;
panZoomImage.ParentBackground := True;
panZoomImage.ParentBackground := False;
*)
end;
procedure TGUISkinEditor.FormDestroy(Sender: TObject);
begin
Tex.Free;
end;
function TGUISkinEditor.Edit(GuiComponent: TVXGuiElementList): Boolean;
var
Mat: TVXMaterial;
GuiLayout: TVXGuiLayout;
XC: Integer;
begin
TheGuiComponent := GuiComponent;
GuiLayout := (GuiComponent.GetOwner as TVXGuiComponent).Owner.GetOwner as
TVXGuiLayout;
Mat := GuiLayout.Material;
GLPanel1.Visible := True;
{ TODO : E2003 Undeclared identifier: 'GuiLayout' }
(*
GLPanel1.GuiLayout := GuiLayout;
GLPanel1.GuiLayoutName := (GuiComponent.GetOwner as TVXGuiComponent).Name;
*)
Zoom := 1.0;
if (Assigned(mat.MaterialLibrary)
and (mat.MaterialLibrary is TVXMaterialLibrary)
and (Mat.LibMaterialName <> '')) then
begin
mat :=
TVXMaterialLibrary(mat.MaterialLibrary).Materials.GetLibMaterialByName(Mat.LibMaterialName).Material;
end;
Width := Mat.Texture.Image.Width;
Height := Mat.Texture.Image.Height;
{ TODO : E2003 Undeclared identifier }
(*
WidthEdit.Text := IntToStr(Mat.Texture.Image.Width);
HeightEdit.Text := IntToStr(Mat.Texture.Image.Height);
GLPanel1.GuiLayout.Material.Assign(Mat);
*)
Tex.Assign(mat.Texture);
{ TODO : E2003 Undeclared identifier }
(*
imgPreview.Bitmap.Canvas.StretchDraw(imgPreview.ClientRect, (Tex.Image
as TVXPersistentImage).Picture.Bitmap);
PreviewWidth := (Tex.Image as TVXPersistentImage).Picture.Width;
Previewheight := (Tex.Image as TVXPersistentImage).Picture.Height;
*)
lbElements.Clear;
for XC := 0 to TheGuiComponent.Count - 1 do
begin
lbElements.Items.Add(TheGuiComponent.Items[XC].Name);
end;
if TheGuiComponent.Count > 0 then
begin
SelectedElement := TheGuiComponent.Items[0];
lbElements.ItemIndex := 0;
end
else
SelectedElement := nil;
Render;
Result := ShowModal = mrOk;
end;
procedure TGUISkinEditor.AddElement(Index: Integer);
begin
end;
procedure TGUISkinEditor.AlignZoomPanel;
begin
end;
procedure TGUISkinEditor.DrawCrossair(Point: TPoint);
begin
end;
procedure TGUISkinEditor.DrawImageFocusRect(ARect: TRect);
begin
end;
procedure TGUISkinEditor.ImageWndProc(var Message: TMessage);
begin
end;
procedure TGUISkinEditor.Render;
begin
end;
procedure TGUISkinEditor.SetEditState(Parent: TControl; Enabled: Boolean);
begin
end;
procedure TGUISkinEditor.SetMax(Scrollbar: TScrollbar; Val: Integer);
begin
end;
procedure TGUISkinEditor.UpdateRegionEdits;
begin
end;
end.
|
unit ZipInterface;
{
********************************************************************************
******* XLSReadWriteII V3.00 *******
******* *******
******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
{$H+}
{$R-}
{$I XLSRWII2.inc}
interface
uses Classes, SysUtils
{$ifdef DELPHI_6_OR_LATER}
{$ifndef BCB}
,XLSReadWriteZIP
{$endif}
{$endif}
;
//* Base class for reading ZIP compressed file. An external unzip library is
//* required when importing Open Office Calc files, as these files are zip
//* compressed. XLSReadWriteII has an interface to the free Abbrevia zip
//* library. See ~[link ZipInterfaceAbbrevia.TXLSReadZipAbbrevia TXLSReadZipAbbrevia]. ~[br]
//* When using another zip library, override the virtual methods in this class.
type TXLSReadZip = class(TObject)
private
{$ifdef DELPHI_6_OR_LATER}
{$ifndef BCB}
FZIP: TXLSZipArchive;
{$endif}
{$endif}
public
constructor Create;
destructor Destroy; override;
//* Open the zip file on disk.
//* ~param Zipfile The zip file to be read.
procedure OpenZip(Zipfile: WideString); virtual;
//* Closes the zip file.
procedure CloseZip; virtual;
//* Reads a comressed file from the zip archive to a stream.
//* ~param Filename The file to read.
//* ~param Stream The destination stream to unzip the compressed file to.
//* ~result True if the file could be read to the stream.
function ReadFileToStream(Filename: WideString; Stream: TStream): boolean; virtual;
end;
implementation
{ TXLSReadZip }
procedure TXLSReadZip.CloseZip;
begin
{$ifdef DELPHI_6_OR_LATER}
{$ifndef BCB}
FZIP.Close;
{$endif}
{$endif}
end;
constructor TXLSReadZip.Create;
begin
{$ifdef DELPHI_6_OR_LATER}
{$ifndef BCB}
FZIP := TXLSZipArchive.Create;
{$endif}
{$endif}
end;
destructor TXLSReadZip.Destroy;
begin
{$ifdef DELPHI_6_OR_LATER}
{$ifndef BCB}
FZIP.Free;
{$endif}
{$endif}
inherited;
end;
procedure TXLSReadZip.OpenZip(Zipfile: WideString);
begin
{$ifdef DELPHI_6_OR_LATER}
{$ifndef BCB}
FZIP.LoadFromFile(ZipFile);
{$endif}
{$endif}
end;
function TXLSReadZip.ReadFileToStream(Filename: WideString; Stream: TStream): boolean;
begin
{$ifdef DELPHI_6_OR_LATER}
{$ifndef BCB}
FZIP.Read(Filename,Stream);
Result := True;
{$endif}
{$else}
Result := False;
{$endif}
end;
end.
|
{..............................................................................}
{ Summary Create and place Schematic objects on a Schematic document. }
{ }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
{..............................................................................}
Var
SchDoc : ISch_Document;
WorkSpace : IWorkSpace;
{..............................................................................}
{..............................................................................}
Procedure PlaceASchPort(Dummy : Integer);
Var
AName : TDynamicString;
Orientation : TRotationBy90;
AElectrical : TPinElectrical;
SchPort : ISch_Port;
Loc : TLocation;
CurView : IServerDocumentView;
Begin
SchPort := SchServer.SchObjectFactory(ePort,eCreate_GlobalCopy);
If SchPort = Nil Then Exit;
SchPort.Location := Point(MilsToCoord(1000),MilsToCoord(1000));
SchPort.Style := ePortRight;
SchPort.IOType := ePortBidirectional;
SchPort.Alignment := eHorizontalCentreAlign;
SchPort.Width := MilsToCoord(1000);
SchPort.AreaColor := 0;
SchPort.TextColor := $FFFFFF;
SchPort.Name := 'Test Port';
SchDoc.RegisterSchObjectInContainer(SchPort);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceASchComponent(Dummy : Integer);
Begin
If IntegratedLibraryManager = Nil Then Exit;
IntegratedLibraryManager.PlaceLibraryComponent(
'Res2',
'Miscellaneous Devices.IntLib',
'ModelType=SIM|ModelParameterName0=Value|ModelParameterValue0=1K|Orientation=1|Location.X=5000000|Location.Y=5000000');
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceASchJunction(Dummy : Integer);
Var
SchJunction : ISch_Junction;
Begin
SchJunction := SchServer.SchObjectFactory(eJunction,eCreate_GlobalCopy);
If SchJunction = Nil Then Exit;
SchJunction.Location := Point(MilsToCoord(3000), MilsToCoord(2000));
SchJunction.SetState_Size := eMedium;
SchJunction.SetState_Locked := False;
SchDoc.RegisterSchObjectInContainer(SchJunction);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceASchNetLabel(Dummy : Integer);
Var
SchNetlabel : ISch_Netlabel;
Begin
SchNetlabel := SchServer.SchObjectFactory(eNetlabel,eCreate_GlobalCopy);
If SchNetlabel = Nil Then Exit;
SchNetlabel.Location := Point(MilsToCoord(2500), MilsToCoord(2500));
SchNetlabel.Orientation := eRotate90;
SchNetlabel.Text := 'Netname';
SchDoc.RegisterSchObjectInContainer(SchNetlabel);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceASchLine(Dummy : Integer);
Var
SchLine : ISch_Line;
Begin
SchLine := SchServer.SchObjectFactory(eLine,eCreate_GlobalCopy);
If SchLine = Nil Then Exit;
SchLine.Location := Point(MilsToCoord(1800), MilsToCoord(2000));
SchLine.Corner := Point(MilsToCoord(1800), MilsToCoord(4000));
SchLine.LineWidth := eMedium;
SchLine.LineStyle := eLineStyleSolid;
SchLine.Color := $FF00FF;
SchDoc.RegisterSchObjectInContainer(SchLine);
End;
{..............................................................................}
{..............................................................................}
Function SortVertices(WireVertices : String) : Integer;
Var
NewValue : String;
Begin
//X1=4540|Y1=4540|X2=4540|Y2=3450|X2=3540|Y2=4560|....
If Pos('|', WireVertices) > 0 Then
Begin
NewValue := Copy(WireVertices, Pos('=', WireVertices) + 1, pos('|', WireVertices) - pos('=', WireVertices) - 1);
Result := NewValue;
End;
End;
{..............................................................................}
{..............................................................................}
Function VerticesTrim(WireVertices : String) : String;
Var
NewValue : String;
Begin
If Pos('|', WireVertices) > 0 Then
Begin
Delete(WireVertices, 1, pos('|', WireVertices));
Result := WireVertices;
End;
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceASchWire(NumberOfVertices : Integer, Vertices : String, LineWidth : Tsize);
Var
ScriptParametres : String;
SchWire : ISch_Wire;
I : Integer;
X : Integer;
Y : Integer;
WireVertices : String;
Begin
SchWire := SchServer.SchObjectFactory(eWire,eCreate_GlobalCopy);
If SchWire = Nil Then Exit;
// Number of vertices. Always 2 for a single wire
WireVertices := Vertices;
X := SortVertices(WireVertices);
WireVertices := VerticesTrim(WireVertices);
Y := SortVertices(WireVertices);
WireVertices := VerticesTrim(WireVertices);
// Set the line width based on TSize type
SchWire.SetState_LineWidth := LineWidth;
// Starting point for the vertex
Schwire.Location := Point(MilsToCoord(X), MilsToCoord(Y));
Schwire.InsertVertex := 1;
SchWire.SetState_Vertex(1, Point(MilsToCOord(X), MilsToCoord(Y)));
For I := 2 to NumberOfVertices Do
Begin
Schwire.InsertVertex := I;
X := SortVertices(WireVertices);
WireVertices := VerticesTrim(WireVertices);
Y := SortVertices(WireVertices);
WireVertices := VerticesTrim(WireVertices);
SchWire.SetState_Vertex(I, Point(MilsToCoord(X), MilsToCoord(Y)));
End;
SchDoc.RegisterSchObjectInContainer(SchWire);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceSchematicObjects;
Begin
WorkSpace := GetWorkSpace;
If WorkSpace = Nil Then Exit;
Workspace.DM_CreateNewDocument('SCH');
If SchServer = Nil Then Exit;
SchDoc := SchServer.GetCurrentSchDocument;
If SchDoc = Nil Then Exit;
PlaceASchPort(0);
PlaceASchJunction(0);
PlaceASchNetLabel(0);
PlaceASchComponent(0);
PlaceASchLine(0);
PlaceASchWire(2, 'X1=2000|Y1=2000|X2=2500|Y2=3000|', eSmall);
PlaceASchWire(2, 'X1=2500|Y1=3000|X2=3000|Y2=2000|', eMedium);
PlaceASchWire(2, 'X1=3000|Y1=2000|X2=2000|Y2=2000|', eLarge);
SchDoc.GraphicallyInvalidate;
ResetParameters;
AddStringParameter('Action', 'Document');
RunProcess('Sch:Zoom');
End;
{..............................................................................}
{..............................................................................}
|
unit EqualsOpTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
uIntX;
type
{ TTestEqualsOp }
TTestEqualsOp = class(TTestCase)
published
procedure Equals2IntX();
procedure EqualsZeroIntX();
procedure EqualsIntIntX();
procedure EqualsNullIntX();
procedure Equals2IntXOp();
end;
implementation
procedure TTestEqualsOp.Equals2IntX();
var
int1, int2: TIntX;
begin
int1 := TIntX.Create(8);
int2 := TIntX.Create(8);
AssertTrue(int1.Equals(int2));
end;
procedure TTestEqualsOp.EqualsZeroIntX();
begin
AssertFalse(TIntX.Create(0) = 1);
end;
procedure TTestEqualsOp.EqualsIntIntX();
var
int1: TIntX;
begin
int1 := TIntX.Create(8);
AssertTrue(int1 = 8);
end;
procedure TTestEqualsOp.EqualsNullIntX();
var
int1: TIntX;
begin
int1 := TIntX.Create(8);
AssertFalse(int1 = Default(TIntX));
end;
procedure TTestEqualsOp.Equals2IntXOp();
var
int1, int2: TIntX;
begin
int1 := TIntX.Create(8);
int2 := TIntX.Create(8);
AssertTrue(int1 = int2);
end;
initialization
RegisterTest(TTestEqualsOp);
end.
|
unit MainFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, NtBase;
type
TMainForm = class(TForm)
MainLabel: TLabel;
MainCombo: TComboBox;
MainGroup: TGroupBox;
PlanLabel: TLabel;
PlanList: TListBox;
NowCheck: TCheckBox;
MainButton: TButton;
ClientLabel: TLabel;
ClientCombo: TComboBox;
ClientGroup: TGroupBox;
NameLabel: TLabel;
NameEdit: TEdit;
AgeLabel: TLabel;
AgeEdit: TEdit;
AgeUpDown: TUpDown;
NewCheck: TCheckBox;
ClientButton: TButton;
procedure FormCreate(Sender: TObject);
procedure MainComboChange(Sender: TObject);
procedure ClientComboChange(Sender: TObject);
procedure MainButtonClick(Sender: TObject);
procedure ClientButtonClick(Sender: TObject);
private
FLanguages: TNtLanguages;
function GetMainLanguage: String;
function GetClientLanguage: String;
property MainLanguage: String read GetMainLanguage;
property ClientLanguage: String read GetClientLanguage;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
TypInfo, NtBaseTranslator, NtTranslator, MainOptionsDlg, ClientOptionsDlg;
const
UI_LANGUAGE = 'en';
function IsClientItem(
host: TComponent;
obj: TObject): Boolean;
begin
// Item is a a client item if it belong to ClientDialog or to ClientGroup grout box of Form1
Result :=
(host = ClientOptionsDialog) or
(host = MainForm) and ((obj = MainForm.ClientGroup) or (obj is TControl) and (TControl(obj).Parent = MainForm.ClientGroup));
end;
procedure TranslateMain(
host: TComponent;
obj: TObject;
propertyInfo: PPropInfo;
const currentValue: Variant;
var newValue: Variant;
var cancel: Boolean);
begin
if IsClientItem(host, obj) then
cancel := True;
end;
procedure TranslateClient(
host: TComponent;
obj: TObject;
propertyInfo: PPropInfo;
const currentValue: Variant;
var newValue: Variant;
var cancel: Boolean);
begin
if not IsClientItem(host, obj) then
cancel := True;
end;
function TMainForm.GetMainLanguage: String;
begin
if MainCombo.ItemIndex >= 0 then
Result := FLanguages[MainCombo.ItemIndex].Code
else
Result := '';
end;
function TMainForm.GetClientLanguage: String;
begin
if ClientCombo.ItemIndex >= 0 then
Result := FLanguages[ClientCombo.ItemIndex].Code
else
Result := '';
end;
procedure TMainForm.FormCreate(Sender: TObject);
procedure SetIndex(value: Integer);
begin
MainCombo.ItemIndex := value;
ClientCombo.ItemIndex := value;
end;
procedure Process(language: TNtLanguage);
begin
MainCombo.Items.AddObject(language.NativeName, language);
ClientCombo.Items.AddObject(language.NativeName, language);
if SameText(TNtBase.GetActiveLocale, language.Code) then
SetIndex(MainCombo.Items.Count - 1);
end;
var
i: Integer;
begin
// Get the available languages
FLanguages := TNtLanguages.Create;
FLanguages.Add(UI_LANGUAGE, LANG_ENGLISH);
TNtBase.GetAvailable(FLanguages);
// Populate the language combo boxes
for i := 0 to FLanguages.Count - 1 do
Process(FLanguages[i]);
if MainCombo.ItemIndex = -1 then
SetIndex(0);
end;
procedure TMainForm.MainComboChange(Sender: TObject);
begin
// Set the NtBeforeTranslate event to accept only items that belong to main
// and translate the application. This translates all but client items.
NtBeforeTranslate := TranslateMain;
TNtTranslator.SetNew(MainLanguage);
end;
procedure TMainForm.ClientComboChange(Sender: TObject);
begin
// Set the NtBeforeTranslate event to accept only items that belong to client
// and translate the application. This translate only client items.
NtBeforeTranslate := TranslateClient;
TNtTranslator.SetNew(ClientLanguage);
end;
procedure TMainForm.MainButtonClick(Sender: TObject);
begin
MainOptionsDialog.ShowModal;
end;
procedure TMainForm.ClientButtonClick(Sender: TObject);
begin
ClientOptionsDialog.ShowModal;
end;
initialization
DefaultLocale := UI_LANGUAGE;
NtEnabledProperties := STRING_TYPES;
end.
|
unit TnAccess_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ExtCtrls, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxTextEdit, cxButtonEdit, cxContainer, cxEdit, cxLabel,
cxControls, cxGroupBox, StdCtrls, cxButtons,
PackageLoad, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase,
ZTypes, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, GlobalSpr,
cxSpinEdit, FIBQuery, pFIBQuery, pFIBStoredProc, Unit_ZGlobal_Consts,
ActnList, zProc, zMessages, TnAccess_DM, cxCheckBox;
type
TFTnAccessControl = class(TForm)
YesBtn: TcxButton;
CancelBtn: TcxButton;
BoxMan: TcxGroupBox;
EditMan: TcxButtonEdit;
LabelMan: TcxLabel;
BoxPriv: TcxGroupBox;
LabelTypeViplata: TcxLabel;
EditViplata: TcxButtonEdit;
Actions: TActionList;
Action1: TAction;
LabelAcctCard: TcxLabel;
MaskEditCard: TcxMaskEdit;
ClearBtn: TcxButton;
procedure CancelBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EditManPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormDestroy(Sender: TObject);
procedure MaskEditCardKeyPress(Sender: TObject; var Key: Char);
procedure EditPrivilegePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure Action1Execute(Sender: TObject);
procedure ClearBtnClick(Sender: TObject);
private
PId_man:Integer;
PId_Viplata:Integer;
PId_TnAccess:variant;
PResault:Variant;
PLanguageIndex:Byte;
DM:TDM_Ctrl;
public
constructor Create(AOwner:TComponent;ComeDB:TISC_DB_HANDLE;AID_man:integer);reintroduce;
property Resault:Variant read PResault;
end;
implementation
uses VarConv;
{$R *.dfm}
constructor TFTnAccessControl.Create(AOwner: TComponent;ComeDB:TISC_DB_HANDLE;AID_man:integer);
begin
inherited Create(AOwner);
PLanguageIndex:=LanguageIndex;
PId_man:=AId_Man;
//******************************************************************************
Caption := Label_Acct_Card[PLanguageIndex];
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
ClearBtn.Caption := ClearBtn_Caption[PLanguageIndex];
LabelMan.Caption := LabelMan_Caption[PLanguageIndex];
LabelTypeViplata.Caption := LabelTypePayment_Caption[PLanguageIndex];
LabelAcctCard.Caption := 'Øèôð äëÿ ïîäàòê³â';
//******************************************************************************
DM:=TDM_Ctrl.Create(self);
with Dm do
begin
DataBase.Handle := ComeDB;
DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_TNACCESS_S_BY_MAN('+IntToStr(AID_man)+')';
DSet.Open;
EditMan.Text := VarToStrDef(DSet['TN'],'')+' - '+VarToStrDef(DSet['FIO'],'');
PId_TnAccess := DSet['ID_TNACCESS'];
if VarIsNULL(DSet['ID_PAYMENT']) then
begin
PId_Viplata:=-99;
MaskEditCard.Text := '';
EditViplata.Text := '';
end
else
begin
PId_Viplata:=DSet['ID_PAYMENT'];
MaskEditCard.Text := varToStrDef(DSet['ACCT_CARD'],'');
EditViplata.Text := DSet['NAME_PAYMENT'];
end;
end;
//******************************************************************************
end;
procedure TFTnAccessControl.CancelBtnClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFTnAccessControl.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if DM.DefaultTransaction.Active then DM.DefaultTransaction.Commit;
end;
procedure TFTnAccessControl.EditManPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var Man:Variant;
begin
Man:=LoadPeopleModal(self,DM.DataBase.Handle);
if VarArrayDimCount(Man)> 0 then
if Man[0]<>NULL then
begin
EditMan.Text := Man[1]+' '+Man[2]+' '+Man[3];
PId_Man := Man[0];
end;
end;
procedure TFTnAccessControl.FormDestroy(Sender: TObject);
begin
if DM<>nil then DM.Destroy;
end;
procedure TFTnAccessControl.MaskEditCardKeyPress(Sender: TObject;
var Key: Char);
begin
if not((Key in ['0'..'9']) and (Length(MaskEditCard.Text)<16)) then Key:=#0;
end;
procedure TFTnAccessControl.EditPrivilegePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var Viplata:variant;
begin
viplata:=LoadViplata(self,DM.DataBase.Handle,zfsModal);
if VarArrayDimCount(Viplata)>0 then
begin
EditViplata.Text := Viplata[1];
PId_Viplata := Viplata[0];
end;
end;
procedure TFTnAccessControl.Action1Execute(Sender: TObject);
begin
with DM do
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_TNACCESS_IUD';
StoredProc.Prepare;
StoredProc.ParamByName('ID_MAN').AsInteger := PId_man;
if PId_Viplata=-99 then
StoredProc.ParamByName('ID_PAYMENT').AsVariant := NULL
else
StoredProc.ParamByName('ID_PAYMENT').AsInteger := PId_Viplata;
if MaskEditCard.Text='' then
StoredProc.ParamByName('ACCT_CARD').AsVariant := NULL
else StoredProc.ParamByName('ACCT_CARD').AsString := MaskEditCard.Text;
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end
end;
procedure TFTnAccessControl.ClearBtnClick(Sender: TObject);
begin
PId_Viplata := -99;
EditViplata.Text := '';
MaskEditCard.Text := '';
end;
end.
|
unit adot.Tools.Rtti;
{ Definition of classes/record types:
TEnumeration<T: record> = record
Conversion between enumeration type, ordinal value and string value.
TRttiUtils = class
IsInstance<T>, ValueAsString<T>, CreateInstance<T: class> etc.
}
interface
uses
System.Rtti,
System.TypInfo,
System.Math,
System.Classes,
System.SysUtils;
type
{ IsInstance<T>, ValueAsString<T>, CreateInstance<T: class> etc }
TRttiUtils = class
public
{ Returns True if T is class (instance can be created) }
class function IsInstance<T>: boolean; static;
class function IsOrdinal<T>: boolean; static;
{ Convert value of type T to string }
class function ValueAsString<T>(const Value: T): string; static;
{ Find latest public constructor in hierarchy and create instance/object of the class. Supports:
Create()
Create(ACapacity: integer)
Create(Capacity: integer)
Create(AOwner: TComponent)
Create(Owner: TComponent) }
class function CreateInstance<T: class>: T; static;
class function FromVariant<T>(const Src: Variant): T; static;
{ can be used for access to private fields }
class function GetFieldValue<T>(Obj: TObject; const AFieldName: string): T; static;
class procedure SetFieldValue<T>(Obj: TObject; const AFieldName: string; const Value: T); static;
end;
{ Simple convertion EnumType->string->EnumType etc.
http://stackoverflow.com/questions/31601707/generic-functions-for-converting-an-enumeration-to-string-and-back#31604647 }
{ Conversion between enumeration type, ordinal value and string value }
TEnumeration<T: record> = record
strict private
class function TypeInfo: PTypeInfo; static;
class function TypeData: PTypeData; static;
public
class function IsEnumeration: Boolean; static;
class function ToOrdinal(Enum: T): Integer; static;
class function FromOrdinal(Value: Integer): T; static;
class function ToString(Enum: T): string; static;
class function FromString(const S: string): T; static;
class function MinValue: Integer; static;
class function MaxValue: Integer; static;
class function InRange(Value: Integer): Boolean; static;
class function EnsureRange(Value: Integer): Integer; static;
end;
implementation
{ TRttiUtils }
class function TRttiUtils.CreateInstance<T>: T;
var
TypInf: PTypeInfo;
Value: TValue;
RttiContext: TRttiContext;
RttiType: TRttiType;
RttiInstanceType: TRttiInstanceType;
Method: TRttiMethod;
Params: TArray<TRttiParameter>;
begin
TypInf := TypeInfo(T);
{ We use more general solution for "Create(AOwner: TComponent)", but
for descendants of TComponent we can avoid extra checks. }
if TypInf.TypeData.ClassType.InheritsFrom(TComponent) then
result := T(TComponentClass(TypInf.TypeData.ClassType).Create(nil));
begin
RttiContext := TRttiContext.Create;
RttiType := RttiContext.GetType(TypeInfo(T));
if not RttiType.IsInstance then
Exit;
for Method in RttiType.GetMethods do
if Method.IsConstructor and SameText(Method.Name, 'Create') then
begin
Params := Method.GetParameters;
{ "Create()". }
if Length(Params)=0 then
begin
RttiInstanceType := RttiType.AsInstance;
Value := Method.Invoke(RttiInstanceType.MetaclassType, []);
Result := Value.AsType<T>;
Exit;
end;
// "Create(ACapacity: integer = 0)".
// There is no way to check default value, but usually such constructor
// hides "Create()", for example:
// "TDictionary<byte,byte>.Create" means "Create(ACapacity = 0)".
if (Length(Params)=1) and
((Params[0].Flags=[]) or (Params[0].Flags=[TParamFlag.pfConst])) and
(Params[0].ParamType<>nil) and (Params[0].ParamType.TypeKind in [tkInteger, tkInt64]) and
(AnsiSameText(Params[0].Name, 'ACapacity') or AnsiSameText(Params[0].Name, 'Capacity'))
then
begin
RttiInstanceType := RttiType.AsInstance;
Value := Method.Invoke(RttiInstanceType.MetaclassType, [0]);
Result := Value.AsType<T>;
Exit;
end;
// "Create(AOwner: TComponent)".
if (Length(Params)=1) and
(Params[0].Flags=[TParamFlag.pfAddress]) and
(Params[0].ParamType<>nil) and (Params[0].ParamType.TypeKind in [tkClass]) and
(AnsiSameText(Params[0].Name, 'AOwner') or AnsiSameText(Params[0].Name, 'Owner'))
then
begin
RttiInstanceType := RttiType.AsInstance;
Value := Method.Invoke(RttiInstanceType.MetaclassType, [nil]);
Result := Value.AsType<T>;
Exit;
end;
end; // For Method in RttiType.GetMethods
end; // If
// Should never happend, because TObject has "Create()".
raise Exception.Create('Default constructor is not found');
end;
class function TRttiUtils.FromVariant<T>(const Src: Variant): T;
begin
result := TValue.FromVariant(Src).AsType<T>;
end;
class function TRttiUtils.GetFieldValue<T>(Obj: TObject; const AFieldName: string): T;
var
RttiType : TRttiType;
RttiContext : TRttiContext;
RttiField : TRttiField;
Ptr : ^T;
begin
RttiType := RttiContext.GetType(Obj.ClassType);
Assert(Assigned(RttiType));
for RttiField in RttiType.GetFields do
if AnsiLowerCase(AFieldName)=AnsiLowerCase(RttiField.Name) then
begin
Ptr := Pointer(PByte(Obj) + RttiField.Offset);
result := Ptr^;
Exit;
end;
raise Exception.Create(format('Field "%s" is not found (%s)', [AFieldName, Obj.ClassName]));
end;
class procedure TRttiUtils.SetFieldValue<T>(Obj: TObject; const AFieldName: string; const Value: T);
var
RttiType : TRttiType;
RttiContext : TRttiContext;
RttiField : TRttiField;
Ptr : ^T;
begin
RttiType := RttiContext.GetType(Obj.ClassType);
Assert(Assigned(RttiType));
for RttiField in RttiType.GetFields do
if AnsiLowerCase(AFieldName)=AnsiLowerCase(RttiField.Name) then
begin
Ptr := Pointer(PByte(Obj) + RttiField.Offset);
Ptr^ := Value;
Exit;
end;
raise Exception.Create(format('Field "%s" is not found (%s)', [AFieldName, Obj.ClassName]));
end;
class function TRttiUtils.IsInstance<T>: boolean;
var
RttiContext: TRttiContext;
RttiType: TRttiType;
begin
RttiContext := TRttiContext.Create;
RttiType := RttiContext.GetType(TypeInfo(T));
result := (RttiType<>nil) and RttiType.IsInstance;
end;
class function TRttiUtils.IsOrdinal<T>: boolean;
var
RttiContext: TRttiContext;
RttiType: TRttiType;
begin
RttiContext := TRttiContext.Create;
RttiType := RttiContext.GetType(TypeInfo(T));
result := (RttiType<>nil) and RttiType.IsOrdinal;
end;
class function TRttiUtils.ValueAsString<T>(const Value: T): string;
begin
result := TValue.From<T>(Value).ToString;
end;
{ TEnumeration<T> }
class function TEnumeration<T>.TypeInfo: PTypeInfo;
begin
Result := System.TypeInfo(T);
end;
class function TEnumeration<T>.TypeData: PTypeData;
begin
Result := System.TypInfo.GetTypeData(TypeInfo);
end;
class function TEnumeration<T>.IsEnumeration: Boolean;
begin
Result := TypeInfo.Kind=tkEnumeration;
end;
class function TEnumeration<T>.ToOrdinal(Enum: T): Integer;
begin
Assert(IsEnumeration);
Assert(SizeOf(Enum)<=SizeOf(Result));
Result := 0; // needed when SizeOf(Enum) < SizeOf(Result)
Move(Enum, Result, SizeOf(Enum));
Assert(InRange(Result));
end;
class function TEnumeration<T>.FromOrdinal(Value: Integer): T;
begin
Assert(IsEnumeration);
Assert(InRange(Value));
Assert(SizeOf(Result)<=SizeOf(Value));
Move(Value, Result, SizeOf(Result));
end;
class function TEnumeration<T>.ToString(Enum: T): string;
begin
Result := GetEnumName(TypeInfo, ToOrdinal(Enum));
end;
class function TEnumeration<T>.FromString(const S: string): T;
begin
Result := FromOrdinal(GetEnumValue(TypeInfo, S));
end;
class function TEnumeration<T>.MinValue: Integer;
begin
Assert(IsEnumeration);
Result := TypeData.MinValue;
end;
class function TEnumeration<T>.MaxValue: Integer;
begin
Assert(IsEnumeration);
Result := TypeData.MaxValue;
end;
class function TEnumeration<T>.InRange(Value: Integer): Boolean;
var
ptd: PTypeData;
begin
Assert(IsEnumeration);
ptd := TypeData;
Result := System.Math.InRange(Value, ptd.MinValue, ptd.MaxValue);
end;
class function TEnumeration<T>.EnsureRange(Value: Integer): Integer;
var
ptd: PTypeData;
begin
Assert(IsEnumeration);
ptd := TypeData;
Result := System.Math.EnsureRange(Value, ptd.MinValue, ptd.MaxValue);
end;
end.
|
// PALETTE.PAS
// By Banshee & Stucuk
// Modifyed for VXLSE III
unit Palette;
interface
uses
Windows, Variants, Graphics,SysUtils, math, Dialogs;
const
TRANSPARENT = 0;
type
TPalette = array[0..255] of TColor;
var
VXLPalette: TPalette;
procedure LoadPaletteFromFile(Filename : string);
procedure LoadPaletteFromFile2(Filename : string; var Palette : TPalette);
procedure SavePaletteToFile(Filename : string);
procedure GetPaletteFromFile(var Palette:TPalette; Filename : string);
Procedure CreateBlankPalette; // does a gradient effect
Procedure CreateBlankPalette_True; // Makes all 0
procedure LoadJASCPaletteFromFile(Filename : string);
procedure LoadJASCPaletteFromFile2(Filename : string; var Palette:TPalette);
procedure SavePaletteToJASCFile(Filename : string);
procedure PaletteGradient(StartNum,EndNum :byte; StartColour,EndColour : TColor);
Function LoadAPaletteFromFile(Filename:String) : integer;
Function LoadAPaletteFromFile2(Filename:String; var Palette:TPalette) : integer;
function getpalettecolour(Palette: TPalette; Colour : Tcolor) : integer;
function getsquarecolour(x,y : integer; image : tbitmap) : integer;
function getnormalcolour(x,y : integer; image : tbitmap) : integer;
implementation
// Loads TS/RA2 Palette into the VXLPalette
procedure LoadPaletteFromFile(Filename : string);
begin
LoadPaletteFromFile2(filename,VXLPalette);
end;
// I have some problems with this function, so I move it. VK
function RGB(r, g, b: Byte): COLORREF;
begin
Result := (r or (g shl 8) or (b shl 16));
end;
procedure LoadPaletteFromFile2(Filename : string; var Palette : TPalette);
var
Palette_f : array [0..255] of record
red,green,blue:byte;
end;
x: Integer;
F : file;
begin
try
// open palette file
AssignFile(F,Filename);
// VK set good file mode for file
// This allow to run program from write-protected media
FileMode := fmOpenRead;
Reset(F,1); // file of byte
BlockRead(F,Palette_f,sizeof(Palette_f));
CloseFile(F);
for x := 0 to 255 do
Palette[x] := RGB(Palette_f[x].red*4,Palette_f[x].green*4,Palette_f[x].blue*4);
except on E : EInOutError do
MessageDlg('Error: ' + E.Message + Char($0A) + Filename, mtError, [mbOK], 0);
end;
end;
// Saves TS/RA2 Palette from the VXLPalette
procedure SavePaletteToFile(Filename : string);
var
Palette_f : array [0..255] of record
red,green,blue:byte;
end;
x: Integer;
F : file;
begin
for x := 0 to 255 do
begin
Palette_f[x].red := GetRValue(VXLPalette[x]) div 4;
Palette_f[x].green := GetGValue(VXLPalette[x]) div 4;
Palette_f[x].blue := GetBValue(VXLPalette[x]) div 4;
end;
try
AssignFile(F,Filename);
FileMode := fmOpenWrite; // VK Set good file open mode
Rewrite(F,1);
BlockWrite(F,Palette_f,sizeof(Palette_f));
CloseFile(F);
except on E : EInOutError do // VK 1.36 U
MessageDlg('Error: ' + E.Message + Char($0A) + Filename + Char($0A) + 'Possible, media is write-protected.', mtError, [mbOK], 0);
end;
end;
procedure GetPaletteFromFile(var Palette:TPalette; Filename : string);
var
Palette_f : array [0..255] of record
red,green,blue:byte;
end;
x: Integer;
Colour : string;
F : file;
begin
// open palette file
try
AssignFile(F,Filename);
FileMode := fmOpenRead;
Reset(F,1); // file of byte
BlockRead(F,Palette_f,sizeof(Palette_f));
CloseFile(F);
for x := 0 to 255 do
begin
Colour := '$00' + IntToHex(Palette_f[x].blue * 4,2) + IntToHex(Palette_f[x].green * 4,2) + IntToHex(Palette_f[x].red * 4,2);
Palette[x] := StringToColor(Colour);
end;
except on E : EInOutError do // VK 1.36 U
MessageDlg('Error: ' + E.Message + Char($0A) + Filename, mtError, [mbOK], 0);
end;
end;
Procedure CreateBlankPalette;
var
x : integer;
begin
for x := 0 to 255 do
VXLPalette[x] := RGB(255-x,255-x,255-x);
end;
Procedure CreateBlankPalette_True;
var
x : integer;
begin
for x := 0 to 255 do
VXLPalette[x] := 0;
end;
// Loads JASC 8Bit Palette into the VXLPalette
procedure LoadJASCPaletteFromFile(Filename : string);
begin
LoadJASCPaletteFromFile2(Filename,VXLPalette);
end;
procedure LoadJASCPaletteFromFile2(Filename : string; var Palette:TPalette);
var
Palette_f : array [0..255] of record
red,green,blue:byte;
end;
signature,binaryvalue:string[10];
x,colours : Integer;
F : text;
R,G,B : byte;
begin
try
// open palette file
AssignFile(F,Filename);
Filemode := fmOpenRead; // VK Read file mode, because we only read from file
Reset(F);
{Jasc format validation}
readln(F,signature); {JASC-PAL}
readln(F,binaryvalue); {0100}
readln(F,colours); {256 (number of colours)}
if (signature <> 'JASC-PAL') then
MessageBox(0,'Error: JASC Signature Incorrect','Load Palette Error',0)
else if ((binaryvalue <> '0100') or (colours <> 256)) then
MessageBox(0,'Error: Palette Must Be 8Bit(256 Colours)','Load Palette Error',0)
else
Begin
{Now, convert colour per colour}
for x:=0 to 255 do
begin
{read source info}
readln(F,R,G,B);
{Note: No colour conversion needed since JASC-PAL colours are the same as VXLPalette ones}
Palette_f[x].red := r;
Palette_f[x].green := g;
Palette_f[x].blue := b;
Palette[x] := RGB(Palette_f[x].red,Palette_f[x].green,Palette_f[x].blue);
end;
end;
CloseFile(F);
except on E : EInOutError do // VK 1.36 U
MessageDlg('Error: ' + E.Message + Char($0A) + Filename, mtError, [mbOK], 0);
end;
end;
// Saves the VXLPalette As JASC-PAL
procedure SavePaletteToJASCFile(Filename : string);
var
signature,binaryvalue:string[10];
x,colours : Integer;
F : system.text;
begin
try
AssignFile(F,Filename);
FileMode := fmOpenWrite; // VK we save it, so Write mode
Rewrite(F);
signature := 'JASC-PAL';
binaryvalue := '0100';
colours := 256;
writeln(F,signature); {JASC-PAL}
writeln(F,binaryvalue); {0100}
writeln(F,colours); {256 (number of colours)}
for x := 0 to 255 do
writeln(F,inttostr(GetRValue(VXLPalette[x]))+' ',inttostr(GetGValue(VXLPalette[x]))+' ',GetBValue(VXLPalette[x]));
CloseFile(F);
except on E : EInOutError do // VK 1.36 U
MessageDlg('Error: ' + E.Message + Char($0A) + Filename, mtError, [mbOK], 0);
end;
end;
procedure PaletteGradient(StartNum,EndNum :byte; StartColour,EndColour : TColor);
var
X,Distance : integer;
StepR,StepG,StepB : Real;
R,G,B : integer;
begin
Distance := EndNum-StartNum;
if Distance = 0 then // Catch the Divison By 0's
begin
MessageBox(0,'Error: PaletteGradient Needs Start Num And '+#13+#13+'End Num To Be Different Numbers','PaletteGradient Input Error',0);
Exit;
end;
StepR := (Max(GetRValue(EndColour),GetRValue(StartColour)) - Min(GetRValue(EndColour),GetRValue(StartColour))) / Distance;
StepG := (Max(GetGValue(EndColour),GetGValue(StartColour)) - Min(GetGValue(EndColour),GetGValue(StartColour))) / Distance;
StepB := (Max(GetBValue(EndColour),GetBValue(StartColour)) - Min(GetBValue(EndColour),GetBValue(StartColour))) / Distance;
if GetRValue(EndColour) < GetRValue(StartColour) then
StepR := -StepR;
if GetGValue(EndColour) < GetGValue(StartColour) then
StepG := -StepG;
if GetBValue(EndColour) < GetBValue(StartColour) then
StepB := -StepB;
R := GetRValue(StartColour);
G := GetGValue(StartColour);
B := GetBValue(StartColour);
for x := StartNum to EndNum do
begin
if Round(R + StepR) < 0 then
R := 0
else
R := Round(R + StepR);
if Round(G + StepG) < 0 then
G := 0
else
G := Round(G + StepG);
if Round(B + StepB) < 0 then
B := 0
else
B := Round(B + StepB);
if R > 255 then
R := 255;
if G > 255 then
G := 255;
if B > 255 then
B := 255;
VXLPalette[x] := RGB(R,G,B);
end;
end;
Function LoadAPaletteFromFile(Filename:String) : integer; // Works out which filetype it is
begin
Result := LoadAPaletteFromFile2(Filename,VXLPalette);
end;
Function LoadAPaletteFromFile2(Filename:String; var Palette:TPalette) : integer; // Works out which filetype it is
var
signature:string[10];
F : system.text;
begin
Result := 1; // Assume TS/RA2
// open palette file
try
AssignFile(F,Filename);
FileMode := fmOpenRead;
Reset(F);
{Jasc format validation}
readln(F,signature); {JASC-PAL}
CloseFile(F);
if (signature <> 'JASC-PAL') then // If Signature is not JASC-PAL Assume its a TS/RA2 Palette
LoadPaletteFromFile2(Filename,Palette)
else
begin
Result := 2;
LoadJASCPaletteFromFile2(Filename,Palette);
end;
except on E : EInOutError do // VK 1.36 U
MessageDlg('Error: ' + E.Message + Char($0A) + Filename, mtError, [mbOK], 0);
end;
end;
function getpalettecolour(Palette: TPalette; Colour : Tcolor) : integer;
var
p,col,ccol : integer;
r,g,b : byte;
t : single;
begin
col := -1;
for p := 0 to 255 do
if Colour = Palette[p] then
col := p;
t := 10000;
if col = -1 then
begin
ccol := -1;
for p := 0 to 255 do
begin
r := GetRValue(ColortoRGB(Colour)) - GetRValue(ColortoRGB(Palette[p])) ;
g := GetGValue(ColortoRGB(Colour)) - GetGValue(ColortoRGB(Palette[p])) ;
b := GetBValue(ColortoRGB(Colour)) - GetBValue(ColortoRGB(Palette[p])) ;
if Sqrt(r*r + g*g + b*b) < t then
begin
t := Sqrt(r*r + g*g + b*b);
ccol := p;
end;
end;
if (ccol = -1) or (t = 10000) then
ccol := 0;
col := ccol;
end;
result := col;
end;
function getsquarecolour(x,y : integer; image : tbitmap) : integer;
begin
Result := getpalettecolour(VXLPalette,Image.Canvas.Pixels[x,y]);
end;
function getnormalcolour(x,y : integer; image : tbitmap) : integer;
begin
Result := GetRValue(Image.Canvas.Pixels[x,y]);
end;
end.
|
unit Number_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ColorButton, Spin, ExtCtrls, jpeg;
type
TForm5 = class(TForm)
imgBackground: TImage;
shpHeader: TShape;
lblMidstream: TLabel;
lblCollege: TLabel;
lblQuizNight: TLabel;
pnlQuestion: TPanel;
lblQuestion: TLabel;
sedQuestion: TSpinEdit;
btnGO: TColorButton;
procedure btnGOClick(Sender: TObject);
procedure sedQuestionKeyPress(Sender: TObject; var Key: Char);
procedure FormActivate(Sender: TObject);
private
//helper method
procedure Heading(iPos : integer; sSubject : string);
{ Private declarations }
public
{ Public declarations }
end;
var
Form5: TForm5;
implementation
uses ScoreSheet_u, GradeMenu_u, Question_u, Teachers_u;
{$R *.dfm}
procedure TForm5.btnGOClick(Sender: TObject);
var
sQuestion, sAnswer : string;
iNo : integer;
begin
//get question number
iNo := sedQuestion.Value;
//change heading
case iNo of
1..5: Heading(192, 'Sport');
6..10: Heading(88, 'Geography');
11..15: Heading(168, 'Science');
16..20: Heading(112, 'Literature');
21..25: Heading(200, 'Music');
26..30: with Form4 do
begin
lblSubject.Hide;
lblMovies.Show;
lblSeries.Show;
end;
31..35: Heading(88, 'Technology');
36..40: Heading(160, 'History');
end;
//teachers
if Form6.bTeachers = true then
begin
Form5.Hide;
sQuestion := Form2.TeachersQuiz.getQuestion(iNo);
sAnswer := Form2.TeachersQuiz.getAnswer(iNo);
with Form4 do
begin
Show;
redQuestion.Text := sQuestion;
TheAnswer := sAnswer;
redOut.SetFocus;
end;
Exit;
end;
//grade 8-12
Form5.Hide;
//get question and answer
sQuestion := Form2.QuizNight.getQuestion(iNo);
sAnswer := Form2.QuizNight.getAnswer(iNo);
//getting ready for buzzers
with Form4 do
begin
Show;
redQuestion.Text := sQuestion;
TheAnswer := sAnswer;
redOut.SetFocus;
end;
end;
procedure TForm5.sedQuestionKeyPress(Sender: TObject; var Key: Char);
begin
//countermeasure for stupid slamming on buzzers
Key := #0;
end;
procedure TForm5.FormActivate(Sender: TObject);
//colours
const
clOrangeRed = TColor($0024FF);
//correct setup
begin
lblQuizNight.Font.Color := clOrangeRed;
lblQuestion.Font.Color := clOrangeRed;
lblQuizNight.Width := 280;
end;
//helper method
procedure TForm5.Heading(iPos: integer; sSubject: string);
begin
with Form4 do
begin
lblSubject.Show;
lblMovies.Hide;
lblSeries.Hide;
lblSubject.Left := iPos;
lblSubject.Caption := sSubject;
end;
end;
end.
|
namespace NullableTypes;
interface
type
ConsoleApp = class
public
class method Main;
end;
implementation
class method ConsoleApp.Main;
method UsingColonOperator;
var
MyString: String := 'Oxygene';
begin
// usual call, lLength = 7;
var lLength: Int32 := MyString.Length;
writeLn(lLength);
MyString := nil;
// nil value will be converted to 0
lLength := MyString:Length;
// lLength2 will be a nullable Int32
var lLength2 := MyString:Length;
writeLn(lLength2);
end;
method AssigningAndCasting;
begin
var n: nullable Int32 := nil;
var i: Int32 := 10;
// nil value will be converted to 0
i := n;
// following line will throw an invalid cast exception because n is nil
// i := Int32(n);
// following line will work fine n = 10;
i:= 10;
n := i;
end;
method UsingValueOrDefault;
begin
var n: nullable Int32; // initialized to nil
var i: Int32; // initialized to 0
// will assign 0 if n is nil
i := valueOrDefault(n);
// will assign -1 if n is nil
i := valueOrDefault(n, -1);
writeLn(i);
end;
begin
AssigningAndCasting;
UsingColonOperator;
UsingValueOrDefault;
end;
end. |
unit UCidade;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.ComCtrls,
Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids,
UCidadeVo, UCidadeController, UController,
UEstado, UEstadoVO, UPaisVO, Generics.Collections, UPais;
type
TTFTelaCadastroCidade = class(TFTelaCadastro)
LabelEditNome: TLabeledEdit;
LabelEditNomeEstado: TLabeledEdit;
LabelEditEstado: TLabeledEdit;
btnConsultaEstado: TBitBtn;
LabelEditNomePais: TLabeledEdit;
btnConsultaPais: TBitBtn;
LabelEditPais: TLabeledEdit;
procedure BitBtnNovoClick(Sender: TObject);
procedure btnConsultaEstadoClick(Sender: TObject);
procedure DoConsultar; override;
function DoExcluir: boolean; override;
function DoSalvar: boolean; override;
procedure FormCreate(Sender: TObject);
function MontaFiltro: string;
procedure btnConsultaPaisClick(Sender: TObject);
procedure CarregaObjetoSelecionado; override;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
function EditsToObject(Cidade: TCidadeVO): TCidadeVO;
procedure GridParaEdits; override;
end;
var
TFTelaCadastroCidade: TTFTelaCadastroCidade;
controllerCidade: TCidadeController;
implementation
{$R *.dfm}
{ TTFTelaCadastroCidade }
procedure TTFTelaCadastroCidade.BitBtnNovoClick(Sender: TObject);
begin
inherited;
LabelEditNome.SetFocus;
end;
procedure TTFTelaCadastroCidade.btnConsultaEstadoClick(Sender: TObject);
var
FormEstadoConsulta: TFTelaCadastroEstado;
begin
FormEstadoConsulta := TFTelaCadastroEstado.Create(nil);
FormEstadoConsulta.FechaForm := true;
FormEstadoConsulta.ShowModal;
if (FormEstadoConsulta.ObjetoRetornoVO <> nil) then
begin
LabelEditEstado.Text:=IntToStr(TEstadoVO(FormEstadoConsulta.ObjetoRetornoVO).idEstado);
LabelEditNomeEstado.Text:=TEstadoVO(FormEstadoConsulta.ObjetoRetornoVO).NomeEstado;
LabelEditPais.Text:=IntToStr(TEstadoVO(FormEstadoConsulta.ObjetoRetornoVO).PaisVO.idPais);
LabelEditNomePais.Text:=TEstadoVO(FormEstadoConsulta.ObjetoRetornoVO).PaisVO.NomePais;
end;
FormEstadoConsulta.Release;
end;
procedure TTFTelaCadastroCidade.btnConsultaPaisClick(Sender: TObject);
var
FormPaisConsulta: TFTelaCadastroPais;
begin
FormPaisConsulta := TFTelaCadastroPais.Create(nil);
FormPaisConsulta.FechaForm := true;
FormPaisConsulta.ShowModal;
if (FormPaisConsulta.ObjetoRetornoVO <> nil) then
begin
LabelEditPais.Text :=
IntToStr(TPaisVO(FormPaisConsulta.ObjetoRetornoVO).idPais);
LabelEditNomePais.Text := TPaisVO(FormPaisConsulta.ObjetoRetornoVO)
.NomePais;
end;
FormPaisConsulta.Release;
end;
procedure TTFTelaCadastroCidade.CarregaObjetoSelecionado;
begin
inherited;
if (not CDSGrid.IsEmpty) then
begin
ObjetoRetornoVO := controllerCidade.ConsultarPorId(CDSGRID.FieldByName('IDCIDADE').AsInteger);
end;
end;
procedure TTFTelaCadastroCidade.DoConsultar;
var
listaCidade: TObjectList<TCidadeVO>;
filtro: string;
begin
filtro := MontaFiltro;
listaCidade := controllerCidade.Consultar(filtro);
PopulaGrid<TCidadeVO>(listaCidade);
end;
function TTFTelaCadastroCidade.DoExcluir: boolean;
var
Cidade: TCidadeVO;
begin
try
try
Cidade := TCidadeVO.Create;
Cidade.idCidade := CDSGrid.FieldByName('IDCIDADE').AsInteger;
controllerCidade.Excluir(Cidade);
except
on E: Exception do
begin
ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 +
E.Message);
Result := false;
end;
end;
finally
end;
end;
function TTFTelaCadastroCidade.DoSalvar: boolean;
var
Cidade : TCidadeVO;
begin
begin
Cidade:=EditsToObject(TCidadeVO.Create);
try
try
if (Cidade.ValidarCamposObrigatorios()) then
begin
if (StatusTela = stInserindo) then
begin
controllerCidade.Inserir(Cidade);
Result := true;
end
else if (StatusTela = stEditando) then
begin
Cidade := controllerCidade.ConsultarPorId(CDSGrid.FieldByName('IDCIDADE')
.AsInteger);
Cidade := EditsToObject(Cidade);
controllerCidade.Alterar(Cidade);
Result := true;
end;
end
else
Result := false;
except
on E: Exception do
begin
ShowMessage(E.Message);
Result := false;
end;
end;
finally
end;
end;
end;
function TTFTelaCadastroCidade.EditsToObject(Cidade: TCidadeVO): TCidadeVO;
begin
Cidade.NomeCidade := LabelEditNome.Text;
if (LabelEditPais.Text <> '') then
Cidade.idPais := strtoint(LabelEditPais.Text);
if (LabelEditEstado.Text <> '') then
Cidade.idEstado := strtoint(LabelEditEstado.Text);
Result := Cidade;
end;
procedure TTFTelaCadastroCidade.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
FreeAndNil(controllerCidade);
end;
procedure TTFTelaCadastroCidade.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TCidadeVO;
controllerCidade:=TCidadeController.Create;
inherited;
end;
procedure TTFTelaCadastroCidade.GridParaEdits;
var
Cidade: TCidadeVO;
begin
inherited;
Cidade := nil;
if not CDSGrid.IsEmpty then
Cidade := controllerCidade.ConsultarPorId(CDSGrid.FieldByName('IDCIDADE')
.AsInteger);
if Assigned(Cidade) then
begin
LabelEditNome.Text := Cidade.NomeCidade;
end;
if (Cidade.idEstado > 0) then
begin
LabelEditEstado.Text := IntToStr(Cidade.EstadoVO.idEstado);
LabelEditNomeEstado.Text := Cidade.EstadoVO.NomeEstado;
end;
if (Cidade.idPais > 0) then
begin
LabelEditPais.Text := IntToStr(Cidade.PaisVO.idPais);
LabelEditNomePais.Text := Cidade.PaisVO.NomePais;
end;
end;
function TTFTelaCadastroCidade.MontaFiltro: string;
begin
result := '';
if (editBusca.Text <> '') then
Result := '( UPPER(NOME) LIKE ' +
QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) ';
end;
end.
|
unit View.Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Edit, FMX.Objects, FMX.ScrollBox, FMX.Memo,
FMX.Layouts, FMX.ListBox,
Common.Barcode, FMX.Memo.Types;
type
TFormMain = class(TForm)
EditRawData: TEdit;
ButtonGenerateBarcode: TButton;
PathBarcode: TPath;
LayoutTop: TLayout;
LayoutClient: TLayout;
MemoSVGPathData: TMemo;
ComboBoxBarcodeType: TComboBox;
LayoutRight: TLayout;
SplitterRight: TSplitter;
TextSVG: TText;
EditAddonData: TEdit;
procedure ButtonGenerateBarcodeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EditRawDataKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
private
{ Private declarations }
FLastSelectedType: TBarcodeType;
function SelectedBarcodeType: TBarcodeType;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
procedure TFormMain.ButtonGenerateBarcodeClick(Sender: TObject);
var
SVGString: string;
begin
FLastSelectedType := SelectedBarcodeType;
SVGString := TBarcode.SVG(FLastSelectedType, EditRawData.Text, EditAddonData.Text);
PathBarcode.Data.Data := SVGString;
MemoSVGPathData.Lines.Text := SVGString;
end;
procedure TFormMain.EditRawDataKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if Key = 13 then
ButtonGenerateBarcodeClick(ButtonGenerateBarcode);
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
FLastSelectedType := TBarcodeType.EAN8;
end;
function TFormMain.SelectedBarcodeType: TBarcodeType;
begin
result := TBarcodeType(ComboBoxBarcodeType.ItemIndex);
end;
initialization
ReportMemoryLeaksOnShutdown := true;
finalization
CheckSynchronize;
end.
|
unit uFrmLimitRole;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmMDI, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, dxBar, dxBarExtItems, cxClasses, ImgList,
ActnList, DB, DBClient, cxGridLevel, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGrid, ExtCtrls, ComCtrls,
cxContainer, cxTreeView, cxPC, uGridConfig, uModelFunIntf, uModelLimitIntf, uFrmApp,
cxTL, cxInplaceContainer, cxGroupBox;
type
TfrmLimitRole = class(TfrmMDI)
btnAdd: TdxBarLargeButton;
actAdd: TAction;
btnModify: TdxBarLargeButton;
btnDel: TdxBarLargeButton;
actModify: TAction;
actDel: TAction;
pnlRolelist: TPanel;
tvRole: TcxTreeView;
pnlAction: TPanel;
pcLimit: TcxPageControl;
tsBase: TcxTabSheet;
gridBase: TcxGrid;
gridTVBase: TcxGridTableView;
gridLVBase: TcxGridLevel;
tsBill: TcxTabSheet;
tsReport: TcxTabSheet;
btnSave: TdxBarLargeButton;
actSaveRoleAction: TAction;
cdsBase: TClientDataSet;
actSetRoleAction: TAction;
btnSetRoleAction: TdxBarLargeButton;
actAddUser: TAction;
btnAddUser: TdxBarLargeButton;
gbUser: TcxGroupBox;
tvUser: TcxTreeView;
actDelUser: TAction;
btnDelUser: TdxBarLargeButton;
gridBill: TcxGrid;
gridTVBill: TcxGridTableView;
gridLVBill: TcxGridLevel;
cdsBill: TClientDataSet;
gridReport: TcxGrid;
gridTVReport: TcxGridTableView;
gridLVReport: TcxGridLevel;
cdsReport: TClientDataSet;
procedure actAddExecute(Sender: TObject);
procedure actModifyExecute(Sender: TObject);
procedure actDelExecute(Sender: TObject);
procedure actSetRoleActionExecute(Sender: TObject);
procedure actSaveRoleActionExecute(Sender: TObject);
procedure tvRoleChange(Sender: TObject; Node: TTreeNode);
procedure actAddUserExecute(Sender: TObject);
procedure actDelUserExecute(Sender: TObject);
private
{ Private declarations }
FModelLimit: IModelLimit;
FGridBase, FGridBill, FGridReport: TGridItem;
FModelFun: IModelFun;
procedure BeforeFormShow; override;
procedure BeforeFormDestroy; override;
procedure InitParamList; override;
procedure IniGridField; override;
procedure LoadGridData(ATypeid: string = ''); override;
procedure LoadRoleTree;
procedure LoadUserTree;
function GetNodeData(AFullname, ATypeid: string): PNodeData;
function SelNodeData(ATV: TcxTreeView): PNodeData;
procedure SetOptState(AReadOnly: Boolean);
function SaveRoleAction: Boolean;
public
{ Public declarations }
end;
var
frmLimitRole: TfrmLimitRole;
implementation
uses uBaseFormPlugin, uSysSvc, uDBIntf, uMoudleNoDef, uModelControlIntf, uDefCom, uParamObject,
uOtherIntf, uPubFun, uBaseInfoDef;
{$R *.dfm}
{ TfrmLimitRole }
procedure TfrmLimitRole.BeforeFormDestroy;
begin
inherited;
FreeBaseTVData(tvRole);
FGridBase.Free;
FGridBill.Free;
FGridReport.Free;
end;
procedure TfrmLimitRole.BeforeFormShow;
begin
inherited;
FModelLimit := IModelLimit((SysService as IModelControl).GetModelIntf(IModelLimit));
FModelFun := SysService as IModelFun;
FGridBase := TGridItem.Create(ClassName + gridBase.Name, gridBase, gridTVBase);
FGridBase.SetGridCellSelect(True);
FGridBase.ShowMaxRow := False;
FGridBill := TGridItem.Create(ClassName + gridBill.Name, gridBill, gridTVBill);
FGridBill.SetGridCellSelect(True);
FGridBill.ShowMaxRow := False;
FGridReport := TGridItem.Create(ClassName + gridReport.Name, gridReport, gridTVReport);
FGridReport.SetGridCellSelect(True);
FGridReport.ShowMaxRow := False;
IniGridField();
LoadRoleTree();
LoadUserTree();
// LoadGridData();
SetOptState(True);
pcLimit.ActivePage := tsBase;
end;
procedure TfrmLimitRole.IniGridField;
var
aColInfo: TColInfo;
begin
inherited;
FGridBase.ClearField();
FGridBase.AddField('LAGUID', 'LAGUID', -1);
FGridBase.AddField('LimitValue', 'LimitValue', -1, cfInt);
aColInfo := FGridBase.AddField('LAName', '模块名称', 200);
aColInfo.GridColumn.Options.Editing := False;
FGridBase.AddCheckBoxCol('LView', '查看', 1, 0);
FGridBase.AddCheckBoxCol('LAdd', '新增', 1, 0);
FGridBase.AddCheckBoxCol('LClass', '分类', 1, 0);
FGridBase.AddCheckBoxCol('LModify', '修改', 1, 0);
FGridBase.AddCheckBoxCol('LDel', '删除', 1, 0);
FGridBase.AddCheckBoxCol('LPrint', '打印', 1, 0);
FGridBase.InitGridData;
FGridBill.ClearField();
FGridBill.AddField('LAGUID', 'LAGUID', -1);
FGridBill.AddField('LimitValue', 'LimitValue', -1, cfInt);
aColInfo := FGridBill.AddField('LAName', '模块名称', 200);
aColInfo.GridColumn.Options.Editing := False;
FGridBill.AddCheckBoxCol('LView', '查看', 1, 0);
FGridBill.AddCheckBoxCol('LInput', '输入', 1, 0);
FGridBill.AddCheckBoxCol('LSettle', '过账', 1, 0);
FGridBill.AddCheckBoxCol('LPrint', '打印', 1, 0);
FGridBill.InitGridData;
FGridReport.ClearField();
FGridReport.AddField('LAGUID', 'LAGUID', -1);
FGridReport.AddField('LimitValue', 'LimitValue', -1, cfInt);
aColInfo := FGridReport.AddField('LAName', '模块名称', 200);
aColInfo.GridColumn.Options.Editing := False;
FGridReport.AddCheckBoxCol('LView', '查看', 1, 0);
FGridReport.AddCheckBoxCol('LPrint', '打印', 1, 0);
FGridReport.InitGridData;
end;
procedure TfrmLimitRole.InitParamList;
begin
inherited;
MoudleNo := fnMdlLimitRole;
end;
procedure TfrmLimitRole.LoadGridData(ATypeid: string);
var
aNodeData: PNodeData;
begin
inherited;
aNodeData := SelNodeData(tvRole);
if not Assigned(aNodeData) then Exit;
FModelLimit.UserLimitData(Limit_Base, aNodeData.Typeid, cdsBase);
FGridBase.LoadData(cdsBase);
FModelLimit.UserLimitData(Limit_Bill, aNodeData.Typeid, cdsBill);
FGridBill.LoadData(cdsBill);
FModelLimit.UserLimitData(Limit_Report, aNodeData.Typeid, cdsReport);
FGridReport.LoadData(cdsReport);
end;
procedure TfrmLimitRole.LoadRoleTree;
var
aCdsRole: TClientDataSet;
aParam: TParamObject;
aNodeData: PNodeData;
aRootNode: TTreeNode;
begin
FreeBaseTVData(tvRole);
tvRole.Items.Clear;
aRootNode := tvRole.Items.AddChildObject(nil, '角色列表', nil);
aCdsRole := TClientDataSet.Create(nil);
aParam := TParamObject.Create;
tvRole.Items.BeginUpdate;
try
aParam.Add('@QryType', 1);
FModelLimit.LimitData(aParam, aCdsRole);
aCdsRole.First;
while not aCdsRole.Eof do
begin
aNodeData := GetNodeData(aCdsRole.FieldByName('LRName').AsString, aCdsRole.FieldByName('LRGUID').AsString);
tvRole.Items.AddChildObject(aRootNode, aNodeData.Fullname, aNodeData);
aCdsRole.Next;
end;
tvRole.FullExpand;
tvRole.Items.GetFirstNode.GetNext.Selected := True;
tvRole.SetFocus;
finally
tvRole.Items.EndUpdate;
aParam.Free;
aCdsRole.Free;
end;
end;
procedure TfrmLimitRole.actAddExecute(Sender: TObject);
var
aName: string;
aAddRole, aOutParam: TParamObject;
aNodeData: PNodeData;
aTreeNode: TTreeNode;
begin
inherited;
aName := '';
if IMsgBox(SysService as IMsgBox).InputBox('角色', '输入角色名称', aName) = mrok then
begin
aAddRole := TParamObject.Create;
aOutParam := TParamObject.Create;
try
aAddRole.Add('RoleName', Trim(aName));
if FModelLimit.SaveLimit(Limit_Save_Role, aAddRole, aOutParam) >= 0 then
begin
aNodeData := GetNodeData(aName, aOutParam.AsString('LRGUID'));
aTreeNode := tvRole.Items.AddChildObject(tvRole.Items.GetFirstNode, aNodeData.Fullname, aNodeData);
aTreeNode.Selected := True;
tvRole.SetFocus;
end;
finally
aOutParam.Free;
aAddRole.Free;
end;
end;
end;
function TfrmLimitRole.GetNodeData(AFullname, ATypeid: string): PNodeData;
var
aNodeData: PNodeData;
begin
New(aNodeData);
aNodeData.Leveal := 1;
aNodeData.Fullname := AFullname;
aNodeData.Typeid := ATypeid;
aNodeData.Parid := '';
Result := aNodeData;
end;
procedure TfrmLimitRole.actModifyExecute(Sender: TObject);
var
aName: string;
aAddRole, aOutParam: TParamObject;
aNodeData: PNodeData;
aTreeNode: TTreeNode;
begin
inherited;
aNodeData := SelNodeData(tvRole);
if not Assigned(aNodeData) then Exit;
aName := aNodeData.Fullname;
if IMsgBox(SysService as IMsgBox).InputBox('角色', '输入角色名称', aName) = mrok then
begin
aAddRole := TParamObject.Create;
aOutParam := TParamObject.Create;
try
aAddRole.Add('RoleName', Trim(aName));
aAddRole.Add('RoleId', aNodeData.Typeid);
if FModelLimit.SaveLimit(Limit_Modify_Role, aAddRole, aOutParam) >= 0 then
begin
tvRole.Items.BeginUpdate;
try
aTreeNode.Text := aName;
aNodeData.Fullname := aName;
tvRole.SetFocus;
finally
tvRole.Items.EndUpdate;
end;
end;
finally
aOutParam.Free;
aAddRole.Free;
end;
end;
end;
procedure TfrmLimitRole.actDelExecute(Sender: TObject);
var
aName: string;
aAddRole, aOutParam: TParamObject;
aNodeData: PNodeData;
aTreeNode: TTreeNode;
begin
inherited;
aNodeData := SelNodeData(tvRole);
if not Assigned(aNodeData) then Exit;
aAddRole := TParamObject.Create;
aOutParam := TParamObject.Create;
try;
aAddRole.Add('RoleId', aNodeData.Typeid);
if FModelLimit.SaveLimit(Limit_Del_Role, aAddRole, aOutParam) >= 0 then
begin
tvRole.Items.BeginUpdate;
try
Dispose(aNodeData);
tvRole.Items.Delete(aTreeNode);
tvRole.Items.GetFirstNode.GetNext.Selected := True;
tvRole.SetFocus;
finally
tvRole.Items.EndUpdate;
end;
end;
finally
aOutParam.Free;
aAddRole.Free;
end;
end;
procedure TfrmLimitRole.SetOptState(AReadOnly: Boolean);
begin
gridTVBill.OptionsData.Editing := not AReadOnly;
gridTVBase.OptionsData.Editing := not AReadOnly;
gridTVReport.OptionsData.Editing := not AReadOnly;
btnSave.Enabled := not AReadOnly;
btnSetRoleAction.Enabled := AReadOnly;
end;
procedure TfrmLimitRole.actSetRoleActionExecute(Sender: TObject);
begin
inherited;
SetOptState(False);
end;
procedure TfrmLimitRole.actSaveRoleActionExecute(Sender: TObject);
begin
inherited;
if SaveRoleAction() then
begin
(SysService as IMsgBox).MsgBox(actSaveRoleAction.Caption + '完成!');
SetOptState(True);
end;
end;
function TfrmLimitRole.SaveRoleAction: Boolean;
var
aRow, aOldLimitValue, aNewLimitValue: Integer;
aLAGUID, aLAName: string;
aLView, aLAdd, aLClass, aLModify, aLDel, aLPrint, aLInput, aLSettle: Boolean;
aSaveRole, aOutParam: TParamObject;
aNodeData: PNodeData;
begin
inherited;
FGridBase.GridPost();
FGridBill.GridPost();
FGridReport.GridPost();
aNodeData := SelNodeData(tvRole);
if not Assigned(aNodeData) then Exit;
Result := False;
aSaveRole := TParamObject.Create;
aOutParam := TParamObject.Create;
try
for aRow := FGridBase.GetFirstRow to FGridBase.GetLastRow do
begin
aSaveRole.Clear;
aOutParam.Clear;
aLAGUID := FGridBase.GetCellValue('LAGUID', aRow);
aLAName := FGridBase.GetCellValue('LAName', aRow);
aLView := FGridBase.GetCellValue('LView', aRow) = 1;
aLAdd := FGridBase.GetCellValue('LAdd', aRow) = 1;
aLClass := FGridBase.GetCellValue('LClass', aRow) = 1;
aLModify := FGridBase.GetCellValue('LModify', aRow) = 1;
aLDel := FGridBase.GetCellValue('LDel', aRow) = 1;
aLPrint := FGridBase.GetCellValue('LPrint', aRow) = 1;
aOldLimitValue := FGridBase.GetCellValue('LimitValue', aRow);
aNewLimitValue := 0;
if aLView then aNewLimitValue := aNewLimitValue + Limit_Base_View;
if aLAdd then aNewLimitValue := aNewLimitValue + Limit_Base_Add;
if aLClass then aNewLimitValue := aNewLimitValue + Limit_Base_Class;
if aLModify then aNewLimitValue := aNewLimitValue + Limit_Base_Modify;
if aLDel then aNewLimitValue := aNewLimitValue + Limit_Base_Del;
if aLPrint then aNewLimitValue := aNewLimitValue + Limit_Base_Print;
if aNewLimitValue = aOldLimitValue then Continue;
aSaveRole.Add('@LAGUID', aLAGUID);
aSaveRole.Add('@RUID', aNodeData.Typeid);
aSaveRole.Add('@RUType', 1);
aSaveRole.Add('@LimitValue', aNewLimitValue);
if FModelLimit.SaveLimit(Limit_Save_RoleAction, aSaveRole, aOutParam) < 0 then
begin
(SysService as IMsgBox).MsgBox('更新权限<' + aLAName + '>失败');
Exit;
end;
end;
for aRow := FGridBill.GetFirstRow to FGridBill.GetLastRow do
begin
aSaveRole.Clear;
aOutParam.Clear;
aLAGUID := FGridBill.GetCellValue('LAGUID', aRow);
aLAName := FGridBill.GetCellValue('LAName', aRow);
aLView := FGridBill.GetCellValue('LView', aRow) = 1;
aLInput := FGridBill.GetCellValue('LInput', aRow) = 1;
aLSettle := FGridBill.GetCellValue('LSettle', aRow) = 1;
aLPrint := FGridBill.GetCellValue('LPrint', aRow) = 1;
aOldLimitValue := FGridBill.GetCellValue('LimitValue', aRow);
aNewLimitValue := 0;
if aLView then aNewLimitValue := aNewLimitValue + Limit_Bill_View;
if aLInput then aNewLimitValue := aNewLimitValue + Limit_Bill_Input;
if aLSettle then aNewLimitValue := aNewLimitValue + Limit_Bill_Settle;
if aLPrint then aNewLimitValue := aNewLimitValue + Limit_Bill_Print;
if aNewLimitValue = aOldLimitValue then Continue;
aSaveRole.Add('@LAGUID', aLAGUID);
aSaveRole.Add('@RUID', aNodeData.Typeid);
aSaveRole.Add('@RUType', 1);
aSaveRole.Add('@LimitValue', aNewLimitValue);
if FModelLimit.SaveLimit(Limit_Save_RoleAction, aSaveRole, aOutParam) < 0 then
begin
(SysService as IMsgBox).MsgBox('更新权限<' + aLAName + '>失败');
Exit;
end;
end;
for aRow := FGridReport.GetFirstRow to FGridReport.GetLastRow do
begin
aSaveRole.Clear;
aOutParam.Clear;
aLAGUID := FGridReport.GetCellValue('LAGUID', aRow);
aLAName := FGridReport.GetCellValue('LAName', aRow);
aLView := FGridReport.GetCellValue('LView', aRow) = 1;
aLPrint := FGridReport.GetCellValue('LPrint', aRow) = 1;
aOldLimitValue := FGridReport.GetCellValue('LimitValue', aRow);
aNewLimitValue := 0;
if aLView then aNewLimitValue := aNewLimitValue + Limit_Report_View;
if aLPrint then aNewLimitValue := aNewLimitValue + Limit_Report_Print;
if aNewLimitValue = aOldLimitValue then Continue;
aSaveRole.Add('@LAGUID', aLAGUID);
aSaveRole.Add('@RUID', aNodeData.Typeid);
aSaveRole.Add('@RUType', 1);
aSaveRole.Add('@LimitValue', aNewLimitValue);
if FModelLimit.SaveLimit(Limit_Save_RoleAction, aSaveRole, aOutParam) < 0 then
begin
(SysService as IMsgBox).MsgBox('更新权限<' + aLAName + '>失败');
Exit;
end;
end;
LoadGridData();
Result := True;
finally
aSaveRole.Free;
aOutParam.Free;
end;
end;
function TfrmLimitRole.SelNodeData(ATV: TcxTreeView): PNodeData;
var
aNodeData: PNodeData;
aTreeNode: TTreeNode;
begin
Result := nil;
aTreeNode := ATV.Selected;
if not Assigned(aTreeNode) then Exit;
aNodeData := aTreeNode.Data;
if not Assigned(aNodeData) then Exit;
Result := aNodeData;
end;
procedure TfrmLimitRole.tvRoleChange(Sender: TObject; Node: TTreeNode);
begin
inherited;
LoadUserTree();
LoadGridData();
end;
procedure TfrmLimitRole.LoadUserTree;
var
aCdsUser: TClientDataSet;
aParam: TParamObject;
aNodeData: PNodeData;
aRootNode: TTreeNode;
begin
aNodeData := SelNodeData(tvRole);
if not Assigned(aNodeData) then Exit;
aCdsUser := TClientDataSet.Create(nil);
aParam := TParamObject.Create;
tvUser.Items.BeginUpdate;
try
aParam.Add('@QryType', 2);
aParam.Add('@Custom', aNodeData.Typeid);
if FModelLimit.LimitData(aParam, aCdsUser) = 0 then
begin
FreeBaseTVData(tvUser);
tvUser.Items.Clear;
aCdsUser.First;
while not aCdsUser.Eof do
begin
aNodeData := GetNodeData(aCdsUser.FieldByName('EFullname').AsString, aCdsUser.FieldByName('UserId').AsString);
aRootNode := tvUser.Items.AddChildObject(nil, aNodeData.Fullname, aNodeData);
aCdsUser.Next;
end;
end;
finally
tvUser.Items.EndUpdate;
aParam.Free;
aCdsUser.Free;
end;
end;
procedure TfrmLimitRole.actAddUserExecute(Sender: TObject);
var
aReturnCount: Integer;
aSelectParam: TSelectBasicParam;
aSelectOptions: TSelectBasicOptions;
aReturnArray: TSelectBasicDatas;
aAddRole, aOutParam: TParamObject;
aNodeData: PNodeData;
aRootNode: TTreeNode;
begin
inherited;
aNodeData := SelNodeData(tvRole);
if not Assigned(aNodeData) then Exit;
DoSelectBasic(btnAddUser, btEtype, aSelectParam, aSelectOptions, aReturnArray, aReturnCount);
if aReturnCount >= 1 then
begin
aAddRole := TParamObject.Create;
aOutParam := TParamObject.Create;
try;
aAddRole.Add('@LRGUID', aNodeData.Typeid);
aAddRole.Add('@UserId', aReturnArray[0].TypeId);
if FModelLimit.SaveLimit(Limit_Save_RU, aAddRole, aOutParam) >= 0 then
begin
LoadUserTree();
(SysService as IMsgBox).MsgBox(btnAddUser.Caption + '完成');
end;
finally
aOutParam.Free;
aAddRole.Free;
end;
end;
end;
procedure TfrmLimitRole.actDelUserExecute(Sender: TObject);
var
aName: string;
aAddRole, aOutParam: TParamObject;
aNodeData: PNodeData;
aTreeNode: TTreeNode;
begin
inherited;
aAddRole := TParamObject.Create;
aOutParam := TParamObject.Create;
try;
aNodeData := SelNodeData(tvRole);
if not Assigned(aNodeData) then Exit;
aAddRole.Add('RoleId', aNodeData.Typeid);
aNodeData := SelNodeData(tvUser);
if not Assigned(aNodeData) then Exit;
aAddRole.Add('UserId', aNodeData.Typeid);
if FModelLimit.SaveLimit(Limit_Del_RU, aAddRole, aOutParam) >= 0 then
begin
LoadUserTree();
end;
finally
aOutParam.Free;
aAddRole.Free;
end;
end;
initialization
gFormManage.RegForm(TfrmLimitRole, fnMdlLimitRole);
end.
|
{ ****************************************************************************** }
{ * parsing library,writen 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 TextParsing;
{$INCLUDE zDefine.inc}
interface
uses Types, CoreClasses, PascalStrings, UnicodeMixedLib, ListEngine;
type
TTextStyle = (tsPascal, tsC, tsText);
TTokenType = (ttTextDecl, ttComment, ttNumber, ttSymbol, ttAscii, ttSpecialSymbol, ttUnknow);
TTokenTypes = set of TTokenType;
TTokenStatistics = array [TTokenType] of Integer;
TTextPos = record
bPos, ePos: Integer;
Text: TPascalString;
end;
PTextPos = ^TTextPos;
TTokenData = record
bPos, ePos: Integer;
Text: TPascalString;
tokenType: TTokenType;
Index: Integer;
end;
PTokenData = ^TTokenData;
TTextParsingCache = record
CommentDecls, TextDecls: TCoreClassList; // PTextPos
TokenDataList: TCoreClassList; // PTokenData
CharToken: array of PTokenData;
end;
TTextParsingData = record
Cache: TTextParsingCache;
Text: TPascalString;
Len: Integer;
end;
TSymbolVector = TArrayPascalString;
TSymbolMatrix = array of TSymbolVector;
TTextParsing = class(TCoreClassObject)
public
TextStyle: TTextStyle;
ParsingData: TTextParsingData;
SymbolTable: TPascalString;
TokenStatistics: TTokenStatistics;
SpecialSymbol: TListPascalString;
RebuildCacheBusy: Boolean;
{ compare char }
function ComparePosStr(const cOffset: Integer; const t: TPascalString): Boolean; overload; inline;
function ComparePosStr(const cOffset: Integer; const p: PPascalString): Boolean; overload; inline;
{ compare comment and text declaration: TokenCache }
function CompareCommentGetEndPos(const cOffset: Integer): Integer;
function CompareTextDeclGetEndPos(const cOffset: Integer): Integer;
{ rebuild support }
procedure RebuildParsingCache;
procedure RebuildText;
procedure RebuildToken;
{ automated context on pick: TokenCache }
function GetContextBeginPos(const cOffset: Integer): Integer;
function GetContextEndPos(const cOffset: Integer): Integer;
{ special symbol support: TokenCache }
function isSpecialSymbol(const cOffset: Integer): Boolean; overload;
function isSpecialSymbol(const cOffset: Integer; var speicalSymbolEndPos: Integer): Boolean; overload;
function GetSpecialSymbolEndPos(const cOffset: Integer): Integer;
{ number decl support: TokenCache }
function isNumber(const cOffset: Integer): Boolean; overload;
function isNumber(const cOffset: Integer; var NumberBegin: Integer; var IsHex: Boolean): Boolean; overload;
function GetNumberEndPos(const cOffset: Integer): Integer;
{ text support: TokenCache }
function isTextDecl(const cOffset: Integer): Boolean;
function GetTextDeclEndPos(const cOffset: Integer): Integer;
function GetTextDeclBeginPos(const cOffset: Integer): Integer;
function GetTextBody(const Text_: TPascalString): TPascalString;
function GetTextDeclPos(const cOffset: Integer; var charBeginPos, charEndPos: Integer): Boolean;
{ symbol support: TokenCache }
function isSymbol(const cOffset: Integer): Boolean;
function GetSymbolEndPos(const cOffset: Integer): Integer;
{ ascii support: TokenCache }
function isAscii(const cOffset: Integer): Boolean;
function GetAsciiBeginPos(const cOffset: Integer): Integer;
function GetAsciiEndPos(const cOffset: Integer): Integer;
{ comment support: TokenCache }
function isComment(const cOffset: Integer): Boolean;
function GetCommentEndPos(const cOffset: Integer): Integer;
function GetCommentBeginPos(const cOffset: Integer): Integer;
function GetCommentPos(const cOffset: Integer; var charBeginPos, charEndPos: Integer): Boolean;
function GetDeletedCommentText: TPascalString;
{ text support: TokenCache }
function isTextOrComment(const cOffset: Integer): Boolean;
function isCommentOrText(const cOffset: Integer): Boolean;
{ word support: TokenCache no used }
class function isWordSplitChar(const c: SystemChar; SplitTokenC: TPascalString): Boolean; overload;
class function isWordSplitChar(const c: SystemChar): Boolean; overload;
class function isWordSplitChar(const c: SystemChar; DefaultChar: Boolean; SplitTokenC: TPascalString): Boolean; overload;
function GetWordBeginPos(const cOffset: Integer; SplitTokenC: TPascalString): Integer; overload;
function GetWordBeginPos(const cOffset: Integer): Integer; overload;
function GetWordBeginPos(const cOffset: Integer; BeginDefaultChar: Boolean; SplitTokenC: TPascalString): Integer; overload;
function GetWordEndPos(const cOffset: Integer; SplitTokenC: TPascalString): Integer; overload;
function GetWordEndPos(const cOffset: Integer): Integer; overload;
function GetWordEndPos(const cOffset: Integer; BeginSplitCharSet, EndSplitCharSet: TPascalString): Integer; overload;
function GetWordEndPos(const cOffset: Integer;
BeginDefaultChar: Boolean; BeginSplitCharSet: TPascalString;
EndDefaultChar: Boolean; EndSplitCharSet: TPascalString): Integer; overload;
{ sniffing }
function SniffingNextChar(const cOffset: Integer; declChar: TPascalString): Boolean; overload;
function SniffingNextChar(const cOffset: Integer; declChar: TPascalString; out OutPos: Integer): Boolean; overload;
{ split char }
function SplitChar(const cOffset: Integer; var LastPos: Integer; const SplitTokenC, SplitEndTokenC: TPascalString; var SplitOutput: TSymbolVector): Integer; overload;
function SplitChar(const cOffset: Integer; const SplitTokenC, SplitEndTokenC: TPascalString; var SplitOutput: TSymbolVector): Integer; overload;
{ split string }
function SplitString(const cOffset: Integer; var LastPos: Integer; const SplitTokenS, SplitEndTokenS: TPascalString; var SplitOutput: TSymbolVector): Integer; overload;
function SplitString(const cOffset: Integer; const SplitTokenS, SplitEndTokenS: TPascalString; var SplitOutput: TSymbolVector): Integer; overload;
{ token operation }
function CompareTokenText(const cOffset: Integer; t: TPascalString): Boolean;
function CompareTokenChar(const cOffset: Integer; const c: array of SystemChar): Boolean;
function GetToken(const cOffset: Integer): PTokenData;
property TokenPos[const cOffset: Integer]: PTokenData read GetToken;
function GetTokenIndex(t: TTokenType; idx: Integer): PTokenData;
property TokenIndex[t: TTokenType; idx: Integer]: PTokenData read GetTokenIndex;
function TokenCount: Integer; overload;
function TokenCountT(t: TTokenTypes): Integer; overload;
function GetTokens(idx: Integer): PTokenData;
property Tokens[idx: Integer]: PTokenData read GetTokens; default;
property Token[idx: Integer]: PTokenData read GetTokens;
property Count: Integer read TokenCount;
function FirstToken: PTokenData;
function LastToken: PTokenData;
function NextToken(p: PTokenData): PTokenData;
function PrevToken(p: PTokenData): PTokenData;
function TokenCombine(const bTokenI, eTokenI: Integer; const acceptT: TTokenTypes): TPascalString; overload;
function TokenCombine(const bTokenI, eTokenI: Integer): TPascalString; overload;
function Combine(const bTokenI, eTokenI: Integer; const acceptT: TTokenTypes): TPascalString; overload;
function Combine(const bTokenI, eTokenI: Integer): TPascalString; overload;
{ token probe StartI->Left }
function TokenProbeL(startI: Integer; const acceptT: TTokenTypes): PTokenData; overload;
function TokenProbeL(startI: Integer; const t: TPascalString): PTokenData; overload;
function TokenProbeL(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData; overload;
function TokenProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData; overload;
function TokenProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData; overload;
function TokenProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData; overload;
function TokenProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData; overload;
{ token probe StartI->Right }
function TokenProbeR(startI: Integer; const acceptT: TTokenTypes): PTokenData; overload;
function TokenProbeR(startI: Integer; const t: TPascalString): PTokenData; overload;
function TokenProbeR(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData; overload;
function TokenProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData; overload;
function TokenProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData; overload;
function TokenProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData; overload;
function TokenProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData; overload;
{ token probe alias StartI->Left }
function ProbeL(startI: Integer; const acceptT: TTokenTypes): PTokenData; overload;
function ProbeL(startI: Integer; const t: TPascalString): PTokenData; overload;
function ProbeL(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData; overload;
function ProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData; overload;
function ProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData; overload;
function ProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData; overload;
function ProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData; overload;
function LProbe(startI: Integer; const acceptT: TTokenTypes): PTokenData; overload;
function LProbe(startI: Integer; const t: TPascalString): PTokenData; overload;
function LProbe(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData; overload;
function LProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData; overload;
function LProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData; overload;
function LProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData; overload;
function LProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData; overload;
{ token probe alias StartI->Right }
function ProbeR(startI: Integer; const acceptT: TTokenTypes): PTokenData; overload;
function ProbeR(startI: Integer; const t: TPascalString): PTokenData; overload;
function ProbeR(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData; overload;
function ProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData; overload;
function ProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData; overload;
function ProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData; overload;
function ProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData; overload;
function RProbe(startI: Integer; const acceptT: TTokenTypes): PTokenData; overload;
function RProbe(startI: Integer; const t: TPascalString): PTokenData; overload;
function RProbe(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData; overload;
function RProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData; overload;
function RProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData; overload;
function RProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData; overload;
function RProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData; overload;
{ free to match all strings from Token[StartIndex] left to right, including any symbols. return token }
function TokenFullStringProbe(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData;
function StringProbe(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData;
{ symbol Indent probe for end indent }
function IndentSymbolEndProbeR(startI: Integer; const indent_begin_symbol, indent_end_symbol: TPascalString): PTokenData;
{ symbol Indent probe for begin indent }
function IndentSymbolBeginProbeL(startI: Integer; const indent_begin_symbol, indent_end_symbol: TPascalString): PTokenData;
{ segmention text as symbol vector, L = output }
function DetectSymbolVector: Boolean;
function FillSymbolVector(L: TPascalStringList): Boolean; overload;
function FillSymbolVector: TSymbolVector; overload;
{ segmention text as symbol matrix }
function FillSymbolMatrix(W, H: Integer; var symbolMatrix: TSymbolMatrix): Boolean;
{ misc }
function GetText(const bPos, ePos: Integer): TPascalString; overload;
function GetStr(const bPos, ePos: Integer): TPascalString; overload;
function GetStr(const tp: TTextPos): TPascalString; overload;
function GetWord(const cOffset: Integer): TPascalString; overload;
function GetPoint(const cOffset: Integer): TPoint;
function GetChar(const cOffset: Integer): SystemChar;
property Len: Integer read ParsingData.Len;
property ParseText: TPascalString read ParsingData.Text;
property Text: TPascalString read ParsingData.Text;
procedure DeletePos(const bPos, ePos: Integer); overload;
procedure DeletePos(const tp: TTextPos); overload;
procedure DeletedComment;
procedure InsertTextBlock(const bPos, ePos: Integer; AInsertText: TPascalString); overload;
procedure InsertTextBlock(const tp: TTextPos; AInsertText: TPascalString); overload;
function SearchWordBody(initPos: Integer; wordInfo: TPascalString; var OutPos: TTextPos): Boolean;
{ string declaration }
class function TranslatePascalDeclToText(const Decl: TPascalString): TPascalString;
class function TranslateTextToPascalDecl(const Decl: TPascalString): TPascalString;
class function TranslateTextToPascalDeclWithUnicode(const Decl: TPascalString): TPascalString;
class function TranslateC_DeclToText(const Decl: TPascalString): TPascalString;
class function TranslateTextToC_Decl(const Decl: TPascalString): TPascalString;
{ comment declaration }
class function TranslatePascalDeclCommentToText(const Decl: TPascalString): TPascalString;
class function TranslateTextToPascalDeclComment(const Decl: TPascalString): TPascalString;
class function TranslateC_DeclCommentToText(const Decl: TPascalString): TPascalString;
class function TranslateTextToC_DeclComment(const Decl: TPascalString): TPascalString;
{ structor }
constructor Create(const Text_: TPascalString; Style_: TTextStyle; SpecialSymbol_: TListPascalString; SpacerSymbol_: SystemString); overload;
constructor Create(const Text_: TPascalString; Style_: TTextStyle; SpecialSymbol_: TListPascalString); overload;
constructor Create(const Text_: TPascalString; Style_: TTextStyle); overload;
constructor Create(const Text_: TPascalString); overload;
destructor Destroy; override;
{ external }
procedure Init; virtual;
function Parsing: Boolean; virtual;
{ debug }
procedure Print;
end;
TTextParsingClass = class of TTextParsing;
const
C_SpacerSymbol = #44#43#45#42#47#40#41#59#58#61#35#64#94#38#37#33#34#91#93#60#62#63#123#125#39#36#124;
var
SpacerSymbol: TAtomString;
implementation
uses DoStatusIO, TypInfo;
const
NullTokenStatistics: TTokenStatistics = (0, 0, 0, 0, 0, 0, 0);
type
TCTranslateStruct = record
s: SystemChar;
c: SystemString;
end;
const
CTranslateTable: array [0 .. 11] of TCTranslateStruct = (
(s: #007; c: '\a'),
(s: #008; c: '\b'),
(s: #012; c: '\f'),
(s: #010; c: '\n'),
(s: #013; c: '\r'),
(s: #009; c: '\t'),
(s: #011; c: '\v'),
(s: #092; c: '\\'),
(s: #063; c: '\?'),
(s: #039; c: '\'#39),
(s: #034; c: '\"'),
(s: #000; c: '\0'));
function TTextParsing.ComparePosStr(const cOffset: Integer; const t: TPascalString): Boolean;
begin
Result := ParsingData.Text.ComparePos(cOffset, t);
end;
function TTextParsing.ComparePosStr(const cOffset: Integer; const p: PPascalString): Boolean;
begin
Result := ParsingData.Text.ComparePos(cOffset, p);
end;
function TTextParsing.CompareCommentGetEndPos(const cOffset: Integer): Integer;
var
L: Integer;
cPos: Integer;
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
if p^.tokenType = TTokenType.ttComment then
Result := p^.ePos
else
Result := cOffset;
exit;
end;
end;
L := ParsingData.Len;
cPos := cOffset;
if cPos < 1 then
cPos := 1;
if cPos > L then
cPos := L;
Result := cPos;
if (TextStyle <> tsText) and (ComparePosStr(Result, '//')) then
begin
inc(Result, 2);
while not CharIn(ParsingData.Text[Result], [#13, #10]) do
begin
if Result + 1 > L then
Break;
inc(Result);
end;
end
else if (TextStyle = tsC) and (ComparePosStr(Result, '#')) then
begin
inc(Result, 1);
while not CharIn(ParsingData.Text[Result], [#13, #10]) do
begin
if Result + 1 > L then
Break;
inc(Result);
end;
end
else if (TextStyle = tsC) and (ComparePosStr(Result, '/*')) then
begin
inc(Result, 2);
while not ComparePosStr(Result, '*/') do
begin
if Result + 1 > L then
Break;
inc(Result);
end;
inc(Result, 2);
end
else if (TextStyle = tsPascal) and (ComparePosStr(Result, '{')) then
begin
inc(Result, 1);
while ParsingData.Text[Result] <> '}' do
begin
if Result + 1 > L then
Break;
inc(Result);
end;
inc(Result, 1);
end
else if (TextStyle = tsPascal) and (ComparePosStr(Result, '(*')) then
begin
inc(Result, 2);
while not ComparePosStr(Result, '*)') do
begin
if Result + 1 > L then
Break;
inc(Result);
end;
inc(Result, 2);
end;
end;
function TTextParsing.CompareTextDeclGetEndPos(const cOffset: Integer): Integer;
var
L: Integer;
cPos: Integer;
tmpPos: Integer;
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
if p^.tokenType = TTokenType.ttTextDecl then
Result := p^.ePos
else
Result := cOffset;
exit;
end;
end;
L := ParsingData.Len;
cPos := cOffset;
if cPos < 1 then
cPos := 1;
if cPos > L then
cPos := L;
if (cPos + 1 < L) and (TextStyle = tsPascal) and (ParsingData.Text[cPos] = #39) then
begin
if ComparePosStr(cPos, #39#39#39#39) then
begin
cPos := CompareTextDeclGetEndPos(cPos + 4);
exit(cPos);
end;
inc(cPos, 1);
while ParsingData.Text[cPos] <> #39 do
begin
if cPos + 1 > L then
Break;
if ParsingData.Text[cPos] = #10 then
exit(cPos);
inc(cPos);
end;
inc(cPos, 1);
end;
if (cPos + 1 < L) and (TextStyle = tsC) and (ParsingData.Text[cPos] = #39) then
begin
inc(cPos, 1);
while ParsingData.Text[cPos] <> #39 do
begin
if ComparePosStr(cPos, '\' + #39) then
inc(cPos, 1);
if cPos + 1 > L then
Break;
if ParsingData.Text[cPos] = #10 then
exit(cPos);
inc(cPos);
end;
inc(cPos, 1);
end;
if (cPos + 1 < L) and (TextStyle = tsC) and (ParsingData.Text[cPos] = '"') then
begin
inc(cPos, 1);
while ParsingData.Text[cPos] <> '"' do
begin
if ComparePosStr(cPos, '\"') then
inc(cPos, 1);
if cPos + 1 > L then
Break;
if ParsingData.Text[cPos] = #10 then
exit(cPos);
inc(cPos);
end;
inc(cPos, 1);
end;
if (cPos + 1 < L) and (TextStyle = tsPascal) and (ParsingData.Text[cPos] = '#') then
begin
repeat
inc(cPos, 1);
while isWordSplitChar(ParsingData.Text[cPos]) do
begin
if cPos + 1 > L then
exit(cPos);
inc(cPos);
end;
while CharIn(ParsingData.Text[cPos], [c0to9], '$') do
begin
if cPos + 1 > L then
exit(cPos);
inc(cPos);
end;
tmpPos := cPos;
while isWordSplitChar(ParsingData.Text[cPos]) do
begin
if cPos + 1 > L then
exit(cPos);
inc(cPos);
end;
until not ComparePosStr(cPos, '#');
cPos := CompareTextDeclGetEndPos(tmpPos);
end;
Result := cPos;
end;
procedure TTextParsing.RebuildParsingCache;
var
i, j: Integer;
L: Integer;
bPos: Integer;
ePos: Integer;
textPosPtr: PTextPos;
LastTokenData: PTokenData;
begin
RebuildCacheBusy := True;
if ParsingData.Cache.CommentDecls <> nil then
begin
for i := 0 to ParsingData.Cache.CommentDecls.Count - 1 do
Dispose(PTextPos(ParsingData.Cache.CommentDecls[i]));
DisposeObject(ParsingData.Cache.CommentDecls);
ParsingData.Cache.CommentDecls := nil;
end;
if ParsingData.Cache.TextDecls <> nil then
begin
for i := 0 to ParsingData.Cache.TextDecls.Count - 1 do
Dispose(PTextPos(ParsingData.Cache.TextDecls[i]));
DisposeObject(ParsingData.Cache.TextDecls);
ParsingData.Cache.TextDecls := nil;
end;
if ParsingData.Cache.TokenDataList <> nil then
begin
for i := 0 to ParsingData.Cache.TokenDataList.Count - 1 do
Dispose(PTokenData(ParsingData.Cache.TokenDataList[i]));
DisposeObject(ParsingData.Cache.TokenDataList);
ParsingData.Cache.TokenDataList := nil;
end;
TokenStatistics := NullTokenStatistics;
ParsingData.Cache.CommentDecls := TCoreClassList.Create;
ParsingData.Cache.TextDecls := TCoreClassList.Create;
ParsingData.Cache.TokenDataList := TCoreClassList.Create;
SetLength(ParsingData.Cache.CharToken, 0);
// rebuild comment and text
L := ParsingData.Len;
bPos := 1;
ePos := bPos;
while (bPos <= L) do
begin
ePos := CompareCommentGetEndPos(bPos);
if ePos > bPos then
begin
new(textPosPtr);
textPosPtr^.bPos := bPos;
textPosPtr^.ePos := ePos;
textPosPtr^.Text := GetStr(textPosPtr^);
ParsingData.Cache.CommentDecls.Add(textPosPtr);
bPos := ePos;
end
else
begin
ePos := CompareTextDeclGetEndPos(bPos);
if ePos > bPos then
begin
new(textPosPtr);
textPosPtr^.bPos := bPos;
textPosPtr^.ePos := ePos;
textPosPtr^.Text := GetStr(textPosPtr^);
ParsingData.Cache.TextDecls.Add(textPosPtr);
bPos := ePos;
end
else
begin
inc(bPos);
ePos := bPos;
end;
end;
end;
// rebuild token
bPos := 1;
ePos := bPos;
LastTokenData := nil;
while bPos <= L do
begin
if isSpecialSymbol(bPos, ePos) then
begin
new(LastTokenData);
LastTokenData^.bPos := bPos;
LastTokenData^.ePos := ePos;
LastTokenData^.Text := GetStr(bPos, ePos);
LastTokenData^.tokenType := ttSpecialSymbol;
LastTokenData^.Index := ParsingData.Cache.TokenDataList.Count;
ParsingData.Cache.TokenDataList.Add(LastTokenData);
inc(TokenStatistics[LastTokenData^.tokenType]);
bPos := ePos
end
else if isTextDecl(bPos) then
begin
ePos := GetTextDeclEndPos(bPos);
new(LastTokenData);
LastTokenData^.bPos := bPos;
LastTokenData^.ePos := ePos;
LastTokenData^.Text := GetStr(bPos, ePos);
LastTokenData^.tokenType := ttTextDecl;
LastTokenData^.Index := ParsingData.Cache.TokenDataList.Count;
ParsingData.Cache.TokenDataList.Add(LastTokenData);
inc(TokenStatistics[LastTokenData^.tokenType]);
bPos := ePos
end
else if isComment(bPos) then
begin
ePos := GetCommentEndPos(bPos);
new(LastTokenData);
LastTokenData^.bPos := bPos;
LastTokenData^.ePos := ePos;
LastTokenData^.Text := GetStr(bPos, ePos);
LastTokenData^.tokenType := ttComment;
LastTokenData^.Index := ParsingData.Cache.TokenDataList.Count;
ParsingData.Cache.TokenDataList.Add(LastTokenData);
inc(TokenStatistics[LastTokenData^.tokenType]);
bPos := ePos;
end
else if isNumber(bPos) then
begin
ePos := GetNumberEndPos(bPos);
new(LastTokenData);
LastTokenData^.bPos := bPos;
LastTokenData^.ePos := ePos;
LastTokenData^.Text := GetStr(bPos, ePos);
LastTokenData^.tokenType := ttNumber;
LastTokenData^.Index := ParsingData.Cache.TokenDataList.Count;
ParsingData.Cache.TokenDataList.Add(LastTokenData);
inc(TokenStatistics[LastTokenData^.tokenType]);
bPos := ePos;
end
else if isSymbol(bPos) then
begin
ePos := GetSymbolEndPos(bPos);
new(LastTokenData);
LastTokenData^.bPos := bPos;
LastTokenData^.ePos := ePos;
LastTokenData^.Text := GetStr(bPos, ePos);
LastTokenData^.tokenType := ttSymbol;
LastTokenData^.Index := ParsingData.Cache.TokenDataList.Count;
ParsingData.Cache.TokenDataList.Add(LastTokenData);
inc(TokenStatistics[LastTokenData^.tokenType]);
bPos := ePos;
end
else if isAscii(bPos) then
begin
ePos := GetAsciiEndPos(bPos);
new(LastTokenData);
LastTokenData^.bPos := bPos;
LastTokenData^.ePos := ePos;
LastTokenData^.Text := GetStr(bPos, ePos);
LastTokenData^.tokenType := ttAscii;
LastTokenData^.Index := ParsingData.Cache.TokenDataList.Count;
ParsingData.Cache.TokenDataList.Add(LastTokenData);
inc(TokenStatistics[LastTokenData^.tokenType]);
bPos := ePos;
end
else
begin
ePos := bPos + 1;
if (LastTokenData = nil) or (LastTokenData^.tokenType <> ttUnknow) then
begin
new(LastTokenData);
LastTokenData^.bPos := bPos;
LastTokenData^.ePos := ePos;
LastTokenData^.Text := GetStr(bPos, ePos);
LastTokenData^.tokenType := ttUnknow;
LastTokenData^.Index := ParsingData.Cache.TokenDataList.Count;
ParsingData.Cache.TokenDataList.Add(LastTokenData);
inc(TokenStatistics[LastTokenData^.tokenType]);
end
else
begin
LastTokenData^.ePos := ePos;
LastTokenData^.Text.Append(GetChar(bPos));
end;
bPos := ePos;
end;
end;
SetLength(ParsingData.Cache.CharToken, L);
for i := 0 to ParsingData.Cache.TokenDataList.Count - 1 do
begin
LastTokenData := PTokenData(ParsingData.Cache.TokenDataList[i]);
for j := LastTokenData^.bPos to LastTokenData^.ePos - 1 do
ParsingData.Cache.CharToken[j - 1] := LastTokenData;
end;
RebuildCacheBusy := False;
end;
procedure TTextParsing.RebuildText;
procedure Recompute(bPos, d: Integer);
var
i: Integer;
p: PTextPos;
begin
for i := 0 to ParsingData.Cache.TextDecls.Count - 1 do
begin
p := PTextPos(ParsingData.Cache.TextDecls[i]);
if bPos < p^.bPos then
begin
p^.bPos := p^.bPos - d;
p^.ePos := p^.ePos - d;
end;
end;
for i := 0 to ParsingData.Cache.CommentDecls.Count - 1 do
begin
p := PTextPos(ParsingData.Cache.CommentDecls[i]);
if bPos < p^.bPos then
begin
p^.bPos := p^.bPos - d;
p^.ePos := p^.ePos - d;
end;
end;
end;
var
p: PTextPos;
i: Integer;
begin
for i := 0 to ParsingData.Cache.TextDecls.Count - 1 do
begin
p := PTextPos(ParsingData.Cache.TextDecls[i]);
if p^.ePos - p^.bPos <> (p^.Text.Len) then
Recompute(p^.bPos, (p^.ePos - p^.bPos) - p^.Text.Len);
ParsingData.Text := GetStr(1, p^.bPos) + p^.Text + GetStr(p^.ePos, ParsingData.Text.Len + 1);
ParsingData.Len := ParsingData.Text.Len;
p^.ePos := p^.bPos + p^.Text.Len;
end;
for i := 0 to ParsingData.Cache.CommentDecls.Count - 1 do
begin
p := PTextPos(ParsingData.Cache.CommentDecls[i]);
if p^.ePos - p^.bPos <> (p^.Text.Len) then
Recompute(p^.bPos, (p^.ePos - p^.bPos) - p^.Text.Len);
ParsingData.Text := GetStr(1, p^.bPos) + p^.Text + GetStr(p^.ePos, ParsingData.Text.Len + 1);
ParsingData.Len := ParsingData.Text.Len;
p^.ePos := p^.bPos + p^.Text.Len;
end;
RebuildParsingCache;
end;
procedure TTextParsing.RebuildToken;
var
p: PTokenData;
i: Integer;
begin
ParsingData.Text := '';
for i := 0 to ParsingData.Cache.TokenDataList.Count - 1 do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[i]);
ParsingData.Text.Append(p^.Text);
end;
ParsingData.Len := ParsingData.Text.Len;
RebuildParsingCache;
end;
function TTextParsing.GetContextBeginPos(const cOffset: Integer): Integer;
var
p: PTokenData;
begin
Result := cOffset;
p := TokenPos[cOffset];
if p = nil then
exit;
Result := p^.bPos;
end;
function TTextParsing.GetContextEndPos(const cOffset: Integer): Integer;
var
p: PTokenData;
begin
Result := cOffset;
p := TokenPos[cOffset];
if p = nil then
exit;
Result := p^.ePos;
end;
function TTextParsing.isSpecialSymbol(const cOffset: Integer): Boolean;
var
ePos: Integer;
begin
Result := isSpecialSymbol(cOffset, ePos);
end;
function TTextParsing.isSpecialSymbol(const cOffset: Integer; var speicalSymbolEndPos: Integer): Boolean;
var
i, EP: Integer;
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
Result := p^.tokenType = TTokenType.ttSpecialSymbol;
if Result then
speicalSymbolEndPos := p^.ePos;
exit;
end;
end;
Result := False;
speicalSymbolEndPos := cOffset;
if SpecialSymbol.Count = 0 then
exit;
if isComment(cOffset) then
exit;
if isTextDecl(cOffset) then
exit;
speicalSymbolEndPos := cOffset;
for i := 0 to SpecialSymbol.Count - 1 do
if ComparePosStr(cOffset, SpecialSymbol.Items_PPascalString[i]) then
begin
EP := cOffset + SpecialSymbol[i].Len;
if EP > speicalSymbolEndPos then
speicalSymbolEndPos := EP;
Result := True;
end;
end;
function TTextParsing.GetSpecialSymbolEndPos(const cOffset: Integer): Integer;
begin
if not isSpecialSymbol(cOffset, Result) then
Result := cOffset;
end;
function TTextParsing.isNumber(const cOffset: Integer): Boolean;
var
tmp: Integer;
IsHex: Boolean;
begin
Result := isNumber(cOffset, tmp, IsHex);
end;
function TTextParsing.isNumber(const cOffset: Integer; var NumberBegin: Integer; var IsHex: Boolean): Boolean;
var
c: SystemChar;
L: Integer;
cPos, bkPos: Integer;
NC: Integer;
dotNum: Integer;
eNum: Integer;
eSymNum: Integer;
pSym: Integer;
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
Result := p^.tokenType = TTokenType.ttNumber;
if Result then
begin
NumberBegin := p^.bPos;
IsHex := p^.Text.ComparePos(1, '$') or p^.Text.ComparePos(1, '0x');
end;
exit;
end;
end;
Result := False;
cPos := cOffset;
L := ParsingData.Len;
if cPos < 1 then
cPos := 1;
if cPos > L then
cPos := L;
if cPos = L then
exit;
IsHex := False;
try
if (CharIn(ParsingData.Text[cPos], '$')) then
begin
// pascal style hex
IsHex := True;
inc(cPos);
if cPos > L then
exit;
end
else if ComparePosStr(cPos, '0x') then
begin
// c style hex
IsHex := True;
inc(cPos, 2);
if cPos > L then
exit;
end;
except
end;
if IsHex then
begin
bkPos := cPos;
NC := 0;
while True do
begin
cPos := GetTextDeclEndPos(GetCommentEndPos(cPos));
if cPos > L then
Break;
c := ParsingData.Text[cPos];
if isWordSplitChar(c, True, SymbolTable) then
begin
if NC > 0 then
Break;
end
else if CharIn(c, cHex) then
inc(NC)
else
begin
Result := False;
exit;
end;
inc(cPos);
end;
Result := (NC > 0);
NumberBegin := bkPos;
exit;
end;
c := ParsingData.Text[cPos];
if CharIn(c, c0to9) then
begin
bkPos := cPos;
NC := 0;
dotNum := 0;
eNum := 0;
eSymNum := 0;
while True do
begin
cPos := GetTextDeclEndPos(GetCommentEndPos(cPos));
if cPos > L then
Break;
c := ParsingData.Text[cPos];
if CharIn(c, '.') then
begin
inc(dotNum);
if dotNum > 1 then
Break;
end
else if CharIn(c, c0to9) then
inc(NC)
else if (NC > 0) and (eNum = 0) and CharIn(c, 'eE') then
begin
inc(eNum);
end
else if (NC > 0) and (eNum = 1) and CharIn(c, '-+') then
begin
inc(eSymNum);
end
else if isWordSplitChar(c, True, SymbolTable) then
begin
Break;
end
else if CharIn(c, cAtoZ) then
begin
Result := False;
exit;
end;
inc(cPos);
end;
Result := (NC > 0) and (dotNum <= 1);
NumberBegin := bkPos;
exit;
end
else if CharIn(c, '+-.') then
begin
bkPos := cPos;
NC := 0;
dotNum := 0;
eNum := 0;
eSymNum := 0;
pSym := 0;
while True do
begin
cPos := GetTextDeclEndPos(GetCommentEndPos(cPos));
if cPos > L then
Break;
c := ParsingData.Text[cPos];
if (NC = 0) and (eSymNum = 0) and (eNum = 0) and CharIn(c, '-+') then
begin
inc(pSym);
end
else if CharIn(c, '.') then
begin
inc(dotNum);
if dotNum > 1 then
Break;
end
else if CharIn(c, c0to9) then
inc(NC)
else if (NC > 0) and (eNum = 0) and CharIn(c, 'eE') then
begin
inc(eNum);
end
else if (NC > 0) and (eNum = 1) and CharIn(c, '-+') then
begin
inc(eSymNum);
end
else if isWordSplitChar(c, True, SymbolTable) then
begin
Break
end
else if CharIn(c, cAtoZ) then
begin
Result := False;
exit;
end;
inc(cPos);
end;
Result := (NC > 0) and (dotNum <= 1);
NumberBegin := bkPos;
exit;
end;
end;
function TTextParsing.GetNumberEndPos(const cOffset: Integer): Integer;
var
IsHex: Boolean;
L: Integer;
cPos: Integer;
c: SystemChar;
NC: Integer;
dotNum: Integer;
eNum: Integer;
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
if p^.tokenType = TTokenType.ttNumber then
Result := p^.ePos
else
Result := cOffset;
exit;
end;
end;
L := ParsingData.Len;
cPos := cOffset;
if cPos < 1 then
cPos := 1;
if cPos > L then
cPos := L;
if isNumber(cPos, Result, IsHex) then
begin
NC := 0;
dotNum := 0;
eNum := 0;
while True do
begin
if isComment(Result) or isTextDecl(Result) then
Break;
c := ParsingData.Text[Result];
if (not CharIn(c, [c0to9])) then
begin
if CharIn(c, '+-') then
begin
if NC > 0 then
begin
if eNum = 1 then
inc(eNum)
else
exit;
end;
end
else if (not IsHex) and CharIn(c, '.') then
begin
if (dotNum > 1) then
exit;
inc(dotNum);
end
else if (not IsHex) and CharIn(c, 'eE') then
begin
if (eNum > 1) then
exit;
inc(eNum);
end
else if (IsHex and (CharIn(c, [cLoAtoF, cHiAtoF]))) then
inc(NC)
else
exit;
end
else
inc(NC);
inc(Result);
if Result > L then
exit;
end;
end
else
Result := cPos;
end;
function TTextParsing.isTextDecl(const cOffset: Integer): Boolean;
var
bPos, ePos: Integer;
begin
Result := GetTextDeclPos(cOffset, bPos, ePos);
end;
function TTextParsing.GetTextDeclEndPos(const cOffset: Integer): Integer;
var
bPos, ePos: Integer;
begin
if GetTextDeclPos(cOffset, bPos, ePos) then
Result := ePos
else
Result := cOffset;
end;
function TTextParsing.GetTextDeclBeginPos(const cOffset: Integer): Integer;
var
bPos, ePos: Integer;
begin
if GetTextDeclPos(cOffset, bPos, ePos) then
Result := bPos
else
Result := cOffset;
end;
function TTextParsing.GetTextBody(const Text_: TPascalString): TPascalString;
begin
if TextStyle = tsPascal then
Result := TranslatePascalDeclToText(Text_)
else if TextStyle = tsC then
Result := TranslateC_DeclToText(Text_)
else
Result := Text_;
end;
function TTextParsing.GetTextDeclPos(const cOffset: Integer; var charBeginPos, charEndPos: Integer): Boolean;
function CompLst(idx: Integer): Integer;
begin
with PTextPos(ParsingData.Cache.TextDecls[idx])^ do
begin
if (cOffset >= bPos) and (cOffset < ePos) then
Result := 0
else if (cOffset >= ePos) then
Result := -1
else if (cOffset < bPos) then
Result := 1
else
Result := -2;
end;
end;
var
cPos, L, r, M: Integer;
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
Result := p^.tokenType = TTokenType.ttTextDecl;
if Result then
begin
charBeginPos := p^.bPos;
charEndPos := p^.ePos;
end;
exit;
end;
end;
cPos := cOffset;
if cPos < 1 then
cPos := 1;
if cPos > ParsingData.Len then
cPos := ParsingData.Len;
if ParsingData.Cache.TextDecls = nil then
RebuildParsingCache;
Result := False;
L := 0;
r := ParsingData.Cache.TextDecls.Count - 1;
while L <= r do
begin
M := (L + r) div 2;
case CompLst(M) of
0:
begin
with PTextPos(ParsingData.Cache.TextDecls[M])^ do
begin
charBeginPos := bPos;
charEndPos := ePos;
end;
Result := True;
exit;
end;
-1: L := M + 1;
1: r := M - 1;
else RaiseInfo('struct error');
end;
end;
end;
function TTextParsing.isSymbol(const cOffset: Integer): Boolean;
var
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
Result := p^.tokenType = TTokenType.ttSymbol;
exit;
end;
end;
Result := CharIn(ParsingData.Text[cOffset], SymbolTable)
end;
function TTextParsing.GetSymbolEndPos(const cOffset: Integer): Integer;
begin
if isSymbol(cOffset) then
Result := cOffset + 1
else
Result := cOffset;
end;
function TTextParsing.isAscii(const cOffset: Integer): Boolean;
var
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
Result := p^.tokenType = TTokenType.ttAscii;
exit;
end;
end;
Result := False;
if isComment(cOffset) then
exit;
if isTextDecl(cOffset) then
exit;
if isSpecialSymbol(cOffset) then
exit;
Result := (not isSymbol(cOffset)) and (not isWordSplitChar(ParsingData.Text[cOffset], True, SymbolTable)) and (not isNumber(cOffset));
end;
function TTextParsing.GetAsciiBeginPos(const cOffset: Integer): Integer;
var
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
if p^.tokenType = TTokenType.ttAscii then
Result := p^.bPos
else
Result := cOffset;
exit;
end;
end;
Result := GetWordBeginPos(cOffset, True, SymbolTable);
end;
function TTextParsing.GetAsciiEndPos(const cOffset: Integer): Integer;
var
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
if p^.tokenType = TTokenType.ttAscii then
Result := p^.ePos
else
Result := cOffset;
exit;
end;
end;
Result := GetWordEndPos(cOffset, True, SymbolTable, True, SymbolTable);
end;
function TTextParsing.isComment(const cOffset: Integer): Boolean;
var
bPos, ePos: Integer;
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
Result := p^.tokenType = TTokenType.ttComment;
exit;
end;
end;
Result := GetCommentPos(cOffset, bPos, ePos);
end;
function TTextParsing.GetCommentEndPos(const cOffset: Integer): Integer;
var
bPos, ePos: Integer;
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
if p^.tokenType = TTokenType.ttComment then
Result := p^.ePos
else
Result := cOffset;
exit;
end;
end;
if GetCommentPos(cOffset, bPos, ePos) then
Result := ePos
else
Result := cOffset;
end;
function TTextParsing.GetCommentBeginPos(const cOffset: Integer): Integer;
var
bPos, ePos: Integer;
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
if p^.tokenType = TTokenType.ttComment then
Result := p^.bPos
else
Result := cOffset;
exit;
end;
end;
if GetCommentPos(cOffset, bPos, ePos) then
Result := bPos
else
Result := cOffset;
end;
function TTextParsing.GetCommentPos(const cOffset: Integer; var charBeginPos, charEndPos: Integer): Boolean;
function CompLst(idx: Integer): Integer;
begin
with PTextPos(ParsingData.Cache.CommentDecls[idx])^ do
begin
if (cOffset >= bPos) and (cOffset < ePos) then
Result := 0
else if (cOffset >= ePos) then
Result := -1
else if (cOffset < bPos) then
Result := 1
else
Result := -2;
end;
end;
var
cPos, L, r, M: Integer;
p: PTokenData;
begin
if not RebuildCacheBusy then
begin
p := TokenPos[cOffset];
if p <> nil then
begin
Result := p^.tokenType = TTokenType.ttComment;
if Result then
begin
charBeginPos := p^.bPos;
charEndPos := p^.ePos;
end;
exit;
end;
end;
cPos := cOffset;
if cPos < 1 then
cPos := 1;
if cPos > ParsingData.Len then
cPos := ParsingData.Len;
if ParsingData.Cache.CommentDecls = nil then
RebuildParsingCache;
Result := False;
L := 0;
r := ParsingData.Cache.CommentDecls.Count - 1;
while L <= r do
begin
M := (L + r) div 2;
case CompLst(M) of
0:
begin
with PTextPos(ParsingData.Cache.CommentDecls[M])^ do
begin
charBeginPos := bPos;
charEndPos := ePos;
end;
Result := True;
exit;
end;
-1: L := M + 1;
1: r := M - 1;
else RaiseInfo('struct error');
end;
end;
end;
function TTextParsing.GetDeletedCommentText: TPascalString;
var
oriPos, cPos, nPos: Integer;
begin
Result := '';
cPos := 1;
oriPos := cPos;
while cPos < ParsingData.Len do
begin
nPos := CompareCommentGetEndPos(cPos);
if nPos > cPos then
begin
Result := Result + GetStr(oriPos, cPos);
cPos := nPos;
oriPos := cPos;
end
else
begin
inc(cPos);
end;
end;
if oriPos <= ParsingData.Len then
Result := Result + GetStr(oriPos, ParsingData.Len + 1);
Result := Result.TrimChar(#32);
end;
function TTextParsing.isTextOrComment(const cOffset: Integer): Boolean;
begin
Result := isTextDecl(cOffset) or isComment(cOffset);
end;
function TTextParsing.isCommentOrText(const cOffset: Integer): Boolean;
begin
Result := isComment(cOffset) or isTextDecl(cOffset);
end;
class function TTextParsing.isWordSplitChar(const c: SystemChar; SplitTokenC: TPascalString): Boolean;
begin
Result := isWordSplitChar(c, True, SplitTokenC);
end;
class function TTextParsing.isWordSplitChar(const c: SystemChar): Boolean;
begin
Result := isWordSplitChar(c, True, '');
end;
class function TTextParsing.isWordSplitChar(const c: SystemChar; DefaultChar: Boolean; SplitTokenC: TPascalString): Boolean;
begin
if DefaultChar then
Result := CharIn(c, [c0to32], SplitTokenC)
else
Result := CharIn(c, SplitTokenC);
end;
function TTextParsing.GetWordBeginPos(const cOffset: Integer; SplitTokenC: TPascalString): Integer;
begin
Result := GetWordBeginPos(cOffset, True, SplitTokenC);
end;
function TTextParsing.GetWordBeginPos(const cOffset: Integer): Integer;
begin
Result := GetWordBeginPos(cOffset, True, '');
end;
function TTextParsing.GetWordBeginPos(const cOffset: Integer; BeginDefaultChar: Boolean; SplitTokenC: TPascalString): Integer;
var
L: Integer;
cPos: Integer;
tbPos: Integer;
begin
L := ParsingData.Len;
cPos := cOffset;
if cPos < 1 then
exit(1);
if cPos > L then
exit(L);
repeat
cPos := GetCommentEndPos(cPos);
tbPos := GetTextDeclBeginPos(cPos);
if tbPos <> cPos then
exit(tbPos);
while (isWordSplitChar(ParsingData.Text[cPos], BeginDefaultChar, SplitTokenC)) do
begin
if cPos >= L then
Break;
inc(cPos);
end;
until not isComment(cPos);
Result := cPos;
while (not isWordSplitChar(ParsingData.Text[Result], BeginDefaultChar, SplitTokenC)) do
begin
if Result - 1 <= 0 then
Break;
dec(Result);
end;
if isWordSplitChar(ParsingData.Text[Result], SplitTokenC) then
inc(Result);
end;
function TTextParsing.GetWordEndPos(const cOffset: Integer; SplitTokenC: TPascalString): Integer;
begin
Result := GetWordEndPos(cOffset, True, SplitTokenC, True, SplitTokenC);
end;
function TTextParsing.GetWordEndPos(const cOffset: Integer): Integer;
begin
Result := GetWordEndPos(cOffset, True, '', True, '');
end;
function TTextParsing.GetWordEndPos(const cOffset: Integer; BeginSplitCharSet, EndSplitCharSet: TPascalString): Integer;
begin
Result := GetWordEndPos(cOffset, True, BeginSplitCharSet, True, EndSplitCharSet);
end;
function TTextParsing.GetWordEndPos(const cOffset: Integer;
BeginDefaultChar: Boolean; BeginSplitCharSet: TPascalString;
EndDefaultChar: Boolean; EndSplitCharSet: TPascalString): Integer;
var
L: Integer;
begin
L := ParsingData.Len;
if cOffset < 1 then
exit(1);
if cOffset > L then
exit(L);
Result := GetWordBeginPos(cOffset, BeginDefaultChar, BeginSplitCharSet);
while (not isWordSplitChar(ParsingData.Text[Result], EndDefaultChar, EndSplitCharSet)) do
begin
inc(Result);
if Result > L then
Break;
end;
end;
function TTextParsing.SniffingNextChar(const cOffset: Integer; declChar: TPascalString): Boolean;
var
tmp: Integer;
begin
Result := SniffingNextChar(cOffset, declChar, tmp);
end;
function TTextParsing.SniffingNextChar(const cOffset: Integer; declChar: TPascalString; out OutPos: Integer): Boolean;
var
L: Integer;
cPos: Integer;
begin
L := ParsingData.Len;
cPos := cOffset;
if cPos < 1 then
cPos := 1;
if cPos > L then
exit(False);
while isWordSplitChar(ParsingData.Text[cPos]) or (isTextOrComment(cPos)) do
begin
inc(cPos);
if cPos > L then
exit(False);
end;
if (cPos < L) then
Result := CharIn(ParsingData.Text[cPos], declChar)
else
Result := False;
if Result then
OutPos := cPos;
end;
function TTextParsing.SplitChar(const cOffset: Integer; var LastPos: Integer; const SplitTokenC, SplitEndTokenC: TPascalString; var SplitOutput: TSymbolVector): Integer;
procedure AddS(const s: TPascalString);
var
n: TPascalString;
L: Integer;
begin
n := s.TrimChar(#32#0);
if n.Len = 0 then
exit;
L := Length(SplitOutput);
SetLength(SplitOutput, L + 1);
SplitOutput[L] := n;
inc(Result);
end;
type
TLastSym = (lsBody, lsNone);
var
L: Integer;
c: SystemChar;
cPos, bPos, ePos: Integer;
LastSym: TLastSym;
begin
Result := 0;
SetLength(SplitOutput, 0);
LastPos := cOffset;
L := ParsingData.Len;
cPos := cOffset;
if cPos < 1 then
cPos := 1;
if cPos > L then
exit;
bPos := cPos;
ePos := bPos;
LastSym := lsNone;
while (cPos <= L) do
begin
if isComment(cPos) then
begin
cPos := GetCommentEndPos(cPos);
Continue;
end;
if isTextDecl(cPos) then
begin
cPos := GetTextDeclEndPos(cPos);
Continue;
end;
c := ParsingData.Text[cPos];
if isWordSplitChar(c, True, SplitTokenC) then
begin
if LastSym = lsBody then
begin
ePos := cPos;
AddS(GetStr(bPos, ePos));
LastSym := lsNone;
end;
inc(cPos);
Continue;
end;
if (isWordSplitChar(c, False, SplitEndTokenC)) then
begin
if LastSym = lsBody then
begin
ePos := cPos;
AddS(GetStr(bPos, ePos));
LastSym := lsNone;
end;
LastPos := cPos;
exit;
end;
if LastSym = lsNone then
begin
bPos := cPos;
LastSym := lsBody;
end;
inc(cPos);
end;
if LastSym = lsBody then
begin
ePos := cPos;
AddS(GetStr(bPos, ePos));
LastSym := lsNone;
end;
LastPos := cPos;
end;
function TTextParsing.SplitChar(const cOffset: Integer; const SplitTokenC, SplitEndTokenC: TPascalString; var SplitOutput: TSymbolVector): Integer;
var
t: Integer;
begin
Result := SplitChar(cOffset, t, SplitTokenC, SplitEndTokenC, SplitOutput);
end;
function TTextParsing.SplitString(const cOffset: Integer; var LastPos: Integer; const SplitTokenS, SplitEndTokenS: TPascalString; var SplitOutput: TSymbolVector): Integer;
procedure AddS(s: TPascalString);
var
L: Integer;
begin
s := s.TrimChar(#32#0);
if s.Len = 0 then
exit;
L := Length(SplitOutput);
SetLength(SplitOutput, L + 1);
SplitOutput[L] := s;
inc(Result);
end;
type
TLastSym = (lsBody, lsNone);
var
L: Integer;
c: SystemChar;
cPos, bPos, ePos: Integer;
LastSym: TLastSym;
begin
Result := 0;
SetLength(SplitOutput, 0);
LastPos := cOffset;
L := ParsingData.Len;
cPos := cOffset;
if cPos < 1 then
cPos := 1;
if cPos > L then
exit;
bPos := cPos;
ePos := bPos;
LastSym := lsNone;
while (cPos <= L) do
begin
if isComment(cPos) then
begin
cPos := GetCommentEndPos(cPos);
Continue;
end;
if isTextDecl(cPos) then
begin
cPos := GetTextDeclEndPos(cPos);
Continue;
end;
if ComparePosStr(cPos, SplitTokenS) then
begin
if LastSym = lsBody then
begin
ePos := cPos;
AddS(GetStr(bPos, ePos));
LastSym := lsNone;
end;
inc(cPos, SplitTokenS.Len);
Continue;
end;
if ComparePosStr(cPos, SplitEndTokenS) then
begin
if LastSym = lsBody then
begin
ePos := cPos;
AddS(GetStr(bPos, ePos));
LastSym := lsNone;
end;
LastPos := cPos;
exit;
end;
if LastSym = lsNone then
begin
bPos := cPos;
LastSym := lsBody;
end;
inc(cPos);
end;
if LastSym = lsBody then
begin
ePos := cPos;
AddS(GetStr(bPos, ePos));
LastSym := lsNone;
end;
LastPos := cPos;
end;
function TTextParsing.SplitString(const cOffset: Integer; const SplitTokenS, SplitEndTokenS: TPascalString; var SplitOutput: TSymbolVector): Integer;
var
t: Integer;
begin
Result := SplitString(cOffset, t, SplitTokenS, SplitEndTokenS, SplitOutput);
end;
function TTextParsing.CompareTokenText(const cOffset: Integer; t: TPascalString): Boolean;
var
p: PTokenData;
begin
Result := False;
p := GetToken(cOffset);
if p = nil then
exit;
Result := p^.Text.Same(t);
end;
function TTextParsing.CompareTokenChar(const cOffset: Integer; const c: array of SystemChar): Boolean;
var
p: PTokenData;
begin
Result := False;
p := GetToken(cOffset);
if p = nil then
exit;
if p^.Text.Len <> 1 then
exit;
Result := CharIn(p^.Text.First, c);
end;
function TTextParsing.GetToken(const cOffset: Integer): PTokenData;
begin
if (cOffset - 1 >= 0) and (cOffset - 1 < Length(ParsingData.Cache.CharToken)) then
Result := ParsingData.Cache.CharToken[cOffset - 1]
else
Result := nil;
end;
function TTextParsing.GetTokenIndex(t: TTokenType; idx: Integer): PTokenData;
var
i, c: Integer;
p: PTokenData;
begin
Result := nil;
c := 0;
for i := 0 to ParsingData.Cache.TokenDataList.Count - 1 do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[i]);
if p^.tokenType = t then
begin
if c = idx then
exit(p)
else
inc(c);
end;
end;
end;
function TTextParsing.TokenCount: Integer;
begin
Result := ParsingData.Cache.TokenDataList.Count;
end;
function TTextParsing.TokenCountT(t: TTokenTypes): Integer;
var
i: Integer;
begin
Result := 0;
for i := ParsingData.Cache.TokenDataList.Count - 1 downto 0 do
if GetTokens(i)^.tokenType in t then
inc(Result);
end;
function TTextParsing.GetTokens(idx: Integer): PTokenData;
begin
Result := PTokenData(ParsingData.Cache.TokenDataList[idx]);
end;
function TTextParsing.FirstToken: PTokenData;
begin
Result := GetTokens(0);
end;
function TTextParsing.LastToken: PTokenData;
begin
Result := GetTokens(TokenCount - 1);
end;
function TTextParsing.NextToken(p: PTokenData): PTokenData;
begin
Result := nil;
if (p = nil) or (p^.Index + 1 >= TokenCount) then
exit;
Result := Tokens[p^.Index + 1];
end;
function TTextParsing.PrevToken(p: PTokenData): PTokenData;
begin
Result := nil;
if (p = nil) or (p^.Index - 1 >= 0) then
exit;
Result := Tokens[p^.Index - 1];
end;
function TTextParsing.TokenCombine(const bTokenI, eTokenI: Integer; const acceptT: TTokenTypes): TPascalString;
var
bi, ei: Integer;
p: PTokenData;
begin
Result := '';
if (bTokenI < 0) or (eTokenI < 0) then
exit;
if bTokenI > eTokenI then
begin
bi := eTokenI;
ei := bTokenI;
end
else
begin
bi := bTokenI;
ei := eTokenI;
end;
while (bi <= ei) and (bi < TokenCount) do
begin
p := Tokens[bi];
if p^.tokenType in acceptT then
Result.Append(p^.Text);
inc(bi);
end;
if (bi >= TokenCount) then
begin
while (Result.Len > 0) and (Result.Last = #0) do
Result.DeleteLast;
if (Result.Len > 0) and (Result.Last = #32) then
Result.DeleteLast;
end;
end;
function TTextParsing.TokenCombine(const bTokenI, eTokenI: Integer): TPascalString;
begin
Result := TokenCombine(bTokenI, eTokenI, [ttTextDecl, ttComment, ttNumber, ttSymbol, ttAscii, ttSpecialSymbol, ttUnknow]);
end;
function TTextParsing.Combine(const bTokenI, eTokenI: Integer; const acceptT: TTokenTypes): TPascalString;
begin
Result := TokenCombine(bTokenI, eTokenI, acceptT);
end;
function TTextParsing.Combine(const bTokenI, eTokenI: Integer): TPascalString;
begin
Result := TokenCombine(bTokenI, eTokenI);
end;
function TTextParsing.TokenProbeL(startI: Integer; const acceptT: TTokenTypes): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx >= 0 do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) then
begin
Result := p;
exit;
end
else
dec(idx);
end;
end;
function TTextParsing.TokenProbeL(startI: Integer; const t: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx >= 0 do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.Text.Same(t)) then
begin
Result := p;
exit;
end
else
dec(idx);
end;
end;
function TTextParsing.TokenProbeL(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx >= 0 do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (p^.Text.Same(t)) then
begin
Result := p;
exit;
end
else
dec(idx);
end;
end;
function TTextParsing.TokenProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx >= 0 do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (p^.Text.Same(t1, t2)) then
begin
Result := p;
exit;
end
else
dec(idx);
end;
end;
function TTextParsing.TokenProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx >= 0 do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (p^.Text.Same(t1, t2, t3)) then
begin
Result := p;
exit;
end
else
dec(idx);
end;
end;
function TTextParsing.TokenProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx >= 0 do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (p^.Text.Same(t1, t2, t3, t4)) then
begin
Result := p;
exit;
end
else
dec(idx);
end;
end;
function TTextParsing.TokenProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx >= 0 do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (p^.Text.Same(t1, t2, t3, t4, t5)) then
begin
Result := p;
exit;
end
else
dec(idx);
end;
end;
function TTextParsing.TokenProbeR(startI: Integer; const acceptT: TTokenTypes): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx < ParsingData.Cache.TokenDataList.Count do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) then
begin
Result := p;
exit;
end
else
inc(idx);
end;
end;
function TTextParsing.TokenProbeR(startI: Integer; const t: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx < ParsingData.Cache.TokenDataList.Count do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.Text.Same(t)) then
begin
Result := p;
exit;
end
else
inc(idx);
end;
end;
function TTextParsing.TokenProbeR(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx < ParsingData.Cache.TokenDataList.Count do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (p^.Text.Same(t)) then
begin
Result := p;
exit;
end
else
inc(idx);
end;
end;
function TTextParsing.TokenProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx < ParsingData.Cache.TokenDataList.Count do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (p^.Text.Same(t1, t2)) then
begin
Result := p;
exit;
end
else
inc(idx);
end;
end;
function TTextParsing.TokenProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx < ParsingData.Cache.TokenDataList.Count do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (p^.Text.Same(t1, t2, t3)) then
begin
Result := p;
exit;
end
else
inc(idx);
end;
end;
function TTextParsing.TokenProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx < ParsingData.Cache.TokenDataList.Count do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (p^.Text.Same(t1, t2, t3, t4)) then
begin
Result := p;
exit;
end
else
inc(idx);
end;
end;
function TTextParsing.TokenProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx < ParsingData.Cache.TokenDataList.Count do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (p^.Text.Same(t1, t2, t3, t4, t5)) then
begin
Result := p;
exit;
end
else
inc(idx);
end;
end;
function TTextParsing.ProbeL(startI: Integer; const acceptT: TTokenTypes): PTokenData;
begin
Result := TokenProbeL(startI, acceptT);
end;
function TTextParsing.ProbeL(startI: Integer; const t: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, t);
end;
function TTextParsing.ProbeL(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, acceptT, t);
end;
function TTextParsing.ProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, acceptT, t1, t2);
end;
function TTextParsing.ProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, acceptT, t1, t2, t3);
end;
function TTextParsing.ProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, acceptT, t1, t2, t3, t4);
end;
function TTextParsing.ProbeL(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, acceptT, t1, t2, t3, t4, t5);
end;
function TTextParsing.LProbe(startI: Integer; const acceptT: TTokenTypes): PTokenData;
begin
Result := TokenProbeL(startI, acceptT);
end;
function TTextParsing.LProbe(startI: Integer; const t: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, t);
end;
function TTextParsing.LProbe(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, acceptT, t);
end;
function TTextParsing.LProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, acceptT, t1, t2);
end;
function TTextParsing.LProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, acceptT, t1, t2, t3);
end;
function TTextParsing.LProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, acceptT, t1, t2, t3, t4);
end;
function TTextParsing.LProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData;
begin
Result := TokenProbeL(startI, acceptT, t1, t2, t3, t4, t5);
end;
function TTextParsing.ProbeR(startI: Integer; const acceptT: TTokenTypes): PTokenData;
begin
Result := TokenProbeR(startI, acceptT);
end;
function TTextParsing.ProbeR(startI: Integer; const t: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, t);
end;
function TTextParsing.ProbeR(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, acceptT, t);
end;
function TTextParsing.ProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, acceptT, t1, t2);
end;
function TTextParsing.ProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, acceptT, t1, t2, t3);
end;
function TTextParsing.ProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, acceptT, t1, t2, t3, t4);
end;
function TTextParsing.ProbeR(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, acceptT, t1, t2, t3, t4, t5);
end;
function TTextParsing.RProbe(startI: Integer; const acceptT: TTokenTypes): PTokenData;
begin
Result := TokenProbeR(startI, acceptT);
end;
function TTextParsing.RProbe(startI: Integer; const t: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, t);
end;
function TTextParsing.RProbe(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, acceptT, t);
end;
function TTextParsing.RProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, acceptT, t1, t2);
end;
function TTextParsing.RProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, acceptT, t1, t2, t3);
end;
function TTextParsing.RProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, acceptT, t1, t2, t3, t4);
end;
function TTextParsing.RProbe(startI: Integer; const acceptT: TTokenTypes; const t1, t2, t3, t4, t5: TPascalString): PTokenData;
begin
Result := TokenProbeR(startI, acceptT, t1, t2, t3, t4, t5);
end;
function TTextParsing.StringProbe(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData;
var
idx: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
while idx < ParsingData.Cache.TokenDataList.Count do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if (p^.tokenType in acceptT) and (ComparePosStr(p^.bPos, t)) then
begin
Result := p;
exit;
end
else
inc(idx);
end;
end;
function TTextParsing.TokenFullStringProbe(startI: Integer; const acceptT: TTokenTypes; const t: TPascalString): PTokenData;
begin
Result := StringProbe(startI, acceptT, t);
end;
function TTextParsing.IndentSymbolEndProbeR(startI: Integer; const indent_begin_symbol, indent_end_symbol: TPascalString): PTokenData;
var
idx, bC, eC: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
bC := 0;
eC := 0;
while idx < ParsingData.Cache.TokenDataList.Count do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if indent_begin_symbol.Exists(p^.Text.buff) then
inc(bC)
else if indent_end_symbol.Exists(p^.Text.buff) then
inc(eC);
if (bC > 0) and (eC = bC) then
begin
Result := p;
exit;
end;
inc(idx);
end;
end;
function TTextParsing.IndentSymbolBeginProbeL(startI: Integer; const indent_begin_symbol, indent_end_symbol: TPascalString): PTokenData;
var
idx, bC, eC: Integer;
p: PTokenData;
begin
Result := nil;
if ParsingData.Cache.TokenDataList.Count <= 0 then
exit;
idx := startI;
bC := 0;
eC := 0;
while idx >= 0 do
begin
p := PTokenData(ParsingData.Cache.TokenDataList[idx]);
if indent_begin_symbol.Exists(p^.Text.buff) then
inc(bC)
else if indent_end_symbol.Exists(p^.Text.buff) then
inc(eC);
if (eC > 0) and (eC = bC) then
begin
Result := p;
exit;
end;
dec(idx);
end;
end;
function TTextParsing.DetectSymbolVector: Boolean;
var
i: Integer;
p1, p2, paramB, paramE: PTokenData;
vExp: U_String;
VectorNum: Integer;
begin
Result := False;
i := 0;
p1 := nil;
p2 := nil;
paramB := FirstToken;
paramE := paramB;
VectorNum := 0;
while i < TokenCount do
begin
p1 := TokenProbeR(i, [ttSymbol]);
if p1 = nil then
begin
// successed
inc(VectorNum);
Break;
end;
if p1^.Text.Same(',', ';') then
begin
paramE := p1;
inc(VectorNum);
paramB := NextToken(paramE);
// successed
if paramB = nil then
Break;
// do loop.
paramE := paramB;
i := paramB^.Index;
end
else if p1^.Text.Same('(') then
begin
p2 := IndentSymbolEndProbeR(p1^.Index, '(', ')');
// error
if p2 = nil then
exit;
// do loop.
paramE := paramB;
i := p2^.Index + 1;
end
else if p1^.Text.Same('[') then
begin
p2 := IndentSymbolEndProbeR(p1^.Index, '[', ']');
// error
if p2 = nil then
exit;
// do loop.
paramE := paramB;
i := p2^.Index + 1;
end
else
inc(i);
end;
Result := VectorNum > 1;
end;
function TTextParsing.FillSymbolVector(L: TPascalStringList): Boolean;
var
i: Integer;
p1, p2, paramB, paramE: PTokenData;
vExp: U_String;
begin
Result := False;
i := 0;
p1 := nil;
p2 := nil;
paramB := FirstToken;
paramE := paramB;
while i < TokenCount do
begin
p1 := TokenProbeR(i, [ttSymbol]);
if p1 = nil then
begin
// successed
vExp := TokenCombine(paramB^.Index, TokenCount - 1);
L.Add(vExp);
Break;
end;
if p1^.Text.Same(',', ';') then
begin
paramE := p1;
if paramB <> paramE then
vExp := TokenCombine(paramB^.Index, paramE^.Index - 1)
else
vExp := '';
L.Add(vExp);
paramB := NextToken(paramE);
// successed
if paramB = nil then
Break;
// do loop.
paramE := paramB;
i := paramB^.Index;
end
else if p1^.Text.Same('(') then
begin
p2 := IndentSymbolEndProbeR(p1^.Index, '(', ')');
// error
if p2 = nil then
exit;
// do loop.
paramE := paramB;
i := p2^.Index + 1;
end
else if p1^.Text.Same('[') then
begin
p2 := IndentSymbolEndProbeR(p1^.Index, '[', ']');
// error
if p2 = nil then
exit;
// do loop.
paramE := paramB;
i := p2^.Index + 1;
end
else
inc(i);
end;
Result := True;
end;
function TTextParsing.FillSymbolVector: TSymbolVector;
var
L: TPascalStringList;
begin
L := TPascalStringList.Create;
if FillSymbolVector(L) then
L.FillTo(Result)
else
SetLength(Result, 0);
DisposeObject(L);
end;
function TTextParsing.FillSymbolMatrix(W, H: Integer; var symbolMatrix: TSymbolMatrix): Boolean;
var
L: TPascalStringList;
i, j, k: Integer;
begin
SetLength(symbolMatrix, 0, 0);
L := TPascalStringList.Create;
Result := FillSymbolVector(L);
if L.Count >= W * H then
begin
SetLength(symbolMatrix, H, W);
k := 0;
for j := 0 to H - 1 do
for i := 0 to W - 1 do
begin
symbolMatrix[j, i] := L[k];
inc(k);
end;
end;
DisposeObject(L);
end;
function TTextParsing.GetText(const bPos, ePos: Integer): TPascalString;
begin
Result := GetStr(bPos, ePos);
end;
function TTextParsing.GetStr(const bPos, ePos: Integer): TPascalString;
begin
if ePos >= ParsingData.Len then
begin
Result := ParsingData.Text.GetString(bPos, ePos + 1);
while (Result.Len > 0) and (Result.Last = #0) do
Result.DeleteLast;
if (Result.Len > 0) and (Result.Last = #32) then
Result.DeleteLast;
end
else
Result := ParsingData.Text.GetString(bPos, ePos);
end;
function TTextParsing.GetStr(const tp: TTextPos): TPascalString;
begin
Result := GetStr(tp.bPos, tp.ePos);
end;
function TTextParsing.GetWord(const cOffset: Integer): TPascalString;
begin
Result := GetStr(GetAsciiBeginPos(cOffset), GetAsciiEndPos(cOffset));
end;
function TTextParsing.GetPoint(const cOffset: Integer): TPoint;
var
i: Integer;
cPos: Integer;
begin
cPos := cOffset;
Result := Point(1, 1);
if cPos > ParsingData.Len then
cPos := ParsingData.Len;
for i := 1 to cPos - 1 do
begin
if ParsingData.Text[i] = #10 then
begin
inc(Result.y);
Result.x := 0;
end
else if not CharIn(ParsingData.Text[i], [#13]) then
inc(Result.x);
end;
end;
function TTextParsing.GetChar(const cOffset: Integer): SystemChar;
begin
Result := ParsingData.Text[cOffset];
end;
procedure TTextParsing.DeletePos(const bPos, ePos: Integer);
begin
ParsingData.Text := GetStr(1, bPos) + GetStr(ePos, Len);
ParsingData.Len := ParsingData.Text.Len;
RebuildParsingCache;
end;
procedure TTextParsing.DeletePos(const tp: TTextPos);
begin
DeletePos(tp.bPos, tp.ePos);
end;
procedure TTextParsing.DeletedComment;
begin
ParsingData.Text := GetDeletedCommentText.TrimChar(#32);
ParsingData.Len := ParsingData.Text.Len;
RebuildParsingCache;
end;
procedure TTextParsing.InsertTextBlock(const bPos, ePos: Integer; AInsertText: TPascalString);
begin
ParsingData.Text := GetStr(1, bPos) + AInsertText + GetStr(ePos, Len + 1);
ParsingData.Len := ParsingData.Text.Len;
RebuildParsingCache;
end;
procedure TTextParsing.InsertTextBlock(const tp: TTextPos; AInsertText: TPascalString);
begin
InsertTextBlock(tp.bPos, tp.ePos, AInsertText);
end;
function TTextParsing.SearchWordBody(initPos: Integer; wordInfo: TPascalString; var OutPos: TTextPos): Boolean;
var
cp: Integer;
ePos: Integer;
begin
Result := False;
cp := initPos;
while cp <= ParsingData.Len do
begin
if isTextDecl(cp) then
begin
ePos := GetTextDeclEndPos(cp);
cp := ePos;
end
else if isComment(cp) then
begin
ePos := GetCommentEndPos(cp);
cp := ePos;
end
else if isNumber(cp) then
begin
ePos := GetNumberEndPos(cp);
if GetStr(cp, ePos).Same(wordInfo) then
begin
OutPos.bPos := cp;
OutPos.ePos := ePos;
Result := True;
Break;
end;
cp := ePos;
end
else if isSymbol(cp) then
begin
ePos := GetSymbolEndPos(cp);
cp := ePos;
end
else if isAscii(cp) then
begin
ePos := GetAsciiEndPos(cp);
if GetStr(cp, ePos).Same(wordInfo) then
begin
OutPos.bPos := cp;
OutPos.ePos := ePos;
Result := True;
Break;
end;
cp := ePos;
end
else
inc(cp);
end;
end;
class function TTextParsing.TranslatePascalDeclToText(const Decl: TPascalString): TPascalString;
var
cPos: Integer;
// ext decl begin flag
VIsTextDecl: Boolean;
nText: TPascalString;
begin
cPos := 1;
VIsTextDecl := False;
Result := '';
while cPos <= Decl.Len do
begin
if Decl.ComparePos(cPos, #39#39#39#39) then
begin
Result.Append(#39);
inc(cPos, 4);
end
else if Decl[cPos] = #39 then
begin
VIsTextDecl := not VIsTextDecl;
inc(cPos);
end
else
begin
if VIsTextDecl then
begin
Result.Append(Decl[cPos]);
inc(cPos);
end
else if Decl[cPos] = '#' then
begin
nText := '';
inc(cPos);
while cPos <= Decl.Len do
begin
if CharIn(Decl[cPos], [cHex], '$') then
begin
nText.Append(Decl[cPos]);
inc(cPos);
end
else
Break;
end;
Result.Append(SystemChar(umlStrToInt(nText, 0)));
end
else
inc(cPos);
end;
end;
end;
class function TTextParsing.TranslateTextToPascalDecl(const Decl: TPascalString): TPascalString;
var
cPos: Integer;
c: SystemChar;
LastIsOrdChar: Boolean;
ordCharInfo: TPascalString;
begin
if Decl.Len = 0 then
begin
Result := #39#39;
exit;
end;
ordCharInfo.Len := 32;
for cPos := 0 to 31 do
ordCharInfo.buff[cPos] := SystemChar(Ord(cPos));
ordCharInfo[32] := #39;
Result := '';
LastIsOrdChar := False;
for cPos := 1 to Decl.Len do
begin
c := Decl[cPos];
if CharIn(c, ordCharInfo) then
begin
if Result.Len = 0 then
Result := '#' + umlIntToStr(Ord(c))
else if LastIsOrdChar then
Result.Append('#' + umlIntToStr(Ord(c)))
else
Result.Append(#39 + '#' + umlIntToStr(Ord(c)));
LastIsOrdChar := True;
end
else
begin
if Result.Len = 0 then
Result := #39 + c
else if LastIsOrdChar then
Result.Append(#39 + c)
else
Result.Append(c);
LastIsOrdChar := False;
end;
end;
if not LastIsOrdChar then
Result.Append(#39);
end;
class function TTextParsing.TranslateTextToPascalDeclWithUnicode(const Decl: TPascalString): TPascalString;
var
cPos: Integer;
c: SystemChar;
LastIsOrdChar: Boolean;
ordCharInfo: TPascalString;
begin
if Decl.Len = 0 then
begin
Result := #39#39;
exit;
end;
ordCharInfo.Len := 32 + 1;
for cPos := 0 to 31 do
ordCharInfo[cPos + 1] := SystemChar(Ord(cPos));
ordCharInfo[33] := #39;
Result := '';
LastIsOrdChar := False;
for cPos := 1 to Decl.Len do
begin
c := Decl[cPos];
if CharIn(c, ordCharInfo) or (Ord(c) >= $80) then
begin
if Result.Len = 0 then
Result := '#' + umlIntToStr(Ord(c))
else if LastIsOrdChar then
Result.Append('#' + umlIntToStr(Ord(c)))
else
Result.Append(#39 + '#' + umlIntToStr(Ord(c)));
LastIsOrdChar := True;
end
else
begin
if Result.Len = 0 then
Result := #39 + c
else if LastIsOrdChar then
Result.Append(#39 + c)
else
Result.Append(c);
LastIsOrdChar := False;
end;
end;
if not LastIsOrdChar then
Result.Append(#39);
end;
class function TTextParsing.TranslateC_DeclToText(const Decl: TPascalString): TPascalString;
var
cPos: Integer;
i: Integer;
// ext decl begin flag
VIsCharDecl: Boolean;
VIsTextDecl: Boolean;
nText: TPascalString;
wasC: Boolean;
begin
cPos := 1;
VIsCharDecl := False;
VIsTextDecl := False;
Result := '';
while cPos <= Decl.Len do
begin
if Decl[cPos] = #39 then
begin
VIsCharDecl := not VIsCharDecl;
inc(cPos);
end
else if Decl[cPos] = '"' then
begin
VIsTextDecl := not VIsTextDecl;
inc(cPos);
end
else
begin
wasC := False;
for i := low(CTranslateTable) to high(CTranslateTable) do
begin
if Decl.ComparePos(cPos, CTranslateTable[i].c) then
begin
inc(cPos, Length(CTranslateTable[i].c));
Result.Append(CTranslateTable[i].s);
wasC := True;
Break;
end;
end;
if (not wasC) then
begin
if VIsTextDecl or VIsCharDecl then
Result.Append(Decl[cPos]);
inc(cPos);
end;
end;
end;
end;
class function TTextParsing.TranslateTextToC_Decl(const Decl: TPascalString): TPascalString;
function GetCStyle(const c: SystemChar): SystemString; inline;
var
i: Integer;
begin
Result := '';
for i := low(CTranslateTable) to high(CTranslateTable) do
if c = CTranslateTable[i].s then
begin
Result := CTranslateTable[i].c;
Break;
end;
end;
var
cPos: Integer;
c: SystemChar;
LastIsOrdChar: Boolean;
n: SystemString;
begin
if Decl.Len = 0 then
begin
Result := '""';
exit;
end;
Result := '';
LastIsOrdChar := False;
for cPos := 1 to Decl.Len do
begin
c := Decl[cPos];
if Result.Len = 0 then
Result := '"' + c
else
begin
n := GetCStyle(c);
if n <> '' then
Result.Append(n)
else
Result.Append(c);
end;
end;
if not LastIsOrdChar then
Result.Append('"');
end;
class function TTextParsing.TranslatePascalDeclCommentToText(const Decl: TPascalString): TPascalString;
begin
Result := umlTrimSpace(Decl);
if umlMultipleMatch(False, '{*}', Result) then
begin
Result.DeleteFirst;
Result.DeleteLast;
if umlMultipleMatch(False, '$*', umlTrimSpace(Result)) then
Result := Decl;
end
else if umlMultipleMatch(False, '(*?*)', Result, '?', '') then
begin
Result.DeleteFirst;
Result.DeleteFirst;
Result.DeleteLast;
Result.DeleteLast;
end
else if umlMultipleMatch(False, '////*', Result) then
begin
Result.DeleteFirst;
Result.DeleteFirst;
Result.DeleteFirst;
Result.DeleteFirst;
while CharIn(Result.Last, [#13, #10]) do
Result.DeleteLast;
end
else if umlMultipleMatch(False, '///*', Result) then
begin
Result.DeleteFirst;
Result.DeleteFirst;
Result.DeleteFirst;
while CharIn(Result.Last, [#13, #10]) do
Result.DeleteLast;
end
else if umlMultipleMatch(False, '//*', Result) then
begin
Result.DeleteFirst;
Result.DeleteFirst;
while CharIn(Result.Last, [#13, #10]) do
Result.DeleteLast;
end;
end;
class function TTextParsing.TranslateTextToPascalDeclComment(const Decl: TPascalString): TPascalString;
var
n: TPascalString;
begin
n := umlTrimSpace(Decl);
if umlMultipleMatch(False, '(*?*)', n, '?', '') then
Result := Decl
else if umlMultipleMatch(False, '{*}', n) then
Result := Decl
else if n.Exists(['{', '}']) then
Result := '(* ' + Decl + ' *)'
else
Result := '{ ' + Decl + ' }';
end;
class function TTextParsing.TranslateC_DeclCommentToText(const Decl: TPascalString): TPascalString;
begin
Result := umlTrimSpace(Decl);
if umlMultipleMatch(False, '#*', Result) then
begin
Result := Decl;
end
else if umlMultipleMatch(False, '/*?*/', Result, '?', '') then
begin
Result.DeleteFirst;
Result.DeleteFirst;
Result.DeleteLast;
Result.DeleteLast;
end
else if umlMultipleMatch(False, '////*', Result) then
begin
Result.DeleteFirst;
Result.DeleteFirst;
Result.DeleteFirst;
Result.DeleteFirst;
end
else if umlMultipleMatch(False, '///*', Result) then
begin
Result.DeleteFirst;
Result.DeleteFirst;
Result.DeleteFirst;
end
else if umlMultipleMatch(False, '//*', Result) then
begin
Result.DeleteFirst;
Result.DeleteFirst;
end;
end;
class function TTextParsing.TranslateTextToC_DeclComment(const Decl: TPascalString): TPascalString;
var
n: TPascalString;
begin
n := umlTrimSpace(Decl);
if umlMultipleMatch(False, '#*', n) then
Result := Decl
else
Result := '/* ' + n + ' */';
end;
constructor TTextParsing.Create(const Text_: TPascalString; Style_: TTextStyle; SpecialSymbol_: TListPascalString; SpacerSymbol_: SystemString);
begin
inherited Create;
ParsingData.Cache.CommentDecls := nil;
ParsingData.Cache.TextDecls := nil;
ParsingData.Cache.TokenDataList := nil;
SetLength(ParsingData.Cache.CharToken, 0);
if Text_.Len = 0 then
ParsingData.Text := #13#10
else
ParsingData.Text := Text_ + #32;
ParsingData.Len := ParsingData.Text.Len + 1;
TextStyle := Style_;
SymbolTable := SpacerSymbol_;
TokenStatistics := NullTokenStatistics;
SpecialSymbol := TListPascalString.Create;
if SpecialSymbol_ <> nil then
SpecialSymbol.Assign(SpecialSymbol_);
RebuildCacheBusy := False;
RebuildParsingCache;
Init;
end;
constructor TTextParsing.Create(const Text_: TPascalString; Style_: TTextStyle; SpecialSymbol_: TListPascalString);
begin
Create(Text_, Style_, SpecialSymbol_, SpacerSymbol.V);
end;
constructor TTextParsing.Create(const Text_: TPascalString; Style_: TTextStyle);
begin
Create(Text_, Style_, nil, SpacerSymbol.V);
end;
constructor TTextParsing.Create(const Text_: TPascalString);
begin
Create(Text_, tsText, nil, SpacerSymbol.V);
end;
destructor TTextParsing.Destroy;
var
i: Integer;
begin
if ParsingData.Cache.CommentDecls <> nil then
begin
for i := 0 to ParsingData.Cache.CommentDecls.Count - 1 do
Dispose(PTextPos(ParsingData.Cache.CommentDecls[i]));
DisposeObject(ParsingData.Cache.CommentDecls);
ParsingData.Cache.CommentDecls := nil;
end;
if ParsingData.Cache.TextDecls <> nil then
begin
for i := 0 to ParsingData.Cache.TextDecls.Count - 1 do
Dispose(PTextPos(ParsingData.Cache.TextDecls[i]));
DisposeObject(ParsingData.Cache.TextDecls);
ParsingData.Cache.TextDecls := nil;
end;
if ParsingData.Cache.TokenDataList <> nil then
begin
for i := 0 to ParsingData.Cache.TokenDataList.Count - 1 do
Dispose(PTokenData(ParsingData.Cache.TokenDataList[i]));
DisposeObject(ParsingData.Cache.TokenDataList);
ParsingData.Cache.TokenDataList := nil;
end;
SetLength(ParsingData.Cache.CharToken, 0);
TokenStatistics := NullTokenStatistics;
DisposeObject(SpecialSymbol);
inherited Destroy;
end;
procedure TTextParsing.Init;
begin
end;
function TTextParsing.Parsing: Boolean;
begin
Result := False;
end;
procedure TTextParsing.Print;
var
i: Integer;
pt: PTokenData;
begin
for i := 0 to ParsingData.Cache.TokenDataList.Count - 1 do
begin
pt := ParsingData.Cache.TokenDataList[i];
DoStatus(PFormat('index: %d type: %s value: %s', [i, GetEnumName(TypeInfo(TTokenType), Ord(pt^.tokenType)), pt^.Text.Text]));
end;
end;
procedure FillSymbol_Test_;
var
t: TTextParsing;
SM: TSymbolMatrix;
begin
t := TTextParsing.Create('1,2,3,4,5,6,7,8,9', tsPascal);
t.FillSymbolMatrix(3, 2, SM);
DisposeObject(t);
end;
initialization
SpacerSymbol := TAtomString.Create(C_SpacerSymbol);
finalization
DisposeObjectAndNil(SpacerSymbol);
end.
|
unit udmSQL;
interface
uses
SysUtils, Classes, DB, DBTables, ADODB, pcnConversao, pcnNFE, Provider,
DBClient, PowerADOQuery, LookUpADOQuery;
const
TIPO_NOTA_VENDA = 0;
TIPO_NOTA_TRANSFERENCIA = 1;
NFE_VERSAO = '1.0.0.22';
type
TdaNotaFiscal = class(TObject)
private
public
function SelectedCount: integer;
function ProximaSelecionada: boolean;
procedure First;
procedure Next;
end;
TdmSQL = class(TDataModule)
ADOConnection: TADOConnection;
dsInvoice: TADODataSet;
dsInvoiceItem: TADODataSet;
adodsNotaFiscal: TADODataSet;
cdsNotaFiscal: TClientDataSet;
dspNotaFiscal: TDataSetProvider;
dsNotaFiscal: TDataSource;
dsImportarVendas: TADODataSet;
spGetNextID: TADOStoredProc;
cmdInsertMovimento: TADOCommand;
dsTransferencia: TADODataSet;
dsTransferenciaItem: TADODataSet;
dsImportarTransferencia: TADODataSet;
dsInvoiceItemIDInventoryMov: TIntegerField;
dsInvoiceItemM_Model: TStringField;
dsInvoiceItemM_Description: TStringField;
dsInvoiceItemIM_QTY: TBCDField;
dsInvoiceItemIM_SalePrice: TBCDField;
dsInvoiceItemU_Unidade: TStringField;
dsInvoiceItemU_Sigla: TStringField;
dsInvoiceItemT_SituacaoTributaria: TIntegerField;
dsInvoiceItemTaxCategoriaPer: TBCDField;
dsInvoiceItemTaxEstadoPerc: TBCDField;
dsInvoiceItemTaxItemPer: TBCDField;
dsInvoiceItemEstadoCliente: TStringField;
dsInvoiceItemEstadoLoja: TStringField;
dsInvoiceItemMVAInterno: TBCDField;
dsInvoiceItemMVAInterestadual: TBCDField;
dsInvoiceItemSitTribItem: TIntegerField;
dsInvoiceItemSitTribCategoria: TIntegerField;
dsTransferenciaItemIDInventoryMov: TIntegerField;
dsTransferenciaItemM_Model: TStringField;
dsTransferenciaItemM_Description: TStringField;
dsTransferenciaItemIM_QTY: TBCDField;
dsTransferenciaItemIM_SalePrice: TBCDField;
dsTransferenciaItemU_Unidade: TStringField;
dsTransferenciaItemU_Sigla: TStringField;
dsTransferenciaItemT_SituacaoTributaria: TIntegerField;
dsTransferenciaItemTaxCategoriaPer: TBCDField;
dsTransferenciaItemTaxEstadoPerc: TBCDField;
dsTransferenciaItemTaxItemPer: TBCDField;
dsTransferenciaItemEstadoCliente: TStringField;
dsTransferenciaItemEstadoLoja: TStringField;
dsTransferenciaItemMVAInterno: TBCDField;
dsTransferenciaItemMVAInterestadual: TBCDField;
dsTransferenciaItemSitTribItem: TIntegerField;
dsTransferenciaItemSitTribCategoria: TIntegerField;
dsInvoiceItemCFOP_Number: TStringField;
dsTransferenciaItemCFOP_Number: TStringField;
dsInvoiceItemT_Aliquota: TCurrencyField;
dsTransferenciaItemT_Aliquota: TCurrencyField;
dsInvoiceItemIM_Frete: TBCDField;
dsTransferenciaItemIM_Frete: TBCDField;
dsInvoiceItemTotalFrete: TBCDField;
dsTransferenciaItemTotalFrete: TBCDField;
dsInvoiceItemIM_Discount: TBCDField;
dsTransferenciaItemIM_Discount: TBCDField;
dsInvoiceItemM_SerialNumber: TBooleanField;
dsTransferenciaItemM_SerialNumber: TBooleanField;
dsInvItemSerial: TADODataSet;
dsInvoiceItemM_NCMCodigo: TStringField;
quLookUPEmpresa: TLookUpADOQuery;
quLookUPEmpresaIDEmpresa: TIntegerField;
quLookUPEmpresaEmpresa: TStringField;
dsLookUpEmpresa: TDataSource;
dsInvoiceItemMVAPercent: TCurrencyField;
dsTransferenciaItemMVAPercent: TCurrencyField;
dsInvoiceItemT_AliquotaST: TBCDField;
dsTransferenciaItemT_AliquotaST: TBCDField;
dsInvoiceItemAliquotaDesc: TStringField;
dsTransferenciaItemAliquotaDesc: TStringField;
dsTransferenciaItemM_NCMCodigo: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure dsInvoiceItemCalcFields(DataSet: TDataSet);
procedure dsInvoiceAfterOpen(DataSet: TDataSet);
procedure dsTransferenciaItemCalcFields(DataSet: TDataSet);
procedure dsTransferenciaAfterOpen(DataSet: TDataSet);
private
FCFOP : String;
function GetNextID(Const sTabela: String): LongInt;
function RetChar(sEntrada: String): String;
function AcertaCEP(sCEP: String): Integer;
function GetTpNF(cInvoiceSubTotal: currency): TpcnTipoNFe;
function GetTipoFrete(iTipo: Integer): TpcnModalidadeFrete;
function GetIndPag(i: integer): TpcnIndicadorPagamento;
function GetUnidade(sUnidade: String): String;
function DateAsSring(aDateTime: TDateTime): String;
function MontaCNPJCPF(sCNPJ, sCPF: String; bJuridico: boolean): String;
function GetNotaFiscalSQL( iSituacaoIndex: integer; sOrigem, sReferencia: String;
dtInicio, dtFim: TDateTime): String;
procedure PreencheVenda(IDInvoice: integer; aNFe: TNFe);
procedure PreencheVendaItem(IDInvoice: integer; aNFe: TNFe);
procedure PreencheTransferencia(IDTransferencia: integer; aNFe: TNFe);
procedure PreencheTransferenciaItem(IDTransferencia: integer; aNFe: TNFe);
function GetModelSerialNumber(iIDInvMov : Integer):String;
public
FTipoNota : Integer;
FAmbiente : TpcnTipoAmbiente;
daNotaFiscal : TdaNotaFiscal;
FCalcFreete : Boolean;
FHideItemDesc : Boolean;
FIDEmpresaVenda : Integer;
FDecimal : Integer;
FNumCopia : Integer;
procedure AbreCdsNotaFiscal( iSituacaoIndex: integer; sOrigem, sReferencia: String;
dtInicio, dtFim: TDateTime);
procedure SelectAll(bSelected: boolean);
procedure PreecheNotaFiscal(aNFe: TNFe);
procedure SalvaFalhaEnvio(sXMLEnviado, sXMLRecebido, sMensagemErro: WideString);
procedure SalvaSucessoEnvio(sXMLEnviado, sXMLRecebido: WideString; sChave : String);
procedure SalvaEnvioCompleto(sXMLEnviado, sXMLRecebido: WideString; sChave : String);
procedure SalvaAprovacaoEnvio(sXMLRecebido: WideString);
procedure SalvaCancelamentoEnvio(sXMLRecebido: WideString);
procedure SalvaImpressao;
function InserirMovimento(AOrigem : String; AID : Integer):boolean;
function RetornaXMLNotaFiscal : String;
function GetIDEmpresa : Variant;
function IsAmbienteProducao: Boolean;
end;
const
SQL_FORMATACAO_DATA = ' YYYYMMDD';
SQL_NF_SITUACAO_PENDENTE = 'Pendente';
SQL_NF_SITUACAO_ERRO_ENVIO = 'ErroEnvio';
SQL_NF_SITUACAO_AGUARDANDO = 'Aguardando';
SQL_NF_SITUACAO_APROVADA = 'Aprovada';
SQL_NF_SITUACAO_REJEITADA = 'Rejeitada';
SQL_NF_SITUACAO_IMPRESSA = 'Impressa';
SQL_NF_SITUACAO_CANCELADA = 'Cancelada';
var
dmSQL: TdmSQL;
implementation
uses ufrmGerenciaEnvioNF, uFrmServerInfo, Registry, uParamFunctions,
uSystemConst, Variants, uStringfunctions, uNumericFunctions;
{$R *.dfm}
{ TdaNF }
procedure TdaNotaFiscal.First;
begin
dmSQL.cdsNotaFiscal.First;
end;
procedure TdaNotaFiscal.Next;
begin
dmSQL.cdsNotaFiscal.Next;
end;
function TdaNotaFiscal.ProximaSelecionada: boolean;
begin
with dmSQL.cdsNotaFiscal do
try
DisableControls;
while (not FieldByName('Selecionado').AsBoolean and not EOF) do
Next;
Result := not EOF;
finally
EnableControls;
end;
end;
function TdaNotaFiscal.SelectedCount: integer;
begin
Result := 0;
with dmSQL.cdsNotaFiscal do
try
DisableControls;
First;
while not EOF do begin
if FieldByName('Selecionado').AsBoolean then
Inc(Result);
Next;
end;
First;
finally
EnableControls
end;
end;
{ TdmSQL }
function TdmSQL.RetChar(sEntrada: String): String;
var
i: integer;
begin
Result := '';
for i := 1 to Length(sEntrada) do
if (sEntrada[i] >= '0') and (sEntrada[i] <= '9') then
Result := Result + sEntrada[i];
end;
function TdmSQL.AcertaCEP(sCEP: String): Integer;
begin
result := StrToIntDef(RetChar(sCEP), 0);
end;
function TdmSQL.GetIndPag(i: integer): TpcnIndicadorPagamento;
begin
case i of
0: result := ipVista;
1: result := ipPrazo;
else result := ipOutras;
end;
end;
function TdmSQL.GetTipoFrete(iTipo: Integer): TpcnModalidadeFrete;
begin
if iTipo = 2 then
Result := mfContaDestinatario
else
Result := mfContaEmitente;
end;
function TdmSQL.GetTpNF(cInvoiceSubTotal: currency): TpcnTipoNFe;
begin
if cInvoiceSubTotal < 0 then
result := tnEntrada
else
result := tnSaida;
end;
function TdmSQL.GetUnidade(sUnidade: String): String;
begin
if Trim(sUnidade) = '' then
result := 'UN'
else
result := Trim(sUnidade);
end;
procedure TdmSQL.PreencheVenda(IDInvoice: integer; aNFe: TNFe);
begin
with dsInvoice do
try
Parameters.ParamByName('IDInvoice').value := IDInvoice;
Parameters.ParamByName('IDEmpresa').value := GetIDEmpresa;
Open;
aNFe.infNFe.ID := FieldByName('I_InvoiceCode').AsString;
// -------------------------------------------------------------------------
// Identificacao
// -------------------------------------------------------------------------
with aNFe.Ide do begin
verProc := NFE_VERSAO;
tpAmb := FAmbiente;
// Descrição da Natureza da Operação
natOp := FieldByName('CFOP_Description').AsString;
// Número do Documento Fiscal
nNF := FieldByName('I_InvoiceCode').AsInteger;
// Código numérico que compõe a Chave de Acesso. Número
// aleatório gerado pelo emitente para cada NF-e para evitar
// acessos indevidos da NF-e.
cNF := FieldByName('I_InvoiceCode').AsInteger;
// Utilizar o código 55 para identificação da NF-e, emitida em
// substituição ao modelo 1 ou 1A.
modelo := 55;
// Série do Documento Fiscal, informar 0 (zero) para série única.
serie := 1;
// Data de emissão do Documento Fiscal
dEmi := FieldByName('I_InvoiceDate').AsDateTime;
// Data de Saída ou da Entrada da Mercadoria/Produto
dSaiEnt := FieldByName('I_InvoiceDate').AsDateTime;
// Tipo do Documento Fiscal (Entrada / Saida)
if FCalcFreete then
tpNF := GetTpNF(FieldByName('I_SubTotal').AsCurrency + FieldByName('I_Frete').AsCurrency)
else
tpNF := GetTpNF(FieldByName('I_SubTotal').AsCurrency);
// Pagamento a vista ou parcelado?
indPag := GetindPag(FieldByName('I_IDFormOfPayment').AsInteger);
// Código da UF do emitente do Documento Fiscal
cUF := StrToIntDef(FieldByName('E_UFCodigo').AsString, 0);
// Código do Município de Ocorrência do Fato Gerador
cMunFG := StrToIntDef(FieldByName('E_MunicipioCode').AsString, 0);
//Indicador de pagamento 0 – pagamento à vista; 1 – pagamento à prazo; 2 - outros.
case FieldByName('I_IndPayment').AsInteger of
0 : indPag := ipVista;
1 : indPag := ipPrazo;
end;
end;
// -------------------------------------------------------------------------
// Emitente
// -------------------------------------------------------------------------
with aNFe.Emit do begin
// Autoexplicativo
CNPJCPF := RetChar(FieldByName('E_CGC').AsString);
// Inscricao estadual
IE := RetChar(FieldByName('E_InscricaoEstadual').AsString);
// Razão Social ou Nome do Emitente
xNome := FieldByName('E_RazaoSocial').AsString;
// Nome fantasia
xFant := FieldByName('E_NomeFantasia').AsString;
end;
// -------------------------------------------------------------------------
// Endereco do Emitente
// -------------------------------------------------------------------------
with aNFe.Emit.EnderEmit do begin
// Logradouro
xLgr := FieldByName('E_Endereco').AsString;
// Numero
nro := FieldByName('E_Numero').AsString;
// Complemento
xCpl := FieldByName('E_Coplemento').AsString;
// Bairro
xBairro := FieldByName('E_Bairro').AsString;
// Codigo do municipio segundo o IBGE
cMun := StrToIntDef(FieldByName('E_MunicipioCode').AsString, 0);
// Nome do município
xMun := FieldByName('E_Municipio').AsString;
// Sigla da UF
UF := FieldByName('E_IDEstado').AsString;
CEP := AcertaCEP(FieldByName('E_CEP').AsString);
cPais := 1058;
xPais := 'BRASIL';
// Preencher com Código DDD + número do telefone
fone := FieldByName('E_Telefone').AsString;
end;
// -------------------------------------------------------------------------
// Destinatario
// -------------------------------------------------------------------------
with aNFe.Dest do begin
// CNPJ ou CPF
CNPJCPF := MontaCNPJCPF( FieldByName('P_CPF').AsString,
FieldByName('P_CPF').AsString,
FieldByName('P_Juridico').AsBoolean );
// Inscricao Estadual
// Informar a IE quando o destinatário for contribuinto do ICMS.
// Informar ISENTO quando o destinatário for contribuinto do
// ICMS, mas não estiver obrigado à inscrição no cadastro de
// contribuintes do ICMS. Não informar o conteúdo da TAG
// se o destinatário não for contribuinte do ICMS.
IE := RetChar(FieldByName('P_InscEstadual').AsString);
//Razão Social ou nome do destinatário
xNome := FieldByName('P_Pessoa').AsString;
end;
// -------------------------------------------------------------------------
// Endereco do destinatario
// -------------------------------------------------------------------------
with aNFe.Dest.EnderDest do begin
xLgr := FieldByName('P_Endereco').AsString;
nro := FieldByName('P_ComplementoNum').AsString;
xCpl := FieldByName('P_Complemento').AsString;
xBairro := FieldByName('P_Bairro').AsString;
cMun := StrToIntDef(FieldByName('P_MunicipioCode').AsString, 0);
xMun := FieldByName('P_Municipio').AsString;
UF := FieldByName('P_IDEstado').AsString;
CEP := AcertaCEP(FieldByName('P_CEP').AsString);
cPais := 1058;
xPais := 'BRASIL';
// Preencher com Código DDD + número do telefone
Fone := Trim( FieldByName('P_PhoneAreaCode').AsString +
FieldByName('P_Telefone').AsString );
end;
// -------------------------------------------------------------------------
// Transportadora
// -------------------------------------------------------------------------
if FieldByName('T_Pessoa').AsString <> '' then
begin
aNFe.Transp.modFrete := GetTipoFrete(FieldByName('T_TipoDeFrete').AsInteger);
aNFe.Transp.veicTransp.RNTC := '';
aNFe.Transp.veicTransp.placa := '';
aNFe.Transp.veicTransp.UF := '';
with aNFe.Transp.Transporta do begin
xEnder := FieldByName('T_Endereco').AsString;
xMun := FieldByName('T_Municipio').AsString;
xNome := FieldByName('T_Pessoa').AsString;
CNPJCPF := FieldByName('T_CPF').AsString;
IE := FieldByName('T_InscEstadual').AsString;
UF := FieldByName('T_IDEstado').AsString;
end;
end;
// -------------------------------------------------------------------------
// INFORMAÇÕES COMPLEMENTARES
// -------------------------------------------------------------------------
if FieldByName('I_DeliverConfirmation').AsBoolean then
begin
aNFe.InfAdic.infCpl := FieldByName('I_DeliverAddress').AsString + '. ';
if FieldByName('I_DeliverOBS').AsString <> '' then
aNFe.InfAdic.infCpl := aNFe.InfAdic.infCpl + FieldByName('I_DeliverOBS').AsString + '. ';
end;
if FieldByName('I_PrintNotes').AsBoolean then
aNFe.InfAdic.infCpl := aNFe.InfAdic.infCpl + FieldByName('I_Notes').AsString + '. ';
finally
Close;
end;
end;
procedure TdmSQL.PreencheVendaItem(IDInvoice: integer; aNFe: TNFe);
var
dciItem: TDetCollectionItem;
iCount: integer;
cTotalFrete, cItemFreteTotal, cAcrescimo, cDesconto : Currency;
sInfoSub, sSerialNum : String;
begin
iCount := 1;
with dsInvoiceItem do
try
Parameters.ParamByName('IDInvoice').value := IDInvoice;
Open;
if FCalcFreete then
cTotalFrete := FieldByName('TotalFrete').AsCurrency
else
cTotalFrete := 0;
cItemFreteTotal := 0;
// Zera os totais
with aNFe.Total.ICMSTot do begin
vBC := 0;
vBCST := 0;
vICMS := 0;
vST := 0;
vNF := 0;
vProd := 0;
end;
while not EOF do begin
// Adiciona um novo item a nota
dciItem := aNFe.Det.Add;
// -----------------------------------------------------------------------
// Produto
// -----------------------------------------------------------------------
with dciItem.Prod do begin
// Numero do item na nota
nItem := iCount;
// Código do produto ou serviço
cProd := FieldByName('M_Model').AsString;
// Descrição do produto ou serviço
xProd := FieldByName('M_Description').AsString;
// NCM do Produto
if (FieldByName('M_NCMCodigo').AsString <> '') then
NCM := ReturnNumber(FieldByName('M_NCMCodigo').AsString);
// Quantidade Comercial
qCom := ABS(FieldByName('IM_QTY').AsCurrency);
// Quantidade Tributável
qTrib := ABS(FieldByName('IM_QTY').AsCurrency);
//Valor Desconto/Acrescimo total do produto
cDesconto := FieldByName('IM_Discount').AsCurrency;
if not FHideItemDesc then
begin
cAcrescimo := 0;
if cDesconto < 0 then
cAcrescimo := ABS(cDesconto)
else
vDesc := cDesconto;
// Valor Unitário de comercialização
vUnCom := ABS(FieldByName('IM_SalePrice').AsCurrency) + (cAcrescimo/qCom);
// Valor Unitário de tributação
vUnTrib := ABS(FieldByName('IM_SalePrice').AsCurrency) + (cAcrescimo/qCom);
end
else
begin //Colocar o valor do desconto dentro do valor de venda
cAcrescimo := 0;
if cDesconto < 0 then
cAcrescimo := ABS(cDesconto)
else
vDesc := 0;
// Valor Unitário de comercialização
vUnCom := ABS(FieldByName('IM_SalePrice').AsCurrency) - (cDesconto) + (cAcrescimo/qCom);
// Valor Unitário de tributação
vUnTrib := ABS(FieldByName('IM_SalePrice').AsCurrency) - (cDesconto) + (cAcrescimo/qCom);
end;
// Valor Total Bruto dos Produtos ou Serviços
vProd := TruncDecimal((vUnCom * qCom) - (vDesc * qCom), FDecimal);
// Unidade Comercial
uCom := GetUnidade(FieldByName('U_Sigla').AsString);
// Unidade Tributável
uTrib := GetUnidade(FieldByName('U_Sigla').AsString);
// Código Fiscal de Operações e Prestações
//TODO
CFOP := FieldByName('CFOP_Number').AsString;
//CFOP := '5949';
// Frete (Total do Frete divido por produto)
if FCalcFreete then
begin
vFrete := FieldByName('IM_Frete').AsCurrency;
cItemFreteTotal := cItemFreteTotal + vFrete;
//Ajustar o ultimo registro arredondando o desconto para bater com desconto total
if (RecNo = RecordCount) then
begin
if (cItemFreteTotal < cTotalFrete) then
vFrete := vFrete + ABS(cItemFreteTotal - cTotalFrete)
else if (cItemFreteTotal > cTotalFrete) then
vFrete := vFrete - ABS(cItemFreteTotal - cTotalFrete);
end;
end
else
vFrete := 0;
end;
//Informações de OBS quando o produto for Substituicao
if (sInfoSub = '') and (FieldByName('T_SituacaoTributaria').AsInteger = TAX_SUBSTITUICAO) then
sInfoSub := 'SUBSTITUIÇÃO TRIB. ICMS CONF. DECRETO Nº 41.961/2009';
// -----------------------------------------------------------------------
// IMPOSTO
// -----------------------------------------------------------------------
{
//cst
- Tributação do ICMS: 00 – Tributada integralmente.
- Tributação do ICMS: 10 - Tributada e com cobrança do ICMS por substituição tributária
- Tributação do ICMS: 20 - Com redução de base de cálculo
- Tributação do ICMS: 30 - Isenta ou não tributada e com cobrança do ICMS por substituição tributária
- Tributação do ICMS: 40 - Isenta
- Tributação do ICMS: 41 - Não tributada
- Tributação do ICMS: 50 - Suspensão
- Tributação do ICMS: 51 - Diferimento A exigência do preenchimento das informações do ICMS diferido fica a critério de cada UF.
- Tributação do ICMS: 60 - ICMS cobrado anteriormente por substituição tributária
- Tributação do ICMS: 70 - Com redução de base de cálculo e cobrança do ICMS por substituição tributária
- Tributação do ICMS: 90 – Outros
}
with dciItem.Imposto.ICMS do begin
// Origem da mercadoria
orig := oeNacional;
case FieldByName('T_SituacaoTributaria').AsInteger of
TAX_NENHUMA,
TAX_ISENTO,
TAX_NAOTRIBUTAVEL,
TAX_ISS,
TAX_TRIBUTAVEL :
begin
CST := cst00;
// Modalidade de determinação da BC do ICMS
modBC := dbiPrecoTabelado;
// Alíquota do imposto
pICMS := FieldByName('T_Aliquota').AsFloat;
// Base de calculo do ICMS
vBC := dciItem.Prod.vProd;
// Valor do ICMS
vICMS := vBC * (pICMS/100);
end;
TAX_SUBSTITUICAO :
begin
//Substituição Tributaria
CST := cst10;
//Modalidade de determinação da BC do ICMS: 0 - Margem Valor Agregado (%); 1 - Pauta (Valor); 2 - Preço Tabelado Máx. (valor); 3 - valor da operação.
//modBC := 0;
//Base de calculo do ICMS
vBC := dciItem.Prod.vProd;
//Alíquota do imposto loja
pICMS := FieldByName('T_Aliquota').AsFloat;
// Valor do ICMS loja
vICMS := vBC * (pICMS/100);
//Modalidade de determinação da BC do ICMS ST: 0 – Preço tabelado ou máximo sugerido; 1 - Lista Negativa (valor); 2 - Lista Positiva (valor); 3 - Lista Neutra (valor); 4 - Margem Valor Agregado (%); 5 - Pauta (valor);
modBCST := dbisPrecoTabelado;
//Percentual da margem de valor Adicionado do ICMS ST
pMVAST := FieldByName('MVAPercent').AsCurrency;
//Percentual da Redução de BC do ICMS ST
pRedBCST := 0;
//Alíquota do imposto substituicao
pICMSST := FieldByName('T_AliquotaST').AsCurrency;
//Valor Base de calculo do ICMS Substituicao
vBCST := (dciItem.Prod.vProd + (dciItem.Prod.vProd * (pICMSST/100)));
//Valor do ICMS Substituicao
vICMSST := ((vBCST * (pICMS/100)) - vICMS);
end;
{
TAX_ISENTO :
begin
CST := cst40;
end;
TAX_NAOTRIBUTAVEL :
begin
CST := cst41;
end;
TAX_ISS :
begin
end;
}
end;
end;
// -----------------------------------------------------------------------
// Adiciona o item aos totais da nota
// -----------------------------------------------------------------------
with aNFe.Total.ICMSTot do begin
// Base de Cálculo do ICMS
vBC := vBC + dciItem.Imposto.ICMS.vBC;
// Base de Cálculo do ICMS Substituicao
vBCST := vBCST + dciItem.Imposto.ICMS.vBCST;
// Valor Total do ICMS
vICMS := vICMS + dciItem.Imposto.ICMS.vICMS;
// Valor Total do ICMS Substituicao
vST := vST + dciItem.Imposto.ICMS.vICMSST;
// Valor Total da NF-e / vST = verificar
vNF := vNF + dciItem.Prod.vProd + dciItem.Imposto.ICMS.vICMSST;
// Valor Total dos produtos e serviços
vProd := vProd + dciItem.Prod.vProd;
// Valor Total do Frete
vFrete := vFrete + dciItem.Prod.vFrete;
// Valor Total de Desconto
vDesc := vDesc + (dciItem.Prod.vDesc * dciItem.Prod.qCom);
end;
//Verifica Numero de Serie do produto
if FieldByName('M_SerialNumber').AsBoolean then
sSerialNum := sSerialNum + FieldByName('M_Model').AsString + ' N/S:' + GetModelSerialNumber(FieldByName('IDInventoryMov').AsInteger) +'. ';
Next;
Inc(iCount);
end;
if sSerialNum <> '' then
aNFe.InfAdic.infCpl := sSerialNum + ' .' + aNFe.InfAdic.infCpl;
if (sInfoSub <> '') then
aNFe.InfAdic.infCpl := aNFe.InfAdic.infCpl + sInfoSub;
finally
Close;
end;
end;
function TdmSQL.GetNotaFiscalSQL(iSituacaoIndex: integer; sOrigem, sReferencia: String;
dtInicio, dtFim: TDateTime): String;
var
slSQL: TStringList;
begin
slSQL := TStringList.Create;
with slSQL do
try
Add('SELECT');
Add(' NF.IDNotaFiscal,');
Add(' Convert(bit, 0) as Selecionado,');
Add(' NF.Origem,');
Add(' NF.Referencia,');
Add(' NF.Situacao,');
Add(' NF.DataSolicitacao,');
Add(' NF.DataUltimoEnvio,');
Add(' NF.DataResultado,');
Add(' NF.DataUltimaImpressao,');
Add(' NF.XMLEnviado,');
Add(' NF.XMLRecebido,');
Add(' NF.DetalhamentoErro,');
Add(' NF.QtdEnvios,');
Add(' NF.QtdImpressao,');
Add(' NF.Chave,');
Add(' I.InvoiceCode,');
Add(' I.SaleCode,');
Add(' (CASE Origem WHEN ' + QuotedStr('Venda') + ' THEN I.InvoiceCode ELSE MT.Number END) as NumeroNota');
Add('FROM');
Add(' NFE_NotaFiscal NF (NOLOCK)');
Add(' LEFT JOIN Invoice I (NOLOCK) ON (I.IDInvoice = NF.Referencia )');
Add(' LEFT JOIN ModelTransf MT (NOLOCK) ON (MT.IDModelTransf = NF.Referencia AND MT.TransferType = 0)');
Add('WHERE');
case iSituacaoIndex of
CMB_SITUACAO_PENDENTE: begin
Add(' NF.Situacao IN (' + QuotedStr(SQL_NF_SITUACAO_PENDENTE) + ',');
Add(' ' + QuotedStr(SQL_NF_SITUACAO_ERRO_ENVIO) + ')');
Add(' AND');
end;
CMB_SITUACAO_AGUARDANDO: begin
Add(' NF.Situacao IN (' + QuotedStr(SQL_NF_SITUACAO_AGUARDANDO) + ')');
Add(' AND');
end;
CMB_SITUACAO_APROVADA: begin
Add(' NF.Situacao IN (' + QuotedStr(SQL_NF_SITUACAO_APROVADA) + ')');
Add(' AND');
end;
CMB_SITUACAO_REJEITADA: begin
Add(' NF.Situacao IN (' + QuotedStr(SQL_NF_SITUACAO_REJEITADA) + ')');
Add(' AND');
end;
CMB_SITUACAO_IMPRESSA: begin
Add(' NF.Situacao IN (' + QuotedStr(SQL_NF_SITUACAO_IMPRESSA) + ')');
Add(' AND');
end;
CMB_SITUACAO_CANCELADA: begin
Add(' NF.Situacao IN (' + QuotedStr(SQL_NF_SITUACAO_CANCELADA) + ')');
Add(' AND');
end;
CMB_SITUACAO_ERROR: begin
Add(' NF.Situacao IN (' + QuotedStr(SQL_NF_SITUACAO_ERRO_ENVIO) + ')');
Add(' AND');
end;
CMB_SITUACAO_TODAS: begin
// Nada
end;
end;
Add(' NF.Origem = ' + QuotedStr(sOrigem));
Add(' AND');
if sReferencia <> '' then
begin
if FTipoNota = TIPO_NOTA_VENDA then
Add(' I.InvoiceCode = ' + QuotedStr(sReferencia))
else
Add(' MT.Number = ' + QuotedStr(sReferencia));
end
else
begin
if FTipoNota = TIPO_NOTA_VENDA then
begin
Add(' I.InvoiceDate >= ' + DateAsSring(Trunc(dtInicio)));
Add(' AND');
Add(' I.InvoiceDate < ' + DateAsSring(Trunc(dtFim) + 1));
end
else
begin
Add(' MT.Data >= ' + DateAsSring(Trunc(dtInicio)));
Add(' AND');
Add(' MT.Data < ' + DateAsSring(Trunc(dtFim) + 1));
end;
end;
Result := Text;
finally
slSQL.Free;
end;
end;
procedure TdmSQL.AbreCdsNotaFiscal(iSituacaoIndex: integer; sOrigem, sReferencia: String;
dtInicio, dtFim: TDateTime);
begin
with adodsNotaFiscal do
begin
Close;
CommandText := GetNotaFiscalSQL( iSituacaoIndex,
sOrigem,
sReferencia,
dtInicio,
dtFim );
Open;
FieldByName('Selecionado').ReadOnly := False;
end;
with cdsNotaFiscal do begin
Close;
Open;
end;
adodsNotaFiscal.Close;
end;
function TdmSQL.DateAsSring(aDateTime: TDateTime): String;
begin
result := QuotedStr(FormatDateTime(SQL_FORMATACAO_DATA, aDateTime));
end;
function TdmSQL.MontaCNPJCPF(sCNPJ, sCPF: String;
bJuridico: boolean): String;
begin
if bJuridico then
Result := sCNPJ
else
Result := sCPF;
Result := RetChar(Result);
end;
procedure TdmSQL.PreecheNotaFiscal(aNFe: TNFe);
begin
// ECOSTA completar transferencia
with cdsNotaFiscal do
case FTipoNota of
TIPO_NOTA_VENDA :
begin
PreencheVenda(FieldByName('Referencia').AsInteger, aNFe);
PreencheVendaItem(FieldByName('Referencia').AsInteger, aNFe);
end;
TIPO_NOTA_TRANSFERENCIA :
begin
PreencheTransferencia(FieldByName('Referencia').AsInteger, aNFe);
PreencheTransferenciaItem(FieldByName('Referencia').AsInteger, aNFe);
end;
end;
end;
procedure TdmSQL.DataModuleCreate(Sender: TObject);
var
sResult : String;
bAbort, ExitConnection : Boolean;
FrmServrInfo : TFrmServerInfo;
UserName, PW, DBAlias, Server, Status : String;
WinLogin, UseNetLib : Boolean;
begin
FrmServrInfo := TFrmServerInfo.Create(self);
try
sResult := FrmServrInfo.Start('4', False, '', bAbort);
ExitConnection := bAbort;
While not ExitConnection do
try
Server := ParseParam(sResult, SV_SERVER);
DBAlias := ParseParam(sResult, SV_DATABASE);
UserName := ParseParam(sResult, SV_USER);
PW := ParseParam(sResult, SV_PASSWORD);
WinLogin := (ParseParam(sResult, SV_WIN_LOGIN)[1] in ['Y']);
UseNetLib := (ParseParam(sResult, SV_USE_NETLIB)[1] = 'Y');
Status := SQL_STATUS_NO_CONNECTED;
if not WinLogin then
if UseNetLib then
sResult := SetConnectionStr(UserName, PW, DBAlias, Server)
else
sResult := SetConnectionStrNoNETLIB(UserName, PW, DBAlias, Server)
else
if UseNetLib then
sResult := SetWinConnectionStr(DBAlias, Server)
else
sResult := SetWinConnectionStrNoNETLIB(DBAlias, Server);
ADOConnection.ConnectionString := sResult;
ExitConnection := True;
except
on E: Exception do
begin
sResult := FrmServrInfo.Start('4', True, E.Message, bAbort);
ExitConnection := bAbort;
end;
end;
finally
FreeAndNil(FrmServrInfo);
end;
daNotaFiscal := TdaNotaFiscal.create;
end;
procedure TdmSQL.DataModuleDestroy(Sender: TObject);
begin
daNotaFiscal.Free;
end;
procedure TdmSQL.SalvaImpressao;
var
slSQL: TStringList;
begin
slSQL := TStringList.Create;
with slSQL do
try
Add('UPDATE Nfe_NotaFiscal SET');
Add(' Situacao = ' + QuotedStr(SQL_NF_SITUACAO_IMPRESSA) + ',');
Add(' DataUltimaImpressao = GetDate(),');
Add(' QtdImpressao = (IsNull(QtdImpressao, 0) + 1)');
Add('WHERE IDNotaFiscal = ' + cdsNotaFiscal.FieldByName('IDNotaFiscal').AsString);
ADOConnection.Execute(Text);
finally
Free;
end;
end;
procedure TdmSQL.SalvaEnvioCompleto(sXMLEnviado, sXMLRecebido: WideString;
sChave : String);
var
slSQL: TStringList;
begin
slSQL := TStringList.Create;
with slSQL do
try
Add('UPDATE Nfe_NotaFiscal SET');
Add(' Situacao = ' + QuotedStr(SQL_NF_SITUACAO_IMPRESSA) + ',');
Add(' DataUltimoEnvio = GetDate(),');
Add(' DataResultado = GetDate(),');
Add(' DataUltimaImpressao = GetDate(),');
Add(' QtdEnvios = (IsNull(QtdEnvios, 0) + 1),');
Add(' QtdImpressao = (IsNull(QtdImpressao, 0) + 1),');
Add(' Chave = ' + QuotedStr(sChave) + ',');
Add(' XMLEnviado = ' + QuotedStr(sXMLEnviado) + ',');
Add(' XMLRecebido = ' + QuotedStr(sXMLRecebido));
Add('WHERE IDNotaFiscal = ' + cdsNotaFiscal.FieldByName('IDNotaFiscal').AsString);
ADOConnection.Execute(Text);
finally
Free;
end;
end;
procedure TdmSQL.SalvaFalhaEnvio(sXMLEnviado, sXMLRecebido, sMensagemErro: WideString);
var
slSQL: TStringList;
begin
slSQL := TStringList.Create;
with slSQL do
try
Add('UPDATE Nfe_NotaFiscal SET');
Add(' Situacao = ' + QuotedStr(SQL_NF_SITUACAO_ERRO_ENVIO) + ',');
Add(' DataUltimoEnvio = GetDate(),');
Add(' QtdEnvios = (IsNull(QtdEnvios, 0) + 1),');
Add(' XMLEnviado = ' + QuotedStr(sXMLEnviado) + ',');
Add(' XMLRecebido = ' + QuotedStr(sXMLRecebido) + ',');
Add(' DetalhamentoErro = ' + QuotedStr(sMensagemErro) );
Add('WHERE IDNotaFiscal = ' + cdsNotaFiscal.FieldByName('IDNotaFiscal').AsString);
ADOConnection.Execute(Text);
finally
Free;
end;
end;
procedure TdmSQL.SalvaSucessoEnvio(sXMLEnviado, sXMLRecebido: WideString;
sChave : String);
var
slSQL: TStringList;
begin
slSQL := TStringList.Create;
with slSQL do
try
Add('UPDATE Nfe_NotaFiscal SET');
Add(' Situacao = ' + QuotedStr(SQL_NF_SITUACAO_AGUARDANDO) + ',');
Add(' DataUltimoEnvio = GetDate(),');
Add(' QtdEnvios = (IsNull(QtdEnvios, 0) + 1),');
Add(' XMLEnviado = ' + QuotedStr(sXMLEnviado) + ',');
Add(' XMLRecebido = ' + QuotedStr(sXMLRecebido) + ',');
Add(' Chave = ' + QuotedStr(sChave) + ',');
Add(' DetalhamentoErro = ' + QuotedStr('') );
Add('WHERE IDNotaFiscal = ' + cdsNotaFiscal.FieldByName('IDNotaFiscal').AsString);
ADOConnection.Execute(Text);
finally
Free;
end;
end;
procedure TdmSQL.SalvaCancelamentoEnvio(sXMLRecebido: WideString);
var
slSQL: TStringList;
begin
slSQL := TStringList.Create;
with slSQL do
try
Add('UPDATE Nfe_NotaFiscal SET');
Add(' Situacao = ' + QuotedStr(SQL_NF_SITUACAO_CANCELADA) + ',');
Add(' DataUltimoEnvio = GetDate(),');
Add(' XMLRecebido = ' + QuotedStr(sXMLRecebido));
Add('WHERE IDNotaFiscal = ' + cdsNotaFiscal.FieldByName('IDNotaFiscal').AsString);
ADOConnection.Execute(Text);
finally
Free;
end;
end;
procedure TdmSQL.SalvaAprovacaoEnvio(sXMLRecebido: WideString);
var
slSQL: TStringList;
begin
slSQL := TStringList.Create;
with slSQL do
try
Add('UPDATE Nfe_NotaFiscal SET');
Add(' Situacao = ' + QuotedStr(SQL_NF_SITUACAO_APROVADA) + ',');
Add(' DataResultado = GetDate(),');
Add(' XMLRecebido = ' + QuotedStr(sXMLRecebido) + ',');
Add(' DetalhamentoErro = ' + QuotedStr('') );
Add('WHERE IDNotaFiscal = ' + cdsNotaFiscal.FieldByName('IDNotaFiscal').AsString);
ADOConnection.Execute(Text);
finally
Free;
end;
end;
procedure TdmSQL.SelectAll(bSelected: boolean);
begin
with dmSQL.cdsNotaFiscal do
try
DisableControls;
First;
while not EOF do begin
Edit;
FieldByName('Selecionado').AsBoolean := bSelected;
Post;
Next;
end;
First;
finally
EnableControls
end;
end;
function TdmSQL.InserirMovimento(AOrigem: String; AID: Integer): boolean;
begin
Result := False;
with cmdInsertMovimento do
begin
Parameters.ParamByName('IDNotaFiscal').Value := GetNextID('NFE_NotaFiscal.IDNotaFiscal');
Parameters.ParamByName('DataSolicitacao').Value := Now;
Parameters.ParamByName('Situacao').Value := 'Pendente';
Parameters.ParamByName('Origem').Value := AOrigem;
Parameters.ParamByName('Referencia').Value := AID;
Parameters.ParamByName('IDUserSolicitacao').Value := 1;
Execute;
end;
Result := True;
end;
function TdmSQL.GetNextID(const sTabela: String): LongInt;
begin
with spGetNextID do
begin
Parameters.ParamByName('@Tabela').Value := sTabela;
ExecProc;
Result := Parameters.ParamByName('@NovoCodigo').Value;
end;
end;
function TdmSQL.RetornaXMLNotaFiscal: String;
begin
Result := dmSQL.cdsNotaFiscal.FieldByName('XMLEnviado').AsString;
end;
procedure TdmSQL.PreencheTransferencia(IDTransferencia: integer;
aNFe: TNFe);
begin
with dsTransferencia do
try
Parameters.ParamByName('IDModelTransf').value := IDTransferencia;
Open;
aNFe.infNFe.ID := FieldByName('I_InvoiceCode').AsString;
// -------------------------------------------------------------------------
// Identificacao
// -------------------------------------------------------------------------
with aNFe.Ide do begin
verProc := NFE_VERSAO;
tpAmb := FAmbiente;
// Descrição da Natureza da Operação
natOp := FieldByName('CFOP_Description').AsString;
// Número do Documento Fiscal
nNF := FieldByName('I_InvoiceCode').AsInteger;
// Código numérico que compõe a Chave de Acesso. Número
// aleatório gerado pelo emitente para cada NF-e para evitar
// acessos indevidos da NF-e.
cNF := FieldByName('I_InvoiceCode').AsInteger;
// Utilizar o código 55 para identificação da NF-e, emitida em
// substituição ao modelo 1 ou 1A.
modelo := 55;
// Série do Documento Fiscal, informar 0 (zero) para série única.
serie := 1;
// Data de emissão do Documento Fiscal
dEmi := FieldByName('I_InvoiceDate').AsDateTime;
// Data de Saída ou da Entrada da Mercadoria/Produto
dSaiEnt := FieldByName('I_InvoiceDate').AsDateTime;
// Tipo do Documento Fiscal (Entrada / Saida)
tpNF := GetTpNF(FieldByName('I_SubTotal').AsCurrency);
// Pagamento a vista ou parcelado?
indPag := GetindPag(FieldByName('I_IDFormOfPayment').AsInteger);
// Código da UF do emitente do Documento Fiscal
cUF := StrToIntDef(FieldByName('E_UFCodigo').AsString, 0);
// Código do Município de Ocorrência do Fato Gerador
cMunFG := StrToIntDef(FieldByName('E_MunicipioCode').AsString, 0);
end;
// -------------------------------------------------------------------------
// Emitente
// -------------------------------------------------------------------------
with aNFe.Emit do begin
// Autoexplicativo
CNPJCPF := RetChar(FieldByName('E_CGC').AsString);
// Inscricao estadual
IE := RetChar(FieldByName('E_InscricaoEstadual').AsString);
// Razão Social ou Nome do Emitente
xNome := FieldByName('E_RazaoSocial').AsString;
// Nome fantasia
xFant := FieldByName('E_NomeFantasia').AsString;
end;
// -------------------------------------------------------------------------
// Endereco do Emitente
// -------------------------------------------------------------------------
with aNFe.Emit.EnderEmit do begin
// Logradouro
xLgr := FieldByName('E_Endereco').AsString;
// Numero
nro := FieldByName('E_Numero').AsString;
// Complemento
xCpl := FieldByName('E_Coplemento').AsString;
// Bairro
xBairro := FieldByName('E_Bairro').AsString;
// Codigo do municipio segundo o IBGE
cMun := StrToIntDef(FieldByName('E_MunicipioCode').AsString, 0);
// Nome do município
xMun := FieldByName('E_Municipio').AsString;
// Sigla da UF
UF := FieldByName('E_IDEstado').AsString;
CEP := AcertaCEP(FieldByName('E_CEP').AsString);
cPais := 1058;
xPais := 'BRASIL';
// Preencher com Código DDD + número do telefone
fone := FieldByName('E_Telefone').AsString;
end;
// -------------------------------------------------------------------------
// Destinatario
// -------------------------------------------------------------------------
with aNFe.Dest do begin
// CNPJ ou CPF
CNPJCPF := RetChar(FieldByName('P_CPF').AsString);
// Inscricao Estadual
// Informar a IE quando o destinatário for contribuinto do ICMS.
// Informar ISENTO quando o destinatário for contribuinto do
// ICMS, mas não estiver obrigado à inscrição no cadastro de
// contribuintes do ICMS. Não informar o conteúdo da TAG
// se o destinatário não for contribuinte do ICMS.
IE := RetChar(FieldByName('P_InscEstadual').AsString);
//Razão Social ou nome do destinatário
xNome := FieldByName('P_Pessoa').AsString;
end;
// -------------------------------------------------------------------------
// Endereco do destinatario
// -------------------------------------------------------------------------
with aNFe.Dest.EnderDest do begin
xLgr := FieldByName('P_Endereco').AsString;
nro := FieldByName('P_ComplementoNum').AsString;
xCpl := FieldByName('P_Complemento').AsString;
xBairro := FieldByName('P_Bairro').AsString;
cMun := StrToIntDef(FieldByName('P_MunicipioCode').AsString, 0);
xMun := FieldByName('P_Municipio').AsString;
UF := FieldByName('P_IDEstado').AsString;
CEP := AcertaCEP(FieldByName('P_CEP').AsString);
cPais := 1058;
xPais := 'BRASIL';
// Preencher com Código DDD + número do telefone
Fone := Trim( FieldByName('P_PhoneAreaCode').AsString +
FieldByName('P_Telefone').AsString );
end;
finally
Close;
end;
end;
procedure TdmSQL.PreencheTransferenciaItem(IDTransferencia: integer;
aNFe: TNFe);
var
dciItem: TDetCollectionItem;
iCount: integer;
begin
iCount := 1;
with dsTransferenciaItem do
try
Parameters.ParamByName('IDTransfer').value := IDTransferencia;
Open;
// Zera os totais
with aNFe.Total.ICMSTot do begin
vBC := 0;
vICMS := 0;
vNF := 0;
vProd := 0;
end;
while not EOF do begin
// Adiciona um novo item a nota
dciItem := aNFe.Det.Add;
// -----------------------------------------------------------------------
// Produto
// -----------------------------------------------------------------------
with dciItem.Prod do begin
// Numero do item na nota
nItem := iCount;
// Código do produto ou serviço
cProd := FieldByName('M_Model').AsString;
// Descrição do produto ou serviço
xProd := FieldByName('M_Description').AsString;
// Valor Unitário de comercialização
vUnCom := ABS(FieldByName('IM_SalePrice').AsCurrency);
// Valor Unitário de tributação
vUnTrib := ABS(FieldByName('IM_SalePrice').AsCurrency);
// Quantidade Comercial
qCom := ABS(FieldByName('IM_QTY').AsCurrency);
// Quantidade Tributável
qTrib := ABS(FieldByName('IM_QTY').AsCurrency);
// Valor Total Bruto dos Produtos ou Serviços
vProd := TruncDecimal(vUnCom * qCom, 2);
// Unidade Comercial
uCom := GetUnidade(FieldByName('U_Sigla').AsString);
// Unidade Tributável
uTrib := GetUnidade(FieldByName('U_Sigla').AsString);
// Código Fiscal de Operações e Prestações
CFOP := FieldByName('CFOP_Number').AsString;
//CFOP := '5949';
end;
// -----------------------------------------------------------------------
// ICMS 00
// -----------------------------------------------------------------------
//TODO
with dciItem.Imposto.ICMS do begin
// Origem da mercadoria
orig := oeNacional;
// Tributação do ICMS. cst00 – Tributada integralmente.
CST := cst00;
// Modalidade de determinação da BC do ICMS
modBC := dbiPrecoTabelado;
// Alíquota do imposto
pICMS := FieldByName('T_Aliquota').AsFloat;
// Base de calculo do ICMS
vBC := dciItem.Prod.vProd;
// Valor do ICMS
vICMS := vBC * (pICMS/100);
end;
// -----------------------------------------------------------------------
// Adiciona o item aos totais da nota
// -----------------------------------------------------------------------
with aNFe.Total.ICMSTot do begin
// Base de Cálculo do ICMS
vBC := vBC + dciItem.Imposto.ICMS.vBC;
// Valor Total do ICMS
vICMS := vICMS + dciItem.Imposto.ICMS.vICMS;
// Valor Total da NF-e
vNF := vNF + dciItem.Prod.vProd;
// Valor Total dos produtos e serviços
vProd := vProd + dciItem.Prod.vProd;;
end;
Next;
Inc(iCount);
end;
finally
Close;
end;
end;
procedure TdmSQL.dsInvoiceItemCalcFields(DataSet: TDataSet);
begin
//ICMS Tributavel
case dsInvoiceItem.FieldByName('T_SituacaoTributaria').AsInteger of
TAX_TRIBUTAVEL :
begin
//Mesmo Estato
if dsInvoiceItem.FieldByName('EstadoCliente').AsString = dsInvoiceItem.FieldByName('EstadoLoja').AsString then
dsInvoiceItemT_Aliquota.AsCurrency := dsInvoiceItem.FieldByName('TaxCategoriaPer').AsCurrency
else
begin
if dsInvoiceItem.FieldByName('TaxEstadoPerc').AsCurrency <> 0 then
dsInvoiceItemT_Aliquota.AsCurrency := dsInvoiceItem.FieldByName('TaxEstadoPerc').AsCurrency
else
dsInvoiceItemT_Aliquota.AsCurrency := dsInvoiceItem.FieldByName('TaxCategoriaPer').AsCurrency
end;
dsInvoiceItem.FieldByName('AliquotaDesc').AsString := 'ICMS: ' + FormatFloat('0.00', dsInvoiceItemT_Aliquota.AsCurrency);
end;
TAX_SUBSTITUICAO :
begin
if dsInvoiceItem.FieldByName('EstadoCliente').AsString = dsInvoiceItem.FieldByName('EstadoLoja').AsString then
dsInvoiceItem.FieldByName('MVAPercent').AsCurrency := dsInvoiceItem.FieldByName('MVAInterno').AsCurrency
else
dsInvoiceItem.FieldByName('MVAPercent').AsCurrency := dsInvoiceItem.FieldByName('MVAInterestadual').AsCurrency;
dsInvoiceItemT_Aliquota.AsCurrency := dsInvoiceItem.FieldByName('TaxCategoriaPer').AsCurrency;
dsInvoiceItem.FieldByName('AliquotaDesc').AsString := '(ICMS: ' + FormatFloat('0.00', dsInvoiceItemT_Aliquota.AsCurrency) +
') (MVA: ' + FormatFloat('0.00', dsInvoiceItem.FieldByName('MVAPercent').AsCurrency) +
') (ICMS-ST: ' + FormatFloat('0.00', dsInvoiceItem.FieldByName('T_AliquotaST').AsCurrency) + ')';
end
else
begin
dsInvoiceItemT_Aliquota.AsCurrency := dsInvoiceItem.FieldByName('TaxCategoriaPer').AsCurrency;
dsInvoiceItem.FieldByName('AliquotaDesc').AsString := 'ICMS: ' + FormatFloat('0.00', dsInvoiceItemT_Aliquota.AsCurrency);
end;
end;
dsInvoiceItemCFOP_Number.AsString := FCFOP;
{
//Industria
if dsInvoiceItemSituacaoTributariaItem.AsInteger <> TAX_NENHUMA then
begin
dsInvoiceItemT_Aliquota.AsCurrency := dsInvoiceItemItemTax.AsCurrency;
end
else
begin
if dsInvoiceItemSituacaoTributaria.AsInteger in [TAX_TRIBUTAVEL, TAX_SUBSTITUICAO, TAX_ISS] then
begin
if dsInvoiceItemTaxEstadoPerc.AsCurrency = 0 then
dsInvoiceItemT_Aliquota.AsCurrency := dsInvoiceItemTaxEstoquePer.AsCurrency
else
dsInvoiceItemT_Aliquota.AsCurrency := dsInvoiceItemTaxEstadoPerc.AsCurrency;
end
else
dsInvoiceItemT_Aliquota.AsCurrency := 0;
end;
}
end;
procedure TdmSQL.dsInvoiceAfterOpen(DataSet: TDataSet);
begin
// Numero da Natureza da Operação
FCFOP := dsInvoice.FieldByName('CFOP_Number').AsString;
end;
procedure TdmSQL.dsTransferenciaItemCalcFields(DataSet: TDataSet);
begin
dsTransferenciaItemCFOP_Number.AsString := FCFOP;
dsTransferenciaItem.FieldByName('AliquotaDesc').AsString := 'ICMS: ' + FormatFloat('0.00', dsTransferenciaItemT_Aliquota.AsCurrency);
end;
procedure TdmSQL.dsTransferenciaAfterOpen(DataSet: TDataSet);
begin
// Numero da Natureza da Operação
FCFOP := dsTransferencia.FieldByName('CFOP_Number').AsString;
end;
function TdmSQL.GetModelSerialNumber(iIDInvMov: Integer): String;
begin
Result := '';
with dsInvItemSerial do
try
Parameters.ParamByName('InventoryMovID').Value := iIDInvMov;
Open;
First;
While not EOF do
begin
Result := Result + Trim(FieldbyName('SerialNumber').AsString);
Next;
if not EOF then
Result := Result + '/';
end;
finally
Close;
end;
end;
function TdmSQL.GetIDEmpresa: Variant;
begin
if FIDEmpresaVenda = 0 then
Result := Null
else
Result := FIDEmpresaVenda;
end;
function TdmSQL.IsAmbienteProducao: Boolean;
begin
Result := (FAmbiente = taProducao);
end;
end.
|
{============== ==================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmTreeNonView
Purpose : To have a non-visual tree component.
Date : 12-01-1999
Author : Ryan J. Mills
Version : 1.92
Notes : This unit was originally based upon the work of Patrick O'Keeffe.
It was at his request that I took the component over and rm'ified it.
================================================================================}
unit rmTreeNonView;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Contnrs;
type
TAddMode = (taAddFirst, taAdd, taInsert) ;
TNodeAttachMode = (naAdd, naAddFirst, naAddChild, naAddChildFirst, naInsert) ;
PNodeInfo = ^TNodeInfo;
TNodeInfo = packed record
Count: Integer;
Text: string[255];
end;
TrmCustomTreeNonView = class;
TrmTreeNonViewNodes = class;
TrmTreeNonViewNode = class;
TrmHashData = class(TObject)
Hash: longint;
IDLength: Integer;
Node: TrmTreeNonViewNode;
end;
{ TrmTreeNonViewNode }
TrmTreeNonViewNode = class(TPersistent)
private
FOwner: TrmTreeNonViewNodes;
FText: string;
FData: Pointer;
FChildList: TList;
FDeleting: Boolean;
FParent: TrmTreeNonViewNode;
fExpanded: boolean;
fHashed : boolean;
function GetLevel: Integer;
function GetParent: TrmTreeNonViewNode;
procedure SetParent(Value: TrmTreeNonViewNode) ;
function GetChildren: Boolean;
function GetIndex: Integer;
function GetItem(Index: Integer) : TrmTreeNonViewNode;
function GetCount: Integer;
function GetrmTreeNonView: TrmCustomTreeNonView;
function IsEqual(Node: TrmTreeNonViewNode) : Boolean;
procedure ReadData(Stream: TStream; Info: PNodeInfo) ;
procedure SetData(Value: Pointer) ;
procedure SetItem(Index: Integer; Value: TrmTreeNonViewNode) ;
procedure SetText(const S: string) ;
procedure WriteData(Stream: TStream; Info: PNodeInfo) ;
function GetItemCount: Integer;
procedure RemoveHash;
procedure RenewHash;
property HasBeenHashed : boolean read fhashed write fhashed;
function GetNodePath: string;
public
constructor Create(AOwner: TrmTreeNonViewNodes) ;
destructor Destroy; override;
procedure Assign(Source: TPersistent) ; override;
procedure Delete;
procedure DeleteChildren;
function GetFirstChild: TrmTreeNonViewNode;
function GetLastChild: TrmTreeNonViewNode;
function GetNext: TrmTreeNonViewNode;
function GetNextChild(Value: TrmTreeNonViewNode) : TrmTreeNonViewNode;
function GetNextSibling: TrmTreeNonViewNode;
function GetPrev: TrmTreeNonViewNode;
function GetPrevChild(Value: TrmTreeNonViewNode) : TrmTreeNonViewNode;
function getPrevSibling: TrmTreeNonViewNode;
function HasAsParent(Value: TrmTreeNonViewNode) : Boolean;
function IndexOf(Value: TrmTreeNonViewNode) : Integer;
function MoveTo(Destination: TrmTreeNonViewNode; Mode: TNodeAttachMode) : TrmTreeNonViewNode;
property Count: Integer read GetCount;
property Data: Pointer read FData write SetData;
property Deleting: Boolean read FDeleting;
property HasChildren: Boolean read GetChildren;
property Expanded: boolean read fExpanded write fExpanded default false;
property Index: Integer read GetIndex;
property Item[Index: Integer]: TrmTreeNonViewNode read GetItem write SetItem; default;
property Level: Integer read GetLevel;
property Owner: TrmTreeNonViewNodes read FOwner;
property Parent: TrmTreeNonViewNode read GetParent write SetParent;
property TreeNonView: TrmCustomTreeNonView read GetrmTreeNonView;
property NodePath: string read GetNodePath;
property Text: string read FText write SetText;
property ItemCount: Integer read GetItemCount;
end;
{ TrmTreeNonViewNodes }
TrmTreeNonViewNodes = class(TPersistent)
private
FOwner: TrmCustomTreeNonView;
FRootNodeList: TList;
FHashList: TObjectList;
function GetNodeFromIndex(Index: Integer) : TrmTreeNonViewNode;
procedure ReadData(Stream: TStream) ;
procedure WriteData(Stream: TStream) ;
function HashValue(St: string) : LongInt;
function LocateHashIndex(Path: string) : integer;
procedure BinaryInsert(Path: string; Node: TrmTreeNonViewNode) ;
procedure RemoveHash(Node: TrmTreeNonViewNode) ;
protected
function InternalAddObject(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer; AddMode: TAddMode) : TrmTreeNonViewNode;
procedure DefineProperties(Filer: TFiler) ; override;
function GetCount: Integer;
procedure SetItem(Index: Integer; Value: TrmTreeNonViewNode) ;
public
procedure dumphash;
constructor Create(AOwner: TrmCustomTreeNonView) ;
destructor Destroy; override;
function AddChildFirst(Node: TrmTreeNonViewNode; const S: string) : TrmTreeNonViewNode;
function AddChild(Node: TrmTreeNonViewNode; const S: string) : TrmTreeNonViewNode;
function AddChildObjectFirst(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer) : TrmTreeNonViewNode;
function AddChildObject(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer) : TrmTreeNonViewNode;
function AddFirst(Node: TrmTreeNonViewNode; const S: string) : TrmTreeNonViewNode;
function Add(Node: TrmTreeNonViewNode; const S: string) : TrmTreeNonViewNode;
function AddObjectFirst(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer) : TrmTreeNonViewNode;
function AddObject(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer) : TrmTreeNonViewNode;
procedure Assign(Source: TPersistent) ; override;
procedure Clear;
procedure Delete(Node: TrmTreeNonViewNode) ;
function GetFirstNode: TrmTreeNonViewNode;
function Insert(Node: TrmTreeNonViewNode; const S: string) : TrmTreeNonViewNode;
function InsertObject(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer) : TrmTreeNonViewNode;
function LocateNode(Path: string) : TrmTreeNonViewNode;
property Count: Integer read GetCount;
property Item[Index: Integer]: TrmTreeNonViewNode read GetNodeFromIndex; default;
property Owner: TrmCustomTreeNonView read FOwner;
end;
{ TrmCustomTreeNonView }
TrmTreeNonViewEvent = procedure(Sender: TObject; Node: TrmTreeNonViewNode) of object;
ErmTreeNonViewError = class(Exception) ;
TrmCustomTreeNonView = class(TComponent)
private
FMemStream: TMemoryStream;
FTreeNodes: TrmTreeNonViewNodes;
FOnDeletion: TrmTreeNonViewEvent;
fOnNodeTextChanged: TrmTreeNonViewEvent;
FSepChar: Char;
procedure SetrmTreeNonViewNodes(Value: TrmTreeNonViewNodes) ;
function ParentName(s: string) : string;
function ChildName(s: string) : string;
protected
function CreateNode: TrmTreeNonViewNode; virtual;
procedure Delete(Node: TrmTreeNonViewNode) ; dynamic;
property SepChar: Char read FSepChar write FSepChar;
property Items: TrmTreeNonViewNodes read FTreeNodes write SetrmTreeNonViewNodes;
property OnDeletion: TrmTreeNonViewEvent read FOnDeletion write FOnDeletion;
property OnNodeTextChanged: TrmTreeNonViewEvent read fOnNodeTextChanged write fOnNodeTextChanged;
public
constructor Create(AOwner: TComponent) ; override;
destructor Destroy; override;
procedure LoadFromFile(const FileName: string) ;
procedure LoadFromStream(Stream: TStream) ;
procedure SaveToFile(const FileName: string) ;
procedure SaveToStream(Stream: TStream) ;
function AddPathNode(Node: TrmTreeNonViewNode; Path: string) : TrmTreeNonViewNode;
function FindPathNode(Path: string) : TrmTreeNonViewNode;
function NodePath(Node: TrmTreeNonViewNode) : string;
procedure TextSort(ParentNode: TrmTreeNonViewNode; Recursive: boolean) ; virtual;
end;
TrmTreeNonView = class(TrmCustomTreeNonView)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
published
{ Published declarations }
property SepChar;
property Items;
property OnDeletion;
property OnNodeTextChanged;
end;
implementation
uses Consts, rmLibrary;
procedure rmTreeNonViewError(const Msg: string) ;
begin
raise ErmTreeNonViewError.Create(Msg) ;
end;
constructor TrmTreeNonViewNode.Create(AOwner: TrmTreeNonViewNodes) ;
begin
inherited Create;
FOwner := AOwner;
FChildList := TList.Create;
fExpanded := false;
fHashed := false;
end;
destructor TrmTreeNonViewNode.Destroy;
begin
FDeleting := True;
Data := nil;
FChildList.Free;
inherited Destroy;
end;
function TrmTreeNonViewNode.GeTrmTreeNonView: TrmCustomTreeNonView;
begin
Result := Owner.Owner;
end;
function TrmTreeNonViewNode.HasAsParent(Value: TrmTreeNonViewNode) : Boolean;
begin
if Value <> nil then
begin
if Parent = nil then
Result := False
else if Parent = Value then
Result := True
else
Result := Parent.HasAsParent(Value) ;
end
else
Result := True;
end;
procedure TrmTreeNonViewNode.SetText(const S: string) ;
var
fRemoved: boolean;
begin
fRemoved := false;
if not (FText = '') and (FText <> S) then
begin
Self.RemoveHash;
fRemoved := true;
end;
FText := S;
if fRemoved and not (fText = '') then
begin
Self.RenewHash;
end;
if assigned(TreeNonView.OnNodeTextChanged) then
TreeNonView.OnNodeTextChanged(TreeNonView, self) ;
end;
procedure TrmTreeNonViewNode.SetData(Value: pointer) ;
begin
FData := Value;
end;
function TrmTreeNonViewNode.GetChildren: Boolean;
begin
Result := FChildList.Count > 0;
end;
function TrmTreeNonViewNode.GetParent: TrmTreeNonViewNode;
begin
Result := FParent;
end;
procedure TrmTreeNonViewNode.SetParent(Value: TrmTreeNonViewNode) ;
var
wHashed : boolean;
begin
wHashed := HasBeenHashed;
if wHashed then
removeHash;
if (fParent <> nil) then
fParent.FChildList.delete(fParent.FChildList.indexOf(self) ) ;
if (value <> nil) then
begin
FParent := Value;
if fParent.FChildList.indexof(self) = -1 then
fParent.FChildList.Add(self) ;
end;
if wHashed then
RenewHash;
end;
function TrmTreeNonViewNode.GetNextSibling: TrmTreeNonViewNode;
var
CurIdx: Integer;
begin
if Parent <> nil then
begin
CurIdx := Parent.FChildList.IndexOf(Self) ;
if (CurIdx + 1) < Parent.FChildList.Count then
Result := Parent.FChildList.Items[CurIdx + 1]
else
Result := nil;
end
else
begin
CurIdx := Owner.FRootNodeList.IndexOf(Self) ;
if (CurIdx + 1) < Owner.FRootNodeList.Count then
Result := Owner.FRootNodeList.Items[CurIdx + 1]
else
Result := nil;
end;
end;
function TrmTreeNonViewNode.GetPrevSibling: TrmTreeNonViewNode;
var
CurIdx: Integer;
begin
if Parent <> nil then
begin
CurIdx := Parent.FChildList.IndexOf(Self) ;
if (CurIdx - 1) >= 0 then
Result := Parent.FChildList.Items[CurIdx - 1]
else
Result := nil;
end
else
begin
CurIdx := Owner.FRootNodeList.IndexOf(Self) ;
if (CurIdx - 1) >= Owner.FRootNodeList.Count then
Result := Owner.FRootNodeList.Items[CurIdx - 1]
else
Result := nil;
end;
end;
function TrmTreeNonViewNode.GetNextChild(Value: TrmTreeNonViewNode) : TrmTreeNonViewNode;
begin
if Value <> nil then
Result := Value.GetNextSibling
else
Result := nil;
end;
function TrmTreeNonViewNode.GetPrevChild(Value: TrmTreeNonViewNode) : TrmTreeNonViewNode;
begin
if Value <> nil then
Result := Value.GetPrevSibling
else
Result := nil;
end;
function TrmTreeNonViewNode.GetFirstChild: TrmTreeNonViewNode;
begin
if FChildList.Count > 0 then
begin
Result := FChildList.Items[0];
end
else
Result := nil;
end;
function TrmTreeNonViewNode.GetLastChild: TrmTreeNonViewNode;
begin
if FChildList.Count > 0 then
begin
Result := FChildList.Items[FChildList.Count - 1]
end
else
Result := nil;
end;
function TrmTreeNonViewNode.GetNext: TrmTreeNonViewNode;
var
N: TrmTreeNonViewNode;
P: TrmTreeNonViewNode;
begin
if HasChildren then
N := GetFirstChild
else
begin
N := GetNextSibling;
if N = nil then
begin
P := Parent;
while P <> nil do
begin
N := P.GetNextSibling;
if N <> nil then
Break;
P := P.Parent;
end;
end;
end;
Result := N;
end;
function TrmTreeNonViewNode.GetPrev: TrmTreeNonViewNode;
var
Node: TrmTreeNonViewNode;
begin
Result := GetPrevSibling;
if Result <> nil then
begin
Node := Result;
repeat
Result := Node;
Node := Result.GetLastChild;
until Node = nil;
end
else
Result := Parent;
end;
function TrmTreeNonViewNode.GetIndex: Integer;
var
Node: TrmTreeNonViewNode;
begin
Result := -1;
Node := parent;
if Node = nil then
begin
if fowner <> nil then
FOwner.FRootNodeList.indexof(self)
end
else
result := parent.FChildList.indexof(self) ;
end;
function TrmTreeNonViewNode.GetItem(Index: Integer) : TrmTreeNonViewNode;
begin
if (index >= 0) and (index < FChildList.count) then
Result := fchildlist[index]
else
begin
result := nil;
rmTreeNonViewError('List Index Out of Bounds') ;
end;
end;
procedure TrmTreeNonViewNode.SetItem(Index: Integer; Value: TrmTreeNonViewNode) ;
begin
item[Index].Assign(Value) ;
end;
function TrmTreeNonViewNode.IndexOf(Value: TrmTreeNonViewNode) : Integer;
begin
Result := fChildList.indexof(Value) ;
end;
function TrmTreeNonViewNode.MoveTo(Destination: TrmTreeNonViewNode; Mode: TNodeAttachMode) : TrmTreeNonViewNode;
var
AddMode: TAddMode;
node: TrmTreeNonViewNode;
begin
Result := nil;
if (Destination = nil) or not Destination.HasAsParent(Self) then
begin
AddMode := taAdd;
if (Destination <> nil) and not (Mode in [naAddChild, naAddChildFirst]) then
Node := Destination.Parent
else
Node := Destination;
case Mode of
naAdd,
naAddChild: AddMode := taAdd;
naAddFirst,
naAddChildFirst: AddMode := taAddFirst;
naInsert:
begin
Node := Destination.GetPrevSibling;
if Node = nil then
AddMode := taAddFirst
else
AddMode := taInsert;
end;
end;
if node <> self then
begin
result := owner.InternalAddObject(node, Text, data, AddMode) ;
delete;
end;
end
else
result := self;
end;
function TrmTreeNonViewNode.GetCount: Integer;
begin
result := FChildList.Count;
end;
function TrmTreeNonViewNode.GetLevel: Integer;
var
Node: TrmTreeNonViewNode;
begin
Result := 0;
Node := Parent;
while Node <> nil do
begin
Inc(Result) ;
Node := Node.Parent;
end;
end;
procedure TrmTreeNonViewNode.Delete;
var
wIndex : integer;
begin
if HasChildren then
DeleteChildren;
Owner.RemoveHash(self) ;
if Parent <> nil then
begin
wIndex := Parent.FChildList.IndexOf(Self);
Parent.FChildList.Delete( wIndex );
Parent.FChildList.Pack;
end
else
begin
wIndex := Owner.FRootNodeList.IndexOf(Self);
Owner.FRootNodeList.Delete( wIndex ) ;
Owner.FRootNodeList.Pack;
end;
TrmCustomTreeNonView(Owner.Owner) .Delete(Self) ;
Free;
end;
procedure TrmTreeNonViewNode.DeleteChildren;
var
Node: TrmTreeNonViewNode;
begin
Node := GetLastChild;
while Node <> nil do
begin
Node.Delete;
Node := GetLastChild;
end;
end;
procedure TrmTreeNonViewNode.Assign(Source: TPersistent) ;
var
Node: TrmTreeNonViewNode;
begin
if Source is TrmTreeNonViewNode then
begin
Node := TrmTreeNonViewNode(Source) ;
Text := Node.Text;
Data := Node.Data;
end
else
inherited Assign(Source) ;
end;
function TrmTreeNonViewNode.IsEqual(Node: TrmTreeNonViewNode) : Boolean;
begin
Result := (Text = Node.Text) and (Data = Node.Data) ;
end;
procedure TrmTreeNonViewNode.ReadData(Stream: TStream; Info: PNodeInfo) ;
var
I, Size, ItemCount: Integer;
ObjType: Integer;
begin
Stream.ReadBuffer(Size, SizeOf(Size) ) ;
Stream.ReadBuffer(Info^, Size) ;
Text := Info^.Text;
ItemCount := Info^.Count;
Stream.ReadBuffer(ObjType, SizeOf(ObjType) ) ;
case ObjType of
0:
begin
//do nothing
end;
1:
begin
Data := Stream.ReadComponent(nil) ;
end;
end;
for I := 0 to ItemCount - 1 do
Owner.AddChild(Self, '') .ReadData(Stream, Info) ;
end;
procedure TrmTreeNonViewNode.WriteData(Stream: TStream; Info: PNodeInfo) ;
var
I,
Size,
L,
ItemCount,
ObjType: Integer;
begin
L := Length(Text) ;
if L > 255 then
L := 255;
Size := SizeOf(TNodeInfo) + L - 255;
Info^.Text := Text;
ItemCount := Count;
Info^.Count := ItemCount;
Stream.WriteBuffer(Size, SizeOf(Size) ) ;
Stream.WriteBuffer(Info^, Size) ;
if Assigned(Self.Data) then
begin
try
TObject(self.data) .classtype;
if (TObject(Self.Data) is TComponent) then
begin
ObjType := 1;
Stream.WriteBuffer(ObjType, SizeOf(ObjType) ) ;
Stream.WriteComponent(TComponent(Data) ) ;
end
else
begin
ObjType := 0;
Stream.WriteBuffer(ObjType, SizeOf(ObjType) ) ;
end;
except
ObjType := 0;
Stream.WriteBuffer(ObjType, SizeOf(ObjType) ) ;
end;
end
else
begin
ObjType := 0;
Stream.WriteBuffer(ObjType, SizeOf(ObjType) ) ;
end;
for I := 0 to ItemCount - 1 do
Item[I].WriteData(Stream, Info) ;
end;
{ TrmTreeNonViewNodes }
constructor TrmTreeNonViewNodes.Create(AOwner: TrmCustomTreeNonView) ;
begin
inherited Create;
FOwner := AOwner;
FRootNodeList := TList.Create;
FHashList := TObjectList.Create;
FHashList.OwnsObjects := true;
end;
destructor TrmTreeNonViewNodes.Destroy;
begin
Clear;
FRootNodeList.Free;
FHashList.Free;
inherited Destroy;
end;
function TrmTreeNonViewNodes.GetCount: Integer;
var
Idx: Integer;
begin
Result := FRootNodeList.Count;
for Idx := 0 to FRootNodeList.Count - 1 do
begin
Result := Result + TrmTreeNonViewNode(FRootNodeList[Idx]) .ItemCount;
end;
end;
procedure TrmTreeNonViewNodes.Delete(Node: TrmTreeNonViewNode) ;
var
wIndex: integer;
begin
wIndex := LocateHashIndex(Owner.NodePath(Node) ) ;
if wIndex > -1 then
FHashList.delete(wIndex) ;
Node.Delete;
end;
procedure TrmTreeNonViewNodes.Clear;
var
N: TrmTreeNonViewNode;
begin
N := GetFirstNode;
while N <> nil do
begin
N.Delete;
N := GetFirstNode;
end;
FHashList.Clear;
end;
function TrmTreeNonViewNodes.AddChildFirst(Node: TrmTreeNonViewNode; const S: string) : TrmTreeNonViewNode;
begin
Result := AddChildObjectFirst(Node, S, nil) ;
end;
function TrmTreeNonViewNodes.AddChildObjectFirst(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer) : TrmTreeNonViewNode;
begin
Result := InternalAddObject(Node, S, Ptr, taAddFirst) ;
end;
function TrmTreeNonViewNodes.AddChild(Node: TrmTreeNonViewNode; const S: string) : TrmTreeNonViewNode;
begin
Result := AddChildObject(Node, S, nil) ;
end;
function TrmTreeNonViewNodes.AddChildObject(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer) : TrmTreeNonViewNode;
begin
Result := InternalAddObject(Node, S, Ptr, taAdd) ;
end;
function TrmTreeNonViewNodes.AddFirst(Node: TrmTreeNonViewNode; const S: string) : TrmTreeNonViewNode;
begin
Result := AddObjectFirst(Node, S, nil) ;
end;
function TrmTreeNonViewNodes.AddObjectFirst(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer) : TrmTreeNonViewNode;
begin
if Node <> nil then Node := Node.Parent;
Result := InternalAddObject(Node, S, Ptr, taAddFirst) ;
end;
function TrmTreeNonViewNodes.Add(Node: TrmTreeNonViewNode; const S: string) : TrmTreeNonViewNode;
begin
Result := AddObject(Node, S, nil) ;
end;
function TrmTreeNonViewNodes.AddObject(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer) : TrmTreeNonViewNode;
begin
if Node <> nil then Node := Node.Parent;
Result := InternalAddObject(Node, S, Ptr, taAdd) ;
end;
function TrmTreeNonViewNodes.Insert(Node: TrmTreeNonViewNode; const S: string) : TrmTreeNonViewNode;
begin
Result := InsertObject(Node, S, nil) ;
end;
function TrmTreeNonViewNodes.InsertObject(Node: TrmTreeNonViewNode; const S: string; Ptr: Pointer) : TrmTreeNonViewNode;
var
Parent: TrmTreeNonViewNode;
AddMode: TAddMode;
Target: TrmTreeNonViewNode;
begin
AddMode := taInsert;
Target := node;
if Node <> nil then
begin
Parent := Node.Parent;
if Parent <> nil then
Node := Node.GetPrevSibling;
if Node = nil then
begin
AddMode := taAddFirst;
target := parent;
end;
end;
Result := InternalAddObject(Target, S, Ptr, AddMode) ;
end;
function TrmTreeNonViewNodes.InternalAddObject(Node: TrmTreeNonViewNode; const S: string;
Ptr: Pointer; AddMode: TAddMode) : TrmTreeNonViewNode;
var
nvnParent: TrmTreeNonViewNode;
nindex: integer;
begin
Result := Owner.CreateNode;
try
case AddMode of
taAddFirst:
begin
if Node = nil then
begin
FRootNodeList.Insert(0, Result) ;
Result.Parent := nil;
end
else
begin
Node.FChildList.Insert(0, Result) ;
Result.Parent := Node;
end;
try
Result.Data := Ptr;
Result.Text := S;
BinaryInsert(Owner.NodePath(Result) , Result) ;
except
raise;
end;
end;
taAdd:
begin
if Node = nil then
begin
FRootNodeList.Add(Result) ;
Result.Parent := nil;
end
else
begin
Node.FChildList.Add(Result) ;
Result.Parent := Node;
end;
try
Result.Data := Ptr;
Result.Text := S;
BinaryInsert(Owner.NodePath(Result) , Result) ;
except
raise;
end;
end;
taInsert:
begin
nvnParent := Node.Parent;
if nvnParent = nil then
begin
if Node = nil then
begin
FRootNodeList.Insert(0, Result) ;
Result.Parent := nil;
end
else
begin
nIndex := fRootNodeList.IndexOf(Node) ;
if nIndex <> -1 then
begin
fRootNodeList.Insert(nIndex, Result) ;
result.parent := nil;
end
else
rmTreeNonViewError('Unable to find Node reference') ;
end;
end
else
begin
nIndex := nvnParent.FChildList.IndexOf(node) ;
if nIndex >= 0 then
begin
nvnParent.FChildList.Insert(nIndex, Result) ;
result.parent := nvnParent;
end
else
rmTreeNonViewError('Unable to find Node reference') ;
end;
try
Result.Data := Ptr;
Result.Text := S;
BinaryInsert(Owner.NodePath(Result) , Result) ;
except
raise;
end;
end;
end;
except
raise;
end;
end;
function TrmTreeNonViewNodes.GetFirstNode: TrmTreeNonViewNode;
begin
if FRootNodeList.Count = 0 then
Result := nil
else
Result := FRootNodeList.Items[0];
end;
function TrmTreeNonViewNodes.GetNodeFromIndex(Index: Integer) : TrmTreeNonViewNode;
var
I: Integer;
begin
Result := GetFirstNode;
I := Index;
while (I <> 0) and (Result <> nil) do
begin
Result := Result.GetNext;
Dec(I) ;
end;
if Result = nil then
rmTreeNonViewError('Index out of range') ;
end;
procedure TrmTreeNonViewNodes.SetItem(Index: Integer; Value: TrmTreeNonViewNode) ;
begin
GetNodeFromIndex(Index) .Assign(Value) ;
end;
procedure TrmTreeNonViewNodes.Assign(Source: TPersistent) ;
var
TreeNodes: TrmTreeNonViewNodes;
MemStream: TMemoryStream;
wNode: TrmTreeNonViewNode;
begin
if Source is TrmTreeNonViewNodes then
begin
TreeNodes := TrmTreeNonViewNodes(Source) ;
Clear;
MemStream := TMemoryStream.Create;
try
TreeNodes.WriteData(MemStream) ;
MemStream.Position := 0;
ReadData(MemStream) ;
finally
MemStream.Free;
end;
//Now that we've assigned all the nodes
//we need to redo that hashlist
wNode := Self.GetFirstNode;
while wNode <> nil do
begin
wNode.RenewHash;
wNode := wNode.GetNextSibling;
end;
end
else
inherited Assign(Source) ;
end;
procedure TrmTreeNonViewNodes.DefineProperties(Filer: TFiler) ;
function WriteNodes: Boolean;
var
I: Integer;
Nodes: TrmTreeNonViewNodes;
begin
Nodes := TrmTreeNonViewNodes(Filer.Ancestor) ;
if Nodes = nil then
Result := Count > 0
else if Nodes.Count <> Count then
Result := True
else
begin
Result := False;
for I := 0 to Count - 1 do
begin
Result := not Item[I].IsEqual(Nodes[I]) ;
if Result then Break;
end
end;
end;
begin
inherited DefineProperties(Filer) ;
Filer.DefineBinaryProperty('Data', ReadData, WriteData, WriteNodes) ;
end;
procedure TrmTreeNonViewNodes.ReadData(Stream: TStream) ;
var
I, Count: Integer;
Info: TNodeInfo;
begin
Clear;
Stream.ReadBuffer(Count, SizeOf(Count) ) ;
for I := 0 to Count - 1 do
Add(nil, '') .ReadData(Stream, @Info) ;
end;
procedure TrmTreeNonViewNodes.WriteData(Stream: TStream) ;
var
I: Integer;
Node: TrmTreeNonViewNode;
Info: TNodeInfo;
begin
I := 0;
Node := GetFirstNode;
while Node <> nil do
begin
Inc(I) ;
Node := Node.GetNextSibling;
end;
Stream.WriteBuffer(I, SizeOf(I) ) ;
Node := GetFirstNode;
while Node <> nil do
begin
Node.WriteData(Stream, @Info) ;
Node := Node.GetNextSibling;
end;
end;
function TrmTreeNonViewNodes.HashValue(St: string) : Longint;
begin
result := GetStrCRC32(St) ;
end;
function TrmTreeNonViewNodes.LocateHashIndex(Path: string) : integer;
var
wHash: longint;
wData: TrmHashData;
First, Middle, Last, Temp: longint;
wFound: boolean;
begin
wHash := HashValue(Path) ;
result := -1;
First := 0;
Last := FHashList.count - 1;
wFound := false;
middle := round((last + first) / 2) ;
while (not wFound) and (first <= last) do
begin
middle := round((last + first) / 2) ;
wData := TrmHashData(fHashlist[middle]) ;
if wHash = wData.hash then
wFound := true
else
begin
if wHash < wData.hash then
last := middle - 1
else
first := middle + 1;
end;
end;
if wFound then
begin
Temp := middle;
while (Middle > 0) and (Middle - 1 >= First) and (TrmHashData(FHashList[middle - 1]) .Hash = wHash) do
dec(Middle) ;
while (result = -1) and (Middle < FHashList.Count) and (Middle + 1 < Last) and (TrmHashData(FHashList[middle + 1]) .Hash = wHash) do
begin
wData := TrmHashData(FHashList[middle]) ;
if (Owner.NodePath(wData.Node) = Path) then
result := middle
else
inc(Middle) ;
end;
if result = -1 then
result := temp;
end;
end;
procedure TrmTreeNonViewNodes.BinaryInsert(Path: string; Node: TrmTreeNonViewNode) ;
var
wHash: longint;
wLen: integer;
wData: TrmHashData;
First, Middle, Last: longint;
wFound: boolean;
begin
wHash := HashValue(Path) ;
wLen := Length(Path) ;
First := 0;
Last := FHashList.count - 1;
wFound := false;
while (not wFound) and (first <= last) do
begin
middle := round((last + first) / 2) ;
wData := TrmHashData(fHashlist[middle]) ;
if wHash = wData.hash then
wFound := true
else
begin
if wHash < wData.hash then
last := middle - 1
else
first := middle + 1;
end;
end;
if wFound then
begin
middle := round((last + first) / 2) ;
wFound := false;
while (Middle > 0) and (Middle - 1 >= First) and (TrmHashData(FHashList[middle - 1]) .Hash = wHash) do
dec(Middle) ;
while (not wfound) and (Middle < FHashList.Count) and (Middle + 1 < Last) and (TrmHashData(FHashList[middle + 1]) .Hash = wHash) do
begin
wData := TrmHashData(FHashList[middle]) ;
if (Owner.NodePath(wData.Node) = Path) then
wFound := true
else
inc(Middle) ;
end;
if not wFound then
first := middle;
end;
if not wfound then
begin
wData := TrmHashData.create;
wData.Hash := wHash;
wData.IDLength := wLen;
wData.Node := Node;
fHashList.Insert(first, wData) ;
Node.HasBeenHashed := true;
end;
end;
function TrmTreeNonViewNodes.LocateNode(Path: string) : TrmTreeNonViewNode;
var
wIndex: integer;
begin
wIndex := LocateHashIndex(Path) ;
if wIndex = -1 then
result := nil
else
result := TrmHashData(FHashList[wIndex]) .Node;
end;
procedure TrmTreeNonViewNodes.RemoveHash(Node: TrmTreeNonViewNode) ;
var
wIndex: integer;
begin
wIndex := LocateHashIndex(Owner.NodePath(Node) ) ;
if wIndex > -1 then
begin
FHashList.delete(wIndex) ;
Node.HasBeenHashed := false;
end;
end;
procedure TrmTreeNonViewNodes.dumphash;
var
fstr: TextFile;
loop: integer;
wdata: trmhashdata;
begin
AssignFile(fstr, '\nvhash.txt') ;
rewrite(fstr) ;
for loop := 0 to fhashlist.count - 1 do
begin
wData := Trmhashdata(fhashlist[loop]) ;
writeln(fstr, owner.nodepath(wdata.node) ) ;
end;
closefile(fstr) ;
end;
{ TrmCustomTreeNonView }
constructor TrmCustomTreeNonView.Create(AOwner: TComponent) ;
begin
inherited Create(AOwner) ;
FSepChar := '/';
FTreeNodes := TrmTreeNonViewNodes.Create(Self) ;
end;
destructor TrmCustomTreeNonView.Destroy;
begin
Items.Free;
FMemStream.Free;
inherited Destroy;
end;
procedure TrmCustomTreeNonView.SetrmTreeNonViewNodes(Value: TrmTreeNonViewNodes) ;
begin
Items.Assign(Value) ;
end;
procedure TrmCustomTreeNonView.Delete(Node: TrmTreeNonViewNode) ;
begin
if Assigned(FOnDeletion) then
FOnDeletion(Self, Node) ;
end;
function TrmCustomTreeNonView.CreateNode: TrmTreeNonViewNode;
begin
Result := TrmTreeNonViewNode.Create(Items) ;
end;
procedure TrmCustomTreeNonView.LoadFromFile(const FileName: string) ;
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead) ;
try
LoadFromStream(Stream) ;
finally
Stream.Free;
end;
end;
procedure TrmCustomTreeNonView.LoadFromStream(Stream: TStream) ;
begin
end;
procedure TrmCustomTreeNonView.SaveToFile(const FileName: string) ;
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmCreate) ;
try
SaveToStream(Stream) ;
finally
Stream.Free;
end;
end;
procedure TrmCustomTreeNonView.SaveToStream(Stream: TStream) ;
var
N: TrmTreeNonViewNode;
L: TStringList;
begin
L := TStringList.Create;
try
N := Items.GetFirstNode;
while N <> nil do
begin
L.Add(NodePath(N) ) ;
N := N.GetNext;
end;
L.SaveToStream(Stream) ;
finally
L.Free;
end;
end;
function TrmCustomTreeNonView.NodePath(Node: TrmTreeNonViewNode) : string;
var
Temp: string;
begin
Temp := '';
while Node <> nil do
begin
Temp := FSepChar + Node.Text + Temp;
Node := Node.Parent;
end;
Result := Temp;
end;
function TrmTreeNonViewNode.GetItemCount: Integer;
var
Idx: Integer;
begin
Result := FChildList.Count;
for Idx := 0 to FChildList.Count - 1 do
begin
Result := Result + TrmTreeNonViewNode(FChildList[Idx]) .ItemCount;
end;
end;
procedure TrmCustomTreeNonView.TextSort(ParentNode: TrmTreeNonViewNode;
Recursive: boolean) ;
var
Child: TrmTreeNonViewNode;
WList, woList: TList;
index: integer;
found: boolean;
begin
if ParentNode = nil then
Child := FTreeNodes.GetFirstNode
else
Child := ParentNode.GetFirstChild;
if assigned(child) then
begin
if child.parent = nil then
woList := FTreeNodes.frootnodelist
else
woList := child.parent.FChildList;
wList := TList.create;
try
while woList.count > 0 do
begin
wList.add(woList[0]) ;
woList.delete(0) ;
end;
if Recursive then
TextSort(TrmTreeNonViewNode(wList[0]) , recursive) ;
woList.add(wList[0]) ;
wList.delete(0) ;
while wList.count > 0 do
begin
if Recursive then
TextSort(TrmTreeNonViewNode(wList[0]) , recursive) ;
index := 0;
found := false;
while index < woList.Count do
begin
if TrmTreeNonViewNode(wList[0]) .FText > TrmTreeNonViewNode(woList[index]) .fText then
inc(index)
else
begin
woList.Insert(index, wList[0]) ;
wList.delete(0) ;
found := true;
break;
end;
end;
if not found then
begin
woList.add(wList[0]) ;
wList.delete(0) ;
end;
end;
finally
wList.free;
end;
end;
end;
function TrmCustomTreeNonView.FindPathNode(Path: string) : TrmTreeNonViewNode;
begin
result := Items.LocateNode(Path) ;
end;
function TrmCustomTreeNonView.AddPathNode(Node: TrmTreeNonViewNode; Path: string) : TrmTreeNonViewNode;
var
wNode, wParent, wChild: TrmTreeNonViewNode;
wPName, wCName: string;
begin
result := nil;
if path = '' then
exit;
if path[1] = sepchar then
path := NodePath(Node) + path
else
path := nodepath(node) + sepchar + path;
wNode := Items.LocateNode(Path) ;
if wNode = nil then
begin
wPName := ParentName(Path) ;
wCName := ChildName(Path) ;
if (wPName = '') and (wCName = '') then
exit;
wParent := Items.LocateNode(wPName) ;
if wParent = nil then
wParent := AddPathNode(nil, wPname) ;
wChild := Items.AddChild(wParent, wCName) ;
result := wChild;
end
else
result := wNode;
end;
function TrmCustomTreeNonView.ParentName(s: string) : string;
var
wLen: integer;
begin
wLen := length(s) ;
if s[wLen] = SepChar then
begin
system.Delete(s, wLen, 1) ;
dec(wLen) ;
end;
while (wlen > 0) and (s[wLen] <> sepchar) do
begin
system.Delete(s, wLen, 1) ;
dec(wLen) ;
end;
if (wLen > 0) and (s[wLen] = SepChar) then
system.Delete(s, wLen, 1) ;
result := s;
end;
function TrmCustomTreeNonView.ChildName(s: string) : string;
var
wLen: integer;
begin
wLen := length(s) ;
if s[wLen] = SepChar then
begin
system.Delete(s, wLen, 1) ;
dec(wLen) ;
end;
while (wLen > 0) and (s[wLen] <> sepchar) do
dec(wLen) ;
system.delete(s, 1, wLen) ;
result := s;
end;
procedure TrmTreeNonViewNode.RemoveHash;
var
wNode: TrmTreeNonViewNode;
begin
FOwner.RemoveHash(self) ;
wNode := getFirstChild;
while wNode <> nil do
begin
wNode.RemoveHash;
wNode := wNode.getNextSibling;
end;
end;
procedure TrmTreeNonViewNode.RenewHash;
var
wNode: TrmTreeNonViewNode;
begin
FOwner.BinaryInsert(FOwner.Owner.NodePath(self) , self) ;
wNode := getFirstChild;
while wNode <> nil do
begin
wNode.RenewHash;
wNode := wNode.getNextSibling;
end;
end;
function TrmTreeNonViewNode.GetNodePath: string;
begin
Result := TreeNonView.NodePath(self) ;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.IDE.VSTProxy;
//The tools api provides no access to the the virtualstringtree type so hacking using RTTI
interface
uses
System.Rtti,
Vcl.Controls,
Vcl.ImgList,
Spring.Collections,
DPM.IDE.Logger,
DPM.IDE.ProjectTree.Containers;
type
TNodeData = record
//many hours of debugging later, seems they point to the same object which implements multiple interfaces
GraphLocation : IGraphLocation;
GraphData : IGraphData;
Dummy : array[0..11] of Byte; //seem to be only used for target platforms children, which we don't need.
end;
PNodeData = ^TNodeData;
PVirtualNode = type Pointer; //just to make it feel more like working with VST :)
//A way of working on a VST when we can't use the class itself
//fortunately VST has a well known interface that is pretty easy
//to call via RTTI
// copied from VirtualTrees.pas
// TODO : check where anything has changed with this since the time of XE2
// mode to describe a move action
TVTNodeAttachMode = (
amNoWhere, // just for simplified tests, means to ignore the Add/Insert command
amInsertBefore, // insert node just before destination (as sibling of destination)
amInsertAfter, // insert node just after destionation (as sibling of destination)
amAddChildFirst, // add node as first child of destination
amAddChildLast // add node as last child of destination
);
//quickndirty
TRttiMethodEntry = class
public
rttiMethod : TRttiMethod;
params : TArray<TRttiParameter>;
end;
TRttiPropEntry = class
public
rttiProp : TRttiProperty
end;
TVirtualStringTreeProxy = class
private
FTreeInstance : TControl;
FRttiCtx : TRttiContext;
FTreeType : TRttiType;
FLogger : IDPMIDELogger;
FMethodCache : IDictionary<string, TRttiMethodEntry>;
FPropCache : IDictionary<string, TRttiPropEntry>;
FExpandedRttiprop : TRttiIndexedProperty;
protected
function GetVSTProperty(const propertyName : string) : TValue;
procedure SetVSTProperty(const propertyName : string; const value : TValue);
//most VST methods take a node pointer so this is just a shortcut
function InvokeMethodWithPointerParam(const methodName : string; const value : Pointer) : TValue;
function GetImages : TCustomImageList;
function GetMethodEntry(const name : string) : TRttiMethodEntry;
function GetPropEntry(const name : string) : TRttiPropEntry;
public
constructor Create(const treeInstance : TControl; const logger : IDPMIDELogger);
destructor Destroy; override;
procedure BeginUpdate;
procedure EndUpdate;
function GetNodeDataSize : integer;
function GetRootNode : PVirtualNode;
function GetFirstVisibleNode : PVirtualNode;
function GetFirstChild(node : PVirtualNode) : PVirtualNode;
function GetFirstNode : PVirtualNode;
function GetNextNode(const node : PVirtualNode) : PVirtualNode;
function GetNextSibling(const node : PVirtualNode) : PVirtualNode;
function GetNextVisible(const node : PVirtualNode) : PVirtualNode;
function GetNodeData(const node : PVirtualNode) : PNodeData;
function AddChildNode(const parentNode : PVirtualNode) : PVirtualNode;
function InsertNode(const parentNode : PVirtualNode; const attachMode : TVTNodeAttachMode) : PVirtualNode;
procedure DeleteChildren(const parentNode : PVirtualNode);
procedure SetExpanded(const node : PVirtualNode; const value : boolean);
property Images : TCustomImageList read GetImages;
end;
implementation
uses
System.SysUtils;
{ TVirtualStringTreeHack }
function TVirtualStringTreeProxy.AddChildNode(const parentNode : PVirtualNode) : PVirtualNode;
var
rttiMethodEntry : TRttiMethodEntry;
param : TValue;
begin
rttiMethodEntry := GetMethodEntry('AddChild');
TValue.Make(@parentNode, rttiMethodEntry.params[0].ParamType.Handle, param);
// function AddChild(Parent: PVirtualNode; UserData: Pointer = nil): PVirtualNode; overload; virtual;
//calling with just the parent fails.. seems like with rtti invoke optional params must be supplied?
Result := PVirtualNode(PPointer(rttiMethodEntry.rttiMethod.Invoke(FTreeInstance, [param, TValue.From<Pointer>(nil)]).GetReferenceToRawData())^);
end;
procedure TVirtualStringTreeProxy.BeginUpdate;
var
rttiMethodEntry : TRttiMethodEntry;
begin
rttiMethodEntry := GetMethodEntry('BeginUpdate');
rttiMethodEntry.rttiMethod.Invoke(FTreeInstance, []);
end;
constructor TVirtualStringTreeProxy.Create(const treeInstance : TControl; const logger : IDPMIDELogger);
begin
FTreeInstance := treeInstance;
FLogger := logger;
FTreeType := FRttiCtx.GetType(FTreeInstance.ClassType).AsInstance;
FMethodCache := TCollections.CreateDictionary<string, TRttiMethodEntry>;
FPropCache := TCollections.CreateDictionary<string, TRttiPropEntry>;
FExpandedRttiprop := nil;
end;
procedure TVirtualStringTreeProxy.DeleteChildren(const parentNode : PVirtualNode);
var
rttiMethodEntry : TRttiMethodEntry;
param : TValue;
begin
rttiMethodEntry := GetMethodEntry('DeleteChildren');
Assert(Length(rttiMethodEntry.params) = 2,'params length is not 2');
TValue.Make(@parentNode, rttiMethodEntry.params[0].ParamType.Handle, param);
rttiMethodEntry.rttiMethod.Invoke(FTreeInstance, [param, true]);
end;
destructor TVirtualStringTreeProxy.Destroy;
var
mEntry : TRttiMethodEntry;
propEntry : TRttiPropEntry;
begin
for mEntry in FMethodCache.Values do
mEntry.Free;
for propEntry in FPropCache.Values do
propEntry.Free;
inherited;
end;
procedure TVirtualStringTreeProxy.EndUpdate;
var
rttiMethodEntry : TRttiMethodEntry;
begin
rttiMethodEntry := GetMethodEntry('EndUpdate');
rttiMethodEntry.rttiMethod.Invoke(FTreeInstance, []);
end;
function TVirtualStringTreeProxy.GetFirstChild(node : PVirtualNode) : PVirtualNode;
begin
Result := PVirtualNode(PPointer(InvokeMethodWithPointerParam('GetFirstChild', node).GetReferenceToRawData())^);
end;
function TVirtualStringTreeProxy.GetFirstNode : PVirtualNode;
var
rttiMethodEntry : TRttiMethodEntry;
res : TValue;
begin
rttiMethodEntry := GetMethodEntry('GetFirst');
//no params so easy
res := rttiMethodEntry.rttiMethod.Invoke(FTreeInstance, []);
Result := PVirtualNode(PPointer(res.GetReferenceToRawData())^);
end;
function TVirtualStringTreeProxy.GetFirstVisibleNode : PVirtualNode;
var
rttiMethodEntry : TRttiMethodEntry;
res : TValue;
begin
rttiMethodEntry := GetMethodEntry('GetFirstVisible');
//no params so easy
res := rttiMethodEntry.rttiMethod.Invoke(FTreeInstance, []);
Result := PVirtualNode(PPointer(res.GetReferenceToRawData())^);
end;
function TVirtualStringTreeProxy.GetImages : TCustomImageList;
begin
Result := GetVSTProperty('Images').AsType<TCustomImageList>();
end;
function TVirtualStringTreeProxy.GetMethodEntry(const name: string): TRttiMethodEntry;
begin
if not FMethodCache.TryGetValue(LowerCase(name), result) then
begin
result := TRttiMethodEntry.Create;
result.rttiMethod := FTreeType.GetMethod(name);
if not Assigned(result.rttiMethod) then
raise Exception.Create('RTTI for method [' + name + '] not found.');
result.params := result.rttiMethod.GetParameters;
FMethodCache[LowerCase(name)] := result;
end;
end;
function TVirtualStringTreeProxy.GetNextNode(const node : PVirtualNode) : PVirtualNode;
begin
Result := PVirtualNode(PPointer(InvokeMethodWithPointerParam('GetNext', node).GetReferenceToRawData())^);
end;
function TVirtualStringTreeProxy.GetNextSibling(const node : PVirtualNode) : PVirtualNode;
begin
Result := PVirtualNode(PPointer(InvokeMethodWithPointerParam('GetNextSibling', node).GetReferenceToRawData())^);
end;
function TVirtualStringTreeProxy.GetNextVisible(const node : PVirtualNode) : PVirtualNode;
begin
Result := PVirtualNode(PPointer(InvokeMethodWithPointerParam('GetNextVisible', node).GetReferenceToRawData())^);
end;
function TVirtualStringTreeProxy.GetNodeData(const node : PVirtualNode) : PNodeData;
var
res : TValue;
begin
res := InvokeMethodWithPointerParam('GetNodeData', node);
Result := PNodeData(PPointer(res.GetReferenceToRawData())^);
end;
function TVirtualStringTreeProxy.GetNodeDataSize : integer;
begin
Result := GetVSTProperty('NodeDataSize').AsType<integer>;
end;
function TVirtualStringTreeProxy.GetPropEntry(const name: string): TRttiPropEntry;
begin
if not FPropCache.TryGetValue(LowerCase(name), result) then
begin
result := TRttiPropEntry.Create;
result.rttiProp := FTreeType.GetProperty(name);
if not Assigned(result.rttiProp) then
raise Exception.Create('RTTI for property [' + name + '] not found.');
FPropCache[LowerCase(name)] := result;
end;
end;
function TVirtualStringTreeProxy.GetRootNode : PVirtualNode;
begin
Result := PVirtualNode(PPointer(GetVSTProperty('RootNode').GetReferenceToRawData())^);
end;
function TVirtualStringTreeProxy.GetVSTProperty(const propertyName : string) : TValue;
var
rttiPropEntry : TRttiPropEntry;
begin
rttiPropEntry := GetPropEntry(propertyName);
Result := rttiPropEntry.rttiProp.GetValue(FTreeInstance)
end;
function TVirtualStringTreeProxy.InsertNode(const parentNode : PVirtualNode; const attachMode : TVTNodeAttachMode) : PVirtualNode;
var
rttiMethodEntry : TRttiMethodEntry;
param1, param2 : TValue;
begin
rttiMethodEntry := GetMethodEntry('InsertNode');
rttiMethodEntry.params := rttiMethodEntry.rttiMethod.GetParameters;
TValue.Make(@parentNode, rttiMethodEntry.params[0].ParamType.Handle, param1);
TValue.Make(@attachMode, rttiMethodEntry.params[1].ParamType.Handle, param2);
//function InsertNode(Node: PVirtualNode; Mode: TVTNodeAttachMode; UserData: Pointer = nil): PVirtualNode;
Result := PVirtualNode(PPointer(rttiMethodEntry.rttiMethod.Invoke(FTreeInstance, [param1, param2, TValue.From<Pointer>(nil)]).GetReferenceToRawData())^);
end;
function TVirtualStringTreeProxy.InvokeMethodWithPointerParam(const methodName : string; const value : Pointer) : TValue;
var
rttiMethodEntry : TRttiMethodEntry;
param : TValue;
begin
rttiMethodEntry := GetMethodEntry(methodName);
TValue.Make(@value, rttiMethodEntry.params[0].ParamType.Handle, param);
Result := rttiMethodEntry.rttiMethod.Invoke(FTreeInstance, [param]);
end;
procedure TVirtualStringTreeProxy.SetExpanded(const node : PVirtualNode; const value : boolean);
var
params : TArray<TRttiParameter>;
param1, param2 : TValue;
begin
if FExpandedRttiprop = nil then
FExpandedRttiprop := FTreeType.GetIndexedProperty('Expanded');
if not Assigned(FExpandedRttiprop) then
raise Exception.Create('RTTI Error accessing [Expanded] property');
params := FExpandedRttiprop.WriteMethod.GetParameters;
TValue.Make(@node, params[0].ParamType.Handle, param1);
TValue.Make(@value, params[1].ParamType.Handle, param2);
FExpandedRttiprop.WriteMethod.Invoke(FTreeInstance, [param1, param2]);
end;
procedure TVirtualStringTreeProxy.SetVSTProperty(const propertyName : string; const value : TValue);
var
rttiPropEntry : TRttiPropEntry;
begin
rttiPropEntry := GetPropEntry(propertyName);
rttiPropEntry.rttiProp.SetValue(FTreeInstance, value);
end;
end.
|
unit htInterfaces;
interface
uses
Classes, Types, Controls,
htMarkup, htStyle;
type
IhtGenerator = interface
['{68C6D14D-FBD4-4CD5-AAEC-ED939492EBDC}']
procedure Generate(inMarkup: ThtMarkup);
end;
//
IhtComponent = interface
['{9549CF05-8732-4893-9DB1-8592AC7502D7}']
function GetPriority: Integer;
property Priority: Integer read GetPriority;
end;
//
IhtControl = interface
['{840D6640-4D1A-4F5D-A57C-AF4DD7D4CB52}']
function GetBoxHeight: Integer;
function GetBoxRect: TRect;
function GetBoxWidth: Integer;
function GetCtrlStyle: ThtStyle;
function GetStyle: ThtStyle;
function GetStyleClass: string;
//
procedure Generate(const inContainer: string; inMarkup: ThtMarkup);
procedure SetStyleClass(const Value: string);
//
property BoxHeight: Integer read GetBoxHeight;
property BoxRect: TRect read GetBoxRect;
property BoxWidth: Integer read GetBoxWidth;
property CtrlStyle: ThtStyle read GetCtrlStyle;
property Style: ThtStyle read GetStyle;
property StyleClass: string read GetStyleClass write SetStyleClass;
end;
function htBoxHeight(inCtrl: TControl): Integer;
function htBoxWidth(inCtrl: TControl): Integer;
implementation
uses
LrVclUtils;
function htBoxHeight(inCtrl: TControl): Integer;
var
c: IhtControl;
begin
if LrIsAs(inCtrl, IhtControl, c) then
Result := c.BoxHeight
else
Result := inCtrl.Height;
end;
function htBoxWidth(inCtrl: TControl): Integer;
var
c: IhtControl;
begin
if LrIsAs(inCtrl, IhtControl, c) then
Result := c.BoxWidth
else
Result := inCtrl.Width;
end;
end.
|
unit EffectsToolUnit;
interface
uses
System.Math,
System.Types,
System.SysUtils,
System.Classes,
Winapi.Windows,
Vcl.Dialogs,
Vcl.Forms,
Vcl.Controls,
Vcl.Graphics,
Vcl.ExtCtrls,
Vcl.ComCtrls,
Vcl.Themes,
MPCommonUtilities,
Dmitry.Controls.WebLink,
ToolsUnit,
ImageHistoryUnit,
Effects,
ExEffects,
ExEffectsUnitW,
OptimizeImageUnit,
UnitBitmapImageList,
EasyListView,
uMemory,
uBitmapUtils,
uSettings,
uListViewUtils,
uEditorTypes,
uTranslate,
uMemoryEx;
type
TEffectsManager = class(TObject)
private
{ Private declarations }
Effects: TBaseEffectProcedures;
ExEffects: TExEffects;
public
{ Public declarations }
function L(StringToTranslate : string) : string;
procedure AddBaseEffect(Effect: TBaseEffectProcW);
function GetBaseEffects: TBaseEffectProcedures;
procedure AddExEffect(Effect: TExEffectsClass);
function GetExEffects: TExEffects;
procedure InitializeBaseEffects;
function GetEffectNameByID(ID: string): string;
end;
type
TEffectsToolPanelClass = class(TToolsPanelClass)
private
{ Private declarations }
NewImage: TBitmap;
CloseLink: TWebLink;
MakeItLink: TWebLink;
EffectsChooser: TEasyListView;
FSelectTimer: TTimer;
FImageList: TBitmapImageList;
EM: TEffectsManager;
BaseEffects: TBaseEffectProcedures;
ExEffects: TExEffects;
BaseImage: TBitmap;
FOnDone: TNotifyEvent;
ApplyOnDone: Boolean;
procedure FreeNewImage;
procedure ListViewItemThumbnailDraw(Sender: TCustomEasyListview; Item: TEasyItem; ACanvas: TCanvas;
ARect: TRect; AlphaBlender: TEasyAlphaBlender; var DoDefault: Boolean);
procedure ListViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure SelectTimerOnTimer(Sender: TObject);
protected
function LangID: string; override;
public
{ Public declarations }
FSID: string;
TempFilterID: string;
FilterID: string;
FilterInitialString: string;
OutFilterInitialString: string;
class function ID: string; override;
function GetProperties: string; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ClosePanel; override;
procedure MakeTransform; override;
procedure ClosePanelEvent(Sender: TObject);
procedure DoMakeImage(Sender: TObject);
procedure SelectEffect(Sender: TCustomEasyListview; Item: TEasyItem);
procedure SetBaseImage(Image: TBitmap);
procedure FillEffects(OneEffectID: string = '');
procedure SetThreadImage(Image: TBitmap; SID: string);
procedure SetProgress(Progress: Integer; SID: string);
procedure SetNewImage(Image: TBitmap);
procedure ExecuteProperties(Properties: string; OnDone: TNotifyEvent); override;
procedure SetProperties(Properties: string); override;
end;
implementation
{ TEffectsToolPanelClass }
uses
EffectsToolThreadUnit,
ImEditor,
ExEffectsUnit,
ExEffectFormUnit;
procedure TEffectsToolPanelClass.ClosePanel;
begin
if Assigned(OnClosePanel) then
OnClosePanel(Self);
if not ApplyOnDone then
inherited;
end;
procedure TEffectsToolPanelClass.ClosePanelEvent(Sender: TObject);
begin
CancelTempImage(True);
NewImage := nil;
ClosePanel;
end;
constructor TEffectsToolPanelClass.Create(AOwner: TComponent);
begin
inherited;
NewImage := nil;
ApplyOnDone := False;
Align := AlClient;
BaseImage := TBitmap.Create;
BaseImage.PixelFormat := pf24bit;
FSelectTimer := TTimer.Create(nil);
FSelectTimer.Interval := 1;
FSelectTimer.Enabled := False;
FSelectTimer.OnTimer := SelectTimerOnTimer;
EffectsChooser := TEasyListview.Create(nil);
EffectsChooser.Parent := AOwner as TWinControl;
EffectsChooser.Left := 5;
EffectsChooser.Top := 5;
EffectsChooser.Width := 180;
EffectsChooser.Height := EffectsChooser.Parent.Height - 75;
EffectsChooser.Anchors := [akLeft, akTop, akRight, akBottom];
EffectsChooser.OnItemSelectionChanged := SelectEffect;
EffectsChooser.OnMouseMove := ListViewMouseMove;
EffectsChooser.DoubleBuffered := True;
EffectsChooser.EditManager.Enabled := False;
EffectsChooser.Scrollbars.SmoothScrolling := AppSettings.Readbool('Options', 'SmoothScrolling', True);
if StyleServices.Enabled and TStyleManager.IsCustomStyleActive then
EffectsChooser.ShowThemedBorder := False;
EffectsChooser.OnItemThumbnailDraw := ListViewItemThumbnailDraw;
SetLVThumbnailSize(EffectsChooser, 130);
SetLVSelection(EffectsChooser, False, [cmbLeft]);
EffectsChooser.Selection.BlendIcon := False;
EffectsChooser.Selection.FullRowSelect := True;
FImageList := TBitmapImageList.Create;
EffectsChooser.View := elsThumbnail;
MakeItLink := TWebLink.Create(nil);
MakeItLink.Parent := AOwner as TWinControl;
MakeItLink.Text := L('Apply');
MakeItLink.Top := EffectsChooser.Top + EffectsChooser.Height + 8;
MakeItLink.Left := 10;
MakeItLink.Visible := True;
MakeItLink.OnClick := DoMakeImage;
MakeItLink.LoadFromResource('DOIT');
MakeItLink.Anchors := [akLeft, akBottom];
MakeItLink.RefreshBuffer(True);
CloseLink := TWebLink.Create(nil);
CloseLink.Parent := AOwner as TWinControl;
CloseLink.Text := L('Close tool');
CloseLink.Top := MakeItLink.Top + MakeItLink.Height + 5;
CloseLink.Left := 10;
CloseLink.Visible := True;
CloseLink.OnClick := ClosePanelEvent;
CloseLink.LoadFromResource('CANCELACTION');
CloseLink.Anchors := [akLeft, akBottom];
CloseLink.RefreshBuffer(True);
end;
destructor TEffectsToolPanelClass.Destroy;
begin
F(CloseLink);
F(EffectsChooser);
F(FSelectTimer);
F(MakeItLink);
F(EM);
F(FImageList);
F(BaseImage);
FreeNewImage;
inherited;
end;
procedure TEffectsToolPanelClass.DoMakeImage(Sender: TObject);
begin
MakeTransform;
end;
procedure TEffectsToolPanelClass.ExecuteProperties(Properties: string; OnDone: TNotifyEvent);
begin
FOnDone := OnDone;
ApplyOnDone := True;
SelectEffect(EffectsChooser, nil);
end;
procedure TEffectsToolPanelClass.FillEffects(OneEffectID: string = '');
var
Item: TEasyItem;
I: Integer;
Bitmap, Bitmap32: TBitmap;
ExEffect: TExEffect;
Filter_ID: string;
begin
EM := TEffectsManager.Create;
EM.InitializeBaseEffects;
BaseEffects := EM.GetBaseEffects;
ExEffects := EM.GetExEffects;
Bitmap := TBitmap.Create;
try
Bitmap.Width := BaseImage.Width;
Bitmap.Height := BaseImage.Height;
Filter_ID := Copy(OneEffectID, 1, 38);
FilterInitialString := Copy(OneEffectID, 39, Length(OneEffectID) - 38);
OutFilterInitialString := FilterInitialString;
for I := 0 to Length(BaseEffects) - 1 do
begin
if OneEffectID <> '' then
if BaseEffects[I].ID <> Filter_ID then
Continue;
BaseEffects[I].Proc(BaseImage, Bitmap);
Bitmap32 := TBitmap.Create;
try
DrawShadowToImage(Bitmap32, Bitmap);
FImageList.AddBitmap(Bitmap32);
Bitmap32 := nil;
finally
F(Bitmap32);
end;
Item := EffectsChooser.Items.Add;
Item.ImageIndex := FImageList.Count - 1;
Item.Data := Pointer(I);
Item.Caption := BaseEffects[I].name;
end;
for I := 0 to Length(ExEffects) - 1 do
begin
ExEffect := ExEffects[I].Create;
try
if OneEffectID <> '' then
if ExEffect.ID <> Filter_ID then
Continue;
ExEffect.GetPreview(BaseImage, Bitmap);
Bitmap32 := TBitmap.Create;
try
DrawShadowToImage(Bitmap32, Bitmap);
FImageList.AddBitmap(Bitmap32);
Bitmap32 := nil;
finally
F(Bitmap32);
end;
Item := EffectsChooser.Items.Add;
Item.ImageIndex := FImageList.Count - 1;
Item.Data := Pointer(I + Length(BaseEffects));
Item.Caption := ExEffect.GetName;
finally
F(ExEffect);
end;
end;
finally
F(Bitmap);
end;
end;
procedure TEffectsToolPanelClass.FreeNewImage;
begin
if Assigned(CancelPointerToImage) then
CancelPointerToImage(NewImage);
F(NewImage);
end;
function TEffectsToolPanelClass.GetProperties: string;
begin
Result := FilterID + '[' + OutFilterInitialString + ']';
end;
class function TEffectsToolPanelClass.ID: string;
begin
Result := '{2AA20ABA-9205-4655-9BCE-DF3534C4DD79}';
end;
function TEffectsToolPanelClass.LangID: string;
begin
Result := 'EffectsTool';
end;
procedure TEffectsToolPanelClass.ListViewMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
Item: TEasyItem;
R: TRect;
ViewportPoint: TPoint;
begin
ViewportPoint := Point(X, Y);
R := EffectsChooser.Scrollbars.ViewableViewportRect;
ViewportPoint.X := ViewportPoint.X + R.Left;
ViewportPoint.Y := ViewportPoint.Y + R.Top;
Item := EffectsChooser.Groups.Groups[0].ItemByPoint(ViewportPoint);
if (Item <> nil) and Item.SelectionHitPt(ViewportPoint, eshtClickSelect) then
EffectsChooser.Cursor := crHandPoint;
end;
procedure TEffectsToolPanelClass.ListViewItemThumbnailDraw(
Sender: TCustomEasyListview; Item: TEasyItem; ACanvas: TCanvas; ARect: TRect;
AlphaBlender: TEasyAlphaBlender; var DoDefault: Boolean);
var
W, H: Integer;
X, Y: Integer;
ImageW, ImageH: Integer;
Graphic: TBitmap;
begin
Graphic := FImageList[Item.ImageIndex].Bitmap;
W := ARect.Right - ARect.Left;
H := ARect.Bottom - ARect.Top + 4;
ImageW := Graphic.Width;
ImageH := Graphic.Height;
ProportionalSize(W, H, ImageW, ImageH);
X := ARect.Left + W div 2 - ImageW div 2;
Y := ARect.Bottom - ImageH;
Graphic.AlphaFormat := afDefined;
ACanvas.Draw(X, Y, Graphic, 255);
end;
procedure TEffectsToolPanelClass.MakeTransform;
begin
if NewImage <> nil then
begin
ImageHistory.Add(NewImage, '{' + ID + '}[' + GetProperties + ']');
SetImagePointer(NewImage);
NewImage := nil;
end;
ClosePanel;
end;
procedure TEffectsToolPanelClass.SelectEffect(Sender: TCustomEasyListview; Item: TEasyItem);
begin
FSelectTimer.Enabled := False;
FSelectTimer.Enabled := True;
end;
procedure TEffectsToolPanelClass.SelectTimerOnTimer(Sender: TObject);
var
ExEffectForm: TExEffectForm;
ExEffect: TExEffect;
Item : TEasyItem;
begin
FSelectTimer.Enabled := False;
FreeNewImage;
NewImage := TBitmap.Create;
NewImage.PixelFormat := pf24bit;
if ApplyOnDone = True then
begin
if EffectsChooser.Items.Count = 1 then
begin
EffectsChooser.Items[0].Selected := True;
EffectsChooser.Items[0].Focused := True;
end else
begin
if Assigned(FOnDone) then
FOnDone(Self);
Exit;
end;
end;
Item := EffectsChooser.Selection.First;
if Item = nil then
Exit;
FSID := IntToStr(Random(MaxInt));
if Integer(Item.Data) <= Length(BaseEffects) - 1 then
begin
NewImage.Assign(Image);
TempFilterID := BaseEffects[Integer(Item.Data)].ID;
(Editor as TImageEditor).StatusBar1.Panels[1].Text := Format(L('Filter "%s" is working'), [BaseEffects[Integer(Item.Data)].name]);
TBaseEffectThread.Create(Self, BaseEffects[Integer(Item.Data)].Proc, NewImage, FSID, SetThreadImage, Editor);
NewImage := nil;
end else
begin
Application.CreateForm(TExEffectForm, ExEffectForm);
try
ExEffectForm.Editor := Editor;
ExEffect := ExEffects[Integer(Item.Data) - Length(BaseEffects)].Create;
try
TempFilterID := ExEffect.ID;
(Editor as TImageEditor).StatusBar1.Panels[1].Text := Format(L('Filter "%s" is working'), [ExEffect.GetName]);
finally
F(ExEffect);
end;
OutFilterInitialString := FilterInitialString;
if not ExEffectForm.Execute(Self, Image, NewImage, ExEffects[Integer(Item.Data) - Length(BaseEffects)],
OutFilterInitialString) then
NewImage := nil;
finally
R(ExEffectForm);
end;
if ApplyOnDone then
begin
MakeTransform;
if Assigned(FOnDone) then
FOnDone(Self);
end;
end;
end;
procedure TEffectsToolPanelClass.SetBaseImage(Image: TBitmap);
begin
BaseImage.Assign(Image);
end;
procedure TEffectsToolPanelClass.SetNewImage(Image: TBitmap);
begin
FilterID := TempFilterID;
FreeNewImage;
Pointer(NewImage) := Pointer(Image);
SetTempImage(Image);
end;
procedure TEffectsToolPanelClass.SetProgress(Progress: Integer; SID: string);
begin
if SID = FSID then
(Editor as TImageEditor).FStatusProgress.Position := Progress;
end;
procedure TEffectsToolPanelClass.SetProperties(Properties: String);
begin
end;
procedure TEffectsToolPanelClass.SetThreadImage(Image: TBitmap; SID: string);
begin
if SID = FSID then
begin
FilterID := TempFilterID;
FreeNewImage;
Pointer(NewImage) := Pointer(Image);
SetTempImage(Image);
end else
F(Image);
if ApplyOnDone then
begin
MakeTransform;
if Assigned(FOnDone) then
FOnDone(Self);
end;
end;
{ TEffectsmanager }
function BaseEffectProcW(Proc: TBaseEffectProc; name: string; ID: string): TBaseEffectProcW;
begin
Result.Proc := Proc;
Result.name := name;
Result.ID := ID;
end;
procedure TEffectsManager.AddBaseEffect(Effect: TBaseEffectProcW);
begin
SetLength(Effects, Length(Effects) + 1);
Effects[Length(Effects) - 1] := Effect;
end;
procedure TEffectsManager.AddExEffect(Effect: TExEffectsClass);
begin
SetLength(ExEffects, Length(ExEffects) + 1);
ExEffects[Length(ExEffects) - 1] := Effect;
end;
function TEffectsManager.GetBaseEffects: TBaseEffectProcedures;
begin
Result := Effects;
end;
function TEffectsManager.GetEffectNameByID(ID: string): string;
var
I: Integer;
ExEffect: TExEffect;
begin
Result := TA('Unknown');
for I := 0 to Length(Effects) - 1 do
begin
if Effects[I].ID = ID then
begin
Result := Effects[I].name;
Exit;
end;
end;
for I := 0 to Length(ExEffects) - 1 do
begin
if ExEffects[I].ID = ID then
begin
ExEffect := ExEffects[I].Create;
try
Result := ExEffect.GetName;
finally
F(ExEffect);
end;
Break;
end;
end;
end;
function TEffectsManager.GetExEffects: TExEffects;
begin
Result := ExEffects;
end;
procedure TEffectsManager.InitializeBaseEffects;
begin
AddBaseEffect(BaseEffectProcW(Sepia, L('Sepia'), '{CA27D483-3F3D-4805-B5CE-56E3D9C3F3ED}'));
AddBaseEffect(BaseEffectProcW(GrayScaleImage, L('Grayscale'), '{92C0D214-A561-4AAA-937E-CD3110905524}'));
AddBaseEffect(BaseEffectProcW(Dither, L('Dither'), '{0A18043D-1696-4B18-A532-8B0EE731B865}'));
AddBaseEffect(BaseEffectProcW(Inverse, L('Inverse'), '{62BE35C1-3C56-4AAC-B521-46076CB1DE20}'));
AddBaseEffect(BaseEffectProcW(AutoLevels, L('Auto levels'), '{F28C1B08-8C3B-4522-BE41-64998F58AC31}'));
AddBaseEffect(BaseEffectProcW(AutoColors, L('Auto colors'), '{B09B7105-8FB8-4E1B-B1D5-09486B33ED5B}'));
AddBaseEffect(BaseEffectProcW(Emboss, L('Emboss'), '{1262A88E-55C5-4894-873F-ED458D1CDD8C}'));
AddBaseEffect(BaseEffectProcW(AntiAlias, L('Smoothing'), '{C0EF3036-EFB4-459E-A16E-6DE8AA7D6EBD}'));
AddBaseEffect(BaseEffectProcW(OptimizeImage, L('Optimize image'), '{718F3546-E030-4CBF-BE61-49DAD7232B10}'));
AddExEffect(TDisorderEffect);
AddExEffect(TGausBlur);
AddExEffect(TSplitBlurEffect);
AddExEffect(TSharpen);
AddExEffect(TPixelsEffect);
AddExEffect(TWaveEffect);
AddExEffect(TGrayScaleEffect);
AddExEffect(TSepeaEffect);
AddExEffect(TReplaceColorEffect);
AddExEffect(TAddColorNoiseEffect);
AddExEffect(TAddMonoNoiseEffect);
AddExEffect(TFishEyeEffect);
AddExEffect(TTwistEffect);
AddExEffect(TCustomMatrixEffect);
end;
function TEffectsManager.L(StringToTranslate: string): string;
begin
Result := TTranslateManager.Instance.SmartTranslate(StringToTranslate, 'Effects');
end;
end.
|
unit uAddPlace;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFControl, uLabeledFControl, uCharControl, uBoolControl,
uSpravControl, uFormControl, StdCtrls, Buttons, uAdr_DataModule,
uAddModifForm;
type
TAdd_Place_Form = class(TAddModifForm)
qFCC_Name: TqFCharControl;
qFSC_Type: TqFSpravControl;
qFSC_Region: TqFSpravControl;
qFSC_District: TqFSpravControl;
qFCC_Zip: TqFCharControl;
qFBC_IsCap: TqFBoolControl;
qFBC_IsRC: TqFBoolControl;
qFBC_IsDC: TqFBoolControl;
qFFC_Place: TqFFormControl;
OkButton: TBitBtn;
CancelButton: TBitBtn;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure qFSC_TypeOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure qFSC_RegionOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure qFSC_DistrictOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
private
{ Private declarations }
public
Mode:TFormMode;
// DBHandle: integer;
constructor Create(AOwner: TComponent ; DMod: TAdrDM; Mode: TFormMode; Where: Variant);
{ Public declarations }
end;
var
Add_Place_Form: TAdd_Place_Form;
implementation
{$R *.dfm}
uses RxMemDS, uUnivSprav;
constructor TAdd_Place_Form.Create(AOwner: TComponent ; DMod: TAdrDM; Mode: TFormMode; Where: Variant);
begin
inherited Create(AOwner);
Self.Mode := Mode;
DBHandle:=Integer(DMod.pFIBDB_Adr.Handle);
qFFC_Place.Prepare(DMod.pFIBDB_Adr,Mode,Where,Null);
end;
procedure TAdd_Place_Form.OkButtonClick(Sender: TObject);
begin
qFFC_Place.Ok;
end;
procedure TAdd_Place_Form.CancelButtonClick(Sender: TObject);
begin
Close;
end;
procedure TAdd_Place_Form.qFSC_TypeOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
Params:TUnivParams;
OutPut : TRxMemoryData;
begin
Params.FormCaption:='Довідник типів міст';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbExit];
Params.AddFormClass:='TAdd_Region_Form';
Params.ModifFormClass:='TAdd_Region_Form';
Params.TableName:='ini_type_place';
Params.Fields:='Name_full,id_type_place';
Params.FieldsName:='Назва';
Params.KeyField:='id_type_place';
Params.ReturnFields:='Name_full,id_type_place';
Params.DeleteSQL:='execute procedure adr_region_d(:id_region);';
Params.DBHandle:=DBHandle;
OutPut:=TRxMemoryData.Create(self);
if GetUnivSprav(Params,OutPut)
then
begin
value:=output['id_type_place'];
DisplayText:=VarToStr(output['Name_full']);
end;
end;
procedure TAdd_Place_Form.qFSC_RegionOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
Params:TUnivParams;
OutPut : TRxMemoryData;
begin
Params.FormCaption:='Довідник регіонів';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit];
Params.AddFormClass:='TAdd_Region_Form';
Params.ModifFormClass:='TAdd_Region_Form';
Params.TableName:='adr_region';
Params.Fields:='Name_region,id_region';
Params.FieldsName:='Назва';
Params.KeyField:='id_region';
Params.ReturnFields:='Name_region,id_region';
Params.DeleteSQL:='execute procedure adr_region_d(:id_region);';
Params.DBHandle:=DBHandle;
OutPut:=TRxMemoryData.Create(self);
if GetUnivSprav(Params,OutPut)
then
begin
// ShowInfo(output);
value:=output['id_region'];
DisplayText:=VarToStr(output['Name_region']);
end;
end;
procedure TAdd_Place_Form.qFSC_DistrictOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
Params:TUnivParams;
OutPut : TRxMemoryData;
begin
if VarIsNull(qFSC_Region.Value) then
begin
ShowMessage('Спочатку оберіть регіон!');
Exit;
end;
Params.FormCaption:='Довідник районів';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit];
Params.AddFormClass:='TAdd_District_Form';
Params.ModifFormClass:='TAdd_District_Form';
Params.TableName:='adr_district_select('+IntToStr(qFSC_Region.Value)+');';
Params.Fields:='Name_district,id_district';
Params.FieldsName:='Район';
Params.KeyField:='id_district';
Params.ReturnFields:='Name_district,id_district';
Params.DeleteSQL:='execute procedure adr_district_d(:id_district);';
Params.DBHandle:=DBHandle;
OutPut:=TRxMemoryData.Create(self);
if GetUnivSprav(Params,OutPut)
then
begin
// ShowInfo(output);
value:=output['id_district'];
DisplayText:=VarToStr(output['Name_district']);
end;
end;
initialization
RegisterClass(TAdd_Place_Form);
end.
|
{ CapeRaven mesh demo.
Changing mesh vertex data, normals and striping redundent data.
Custom cube class declared for vertex point identification.
On moving these vertex modifiers, the apointed vertex follows.
}
unit FMeshShow;
interface
uses
Winapi.Windows, Winapi.Messages,
System.Contnrs, System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Buttons,
GLScene, GLVectorFileObjects, GLWin32Viewer, GlFile3DS, GLObjects, GLTexture,
OpenGL1X, GLState,{ HoloGizmo, } GLMaterial, GLGeomObjects, GLGraph,
GLCadencer, GLVectorTypes, GLVectorGeometry, GLCoordinates, GLColor, OpenGLTokens,
GLPersistentClasses, GLVectorLists, GLMeshUtils, GLCrossPlatform, GLBaseClasses;
type
TMovingAxis = (maAxisX, maAxisY, maAxisZ, maAxisXY, maAxisXZ, maAxisYZ);
TModifierCube = class(TGLCube)
public
FVectorIndex : Integer;
FMeshObjIndex : Integer;
constructor Create(AOwner: TComponent); override;
end;
TMeshShowFrm = class(TForm)
Scn: TGLSceneViewer;
GLScene1: TGLScene;
GLCamera1: TGLCamera;
GLFreeForm1: TGLFreeForm;
GLLightSource1: TGLLightSource;
MainMenu1: TMainMenu;
File1: TMenuItem;
Open1: TMenuItem;
Save1: TMenuItem;
Edit1: TMenuItem;
N1: TMenuItem;
Exit1: TMenuItem;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
GLDummyCube1: TGLDummyCube;
StatusBar: TStatusBar;
ControlPanel: TPanel;
ViewControlPanel: TMenuItem;
dcModifiers: TGLDummyCube;
Splitter1: TSplitter;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
GroupBox2: TGroupBox;
rbXY: TRadioButton;
rbZY: TRadioButton;
tbPos: TTrackBar;
Label6: TLabel;
GroupBox1: TGroupBox;
Bevel1: TBevel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label7: TLabel;
chbShowAxis: TCheckBox;
chbViewPoints: TCheckBox;
cbPolygonMode: TComboBox;
Label2: TLabel;
TabSheet3: TTabSheet;
TrackBar1: TTrackBar;
GroupBox3: TGroupBox;
btnVertex: TBitBtn;
btnNormals: TBitBtn;
btnTextcoords: TBitBtn;
btnGroups: TBitBtn;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure ShowHint(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ScnMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ScnMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure TrackBar1Change(Sender: TObject);
procedure Open1Click(Sender: TObject);
procedure Save1Click(Sender: TObject);
procedure Contents1Click(Sender: TObject);
procedure OnHelp1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure ScnMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cbPolygonModeChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure chbViewPointsClick(Sender: TObject);
procedure chbShowAxisClick(Sender: TObject);
procedure tbPosChange(Sender: TObject);
procedure ScnBeforeRender(Sender: TObject);
procedure btnVertexClick(Sender: TObject);
procedure btnNormalsClick(Sender: TObject);
procedure btnTextcoordsClick(Sender: TObject);
procedure btnGroupsClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ViewControlPanelClick(Sender: TObject);
private
FOldX, FOldY : Integer;
FModifierList : TObjectList;
FSelectedModifier : TModifierCube;
FMoveZ : Boolean;
FOldMouseWorldPos : TVector;
function GetPolygonMode: TPolygonMode;
procedure SetPolygonMode(const Value: TPolygonMode);
{ function MouseWorldPos(x, y: Integer): TVector;}
{Create cubes used to modify vertex points}
procedure SetVertexModifiers;
{Populate statusbar with object information}
procedure ShowModifierStatus(const aObj : TModifierCube);
{Change the mesh vector property for the selected modifier.}
procedure ChangeMeshVector(const aObj : TModifierCube; const aPos : TVector4f);
{Identify mouse position in X, Y and Z axis}
function MouseWorldPos(x, y : Integer) : TVector;
{Strip redundent data, recalculate normals and faces}
procedure StripAndRecalc;
{Set Freeform's polygon mode: line, fill or points}
property PolygonMode : TPolygonMode read GetPolygonMode write SetPolygonMode;
public
MovingAxis: TMovingAxis;
Pick : TGLCustomSceneObject;
SelectedObject: TGLCustomSceneObject;
OldCursorPick: TGLCustomSceneObject;
{ GizmoX,
GizmoY,
GizmoZ: TGLGizmoArrow;
GizmoCornerXY,
GizmoCornerXZ,
GizmoCornerYZ: TGLGizmoCorner; }
mx, my : Integer;
lastMouseWorldPos: TVector;
procedure UpdateGizmo;
end;
var
MeshShowFrm: TMeshShowFrm;
implementation
uses
FMeshData, uGlobals;
{$R *.dfm}
const
{Default combobox index for startup}
CLinePolyMode = 1;
{Scale dimention}
CModifierDim = 0.04;
var
{Modifier colors}
CModColorNormal : TColorVector;
CModColorSelect : TColorVector;
constructor TModifierCube.Create(AOwner: TComponent);
begin
inherited;
{Set the modifiers initial size and color}
CubeWidth := CModifierDim;
CubeHeight := CModifierDim;
CubeDepth := CModifierDim;
Material.FrontProperties.Diffuse.Color := CModColorNormal;
end;
procedure GenerateIcosahedron(Vertices : TAffineVectorList; Indices : TIntegerList);
var
phi, a, b : Single;
begin
if not (Assigned(Vertices) or Assigned(Indices)) then exit;
phi:=(1+sqrt(5))/2;
a:=0.5;
b:=1/(2*phi);
Vertices.Clear;
with Vertices do begin
Add( 0,-b,-a);
Add( 0,-b, a);
Add( 0, b,-a);
Add( 0, b, a);
Add(-a, 0,-b);
Add(-a, 0, b);
Add( a, 0,-b);
Add( a, 0, b);
Add(-b,-a, 0);
Add(-b, a, 0);
Add( b,-a, 0);
Add( b, a, 0);
end;
Indices.Clear;
Indices.AddIntegers(
[ 2,11, 9,
3, 9,11,
3, 1, 5,
3, 7, 1,
2, 0, 6,
2, 4, 0,
1,10, 8,
0, 8,10,
9, 5, 4,
8, 4, 5,
11, 6, 7,
10, 7, 6,
3, 5, 9,
3,11, 7,
2, 9, 4,
2, 6,11,
0, 4, 8,
0,10, 6,
1, 8, 5,
1, 7,10 ] );
end;
procedure BuildGeosphere(GLBaseMesh : TGLBaseMesh; Iterations : Integer);
var
i : Integer;
mesh : TMeshObject;
facegroup : TFGVertexIndexList;
begin
mesh:=TMeshObject.CreateOwned(GLBaseMesh.MeshObjects);
mesh.Mode:=momFaceGroups;
facegroup:=TFGVertexIndexList.CreateOwned(mesh.FaceGroups);
GenerateIcosahedron(mesh.Vertices, facegroup.VertexIndices);
mesh.BuildNormals(facegroup.VertexIndices, momTriangles);
for i:=0 to Iterations-1 do
SubdivideTriangles(1, mesh.Vertices, facegroup.VertexIndices, mesh.Normals);
end;
{
function THoloForm.MouseWorldPos(x, y: Integer): TVector;
var
v : TVector;
begin
y := GLSceneViewer.Height - y;
if Assigned(FSelectedModifier) then
begin
SetVector(v, x, y, 0);
if FMoveZ then
GLSceneViewer.Buffer.ScreenVectorIntersectWithPlaneXZ(v, FSelectedModifier.Position.Y, Result)
else
GLSceneViewer.Buffer.ScreenVectorIntersectWithPlaneXY(v, FSelectedModifier.Position.Z, Result);
end
else
SetVector(Result, NullVector);
end;}
function TMeshShowFrm.MouseWorldPos(x, y : Integer) : TVector;
var
v : TVector;
begin
y:=Scn.Height-y;
if Assigned(FSelectedModifier) then
begin
SetVector(v, x, y, 0);
if FMoveZ then
Scn.Buffer.ScreenVectorIntersectWithPlaneXZ(v, FSelectedModifier.Position.Y, Result)
else
Scn.Buffer.ScreenVectorIntersectWithPlaneXY(v, FSelectedModifier.Position.Z, Result);
end
else
if Assigned(SelectedObject) then
begin
SetVector(v, x, y, 0);
case MovingAxis of
maAxisX : begin
Scn.Buffer.ScreenVectorIntersectWithPlaneXZ(v, SelectedObject.Position.Y, Result);
end;
maAxisY : begin
Scn.Buffer.ScreenVectorIntersectWithPlaneYZ(v, SelectedObject.Position.X, Result);
end;
maAxisZ : begin
Scn.Buffer.ScreenVectorIntersectWithPlaneYZ(v, SelectedObject.Position.X, Result);
end;
maAxisXY: begin
Scn.Buffer.ScreenVectorIntersectWithPlaneXY(v, SelectedObject.Position.Z, Result);
end;
maAxisXZ: begin
Scn.Buffer.ScreenVectorIntersectWithPlaneXZ(v, SelectedObject.Position.Y, Result);
end;
maAxisYZ: begin
Scn.Buffer.ScreenVectorIntersectWithPlaneYZ(v, SelectedObject.Position.X, Result);
end;
end;
end
else SetVector(Result, NullVector);
end;
procedure TMeshShowFrm.FormShow(Sender: TObject);
begin
Application.OnHint := ShowHint;
end;
procedure TMeshShowFrm.FormCreate(Sender: TObject);
begin
top:=HoloFormY;
left:=HoloFormX;
{ GizmoX := TGLGizmoArrow.Create(GLScene1);
GizmoX.GizmoType := gtAxisX;
GizmoX.Name := 'GizmoX';
GizmoX.Height := 0.5;
GLDummyCube1.AddChild(GizmoX);
GizmoY := TGLGizmoArrow.Create(GLScene1);
GizmoY.GizmoType := gtAxisY;
GizmoY.Name := 'GizmoY';
GizmoY.Height := 0.5;
GLDummyCube1.AddChild(GizmoY);
GizmoZ := TGLGizmoArrow.Create(GLScene1);
GizmoZ.GizmoType := gtAxisZ;
GizmoZ.Name := 'GizmoZ';
GizmoZ.Height := 0.5;
GLDummyCube1.AddChild(GizmoZ);
GizmoCornerXY := TGLGizmoCorner.Create(GLScene1);
GizmoCornerXY.GizmoType := gtPlaneXY;
GizmoCornerXY.Name := 'GizmoXY';
GizmoCornerXY.Height := 0.2;
GizmoCornerXY.Distance := 0.5;
GLDummyCube1.AddChild(GizmoCornerXY);
GizmoCornerXZ := TGLGizmoCorner.Create(GLScene1);
GizmoCornerXZ.GizmoType := gtPlaneXZ;
GizmoCornerXZ.Name := 'GizmoXZ';
GizmoCornerXZ.Height := 0.2;
GizmoCornerXZ.Distance := 0.5;
GLDummyCube1.AddChild(GizmoCornerXZ);
GizmoCornerYZ := TGLGizmoCorner.Create(GLScene1);
GizmoCornerYZ.GizmoType := gtPlaneYZ;
GizmoCornerYZ.Name := 'GizmoYZ';
GizmoCornerYZ.Height := 0.2;
GizmoCornerYZ.Distance := 0.5;
GLDummyCube1.AddChild(GizmoCornerYZ);}
{Do initial setup}
FModifierList := TObjectList.Create;
CModColorNormal := clrCoral;
CModColorSelect := clrSkyBlue;
BuildGeosphere(GLFreeForm1, 3);
StripAndRecalc;
SetVertexModifiers;
GLFreeForm1.StructureChanged;
cbPolygonMode.ItemIndex := CLinePolyMode;
end;
function TMeshShowFrm.GetPolygonMode: TPolygonMode;
begin
Result := GLFreeForm1.Material.PolygonMode;
end;
procedure TMeshShowFrm.SetPolygonMode(const Value: TPolygonMode);
begin
GLFreeForm1.Material.PolygonMode := Value;
end;
procedure TMeshShowFrm.cbPolygonModeChange(Sender: TObject);
begin
{GLFreeForm1.Material.FrontProperties.}
PolygonMode :=
TPolygonMode(cbPolygonMode.ItemIndex);
{ if CheckBox1.Checked then
GLFreeForm1.Material.PolygonMode:=pmFill
else
GLFreeForm1.Material.PolygonMode:=pmLines;}
end;
procedure TMeshShowFrm.ShowHint(Sender: TObject);
begin
{ HintPanel.Caption := GetLongHint(Application.Hint);}
StatusBar.Panels[0].Text := Application.Hint;
end;
procedure TMeshShowFrm.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TMeshShowFrm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
HoloFormY:= MeshShowFrm.top;
HoloFormX:= MeshShowFrm.left;
end;
procedure TMeshShowFrm.FormDestroy(Sender: TObject);
begin
FModifierList.Clear;
FreeAndNil(FModifierList);
end;
procedure TMeshShowFrm.ScnMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
lObj : TGLBaseSceneObject;
begin
mx:=x; my:=y;
FOldX := X; FOldY := Y;
{If selecting a different modifier, change the last one's color back to default}
if Assigned(FSelectedModifier) then
FSelectedModifier.Material.FrontProperties.Diffuse.Color := CModColorNormal;
{Get selected objects}
if (ssCtrl in Shift) then
begin
{Check if selected object is a modifier.
If so, change modifiers color as to indicated selected modifier.}
lObj := scn.Buffer.GetPickedObject(X, Y);
if (lObj is TModifierCube) then
begin
FSelectedModifier := TModifierCube(lObj);
FSelectedModifier.Material.FrontProperties.Diffuse.Color := CModColorSelect;
FSelectedModifier.NotifyChange(FSelectedModifier);
ShowModifierStatus(TModifierCube(lObj));
FMoveZ := rbZY.Checked;
FOldMouseWorldPos := MouseWorldPos(X, Y);
end;
end;
if Shift=[ssLeft] then
begin
pick:=(Scn.Buffer.GetPickedObject(x, y) as TGLCustomSceneObject);
if Assigned(Pick) then
begin
if Pick.Name = 'GizmoX' then
begin
MovingAxis := maAxisX;
end
else if Pick.Name = 'GizmoY' then
begin
MovingAxis := maAxisY;
end
else if Pick.Name = 'GizmoZ' then
begin
MovingAxis := maAxisZ;
end
else if Pick.Name = 'GizmoXY' then
begin
MovingAxis := maAxisXY;
end
else if Pick.Name = 'GizmoXZ' then
begin
MovingAxis := maAxisXZ;
end
else if Pick.Name = 'GizmoYZ' then
begin
MovingAxis := maAxisYZ;
end
else if Pick.Tag = 0 then
begin
SelectedObject := Pick;
GLDummyCube1.Visible := True;
UpdateGizmo;
end;
lastMouseWorldPos := MouseWorldPos(x, y);
end
else
begin
GLDummyCube1.Visible := False;
SelectedObject := nil;
UpdateGizmo;
end;
end;
end;
procedure TMeshShowFrm.ScnMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
{vec1,
vec2,
newPos : TVector;
CursorPick: TGLCustomSceneObject;}
lCurrentPos : TVector;
lOldV : TVector3f;
lDiff : TVector4f;
begin
{If ctrl is not in use, move around freeform}
if (ssLeft in Shift) and (not (ssCtrl in Shift)) then
begin
GLCamera1.MoveAroundTarget(FOldY - Y, FOldX - X);
FOldX := X; FOldY := Y;
Exit;
end;
{Move modifier and change relevant vertex data}
if (ssLeft in Shift) then
begin
FMoveZ := rbZY.Checked;
lCurrentPos := MouseWorldPos(X, Y);
if Assigned(FSelectedModifier) and (VectorNorm(FOldMouseWorldPos) <> 0) then
begin
MakeVector(lOldV, FSelectedModifier.Position.X, FSelectedModifier.Position.Y, FSelectedModifier.Position.Z);
lDiff := VectorSubtract(lCurrentPos, FOldMouseWorldPos);
FSelectedModifier.Position.Translate(lDiff);
ChangeMeshVector(FSelectedModifier, lDiff);
end;
FOldMouseWorldPos := lCurrentPos;
end;
{ if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x; my:=y;}
if Shift=[ssRight] then
begin
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x; my:=y;
{UpdateGizmo;}
end;
{if (Shift=[ssLeft]) and (SelectedObject <> nil) then
begin
newPos:=MouseWorldPos(x, y);
if (VectorNorm(lastMouseWorldPos)<>0) then
begin
vec1 := newPos;
vec2 := lastMouseWorldPos;
case MovingAxis of
maAxisX : begin
vec1[1] := 0;
vec1[2] := 0;
vec1[3] := 0;
vec2[1] := 0;
vec2[2] := 0;
vec2[3] := 0;
end;
maAxisY : begin
vec1[0] := 0;
vec1[2] := 0;
vec1[3] := 0;
vec2[0] := 0;
vec2[2] := 0;
vec2[3] := 0;
end;
maAxisZ : begin
vec1[0] := 0;
vec1[1] := 0;
vec1[3] := 0;
vec2[0] := 0;
vec2[1] := 0;
vec2[3] := 0;
end;
end;
SelectedObject.Position.Translate(VectorSubtract(vec1, vec2));
end;
lastMouseWorldPos:=newPos;
UpdateGizmo;
end
else if Shift = [] then
begin
CursorPick := (Scn.Buffer.GetPickedObject(x, y) as TGLCustomSceneObject);
if OldCursorPick <> CursorPick then
begin
if (CursorPick <> nil) and (Pos('Gizmo', CursorPick.Name) = 1) then
begin
Scn.Cursor := crSizeAll;
if CursorPick is TGLGizmoArrow then
(CursorPick as TGLGizmoArrow).Selected := True;
if CursorPick is TGLGizmoCorner then
begin
(CursorPick as TGLGizmoCorner).Selected := True;
if CursorPick.Name = 'GizmoXY' then
begin
GizmoX.Selected := True;
GizmoY.Selected := True;
end
else if CursorPick.Name = 'GizmoXZ' then
begin
GizmoX.Selected := True;
GizmoZ.Selected := True;
end
else if CursorPick.Name = 'GizmoYZ' then
begin
GizmoY.Selected := True;
GizmoZ.Selected := True;
end;
end;
end
else
begin
Scn.Cursor := crDefault;
end;
if (OldCursorPick is TGLGizmoArrow) then
(OldCursorPick as TGLGizmoArrow).Selected := False;
if (OldCursorPick is TGLGizmoCorner) then
begin
(OldCursorPick as TGLGizmoCorner).Selected := False;
if OldCursorPick.Name = 'GizmoXY' then
begin
GizmoX.Selected := False;
GizmoY.Selected := False;
end
else if OldCursorPick.Name = 'GizmoXZ' then
begin
GizmoX.Selected := False;
GizmoZ.Selected := False;
end
else if OldCursorPick.Name = 'GizmoYZ' then
begin
GizmoY.Selected := False;
GizmoZ.Selected := False;
end;
end;
OldCursorPick := CursorPick;
end;
end;}
end;
procedure TMeshShowFrm.TrackBar1Change(Sender: TObject);
begin
GLFreeForm1.MeshObjects.Clear;
BuildGeosphere(GLFreeForm1, TrackBar1.Position);
GLFreeForm1.StructureChanged;
end;
procedure TMeshShowFrm.Open1Click(Sender: TObject);
var
F: TextFile;
S: string;
begin
if OpenDialog1.Execute then { Display Open dialog box }
begin
AssignFile(F, OpenDialog1.FileName); { File selected in dialog box }
Reset(F);
Readln(F, S); { Read the first line out of the file }
//Edit1.Text := S; { Put string in a TEdit control }
CloseFile(F);
end;
end;
procedure TMeshShowFrm.Save1Click(Sender: TObject);
var F: TextFile;
{I: integer;
FirstLine: string;}
begin
if SaveDialog1.Execute then
begin
AssignFile(F, SaveDialog1.filename);
Rewrite(F);
{ Writeln(F, 'Just created file with this text in it...'); }
CloseFile(F);
end;
end;
procedure TMeshShowFrm.ViewControlPanelClick(Sender: TObject);
begin
ViewControlPanel.Checked:=(not ViewControlPanel.Checked);
If ViewControlPanel.Checked then
begin
Scn.Align:=alNone;
ControlPanel.Visible:=True;
ControlPanel.Align:=alLeft;
Scn.Align:=alClient;
end else
begin
Scn.Align:=alNone;
ControlPanel.Visible:=False;
ControlPanel.Align:=alNone;
Scn.Align:=alClient;
end;
end;
procedure TMeshShowFrm.Contents1Click(Sender: TObject);
begin
Application.HelpCommand(HELP_CONTENTS, 0);
end;
procedure TMeshShowFrm.OnHelp1Click(Sender: TObject);
begin
Application.HelpCommand(HELP_HELPONHELP, 0);
end;
procedure TMeshShowFrm.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera1.AdjustDistanceToTarget(PowerSingle(1.1, WheelDelta / 120));
UpdateGizmo;
end;
procedure TMeshShowFrm.UpdateGizmo;
var
absDir: TVector;
begin
if SelectedObject = nil then
begin
StatusBar.Panels[1].Text := 'X:';
StatusBar.Panels[2].Text := 'Y:';
StatusBar.Panels[3].Text := 'Z:';
Exit;
end;
absDir := VectorSubtract(SelectedObject.absolutePosition, GLCamera1.AbsolutePosition);
NormalizeVector(absDir);
ScaleVector(absDir, 4);
absDir := VectorAdd(GLCamera1.AbsolutePosition, absDir);
GLDummyCube1.Position.AsVector := absDir;
StatusBar.Panels[0].Text := SelectedObject.Name;
StatusBar.Panels[1].Text := Format('X: %.2f', [SelectedObject.Position.X]);
StatusBar.Panels[2].Text := Format('Y: %.2f', [SelectedObject.Position.Y]);
StatusBar.Panels[3].Text := Format('Z: %.2f', [SelectedObject.Position.Z]);
end;
procedure TMeshShowFrm.ScnMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
pick := nil;
// SelectedObject := nil;
if Assigned(FSelectedModifier) then
begin
FSelectedModifier.Material.FrontProperties.Diffuse.Color := CModColorNormal;
FSelectedModifier := nil;
{Recalculate structure and redraw freeform}
StripAndRecalc;
{Reset vertex modifiers and their data.}
SetVertexModifiers;
end;
end;
procedure TMeshShowFrm.SetVertexModifiers;
procedure ScaleVector(var V1, V2 : TVector3F);
begin
V1.X := V1.X * V2.X;
V1.Y := V1.Y * V2.Y;
V1.Z := V1.Z * V2.Z;
end;
var
i, j : Integer;
lVector, lScale : TVector3F;
lModifier : TModifierCube;
begin
FModifierList.Clear;
GLScene1.BeginUpdate;
try
with GLFreeForm1.MeshObjects do
begin
for i := 0 to Count - 1 do
for j := 0 to Items[i].Vertices.Count - 1 do
begin
lVector := Items[i].Vertices.Items[j];
lModifier := TModifierCube.Create(nil);
lModifier.FVectorIndex := j;
lModifier.FMeshObjIndex := i;
FModifierList.Add(lModifier);
GLScene1.Objects.AddChild(lModifier);
lScale := GLFreeForm1.Scale.AsAffineVector;
ScaleVector(lVector, lScale);
lModifier.Position.Translate(lVector);
end;
end;
finally
GLScene1.EndUpdate;
end;
end;
procedure TMeshShowFrm.ShowModifierStatus(const aObj: TModifierCube);
begin
if aObj = nil then
StatusBar.Panels[0].Text := ''
else
StatusBar.Panels[0].Text := Format('Modifier vector index [%d]', [aObj.FVectorIndex]);
end;
procedure TMeshShowFrm.ChangeMeshVector(const aObj : TModifierCube; const aPos : TVector4f);
var
lVIndex,
lMIndex : Integer;
v : TVector3f;
begin
if aObj = nil then
Exit;
lVIndex := aObj.FVectorIndex;
lMIndex := aObj.FMeshObjIndex;
{Get new vertex position, keep freeform scale in mind and redraw freeform.}
MakeVector(v, aPos.X/CModifierDim, aPos.Y/CModifierDim, aPos.Z/CModifierDim);
GLFreeForm1.MeshObjects.Items[lMIndex].Vertices.TranslateItem(lVIndex, v);
GLFreeForm1.StructureChanged;
end;
procedure TMeshShowFrm.StripAndRecalc;
var
lTrigList,
lNormals : TAffineVectorList;
lIndices : TIntegerList;
lObj : TMeshObject;
lStrips : TPersistentObjectList;
lFaceGroup : TFGVertexIndexList;
i : Integer;
begin
// Extract raw triangle data to work with.
lTrigList := GLFreeForm1.MeshObjects.ExtractTriangles;
// Builds a vector-count optimized indices list.
lIndices := BuildVectorCountOptimizedIndices(lTrigList);
// Alter reference/indice pair and removes unused reference values.
RemapAndCleanupReferences(lTrigList, lIndices);
// Calculate normals.
lNormals := BuildNormals(lTrigList, lIndices);
// Strip where posible.
lStrips := StripifyMesh(lIndices, lTrigList.Count, True);
// Clear current mesh object data.
GLFreeForm1.MeshObjects.Clear;
// Setup new mesh object.
lObj := TMeshObject.CreateOwned(GLFreeForm1.MeshObjects);
lObj.Vertices := lTrigList;
lObj.Mode := momFaceGroups;
lObj.Normals := lNormals;
for i:=0 to lStrips.Count-1 do
begin
lFaceGroup := TFGVertexIndexList.CreateOwned(lObj.FaceGroups);
lFaceGroup.VertexIndices := (lStrips[i] as TIntegerList);
if i > 0 then
lFaceGroup.Mode := fgmmTriangleStrip
else
lFaceGroup.Mode := fgmmTriangles;
lFaceGroup.MaterialName:=IntToStr(i and 15);
end;
// Redraw freeform
GLFreeForm1.StructureChanged;
lTrigList.Free;
lNormals.Free;
lIndices.Free;
end;
procedure TMeshShowFrm.chbViewPointsClick(Sender: TObject);
var
i : Integer;
begin
GLScene1.BeginUpdate;
try
for i := 0 to FModifierList.Count - 1 do
TModifierCube(FModifierList.Items[i]).Visible := chbViewPoints.Checked;
finally
GLScene1.EndUpdate;
end;
end;
procedure TMeshShowFrm.chbShowAxisClick(Sender: TObject);
begin
dcModifiers.ShowAxes := TCheckBox(Sender).Checked;
end;
procedure TMeshShowFrm.tbPosChange(Sender: TObject);
begin
GLCamera1.Position.Z := tbPos.Position;
end;
procedure TMeshShowFrm.ScnBeforeRender(Sender: TObject);
begin
glEnable(GL_NORMALIZE);
end;
procedure TMeshShowFrm.btnVertexClick(Sender: TObject);
var
i, j : Integer;
lList : TStringList;
lVector : TVector3f;
begin
lList := TStringList.Create;
try
with GLFreeForm1.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
for j := 0 to Items[i].Vertices.Count - 1 do
begin
lVector := Items[i].Vertices.Items[j];
lList.Add(Format('%f %f %f', [lVector.X, lVector.Y, lVector.Z]));
end;
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TMeshShowFrm.btnNormalsClick(Sender: TObject);
var
i, j : Integer;
lList : TStringList;
lVector : TVector3f;
begin
lList := TStringList.Create;
try
with GLFreeForm1.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
for j := 0 to Items[i].Normals.Count - 1 do
begin
lVector := Items[i].Normals.Items[j];
lList.Add(Format('%f %f %f', [lVector.X, lVector.Y, lVector.Z]));
end;
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TMeshShowFrm.btnTextcoordsClick(Sender: TObject);
var
i, j : Integer;
lList : TStringList;
lVector : TVector3f;
begin
lList := TStringList.Create;
try
with GLFreeForm1.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
for j := 0 to Items[i].TexCoords.Count - 1 do
begin
lVector := Items[i].TexCoords.Items[j];
lList.Add(Format('%f %f %f', [lVector.X, lVector.Y, lVector.Z]));
end;
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TMeshShowFrm.btnGroupsClick(Sender: TObject);
var
i : Integer;
lList : TStringList;
begin
lList := TStringList.Create;
try
with GLFreeForm1.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
lList.Add(IntToStr(Items[i].TriangleCount));
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFCookieManager;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefCookieManagerRef = class(TCefBaseRefCountedRef, ICefCookieManager)
protected
procedure SetSupportedSchemes(schemes: TStrings; const callback: ICefCompletionCallback);
procedure SetSupportedSchemesProc(schemes: TStrings; const callback: TCefCompletionCallbackProc);
function VisitAllCookies(const visitor: ICefCookieVisitor): Boolean;
function VisitAllCookiesProc(const visitor: TCefCookieVisitorProc): Boolean;
function VisitUrlCookies(const url: ustring; includeHttpOnly: Boolean; const visitor: ICefCookieVisitor): Boolean;
function VisitUrlCookiesProc(const url: ustring; includeHttpOnly: Boolean; const visitor: TCefCookieVisitorProc): Boolean;
function SetCookie(const url: ustring; const name, value, domain, path: ustring; secure, httponly, hasExpires: Boolean; const creation, lastAccess, expires: TDateTime; const callback: ICefSetCookieCallback): Boolean;
function SetCookieProc(const url: ustring; const name, value, domain, path: ustring; secure, httponly, hasExpires: Boolean; const creation, lastAccess, expires: TDateTime; const callback: TCefSetCookieCallbackProc): Boolean;
function DeleteCookies(const url, cookieName: ustring; const callback: ICefDeleteCookiesCallback): Boolean;
function DeleteCookiesProc(const url, cookieName: ustring; const callback: TCefDeleteCookiesCallbackProc): Boolean;
function SetStoragePath(const path: ustring; persistSessionCookies: Boolean; const callback: ICefCompletionCallback): Boolean;
function SetStoragePathProc(const path: ustring; persistSessionCookies: Boolean; const callback: TCefCompletionCallbackProc): Boolean;
function FlushStore(const handler: ICefCompletionCallback): Boolean;
function FlushStoreProc(const proc: TCefCompletionCallbackProc): Boolean;
public
class function UnWrap(data: Pointer): ICefCookieManager;
class function Global(const callback: ICefCompletionCallback): ICefCookieManager;
class function GlobalProc(const callback: TCefCompletionCallbackProc): ICefCookieManager;
class function New(const path: ustring; persistSessionCookies: Boolean; const callback: ICefCompletionCallback): ICefCookieManager;
class function NewProc(const path: ustring; persistSessionCookies: Boolean; const callback: TCefCompletionCallbackProc): ICefCookieManager;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFCompletionCallback, uCEFDeleteCookiesCallback,
uCEFSetCookieCallback, uCEFCookieVisitor;
class function TCefCookieManagerRef.New(const path: ustring; persistSessionCookies: Boolean;
const callback: ICefCompletionCallback): ICefCookieManager;
var
pth: TCefString;
begin
pth := CefString(path);
Result := UnWrap(cef_cookie_manager_create_manager(@pth, Ord(persistSessionCookies), CefGetData(callback)));
end;
class function TCefCookieManagerRef.NewProc(const path: ustring;
persistSessionCookies: Boolean;
const callback: TCefCompletionCallbackProc): ICefCookieManager;
begin
Result := New(path, persistSessionCookies, TCefFastCompletionCallback.Create(callback));
end;
function TCefCookieManagerRef.DeleteCookies(const url,
cookieName: ustring; const callback: ICefDeleteCookiesCallback): Boolean;
var
u, n: TCefString;
begin
u := CefString(url);
n := CefString(cookieName);
Result := PCefCookieManager(FData).delete_cookies(
PCefCookieManager(FData), @u, @n, CefGetData(callback)) <> 0;
end;
function TCefCookieManagerRef.DeleteCookiesProc(const url, cookieName: ustring;
const callback: TCefDeleteCookiesCallbackProc): Boolean;
begin
Result := DeleteCookies(url, cookieName, TCefFastDeleteCookiesCallback.Create(callback));
end;
function TCefCookieManagerRef.FlushStore(
const handler: ICefCompletionCallback): Boolean;
begin
Result := PCefCookieManager(FData).flush_store(PCefCookieManager(FData),
CefGetData(handler)) <> 0;
end;
function TCefCookieManagerRef.FlushStoreProc(
const proc: TCefCompletionCallbackProc): Boolean;
begin
Result := FlushStore(TCefFastCompletionCallback.Create(proc))
end;
class function TCefCookieManagerRef.Global(const callback: ICefCompletionCallback): ICefCookieManager;
begin
Result := UnWrap(cef_cookie_manager_get_global_manager(CefGetData(callback)));
end;
class function TCefCookieManagerRef.GlobalProc(
const callback: TCefCompletionCallbackProc): ICefCookieManager;
begin
Result := Global(TCefFastCompletionCallback.Create(callback));
end;
function TCefCookieManagerRef.SetCookie(const url, name, value, domain,
path: ustring; secure, httponly, hasExpires: Boolean; const creation,
lastAccess, expires: TDateTime; const callback: ICefSetCookieCallback): Boolean;
var
str: TCefString;
cook: TCefCookie;
begin
str := CefString(url);
cook.name := CefString(name);
cook.value := CefString(value);
cook.domain := CefString(domain);
cook.path := CefString(path);
cook.secure := Ord(secure);
cook.httponly := Ord(httponly);
cook.creation := DateTimeToCefTime(creation);
cook.last_access := DateTimeToCefTime(lastAccess);
cook.has_expires := Ord(hasExpires);
if hasExpires then
cook.expires := DateTimeToCefTime(expires) else
FillChar(cook.expires, SizeOf(TCefTime), 0);
Result := PCefCookieManager(FData).set_cookie(
PCefCookieManager(FData), @str, @cook, CefGetData(callback)) <> 0;
end;
function TCefCookieManagerRef.SetCookieProc(const url, name, value, domain,
path: ustring; secure, httponly, hasExpires: Boolean; const creation,
lastAccess, expires: TDateTime;
const callback: TCefSetCookieCallbackProc): Boolean;
begin
Result := SetCookie(url, name, value, domain, path, secure,
httponly, hasExpires, creation, lastAccess, expires,
TCefFastSetCookieCallback.Create(callback));
end;
function TCefCookieManagerRef.SetStoragePath(const path: ustring;
persistSessionCookies: Boolean; const callback: ICefCompletionCallback): Boolean;
var
p: TCefString;
begin
p := CefString(path);
Result := PCefCookieManager(FData)^.set_storage_path(
PCefCookieManager(FData), @p, Ord(persistSessionCookies), CefGetData(callback)) <> 0;
end;
function TCefCookieManagerRef.SetStoragePathProc(const path: ustring;
persistSessionCookies: Boolean;
const callback: TCefCompletionCallbackProc): Boolean;
begin
Result := SetStoragePath(path, persistSessionCookies, TCefFastCompletionCallback.Create(callback));
end;
procedure TCefCookieManagerRef.SetSupportedSchemes(schemes: TStrings; const callback: ICefCompletionCallback);
var
list: TCefStringList;
i: Integer;
item: TCefString;
begin
list := cef_string_list_alloc();
try
if (schemes <> nil) then
for i := 0 to schemes.Count - 1 do
begin
item := CefString(schemes[i]);
cef_string_list_append(list, @item);
end;
PCefCookieManager(FData).set_supported_schemes(
PCefCookieManager(FData), list, CefGetData(callback));
finally
cef_string_list_free(list);
end;
end;
procedure TCefCookieManagerRef.SetSupportedSchemesProc(schemes: TStrings;
const callback: TCefCompletionCallbackProc);
begin
SetSupportedSchemes(schemes, TCefFastCompletionCallback.Create(callback));
end;
class function TCefCookieManagerRef.UnWrap(data: Pointer): ICefCookieManager;
begin
if data <> nil then
Result := Create(data) as ICefCookieManager else
Result := nil;
end;
function TCefCookieManagerRef.VisitAllCookies(
const visitor: ICefCookieVisitor): Boolean;
begin
Result := PCefCookieManager(FData).visit_all_cookies(
PCefCookieManager(FData), CefGetData(visitor)) <> 0;
end;
function TCefCookieManagerRef.VisitAllCookiesProc(
const visitor: TCefCookieVisitorProc): Boolean;
begin
Result := VisitAllCookies(
TCefFastCookieVisitor.Create(visitor) as ICefCookieVisitor);
end;
function TCefCookieManagerRef.VisitUrlCookies(const url: ustring;
includeHttpOnly: Boolean; const visitor: ICefCookieVisitor): Boolean;
var
str: TCefString;
begin
str := CefString(url);
Result := PCefCookieManager(FData).visit_url_cookies(PCefCookieManager(FData), @str, Ord(includeHttpOnly), CefGetData(visitor)) <> 0;
end;
function TCefCookieManagerRef.VisitUrlCookiesProc(const url: ustring;
includeHttpOnly: Boolean; const visitor: TCefCookieVisitorProc): Boolean;
begin
Result := VisitUrlCookies(url, includeHttpOnly,
TCefFastCookieVisitor.Create(visitor) as ICefCookieVisitor);
end;
end.
|
Type
NodeKind = (String_, Number, Boolean_, Array_, Object_, Null);
Node = Class
Public
Kind : NodeKind;
End;
NodeList = Array[0..15] Of Node;
ObjectEntry = Class
Public
Key : String;
Value : Node;
Constructor Init(k : String; v : Node);
End;
ObjectEntryList = Array[0..15] Of ObjectEntry;
StringNode = Class(Node)
Public
Value : String;
Constructor Init(s: String);
End;
NumberNode = Class(Node)
Public
Value : Real;
Constructor Init(v : Real);
End;
ArrayNode = Class(Node)
Public
Value : NodeList;
Constructor Init(n : NodeList);
End;
BooleanNode = Class(Node)
Public
Value: Boolean;
Constructor Init(v : Boolean);
End;
NullNode = Class(Node)
Public
Constructor Init();
End;
ObjectNode = Class(Node)
Public
Value : ObjectEntryList;
Constructor Init(e : ObjectEntryList);
End;
Constructor ObjectEntry.Init(k : String; v : Node);
Begin
Key := k;
Value := v;
End;
Constructor StringNode.Init(s : String);
Begin
Kind := String_;
Value := s;
End;
Constructor NumberNode.Init(v : Real);
Begin
Kind := Number;
Value := v;
End;
Constructor ArrayNode.Init(n : NodeList);
Begin
Kind := Array_;
Value := n;
End;
Constructor BooleanNode.Init(v : Boolean);
Begin
Kind := Boolean_;
Value := v;
End;
Constructor NullNode.Init();
Begin
Kind := Null;
End;
Constructor ObjectNode.Init(e : ObjectEntryList);
Begin
Kind := Object_;
Value := e;
End;
|
unit Main;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TfrmMain = class(TForm)
pbPermutate: TButton;
reReport: TRichEdit;
edPool: TEdit;
lblPermutations: TLabel;
Label1: TLabel;
pbSaveAs: TButton;
SaveDialog1: TSDUSaveDialog;
procedure pbPermutateClick(Sender: TObject);
procedure edPoolChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure pbSaveAsClick(Sender: TObject);
private
{ Private declarations }
protected
function PermutationCount(pool: string): string;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
SDUGeneral;
procedure TfrmMain.pbPermutateClick(Sender: TObject);
const
// The number of characters in the pool before the user gets warned that it
// could take awhile...
WARN_POOL_SIZE = 8;
var
stlPermutations: TStringList;
csrBegin: TCursor;
begin
if (length(edPool.Text) >= WARN_POOL_SIZE) then
begin
if (MessageDlg(
'There are '+PermutationCount(edPool.text)+' permutations of "'+edPool.text+'".'+SDUCRLF+
SDUCRLF+
'It could take a while to generate them all.'+SDUCRLF+
SDUCRLF+
'Do you wish to proceed?', mtWarning, [mbYes, mbNo], 0) = mrNo) then
begin
exit;
end;
end;
reReport.lines.clear();
csrBegin := Screen.Cursor;
stlPermutations:= TStringList.Create();
try
Screen.Cursor := crHourGlass;
SDUPermutate(edPool.Text, stlPermutations);
reReport.lines.Add('Permutated string: '+edPool.Text);
reReport.lines.Add('Permutations: '+inttostr(stlPermutations.count));
reReport.lines.AddStrings(stlPermutations);
pbSaveAs.Enabled := TRUE;
finally
stlPermutations.Free();
Screen.Cursor := csrBegin;
end;
end;
function TfrmMain.PermutationCount(pool: string): string;
var
li: LARGE_INTEGER;
strPermCount: string;
begin
try
li := SDUFactorial(length(pool));
strPermCount := inttostr(li.QuadPart);
except
// Just in case we overflowed...
// Note: Project must be compiled with Project Options (compiler tab)
// overflow checking turned *on* for this exception to be raised
on EIntOverflow do
begin
strPermCount := 'a large number(!) of'
end;
end;
Result := strPermCount;
end;
procedure TfrmMain.edPoolChange(Sender: TObject);
var
strPermCount: string;
begin
strPermCount := PermutationCount(edPool.text);
lblPermutations.caption := inttostr(length(edPool.text)) +' characters have '+ strPermCount +' permutations';
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
// Update permutations count display...
edPoolChange(nil);
reReport.Clear();
self.Caption := Application.Title;
reReport.PlainText := TRUE;
pbSaveAs.Enabled := FALSE;
end;
procedure TfrmMain.pbSaveAsClick(Sender: TObject);
begin
if (SaveDialog1.Execute()) then
begin
reReport.Lines.SaveToFile(SaveDialog1.Filename);
end;
end;
END.
|
unit UPostfix;
interface
function toPostfix(str: String):String;
function calcRank(str: String):Integer;
implementation
type
TList = ^TElem;
TElem = record
sym: Char;
next: TList;
end;
var
stack: TList;
procedure createList(var stack: TList);
begin
new(stack);
end;
procedure push(stack: TList; sym: Char);
var
temp: TList;
begin
new(temp);
temp^.sym := sym;
temp^.next := stack^.next;
stack^.next := temp;
end;
function pop(stack: TList):Char;
var
temp: TList;
begin
temp := stack^.next;
stack^.next := temp^.next;
result := temp^.sym;
end;
procedure destroyList(var stack: TList);
begin
while (stack <> nil) and (stack^.next <> nil) do
pop(stack);
dispose(stack);
stack := nil;
end;
function getPriority(ch: Char):Integer;
begin
case ch of
'(':
result := 0;
'+', '-':
result := 2;
'*', '/':
result := 4;
'^':
result := 5;
else
result := 8;
end;
end;
function getPriorityBase(ch: Char):Integer;
begin
case ch of
')':
result := 0;
'(':
result := 9;
'+', '-':
result := 1;
'*', '/':
result := 3;
'^':
result := 6;
else
result := 7;
end;
end;
function getBiggerPart(stack: TList; ch: Char):String;
var
pr: Integer;
temp: Char;
begin
result := '';
pr := getPriorityBase(ch);
if pr = 0 then
begin
while (stack^.next <> nil) and (stack^.next^.sym <> '(') do
result := result + pop(stack);
pop(stack);
end
else
begin
while (stack^.next <> nil) and (getPriority(stack^.next^.sym) >= pr) do
begin
temp := pop(stack);
if temp <> '(' then
result := result + temp;
end;
end;
end;
function toPostfix(str: String):String;
var
i: Integer;
begin
i := 1;
result := '';
while i <= length(str)do
begin
case str[i] of
'+', '-', '/', '*', '^', 'a'..'z', '0'..'9':
begin
result := result + getBiggerPart(stack, str[i]);
push(stack, str[i]);
end;
'(':
begin
push(stack, '(');
end;
')':
begin
result := result + getBiggerPart(stack, ')');
end;
end;
inc(i);
end;
while stack^.next <> nil do
result := result + pop(stack);
end;
function calcRank(str: String):Integer;
const
oper: set of char = ['a'..'z', 'A'..'Z', '0'..'9', 'À'..'ß', 'à'..'ÿ'];
var
i: Integer;
error: Boolean;
begin
i := 1;
error := false;
result := 0;
while i <= length(str) do
begin
if i < length(str) then
if (str[i] in oper) and (str[i + 1] in oper) then
error := true;
if str[i] = ')' then
dec(result);
if str[i] = '(' then
inc(result);
if result < 0 then
error := true;
inc(i);
end;
if result <> 0 then
error := true;
result := 0;
if not error then
begin
for i := 1 to length(str) do
begin
case str[i] of
'+', '-', '*', '/', '^':
dec(result);
'(', ')':
;
else
inc(result);
end;
end;
end;
end;
initialization
createList(stack);
finalization
destroyList(stack);
end.
|
unit UDLogOnServer;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, UCrpe32;
type
TCrpeLogOnServerDlg = class(TForm)
pnlLogOnServer1: TPanel;
lblNumber: TLabel;
lbNumbers: TListBox;
btnOk: TButton;
btnLogOn: TButton;
btnLogOff: TButton;
btnAdd: TButton;
btnDelete: TButton;
btnRetrieve: TButton;
btnClear: TButton;
lblCount: TLabel;
editCount: TEdit;
lblServerName: TLabel;
lblDatabaseName: TLabel;
lblUserID: TLabel;
lblPassword: TLabel;
lblDLLName: TLabel;
editServerName: TEdit;
editDatabaseName: TEdit;
editUserID: TEdit;
editPassword: TEdit;
editDLLName: TEdit;
lblLogNumber: TLabel;
editLogNumber: TEdit;
cbIsLoggedOn: TCheckBox;
procedure btnLogOnClick(Sender: TObject);
procedure btnLogOffClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure btnRetrieveClick(Sender: TObject);
procedure lbNumbersClick(Sender: TObject);
procedure editServerNameChange(Sender: TObject);
procedure editUserIDChange(Sender: TObject);
procedure editPasswordChange(Sender: TObject);
procedure editDatabaseNameChange(Sender: TObject);
procedure editDLLNameChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnOkClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure UpdateLogOnServer;
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
SIndex : smallint;
end;
var
CrpeLogOnServerDlg: TCrpeLogOnServerDlg;
bLogOnServer : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl, UDLogOnServerAdd;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.FormCreate(Sender: TObject);
begin
bLogOnServer := True;
LoadFormPos(Self);
btnOk.Tag := 1;
btnAdd.Tag := 1;
btnRetrieve.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.FormShow(Sender: TObject);
begin
UpdateLogOnServer;
end;
{------------------------------------------------------------------------------}
{ UpdateLogOnServer }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.UpdateLogOnServer;
var
OnOff : boolean;
i : integer;
begin
{Enable/Disable controls}
btnRetrieve.Enabled := not IsStrEmpty(Cr.ReportName);
OnOff := (Cr.LogOnServer.Count > 0);
InitializeControls(OnOff);
{Get LogOnServer Index}
if Cr.LogOnServer.ItemIndex > -1 then
SIndex := Cr.LogOnServer.ItemIndex
else
SIndex := 0;
if OnOff then
begin
lbNumbers.Clear;
for i := 0 to Cr.LogOnServer.Count - 1 do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Cr.LogOnServer.Count);
lbNumbers.ItemIndex := SIndex;
lbNumbersClick(Self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
if not OnOff then
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.lbNumbersClick(Sender: TObject);
begin
SIndex := lbNumbers.ItemIndex;
Cr.LogOnServer[SIndex];
editServerName.Text := Cr.LogOnServer.Item.ServerName;
editDatabaseName.Text := Cr.LogOnServer.Item.DatabaseName;
editUserID.Text := Cr.LogOnServer.Item.UserID;
editPassword.Text := Cr.LogOnServer.Item.Password;
editDLLName.Text := Cr.LogOnServer.Item.DLLName;
editLogNumber.Text := IntToStr(Cr.LogOnServer.Item.LogNumber);
cbIsLoggedOn.Checked := Cr.LogOnServer.Item.IsLoggedOn;
btnLogOff.Enabled := (Cr.LogOnServer.Item.LogNumber > 0);
btnLogOn.Enabled := (Cr.LogOnServer.Item.LogNumber < 1);
end;
{------------------------------------------------------------------------------}
{ btnLogOnClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.btnLogOnClick(Sender: TObject);
begin
{Check to see if already Logged On}
if Cr.LogOnServer.Item.LogNumber > 0 then
begin
MessageDlg('Already Logged On! Use "Add" to add another ServerName.',
mtWarning, [mbOk], 0);
Exit;
end;
{Try Logging On...}
if Cr.LogOnServer.Item.LogOn then
UpdateLogOnServer
else
MessageDlg('LogOn Failed.' + Chr(10) + Cr.LastErrorString, mtError, [mbOk], 0);
end;
{------------------------------------------------------------------------------}
{ btnLogOffClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.btnLogOffClick(Sender: TObject);
begin
{Try LogOff}
if not Cr.LogOnServer.Item.LogOff then
MessageDlg('LogOff Failed.' + Chr(10) + Cr.LastErrorString, mtError, [mbOk], 0)
else
UpdateLogOnServer;
end;
{------------------------------------------------------------------------------}
{ btnAddClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.btnAddClick(Sender: TObject);
begin
CrpeLogOnServerAddDlg := TCrpeLogOnServerAddDlg.Create(Application);
CrpeLogOnServerAddDlg.ShowModal;
if CrpeLogOnServerAddDlg.ModalResult = mrOk then
begin
{Add LogOnServer item to VCL}
Cr.LogOnServer.Add(CrpeLogOnServerAddDlg.editServerName.Text);
Cr.LogOnServer.Item.DatabaseName := CrpeLogOnServerAddDlg.editDatabaseName.Text;
Cr.LogOnServer.Item.UserID := CrpeLogOnServerAddDlg.editUserID.Text;
Cr.LogOnServer.Item.Password := CrpeLogOnServerAddDlg.editPassword.Text;
Cr.LogOnServer.Item.DLLName := CrpeLogOnServerAddDlg.editDLLName.Text;
{Set ItemIndex to new item}
SIndex := (Cr.LogOnServer.Count-1);
UpdateLogOnServer;
end;
CrpeLogOnServerAddDlg.Release;
end;
{------------------------------------------------------------------------------}
{ btnDeleteClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.btnDeleteClick(Sender: TObject);
begin
Cr.LogOnServer.Delete(SIndex);
UpdateLogOnServer;
end;
{------------------------------------------------------------------------------}
{ btnClearClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.btnClearClick(Sender: TObject);
begin
Cr.LogOnServer.Clear;
UpdateLogOnServer;
end;
{------------------------------------------------------------------------------}
{ btnRetrieveLogOnClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.btnRetrieveClick(Sender: TObject);
begin
Cr.LogOnServer.Retrieve;
UpdateLogOnServer;
end;
{------------------------------------------------------------------------------}
{ editServerName1Change procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.editServerNameChange(Sender: TObject);
begin
Cr.LogOnServer.Item.ServerName := editServerName.Text;
end;
{------------------------------------------------------------------------------}
{ editDatabaseName1Change procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.editDatabaseNameChange(Sender: TObject);
begin
Cr.LogOnServer.Item.DatabaseName := editDatabaseName.Text;
end;
{------------------------------------------------------------------------------}
{ editUserID1Change procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.editUserIDChange(Sender: TObject);
begin
Cr.LogOnServer.Item.UserID := editUserID.Text;
end;
{------------------------------------------------------------------------------}
{ editPassword1Change procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.editPasswordChange(Sender: TObject);
begin
Cr.LogOnServer.Item.Password := editPassword.Text;
end;
{------------------------------------------------------------------------------}
{ editDLLName1Change procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.editDLLNameChange(Sender: TObject);
begin
Cr.LogOnServer.Item.DLLName := editDLLName.Text;
end;
{------------------------------------------------------------------------------}
{ btnOkClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpeLogOnServerDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bLogOnServer := False;
Release;
end;
end.
|
(*
SMPEG library (MPEG-1) components
This file is a part of Audio Components Suite.
Copyright (C) 2002-2005 Andrei Borovsky. All rights reserved.
See the license file for more details.
This is the ACS for Linux and Windows version of the unit.
*)
{
Status: tested
}
unit acs_mp3;
interface
uses
Classes, SysUtils, ACS_file, ACS_classes,
{$ifndef WIN64}smpeg,{$endif}
mp3;
type
{$ifndef WIN64}
TMPEGIn = class(TAcsCustomFileIn)
private
_M: Pointer;
info: SMPEG_info;
protected
procedure OpenFile(); override;
procedure CloseFile(); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
function GetData(ABuffer: Pointer; ABufferSize: Integer): Integer; override;
end;
{$endif}
{ TMP3In }
TMP3In = class(TAcsCustomFileIn)
private
h: TPdmp3Handle;
protected
procedure OpenFile(); override;
procedure CloseFile(); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
function GetData(ABuffer: Pointer; ABufferSize: Integer): Integer; override;
end;
implementation
uses Math;
{ TMP3In }
procedure TMP3In.OpenFile();
var
res, done, BufSize: Integer;
rate, channels, enc: Integer;
outbuf: array[0..INBUF_SIZE-1] of Byte;
begin
inherited OpenFile();
if FOpened then
begin
pdmp3_open_feed(h);
// read first chunk
BufSize := Length(FBuffer);
FStream.Read(FBuffer[0], BufSize);
// rewind back
FStream.Position := 0;
res := pdmp3_decode(h, FBuffer[0], BufSize, outbuf, SizeOf(outbuf), done);
if (res = PDMP3_OK) or (res = PDMP3_NEW_FORMAT) then
begin
//if (res = PDMP3_NEW_FORMAT) then
begin
pdmp3_getformat(h, rate, channels, enc);
FSR := rate;
FChan := channels;
FBPS := 16;
FSampleSize := FChan * (FBPS div 8);
FTotalSamples := (FStream.Size div GetFrameSize(h)) * GetSamplesPerFrame(h);
FSize := FStream.Size;
FValid := True;
FOpened := True;
end;
end;
// re-open
pdmp3_open_feed(h);
end;
end;
procedure TMP3In.CloseFile();
begin
inherited CloseFile();
end;
constructor TMP3In.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBufferSize := INBUF_SIZE div 2;
BufferSize := FBufferSize;
end;
destructor TMP3In.Destroy();
begin
inherited Destroy();
end;
function TMP3In.GetData(ABuffer: Pointer; ABufferSize: Integer): Integer;
var
res, done, BufSize: Integer;
outbuf: array[0..INBUF_SIZE-1] of Byte;
begin
//Result:=inherited GetData(ABuffer, ABufferSize);
BufSize := Min(ABufferSize, BufferSize);
//done := FStream.Read(FBuffer[0], BufSize);
//BufSize := Min(BufSize, done);
Result := 0;
if BufSize = 0 then
begin
Result := 0;
Exit;
end;
res := PDMP3_OK;
while (Result < ABufferSize) and ((res = PDMP3_OK) or (res = PDMP3_NEW_FORMAT)) do
begin
//res := pdmp3_decode(h, FBuffer[0], BufSize, outbuf, SizeOf(outbuf), done);
done := 0;
BufSize := Min(SizeOf(outbuf), ABufferSize - Result);
res := pdmp3_read(h, outbuf, BufSize, done);
if (res = PDMP3_OK) or (res = PDMP3_NEW_FORMAT) then
begin
Result := Result + done;
Assert(done <= SizeOf(outbuf));
Move(outbuf, ABuffer^, done);
Inc(ABuffer, done);
end
else
if res = PDMP3_NEED_MORE then
begin
BufSize := Min(INBUF_SIZE, BufferSize);
done := FStream.Read(FBuffer[0], BufSize);
if done = 0 then
Break;
res := pdmp3_feed(h, FBuffer[0], done);
end;
end;
end;
{$ifndef WIN64}
constructor TMPEGIn.Create();
begin
inherited Create(AOwner);
FBufferSize:=$8000;
FStreamDisabled:=True;
end;
destructor TMPEGIn.Destroy();
begin
inherited Destroy;
end;
procedure TMPEGIn.OpenFile();
var
spec: SDL_AudioSpec;
begin
inherited OpenFile();
if FOpened then
begin
(* the next call is needed just to make sure
the SDL library is loaded *)
{
_M:=SMPEG_new(PChar(FFileName), info, 1);
SMPEG_delete(_M);
FValid:=True;
}
_M:=SMPEG_new(PChar(FFileName), info, 0);
if not Assigned(_M) then Exit;
if info.has_audio <> 1 then
begin
SMPEG_delete(_M);
_M:=nil;
FValid:=False;
Exit;
end;
FTotalTime:=info.total_time / 2;
SMPEG_wantedSpec(_M, spec);
FSR:=spec.freq;
FBPS:=16;
if (spec.format = AUDIO_S8) or (spec.format = AUDIO_U8) then
FBPS:=8;
if (spec.format = AUDIO_S32) then
FBPS:=32;
if (spec.format = AUDIO_F32) then
FBPS:=32;
FChan:=spec.channels;
FSampleSize:=FChan * (FBPS div 8);
FSize:=Round(FTotalTime * FSR) * FSampleSize;
FBufferSize:=spec.samples * FSampleSize;
FValid:=True;
FOpened:=True;
SMPEG_play(_M);
end;
end;
procedure TMPEGIn.CloseFile();
begin
if FOpened then
begin
if SMPEG_status(_M) = SMPEG_PLAYING then SMPEG_stop(_M);
SMPEG_delete(_M);
inherited CloseFile();
end;
end;
function TMPEGIn.GetData(ABuffer: Pointer; ABufferSize: Integer): Integer;
var
Len, offs, AlignedSize: Integer;
//tmp: Single;
begin
if (not Active) or (not FOpened) then
raise EACSException.Create('The Stream is not opened');
if FAudioBuffer.UnreadSize <= 0 then
begin
//if FAudioBuffer.Size <> FBufferSize then FAudioBuffer.Size:=FBufferSize;
FAudioBuffer.Reset();
{
if FOffset <> 0 then
begin
offs:=Round((FOffset / 100) * FSize);
FPosition:=FPosition + offs;
if FPosition < 0 then
FPosition:=0
else
if FPosition > FSize then FPosition:=FSize;
if FOffset < 0 then
begin
SMPEG_rewind(_M);
SMPEG_play(_M);
tmp:=(FPosition / FSize) * FTotalTime;
SMPEG_skip(_M, tmp);
end;
tmp:=(FOffset / 100) * FTotalTime;
SMPEG_skip(_M, tmp);
FOffset:=0;
end;
}
// it's very special voodoo!! looks like, SMPEG use XOR to set buffer content
FillChar(FAudioBuffer.Memory^, FAudioBuffer.Size, 0);
// align buffer size
AlignedSize:=FAudioBuffer.Size - (FAudioBuffer.Size mod FSampleSize);
// decode audio to PCM
Len:=SMPEG_playAudio(_M, FAudioBuffer.Memory, AlignedSize);
FAudioBuffer.WritePosition:=FAudioBuffer.WritePosition + Len;
if Len = 0 then
begin
{
if FLoop then
begin
Done();
Init();
SMPEG_rewind(_M);
SMPEG_play(_M);
FPosition:=0;
//Len:=SMPEG_playAudio(_M, @FBuffer[BufEnd+1], ABufferSize - BufEnd);
Len:=SMPEG_playAudio(_M, @Self.FBuffer[0], Self.BufferSize);
end
else
}
begin
Result:=0;
Exit;
end;
end;
end;
Result:=FAudioBuffer.UnreadSize;
if Result > ABufferSize then Result:=ABufferSize;
FAudioBuffer.Read(ABuffer^, Result);
Inc(FPosition, Result);
end;
{$endif}
initialization
FileFormats.Add('mp3', 'Mpeg Audio Layer 3', TMP3In);
{$ifndef WIN64}
if LoadMPEGLibrary() then
begin
//FileFormats.Add('mp3', 'Mpeg Audio Layer 3', TMPEGIn);
FileFormats.Add('mp2', 'Mpeg Audio Layer 2', TMPEGIn);
FileFormats.Add('mpeg', 'Mpeg Audio', TMPEGIn);
end;
{$endif}
finalization
{$ifndef WIN64}
UnLoadMPEGLibrary();
{$endif}
end.
|
unit ufrmWastageReal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, Vcl.ActnList,
cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils,
Vcl.Menus, cxButtons, cxCurrencyEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxNavigator, Data.DB, cxDBData, System.Actions,
ufraFooter4Button, cxLabel, cxGridLevel, cxClasses, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC;
type
TfrmWastageReal = class(TfrmMasterBrowse)
pnl1: TPanel;
lbl1: TLabel;
lbl2: TLabel;
lbl3: TLabel;
lbl4: TLabel;
dtTgl: TcxDateEdit;
curredtSubTotal: TcxCurrencyEdit;
mmoNote: TMemo;
lbl6: TLabel;
curredtPPN: TcxCurrencyEdit;
curredtPPNBM: TcxCurrencyEdit;
curredtTotWastage: TcxCurrencyEdit;
lbl10: TLabel;
lbl11: TLabel;
edtWastageNo: TEdit;
lblXXX: TLabel;
Label1: TLabel;
pnl4: TPanel;
lbl7: TLabel;
edtProductName: TEdit;
cxcolKODEBARANG: TcxGridDBColumn;
cxcolALIASBARANG: TcxGridDBColumn;
cxcolUOM: TcxGridDBColumn;
cxcolQTY: TcxGridDBColumn;
procedure actAddExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actPrintExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure strgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer;
var IsFloat: Boolean; var FloatFormat: String);
procedure cbpWstgRealNoKeyPress(Sender: TObject; var Key: Char);
procedure edtWastageNoKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure fraFooter5Button1btnDeleteClick(Sender: TObject);
procedure colgridCanEditCell(Sender: TObject; ARow, ACol: Integer;
var CanEdit: Boolean);
procedure colgridClickCell(Sender: TObject; ARow, ACol: Integer);
private
// FBarang: TNewBarang;
FParamList: TStringList;
// FWastage: TWastage;
procedure ClearForm();
procedure SetParamList(const Value: TStringList);
public
FNoBukti: string;
procedure JumlahAkhir;
procedure LoadDataWastage;
procedure LoadDetilWastage;
procedure LoadHeaderWastage;
procedure RefreshData; override;
property ParamList: TStringList read FParamList write SetParamList;
end;
var
frmWastageReal: TfrmWastageReal;
implementation
uses uTSCommonDlg, ufrmSearchWastageReal, uConstanta, udmReport, uSpell,
ufrmDialogPrintPreview, ufrmDialogWastageReal, uRetnoUnit;
const
_kolTotal : Integer = 10;
_kolPPNBM : Integer = 9;
_kolPPNBMPersen : Integer = 8;
_kolPPN : Integer = 7;
_kolPPNPersen : Integer = 6;
_kolUOMStock : Integer = 5;
_kolHargaAverage : Integer = 4;
_kolQTY : Integer = 3;
_kolUOMKonversi : Integer = 2;
_kolAliasBarang : Integer = 1;
_kolKodeBarang : Integer = 0;
{$R *.dfm}
procedure TfrmWastageReal.actAddExecute(Sender: TObject);
begin
inherited;
FNoBukti := '';
frmDialogWastageReal := TfrmDialogWastageReal.Create(Self);
SetFormPropertyAndShowDialog(frmDialogWastageReal);
end;
procedure TfrmWastageReal.actEditExecute(Sender: TObject);
begin
inherited;
// if Trim(FWastage.WSTRL_NO) = '' then
begin
CommonDlg.ShowError('No Bukti Belum Dipilih');
edtWastageNo.SetFocus;
Exit;
end;
// FNoBukti := FWastage.WSTRL_NO;
frmDialogWastageReal := TfrmDialogWastageReal.Create(Self);
frmDialogWastageReal.Show;
end;
procedure TfrmWastageReal.actPrintExecute(Sender: TObject);
begin
inherited;
if edtWastageNo.Text <> '' then
begin
// DoSlipWastage(Trim(edtWastageNo.Text),IntToStr(masternewunit.id),Floginfullname, masternewunit.Nama,MasterNewUnit.ID);
end
else
CommonDlg.ShowErrorEmpty('NO Transaksi');
end;
procedure TfrmWastageReal.actRefreshExecute(Sender: TObject);
begin
inherited;
// FWastage.LoadByWSTRL_NO(edtWastageNo.Text, masternewunit.id);
LoadHeaderWastage;
LoadDetilWastage;
end;
procedure TfrmWastageReal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmWastageReal.FormCreate(Sender: TObject);
begin
inherited;
lblHeader.Caption := 'WASTAGE DAMAGE / REAL';
ParamList := TStringList.Create;
// FWastage := TWastage.Create(Self);
// FBarang := TNewBarang.Create(Self);
end;
procedure TfrmWastageReal.FormDestroy(Sender: TObject);
begin
inherited;
frmWastageReal := nil;
end;
procedure TfrmWastageReal.FormShow(Sender: TObject);
begin
inherited;
ClearForm();
end;
procedure TfrmWastageReal.ClearForm();
begin
end;
procedure TfrmWastageReal.SetParamList(const Value: TStringList);
begin
FParamList := Value;
end;
procedure TfrmWastageReal.strgGridGetFloatFormat(Sender: TObject; ACol,
ARow: Integer; var IsFloat: Boolean; var FloatFormat: String);
begin
inherited;
FloatFormat := '%.2n';
if ACol in [3,4,5] then
IsFloat := True
else
IsFloat := False;
end;
procedure TfrmWastageReal.cbpWstgRealNoKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
// Key := CharUpper(Key);
end;
procedure TfrmWastageReal.edtWastageNoKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
sSQL: string;
begin
inherited;
if (Key = vk_F5 ) then
begin
sSQL := 'select wstrl_no as "NO WASTAGE", wstrl_date as "TANGGAL" '
+ ' from wastage_real '
+ ' where wstrl_unt_id = ' + IntToStr(masternewunit);
{
with cLookUp('DAFTAR WASTAGE',sSQL,200,1,True) do
begin
if Strings[0] <> '' then
begin
edtWastageNo.Text := Strings[0];
LoadDataWastage;
end;
Free;
end;
}
end;
end;
procedure TfrmWastageReal.JumlahAkhir;
begin
// curredtSubTotal.Value := SumColAdvColGrid(colgrid, _kolTotal);
// curredtPPN.Value := SumColAdvColGrid(colgrid, _kolPPN);
// curredtPPNBM.Value := SumColAdvColGrid(colgrid, _kolPPNBM);
curredtTotWastage.Value := curredtSubTotal.Value + curredtPPN.Value + curredtPPNBM.Value ;
end;
procedure TfrmWastageReal.LoadDetilWastage;
var
j: Integer;
i: Integer;
begin
{
cClearGrid(colgrid, False);
j := colgrid.FixedRows;
for i := 0 to FWastage.WastageItems.Count - 1 do
begin
colgrid.Cells[_kolKodeBarang, j] := FWastage.WastageItems[i].Barang.Kode;
colgrid.Cells[_kolAliasBarang, j] := FWastage.WastageItems[i].Barang.Alias;
colgrid.Cells[_kolUOMKonversi, j] := FWastage.WastageItems[i].SATUAN;
colgrid.Floats[_kolQTY, j] := (FWastage.WastageItems[i].QTY);
colgrid.Cells[_kolHargaAverage, j] := FloatToStr(FWastage.WastageItems[i].HARGA);
colgrid.Cells[_kolUOMStock, j] := FWastage.WastageItems[i].Barang.KodeSatuanStock.UOM;
colgrid.Cells[_kolPPNPersen, j] :=FloatToStr(FWastage.WastageItems[i].PPN_PERSEN);
colgrid.Cells[_kolPPN, j ] := FloatToStr(FWastage.WastageItems[i].PPN_NOMINAL);
colgrid.Cells[_kolPPNBMPersen, j] := FloatToStr(FWastage.WastageItems[i].PPNBM_PERSEN);
colgrid.Cells[_kolPPNBM, j] := FloatToStr(FWastage.WastageItems[i].PPNBM_NOMINAL);
colgrid.Cells[_kolTotal , j] := FloatToStr(FWastage.WastageItems[i].Total);
colgrid.AddRow;
Inc(j);
end;
HapusBarisKosong(colgrid,_kolKodeBarang);
JumlahAkhir;
}
end;
procedure TfrmWastageReal.LoadHeaderWastage;
begin
// edtWastageNo.Text := FWastage.WSTRL_NO;
// dtTgl.Date := FWastage.WSTRL_DATE;
// mmoNote.Text := FWastage.WSTRL_DESCRIPTION;
end;
procedure TfrmWastageReal.fraFooter5Button1btnDeleteClick(Sender: TObject);
begin
inherited;
{
if CommonDlg.Confirm('Anda Yakin Ingin Menghapus Data Wastage Dengan No ' + edtWastageNo.Text) = mrYes then
begin
if not FWastage.RemoveFromDB then
begin
cRollbackTrans;
CommonDlg.ShowMessage('Gagal Menghapus Data');
end
else
begin
cCommitTrans;
cClearGrid(ColGrid, False);
ClearByTag(frmWastageReal, [0]);
CommonDlg.ShowMessage('Berhasil Menghapus Data');
end;
end;
}
end;
procedure TfrmWastageReal.colgridCanEditCell(Sender: TObject; ARow,
ACol: Integer; var CanEdit: Boolean);
begin
inherited;
CanEdit := False;
end;
procedure TfrmWastageReal.colgridClickCell(Sender: TObject; ARow,
ACol: Integer);
begin
inherited;
{
FBarang.LoadByKode(colgrid.Cells[_kolKodeBarang, colgrid.Row]);
edtProductName.Text := FBarang.Alias;
}
end;
procedure TfrmWastageReal.LoadDataWastage;
begin
// FWastage.LoadByWSTRL_NO(edtWastageNo.Text, masternewunit.id);
// LoadHeaderWastage;
// LoadDetilWastage;
end;
procedure TfrmWastageReal.RefreshData;
begin
inherited;
// TODO -cMM: TfrmWastageReal.RefreshData default body inserted
end;
end.
|
(* WPC 59: Determine endianness without using C *)
program endianness;
type VariantRecord = record
case selector: Byte of
0: (WordValue: Word);
1: (ByteValue: Array[1..2] of Byte);
end;
procedure UsingVariantRecords;
var VRec: VariantRecord;
begin
VRec.WordValue := 1;
if (VRec.ByteValue[2] = 0) and (VRec.ByteValue[1] = 1) then
Writeln('Variant record says: Little endian')
else if (VRec.ByteValue[2] = 1) and (VRec.ByteValue[1] = 0) then
Writeln('Variant record says: Big endian')
else
Writeln('Variant record says: Cannot determine endianness')
end;
procedure UsingPointers;
var AWord: Word;
BytePointer: ^Byte;
Byte1, Byte2: Byte;
begin
AWord := 1;
BytePointer := @AWord;
Byte1 := BytePointer^;
Inc(BytePointer);
Byte2 := BytePointer^;
if (Byte1 = 1) and (Byte2 = 0) then
Writeln('Pointer says: Little endian')
else if (Byte1 = 0) and (Byte2 = 1) then
Writeln('Pointer says: Big endian')
else
Writeln('Pointer says: Cannot determine endianness');
end;
procedure UsingCompiler;
begin
{$IFDEF ENDIAN_BIG}
Writeln('Compiler says: Big endian')
{$ELSE}
{$IFDEF ENDIAN_LITTLE}
Writeln('Compiler says: Little endian')
{$ELSE}
Writeln('Compiler says: Cannot determine endianness')
{$ENDIF}
{$ENDIF}
end;
begin
UsingVariantRecords;
UsingPointers;
UsingCompiler;
end.
|
{ Visual PlanIt datastore using an ini file }
{$I vp.inc}
unit VpIniDs;
interface
uses
SysUtils, Classes,
VpData, VpBaseDS;
type
TVpIniDatastore = class(TVpCustomDatastore)
private
FFilename: String;
FFormatSettings: TFormatSettings;
procedure SetFilename(const AValue: String);
protected
function ContactToStr(AContact: TVpContact): String;
function EventToStr(AEvent: TVpEvent): String;
function ResourceToStr(AResource: TVpResource): String;
function TaskToStr(ATask: TVpTask): String;
procedure StrToContact(AString: String; AContact: TVpContact);
procedure StrToEvent(AString: String; AEvent: TVpEvent);
procedure StrToEventTimes(AString: String; out AStartTime, AEndTime: TDateTime);
procedure StrToResource(AString: String; AResource: TVpResource);
procedure StrToTask(AString: String; ATask: TVpTask);
procedure SetConnected(const AValue: Boolean); override;
procedure Split(const AString: String; AList: TStrings);
function UniqueID(AValue: Integer): Boolean;
procedure Loaded; override;
procedure ReadFromIni;
procedure WriteToIni;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetNextID(TableName: string): Integer; override;
procedure LoadEvents; override;
procedure LoadContacts; override;
procedure LoadTasks; override;
procedure PostContacts; override;
procedure PostEvents; override;
procedure PostResources; override;
procedure PostTasks; override;
procedure SetResourceByName(Value: String); override;
published
property AutoConnect default false;
property FileName: String read FFileName write SetfileName;
end;
implementation
uses
typinfo, StrUtils, Strings, IniFiles,
VpConst, VpMisc, VpSR;
procedure IniError(const AMsg: String);
begin
raise Exception.Create(AMsg);
end;
{ TVpIniDatastore }
constructor TVpIniDatastore.Create(AOwner: TComponent);
begin
inherited;
FFormatSettings := DefaultFormatSettings;
FFormatSettings.DecimalSeparator := '.';
FFormatSettings.ThousandSeparator := #0;
FFormatSettings.ShortDateFormat := 'yyyy/mm/dd';
FFormatSettings.LongTimeFormat := 'hh:nn:ss';
FFormatSettings.DateSeparator := '/';
FFormatSettings.TimeSeparator := ':';
FDayBuffer := 1000*365; // 1000 years, i.e. deactivate daybuffer mechanism
end;
destructor TVpIniDatastore.Destroy;
begin
SetConnected(false);
inherited;
end;
function TVpIniDatastore.ContactToStr(AContact: TVpContact): String;
begin
Result := '{' + // RecordID is stored in ini value name.
AContact.FirstName + '}|{' +
AContact.LastName + '}|{' +
IfThen(AContact.BirthDate = 0.0, '',
FormatDateTime('ddddd', AContact.BirthDate, FFormatSettings)) + '}|{' + // Short date format
IfThen(AContact.Anniversary = 0.0, '',
FormatDateTime('ddddd', AContact.Anniversary, FFormatSettings)) + '}|{' +
AContact.Title + '}|{' +
AContact.Company + '}|{' +
AContact.Job_Position + '}|{' +
AContact.EMail + '}|{' +
AContact.Address + '}|{' +
AContact.City + '}|{' +
AContact.State + '}|{' +
AContact.Zip + '}|{' +
AContact.Country + '}|{' +
EncodeLineEndings(AContact.Notes) + '}|{' +
AContact.Phone1 + '}|{' +
AContact.Phone2 + '}|{' +
AContact.Phone3 + '}|{' +
AContact.Phone4 + '}|{' +
AContact.Phone5 + '}|{' +
IntToStr(AContact.PhoneType1) + '}|{' +
IntToStr(AContact.PhoneType2) + '}|{' +
IntToStr(AContact.PhoneType3) + '}|{' +
IntToStr(AContact.PhoneType4) + '}|{' +
IntToStr(AContact.PhoneType5) + '}|{' +
IntToStr(AContact.Category) + '}|{' +
AContact.Custom1 + '}|{' +
AContact.Custom2 + '}|{' +
AContact.Custom3 + '}|{' +
AContact.Custom4 + '}|{' +
AContact.UserField0 + '}|{' +
AContact.UserField1 + '}|{' +
AContact.UserField2 + '}|{' +
AContact.UserField3 + '}|{' +
AContact.UserField4 + '}|{' +
AContact.UserField5 + '}|{' +
AContact.UserField6 + '}|{' +
AContact.UserField7 + '}|{' +
AContact.UserField8 + '}|{' +
AContact.UserField9 + '}';
end;
function TVpIniDatastore.EventToStr(AEvent: TVpEvent): String;
begin
Result := '{' + // RecordID is stored as ini value name
IfThen(AEvent.StartTime = 0.0, '',
FormatDateTime('c', AEvent.StartTime, FFormatSettings)) + '}|{' + // Short date + long time
IfThen(AEvent.EndTime = 0.0, '',
FormatDateTime('c', AEvent.EndTime, FFormatSettings)) +'}|{' +
AEvent.Description + '}|{' +
AEvent.Location + '}|{' +
EncodeLineEndings(AEvent.Notes) + '}|{' +
IntToStr(AEvent.Category) + '}|{' +
AEvent.DingPath + '}|{' +
BoolToStr(AEvent.AllDayEvent, strTRUE, strFALSE) + '}|{' +
BoolToStr(AEvent.AlarmSet, strTRUE, strFALSE) + '}|{' +
IntToStr(AEvent.AlarmAdvance) + '}|{' +
GetEnumName(TypeInfo(TVpAlarmAdvType), ord(AEvent.AlarmAdvanceType)) + '}|{' +
FormatDateTime('tt', AEvent.SnoozeTime, FFormatSettings) + '}|{' + // long time format
GetEnumName(TypeInfo(TVpRepeatType), ord(AEvent.RepeatCode)) + '}|{' +
IfThen(AEvent.RepeatRangeEnd = 0.0, '',
FormatDateTime('ddddd', AEvent.RepeatRangeEnd, FFormatSettings)) + '}|{' + // Short date format
IntToStr(AEvent.CustomInterval) + '}|{' +
AEvent.UserField0 + '}|{' +
AEvent.UserField1 + '}|{' +
AEvent.UserField2 + '}|{' +
AEvent.UserField3 + '}|{' +
AEvent.UserField4 + '}|{' +
AEvent.UserField5 + '}|{' +
AEvent.UserField6 + '}|{' +
AEvent.UserField7 + '}|{' +
AEvent.UserField8 + '}|{' +
AEvent.UserField9 + '}';
end;
function TVpIniDatastore.GetNextID(TableName: string): Integer;
begin
Unused(TableName);
repeat
Result := Random(High(Integer));
until UniqueID(Result) and (Result <> -1);
end;
function TVpIniDatastore.UniqueID(AValue: Integer): Boolean;
var
i, j: Integer;
res: TVpResource;
begin
Result := false;
for i:=0 to Resources.Count-1 do begin
res := Resources.Items[i];
if res.ResourceID = AValue then
exit;
for j:=0 to res.Contacts.Count-1 do
if res.Contacts.GetContact(j).RecordID = AValue then
exit;
for j:=0 to res.Tasks.Count-1 do
if res.Tasks.GetTask(j).RecordID = AValue then
exit;
for j:=0 to res.Schedule.EventCount-1 do
if res.Schedule.GetEvent(j).RecordID = AValue then
exit;
end;
Result := true;
end;
function TVpIniDatastore.ResourceToStr(AResource: TVpResource): String;
begin
result := '{' +
AResource.Description + '}|{' +
EncodeLineEndings(AResource.Notes) + '}|{' +
BoolToStr(AResource.ResourceActive, strTRUE, strFALSE) + '}|{' +
AResource.UserField0 + '}|{' +
AResource.UserField1 + '}|{' +
AResource.UserField2 + '}|{' +
AResource.UserField3 + '}|{' +
AResource.UserField4 + '}|{' +
AResource.UserField5 + '}|{' +
AResource.UserField6 + '}|{' +
AResource.UserField7 + '}|{' +
AResource.UserField8 + '}|{' +
AResource.UserField9 + '}';
end;
procedure TVpIniDatastore.SetConnected(const AValue: Boolean);
begin
if AValue = Connected then
exit;
if AValue then
ReadFromIni
else
WriteToIni;
inherited SetConnected(AValue);
end;
procedure TVpIniDatastore.SetResourceByName(Value: string);
var
I: integer;
res : TVpResource;
begin
for I := 0 to pred(Resources.Count) do begin
res := Resources.Items[I];
if Res = nil then
Continue;
if res.Description = Value then begin
if ResourceID <> Res.ResourceID then begin
ResourceID := Res.ResourceID;
RefreshResource;
end;
Exit;
end;
end;
end;
procedure TVpIniDatastore.Split(const AString: String; AList: TStrings);
var
p: PChar;
pStart, pEnd: PChar;
procedure AddString;
var
s: String;
begin
SetLength(s, {%H-}PtrInt(pEnd) - {%H-}PtrInt(pStart));
StrLCopy(PChar(s), pStart, {%H-}PtrInt(pEnd) - {%H-}PtrInt(pStart));
AList.Add(s);
end;
begin
AList.Clear;
if AString = '' then
exit;
p := @AString[1];
if p^ <> '{' then
IniError(RSIniFileStructure);
inc(p);
pStart := p;
while true do begin
case p^ of
#0: break;
'}': begin
pEnd := p;
inc(p);
if p^ = #0 then begin
AddString;
exit;
end;
if p^ <> '|' then
IniError(RSIniFileStructure);
inc(p);
if p^ <> '{' then
IniError(RSIniFileStructure);
AddString;
inc(p);
pstart := p;
end;
else inc(p);
end;
end;
end;
function TVpIniDatastore.TaskToStr(ATask: TVpTask): String;
begin
Result := '{' + // RecordID is stored as ini value name.
BoolToStr(ATask.Complete, strTRUE, strFALSE) + '}|{' +
ATask.Description + '}|{' +
EncodeLineendings(ATask.Details) + '}|{' +
IfThen(ATask.CreatedOn = 0.0, '',
FormatDateTime('ddddd', ATask.CreatedOn, FFormatsettings)) + '}|{' +
IfThen(ATask.CompletedOn = 0.0, '',
FormatDateTime('ddddd', ATask.CompletedOn, FFormatSettings)) + '}|{' +
IntToStr(ATask.Priority) + '}|{' +
IntToStr(ATask.Category) + '}|{' +
IfThen(ATask.DueDate = 0.0, '',
FormatDateTime('ddddd', ATask.DueDate, FFormatSettings)) + '}|{' +
ATask.UserField0 + '}|{' +
ATask.UserField1 + '}|{' +
ATask.UserField2 + '}|{' +
ATask.UserField3 + '}|{' +
ATask.UserField4 + '}|{' +
ATask.UserField5 + '}|{' +
ATask.UserField6 + '}|{' +
ATask.UserField7 + '}|{' +
ATask.UserField8 + '}|{' +
ATask.UserField9 + '}'
end;
procedure TVpIniDatastore.SetFileName(const AValue: String);
begin
FFileName := AValue;
if AutoConnect then ReadFromIni;
end;
procedure TVpIniDatastore.LoadContacts;
begin
// Nothing to do here...
end;
procedure TVpIniDatastore.Loaded;
begin
inherited;
if not (csDesigning in ComponentState) then
Connected := AutoConnect;
end;
procedure TVpIniDatastore.LoadEvents;
begin
// Nothing to do here...
end;
procedure TVpIniDatastore.LoadTasks;
begin
// Nothing to do here...
end;
procedure TVpIniDatastore.PostContacts;
var
i: Integer;
contact: TVpContact;
begin
if Resource = nil then
exit;
for i := Resource.Contacts.Count-1 downto 0 do begin
contact := Resource.Contacts.GetContact(i);
if contact.Deleted then
contact.Free;
end;
RefreshContacts;
end;
procedure TVpIniDatastore.PostEvents;
var
i: Integer;
event: TVpEvent;
begin
if Resource = nil then
exit;
for i := Resource.Schedule.EventCount-1 downto 0 do begin
event := Resource.Schedule.GetEvent(i);
if event.Deleted then
event.Free;
end;
RefreshEvents;
end;
procedure TVpIniDatastore.PostResources;
begin
// Nothing to do...
end;
procedure TVpIniDatastore.PostTasks;
var
i: Integer;
task: TVpTask;
begin
if Resource = nil then
exit;
for i := Resource.Tasks.Count-1 downto 0 do begin
task := Resource.Tasks.GetTask(i);
if task.Deleted then
task.Free;
end;
RefreshTasks;
end;
procedure TVpIniDatastore.StrToContact(AString: String; AContact: TVpContact);
var
L: TStrings;
begin
L := TStringList.Create;
try
Split(AString, L);
if L.Count <> 39 then
IniError(RSIniFileStructure);
AContact.FirstName := L[0];
AContact.LastName := L[1];
if L[2] = '' then
AContact.BirthDate := 0.0 else
AContact.BirthDate := StrToDate(L[2], FFormatSettings);
if L[3] = '' then
AContact.Anniversary := 0.0 else
AContact.Anniversary := StrToDate(L[3], FFormatSettings);
AContact.Title := L[4];
AContact.Company := L[5];
AContact.Job_Position := L[6];
AContact.EMail := L[7];
AContact.Address := L[8];
AContact.City := L[9];
AContact.State := L[10];
AContact.Zip := L[11];
AContact.Country := L[12];
AContact.Notes := DecodeLineEndings(L[13]);
AContact.Phone1 := L[14];
AContact.Phone2 := L[15];
AContact.Phone3 := L[16];
AContact.Phone4 := L[17];
AContact.Phone5 := L[18];
AContact.PhoneType1 := StrToInt(L[19]);
AContact.PhoneType2 := StrToInt(L[20]);
AContact.PhoneType3 := StrToInt(L[21]);
AContact.PhoneType4 := StrToInt(L[22]);
AContact.PhoneType5 := StrToInt(L[23]);
AContact.Category := StrToInt(L[24]);
AContact.Custom1 := L[25];
AContact.Custom2 := L[26];
AContact.Custom3 := L[27];
AContact.Custom4 := L[28];
AContact.UserField0 := L[29];
AContact.UserField1 := L[30];
AContact.UserField2 := L[31];
AContact.UserField3 := L[32];
AContact.UserField4 := L[33];
AContact.UserField5 := L[34];
AContact.UserField6 := L[35];
AContact.UserField7 := L[36];
AContact.UserField8 := L[37];
AContact.UserField9 := L[38];
finally
L.Free;
end;
end;
procedure TVpIniDatastore.StrToEventTimes(AString: String;
out AStartTime, AEndTime: TDateTime);
var
L: TStrings;
begin
L := TStringList.Create;
try
Split(AString, L);
if L.Count < 2 then
IniError(RSIniFileStructure);
if L[0] = '' then
AStartTime := 0 else
AStartTime := StrToDateTime(L[0], FFormatSettings);
if L[1] = '' then
AEndTime := 0 else
AEndtime := StrToDateTime(L[1], FFormatSettings);
finally
L.Free;
end;
end;
procedure TVpIniDatastore.StrToEvent(AString: String; AEvent: TVpEvent);
var
L: TStrings;
begin
L := TStringList.Create;
try
Split(AString, L);
if L.Count <> 25 then
IniError(RSIniFileStructure);
if L[0] = '' then
AEvent.StartTime := 0 else
AEvent.StartTime := StrToDateTime(L[0], FFormatSettings);
if L[1] = '' then
AEvent.EndTime := 0 else
AEvent.EndTime := StrToDateTime(L[1], FFormatSettings);
AEvent.Description := L[2];
AEvent.Location := L[3];
AEvent.Notes := DecodeLineEndings(L[4]);
AEvent.Category := StrToInt(L[5]);
AEvent.DingPath := L[6];
AEvent.AllDayEvent := StrToBool(L[7]);
AEvent.AlarmSet := StrToBool(L[8]);
AEvent.AlarmAdvance := StrToInt(L[9]);
AEvent.AlarmAdvanceType := TVpAlarmAdvType(GetEnumValue(TypeInfo(TVpAlarmAdvType), L[10]));
AEvent.SnoozeTime := StrToTime(L[11]);
AEvent.RepeatCode := TVpRepeatType(GetEnumValue(TypeInfo(TVpRepeatType), L[12]));
if L[13] = '' then
AEvent.RepeatRangeEnd := 0 else
AEvent.RepeatRangeEnd := StrToDate(L[13], FFormatSettings);
AEvent.CustomInterval := StrToInt(L[14]);
AEvent.UserField0 := L[15];
AEvent.UserField1 := L[16];
AEvent.UserField2 := L[17];
AEvent.UserField3 := L[18];
AEvent.UserField4 := L[19];
AEvent.UserField5 := L[20];
AEvent.UserField6 := L[21];
AEvent.UserField7 := L[22];
AEvent.UserField8 := L[23];
AEvent.UserField9 := L[24];
finally
L.Free;
end;
end;
procedure TVpIniDatastore.StrToResource(AString: String; AResource: TVpResource);
var
L: TStrings;
begin
L := TStringList.Create;
try
Split(AString, L);
if L.Count <> 13 then
IniError(RSIniFileStructure);
AResource.Description := L[0];
AResource.Notes := DecodeLineEndings(L[1]);
AResource.ResourceActive := StrToBool(L[2]);
AResource.UserField0 := L[3];
AResource.UserField1 := L[4];
AResource.UserField2 := L[5];
AResource.UserField3 := L[6];
AResource.UserField4 := L[7];
AResource.UserField5 := L[8];
AResource.UserField6 := L[9];
AResource.UserField7 := L[10];
AResource.UserField8 := L[11];
AResource.UserField9 := L[12];
finally
L.Free;
end;
end;
procedure TVpIniDatastore.StrToTask(AString: String; ATask: TVpTask);
var
L: TStrings;
begin
L := TStringList.Create;
try
Split(AString, L);
if L.Count <> 18 then
IniError(RSIniFileStructure);
ATask.Complete := StrToBool(L[0]);
ATask.Description := L[1];
ATask.Details := DecodeLineEndings(L[2]);
if L[3] = '' then
ATask.CreatedOn := 0.0 else
ATask.CreatedOn := StrToDate(L[3], FFormatSettings);
if L[4] = '' then
ATask.CompletedOn := 0.0 else
ATask.CompletedOn := StrToDate(L[4], FFormatSettings);
ATask.Priority := StrToInt(L[5]);
ATask.Category := StrToInt(L[6]);
if L[7] = '' then
ATask.DueDate := 0.0 else
ATask.DueDate := StrtoDate(L[7], FFormatSettings);
ATask.UserField0 := L[8];
ATask.UserField1 := L[9];
ATask.UserField2 := L[10];
ATask.UserField3 := L[11];
ATask.UserField4 := L[12];
ATask.UserField5 := L[13];
ATask.UserField6 := L[14];
ATask.UserField7 := L[15];
ATask.UserField8 := L[16];
ATask.UserField9 := L[17];
finally
L.Free;
end;
end;
procedure TVpIniDatastore.ReadFromIni;
var
ini: TCustomIniFile;
ResList, L: TStrings;
res: TVpResource;
contact: TVpContact;
event: TVpEvent;
task: TVpTask;
i,j: Integer;
s: String;
key: String;
resID, id: Integer;
tStart, tEnd: TDateTime;
begin
if FFileName = '' then
exit;
ini := TMemIniFile.Create(FFileName);
ResList := TStringList.Create;
L := TStringList.Create;
try
Resources.ClearResources;
ini.ReadSection('Resources', ResList);
for i:=0 to ResList.Count-1 do begin
s := ini.ReadString('Resources', ResList[i], '');
if s = '' then
IniError(RSIniFileStructure);
resID := StrToInt(ResList[i]);
res := Resources.AddResource(resID);
StrToResource(s, res);
key := Format('Contacts of resource %d', [resID]);
L.Clear;
ini.ReadSection(key, L);
for j:=0 to L.Count-1 do begin
id := StrToInt(L[j]);
contact := res.Contacts.AddContact(id);
s := ini.ReadString(key, L[j], '');
StrToContact(s, contact);
end;
key := Format('Events of resource %d', [resID]);
L.Clear;
ini.ReadSection(key, L);
for j:=0 to L.Count-1 do begin
id := StrToInt(L[j]);
s := ini.ReadString(key, L[j], '');
StrToEventTimes(s, tStart, tEnd);
event := res.Schedule.AddEvent(id, tStart, tEnd);
StrToEvent(s, event);
end;
key := Format('Tasks of resource %d', [resID]);
L.Clear;
ini.ReadSection(key, L);
for j:=0 to L.Count-1 do begin
id := StrToInt(L[j]);
task := res.Tasks.AddTask(id);
s := ini.ReadString(key, L[j], '');
StrToTask(s, task);
end;
end;
finally
ini.Free;
L.Free;
ResList.Free;
end;
end;
procedure TVpIniDatastore.WriteToIni;
var
ini: TMemIniFile;
i, j: Integer;
res: TVpResource;
contact: TVpContact;
event: TVpEvent;
task: TVpTask;
key: String;
begin
if FFileName = '' then
exit;
ini := TMemIniFile.Create(FFileName);
try
ini.Clear;
for i:=0 to Resources.Count-1 do begin
res := Resources.Items[i];
if not res.Deleted then
ini.WriteString('Resources', IntToStr(res.ResourceID), ResourceToStr(res));
end;
for i:=0 to Resources.Count-1 do begin
res := Resources.Items[i];
key := Format('Contacts of resource %d', [res.ResourceID]);
for j:=0 to res.Contacts.Count-1 do begin
contact := res.Contacts.GetContact(j);
if not contact.Deleted then
ini.WriteString(key, IntToStr(contact.RecordID), ContactToStr(contact));
end;
end;
for i:=0 to Resources.Count-1 do begin
res := Resources.Items[i];
key := Format('Tasks of resource %d', [res.ResourceID]);
for j:=0 to res.Tasks.Count-1 do begin
task := res.Tasks.GetTask(j);
if not task.Deleted then
ini.WriteString(key, IntToStr(task.RecordID), TaskToStr(task));
end;
end;
for i:=0 to Resources.Count-1 do begin
res := Resources.Items[i];
key := Format('Events of resource %d', [res.ResourceID]);
for j:=0 to res.Schedule.EventCount-1 do begin
event := res.Schedule.GetEvent(j);
if not event.Deleted then
ini.WriteString(key, IntToStr(event.RecordID), EventToStr(event));
end;
end;
finally
ini.Free;
end;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.IDE.Constants;
interface
const
cWizardTitle = 'DPM Package Manager';
cWizardDescription = 'DPM is an Open Source package manager - it makes managing dependencies easy' + #13#10 +
'(c) Copyright Vincent Parrett and contributors' + #13#10 +
'https://github.com/DelphiPackageManager/DPM';
cWizardProjectMenuCaption = 'Manage DPM Packages';
cDPMPackages = 'DPM Packages';
cDPMContainer = 'DPMPackagesContainer'; //just needs to be something the IDE doesn't use already
dDPMPackageContainer = 'DPMPackageContainer';
cDPMPlatformContainer = 'DPMPlatformContainer';
implementation
end.
|
unit ShortestU;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
GLScene,
GLTerrainRenderer,
GLObjects, GLTexture,
GLWin32Viewer,
GLMaterial,
GLCoordinates,
GLCrossPlatform,
GLBaseClasses,
// Unit where the random landscape are coded
GLRandomHDS;
type
TForm1 = class(TForm)
// These are the minimum GLScene object needed.
// Built ąt design time
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLMaterialLibrary1: TGLMaterialLibrary; // Linked to the terrain renderer
GLCamera1: TGLCamera; // Linked to the Scene Viewer
GLDummyCube1: TGLDummyCube;
// Contains the terrain renderer. Allows to change its scale
GLTerrainRenderer1: TGLTerrainRenderer;
procedure FormCreate(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
private
hdsLandscape: TGLFractalHDS; // Declare the landscape manually
mx, my: Integer;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
{ Setting up terrain renderer. This could be done at design time but you have
missed it. These transformations are needed because, in a HDS, the z vector
is pointing upward. }
GLTerrainRenderer1.Up.SetVector(0, 0, 1);
GLTerrainRenderer1.Direction.SetVector(0, 1, 0);
{ Position the camera to have an interesting view }
GLCamera1.Position.SetPoint(-64, 16, 64);
{ Creation and minimal set-up of a fractal landscape }
hdsLandscape := TGLFractalHDS.Create(Self);
with hdsLandscape do
begin
TerrainRenderer := GLTerrainRenderer1;
Depth := 8;
// 3 < Depth < 10, Not needed but gives a nicer landscape (default depth is 4)
Cyclic := True; // Not needed but give a "infinite" landscape
BuildLandscape; // Build a landscape with the default parameters
end; // with
end;
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera1.AdjustDistanceToTarget(Power(1.03, WheelDelta/120));
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
mx := X;
my := Y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my - Y, mx - X);
{
if ssRight in Shift then
GLCamera1.MoveTargetInEyeSpace((Y - my) * 0.05, (mx - X) * 0.05, 0);
}
mx := X;
my := Y;
end;
end.
|
unit uAddRegion;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, {uCharControl, uFControl, uLabeledFControl, uSpravControl,}
StdCtrls, Buttons,{ uFormControl,} uAdr_DataModule,{ uAddModifForm,}
cxLookAndFeelPainters, FIBQuery, pFIBQuery, pFIBStoredProc, DB,
FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, ActnList, cxButtons,
cxLabel, cxControls, cxContainer, cxEdit, cxTextEdit, AdrSp_MainForm, AdrSp_Types,
IBase, cxMaskEdit, cxButtonEdit, cxCheckBox, Address_ZMessages;
type
TAdd_Region_Form = class(TAdrEditForm)
NameTE: TcxTextEdit;
NameLbl: TcxLabel;
AcceptBtn: TcxButton;
CancelBtn: TcxButton;
ActionList: TActionList;
AcceptAction: TAction;
CancelAction: TAction;
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
DSet: TpFIBDataSet;
StProc: TpFIBStoredProc;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
TypeBE: TcxButtonEdit;
CountryBE: TcxButtonEdit;
EqualCB: TcxCheckBox;
Zip1: TcxMaskEdit;
Zip2: TcxMaskEdit;
cxLabel3: TcxLabel;
cxLabel4: TcxLabel;
procedure TypeBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure CountryBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CancelActionExecute(Sender: TObject);
procedure AcceptActionExecute(Sender: TObject);
procedure EqualCBPropertiesChange(Sender: TObject);
procedure Zip1PropertiesEditValueChanged(Sender: TObject);
procedure Zip2PropertiesEditValueChanged(Sender: TObject);
private
pIdRegion:Integer;
procedure UpdateZip2;
function CheckData:Boolean;
public
// Mode:TFormMode;
// DBHandle: integer;
// constructor Create(AOwner: TComponent ; DMod: TAdrDM; Mode: TFormMode; Where: Variant);reintroduce;
pIdCountry:Integer;
pIdType:Integer;
constructor Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AIdRegion:Integer=-1);reintroduce;
end;
implementation
{$R *.dfm}
uses RxMemDS, Math;
constructor TAdd_Region_Form.Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AIdRegion:Integer=-1);
begin
inherited Create(AOwner);
//******************************************************************************
DB.Handle:=ADB_HANDLE;
StartId:=AIdRegion;
end;
procedure TAdd_Region_Form.TypeBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
Params:TSpParams;
OutPut:TRxMemoryData;
begin
Params.FormCaption:='Довідник типів регіонів';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbExit];
Params.AddFormClass:='TAdd_Region_Form';
Params.ModifFormClass:='TAdd_Region_Form';
Params.TableName:='ini_type_region';
Params.Fields:='Name_full,id_region_type';
Params.FieldsName:='Назва';
Params.KeyField:='id_region_type';
Params.ReturnFields:='Name_full,id_region_type';
Params.DeleteSQL:='execute procedure adr_region_d(:id_region);';
Params.DBHandle:=Integer(DB.Handle);
OutPut:=TRxMemoryData.Create(self);
if GetAdressesSp(Params,OutPut) then
begin
pIdType:=output['id_region_type'];
TypeBE.Text:=VarToStr(output['Name_full']);
end;
end;
procedure TAdd_Region_Form.CountryBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
Params:TSpParams;
OutPut:TRxMemoryData;
begin
Params.FormCaption:='Довідник країн';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit];
Params.AddFormClass:='TAdd_Country_Form';
Params.ModifFormClass:='TAdd_Country_Form';
Params.TableName:='adr_country_select';
Params.Fields:='Name_country,id_country';
Params.FieldsName:='Назва';
Params.KeyField:='id_country';
Params.ReturnFields:='Name_country,id_country';
Params.DeleteSQL:='execute procedure adr_country_d(:id_country);';
Params.DBHandle:=Integer(DB.Handle);
OutPut:=TRxMemoryData.Create(self);
if GetAdressesSp(Params,OutPut) then
begin
pIdCountry:=output['id_country'];
CountryBE.Text:=VarToStr(output['Name_country']);
end;
end;
procedure TAdd_Region_Form.FormShow(Sender: TObject);
begin
ReadTransaction.Active:=True;
pIdRegion:=StartId;
if pIdRegion>-1 then
begin
// изменение
Caption:='Змінити регіон';
if DSet.Active then DSet.Close;
DSet.SQLs.SelectSQL.Text:='SELECT * FROM ADR_REGION_S('+IntToStr(pIdRegion)+')';
DSet.Open;
NameTE.Text:=DSet['NAME_REGION'];
pIdCountry:=DSet['ID_COUNTRY'];
pIdType:=DSet['ID_REGION_TYPE'];
CountryBE.Text:=DSet['NAME_COUNTRY'];
TypeBE.Text:=DSet['TYPE_NAME'];
Zip1.Text:=VarToStr(DSet['ZIP_BEG']);
Zip2.Text:=VarToStr(DSet['ZIP_END']);
end
else
begin
Caption:='Додати регіон';
if (VarIsArray(Additional)) and (not (VarIsNull(Additional))) then
begin
pIdCountry:=Additional[0];
CountryBE.Text:=VarToStr(Additional[1]);
end;
end;
end;
procedure TAdd_Region_Form.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ReadTransaction.Active:=False;
end;
procedure TAdd_Region_Form.CancelActionExecute(Sender: TObject);
begin
// Ничего не меняли, а, следовательно, обновлять ничего не надо
ResultId:=-1;
ModalResult:=mrCancel;
end;
function TAdd_Region_Form.CheckData:Boolean;
begin
Result:=True;
if NameTE.Text='' then
begin
ZShowMessage('Помилка!','Вкажіть назву регіона',mtError,[mbOK]);
NameTE.SetFocus;
Result:=False;
Exit;
end;
if TypeBE.Text='' then
begin
ZShowMessage('Помилка!','Вкажіть тип регіона',mtError,[mbOK]);
TypeBE.SetFocus;
Result:=False;
Exit;
end;
if CountryBE.Text='' then
begin
ZShowMessage('Помилка!','Вкажіть країну',mtError,[mbOK]);
CountryBE.SetFocus;
Result:=False;
Exit;
end;
if ((Zip1.Text='') or (Zip2.Text='')) and
not((Zip1.Text='') and (Zip2.Text='')) then
begin
ZShowMessage('Помилка!','Вкажіть діапазон повністю',mtError,[mbOK]);
if (Zip1.Text='') then
Zip1.SetFocus
else
Zip2.SetFocus;
Result:=False;
Exit;
end;
if not((Zip1.Text='') and (Zip2.Text='')) and
(Zip1.EditValue>Zip2.EditValue) then
begin
ZShowMessage('Помилка!','Кінець діапазону має бути більшим за початок',mtError,[mbOK]);
Result:=False;
Zip1.SetFocus;
Exit;
end;
end;
procedure TAdd_Region_Form.AcceptActionExecute(Sender: TObject);
begin
if not(CheckData) then Exit;
try
StProc.StoredProcName:='ADR_REGION_IU';
WriteTransaction.StartTransaction;
StProc.Prepare;
if pIdRegion>-1 then
StProc.ParamByName('ID_R').AsInteger:=pIdRegion;
StProc.ParamByName('NAME_REGION').AsString:=NameTE.Text;
StProc.ParamByName('ID_COUNTRY').AsInteger:=pIdCountry;
StProc.ParamByName('ID_REGION_TYPE').AsInteger:=pIdType;
StProc.ExecProc;
pIdRegion:=StProc.FN('ID_REGION').AsInteger;
// WriteTransaction.Commit;
if not((Zip1.Text='')) and not((Zip2.Text='')) then
begin
StProc.StoredProcName:='ADR_ZIP_REGION_IU';
// WriteTransaction.StartTransaction;
StProc.Prepare;
StProc.ParamByName('ID_REGION').AsInteger:=pIdRegion;
StProc.ParamByName('ZIP_BEG').AsInteger:=Zip1.EditValue;
StProc.ParamByName('ZIP_END').AsInteger:=Zip2.EditValue;
StProc.ExecProc;
end;
WriteTransaction.Commit;
ResultId:=pIdRegion;
ModalResult:=mrOk;
except
on E:Exception do
begin
WriteTransaction.Rollback;
ZShowMessage('Помилка',E.Message,mtError,[mbOk]);
end;
end;
end;
procedure TAdd_Region_Form.UpdateZip2;
//var c:Variant;
begin
if EqualCB.Checked then
Zip2.EditValue:=Zip1.EditValue
{ else
if (Zip1.EditValue>Zip2.EditValue) and not((Zip2.Text='')) then
begin
c:=Zip1.EditValue;
Zip1.EditValue:=Zip2.EditValue;
Zip2.EditValue:=c;
end;}
end;
procedure TAdd_Region_Form.EqualCBPropertiesChange(Sender: TObject);
begin
Zip2.Enabled:=not(EqualCB.Checked);
UpdateZip2;
end;
procedure TAdd_Region_Form.Zip1PropertiesEditValueChanged(Sender: TObject);
begin
UpdateZip2;
end;
procedure TAdd_Region_Form.Zip2PropertiesEditValueChanged(Sender: TObject);
begin
UpdateZip2;
end;
initialization
RegisterClass(TAdd_Region_Form);
end.
|
unit htTurboBox;
interface
uses
Windows, SysUtils, Types, Classes, Controls, Graphics,
htInterfaces, htTag, htMarkup, htControls, htPanel, htAjaxPanel;
type
ThtTurboGraphicControl = class(ThtGraphicControl, IhtAjaxControl)
protected
procedure MarkupStyles(const inStyleBase: string; inMarkup: ThtMarkup);
public
procedure GenerateTag(inTag: ThtTag;
inMarkup: ThtMarkup); virtual; abstract;
end;
//
ThtTurboCustomControl = class(ThtCustomControl, IhtAjaxControl)
protected
procedure MarkupStyles(const inStyleBase: string; inMarkup: ThtMarkup);
public
procedure GenerateTag(inTag: ThtTag;
inMarkup: ThtMarkup); virtual; abstract;
end;
//
ThtTurboBox = class(ThtTurboCustomControl)
private
FBoxPicture: TPicture;
protected
procedure AdjustClientRect(var inRect: TRect); override;
procedure Paint; override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
procedure GenerateTag(inTag: ThtTag; inMarkup: ThtMarkup); override;
published
property Align;
property Caption;
property Outline;
property Style;
//property Transparent;
property Visible;
end;
implementation
uses
LrVclUtils, LrControlIterator, htPaint;
{ ThtTurboGraphicControl }
procedure ThtTurboGraphicControl.MarkupStyles(const inStyleBase: string;
inMarkup: ThtMarkup);
var
s: string;
begin
case Align of
alLeft, alRight: s := Format(' width: %dpx;', [ ClientWidth ]);
alTop, alBottom: s := Format(' height: %dpx;', [ ClientHeight ]);
else s := '';
end;
s := inStyleBase + s;
if (s <> '') then
inMarkup.Styles.Add(Format('#%s { %s }', [ Name, s ]));
end;
{ ThtTurboCustomControl }
procedure ThtTurboCustomControl.MarkupStyles(const inStyleBase: string;
inMarkup: ThtMarkup);
var
s: string;
begin
case Align of
alLeft, alRight: s := Format(' width: %dpx;', [ ClientWidth ]);
alTop, alBottom: s := Format(' height: %dpx;', [ ClientHeight ]);
else s := '';
end;
s := inStyleBase + s;
if (s <> '') then
inMarkup.Styles.Add(Format('#%s { %s }', [ Name, s ]));
end;
{ ThtTurboBox }
constructor ThtTurboBox.Create(inOwner: TComponent);
begin
inherited;
FBoxPicture := TPicture.Create;
FBoxPicture.LoadFromFile('C:\Inetpub\wwwroot\turboajax\test\images\big_box_white.gif');
ControlStyle := ControlStyle + [ csAcceptsControls ];
end;
destructor ThtTurboBox.Destroy;
begin
FBoxPicture.Free;
inherited;
end;
procedure ThtTurboBox.AdjustClientRect(var inRect: TRect);
begin
with inRect do
inRect := Rect(Left + 14, Top + 27, Right - 14, Bottom - 18);
end;
procedure ThtTurboBox.GenerateTag(inTag: ThtTag; inMarkup: ThtMarkup);
begin
with inTag do
begin
Element := 'div';
Attributes['turboAlign'] := AlignToAjaxAlign(Align);
Attributes['dojoType'] := 'TurboBox';
Attributes['id'] := Name;
with Add do
begin
Element := 'div';
Add(Caption);
end;
end;
MarkupStyles(Style.InlineAttribute, inMarkup);
AjaxGenerateChildren(Self, inTag, inMarkup);
{
if not included then
begin
included := true;
inMarkup.AddJavaScriptInclude('/turboajax/turbo/widgets/TurboBox.js');
end;
}
end;
procedure ThtTurboBox.Paint;
const
margin = 14;
var
r, src, dst: TRect;
w, h: Integer;
begin
inherited;
r := BoxRect;
w := BoxWidth;
h := BoxHeight;
//
src := Rect(0, 0, margin, h - margin);
dst := src;
OffsetRect(dst, r.Left, r.Top);
Canvas.CopyRect(dst, FBoxPicture.Bitmap.Canvas, src);
//
src := Rect(FBoxPicture.Width - (w - margin), 0, FBoxPicture.Width, h - margin);
dst := Rect(margin, 0, w, h - margin);
OffsetRect(dst, r.Left, r.Top);
Canvas.CopyRect(dst, FBoxPicture.Bitmap.Canvas, src);
//
SetBkMode(Canvas.Handle, Windows.TRANSPARENT);
Canvas.TextOut(dst.Left + margin, dst.Top + 2, Caption);
//
src := Rect(0, FBoxPicture.Height - margin, margin, FBoxPicture.Height);
dst := Rect(0, h - margin, margin, h);
OffsetRect(dst, r.Left, r.Top);
Canvas.CopyRect(dst, FBoxPicture.Bitmap.Canvas, src);
//
src := Rect(FBoxPicture.Width - (w- margin), FBoxPicture.Height - margin, FBoxPicture.Width, FBoxPicture.Height);
dst := Rect(margin, h - margin, w, h);
OffsetRect(dst, r.Left, r.Top);
Canvas.CopyRect(dst, FBoxPicture.Bitmap.Canvas, src);
//
end;
end.
|
unit Server.WiRL;
interface
uses
Neon.Core.Types
, WiRL.Core.Engine
, WiRL.http.Server
, WiRL.http.Server.Indy
, Spring.Logging
, Server.Configuration
;
type
TServerREST = class
private
FServer: TWiRLServer;
FLogger: ILogger;
function GetActive: Boolean;
procedure SetActive(const Value: Boolean);
public
constructor Create(const AConfiguration: TConfiguration; const ALogger: ILogger);
destructor Destroy; override;
property Active: Boolean read GetActive write SetActive;
property Logger: ILogger read FLogger;
end;
implementation
{ TServerREST }
uses
System.SysUtils,Common.Entities.Card, WiRL.Configuration.Neon;
{======================================================================================================================}
constructor TServerREST.Create(const AConfiguration: TConfiguration; const ALogger: ILogger);
{======================================================================================================================}
begin
FLogger := ALogger;
Logger.Enter('TServerREST.Create');
FServer := TWiRLServer.Create(nil);
FServer
.SetPort(AConfiguration.ServerPort)
.SetThreadPoolSize(20)
.AddEngine<TWiRLEngine>('/rest')
.SetEngineName('Tarock Server')
.AddApplication('/app')
.SetAppName('Tarock')
.SetResources('*')
.SetFilters('*')
.Plugin.Configure<IWiRLConfigurationNeon>
.SetUseUTCDate(True)
.SetMemberCase(TNeonCase.SnakeCase)
.BackToApp;
// .ConfigureSerializer
// .GetSerializers.RegisterSerializer(TCardKeySerializer);
Logger.Leave('TServerREST.Create');
end;
{======================================================================================================================}
destructor TServerREST.Destroy;
{======================================================================================================================}
begin
Logger.Enter('TServerREST.Destroy');
Active := False;
FServer.Free;
inherited;
Logger.Leave('TServerREST.Destroy');
end;
{======================================================================================================================}
function TServerREST.GetActive: Boolean;
{======================================================================================================================}
begin
Result := FServer.Active;
end;
{======================================================================================================================}
procedure TServerREST.SetActive(const Value: Boolean);
{======================================================================================================================}
begin
if FServer.Active <> Value then begin
FServer.Active := Value;
Logger.Info('TServerREST.SetActive :: %s is the new value', [BoolToStr(Value, True)]);
end;
end;
end.
|
unit toolsparams;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, Graphics, ExtCtrls, Dialogs, Spin,
StdCtrls, Figures;
type
TParam = class
procedure CreateObjects(Panel: TPanel); virtual; abstract;
end;
TPenColorParam = class(TParam)
procedure ChangePenColor(Sender: TObject);
procedure CreateObjects(Panel: TPanel); override;
end;
TBrushColorParam = class(TParam)
procedure ChangeBrushColor(Sender: TObject);
procedure CreateObjects(Panel: TPanel); override;
end;
TWidthParam = class(TParam)
procedure ChangeWidth(Sender: TObject);
procedure CreateObjects(Panel: TPanel); override;
end;
TRoundingRadiusParamX = class(TParam)
procedure ChangeRoundX(Sender: TObject);
procedure CreateObjects(Panel: TPanel); override;
end;
TRoundingRadiusParamY = class(TParam)
procedure ChangeRoundY(Sender: TObject);
procedure CreateObjects(Panel: TPanel); override;
end;
TBrushStyleParam = class(TParam)
const BStyles: array [0..7] of TBrushStyle = (bsClear, bsSolid,
bsHorizontal, bsVertical, bsFDiagonal, bsBDiagonal, bsCross, bsDiagCross);
procedure ChangeBrushStyle(Sender: TObject);
procedure CreateObjects(Panel: TPanel); override;
end;
TPenStyleParam = class(TParam)
procedure ChangePenStyle(Sender: TObject);
procedure CreateObjects(Panel: TPanel); override;
const PStyles: array[0..5] of TPenStyle = (psSolid, psClear, psDot,
psDash, psDashDot, psDashDotDot);
end;
var
CurrentFigures: array of TFigure;
APenColor, ABrushColor: TColor;
APenStyle: TPenStyle;
ABrushStyle: TBrushStyle;
AWidth,ARadiusX,ARadiusY: integer;
SelectedBStyleIndex, SelectedPStyleIndex: integer;
implementation
procedure TPenColorParam.CreateObjects(Panel: TPanel);
var
ColorLabel: TLabel;
PenColor: TColorButton;
begin
ColorLabel := TLabel.Create(Panel);
ColorLabel.Caption := 'Цвет карандаша';
ColorLabel.Top :=0;
ColorLabel.Parent:=Panel;
PenColor := TColorButton.Create(Panel);
PenColor.Top := 20;
PenColor.Parent := Panel;
PenColor.ButtonColor := APenColor;
PenColor.OnColorChanged := @ChangePenColor;
end;
procedure TPenColorParam.ChangePenColor(Sender: TObject);
begin
APenColor := (Sender as TColorButton).ButtonColor;
end;
procedure TPenStyleParam.CreateObjects(Panel: TPanel);
var
StyleLabel: TLabel;
PenStyle: TComboBox;
i: integer;
s: string;
begin
StyleLabel := TLabel.Create(Panel);
StyleLabel.Caption := 'Стиль линии';
StyleLabel.Top := 120;
StyleLabel.Parent:=Panel;
PenStyle := TComboBox.Create(panel);
for i:=0 to 5 do
begin
WriteStr(s, PStyles[i]);
PenStyle.Items.Add(s);
end;
PenStyle.Top := 140;
PenStyle.Parent := Panel;
PenStyle.ReadOnly := True;
PenStyle.ItemIndex := SelectedPStyleIndex;
PenStyle.OnChange := @ChangePenStyle;
end;
procedure TPenStyleParam.ChangePenStyle(Sender: TObject);
begin
APenStyle := PStyles[(Sender as TComboBox).ItemIndex];
SelectedPStyleIndex := (Sender as TComboBox).ItemIndex;
end;
procedure TBrushColorParam.CreateObjects(Panel: TPanel);
var
ColorLabel: TLabel;
BrushColor: TColorButton;
begin
ColorLabel := TLabel.Create(Panel);
ColorLabel.Caption := 'Цвет заливки';
ColorLabel.Top := 80;
ColorLabel.Parent := Panel;
BrushColor := TColorButton.Create(Panel);
BrushColor.Top := 100;
BrushColor.Parent := Panel;
BrushColor.ButtonColor := ABrushColor;
BrushColor.OnColorChanged := @ChangeBrushColor;
end;
procedure TBrushColorParam.ChangeBrushColor(Sender: TObject);
begin
ABrushColor := (Sender as TColorButton).ButtonColor;
end;
procedure TWidthParam.CreateObjects(Panel: TPanel);
var
WidthLabel: TLabel;
WidthParam: TSpinEdit;
begin
WidthLabel := TLabel.Create(Panel);
WidthLabel.Caption := 'Ширина карандаша';
WidthLabel.Top := 40;
WidthLabel.Parent := Panel;
WidthParam := TSpinEdit.Create(Panel);
WidthParam.Top := 60;
WidthParam.MinValue := 1;
WidthParam.Parent:= Panel;
WidthParam.Value := AWidth;
WidthParam.OnChange := @ChangeWidth;
end;
procedure TBrushStyleParam.CreateObjects(Panel: TPanel);
var
StyleLabel: TLabel;
BrushStyle: TComboBox;
i: Integer;
s: String;
begin
StyleLabel := TLabel.Create(Panel);
StyleLabel.Caption := 'Стиль заливки ';
StyleLabel.Top := 160;
StyleLabel.Parent:=Panel;
BrushStyle := TComboBox.Create(Panel);
for i:=0 to 7 do
begin
WriteStr(s, BStyles[i]);
BrushStyle.Items.Add(s);
end;
BrushStyle.Top := 180;
BrushStyle.Parent := Panel;
BrushStyle.ItemIndex := SelectedBStyleIndex;
BrushStyle.ReadOnly := True;
BrushStyle.OnChange := @ChangeBrushStyle;
end;
procedure TBrushStyleParam.ChangeBrushStyle(Sender: TObject);
begin
ABrushStyle := BStyles[(Sender as TComboBox).ItemIndex];
SelectedBStyleIndex := (Sender as TComboBox).ItemIndex;
end;
procedure TWidthParam.ChangeWidth(Sender: TObject);
begin
AWidth := (Sender as TSpinEdit).Value;
end;
procedure TRoundingRadiusParamX.CreateObjects(Panel: TPanel);
var
RoundingRadiusLabel: TLabel;
RoundingRadiusX: TSpinEdit;
begin
RoundingRadiusLabel := TLabel.Create(Panel);
RoundingRadiusLabel.Caption := 'Радиус округления X';
RoundingRadiusLabel.Top := 200;
RoundingRadiusLabel.Parent := Panel;
RoundingRadiusX := TSpinEdit.Create(Panel);
RoundingRadiusX.Top := 220;
RoundingRadiusX.MinValue := 0;
RoundingRadiusX.Parent := Panel;
RoundingRadiusX.Value := ARadiusX;
RoundingRadiusX.OnChange := @ChangeRoundX;
end;
procedure TRoundingRadiusParamX.ChangeRoundX(Sender: TObject);
begin
ARadiusX := (Sender as TSpinEdit).Value;
end;
procedure TRoundingRadiusParamY.CreateObjects(Panel: TPanel);
var
RoundingRadiusLabel: TLabel;
RoundingRadiusY: TSpinEdit;
begin
RoundingRadiusLabel := TLabel.Create(Panel);
RoundingRadiusLabel.Caption := 'Радиус округления Y';
RoundingRadiusLabel.Top := 240;
RoundingRadiusLabel.Parent :=Panel;
RoundingRadiusY := TSpinEdit.Create(Panel);
RoundingRadiusY.Top := 260;
RoundingRadiusY.MinValue := 0;
RoundingRadiusY.Parent := Panel;
RoundingRadiusY.Value := ARadiusY;
RoundingRadiusY.OnChange := @ChangeRoundY;
end;
procedure TRoundingRadiusParamY.ChangeRoundY(Sender: TObject);
begin
ARadiusY := (Sender as TSpinEdit).Value;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, NtBase;
type
TForm1 = class(TForm)
LanguageGroup: TGroupBox;
NameGroup: TGroupBox;
NativeRadio: TRadioButton;
LocalizedRadio: TRadioButton;
EnglishRadio: TRadioButton;
SystemRadio: TRadioButton;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure NameRadioChange(Sender: TObject);
private
FUpdating: Boolean;
FLanguages: TNtLanguages;
FRadioButtons: array of TRadioButton;
function GetLanguageName: TNtLanguageName;
procedure UpdateLanguages;
procedure LanguageRadioChanged(sender: TObject);
property LanguageName: TNtLanguageName read GetLanguageName;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
NtBaseTranslator,
NtResource,
NtResourceString,
FMX.NtTranslator;
function TForm1.GetLanguageName: TNtLanguageName;
begin
if NativeRadio.IsChecked then
Result := lnNative
else if LocalizedRadio.IsChecked then
Result := lnLocalized
else if EnglishRadio.IsChecked then
Result := lnEnglish
else
Result := lnSystem
end;
procedure TForm1.UpdateLanguages;
var
i: Integer;
locale: String;
language: TNtLanguage;
radio: TRadioButton;
begin
FUpdating := True;
locale := TNtBase.GetActiveLocale;
if locale = '' then
locale := OriginalLanguage;
for i := 0 to FLanguages.Count - 1 do
begin
language := FLanguages[i];
radio := FRadioButtons[i];
radio.Text := language.Names[LanguageName];
radio.IsChecked := language.Code = locale;
end;
FUpdating := False;
end;
procedure TForm1.LanguageRadioChanged(sender: TObject);
var
language: TNtLanguage;
radio: TRadioButton;
begin
if FUpdating then
Exit;
radio := sender as TRadioButton;
if not radio.IsChecked then
Exit;
language := radio.TagObject as TNtLanguage;
TNtTranslator.SetNew(language.Code);
UpdateLanguages;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i, radioWidth: Integer;
radio: TRadioButton;
language: TNtLanguage;
resourcestring
SEnglish = 'English';
SFinnish = 'Finnish';
SGerman = 'German';
SFrench = 'French';
SJapanese = 'Japanese';
begin
NtResources.Add('English', 'English', SEnglish, 'en');
NtResources.Add('Finnish', 'suomi', SFinnish, 'fi');
NtResources.Add('German', 'Deutsch', SGerman, 'de');
NtResources.Add('French', 'français', SFrench, 'fr');
NtResources.Add('Japanese', '日本語', SJapanese, 'ja');
_T(Self);
FLanguages := TNtLanguages.Create;
FLanguages.Add('en', 9);
TNtBase.GetAvailable(FLanguages);
SetLength(FRadioButtons, FLanguages.Count);
radioWidth := Round((LanguageGroup.Width - 16)/FLanguages.Count) - 8;
for i := 0 to FLanguages.Count - 1 do
begin
language := FLanguages[i];
radio := TRadioButton.Create(Self);
radio.Parent := LanguageGroup;
radio.TagObject := language;
radio.Width := radioWidth;
radio.Position.Y := 24;
radio.Position.X := 8 + i*radioWidth;
radio.OnChange := LanguageRadioChanged;
FRadioButtons[i] := radio;
end;
NativeRadio.IsChecked := True;
UpdateLanguages;
end;
procedure TForm1.NameRadioChange(Sender: TObject);
begin
UpdateLanguages;
end;
initialization
NtEnabledProperties := STRING_TYPES;
end.
|
{
Copyright (c) 2016, Vencejo Software
Distributed under the terms of the Modified BSD License
The full license is distributed with this software
}
unit ooConfigSectionMock;
interface
uses
ooTextKey,
ooDataInput.Intf, ooDataOutput.Intf,
ooConfig.Intf;
type
TConfigSectionMock = class sealed(TInterfacedObject, IConfigSection)
strict private
const
INTEGER_KEY = 'IntegerKey';
STRING_KEY = 'StringKey';
BOOLEAN_KEY = 'BooleanKey';
FLOAT_KEY = 'FloatKey';
DATETIME_KEY = 'DateTimeKey';
public
ValueInteger: Longint;
ValueString: string;
ValueBoolean: Boolean;
ValueFloat: Extended;
ValueDateTime: TDateTime;
function Marshal(const DataOutput: IDataOutput): Boolean;
function Unmarshal(const DataInput: IDataInput): Boolean;
function Name: String;
function Description: String;
class function New: IConfigSection;
end;
implementation
function TConfigSectionMock.Name: String;
begin
Result := 'SECTION_ONE';
end;
function TConfigSectionMock.Description: String;
begin
Result := 'Config mock';
end;
function TConfigSectionMock.Unmarshal(const DataInput: IDataInput): Boolean;
begin
ValueInteger := DataInput.ReadInteger(TTextKey.New(INTEGER_KEY));
ValueString := DataInput.ReadString(TTextKey.New(STRING_KEY));
ValueBoolean := DataInput.ReadBoolean(TTextKey.New(BOOLEAN_KEY));
ValueFloat := DataInput.ReadFloat(TTextKey.New(FLOAT_KEY));
ValueDateTime := DataInput.ReadDateTime(TTextKey.New(DATETIME_KEY));
Result := True;
end;
function TConfigSectionMock.Marshal(const DataOutput: IDataOutput): Boolean;
begin
DataOutput.WriteInteger(TTextKey.New(INTEGER_KEY), ValueInteger);
DataOutput.WriteString(TTextKey.New(STRING_KEY), ValueString);
DataOutput.WriteBoolean(TTextKey.New(BOOLEAN_KEY), ValueBoolean);
DataOutput.WriteFloat(TTextKey.New(FLOAT_KEY), ValueFloat);
DataOutput.WriteDateTime(TTextKey.New(DATETIME_KEY), ValueDateTime);
Result := True;
end;
class function TConfigSectionMock.New: IConfigSection;
begin
Result := TConfigSectionMock.Create;
end;
end.
|
unit UDOLAPCubes;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32;
type
TCrpeOLAPCubesDlg = class(TForm)
pnlOLAPCubes: TPanel;
lblNumber: TLabel;
lbNumbers: TListBox;
editCount: TEdit;
lblCount: TLabel;
gbFormat: TGroupBox;
btnBorder: TButton;
btnFormat: TButton;
editTop: TEdit;
lblTop: TLabel;
lblLeft: TLabel;
editLeft: TEdit;
lblSection: TLabel;
editWidth: TEdit;
lblWidth: TLabel;
lblHeight: TLabel;
editHeight: TEdit;
cbSection: TComboBox;
btnOk: TButton;
btnClear: TButton;
rgUnits: TRadioGroup;
btnTest: TButton;
lblServerName: TLabel;
lblDatabaseName: TLabel;
lblUserID: TLabel;
lblPassword: TLabel;
editServerName: TEdit;
editDatabaseName: TEdit;
editUserID: TEdit;
editPassword: TEdit;
lblCubeName: TLabel;
editCubeName: TEdit;
lblConnectionString: TLabel;
editConnectionString: TEdit;
procedure btnClearClick(Sender: TObject);
procedure lbNumbersClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure UpdateOLAPCubes;
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure editSizeEnter(Sender: TObject);
procedure editSizeExit(Sender: TObject);
procedure cbSectionChange(Sender: TObject);
procedure btnBorderClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure rgUnitsClick(Sender: TObject);
procedure btnFormatClick(Sender: TObject);
procedure editServerNameChange(Sender: TObject);
procedure editDatabaseNameChange(Sender: TObject);
procedure editCubeNameChange(Sender: TObject);
procedure editUserIDChange(Sender: TObject);
procedure editPasswordChange(Sender: TObject);
procedure editConnectionStringChange(Sender: TObject);
procedure btnTestClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
OlapIndex : smallint;
PrevSize : string;
end;
var
CrpeOLAPCubesDlg: TCrpeOLAPCubesDlg;
bOLAPCubes : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl, UDBorder, UDFormat;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.FormCreate(Sender: TObject);
begin
bOLAPCubes := True;
LoadFormPos(Self);
btnOk.Tag := 1;
OlapIndex := -1;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.FormShow(Sender: TObject);
begin
UpdateOLAPCubes;
end;
{------------------------------------------------------------------------------}
{ UpdateOLAPCubes }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.UpdateOLAPCubes;
var
OnOff : boolean;
i : integer;
begin
OlapIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
OnOff := False
else
begin
OnOff := (Cr.OLAPCubes.Count > 0);
{Get OLAPCubes Index}
if OnOff then
begin
if Cr.OLAPCubes.ItemIndex > -1 then
OlapIndex := Cr.OLAPCubes.ItemIndex
else
OlapIndex := 0;
end
else
OlapIndex := -1;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff then
begin
{Fill Section ComboBox}
cbSection.Clear;
cbSection.Items.AddStrings(Cr.SectionFormat.Names);
{Fill Numbers ListBox}
for i := 0 to Cr.OLAPCubes.Count - 1 do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Cr.OLAPCubes.Count);
lbNumbers.ItemIndex := OlapIndex;
lbNumbersClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.lbNumbersClick(Sender: TObject);
var
OnOff : Boolean;
begin
OlapIndex := lbNumbers.ItemIndex;
OnOff := (Cr.OLAPCubes[OlapIndex].Handle <> 0);
btnBorder.Enabled := OnOff;
btnFormat.Enabled := OnOff;
editServerName.Text := Cr.OLAPCubes.Item.ServerName;
editDatabaseName.Text := Cr.OLAPCubes.Item.DatabaseName;
editUserID.Text := Cr.OLAPCubes.Item.UserID;
editPassword.Text := Cr.OLAPCubes.Item.Password;
editCubeName.Text := Cr.OLAPCubes.Item.CubeName;
editConnectionString.Text := Cr.OLAPCubes.Item.ConnectionString;
cbSection.ItemIndex := cbSection.Items.IndexOf(Cr.OLAPCubes.Item.Section);
rgUnitsClick(Self);
end;
{------------------------------------------------------------------------------}
{ editServerNameChange }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.editServerNameChange(Sender: TObject);
begin
Cr.OLAPCubes.Item.ServerName := editServerName.Text;
end;
{------------------------------------------------------------------------------}
{ editDatabaseNameChange }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.editDatabaseNameChange(Sender: TObject);
begin
Cr.OLAPCubes.Item.DatabaseName := editDatabaseName.Text;
end;
{------------------------------------------------------------------------------}
{ editCubeNameChange }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.editCubeNameChange(Sender: TObject);
begin
Cr.OLAPCubes.Item.CubeName := editCubeName.Text;
end;
{------------------------------------------------------------------------------}
{ editUserIDChange }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.editUserIDChange(Sender: TObject);
begin
Cr.OLAPCubes.Item.UserID := editUserID.Text;
end;
{------------------------------------------------------------------------------}
{ editPasswordChange }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.editPasswordChange(Sender: TObject);
begin
Cr.OLAPCubes.Item.Password := editPassword.Text;
end;
{------------------------------------------------------------------------------}
{ editConnectionStringChange }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.editConnectionStringChange(Sender: TObject);
begin
Cr.OLAPCubes.Item.ConnectionString := editConnectionString.Text;
end;
{------------------------------------------------------------------------------}
{ btnTestClick }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.btnTestClick(Sender: TObject);
begin
if Cr.OLAPCubes.Item.Test then
MessageDlg('Connection Succeeded!', mtInformation, [mbOk], 0)
else
MessageDlg('Connection Failed.' + Chr(10) + Cr.LastErrorString, mtError, [mbOk], 0);
end;
{------------------------------------------------------------------------------}
{ rgUnitsClick }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.rgUnitsClick(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
editTop.Text := TwipsToInchesStr(Cr.OLAPCubes.Item.Top);
editWidth.Text := TwipsToInchesStr(Cr.OLAPCubes.Item.Width);
editLeft.Text := TwipsToInchesStr(Cr.OLAPCubes.Item.Left);
editHeight.Text := TwipsToInchesStr(Cr.OLAPCubes.Item.Height);
end
else {twips}
begin
editTop.Text := IntToStr(Cr.OLAPCubes.Item.Top);
editWidth.Text := IntToStr(Cr.OLAPCubes.Item.Width);
editLeft.Text := IntToStr(Cr.OLAPCubes.Item.Left);
editHeight.Text := IntToStr(Cr.OLAPCubes.Item.Height);
end;
end;
{------------------------------------------------------------------------------}
{ editSizeEnter }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.editSizeEnter(Sender: TObject);
begin
if Sender is TEdit then
PrevSize := TEdit(Sender).Text;
end;
{------------------------------------------------------------------------------}
{ editSizeExit }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.editSizeExit(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
if not IsFloating(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.OLAPCubes.Item.Top := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editWidth' then
Cr.OLAPCubes.Item.Width := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.OLAPCubes.Item.Left := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editHeight' then
Cr.OLAPCubes.Item.Height := InchesStrToTwips(TEdit(Sender).Text);
UpdateOLAPCubes; {this will truncate any decimals beyond 3 places}
end;
end
else {twips}
begin
if not IsNumeric(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.OLAPCubes.Item.Top := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editWidth' then
Cr.OLAPCubes.Item.Width := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.OLAPCubes.Item.Left := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editHeight' then
Cr.OLAPCubes.Item.Height := StrToInt(TEdit(Sender).Text);
end;
end;
end;
{------------------------------------------------------------------------------}
{ cbSectionChange }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.cbSectionChange(Sender: TObject);
begin
Cr.OLAPCubes.Item.Section := cbSection.Items[cbSection.ItemIndex];
end;
{------------------------------------------------------------------------------}
{ btnBorderClick }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.btnBorderClick(Sender: TObject);
begin
CrpeBorderDlg := TCrpeBorderDlg.Create(Application);
CrpeBorderDlg.Border := Cr.OLAPCubes.Item.Border;
CrpeBorderDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnFormatClick }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.btnFormatClick(Sender: TObject);
begin
CrpeFormatDlg := TCrpeFormatDlg.Create(Application);
CrpeFormatDlg.Format := Cr.OLAPCubes.Item.Format;
CrpeFormatDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.btnClearClick(Sender: TObject);
begin
Cr.OLAPCubes.Clear;
UpdateOLAPCubes;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.btnOkClick(Sender: TObject);
begin
rgUnits.ItemIndex := 1; {change to twips to avoid the UpdateOLAPCubes call}
if (not IsStrEmpty(Cr.ReportName)) and (OlapIndex > -1) then
begin
editSizeExit(editTop);
editSizeExit(editWidth);
editSizeExit(editLeft);
editSizeExit(editHeight);
end;
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeOLAPCubesDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bOLAPCubes := False;
Release;
end;
end.
|
(*
Category: SWAG Title: FILE HANDLING ROUTINES
Original name: 0029.PAS
Description: Check if IS File
Author: MARTIN RICHARDSON
Date: 09-26-93 09:11
*)
uses Dos;
{*****************************************************************************
* Function ...... IsFile()
* Purpose ....... Checks for the existance of a file
* Parameters .... sFile File to check for
* Returns ....... TRUE if sFile exists
* Notes ......... None
* Author ........ Martin Richardson
* Date .......... May 13, 1992
*****************************************************************************}
{ Checks for existance of a file }
FUNCTION IsFile( sFile: STRING ): BOOLEAN;
VAR s : SearchRec;
BEGIN
FINDFIRST( sFile, directory, s );
IsFile := (DOSError = 0) AND
(s.Attr AND Directory <> Directory) AND
(POS( '?', sFile ) = 0) AND
(POS( '*', sFile ) = 0);
END;
BEGIN
if IsFile('CheckIfIsFile.pas') then
WriteLn('CheckIfIsFile.pas is a valid file')
else
WriteLn('CheckIfIsFile.pas is not a valid file (or not found)');
if IsFile('1.pas') then
WriteLn('1.pas is a valid file')
else
WriteLn('1.pas is not a valid file (or not found)');
if IsFile('*.pas') then
WriteLn('*.pas is a valid file')
else
WriteLn('*.pas is not a valid file (or not found)');
END.
|
object frmAddToForm: TfrmAddToForm
Left = 267
Top = 162
HelpContext = 2000
BorderStyle = bsDialog
BorderWidth = 8
Caption = 'Add file/folder to AceBackup project'
ClientHeight = 509
ClientWidth = 510
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
OnCreate = FormCreate
DesignSize = (
510
509)
PixelsPerInch = 96
TextHeight = 13
object Bevel1: TBevel
Left = 0
Top = 476
Width = 510
Height = 33
Align = alBottom
Shape = bsSpacer
end
object btnOk: TButton
Left = 260
Top = 484
Width = 80
Height = 24
Anchors = [akRight, akBottom]
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 0
end
object btnCancel: TButton
Left = 344
Top = 484
Width = 80
Height = 24
Anchors = [akRight, akBottom]
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 1
end
object btnHelp: TButton
Left = 428
Top = 484
Width = 80
Height = 24
Anchors = [akRight, akBottom]
Caption = '&Help'
TabOrder = 2
OnClick = btnHelpClick
end
object PageControl: TPageControl
Left = 0
Top = 0
Width = 510
Height = 476
ActivePage = TabSheet1
Align = alClient
TabOrder = 3
object TabSheet1: TTabSheet
Caption = 'Project'
DesignSize = (
502
448)
object lblError: TLabel
Tag = 1
AlignWithMargins = True
Left = 12
Top = 192
Width = 478
Height = 13
Margins.Left = 12
Margins.Top = 4
Margins.Right = 12
Margins.Bottom = 4
Align = alTop
Caption = 'lblProjectInfo'
Transparent = True
Visible = False
WordWrap = True
end
object Label1: TLabel
AlignWithMargins = True
Left = 12
Top = 68
Width = 478
Height = 13
Margins.Left = 12
Margins.Top = 4
Margins.Right = 12
Margins.Bottom = 4
Align = alTop
Caption = '&Project Name:'
FocusControl = cbProject
Transparent = True
end
object lblVolume: TLabel
AlignWithMargins = True
Left = 12
Top = 146
Width = 478
Height = 13
Margins.Left = 12
Margins.Top = 4
Margins.Right = 12
Margins.Bottom = 4
Align = alTop
Caption = '&Volume:'
FocusControl = cbVolumes
Transparent = True
end
object lblEncryption: TLabel
Tag = 2
AlignWithMargins = True
Left = 12
Top = 234
Width = 478
Height = 13
Margins.Left = 12
Margins.Top = 4
Margins.Right = 12
Margins.Bottom = 4
Align = alTop
Caption = 'lblEncryption'
Transparent = True
WordWrap = True
end
object lblSchedule: TLabel
Tag = 2
AlignWithMargins = True
Left = 12
Top = 255
Width = 478
Height = 13
Margins.Left = 12
Margins.Top = 4
Margins.Right = 12
Margins.Bottom = 4
Align = alTop
Caption = 'lblSchedule'
Transparent = True
WordWrap = True
end
object lblCompression: TLabel
Tag = 2
AlignWithMargins = True
Left = 12
Top = 213
Width = 478
Height = 13
Margins.Left = 12
Margins.Top = 4
Margins.Right = 12
Margins.Bottom = 4
Align = alTop
Caption = 'lblCompression'
Transparent = True
WordWrap = True
end
object btnOpen: TButton
Left = 204
Top = 120
Width = 92
Height = 24
Anchors = [akTop, akRight]
Caption = '&Open...'
TabOrder = 1
OnClick = btnOpenClick
end
object btnNew: TButton
Left = 300
Top = 120
Width = 92
Height = 24
Anchors = [akTop, akRight]
Caption = '&New...'
TabOrder = 2
OnClick = btnNewClick
end
object btnSettings: TButton
Left = 396
Top = 120
Width = 92
Height = 24
Anchors = [akTop, akRight]
Caption = '&Settings...'
TabOrder = 3
OnClick = btnSettingsClick
end
object cbProject: TComboBox
AlignWithMargins = True
Left = 12
Top = 85
Width = 478
Height = 21
Margins.Left = 12
Margins.Top = 0
Margins.Right = 12
Margins.Bottom = 36
Align = alTop
Style = csDropDownList
TabOrder = 0
OnChange = cbProjectChange
end
object chkProcessNow: TCheckBox
AlignWithMargins = True
Left = 12
Top = 423
Width = 478
Height = 17
Margins.Left = 12
Margins.Top = 4
Margins.Right = 12
Margins.Bottom = 8
Align = alBottom
Caption = 'Process project immediately'
TabOrder = 5
end
object cbVolumes: TComboBox
AlignWithMargins = True
Left = 12
Top = 163
Width = 478
Height = 21
Margins.Left = 12
Margins.Top = 0
Margins.Right = 12
Margins.Bottom = 4
Align = alTop
Style = csDropDownList
TabOrder = 4
OnChange = cbVolumesChange
end
object Panel1: TPanel
AlignWithMargins = True
Left = 12
Top = 12
Width = 478
Height = 48
Margins.Left = 12
Margins.Top = 12
Margins.Right = 12
Margins.Bottom = 4
Align = alTop
BevelOuter = bvNone
TabOrder = 6
object Image1: TImage
Left = 0
Top = 0
Width = 32
Height = 48
Align = alLeft
AutoSize = True
Center = True
end
object lblFileName: TLabel
AlignWithMargins = True
Left = 52
Top = 4
Width = 422
Height = 40
Margins.Left = 20
Margins.Top = 4
Margins.Right = 4
Margins.Bottom = 4
Align = alClient
AutoSize = False
Caption = '........'
EllipsisPosition = epPathEllipsis
Layout = tlCenter
end
end
end
end
object OpenDialog: TOpenDialog
Filter = 'AceBackup projects (*.nsb)|*.nsb|All Files (*.*)|*.*'
Options = [ofHideReadOnly, ofFileMustExist, ofEnableSizing]
Left = 140
Top = 304
end
end
|
(*
Category: SWAG Title: SORTING ROUTINES
Original name: 0007.PAS
Description: COUNT1.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:57
*)
{
...Well, as Greg Vigneault reminded me, there is a much faster
method of sorting this sort of data called a "Count" sort. I
often overlook this method, as it doesn't appear to be a sort
at all at first glance:
}
Program Count_Sort_Demo;
Const
co_MaxItem = 200;
Type
byar_MaxItem = Array[1..co_MaxItem] of Byte;
byar_256 = Array[0..255] of Byte;
Var
by_Index : Byte;
wo_Index : Word;
DataBuffer : byar_MaxItem;
SortTable : byar_256;
begin
(* Initialize the pseudo-random number generator. *)
randomize;
(* Clear the CountSort table. *)
fillChar(SortTable, sizeof(SortTable), 0);
(* Create random Byte data. *)
For wo_Index := 1 to co_MaxItem do
DataBuffer[wo_Index] := random(256);
(* Display random data. *)
Writeln;
Writeln('RANDOM Byte DATA');
For wo_Index := 1 to co_MaxItem do
Write(DataBuffer[wo_Index]:4);
(* CountSort the random data. *)
For wo_Index := 1 to co_MaxItem do
inc(SortTable[DataBuffer[wo_Index]]);
(* Display the CountSorted data. *)
Writeln;
Writeln('COUNTSORTED Byte DATA');
For by_Index := 0 to 255 do
if (SortTable[by_Index] > 0) then
For wo_Index := 1 to SortTable[by_Index] do
Write(by_Index:4)
end.
{
...This Type of sort is EXTEMELY fast, even when compared to
QuickSort, as there is so little data manipulation being done.
>BTW, why are there so many different sorting methods?
>Quick, bubble, Radix.. etc, etc
...Because, Not all data is created equally.
(ie: Some Types of sorts perform well on data that is very
random, While other Types of sorts perform well on data
that is "semi-sorted" or "almost sorted".)
}
|
unit uFormSelectDuplicateDirectories;
interface
uses
Generics.Collections,
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.StdCtrls,
Vcl.Imaging.pngimage,
Vcl.ExtCtrls,
Dmitry.Utils.Files,
Dmitry.Utils.System,
Dmitry.PathProviders,
Dmitry.PathProviders.MyComputer,
uDBForm,
uMemory,
uFormInterfaces,
uVCLHelpers;
type
TFormSelectDuplicateDirectories = class(TDBForm, IFormSelectDuplicateDirectories)
ImMain: TImage;
LbInfo: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FSelectedFolder: string;
procedure SelectDirectoryClick(Sender: TObject);
procedure CancelDirectoriesSeletion(Sender: TObject);
protected
function GetFormID: string; override;
procedure InterfaceDestroyed; override;
public
{ Public declarations }
function Execute(DirectoriesInfo: TList<string>): string;
end;
var
FormSelectDuplicateDirectories: TFormSelectDuplicateDirectories;
implementation
{$R *.dfm}
{ TFormSelectDuplicateDirectories }
procedure TFormSelectDuplicateDirectories.CancelDirectoriesSeletion(
Sender: TObject);
begin
Close;
end;
function TFormSelectDuplicateDirectories.Execute(
DirectoriesInfo: TList<string>): string;
const
Padding = 7;
var
I: Integer;
TopHeight: Integer;
Button: TButton;
Folder: string;
begin
FSelectedFolder := '';
DirectoriesInfo.Add('');
TopHeight := ImMain.BoundsRect.Bottom + Padding;
for I := 0 to DirectoriesInfo.Count - 1 do
begin
Folder := DirectoriesInfo[I];
Button := TButton.Create(Self);
Button.Parent := Self;
Button.OnClick := SelectDirectoryClick;
Button.Left := Padding;
Button.Top := TopHeight;
Button.Width := ClientWidth - Padding * 2;
if IsWindowsVista then
begin
Button.Style := bsCommandLink;
Button.Caption := ExtractFileName(Folder);
if IsDrive(Folder) then
Button.Caption := GetCDVolumeLabelEx(UpCase(Folder[1])) + ' (' + Folder[1] + ':)';
end else
begin
Button.Style := bsPushButton;
Button.Caption := Folder;
end;
Button.CommandLinkHint := Folder;
if I = DirectoriesInfo.Count - 1 then
begin
if IsWindowsVista then
begin
Button.Caption := L('Cancel');
Button.CommandLinkHint := L('Cancel pending operation');
end else
begin
Button.Caption := L('Cancel pending operation');
Button.CommandLinkHint := L('');
end;
Button.OnClick := CancelDirectoriesSeletion;
end;
Button.AdjustButtonHeight;
Inc(TopHeight, Button.Height + Padding);
end;
ClientHeight := TopHeight;
ShowModal;
Result := FSelectedFolder;
end;
procedure TFormSelectDuplicateDirectories.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TFormSelectDuplicateDirectories.FormCreate(Sender: TObject);
begin
Caption := L('Select directory with originals');
LbInfo.Caption := L('Please select directory with original photos. Duplicate photos from other directories will be deleted.');
end;
procedure TFormSelectDuplicateDirectories.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
function TFormSelectDuplicateDirectories.GetFormID: string;
begin
Result := 'DuplicatesSelectDirectory';
end;
procedure TFormSelectDuplicateDirectories.InterfaceDestroyed;
begin
inherited;
Release;
end;
procedure TFormSelectDuplicateDirectories.SelectDirectoryClick(Sender: TObject);
begin
FSelectedFolder := TButton(Sender).CommandLinkHint;
Close;
end;
initialization
FormInterfaces.RegisterFormInterface(IFormSelectDuplicateDirectories, TFormSelectDuplicateDirectories);
end.
|
unit OTFEBestCryptBytesToString_U;
// Description: Transforms bytes array to human readable form string
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// Basically, a port of Jetico's "byte2string.cpp" file - contact Jetico
// for further detail/a copy of this file, which at time of writing, does
// not appear in the BestCrypt BDK
//
interface
uses
HashValue_U,
HashAlg_U;
function SE_EncodeString(var str: string; var written: integer; bf: THashArray; bfSize: integer): boolean;
function SE_DecodeString(var buffer: THashArray; var written: integer; var str: string): boolean;
implementation
const
// SE_bitsForDecoding by char from codeTable[ 1 << SE_bitsForDecoding ]
SE_bitsForDecoding = 5;
codeTable: array [0..32] of char = (
'1','2','3','4','5','6','7','8','9','Q',
'W','E','R','T','Y','P','A','S','D','F',
'G','H','J','K','L','Z','X','C','V','B',
'N','M',
#0 // Add in an extra #0 as getCode(...)
// uses this to tell if it's run off
// the end of the array
);
// Forward function/procedure definitions
procedure setBits(var buff: THashArray; bitStart: integer; value: integer; valueBitSize: integer); forward;
function getBits(buff: THashArray; bitStart: integer; valueBitSize: integer): integer; forward;
function extend(var extBuff: string; var written: integer; buff: THashArray; buffSize: integer): boolean; forward;
function getCode(symbol: char): integer; forward;
function compact(var buff: THashArray; var written: integer; const extBuff: string; extBuffSize: integer): boolean; forward;
// Function/procedure implementations
procedure setBits(var buff: THashArray; bitStart: integer; value: integer; valueBitSize: integer);
var
leftPos, rightPos: integer;
byteNum, bitNum: integer;
mask: integer;
tmp: integer;
begin
assert(valueBitSize <= 8);
byteNum := (bitStart div 8);
bitNum := (bitStart mod 8);
// left = buff + byteNum;
leftPos := byteNum;
// right = left + 1;
rightPos := leftPos + 1;
mask := $FF shr (8 - valueBitSize);
value := value and mask;
tmp := buff[leftPos] or ( buff[rightPos] shl 8 );
tmp := tmp and (not( mask shl bitNum ));
tmp := tmp or (value shl bitNum);
buff[leftPos] := byte(tmp);
buff[rightPos] := byte(( tmp shr 8 ));
end;
function getBits(buff: THashArray; bitStart: integer; valueBitSize: integer): integer;
var
byteNum, bitNum: integer;
left, right: byte;
mask: byte;
value: integer;
begin
assert(valueBitSize<=8);
byteNum := (bitStart div 8);
bitNum := (bitStart mod 8);
left := buff[byteNum];
right := buff[byteNum+1];
mask := $FF shr (8 - valueBitSize);
value := ( ( ( left or ( right shl 8) ) shr bitNum ) and mask );
Result:= value;
end;
// extBuff - will be set to the coded version of the hash
// written - this will be set to the length of extBuff
// buff - set this to the hash digest to be coded
// buffSize - set this to the digest size in bytes
function extend(var extBuff: string; var written: integer; buff: THashArray; buffSize: integer): boolean;
var
last: integer;
bit: integer;
value: integer;
begin
last := ((buffSize * 8) div SE_bitsForDecoding) + 1;
// increment last; required as the original code was written in C, which
// indexes from 0. Delphi indexes from 1
inc(last);
if (last > written) then
begin
written := last;
Result := FALSE;
exit;
end;
dec(last);
// The BestCrypt C version of this function sets #0 to be the end of the
// coded hash.
// We just initialize the buffer to contain the required number of chars
// extBuff[last] := #0; // EOF.
extBuff := StringOfChar('.', last-1);
bit := 0;
while (bit<buffSize * 8) do
begin
value := getBits(buff, bit, SE_bitsForDecoding);
if ( (value > sizeof(codeTable)) or
(value < 0 ) ) then
begin
Result := FALSE;
exit;
end;
dec(last);
extBuff[last] := codeTable[value];
inc(bit, SE_bitsForDecoding);
end;
// This loop terminates at 1, as Delphi indexes from 1, as opposed to 0,
// which C indexes from
while(last<>1) do
begin
dec(last);
extBuff[last] := codeTable[0];
end;
Result:= TRUE;
end;
function getCode(symbol: char): integer;
var
ch: char;
i: integer;
begin
i := 0;
while (TRUE) do
begin
ch := codeTable[i];
if (ch=#0) then // Not found...
begin
break;
end;
if (ch=symbol) then // Found...
begin
Result := i;
exit;
end;
inc(i);
end;
Result := -1;
end;
function compact(var buff: THashArray; var written: integer; const extBuff: string; extBuffSize: integer): boolean;
var
bit: integer;
last: integer;
value: integer;
sizeRequired: integer;
begin
sizeRequired := ( extBuffSize * SE_bitsForDecoding) div 8;
if (sizeRequired > written) then
begin
written := sizeRequired;
Result := FALSE;
exit;
end;
last := extBuffSize;
bit := 0;
while (bit < extBuffSize*5) do
begin
dec(last);
value := getCode(extBuff[last+1]);
if ( value = -1 ) then
begin
Result := FALSE;
exit;
end;
setBits(buff, bit, value, SE_bitsForDecoding);
inc(bit, SE_bitsForDecoding);
end;
Result := TRUE;
end;
function SE_EncodeString(var str: string; var written: integer; bf: THashArray; bfSize: integer): boolean;
begin
Result := extend(str, written, bf, bfSize);
end;
function SE_DecodeString(var buffer: THashArray; var written: integer; var str: string): boolean;
begin
Result := compact(buffer, written, str, length(str));
end;
END.
|
unit Odontologia.Controlador.Interfaces;
interface
uses
Odontologia.Controlador.Agenda.Interfaces,
Odontologia.Controlador.Ciudad.Interfaces,
Odontologia.Controlador.Departamento.Interfaces,
Odontologia.Controlador.Empresa.Interfaces,
Odontologia.Controlador.EmpresaTipo.Interfaces,
Odontologia.Controlador.Estado.Interfaces,
Odontologia.Controlador.Estado.Cita.Interfaces,
Odontologia.Controlador.Medico.Interfaces,
Odontologia.Controlador.Paciente.Interfaces,
Odontologia.Controlador.Pais.Interfaces,
Odontologia.Controlador.Pedido.Interfaces,
Odontologia.Controlador.Producto.Interfaces,
Odontologia.Controlador.Usuario.Interfaces;
type
iController = interface
['{2ED23A69-9FB5-4B6A-936D-075F0A044F80}']
function Agenda : iControllerAgenda;
function Ciudad : iControllerCiudad;
function Departamento : iControllerDepartamento;
function Empresa : iControllerEmpresa;
function EmpresaTipo : iControllerEmpresaTipo;
function Estado : iControllerEstado;
function EstadoCita : iControllerEstadoCita;
function Medico : iControllerMedico;
function Paciente : iControllerPaciente;
function Pais : iControllerPais;
function pedido : icontrollerpedido;
function pedidoItem : icontrollerpedidoitem;
function Producto : iControllerProducto;
function Usuario : iControllerUsuario;
end;
implementation
end.
|
unit Produto;
interface
Type
TProduto = class
private
FTipo: String;
FNome: String;
FPreco: real;
FTotal: integer;
procedure setNome(const Value: String);
procedure setPreco(const Value: real);
procedure setTipo(const Value: String);
procedure SetTotal(const Value: integer);
protected
{ protected declarations }
public
{ public declarations }
property Tipo: String read FTipo write setTipo;
property Nome: String read FNome write setNome;
property Preco: real read FPreco write setPreco;
property Total : integer read FTotal write SetTotal;
published
{ published declarations }
end;
implementation
procedure TProduto.setNome(const Value: String);
begin
FNome := Value;
end;
procedure TProduto.setPreco(const Value: Real);
begin
FPreco := Value;
end;
procedure TProduto.setTipo(const Value: String);
begin
FTipo := Value;
end;
procedure TProduto.SetTotal(const Value: integer);
begin
FTotal := Value;
end;
end. |
unit UnitFormMain;
{===============================================================================
CodeRage 9 - Demo for Parallel Future
This code shows how to use the parallel function Future.
If you click on the Get button immediately after the Start Button the GUI
will freeze for 3 seconds; the time it takes to get the string result from the
Future. If you wait 3 seconds between clikcing Start and Get you'll get the
string back immediately.
Author: Danny Wind
===============================================================================}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Threading,
FMX.StdCtrls;
type
TFormMain = class(TForm)
ButtonStart: TButton;
ButtonGet: TButton;
procedure ButtonStartClick(Sender: TObject);
procedure ButtonGetClick(Sender: TObject);
private
{ Private declarations }
FutureString: IFuture<string>;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
procedure TFormMain.ButtonGetClick(Sender: TObject);
begin
ButtonGet.Text := FutureString.Value;
end;
procedure TFormMain.ButtonStartClick(Sender: TObject);
begin
FutureString := TTask.Future<string>(
function:string
begin
{Some calculation that takes time}
Sleep(3000);
Result := 'Hello CodeRage 9 ' + Random(42).ToString;
end);
end;
end.
|
unit OTFECrossCrypt_PasswordConfirm;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls;
type
TOTFECrossCrypt_PasswordConfirm_F = class(TForm)
lblMultipleKeyMode: TLabel;
rePasswords: TRichEdit;
lblPasswordCount: TLabel;
pbCancel: TButton;
pbOK: TButton;
Label2: TLabel;
Label1: TLabel;
pbLoadFromFile: TButton;
OpenKeyfileDlg: TOpenDialog;
procedure FormShow(Sender: TObject);
procedure rePasswordsChange(Sender: TObject);
procedure pbCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure pbOKClick(Sender: TObject);
procedure pbLoadFromFileClick(Sender: TObject);
private
FMultipleKey: boolean;
FPasswords: TStringList;
procedure ClearPasswords();
procedure UpdatePasswordCount();
procedure WipeGUI();
procedure WipeInternal();
public
property MultipleKey: boolean read FMultipleKey write FMultipleKey;
procedure GetSinglePassword(var password: Ansistring);
procedure GetMultiplePasswords(passwords: TStringList);
// Clear down the dialog's internals...
procedure Wipe();
end;
implementation
{$R *.DFM}
uses
OTFECrossCrypt_DriverAPI;
procedure TOTFECrossCrypt_PasswordConfirm_F.FormShow(Sender: TObject);
begin
rePasswords.Lines.Clear();
rePasswords.PlainText := TRUE;
if MultipleKey then
begin
lblMultipleKeyMode.caption := '(Multiple key)';
rePasswords.WordWrap := FALSE;
end
else
begin
lblMultipleKeyMode.caption := '(Single key)';
rePasswords.WordWrap := TRUE;
end;
lblMultipleKeyMode.left := ((self.width - lblMultipleKeyMode.width) div 2);
// Mask the user's password...
SendMessage(rePasswords.Handle, EM_SETPASSWORDCHAR, Ord('*'), 0);
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.ClearPasswords();
var
i: integer;
begin
for i:=0 to (FPasswords.count-1) do
begin
FPasswords[i] := StringOfChar('X', length(FPasswords[i]));
end;
FPasswords.Clear();
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.Wipe();
begin
WipeInternal();
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.WipeGUI();
begin
// Cleardown the GUI components...
rePasswords.Text := StringOfChar('X', length(rePasswords.text));
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.WipeInternal();
begin
// Cleardown the internal store...
ClearPasswords();
FMultipleKey := FALSE;
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.UpdatePasswordCount();
begin
if (MultipleKey) then
begin
lblPasswordCount.caption := 'Passwords entered: '+inttostr(rePasswords.lines.count)+'/'+inttostr(MULTIKEY_PASSWORD_REQUIREMENT);
end
else
begin
lblPasswordCount.caption := '';
end;
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.rePasswordsChange(Sender: TObject);
begin
UpdatePasswordCount();
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.pbCancelClick(Sender: TObject);
begin
// Cleardown...
Wipe();
ModalResult := mrCancel;
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.FormCreate(Sender: TObject);
begin
FPasswords := TStringList.Create();
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
WipeGUI();
end;
// Get the single password
procedure TOTFECrossCrypt_PasswordConfirm_F.GetSinglePassword(var password: Ansistring);
begin
password := FPasswords.Text; { TODO 1 -otdk -cbug : alert user if use unicode }
// Trim off the CRLF
Delete(password, (Length(password)-1), 2);
end;
// Returns '' on failure
procedure TOTFECrossCrypt_PasswordConfirm_F.GetMultiplePasswords(passwords: TStringList);
begin
passwords.Text := StringOfChar('X', length(passwords.text));
passwords.Clear();
passwords.AddStrings(FPasswords);
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.pbOKClick(Sender: TObject);
begin
FPasswords.Clear();
FPasswords.AddStrings(rePasswords.Lines);
ModalResult := mrOK;
end;
procedure TOTFECrossCrypt_PasswordConfirm_F.pbLoadFromFileClick(
Sender: TObject);
begin
if OpenKeyfileDlg.Execute() then
begin
rePasswords.Lines.LoadFromFile(OpenKeyfileDlg.Filename);
end;
end;
END.
|
{ *********************************************************************** }
{ }
{ GUI Hangman }
{ Version 1.0 - First release of program }
{ Last Revised: 27nd of July 2004 }
{ Copyright (c) 2004 Chris Alley }
{ }
{ *********************************************************************** }
unit ULogin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UNewPlayer, UDataModule;
type
TLoginForm = class(TForm)
LoginRadioGroup: TRadioGroup;
LoginNameLabeledEdit: TLabeledEdit;
LoginLabel: TLabel;
OKButton: TButton;
CancelButton: TButton;
procedure OKButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure LoginNameLabeledEditChange(Sender: TObject);
procedure LoginNameLabeledEditEnter(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
PlayerLogin: string;
end;
implementation
{$R *.dfm}
procedure TLoginForm.OKButtonClick(Sender: TObject);
{ When the user clicks OK, this method checks to see what radio button is
selected. Depending on several factors, the method will either log the player
in, open up the New Player window, or report an error if the inputted login
in LoginNameLabeledEdit is invalid. }
var
NewPlayerDialog: TNewPlayerDialog;
begin
if Self.LoginRadioGroup.ItemIndex = 0 then
begin
if HangmanDataModule.CheckIfLoginExistsInDatabase(
Self.LoginNameLabeledEdit.Text) = True then
begin
PlayerLogin := Self.LoginNameLabeledEdit.Text;
Self.ModalResult := mrOK;
end
else
ShowMessage('Login not found.');
end;
if Self.LoginRadioGroup.ItemIndex = 1 then
begin
if HangmanDataModule.CheckIfLoginExistsInDatabase(
Self.LoginNameLabeledEdit.Text) = True then
ShowMessage('That login name has already been chosen.')
else
begin
NewPlayerDialog := UNewPlayer.TNewPlayerDialog.Create(Self);
NewPlayerDialog.WelcomeLabel.Caption := 'Welcome to GUI Hangman. ' +
'You will be registered on the ' + chr(13) + chr(10) +
'database with a login of "' + Self.LoginNameLabeledEdit.Text + '". ' +
chr(13) + chr(10) + 'Please enter your first and last names and ' +
'click OK.';
NewPlayerDialog.OKButton.Enabled := False;
NewPlayerDialog.ShowModal;
if NewPlayerDialog.ModalResult = mrOK then
begin
if HangmanDataModule.AddNewPlayerToDatabase(
Self.LoginNameLabeledEdit.Text,
NewPlayerDialog.FirstNameLabeledEdit.Text,
NewPlayerDialog.LastNameLabeledEdit.Text) = True then
begin
ShowMessage('Your new profile was added to the database.');
Self.LoginRadioGroup.ItemIndex := 0;
end;
end;
NewPlayerDialog.Release;
end;
end;
end;
procedure TLoginForm.FormCreate(Sender: TObject);
{ Sets the LoginRadioGroup to the default radio button. }
begin
Self.LoginRadioGroup.ItemIndex := 0;
end;
procedure TLoginForm.LoginNameLabeledEditChange(Sender: TObject);
{ Disables the Login form's OK Button unless the string in LoginNameLabeledEdit
consists of only letters, numbers, and underscores and is not empty. }
var
Count: integer;
begin
if Self.LoginNameLabeledEdit.Text = '' then
Self.OKButton.Enabled := False
else
begin
Self.OKButton.Enabled := True;
for Count := 1 to length(Self.LoginNameLabeledEdit.Text) do
begin
if not(Upcase(Self.LoginNameLabeledEdit.Text[Count]) in ['A'..'Z']) and
not(Self.LoginNameLabeledEdit.Text[Count] in ['0'..'9']) and
not(Self.LoginNameLabeledEdit.Text[Count] = '_') then
Self.OKButton.Enabled := False;
end;
end;
end;
procedure TLoginForm.LoginNameLabeledEditEnter(Sender: TObject);
{ Calls the OKButtonClick procedure when the user presses Enter straight after
typing in his or her name. }
begin
Self.OKButton.Default := True;
end;
end.
|
unit uFchCustomerType;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaiDeFichas, FormConfig, DB, ADODB, PowerADOQuery, siComp,
siLangRT, StdCtrls, Buttons, LblEffct, ExtCtrls, Mask, DBCtrls, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
DBClient, Provider;
type
TFchCustomerType = class(TbrwFrmParent)
quDiscount: TADODataSet;
dtsDiscount: TDataSource;
quDiscountIDTipoPessoa: TIntegerField;
quDiscountIDGroup: TIntegerField;
quDiscountDiscount: TFloatField;
quDiscountCategory: TStringField;
pnlDiscount: TPanel;
pnlDiscountTitle: TPanel;
grdDiscount: TcxGrid;
grdDiscountDB: TcxGridDBTableView;
grdDiscountDBIDTipoPessoa: TcxGridDBColumn;
grdDiscountDBIDGroup: TcxGridDBColumn;
grdDiscountDBCategory: TcxGridDBColumn;
grdDiscountDBDiscount: TcxGridDBColumn;
grdDiscountLevel: TcxGridLevel;
lblCustomerType: TLabel;
edtCustomerType: TDBEdit;
lblCustomerTypeRequired: TLabel;
quFormIDTipoCliente: TIntegerField;
quFormTipoCliente: TStringField;
quFormPath: TStringField;
quFormPathName: TStringField;
dspDiscount: TDataSetProvider;
cdsDiscount: TClientDataSet;
cmdInsDiscount: TADOCommand;
cmdUpdDiscount: TADOCommand;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure quFormAfterOpen(DataSet: TDataSet);
procedure dspDiscountGetTableName(Sender: TObject; DataSet: TDataSet;
var TableName: String);
procedure grdDiscountEnter(Sender: TObject);
procedure grdDiscountExit(Sender: TObject);
procedure grdDiscountDBKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
procedure DiscountOpen;
procedure DiscountClose;
procedure DiscountSave;
procedure InsertDiscount;
procedure UpdateDiscount;
end;
implementation
uses uDM;
{$R *.dfm}
{ TFchCustomerType }
procedure TFchCustomerType.DiscountClose;
begin
with cdsDiscount do
begin
if Active then
Close;
end;
end;
procedure TFchCustomerType.DiscountOpen;
begin
with cdsDiscount do
if not Active then
begin
FetchParams;
Params.ParamByName('IDTipoPessoa').Value :=
quForm.FieldByName('IDTipoCliente').AsInteger;
Open;
end
end;
procedure TFchCustomerType.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
if ModalResult = mrOk then
DiscountSave;
DiscountClose;
end;
procedure TFchCustomerType.quFormAfterOpen(DataSet: TDataSet);
begin
inherited;
DiscountOpen;
end;
procedure TFchCustomerType.dspDiscountGetTableName(Sender: TObject;
DataSet: TDataSet; var TableName: String);
begin
inherited;
TableName := 'Ent_CustomerDiscount';
end;
procedure TFchCustomerType.DiscountSave;
begin
dtsDiscount.DataSet := nil;
with cdsDiscount do
begin
First;
while not Eof do
begin
if (FieldByName('IDTipoPessoa').IsNull) and (FieldByName('Discount').AsFloat > 0) then
InsertDiscount
else if FieldByName('Discount').OldValue <> FieldByName('Discount').Value then
UpdateDiscount;
Next;
end;
end;
dtsDiscount.DataSet := cdsDiscount;
end;
procedure TFchCustomerType.InsertDiscount;
begin
with cmdInsDiscount do
begin
Parameters.ParamByName('IDTipoPessoa').Value := quForm.FieldByName('IDTipoCliente').AsInteger;
Parameters.ParamByName('IDGroup').Value := cdsDiscount.FieldByName('IDGroup').AsInteger;
Parameters.ParamByName('Discount').Value := cdsDiscount.FieldByName('Discount').AsFloat;
Execute;
end;
end;
procedure TFchCustomerType.UpdateDiscount;
begin
with cmdUpdDiscount do
begin
Parameters.ParamByName('IDTipoPessoa').Value := cdsDiscount.FieldByName('IDTipoPessoa').AsInteger;
Parameters.ParamByName('IDGroup').Value := cdsDiscount.FieldByName('IDGroup').AsInteger;
Parameters.ParamByName('Discount').Value := cdsDiscount.FieldByName('Discount').AsFloat;
Execute;
end;
end;
procedure TFchCustomerType.grdDiscountEnter(Sender: TObject);
begin
inherited;
btClose.Default := False;
end;
procedure TFchCustomerType.grdDiscountExit(Sender: TObject);
begin
inherited;
btClose.Default := True;
end;
procedure TFchCustomerType.grdDiscountDBKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = VK_Return) and (grdDiscountDBDiscount.Focused) then
with cdsDiscount do
begin
Next;
if not Eof then
FieldByName('Discount').FocusControl;
end;
end;
end.
|
unit UUnRar;
(*====================================================================
RAR files decompression
======================================================================*)
interface
const
ERAR_END_ARCHIVE = 10;
ERAR_NO_MEMORY = 11;
ERAR_BAD_DATA = 12;
ERAR_BAD_ARCHIVE = 13;
ERAR_UNKNOWN_FORMAT = 14;
ERAR_EOPEN = 15;
ERAR_ECREATE = 16;
ERAR_ECLOSE = 17;
ERAR_EREAD = 18;
ERAR_EWRITE = 19;
ERAR_SMALL_BUF = 20;
ERAR_UNKNOWN = 21;
RAR_OM_LIST = 0;
RAR_OM_EXTRACT = 1;
RAR_SKIP = 0;
RAR_TEST = 1;
RAR_EXTRACT = 2;
RAR_VOL_ASK = 0;
RAR_VOL_NOTIFY = 1;
type
TRarOpenArchiveData = record
ArcName : PChar;
OpenMode : longword;
OpenResult: longword;
CmtBuf : PChar;
CmtBufSize: longword;
CmtSize : longword;
CmtState : longword;
end;
TRarHeaderData = record
ArcName : array[0..259] of char;
FileName : array[0..259] of char;
Flags : longword;
PackSize : longword;
UnpSize : longword;
HostOS : longword;
FileCRC : longword;
FileTime : longword;
UnpVer : longword;
Method : longword;
FileAttr : longword;
CmtBuf : pChar;
CmtBufSize: longword;
CmtSize : longword;
CmtState : longword;
end;
TRarOpenArchive = function (var ArchiveData: TRarOpenArchiveData): longword; stdcall;
TRarCloseArchive = function (hArcData: longword): longint; stdcall;
TRarReadHeader = function (hArcData: longword; var HeaderData: TRarHeaderData): longint; stdcall;
TRarProcessFile = function (hArcData: longword; Operation: longint;
DestPath: pChar; DestName: pChar): longint; stdcall;
TRarGetDllVersion = function (): longint; stdcall;
var
RarOpenArchive : TRarOpenArchive;
RarCloseArchive : TRarCloseArchive;
RarReadHeader : TRarReadHeader;
RarProcessFile : TRarProcessFile;
RarGetDllVersion: TRarGetDllVersion;
function UnRarDllLoaded(): boolean;
function ExtractRarFile(szArchiveFileName: PChar;
szFileToExtract: PChar;
szTargetFileName: PChar;
iMaxSizeToExtract: longint;
iArchiveOffset: longint): longint;
implementation
uses
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
SysUtils, UBaseUtils;
var
DllHandle: THandle;
//RarOpenArchiveData: TRarOpenArchiveData;
//RarHeaderData : TRarHeaderData;
DllName: String;
ZString: array[0..256] of char;
iRarDllLoaded : integer;
function UnRarDllLoaded(): boolean;
begin
Result := false;
{$ifdef mswindows}
if (iRarDllLoaded = -1) then // we did not try it yet
begin
iRarDllLoaded := 0;
DllName := 'unrar.dll';
DllHandle := LoadLibrary(StrPCopy(ZString, GetProgramDir + DllName));
if DllHandle <= 32 then exit;
@RarOpenArchive := GetProcAddress(DllHandle, 'RAROpenArchive' );
@RarCloseArchive := GetProcAddress(DllHandle, 'RARCloseArchive');
@RarReadHeader := GetProcAddress(DllHandle, 'RARReadHeader' );
@RarProcessFile := GetProcAddress(DllHandle, 'RARProcessFile' );
@RarGetDllVersion:= GetProcAddress(DllHandle, 'RARGetDllVersion');
if ((@RarOpenArchive = nil) or
(@RarCloseArchive = nil) or
(@RarReadHeader = nil) or
(@RarProcessFile = nil) or
(@RarGetDllVersion= nil)) then
begin
FreeLibrary(DllHandle);
exit;
end;
iRarDllLoaded := 1;
end;
Result := iRarDllLoaded = 1;
{$else}
{$endif}
end;
//-----------------------------------------------------------------------------
function ExtractRarFile(szArchiveFileName: PChar;
szFileToExtract: PChar;
szTargetFileName: PChar;
iMaxSizeToExtract: longint;
iArchiveOffset: longint): longint;
var
hRarArchive: integer;
RarOpenArchiveData: TRarOpenArchiveData;
RarHeaderData : TRarHeaderData;
RHCode : longint;
PFCode : longint;
//Dir : ShortString;
//FileName : ShortString;
//OrigSize : longint;
//DateTime : longint;
//Attr : longint;
//LocHeadOffset: longint;
iLen : integer;
//LastSlash : integer;
//i : integer;
szFileBuf : array[0..512] of char;
begin
Result := 100; // dummy error value
if not UnRarDllLoaded then exit;
RarOpenArchiveData.ArcName := szArchiveFileName;
RarOpenArchiveData.OpenMode := RAR_OM_EXTRACT;
RarOpenArchiveData.OpenResult := 0;
RarOpenArchiveData.CmtBuf := nil;
RarOpenArchiveData.CmtBufSize := 0;
RarOpenArchiveData.CmtSize := 0;
RarOpenArchiveData.CmtState := 0;
hRarArchive := RarOpenArchive(RarOpenArchiveData);
if (RarOpenArchiveData.OpenResult <> 0) then // unsuccessful
begin
RarCloseArchive(hRarArchive);
end;
repeat
RHCode:= RARReadHeader(hRarArchive, RarHeaderData);
if RHCode<>0 then Break;
if (RarHeaderData.FileAttr and
(faDirectory or faVolumeID) = 0) and
(strlen(RarHeaderData.FileName) < 512) then
begin
///OemToCharBuff(@(RarHeaderData.FileName), @szFileBuf, strlen(RarHeaderData.FileName)+1);
if StrIComp(szFileBuf, szFileToExtract) = 0 then
begin
// we found it
iLen := strlen(szTargetFileName);
//CopyMemory(@szFile, , iLen+1);
///CharToOemBuff(szTargetFileName, @szFileBuf, iLen+1);
PFCode:= RARProcessFile(hRarArchive, RAR_EXTRACT, nil, szFileBuf);
Result := PFCode;
RarCloseArchive(hRarArchive);
exit;
end;
end;
PFCode:= RARProcessFile(hRarArchive, RAR_SKIP, nil, nil);
if (PFCode<>0) then Break;
until False;
RarCloseArchive(hRarArchive);
end;
//-----------------------------------------------------------------------------
begin
iRarDllLoaded := -1;
end.
|
unit MouseRNGCaptureDlg_U;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
MouseRNG, StdCtrls, SDUForms;
const
BUFFER_SIZE = 1024*1024*8; // 1MB of data
type
TMouseRNGCaptureDlg = class(TSDUForm)
pbOK: TButton;
pbCancel: TButton;
MouseRNG: TMouseRNG;
lblStored: TLabel;
lblRequired: TLabel;
lblInstructions: TLabel;
procedure FormShow(Sender: TObject);
procedure pbCancelClick(Sender: TObject);
procedure pbOKClick(Sender: TObject);
procedure MouseRNGByteGenerated(Sender: TObject; random: Byte);
procedure FormResize(Sender: TObject);
private
protected
FRequiredBits: integer;
FBitsCollected: integer;
FData: array [1..BUFFER_SIZE] of byte;
procedure UpdateDisplay();
procedure SetRequiredBits(bits: integer);
public
property RequiredBits: integer read FRequiredBits write SetRequiredBits;
property BitsCollected: integer read FBitsCollected;
// Copy up to "count" ***bits*** into the buffer, return the number of bits
// copied
// Note: "buffer" is indexed from 0
// countBits - Set to the number of *bits* to copy into "data"
// data - Zero indexed array into which the random data should be copied
// Returns: The number of bits copied into "data"
function RandomData(countBits: integer; var data: array of byte): integer;
// Securely cleardown any random data collected
procedure Wipe();
end;
implementation
{$R *.DFM}
uses
SDUGeneral,
Math; // Required for "min(...)"
resourcestring
BITS_REQUIRED = 'Bits required: %1';
BITS_GENERATED = 'Bits generated: %1';
procedure TMouseRNGCaptureDlg.SetRequiredBits(bits: integer);
begin
FRequiredBits := bits;
end;
procedure TMouseRNGCaptureDlg.FormShow(Sender: TObject);
begin
UpdateDisplay();
MouseRNG.Enabled := TRUE;
end;
procedure TMouseRNGCaptureDlg.UpdateDisplay();
var
enoughGenerated: boolean;
begin
if FRequiredBits>0 then
begin
lblRequired.visible := TRUE;
lblRequired.caption := SDUParamSubstitute(BITS_REQUIRED, [FRequiredBits]);
enoughGenerated := (FBitsCollected>=FRequiredBits);
SDUEnableControl(pbOK, enoughGenerated);
if (enoughGenerated) then
begin
MouseRNG.Enabled := FALSE;
MouseRNG.Color := clBtnFace;
SetFocusedControl(pbOK);
end;
end
else
begin
lblRequired.visible := FALSE;
SDUEnableControl(pbOK, TRUE);
end;
lblStored.caption := SDUParamSubstitute(BITS_GENERATED, [FBitsCollected]);
end;
procedure TMouseRNGCaptureDlg.Wipe();
var
i: integer;
begin
MouseRNG.Enabled := FALSE;
for i:=low(FData) to high(FData) do
begin
FData[i] := random(255);
FData[i] := 0;
end;
FRequiredBits:= 0;
FBitsCollected:= 0;
end;
procedure TMouseRNGCaptureDlg.pbCancelClick(Sender: TObject);
begin
MouseRNG.Enabled := FALSE;
Wipe();
ModalResult := mrCancel;
end;
procedure TMouseRNGCaptureDlg.pbOKClick(Sender: TObject);
begin
MouseRNG.Enabled := FALSE;
ModalResult := mrOK;
end;
function TMouseRNGCaptureDlg.RandomData(countBits: integer; var data: array of byte): integer;
var
copyCountBytes: integer;
i: integer;
begin
copyCountBytes := min((countBits div 8), (FBitsCollected div 8));
for i:=0 to (copyCountBytes-1) do begin
data[i] := FData[(FBitsCollected div 8) - i];
end;
Result := (copyCountBytes * 8);
end;
procedure TMouseRNGCaptureDlg.MouseRNGByteGenerated(Sender: TObject;
random: Byte);
begin
inc(FBitsCollected, 8);
FData[(FBitsCollected div 8)] := random;
UpdateDisplay();
end;
procedure TMouseRNGCaptureDlg.FormResize(Sender: TObject);
var
twoButtonsFullWidth: integer;
twoButtonsGap: integer;
begin
// Horizontally center the labels...
lblInstructions.left := (self.width-lblInstructions.width) div 2;
lblStored.left := (self.width-lblStored.width) div 2;
lblRequired.left := (self.width-lblRequired.width) div 2;
// Nicely horizontally center the buttons...
twoButtonsGap := pbCancel.left - (pbOK.left + pbOK.width);
twoButtonsFullWidth := pbOK.width + twoButtonsGap + pbCancel.width;
pbOK.left := (self.width-twoButtonsFullWidth) div 2;
pbCancel.left := pbOK.left + pbOK.width + twoButtonsGap;
end;
END.
|
unit ufTarefa1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufBase, Vcl.StdCtrls, Vcl.Buttons,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, uspQuery, FireDAC.Phys.FBDef, FireDAC.Phys,
FireDAC.Phys.IBBase, FireDAC.Phys.FB;
type
TfTarefa1 = class(TfBase)
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
GroupBox4: TGroupBox;
memoColunas: TMemo;
memoTabelas: TMemo;
memoCondicoes: TMemo;
memoSQL: TMemo;
btnGerarSQL: TBitBtn;
spQuery1: TspQuery;
procedure FormDestroy(Sender: TObject);
procedure btnGerarSQLClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fTarefa1: TfTarefa1;
implementation
{$R *.dfm}
procedure TfTarefa1.btnGerarSQLClick(Sender: TObject);
begin
memoSQL.Lines.Clear;
spQuery1.spColunas := memoColunas.Lines;
spQuery1.spTabelas := memoTabelas.Lines;
spQuery1.spCondicoes := memoCondicoes.Lines;
spQuery1.GeraSQL;
memoSQL.Lines := spQuery1.SQL;
end;
procedure TfTarefa1.FormDestroy(Sender: TObject);
begin
fTarefa1 := nil;
end;
end.
|
unit UTrieNode;
interface
uses Classes, ComCtrls;
type
TIndex = 'a'..'z';
TNode = class
private
ptrs : array[TIndex] of TNode;
eow : boolean;
public
constructor Create;
procedure push(s: string);
procedure GetWord(s: string; var res: integer);
procedure print(treeView: TTreeView; parent:TTreeNode);
destructor Destroy; override;
end;
implementation
constructor TNode.Create;
var
i: TIndex;
begin
inherited;
self.eow :=false;
for i:=low(TIndex) to high(TIndex) do
ptrs[i] := nil;
end;
procedure TNode.GetWord(s: string; var res: integer);
const
MN=['b','c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'];
var
ch:TIndex;
begin
if eow then
begin
if s[Length(s)] in MN then
inc (res);
end;
for ch:=Low(TIndex) to High(TIndex) do
if Ptrs[ch]<>nil then
Ptrs[ch].GetWord(s+ch,res)
end;
procedure TNode.print(treeView: TTreeView; parent:TTreeNode);
var
i:Char;
newParent: TTreeNode;
begin
for i:= Low(TIndex) to high(TIndex) do
if ptrs[i]<>nil then
begin
newParent := treeView.Items.AddChild(parent, i);
ptrs[i].print(treeView, newParent);
end;
end;
procedure TNode.push(s: string);
begin
if s = '' then
eow := True
else
begin
if ptrs[s[1]] = nil then
ptrs[s[1]] := TNode.Create;
ptrs[s[1]].push(Copy(s,2,Length(s)));
end;
end;
destructor TNode.Destroy;
var
i:TIndex;
begin
for i:=Low(TIndex) to High(TIndex) do
ptrs[i].Free;
inherited;
end;
end.
|
{******************************************************************************}
{* MvxIntf.pas *}
{* This module is part of Internal Project but is released under *}
{* the MIT License: http://www.opensource.org/licenses/mit-license.php *}
{* Copyright (c) 2006 by Jaimy Azle *}
{* All rights reserved. *}
{******************************************************************************}
{* Desc: *}
{******************************************************************************}
unit MvxIntf;
interface
uses
SysUtils, Windows, Messages, Classes;
const
MVX_SOCKET_DLL = 'MvxSock.dll';
type
UChar = Byte; // 8 bit unsigned
UShort = Word;
Uint = DWORD;
Long = LongInt; // 32 bit signed
ULong = DWord; // 32 bit unsigned
MvxSocket = DWORD;
wchar_u = WORD;
PUChar = ^UChar;
PULong = ^Ulong;
PWChar_u = ^wchar_u;
PMvxField = ^TMvxField;
TMvxField = packed record
Name: array[0..7] of char;
Data: array[0..327] of char;
Next: PMvxField;
end;
PMvxFieldMap = ^TMvxFieldMap;
TMvxFieldMap = packed record
Name: array[0..15] of char;
Reserved: array[0..7] of char;
PMap: PChar;
Next: PMvxFieldMap;
end;
PMvxServerID = ^TMvxServerID;
TMvxServerID = packed record
ServerName: array[0..31] of char;
ServerPortNr: UShort;
Flags: UShort;
AppName: array[0..16] of char;
MsgID: array[0..7] of char;
BadField: array[0..6] of char;
Buffer: array[0..255] of char;
TheSocket: MvxSocket;
CryptOn: Integer;
CryptKey: array[0..56] of Char;
Trim: Integer;
NextGen: Integer;
Token: Integer;
PField: PChar;
PCurTrans: PChar;
PTrans: PChar;
PMvxIn: PMvxFieldMap;
PMvxOut: PMvxFieldMap;
PMvxField: PMvxField;
Reserved: array[0..14] of char;
end;
EAPICallException = Exception;
IMvxAPILibrary = interface
['{480FBB21-4C1C-4CEE-80D9-CB8C545F825F}']
function GetLibName:string;
procedure FreeMvxLibrary;
function MvxSockSetup(PStruct: PMvxServerID;
WrapperName: PChar;
WrapperPort: Integer;
ApplicationName: PChar;
CryptOn: Integer;
CryptKey: PChar): ULong; stdcall;
function MvxSockConfig(PStruct: PMvxServerID; ConfigFileName: PChar): ULong; stdcall;
function MvxSockInit(PStruct: PMvxServerID;
ComputerName: PChar;
UserID: PChar;
UserPwd: PChar;
AS400Program: PChar): ULong; stdcall;
function MvxSockConnect(PStruct: PMvxServerID;
Host: PChar;
Port: Integer;
UserID: PChar;
Pwd: PChar;
MI: PChar;
Key: PChar): ULong; stdcall;
function MvxSockTrans(PStruct: PMvxServerID;
PSendBuffer: PChar;
PRetBuffer: PChar;
PRetLength: PULong): ULong; stdcall;
function MvxSockTransW(PStruct: PMvxServerID;
PSendBuffer: PWChar_u;
PRetBuffer: PWChar_u;
PRetLength: PULong): ULong; stdcall;
function MvxSockReceive(PStruct: PMvxServerID;
PRecvBuffer: PChar;
PRetLength: PULong): ULong; stdcall;
function MvxSockReceiveW(PStruct: PMvxServerID;
PRecvBuffer: PWChar_u;
PRetLength: PULong): ULong; stdcall;
function MvxSockSend(PStruct: PMvxServerID; PSendBuffer: PChar): ULong; stdcall;
function MvxSockSendW(PStruct: PMvxServerID; PSendBuffer: PWChar_u): ULong; stdcall;
function MvxSockSetMode(PStruct: PMvxServerID;
mode: Integer;
PTransName: PChar;
PResult: PChar;
PRetLength: PULong): ULong; stdcall;
function MvxSockVersion: UShort; stdcall;
procedure MvxSockShowLastError(PStruct: PMvxServerID; ErrText: PChar); stdcall;
function MvxSockGetLastError(PStruct: PMvxServerID;
Buffer: PChar;
BuffSize: Integer): PChar; stdcall;
function MvxSockGetLastMessageID(PStruct: PMvxServerID;
Buffer: PChar;
BuffSize: Integer): PChar; stdcall;
function MvxSockGetLastBadField(PStruct: PMvxServerID;
Buffer: PChar;
BuffSize: Integer): PChar; stdcall;
function MvxSockClose(PStruct: PMvxServerID): ULong; stdcall;
function MvxSockChgPwd(PStruct: PMvxServerID;
User: PChar;
OldPwd: PChar;
NewPwd: PChar): ULong; stdcall;
function MvxSockAccess(PStruct: PMvxServerID; Trans: PChar): ULong; stdcall;
procedure MvxSockClearFields(PStruct: PMvxServerID); stdcall;
function MvxSockGetField(PStruct: PMvxServerID; pszFldName: PChar): PChar; stdcall;
function MvxSockGetFieldW(PStruct: PMvxServerID; pszFldName: PChar): PWChar_u; stdcall;
procedure MvxSockSetField(PStruct: PMvxServerID; pszFldName, pszData: PChar); stdcall;
procedure MvxSockSetFieldW(PStruct: PMvxServerID; pszFldName: PChar; pszData: PWChar_u); stdcall;
function MvxSockMore(PStruct: PMvxServerID): ULong; stdcall;
// procedure AS400ToMovexJava(PStruct: PMvxServerID); stdcall;
function MvxSockSetMaxWait(PStruct: PMvxServerID; milli: integer): ULong; stdcall;
function MvxSockSetBlob(PStruct: PMvxServerID; PByte: PUChar; Size: ULong): ULong; stdcall;
function MvxSockGetBlob(PStruct: PMvxServerID; PByte: PUChar; Size: PULong): ULong; stdcall;
property LibraryName:string read GetLibName;
end;
{**
* Description: Alternative way of configuring the Sockets communication
* where no cfg file is used. Instead the IP-adress and socket port
* are given as arguments.
*
* Argument: pointer to struct
* IP-adress of FPW server
* Socket port of FPW
* Application name
* Encryption on/off
* Encryption key
*
* Returns: 0 = OK 0 >Error.
*
* Remark: Application name are for logging purposes only.
* Call MvxSockSetup OR MvxSockConfig before opening connection
*
* Example call:
* result=MvxSockSetup(TheServerStruct, "10.20.20.238", 6000, "MyTestApp", 0, NULL);
*
*}
TMvxSockSetup = function(PStruct: PMvxServerID; WrapperName: PChar;
WrapperPort: Integer; ApplicationName: PChar; CryptOn: Integer; CryptKey: PChar): ULong; stdcall;
{**
* Description: Load the configuration file. In the cfg-file IP-address
* of the FPW server and Socket port are located.
*
* Argument: Pointer to PSERVER_ID struct
* Namepath of configuration file
*
* Returns: 0 = OK 0 > Error.
*
* Remark: Call MvxSockConfig OR MvxSockSetup before opening connection
*
*}
TMvxSockConfig = function(PStruct: PMvxServerID; ConfigFileName: PChar): ULong; stdcall;
{**
* Initialization function for starting up the communication.
*
* Argument: pstruct = Pointer to PSERVER_ID structure
* ComputerName = LOCALA when used with standard FPW
* UserId = User Id
* UserPwd = Password
* AS400program = name of communication program on the AS/400 given
* as "LIBRARY/PGMNAME"
*
* Return: 0 = OK, 0 > Error
*
* Remark: The function can NOT verify the user and password or the existence of the
* given program.
*}
TMvxSockInit = function(PStruct: PMvxServerID; ComputerName: PChar; UserID: PChar;
UserPwd: PChar; AS400Program: PChar): ULong; stdcall;
{**
* Description: Simplified, combined setup and initiation function
*
* Argument: pstruct = Pointer to PSERVER_ID structure
* UserId = User Id on Movex application server
* Pwd = Password
* MI = name of MI program on application server given as "LIBRARY/PGMNAME" or "PGMNAME"
* Host = IP-adress of application server
* Port = Socket port of application server
* Key = Encryption key, if not used set it NULL
*
* Return: 0 = OK, 0 > Error
*
* Remark:
*
*}
TMvxSockConnect = function(PStruct: PMvxServerID; Host: PChar; Port: Integer;
UserID: PChar; Pwd: PChar; MI: PChar; Key: PChar): ULong; stdcall;
{**
* Description: The transfer function. Transfers a null terminated string
* to the program initiated. Layout/protocol of string should
* be coordinated with that program.
*
* Argument: Pointer to struct
* Pointer to data to be sent.
* Pointer to return buffer
* Pointer to unsigned long variable to receive returned length
* OBS! On entry to the function it should contain the size of return buffer.
*
* Return: 0 = OK, 0 > Error
*
* Remark: The wide chars supported are UCS-2, ie two bytes.
*}
TMvxSockTrans = function(PStruct: PMvxServerID; PSendBuffer: PChar;
PRetBuffer: PChar; PRetLength: PULong): ULong; stdcall;
TMvxSockTransW = function(PStruct: PMvxServerID; PSendBuffer: PWChar_u;
PRetBuffer: PWChar_u; PRetLength: PULong): ULong; stdcall;
{**
* Description: The receive functions. Used when more than one record is to be retrieved.
* Repeatedly called in a loop. Break loop when OK is received.
*
* Argument: Pointer to struct
* Pointer to return buffer
* Pointer to unsigned long variable to receive returned length in bytes.
* OBS! On entry to the function it should contain the size of return buffer.
*
* Return: 0 = OK, 0 > Error
*
* Remark: The wide chars supported are UCS-2, ie two bytes.
*}
TMvxSockReceive = function(PStruct: PMvxServerID; PRecvBuffer: PChar; PRetLength: PULong): ULong; stdcall;
TMvxSockReceiveW = function(PStruct: PMvxServerID; PRecvBuffer: PWChar_u; PRetLength: PULong): ULong; stdcall;
{**
* Description: The send function. Used only with transactions beginning with the
* letters "Snd". The purpose is to offer a fast way to upload data.
* The function does not expect the MI - program to reply on the sent
* information. No error information can therefore be returned as well.
*
* Argument: Pointer to struct
* Pointer to send buffer (NULL terminated)
* Pointer to unsigned long variable with sending length
*
* Return: 0 = OK, 0 > Error
*
* Remark: Only certain special transactions support use of this function. You
* need to verify in the transaction documentation if this is the case.
* The wide chars supported are UCS-2, ie two bytes.
*}
TMvxSockSend = function(PStruct: PMvxServerID; PSendBuffer: PChar): ULong; stdcall;
TMvxSockSendW = function(PStruct: PMvxServerID; PSendBuffer: PWChar_u): ULong; stdcall;
{**
* ***************************************************************
* * OBSOLETE function!!! No longer used in the Send context. *
* ***************************************************************
*
* Description: Change mode. Currently only two modes are allowed: normal mode and
* multiple sending mode. The multiple sending mode should only be used
* when you need to upload lots of data and you get performance problems
* if you upload the data with MvxSockTrans().
* Allowed modes are: SOCKMODESEND, SOCKMODENORMAL
*
*}
TMvxSockSetMode = function(PStruct: PMvxServerID; mode: Integer; PTransName: PChar; PResult: PChar;
PRetLength: PULong): ULong; stdcall;
{**
* Description: Get current MvxSock version
*
* Argument: none
*
* Returns: SHORT
*
* Remark: Major version in HIBYTE(v), minor in LOBYTE(v)
* E.g. version 1.0 gives highbyte==1, lowbyte==0
*}
TMvxSockVersion = function: UShort; stdcall;
{**
* Description: Show the last error in a message box.
*
* Argument: struct pointer
* Pointer to additional error text.
* Returns:
*
* Remark:
*
*}
TMvxSockShowLastError = procedure(PStruct: PMvxServerID; ErrText: PChar); stdcall;
{**
* Description: Returns the last error in given buffer.
*
* Argument: struct pointer
* Pointer to buffer or NULL.
* Size of the buffer in where to store error text.
*
* Returns: Pointer to buffer if not NULL.
* If buffer is NULL, a pointer to internal storage is returned.
*
* Remark: Always returns text in ANSI/ASCII format.
*
*}
TMvxSockGetLastError = function(PStruct: PMvxServerID; Buffer: PChar; BuffSize: Integer): PChar; stdcall;
{**
* Description: Retrieve message ID from the last NOK error.
*
* Argument: struct pointer
* Pointer to buffer or NULL.
* Size of the buffer in where to store text.
*
* Returns: Pointer to buffer if not NULL.
* If buffer is NULL, a pointer to internal storage is returned.
*
* Remark: Always returns text in ANSI/ASCII format.
*
*}
TMvxSockGetLastMessageID = function(PStruct: PMvxServerID; Buffer: PChar; BuffSize: Integer): PChar; stdcall;
{**
* Description: Retrieve name of the input field containing erroneous data
* as returned from the last NOK error.
*
* Argument: struct pointer
* Pointer to buffer or NULL.
* Size of the buffer in where to store text.
*
* Returns: Pointer to buffer if not NULL.
* If buffer is NULL, a pointer to internal storage is returned.
*
* Remark: Always returns text in ANSI/ASCII format.
*
*}
TMvxSockGetLastBadField = function(PStruct: PMvxServerID; Buffer: PChar; BuffSize: Integer): PChar; stdcall;
{**
* Close the conversation
*}
TMvxSockClose = function(PStruct: PMvxServerID): ULong; stdcall;
{* This one is not really supported. *}
TMvxSockChgPwd = function(PStruct: PMvxServerID; User: PChar; OldPwd: PChar; NewPwd: PChar): ULong; stdcall;
{**
* Description: Function to build and execute a transaction built up from field
* name/data pairs.
*
* Argument: Pointer to struct
* Name of transaction to execute
*
* Returns: 0 = OK, 0 > Error. 8 is often recoverable, the others are not.
*
* Remark: When called with only the struct pointer and NULL for trans name as arguments
* the function retrieves the next record in a Lst (multiple) transaction.
* The function allocates and maintain it's own memory buffers. To avoid memory
* leakage MvxSockClose() shall always be called to close the communication.
*}
TMvxSockAccess = function(PStruct: PMvxServerID; Trans: PChar): ULong; stdcall;
{**
* Description: Clear fields set with MvxSockSetField
*
* Argument: Pointer to struct
*
* Returns:
*
* Remark: Used eg. in pooling functionality. If set fields are not to be used.
*
*}
TMvxSockClearFields = procedure(PStruct: PMvxServerID); stdcall;
{**
* Description: Get the data for a specific field.
*
* Argument: Pointer to struct
* Name of the field to return data from.
*
* Returns: Pointer to an internal buffer containing data from the field.
* Data is null terminated and trailing blanks removed.
*
* Remark: This function does only work in conjunction with MvxSockAccess().
*
*}
TMvxSockGetField = function(PStruct: PMvxServerID; pszFldName: PChar): PChar; stdcall;
{**
* Description: Get the data for a specific field.
*
* Argument: Pointer to struct
* Name of the field to return data from.
*
* Returns: Pointer to an internal buffer containing Unicode data from the field.
* Data is null terminated and trailing blanks removed.
*
* Remark: This function does only work in conjunction with MvxSockAccess().
*
*}
TMvxSockGetFieldW = function(PStruct: PMvxServerID; pszFldName: PChar): PWChar_u; stdcall;
{**
* Description: Set the data for a specific field, preparing to call MvxSockAccess.
*
* Argument: Pointer to struct
* Name of the field to return data from.
* Data for the named field.
*
* Returns: Nothing
*
* Remark: This function does only work in conjunction with MvxSockAccess().
*
*}
TMvxSockSetField = procedure(PStruct: PMvxServerID; pszFldName, pszData: PChar); stdcall;
{**
* Description: Set the data for a specific field, preparing to call MvxSockAccess.
*
* Argument: Pointer to struct
* Name of the field to return data from.
* Data for the named field in Unicode UCS2 encoding.
*
* Returns: Nothing
*
* Remark: This function does only work in conjunction with MvxSockAccess().
*
*}
TMvxSockSetFieldW = procedure(PStruct: PMvxServerID; pszFldName: PChar; pszData: PWChar_u); stdcall;
{**
* Description: Returns TRUE if there is more data to retrieve using MvxSockGetField()
*
* Argument: Pointer to struct
*
* Returns: TRUE = more data to retreive, FALSE = no more data
*
* Remark: To be used in loops for "Lst" transactions
*
*}
TMvxSockMore = function(PStruct: PMvxServerID): ULong; stdcall;
{**
* Description: Function to, from an AS400 client, enable communication towards Movex Java
*
* Argument: Pointer to struct
*
* Returns: nothing
*
* Remark: This one is only available, and only needed, in an AS400 client running against
* Movex Java that communicates with UCS2.
*}
// TAS400ToMovexJava = procedure(PStruct: PMvxServerID); stdcall;
{**
* Description: Set Receive timeout. Max time to wait before receiving answer from Movex.
*
* Argument: Pointer to struct.
* Time to wait in milli seconds.
*
* Returns: 0 if OK, 7 otherwise.
*
* Remark: In Windows requires Winsock 2.0.
* Read plain text message for details.
* Primarily for use with Movex Java where no server side timeout exist.
*
*}
TMvxSockSetMaxWait = function(PStruct: PMvxServerID; milli: integer): ULong; stdcall;
{**
* Description: Sends a binary large object to the server.
*
* Argument: Pointer to a buffer containing the blob, size of the blob.
*
* Returns: 0 if ok, 7 or 8 otherwise. Read plain text in Buff struct member.
*
* Remark: This function must be called and the blob thus sent prior to sending the application
* unique transaction that completes the process of setting a blob.
*
*}
TMvxSockSetBlob = function(PStruct: PMvxServerID; PByte: PUChar; Size: ULong): ULong; stdcall;
{**
* Description: Retrieve a binary large object from the application server.
*
* Argument: Pointer to a byte buffer, pointer to a long receiving the size of blob.
*
* Returns: 0 if ok, 7 or 8 otherwise. Read plain text in Buff struct member.
*
* Remark: This function is to be called in two steps. The first time with a null pointer to
* buffer but with pointer to size storage. The client use this size indicator to allocate
* a memory buffer with enough size to contain the compete blob and then calls the function again.
* This function is to be called after an application unique transaction
* that, on the server side, picks up the blob and makes it available for retrieval with
* this function.
*
*}
TMvxSockGetBlob = function(PStruct: PMvxServerID; PByte: PUChar; Size: PULong): ULong; stdcall;
TMvxClientLibrary = class(TInterfacedObject, IMvxAPILibrary)
private
FLibraryHandle: THandle;
FLibraryName:string;
private
FMvxSockSetup: TMvxSockSetup;
FMvxSockConfig: TMvxSockConfig;
FMvxSockInit: TMvxSockInit;
FMvxSockConnect: TMvxSockConnect;
FMvxSockTrans: TMvxSockTrans;
FMvxSockTransW: TMvxSockTransW;
FMvxSockReceive: TMvxSockReceive;
FMvxSockReceiveW: TMvxSockReceiveW;
FMvxSockSend: TMvxSockSend;
FMvxSockSendW: TMvxSockSendW;
FMvxSockSetMode: TMvxSockSetMode;
FMvxSockVersion: TMvxSockVersion;
FMvxSockShowLastError: TMvxSockShowLastError;
FMvxSockGetLastError: TMvxSockGetLastError;
FMvxSockGetLastMessageID: TMvxSockGetLastMessageID;
FMvxSockGetLastBadField: TMvxSockGetLastBadField;
FMvxSockClose: TMvxSockClose;
FMvxSockChgPwd: TMvxSockChgPwd;
FMvxSockAccess: TMvxSockAccess;
FMvxSockClearFields: TMvxSockClearFields;
FMvxSockGetField: TMvxSockGetField;
FMvxSockGetFieldW: TMvxSockGetFieldW;
FMvxSockSetField: TMvxSockSetField;
FMvxSockSetFieldW: TMvxSockSetFieldW;
FMvxSockMore: TMvxSockMore;
// FAS400ToMovexJava: TAS400ToMovexJava;
FMvxSockSetMaxWait: TMvxSockSetMaxWait;
FMvxSockSetBlob: TMvxSockSetBlob;
FMvxSockGetBlob: TMvxSockGetBlob;
private
function GetLibName:string;
function MvxSockSetup(PStruct: PMvxServerID;
WrapperName: PChar;
WrapperPort: Integer;
ApplicationName: PChar;
CryptOn: Integer;
CryptKey: PChar): ULong; stdcall;
function MvxSockConfig(PStruct: PMvxServerID; ConfigFileName: PChar): ULong; stdcall;
function MvxSockInit(PStruct: PMvxServerID;
ComputerName: PChar;
UserID: PChar;
UserPwd: PChar;
AS400Program: PChar): ULong; stdcall;
function MvxSockConnect(PStruct: PMvxServerID;
Host: PChar;
Port: Integer;
UserID: PChar;
Pwd: PChar;
MI: PChar;
Key: PChar): ULong; stdcall;
function MvxSockTrans(PStruct: PMvxServerID;
PSendBuffer: PChar;
PRetBuffer: PChar;
PRetLength: PULong): ULong; stdcall;
function MvxSockTransW(PStruct: PMvxServerID;
PSendBuffer: PWChar_u;
PRetBuffer: PWChar_u;
PRetLength: PULong): ULong; stdcall;
function MvxSockReceive(PStruct: PMvxServerID;
PRecvBuffer: PChar;
PRetLength: PULong): ULong; stdcall;
function MvxSockReceiveW(PStruct: PMvxServerID;
PRecvBuffer: PWChar_u;
PRetLength: PULong): ULong; stdcall;
function MvxSockSend(PStruct: PMvxServerID; PSendBuffer: PChar): ULong; stdcall;
function MvxSockSendW(PStruct: PMvxServerID; PSendBuffer: PWChar_u): ULong; stdcall;
function MvxSockSetMode(PStruct: PMvxServerID;
mode: Integer;
PTransName: PChar;
PResult: PChar;
PRetLength: PULong): ULong; stdcall;
function MvxSockVersion: UShort; stdcall;
procedure MvxSockShowLastError(PStruct: PMvxServerID; ErrText: PChar); stdcall;
function MvxSockGetLastError(PStruct: PMvxServerID;
Buffer: PChar;
BuffSize: Integer): PChar; stdcall;
function MvxSockGetLastMessageID(PStruct: PMvxServerID;
Buffer: PChar;
BuffSize: Integer): PChar; stdcall;
function MvxSockGetLastBadField(PStruct: PMvxServerID;
Buffer: PChar;
BuffSize: Integer): PChar; stdcall;
function MvxSockClose(PStruct: PMvxServerID): ULong; stdcall;
function MvxSockChgPwd(PStruct: PMvxServerID;
User: PChar;
OldPwd: PChar;
NewPwd: PChar): ULong; stdcall;
function MvxSockAccess(PStruct: PMvxServerID; Trans: PChar): ULong; stdcall;
procedure MvxSockClearFields(PStruct: PMvxServerID); stdcall;
function MvxSockGetField(PStruct: PMvxServerID; pszFldName: PChar): PChar; stdcall;
function MvxSockGetFieldW(PStruct: PMvxServerID; pszFldName: PChar): PWChar_u; stdcall;
procedure MvxSockSetField(PStruct: PMvxServerID; pszFldName, pszData: PChar); stdcall;
procedure MvxSockSetFieldW(PStruct: PMvxServerID; pszFldName: PChar; pszData: PWChar_u); stdcall;
function MvxSockMore(PStruct: PMvxServerID): ULong; stdcall;
// procedure AS400ToMovexJava(PStruct: PMvxServerID); stdcall;
function MvxSockSetMaxWait(PStruct: PMvxServerID; milli: integer): ULong; stdcall;
function MvxSockSetBlob(PStruct: PMvxServerID; PByte: PUChar; Size: ULong): ULong; stdcall;
function MvxSockGetBlob(PStruct: PMvxServerID; PByte: PUChar; Size: PULong): ULong; stdcall;
public
constructor Create(const aLibName:string);
destructor Destroy; override;
procedure LoadMvxLibrary;
procedure FreeMvxLibrary;
end;
{ Library Initialization }
function GetClientLibrary(const aLibName:string):IMvxAPILibrary;
implementation
var
vClientLibs:TInterfaceList;
resourcestring
SCantFindApiProc ='Can''t find procedure %s in %s';
SCantLoadLibrary ='Can''t load library %s ';
SUnknownClientLibrary='Can''t perform operation %s. Unknown client library';
procedure InitFPU;
var
Default8087CW: Word;
begin
asm
FSTCW Default8087CW
OR Default8087CW, 0300h
FLDCW Default8087CW
end;
end;
function GetClientLibrary(const aLibName:string):IMvxAPILibrary;
var
I: Integer;
begin
for I := 0 to vClientLibs.Count - 1 do
if IMvxAPILibrary(vClientLibs[i]).LibraryName=aLibName then
begin
Result:=IMvxAPILibrary(vClientLibs[i]);
Exit;
end;
Result:=TMvxClientLibrary.Create(aLibName);
vClientLibs.Add(Result)
end;
{ TMvxClientLibrary }
constructor TMvxClientLibrary.Create(const aLibName: string);
begin
inherited Create;
FLibraryName:=aLibName;
LoadMvxLibrary;
end;
destructor TMvxClientLibrary.Destroy;
begin
FreeMvxLibrary;
end;
procedure TMvxClientLibrary.FreeMvxLibrary;
begin
if (FLibraryHandle > HINSTANCE_ERROR) then
begin
FreeLibrary(FLibraryHandle);
FLibraryHandle:=HINSTANCE_ERROR
end;
end;
function TMvxClientLibrary.GetLibName: string;
begin
Result:=FLibraryName
end;
procedure TMvxClientLibrary.LoadMvxLibrary;
function TryGetProcAddr(ProcName: PChar): Pointer;
begin
Result := GetProcAddress(FLibraryHandle, ProcName);
end;
function GetProcAddr(ProcName: PChar): Pointer;
begin
Result := GetProcAddress(FLibraryHandle, ProcName);
if not Assigned(Result) then
RaiseLastOSError
end;
begin
FLibraryHandle := LoadLibrary(PChar(FLibraryName));
if (FLibraryHandle > HINSTANCE_ERROR) then
begin
FMvxSockSetup:= GetProcAddr('MvxSockSetup');
FMvxSockConfig:= GetProcAddr('MvxSockConfig');
FMvxSockInit:= GetProcAddr('MvxSockInit');
FMvxSockConnect:= GetProcAddr('MvxSockConnect');
FMvxSockTrans:= GetProcAddr('MvxSockTrans');
FMvxSockTransW:= GetProcAddr('MvxSockTransW');
FMvxSockReceive:= GetProcAddr('MvxSockReceive');
FMvxSockReceiveW:= GetProcAddr('MvxSockReceiveW');
FMvxSockSend:= GetProcAddr('MvxSockSend');
FMvxSockSendW:= GetProcAddr('MvxSockSendW');
FMvxSockSetMode:= GetProcAddr('MvxSockSetMode');
FMvxSockVersion:= GetProcAddr('MvxSockVersion');
FMvxSockShowLastError:= GetProcAddr('MvxSockShowLastError');
FMvxSockGetLastError:= GetProcAddr('MvxSockGetLastError');
FMvxSockGetLastMessageID:= GetProcAddr('MvxSockGetLastMessageID');
FMvxSockGetLastBadField:= GetProcAddr('MvxSockGetLastBadField');
FMvxSockClose:= GetProcAddr('MvxSockClose');
FMvxSockChgPwd:= GetProcAddr('MvxSockChgPwd');
FMvxSockAccess:= GetProcAddr('MvxSockAccess');
FMvxSockClearFields:= GetProcAddr('MvxSockClearFields');
FMvxSockGetField:= GetProcAddr('MvxSockGetField');
FMvxSockGetFieldW:= GetProcAddr('MvxSockGetFieldW');
FMvxSockSetField:= GetProcAddr('MvxSockSetField');
FMvxSockSetFieldW:= GetProcAddr('MvxSockSetFieldW');
FMvxSockMore:= GetProcAddr('MvxSockMore');
// FAS400ToMovexJava:= GetProcAddr('AS400ToMovexJava');
FMvxSockSetMaxWait:= GetProcAddr('MvxSockSetMaxWait');
FMvxSockSetBlob:= GetProcAddr('MvxSockSetBlob');
FMvxSockGetBlob:= GetProcAddr('MvxSockGetBlob');
end
else
begin
// Can't load Library
raise EAPICallException.Create(Format(SCantLoadLibrary,[FLibraryName]));
end;
InitFPU;
end;
function TMvxClientLibrary.MvxSockAccess(PStruct: PMvxServerID;
Trans: PChar): ULong;
begin
if Assigned(FMvxSockAccess) then
Result := FMvxSockAccess(PStruct, Trans)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockAccess', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockChgPwd(PStruct: PMvxServerID; User,
OldPwd, NewPwd: PChar): ULong;
begin
if Assigned(FMvxSockChgPwd) then
Result := FMvxSockChgPwd(PStruct, User, OldPwd, NewPwd)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockChgPwd', FLibraryName])
);
end;
procedure TMvxClientLibrary.MvxSockClearFields(PStruct: PMvxServerID);
begin
if Assigned(FMvxSockClearFields) then
FMvxSockClearFields(PStruct)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockClearFields', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockClose(PStruct: PMvxServerID): ULong;
begin
if Assigned(FMvxSockClose) then
Result := FMvxSockClose(PStruct)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockClose', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockConfig(PStruct: PMvxServerID;
ConfigFileName: PChar): ULong;
begin
if Assigned(FMvxSockConfig) then
Result := FMvxSockConfig(PStruct, ConfigFileName)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockConfig', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockConnect(PStruct: PMvxServerID;
Host: PChar; Port: Integer; UserID, Pwd, MI, Key: PChar): ULong;
begin
if Assigned(FMvxSockConnect) then
Result := FMvxSockConnect(PStruct, Host, Port, UserID, Pwd, MI, Key)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockConnect', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockGetBlob(PStruct: PMvxServerID;
PByte: PUChar; Size: PULong): ULong;
begin
if Assigned(FMvxSockGetBlob) then
Result := FMvxSockGetBlob(PStruct, PByte, Size)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockGetBlob', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockGetField(PStruct: PMvxServerID;
pszFldName: PChar): PChar;
begin
if Assigned(FMvxSockGetField) then
Result := FMvxSockGetField(PStruct, pszFldName)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockGetField', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockGetFieldW(PStruct: PMvxServerID;
pszFldName: PChar): PWChar_u;
begin
if Assigned(FMvxSockGetFieldW) then
Result := FMvxSockGetFieldW(PStruct, pszFldName)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockGetFieldW', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockGetLastBadField(PStruct: PMvxServerID;
Buffer: PChar; BuffSize: Integer): PChar;
begin
if Assigned(FMvxSockGetLastBadField) then
Result := FMvxSockGetLastBadField(PStruct, Buffer, BuffSize)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockGetLastBadField', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockGetLastError(PStruct: PMvxServerID;
Buffer: PChar; BuffSize: Integer): PChar;
begin
if Assigned(FMvxSockGetLastError) then
Result := FMvxSockGetLastError(PStruct, Buffer, BuffSize)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockGetLastError', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockGetLastMessageID(PStruct: PMvxServerID;
Buffer: PChar; BuffSize: Integer): PChar;
begin
if Assigned(FMvxSockGetLastMessageID) then
Result := FMvxSockGetLastMessageID(PStruct, Buffer, BuffSize)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockGetLastMessageID', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockInit(PStruct: PMvxServerID; ComputerName,
UserID, UserPwd, AS400Program: PChar): ULong;
begin
if Assigned(FMvxSockInit) then
Result := FMvxSockInit(PStruct, ComputerName, UserID, UserPwd, AS400Program)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockInit', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockMore(PStruct: PMvxServerID): ULong;
begin
if Assigned(FMvxSockMore) then
Result := FMvxSockMore(PStruct)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockMore', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockReceive(PStruct: PMvxServerID;
PRecvBuffer: PChar; PRetLength: PULong): ULong;
begin
if Assigned(FMvxSockReceive) then
Result := FMvxSockReceive(PStruct, PRecvBuffer, PRetLength)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockReceive', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockReceiveW(PStruct: PMvxServerID;
PRecvBuffer: PWChar_u; PRetLength: PULong): ULong;
begin
if Assigned(FMvxSockReceiveW) then
Result := FMvxSockReceiveW(PStruct, PRecvBuffer, PRetLength)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockReceiveW', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockSend(PStruct: PMvxServerID;
PSendBuffer: PChar): ULong;
begin
if Assigned(FMvxSockSend) then
Result := FMvxSockSend(PStruct, PSendBuffer)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockSend', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockSendW(PStruct: PMvxServerID;
PSendBuffer: PWChar_u): ULong;
begin
if Assigned(FMvxSockSendW) then
Result := FMvxSockSendW(PStruct, PSendBuffer)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockSendW', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockSetBlob(PStruct: PMvxServerID;
PByte: PUChar; Size: ULong): ULong;
begin
if Assigned(FMvxSockSetBlob) then
Result := FMvxSockSetBlob(PStruct, PByte, Size)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockSetBlob', FLibraryName])
);
end;
procedure TMvxClientLibrary.MvxSockSetField(PStruct: PMvxServerID;
pszFldName, pszData: PChar);
begin
if Assigned(FMvxSockSetField) then
FMvxSockSetField(PStruct, pszFldName, pszData)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockSetField', FLibraryName])
);
end;
procedure TMvxClientLibrary.MvxSockSetFieldW(PStruct: PMvxServerID;
pszFldName: PChar; pszData: PWChar_u);
begin
if Assigned(FMvxSockSetFieldW) then
FMvxSockSetFieldW(PStruct, pszFldName, pszData)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockSetFieldW', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockSetMaxWait(PStruct: PMvxServerID;
milli: integer): ULong;
begin
if Assigned(FMvxSockSetMaxWait) then
Result := FMvxSockSetMaxWait(PStruct, milli)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockSetMaxWait', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockSetMode(PStruct: PMvxServerID;
mode: Integer; PTransName, PResult: PChar; PRetLength: PULong): ULong;
begin
if Assigned(FMvxSockSetMode) then
Result := FMvxSockSetMode(PStruct, mode, PTransName, PResult, PRetLength)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockSetMode', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockSetup(PStruct: PMvxServerID;
WrapperName: PChar; WrapperPort: Integer; ApplicationName: PChar;
CryptOn: Integer; CryptKey: PChar): ULong;
begin
if Assigned(FMvxSockSetup) then
Result := FMvxSockSetup(PStruct, WrapperName, WrapperPort, ApplicationName, CryptOn, CryptKey)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockSetup', FLibraryName])
);
end;
procedure TMvxClientLibrary.MvxSockShowLastError(PStruct: PMvxServerID;
ErrText: PChar);
begin
if Assigned(FMvxSockShowLastError) then
FMvxSockShowLastError(PStruct, ErrText)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockShowLastError', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockTrans(PStruct: PMvxServerID; PSendBuffer,
PRetBuffer: PChar; PRetLength: PULong): ULong;
begin
if Assigned(FMvxSockTrans) then
Result := FMvxSockTrans(PStruct, PSendBuffer, PRetBuffer, PRetLength)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockTrans', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockTransW(PStruct: PMvxServerID;
PSendBuffer, PRetBuffer: PWChar_u; PRetLength: PULong): ULong;
begin
if Assigned(FMvxSockTransW) then
Result := FMvxSockTransW(PStruct, PSendBuffer, PRetBuffer, PRetLength)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockTransW', FLibraryName])
);
end;
function TMvxClientLibrary.MvxSockVersion: UShort;
begin
if Assigned(FMvxSockVersion) then
Result := FMvxSockVersion
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['MvxSockVersion', FLibraryName])
);
end;
{
procedure TMvxClientLibrary.AS400ToMovexJava(PStruct: PMvxServerID);
begin
if Assigned(FAS400ToMovexJava) then
FAS400ToMovexJava(PStruct)
else
raise EAPICallException.Create(
Format(SCantFindApiProc,['AS400ToMovexJava', FLibraryName])
);
end;
}
initialization
vClientLibs:=TInterfaceList.Create;
finalization
vClientLibs.Free;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit CustomizedDataSnapUIUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DSServerExpertsUI, ExpertsUIWizard;
type
TCustomizedDataSnapUIModule = class(TDSServerExpertsUIModule)
CommentsWizardPage1: TExpertsFrameWizardPage;
WelcomeWizardsPage1: TExpertsFrameWizardPage;
procedure CommentsWizardPage1FrameCreate(
Sender: TCustomExpertsFrameWizardPage; AOwner: TComponent;
out AFrame: TFrame);
procedure WelcomeWizardsPage1FrameCreate(
Sender: TCustomExpertsFrameWizardPage; AOwner: TComponent;
out AFrame: TFrame);
private
function GetComments: string;
protected
procedure EnablePages; override;
procedure SetDefaults; override;
{ Private declarations }
public
{ Public declarations }
property Comments: string read GetComments;
end;
var
CustomizedDataSnapUIModule: TCustomizedDataSnapUIModule;
implementation
{$R *.dfm}
uses DSServerFeatures, DSServerFeatureManager,
CustomizedFeatures,
WelcomeFrameUnit,
CommentFrameUnit;
procedure TCustomizedDataSnapUIModule.SetDefaults;
begin
// Modify wizard defaults
inherited;
DSStandAloneAppWizard.Caption := 'New Customized DataSnap Server';
// Specify which features to check by default
Features := Features + [cCustomFeatureCommentModule,
cCustomFeatureTimeStampModule,
cCustomFeatureSampleMethods];
// Uncomment to uncheck TCPProtocol by default
// Features := Features - [dsTCPProtocol];
// Populate features page with custom features
FeatureDescriptions := CustomFeatureDescriptions;
end;
procedure TCustomizedDataSnapUIModule.WelcomeWizardsPage1FrameCreate(
Sender: TCustomExpertsFrameWizardPage; AOwner: TComponent;
out AFrame: TFrame);
begin
AFrame := TWelcomeFrame.Create(AOwner);
TWelcomeFrame(AFrame).Label1.Caption :=
'Welcome to the "' + DSStandAloneAppWizard.Caption + '" Wizard'
end;
procedure TCustomizedDataSnapUIModule.CommentsWizardPage1FrameCreate(
Sender: TCustomExpertsFrameWizardPage; AOwner: TComponent;
out AFrame: TFrame);
begin
AFrame := TCommentFrame.Create(AOwner);
end;
procedure TCustomizedDataSnapUIModule.EnablePages;
begin
inherited;
// Customization: Hide or show comments page
DSStandAloneAppWizard.PageEnabled[CommentsWizardPage1] :=
(Features * [cCustomFeatureCommentModule] <> []);
end;
function TCustomizedDataSnapUIModule.GetComments: string;
begin
if CommentsWizardPage1.Frame <> nil then
Result := TCommentFrame(CommentsWizardPage1.Frame).Memo1.Lines.Text
else
Result := '';
end;
end.
|
unit FRegister;
(*##*)
(*******************************************************************
* *
* F R E G I S T E R *
* register form of CVRT2WBMP, part of CVRT2WBMP *
* *
* Copyright (c) 2001 Andrei Ivanov. All rights reserved. *
* *
* Conditional defines: *
* *
* Last Revision: Jun 07 2001 *
* Last fix : *
* Lines : *
* History : *
* Printed : --- *
* *
********************************************************************)
(*##*)
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, Registry, ExtCtrls;
type
TFormRegister = class(TForm)
BEnterCode: TButton;
BCancel: TButton;
Label3: TLabel;
ERegCode: TEdit;
MDesc: TMemo;
BRegister: TButton;
BDetails: TButton;
LName: TLabel;
EUserName: TEdit;
EProduct: TEdit;
Label1: TLabel;
procedure BRegisterClick(Sender: TObject);
procedure BDetailsClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormRegister: TFormRegister;
implementation
{$R *.DFM}
uses
util1, fmain;
procedure TFormRegister.BRegisterClick(Sender: TObject);
begin
util1.EExecuteFile(REGISTER_URL);
end;
procedure TFormRegister.BDetailsClick(Sender: TObject);
begin
util1.EExecuteFile(REGISTER_HOWTO_URL);
end;
procedure TFormRegister.FormCreate(Sender: TObject);
begin
// EManufacturer.Text:= FParameters.Values[ParameterNames[ID_MANUFACTURER]];
with FormMain.FParameters do begin
// EProduct.Text:= IntToStr(REGISTER_REGSOFTPRODUCTCODE);
EUserName.Text:= Values[ParameterNames[ID_USER]];
ERegCode.Text:= Values[ParameterNames[ID_CODE]];
end;
end;
end.
|
{
@abstract Implements routine that makes the default locale to match the locale of the user instead the language of the operating system.
The default locale of a Delphi application depends on the Delphi version. Up to
Delphi 2009 the default locale was locale set in the Regional Settings of
Control Panel. Starting from Delphi 2010 this no longer the case. The default
locale is the language of the operating system itself.
If you want to have the old behaviour with Delphi 2010 or later use this unit.
The unit does not expose any functions but you just add this into your project such
way that the unit is called first. A suitable place is the first item in the uses
clause of the program.
@longCode(#
program Project1;
uses
NtInitialLocale,
Forms,
Unit1 in 'Unit1.pas';
#)
This makes sure that the initialization block of the unit is called before calling
any other initialization block.
See @italic(Samples\Delphi\VCL\LanguageSwitch) sample to see how to use the unit.
}
unit NtInitialLocale;
{$I NtVer.inc}
interface
implementation
{$IFDEF DELPHI2010}
uses
NtBase;
initialization
TNtBase.SetInitialLocale(lsSettings);
{$ENDIF}
end.
|
//This Form demonstrates basic "hierarchical" movements
unit FSkyPilot;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.Imaging.jpeg, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons,
GLScene, GLObjects, GLVectorGeometry,
GLWin32Viewer, GLCadencer,
GLTexture, GLMaterial, GLCoordinates, GLCrossPlatform, GLBaseClasses;
type
TSkyPilotFrm = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLLightSource1: TGLLightSource;
SunSphere: TGLSphere;
SunCube: TGLDummyCube;
SceneCamera: TGLCamera;
CameraCube: TGLDummyCube;
SkyCamera: TGLCamera;
MarsCube: TGLDummyCube;
VenusCube: TGLDummyCube;
EarthCube: TGLDummyCube;
MercuryCube: TGLDummyCube;
JupiterCube: TGLDummyCube;
SaturnCube: TGLDummyCube;
UranusCube: TGLDummyCube;
NeptuneCube: TGLDummyCube;
PlutoCube: TGLDummyCube;
PlutoSphere: TGLSphere;
NeptuneSphere: TGLSphere;
UranusSphere: TGLSphere;
SaturnSphere: TGLSphere;
JupiterSphere: TGLSphere;
MarsSphere: TGLSphere;
EarthSphere: TGLSphere;
MoonCube: TGLDummyCube;
MoonSphere: TGLSphere;
VenusSphere: TGLSphere;
MercurySphere: TGLSphere;
MarsPhobosCube: TGLDummyCube;
MarsDeimosCube: TGLDummyCube;
MarsDeimosSphere: TGLSphere;
MarsPhobosSphere: TGLSphere;
JupiterIoCube: TGLDummyCube;
JupiterEuropaCube: TGLDummyCube;
JupiterEuropaSphere: TGLSphere;
JupiterIoSphere: TGLSphere;
JupiterGanymedeCube: TGLDummyCube;
JupiterGanymedeSphere: TGLSphere;
JupiterCallistoCube: TGLDummyCube;
JupiterCallistoSphere: TGLSphere;
SaturnMimasCube: TGLDummyCube;
SaturnMimasSphere: TGLSphere;
UranusArielCube: TGLDummyCube;
UranusArielSphere: TGLSphere;
UranusUmbrielCube: TGLDummyCube;
UranusUmbrielSphere: TGLSphere;
NeptuneNereidCube: TGLDummyCube;
NeptuneNereidSphere: TGLSphere;
CharonCube: TGLDummyCube;
CharonSphere: TGLSphere;
CometHalleyCube: TGLDummyCube;
CometHalleySphere: TGLSphere;
KuiperBeltCube: TGLDummyCube;
KuiperBeltSphere: TGLSphere;
OortCloudCube: TGLDummyCube;
OortCloudSphere: TGLSphere;
GLCadencer1: TGLCadencer;
Timer1: TTimer;
Panel1: TPanel;
TrackBar: TTrackBar;
CBPlay: TCheckBox;
LoadBtn: TSpeedButton;
SaturnEnceladusCube: TGLDummyCube;
SaturnEnceladusSphere: TGLSphere;
SaturnTethysCube: TGLDummyCube;
SaturnTethysSphere: TGLSphere;
SaturnDioneCube: TGLDummyCube;
SaturnDioneSphere: TGLSphere;
SaturnRheaCube: TGLDummyCube;
SaturnRheaSphere: TGLSphere;
SaturnTitanCube: TGLDummyCube;
SaturnTitanSphere: TGLSphere;
SaturnHyperionCube: TGLDummyCube;
SaturnHyperionSphere: TGLSphere;
SaturnIapetusCube: TGLDummyCube;
SaturnIapetusSphere: TGLSphere;
SaturnPhoebeCube: TGLDummyCube;
SaturnPhoebeSphere: TGLSphere;
UranusTitaniaCube: TGLDummyCube;
UranusTitaniaSphere: TGLSphere;
UranusOberonCube: TGLDummyCube;
UranusOberonSphere: TGLSphere;
UranusMirandaCube: TGLDummyCube;
UranusMirandaSphere: TGLSphere;
NeptuneTritonCube: TGLDummyCube;
NeptuneTritonSphere: TGLSphere;
NeptuneLarissaCube: TGLDummyCube;
NeptuneLarissaSphere: TGLSphere;
NeptuneProteusCube: TGLDummyCube;
NeptuneProteusSphere: TGLSphere;
GLMaterialLibrary: TGLMaterialLibrary;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormResize(Sender: TObject);
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseEnter(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure Timer1Timer(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure LoadBtnClick(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure TrackBarChange(Sender: TObject);
procedure MishMash;
procedure CBPlayClick(Sender: TObject);
private
PlanetsLoaded:Boolean;
EarthProjectPath:String;
public
deltaTimeGlobal:Double;
timeMultiplier : Single;
mx, my, dmx, dmy : Integer;
end;
var
SkyPilotFrm: TSkyPilotFrm;
implementation
{uses HoloGlobals;}
{$R *.DFM}
procedure TSkyPilotFrm.FormCreate(Sender: TObject);
begin
CBPlay.Checked:=False;
Timer1.Enabled:=False;
{ top := HoloSkypilotFormY;
left := HoloSkypilotFormX; }
EarthProjectPath:= ExtractFilePath(ParamStr(0))+'EarthData\';
PlanetsLoaded:=False;
timeMultiplier:=1;
deltaTimeGlobal:=0;
if FileExists(ExtractFilePath(ParamStr(0))+'Holographic.hlp') THEN
Application.HelpFile := ExtractFilePath(ParamStr(0))+ 'Holographic.hlp';
end;
procedure TSkyPilotFrm.FormShow(Sender: TObject);
begin
Timer1.Enabled:=True;
GLCadencer1.Enabled:=True;
end;
procedure TSkyPilotFrm.FormHide(Sender: TObject);
begin
CBPlay.Checked:=False;
Timer1.Enabled:=False;
GLCadencer1.Enabled:=False;
end;
procedure TSkyPilotFrm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
// We need to stop playing here :
// since the timer is asynchronous, if we don't stop play,
// it may get triggered during the form's destruction
CBPlay.Checked:=False;
end;
procedure TSkyPilotFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
{ HoloSkyPilotFormY := HoloSkyPilotForm.top;
HoloSkyPilotFormX := HoloSkyPilotForm.left;}
end;
procedure TSkyPilotFrm.FormResize(Sender: TObject);
begin
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TSkyPilotFrm.LoadBtnClick(Sender: TObject);
procedure LoadHighResTexture(libMat : TGLLibMaterial; const fileName : String);
begin
if FileExists(fileName) then begin
// libMat.Material.Texture.Compression := tcStandard;
libMat.Material.Texture.Image.LoadFromFile(fileName);
end;
end;
begin
if not PlanetsLoaded then
begin
GLSceneViewer1.Cursor:=crHourGlass;
try
with GLMaterialLibrary do
begin
If FileExists(EarthProjectPath+'Sun.jpg') then
begin
with AddTextureMaterial('Sun',EarthProjectPath+'Sun.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SunSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SunSphere.Material.LibMaterialName:='Sun';
SunSphere.Material.Texture.Disabled:=False;
end;
end else showmessage(EarthProjectPath+'Sun.jpg is missing');
If FileExists(EarthProjectPath+'Mercury.jpg') then
with AddTextureMaterial('Mercury',EarthProjectPath+'Mercury.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
MercurySphere.Material.MaterialLibrary:= GLMaterialLibrary;
MercurySphere.Material.LibMaterialName:='Mercury';
MercurySphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Venus.jpg') then
with AddTextureMaterial('Venus',EarthProjectPath+'Venus.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
VenusSphere.Material.MaterialLibrary:= GLMaterialLibrary;
VenusSphere.Material.LibMaterialName:='Venus';
VenusSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Earth.jpg') then
with AddTextureMaterial('Earth',EarthProjectPath+'Earth.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
EarthSphere.Material.MaterialLibrary:= GLMaterialLibrary;
EarthSphere.Material.LibMaterialName:='Earth';
EarthSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Moon.jpg') then
with AddTextureMaterial('Moon',EarthProjectPath+'Moon.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
MoonSphere.Material.MaterialLibrary:= GLMaterialLibrary;
MoonSphere.Material.LibMaterialName:='Moon';
MoonSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Mars.jpg') then
with AddTextureMaterial('Mars',EarthProjectPath+'Mars.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
MarsSphere.Material.MaterialLibrary:= GLMaterialLibrary;
MarsSphere.Material.LibMaterialName:='Mars';
MarsSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Phobos.jpg') then
with AddTextureMaterial('Phobos',EarthProjectPath+'Phobos.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
MarsPhobosSphere.Material.MaterialLibrary:= GLMaterialLibrary;
MarsPhobosSphere.Material.LibMaterialName:='Phobos';
MarsPhobosSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Deimos.jpg') then
with AddTextureMaterial('Deimos',EarthProjectPath+'Deimos.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
MarsDeimosSphere.Material.MaterialLibrary:= GLMaterialLibrary;
MarsDeimosSphere.Material.LibMaterialName:='Deimos';
MarsDeimosSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Jupiter.jpg') then
with AddTextureMaterial('Jupiter',EarthProjectPath+'Jupiter.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
JupiterSphere.Material.MaterialLibrary:= GLMaterialLibrary;
JupiterSphere.Material.LibMaterialName:='Jupiter';
JupiterSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Io.jpg') then
with AddTextureMaterial('Io',EarthProjectPath+'Io.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
JupiterIoSphere.Material.MaterialLibrary:= GLMaterialLibrary;
JupiterIoSphere.Material.LibMaterialName:='Io';
JupiterIoSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Europa.jpg') then
with AddTextureMaterial('Europa',EarthProjectPath+'Europa.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
JupiterEuropaSphere.Material.MaterialLibrary:= GLMaterialLibrary;
JupiterEuropaSphere.Material.LibMaterialName:='Europa';
JupiterEuropaSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Ganymede.jpg') then
with AddTextureMaterial('Ganymede',EarthProjectPath+'Ganymede.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
JupiterGanymedeSphere.Material.MaterialLibrary:= GLMaterialLibrary;
JupiterGanymedeSphere.Material.LibMaterialName:='Ganymede';
JupiterGanymedeSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Callisto.jpg') then
with AddTextureMaterial('Callisto',EarthProjectPath+'Callisto.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
JupiterCallistoSphere.Material.MaterialLibrary:= GLMaterialLibrary;
JupiterCallistoSphere.Material.LibMaterialName:='Callisto';
JupiterCallistoSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Saturn.jpg') then
with AddTextureMaterial('Saturn',EarthProjectPath+'Saturn.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SaturnSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SaturnSphere.Material.LibMaterialName:='Saturn';
SaturnSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Mimas.jpg') then
with AddTextureMaterial('Mimas',EarthProjectPath+'Mimas.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SaturnMimasSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SaturnMimasSphere.Material.LibMaterialName:='Mimas';
SaturnMimasSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Enceladus.jpg') then
with AddTextureMaterial('Enceladus',EarthProjectPath+'Enceladus.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SaturnEnceladusSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SaturnEnceladusSphere.Material.LibMaterialName:='Enceladus';
SaturnEnceladusSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Tethys.jpg') then
with AddTextureMaterial('Tethys',EarthProjectPath+'Tethys.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SaturnTethysSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SaturnTethysSphere.Material.LibMaterialName:='Tethys';
SaturnTethysSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Dione.jpg') then
with AddTextureMaterial('Dione',EarthProjectPath+'Dione.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SaturnDioneSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SaturnDioneSphere.Material.LibMaterialName:='Dione';
SaturnDioneSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Rhea.jpg') then
with AddTextureMaterial('Rhea',EarthProjectPath+'Rhea.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SaturnRheaSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SaturnRheaSphere.Material.LibMaterialName:='Rhea';
SaturnRheaSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Titan.jpg') then
with AddTextureMaterial('Titan',EarthProjectPath+'Titan.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SaturnTitanSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SaturnTitanSphere.Material.LibMaterialName:='Titan';
SaturnTitanSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Hyperion.jpg') then
with AddTextureMaterial('Hyperion',EarthProjectPath+'Hyperion.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SaturnHyperionSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SaturnHyperionSphere.Material.LibMaterialName:='Hyperion';
SaturnHyperionSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Iapetus.jpg') then
with AddTextureMaterial('Iapetus',EarthProjectPath+'Iapetus.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SaturnIapetusSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SaturnIapetusSphere.Material.LibMaterialName:='Iapetus';
SaturnIapetusSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Phoebe.jpg') then
with AddTextureMaterial('Phoebe',EarthProjectPath+'Phoebe.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
SaturnPhoebeSphere.Material.MaterialLibrary:= GLMaterialLibrary;
SaturnPhoebeSphere.Material.LibMaterialName:='Phoebe';
SaturnPhoebeSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Uranus.jpg') then
with AddTextureMaterial('Uranus',EarthProjectPath+'Uranus.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
UranusSphere.Material.MaterialLibrary:= GLMaterialLibrary;
UranusSphere.Material.LibMaterialName:='Uranus';
UranusSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Ariel.jpg') then
with AddTextureMaterial('Ariel',EarthProjectPath+'Ariel.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
UranusArielSphere.Material.MaterialLibrary:= GLMaterialLibrary;
UranusArielSphere.Material.LibMaterialName:='Ariel';
UranusArielSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Umbriel.jpg') then
with AddTextureMaterial('Umbriel',EarthProjectPath+'Umbriel.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
UranusUmbrielSphere.Material.MaterialLibrary:= GLMaterialLibrary;
UranusUmbrielSphere.Material.LibMaterialName:='Umbriel';
UranusUmbrielSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Titania.jpg') then
with AddTextureMaterial('Titania',EarthProjectPath+'Titania.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
UranusTitaniaSphere.Material.MaterialLibrary:= GLMaterialLibrary;
UranusTitaniaSphere.Material.LibMaterialName:='Titania';
UranusTitaniaSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Oberon.jpg') then
with AddTextureMaterial('Oberon',EarthProjectPath+'Oberon.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
UranusOberonSphere.Material.MaterialLibrary:= GLMaterialLibrary;
UranusOberonSphere.Material.LibMaterialName:='Oberon';
UranusOberonSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Miranda.jpg') then
with AddTextureMaterial('Miranda',EarthProjectPath+'Miranda.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
UranusMirandaSphere.Material.MaterialLibrary:= GLMaterialLibrary;
UranusMirandaSphere.Material.LibMaterialName:='Miranda';
UranusMirandaSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Neptune.jpg') then
with AddTextureMaterial('Neptune',EarthProjectPath+'Neptune.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
NeptuneSphere.Material.MaterialLibrary:= GLMaterialLibrary;
NeptuneSphere.Material.LibMaterialName:='Neptune';
NeptuneSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Triton.jpg') then
with AddTextureMaterial('Triton',EarthProjectPath+'Triton.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
NeptuneTritonSphere.Material.MaterialLibrary:= GLMaterialLibrary;
NeptuneTritonSphere.Material.LibMaterialName:='Triton';
NeptuneTritonSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Nereid.jpg') then
with AddTextureMaterial('Nereid',EarthProjectPath+'Nereid.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
NeptuneNereidSphere.Material.MaterialLibrary:= GLMaterialLibrary;
NeptuneNereidSphere.Material.LibMaterialName:='Nereid';
NeptuneNereidSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Larissa.jpg') then
with AddTextureMaterial('Larissa',EarthProjectPath+'Larissa.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
NeptuneLarissaSphere.Material.MaterialLibrary:= GLMaterialLibrary;
NeptuneLarissaSphere.Material.LibMaterialName:='Larissa';
NeptuneLarissaSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Proteus.jpg') then
with AddTextureMaterial('Proteus',EarthProjectPath+'Proteus.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
NeptuneProteusSphere.Material.MaterialLibrary:= GLMaterialLibrary;
NeptuneProteusSphere.Material.LibMaterialName:='Proteus';
NeptuneProteusSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Pluto.jpg') then
with AddTextureMaterial('Pluto',EarthProjectPath+'Pluto.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
PlutoSphere.Material.MaterialLibrary:= GLMaterialLibrary;
PlutoSphere.Material.LibMaterialName:='Pluto';
PlutoSphere.Material.Texture.Disabled:=False;
end;
If FileExists(EarthProjectPath+'Charon.jpg') then
with AddTextureMaterial('Charon',EarthProjectPath+'Charon.jpg') do
begin {Create the matlib}
Material.Texture.TextureMode:=tmDecal;
CharonSphere.Material.MaterialLibrary:= GLMaterialLibrary;
CharonSphere.Material.LibMaterialName:='Charon';
CharonSphere.Material.Texture.Disabled:=False;
end;
{ sunmap.jpg
Mercury NOT: mer0muu2.jpg
Venus ven0ajj2.jpg OR ven0aaa2.jpg or
ven0auu1.jpg or ven0mss2.jpg
Earth Earth5.jpg or ear0xuu2.jpg
Moon
Mars mar0kuu2.jpg
Phobos mar1kuu2.jpg
Deimos mar2kuu2.jpg
Jupiter jup0vss1.jpg
Io jup1vuu2.jpg or jup1vss2.jpg
Europa jup2vuu2.jpg or jup2vss2.jpg
Ganymede jup3vss2.jpg or jup3vuu2.jpg
Callisto jup4vuu2.jpg or jup4vss2.jpg
Saturn sat0fds1.jpg
Mimas sat1vuu2.jpg or sat1vss2.jpg
Enceladus sat2vuu2.jpg or sat2vss2.jpg
Tethys sat3vuu2.jpg or sat3vss2.jpg
Dione sat4vuu2.jpg or sat4vss2.jpg
Rhea sat5vuu2.jpg or sat5vss2.jpg
Titan sat6vuu2.jpg or sat6vss2.jpg
Hyperion [] sat7vuu2.jpg or sat7vss2.jpg
Iapetus sat8vuu2.jpg or sat8vss2.jpg
Phoebe[] sat9vuu2.jpg or sat9vss2.jpg
Uranus ura0fss1.jpg uranusmap.jpg
1/Ariel ura1vuu2.jpg
2/Umbriel ura2vuu2.jpg
3/Titania ura3vuu2.jpg
4/Oberon ura4vuu2.jpg
5/Miranda ura5vuu2.jpg
Neptune nep0fds1.jpg or nep0vtt1.jpg
Triton nep1vuu2.jpg
Nereid []
Larissa []
Proteus nep8vpp2.jpg
Pluto plu0rss1.jpg or plu0hbb1.jpg
Charon plu1rss1.jpg
CometHalleyCube
KuiperBeltCube
OortCloudCube
}
end;
finally
GLSceneViewer1.Cursor:=crDefault;
end;
PlanetsLoaded:=True;
end;
end;
procedure TSkyPilotFrm.SpeedButton1Click(Sender: TObject);
begin
Application.HelpContext(5000);
end;
procedure TSkyPilotFrm.GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
begin
if CBPlay.Checked and Visible then
begin
// simulate a user action on the trackbar...
TrackBar.Position:=((TrackBar.Position+1) mod 360);
end;
deltaTimeGlobal:=deltaTime;
if (dmy<>0) or (dmx<>0) then
begin
SceneCamera.MoveAroundTarget(dmy,dmx);
dmx:=0;
dmy:=0;
end;
end;
procedure TSkyPilotFrm.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x; my:=y;
end;
procedure TSkyPilotFrm.GLSceneViewer1MouseEnter(Sender: TObject);
begin
GLSceneViewer1.SetFocus;// GLSceneViewer.Focused;
end;
procedure TSkyPilotFrm.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if Shift=[ssLeft] then
begin
dmx:=dmx+(mx-x);
dmy:=dmy+(my-y);
end else if Shift=[ssRight] then
SceneCamera.FocalLength:=SceneCamera.FocalLength*PowerSingle(1.05, (my-y)*0.1);
mx:=x; my:=y;
end;
procedure TSkyPilotFrm.FormKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
#27 : Close;
{They all orbit in the same direction
(counter-clockwise looking down
from above the Sun's north pole);
all but Venus, Uranus and Pluto
also rotate in that same sense.
'e', 'E' : begin
GLCamera.MoveTo(DCEarthSystem);
GLCameraControler.MoveTo(DCEarthSystem);
GLCamera.TargetObject:=DCEarthSystem;
GLCameraControler.TargetObject:=DCEarthSystem;
end;
Spacebar Sun
M Mercury,
V Venus,
E Earth,M Moon,
A Mars,
J Jupiter,
S Saturn,
U Uranus,
N Neptune,
P Pluto,
T Asteroids}
'm', 'M' :
begin
SceneCamera.MoveTo(MercurySphere);
SceneCamera.TargetObject:=MercurySphere;
end;
'v', 'V' :
begin
SceneCamera.MoveTo(VenusSphere);
SceneCamera.TargetObject:=VenusSphere;
end;
'e', 'E' :
begin
SceneCamera.MoveTo(EarthSphere);
SceneCamera.TargetObject:=EarthSphere;
end;
'a', 'A' :
begin
SceneCamera.MoveTo(MarsSphere);
SceneCamera.TargetObject:=MarsSphere;
end;
'j', 'J' :
begin
SceneCamera.MoveTo(JupiterSphere);
SceneCamera.TargetObject:=JupiterSphere;
end;
's', 'S' :
begin
SceneCamera.MoveTo(SaturnSphere);
SceneCamera.TargetObject:=SaturnSphere;
end;
'u', 'U' :
begin
SceneCamera.MoveTo(UranusSphere);
SceneCamera.TargetObject:=UranusSphere;
end;
'n', 'N' :
begin
SceneCamera.MoveTo(NeptuneSphere);
SceneCamera.TargetObject:=NeptuneSphere;
end;
'p', 'P' :
begin
SceneCamera.MoveTo(PlutoSphere);
SceneCamera.TargetObject:=PlutoSphere;
end;
' ':
begin
SceneCamera.MoveTo(SunCube);
SceneCamera.TargetObject:=SunCube;
end;
'0'..'9' : timeMultiplier:=PowerInteger(Integer(Key)-Integer('0'), 3);
end;
end;
procedure TSkyPilotFrm.FormMouseWheel(Sender: TObject;
Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint;
var Handled: Boolean);
var
f : Single;
begin
if (WheelDelta>0) or ({GLCameraControler}SceneCamera.Position.VectorLength>0.90) then begin
f:=PowerSingle(1.05, WheelDelta*(1/120));
{GLCameraControler}SceneCamera.AdjustDistanceToTarget(f);
end;
Handled:=True;
end;
procedure TSkyPilotFrm.Timer1Timer(Sender: TObject);
begin
Caption:='Sky Pilot: '+Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TSkyPilotFrm.TrackBarChange(Sender: TObject);
begin
MishMash;
end;
{
Mercury -3715 -3693 39 Scale XYZ 0.382 Position X -39
Venus -8392 -451 478 Scale XYZ 0.949 Position X -478
Earth
Moon: 277604 687816 29574 Scale Moon/Earth radii = 3475/12756
Mars -5882 17881 518 Scale XYZ 0.533 Position X 518
Jupiter -61941 13502 1329 Scale XYZ 11.209 Position X 1329
Saturn -25401 102463 -779 Scale XYZ 9.45 Position X -779
Uranus 209552 -104695 -3108 Scale XYZ 4.007 Position X -3108
Neptune 241251 -255428 -291 Scale XYZ 3.883 Position X -291
Pluto...
Charon
Ooort
Kuiper Belt Asteroids
Comet Halley}
procedure TSkyPilotFrm.MishMash;
var t : Double;
Begin
{if CBPlay.Checked and Visible then
t:=TrackBar.Position else t:=deltaTimeGlobal*timeMultiplier;}
t:=TrackBar.Position;
{The Hierarchy is NOT exactly like demo..
All Planets Spin themselves}
{ DummyCubeRed3.PitchAngle:=stage[3].rot_x*(Rotator);
DummyCubeRed3.RollAngle:=stage[3].rot_y*(Rotator);
DummyCubeRed3.TurnAngle:=stage[3].rot_z*(Rotator);}
// the "sun" spins slowly
SunCube.TurnAngle:=-t;
SunSphere.TurnAngle:=t/4;
MercuryCube.TurnAngle:=t*3;
VenusCube.TurnAngle:=t*1.3;
// "earth" rotates around the sun and spins
EarthCube.TurnAngle:=t*2;
// "moon" rotates around earth and spins
EarthSphere.RollAngle:=3*t;
MoonSphere.TurnAngle:=4*t;
MoonSphere.TurnAngle:=MoonSphere.TurnAngle+t/29.5;
MarsCube.TurnAngle:=t*4;
MarsDeimosCube.RollAngle:=t*2;
MarsPhobosCube.RollAngle:=t*4;
JupiterCube.TurnAngle:=t*5;
JupiterCallistoCube.RollAngle:=t*1;
JupiterGanymedeCube.RollAngle:=t*2;
JupiterEuropaCube.RollAngle:=t*3;
JupiterIoCube.RollAngle:=t*4;
SaturnCube.TurnAngle:=t*2;
SaturnMimasCube.RollAngle:=t*1;
SaturnEnceladusCube.RollAngle:=t*2;
SaturnTethysCube.RollAngle:=t*3;
SaturnDioneCube.RollAngle:=t*4;
SaturnRheaCube.RollAngle:=t*5;
SaturnTitanCube.RollAngle:=t*6;
SaturnHyperionCube.RollAngle:=t*7;
SaturnIapetusCube.RollAngle:=t*8;
SaturnPhoebeCube.RollAngle:=t*9;
UranusCube.TurnAngle:=t*7;
UranusArielCube.RollAngle:=t*1;
UranusUmbrielCube.RollAngle:=t*2;
UranusTitaniaCube.RollAngle:=t*3;
UranusOberonCube.RollAngle:=t*4;
UranusMirandaCube.RollAngle:=t*5;
NeptuneCube.TurnAngle:=t*2;
NeptuneTritonCube.RollAngle:=t*1;
NeptuneNereidCube.RollAngle:=t*2;
NeptuneLarissaCube.RollAngle:=t*3;
NeptuneProteusCube.RollAngle:=t*4;
PlutoCube.TurnAngle:=t*12;
CharonCube.TurnAngle:=t*5;
CometHalleyCube.TurnAngle:=t*3;
KuiperBeltCube.TurnAngle:=t*8;
OortCloudCube.TurnAngle:=t*5;
GLSceneViewer1.Invalidate;
End;
procedure TSkyPilotFrm.CBPlayClick(Sender: TObject);
begin
Timer1.Enabled:=True;
GLCadencer1.Enabled:=True;
end;
end.
|
unit GDIPlusRotate;
{$ALIGN ON}
{$MINENUMSIZE 4}
interface
uses
Windows,
Classes,
SysUtils,
ActiveX,
Dmitry.Utils.Files,
uTime,
uTranslate,
uLockedFileNotifications;
type
{$EXTERNALSYM EncoderValue}
EncoderValue = (EncoderValueColorTypeCMYK, EncoderValueColorTypeYCCK, EncoderValueCompressionLZW,
EncoderValueCompressionCCITT3, EncoderValueCompressionCCITT4, EncoderValueCompressionRle,
EncoderValueCompressionNone, EncoderValueScanMethodInterlaced, EncoderValueScanMethodNonInterlaced,
EncoderValueVersionGif87, EncoderValueVersionGif89, EncoderValueRenderProgressive,
EncoderValueRenderNonProgressive, EncoderValueTransformRotate90, EncoderValueTransformRotate180,
EncoderValueTransformRotate270, EncoderValueTransformFlipHorizontal, EncoderValueTransformFlipVertical,
EncoderValueMultiFrame, EncoderValueLastFrame, EncoderValueFlush, EncoderValueFrameDimensionTime,
EncoderValueFrameDimensionResolution, EncoderValueFrameDimensionPage);
TEncoderValue = EncoderValue;
const
WINGDIPDLL = 'gdiplus.dll';
type
{$EXTERNALSYM Status}
Status = (Ok, GenericError, InvalidParameter, OutOfMemory, ObjectBusy, InsufficientBuffer, NotImplemented,
Win32Error, WrongState, Aborted, FileNotFound, ValueOverflow, AccessDenied, UnknownImageFormat,
FontFamilyNotFound, FontStyleNotFound, NotTrueTypeFont, UnsupportedGdiplusVersion, GdiplusNotInitialized,
PropertyNotFound, PropertyNotSupported);
TStatus = Status;
GpStatus = TStatus;
GpImage = Pointer;
// ---------------------------------------------------------------------------
// Encoder Parameter structure
// ---------------------------------------------------------------------------
{$EXTERNALSYM EncoderParameter}
EncoderParameter = packed record
Guid: TGUID; // GUID of the parameter
NumberOfValues: ULONG; // Number of the parameter values
Type_: ULONG; // Value type, like ValueTypeLONG etc.
Value: Pointer; // A pointer to the parameter values
end;
TEncoderParameter = EncoderParameter;
PEncoderParameter = ^TEncoderParameter;
// ---------------------------------------------------------------------------
// Encoder Parameters structure
// ---------------------------------------------------------------------------
{$EXTERNALSYM EncoderParameters}
EncoderParameters = packed record
Count: UINT; // Number of parameters in this structure
Parameter: array [0 .. 0] of TEncoderParameter; // Parameter values
end;
TEncoderParameters = EncoderParameters;
PEncoderParameters = ^TEncoderParameters;
// --------------------------------------------------------------------------
// ImageCodecInfo structure
// --------------------------------------------------------------------------
{$EXTERNALSYM ImageCodecInfo}
ImageCodecInfo = packed record
Clsid: TGUID;
FormatID: TGUID;
CodecName: PWCHAR;
DllName: PWCHAR;
FormatDescription: PWCHAR;
FilenameExtension: PWCHAR;
MimeType: PWCHAR;
Flags: DWORD;
Version: DWORD;
SigCount: DWORD;
SigSize: DWORD;
SigPattern: PBYTE;
SigMask: PBYTE;
end;
TImageCodecInfo = ImageCodecInfo;
PImageCodecInfo = ^TImageCodecInfo;
const
EncoderTransformation: TGUID = '{8d0eb2d1-a58e-4ea8-aa14-108074b7b6f9}';
EncoderParameterValueTypeLong: Integer = 4; // 32-bit unsigned int
type
{$EXTERNALSYM NotificationHookProc}
NotificationHookProc = function(out Token: ULONG): Status; stdcall;
{$EXTERNALSYM NotificationUnhookProc}
NotificationUnhookProc = procedure(Token: ULONG); stdcall;
{$EXTERNALSYM GdiplusStartupOutput}
GdiplusStartupOutput = packed record
// The following 2 fields are NULL if SuppressBackgroundThread is FALSE.
// Otherwise, they are functions which must be called appropriately to
// replace the background thread.
//
// These should be called on the application's main message loop - i.e.
// a message loop which is active for the lifetime of GDI+.
// "NotificationHook" should be called before starting the loop,
// and "NotificationUnhook" should be called after the loop ends.
NotificationHook: NotificationHookProc;
NotificationUnhook: NotificationUnhookProc;
end;
TGdiplusStartupOutput = GdiplusStartupOutput;
PGdiplusStartupOutput = ^TGdiplusStartupOutput;
type
{$EXTERNALSYM DebugEventLevel}
DebugEventLevel = (DebugEventLevelFatal, DebugEventLevelWarning);
TDebugEventLevel = DebugEventLevel;
{$EXTERNALSYM DebugEventProc}
DebugEventProc = procedure(Level: DebugEventLevel; message: PChar); stdcall;
{$EXTERNALSYM GdiplusStartupInput}
GdiplusStartupInput = packed record
GdiplusVersion: Cardinal; // Must be 1
DebugEventCallback: DebugEventProc; // Ignored on free builds
SuppressBackgroundThread: BOOL; // FALSE unless you're prepared to call
// the hook/unhook functions properly
SuppressExternalCodecs: BOOL; // FALSE unless you want GDI+ only to use
end;
// its internal image codecs.
TGdiplusStartupInput = GdiplusStartupInput;
PGdiplusStartupInput = ^TGdiplusStartupInput;
var
StartupInput: TGDIPlusStartupInput;
GdiplusToken: ULONG;
GDIPlusLib: THandle = 0;
GDIPlusPresent: Boolean = False;
type
TGdipLoadImageFromStream = function(Stream: ISTREAM; out image: GPIMAGE): GPSTATUS; stdcall;
TGdipLoadImageFromFile = function(Filename: PWCHAR; out Image: GPIMAGE): GPSTATUS; stdcall;
// external WINGDIPDLL name 'GdipLoadImageFromFile';
TGdipGetImageEncodersSize = function(out NumEncoders: UINT; out Size: UINT): GPSTATUS; stdcall;
// external WINGDIPDLL name 'GdipGetImageEncodersSize';
TGdipGetImageEncoders = function(NumEncoders: UINT; Size: UINT; Encoders: PIMAGECODECINFO): GPSTATUS; stdcall;
// external WINGDIPDLL name 'GdipGetImageEncoders';
TGdipSaveImageToFile = function(Image: GPIMAGE; Filename: PWCHAR; ClsidEncoder: PGUID;
EncoderParams: PENCODERPARAMETERS): GPSTATUS; stdcall; // external WINGDIPDLL name 'GdipSaveImageToFile';
TGdipSaveImageToStream = function (image: GPIMAGE; stream: ISTREAM;
clsidEncoder: PGUID; encoderParams: PENCODERPARAMETERS): GPSTATUS; stdcall;
TGdipDisposeImage = function(Image: GPIMAGE): GPSTATUS; stdcall; // external WINGDIPDLL name 'GdipDisposeImage';
TGdiplusStartup = function(out Token: ULONG; Input: PGdiplusStartupInput; Output: PGdiplusStartupOutput): Status;
stdcall; // external WINGDIPDLL name 'GdiplusStartup';
TGdiplusShutdown = procedure(Token: ULONG); stdcall; // external WINGDIPDLL name 'GdiplusShutdown';
var
GdipLoadImageFromFile: TGdipLoadImageFromFile;
GdipLoadImageFromStream: TGdipLoadImageFromStream;
GdipGetImageEncodersSize: TGdipGetImageEncodersSize;
GdipGetImageEncoders: TGdipGetImageEncoders;
GdipSaveImageToFile: TGdipSaveImageToFile;
GdipSaveImageToStream: TGdipSaveImageToStream;
GdipDisposeImage: TGdipDisposeImage;
GdiplusStartup: TGdiplusStartup;
GdiplusShutdown: TGdiplusShutdown;
procedure InitGDIPlus;
procedure RotateGDIPlusJPEGFile(AFileName: string; Encode: TEncoderValue; OtherFile: string = '');
function AGetTempFileName(FileName: string): string;
procedure RotateGDIPlusJPEGStream(Src : TStream; Dst: TStream; Encode: TEncoderValue);
implementation
function AGetTempFileName(FileName: string): string;
begin
Result := FileName + '$temp$.$$$';
end;
function GetImageEncodersSize(out NumEncoders, Size: UINT): TStatus;
begin
Result := GdipGetImageEncodersSize(NumEncoders, Size);
end;
function GetImageEncoders(NumEncoders, Size: UINT; Encoders: PImageCodecInfo): TStatus;
begin
Result := GdipGetImageEncoders(NumEncoders, Size, Encoders);
end;
function GetEncoderClsid(Format: string; out PClsid: TGUID): Integer;
var
Num, Size, J: UINT;
ImageCodecInfo: PImageCodecInfo;
type
ArrIMgInf = array of TImageCodecInfo;
begin
Num := 0; // number of image encoders
Size := 0; // size of the image encoder array in bytes
Result := -1;
GetImageEncodersSize(Num, Size);
if (Size = 0) then
Exit;
GetMem(ImageCodecInfo, Size);
if (ImageCodecInfo = nil) then
Exit;
GetImageEncoders(Num, Size, ImageCodecInfo);
for J := 0 to Num - 1 do
begin
if (ArrIMgInf(ImageCodecInfo)[J].MimeType = Format) then
begin
PClsid := ArrIMgInf(ImageCodecInfo)[J].Clsid;
Result := J; // Success
end;
end;
FreeMem(ImageCodecInfo, Size);
end;
{
procedure SavetoFile(aFile: string;Bitmap: tbitmap);
var
imgFile : GPIMAGE;
mem : TMemoryStream;
aptr : IStream;
encoderClsid : TGUID;
input: TGdiplusStartupInput;
token: dword;
begin
mem := TMemoryStream.Create;
Bitmap.SaveToStream(mem);
mem.Seek(0, soFromBeginning);
aptr := TStreamAdapter.Create(mem, soReference) as IStream;
imgFile := nil;
FillChar(input, SizeOf(input), 0);
input.GdiplusVersion := 1;
GdiplusStartup(token, @input, nil);
GdipLoadImageFromStream(aptr, imgFile);
GetEncoderClsid('image/jpeg', encoderClsid);
GdipSaveImageToFile(imgFile, pwchar(aFile), @encoderClsid, nil);
GdiplusShutdown(token);
aptr := nil;
mem.Free;
end;
}
procedure RotateGDIPlusJPEGStream(Src : TStream; Dst: TStream; Encode: TEncoderValue);
var
AdapterS, AdapterD : IStream;
NativeImage: GpImage;
CLSID: TGUID;
EV: TEncoderValue;
PIP: PEncoderParameters;
EncoderParameters: TEncoderParameters;
begin;
Src.Seek(0, soFromBeginning);
AdapterS := TStreamAdapter.Create(Src, soReference) as IStream;
try
GdipLoadImageFromStream(AdapterS, NativeImage);
try
AdapterD := TStreamAdapter.Create(Dst, soReference) as IStream;
try
GetEncoderClsid('image/jpeg', Clsid);
EncoderParameters.Count := 1;
EncoderParameters.Parameter[0].Guid := EncoderTransformation;
EncoderParameters.Parameter[0].Type_ := EncoderParameterValueTypeLong;
EncoderParameters.Parameter[0].NumberOfValues := 1;
EV := Encode;
EncoderParameters.Parameter[0].Value := @EV;
PIP := @EncoderParameters;
GdipSaveImageToStream(NativeImage, AdapterD, @Clsid, PIP);
finally
AdapterD := nil;
end;
finally
GdipDisposeImage(NativeImage);
end;
finally
AdapterS := nil;
end;
end;
procedure RotateGDIPlusJPEGFile(AFileName: string; Encode: TEncoderValue; OtherFile: string = '');
var
CLSID: TGUID;
EncoderParameters: TEncoderParameters;
EV: TEncoderValue;
PIP: PEncoderParameters;
NativeImage: GpImage;
FileNameTemp: WideString;
UseOtherFile: Boolean;
begin
NativeImage := nil;
GdipLoadImageFromFile(PWideChar(AFileName), NativeImage);
GetEncoderClsid('image/jpeg', Clsid);
EncoderParameters.Count := 1;
EncoderParameters.Parameter[0].Guid := EncoderTransformation;
EncoderParameters.Parameter[0].Type_ := EncoderParameterValueTypeLong;
EncoderParameters.Parameter[0].NumberOfValues := 1;
EV := Encode;
EncoderParameters.Parameter[0].Value := @EV;
PIP := @EncoderParameters;
UseOtherFile := AnsiLowerCase(AFileName) <> AnsiLowerCase(OtherFile);
if not UseOtherFile then
begin
FileNameTemp := AGetTempFileName(AFileName);
TLockFiles.Instance.AddLockedFile(FileNameTemp, 10000);
try
if Ok <> GdipSaveImageToFile(NativeImage, PWideChar(FileNameTemp), @Clsid, PIP) then
raise Exception.Create(Format(TA('Can''t write to file %s!'), [FileNameTemp]));
finally
GdipDisposeImage(NativeImage);
DeleteFile(PWideChar(AFileName));
RenameFile(FileNameTemp, AFileName);
end;
TLockFiles.Instance.AddLockedFile(AFileName, 1000);
end else
begin
if FileExists(OtherFile) then
SilentDeleteFile(0, PWideChar(OtherFile), True, True);
FileNameTemp := OtherFile;
try
if Ok <> GdipSaveImageToFile(NativeImage, PWideChar(FileNameTemp), @Clsid, PIP) then
raise Exception.Create(Format(TA('Can''t write to file %s!'), [FileNameTemp]));
finally
GdipDisposeImage(NativeImage);
end;
end;
end;
procedure InitGDIPlus;
begin
TW.I.Start('WINGDIPDLL');
if GDIPlusLib = 0 then
begin
if AnsiUpperCase(ParamStr(1)) <> '/SAFEMODE' then
if AnsiUpperCase(ParamStr(1)) <> '/UNINSTALL' then
GDIPlusLib := LoadLibrary(WINGDIPDLL);
if GDIPlusLib <> 0 then
begin
GDIPlusPresent := True;
GdipLoadImageFromFile := GetProcAddress(GDIPlusLib, 'GdipLoadImageFromFile');
GdipLoadImageFromStream := GetProcAddress(GDIPlusLib, 'GdipLoadImageFromStream');
GdipGetImageEncodersSize := GetProcAddress(GDIPlusLib, 'GdipGetImageEncodersSize');
GdipGetImageEncoders := GetProcAddress(GDIPlusLib, 'GdipGetImageEncoders');
GdipSaveImageToFile := GetProcAddress(GDIPlusLib, 'GdipSaveImageToFile');
GdipSaveImageToStream := GetProcAddress(GDIPlusLib, 'GdipSaveImageToStream');
GdipDisposeImage := GetProcAddress(GDIPlusLib, 'GdipDisposeImage');
GdiplusStartup := GetProcAddress(GDIPlusLib, 'GdiplusStartup');
GdiplusShutdown := GetProcAddress(GDIPlusLib, 'GdiplusShutdown');
// Initialize StartupInput structure
StartupInput.DebugEventCallback := nil;
StartupInput.SuppressBackgroundThread := False;
StartupInput.SuppressExternalCodecs := False;
StartupInput.GdiplusVersion := 1;
// Initialize GDI+
GdiplusStartup(GdiplusToken, @StartupInput, nil);
end else
begin
GDIPlusPresent := False;
end;
TW.I.Start('WINGDIPDLL - END');
end;
end;
initialization
finalization
begin
// Close GDI +
if GDIPlusPresent then
begin
GdiplusShutdown(GdiplusToken);
FreeLibrary(GDIPlusLib);
end;
end;
end.
|
{
*************************************************************************
CoYOT(e) - the simple and lightweight time tracking tool *
Copyright (C) 2014 Philip Märksch and the CoYOT(e)-team *
*
This program is free software: you can redistribute it and/or modify *
it under the terms of the GNU General Public License as published by *
the Free Software Foundation, either version 3 of the License, or *
(at your option) any later version. *
*
This program is distributed in the hope that it will be useful, *
but WITHOUT ANY WARRANTY; without even the implied warranty of *
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
GNU General Public License for more details. *
*
You should have received a copy of the GNU General Public License *
along with this program. If not, see http://www.gnu.org/licenses/ *
*
*************************************************************************
This is a programme I made for myself, to help me have an overview on
working times and vacation days. Primarily I did this, because I wanted
to get comfortable with Lazarus, so the use of the programme was not the
significant goal. I just wanted to learn stuff.
Sorry for any German in the code, I may have mixed it up sometimes ;)
Also my English is a bastard mix of British and American - Philos
}
// Todo:
// * database commit and download
// * save all people and lists in one file
// * implement new saving function.
// * Code week editing like I did with PersonForm
// # some pictures/icons in the popup menus are not properly shown on Linux Version!! - Lazarus Bug?
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, RTTIGrids, RTTICtrls, Forms, Controls, Dialogs,
ComCtrls, DBCtrls, EditBtn, Grids, Menus, StdCtrls, ExtCtrls, Buttons,
ActnList, IBConnection, DateUtils, INIFiles, TypInfo,
{ own Forms }
WeekEditForm, WeekAddForm, about, DBConnectForm, PersonEditForm, SettingsForm,
{ own Units }
workdays, funcs, CoyoteDefaults, people;
type
{ TForm1 }
TForm1 = class(TForm)
ComboBox1: TComboBox;
ComboBox2: TComboBox;
IBConnection1: TIBConnection;
ImageList1: TImageList;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
MainMenu1: TMainMenu;
MenuItem1: TMenuItem;
MenuDBSettings: TMenuItem;
MenuItem10: TMenuItem;
MenuItem12: TMenuItem;
MenuNew: TMenuItem;
MenuMove: TMenuItem;
MenuMoveTop: TMenuItem;
MenuMoveUp: TMenuItem;
MenuMoveDown: TMenuItem;
MenuMoveBottom: TMenuItem;
MenuSort: TMenuItem;
MenuItem17: TMenuItem;
MenuItem18: TMenuItem;
PopupAddPeriod: TMenuItem;
PopupEditPeriod: TMenuItem;
PopupRemovePeriod: TMenuItem;
MenuItem5: TMenuItem;
MenuStatistics: TMenuItem;
MenuOpenRecent: TMenuItem;
MenuDBDownload: TMenuItem;
MenuDBUpload: TMenuItem;
MenuSettings: TMenuItem;
MenuLanguage: TMenuItem;
MenuEnglish: TMenuItem;
MenuGerman: TMenuItem;
MenuManual: TMenuItem;
MenuSaveAs: TMenuItem;
MenuLoad: TMenuItem;
MenuQuickSave: TMenuItem;
MenuColorTheme: TMenuItem;
MenuItem2: TMenuItem;
MenuItem21: TMenuItem;
MenuItem22: TMenuItem;
MenuPeople: TMenuItem;
MenuItem3: TMenuItem;
MenuItem4: TMenuItem;
MenuQuit: TMenuItem;
MenuAbout: TMenuItem;
MenuItem9: TMenuItem;
PopupMenu1: TPopupMenu;
ToolButton1: TToolButton;
ToolButton10: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
ToolButton9: TToolButton;
UsersList: TPopupMenu;
StatusBar1: TStatusBar;
StringGrid1: TStringGrid;
ToolBar1: TToolBar;
AddWeekButton: TToolButton;
EditWeekButton: TToolButton;
ToolButton4: TToolButton;
procedure AddWeek(Sender: TObject);
procedure ComboBox1Select(Sender: TObject);
procedure ComboBox2Select(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure FormDestroy(Sender: TObject);
procedure MenuAboutClick(Sender: TObject);
procedure ColorThemeClick(Sender: TObject);
procedure MenuDatabaseClick(Sender: TObject);
procedure MenuEnglishClick(Sender: TObject);
procedure MenuGermanClick(Sender: TObject);
procedure MenuLoadClick(Sender: TObject);
procedure MenuNewClick(Sender: TObject);
procedure MenuPeopleClick(Sender: TObject);
procedure MenuQuickSaveClick(Sender: TObject);
procedure MenuSaveClick(Sender: TObject);
procedure MenuSettingsClick(Sender: TObject);
procedure RemoveSelected(Sender: TObject);
procedure RemoveAll(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure MenuQuitClick(Sender: TObject);
procedure MoveClick(Sender: TObject);
procedure SelectWeek(Sender: TObject; aCol, aRow: integer; var CanSelect: boolean);
procedure ToolButton10Click(Sender: TObject);
private
{ private declarations }
FWeekList: TWeekList; // List of Weeks shown in the StringGrid
FPersonList: TPersonList;
FSelectionIndex: integer; // Index of the Week that was selected in the grid
FPersonIndex: integer; // Index of the person selected - maybe change to string?
FPeriodIndex: integer;
FOSName: string; // The Internal Name for the used Operating System
//FLanguage: string; // Language chosen by User - default is English
FLanguageID: string;
AboutForm: TForm2; // The Window showing information about CoYOT(e)
EditWeekForm: TForm3; // The window that you can edit a week with
AddWeekForm: TForm4; // A window to add a new week to the "data base"
DBForm: TForm6; // The window to connect to the firebird database
PersonForm: TForm5; // Window showing personal information
EditSettingsForm: TForm7; // The settings "menu"
//FCurrentUser: Integer; // ID of the currently selected "User"/Person
FCurrentFilePath: string; // If known - Name of the currently opened File
FOpenRecent: TStringList; // The files that have been opened lately - will be in ini file
FCanSave: boolean; // True, if changes have been made to the file
// triggered when a week is added
procedure AddWeekToList(Sender: TObject; AWeek: TWorkWeek; EditAfterwards: boolean);
// triggered when a week got edited
procedure AssignWeek(Sender: TObject; AWeek: TWorkWeek; Index: integer);
// triggered when a Form wants a specific week
procedure GetWeek(Sender: TObject; Index: integer);
// triggered when a certain week is deleted
procedure RemoveWeekFromList(Sender: TObject; AIndex: integer);
// Merges two weeks and by default deletes the second one afterwards
procedure MergeWeeks(Sender: TObject; AIndex1, AIndex2: integer; DeleteFirst: boolean = False);
// Checks for each button, wether it has to get enabled or disabled
procedure EnableButtons;
// Updates the Information shown
procedure UpdateWindow;
// Clears all values like filename etc..
procedure Clear;
procedure TranslateCaptions;
// Load the values from ini file
procedure LoadIniFile;
procedure SaveIniFile;
procedure LoadFile(FileName: string);
// apply a color to the theme
procedure ApplyColor(AColor: integer);
// adds a filename to the recent files-list and adds it to the mainmenu
procedure AddToOpenRecent(AFilePath: string; AList: TStringList; AMenuItem: TMenuItem);
procedure OpenRecentCLick(Sender: TObject); // dynamic onClick-Event for Recent Files
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
FOSName := 'unknown'; // for those poor guys using Minix, BSD, Solaris and such things ;)
// detectable OS
{$IFDEF macos}
FOSName := 'MacOS'; // for those poor guys with the little penis ;)
{$ENDIF}
{$IFDEF mswindows}
FOSName := 'Windows'; // for those poor guys with the little brain ;)
{$ENDIF}
{$IFDEF linux}
FOSName := 'Linux'; // for those poor guys with the huge brain and the monstrous penis ;)
{$ENDIF}
self.Caption := ProgrammeName + ' ' + VersionNr + ' - WORK IN PROGRESS';
// Create Instances
FWeekList := TWeekList.Create;
FPersonList := TPersonList.Create;
FOpenRecent := TStringList.Create;
Clear;
// Sub-Forms
AboutForm := TForm2.Create(self);
EditWeekForm := TForm3.Create(self);
AddWeekForm := TForm4.Create(self);
DBForm := TForm6.Create(self);
PersonForm := TForm5.Create(self);
EditSettingsForm := TForm7.Create(self);
AboutForm.Label1.Caption := 'Version: ' + VersionNr + ' ( ' + FOSName + ' )';
AboutForm.Label2.Caption := 'Build Date: ' + VersionDate;
// Handling events that come from the subforms
AddWeekForm.OnApplyClick := @AddWeekToList; // assign event of the add-form
EditWeekForm.OnRemoveClick := @RemoveWeekFromList; // assign event for deletion
EditWeekForm.OnApplyClick := @AssignWeek; // assign event for applying changes to week
EditWeekForm.OnNextWeekClick := @GetWeek; // switch to specified week via Index
EditWeekForm.OnMergeWeeksClick := @MergeWeeks; // assign the merge event of the EditWeekForm to merge function
LoadIniFile;
TranslateCaptions; // automatically updates the window
// Constraints
self.Constraints.MinWidth := Groupbox1.Width;
self.Constraints.MinHeight := round(Groupbox1.Width / 2);
if (FOpenRecent.Count > 0) and option_openLatestFile then
begin
loadFile(FOpenRecent[FOPenRecent.Count - 1]);
end;
end;
procedure TForm1.Clear;
begin
FSelectionIndex := -1;
FPeriodIndex := 0;
FPersonIndex := 0;
FCurrentFilePath := '';
FCanSave := False;
FWeekList.Clear;
FPersonList.Clear;
StringGrid1.Clear;
{
FPersonList.add(TPerson.Create);
FPersonList.Items[0].FirstName := 'User1';
FPersonList.Items[0].FamilyName := '';
FPersonList.Items[0].TimeData.Add(TWeekList.Create);
FPersonList.add(TPerson.Create);
FPersonList.Items[1].FirstName := 'Test';
FPersonList.Items[1].FamilyName := 'User';
FPersonList.Items[1].PhoneNumber1 := '1234/56789';
FPersonList.Items[1].Email := 'Test@User.de';
FPersonList.Items[1].TimeData.Add(TWeekList.Create); }
updateWindow;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
AboutForm.Free;
EditWeekForm.Free;
AddWeekForm.Free;
PersonForm.Free;
EditSettingsForm.Free;
DBForm.Free;
FWeekList.Free;
FPersonList.Free;
end;
procedure TForm1.SelectWeek(Sender: TObject; aCol, aRow: integer; var CanSelect: boolean);
begin
if (StringGrid1.RowCount > 1) and canSelect then
begin
FSelectionIndex := aRow - 1;
end;
end;
procedure TForm1.ToolButton10Click(Sender: TObject);
begin
PersonForm.ShowPersonList(FPersonList, FPersonIndex);
PersonForm.Show;
end;
procedure TForm1.AddWeek(Sender: TObject);
begin
AddWeekForm.Visible := True;
AddWeekForm.Show;
end;
procedure TForm1.ComboBox1Select(Sender: TObject);
begin
if (FPersonList.Count > 0) then
begin
FPersonIndex := ComboBox1.ItemIndex;
end
else
begin
FPersonIndex := -1;
end;
StatusBar1.Panels[0].Text := ComboBox1.Items[FPersonIndex];
updateWindow;
end;
procedure TForm1.ComboBox2Select(Sender: TObject);
begin
if (FPersonIndex >= 0) and (ComboBox2.ItemIndex >= 0) then
begin
// I hope this line keeps us from rewriting all the places where FWeekList
// is involved
FWeekList := FPersonList[FPersonIndex].TimeData[ComboBox2.ItemIndex];
end
else
begin
FWeekList := nil;
end;
updateWindow;
end;
procedure TForm1.MergeWeeks(Sender: TObject; AIndex1, AIndex2: integer; DeleteFirst: boolean = False);
var
I: integer;
begin
if DeleteFirst then
begin
swap(AIndex1, AIndex2);
end;
for I := 0 to FWeekList.Items[AIndex2].Days.Count - 1 do
begin
// calling the copy-constructor
FWeekList.Items[AIndex1].Days.Add(FWeekList.Items[AIndex2].Days[I]);
FWeekList.Items[AIndex1].WeekLength := FWeekList.Items[AIndex1].WeekLength + 1;
end;
FWeekList.Delete(AIndex2);
FCanSave := True;
updateWindow;
end;
procedure TForm1.AssignWeek(Sender: TObject; AWeek: TWorkWeek; Index: integer);
begin
FWeekList.Items[Index].Assign(AWeek);
WeeksToComboBox(EditWeekForm.ComboBox1, FweekList);
WeeksToComboBox(EditWeekForm.ComboBox2, FweekList);
EditWeekForm.ComboBox1.ItemIndex := EditWeekForm.WeekIndex;
FCanSave := True;
updateWindow;
end;
procedure TForm1.EditButtonClick(Sender: TObject);
begin
if (FweekList.Count > 0) and (FSelectionIndex >= 0) then
begin
if (FWeekList.Count > 1) then
begin
EditWeekForm.ButtonLeft.Enabled := True;
EditWeekForm.ButtonRight.Enabled := True;
end
else
begin
EditWeekForm.ButtonLeft.Enabled := False;
EditWeekForm.ButtonRight.Enabled := False;
end;
EditWeekForm.showWeek(FWeekList.Items[FSelectionIndex], FSelectionIndex);
EditWeekForm.Visible := True;
WeeksToComboBox(EditWeekForm.ComboBox1, FweekList);
WeeksToComboBox(EditWeekForm.ComboBox2, FweekList);
EditWeekForm.ComboBox1.ItemIndex := FSelectionIndex;
end;
end;
procedure TForm1.FormActivate(Sender: TObject);
begin
UpdateWindow;
end;
procedure TForm1.getWeek(Sender: TObject; Index: integer);
begin
if (FWeekList.Count > 0) then
begin
if (Index >= FWeekList.Count) then
begin
Index := 0;
end;
if (Index < 0) then
begin
Index := FWeekList.Count - 1;
end;
EditWeekForm.showWeek(FWeekList.Items[Index], Index);
EditWeekForm.ComboBox1.ItemIndex := EditWeekForm.WeekIndex;
EditWeekForm.ComboBox2.ItemIndex := 0;
end;
end;
procedure TForm1.RemoveSelected(Sender: TObject);
begin
if (FSelectionIndex >= 0) then
begin
if (MessageDlg(txtCaptionDelete, txtDeleteMsg, mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
begin
FWeekList.Delete(FSelectionIndex);
FSelectionIndex := -1;
FCanSave := True;
end;
updateWindow;
end;
end;
procedure TForm1.RemoveAll(Sender: TObject);
begin
if (FWeekList.Count > 0) then
begin
if (MessageDlg(txtCaptionDelete, txtDeleteAllMsg, mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
begin
FWeekList.Clear;
updateWindow;
FCanSave := True;
end;
end;
end;
procedure TForm1.AddWeekToList(Sender: TObject; AWeek: TWorkWeek; EditAfterwards: boolean);
begin
FWeekList.Add(AWeek);
updateWindow;
FCanSave := True;
EnableButtons;
if EditAfterwards then
begin
FSelectionIndex := FWeekList.Count - 1;
EditButtonClick(self);
end;
end;
procedure TForm1.RemoveWeekFromList(Sender: TObject; AIndex: integer);
begin
if (AIndex >= 0) and (AIndex < FWeekList.Count) then
begin
FWeekList.Delete(AIndex);
updateWindow;
FCanSave := True;
end;
end;
procedure TForm1.MenuAboutClick(Sender: TObject);
begin
AboutForm.Visible := True;
end;
procedure TForm1.ColorThemeClick(Sender: TObject);
var
colorDlg: TColorDialog;
begin
colorDlg := TColorDialog.Create(nil);
try
colorDlg.Color := Toolbar1.Color;
if colorDlg.Execute then
begin
ApplyColor(colorDlg.Color);
end;
finally
colorDlg.Free;
end;
end;
procedure TForm1.MenuDatabaseClick(Sender: TObject);
begin
DBForm.Show;
end;
procedure TForm1.MenuEnglishClick(Sender: TObject);
begin
FLanguageID := 'en';
LoadFromLanguageFile('../languages/en.lang');
translateCaptions;
//updateWindow;
end;
procedure TForm1.MenuGermanClick(Sender: TObject);
begin
FLanguageID := 'de';
LoadFromLanguageFile('../languages/de.lang');
translateCaptions;
//updateWindow;
end;
procedure TForm1.MenuLoadClick(Sender: TObject);
var
OpenDlg: TOpenDialog;
begin
OpenDlg := TOpenDialog.Create(self);
OpenDlg.Title := mcOpen;
try
OpenDlg.InitialDir := '../data/';
OpenDlg.DoFolderChange;
if OpenDlg.Execute then
begin
loadFile(OpenDlg.FileName);
end;
finally
OpenDlg.Free;
FCanSave := False;
updateWindow;
end;
end;
procedure TForm1.LoadFile(FileName: string);
begin
if loadFromFile(FileName, FWeekList) then
begin
StatusBar1.Panels[0].Text := '"' + ExtractFileName(FileName) + '" loaded!';
FCurrentFilePath := FileName;
AddToOpenRecent(FCurrentFilePath, FOpenRecent, MenuOpenRecent);
end
else
begin
StatusBar1.Panels[0].Text := '"' + ExtractFileName(FileName) + '" could not be loaded!';
FCurrentFilePath := '';
end;
end;
procedure TForm1.MenuNewClick(Sender: TObject);
begin
Clear;
Statusbar1.Panels[0].Text := txtNewFile;
UpdateWindow;
end;
procedure TForm1.MenuPeopleClick(Sender: TObject);
begin
PersonForm.ShowPersonList(FPersonList, FPersonIndex);
PersonForm.Show;
end;
procedure TForm1.MenuQuickSaveClick(Sender: TObject);
begin
if (FCurrentFilePath <> '') then
begin
SaveToFile(FCurrentFilePath, FWeekList);
AddToOpenRecent(FCurrentFilePath, FOpenRecent, MenuOpenRecent);
StatusBar1.Panels[0].Text := txtFileSaved;
FCanSave := False;
EnableButtons;
end
else
begin
MenuSaveClick(nil);
end;
end;
procedure TForm1.MenuSaveClick(Sender: TObject);
var
SaveDlg: TSaveDialog;
begin
SaveDlg := TSaveDialog.Create(self);
SaveDlg.InitialDir := '../data/';
SaveDlg.DoFolderChange;
SaveDlg.FileName := 'test user.sav';
SaveDlg.Options := [ofOverwritePrompt];
SaveDlg.Title := mcSaveAs;
try
if SaveDlg.Execute then
begin
SaveToFile(SaveDlg.FileName, FWeekList);
NEWSaveToFile(SaveDlg.FileName+'2', FPersonList);
AddToOpenRecent(SaveDlg.FileName, FOpenRecent, MenuOpenRecent);
StatusBar1.Panels[0].Text := txtFileSaved;
FCurrentFilePath := SaveDlg.FileName;
end;
finally
SaveDlg.Free;
FCanSave := False;
EnableButtons;
end;
end;
procedure TForm1.MenuSettingsClick(Sender: TObject);
begin
EditSettingsForm.Visible := True;
EditSettingsForm.StringGrid1.Cells[1, 1] := FloatToStr(defHoursPerDay);
EditSettingsForm.StringGrid1.Cells[1, 2] := FloatToStr(defPausePerDay);
EditSettingsForm.StringGrid1.Cells[1, 3] := FloatToStr(defHoursUntilPause);
EditSettingsForm.ColorButton1.ButtonColor := colorMarkedDays;
EditSettingsForm.ColorButton2.ButtonColor := colorVacationDays;
EditSettingsForm.CheckBox1.Checked := option_openLatestFile;
end;
procedure TForm1.MenuQuitClick(Sender: TObject);
begin
if FCanSave then
begin
if (MessageDlg(txtQuitProgramme, txtQuitMsg, mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
begin
MenuQuickSaveClick(nil);
SaveIniFile;
Application.Terminate;
end
else
begin
SaveIniFile;
Application.Terminate;
end;
end
else
begin
SaveIniFile;
Application.Terminate;
end;
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: boolean);
begin
if FCanSave then
begin
if (MessageDlg(txtQuitProgramme, txtQuitMsg, mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
begin
MenuQuickSaveClick(nil);
SaveIniFile;
CanClose := True;
end
else
begin
SaveIniFile;
CanClose := True;
end;
end
else
begin
SaveIniFile;
CanClose := True;
end;
end;
procedure TForm1.SaveIniFile;
var
INI: TINIFile;
I: integer;
fs: TFormatSettings;
begin
fs.DecimalSeparator := '.';
INI := TINIFile.Create('coyote.ini');
if (self.WindowState <> wsMaximized) then
begin
INI.WriteString('MainForm', 'xpos', IntToStr(self.Left));
INI.WriteString('MainForm', 'ypos', IntToStr(self.Top));
INI.WriteString('MainForm', 'width', IntToStr(self.Width));
INI.WriteString('MainForm', 'height', IntToStr(self.Height));
end;
INI.WriteString('MainForm', 'state', GetEnumName(TypeInfo(TWindowState), integer(self.WindowState)));
INI.WriteString('EditWeekForm', 'xpos', IntToStr(EditWeekForm.Left));
INI.WriteString('EditWeekForm', 'ypos', IntToStr(EditWeekForm.Top));
INI.WriteString('EditWeekForm', 'width', IntToStr(EditWeekForm.Width));
INI.WriteString('EditWeekForm', 'height', IntToStr(EditWeekForm.Height));
INI.WriteString('EditWeekForm', 'state', GetEnumName(TypeInfo(TWindowState), integer(EditWeekForm.WindowState)));
INI.WriteString('DBInfo', 'hostname', DBForm.LabeledEdit1.Text);
INI.WriteString('DBInfo', 'port', DBForm.LabeledEdit2.Text);
INI.WriteString('DBInfo', 'dbname', DBForm.LabeledEdit5.Text);
INI.WriteString('DBInfo', 'user', DBForm.LabeledEdit3.Text);
INI.WriteString('SettingsForm', 'xpos', IntToStr(EditSettingsForm.Left));
INI.WriteString('SettingsForm', 'ypos', IntToStr(EditSettingsForm.Top));
INI.WriteString('SettingsForm', 'width', IntToStr(EditSettingsForm.Width));
INI.WriteString('SettingsForm', 'height', IntToStr(EditSettingsForm.Height));
INI.WriteString('SettingsForm', 'state', GetEnumName(TypeInfo(TWindowState), integer(EditSettingsForm.WindowState)));
INI.WriteString('Defaults', 'HoursUntilPause', FloatToStr(defHoursUntilPause, fs));
INI.WriteString('Defaults', 'HoursPerDay', FloatToStr(defHoursPerDay, fs));
INI.WriteString('Defaults', 'PausePerDay', FloatToStr(defPausePerDay, fs));
INI.WriteString('Defaults', 'ColorMarkedDays', IntToStr(colorMarkedDays));
INI.WriteString('Defaults', 'ColorVacationDays', IntToStr(colorVacationDays));
INI.WriteString('Defaults', 'Language', FLanguageID);
// Recent Files
INI.WriteString('RecentFiles', 'open_latest', BoolToStr(option_openLatestFile));
INI.WriteString('RecentFiles', 'count', IntToStr(FOpenRecent.Count));
for I := 0 to FOpenRecent.Count - 1 do
begin
INI.WriteString('RecentFiles', IntToStr(I), FOpenRecent[I]);
end;
// grid column sizes
for I := 0 to EditWeekForm.WeekGrid.ColCount - 1 do
begin
INI.WriteString('EditWeekForm', 'col' + IntToStr(I + 1), IntToStr(EditWeekForm.WeekGrid.Columns.Items[I].Width));
end;
for I := 0 to EditSettingsForm.StringGrid1.ColCount - 1 do
begin
INI.WriteString('SettingsForm', 'col' + IntToStr(I + 1), IntToStr(EditSettingsForm.StringGrid1.ColWidths[I]));
end;
for I := 0 to StringGrid1.ColCount - 1 do
begin
INI.WriteString('MainForm', 'col' + IntToStr(I + 1), IntToStr(StringGrid1.Columns.Items[I].Width));
end;
INI.WriteString('Theme', 'color', IntToStr(Toolbar1.Color));
INI.Free;
end;
procedure TForm1.LoadIniFile;
var
INI: TINIFile;
s: string;
I: integer;
fs: TFormatSettings;
begin
fs.DecimalSeparator := '.';
INI := TINIFile.Create('coyote.ini');
s := INI.ReadString('MainForm', 'state', GetEnumName(TypeInfo(TWindowState), integer(wsNormal)));
self.WindowState := TWindowState(GetEnumValue(TypeInfo(TWindowState), s));
if (self.WindowState <> wsMaximized) then
begin
self.Left := StrToInt(INI.ReadString('MainForm', 'xpos', IntToStr(self.Left)));
self.Top := StrToInt(INI.ReadString('MainForm', 'ypos', IntToStr(self.Top)));
self.Width := StrToInt(INI.ReadString('MainForm', 'width', IntToStr(self.Width)));
self.Height := StrToInt(INI.ReadString('MainForm', 'height', IntToStr(self.Height)));
end;
EditWeekForm.Left := StrToInt(INI.ReadString('EditWeekForm', 'xpos', IntToStr(self.Left)));
EditWeekForm.Top := StrToInt(INI.ReadString('EditWeekForm', 'ypos', IntToStr(self.Top)));
EditWeekForm.Width := StrToInt(INI.ReadString('EditWeekForm', 'width', IntToStr(self.Width)));
EditWeekForm.Height := StrToInt(INI.ReadString('EditWeekForm', 'height', IntToStr(self.Height)));
s := INI.ReadString('EditWeekForm', 'state', GetEnumName(TypeInfo(TWindowState), integer(wsNormal)));
EditWeekForm.WindowState := TWindowState(GetEnumValue(TypeInfo(TWindowState), s));
DBForm.LabeledEdit1.Text := INI.ReadString('DBInfo', 'hostname', '');
DBForm.LabeledEdit2.Text := INI.ReadString('DBInfo', 'port', dbDefaultFirebirdPort);
DBForm.LabeledEdit5.Text := INI.ReadString('DBInfo', 'dbname', '');
DBForm.LabeledEdit3.Text := INI.ReadString('DBInfo', 'user', dbDefaultFirebirdUser);
EditSettingsForm.Left := StrToInt(INI.ReadString('SettingsForm', 'xpos', IntToStr(EditSettingsForm.Left)));
EditSettingsForm.Top := StrToInt(INI.ReadString('SettingsForm', 'ypos', IntToStr(EditSettingsForm.Top)));
EditSettingsForm.Width := StrToInt(INI.ReadString('SettingsForm', 'width', IntToStr(EditSettingsForm.Width)));
EditSettingsForm.Height := StrToInt(INI.ReadString('SettingsForm', 'height', IntToStr(EditSettingsForm.Height)));
s := INI.ReadString('SettingsForm', 'state', GetEnumName(TypeInfo(TWindowState), integer(wsNormal)));
EditSettingsForm.WindowState := TWindowState(GetEnumValue(TypeInfo(TWindowState), s));
defHoursUntilPause := StrToFloat(INI.ReadString('Defaults', 'HoursUntilPause',
FloatToStr(defHoursUntilPause, fs)), fs);
defHoursPerDay := StrToFloat(INI.ReadString('Defaults', 'HoursPerDay', FloatToStr(defHoursPerDay, fs)), fs);
defPausePerDay := StrToFloat(INI.ReadString('Defaults', 'PausePerDay', FloatToStr(defPausePerDay, fs)), fs);
colorMarkedDays := StrToInt(INI.ReadString('Defaults', 'ColorMarkedDays', IntToStr(colorMarkedDays)));
colorVacationDays := StrToInt(INI.ReadString('Defaults', 'ColorVacationDays', IntToStr(colorVacationDays)));
FLanguageID := INI.ReadString('Defaults', 'Language', defLanguageID);
option_openLatestFile := StrToBool(INI.ReadString('RecentFiles', 'open_Latest', BoolToStr(option_openLatestFile)));
for I := 0 to StrToInt(INI.ReadString('RecentFiles', 'count', '0')) - 1 do
begin
AddToOpenRecent(INI.ReadString('RecentFiles', IntToStr(I), ''), FOpenRecent, MenuOpenRecent);
end;
for I := 0 to EditWeekForm.WeekGrid.ColCount - 1 do
begin
EditWeekForm.WeekGrid.Columns.Items[I].Width :=
StrToInt(INI.ReadString('EditWeekForm', 'col' + IntToStr(I + 1),
IntToStr(EditWeekForm.WeekGrid.Columns.Items[I].Width)));
end;
for I := 0 to EditSettingsForm.StringGrid1.ColCount - 1 do
begin
EditSettingsForm.StringGrid1.ColWidths[I] :=
StrToInt(INI.ReadString('SettingsForm', 'col' + IntToStr(I + 1),
IntToStr(EditSettingsForm.StringGrid1.ColWidths[I])));
end;
for I := 0 to StringGrid1.ColCount - 1 do
begin
StringGrid1.Columns.Items[I].Width :=
StrToInt(INI.ReadString('MainForm', 'col' + IntToStr(I + 1), IntToStr(StringGrid1.Columns.Items[I].Width)));
end;
if (FLanguageID <> 'en') then
begin
loadFromLanguageFile('../languages/' + FLanguageID + '.lang');
translateCaptions;
end;
ApplyColor(StrToInt(INI.ReadString('Theme', 'color', IntToStr(defToolbarColor))));
INI.Free;
end;
procedure TForm1.ApplyColor(AColor: integer);
begin
Toolbar1.Color := AColor;
EditWeekForm.ToolBar1.Color := AColor;
PersonForm.Toolbar1.Color := AColor;
end;
procedure TForm1.UpdateWindow;
var
I: integer;
sum: double;
goal: double;
diff: double;
vacationdays: double;
locDay: TWorkDay;
begin
sum := 0;
goal := 0;
diff := 0;
vacationdays := 0;
Label1.Caption := txtSum + ':';
Label2.Caption := txtGoal + ':';
Label3.Caption := txtDiff + ':';
Label4.Caption := txtEarliestBegin + ':';
Label5.Caption := txtLatestLeave + ':';
Label6.Caption := txtVacation + ':';
Label7.Caption := txtLongestDay + ':';
// Person List
if (FPersonList.Count > 0) then
begin
NamesToComboBox(ComboBox1, FPersonList);
ComboBox1.ItemIndex := FPersonIndex;
// Timedata List
if (FPersonIndex >= 0) then
begin
WeekListsToComboBox(ComboBox2, FPersonList[FPersonIndex].TimeData);
end;
end
else
begin
ComboBox1.Clear;
ComboBox2.Clear;
end;
// Statistics on the right
for I := 0 to FWeekList.Count - 1 do
begin
sum += FWeekList.Items[I].getSum;
goal += FWeekList.Items[I].getGoalHours;
vacationdays += FWeekList.Items[I].getAmountOfVacation;
end;
WeeksToStringGrid(StringGrid1, FWeekList, FSelectionIndex);
if (FWeekList.Count > 0) then
begin
diff := sum - goal;
Label1.Caption := txtSum + ': ' + FormatFloat('0.00', sum) + ' h';
Label2.Caption := txtGoal + ': ' + FormatFloat('0.00', goal) + ' h';
Label3.Caption := txtDiff + ': ' + FormatFloat('0.00', diff) + ' h';
if (diff >= defHoursPerDay) then
begin
Label3.Caption := Label3.Caption + ' (' + FormatFloat('0.00', (diff / defHoursPerDay)) + ' d)';
end;
Label6.Caption := txtVacation + ': ' + FormatFloat('0.0', vacationdays) + ' ' + txtDays;
colorText(Label3, sum, goal, 0.5);
end;
if (getDayOfEarliestBegin(FWeekList) <> nil) then
begin
locDay := getDayOfEarliestBegin(FWeekList);
Label4.Caption := txtEarliestBegin + ': ' + locDay.StartTime.ToText +
' (' + DateToStr(locDay.Date) + ')';
end;
if (getDayOfLatestQuitting(FWeekList) <> nil) then
begin
locDay := getDayOfLatestQuitting(FWeekList);
Label5.Caption := txtLatestLeave + ': ' + locDay.EndTime.ToText +
' (' + DateToStr(locDay.Date) + ')';
end;
if (getLongestDay(FWeekList) <> nil) then
begin
locDay := getLongestDay(FWeekList);
Label7.Caption := txtLongestDay + ': ' + DateToStr(locDay.Date) + ' (' +
FloatToStr(locDay.getAmountOfTime) + ' h)';
end;
EnableButtons;
end;
procedure TForm1.EnableButtons;
begin
if (FWeekList.Count > 0) then
begin
Toolbar1.Buttons[1].Enabled := True;
Toolbar1.Buttons[2].Enabled := True;
ToolButton1.Enabled := True;
EditWeekButton.Enabled := True;
PopupEditPeriod.Enabled := True;
PopupRemovePeriod.Enabled := True;
MenuSaveAs.Enabled := True;
end
else
begin
Toolbar1.Buttons[1].Enabled := False;
Toolbar1.Buttons[2].Enabled := False;
ToolButton1.Enabled := False;
EditWeekButton.Enabled := False;
EditWeekButton.Enabled := False;
PopupEditPeriod.Enabled := False;
PopupRemovePeriod.Enabled := False;
MenuSaveAs.Enabled := False;
end;
MenuQuickSave.Enabled := FCanSave and (FCurrentFilePath <> '');
ToolButton1.Enabled := FCanSave and (FCurrentFilePath <> '');
MenuOpenRecent.Enabled := (MenuOpenRecent.Count > 0);
MenuMove.Enabled := (FWeekList.Count > 1);
end;
procedure TForm1.AddToOpenRecent(AFilePath: string; AList: TStringList; AMenuItem: TMenuItem);
var
I: integer;
found: integer;
begin
found := -1;
if (AFilePath <> '') then
begin
// delete earlier entries and clear menuitem
for I := 0 to AList.Count - 1 do
begin
if (AList[I] = AFilePath) then
found := I;
end;
if (found >= 0) then
begin
AList.Delete(found);
end;
AList.Add(AFilePath);
if (AList.Count > 10) then
begin
Alist.Delete(0);
end;
AMenuItem.Clear;
for I := AList.Count - 1 downto 0 do
begin
AMenuItem.Add(TMenuItem.Create(nil));
AMenuItem.Items[AList.Count - 1 - I].Caption := AList[I];
AMenuItem.Items[AList.Count - 1 - I].OnClick := @OpenRecentCLick;
end;
end;
UpdateWindow;
end;
procedure TForm1.OpenRecentCLick(Sender: TObject);
var
filename: string;
begin
filename := TMenuItem(Sender).Caption;
try
loadFromFile(filename, FWeekList);
StatusBar1.Panels[0].Text := '"' + ExtractFileName(filename) + '" loaded!';
FCurrentFilePath := filename;
AddToOpenRecent(FCurrentFilePath, FOpenRecent, MenuOpenRecent);
FCanSave := False;
except
on e: Exception do
begin
Application.MessageBox(PChar(emFileNotFound), 'File not found', 0);
FOpenRecent.Delete(FOpenRecent.Count - 1 - MenuOpenRecent.IndexOf(TMenuItem(Sender))); // Menu is reversed order
MenuOpenRecent.Delete(MenuOpenRecent.IndexOf(TMenuItem(Sender)));
end;
end;
UpdateWindow;
end;
procedure TForm1.MoveClick(Sender: TObject);
var
tempIndex: integer;
begin
if (FWeekList.Count > 1) then
begin
tempIndex := FSelectionIndex;
// Move Item to Top
if (Sender = MenuMoveTop) then
begin
FWeekList.Insert(0, TWorkWeek.Create(FWeekList.Items[FSelectionIndex]));
FWeekList.Delete(FSelectionIndex + 1);
tempIndex := 0;
FCanSave := True;
end;
// Move Item to Bottom
if (Sender = MenuMoveBottom) then
begin
FWeekList.Insert(FWeekList.Count, TWorkWeek.Create(FWeekList.Items[FSelectionIndex]));
FWeekList.Delete(FSelectionIndex);
tempIndex := FWeekList.Count - 1;
FCanSave := True;
end;
// Move Item 1 step up
if (Sender = MenuMoveUp) then
begin
if (FSelectionIndex >= 1) and (FSelectionIndex < FWeekList.Count) then
begin
FWeekList.Insert(FSelectionIndex - 1, TWorkWeek.Create(FWeekList.Items[FSelectionIndex]));
FWeekList.Delete(FSelectionIndex + 1);
tempIndex -= 1;
FCanSave := True;
end;
end;
// Move Item 1 step down
if (Sender = MenuMoveDown) then
begin
if (FSelectionIndex >= 0) and (FSelectionIndex < FWeekList.Count - 1) then
begin
FWeekList.Insert(FSelectionIndex + 2, TWorkWeek.Create(FWeekList.Items[FSelectionIndex]));
FWeekList.Delete(FSelectionIndex);
tempIndex += 1;
FCanSave := True;
end;
end;
updateWindow;
// Updating the EditweekForm
EditWeekForm.showWeek(FWeekList.Items[tempIndex], tempIndex);
EditWeekForm.WeekIndex := tempIndex;
WeeksToCombobox(EditWeekForm.ComboBox1, FWeekList);
WeeksToCombobox(EditWeekForm.ComboBox2, FWeekList);
EditWeekForm.ComboBox1.ItemIndex := tempIndex;
EditWeekForm.ComboBox2.ItemIndex := tempIndex;
end;
end;
procedure TForm1.TranslateCaptions;
begin
// Main Menu
MenuItem1.Caption := mcFile;
MenuItem2.Caption := mcEdit;
MenuItem5.Caption := mcShow;
MenuItem3.Caption := mcDatabase;
MenuItem9.Caption := mcOptions;
MenuItem4.Caption := mcHelp;
MenuNew.Caption := mcNew;
MenuSaveAs.Caption := mcSaveAs;
MenuQuickSave.Caption := mcSave;
MenuLoad.Caption := mcOpen;
MenuOpenRecent.Caption := mcOpenRecent;
MenuQuit.Caption := mcExit;
MenuPeople.Caption := mcPeople;
MenuStatistics.Caption := mcStatistics;
MenuDBSettings.Caption := mcDatabaseSettings;
MenuDBDownload.Caption := mcDatabaseDownload;
MenuDBUpload.Caption := mcDatabaseUpload;
MenuSettings.Caption := mcProgrammeSettings;
MenuColorTheme.Caption := mcColorTheme;
MenuLanguage.Caption := mcLanguage;
MenuManual.Caption := mcManual;
MenuAbout.Caption := mcAbout;
// Buttons
EditWeekForm.ApplyButton.Caption := bcApply;
EditSettingsForm.ApplyButton.Caption := bcApply;
PersonForm.ApplyButton.Caption := bcApply;
AddWeekForm.ApplyButton.Caption := bcApply;
EditWeekForm.BackButton.Caption := bcBack;
EditSettingsForm.BackButton.Caption := bcBack;
PersonForm.BackButton.Caption := bcBack;
DBForm.BackButton.Caption := bcBack;
AddWeekForm.BackButton.Caption := bcBack;
DBForm.ResetButton.Caption := bcReset;
EditSettingsForm.ResetButton.Caption := bcReset;
// form-Captions
AboutForm.Caption := mcAbout;
EditSettingsForm.Caption := mcProgrammeSettings;
AboutForm.PageControl1.Pages[0].Caption := mcAbout;
PersonForm.Caption := mcPeople;
DBForm.Caption := mcDatabaseSettings;
GroupBox1.Caption := txtSummary;
EditWeekForm.GroupBox1.Caption := txtSummary;
// StringGrid
StringGrid1.Columns.Items[1].Title.Caption := txtPeriod;
StringGrid1.Columns.Items[2].Title.Caption := txtDays;
StringGrid1.Columns.Items[3].Title.Caption := txtSum;
StringGrid1.Columns.Items[4].Title.Caption := txtGoal;
StringGrid1.Columns.Items[5].Title.Caption := txtDiff;
EditWeekForm.WeekGrid.Columns.Items[5].Title.Caption := txtVacation;
EditWeekForm.WeekGrid.Columns.Items[6].Title.Caption := txtSum;
EditWeekForm.WeekGrid.Columns.Items[7].Title.Caption := txtDiff;
updateWindow;
Groupbox1.Repaint;
EditWeekForm.UpdateWindow;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2018 Kike Pérez
Unit : Quick.Logger.Provider.ADO
Description : Log ADO DB Provider
Author : Kike Pérez
Version : 1.22
Created : 21/05/2018
Modified : 26/05/2018
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Logger.Provider.ADODB;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
Data.Win.ADODB,
Winapi.ActiveX,
Quick.Commons,
Quick.Logger;
type
TFieldsMapping = class
private
fEventDate : string;
fEventType : string;
fMsg : string;
fEnvironment : string;
fPlatformInfo : string;
fOSVersion : string;
fAppName : string;
fUserName : string;
fHost : string;
public
property EventDate : string read fEventDate write fEventDate;
property EventType : string read fEventType write fEventType;
property Msg : string read fMsg write fMsg;
property Environment : string read fEnvironment write fEnvironment;
property PlatformInfo : string read fPlatformInfo write fPlatformInfo;
property OSVersion : string read fOSVersion write fOSVersion;
property AppName : string read fAppName write fAppName;
property UserName : string read fUserName write fUserName;
property Host : string read fHost write fHost;
end;
TDBProvider = (dbMSAccess2000, dbMSAccess2007, dbMSSQL, dbMSSQLnc10, dbMSSQLnc11, dbAS400);
const
{$IFDEF DELPHIXE7_UP}
ProviderName : array of string = ['Microsoft.Jet.OLEDB.4.0','Microsoft.ACE.OLEDB.12.0','SQLOLEDB.1','SQLNCLI10','SQLNCLI11','IBMDA400'];
{$ELSE}
ProviderName : array[0..5] of string = ('Microsoft.Jet.OLEDB.4.0','Microsoft.ACE.OLEDB.12.0','SQLOLEDB.1','SQLNCLI10','SQLNCLI11','IBMDA400');
{$ENDIF}
type
{$M+}
TDBConfig = class
private
fDBProvider : TDBProvider;
fServer : string;
fDatabase : string;
fTable : string;
fUserName : string;
fPassword : string;
published
property Provider : TDBProvider read fDBProvider write fDBProvider;
property Server : string read fServer write fServer;
property Database : string read fDatabase write fDatabase;
property Table : string read fTable write fTable;
property UserName : string read fUserName write fUserName;
property Password : string read fPassword write fPassword;
end;
{$M-}
TLogADODBProvider = class (TLogProviderBase)
private
fDBConnection : TADOConnection;
fDBQuery : TADOQuery;
fConnectionString : string;
fDBConfig : TDBConfig;
fFieldsMapping : TFieldsMapping;
function CreateConnectionString : string;
function CreateTable : Boolean;
procedure AddColumnToTable(const aColumnName, aDataType : string);
procedure AddToQuery(var aFields, aValues : string; const aNewField, aNewValue : string); overload;
//procedure AddToQuery(var aFields, aValues : string; const aNewField : string; aNewValue : Integer); overload;
public
constructor Create; override;
destructor Destroy; override;
property ConnectionString : string read fConnectionString write fConnectionString;
property DBConfig : TDBConfig read fDBConfig write fDBConfig;
property FieldsMapping : TFieldsMapping read fFieldsMapping write fFieldsMapping;
procedure Init; override;
procedure Restart; override;
procedure WriteLog(cLogItem : TLogItem); override;
end;
var
GlobalLogADODBProvider : TLogADODBProvider;
implementation
constructor TLogADODBProvider.Create;
begin
inherited;
CoInitialize(nil);
LogLevel := LOG_ALL;
//set default db fields mapping
fFieldsMapping := TFieldsMapping.Create;
fFieldsMapping.EventDate := 'EventDate';
fFieldsMapping.EventType := 'EventType';
fFieldsMapping.Msg := 'Msg';
fFieldsMapping.Environment := 'Environment';
fFieldsMapping.PlatformInfo := 'PlaftormInfo';
fFieldsMapping.OSVersion := 'OSVersion';
fFieldsMapping.AppName := 'AppName';
fFieldsMapping.UserName := 'UserName';
fFieldsMapping.Host := 'Host';
//set default db config
fDBConfig := TDBConfig.Create;
fDBConfig.Provider := dbMSSQL;
fDBConfig.Server := 'localhost';
fDBConfig.Table := 'Logger';
IncludedInfo := [iiAppName,iiHost];
end;
function TLogADODBProvider.CreateConnectionString: string;
begin
Result := Format('Provider=%s;Persist Security Info=False;User ID=%s;Password=%s;Database=%s;Data Source=%s',[
ProviderName[Integer(fDBConfig.Provider)],
fDBConfig.UserName,
fDBConfig.Password,
fDBConfig.Database,
fDBConfig.Server]);
end;
procedure TLogADODBProvider.AddColumnToTable(const aColumnName, aDataType : string);
begin
fDBQuery.SQL.Clear;
//fDBQuery.SQL.Add(Format('IF COL_LENGTH(''%s'', ''%s'') IS NULL',[fDBConfig.Table,aColumnName]));
fDBQuery.SQL.Add('IF COL_LENGTH(:LOGTABLE,:NEWFIELD) IS NULL');
fDBQuery.SQL.Add('BEGIN');
fDBQuery.SQL.Add(Format('ALTER TABLE %s',[fDBConfig.Table]));
fDBQuery.SQL.Add(Format('ADD %s %s',[aColumnName,aDataType]));
fDBQuery.SQL.Add('END');
fDBQuery.Parameters.ParamByName('LOGTABLE').Value := fDBConfig.Table;
fDBQuery.Parameters.ParamByName('NEWFIELD').Value := aColumnName;
if fDBQuery.ExecSQL = 0 then raise Exception.Create('Error creating table fields');
end;
function TLogADODBProvider.CreateTable: Boolean;
begin
fDBQuery.SQL.Clear;
fDBQuery.SQL.Add('IF NOT EXISTS (SELECT name FROM sys.tables WHERE name = :LOGTABLE)');
fDBQuery.SQL.Add(Format('CREATE TABLE %s (',[fDBConfig.Table]));
fDBQuery.SQL.Add(Format('%s DateTime,',[fFieldsMapping.EventDate]));
fDBQuery.SQL.Add(Format('%s varchar(20),',[fFieldsMapping.EventType]));
fDBQuery.SQL.Add(Format('%s varchar(max));',[fFieldsMapping.Msg]));
fDBQuery.Parameters.ParamByName('LOGTABLE').Value := fDBConfig.Table;
if fDBQuery.ExecSQL = 0 then raise Exception.Create('Error creating table!');
if iiEnvironment in IncludedInfo then AddColumnToTable(fFieldsMapping.Environment,'varchar(50)');
if iiPlatform in IncludedInfo then AddColumnToTable(fFieldsMapping.PlatformInfo,'varchar(50)');
if iiOSVersion in IncludedInfo then AddColumnToTable(fFieldsMapping.OSVersion,'varchar(70)');
if iiHost in IncludedInfo then AddColumnToTable(fFieldsMapping.Host,'varchar(20)');
if iiUserName in IncludedInfo then AddColumnToTable(fFieldsMapping.UserName,'varchar(50)');
if iiAppName in IncludedInfo then AddColumnToTable(fFieldsMapping.AppName,'varchar(70)');
Result := True;
end;
destructor TLogADODBProvider.Destroy;
begin
if Assigned(fDBQuery) then fDBQuery.Free;
if Assigned(fDBConnection) then fDBConnection.Free;
fFieldsMapping.Free;
fDBConfig.Free;
CoUninitialize;
inherited;
end;
procedure TLogADODBProvider.Init;
begin
fDBConnection := TADOConnection.Create(nil);
if fConnectionString <> '' then fDBConnection.ConnectionString := fConnectionString
else fConnectionString := CreateConnectionString;
fDBConnection.ConnectionString := fConnectionString;
fDBConnection.LoginPrompt := False;
fDBConnection.Connected := True;
fDBQuery := TADOQuery.Create(nil);
fDBQuery.Connection := fDBConnection;
CreateTable;
inherited;
end;
procedure TLogADODBProvider.Restart;
begin
Stop;
if Assigned(fDBQuery) then fDBQuery.Free;
if Assigned(fDBConnection) then fDBConnection.Free;
Init;
end;
procedure TLogADODBProvider.AddToQuery(var aFields, aValues : string; const aNewField, aNewValue : string);
begin
aFields := Format('%s,%s',[aFields,aNewField]);
aValues := Format('%s,''%s''',[aValues,aNewValue]);
end;
//procedure TLogADODBProvider.AddToQuery(var aFields, aValues : string; const aNewField : string; aNewValue : Integer);
//begin
// aFields := Format('%s,%s',[aFields,aNewField]);
// aValues := Format('%s,%d',[aValues,aNewValue]);
//end;
procedure TLogADODBProvider.WriteLog(cLogItem : TLogItem);
var
fields : string;
values : string;
begin
//prepare fields and values for insert query
fields := fFieldsMapping.EventDate;
values := Format('''%s''',[DateTimeToStr(cLogItem.EventDate,FormatSettings)]);
AddToQuery(fields,values,fFieldsMapping.EventType,EventTypeName[cLogItem.EventType]);
if iiHost in IncludedInfo then AddToQuery(fields,values,fFieldsMapping.Host,SystemInfo.HostName);
if iiAppName in IncludedInfo then AddToQuery(fields,values,fFieldsMapping.AppName,SystemInfo.AppName);
if iiEnvironment in IncludedInfo then AddToQuery(fields,values,fFieldsMapping.Environment,Environment);
if iiOSVersion in IncludedInfo then AddToQuery(fields,values,fFieldsMapping.OSVersion,SystemInfo.OsVersion);
if iiPlatform in IncludedInfo then AddToQuery(fields,values,fFieldsMapping.PlatformInfo,PlatformInfo);
if iiUserName in IncludedInfo then AddToQuery(fields,values,fFieldsMapping.UserName,SystemInfo.UserName);
AddToQuery(fields,values,fFieldsMapping.Msg,StringReplace(cLogItem.Msg,'''','"',[rfReplaceAll]));
fDBQuery.SQL.Clear;
fDBQuery.SQL.Add(Format('INSERT INTO %s (%s)',[fDBConfig.Table,fields]));
fDBQuery.SQL.Add(Format('VALUES (%s)',[values]));
if fDBQuery.ExecSQL = 0 then raise ELogger.Create('[TLogADODBProvider] : Error trying to write to ADODB');
end;
initialization
GlobalLogADODBProvider := TLogADODBProvider.Create;
finalization
if Assigned(GlobalLogADODBProvider) and (GlobalLogADODBProvider.RefCount = 0) then GlobalLogADODBProvider.Free;
end.
|
unit FMX.Devgear.HelperClass;
interface
uses
System.Classes,
FMX.Graphics,
System.SysUtils,
IdHttp, IdTCPClient;
type
TBitmapHelper = class helper for TBitmap
public
function CreateThumbnailWithScale(const AWidth, AHeight: Integer): TBitmap;
procedure LoadFromUrl(AUrl: string);
procedure LoadThumbnailFromUrl(AUrl: string; const AFitWidth, AFitHeight: Integer);
procedure SaveToFileFromUrl(AUrl, APath: String; CallBack: TProc = nil);
end;
var
Mem: TMemoryStream;
// Http: TIdHttp;
implementation
uses
System.Types, AnonThread;
function TBitmapHelper.CreateThumbnailWithScale(const AWidth,
AHeight: Integer): TBitmap;
var
Scale: Single;
NewWidth, NewHeight: Integer;
begin
if Self.Height > Self.Width then begin
NewHeight := AHeight;
Scale := NewHeight / Self.Height;
NewWidth := Round(Self.Width * Scale);
end
else if Self.Height < Self.Width then begin
NewWidth := AWidth;
Scale := NewWidth / Self.Width;
NewHeight := Round(Self.Height * Scale);
end
else begin
NewHeight := AWidth;
NewWidth := AWidth;
end;
Result := Self.CreateThumbnail(NewWidth, NewHeight);
end;
procedure TBitmapHelper.LoadFromUrl(AUrl: string);
var
_Thread: TAnonymousThread<TMemoryStream>;
begin
_Thread := TAnonymousThread<TMemoryStream>.Create(
function: TMemoryStream
var
Http: TIdHttp;
begin
Result := TMemoryStream.Create;
if not Assigned(Http) then
Http := TIdHttp.Create(nil);
try
try
Http.Get(AUrl, Result);
except
Result.Free;
end;
finally
Http.Free;
end;
end,
procedure(AResult: TMemoryStream)
begin
if Assigned(AResult) then begin
if AResult.Size > 0 then
LoadFromStream(AResult);
AResult.Free;
end;
end,
procedure(AException: Exception)
begin
end
);
end;
procedure TBitmapHelper.LoadThumbnailFromUrl(AUrl: string; const AFitWidth,
AFitHeight: Integer);
var
Bitmap: TBitmap;
scale: Single;
begin
LoadFromUrl(AUrl);
scale := 1;//RectF(0, 0, Width, Height).Fit(RectF(0, 0, AFitWidth, AFitHeight));
Bitmap := CreateThumbnail(Round(Width / scale), Round(Height / scale));
try
Assign(Bitmap);
finally
Bitmap.Free;
end;
end;
procedure TBitmapHelper.SaveToFileFromUrl(AUrl, APath: String; CallBack: TProc);
var
_Thread: TAnonymousThread<TMemoryStream>;
begin
_Thread := TAnonymousThread<TMemoryStream>.Create(
function: TMemoryStream
var
Http: TIdHttp;
begin
Result := TMemoryStream.Create;
Http := TIdHttp.Create(nil);
try
try
Http.Get(AUrl, Result);
except
Result.Free;
end;
finally
Http.Free;
end;
end,
procedure(AResult: TMemoryStream)
begin
if Assigned(AResult) then begin
try
if AResult.Size > 0 then begin
AResult.SaveToFile(APath);
if Assigned(CallBack) then
CallBack;
end;
finally
AResult.Free;
end;
end;
end,
procedure(AException: Exception)
begin
end
);
end;
end.
|
unit CustomInspector;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
TypInfo, Dialogs, StdCtrls,
dcgen, dcsystem, dcdsgnstuff, dcdsgnutil, dcedit, oinspect;
type
TCustomInplaceEdit = class(TOInplaceEdit)
protected
function GetEditType: TControlClass; override;
function GetPopupType: TWinControlClass; override;
end;
//
TCustomProperty = class(TInterfacedObject, IDcDsgnProperty)
public
procedure GetProperties(Proc: TDCDsgnGetPropProc); virtual;
function GetPropInfo: PPropInfo; virtual;
function GetName: string; virtual;
procedure Edit; virtual;
function AllEqual: Boolean; virtual;
function GetValue: string; virtual;
procedure GetValues(Proc: TGetStrProc); virtual;
procedure SetValue(const Value: string); virtual;
function GetPropType: PTypeInfo; virtual;
function AutoFill: Boolean; virtual;
procedure Activate; virtual;
function ValueAvailable: Boolean; virtual;
function GetAttributes: TDCDsgnPropertyAttributes; virtual;
function HasInstance(Instance: TPersistent): Boolean; virtual;
function GetEditLimit: Integer; virtual;
function GetEditValue(out Value: string): Boolean; virtual;
procedure Revert; virtual;
destructor Destroy; override;
end;
//
TCustomInspector = class(TCustomObjectInspector)
protected
PropList: TList;
protected
{
procedure GetAllPropertyEditors(Components: TComponentList;
Filter: TTypeKinds; Designer: TFormDesigner;
Proc: TGetPropEditProc); override;
}
function GetEditorClass(const PropEdit: TDCDsgnProp): TControlClass; override;
function GetInplaceEditClass: TInplaceEditClass; override;
function GetPopupClass(const PropEdit: TDCDsgnProp): TWinControlClass; override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
{ TCustomInplaceEdit }
function TCustomInplaceEdit.GetEditType: TControlClass;
begin
Result := TEdit; //TDCSimpleEdit;
end;
function TCustomInplaceEdit.GetPopupType: TWinControlClass;
begin
Result := TPopupListBox;
end;
{ TCustomProperty }
procedure TCustomProperty.Activate;
begin
//
end;
function TCustomProperty.AllEqual: Boolean;
begin
Result := false;
end;
function TCustomProperty.AutoFill: Boolean;
begin
Result := true;
end;
destructor TCustomProperty.Destroy;
begin
inherited;
end;
procedure TCustomProperty.Edit;
begin
//
end;
function TCustomProperty.GetAttributes: TDCDsgnPropertyAttributes;
begin
Result := [ paDialog ];
end;
function TCustomProperty.GetEditLimit: Integer;
begin
Result := 65;
end;
function TCustomProperty.GetEditValue(out Value: string): Boolean;
begin
Value := 'Edit Value';
Result := true;
end;
function TCustomProperty.GetName: string;
begin
Result := 'Property';
end;
procedure TCustomProperty.GetProperties(Proc: TDCDsgnGetPropProc);
begin
//
end;
function TCustomProperty.GetPropInfo: PPropInfo;
begin
Result := nil;
end;
function TCustomProperty.GetPropType: PTypeInfo;
begin
Result := nil;
end;
function TCustomProperty.GetValue: string;
begin
Result := 'Value';
end;
procedure TCustomProperty.GetValues(Proc: TGetStrProc);
begin
//
end;
function TCustomProperty.HasInstance(Instance: TPersistent): Boolean;
begin
Result := false;
end;
procedure TCustomProperty.Revert;
begin
//
end;
procedure TCustomProperty.SetValue(const Value: string);
begin
//
end;
function TCustomProperty.ValueAvailable: Boolean;
begin
Result := true;
end;
{ TCustomInspector }
constructor TCustomInspector.Create(inOwner: TComponent);
begin
inherited;
CurrentControl := Self;
PropList := TList.Create;
end;
destructor TCustomInspector.Destroy;
begin
PropList.Free;
inherited;
end;
function TCustomInspector.GetEditorClass(
const PropEdit: TDCDsgnProp): TControlClass;
begin
Result := TDCSimpleEdit;
end;
{
procedure TCustomInspector.GetAllPropertyEditors(Components: TComponentList;
Filter: TTypeKinds; Designer: TFormDesigner; Proc: TGetPropEditProc);
var
i: Integer;
prop: TCustomProperty;
begin
PropList.Clear;
for i := 0 to 5 do
begin
prop := TCustomProperty.Create;
PropList.Add(prop);
Proc(prop);
end;
end;
}
function TCustomInspector.GetPopupClass(
const PropEdit: TDCDsgnProp): TWinControlClass;
begin
Result := TPopupListBox;
end;
function TCustomInspector.GetInplaceEditClass: TInplaceEditClass;
begin
Result := TCustomInplaceEdit;
end;
end.
|
(* SymTab: HDO, 2004-02-06
------
Symbol table handling for the MiniPascal Interpreter and
the MiniPascal Compiler.
===================================================================*)
UNIT SymTab;
INTERFACE
PROCEDURE InitSymbolTable;
PROCEDURE DeclVar(id: STRING; VAR ok: BOOLEAN);
FUNCTION IsDecl(id: STRING): BOOLEAN;
(*for the MiniPascal Interpreter only:*)
PROCEDURE SetVal(id: STRING; val: INTEGER);
PROCEDURE GetVal(id: STRING; VAR val: INTEGER);
(*for the MiniPascal Compiler only:*)
FUNCTION AddrOf(id: STRING): INTEGER;
IMPLEMENTATION
CONST
max = 20;
TYPE
VarInfo = RECORD
id: STRING; (*identifier*)
val: INTEGER; (*used in the interpreter only*)
addr: INTEGER; (*used in the compiler only*)
END; (*RECORD*)
VAR
st: ARRAY [1 .. max] OF VarInfo;
n: INTEGER;
FUNCTION Lookup (id: STRING): INTEGER;
VAR
i: INTEGER;
BEGIN
i := 1;
WHILE (i <= n) AND (id <> st[i].id) DO BEGIN
i := i + 1;
END; (*WHILE*)
IF i <= n THEN
Lookup := i (*id is at index i in st*)
ELSE
Lookup := 0; (*id not found*)
END; (*Lookup*)
PROCEDURE InitSymbolTable;
(*-----------------------------------------------------------------*)
BEGIN
n := 0;
END; (*InitSymbolTable*)
PROCEDURE DeclVar(id: STRING; VAR ok: BOOLEAN);
(*-----------------------------------------------------------------*)
BEGIN
ok := (Lookup(id) = 0) AND (n < max);
IF ok THEN BEGIN
n := n + 1;
st[n].id := id;
st[n].val := 0;
st[n].addr := n - 1;
END; (*if*)
END; (*DeclVar*)
FUNCTION IsDecl(id: STRING): BOOLEAN;
(*-----------------------------------------------------------------*)
BEGIN
IsDecl := (Lookup(id) > 0);
END; (*IsDecl*)
(*for the MiniPascal Interpreter only:*)
PROCEDURE SetVal(id: STRING; val: INTEGER);
(*-----------------------------------------------------------------*)
BEGIN
st[Lookup(id)].val := val;
END; (*SetVal*)
PROCEDURE GetVal(id: STRING; VAR val: INTEGER);
(*-----------------------------------------------------------------*)
BEGIN
val := st[Lookup(id)].val;
END; (*SetVal*)
(*for the MiniPascal Compiler only:*)
FUNCTION AddrOf(id: STRING): INTEGER;
(*-----------------------------------------------------------------*)
BEGIN (*AdrOf*)
AddrOf := st[Lookup(id)].addr;
END; (*AddrOf*)
END. (*SymTab*) |
(*
Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES
Original name: 0080.PAS
Description: Numeric Converter
Author: MARCO ANTONIO ALVARADO PEREZ
Date: 11-29-96 08:17
*)
{----------------------------------------------------------------------------}
{ NUMERIC CONVERTER version 2.1
Written by Marco Antonio Alvarado Perez.
Costa Rica, September 1996.
Internet: 9500149@ITCR-LI.LI.ITCR.Ac.CR
About the tool:
Firstly I wrote the program for curiosity, and then I found it was very
useful to translate those huge bitmaps that I wanted to insert in the
source code. Actually, I use a version that reads text files and builts the
arrays.
About Turbo Pascal 7.0:
You can call this program directly from the editor. Insert it as a tool
with Options - Tools in the menu bar.
About the language:
I hope you could understand my English. I have source code in Spanish, if
you want a copy just send me E-Mail.
}
{----------------------------------------------------------------------------}
PROGRAM NumericConverter;
CONST
GreaterDigit = 15;
Digits : ARRAY [0..GreaterDigit] OF Char = '0123456789ABCDEF';
FUNCTION DigitToValue (Digit : Char) : Byte;
VAR
Index : Byte;
BEGIN
Digit := UpCase (Digit);
Index := GreaterDigit;
WHILE (Index > 0) AND (Digit <> Digits [Index]) DO Dec (Index);
{unknow digit = 0}
DigitToValue := Index;
END;
FUNCTION PositionValue (Position, Base : Byte) : LongInt;
VAR
Value : LongInt;
Index : Byte;
BEGIN
Value := 1;
FOR Index := 2 TO Position DO Value := Value * Base;
PositionValue := Value;
END;
FUNCTION StringToValue (Str : STRING; Base : Byte) : LongInt;
VAR
Value : LongInt;
Index : Byte;
BEGIN
Value := 0;
FOR Index := 1 TO Length (Str) DO Inc (Value, DigitToValue (Str
[Index]) * PositionValue (Length (Str) - Index + 1, Base));
StringToValue := Value;
END;
FUNCTION ValueToString (Value : LongInt; Base : Byte) : STRING;
VAR
Str : STRING;
BEGIN
IF Value = 0 THEN Str := Digits [0] ELSE
BEGIN
Str := '';
WHILE Value > 0 DO
BEGIN
Str := Digits [Value MOD Base] + Str;
Value := Value DIV Base;
END;
END;
ValueToString := Str;
END;
PROCEDURE ShowHelp;
BEGIN
WriteLn ('CONV - Numeric Converter');
WriteLn;
WriteLn ('Written by Marco Antonio Alvarado.');
WriteLn ('Costa Rica, September 1996.');
WriteLn;
WriteLn ('Internet: 9500149@ITCR-LI.LI.ITCR.Ac.CR');
WriteLn;
WriteLn ('Use:');
WriteLn (' CONV <number> <base of number> <base to convert>');
WriteLn;
WriteLn ('Bases:');
WriteLn (' B binary');
WriteLn (' O octal');
WriteLn (' D decimal');
WriteLn (' H hexadecimal');
WriteLn;
WriteLn ('Example:');
WriteLn (' CONV A000 H D');
END;
VAR
Number : STRING;
Base : STRING [1];
BaseNumber : Byte;
BaseConvert : Byte;
BEGIN
Number := '0';
BaseNumber := 10;
BaseConvert := 10;
IF ParamCount = 3 THEN
BEGIN
Number := ParamStr (1);
Base := ParamStr (2);
Base := UpCase (Base [1]);
IF Base = 'B' THEN BaseNumber := 2;
IF Base = 'O' THEN BaseNumber := 8;
IF Base = 'D' THEN BaseNumber := 10;
IF Base = 'H' THEN BaseNumber := 16;
Base := ParamStr (3);
Base := UpCase (Base [1]);
IF Base = 'B' THEN BaseConvert := 2;
IF Base = 'O' THEN BaseConvert := 8;
IF Base = 'D' THEN BaseConvert := 10;
IF Base = 'H' THEN BaseConvert := 16;
Write (Number, ' ', ParamStr (2), ' = ');
WriteLn (ValueToString (StringToValue (Number, BaseNumber), BaseConvert),
' ', ParamStr (3));
END ELSE ShowHelp;
END.
|
unit uDMApplicationHub;
interface
uses
SysUtils, Classes, DB, DBClient, MConnect, SConnect, Forms, uNTDataSetControl,
uNTUpdateControl, uNTTraceControl, cxContainer, cxEdit;
const
FK_ERROR_ID = 'COLUMN REFERENCE constraint';
type
TDMApplicationHub = class(TDataModule)
conDCOM: TDCOMConnection;
conTeste: TSharedConnection;
conSocket: TSocketConnection;
conWeb: TWebConnection;
conLookup: TSharedConnection;
scEdit: TcxEditStyleController;
procedure DataModuleDestroy(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
private
fClientID,
fStore,
fStation : String;
FDataSetControl: TmrDataSetControl;
FUpdateControl: TmrUpdateControl;
FActiveConnection: TDispatchConnection;
FTraceControl: TmrTraceControl;
procedure SetConnectionProperties;
procedure ReconcileError(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction);
procedure ShowFKError(aFKName: String);
function ExtractConstraintName(aMessage: String): String;
public
property ActiveConnection: TDispatchConnection read FActiveConnection write FActiveConnection;
property DataSetControl: TmrDataSetControl read FDataSetControl write FDataSetControl;
property UpdateControl: TmrUpdateControl read FUpdateControl write FUpdateControl;
property TraceControl: TmrTraceControl read FTraceControl write FTraceControl;
end;
var
DMApplicationHub: TDMApplicationHub;
implementation
uses IniFiles, uHandleException, mrMsgBox;
{$R *.dfm}
procedure TDMApplicationHub.DataModuleCreate(Sender: TObject);
begin
SetConnectionProperties;
FDataSetControl := TmrDataSetControl.Create(Self);
FDataSetControl.Connection := ActiveConnection;
FDataSetControl.OnReconcileError := ReconcileError;
FUpdateControl := TmrUpdateControl.Create;
FUpdateControl.Connection := ActiveConnection;
FUpdateControl.OnReconcileError := ReconcileError;
FTraceControl := TmrTraceControl.Create;
FTraceControl.Connection := ActiveConnection;
end;
procedure TDMApplicationHub.DataModuleDestroy(Sender: TObject);
begin
FActiveConnection.AppServer.Logout(fClientID);
FActiveConnection.Connected := False;
end;
procedure TDMApplicationHub.ReconcileError(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction);
begin
Action := raCancel;
// RollBack a exist Transaction
if ActiveConnection.AppServer.InTransaction then
ActiveConnection.AppServer.RollBackTransaction;
if (UpdateKind = ukDelete) and (ExtractConstraintName(E.Message) <> '') then
ShowFKError(ExtractConstraintName(E.Message))
else
raise EmrReconcileError.Create(E.Message, UpdateKind);
end;
procedure TDMApplicationHub.SetConnectionProperties;
var
ConType: String;
begin
with TIniFile.Create(ExtractFilePath(Application.ExeName) + 'AppClient.ini') do
try
ConType := ReadString('Connection', 'Type', '');
fClientID := ReadString('Connection', 'ClientID', '');
fStore := ReadString('Connection', 'Store', '');
fStation := ReadString('Connection', 'Station', '');
if ConType = 'SOCKET' then
begin
FActiveConnection := conSocket;
TSocketConnection(FActiveConnection).Host := ReadString('Connection', 'Host', '');
end
else if ConType = 'DCOM' then
begin
FActiveConnection := conDCOM;
TDCOMConnection(FActiveConnection).ComputerName := ReadString('Connection', 'Host', '');
end
else if ConType = 'WEB' then
begin
FActiveConnection := conWeb;
TWebConnection(FActiveConnection).Proxy := ReadString('Connection', 'Host', '');
end;
conTeste.ParentConnection := FActiveConnection;
FActiveConnection.ServerName := ReadString('Connection', 'ServerName', '');
FActiveConnection.ServerGUID := ReadString('Connection', 'ServerGUID', '');
FActiveConnection.Connected := True;
FActiveConnection.AppServer.Login(fClientID, fStore, fStation);
finally
Free;
end;
end;
procedure TDMApplicationHub.ShowFKError(aFKName: String);
var
sTableName: String;
begin
//sTableName := ActiveConnection.AppServer.GetTableNameByFK(aFKName);
MsgBox('Registro não pode ser deletado._Ele possui referência na tabela [' + sTableName + '].', vbOkOnly +vbWaring);
end;
function TDMApplicationHub.ExtractConstraintName(aMessage: String): String;
var
iBegin, iEnd: integer;
begin
iBegin := POS(FK_ERROR_ID, aMessage);
Result := '';
if iBegin <> 0 then
begin
Result := Copy(aMessage, iBegin + Length(FK_ERROR_ID)+2, Length(aMessage));
iEnd := POS('''', Result);
Result := Copy (Result, 1, iEnd-1);
end;
end;
end.
|
//=============================================================================
// sgGraphics.pas
//=============================================================================
//
// The Graphics unit is responsible for all of the drawing of anything to the
// screen or other surfaces. The standard draw routines draw to the
// screen using the camera settings. Finally the overloaded drawing methods
// with a destination Bitmap will draw onto the supplied bitmap.
//
//=============================================================================
/// The graphics code of SwinGame is used to draw primitive shapes to the screen
/// or onto bitmaps.
///
/// @module Graphics
/// @static
unit sgGraphics;
//=============================================================================
interface
uses sgTypes;
//=============================================================================
//----------------------------------------------------------------------------
// Window management
//----------------------------------------------------------------------------
/// Sets the icon for the window. This must be called before openning the
/// graphics window. The icon is loaded as a bitmap, though this can be from
/// any kind of bitmap file.
///
/// @param filename The name of the file to load as the images icon
///
///Side Effects
/// - The icon will be loaded and used as the windows icon when the window
/// is opened.
///
/// @lib
procedure SetIcon(const filename: String);
/// Returns the number of resolutions in the list of available resolutions.
///
/// @lib
function NumberOfResolutions(): Longint;
/// Returns the details of one of the available resolutions. Use idx from 0 to
/// `NumberOfResolutions` - 1 to access all of the available resolutions.
///
/// @lib
function AvailableResolution(idx: LongInt): Resolution;
/// Opens the graphical window so that it can be drawn onto. You can set the
/// icon for this window using `SetIcon`. The window itself is only drawn when
/// you call `RefreshScreen`. All windows are opened at 32 bits per pixel. You
/// can toggle fullscreen using `ToggleFullScreen`. The window is closed when
/// the application terminates.
///
/// @param caption The caption for the window
/// @param width The width of the window
/// @param height The height of the window
///
/// Side Effects:
/// - A graphical window is opened
///
/// @lib
/// @uname OpenGraphicsWindow
/// @sn openGraphicsWindow:%s width:%s height:%s
///
/// @deprecated
procedure OpenGraphicsWindow(const caption: String; width, height: Longint); overload;
/// Shows the SwinGame intro splash screen.
/// It would be great if you could include this at the start of
/// your game to help us promote the SwinGame API.
///
/// @lib
///
/// @deprecated
procedure ShowSwinGameSplashScreen();
/// Saves the current screen a bitmap file. The file will be saved into the
/// current directory.
///
/// @param basename The base name for the screen shot. e.g. "GemCollector"
///
/// Side Effects:
/// - Saves the current screen image to a bitmap file.
///
/// @lib TakeScreenshot
procedure TakeScreenshot(const basename: String);
//----------------------------------------------------------------------------
// Refreshing the screen
//----------------------------------------------------------------------------
/// Draws the current drawing to the screen. This must be called to display
/// anything to the screen. This will draw all drawing operations, as well
/// as the text being entered by the user.
///
/// Side Effects:
/// - The current drawing is shown on the screen.
///
/// @lib RefreshScreen
procedure RefreshScreen(); overload;
/// Refresh with a target FPS. This will delay a period of time that will
/// approximately meet the targetted frames per second.
///
/// @lib RefreshScreenRestrictFPS
procedure RefreshScreen(TargetFPS: LongInt); overload;
/// Refresh the display on the passed in window.
///
/// @lib RefreshScrenWindowFPS
procedure RefreshScreen(wnd: Window; targetFPS: Longint); overload;
//----------------------------------------------------------------------------
// Color
//----------------------------------------------------------------------------
/// Creates and returns a random color where R, G, B and A are all randomised.
///
/// @lib
///
/// @doc_group colors
function RandomColor(): Color;
/// Creates and returns a random color where R, G, and B are all randomised, and A is set
/// to the passed in value.
///
/// @param alpha: the opacity of the random color
///
/// @lib
///
/// @doc_group colors
function RandomRGBColor(alpha: Byte): Color;
/// Gets a color given its RGBA components.
///
/// @param red, green, blue, alpha: Components of the color
/// @returns: The matching colour
///
/// @lib
/// @sn rgbaColorRed:%s green:%s blue:%s alpha:%s
///
/// @doc_group colors
function RGBAColor(red, green, blue, alpha: Byte): Color;
/// Gets a color given its RGB components.
///
/// @param red, green, blue: Components of the color
/// @returns: The matching colour
///
/// @lib RGBAColor(red, green, blue, 255)
/// @uname RGBColor
/// @sn rgbColorRed:%s green:%s blue:%s
///
/// @doc_group colors
function RGBColor(red, green, blue: Byte): Color;
/// Gets a color given its RGBA components.
///
/// @lib
/// @sn colorComponentsOf:%s red:%s green:%s blue:%s alpha:%s
///
/// @doc_group colors
procedure ColorComponents(c: Color; out r, g, b, a: Byte);
/// returns color to string.
///
/// @lib
///
/// @doc_group colors
function ColorToString(c: Color): String;
/// Returns a color from a floating point RBG value set.
///
/// @param r,g,b: Components for color 0 = none 1 = full
///
/// @lib
/// @sn rgbFloatColorRed:%s green:%s blue:%s
///
/// @doc_group colors
function RGBFloatColor(r,g,b: Single): Color;
/// Returns a color from a floating point RBGA value set.
///
/// @param r,g,b,a: Components for color 0 = none 1 = full
///
/// @lib
/// @sn rgbaFloatColorRed:%s green:%s blue:%s alpha:%s
///
/// @doc_group colors
function RGBAFloatColor(r,g,b, a: Single): Color;
/// Returs a color from the HSB input.
///
/// @param hue, saturation, brightness: Values between 0 and 1
/// @returns The matching color
///
/// @lib
/// @sn hsbColorHue:%s sat:%s bri:%s
///
/// @doc_group colors
function HSBColor(hue, saturation, brightness: Single): Color;
/// Get the transpareny value of ``color``.
///
/// @lib
///
/// @doc_group colors
function TransparencyOf(c: Color): byte;
/// Get the red value of ``color``.
///
/// @lib
///
/// @doc_group colors
function RedOf(c: Color): byte;
/// Get the green value of ``color``.
///
/// @lib
///
/// @doc_group colors
function GreenOf(c: Color): byte;
/// Get the blue value of ``color``.
///
/// @lib
///
/// @doc_group colors
function BlueOf(c: Color): byte;
/// Gets the hue ``h``, saturation ``s``, and brightness ``b`` values from
/// the color.
///
/// @lib
/// @sn hsbValueOf:%s hue:%s sat:%s bri:%s
///
/// @doc_group colors
procedure HSBValuesOf(c: Color; out h, s, b: Single);
/// Get the hue of the ``color``.
///
/// @lib
///
/// @doc_group colors
function HueOf(c: Color): Single;
/// Get the saturation of the ``color``.
///
/// @lib
///
/// @doc_group colors
function SaturationOf(c: Color) : Single;
/// Get the brightness of the ``color``.
///
/// @lib
///
/// @doc_group colors
function BrightnessOf(c: Color) : Single;
//---------------------------------------------------------------------------
// Circle drawing code
//---------------------------------------------------------------------------
/// Draw a circle onto a destination bitmap.
///
/// @lib DrawCircleOpts
/// @sn drawCircleColor:%s atX:%s y:%s radius:%s opts:%s
procedure DrawCircle(clr : Color; x, y, radius: Single; const opts : DrawingOptions); overload;
/// Draw a circle in the game.
///
/// @lib
/// @sn drawCircleColor:%s atX:%s y:%s radius:%s
///
/// @doc_idx 0
procedure DrawCircle(clr : Color; x, y, radius : Single);
/// Draw a circle onto a destination bitmap.
///
/// @lib DrawCircleStructOpts
/// @sn drawCircleColor:%s data:%s opts:%s
procedure DrawCircle(clr : Color; const c: Circle; const opts : DrawingOptions); overload;
/// Draw a circle in the game.
///
/// @lib DrawCircleStruct
/// @sn drawCircleColor:%s data:%s
procedure DrawCircle(clr : Color; const c: Circle);
/// Fill a circle onto a destination bitmap.
///
/// @lib FillCircleOpts
/// @sn fillCircleColor:%s atX:%s y:%s radius:%s opts:%s
procedure FillCircle(clr : Color; x, y, radius: Single; const opts : DrawingOptions); overload;
/// Fill a circle in the game.
///
/// @lib
/// @sn fillCircleColor:%s atX:%s y:%s radius:%s
///
/// @doc_idx 0
procedure FillCircle(clr : Color; x, y, radius : Single);
/// Fill a circle onto a destination bitmap.
///
/// @lib FillCircleStructOpts
/// @sn fillCircleColor:%s data:%s opts:%s
procedure FillCircle(clr : Color; const c: Circle; const opts : DrawingOptions); overload;
/// Fill a circle in the game.
///
/// @lib FillCircleStruct
/// @sn fillCircleColor:%s data:%s
procedure FillCircle(clr : Color; const c: Circle);
/// Fill a circle at a given point using the passed in drawing options.
///
/// @lib FillCircleAtPointWithOpts
/// @sn fillCircleColor:%s at:%s radius:%s opts:%s
procedure FillCircle(clr : Color; const pt: Point2D; radius: Longint; const opts : DrawingOptions); overload;
/// Fill a circle in the game.
///
/// @lib FillCircleAtPoint
/// @sn fillCircleColor:%s at:%s radius:%s
procedure FillCircle(clr : Color; const pt: Point2D; radius: Longint);
//---------------------------------------------------------------------------
// Triangle drawing code
//---------------------------------------------------------------------------
/// Draw a triangle onto a destination bitmap.
///
/// @lib DrawTriangleOpts
/// @sn drawTriangleColor:%s atX1:%s y1:%s x2:%s y2:%s x3:%s y3:%s opts:%s
procedure DrawTriangle(clr : Color; x1, y1, x2, y2, x3, y3: Single; const opts : DrawingOptions); overload;
/// Draw a triangle in the game.
///
/// @lib
/// @sn drawTriangleColor:%s atX1:%s y1:%s x2:%s y2:%s x3:%s y3:%s
///
/// @doc_idx 0
procedure DrawTriangle(clr : Color; x1, y1, x2, y2, x3, y3: Single);
/// Draw a triangle onto a destination bitmap.
///
/// @lib DrawTriangleStructOpts
/// @sn drawTriangleColor:%s data:%s opts:%s
procedure DrawTriangle(clr : Color; const tri: Triangle; const opts : DrawingOptions); overload;
/// Draw a triangle in the game.
///
/// @lib DrawTriangleStruct
/// @sn drawTriangleColor:%s data:%s
procedure DrawTriangle(clr : Color; const tri: Triangle);
/// Fill a triangle onto a destination bitmap.
///
/// @lib FillTriangleOpts
/// @sn fillTriangleColor:%s atX1:%s y1:%s x2:%s y2:%s x3:%s y3:%s opts:%s
procedure FillTriangle(clr: Color; x1, y1, x2, y2, x3, y3: Single; const opts : DrawingOptions); overload;
/// Fill a triangle in the game.
///
/// @lib
/// @sn fillTriangleColor:%s atX1:%s y1:%s x2:%s y2:%s x3:%s y3:%s
///
/// @doc_idx 0
procedure FillTriangle(clr : Color; x1, y1, x2, y2, x3, y3: Single);
/// Fill a triangle onto a destination bitmap.
///
/// @lib FillTriangleStructOpts
/// @sn fillTriangleColor:%s data:%s opts:%s
procedure FillTriangle(clr : Color; const tri: Triangle; const opts : DrawingOptions); overload;
/// Fill a triangle in the game.
///
/// @lib FillTriangleStruct
/// @sn fillTriangleColor:%s data:%s
procedure FillTriangle(clr : Color; const tri: Triangle);
//---------------------------------------------------------------------------
// Screen clearing routines
//---------------------------------------------------------------------------
/// Clear the screen black.
///
/// @lib ClearScreen
/// @sn clearScreen
procedure ClearScreen(); overload;
/// Clear the screen to a specified color.
///
/// @lib ClearScreenTo
/// @sn clearScreen:%s
procedure ClearScreen(toColor : Color); overload;
//---------------------------------------------------------------------------
// Pixel drawing
//---------------------------------------------------------------------------
/// Draw a pixel in the game.
///
/// @lib
/// @sn drawPixel:%s atX:%s y:%s
procedure DrawPixel(clr: Color; x, y: Single); overload;
/// Draw a pixel in the game.
///
/// @lib DrawPixelAtPoint
/// @sn drawPixel:%s At:%s
/// @doc_details
procedure DrawPixel(clr: Color; const position: Point2D); overload;
/// Draw a pixel with options.
///
/// @lib DrawPixelOpts
/// @sn drawPixel:%s atX:%s y:%s opts:%s
/// @doc_details
procedure DrawPixel(clr: Color; x, y: Single; const opts: DrawingOptions); overload;
/// Draw a pixel with options.
///
/// @lib DrawPixelAtPointOpts
/// @sn drawPixel:%s at:%s opts:%s
/// @doc_details
procedure DrawPixel(clr: Color; const position: Point2D; const opts: DrawingOptions); overload;
//---------------------------------------------------------------------------
// Rectangle drawing
//---------------------------------------------------------------------------
/// Draw a rectangle onto a destination bitmap.
///
/// @lib DrawRectangleOpts
/// @sn drawRectangleColor:%s atX:%s y:%s width:%s height:%s opts:%s
procedure DrawRectangle(clr : Color; xPos, yPos, width, height: Single; const opts : DrawingOptions); overload;
/// Draw a rectangle in the game.
///
/// @lib
/// @sn drawRectangleColor:%s atX:%s y:%s width:%s height:%s
///
/// @doc_idx 0
procedure DrawRectangle(clr : Color; x, y, width, height : Single);
/// Draw a rectangle onto a destination bitmap.
///
/// @lib DrawRectangleStructOpts
/// @sn drawRectangleColor:%s data:%s opts:%s
procedure DrawRectangle(clr : Color; const rect: Rectangle; const opts : DrawingOptions); overload;
/// Draw a rectangle in the game.
///
/// @lib DrawRectangleStruct
/// @sn drawRectangleColor:%s data:%s
procedure DrawRectangle(clr : Color; const rect: Rectangle);
/// Draw a quad in the game.
///
/// @lib DrawQuadStruct
/// @sn drawQuadColor:%s data:%s
procedure DrawQuad(clr : Color; const q: Quad); overload;
/// Fill a quad in the game.
///
/// @lib FillQuadStruct
/// @sn fillQuadColor:%s data:%s
procedure FillQuad(clr : Color; const q: Quad); overload;
/// Draw a quad in the game.
///
/// @lib DrawQuadStructOpts
/// @sn drawQuadColor:%s data:%s opts:%s
procedure DrawQuad(clr : Color; const q: Quad; const opts: DrawingOptions); overload;
/// Fill a quad in the game.
///
/// @lib FillQuadStructOpts
/// @sn fillQuadColor:%s data:%s opts:%s
procedure FillQuad(clr : Color; const q: Quad; const opts: DrawingOptions); overload;
/// Fill a rectangle onto a destination bitmap.
///
/// @lib FillRectangleOpts
/// @sn fillRectangleColor:%s atX:%s y:%s width:%s height:%s opts:%s
procedure FillRectangle(clr : Color; xPos, yPos, width, height: Single; const opts : DrawingOptions); overload;
/// Fill a rectangle in the game.
///
/// @lib
/// @sn FillRectangleColor:%s atX:%s y:%s width:%s height:%s
///
/// @doc_idx 0
procedure FillRectangle(clr : Color; x, y, width, height : Single);
/// Fill a rectangle onto a destination bitmap.
///
/// @lib FillRectangleStructOpts
/// @sn fillRectangleColor:%s data:%s opts:%s
procedure FillRectangle(clr : Color; const rect: Rectangle; const opts : DrawingOptions); overload;
/// Fill a rectangle in the game.
///
/// @lib FillRectangleStruct
/// @sn fillRectangleColor:%s data:%s
procedure FillRectangle(clr : Color; const rect: Rectangle);
//---------------------------------------------------------------------------
// Line drawing
//---------------------------------------------------------------------------
/// Draw a line with the provided DrawingOptions.
///
/// @lib DrawLineOpts
/// @sn drawLineColor:%s fromX:%s y:%s toX:%s y:%s opts:%s
procedure DrawLine(clr: Color; xPosStart, yPosStart, xPosEnd, yPosEnd: Single; const opts : DrawingOptions);
/// Draw a line in the game.
///
/// @lib
/// @sn drawLineColor:%s fromX:%s y:%s toX:%s y:%s
///
/// @doc_idx 0
procedure DrawLine(clr : Color; x1, y1, x2, y2: Single);
/// Draw a line in the game from one point to another point.
///
/// @lib DrawLinePt2PtOpts
/// @sn drawLineColor:%s fromPt:%s toPt:%s opts:%s
procedure DrawLine(clr: Color; const fromPt, toPt: Point2D; const opts : DrawingOptions);
/// Draw a line in the game.
///
/// @lib DrawLinePt2Pt
/// @sn drawLineColor:%s fromPt:%s toPt:%s
///
/// @doc_idx 0
procedure DrawLine(clr : Color; const fromPt, toPt: Point2D);
/// Draw a line onto a destination bitmap.
///
/// @lib DrawLineStructOpts
/// @sn drawLineColor:%s data:%s opts:%s
procedure DrawLine(clr : Color; const l : LineSegment; const opts : DrawingOptions); overload;
/// Draw a line in the game.
///
/// @lib DrawLineStruct
/// @sn drawLineColor:%s data:%s
procedure DrawLine(clr : Color; const l : LineSegment);
//---------------------------------------------------------------------------
// Ellipse drawing
//---------------------------------------------------------------------------
/// Draw a ellipse onto a destination bitmap.
///
/// @lib DrawEllipseOpts
/// @sn drawEllipseColor:%s atX:%s y:%s width:%s height:%s opts:%s
procedure DrawEllipse(clr : Color; xPos, yPos, width, height: Single; const opts : DrawingOptions); overload;
/// Draw a ellipse in the game.
///
/// @lib
/// @sn drawEllipseColor:%s atX:%s y:%s width:%s height:%s
///
/// @doc_idx 0
procedure DrawEllipse(clr : Color; xPos, yPos, width, height: Single);
/// Draw a ellipse onto a destination bitmap.
///
/// @lib DrawEllipseStructOpts
/// @sn drawEllipseColor:%s data:%s opts:%s
procedure DrawEllipse(clr : Color; const rec: Rectangle; const opts : DrawingOptions); overload;
/// Draw a ellipse in the game.
///
/// @lib DrawEllipseStruct
/// @sn drawEllipseColor:%s data:%s
procedure DrawEllipse(clr : Color; const rec: Rectangle);
/// Fill a ellipse onto a destination bitmap.
///
/// @lib FillEllipseOpts
/// @sn fillEllipseColor:%s atX:%s y:%s width:%s height:%s opts:%s
procedure FillEllipse(clr : Color; xPos, yPos, width, height: Single; const opts : DrawingOptions); overload;
/// Fill a ellipse in the game.
///
/// @lib
/// @sn fillEllipseColor:%s atX:%s y:%s width:%s height:%s
///
/// @doc_idx 0
procedure FillEllipse(clr : Color; xPos, yPos, width, height: Single);
/// Fill a ellipse onto a destination bitmap.
///
/// @lib FillEllipseStructOpts
/// @sn fillEllipseColor:%s data:%s opts:%s
procedure FillEllipse(clr : Color; const rec: Rectangle; const opts : DrawingOptions); overload;
/// Fill a ellipse in the game.
///
/// @lib FillEllipseStruct
/// @sn fillEllipseColor:%s data:%s
procedure FillEllipse(clr : Color; const rec: Rectangle);
//---------------------------------------------------------------------------
// Clipping
//---------------------------------------------------------------------------
/// Push a clip rectangle to the current window. This can be undone using PopClip.
///
/// @lib PushClipRect
/// @sn pushClip:%s
procedure PushClip(const r: Rectangle); overload;
/// Add the clipping rectangle of a bitmap and uses the intersect between the new rectangle and previous clip.
///
/// @lib PushClipRectForBitmap
/// @sn bitmap:%s PushClipRect:%s
///
/// @class Bitmap
/// @overload PushClip PushClipRect
/// @csn pushClip:%s
procedure PushClip(bmp: Bitmap; const r: Rectangle); overload;
/// Add the clipping rectangle of a window and uses the intersect between the new rectangle and previous clip.
///
/// @lib PushClipRectForWindow
/// @sn window:%s PushClipRect:%s
///
/// @class Window
/// @overload PushClip PushClipRect
/// @csn pushClip:%s
procedure PushClip(wnd: Window; const r: Rectangle); overload;
/// Reset the clipping rectangle of the current window.
///
/// @lib
procedure ResetClip(); overload;
/// Reset the clipping rectangle on a window.
///
/// @lib ResetClipForWindow
///
/// @class Window
/// @method ResetClip
procedure ResetClip(wnd: Window); overload;
/// Reset the clipping rectangle on a bitmap.
///
/// @lib ResetClipForBitmap
///
/// @class Bitmap
/// @method ResetClip
procedure ResetClip(bmp: Bitmap); overload;
/// Set the clip rectangle of the bitmap.
///
/// @lib SetClipForBitmap
/// @sn bitmap:%s setClip:%s
///
/// @class Bitmap
/// @method SetClip
procedure SetClip(bmp: Bitmap; const r: Rectangle); overload;
/// Set the clip rectangle of a window.
///
/// @lib SetClipForWindow
/// @sn window:%s setClip:%s
///
/// @class Window
/// @method SetClip
procedure SetClip(wnd: Window; const r: Rectangle); overload;
/// Set the clip rectangle of the current window.
///
/// @lib SetClip
/// @sn setClip:%s
procedure SetClip(const r: Rectangle); overload;
/// Pop the clip rectangle of the screen.
///
/// @lib PopClipScreen
procedure PopClip(); overload;
/// Pop the clipping rectangle of a bitmap.
///
/// @lib PopClipForBitmap
/// @sn popClipForBitmap:%s
///
/// @class Bitmap
/// @method PopClip
procedure PopClip(bmp: Bitmap); overload;
/// Pop the clipping rectangle of a bitmap.
///
/// @lib PopClipForWindow
/// @sn popClipForWindow:%s
///
/// @class Window
/// @method PopClip
procedure PopClip(wnd: Window); overload;
/// Returns the rectangle of the current clip area for a bitmap
///
/// @lib CurrentClipForBitmap
/// @sn currentClipForBitmap:%s
///
/// @class Bitmap
/// @getter CurrentClip
function CurrentClip(bmp: Bitmap): Rectangle; overload;
/// Returns the rectangle of the clip area for a window
///
/// @lib CurrentClipForWindow
/// @sn currentClipForWindow:%s
///
/// @class Window
/// @getter CurrentClip
function CurrentClip(wnd: Window): Rectangle; overload;
/// Returns the rectangle of the clip area of the current window
///
/// @lib CurrentWindowClip
function CurrentClip(): Rectangle; overload;
//---------------------------------------------------------------------------
// Pixel reading functions
//---------------------------------------------------------------------------
/// Returns the color of the pixel at the x,y location on
/// the supplied bitmap.
///
/// @lib GetPixelFromBitmap
/// @sn bitmap:%s colorAtX:%s y:%s
///
/// @class Bitmap
/// @method GetPixel
/// @csn colorAtX:%s y:%s
function GetPixel(bmp: Bitmap; x, y: Single): Color;
/// Returns the color of the pixel at the x,y location on
/// the supplied window.
///
/// @lib GetPixelFromWindow
/// @sn WindowPixelColor:%s x:%s y:%s
///
/// @class Window
/// @method GetPixel
/// @csn colorAtX:%s y:%s
function GetPixel(wnd: Window; x, y: Single): Color;
/// Returns the color of the pixel at the given x,y location.
///
/// @lib
/// @sn colorOnScreenAtX:%s y:%s
function GetPixelFromScreen(x, y: Single): Color;
//---------------------------------------------------------------------------
// Color Functions
//---------------------------------------------------------------------------
/// The color Swinburne Red
///
/// @lib
function ColorSwinburneRed(): Color;
/// The color Grey
///
/// @lib
function ColorGrey(): Color;
/// The color Transparent
///
/// @lib
function ColorLightGrey(): Color;
/// The color Transparent
///
/// @lib
function ColorTransparent(): Color;
/// The color AliceBlue
///
/// @lib
function ColorAliceBlue(): Color;
/// The color AntiqueWhite
///
/// @lib
function ColorAntiqueWhite(): Color;
/// The color Aqua
///
/// @lib
function ColorAqua(): Color;
/// The color Aquamarine
///
/// @lib
function ColorAquamarine(): Color;
/// The color Azure
///
/// @lib
function ColorAzure(): Color;
/// The color Beige
///
/// @lib
function ColorBeige(): Color;
/// The color Bisque
///
/// @lib
function ColorBisque(): Color;
/// The color Black
///
/// @lib
function ColorBlack(): Color;
/// The color BlanchedAlmond
///
/// @lib
function ColorBlanchedAlmond(): Color;
/// The color Blue
///
/// @lib
function ColorBlue(): Color;
/// The color BlueViolet
///
/// @lib
function ColorBlueViolet(): Color;
/// The color Brown
///
/// @lib
function ColorBrown(): Color;
/// The color BurlyWood
///
/// @lib
function ColorBurlyWood(): Color;
/// The color CadetBlue
///
/// @lib
function ColorCadetBlue(): Color;
/// The color Chartreuse
///
/// @lib
function ColorChartreuse(): Color;
/// The color Chocolate
///
/// @lib
function ColorChocolate(): Color;
/// The color Coral
///
/// @lib
function ColorCoral(): Color;
/// The color CornflowerBlue
///
/// @lib
function ColorCornflowerBlue(): Color;
/// The color Cornsilk
///
/// @lib
function ColorCornsilk(): Color;
/// The color Crimson
///
/// @lib
function ColorCrimson(): Color;
/// The color Cyan
///
/// @lib
function ColorCyan(): Color;
/// The color DarkBlue
///
/// @lib
function ColorDarkBlue(): Color;
/// The color DarkCyan
///
/// @lib
function ColorDarkCyan(): Color;
/// The color DarkGoldenrod
///
/// @lib
function ColorDarkGoldenrod(): Color;
/// The color DarkGray
///
/// @lib
function ColorDarkGray(): Color;
/// The color DarkGreen
///
/// @lib
function ColorDarkGreen(): Color;
/// The color DarkKhaki
///
/// @lib
function ColorDarkKhaki(): Color;
/// The color DarkMagenta
///
/// @lib
function ColorDarkMagenta(): Color;
/// The color DarkOliveGreen
///
/// @lib
function ColorDarkOliveGreen(): Color;
/// The color DarkOrange
///
/// @lib
function ColorDarkOrange(): Color;
/// The color DarkOrchid
///
/// @lib
function ColorDarkOrchid(): Color;
/// The color DarkRed
///
/// @lib
function ColorDarkRed(): Color;
/// The color DarkSalmon
///
/// @lib
function ColorDarkSalmon(): Color;
/// The color DarkSeaGreen
///
/// @lib
function ColorDarkSeaGreen(): Color;
/// The color DarkSlateBlue
///
/// @lib
function ColorDarkSlateBlue(): Color;
/// The color DarkSlateGray
///
/// @lib
function ColorDarkSlateGray(): Color;
/// The color DarkTurquoise
///
/// @lib
function ColorDarkTurquoise(): Color;
/// The color DarkViolet
///
/// @lib
function ColorDarkViolet(): Color;
/// The color DeepPink
///
/// @lib
function ColorDeepPink(): Color;
/// The color DeepSkyBlue
///
/// @lib
function ColorDeepSkyBlue(): Color;
/// The color DimGray
///
/// @lib
function ColorDimGray(): Color;
/// The color DodgerBlue
///
/// @lib
function ColorDodgerBlue(): Color;
/// The color Firebrick
///
/// @lib
function ColorFirebrick(): Color;
/// The color FloralWhite
///
/// @lib
function ColorFloralWhite(): Color;
/// The color ForestGreen
///
/// @lib
function ColorForestGreen(): Color;
/// The color Fuchsia
///
/// @lib
function ColorFuchsia(): Color;
/// The color Gainsboro
///
/// @lib
function ColorGainsboro(): Color;
/// The color GhostWhite
///
/// @lib
function ColorGhostWhite(): Color;
/// The color Gold
///
/// @lib
function ColorGold(): Color;
/// The color Goldenrod
///
/// @lib
function ColorGoldenrod(): Color;
/// The color Gray
///
/// @lib
function ColorGray(): Color;
/// The color Green
///
/// @lib
function ColorGreen(): Color;
/// The color Green
///
/// @lib
function ColorBrightGreen(): Color;
/// The color GreenYellow
///
/// @lib
function ColorGreenYellow(): Color;
/// The color Honeydew
///
/// @lib
function ColorHoneydew(): Color;
/// The color HotPink
///
/// @lib
function ColorHotPink(): Color;
/// The color IndianRed
///
/// @lib
function ColorIndianRed(): Color;
/// The color Indigo
///
/// @lib
function ColorIndigo(): Color;
/// The color Ivory
///
/// @lib
function ColorIvory(): Color;
/// The color Khaki
///
/// @lib
function ColorKhaki(): Color;
/// The color Lavender
///
/// @lib
function ColorLavender(): Color;
/// The color LavenderBlush
///
/// @lib
function ColorLavenderBlush(): Color;
/// The color LawnGreen
///
/// @lib
function ColorLawnGreen(): Color;
/// The color LemonChiffon
///
/// @lib
function ColorLemonChiffon(): Color;
/// The color LightBlue
///
/// @lib
function ColorLightBlue(): Color;
/// The color LightCoral
///
/// @lib
function ColorLightCoral(): Color;
/// The color LightCyan
///
/// @lib
function ColorLightCyan(): Color;
/// The color LightGoldenrodYellow
///
/// @lib
function ColorLightGoldenrodYellow(): Color;
/// The color LightGreen
///
/// @lib
function ColorLightGreen(): Color;
/// The color LightGray
///
/// @lib
function ColorLightGray(): Color;
/// The color LightPink
///
/// @lib
function ColorLightPink(): Color;
/// The color LightSalmon
///
/// @lib
function ColorLightSalmon(): Color;
/// The color LightSeaGreen
///
/// @lib
function ColorLightSeaGreen(): Color;
/// The color LightSkyBlue
///
/// @lib
function ColorLightSkyBlue(): Color;
/// The color LightSlateGray
///
/// @lib
function ColorLightSlateGray(): Color;
/// The color LightSteelBlue
///
/// @lib
function ColorLightSteelBlue(): Color;
/// The color LightYellow
///
/// @lib
function ColorLightYellow(): Color;
/// The color Lime
///
/// @lib
function ColorLime(): Color;
/// The color LimeGreen
///
/// @lib
function ColorLimeGreen(): Color;
/// The color Linen
///
/// @lib
function ColorLinen(): Color;
/// The color Magenta
///
/// @lib
function ColorMagenta(): Color;
/// The color Maroon
///
/// @lib
function ColorMaroon(): Color;
/// The color MediumAquamarine
///
/// @lib
function ColorMediumAquamarine(): Color;
/// The color MediumBlue
///
/// @lib
function ColorMediumBlue(): Color;
/// The color MediumOrchid
///
/// @lib
function ColorMediumOrchid(): Color;
/// The color MediumPurple
///
/// @lib
function ColorMediumPurple(): Color;
/// The color MediumSeaGreen
///
/// @lib
function ColorMediumSeaGreen(): Color;
/// The color MediumSlateBlue
///
/// @lib
function ColorMediumSlateBlue(): Color;
/// The color MediumSpringGreen
///
/// @lib
function ColorMediumSpringGreen(): Color;
/// The color MediumTurquoise
///
/// @lib
function ColorMediumTurquoise(): Color;
/// The color MediumVioletRed
///
/// @lib
function ColorMediumVioletRed(): Color;
/// The color MidnightBlue
///
/// @lib
function ColorMidnightBlue(): Color;
/// The color MintCream
///
/// @lib
function ColorMintCream(): Color;
/// The color MistyRose
///
/// @lib
function ColorMistyRose(): Color;
/// The color Moccasin
///
/// @lib
function ColorMoccasin(): Color;
/// The color NavajoWhite
///
/// @lib
function ColorNavajoWhite(): Color;
/// The color Navy
///
/// @lib
function ColorNavy(): Color;
/// The color OldLace
///
/// @lib
function ColorOldLace(): Color;
/// The color Olive
///
/// @lib
function ColorOlive(): Color;
/// The color OliveDrab
///
/// @lib
function ColorOliveDrab(): Color;
/// The color Orange
///
/// @lib
function ColorOrange(): Color;
/// The color OrangeRed
///
/// @lib
function ColorOrangeRed(): Color;
/// The color Orchid
///
/// @lib
function ColorOrchid(): Color;
/// The color PaleGoldenrod
///
/// @lib
function ColorPaleGoldenrod(): Color;
/// The color PaleGreen
///
/// @lib
function ColorPaleGreen(): Color;
/// The color PaleTurquoise
///
/// @lib
function ColorPaleTurquoise(): Color;
/// The color PaleVioletRed
///
/// @lib
function ColorPaleVioletRed(): Color;
/// The color PapayaWhip
///
/// @lib
function ColorPapayaWhip(): Color;
/// The color PeachPuff
///
/// @lib
function ColorPeachPuff(): Color;
/// The color Peru
///
/// @lib
function ColorPeru(): Color;
/// The color Pink
///
/// @lib
function ColorPink(): Color;
/// The color Plum
///
/// @lib
function ColorPlum(): Color;
/// The color PowderBlue
///
/// @lib
function ColorPowderBlue(): Color;
/// The color Purple
///
/// @lib
function ColorPurple(): Color;
/// The color Red
///
/// @lib
function ColorRed(): Color;
/// The color RosyBrown
///
/// @lib
function ColorRosyBrown(): Color;
/// The color RoyalBlue
///
/// @lib
function ColorRoyalBlue(): Color;
/// The color SaddleBrown
///
/// @lib
function ColorSaddleBrown(): Color;
/// The color Salmon
///
/// @lib
function ColorSalmon(): Color;
/// The color SandyBrown
///
/// @lib
function ColorSandyBrown(): Color;
/// The color SeaGreen
///
/// @lib
function ColorSeaGreen(): Color;
/// The color SeaShell
///
/// @lib
function ColorSeaShell(): Color;
/// The color Sienna
///
/// @lib
function ColorSienna(): Color;
/// The color Silver
///
/// @lib
function ColorSilver(): Color;
/// The color SkyBlue
///
/// @lib
function ColorSkyBlue(): Color;
/// The color SlateBlue
///
/// @lib
function ColorSlateBlue(): Color;
/// The color SlateGray
///
/// @lib
function ColorSlateGray(): Color;
/// The color Snow
///
/// @lib
function ColorSnow(): Color;
/// The color SpringGreen
///
/// @lib
function ColorSpringGreen(): Color;
/// The color SteelBlue
///
/// @lib
function ColorSteelBlue(): Color;
/// The color Tan
///
/// @lib
function ColorTan(): Color;
/// The color Teal
///
/// @lib
function ColorTeal(): Color;
/// The color Thistle
///
/// @lib
function ColorThistle(): Color;
/// The color Tomato
///
/// @lib
function ColorTomato(): Color;
/// The color Turquoise
///
/// @lib
function ColorTurquoise(): Color;
/// The color Violet
///
/// @lib
function ColorViolet(): Color;
/// The color Wheat
///
/// @lib
function ColorWheat(): Color;
/// The color White
///
/// @lib
function ColorWhite(): Color;
/// The color WhiteSmoke
///
/// @lib
function ColorWhiteSmoke(): Color;
/// The color Yellow
///
/// @lib
function ColorYellow(): Color;
/// The color YellowGreen
///
/// @lib
function ColorYellowGreen(): Color;
//=============================================================================
implementation
//=============================================================================
uses Math, Classes, SysUtils, // system
sgTrace,
sgCamera, sgShared, sgGeometry, sgResources, sgImages, sgUtils, sgDriverGraphics, sgDriver, sgDriverImages, sgInput, sgAudio, sgText, sgAnimations, sgDrawingOptions,
sgInputBackend, sgBackendTypes, sgWindowManager, sgDriverSDL2Types;
/// Clears the surface of the screen to the passed in color.
///
/// @param toColor: The colour to clear the bitmap to
///
/// Side Effects:
/// - Screen's surface is set to the toColor
procedure ClearScreen(toColor : Color); overload;
begin
ClearSurface(ToSurfacePtr(_CurrentWindow), toColor);
end;
/// Clears the screen to Black.
///
/// Side Effects:
/// - screen's surface is set to black
procedure ClearScreen(); overload;
begin
ClearScreen(ColorWhite);
end;
function GetPixel(bmp: Bitmap; x, y: Single): Color;
begin
result := sgDriverGraphics.GetPixel(ToSurfacePtr(bmp), x, y);
end;
function GetPixel(wnd: Window; x, y: Single): Color;
begin
result := sgDriverGraphics.GetPixel(ToSurfacePtr(wnd), x, y);
end;
function GetPixelFromScreen(x, y: Single): Color;
begin
result := sgDriverGraphics.GetPixel(ToSurfacePtr(_CurrentWindow), x, y);
end;
//=============================================================================
procedure DrawRectangle(clr : Color; x, y, width, height : Single);
begin
DrawRectangle(clr, x, y, width, height, OptionDefaults());
end;
procedure DrawRectangle(clr : Color; const rect : Rectangle);
begin
DrawRectangle(clr, rect.x, rect.y, rect.width, rect.height, OptionDefaults());
end;
procedure DrawRectangle(clr : Color; const rect : Rectangle; const opts : DrawingOptions);
begin
DrawRectangle(clr, rect.x, rect.y, rect.width, rect.height, opts);
end;
procedure FillRectangle(clr : Color; x, y, width, height : Single);
begin
FillRectangle(clr, x, y, width, height, OptionDefaults());
end;
procedure FillRectangle(clr : Color; const rect : Rectangle);
begin
FillRectangle(clr, rect.x, rect.y, rect.width, rect.height, OptionDefaults());
end;
procedure FillRectangle(clr : Color; const rect : Rectangle; const opts : DrawingOptions);
begin
FillRectangle(clr, rect.x, rect.y, rect.width, rect.height, opts);
end;
//=============================================================================
procedure DrawTriangle(clr : Color; x1, y1, x2, y2, x3, y3: Single);
begin
DrawTriangle(clr, x1, y1, x2, y2, x3, y3, OptionDefaults());
end;
procedure DrawTriangle(clr : Color; const tri: Triangle; const opts : DrawingOptions); overload;
begin
DrawTriangle(clr,
tri.points[0].x, tri.points[0].y,
tri.points[1].x, tri.points[1].y,
tri.points[2].x, tri.points[2].y,
opts);
end;
procedure DrawTriangle(clr : Color; const tri: Triangle);
begin
DrawTriangle(clr,
tri.points[0].x, tri.points[0].y,
tri.points[1].x, tri.points[1].y,
tri.points[2].x, tri.points[2].y,
OptionDefaults());
end;
procedure FillTriangle(clr : Color; x1, y1, x2, y2, x3, y3: Single);
begin
FillTriangle(clr, x1, y1, x2, y2, x3, y3, OptionDefaults());
end;
procedure FillTriangle(clr : Color; const tri: Triangle; const opts : DrawingOptions); overload;
begin
FillTriangle(clr,
tri.points[0].x, tri.points[0].y,
tri.points[1].x, tri.points[1].y,
tri.points[2].x, tri.points[2].y,
opts);
end;
procedure FillTriangle(clr : Color; const tri: Triangle);
begin
FillTriangle(clr,
tri.points[0].x, tri.points[0].y,
tri.points[1].x, tri.points[1].y,
tri.points[2].x, tri.points[2].y,
OptionDefaults());
end;
//=============================================================================
procedure DrawLine(clr : Color; x1, y1, x2, y2: Single);
begin
DrawLine(clr,x1,y1,x2,y2,OptionDefaults());
end;
procedure DrawLine(clr: Color; const fromPt, toPt: Point2D; const opts : DrawingOptions);
begin
DrawLine(clr, fromPt.x, fromPt.y, toPt.x, toPt.y, opts);
end;
procedure DrawLine(clr : Color; const fromPt, toPt: Point2D);
begin
DrawLine(clr, fromPt.x, fromPt.y, toPt.x, toPt.y, OptionDefaults());
end;
procedure DrawLine(clr : Color; const l : LineSegment; const opts : DrawingOptions); overload;
begin
DrawLine(clr,l.startPoint.x,l.startPoint.y,l.endPoint.x,l.endPoint.y,opts);
end;
procedure DrawLine(clr : Color; const l : LineSegment);
begin
DrawLine(clr,l.startPoint.x,l.startPoint.y,l.endPoint.x,l.endPoint.y,OptionDefaults());
end;
//=============================================================================
procedure DrawCircle(clr : Color; x, y, radius : Single);
begin
DrawCircle(clr, x, y, radius, OptionDefaults());
end;
procedure DrawCircle(clr : Color; const c: Circle; const opts : DrawingOptions); overload;
begin
DrawCircle(clr, c.center.x, c.center.y, c.radius, opts);
end;
procedure DrawCircle(clr : Color; const c: Circle);
begin
DrawCircle(clr, c.center.x, c.center.y, c.radius, OptionDefaults());
end;
procedure FillCircle(clr : Color; x, y, radius : Single);
begin
FillCircle(clr, x, y, radius, OptionDefaults());
end;
procedure FillCircle(clr : Color; const c: Circle; const opts : DrawingOptions); overload;
begin
FillCircle(clr, c.center.x, c.center.y, c.radius, opts);
end;
procedure FillCircle(clr : Color; const c: Circle);
begin
FillCircle(clr, c.center.x, c.center.y, c.radius, OptionDefaults());
end;
procedure FillCircle(clr : Color; const pt: Point2D; radius: Longint; const opts : DrawingOptions); overload;
begin
FillCircle(clr, pt.x, pt.y, radius, opts);
end;
procedure FillCircle(clr : Color; const pt: Point2D; radius: Longint);
begin
FillCircle(clr, pt.x, pt.y, radius, OptionDefaults());
end;
//=============================================================================
procedure DrawEllipse(clr: Color; xPos, yPos, width, height: Single; const opts : DrawingOptions); overload;
begin
sgDriverGraphics.DrawEllipse(clr, xPos, yPos, width, height, opts);
end;
procedure DrawEllipse(clr : Color; xPos, yPos, width, height: Single);
begin
sgDriverGraphics.DrawEllipse(clr, xPos, yPos, width, height, OptionDefaults());
end;
procedure DrawEllipse(clr : Color; const rec: Rectangle; const opts : DrawingOptions); overload;
begin
sgDriverGraphics.DrawEllipse(clr, rec.x, rec.y, rec.width, rec.height, opts);
end;
procedure DrawEllipse(clr : Color; const rec: Rectangle);
begin
sgDriverGraphics.DrawEllipse(clr, rec.x, rec.y, rec.width, rec.height, OptionDefaults());
end;
//=============================================================================
procedure FillEllipse(clr: Color; xPos, yPos, width, height: Single; const opts : DrawingOptions);
begin
sgDriverGraphics.FillEllipse(clr, xPos, yPos, width, height, opts);
end;
procedure FillEllipse(clr : Color; xPos, yPos, width, height: Single);
begin
sgDriverGraphics.FillEllipse(clr, xPos, yPos, width, height, OptionDefaults());
end;
procedure FillEllipse(clr : Color; const rec: Rectangle; const opts : DrawingOptions); overload;
begin
sgDriverGraphics.FillEllipse(clr, rec.x, rec.y, rec.width, rec.height, opts);
end;
procedure FillEllipse(clr : Color; const rec: Rectangle);
begin
sgDriverGraphics.FillEllipse(clr, rec.x, rec.y, rec.width, rec.height, OptionDefaults());
end;
//=============================================================================
procedure DrawRectangle(clr : Color; xPos, yPos, width, height : Single; const opts : DrawingOptions); overload;
var
rect: Rectangle;
begin
if opts.dest = nil then begin RaiseWarning('DrawRectangle - No destination bitmap supplied'); exit; end;
if width < 0 then
begin
rect.x := xPos + width; //move back by width
width := -width;
end else rect.x := xPos;
if height < 0 then
begin
rect.y := yPos + height; //move up by height
height := -height;
end else rect.y := yPos;
rect.width := Round(width);
rect.height := Round(height);
sgDriverGraphics.DrawRectangle(clr, rect, opts);
end;
procedure FillRectangle(clr : Color; xPos, yPos, width, height : Single; const opts : DrawingOptions);
var
rect: Rectangle;
begin
if opts.dest = nil then begin RaiseWarning('FillRectangle - No destination bitmap supplied'); exit; end;
if width < 0 then
begin
rect.x := xPos + width; //move back by width
width := -width;
end else rect.x := xPos;
if height < 0 then
begin
rect.y := yPos + height; //move up by height
height := -height;
end else rect.y := yPos;
rect.width := Round(width);
rect.height := Round(height);
sgDriverGraphics.FillRectangle(clr, rect, opts);
end;
procedure DrawTriangle(clr : Color; x1, y1, x2, y2, x3, y3: Single; const opts : DrawingOptions);
begin
if opts.dest = nil then
begin
RaiseWarning('DrawTriangle - No destination bitmap supplied');
exit;
end;
sgDriverGraphics.DrawTriangle(clr, x1, y1, x2, y2, x3, y3, opts);
end;
procedure FillTriangle(clr: Color; x1, y1, x2, y2, x3, y3: Single; const opts : DrawingOptions); overload;
begin
if opts.dest = nil then
begin
RaiseWarning('FillTriangle - No destination bitmap supplied');
exit;
end;
sgDriverGraphics.FillTriangle(clr, x1, y1, x2, y2, x3, y3, opts);
end;
procedure DrawCircle(clr: Color; x, y, radius: Single; const opts : DrawingOptions); overload;
begin
if opts.dest = nil then
begin
RaiseWarning('DrawCircle - No destination bitmap supplied');
exit;
end;
sgDriverGraphics.DrawCircle(clr, x, y, radius, opts);
end;
procedure FillCircle(clr: Color; x, y, radius: Single; const opts : DrawingOptions);
begin
if opts.dest = nil then
begin
RaiseWarning('FillCircle - No destination bitmap supplied');
exit;
end;
sgDriverGraphics.FillCircle(clr, x, y, radius, opts);
end;
procedure DrawLine(clr: Color; xPosStart, yPosStart, xPosEnd, yPosEnd: Single; const opts : DrawingOptions);
begin
if opts.dest = nil then
begin
RaiseWarning('DrawLine - No destination bitmap supplied');
exit;
end;
sgDriverGraphics.DrawLine(clr, xPosStart, yPosStart, xPosEnd, yPosEnd, opts);
end;
//=============================================================================
procedure DrawPixel(clr: Color; x, y: Single; const opts: DrawingOptions); overload;
begin
if opts.dest = nil then begin RaiseWarning('DrawPixel - No destination supplied'); exit; end;
sgDriverGraphics.DrawPixel(clr, x, y, opts);
end;
procedure DrawPixel(clr: Color; x, y: Single); overload;
begin
DrawPixel(clr, x, y, OptionDefaults());
end;
procedure DrawPixel(clr: Color; const position : Point2D; const opts: DrawingOptions); overload;
begin
DrawPixel(clr, position.x, position.y, opts);
end;
procedure DrawPixel(clr: Color; const position: Point2D); overload;
begin
DrawPixel(clr, position.x, position.y, OptionDefaults());
end;
//=============================================================================
procedure ResetClip(var img: ImageData); overload;
begin
SetLength(img.clipStack, 0);
sgDriverGraphics.ResetClip(@img.surface);
end;
procedure ResetClip(bmp: Bitmap); overload;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if Assigned(b) then ResetClip(b^.image);
end;
procedure ResetClip(wnd: Window); overload;
var
w: WindowPtr;
begin
w := ToWindowPtr(wnd);
if Assigned(w) then ResetClip(w^.image);
end;
procedure ResetClip(); overload;
var
surf: psg_drawing_surface;
begin
surf := ToSurfacePtr(_CurrentWindow);
if Assigned(surf) then
ResetClip(surf);
end;
procedure DoSetClip(surf: psg_drawing_surface; const r: Rectangle); overload;
begin
sgDriverGraphics.SetClipRectangle(surf, r);
end;
procedure PushClip(var img: ImageData; const r: Rectangle); overload;
begin
SetLength(img.clipStack, Length(img.clipStack) + 1);
if Length(img.clipStack) > 1 then
begin
img.clipStack[high(img.clipStack)] := Intersection(r, img.clipStack[High(img.clipStack) - 1]);
end
else
img.clipStack[high(img.clipStack)] := r;
DoSetClip(@img.surface, img.clipStack[high(img.clipStack)]);
end;
procedure PushClip(bmp: Bitmap; const r: Rectangle); overload;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if b = nil then begin exit; end;
PushClip(b^.image, r);
end;
procedure PushClip(wnd: Window; const r: Rectangle); overload;
var
w: WindowPtr;
begin
w := ToWindowPtr(wnd);
if w = nil then begin exit; end;
PushClip(w^.image, r);
end;
procedure PushClip(const r: Rectangle); overload;
begin
PushClip(Window(_CurrentWindow), r);
end;
procedure SetClip(bmp: Bitmap; const r: Rectangle); overload;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if assigned(b) then
begin
SetLength(b^.image.clipStack, 0);
PushClip(bmp, r);
end;
end;
procedure SetClip(wnd: Window; const r: Rectangle); overload;
var
w: WindowPtr;
begin
w := ToWindowPtr(wnd);
if assigned(w) then
begin
SetLength(w^.image.clipStack, 0);
PushClip(wnd, r);
end;
end;
procedure SetClip(const r: Rectangle); overload;
begin
SetClip(Window(_CurrentWindow), r);
end;
procedure PopClip(); overload;
begin
PopClip(Window(_CurrentWindow));
end;
procedure PopClip(var img: ImageData); overload;
begin
Setlength(img.clipStack, Length(img.clipStack)-1);
if Length(img.clipStack) > 0 then
DoSetClip(@img.surface, img.clipStack[High(img.clipStack)])
else
ResetClip(img);
end;
procedure PopClip(bmp: Bitmap); overload;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not Assigned(b) then exit;
PopClip(b^.image);
end;
procedure PopClip(wnd: Window); overload;
var
w: WindowPtr;
begin
w := ToWindowPtr(wnd);
if not Assigned(w) then exit;
PopClip(w^.image);
end;
function CurrentClip(const img: ImageData): Rectangle; overload;
begin
if Length(img.clipStack) <> 0 then
result := img.clipStack[high(img.clipStack)]
else
result := RectangleFrom(0, 0, img.surface.width, img.surface.height);
end;
function CurrentClip(bmp: Bitmap): Rectangle; overload;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not Assigned(b) then exit;
result := CurrentClip(b^.image);
end;
function CurrentClip(wnd: Window): Rectangle; overload;
var
w: WindowPtr;
begin
w := ToWindowPtr(wnd);
if not Assigned(w) then exit;
result := CurrentClip(w^.image);
end;
function CurrentClip(): Rectangle; overload;
begin
result := CurrentClip(Window(_CurrentWindow));
end;
//=============================================================================
procedure DrawLines(clr: Color; const lines: LinesArray); //TODO: overload;
var
i: Longint;
begin
for i := 0 to High(lines) do
begin
DrawLine(clr, lines[i]);
end;
end;
procedure DrawQuad(clr : Color; const q: Quad); overload;
begin
DrawQuad(clr, q, OptionDefaults());
end;
procedure FillQuad(clr : Color; const q: Quad); overload;
begin
FillQuad(clr, q, OptionDefaults());
end;
procedure DrawQuad(clr : Color; const q: Quad; const opts: DrawingOptions); overload;
begin
sgDriverGraphics.DrawQuad(clr, q, opts);
end;
procedure FillQuad(clr : Color; const q: Quad; const opts: DrawingOptions); overload;
begin
sgDriverGraphics.FillQuad(clr, q, opts);
end;
//----------------------------------------------------------------------------
// Set Icon / Window Open / Screen Size / Resize
//----------------------------------------------------------------------------
procedure SetIcon(const filename: String);
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'SetIcon');
{$ENDIF}
iconFile := filename;
{$IFDEF TRACE}
TraceExit('sgGraphics', 'SetIcon');
{$ENDIF}
end;
procedure OpenGraphicsWindow(const caption: String; width: Longint; height: Longint); overload;
begin
OpenWindow(caption, width, height);
end;
procedure SaveSurface(const image: ImageData; const basename: String);
var
path: String;
filename: String;
i: Longint;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'TakeScreenShot');
{$ENDIF}
path := IncludeTrailingPathDelimiter(GetUserDir()) + 'Desktop' + PathDelim;
if not DirectoryExists(path) then
path := IncludeTrailingPathDelimiter(GetUserDir());
filename := basename + '.png';
i := 1;
while FileExists(path + filename) do
begin
filename := basename + IntToStr(i) + '.png';
i := i + 1;
end;
sgDriverImages.SaveSurface(@image.surface, path + filename);
{$IFDEF TRACE}
TraceExit('sgGraphics', 'TakeScreenShot');
{$ENDIF}
end;
procedure TakeScreenShot(wnd: Window; const basename: String);
var
w: WindowPtr;
begin
w := ToWindowPtr(wnd);
if Assigned(wnd) then SaveSurface(w^.image, basename);
end;
procedure TakeScreenShot(const basename: String);
begin
TakeScreenshot(Window(_CurrentWindow), basename);
end;
procedure RefreshScreen(); overload;
begin
RefreshScreen(-1);
end;
procedure RefreshScreen(wnd: Window; targetFPS: Longint); overload;
var
nowTime: Longword;
delta, delayTime: Longword;
w: WindowPtr;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'RefreshScreen');
{$ENDIF}
w := ToWindowPtr(wnd);
if not Assigned(w) then exit;
DrawCollectedText(w);
sgDriverGraphics.RefreshWindow(w);
nowTime := GetTicks();
delta := nowTime - _lastUpdateTime;
//dont sleep if 5ms remaining...
while (targetFPS > 0) and ((delta + 8) * targetFPS < 1000) do
begin
delayTime := (1000 div targetFPS) - delta;
Delay(delayTime);
nowTime := GetTicks();
delta := nowTime - _lastUpdateTime;
end;
_UpdateFPSData(delta);
_lastUpdateTime := nowTime;
{$IFDEF TRACE}
TraceExit('sgGraphics', 'RefreshScreen');
{$ENDIF}
end;
procedure RefreshScreen(targetFPS: Longint); overload;
begin
RefreshScreen(Window(_CurrentWindow), targetFPS);
end;
//----------------------------------------------------------------------------
// Colour
//----------------------------------------------------------------------------
function ColorToString(c: Color): string;
var
r,g,b,a : byte;
begin
ColorComponents(c,r,g,b,a);
result:=IntToStr(r)+','+IntToStr(g)+','+IntToStr(b)+','+IntToStr(a);
end;
procedure ColorComponents(c: Color; out r, g, b, a: byte);
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'ColorComponents');
{$ENDIF}
sgDriverGraphics.ColorComponents(c, r, g, b, a);
{$IFDEF TRACE}
TraceExit('sgGraphics', 'ColorComponents');
{$ENDIF}
end;
function RedOf(c: Color): byte;
var
r,g,b,a: Byte;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'RedOf');
{$ENDIF}
ColorComponents(c, r, g, b, a);
result := r;
{$IFDEF TRACE}
TraceExit('sgGraphics', 'RedOf');
{$ENDIF}
end;
function GreenOf(c: Color): byte;
var
r,g,b,a: Byte;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'GreenOf');
{$ENDIF}
ColorComponents(c, r, g, b, a);
result := g;
{$IFDEF TRACE}
TraceExit('sgGraphics', 'GreenOf');
{$ENDIF}
end;
function BlueOf(c: Color): byte;
var
r,g,b,a: Byte;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'BlueOf');
{$ENDIF}
ColorComponents(c, r, g, b, a);
result := b;
{$IFDEF TRACE}
TraceExit('sgGraphics', 'BlueOf');
{$ENDIF}
end;
function TransparencyOf(c: Color): byte;
var
r,g,b,a: Byte;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'TransparencyOf');
{$ENDIF}
ColorComponents(c, r, g, b, a);
result := a;
{$IFDEF TRACE}
TraceExit('sgGraphics', 'TransparencyOf');
{$ENDIF}
end;
procedure HSBValuesOf(c: Color; out h, s, b: Single);
var
red, green, blue, alpha: byte;
rf, gf, bf: Single;
minRGB, maxRGB, delta: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'HSBValuesOf');
{$ENDIF}
H := 0.0 ;
ColorComponents(c, red, green, blue, alpha);
rf := red / 255;
gf := green / 255;
bf := blue / 255;
minRGB := Min(Min(rf, gf), bf);
maxRGB := Max(Max(rf, gf), bf);
delta := (maxRGB - minRGB);
b := maxRGB;
if (maxRGB <> 0.0) then s := delta / maxRGB
else s := 0.0;
if (s <> 0.0) then
begin
if rf = maxRGB then h := (gf - bf) / Delta
else
if gf = maxRGB then h := 2.0 + (bf - rf) / Delta
else
if bf = maxRGB then h := 4.0 + (rf - gf) / Delta
end
else h := -1.0;
h := h * 60 ;
if h < 0.0 then h := h + 360.0;
h := h / 360.0;
{$IFDEF TRACE}
TraceExit('sgGraphics', 'HSBValuesOf');
{$ENDIF}
end;
function HueOf(c: Color) : Single;
var
s, b: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'HueOf');
{$ENDIF}
HSBValuesOf(c, result, s, b);
{$IFDEF TRACE}
TraceExit('sgGraphics', 'HueOf');
{$ENDIF}
end;
function SaturationOf(c: Color) : Single;
var
h, b: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'SaturationOf');
{$ENDIF}
HSBValuesOf(c, h, result, b);
{$IFDEF TRACE}
TraceExit('sgGraphics', 'SaturationOf');
{$ENDIF}
end;
function BrightnessOf(c: Color) : Single;
var
h, s: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'BrightnessOf');
{$ENDIF}
HSBValuesOf(c, h, s, result);
{$IFDEF TRACE}
TraceExit('sgGraphics', 'BrightnessOf');
{$ENDIF}
end;
function RGBAColor(red, green, blue, alpha: Byte): Color;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'RGBAColor');
{$ENDIF}
result := sgDriverGraphics.RGBAColor(red, green, blue, alpha);
{$IFDEF TRACE}
TraceExit('sgGraphics', 'RGBAColor');
{$ENDIF}
end;
function RGBColor(red, green, blue: Byte): Color;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'RGBColor');
{$ENDIF}
result := RGBAColor(red, green, blue, 255);
{$IFDEF TRACE}
TraceExit('sgGraphics', 'RGBColor');
{$ENDIF}
end;
function RGBFloatColor(r,g,b: Single): Color;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'RGBFloatColor');
{$ENDIF}
result := RGBColor(Round(r * 255), Round(g * 255), Round(b * 255));
{$IFDEF TRACE}
TraceExit('sgGraphics', 'RGBFloatColor');
{$ENDIF}
end;
function RGBAFloatColor(r,g,b, a: Single): Color;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'RGBAFloatColor');
{$ENDIF}
result := RGBAColor(Round(r * 255), Round(g * 255), Round(b * 255), Round(a * 255));
{$IFDEF TRACE}
TraceExit('sgGraphics', 'RGBAFloatColor');
{$ENDIF}
end;
function HSBColor(hue, saturation, brightness: Single): Color;
var
domainOffset: Single;
red, green, blue: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'HSBColor');
{$ENDIF}
if brightness = 0 then
begin
result := ColorBlack;
exit;
end;
if saturation = 0 then
begin
result := RGBFloatColor(brightness, brightness, brightness);
exit;
end;
if hue < 1.0 / 6 then
begin // red domain... green ascends
domainOffset := hue;
red := brightness;
blue := brightness * (1.0 - saturation);
green := blue + (brightness - blue) * domainOffset * 6;
end
else if hue < 2.0 / 6 then
begin // yellow domain; red descends
domainOffset := hue - 1.0 / 6;
green := brightness;
blue := brightness * (1.0 - saturation);
red := green - (brightness - blue) * domainOffset * 6;
end
else if hue < 3.0 / 6 then
begin // green domain; blue ascends
domainOffset := hue - 2.0 / 6;
green := brightness;
red := brightness * (1.0 - saturation);
blue := red + (brightness - red) * domainOffset * 6;
end
else if hue < 4.0 / 6 then
begin // cyan domain; green descends
domainOffset := hue - 3.0 / 6;
blue := brightness;
red := brightness * (1.0 - saturation);
green := blue - (brightness - red) * domainOffset * 6;
end
else if hue < 5.0 / 6 then
begin // blue domain; red ascends
domainOffset := hue - 4.0 / 6;
blue := brightness;
green := brightness * (1.0 - saturation);
red := green + (brightness - green) * domainOffset * 6;
end
else
begin // magenta domain; blue descends
domainOffset := hue - 5.0 / 6;
red := brightness;
green := brightness * (1.0 - saturation);
blue := red - (brightness - green) * domainOffset * 6;
end;
result := RGBFloatColor(red, green, blue);
{$IFDEF TRACE}
TraceExit('sgGraphics', 'HSBColor');
{$ENDIF}
end;
function RandomColor(): Color;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'RandomColor');
{$ENDIF}
result := RGBAFloatColor(Rnd(), Rnd(), Rnd(), Rnd());
{$IFDEF TRACE}
TraceExit('sgGraphics', 'RandomColor');
{$ENDIF}
end;
function RandomRGBColor(alpha: Byte): Color;
begin
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'RandomRGBColor');
{$ENDIF}
result := RGBAColor(Byte(Rnd(256)), Byte(Rnd(256)), Byte(Rnd(256)), alpha);
{$IFDEF TRACE}
TraceExit('sgGraphics', 'RandomRGBColor');
{$ENDIF}
end;
function AvailableResolution(idx: LongInt): Resolution;
var
temp: ResolutionArray;
begin
temp := sgDriverGraphics.AvailableResolutions();
if (idx >= 0) and (idx <= High(temp)) then
result := temp[idx]
else
begin
result.format := 0;
result.refreshRate := 0;
result.width := 0;
result.height := 0;
end;
end;
function NumberOfResolutions(): Longint;
begin
result := Length(sgDriverGraphics.AvailableResolutions());
end;
//-----------------------------------------------------------------------------
procedure ShowSwinGameSplashScreen();
var
aniX, aniY, txtX, txtY : LongInt;
i: Longint;
f: Font;
txt: String;
//oldW, oldH: Longint;
//isStep: Boolean;
isPaused: Boolean;
isSkip: Boolean;
startAni: Animation;
aniBmp: sgTypes.Bitmap;
procedure InnerProcessEvents();
begin
ProcessEvents();
if (KeyDown(sgTypes.SuperKey) or KeyDown(sgTypes.CtrlKey)) and KeyTyped(PKey) then
begin
isPaused := not isPaused;
end;
if WindowCloseRequested() or KeyDown(sgTypes.EscapeKey) then isSkip := true;
end;
begin
isPaused := false;
isSkip := false;
{$IFDEF TRACE}
TraceEnter('sgGraphics', 'ShowSwinGameSplashScreen');
{$ENDIF}
try
ClearScreen(ColorWhite);
RefreshScreen();
try
//oldW := ScreenWidth();
//oldH := ScreenHeight();
//if (oldW <> 800) or (oldH <> 600) then ChangeScreenSize(800, 600);
// ToggleWindowBorder();
LoadResourceBundle('splash.txt', False);
i := 1;
while isPaused or (i < 120) do
begin
aniBmp := BitmapNamed('Swinburne');
aniX := (ScreenWidth() - BitmapCellWidth(aniBmp)) div 2;
aniY := (ScreenHeight() - BitmapCellHeight(aniBmp)) div 2;
ClearScreen(ColorWhite);
sgImages.DrawBitmap(aniBmp, aniX, aniY);
f := FontNamed('SwinGameText');
txt := 'SwinGame API by Swinburne University of Technology';
txtX := (ScreenWidth() - TextWidth(f, txt)) div 2;
txtY := aniY + (ScreenHeight() - aniY + BitmapCellHeight(aniBmp)) div 2;
if txtY > aniY+ BitmapCellHeight(aniBmp) then DrawText(txt, ColorBlack, f, txtX, txtY );
f := FontNamed('LoadingFont');
DrawText(DLL_VERSION, ColorLightGrey, f, 5, ScreenHeight() - TextHeight(f, DLL_VERSION) - 2);
i += 1;
InnerProcessEvents();
RefreshScreen(60);
if isSkip then break;
end;
aniBmp := BitmapNamed('SwinGameAni');
aniX := (ScreenWidth() - BitmapCellWidth(aniBmp)) div 2;
aniY := (ScreenHeight() - BitmapCellHeight(aniBmp)) div 2;
{$IFDEF TRACE}
startAni := CreateAnimation('splash-debug', AnimationScriptNamed('Startup'));
{$ELSE}
startAni := CreateAnimation('splash', AnimationScriptNamed('Startup'));
{$ENDIF}
while not AnimationEnded(startAni) do
begin
ClearScreen(ColorWhite);
DrawAnimation(startAni, aniBmp, aniX, aniY);
UpdateAnimation(startAni);
RefreshScreen();
InnerProcessEvents();
if isSkip then break;
Delay(15);
end;
ClearScreen(ColorWhite);
RefreshScreen();
while SoundEffectPlaying(SoundEffectNamed('SwinGameStart')) or isPaused do
begin
InnerProcessEvents();
if isSkip then break;
end;
StopSoundEffect('SwinGameStart');
// i := 1;
// while isPaused or (i < 30) do
// begin
// i += 1;
// InnerProcessEvents();
// RefreshScreen(60);
// if isSkip then break;
// end;
except on e:Exception do
{$IFDEF TRACE}
begin
Trace('sgGraphics', 'Error', 'ShowSwinGameSplashScreen', 'Error loading and drawing splash.');
Trace('sgGraphics', 'Error', 'ShowSwinGameSplashScreen', e.Message);
end;
{$ENDIF}
end;
finally
try
ReleaseResourceBundle('splash.txt');
except on e1: Exception do
begin
RaiseWarning('Error releating splash resources.');
{$IFDEF TRACE}
Trace('sgGraphics', 'Error', 'ShowSwinGameSplashScreen', 'Error freeing splash.');
Trace('sgGraphics', 'Error', 'ShowSwinGameSplashScreen', e1.Message);
{$ENDIF}
end;
end;
// ToggleWindowBorder();
//if (oldW <> 800) or (oldH <> 600) then ChangeScreenSize(oldW, oldH);
end;
{$IFDEF TRACE}
TraceExit('sgGraphics', 'ShowSwinGameSplashScreen');
{$ENDIF}
end;
function ColorGrey(): Color;
begin
result := RGBAColor(128, 128, 128, 255);
end;
function ColorLightGrey(): Color;
begin
result := RGBAColor(200, 200, 200, 255);
end;
function ColorTransparent(): Color;
begin
result := RGBAColor(0, 0, 0, 0);
end;
function ColorAliceBlue(): Color;
begin
result := RGBAColor(240, 248, 255, 255);
end;
function ColorAntiqueWhite(): Color;
begin
result := RGBAColor(250, 235, 215, 255);
end;
function ColorAqua(): Color;
begin
result := RGBAColor(0, 255, 255, 255);
end;
function ColorAquamarine(): Color;
begin
result := RGBAColor(127, 255, 212, 255);
end;
function ColorAzure(): Color;
begin
result := RGBAColor(240, 255, 255, 255);
end;
function ColorBeige(): Color;
begin
result := RGBAColor(245, 245, 220, 255);
end;
function ColorBisque(): Color;
begin
result := RGBAColor(255, 228, 196, 255);
end;
function ColorBlack(): Color;
begin
result := RGBAColor(0, 0, 0, 255);
end;
function ColorBlanchedAlmond(): Color;
begin
result := RGBAColor(255, 235, 205, 255);
end;
function ColorBlue(): Color;
begin
result := RGBAColor(0, 0, 255, 255);
end;
function ColorBlueViolet(): Color;
begin
result := RGBAColor(138, 43, 226, 255);
end;
function ColorBrown(): Color;
begin
result := RGBAColor(165, 42, 42, 255);
end;
function ColorBurlyWood(): Color;
begin
result := RGBAColor(222, 184, 135, 255);
end;
function ColorCadetBlue(): Color;
begin
result := RGBAColor(95, 158, 160, 255);
end;
function ColorChartreuse(): Color;
begin
result := RGBAColor(127, 255, 0, 255);
end;
function ColorChocolate(): Color;
begin
result := RGBAColor(210, 105, 30, 255);
end;
function ColorCoral(): Color;
begin
result := RGBAColor(255, 127, 80, 255);
end;
function ColorCornflowerBlue(): Color;
begin
result := RGBAColor(100, 149, 237, 255);
end;
function ColorCornsilk(): Color;
begin
result := RGBAColor(255, 248, 220, 255);
end;
function ColorCrimson(): Color;
begin
result := RGBAColor(220, 20, 60, 255);
end;
function ColorCyan(): Color;
begin
result := RGBAColor(0, 255, 255, 255);
end;
function ColorDarkBlue(): Color;
begin
result := RGBAColor(0, 0, 139, 255);
end;
function ColorDarkCyan(): Color;
begin
result := RGBAColor(0, 139, 139, 255);
end;
function ColorDarkGoldenrod(): Color;
begin
result := RGBAColor(184, 134, 11, 255);
end;
function ColorDarkGray(): Color;
begin
result := RGBAColor(169, 169, 169, 255);
end;
function ColorDarkGreen(): Color;
begin
result := RGBAColor(0, 100, 0, 255);
end;
function ColorDarkKhaki(): Color;
begin
result := RGBAColor(189, 183, 107, 255);
end;
function ColorDarkMagenta(): Color;
begin
result := RGBAColor(139, 0, 139, 255);
end;
function ColorDarkOliveGreen(): Color;
begin
result := RGBAColor(85, 107, 47, 255);
end;
function ColorDarkOrange(): Color;
begin
result := RGBAColor(255, 140, 0, 255);
end;
function ColorDarkOrchid(): Color;
begin
result := RGBAColor(153, 50, 204, 255);
end;
function ColorDarkRed(): Color;
begin
result := RGBAColor(139, 0, 0, 255);
end;
function ColorDarkSalmon(): Color;
begin
result := RGBAColor(233, 150, 122, 255);
end;
function ColorDarkSeaGreen(): Color;
begin
result := RGBAColor(143, 188, 139, 255);
end;
function ColorDarkSlateBlue(): Color;
begin
result := RGBAColor(72, 61, 139, 255);
end;
function ColorDarkSlateGray(): Color;
begin
result := RGBAColor(47, 79, 79, 255);
end;
function ColorDarkTurquoise(): Color;
begin
result := RGBAColor(0, 206, 209, 255);
end;
function ColorDarkViolet(): Color;
begin
result := RGBAColor(148, 0, 211, 255);
end;
function ColorDeepPink(): Color;
begin
result := RGBAColor(255, 20, 147, 255);
end;
function ColorDeepSkyBlue(): Color;
begin
result := RGBAColor(0, 191, 255, 255);
end;
function ColorDimGray(): Color;
begin
result := RGBAColor(105, 105, 105, 255);
end;
function ColorDodgerBlue(): Color;
begin
result := RGBAColor(30, 144, 255, 255);
end;
function ColorFirebrick(): Color;
begin
result := RGBAColor(178, 34, 34, 255);
end;
function ColorFloralWhite(): Color;
begin
result := RGBAColor(255, 250, 240, 255);
end;
function ColorForestGreen(): Color;
begin
result := RGBAColor(34, 139, 34, 255);
end;
function ColorFuchsia(): Color;
begin
result := RGBAColor(255, 0, 255, 255);
end;
function ColorGainsboro(): Color;
begin
result := RGBAColor(220, 220, 220, 255);
end;
function ColorGhostWhite(): Color;
begin
result := RGBAColor(248, 248, 255, 255);
end;
function ColorGold(): Color;
begin
result := RGBAColor(255, 215, 0, 255);
end;
function ColorGoldenrod(): Color;
begin
result := RGBAColor(218, 165, 32, 255);
end;
function ColorGray(): Color;
begin
result := RGBAColor(128, 128, 128, 255);
end;
function ColorGreen(): Color;
begin
result := RGBAColor(0, 128, 0, 255);
end;
function ColorBrightGreen(): Color;
begin
result := RGBAColor(0, 255, 0, 255);
end;
function ColorGreenYellow(): Color;
begin
result := RGBAColor(173, 255, 47, 255);
end;
function ColorHoneydew(): Color;
begin
result := RGBAColor(240, 255, 240, 255);
end;
function ColorHotPink(): Color;
begin
result := RGBAColor(255, 105, 180, 255);
end;
function ColorIndianRed(): Color;
begin
result := RGBAColor(205, 92, 92, 255);
end;
function ColorIndigo(): Color;
begin
result := RGBAColor(75, 0, 130, 255);
end;
function ColorIvory(): Color;
begin
result := RGBAColor(255, 255, 240, 255);
end;
function ColorKhaki(): Color;
begin
result := RGBAColor(240, 230, 140, 255);
end;
function ColorLavender(): Color;
begin
result := RGBAColor(230, 230, 250, 255);
end;
function ColorLavenderBlush(): Color;
begin
result := RGBAColor(255, 240, 245, 255);
end;
function ColorLawnGreen(): Color;
begin
result := RGBAColor(124, 252, 0, 255);
end;
function ColorLemonChiffon(): Color;
begin
result := RGBAColor(255, 250, 205, 255);
end;
function ColorLightBlue(): Color;
begin
result := RGBAColor(173, 216, 230, 255);
end;
function ColorLightCoral(): Color;
begin
result := RGBAColor(240, 128, 128, 255);
end;
function ColorLightCyan(): Color;
begin
result := RGBAColor(224, 255, 255, 255);
end;
function ColorLightGoldenrodYellow(): Color;
begin
result := RGBAColor(250, 250, 210, 255);
end;
function ColorLightGreen(): Color;
begin
result := RGBAColor(144, 238, 144, 255);
end;
function ColorLightGray(): Color;
begin
result := RGBAColor(211, 211, 211, 255);
end;
function ColorLightPink(): Color;
begin
result := RGBAColor(255, 182, 193, 255);
end;
function ColorLightSalmon(): Color;
begin
result := RGBAColor(255, 160, 122, 255);
end;
function ColorLightSeaGreen(): Color;
begin
result := RGBAColor(32, 178, 170, 255);
end;
function ColorLightSkyBlue(): Color;
begin
result := RGBAColor(135, 206, 250, 255);
end;
function ColorLightSlateGray(): Color;
begin
result := RGBAColor(119, 136, 153, 255);
end;
function ColorLightSteelBlue(): Color;
begin
result := RGBAColor(176, 196, 222, 255);
end;
function ColorLightYellow(): Color;
begin
result := RGBAColor(255, 255, 224, 255);
end;
function ColorLime(): Color;
begin
result := RGBAColor(0, 255, 0, 255);
end;
function ColorLimeGreen(): Color;
begin
result := RGBAColor(50, 205, 50, 255);
end;
function ColorLinen(): Color;
begin
result := RGBAColor(250, 240, 230, 255);
end;
function ColorMagenta(): Color;
begin
result := RGBAColor(255, 0, 255, 255);
end;
function ColorMaroon(): Color;
begin
result := RGBAColor(128, 0, 0, 255);
end;
function ColorMediumAquamarine(): Color;
begin
result := RGBAColor(102, 205, 170, 255);
end;
function ColorMediumBlue(): Color;
begin
result := RGBAColor(0, 0, 205, 255);
end;
function ColorMediumOrchid(): Color;
begin
result := RGBAColor(186, 85, 211, 255);
end;
function ColorMediumPurple(): Color;
begin
result := RGBAColor(147, 112, 219, 255);
end;
function ColorMediumSeaGreen(): Color;
begin
result := RGBAColor(60, 179, 113, 255);
end;
function ColorMediumSlateBlue(): Color;
begin
result := RGBAColor(123, 104, 238, 255);
end;
function ColorMediumSpringGreen(): Color;
begin
result := RGBAColor(0, 250, 154, 255);
end;
function ColorMediumTurquoise(): Color;
begin
result := RGBAColor(72, 209, 204, 255);
end;
function ColorMediumVioletRed(): Color;
begin
result := RGBAColor(199, 21, 133, 255);
end;
function ColorMidnightBlue(): Color;
begin
result := RGBAColor(25, 25, 112, 255);
end;
function ColorMintCream(): Color;
begin
result := RGBAColor(245, 255, 250, 255);
end;
function ColorMistyRose(): Color;
begin
result := RGBAColor(255, 228, 225, 255);
end;
function ColorMoccasin(): Color;
begin
result := RGBAColor(255, 228, 181, 255);
end;
function ColorNavajoWhite(): Color;
begin
result := RGBAColor(255, 222, 173, 255);
end;
function ColorNavy(): Color;
begin
result := RGBAColor(0, 0, 128, 255);
end;
function ColorOldLace(): Color;
begin
result := RGBAColor(253, 245, 230, 255);
end;
function ColorOlive(): Color;
begin
result := RGBAColor(128, 128, 0, 255);
end;
function ColorOliveDrab(): Color;
begin
result := RGBAColor(107, 142, 35, 255);
end;
function ColorOrange(): Color;
begin
result := RGBAColor(255, 165, 0, 255);
end;
function ColorOrangeRed(): Color;
begin
result := RGBAColor(255, 69, 0, 255);
end;
function ColorOrchid(): Color;
begin
result := RGBAColor(218, 112, 214, 255);
end;
function ColorPaleGoldenrod(): Color;
begin
result := RGBAColor(238, 232, 170, 255);
end;
function ColorPaleGreen(): Color;
begin
result := RGBAColor(152, 251, 152, 255);
end;
function ColorPaleTurquoise(): Color;
begin
result := RGBAColor(175, 238, 238, 255);
end;
function ColorPaleVioletRed(): Color;
begin
result := RGBAColor(219, 112, 147, 255);
end;
function ColorPapayaWhip(): Color;
begin
result := RGBAColor(255, 239, 213, 255);
end;
function ColorPeachPuff(): Color;
begin
result := RGBAColor(255, 218, 185, 255);
end;
function ColorPeru(): Color;
begin
result := RGBAColor(205, 133, 63, 255);
end;
function ColorPink(): Color;
begin
result := RGBAColor(255, 192, 203, 255);
end;
function ColorPlum(): Color;
begin
result := RGBAColor(221, 160, 221, 255);
end;
function ColorPowderBlue(): Color;
begin
result := RGBAColor(176, 224, 230, 255);
end;
function ColorPurple(): Color;
begin
result := RGBAColor(128, 0, 128, 255);
end;
function ColorRed(): Color;
begin
result := RGBAColor(255, 0, 0, 255);
end;
function ColorRosyBrown(): Color;
begin
result := RGBAColor(188, 143, 143, 255);
end;
function ColorRoyalBlue(): Color;
begin
result := RGBAColor(65, 105, 225, 255);
end;
function ColorSaddleBrown(): Color;
begin
result := RGBAColor(139, 69, 19, 255);
end;
function ColorSalmon(): Color;
begin
result := RGBAColor(250, 128, 114, 255);
end;
function ColorSandyBrown(): Color;
begin
result := RGBAColor(244, 164, 96, 255);
end;
function ColorSeaGreen(): Color;
begin
result := RGBAColor(46, 139, 87, 255);
end;
function ColorSeaShell(): Color;
begin
result := RGBAColor(255, 245, 238, 255);
end;
function ColorSienna(): Color;
begin
result := RGBAColor(160, 82, 45, 255);
end;
function ColorSilver(): Color;
begin
result := RGBAColor(192, 192, 192, 255);
end;
function ColorSkyBlue(): Color;
begin
result := RGBAColor(135, 206, 235, 255);
end;
function ColorSlateBlue(): Color;
begin
result := RGBAColor(106, 90, 205, 255);
end;
function ColorSlateGray(): Color;
begin
result := RGBAColor(112, 128, 144, 255);
end;
function ColorSnow(): Color;
begin
result := RGBAColor(255, 250, 250, 255);
end;
function ColorSpringGreen(): Color;
begin
result := RGBAColor(0, 255, 127, 255);
end;
function ColorSteelBlue(): Color;
begin
result := RGBAColor(70, 130, 180, 255);
end;
function ColorTan(): Color;
begin
result := RGBAColor(210, 180, 140, 255);
end;
function ColorTeal(): Color;
begin
result := RGBAColor(0, 128, 128, 255);
end;
function ColorThistle(): Color;
begin
result := RGBAColor(216, 191, 216, 255);
end;
function ColorTomato(): Color;
begin
result := RGBAColor(255, 99, 71, 255);
end;
function ColorTurquoise(): Color;
begin
result := RGBAColor(64, 224, 208, 255);
end;
function ColorViolet(): Color;
begin
result := RGBAColor(238, 130, 238, 255);
end;
function ColorWheat(): Color;
begin
result := RGBAColor(245, 222, 179, 255);
end;
function ColorWhite(): Color;
begin
result := RGBAColor(255, 255, 255, 255);
end;
function ColorWhiteSmoke(): Color;
begin
result := RGBAColor(245, 245, 245, 255);
end;
function ColorYellow(): Color;
begin
result := RGBAColor(255, 255, 0, 255);
end;
function ColorYellowGreen(): Color;
begin
result := RGBAColor(154, 205, 50, 255);
end;
function ColorSwinburneRed(): Color;
begin
result := RGBAColor(237, 36, 25, 255);
end;
//=============================================================================
initialization
begin
InitialiseSwinGame();
end;
end.
|
unit ModpathResponseFileWriterUnit;
interface
uses SysUtils, PhastModelUnit, ModflowPackageSelectionUnit, CustomModflowWriterUnit,
DataSetUnit;
type
// MODPATH version 5
TModpathResponseFileWriter = class(TCustomModflowWriter)
private
FOptions: TModpathSelection;
FNewBudgetFile: Boolean;
FArchive: Boolean;
function GetCBF_Option(const AFileName: string): TCompositeBudgetFileOption;
function CompositeBudgetFileSize: Int64;
function RespondToLargeBudgetFile(
CBF_Option: TCompositeBudgetFileOption): string;
procedure WriteResponse;
procedure WriteRspFile(NameOfFile: string; const AFileName: string);
protected
class function Extension: string; override;
public
FLargeBudgetFileResponse: string;
Constructor Create(Model: TCustomModel; EvaluationType: TEvaluationType); override;
procedure WriteFile(const AFileName: string; NewBudgetFile: boolean);
end;
// MODPATH version 6
TModpathSimFileWriter = class(TCustomModflowWriter)
private
FOptions: TModpathSelection;
FNameFile: string;
FTimePointOption: Integer;
FModelName: string;
procedure ArchiveOutputFileName(var AFileName: string);
procedure WriteDataSet0;
procedure WriteDataSet1(IsArchive: Boolean);
procedure WriteDataSet2(Archive: Boolean);
procedure WriteDataSet3;
procedure WriteDataSet4(Archive: Boolean);
procedure WriteDataSet5(Archive: Boolean);
procedure WriteDataSet6(Archive: Boolean);
procedure WriteDataSet7(Archive: Boolean);
procedure WriteDataSet8;
procedure WriteDataSet10;
procedure WriteDataSet22;
procedure WriteDataSet23;
procedure WriteDataSet24;
procedure WriteDataSet25;
procedure WriteDataSets26and27;
procedure WriteDataSet28(Archive: Boolean);
procedure WriteDataSet29;
procedure WriteDataSet30;
procedure WriteDataSet31;
procedure WriteDataSet(const DataSetName: string; DataArray: TDataArray);
procedure WriteDataSets32and33;
procedure SaveFile(NameOfFile: string; IsArchive: Boolean);
protected
function PackageID_Comment(APackage: TModflowPackageSelection): string; override;
public
class function Extension: string; override;
Constructor Create(Model: TCustomModel; EvaluationType: TEvaluationType); override;
procedure WriteFile(const AFileName: string);
end;
implementation
uses
ModflowGridUnit, LayerStructureUnit, ModpathStartingLocationsWriter,
ModpathParticleUnit, frmProgressUnit, GoPhastTypes, Forms, frmGoPhastUnit,
frmErrorsAndWarningsUnit, ModflowTimeUnit, ArchiveNodeInterface;
resourcestring
StrWritingDataSets32and33 = ' Writing Data Sets 32 and 33.';
StrThereIsAnIllegal = 'There is an illegal value (less than or equal to ze' +
'ro) in %s';
StrInSAllValuesSh = 'In %s, all values should be greater than or equal to ' +
'1';
StrLayerRowColumn = 'Layer, Row, Column = (%0:d, %1:d, %2:d)';
StrBecauseThe0sStr = 'Because the %0:s stress period is not steady-state, ' +
'the particles will end at the %1:s of the model simulation. See the docum' +
'entation for StopOption in the MODPATH documentation.';
StrLast = 'last';
StrEnd = 'end';
StrFirst = 'first';
StrBeginning = 'beginning';
StrTheMODPATHStopOpti = 'The MODPATH StopOption may not work as expected.';
StrInvalidMODPATHStop = 'Invalid MODPATH StopZone number';
StrInMODPATHVersion5 = 'In MODPATH version 5, the zone number in which to ' +
'stop particles must be greater than 1. Edit this in the MODFLOW Packages ' +
'and Programs dialog box.';
StrInvalidMODPATHPart = 'Invalid MODPATH particle release time';
StrTheLastForward = 'The last particle release time is after the end of th' +
'e simulation. Edit this in the MODFLOW Packages and Programs dialog box.';
StrTheLastBackward = 'The last particle release time is before the beginni' +
'ng of the simulation. Edit this in the MODFLOW Packages and Programs dial' +
'og box.';
{ TModpathResponseFileWriter }
constructor TModpathResponseFileWriter.Create(Model: TCustomModel; EvaluationType: TEvaluationType);
begin
inherited Create(Model, EvaluationType);
FArrayWritingFormat := awfModflow;
FOptions := Model.ModflowPackages.ModPath;
end;
class function TModpathResponseFileWriter.Extension: string;
begin
result := '.mprsp';
end;
function TModpathResponseFileWriter.GetCBF_Option(
const AFileName: string): TCompositeBudgetFileOption;
var
CompositeBudgetFileName: string;
BudgetFileName: string;
CompositeDate: TDateTime;
BudgetDate: TDateTime;
begin
if FNewBudgetFile or FArchive then
begin
result := cbfGenerateNew;
Exit;
end;
CompositeBudgetFileName := ChangeFileExt(AFileName, '.cbf');
BudgetFileName := ChangeFileExt(AFileName, StrCbcExt);
if FileExists(CompositeBudgetFileName) and FileExists(BudgetFileName) then
begin
if FileAge(CompositeBudgetFileName, CompositeDate)
and FileAge(BudgetFileName, BudgetDate) then
begin
if (CompositeDate > BudgetDate) then
begin
result := cbfUseOldFile;
end
else
begin
result := cbfGenerateNew;
end;
end
else
begin
result := cbfGenerateNew;
end;
end
else
begin
result := cbfGenerateNew;
end;
end;
function TModpathResponseFileWriter.CompositeBudgetFileSize: Int64;
var
NSTEPS: Int64;
Grid: TModflowGrid;
NROW: Int64;
NLAY: Int64;
NHLAY: Int64;
GroupIndex: integer;
Group: TLayerGroup;
NRPTS: Int64;
NREC: Int64;
NCOL: Int64;
begin
// based on the subroutine CBFSIZ in the MODPATH source code.
NSTEPS := Model.ModflowFullStressPeriods.NumberOfSteps;
Grid := Model.ModflowGrid;
NROW := Grid.RowCount;
NCOL := Grid.ColumnCount;
NLAY := Model.ModflowLayerCount;
NHLAY := 0;
for GroupIndex := 1 to Model.LayerStructure.Count - 1 do
begin
Group := Model.LayerStructure.LayerGroups[GroupIndex];
if Group.RunTimeSimulated then
begin
if Group.AquiferType > 0 then
begin
NHLAY := NHLAY + Group.LayerCount;
end;
end;
end;
NRPTS := (6*NROW*NLAY) + (NROW*NHLAY) + NROW + NLAY;
NREC := (1 + (1+NRPTS)*NSTEPS);
result := 4*(NCOL+1)*NREC;
end;
procedure TModpathResponseFileWriter.WriteResponse;
begin
WriteString('@RESPONSE:');
NewLine;
end;
procedure TModpathResponseFileWriter.WriteFile(const AFileName: string;
NewBudgetFile: boolean);
var
NameOfFile: string;
begin
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrInvalidMODPATHStop);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrInvalidMODPATHPart);
FLargeBudgetFileResponse := '';
FNewBudgetFile := NewBudgetFile;
FArchive := False;
NameOfFile := FileName(AFileName);
WriteRspFile(NameOfFile, AFileName);
FArchive := True;
NameOfFile := NameOfFile + ArchiveExt;
WriteRspFile(NameOfFile, AFileName);
Model.AddModpathInputFile(NameOfFile);
end;
procedure TModpathResponseFileWriter.WriteRspFile(NameOfFile: string;
const AFileName: string);
var
CBF_Option: TCompositeBudgetFileOption;
LastReleaseTime: Double;
ReferenceTime: Real;
ComputeLocations: Boolean;
Index: Integer;
begin
OpenFile(NameOfFile);
try
// interactive input
WriteString('@[MODPATH 5.0]');
NewLine;
for Index := 0 to FOptions.Comments.Count - 1 do
begin
WriteString('@ ' + FOptions.Comments[Index]);
NewLine;
end;
// MODPATH name file
// 'ENTER THE NAME FILE:';
WriteString('* ENTER THE NAME FILE:');
NewLine;
WriteResponse;
WriteString(ExtractFileName(AFileName));
NewLine;
ReferenceTime := 0;
CBF_Option := GetCBF_Option(AFileName);
if not Model.ModflowStressPeriods.TransientModel then
begin
// 'DO YOU WANT TO STOP COMPUTING PATHS AFTER A SPECIFIED LENGTH OF TIME ?';
WriteString('* DO YOU WANT TO STOP COMPUTING PATHS AFTER A SPECIFIED LENGTH OF TIME ?');
NewLine;
WriteResponse;
if FOptions.StopAfterMaxTime then
begin
WriteString('Y');
end
else
begin
WriteString('N');
end;
NewLine;
if FOptions.StopAfterMaxTime then
begin
// 'ENTER: MAXIMUM TRACKING TIME & TIME UNITS CONVERSION FACTOR';
WriteString('* ENTER: MAXIMUM TRACKING TIME & TIME UNITS CONVERSION FACTOR');
NewLine;
WriteResponse;
WriteFloat(FOptions.MaxTime);
WriteFloat(1);
NewLine;
end;
end
else
begin
WriteString('* DEFINE A REFERENCE TIME FOR RELEASING PARTICLES ...');
NewLine;
WriteString('* SELECT AN OPTION:');
NewLine;
WriteString('* 1 = SPECIFY BY ENTERING A STRESS PERIOD AND TIME STEP');
NewLine;
WriteString('* 2 = SPECIFY BY ENTERING A VALUE OF SIMULATION TIME');
NewLine;
// 'DEFINE A REFERENCE TIME FOR RELEASING PARTICLES ...';
// ' SELECT AN OPTION:';
// ' 1 = SPECIFY BY ENTERING A STRESS PERIOD AND TIME STEP';
// ' 2 = SPECIFY BY ENTERING A VALUE OF SIMULATION TIME';
WriteResponse;
WriteInteger(2);
NewLine;
// ' ENTER: REFERENCE TIME & TIME UNITS CONVERSION FACTOR';
// Offset the reference time by the beginning of the first stress period.
WriteString('* ENTER: REFERENCE TIME & TIME UNITS CONVERSION FACTOR');
NewLine;
case FOptions.TrackingDirection of
tdForward:
begin
ReferenceTime := FOptions.ReferenceTime;
end;
tdBackward:
begin
ReferenceTime := FOptions.BackwardsTrackingReleaseTime;
end;
else
// - PhastModel.ModflowStressPeriods[0].StartTime;
Assert(False);
end;
WriteResponse;
WriteFloat(ReferenceTime);
WriteInteger(1);
NewLine;
// ' ENTER: STRESS PERIOD & TIME STEP ';
// ' ENTER: RELATIVE TIME WITHIN TIME STEP';
// ' (VALUE FROM 0 TO 1)';
// 'STOP COMPUTING PATHS AT A SPECIFIED VALUE OF TRACKING TIME ?';
WriteString('* STOP COMPUTING PATHS AT A SPECIFIED VALUE OF TRACKING TIME ?');
NewLine;
WriteResponse;
if FOptions.StopAfterMaxTime then
begin
WriteString('Y');
end
else
begin
WriteString('N');
end;
NewLine;
if FOptions.StopAfterMaxTime then
begin
// 'ENTER: MAXIMUM TRACKING TIME & TIME UNITS CONVERSION FACTOR'
WriteString('* ENTER: MAXIMUM TRACKING TIME & TIME UNITS CONVERSION FACTOR');
NewLine;
WriteResponse;
WriteFloat(FOptions.MaxTime);
WriteFloat(1);
NewLine;
end;
// 'SPECIFY AN OPTION FOR READING HEAD AND FLOW RATE DATA:';
// ' 1 = READ STANDARD MODFLOW UNFORMATTED FILES & GENERATE A';
// ' COMPOSITE BUDGET FILE';
// ' 2 = READ FROM AN EXISTING COMPOSITE BUDGET FILE';
WriteString('* SPECIFY AN OPTION FOR READING HEAD AND FLOW RATE DATA:');
NewLine;
WriteString('* 1 = READ STANDARD MODFLOW UNFORMATTED FILES & GENERATE A');
NewLine;
WriteString('* COMPOSITE BUDGET FILE');
NewLine;
WriteString('* 2 = READ FROM AN EXISTING COMPOSITE BUDGET FILE');
NewLine;
// Create a new CBF file if the CBF file doesn't exist or if
// is older the the budget file.
WriteResponse;
case CBF_Option of
cbfGenerateNew:
WriteInteger(1);
cbfUseOldFile:
WriteInteger(2);
else
Assert(False);
end;
NewLine;
end;
WriteString('* SELECT THE OUTPUT MODE:');
NewLine;
WriteString('* 1 = ENDPOINTS');
NewLine;
WriteString('* 2 = PATHLINE');
NewLine;
WriteString('* 3 = TIME SERIES');
NewLine;
// 'SELECT THE OUTPUT MODE:';
// ' 1 = ENDPOINTS';
// ' 2 = PATHLINE';
// ' 3 = TIME SERIES';
WriteResponse;
case FOptions.OutputMode of
mopEndpoints:
WriteInteger(1);
mopPathline:
WriteInteger(2);
mopTimeSeries:
WriteInteger(3);
else
Assert(False);
end;
NewLine;
if (FOptions.OutputMode in [mopPathline, mopTimeSeries]) then
begin
ComputeLocations := False;
case FOptions.TimeSeriesMethod of
tsmUniform:
ComputeLocations := FOptions.TimeSeriesMaxCount > 0;
tsmIndividual:
ComputeLocations := FOptions.OutputTimes.Count > 0;
else
Assert(False);
end;
if FOptions.OutputMode = mopPathline then
begin
// 'DO YOU WANT TO COMPUTE LOCATIONS AT SPECIFIC POINTS IN TIME?';
WriteString('* DO YOU WANT TO COMPUTE LOCATIONS AT SPECIFIC POINTS IN TIME?');
NewLine;
WriteResponse;
if ComputeLocations then
begin
WriteString('Y');
end
else
begin
WriteString('N');
end;
NewLine;
end;
if ComputeLocations then
begin
// 'HOW SHOULD POINTS IN TIME BE SPECIFIED ?';
// ' 1 = WITH A CONSTANT TIME INTERVAL';
// ' 2 = VALUES OF TIME POINTS ARE READ FROM A FILE';
WriteString('* HOW SHOULD POINTS IN TIME BE SPECIFIED ?');
NewLine;
WriteString('* 1 = WITH A CONSTANT TIME INTERVAL');
NewLine;
WriteString('* 2 = VALUES OF TIME POINTS ARE READ FROM A FILE');
NewLine;
WriteResponse;
case FOptions.TimeSeriesMethod of
tsmUniform:
WriteInteger(1);
tsmIndividual:
WriteInteger(2);
else
Assert(False);
end;
NewLine;
end;
if ComputeLocations and (FOptions.TimeSeriesMethod = tsmUniform) then
begin
// 'ENTER: TIME INTERVAL & TIME UNITS CONVERSION FACTOR';
WriteString('* ENTER: TIME INTERVAL & TIME UNITS CONVERSION FACTOR');
NewLine;
WriteResponse;
WriteFloat(FOptions.TimeSeriesInterval);
WriteFloat(1);
NewLine;
// 'ENTER THE MAXIMUM NUMBER OF TIME POINTS ALLOWED';
WriteString('* ENTER THE MAXIMUM NUMBER OF TIME POINTS ALLOWED');
NewLine;
WriteResponse;
WriteInteger(FOptions.TimeSeriesMaxCount);
NewLine;
LastReleaseTime := FOptions.TimeSeriesInterval * FOptions.TimeSeriesMaxCount;
case FOptions.TrackingDirection of
tdForward:
begin
if ReferenceTime + LastReleaseTime > Model.ModflowFullStressPeriods.Last.EndTime then
begin
frmErrorsAndWarnings.AddError(Model, StrInvalidMODPATHPart, StrTheLastForward);
end;
end;
tdBackward:
begin
if ReferenceTime - LastReleaseTime < Model.ModflowFullStressPeriods.First.StartTime then
begin
frmErrorsAndWarnings.AddError(Model, StrInvalidMODPATHPart, StrTheLastBackward);
end;
end;
else
Assert(False);
end;
end;
end;
// 'HOW ARE STARTING LOCATIONS TO BE ENTERED?';
// ' 1 = FROM AN EXISTING DATA FILE';
// ' 2 = ARRAYS OF PARTICLES WILL BE GENERATED INTERNALLY';
WriteString('* HOW ARE STARTING LOCATIONS TO BE ENTERED?');
NewLine;
WriteString('* 1 = FROM AN EXISTING DATA FILE');
NewLine;
WriteString('* 2 = ARRAYS OF PARTICLES WILL BE GENERATED INTERNALLY');
NewLine;
WriteResponse;
WriteInteger(1);
NewLine;
// 'ENTER NAME OF DATA FILE CONTAINING STARTING LOCATIONS:';
// 'DO YOU WANT TO STORE INTERNALLY-GENERATED STARTING LOCATIONS ON DISK ?';
// 'ENTER A FILE NAME:';
// 'IN WHICH DIRECTION SHOULD PARTICLES BE TRACKED?';
// ' 1 = FORWARD IN THE DIRECTION OF FLOW';
// ' 2 = BACKWARDS TOWARD RECHARGE LOCATIONS';
WriteString('* IN WHICH DIRECTION SHOULD PARTICLES BE TRACKED?');
NewLine;
WriteString('* 1 = FORWARD IN THE DIRECTION OF FLOW');
NewLine;
WriteString('* 2 = BACKWARDS TOWARD RECHARGE LOCATIONS');
NewLine;
WriteResponse;
case FOptions.TrackingDirection of
tdForward:
WriteInteger(1);
tdBackward:
WriteInteger(2);
else
Assert(False);
end;
NewLine;
// 'HOW SHOULD PARTICLES BE TREATED WHEN THEY ENTER CELLS WITH INTERNAL SINKS ?';
// ' 1 = PASS THROUGH WEAK SINK CELLS';
// ' 2 = STOP AT WEAK SINK CELLS';
// ' 3 = STOP AT WEAK SINK CELLS THAT EXCEED A SPECIFIED STRENGTH';
WriteString('* HOW SHOULD PARTICLES BE TREATED WHEN THEY ENTER CELLS WITH INTERNAL SINKS ?');
NewLine;
WriteString('* 1 = PASS THROUGH WEAK SINK CELLS');
NewLine;
WriteString('* 2 = STOP AT WEAK SINK CELLS');
NewLine;
WriteString('* 3 = STOP AT WEAK SINK CELLS THAT EXCEED A SPECIFIED STRENGTH');
NewLine;
WriteResponse;
case FOptions.WeakSink of
wsPassThrough:
WriteInteger(1);
wsStop:
WriteInteger(2);
wsThreshold:
WriteInteger(3);
else
Assert(False);
end;
NewLine;
if FOptions.WeakSink = wsThreshold then
begin
// 'ENTER A NUMBER BETWEEN 0 AND 1:';
// ' (0.0 => NONE OF THE INFLOW TO THE CELL IS DISCHARGED TO INTERNAL SINKS)';
// ' (1.0 => ALL INFLOW TO THE CELL IS DISCHARGED TO INTERNAL SINKS)';
WriteString('* ENTER A NUMBER BETWEEN 0 AND 1:');
NewLine;
WriteString('* (0.0 => NONE OF THE INFLOW TO THE CELL IS DISCHARGED TO INTERNAL SINKS)');
NewLine;
WriteString('* (1.0 => ALL INFLOW TO THE CELL IS DISCHARGED TO INTERNAL SINKS)');
NewLine;
WriteResponse;
WriteFloat(FOptions.WeakSinkThreshold);
NewLine;
end;
WriteString('* DO YOU WANT TO STOP PARTICLES WHENEVER THEY ENTER ONE SPECIFIC ZONE ?');
NewLine;
// 'DO YOU WANT TO STOP PARTICLES WHENEVER THEY ENTER ONE SPECIFIC ZONE ?';
WriteResponse;
if FOptions.StopInZone then
begin
WriteString('Y');
end
else
begin
WriteString('N');
end;
NewLine;
if FOptions.StopInZone then
begin
// 'ENTER THE ZONE NUMBER (MUST BE > 1):';
WriteString('* ENTER THE ZONE NUMBER (MUST BE > 1):');
NewLine;
WriteResponse;
WriteInteger(FOptions.StopZoneNumber);
if FOptions.StopZoneNumber <= 1 then
begin
frmErrorsAndWarnings.AddError(Model, StrInvalidMODPATHStop, StrInMODPATHVersion5);
end;
NewLine;
if FOptions.OutputMode = mopEndpoints then
begin
// 'SPECIFY WHICH ENDPOINTS TO RECORD:';
// ' 1 = ENDPOINT DATA RECORDED FOR ALL PARTICLES';
// ' 2 = ENDPOINT DATA RECORDED ONLY FOR PARTICLES';
// ' TERMINATING IN ZONE ';
WriteResponse;
case FOptions.EndpointWrite of
ewAll:
WriteInteger(1);
ewInStoppingZone:
WriteInteger(2);
else
Assert(False);
end;
NewLine;
end;
end;
FLargeBudgetFileResponse := RespondToLargeBudgetFile(CBF_Option);
if FOptions.StopInZone then
begin
// 'DO YOU WANT TO CHANGE ANY OF THE ZONE CODES IN THE IBOUND ARRAY ?';
WriteString('* DO YOU WANT TO CHANGE ANY OF THE ZONE CODES IN THE IBOUND ARRAY ?');
NewLine;
WriteResponse;
WriteString('N');
NewLine;
end;
// 'DO YOU WANT TO COMPUTE VOLUMETRIC BUDGETS FOR ALL CELLS ?';
WriteString('* DO YOU WANT TO COMPUTE VOLUMETRIC BUDGETS FOR ALL CELLS ?');
NewLine;
WriteResponse;
if FOptions.ComputeBudgetInAllCells then
begin
WriteString('Y');
end
else
begin
WriteString('N');
end;
NewLine;
if FOptions.ComputeBudgetInAllCells then
begin
// 'SPECIFY AN ERROR TOLERANCE (IN PERCENT):';
WriteString('* SPECIFY AN ERROR TOLERANCE (IN PERCENT):');
NewLine;
WriteResponse;
WriteFloat(FOptions.ErrorTolerance);
NewLine;
end;
// ' DO YOU WANT TO CHECK DATA CELL BY CELL ?';
WriteString('* DO YOU WANT TO CHECK DATA CELL BY CELL ?');
NewLine;
WriteResponse;
WriteString('N');
NewLine;
// 'SUMMARIZE FINAL STATUS OF PARTICLES IN SUMMARY.PTH FILE ?';
WriteString('* SUMMARIZE FINAL STATUS OF PARTICLES IN SUMMARY.PTH FILE ?');
NewLine;
WriteResponse;
if FOptions.Summarize then
begin
WriteString('Y');
end
else
begin
WriteString('N');
end;
NewLine;
finally
CloseFile;
end;
end;
function TModpathResponseFileWriter.RespondToLargeBudgetFile(
CBF_Option: TCompositeBudgetFileOption): string;
const
MAXSIZ = 150000000;
var
BigFile: Boolean;
CBFileSize: Int64;
begin
result := '';
if CBF_Option = cbfGenerateNew then
begin
CBFileSize := CompositeBudgetFileSize;
if FOptions.MaximumSize = 0 then
begin
BigFile := CBFileSize > MAXSIZ;
end
else
begin
BigFile := CBFileSize > FOptions.MaximumSize;
end;
if BigFile then
begin
// WriteString('* THIS RUN WILL GENERATE A COMPOSITE BUDGET FILE THAT CONTAINS:');
// NewLine;
// KCBFileSize := CBFileSize / 1024;
// MCBFileSize := KCBFileSize/ 1024;
// if KCBFileSize < 500 then
// begin
// WriteString('* ' + IntToStr(CBFileSize) + ' BYTES ('
// + FloatToStr(KCBFileSize) + ' KB)');
// NewLine;
// end
// else
// begin
// WriteString('* ' + IntToStr(CBFileSize) + ' BYTES ('
// + FloatToStr(MCBFileSize) + ' MB)');
// NewLine;
// end;
// WriteString('* YOU CAN CONTINUE OR STOP NOW.');
// NewLine;
// WriteString('* SELECT AN OPTION:');
// NewLine;
// WriteString('* 1 = CONTINUE');
// NewLine;
// WriteString('* 2 = STOP NOW, DO NOT GENERATE THE FILE');
// NewLine;
// WriteResponse;
if FOptions.MakeBigBudgetFile then
begin
result := '1';
end
else
begin
result := '2';
end;
end;
end;
end;
{ TModpathSimFileWriter }
procedure TModpathSimFileWriter.ArchiveOutputFileName(var AFileName: string);
begin
AFileName := '..\..\output\' + FModelName + '_Modpath\' + AFileName;
end;
constructor TModpathSimFileWriter.Create(Model: TCustomModel;
EvaluationType: TEvaluationType);
begin
inherited Create(Model, EvaluationType);
FArrayWritingFormat := awfModflow;
FOptions := Model.ModflowPackages.ModPath;
end;
class function TModpathSimFileWriter.Extension: string;
begin
result := '.mpsim';
end;
function TModpathSimFileWriter.PackageID_Comment(
APackage: TModflowPackageSelection): string;
begin
result := File_Comment(APackage.PackageIdentifier + ' Simulation file');
end;
procedure TModpathSimFileWriter.WriteDataSet(const DataSetName: string;
DataArray: TDataArray);
var
LayerIndex: integer;
begin
Assert(DataArray <> nil);
for LayerIndex := 0 to Model.ModflowGrid.LayerCount - 1 do
begin
if Model.IsLayerSimulated(LayerIndex) then
begin
WriteArray(DataArray, LayerIndex, DataSetName + ' '
+ Model.ModflowLayerBottomDescription(LayerIndex), StrNoValueAssigned, DataSetName);
end;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet0;
begin
WriteCommentLine(PackageID_Comment(FOptions));
WriteCommentLines(FOptions.Comments);
end;
procedure TModpathSimFileWriter.WriteDataSet1(IsArchive: Boolean);
begin
frmProgressMM.AddMessage(StrWritingDataSet1);
if IsArchive then
begin
Model.AddModpathInputFile(FNameFile + ArchiveExt);
end;
WriteString(ExtractFileName(FNameFile));
// WriteString(' # Data Set 1. ModpathNameFile');
NewLine;
end;
procedure TModpathSimFileWriter.WriteDataSet10;
var
StopTime: Real;
begin
if FOptions.StopOption = soTrackingTime then
begin
frmProgressMM.AddMessage(StrWritingDataSet10);
StopTime := FOptions.StopTime;
WriteFloat(StopTime);
WriteString(' # Data Set 10: StopTime');
NewLine;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet2(Archive: Boolean);
var
AFileName: string;
begin
frmProgressMM.AddMessage(StrWritingDataSet2);
AFileName := ChangeFileExt(FNameFile, '.mplst');
Model.AddModpathOutputFile(AFileName);
AFileName := ExtractFileName(AFileName);
if Archive then
begin
ArchiveOutputFileName(AFileName);
end;
WriteString(AFileName);
// WriteString(' # Data Set 2. ModpathListingFile');
NewLine;
end;
procedure TModpathSimFileWriter.WriteDataSet22;
var
AFileName: string;
begin
frmProgressMM.AddMessage(StrWritingDataSet22);
AFileName := ChangeFileExt(FNameFile,
TModpathStartingLocationsWriter.Extension);
Model.AddModpathInputFile(AFileName);
AFileName := ExtractFileName(AFileName);
WriteString(AFileName);
// WriteString(' # Data Set 22. StartingLocationsFile');
NewLine;
end;
procedure TModpathSimFileWriter.WriteDataSet23;
var
TimePointCount: integer;
begin
if FTimePointOption in [2,3] then
begin
frmProgressMM.AddMessage(StrWritingDataSet23);
TimePointCount := -1;
case FTimePointOption of
2:
begin
TimePointCount := FOptions.TimeSeriesMaxCount;
end;
3:
begin
TimePointCount := FOptions.OutputTimes.Count;
end;
else Assert(False);
end;
WriteInteger(TimePointCount);
WriteString(' # Data Set 23: TimePointCount');
NewLine;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet24;
var
ReleaseTimeIncrement: Double;
begin
if FTimePointOption = 2 then
begin
frmProgressMM.AddMessage(StrWritingDataSet24);
ReleaseTimeIncrement := FOptions.TimeSeriesInterval;
WriteFloat(ReleaseTimeIncrement);
WriteString(' # Data Set 24: ReleaseTimeIncrement');
NewLine;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet25;
var
Index: Integer;
Item: TModpathTimeItem;
begin
if FTimePointOption = 3 then
begin
frmProgressMM.AddMessage(StrWritingDataSet25);
for Index := 0 to FOptions.OutputTimes.Count - 1 do
begin
Item := FOptions.
OutputTimes.Items[Index] as TModpathTimeItem;
WriteFloat(Item.Time);
if Index = FOptions.OutputTimes.Count - 1 then
begin
WriteString(' # Data Set 25: TimePoints');
end;
if (((Index + 1) mod 10) = 0) or (Index = FOptions.OutputTimes.Count - 1) then
begin
NewLine;
end;
end;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet28(Archive: Boolean);
var
AFileName: string;
begin
if FOptions.BudgetChecking = bcTrace then
begin
frmProgressMM.AddMessage(StrWritingDataSet28);
AFileName := ChangeFileExt(FNameFile, '.trace');
frmGoPhast.PhastModel.AddModpathOutputFile(AFileName);
AFileName := ExtractFileName(AFileName);
if Archive then
begin
ArchiveOutputFileName(AFileName);
end;
WriteString(AFileName);
// WriteString(' # Data Set 29. TraceFile');
NewLine;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet29;
var
TraceID: integer;
begin
if FOptions.BudgetChecking = bcTrace then
begin
frmProgressMM.AddMessage(StrWritingDataSet29);
TraceID := FOptions.TraceID;
WriteInteger(TraceID);
WriteString(' # Data Set 29: TraceID');
NewLine;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet3;
const
ReferenceTimeOption = 1;
ParticleGenerationOption = 2;
var
SimulationType: integer;
TrackingDirection: Integer;
WeakSinkOption: integer;
WeakSouceOption: integer;
StopOption: integer;
BudgetOutputOption: Integer;
ZoneArrayOption: Integer;
RetardationOption: Integer;
AdvectiveObservationsOption: Integer;
StressPeriod: TModflowStressPeriod;
Warning: string;
begin
frmProgressMM.AddMessage(StrWritingDataSet3);
SimulationType := Ord(FOptions.OutputMode) + 1;
TrackingDirection := Ord(FOptions.TrackingDirection) + 1;
WeakSinkOption := Ord(FOptions.WeakSink) + 1;
if WeakSinkOption > 2 then
begin
WeakSinkOption := 2;
end;
WeakSouceOption := Ord(FOptions.WeakSource) + 1;
if WeakSouceOption > 2 then
begin
WeakSouceOption := 2;
end;
StopOption := Ord(FOptions.StopOption) + 1;
if StopOption = 2 then
begin
if TrackingDirection = 1 then
begin
// forward tracking
StressPeriod := Model.ModflowFullStressPeriods.Last;
end
else
begin
// backwards tracking
Assert(TrackingDirection = 2);
StressPeriod := Model.ModflowFullStressPeriods.First;
end;
if StressPeriod.StressPeriodType <> sptSteadyState then
begin
if TrackingDirection = 1 then
begin
// forward tracking
Warning := Format(StrBecauseThe0sStr, [StrLast, StrEnd]);
end
else
begin
// backwards tracking
Assert(TrackingDirection = 2);
Warning := Format(StrBecauseThe0sStr, [StrFirst, StrBeginning]);
end;
frmErrorsAndWarnings.AddWarning(Model, StrTheMODPATHStopOpti, Warning);
end;
end;
FTimePointOption := 0;
if (FOptions.OutputMode in [mopPathline, mopTimeSeries]) then
begin
case FOptions.TimeSeriesMethod of
tsmUniform:
begin
if FOptions.TimeSeriesMaxCount > 0 then
begin
FTimePointOption := 2;
end
else
begin
FTimePointOption := 1;
end;
end;
tsmIndividual:
begin
if FOptions.OutputTimes.Count > 0 then
begin
FTimePointOption := 3;
end
else
begin
FTimePointOption := 1;
end;
end;
else Assert(False);
end;
end
else
begin
FTimePointOption := 1;
end;
BudgetOutputOption := Ord(FOptions.BudgetChecking) + 1;
ZoneArrayOption := Ord(FOptions.StopInZone) + 1;
RetardationOption := Ord(FOptions.RetardationOption) + 1;
if FOptions.OutputMode = mopTimeSeries then
begin
AdvectiveObservationsOption := Ord(FOptions.AdvectiveObservations) + 1;
end
else
begin
AdvectiveObservationsOption := 1;
end;
WriteInteger(SimulationType);
WriteInteger(TrackingDirection);
WriteInteger(WeakSinkOption);
WriteInteger(WeakSouceOption);
WriteInteger(ReferenceTimeOption);
WriteInteger(StopOption);
WriteInteger(ParticleGenerationOption);
WriteInteger(FTimePointOption);
WriteInteger(BudgetOutputOption);
WriteInteger(ZoneArrayOption);
WriteInteger(RetardationOption);
WriteInteger(AdvectiveObservationsOption);
WriteString(' # Data Set 3: SimulationType, TrackingDirection, '
+ 'WeakSinkOption, WeakSouceOption, ReferenceTimeOption, StopOption, '
+ 'ParticleGenerationOption, TimePointOption, BudgetOutputOption, '
+ 'ZoneArrayOption, RetardationOption, AdvectiveObservationsOption');
NewLine;
end;
procedure TModpathSimFileWriter.WriteDataSet30;
var
StopZone: integer;
begin
if FOptions.StopInZone then
begin
frmProgressMM.AddMessage(StrWritingDataSet30);
StopZone := FOptions.StopZoneNumber;
WriteInteger(StopZone);
WriteString(' # Data Set 30: StopZone');
NewLine;
// removed from code
// if StopZone >= 1 then
// begin
// // undocumented. See lines 346-366 of MP6MPBAS1.FOR
// StopZone := FOptions.StopZoneNumber;
// WriteInteger(StopZone);
// WriteString(' # Data Set 30a: StopZone');
// NewLine;
// end;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet31;
var
ZoneDataArray: TDataArray;
begin
if FOptions.StopInZone then
begin
frmProgressMM.AddMessage(StrWritingDataSet31);
ZoneDataArray := Model.DataArrayManager.GetDataSetByName(StrModpathZone);
WriteDataSet('Data Set 31: Zone', ZoneDataArray);
end;
end;
procedure TModpathSimFileWriter.WriteDataSet4(Archive: Boolean);
var
AFileName: string;
begin
frmProgressMM.AddMessage(StrWritingDataSet4);
AFileName := ChangeFileExt(FNameFile, '.end');
Model.AddModpathOutputFile(AFileName);
AFileName := ExtractFileName(AFileName);
if Archive then
begin
ArchiveOutputFileName(AFileName);
end;
WriteString(AFileName);
// WriteString(' # Data Set 4. EndpointFile');
NewLine;
end;
procedure TModpathSimFileWriter.WriteDataSet5(Archive: Boolean);
var
AFileName: string;
begin
if FOptions.OutputMode = mopPathline then
begin
frmProgressMM.AddMessage(StrWritingDataSet5);
AFileName := ChangeFileExt(FNameFile, '.path');
Model.AddModpathOutputFile(AFileName);
AFileName := ExtractFileName(AFileName);
if Archive then
begin
ArchiveOutputFileName(AFileName);
end;
WriteString(AFileName);
// WriteString(' # Data Set 5. PathlineFile');
NewLine;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet6(Archive: Boolean);
var
AFileName: string;
begin
if FOptions.OutputMode = mopTimeSeries then
begin
frmProgressMM.AddMessage(StrWritingDataSet6);
AFileName := ChangeFileExt(FNameFile, '.ts');
Model.AddModpathOutputFile(AFileName);
AFileName := ExtractFileName(AFileName);
if Archive then
begin
ArchiveOutputFileName(AFileName);
end;
WriteString(AFileName);
// WriteString(' # Data Set 6. TimeSeriesFile');
NewLine;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet7(Archive: Boolean);
var
AFileName: string;
begin
if (FOptions.AdvectiveObservations = aoAll)
and (FOptions.OutputMode = mopTimeSeries) then
begin
frmProgressMM.AddMessage(StrWritingDataSet7);
AFileName := ChangeFileExt(FNameFile, '.advobs');
Model.AddModpathOutputFile(AFileName);
if Archive then
begin
ArchiveOutputFileName(AFileName);
end;
AFileName := ExtractFileName(AFileName);
WriteString(AFileName);
// WriteString(' # Data Set 7. AdvectionObservationsFile');
NewLine;
end;
end;
procedure TModpathSimFileWriter.WriteDataSet8;
var
ReferenceTime: Real;
begin
// ReferenceTimeOption is always set to 1
// so this data set is always exported and
// data set 9 is never exported.
frmProgressMM.AddMessage(StrWritingDataSet8);
ReferenceTime := FOptions.ReferenceTime
- Model.ModflowStressPeriods[0].StartTime;
WriteFloat(ReferenceTime);
WriteString(' # Data Set 8: ReferenceTime');
NewLine;
end;
procedure TModpathSimFileWriter.WriteDataSets26and27;
const
Grid = 1;
var
DataArray: TDataArray;
CellBudgetCount: integer;
LayerIndex: integer;
RowIndex: integer;
ColIndex: integer;
begin
if FOptions.BudgetChecking = bcList then
begin
frmProgressMM.AddMessage(StrWritingDataSet26);
DataArray := Model.DataArrayManager.GetDataSetByName(KModpathBudget);
DataArray.Initialize;
CellBudgetCount := 0;
for LayerIndex := 0 to DataArray.LayerCount - 1 do
begin
if Model.IsLayerSimulated(LayerIndex) then
begin
for RowIndex := 0 to DataArray.RowCount - 1 do
begin
for ColIndex := 0 to DataArray.ColumnCount - 1 do
begin
if DataArray.BooleanData[LayerIndex,RowIndex,ColIndex] then
begin
Inc(CellBudgetCount);
end;
end;
end;
end;
end;
WriteInteger(CellBudgetCount);
WriteString(' # Data Set 26: CellBudgetCount');
NewLine;
frmProgressMM.AddMessage(StrWritingDataSet27);
for LayerIndex := 0 to DataArray.LayerCount - 1 do
begin
if Model.IsLayerSimulated(LayerIndex) then
begin
for RowIndex := 0 to DataArray.RowCount - 1 do
begin
for ColIndex := 0 to DataArray.ColumnCount - 1 do
begin
if DataArray.BooleanData[LayerIndex,RowIndex,ColIndex] then
begin
WriteInteger(Grid);
WriteInteger(LayerIndex+1);
WriteInteger(RowIndex+1);
WriteInteger(ColIndex+1);
WriteString(' # Data Set 27: Grid, Layer, Row, Column');
NewLine;
end;
end;
end;
end;
end;
end;
end;
procedure TModpathSimFileWriter.WriteDataSets32and33;
var
RetardationDataArray: TDataArray;
LayerIndex: Integer;
DataSetName: string;
ActiveDataArray: TDataArray;
RowIndex: Integer;
ColIndex: Integer;
AValue: Double;
ErrorRoot: string;
WarningRoot: string;
begin
frmErrorsAndWarnings.BeginUpdate;
try
if FOptions.RetardationOption = roUsed then
begin
frmProgressMM.AddMessage(StrWritingDataSets32and33);
RetardationDataArray := Model.DataArrayManager.GetDataSetByName(KModpathRetardation);
Assert(RetardationDataArray <> nil);
for LayerIndex := 0 to Model.ModflowGrid.LayerCount - 1 do
begin
if Model.IsLayerSimulated(LayerIndex) then
begin
DataSetName := 'Data Set 32: RetardationFactor ';
end
else
begin
DataSetName := 'Data Set 32: RetardationFactorCB ';
end;
WriteArray(RetardationDataArray, LayerIndex, DataSetName
+ Model.ModflowLayerBottomDescription(LayerIndex), StrNoValueAssigned, DataSetName);
end;
ErrorRoot := Format(StrThereIsAnIllegal,
[RetardationDataArray.DisplayName]);
WarningRoot := Format(StrInSAllValuesSh,
[RetardationDataArray.DisplayName]);
frmErrorsAndWarnings.RemoveErrorGroup(Model, ErrorRoot);
frmErrorsAndWarnings.RemoveWarningGroup(Model, WarningRoot);
ActiveDataArray := Model.DataArrayManager.GetDataSetByName(rsActive);
for LayerIndex := 0 to Model.ModflowGrid.LayerCount - 1 do
begin
for RowIndex := 0 to Model.ModflowGrid.RowCount - 1 do
begin
for ColIndex := 0 to Model.ModflowGrid.ColumnCount - 1 do
begin
if ActiveDataArray.BooleanData[LayerIndex,RowIndex,ColIndex] then
begin
AValue := RetardationDataArray.RealData[LayerIndex,RowIndex,ColIndex];
if AValue <= 0 then
begin
frmErrorsAndWarnings.AddError(Model, ErrorRoot,
Format(StrLayerRowColumn,
[LayerIndex+1, RowIndex+1, ColIndex+1]));
end
else if AValue < 1 then
begin
frmErrorsAndWarnings.AddWarning(Model, WarningRoot,
Format(StrLayerRowColumn,
[LayerIndex+1, RowIndex+1, ColIndex+1]));
end;
end;
end;
end;
end;
end;
finally
frmErrorsAndWarnings.EndUpdate;
end;
end;
procedure TModpathSimFileWriter.SaveFile(NameOfFile: string;
IsArchive: Boolean);
begin
OpenFile(NameOfFile);
try
WriteDataSet0;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet1(IsArchive);
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet2(IsArchive);
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet3;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet4(IsArchive);
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet5(IsArchive);
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet6(IsArchive);
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet7(IsArchive);
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet8;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet10;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet22;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet23;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet24;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet25;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSets26and27;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet28(IsArchive);
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet29;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet30;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSet31;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
WriteDataSets32and33;
finally
CloseFile
end;
end;
procedure TModpathSimFileWriter.WriteFile(const AFileName: string);
var
NameOfFile: string;
ADirectory: string;
begin
frmErrorsAndWarnings.RemoveWarningGroup(Model, StrTheMODPATHStopOpti);
FNameFile := AFileName;
NameOfFile := FileName(AFileName);
FModelName := ExtractFileName(AFileName);
FModelName := ChangeFileExt(FModelName , '');
SaveFile(NameOfFile, False);
SaveFile(NameOfFile + ArchiveExt, True);
Model.AddModpathInputFile(NameOfFile + ArchiveExt);
ADirectory := IncludeTrailingPathDelimiter(ExtractFileDir(NameOfFile));
Model.AddModpathOutputFile(ADirectory + 'MPATH6.LOG');
// Model.AddModelInputFile(NameOfFile);
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [NFE_CABECALHO]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit NfeCabecalhoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
NfeDestinatarioVO, NfeDetalheVO, NfeFormaPagamentoVO;
type
TNfeCabecalhoVO = class(TVO)
private
FID: Integer;
FID_NFCE_MOVIMENTO: Integer;
FID_VENDEDOR: Integer;
FID_TRIBUT_OPERACAO_FISCAL: Integer;
FID_VENDA_CABECALHO: Integer;
FID_EMPRESA: Integer;
FID_FORNECEDOR: Integer;
FID_CLIENTE: Integer;
FUF_EMITENTE: Integer;
FCODIGO_NUMERICO: String;
FNATUREZA_OPERACAO: String;
FINDICADOR_FORMA_PAGAMENTO: Integer;
FCODIGO_MODELO: String;
FSERIE: String;
FNUMERO: String;
FDATA_HORA_EMISSAO: TDateTime;
FDATA_HORA_ENTRADA_SAIDA: TDateTime;
FTIPO_OPERACAO: Integer;
FLOCAL_DESTINO: Integer;
FCODIGO_MUNICIPIO: Integer;
FFORMATO_IMPRESSAO_DANFE: Integer;
FTIPO_EMISSAO: Integer;
FCHAVE_ACESSO: String;
FDIGITO_CHAVE_ACESSO: String;
FAMBIENTE: Integer;
FFINALIDADE_EMISSAO: Integer;
FCONSUMIDOR_OPERACAO: Integer;
FCONSUMIDOR_PRESENCA: Integer;
FPROCESSO_EMISSAO: Integer;
FVERSAO_PROCESSO_EMISSAO: String;
FDATA_ENTRADA_CONTINGENCIA: TDateTime;
FJUSTIFICATIVA_CONTINGENCIA: String;
FBASE_CALCULO_ICMS: Extended;
FVALOR_ICMS: Extended;
FVALOR_ICMS_DESONERADO: Extended;
FBASE_CALCULO_ICMS_ST: Extended;
FVALOR_ICMS_ST: Extended;
FVALOR_TOTAL_PRODUTOS: Extended;
FVALOR_FRETE: Extended;
FVALOR_SEGURO: Extended;
FVALOR_DESCONTO: Extended;
FVALOR_IMPOSTO_IMPORTACAO: Extended;
FVALOR_IPI: Extended;
FVALOR_PIS: Extended;
FVALOR_COFINS: Extended;
FVALOR_DESPESAS_ACESSORIAS: Extended;
FVALOR_TOTAL: Extended;
FVALOR_SERVICOS: Extended;
FBASE_CALCULO_ISSQN: Extended;
FVALOR_ISSQN: Extended;
FVALOR_PIS_ISSQN: Extended;
FVALOR_COFINS_ISSQN: Extended;
FDATA_PRESTACAO_SERVICO: TDateTime;
FVALOR_DEDUCAO_ISSQN: Extended;
FOUTRAS_RETENCOES_ISSQN: Extended;
FDESCONTO_INCONDICIONADO_ISSQN: Extended;
FDESCONTO_CONDICIONADO_ISSQN: Extended;
FTOTAL_RETENCAO_ISSQN: Extended;
FREGIME_ESPECIAL_TRIBUTACAO: Integer;
FVALOR_RETIDO_PIS: Extended;
FVALOR_RETIDO_COFINS: Extended;
FVALOR_RETIDO_CSLL: Extended;
FBASE_CALCULO_IRRF: Extended;
FVALOR_RETIDO_IRRF: Extended;
FBASE_CALCULO_PREVIDENCIA: Extended;
FVALOR_RETIDO_PREVIDENCIA: Extended;
FCOMEX_UF_EMBARQUE: String;
FCOMEX_LOCAL_EMBARQUE: String;
FCOMEX_LOCAL_DESPACHO: String;
FCOMPRA_NOTA_EMPENHO: String;
FCOMPRA_PEDIDO: String;
FCOMPRA_CONTRATO: String;
FINFORMACOES_ADD_FISCO: String;
FINFORMACOES_ADD_CONTRIBUINTE: String;
FSTATUS_NOTA: Integer;
FTROCO: Extended;
FNfeDestinatarioVO: TNfeDestinatarioVO;
FListaNfeDetalheVO: TListaNfeDetalheVO;
FListaNfeFormaPagamentoVO: TListaNfeFormaPagamentoVO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdNfceMovimento: Integer read FID_NFCE_MOVIMENTO write FID_NFCE_MOVIMENTO;
property IdVendedor: Integer read FID_VENDEDOR write FID_VENDEDOR;
property IdTributOperacaoFiscal: Integer read FID_TRIBUT_OPERACAO_FISCAL write FID_TRIBUT_OPERACAO_FISCAL;
property IdVendaCabecalho: Integer read FID_VENDA_CABECALHO write FID_VENDA_CABECALHO;
property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA;
property IdFornecedor: Integer read FID_FORNECEDOR write FID_FORNECEDOR;
property IdCliente: Integer read FID_CLIENTE write FID_CLIENTE;
property UfEmitente: Integer read FUF_EMITENTE write FUF_EMITENTE;
property CodigoNumerico: String read FCODIGO_NUMERICO write FCODIGO_NUMERICO;
property NaturezaOperacao: String read FNATUREZA_OPERACAO write FNATUREZA_OPERACAO;
property IndicadorFormaPagamento: Integer read FINDICADOR_FORMA_PAGAMENTO write FINDICADOR_FORMA_PAGAMENTO;
property CodigoModelo: String read FCODIGO_MODELO write FCODIGO_MODELO;
property Serie: String read FSERIE write FSERIE;
property Numero: String read FNUMERO write FNUMERO;
property DataHoraEmissao: TDateTime read FDATA_HORA_EMISSAO write FDATA_HORA_EMISSAO;
property DataHoraEntradaSaida: TDateTime read FDATA_HORA_ENTRADA_SAIDA write FDATA_HORA_ENTRADA_SAIDA;
property TipoOperacao: Integer read FTIPO_OPERACAO write FTIPO_OPERACAO;
property LocalDestino: Integer read FLOCAL_DESTINO write FLOCAL_DESTINO;
property CodigoMunicipio: Integer read FCODIGO_MUNICIPIO write FCODIGO_MUNICIPIO;
property FormatoImpressaoDanfe: Integer read FFORMATO_IMPRESSAO_DANFE write FFORMATO_IMPRESSAO_DANFE;
property TipoEmissao: Integer read FTIPO_EMISSAO write FTIPO_EMISSAO;
property ChaveAcesso: String read FCHAVE_ACESSO write FCHAVE_ACESSO;
property DigitoChaveAcesso: String read FDIGITO_CHAVE_ACESSO write FDIGITO_CHAVE_ACESSO;
property Ambiente: Integer read FAMBIENTE write FAMBIENTE;
property FinalidadeEmissao: Integer read FFINALIDADE_EMISSAO write FFINALIDADE_EMISSAO;
property ConsumidorOperacao: Integer read FCONSUMIDOR_OPERACAO write FCONSUMIDOR_OPERACAO;
property ConsumidorPresenca: Integer read FCONSUMIDOR_PRESENCA write FCONSUMIDOR_PRESENCA;
property ProcessoEmissao: Integer read FPROCESSO_EMISSAO write FPROCESSO_EMISSAO;
property VersaoProcessoEmissao: String read FVERSAO_PROCESSO_EMISSAO write FVERSAO_PROCESSO_EMISSAO;
property DataEntradaContingencia: TDateTime read FDATA_ENTRADA_CONTINGENCIA write FDATA_ENTRADA_CONTINGENCIA;
property JustificativaContingencia: String read FJUSTIFICATIVA_CONTINGENCIA write FJUSTIFICATIVA_CONTINGENCIA;
property BaseCalculoIcms: Extended read FBASE_CALCULO_ICMS write FBASE_CALCULO_ICMS;
property ValorIcms: Extended read FVALOR_ICMS write FVALOR_ICMS;
property ValorIcmsDesonerado: Extended read FVALOR_ICMS_DESONERADO write FVALOR_ICMS_DESONERADO;
property BaseCalculoIcmsSt: Extended read FBASE_CALCULO_ICMS_ST write FBASE_CALCULO_ICMS_ST;
property ValorIcmsSt: Extended read FVALOR_ICMS_ST write FVALOR_ICMS_ST;
property ValorTotalProdutos: Extended read FVALOR_TOTAL_PRODUTOS write FVALOR_TOTAL_PRODUTOS;
property ValorFrete: Extended read FVALOR_FRETE write FVALOR_FRETE;
property ValorSeguro: Extended read FVALOR_SEGURO write FVALOR_SEGURO;
property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO;
property ValorImpostoImportacao: Extended read FVALOR_IMPOSTO_IMPORTACAO write FVALOR_IMPOSTO_IMPORTACAO;
property ValorIpi: Extended read FVALOR_IPI write FVALOR_IPI;
property ValorPis: Extended read FVALOR_PIS write FVALOR_PIS;
property ValorCofins: Extended read FVALOR_COFINS write FVALOR_COFINS;
property ValorDespesasAcessorias: Extended read FVALOR_DESPESAS_ACESSORIAS write FVALOR_DESPESAS_ACESSORIAS;
property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL;
property ValorServicos: Extended read FVALOR_SERVICOS write FVALOR_SERVICOS;
property BaseCalculoIssqn: Extended read FBASE_CALCULO_ISSQN write FBASE_CALCULO_ISSQN;
property ValorIssqn: Extended read FVALOR_ISSQN write FVALOR_ISSQN;
property ValorPisIssqn: Extended read FVALOR_PIS_ISSQN write FVALOR_PIS_ISSQN;
property ValorCofinsIssqn: Extended read FVALOR_COFINS_ISSQN write FVALOR_COFINS_ISSQN;
property DataPrestacaoServico: TDateTime read FDATA_PRESTACAO_SERVICO write FDATA_PRESTACAO_SERVICO;
property ValorDeducaoIssqn: Extended read FVALOR_DEDUCAO_ISSQN write FVALOR_DEDUCAO_ISSQN;
property OutrasRetencoesIssqn: Extended read FOUTRAS_RETENCOES_ISSQN write FOUTRAS_RETENCOES_ISSQN;
property DescontoIncondicionadoIssqn: Extended read FDESCONTO_INCONDICIONADO_ISSQN write FDESCONTO_INCONDICIONADO_ISSQN;
property DescontoCondicionadoIssqn: Extended read FDESCONTO_CONDICIONADO_ISSQN write FDESCONTO_CONDICIONADO_ISSQN;
property TotalRetencaoIssqn: Extended read FTOTAL_RETENCAO_ISSQN write FTOTAL_RETENCAO_ISSQN;
property RegimeEspecialTributacao: Integer read FREGIME_ESPECIAL_TRIBUTACAO write FREGIME_ESPECIAL_TRIBUTACAO;
property ValorRetidoPis: Extended read FVALOR_RETIDO_PIS write FVALOR_RETIDO_PIS;
property ValorRetidoCofins: Extended read FVALOR_RETIDO_COFINS write FVALOR_RETIDO_COFINS;
property ValorRetidoCsll: Extended read FVALOR_RETIDO_CSLL write FVALOR_RETIDO_CSLL;
property BaseCalculoIrrf: Extended read FBASE_CALCULO_IRRF write FBASE_CALCULO_IRRF;
property ValorRetidoIrrf: Extended read FVALOR_RETIDO_IRRF write FVALOR_RETIDO_IRRF;
property BaseCalculoPrevidencia: Extended read FBASE_CALCULO_PREVIDENCIA write FBASE_CALCULO_PREVIDENCIA;
property ValorRetidoPrevidencia: Extended read FVALOR_RETIDO_PREVIDENCIA write FVALOR_RETIDO_PREVIDENCIA;
property ComexUfEmbarque: String read FCOMEX_UF_EMBARQUE write FCOMEX_UF_EMBARQUE;
property ComexLocalEmbarque: String read FCOMEX_LOCAL_EMBARQUE write FCOMEX_LOCAL_EMBARQUE;
property ComexLocalDespacho: String read FCOMEX_LOCAL_DESPACHO write FCOMEX_LOCAL_DESPACHO;
property CompraNotaEmpenho: String read FCOMPRA_NOTA_EMPENHO write FCOMPRA_NOTA_EMPENHO;
property CompraPedido: String read FCOMPRA_PEDIDO write FCOMPRA_PEDIDO;
property CompraContrato: String read FCOMPRA_CONTRATO write FCOMPRA_CONTRATO;
property InformacoesAddFisco: String read FINFORMACOES_ADD_FISCO write FINFORMACOES_ADD_FISCO;
property InformacoesAddContribuinte: String read FINFORMACOES_ADD_CONTRIBUINTE write FINFORMACOES_ADD_CONTRIBUINTE;
property StatusNota: Integer read FSTATUS_NOTA write FSTATUS_NOTA;
property Troco: Extended read FTROCO write FTROCO;
property NfeDestinatarioVO: TNfeDestinatarioVO read FNfeDestinatarioVO write FNfeDestinatarioVO;
property ListaNfeDetalheVO: TListaNFeDetalheVO read FListaNfeDetalheVO write FListaNfeDetalheVO;
property ListaNfeFormaPagamentoVO: TListaNfeFormaPagamentoVO read FListaNfeFormaPagamentoVO write FListaNfeFormaPagamentoVO;
end;
TListaNfeCabecalhoVO = specialize TFPGObjectList<TNfeCabecalhoVO>;
implementation
constructor TNfeCabecalhoVO.Create;
begin
inherited;
FNfeDestinatarioVO := TNfeDestinatarioVO.Create;
FListaNfeDetalheVO := TListaNfeDetalheVO.Create;
FListaNfeFormaPagamentoVO := TListaNfeFormaPagamentoVO.Create;
end;
destructor TNfeCabecalhoVO.Destroy;
begin
FreeAndNil(FNfeDestinatarioVO);
FreeAndNil(FListaNfeDetalheVO);
FreeAndNil(FListaNfeFormaPagamentoVO);
inherited;
end;
initialization
Classes.RegisterClass(TNfeCabecalhoVO);
finalization
Classes.UnRegisterClass(TNfeCabecalhoVO);
end.
|
unit ShortCutCollection;
interface
uses
SysUtils,Windows,Classes,Menus;
type
TKeyShortCut=class(TCollectionItem)
private
FShiftState: TShiftState;
FKey: Word;
procedure SetKey(const Value: Word);
procedure SetShiftState(const Value: TShiftState);
public
procedure Execute(var Key:Word;Shift:TShiftState);virtual;abstract;
property ShiftState:TShiftState read FShiftState write SetShiftState;
property Key:Word read FKey write SetKey;
end;
TKeyShortCutEvent=procedure(Sender:TObject;var Key:Word;Shift:TShiftState) of object;
TPublicKeyShortCut=class(TKeyShortCut)
private
FOnShortCut: TKeyShortCutEvent;
FName: string;
procedure SetShortCut(const Value: TShortCut);
function GetShortCut: TShortCut;
procedure SetOnShortCut(const Value: TKeyShortCutEvent);
procedure SetName(const Value: string);
public
function GetNamePath:string;override;
procedure Execute(var Key:Word;Shift:TShiftState);override;
published
property ShortCut:TShortCut read GetShortCut write SetShortCut;
property OnShortCut:TKeyShortCutEvent read FOnShortCut write SetOnShortCut;
property Name:string read FName write SetName;
end;
TMouseShortCut=class(TCollectionItem)
private
FShiftState: TShiftState;
procedure SetShiftState(const Value: TShiftState);
public
procedure Execute(X,Y:Integer;Shift:TShiftState);virtual;abstract;
property ShiftState:TShiftState read FShiftState write SetShiftState;
end;
TMouseShortCutEvent=procedure(Sender:TObject;X,Y:Integer;Shift:TShiftState) of object;
TPublicMouseShortCut=class(TMouseShortCut)
private
FOnShortCut: TMouseShortCutEvent;
FName: string;
procedure SetOnShortCut(const Value: TMouseShortCutEvent);
procedure SetName(const Value: string);
public
function GetNamePath:string;override;
procedure Execute(X,Y:Integer;Shift:TShiftState);override;
published
property ShiftState;
property OnShortCut:TMouseShortCutEvent read FOnShortCut write SetOnShortCut;
property Name:string read FName write SetName;
end;
TKeyShortCutCollection=class(TOwnedCollection)
private
function GetItem(Index: Integer): TKeyShortCut;
procedure SetItem(Index: Integer; const Value: TKeyShortCut);
public
function Add:TKeyShortCut;
property Item[Index:Integer]:TKeyShortCut read GetItem write SetItem;default;
end;
TMouseShortCutCollection=class(TOwnedCollection)
private
function GetItem(Index: Integer): TMouseShortCut;
procedure SetItem(Index: Integer; const Value: TMouseShortCut);
public
function Add:TMouseShortCut;
property Item[Index:Integer]:TMouseShortCut read GetItem write SetItem;
end;
procedure ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState); //a little "fix"
function ShortCut(Key: Word; Shift: TShiftState): TShortCut;
implementation
const
scLeft = $100;
scRight = $200;
scMiddle = $400;
scDouble = $800;
function ShortCut(Key: Word; Shift: TShiftState): TShortCut;
begin
Result := 0;
if WordRec(Key).Hi <> 0 then Exit;
Result := Key;
if ssShift in Shift then Inc(Result, scShift);
if ssCtrl in Shift then Inc(Result, scCtrl);
if ssAlt in Shift then Inc(Result, scAlt);
if ssLeft in Shift then Inc(Result, scLeft);
if ssRight in Shift then Inc(Result, scRight);
if ssMiddle in Shift then Inc(Result, scMiddle);
if ssDouble in Shift then Inc(Result, scDouble);
end;
procedure ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState);
begin
Key := Byte(ShortCut);
Shift := [];
if ShortCut and scShift <> 0 then Include(Shift, ssShift);
if ShortCut and scCtrl <> 0 then Include(Shift, ssCtrl);
if ShortCut and scAlt <> 0 then Include(Shift, ssAlt);
if ShortCut and scLeft <> 0 then Include(Shift, ssLeft);
if ShortCut and scMiddle <> 0 then Include(Shift, ssRight);
if ShortCut and scRight <> 0 then Include(Shift, ssMiddle);
if ShortCut and scDouble <> 0 then Include(Shift, ssDouble);
end;
{ TKeyShortCut }
procedure TKeyShortCut.SetKey(const Value: Word);
begin
FKey := Value;
end;
procedure TKeyShortCut.SetShiftState(
const Value: TShiftState);
begin
FShiftState := Value;
end;
{ TPublicKeyShortCut }
procedure TPublicKeyShortCut.Execute(var Key: Word; Shift: TShiftState);
begin
if Assigned(FOnShortCut) then
FOnShortCut(Self,Key,Shift);
end;
function TPublicKeyShortCut.GetNamePath: string;
begin
if FName<>'' then
Result:=Collection.GetNamePath+'_'+FName
else
Result:=inherited GetNamePath;
end;
function TPublicKeyShortCut.GetShortCut: TShortCut;
begin
Result:=ShortCutCollection.ShortCut(FKey,FShiftState);
end;
procedure TPublicKeyShortCut.SetName(const Value: string);
begin
FName := Value;
end;
procedure TPublicKeyShortCut.SetOnShortCut(
const Value: TKeyShortCutEvent);
begin
FOnShortCut := Value;
end;
procedure TPublicKeyShortCut.SetShortCut(const Value: TShortCut);
begin
ShortCutToKey(Value,FKey,FShiftState);
end;
{ TMouseShortCut }
procedure TMouseShortCut.SetShiftState(const Value: TShiftState);
begin
FShiftState := Value;
end;
{ TPublicMouseShortCut }
procedure TPublicMouseShortCut.Execute(X, Y: Integer; Shift: TShiftState);
begin
if Assigned(FOnShortCut) then
FOnShortCut(Self,X,Y,Shift);
end;
function TPublicMouseShortCut.GetNamePath: string;
begin
if FName<>'' then
Result:=Collection.GetNamePath+'_'+FName
else
Result:=inherited GetNamePath;
end;
procedure TPublicMouseShortCut.SetName(const Value: string);
begin
FName := Value;
end;
procedure TPublicMouseShortCut.SetOnShortCut(
const Value: TMouseShortCutEvent);
begin
FOnShortCut := Value;
end;
{ TKeyShortCutCollection }
function TKeyShortCutCollection.Add: TKeyShortCut;
begin
Result:=(inherited Add) as TKeyShortCut;
end;
function TKeyShortCutCollection.GetItem(Index: Integer): TKeyShortCut;
begin
Result:=(inherited GetItem(Index)) as TKeyShortCut;
end;
procedure TKeyShortCutCollection.SetItem(Index: Integer;
const Value: TKeyShortCut);
begin
inherited SetItem(Index,Value);
end;
{ TMouseShortCutCollection }
function TMouseShortCutCollection.Add: TMouseShortCut;
begin
Result:=(inherited Add) as TMouseShortCut;
end;
function TMouseShortCutCollection.GetItem(Index: Integer): TMouseShortCut;
begin
Result:=(inherited GetItem(Index)) as TMouseShortCut;
end;
procedure TMouseShortCutCollection.SetItem(Index: Integer;
const Value: TMouseShortCut);
begin
inherited SetItem(Index,Value);
end;
end.
|
unit LanguageSetLoaderUnit;
interface
uses
Classes, SysUtils,
LanguageSetUnit;
type
TLanguageSetLoaderClass = class of TLanguageSetLoader;
{ TLanguageSetLoader }
TLanguageSetLoader = class
protected
FStream: TStream;
FLanguageSet: TLanguageSet;
property Stream: TStream read FStream;
public
property LanguageSet: TLanguageSet read FLanguageSet;
constructor Create(const aStream: TStream); virtual;
procedure Load; virtual; abstract;
class function LoadFromStream(const aStream: TStream): TLanguageSet;
class function LoadFromResource(const aName: string; const aType: PChar): TLanguageSet;
class function LoadFromFile(const aFileName: string)
: TLanguageSet;
end;
TLanguageSetLoaderException = class(Exception);
implementation
{ TLanguageSetLoader }
constructor TLanguageSetLoader.Create(const aStream: TStream);
begin
inherited Create;
FStream := aStream;
end;
class function TLanguageSetLoader.LoadFromStream(const aStream: TStream): TLanguageSet;
var
l: TLanguageSetLoader;
begin
try
l := self.Create(aStream);
l.Load;
result := l.LanguageSet;
finally
l.Free;
end;
end;
class function TLanguageSetLoader.LoadFromResource(const aName: string; const aType: PChar)
: TLanguageSet;
var
s: TResourceStream;
begin
s := nil;
try
s := TResourceStream.Create(HINSTANCE, aName, aType);
result := LoadFromStream(s);
finally
s.Free;
end;
end;
class function TLanguageSetLoader.LoadFromFile(const aFileName: string): TLanguageSet;
var
s: TStream;
begin
s := nil;
try
s := TFileStream.Create(aFileName, fmOpenRead);
result := LoadFromStream(s);
finally
s.Free;
end;
end;
end.
|
unit AddAction;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ClassActions, MainDM, IBDatabase, Db, IBCustomDataSet,
IBStoredProc;
type
TFormAddAction = class(TForm)
EditName: TEdit;
EditFullName: TEdit;
ButtonOk: TButton;
ButtonCancel: TButton;
LabelAdd: TLabel;
LabelFullName: TLabel;
IBStoredProcIns: TIBStoredProc;
IBTransaction: TIBTransaction;
IBStoredProcUpd: TIBStoredProc;
procedure FormCreate(Sender: TObject);
procedure ButtonOkClick(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
private
{ Private declarations }
FMode: Integer;
public
{ Public declarations }
ResultID: Integer;
constructor Create(Owner: TComponent; Mode: Integer);
end;
implementation
{$R *.DFM}
constructor TFormAddAction.Create(Owner: TComponent; Mode: Integer);
begin
inherited Create(Owner);
FMode := Mode;
end;
procedure TFormAddAction.FormCreate(Sender: TObject);
begin
ResultID := -1;
case FMode of
fmEdit: begin
ButtonOk.Caption := 'Применить';
end;
fmView: begin
ButtonOk.Caption := 'ОК';
ButtonCancel.Caption := 'Выход';
EditName.Enabled := false;
EditFullName.Enabled := false;
end;
end;
if (FMode = fmEdit) or (FMode = fmView) then
begin
EditName.Text := TFormClassAction(Owner).IBQueryActions.FieldByName('name_action').AsString;
EditFullName.Text := TFormClassAction(Owner).IBQueryActions.FieldByName('full_name_action').AsString;
end;
end;
procedure TFormAddAction.ButtonOkClick(Sender: TObject);
var
IBStoredProcAction: TIBStoredProc;
begin
case FMode of
fmAdd : IBStoredProcAction := IBStoredProcIns;
fmEdit: begin
IBStoredProcAction := IBStoredProcUpd;
IBStoredProcAction.ParamByName('PID_ACTION').Value :=
TFormClassAction(Owner).IBQueryActions.FieldByName('ID_ACTION').Value;
end;
end;
IBStoredProcAction.ParamByName('PNAME_ACTION').Value := Trim(EditName.Text);
IBStoredProcAction.ParamByName('PFULL_NAME_ACTION').Value := Trim(EditFullName.Text);
try
IBTransaction.StartTransaction;
IBStoredProcAction.ExecProc;
except
on exc: Exception do
begin
MessageBox(Handle,
PChar('Ошибка! Невозможно выполнить хранимую процедуру ! '+exc.Message),
PChar('Ошибка'),MB_OK+MB_ICONERROR);
IBTransaction.Rollback;
ModalResult := mrCancel; Exit;
end;
end;
IBTransaction.Commit;
if FMode = fmAdd then
ResultID := IBStoredProcIns.ParamByName('PID_ACTION').AsInteger;
ModalResult := mrOk;
end;
procedure TFormAddAction.ButtonCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
end.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, System.Messaging, System.Permissions,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Objects, FMX.Controls.Presentation, System.Actions, FMX.ActnList,
FMX.Edit, FMX.Media, ZXing.BarcodeFormat, ZXing.ReadResult, ZXing.ScanManager,
FMX.Platform, FMX.Layouts, FMX.StdActns, FMX.MediaLibrary.Actions,
FMX.ScrollBox, FMX.Memo, System.IOUtils, AudioManager;
type
TMainForm = class(TForm)
memLog: TMemo;
imgCamera: TImage;
ToolBar1: TToolBar;
butStart: TButton;
butStop: TButton;
StyleBook1: TStyleBook;
lblScanStatus: TLabel;
butShare: TButton;
ActionList1: TActionList;
ShowShareSheetAction1: TShowShareSheetAction;
Camera: TCameraComponent;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure butStartClick(Sender: TObject);
procedure butStopClick(Sender: TObject);
procedure ShowShareSheetAction1BeforeExecute(Sender: TObject);
procedure memLogChangeTracking(Sender: TObject);
procedure CameraSampleBufferReady(Sender: TObject; const ATime: TMediaTime);
private
{ Private declarations }
// for new Android security model
FPermissionCamera, FPermissionReadExternalStorage,
FPermissionWriteExternalStorage: string;
// audio (beep)
fAudioF: string;
fAudioM: TAudioManager;
// for the native zxing.delphi library
fScanManager: TScanManager;
fScanInProgress: Boolean;
fFrameTake: Integer;
procedure ParseBitmap;
function AppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean;
// for new Android security model
procedure DisplayRationale(Sender: TObject;
const APermissions: TArray<string>; const APostRationaleProc: TProc);
procedure TakePicturePermissionRequestResult(Sender: TObject;
const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
const
// Skip n frames to do a barcode scan
SCAN_EVERY_N_FRAME_FREQ: Integer = 2;
implementation
{$R *.fmx}
{$R *.NmXhdpiPh.fmx ANDROID}
uses System.Threading,
{$IFDEF ANDROID}
Androidapi.Helpers,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Os,
{$ENDIF}
FMX.DialogService;
procedure TMainForm.FormCreate(Sender: TObject);
var
AppEventSvc: IFMXApplicationEventService;
begin
if TPlatformServices.Current.SupportsPlatformService
(IFMXApplicationEventService, IInterface(AppEventSvc)) then
begin
AppEventSvc.SetApplicationEventHandler(AppEvent);
end;
fFrameTake := 0;
lblScanStatus.Text := '';
fScanManager := TScanManager.Create(TBarcodeFormat.Auto, nil);
fAudioM := TAudioManager.Create;
fAudioF := TPath.Combine(TPath.GetDocumentsPath, 'Ok.wav');
if FileExists(fAudioF) then
fAudioM.AddSound(fAudioF);
{$IFDEF ANDROID}
FPermissionCamera := JStringToString(TJManifest_permission.JavaClass.Camera);
FPermissionReadExternalStorage :=
JStringToString(TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE);
FPermissionWriteExternalStorage :=
JStringToString(TJManifest_permission.JavaClass.WRITE_EXTERNAL_STORAGE);
{$ENDIF}
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
fScanManager.Free;
fAudioM.Free;
end;
procedure TMainForm.TakePicturePermissionRequestResult(Sender: TObject;
const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
begin
// 3 permissions involved: CAMERA, READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE
if (length(AGrantResults) = 3) and
(AGrantResults[0] = TPermissionStatus.Granted) and
(AGrantResults[1] = TPermissionStatus.Granted) and
(AGrantResults[2] = TPermissionStatus.Granted) then
begin
// workaround for resolution changing when activating for second time
try
Camera.Active := False;
Camera.Quality := FMX.Media.TVideoCaptureQuality.LowQuality;
Camera.Active := True;
finally
Camera.Active := False;
Camera.Kind := FMX.Media.TCameraKind.BackCamera;
Camera.FocusMode := FMX.Media.TFocusMode.ContinuousAutoFocus;
Camera.Quality := FMX.Media.TVideoCaptureQuality.MediumQuality;
Camera.Active := True;
end;
lblScanStatus.Text := '';
memLog.Lines.Clear;
end
else
begin
TDialogService.ShowMessage
('Cannot take a photo because the required permissions are not all granted!');
end;
end;
procedure TMainForm.DisplayRationale(Sender: TObject;
const APermissions: TArray<string>; const APostRationaleProc: TProc);
var
I: Integer;
RationaleMsg: string;
begin
for I := 0 to High(APermissions) do
begin
if APermissions[I] = FPermissionCamera then
RationaleMsg := RationaleMsg +
'The app needs to access the camera to take a photo' + SLineBreak +
SLineBreak
else if APermissions[I] = FPermissionReadExternalStorage then
RationaleMsg := RationaleMsg +
'The app needs to read a photo file from your device';
end;
// Show an explanation to the user *asynchronously* - don't block this thread waiting for the user's response!
// After the user sees the explanation, invoke the post-rationale routine to request the permissions
TDialogService.ShowMessage(RationaleMsg,
procedure(const AResult: TModalResult)
begin
APostRationaleProc;
end)
end;
procedure TMainForm.butStartClick(Sender: TObject);
begin
PermissionsService.RequestPermissions
([FPermissionCamera, FPermissionReadExternalStorage,
FPermissionWriteExternalStorage], TakePicturePermissionRequestResult,
DisplayRationale);
end;
procedure TMainForm.butStopClick(Sender: TObject);
begin
Camera.Active := False;
end;
procedure TMainForm.CameraSampleBufferReady(Sender: TObject;
const ATime: TMediaTime);
begin
TThread.Synchronize(TThread.CurrentThread, ParseBitmap);
end;
procedure TMainForm.ParseBitmap;
var
ReadResult: TReadResult;
begin
ReadResult := nil;
Camera.SampleBufferToBitmap(imgCamera.Bitmap, True);
// already parsing...
if fScanInProgress then
exit;
// frame control...
Inc(fFrameTake);
if ((fFrameTake mod SCAN_EVERY_N_FRAME_FREQ) <> 0) then
begin
exit;
end;
TTask.Run(
procedure
begin
try
fScanInProgress := True;
try
ReadResult := fScanManager.Scan(imgCamera.Bitmap);
except
on E: Exception do
begin
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
lblScanStatus.Text := E.Message;
end);
exit;
end;
end;
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
if (length(lblScanStatus.Text) > 10) then
lblScanStatus.Text := '*'
else
lblScanStatus.Text := lblScanStatus.Text + '*';
if (ReadResult <> nil) then
begin
memLog.Lines.Add(FormatDateTime('hh:nn:ss', Now) + ' - ' +
ReadResult.Text);
memLog.GoToTextEnd;
fAudioM.PlaySound(0);
end;
end);
finally
ReadResult.Free;
fScanInProgress := False;
end;
end);
end;
function TMainForm.AppEvent(AAppEvent: TApplicationEvent;
AContext: TObject): Boolean;
begin
Result := True;
case AAppEvent of
TApplicationEvent.WillBecomeInactive:
Camera.Active := False;
TApplicationEvent.EnteredBackground:
Camera.Active := False;
TApplicationEvent.WillTerminate:
Camera.Active := False;
end;
end;
procedure TMainForm.memLogChangeTracking(Sender: TObject);
begin
ShowShareSheetAction1.Enabled := not memLog.Text.IsEmpty;
end;
procedure TMainForm.ShowShareSheetAction1BeforeExecute(Sender: TObject);
begin
ShowShareSheetAction1.TextMessage := memLog.Text;
end;
end.
|
unit UtilsBase;
interface
uses
Sysutils, Classes, Controls, Contnrs, Graphics, Windows, Messages,
DateUtils, StrUtils, RTLConsts, Math, db, Variants, Dialogs;
//compare simple and array variants
function VarEqual(v1, v2: Variant): Boolean;
//can check vararray (1 dim only)
//Return True, if all variants in array = Null
function VarIsNullEx(v: Variant): Boolean;
function VarIsAssigned(Value: Variant): Boolean;
function VarToInt(AVariant: variant; DefaultValue: Integer = 0): Integer;
function VarToFloat(AVariant: Variant; DefaultValue: Double = 0): Double;
function VarToStrExt(AVariant: Variant; DefaultValue: string = 'Null'): string;
function IsValidFloat(Value: string): Boolean;
function IsMaxDouble(Value: Double): Boolean;
function VarDateTimeToStr(Value: Variant): string;
procedure DoError(AMessage: string);
procedure ShowError(AMessage: string);
implementation
function VarEqual(v1, v2: Variant): Boolean;
var
l, h, i: Integer;
begin
Result := False;
if VarIsEmpty(v1) or VarIsEmpty(v2) then
Exit;
if VarIsArray(v1) then
begin
//comparing VarArray with Variant -> False
if not VarIsArray(v2) then
Exit;
l := VarArrayLowBound(v1, 1);
h := VarArrayHighBound(v1, 1);
Assert((l = VarArrayLowBound(v2, 1)) and (h = VarArrayHighBound(v2, 1)),
'VarEqual: Unequal variant''s bounds');
for i := l to h do
begin
Result := VarEqual(v1[i], v2[i]);
if not Result then
Exit;
end;
end
else
begin
Assert(not VarIsArray(v2), 'VarEqual: comparing Variant with VarArray');
Result := (v1 = v2) and (not (VarIsNull(v1) or VarIsNull(v2)));
end;
end;
function VarIsNullEx(v: Variant): Boolean;
var
i: Integer;
begin
if VarIsArray(v) then
begin
Result := False;
for i := VarArrayLowBound(v, 1) to VarArrayHighBound(v, 1) do
if not VarIsNull(v[i]) then
Exit;
Result := True;
end
else
Result := VarIsNull(v);
end;
function VarIsAssigned(Value: Variant): Boolean;
begin
Result := not(VarIsNull(Value) or VarIsEmpty(Value));
end;
function VarToInt(AVariant: Variant; DefaultValue: Integer = 0): Integer;
begin
If VarIsAssigned(AVariant) then
Result := AVariant
else
Result := DefaultValue;
end;
function VarToFloat(AVariant: Variant; DefaultValue: Double = 0): Double;
begin
if VarToStr(AVariant) = '' then
Result := DefaultValue
else
Result := AVariant;
end;
function VarToStrExt(AVariant: Variant; DefaultValue: string = 'Null'): string;
begin
If VarIsAssigned(AVariant) then
Result := AVariant
else
Result := DefaultValue;
end;
function IsValidFloat(Value: string): Boolean;
var
Dummy: Double;
begin
Result := TryStrToFloat(Value, Dummy);
end;
function IsMaxDouble(Value: Double): Boolean;
begin
Result := Value > (MaxDouble / 1.00000001); // 'cause MaxDouble <> MaxDouble
end;
procedure DoError(AMessage: string);
begin
raise Exception.Create(AMessage);
end;
procedure ShowError(AMessage: string);
begin
MessageDlg(AMessage, mtError, [mbOk], 0);
end;
function VarDateTimeToStr(Value: Variant): string;
begin
if VarIsAssigned(Value) then
Result := FormatDateTime('dd.mm.yyyy hh:nn:ss', Value)
else
Result := '';
end;
end.
|
unit _3dpoly;
{*******************************************************************}
{ _3dpoly : 3D Polygons drawing functions. }
{ Copyright (c) 1996 Yves Borckmans }
{*******************************************************************}
interface
uses _3d, {for TYPE definitions}
Classes, {for TStringList}
WinTypes, {for Win API drawing functions only, removed later}
WinProcs; {for Win API drawing functions only, removed later}
function POLY_Simple_VerticalFill(polygon : Integer) : Integer;
procedure POLY_ScanEdge(X1, Y1, X2, Y2, SetYStart, SkipFirst : Integer;
VAR EdgePointPtr : Integer);
procedure POLY_DrawVerticalLineList;
Type
TPOLY_Segment = class
YStart,
YEnd : Integer;
end;
var
POLY_FirstVX,
POLY_LastVX,
POLY_NumVX : Integer; { this will avoid passing parameters }
POLY_Segments : TStringList; { list of segments to draw }
POLY_XStart : Integer;
implementation
uses render; {for drawing purposes only}
procedure INDEX_FORWARD(VAR Index : Integer);
begin
Inc(Index);
if Index > POLY_LastVX then Index := POLY_FirstVX;
end;
procedure INDEX_BACKWARD(VAR Index : Integer);
begin
Dec(Index);
if Index < POLY_FirstVX then Index := POLY_LastVX;
end;
procedure INDEX_MOVE(VAR Index : Integer; Direction : Integer);
begin
if Direction > 0 then
begin
Inc(Index);
if Index > POLY_LastVX then Index := POLY_FirstVX;
end
else
begin
Dec(Index);
if Index < POLY_FirstVX then Index := POLY_LastVX;
end;
end;
{ This function is very much inspired by listing 21.1 in Michel Abrash's }
{ excellent _ZEN of Graphics Programming_ }
{ I just draw top => bottom instead of left => right for constant Z reasons }
{ Returns 1 = success }
{ 0 = nothing to do (degenerated polygons) }
function POLY_Simple_VerticalFill(polygon : Integer) : Integer;
var The3DPolygon : T3DPolygon; { The polygon }
The3DVertex : T3DVertex; { A vertex }
The3DVertex2 : T3DVertex; { A vertex }
i,j,k : Integer; { loop counters }
MinL, { bottommost left vertex }
MaxL, { topmost left vertex }
RightVx : Integer; { most right vertex }
MinX, { min X of scan range }
MaxX : Integer; { max X of scan range }
LeftIsFlat : Integer; { is leftmost part of polygon an edge ? }
{ 1 if so, 0 else (simple vertex) }
TopEdgeDir : Integer; { does the top edge run like the vertices }
{ array (1) or the contrary (-1) ? }
SkipFirst : Integer; { flag used to skip one line if necessary }
NextIndex, { an index to traverse the vertices list }
PrevIndex : Integer; { an index to traverse the vertices list }
CurrIndex : Integer; { an index to traverse the vertices list }
temp : Integer; { used in exchanging two variables }
EdgePointPtr : Integer; { "pointer" in the list of segments }
DeltaXN,
DeltaYN,
DeltaXP,
DeltaYP : Integer; { used to compute slopes }
AReal : Real;
begin
{Get the polygon from the polygon list}
The3DPolygon := T3DPolygon(PolyList.Objects[polygon]);
{not a polygon!}
if The3DPolygon.numvx < 3 then
begin
Result := 0;
exit;
end;
POLY_NumVX := The3DPolygon.numvx;
POLY_FirstVX := The3DPolygon.first;
POLY_LastVX := The3DPolygon.first + The3DPolygon.numvx - 1;
{first find our left and right scan range}
The3DVertex := T3DVertex(VertexList.Objects[POLY_FirstVX]);
MinL := POLY_FirstVX;
RightVx := POLY_FirstVX;
MinX := The3DVertex.u;
MaxX := The3DVertex.u;
for i := POLY_FirstVX + 1 to POLY_LastVX do
begin
The3DVertex := T3DVertex(VertexList.Objects[i]);
if The3DVertex.u < MinX then
begin
MinL := i;
MinX := The3DVertex.u;
end
else
if The3DVertex.u > MaxX then
begin
RightVx := i;
MaxX := The3DVertex.u;
end;
end;
{polygon has 0 width}
if MinX = MaxX then
begin
Result := 0;
exit;
end;
{so we now have range (MinX,MaxX),
with a left vertex in MinL and a right vertex in RightVx
May be more than one, so find the upper left, and upper right}
MaxL := MinL;
repeat
INDEX_BACKWARD(MinL);
The3DVertex := T3DVertex(VertexList.Objects[MinL]);
until The3DVertex.u <> MinX;
INDEX_FORWARD(MinL);
The3DVertex := T3DVertex(VertexList.Objects[MinL]);
repeat
INDEX_FORWARD(MaxL);
The3DVertex2 := T3DVertex(VertexList.Objects[MaxL]);
until The3DVertex2.u <> MinX;
INDEX_BACKWARD(MaxL);
The3DVertex2 := T3DVertex(VertexList.Objects[MaxL]);
if (The3DVertex.v <> The3DVertex2.v) then
LeftIsFlat := 1
else
LeftIsFlat := 0;
{now, find in which direction to travel the top and bottom edges
(upper left=>upper right and lower left=>lower right, respectively)
in the list of vertices}
{ assume top edge runs same direction as vertex array }
TopEdgeDir := 1;
if (LeftIsFlat = 1) then
begin
{just see which of MinL or MaxL is topmost}
if The3DVertex.v > The3DVertex2.v then
begin
{ it seems that we assumed wrong, so reverse... }
TopEdgeDir := -1;
temp := MinL;
MinL := MaxL;
MaxL := temp;
end;
end
else
begin
{ now, this is a bit more difficult, lets examine the next and
previous points using our assumption}
The3DVertex := T3DVertex(VertexList.Objects[MinL]);
PrevIndex := MinL;
INDEX_BACKWARD(PrevIndex);
The3DVertex2 := T3DVertex(VertexList.Objects[PrevIndex]);
DeltaXP := The3DVertex2.u - The3DVertex.u;
DeltaYP := The3DVertex2.v - The3DVertex.v;
The3DVertex := T3DVertex(VertexList.Objects[MaxL]);
NextIndex := MaxL;
INDEX_FORWARD(NextIndex);
The3DVertex2 := T3DVertex(VertexList.Objects[NextIndex]);
DeltaXN := The3DVertex2.u - The3DVertex.u;
DeltaYN := The3DVertex2.v - The3DVertex.v;
AReal := 1.0;
AReal := AReal * DeltaXN * DeltaYP - AReal * DeltaYN * DeltaXP;
{ if the actual slopes don't agree with what we assumed just reverse ! }
if AReal < 0 then
begin
TopEdgeDir := -1;
temp := MinL;
MinL := MaxL;
MaxL := temp;
end;
end;
{ polygon has zero drawable width }
if (MaxX - MinX - 1 + LeftIsFlat) <= 0 then
begin
Result := 0;
exit;
end;
{ On to creating the segments now }
POLY_Segments := TStringList.Create; {could perhaps use a TList instead}
POLY_XStart := MinX - 1 + LeftIsFlat;
EdgePointPtr := 0;
PrevIndex := MaxL;
CurrIndex := MaxL;
SkipFirst := 1 - LeftIsFlat;
{scan convert each line in the top edge from left to right}
repeat
INDEX_MOVE(CurrIndex, TopEdgeDir);
The3DVertex := T3DVertex(VertexList.Objects[PrevIndex]);
The3DVertex2 := T3DVertex(VertexList.Objects[CurrIndex]);
POLY_ScanEdge(The3DVertex.u, The3DVertex.v,
The3DVertex2.u, The3DVertex2.v,
0, SkipFirst, EdgePointPtr);
PrevIndex := CurrIndex;
SkipFirst := 0;
until CurrIndex = RightVx;
EdgePointPtr := 0;
PrevIndex := MinL;
CurrIndex := MinL;
SkipFirst := 1 - LeftIsFlat;
{scan convert each line in the bottom edge from left to right}
repeat
INDEX_MOVE(CurrIndex, -TopEdgeDir);
The3DVertex := T3DVertex(VertexList.Objects[PrevIndex]);
The3DVertex2 := T3DVertex(VertexList.Objects[CurrIndex]);
POLY_ScanEdge(The3DVertex.u, The3DVertex.v-1,
The3DVertex2.u, The3DVertex2.v-1,
1, SkipFirst, EdgePointPtr);
PrevIndex := CurrIndex;
SkipFirst := 0;
until CurrIndex = RightVx;
{ finally, draw the list of segments }
POLY_DrawVerticalLineList;
Result := 1;
end;
procedure POLY_ScanEdge(X1, Y1, X2, Y2, SetYStart, SkipFirst : Integer;
VAR EdgePointPtr : Integer);
var X, DeltaX, DeltaY : Integer;
InverseSlope : Real;
TempR : Real;
PolySeg : TPOLY_Segment;
begin
DeltaX := X2 - X1;
DeltaY := Y2 - Y1;
if DeltaX <= 0 then exit;
InverseSlope := DeltaY / DeltaX;
for x := X1 + SkipFirst to X2 - 1 do
begin
if SetYStart = 0 then
begin
PolySeg := TPOLY_Segment.Create;
TempR := (x-X1) * InverseSlope;
{ the Ceil function is mising in DELPHI, so improvise... }
if TempR < 0 then
PolySeg.YStart := Y1 + Trunc(TempR - 0.5)
else
PolySeg.YStart := Y1 + Trunc(TempR + 0.5);
POLY_Segments.AddObject('S', PolySeg);
end
else
begin
PolySeg := TPOLY_Segment(POLY_Segments.Objects[EdgePointPtr]);
TempR := (x-X1) * InverseSlope;
{ the Ceil function is mising in DELPHI, so improvise... }
if TempR < 0 then
PolySeg.YEnd := Y1 + Trunc(TempR - 0.5)
else
PolySeg.YEnd := Y1 + Trunc(TempR + 0.5);
Inc(EdgePointPtr);
end;
end;
end;
procedure POLY_DrawVerticalLineList;
var i,j : Integer;
PolySeg : TPOLY_Segment;
TheHandle : THandle;
begin
for i := 0 to POLY_Segments.Count - 1 do
begin
PolySeg := TPOLY_Segment(POLY_Segments.Objects[i]);
{ draw from (POLY_XStart, PolySeg.YStart) to (POLY_XStart, PolySeg.YEnd) }
{ using MoveTo LineTo generates gaps, because LineTo doesn't
draw the last pixel !!
Anyway, we need pixel by pixel for texture mapping, so it isn't
really a problem }
{
Renderer.MoveTo2(POLY_XStart + i, PolySeg.YStart);
Renderer.LineTo2(POLY_XStart + i, PolySeg.YEnd);
}
TheHandle := Renderer.RenderBox.Canvas.Handle;
for j := PolySeg.YStart to PolySeg.YEnd do
SetPixel(TheHandle,
RendererSettings.CenterX + POLY_XStart + i,
RendererSettings.CenterY - j,
$01000000);
end;
POLY_Segments.Free;
end;
end.
|
unit D2XXUnit;
{$MODE DELPHI}
interface
Type FT_Result = Integer;
// Device Info Node structure for info list functions
type FT_Device_Info_Node = record
Flags : DWord;
DeviceType : Dword;
ID : DWord;
LocID : DWord;
SerialNumber : array [0..15] of Char;
Description : array [0..63] of Char;
DeviceHandle : DWord;
end;
type TDWordptr = ^DWord;
// Structure to hold EEPROM data for FT_EE_Program function
TFT_Program_Data = record
Signature1 : DWord;
Signature2 : DWord;
Version : DWord;
VendorID : Word;
ProductID : Word;
Manufacturer : PChar;
ManufacturerID : PChar;
Description : PChar;
SerialNumber : PChar;
MaxPower : Word;
PnP : Word;
SelfPowered : Word;
RemoteWakeup : Word;
// Rev4 extensions
Rev4 : Byte;
IsoIn : Byte;
IsoOut : Byte;
PullDownEnable : Byte;
SerNumEnable : Byte;
USBVersionEnable : Byte;
USBVersion : Word;
// FT2232C extensions
Rev5 : Byte;
IsoInA : Byte;
IsoInB : Byte;
IsoOutA : Byte;
IsoOutB : Byte;
PullDownEnable5 : Byte;
SerNumEnable5 : Byte;
USBVersionEnable5 : Byte;
USBVersion5 : Word;
AIsHighCurrent : Byte;
BIsHighCurrent : Byte;
IFAIsFifo : Byte;
IFAIsFifoTar : Byte;
IFAIsFastSer : Byte;
AIsVCP : Byte;
IFBIsFifo : Byte;
IFBIsFifoTar : Byte;
IFBIsFastSer : Byte;
BIsVCP : Byte;
// FT232R extensions
UseExtOsc : Byte;
HighDriveIOs : Byte;
EndpointSize : Byte;
PullDownEnableR : Byte;
SerNumEnableR : Byte;
InvertTXD : Byte;
InvertRXD : Byte;
InvertRTS : Byte;
InvertCTS : Byte;
InvertDTR : Byte;
InvertDSR : Byte;
InvertDCD : Byte;
InvertRI : Byte;
Cbus0 : Byte;
Cbus1 : Byte;
Cbus2 : Byte;
Cbus3 : Byte;
Cbus4 : Byte;
RIsVCP : Byte;
end;
// Exported Functions
// Classic Functions
Function GetFTDeviceCount : FT_Result;
Function GetFTDeviceSerialNo(DeviceIndex:DWord) : FT_Result;
Function GetFTDeviceDescription(DeviceIndex:DWord) : FT_Result;
Function GetFTDeviceLocation(DeviceIndex:DWord) : FT_Result;
Function Open_USB_Device : FT_Result;
Function Open_USB_Device_By_Serial_Number(Serial_Number:string) : FT_Result;
Function Open_USB_Device_By_Device_Description(Device_Description:string) : FT_Result;
Function Open_USB_Device_By_Device_Location(Location:DWord) : FT_Result;
Function Close_USB_Device : FT_Result;
Function Read_USB_Device_Buffer(Read_Count:Integer) : Integer;
Function Write_USB_Device_Buffer(Write_Count:Integer) : Integer;
Function Reset_USB_Device : FT_Result;
Function Set_USB_Device_BaudRate : FT_Result;
Function Set_USB_Device_BaudRate_Divisor(Divisor:Dword) : FT_Result;
Function Set_USB_Device_DataCharacteristics : FT_Result;
Function Set_USB_Device_FlowControl : FT_Result;
Function Set_USB_Device_RTS : FT_Result;
Function Clr_USB_Device_RTS : FT_Result;
Function Set_USB_Device_DTR : FT_Result;
Function Clr_USB_Device_DTR : FT_Result;
Function Get_USB_Device_ModemStatus : FT_Result;
Function Set_USB_Device_Chars : FT_Result;
Function Purge_USB_Device_Out : FT_Result;
Function Purge_USB_Device_In : FT_Result;
Function Set_USB_Device_TimeOuts(ReadTimeOut,WriteTimeOut:DWord) : FT_Result;
Function Get_USB_Device_QueueStatus : FT_Result;
Function Set_USB_Device_Break_On : FT_Result;
Function Set_USB_Device_Break_Off : FT_Result;
Function Get_USB_Device_Status : FT_Result;
Function Set_USB_Device_Event_Notification(EventMask:DWord) : FT_Result;
Function USB_FT_GetDeviceInfo(DevType,ID:DWord; SerialNumber,Description:array of char) : FT_Result;
Function Set_USB_Device_Reset_Pipe_Retry_Count(RetryCount:DWord) : FT_Result;
Function Stop_USB_Device_InTask : FT_Result;
Function Restart_USB_Device_InTask : FT_Result;
Function Reset_USB_Port : FT_Result;
Function Cycle_USB_Port : FT_Result;
Function Create_USB_Device_List : FT_Result;
Function Get_USB_Device_List : FT_Result;
Function Get_USB_Device_List_Detail(Index:DWord) : FT_Result;
// EEPROM Functions
function USB_FT_EE_Read : FT_Result;
function USB_FT_C_EE_Read : FT_Result;
function USB_FT_R_EE_Read : FT_Result;
function USB_FT_EE_Program : FT_Result;
function USB_FT_ReadEE(WordAddr:Dword) : FT_Result;
function USB_FT_WriteEE(WordAddr:Dword;WordData:Word) : FT_Result;
function USB_FT_EraseEE : FT_Result;
function USB_FT_EE_UARead : FT_Result;
function USB_FT_EE_UAWrite : FT_Result;
function USB_FT_EE_UASize : FT_Result;
// FT2232C, FT232BM and FT245BM Extended API Functions
Function Get_USB_Device_LatencyTimer : FT_Result;
Function Set_USB_Device_LatencyTimer(Latency : Byte) : FT_Result;
Function Get_USB_Device_BitMode(var BitMode:Byte) : FT_Result;
Function Set_USB_Device_BitMode(Mask, Enable:Byte) : FT_Result;
Function Set_USB_Parameters(InSize, OutSize:Dword) : FT_Result;
Function Get_USB_Driver_Version(DrVersion : TDWordptr): FT_Result;
Function Get_USB_Library_Version(LbVersion : TDWordptr): FT_Result;
Var
// Port Handle Returned by the Open Function
// Used by the Subsequent Function Calls
FT_HANDLE : DWord = 0;
// Used to handle multiple device instances in future
// versions. Must be set to 0 for now.
// PV_Device : DWord = 0;
// Holding Variables for the current settings
// Can be configured visually using the CFGUnit Unit
// or manually before calling SetUp_USB_Device
FT_Current_Baud : Dword;
FT_Current_DataBits : Byte;
FT_Current_StopBits : Byte;
FT_Current_Parity : Byte;
FT_Current_FlowControl : Word;
FT_RTS_On : Boolean;
FT_DTR_On : Boolean;
FT_Event_On : Boolean;
FT_Error_On : Boolean;
FT_XON_Value : Byte = $11;
FT_XOFF_Value : Byte = $13;
FT_EVENT_Value : Byte = $0;
FT_ERROR_Value : Byte = $0;
// Used by CFGUnit to flag a bad value
FT_SetupError : Boolean;
// Used to Return the current Modem Status
FT_Modem_Status : DWord;
// Used to return the number of bytes pending
// in the Rx Buffer Queue
FT_Q_Bytes : DWord;
FT_TxQ_Bytes : DWord;
FT_Event_Status : DWord;
// Used to Enable / Disable the Error Report Dialog
FT_Enable_Error_Report : Boolean = True;
// Deposit for Get latency timer
FT_LatencyRd : Byte;
FT_DeviceInfoList : array of FT_Device_Info_Node;
Manufacturer: array [0..63] of char;
ManufacturerID: array [0..15] of char;
Description: array [0..63] of char;
SerialNumber: array [0..15] of char;
LocID : DWord;
EEDataBuffer : TFT_Program_Data;
UserData : array [0..63] of byte;
FT_UA_Size : integer;
WordRead : Word;
Const
// FT_Result Values
FT_OK = 0;
FT_INVALID_HANDLE = 1;
FT_DEVICE_NOT_FOUND = 2;
FT_DEVICE_NOT_OPENED = 3;
FT_IO_ERROR = 4;
FT_INSUFFICIENT_RESOURCES = 5;
FT_INVALID_PARAMETER = 6;
FT_SUCCESS = FT_OK;
FT_INVALID_BAUD_RATE = 7;
FT_DEVICE_NOT_OPENED_FOR_ERASE = 8;
FT_DEVICE_NOT_OPENED_FOR_WRITE = 9;
FT_FAILED_TO_WRITE_DEVICE = 10;
FT_EEPROM_READ_FAILED = 11;
FT_EEPROM_WRITE_FAILED = 12;
FT_EEPROM_ERASE_FAILED = 13;
FT_EEPROM_NOT_PRESENT = 14;
FT_EEPROM_NOT_PROGRAMMED = 15;
FT_INVALID_ARGS = 16;
FT_OTHER_ERROR = 17;
// FT_Open_Ex Flags
FT_OPEN_BY_SERIAL_NUMBER = 1;
FT_OPEN_BY_DESCRIPTION = 2;
FT_OPEN_BY_LOCATION = 4;
// FT_List_Devices Flags
FT_LIST_NUMBER_ONLY = $80000000;
FT_LIST_BY_INDEX = $40000000;
FT_LIST_ALL = $20000000;
// Baud Rate Selection
FT_BAUD_300 = 300;
FT_BAUD_600 = 600;
FT_BAUD_1200 = 1200;
FT_BAUD_2400 = 2400;
FT_BAUD_4800 = 4800;
FT_BAUD_9600 = 9600;
FT_BAUD_14400 = 14400;
FT_BAUD_19200 = 19200;
FT_BAUD_38400 = 38400;
FT_BAUD_57600 = 57600;
FT_BAUD_115200 = 115200;
FT_BAUD_230400 = 230400;
FT_BAUD_460800 = 460800;
FT_BAUD_921600 = 921600;
// Data Bits Selection
FT_DATA_BITS_7 = 7;
FT_DATA_BITS_8 = 8;
// Stop Bits Selection
FT_STOP_BITS_1 = 0;
FT_STOP_BITS_2 = 2;
// Parity Selection
FT_PARITY_NONE = 0;
FT_PARITY_ODD = 1;
FT_PARITY_EVEN = 2;
FT_PARITY_MARK = 3;
FT_PARITY_SPACE = 4;
// Flow Control Selection
FT_FLOW_NONE = $0000;
FT_FLOW_RTS_CTS = $0100;
FT_FLOW_DTR_DSR = $0200;
FT_FLOW_XON_XOFF = $0400;
// Purge Commands
FT_PURGE_RX = 1;
FT_PURGE_TX = 2;
// Notification Events
FT_EVENT_RXCHAR = 1;
FT_EVENT_MODEM_STATUS = 2;
// Modem Status
CTS = $10;
DSR = $20;
RI = $40;
DCD = $80;
// Bit Modes
FT_BITMODE_RESET = $00; //Reset
FT_BITMODE_ASYNC_BITBANG = $01; //Asynchronous Bit Bang
FT_BITMODE_MPSSE = $02; //MPSSE (FT2232, FT2232H, FT4232H and FT232H devices only)
FT_BITMODE_SYNC_BITBANG = $04; //Synchronous Bit Bang (FT232R, FT245R, FT2232, FT2232H, FT4232H and FT232H devices only)
FT_BITMODE_MCU_HOST = $08; //MCU Host Bus Emulation Mode (FT2232, FT2232H, FT4232H and FT232H devices only)
FT_BITMODE_FAST_SERIAL = $10; //Fast Opto-Isolated Serial Mode (FT2232, FT2232H, FT4232H and FT232H devices only)
FT_BITMODE_CBUS_BITBANG = $20; //CBUS Bit Bang Mode (FT232R and FT232H devices only)
FT_BITMODE_SYNC_FIFO = $40; //Single Channel Synchronous 245 FIFO Mode (FT2232H and FT232H devices only)
// IO Buffer Sizes
FT_In_Buffer_Size = $10000; // 64k
FT_In_Buffer_Index = FT_In_Buffer_Size - 1;
FT_Out_Buffer_Size = $10000; // 64k
FT_Out_Buffer_Index = FT_Out_Buffer_Size - 1;
// DLL Name
FT_DLL_Name = 'FTD2XX.DLL';
var
// Declare Input and Output Buffers
FT_In_Buffer : Array[0..FT_In_Buffer_Index] of Byte;
FT_Out_Buffer : Array[0..FT_Out_Buffer_Index] of Byte;
// A variable used to detect time-outs
// Attach a timer to the main project form
// which decrements this every 10mS if
// FT_TimeOut_Count <> 0
FT_TimeOut_Count : Integer = 0;
// Used to determine how many bytes were
// actually received by FT_Read_Device_All
// in the case of a time-out
FT_All_Bytes_Received : Integer = 0;
FT_IO_Status : Ft_Result = FT_OK;
// Used By FT_ListDevices
FT_Device_Count : DWord;
FT_Device_String_Buffer : array [1..50] of Char;
FT_Device_String : String;
FT_Device_Location : DWord;
USB_Device_Info_Node : FT_Device_Info_Node;
FT_Event_Handle : DWord;
implementation
uses main;
//Classic functions
function FT_GetNumDevices(pvArg1:Pointer; pvArg2:Pointer; dwFlags:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_ListDevices';
function FT_ListDevices(pvArg1:Dword; pvArg2:Pointer; dwFlags:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_ListDevices';
function FT_Open(Index:Integer; ftHandle:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_Open';
function FT_OpenEx(pvArg1:Pointer; dwFlags:Dword; ftHandle:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_OpenEx';
function FT_OpenByLocation(pvArg1:DWord; dwFlags:Dword; ftHandle:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_OpenEx';
function FT_Close(ftHandle:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_Close';
function FT_Read(ftHandle:Dword; FTInBuf:Pointer; BufferSize:LongInt; ResultPtr:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_Read';
function FT_Write(ftHandle:Dword; FTOutBuf:Pointer; BufferSize:LongInt; ResultPtr:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_Write';
function FT_ResetDevice(ftHandle:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_ResetDevice';
function FT_SetBaudRate(ftHandle:Dword; BaudRate:DWord):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetBaudRate';
function FT_SetDivisor(ftHandle:Dword; Divisor:DWord):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetDivisor';
function FT_SetDataCharacteristics(ftHandle:Dword; WordLength,StopBits,Parity:Byte):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetDataCharacteristics';
function FT_SetFlowControl(ftHandle:Dword; FlowControl:Word; XonChar,XoffChar:Byte):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetFlowControl';
function FT_SetDtr(ftHandle:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetDtr';
function FT_ClrDtr(ftHandle:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_ClrDtr';
function FT_SetRts(ftHandle:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetRts';
function FT_ClrRts(ftHandle:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_ClrRts';
function FT_GetModemStatus(ftHandle:Dword; ModemStatus:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetModemStatus';
function FT_SetChars(ftHandle:Dword; EventChar,EventCharEnabled,ErrorChar,ErrorCharEnabled:Byte):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetChars';
function FT_Purge(ftHandle:Dword; Mask:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_Purge';
function FT_SetTimeouts(ftHandle:Dword; ReadTimeout,WriteTimeout:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetTimeouts';
function FT_GetQueueStatus(ftHandle:Dword; RxBytes:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetQueueStatus';
function FT_SetBreakOn(ftHandle:Dword) : FT_Result; stdcall; External FT_DLL_Name name 'FT_SetBreakOn';
function FT_SetBreakOff(ftHandle:Dword) : FT_Result; stdcall; External FT_DLL_Name name 'FT_SetBreakOff';
function FT_GetStatus(ftHandle:DWord; RxBytes,TxBytes,EventStatus:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetStatus';
function FT_SetEventNotification(ftHandle:DWord; EventMask:DWord; pvArgs:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetEventNotification';
function FT_GetDeviceInfo(ftHandle:DWord; DevType,ID,SerNum,Desc,pvDummy:Pointer) : FT_Result; stdcall; External FT_DLL_Name name 'FT_GetDeviceInfo';
function FT_SetResetPipeRetryCount(ftHandle:Dword; RetryCount:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetResetPipeRetryCount';
function FT_StopInTask(ftHandle:Dword) : FT_Result; stdcall; External FT_DLL_Name name 'FT_StopInTask';
function FT_RestartInTask(ftHandle:Dword) : FT_Result; stdcall; External FT_DLL_Name name 'FT_RestartInTask';
function FT_ResetPort(ftHandle:Dword) : FT_Result; stdcall; External FT_DLL_Name name 'FT_ResetPort';
function FT_CyclePort(ftHandle:Dword) : FT_Result; stdcall; External 'FTD2XX.DLL' name 'FT_CyclePort';
function FT_CreateDeviceInfoList(NumDevs:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_CreateDeviceInfoList';
function FT_GetDeviceInfoList(pFT_Device_Info_List:Pointer; NumDevs:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetDeviceInfoList';
function FT_GetDeviceInfoDetail(Index:DWord; Flags,DevType,ID,LocID,SerialNumber,Description,DevHandle:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetDeviceInfoDetail';
function FT_GetDriverVersion(ftHandle:Dword; DrVersion:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetDriverVersion';
function FT_GetLibraryVersion(LbVersion:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetLibraryVersion';
// EEPROM functions
function FT_EE_Read(ftHandle:DWord; pEEData:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_EE_Read';
function FT_EE_Program(ftHandle:DWord; pEEData:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_EE_Program';
// EEPROM primitives - you need an NDA for EEPROM checksum
function FT_ReadEE(ftHandle:DWord; WordAddr:DWord; WordRead:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_ReadEE';
function FT_WriteEE(ftHandle:DWord; WordAddr:DWord; WordData:word):FT_Result; stdcall; External FT_DLL_Name name 'FT_WriteEE';
function FT_EraseEE(ftHandle:DWord):FT_Result; stdcall; External FT_DLL_Name name 'FT_EraseEE';
function FT_EE_UARead(ftHandle:DWord; Data:Pointer; DataLen:DWord; BytesRead:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_EE_UARead';
function FT_EE_UAWrite(ftHandle:DWord; Data:Pointer; DataLen:DWord):FT_Result; stdcall; External FT_DLL_Name name 'FT_EE_UAWrite';
function FT_EE_UASize(ftHandle:DWord; UASize:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_EE_UASize';
// FT2232C, FT232BM and FT245BM Extended API Functions
function FT_GetLatencyTimer(ftHandle:Dword; Latency:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetLatencyTimer';
function FT_SetLatencyTimer(ftHandle:Dword; Latency:Byte):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetLatencyTimer';
function FT_GetBitMode(ftHandle:Dword; BitMode:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetBitMode';
function FT_SetBitMode(ftHandle:Dword; Mask,Enable:Byte):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetBitMode';
function FT_SetUSBParameters(ftHandle:Dword; InSize,OutSize:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetUSBParameters';
Procedure FT_Error_Report(ErrStr: String; PortStatus : Integer);
Var Str : String;
Begin
If Not FT_Enable_Error_Report then Exit;
If PortStatus = FT_OK then Exit;
Case PortStatus of
FT_INVALID_HANDLE : Str := ErrStr+' - Invalid handle...';
FT_DEVICE_NOT_FOUND : Str := ErrStr+' - Device not found...';
FT_DEVICE_NOT_OPENED : Str := ErrStr+' - Device not opened...';
FT_IO_ERROR : Str := ErrStr+' - General IO error...';
FT_INSUFFICIENT_RESOURCES : Str := ErrStr+' - Insufficient resources...';
FT_INVALID_PARAMETER : Str := ErrStr+' - Invalid parameter...';
FT_INVALID_BAUD_RATE : Str := ErrStr+' - Invalid baud rate...';
FT_DEVICE_NOT_OPENED_FOR_ERASE : Str := ErrStr+' Device not opened for erase...';
FT_DEVICE_NOT_OPENED_FOR_WRITE : Str := ErrStr+' Device not opened for write...';
FT_FAILED_TO_WRITE_DEVICE : Str := ErrStr+' - Failed to write...';
FT_EEPROM_READ_FAILED : Str := ErrStr+' - EEPROM read failed...';
FT_EEPROM_WRITE_FAILED : Str := ErrStr+' - EEPROM write failed...';
FT_EEPROM_ERASE_FAILED : Str := ErrStr+' - EEPROM erase failed...';
FT_EEPROM_NOT_PRESENT : Str := ErrStr+' - EEPROM not present...';
FT_EEPROM_NOT_PROGRAMMED : Str := ErrStr+' - EEPROM not programmed...';
FT_INVALID_ARGS : Str := ErrStr+' - Invalid arguments...';
FT_OTHER_ERROR : Str := ErrStr+' - Other error ...';
End;
LogPrint(Str);
End;
Function GetDeviceString : String;
Var I : Integer;
Begin
Result := ''; I := 1;
FT_Device_String_Buffer[50] := Chr(0); // Just in case !
While FT_Device_String_Buffer[I] <> Chr(0) do
Begin
Result := Result + FT_Device_String_Buffer[I];
Inc(I);
End;
End;
Procedure SetDeviceString ( S : String );
Var I,L : Integer;
Begin
FT_Device_String_Buffer[1] := Chr(0);
L := Length(S); If L > 49 then L := 49;
If L = 0 then Exit;
For I := 1 to L do FT_Device_String_Buffer[I] := S[I];
FT_Device_String_Buffer[L+1] := Chr(0);
End;
// FTD2XX functions from here
Function GetFTDeviceCount : FT_Result;
Begin
Result := FT_GetNumDevices(@FT_Device_Count,Nil,FT_LIST_NUMBER_ONLY);
If Result <> FT_OK then FT_Error_Report('GetFTDeviceCount',Result);
End;
Function GetFTDeviceSerialNo(DeviceIndex:DWord) : FT_Result;
Begin
Result := FT_ListDevices(DeviceIndex,@SerialNumber,(FT_OPEN_BY_SERIAL_NUMBER or FT_LIST_BY_INDEX));
If Result = FT_OK then FT_Device_String := SerialNumber;
If Result <> FT_OK then FT_Error_Report('GetFTDeviceSerialNo',Result);
End;
Function GetFTDeviceDescription(DeviceIndex:DWord) : FT_Result;
Begin
Result := FT_ListDevices(DeviceIndex,@Description,(FT_OPEN_BY_DESCRIPTION or FT_LIST_BY_INDEX));
If Result = FT_OK then FT_Device_String := Description;
If Result <> FT_OK then FT_Error_Report('GetFTDeviceDescription',Result);
End;
Function GetFTDeviceLocation(DeviceIndex:DWord) : FT_Result;
Begin
Result := FT_ListDevices(DeviceIndex,@LocID,(FT_OPEN_BY_LOCATION or FT_LIST_BY_INDEX));
If Result = FT_OK then FT_Device_Location := LocID;
If Result <> FT_OK then FT_Error_Report('GetFTDeviceLocation',Result);
End;
Function Open_USB_Device : FT_Result;
Var
DevIndex : DWord;
Begin
DevIndex := 0;
Result := FT_Open(DevIndex,@FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_Open',Result);
End;
Function Open_USB_Device_By_Serial_Number(Serial_Number:string) : FT_Result;
Begin
SetDeviceString(Serial_Number);
Result := FT_OpenEx(@FT_Device_String_Buffer,FT_OPEN_BY_SERIAL_NUMBER,@FT_Handle);
If Result <> FT_OK then FT_Error_Report('Open_USB_Device_By_Serial_Number',Result);
End;
Function Open_USB_Device_By_Device_Description(Device_Description:string) : FT_Result;
Begin
SetDeviceString(Device_Description);
Result := FT_OpenEx(@FT_Device_String_Buffer,FT_OPEN_BY_DESCRIPTION,@FT_Handle);
If Result <> FT_OK then FT_Error_Report('Open_USB_Device_By_Device_Description',Result);
End;
Function Open_USB_Device_By_Device_Location(Location:DWord) : FT_Result;
Begin
Result := FT_OpenByLocation(Location,FT_OPEN_BY_LOCATION,@FT_Handle);
If Result <> FT_OK then FT_Error_Report('Open_USB_Device_By_Device_Location',Result);
End;
Function Close_USB_Device : FT_Result;
Begin
Result := FT_Close(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_Close',Result);
End;
function Read_USB_Device_Buffer( Read_Count : Integer ) : Integer;
// Reads Read_Count Bytes (or less) from the USB device to the FT_In_Buffer
// Function returns the number of bytes actually received which may range from zero
// to the actual number of bytes requested, depending on how many have been received
// at the time of the request + the read timeout value.
Var Read_Result : Integer;
Begin
if (read_count = 1) then
begin
read_result := read_count;
end;
FT_IO_Status := FT_Read(FT_Handle,@FT_In_Buffer,Read_Count,@Read_Result);
If FT_IO_Status <> FT_OK then FT_Error_Report('FT_Read',FT_IO_Status);
Result := Read_Result;
End;
function Write_USB_Device_Buffer( Write_Count : Integer ) : Integer;
// Writes Write_Count Bytes from FT_Out_Buffer to the USB device
// Function returns the number of bytes actually sent
// In this example, Write_Count should be 32k bytes max
Var Write_Result : Integer;
Begin
FT_IO_Status := FT_Write(FT_Handle,@FT_Out_Buffer,Write_Count,@Write_Result);
If FT_IO_Status <> FT_OK then FT_Error_Report('FT_Write',FT_IO_Status);
Result := Write_Result;
End;
Function Reset_USB_Device : FT_Result;
Begin
Result := FT_ResetDevice(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_ResetDevice',Result);
End;
Function Set_USB_Device_BaudRate : FT_Result;
Begin
Result := FT_SetBaudRate(FT_Handle,FT_Current_Baud);
If Result <> FT_OK then FT_Error_Report('FT_SetBaudRate',Result);
End;
Function Set_USB_Device_BaudRate_Divisor(Divisor:Dword) : FT_Result;
Begin
Result := FT_SetDivisor(FT_Handle,Divisor);
If Result <> FT_OK then FT_Error_Report('FT_SetDivisor',Result);
End;
Function Set_USB_Device_DataCharacteristics : FT_Result;
Begin
Result := FT_SetDataCharacteristics(FT_Handle,FT_Current_DataBits,FT_Current_StopBits,FT_Current_Parity);
If Result <> FT_OK then FT_Error_Report('FT_SetDataCharacteristics',Result);
End;
Function Set_USB_Device_FlowControl : FT_Result;
Begin
Result := FT_SetFlowControl(FT_Handle,FT_Current_FlowControl,FT_XON_Value,FT_XOFF_Value);
If Result <> FT_OK then FT_Error_Report('FT_SetFlowControl',Result);
End;
Function Set_USB_Device_RTS : FT_Result;
Begin
Result := FT_SetRTS(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_SetRTS',Result);
End;
Function Clr_USB_Device_RTS : FT_Result;
Begin
Result := FT_ClrRTS(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_ClrRTS',Result);
End;
Function Set_USB_Device_DTR : FT_Result;
Begin
Result := FT_SetDTR(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_SetDTR',Result);
End;
Function Clr_USB_Device_DTR : FT_Result;
Begin
Result := FT_ClrDTR(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_ClrDTR',Result);
End;
Function Get_USB_Device_ModemStatus : FT_Result;
Begin
Result := FT_GetModemStatus(FT_Handle,@FT_Modem_Status);
If Result <> FT_OK then FT_Error_Report('FT_GetModemStatus',Result);
End;
Function Set_USB_Device_Chars : FT_Result;
Var Events_On,Errors_On : Byte;
Begin
If FT_Event_On then Events_On := 1 else Events_On := 0;
If FT_Error_On then Errors_On := 1 else Errors_On := 0;
Result := FT_SetChars(FT_Handle,FT_EVENT_Value,Events_On,FT_ERROR_Value,Errors_On);
If Result <> FT_OK then FT_Error_Report('FT_SetChars',Result);
End;
Function Purge_USB_Device_Out : FT_Result;
Begin
Result := FT_Purge(FT_Handle,FT_PURGE_RX);
If Result <> FT_OK then FT_Error_Report('FT_Purge RX',Result);
End;
Function Purge_USB_Device_In : FT_Result;
Begin
Result := FT_Purge(FT_Handle,FT_PURGE_TX);
If Result <> FT_OK then FT_Error_Report('FT_Purge TX',Result);
End;
Function Set_USB_Device_TimeOuts(ReadTimeOut,WriteTimeOut:DWord) : FT_Result;
Begin
Result := FT_SetTimeouts(FT_Handle,ReadTimeout,WriteTimeout);
If Result <> FT_OK then FT_Error_Report('FT_SetTimeouts',Result);
End;
Function Get_USB_Device_QueueStatus : FT_Result;
Begin
Result := FT_GetQueueStatus(FT_Handle,@FT_Q_Bytes);
If Result <> FT_OK then FT_Error_Report('FT_GetQueueStatus',Result);
End;
Function Set_USB_Device_Break_On : FT_Result;
Begin
Result := FT_SetBreakOn(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_SetBreakOn',Result);
End;
Function Set_USB_Device_Break_Off : FT_Result;
Begin
Result := FT_SetBreakOff(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_SetBreakOff',Result);
End;
Function Get_USB_Device_Status : FT_Result;
Begin
Result := FT_GetStatus(FT_Handle, @FT_Q_Bytes, @FT_TxQ_Bytes, @FT_Event_Status);
If Result <> FT_OK then FT_Error_Report('FT_GetStatus',Result);
End;
Function Set_USB_Device_Event_Notification(EventMask:DWord) : FT_Result;
Begin
Result := FT_SetEventNotification(FT_Handle,EventMask,FT_Event_Handle);
If Result <> FT_OK then FT_Error_Report('FT_SetEventNotification ',Result);
End;
Function USB_FT_GetDeviceInfo(DevType,ID:DWord; SerialNumber,Description:array of char) : FT_Result;
begin
Result := FT_GetDeviceInfo(FT_Handle,@DevType,@ID,@SerialNumber,@Description,Nil);
If Result <> FT_OK then FT_Error_Report('FT_GetDeviceInfo ',Result);
end;
Function Set_USB_Device_Reset_Pipe_Retry_Count(RetryCount:DWord) : FT_Result;
Begin
Result := FT_SetResetPiperetryCount(FT_Handle, RetryCount);
If Result <> FT_OK then FT_Error_Report('FT_SetResetPipeRetryCount',Result);
End;
Function Stop_USB_Device_InTask : FT_Result;
Begin
Result := FT_StopInTask(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_StopInTask',Result);
End;
Function Restart_USB_Device_InTask : FT_Result;
Begin
Result := FT_RestartInTask(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_RestartInTask',Result);
End;
Function Reset_USB_Port : FT_Result;
Begin
Result := FT_ResetPort(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_ResetPort',Result);
End;
Function Cycle_USB_Port : FT_Result;
Begin
Result := FT_CyclePort(FT_Handle);
If Result <> FT_OK then FT_Error_Report('FT_CyclePort',Result);
End;
Function Create_USB_Device_List : FT_Result;
Begin
Result := FT_CreateDeviceInfoList(@FT_Device_Count);
If Result <> FT_OK then FT_Error_Report('FT_CreateDeviceInfoList',Result);
End;
Function Get_USB_Device_List : FT_Result;
Begin
SetLength(FT_DeviceInfoList,FT_Device_Count);
Result := FT_GetDeviceInfoList(FT_DeviceInfoList, @FT_Device_Count);
If Result <> FT_OK then FT_Error_Report('FT_GetDeviceInfoList',Result);
End;
Function Get_USB_Driver_Version(DrVersion : TDWordPtr) : FT_Result;
Begin
Result := FT_GetDriverVersion(FT_Handle, DrVersion);
If Result <> FT_OK then FT_Error_Report('FT_GetDriverVersion',Result);
End;
Function Get_USB_Library_Version(LbVersion : TDWordPtr) : FT_Result;
Begin
Result := FT_GetLibraryVersion(LbVersion);
If Result <> FT_OK then FT_Error_Report('FT_GetLibraryVersion',Result);
End;
Function Get_USB_Device_List_Detail(Index:DWord) : FT_Result;
Begin
// Initialise structure
USB_Device_Info_Node.Flags := 0;
USB_Device_Info_Node.DeviceType := 0;
USB_Device_Info_Node.ID := 0;
USB_Device_Info_Node.LocID := 0;
USB_Device_Info_Node.SerialNumber := '';
USB_Device_Info_Node.Description := '';
USB_Device_Info_Node.DeviceHandle := 0;
Result := FT_GetDeviceInfoDetail(Index,@USB_Device_Info_Node.Flags,@USB_Device_Info_Node.DeviceType,
@USB_Device_Info_Node.ID,@USB_Device_Info_Node.LocID,@USB_Device_Info_Node.SerialNumber,
@USB_Device_Info_Node.Description,@USB_Device_Info_Node.DeviceHandle);
If Result <> FT_OK then FT_Error_Report('FT_GetDeviceInfoListDetail',Result);
End;
function USB_FT_EE_Read : FT_Result;
// Read BM/AM device EEPROM
begin
EEDataBuffer.Signature1 := 0;
EEDataBuffer.Signature2 := $FFFFFFFF;
EEDataBuffer.Version := 0; // 0 for AM/BM, 1 for C, 2 for R
EEDataBuffer.VendorId :=0;
EEDataBuffer.ProductId := 0;
EEDataBuffer.Manufacturer := @Manufacturer;
EEDataBuffer.ManufacturerId := @ManufacturerId;
EEDataBuffer.Description := @Description;
EEDataBuffer.SerialNumber := @SerialNumber;
EEDataBuffer.MaxPower := 0;
EEDataBuffer.PnP := 0;
EEDataBuffer.SelfPowered := 0;
EEDataBuffer.RemoteWakeup := 0;
EEDataBuffer.Rev4 := 0;
EEDataBuffer.IsoIn := 0;
EEDataBuffer.IsoOut := 0;
EEDataBuffer.PullDownEnable := 0;
EEDataBuffer.SerNumEnable := 0;
EEDataBuffer.USBVersionEnable := 0;
EEDataBuffer.USBVersion := 0;
// FT2232C Extensions
EEDataBuffer.Rev5 := 0;
EEDataBuffer.IsoInA := 0;
EEDataBuffer.IsoInB := 0;
EEDataBuffer.IsoOutA := 0;
EEDataBuffer.IsoOutB := 0;
EEDataBuffer.PullDownEnable5 := 0;
EEDataBuffer.SerNumEnable5 := 0;
EEDataBuffer.USBVersionEnable5 := 0;
EEDataBuffer.USBVersion5 := 0;
EEDataBuffer.AIsHighCurrent := 0;
EEDataBuffer.BIsHighCurrent := 0;
EEDataBuffer.IFAIsFifo := 0;
EEDataBuffer.IFAIsFifoTar := 0;
EEDataBuffer.IFAIsFastSer := 0;
EEDataBuffer.AIsVCP := 0;
EEDataBuffer.IFBIsFifo := 0;
EEDataBuffer.IFBIsFifoTar := 0;
EEDataBuffer.IFBIsFastSer := 0;
EEDataBuffer.BIsVCP := 0;
// FT232R extensions
EEDataBuffer.UseExtOsc := 0;
EEDataBuffer.HighDriveIOs := 0;
EEDataBuffer.EndpointSize := 0;
EEDataBuffer.PullDownEnableR := 0;
EEDataBuffer.SerNumEnableR := 0;
EEDataBuffer.InvertTXD := 0;
EEDataBuffer.InvertRXD := 0;
EEDataBuffer.InvertRTS := 0;
EEDataBuffer.InvertCTS := 0;
EEDataBuffer.InvertDTR := 0;
EEDataBuffer.InvertDSR := 0;
EEDataBuffer.InvertDCD := 0;
EEDataBuffer.InvertRI := 0;
EEDataBuffer.Cbus0 := 0;
EEDataBuffer.Cbus1 := 0;
EEDataBuffer.Cbus2 := 0;
EEDataBuffer.Cbus3 := 0;
EEDataBuffer.Cbus4 := 0;
EEDataBuffer.RIsVCP := 0;
Result := FT_EE_Read(FT_Handle,@EEDataBuffer);
If Result <> FT_OK then FT_Error_Report('FT_EE_Read ',Result);
end;
function USB_FT_C_EE_Read : FT_Result;
// Read FT2232C device EEPROM
begin
EEDataBuffer.Signature1 := 0;
EEDataBuffer.Signature2 := $FFFFFFFF;
EEDataBuffer.Version := 1; // 0 for AM/BM, 1 for C, 2 for R
EEDataBuffer.VendorId :=0;
EEDataBuffer.ProductId := 0;
EEDataBuffer.Manufacturer := @Manufacturer;
EEDataBuffer.ManufacturerId := @ManufacturerId;
EEDataBuffer.Description := @Description;
EEDataBuffer.SerialNumber := @SerialNumber;
EEDataBuffer.MaxPower := 0;
EEDataBuffer.PnP := 0;
EEDataBuffer.SelfPowered := 0;
EEDataBuffer.RemoteWakeup := 0;
EEDataBuffer.Rev4 := 0;
EEDataBuffer.IsoIn := 0;
EEDataBuffer.IsoOut := 0;
EEDataBuffer.PullDownEnable := 0;
EEDataBuffer.SerNumEnable := 0;
EEDataBuffer.USBVersionEnable := 0;
EEDataBuffer.USBVersion := 0;
// FT2232C Extensions
EEDataBuffer.Rev5 := 0;
EEDataBuffer.IsoInA := 0;
EEDataBuffer.IsoInB := 0;
EEDataBuffer.IsoOutA := 0;
EEDataBuffer.IsoOutB := 0;
EEDataBuffer.PullDownEnable5 := 0;
EEDataBuffer.SerNumEnable5 := 0;
EEDataBuffer.USBVersionEnable5 := 0;
EEDataBuffer.USBVersion5 := 0;
EEDataBuffer.AIsHighCurrent := 0;
EEDataBuffer.BIsHighCurrent := 0;
EEDataBuffer.IFAIsFifo := 0;
EEDataBuffer.IFAIsFifoTar := 0;
EEDataBuffer.IFAIsFastSer := 0;
EEDataBuffer.AIsVCP := 0;
EEDataBuffer.IFBIsFifo := 0;
EEDataBuffer.IFBIsFifoTar := 0;
EEDataBuffer.IFBIsFastSer := 0;
EEDataBuffer.BIsVCP := 0;
// FT232R extensions
EEDataBuffer.UseExtOsc := 0;
EEDataBuffer.HighDriveIOs := 0;
EEDataBuffer.EndpointSize := 0;
EEDataBuffer.PullDownEnableR := 0;
EEDataBuffer.SerNumEnableR := 0;
EEDataBuffer.InvertTXD := 0;
EEDataBuffer.InvertRXD := 0;
EEDataBuffer.InvertRTS := 0;
EEDataBuffer.InvertCTS := 0;
EEDataBuffer.InvertDTR := 0;
EEDataBuffer.InvertDSR := 0;
EEDataBuffer.InvertDCD := 0;
EEDataBuffer.InvertRI := 0;
EEDataBuffer.Cbus0 := 0;
EEDataBuffer.Cbus1 := 0;
EEDataBuffer.Cbus2 := 0;
EEDataBuffer.Cbus3 := 0;
EEDataBuffer.Cbus4 := 0;
EEDataBuffer.RIsVCP := 0;
Result := FT_EE_Read(FT_Handle,@EEDataBuffer);
If Result <> FT_OK then FT_Error_Report('FT_EE_Read ',Result);
end;
function USB_FT_R_EE_Read : FT_Result;
// Read FT232R device EEPROM
begin
EEDataBuffer.Signature1 := 0;
EEDataBuffer.Signature2 := $FFFFFFFF;
EEDataBuffer.Version := 2; // 0 for AM/BM, 1 for C, 2 for R
EEDataBuffer.VendorId :=0;
EEDataBuffer.ProductId := 0;
EEDataBuffer.Manufacturer := @Manufacturer;
EEDataBuffer.ManufacturerId := @ManufacturerId;
EEDataBuffer.Description := @Description;
EEDataBuffer.SerialNumber := @SerialNumber;
EEDataBuffer.MaxPower := 0;
EEDataBuffer.PnP := 0;
EEDataBuffer.SelfPowered := 0;
EEDataBuffer.RemoteWakeup := 0;
EEDataBuffer.Rev4 := 0;
EEDataBuffer.IsoIn := 0;
EEDataBuffer.IsoOut := 0;
EEDataBuffer.PullDownEnable := 0;
EEDataBuffer.SerNumEnable := 0;
EEDataBuffer.USBVersionEnable := 0;
EEDataBuffer.USBVersion := 0;
// FT2232C Extensions
EEDataBuffer.Rev5 := 0;
EEDataBuffer.IsoInA := 0;
EEDataBuffer.IsoInB := 0;
EEDataBuffer.IsoOutA := 0;
EEDataBuffer.IsoOutB := 0;
EEDataBuffer.PullDownEnable5 := 0;
EEDataBuffer.SerNumEnable5 := 0;
EEDataBuffer.USBVersionEnable5 := 0;
EEDataBuffer.USBVersion5 := 0;
EEDataBuffer.AIsHighCurrent := 0;
EEDataBuffer.BIsHighCurrent := 0;
EEDataBuffer.IFAIsFifo := 0;
EEDataBuffer.IFAIsFifoTar := 0;
EEDataBuffer.IFAIsFastSer := 0;
EEDataBuffer.AIsVCP := 0;
EEDataBuffer.IFBIsFifo := 0;
EEDataBuffer.IFBIsFifoTar := 0;
EEDataBuffer.IFBIsFastSer := 0;
EEDataBuffer.BIsVCP := 0;
// FT232R extensions
EEDataBuffer.UseExtOsc := 0;
EEDataBuffer.HighDriveIOs := 0;
EEDataBuffer.EndpointSize := 0;
EEDataBuffer.PullDownEnableR := 0;
EEDataBuffer.SerNumEnableR := 0;
EEDataBuffer.InvertTXD := 0;
EEDataBuffer.InvertRXD := 0;
EEDataBuffer.InvertRTS := 0;
EEDataBuffer.InvertCTS := 0;
EEDataBuffer.InvertDTR := 0;
EEDataBuffer.InvertDSR := 0;
EEDataBuffer.InvertDCD := 0;
EEDataBuffer.InvertRI := 0;
EEDataBuffer.Cbus0 := 0;
EEDataBuffer.Cbus1 := 0;
EEDataBuffer.Cbus2 := 0;
EEDataBuffer.Cbus3 := 0;
EEDataBuffer.Cbus4 := 0;
EEDataBuffer.RIsVCP := 0;
Result := FT_EE_Read(FT_Handle,@EEDataBuffer);
If Result <> FT_OK then FT_Error_Report('FT_EE_Read ',Result);
end;
function USB_FT_EE_Program : FT_Result;
begin
Result := FT_EE_Program(FT_Handle, @EEDataBuffer);
If Result <> FT_OK then FT_Error_Report('FT_EE_Read ',Result);
end;
function USB_FT_WriteEE(WordAddr:Dword; WordData:Word) : FT_Result;
begin
Result := FT_WriteEE(FT_Handle,WordAddr,WordData);
end;
function USB_FT_ReadEE(WordAddr:Dword) : FT_Result;
begin
Result := FT_ReadEE(FT_Handle,WordAddr,@WordRead);
end;
function USB_FT_EraseEE : FT_Result;
begin
Result := FT_EraseEE(FT_Handle);
end;
function USB_FT_EE_UARead : FT_Result;
begin
Result := FT_EE_UARead(FT_Handle,@UserData,64,@FT_UA_Size);
If Result <> FT_OK then FT_Error_Report('FT_EE_UARead ',Result);
end;
function USB_FT_EE_UAWrite : FT_Result;
begin
Result := FT_EE_UAWrite(FT_Handle,@UserData,FT_UA_Size);
If Result <> FT_OK then FT_Error_Report('FT_EE_UAWrite ',Result);
end;
function USB_FT_EE_UASize : FT_Result;
begin
Result := FT_EE_UASize(FT_Handle,@FT_UA_Size);
If Result <> FT_OK then FT_Error_Report('FT_EE_UASize ',Result);
end;
Function Get_USB_Device_LatencyTimer : FT_Result;
Begin
Result := FT_GetLatencyTimer(FT_Handle,@FT_LatencyRd);
If Result <> FT_OK then FT_Error_Report('FT_GetLatencyTimer ',Result);
End;
Function Set_USB_Device_LatencyTimer(Latency:Byte) : FT_Result;
Begin
Result := FT_SetLatencyTimer(FT_Handle, Latency);
If Result <> FT_OK then FT_Error_Report('FT_SetLatencyTimer ',Result);
End;
Function Get_USB_Device_BitMode(var BitMode:Byte) : FT_Result;
Begin
Result := FT_GetBitMode(FT_Handle,@BitMode);
If Result <> FT_OK then FT_Error_Report('FT_GetBitMode ',Result);
End;
Function Set_USB_Device_BitMode(Mask,Enable:Byte) : FT_Result ;
Begin
Result := FT_SetBitMode(FT_Handle,Mask,Enable);
If Result <> FT_OK then FT_Error_Report('FT_SetBitMode ',Result);
End;
Function Set_USB_Parameters(InSize,OutSize:Dword) : FT_Result ;
Begin
Result := FT_SetUSBParameters(FT_Handle,InSize,OutSize);
If Result <> FT_OK then FT_Error_Report('FT_SetUSBParameters ',Result);
End;
End.
|
unit GLForces;
interface
uses
System.Classes,
Vcl.Dialogs,
GLVectorGeometry,
GLXCollection,
GLScene,
GLBehaviours,
GLCoordinates
{, GLSceneRegister};
type
TGLForce = class;
TForceType = (ftHookes, ftGravitation, ftCustom);
TOnCustomForce = procedure() of object;
TGLForce = class(TXCollectionItem)
private
fObject1: TGLBaseSceneObject;
fObject2: TGLBaseSceneObject;
fposition1: TGLCoordinates;
fposition2: TGLCoordinates;
object1Name: String;
object2Name: String;
// fOnCustomForce: TOnCustomForce;
protected
procedure Loaded; override;
procedure SetName(const val: String); override;
{ Returns the TGLBaseSceneObject on which the behaviour should be applied.<p>
Does NOT check for nil owners }
// function OwnerBaseSceneObject : TGLBaseSceneObject;
public
// constructor Create(Collection: TCollection);override;
{ Override this function to write subclass data. }
procedure WriteToFiler(writer: TWriter); override;
{ Override this function to read subclass data. }
procedure ReadFromFiler(reader: TReader); override;
constructor Create(aOwner: TXCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function FriendlyName: String; override;
class function FriendlyDescription: String; override;
class function UniqueItem: Boolean; override;
procedure SetObject1(const val: TGLBaseSceneObject);
procedure SetObject2(const val: TGLBaseSceneObject);
procedure SetPosition1(const val: TGLCoordinates);
procedure SetPosition2(const val: TGLCoordinates);
function CalculateForce(): TAffineVector; virtual;
published
property Object1: TGLBaseSceneObject read fObject1 write SetObject1;
property Object2: TGLBaseSceneObject read fObject2 write SetObject2;
property Position1: TGLCoordinates read fposition1 write SetPosition1;
property Position2: TGLCoordinates read fposition2 write SetPosition2;
// property OnCustomForce:TOnCustomForce read fOnCustomForce write fOnCustomForce;
end;
TGLHookesSpring = class(TGLForce)
private
fNaturalLength: Real;
fElasticity: Real;
fLength: Real;
fExtension: Real;
fDamping: TGLDamping;
public
procedure WriteToFiler(writer: TWriter); override;
procedure ReadFromFiler(reader: TReader); override;
constructor Create(aOwner: TXCollection); override;
destructor Destroy; override;
class function FriendlyName: String; override;
class function FriendlyDescription: String; override;
class function UniqueItem: Boolean; override;
procedure SetDamping(const val: TGLDamping);
function CalculateForce(): TAffineVector; override;
published
property NaturalLength: Real read fNaturalLength write fNaturalLength;
property Elasticity: Real read fElasticity write fElasticity;
property Damping: TGLDamping read fDamping write SetDamping;
// property Name;
end;
TGLHookesString = class(TGLHookesSpring)
protected
// procedure WriteToFiler(writer : TWriter); override;
// procedure ReadFromFiler(reader : TReader); override;
public
constructor Create(aOwner: TXCollection); override;
destructor Destroy; override;
class function FriendlyName: String; override;
class function FriendlyDescription: String; override;
class function UniqueItem: Boolean; override;
function CalculateForce(): TAffineVector; override;
end;
//--------------------------------------------------------------
//--------------------------------------------------------------
//--------------------------------------------------------------
implementation
//--------------------------------------------------------------
//--------------------------------------------------------------
//--------------------------------------------------------------
uses
GLInertias,
GLPhysics;
constructor TGLForce.Create(aOwner: TXCollection);
begin
inherited { Create(aOwner) };
fposition1 := TGLCoordinates.CreateInitialized(Self, NullHmgVector, csVector);
fposition2 := TGLCoordinates.CreateInitialized(Self, NullHmgVector, csVector);
// fObject1:=TGLBaseSceneObject.Create(Self);
// fObject2:=TGLBaseSceneObject.Create(Self);
end;
destructor TGLForce.Destroy;
begin
fposition1.Free();
fposition2.Free();
// SetObject1(nil);
// SetObject2(nil);
// fObject1.Free();
// fObject2.Free();
inherited Destroy;
end;
procedure TGLForce.Assign(Source: TPersistent);
begin
// inherited Assign(Source);
fposition1.Assign(TGLForce(Source).fposition1);
fposition2.Assign(TGLForce(Source).fposition2);
Object1 := TGLForce(Source).Object1;
Object2 := TGLForce(Source).Object2;
inherited Assign(Source);
end;
procedure TGLForce.SetObject1(const val: TGLBaseSceneObject);
begin
// if val.Behaviours.IndexOfClass(TGLBaseInertia) >=0 then
fObject1 := val
// else
// messagedlg('Object1 does not have an inertia behaviour',mtWarning,[mbOk],0);
end;
procedure TGLForce.SetObject2(const val: TGLBaseSceneObject);
begin
// if val.Behaviours.IndexOfClass(TGLBaseInertia) >=0 then
fObject2 := val
// else
// messagedlg('Object2 does not have an inertia behaviour',mtWarning,[mbOk],0);
end;
procedure TGLForce.SetPosition1(const val: TGLCoordinates);
begin
fposition1.Assign(val); // DB101
end;
procedure TGLForce.SetPosition2(const val: TGLCoordinates);
begin
fposition2.Assign(val);
end;
procedure TGLForce.Loaded;
var
PhysMan: TGLPhysicsManager;
begin
inherited Loaded;
// not nice, not nice at all!!!!!!
// assumes owner is TGLForces belonging to TGLPhysicsManager
PhysMan := TGLPhysicsManager(Self.Owner.Owner);
if (object1Name <> '') then
begin
// PhysMan:=TGLPhysicsManager(Self.Owner.Owner);
fObject1 := PhysMan.FindObjectByName(object1Name);
// fObject1:=TGLBaseSceneObject(FindComponent(Object1Name));
// Object1Name:='';
end;
if object2Name <> '' then
begin
fObject2 := PhysMan.FindObjectByName(object2Name);
// Object2Name:='';
end;
end;
class function TGLForce.FriendlyName: String;
begin
Result := 'Force';
end;
// FriendlyDescription
//
class function TGLForce.FriendlyDescription: String;
begin
Result := 'Physics Force';
end;
class function TGLForce.UniqueItem: Boolean;
begin
Result := false;
end;
procedure TGLForce.WriteToFiler(writer: TWriter);
begin
inherited WriteToFiler(writer);
// messagedlg('Writing to filer'+GetNamePath,mtInformation,[mbOk],0);
with writer do
begin
fposition1.WriteToFiler(writer);
fposition2.WriteToFiler(writer);
if Assigned(fObject1) then
WriteString(fObject1.GetNamePath)
else
WriteString('');
if Assigned(fObject2) then
WriteString(fObject2.GetNamePath)
else
WriteString('');
// WriteString(Object2Name);
end;
end;
procedure TGLForce.ReadFromFiler(reader: TReader);
begin
// messagedlg('Reading from filer'+GetNamePath,mtInformation,[mbOk],0);
inherited ReadFromFiler(reader);
with reader do
begin
fposition1.ReadFromFiler(reader);
fposition2.ReadFromFiler(reader);
object1Name := ReadString;
fObject1 := nil;
object2Name := ReadString;
fObject2 := nil;
end;
// Loaded;
end;
procedure TGLForce.SetName(const val: String);
begin
inherited SetName(val);
// if Assigned(vGLBehaviourNameChangeEvent) then
// vGLBehaviourNameChangeEvent(Self);
end;
function TGLForce.CalculateForce(): TAffineVector;
begin
//
end;
constructor TGLHookesSpring.Create(aOwner: TXCollection);
begin
inherited Create(aOwner);
fNaturalLength := 1;
fElasticity := 1;
fDamping := TGLDamping.Create(Self);
end;
destructor TGLHookesSpring.Destroy;
begin
fDamping.Free;
inherited Destroy;
end;
procedure TGLHookesSpring.WriteToFiler(writer: TWriter);
begin
inherited;
with writer do
begin
WriteFloat(fNaturalLength); // :Real;
WriteFloat(fElasticity); // :Real;
WriteFloat(fLength); // :Real;
WriteFloat(fExtension); // :Real;
fDamping.WriteToFiler(writer);
end;
end;
procedure TGLHookesSpring.ReadFromFiler(reader: TReader);
begin
inherited;
with reader do
begin
fNaturalLength := ReadFloat(); // :Real;
fElasticity := ReadFloat(); // :Real;
fLength := ReadFloat(); // :Real;
fExtension := ReadFloat(); // :Real;
fDamping.ReadFromFiler(reader);
end;
end;
procedure TGLHookesSpring.SetDamping(const val: TGLDamping);
begin
fDamping.Assign(val);
end;
function TGLHookesSpring.CalculateForce(): TAffineVector;
var
rvector, vvector: TAffineVector;
Inertia1, Inertia2: TGLParticleInertia;
begin
if (fObject1 = nil) or (fObject2 = nil) then
Exit;
Inertia2 := TGLParticleInertia
(Object2.Behaviours.GetByClass(TGLParticleInertia));
Inertia1 := TGLParticleInertia
(Object1.Behaviours.GetByClass(TGLParticleInertia));
// rvector:=VectorSubtract({VectorAdd(Object2.Position.asAffineVector,}VectorTransform(Position2.AsAffineVector,Object2.Matrix{)}),
// {VectorAdd(Object1.Position.asAffineVector,}VectorTransform(Position1.AsAffineVector,Object1.Matrix){)});
rvector := VectorSubtract(Object2.LocalToAbsolute(Position2.AsAffineVector),
Object1.LocalToAbsolute(Position1.AsAffineVector));
{ rvector:=VectorSubtract(VectorAdd(Object2.Position.asAffineVector,VectorTransform(Position2.AsAffineVector,Object2.Matrix)),
VectorAdd(Object1.Position.asAffineVector,VectorTransform(Position1.AsAffineVector,Object1.Matrix)));
}
fLength := VectorLength(rvector);
NormalizeVector(rvector);
fExtension := fLength - fNaturalLength;
// fDamping.Calculate();
Result := VectorScale(rvector, fElasticity * fExtension / fNaturalLength);
if Assigned(Inertia2) then
Inertia2.ApplyForce(Position2.AsAffineVector, VectorNegate(Result));
if Assigned(Inertia1) then
Inertia1.ApplyForce(Position1.AsAffineVector, Result);
// TGLInertia(Object1.Behaviours.GetByClass(TGLInertia)).ApplyForce(Position1.AsAffineVector,Result);
end;
class function TGLHookesSpring.FriendlyName: String;
begin
Result := 'Hookes Spring';
end;
class function TGLHookesSpring.FriendlyDescription: String;
begin
Result := 'A spring obeying Hookes Law';
end;
class function TGLHookesSpring.UniqueItem: Boolean;
begin
Result := false;
end;
constructor TGLHookesString.Create(aOwner: TXCollection);
begin
inherited Create(aOwner);
end;
destructor TGLHookesString.Destroy;
begin
inherited Destroy;
end;
class function TGLHookesString.FriendlyName: String;
begin
Result := 'Hookes String';
end;
class function TGLHookesString.FriendlyDescription: String;
begin
Result := 'A string (that can go slack) obeying Hookes Law';
end;
class function TGLHookesString.UniqueItem: Boolean;
begin
Result := false;
end;
function TGLHookesString.CalculateForce(): TAffineVector;
var
rvector: TAffineVector;
Inertia1, Inertia2: TGLParticleInertia;
begin
if (Object1 = nil) or (Object2 = nil) then
Exit;
rvector := VectorSubtract(Object2.LocalToAbsolute(Position2.AsAffineVector),
Object1.LocalToAbsolute(Position1.AsAffineVector));
// VectorAdd(Object2.Position.asAffineVector,VectorTransform(Object2.Position2.AsAffineVector,Object2.Matrix)),
// VectorAdd(Object1.Position.asAffineVector,VectorTransform(Position1.AsAffineVector,Object1.Matrix)));
fLength := VectorLength(rvector);
if (fLength < fNaturalLength) then
Result := NullVector
else
begin
NormalizeVector(rvector);
fExtension := fLength - fNaturalLength;
Result := VectorScale(rvector, fElasticity * fExtension / fNaturalLength);
// TGLInertia(Object2.Behaviours.GetByClass(TGLInertia)).ApplyForce(Position2.AsAffineVector,VectorNegate(Result));
// TGLInertia(Object1.Behaviours.GetByClass(TGLInertia)).ApplyForce(Position1.AsAffineVector,Result);
Inertia2 := TGLParticleInertia
(Object2.Behaviours.GetByClass(TGLParticleInertia));
Inertia1 := TGLParticleInertia
(Object1.Behaviours.GetByClass(TGLParticleInertia));
if Assigned(Inertia2) then
Inertia2.ApplyForce(Position2.AsAffineVector, VectorNegate(Result));
if Assigned(Inertia1) then
Inertia1.ApplyForce(Position1.AsAffineVector, Result);
end;
// Result:= inherited CalculateForce();
// if (fLength < fNaturalLength) then Result:=NullVector;
end;
//=================================================================
initialization
//=================================================================
RegisterXCollectionItemClass(TGLHookesSpring);
RegisterXCollectionItemClass(TGLHookesString);
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmTrayIcon
Purpose : To allow the program to have an Icon in the Win95 Shell Icontray.
Date : 12-01-1998
Author : Ryan J. Mills
Version : 1.92
Notes : I don't remember where I originally got the code for this component.
I have modified very little from the original source.
================================================================================}
unit rmTrayIcon;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ShellAPI, Menus;
const
wm_IconMessage = wm_user + 1;
wm_ResetIconToolTip = WM_USER+2;
type
TrmTrayIcon = class(TComponent)
private
{ Private declarations }
fIconData: TNOTIFYICONDATA;
fIcon: TIcon;
fToolTip: string;
fWindowHandle: HWND;
fOnClick: TNotifyEvent;
fOnDblClick: TNotifyEvent;
fOnRightClick: TMouseEvent;
fPopupMenu: TPopupMenu;
fShowDesigning: boolean;
fActive: boolean;
fShowApp: boolean;
procedure FillDataStructure;
function AddIcon : boolean;
function ModifyIcon : boolean;
function DeleteIcon : boolean;
procedure IconTrayWndProc(var msg: TMessage);
procedure DoRightClick(Sender: TObject);
procedure SetActive(const Value: boolean);
procedure SetIcon(const Value: TIcon);
procedure SetShowApp(const Value: boolean);
procedure SetShowDesigning(const Value: boolean);
procedure SetToolTip(const Value: string);
protected
{ Protected declarations }
public
{ Public declarations }
constructor create(aOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property Active: boolean read fActive write SetActive;
property Icon: TIcon read fIcon write SetIcon;
property PopupMenu: TPopupMenu read fPopupMenu write fPopupMenu;
property ShowDesigning: boolean read fShowDesigning write SetShowDesigning;
property ShowApp: boolean read fShowApp write SetShowApp;
property ToolTip: string read fTooltip write SetToolTip;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick;
property OnRightClick: TMouseEvent read FOnRightClick write FonRightClick;
end;
implementation
{ TrmTrayIcon }
function TrmTrayIcon.AddIcon: boolean;
begin
FillDataStructure;
result := Shell_NotifyIcon(NIM_ADD,@fIconData);
if fToolTip = '' then
PostMessage(fWindowHandle, wm_ResetIconToolTip, 0, 0);
end;
constructor TrmTrayIcon.create(aOwner: TComponent);
begin
inherited;
fIcon := TIcon.create;
{$ifdef D6_or_higher}
FWindowHandle := Classes.AllocateHWnd(IconTrayWndProc);
{$else}
FWindowHandle := AllocateHWnd(IconTrayWndProc);
{$endif}
SetShowApp(False);
end;
function TrmTrayIcon.DeleteIcon: boolean;
begin
result := Shell_NotifyIcon(NIM_DELETE,@fIconData);
end;
destructor TrmTrayIcon.Destroy;
begin
DeleteIcon;
{$ifdef D6_or_higher}
Classes.DeAllocateHWnd(FWindowHandle);
{$else}
DeAllocateHWnd(FWindowHandle);
{$endif}
fIcon.free;
inherited;
end;
procedure TrmTrayIcon.DoRightClick(Sender: TObject);
var
MouseCo: Tpoint;
begin
GetCursorPos(MouseCo);
if assigned(fPopupMenu) then
begin
SetForegroundWindow(Application.Handle);
Application.ProcessMessages;
fPopupmenu.Popup(Mouseco.X, Mouseco.Y);
end;
if assigned(FOnRightClick) then
FOnRightClick(self, mbRight, [], MouseCo.x, MouseCo.y);
end;
procedure TrmTrayIcon.FillDataStructure;
begin
with fIconData do
begin
cbSize := sizeof(TNOTIFYICONDATA);
wnd := FWindowHandle;
uID := 1;
uFlags := NIF_MESSAGE + NIF_ICON + NIF_TIP;
hIcon := fIcon.Handle;
StrPCopy(szTip, fToolTip);
uCallbackMessage := wm_IconMessage;
end;
end;
procedure TrmTrayIcon.IconTrayWndProc(var msg: TMessage);
begin
case msg.msg of
wm_ResetIconToolTip:
begin
SetToolTip( fToolTip );
end;
wm_IconMessage:
begin
case msg.lParam of
WM_LBUTTONDBLCLK:
if assigned(FOnDblClick) then FOnDblClick(self);
WM_LBUTTONUP:
if assigned(FOnClick) then FOnClick(self);
WM_RBUTTONUP: DoRightClick(self);
end;
end;
else
msg.Result := DefWindowProc(FWindowHandle, Msg.Msg, Msg.wParam, Msg.lParam);
end;
end;
function TrmTrayIcon.ModifyIcon: boolean;
begin
FillDataStructure;
if fActive then
result := Shell_NotifyIcon(NIM_MODIFY,@fIconData)
else
result := True;
end;
procedure TrmTrayIcon.SetActive(const Value: boolean);
begin
if value <> fActive then
begin
fActive := Value;
if not (csdesigning in ComponentState) then
begin
if Value then
AddIcon
else
DeleteIcon;
end;
end;
end;
procedure TrmTrayIcon.SetIcon(const Value: TIcon);
begin
if Value <> fIcon then
begin
fIcon.Assign(value);
ModifyIcon;
end;
end;
procedure TrmTrayIcon.SetShowApp(const Value: boolean);
begin
if value <> fShowApp then
fShowApp := value;
if not (csdesigning in ComponentState) then
begin
if Value then
ShowWindow(Application.Handle, SW_SHOW)
else
ShowWindow(Application.Handle, SW_HIDE);
end;
end;
procedure TrmTrayIcon.SetShowDesigning(const Value: boolean);
begin
if csdesigning in ComponentState then
begin
if value <> fShowDesigning then
begin
fShowDesigning := Value;
if Value then
AddIcon
else
DeleteIcon;
end;
end;
end;
procedure TrmTrayIcon.SetToolTip(const Value: string);
begin
if length(Value) > 62 then
fToolTip := copy(Value, 1, 62)
else
fToolTip := value;
ModifyIcon;
end;
initialization
end.
|
unit frmDisposePrice;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, cxGridLevel, cxClasses, cxControls,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGrid,
StdCtrls, ComCtrls, ExtCtrls, Buttons, DB, DBClient, cxDBData,
cxGridDBTableView;
type
TDisposePriceForm = class(TForm)
Panel1: TPanel;
tbcAccident: TTabControl;
gbLeft: TGroupBox;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
btn_Exit: TBitBtn;
btnSubmit: TBitBtn;
cbb_Result: TComboBox;
Label1: TLabel;
Label2: TLabel;
dsPrice: TDataSource;
cdsPrice: TClientDataSet;
cxgridPrice: TcxGrid;
cxgridtvPrice: TcxGridDBTableView;
cxgridlPrice: TcxGridLevel;
mmRemark: TMemo;
btnQuery: TBitBtn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure QueryData;
procedure SaveData;
procedure FilterPrice;
procedure tbcAccidentChange(Sender: TObject);
procedure btnSubmitClick(Sender: TObject);
procedure btnQueryClick(Sender: TObject);
procedure btn_ExitClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DisposePriceForm: TDisposePriceForm;
implementation
uses StrUtils, uDictionary, UAppOption,
uFNMArtInfo, uGlobal, ServerDllPub, uFNMResource,
uLogin, uShowMessage,uGridDecorator;
{$R *.dfm}
procedure TDisposePriceForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TDisposePriceForm.FormDestroy(Sender: TObject);
begin
DisposePriceForm:= nil;
end;
procedure TDisposePriceForm.QueryData();
var
sSQL,sErrMsg:WideString;
vData:OleVariant;
begin
//刷新列表
sSQL := '2';
FNMServerObj.GetQueryData(vData,'SaveWorkerPrice',sSQL,sErrMsg);
if sErrMsg <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrMsg, mtError);
Exit;
end;
cdsprice.Data := vData;
GridDecorator.BindCxViewWithDataSource(cxgridtvPrice,dsprice,True);
end;
procedure TDisposePriceForm.FormCreate(Sender: TObject);
begin
QueryData;
end;
procedure TDisposePriceForm.FilterPrice;
var
iGrade:Integer;
begin
if not cdsPrice.Active then Exit;
iGrade := tbcAccident.TabIndex;
cdsPrice.Filtered := False;
cdsPrice.Filter := 'Grade= '+ IntToStr(iGrade);
cdsPrice.Filtered := True;
GridDecorator.BindCxViewWithDataSource(cxgridtvPrice,dsprice,True);
//GridDecorator.BindcxTableView(cxgridtvPrice, cdsPrice, ['iden', 'group_id', 'fn_card', 'finder_id', 'machine_ID', 'Operation', 'score']);
//cxgtv_AccidentList.Columns[cxgtv_AccidentList.FindItemByName('Grade').Index].Visible := False;
end;
procedure TDisposePriceForm.tbcAccidentChange(Sender: TObject);
begin
FilterPrice;
end;
procedure TDisposePriceForm.btnSubmitClick(Sender: TObject);
begin
SaveData;
end;
procedure TDisposePriceForm.SaveData;
var
sIden:string;
i:Integer;
sSQL,sErrMsg:WideString;
vData:OleVariant;
begin
//刷新列表
sIden := '';
with cxgridtvPrice do
begin
for i:=0 to Controller.SelectedRowCount - 1 do
begin
sIden := sIden + IntToStr(Controller.SelectedRows[i].Values[GetColumnByFieldName('iden').Index]) + ',';
end;
end;
if sIden = '' then Exit;
sSQL := '3' + ',' + QuotedStr(sIden) + ',' + QuotedStr(cbb_Result.Text) + ',' + QuotedStr(mmRemark.Text) + ',' + QuotedStr(login.LoginID);
FNMServerObj.GetQueryData(vData,'SaveWorkerPrice',sSQL,sErrMsg);
if sErrMsg <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrMsg, mtError);
Exit;
end;
end;
procedure TDisposePriceForm.btnQueryClick(Sender: TObject);
begin
QueryData;
FilterPrice;
end;
procedure TDisposePriceForm.btn_ExitClick(Sender: TObject);
begin
close;
end;
end.
|
unit uMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms3D, FMX.Forms, FMX.Dialogs, FMX.Sensors,
FMX.Controls3D, FMX.Objects3D, System.Sensors, FMX.StdCtrls, FMX.Layers3D,
FMX.MaterialSources;
type
TGyroscopeForm = class(TForm3D)
Rectangle3D1: TRectangle3D;
Timer1: TTimer;
LightMaterialSource1: TLightMaterialSource;
Light1: TLight;
Layer3D1: TLayer3D;
Label1: TLabel;
procedure Timer1Timer(Sender: TObject);
procedure Form3DCreate(Sender: TObject);
private
{ Private declarations }
FSensors: TSensorArray;
FSensorManager: TSensorManager;
public
{ Public declarations }
end;
var
GyroscopeForm: TGyroscopeForm;
implementation
{$R *.fmx}
procedure TGyroscopeForm.Form3DCreate(Sender: TObject);
begin
{ attempt to get and activate the sensor manager }
FSensorManager := TSensorManager.Current;
FSensorManager.Activate;
{ attempt to get an orientation sensor }
FSensors := TSensorManager.Current.GetSensorsByCategory(TSensorCategory.Orientation);
if Length(FSensors) = 0 then
begin
Label1.Text := 'Gyro not found';
Exit; { no sensors available }
end;
if not (FSensors[0] is TCustomOrientationSensor) then
Exit; { no orientation sensor is available }
{ start the sensor if it is not started }
if not TCustomOrientationSensor(FSensors[0]).Started then
begin
TCustomOrientationSensor(FSensors[0]).Start;
Timer1.Enabled := True;
end;
end;
procedure TGyroscopeForm.Timer1Timer(Sender: TObject);
begin
{ check for sensor assignment }
if Length(FSensors) > 0 then
if Assigned(FSensors[0]) then
begin
{ and rotate the cube }
Rectangle3D1.RotationAngle.X := TCustomOrientationSensor(FSensors[0]).TiltX;
Rectangle3D1.RotationAngle.Y := TCustomOrientationSensor(FSensors[0]).TiltY;
Rectangle3D1.RotationAngle.Z := TCustomOrientationSensor(FSensors[0]).TiltZ;
Label1.Text := Format('Gyro: %3.1f %3.1f %3.1f',[Rectangle3D1.RotationAngle.X,
Rectangle3D1.RotationAngle.Y,
Rectangle3D1.RotationAngle.Z]);
end;
end;
end.
|
unit SpeeduinoShell;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Shell,
inifiles,
speeduinomessagehandler;
type
//Create a class for our shell command, descended from TShellCommand
TSpeeduinoShellCommand = class(TShellCommand)
public
constructor Create;
private
public
speedymessage : tspeeduinomessagehandler;
//Override the DoHelp, DoInfo and DoCommand methods
function DoHelp(AShell:TShell;ASession:TShellSession):Boolean; override;
function DoInfo(AShell:TShell;ASession:TShellSession):Boolean; override;
function DoCommand(AShell:TShell;ASession:TShellSession;AParameters:TStrings):Boolean; override;
end;
var
cmd : TSpeeduinoShellCommand;
implementation
constructor TSpeeduinoShellCommand.Create;
begin
{}
inherited Create;
//In the Create() method we have to set the name of our commmand
//Name is the name of the command, eg what the user has to type
Name:='DATALOG';
//Flags tell the shell if this command provides help or info
Flags:=SHELL_COMMAND_FLAG_INFO or SHELL_COMMAND_FLAG_HELP;
end;
function TSpeeduinoShellCommand.DoHelp(AShell:TShell;ASession:TShellSession):Boolean;
begin
//The DoHelp method is called when someone types HELP <COMMAND>
Result:=False;
if AShell = nil then Exit;
AShell.DoOutput(ASession,'DATALOG - control the logging functions');
AShell.DoOutput(ASession,'DATALOG RESUME - start logging (retain file number)');
AShell.DoOutput(ASession,'DATALOG PAUSE - stop logging (retain file number)');
AShell.DoOutput(ASession,'DATALOG NEXT - move to next log file');
AShell.DoOutput(ASession,'DATALOG CLEANUP - remove all files prior to current file number');
AShell.DoOutput(ASession,'DATALOG RESET - restore the file nuber back to 0. WARNING: files will be overwritten');
AShell.DoOutput(ASession,'DATALOG WEBON - Enable the web server (requires a restart)');
AShell.DoOutput(ASession,'DATALOG WEBOFF - Disable the web server (requires a restart)');
AShell.DoOutput(ASession,'RESTART - restart the system after config changes');
Result := True;
end;
function TSpeeduinoShellCommand.DoInfo(AShell:TShell;ASession:TShellSession):Boolean;
begin
//The DoInfo method is called when someone types INFO or INFO <COMMAND>
Result:=False;
if AShell = nil then Exit;
AShell.DoOutput(ASession,'No info for DATALOG command at present');
Result := True;
end;
function TSpeeduinoShellCommand.DoCommand(AShell:TShell;ASession:TShellSession;AParameters:TStrings):Boolean;
var
Parameter:String;
ini: TIniFile;
begin
//The DoCommand method is called when someone types our command in the shell
//We also get any parameters they added in the AParameters object
Result:=False;
if AShell = nil then Exit;
//Get the parameter (if any)
Parameter:=AShell.ParameterIndex(0,AParameters);
if Length(Parameter) > 0 then
begin
if (upcase(Parameter) = 'PAUSE') then
begin
//stop logging
SpeedyMessage.PauseLogging;
Result:=AShell.DoOutput(ASession,'Logging stopped');
end
else
if (upcase(Parameter) = 'RESUME') then
begin
//start logging going again
SpeedyMessage.ResumeLogging;
Result:=AShell.DoOutput(ASession,'Logging started');
end
else
if (upcase(Parameter) = 'NEXT') then
begin
SpeedyMessage.EndLogging;
Result:=AShell.DoOutput(ASession,'Starting next log file');
end
else
if (upcase(Parameter) = 'CLEANUP') then
begin
speedymessage.DeleteLogs;
Result:=AShell.DoOutput(ASession,'Old logs removed; current one left active.');
end
else
if (upcase(Parameter) = 'RESET') then
begin
speedymessage.ResetLogs;
Result:=AShell.DoOutput(ASession,'Log file number set to zero. Logs will be overwritten.');
end
else
if (upcase(Parameter) = 'WEBON') then
begin
ini := TIniFile.Create('c:\speedylog.ini');
ini.WriteString('webserver','enabled', '1');
ini.Free;
end
else
if (upcase(Parameter) = 'WEBOFF') then
begin
ini := TIniFile.Create('c:\speedylog.ini');
ini.WriteString('webserver','enabled', '0');
ini.Free;
end;
end;
end;
initialization
//Register our new shell command so it is available in any shell
cmd := TSpeeduinoShellCommand.Create;
ShellRegisterCommand(cmd);
end.
|
unit uFrEmprestimo;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uFrPadrao, Data.DB, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Buttons, Vcl.Grids,
Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.WinXPickers,
Vcl.Mask, uEmprestimoController, uUsuarioModel;
type
TfrEmprestimo = class(TfrPadrao)
edtCodigo: TLabeledEdit;
cbxLivro: TComboBox;
cbxUsuario: TComboBox;
lblLivro: TLabel;
lblUsuario: TLabel;
edtDataRetirada: TMaskEdit;
edtDataVencimento: TMaskEdit;
lblDataRetirada: TLabel;
lblDataVencimento: TLabel;
edtDataDevolucao: TMaskEdit;
lblDataDevolucao: TLabel;
procedure btnGravarClick(Sender: TObject);
procedure btnIncluirClick(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dbgPadraoDblClick(Sender: TObject);
private
FEmprestimoController: TEmprestimoController;
procedure LimpaCampos();
procedure IncluirRegistro();
function GravarRegistro(): Boolean;
function ExcluirRegistro(): Boolean;
procedure PesquisarRegistros();
function ValidaCampos(): Boolean;
procedure EditarRegistro();
procedure AlimentaComboUsuarios();
procedure AlimentaComboLivros();
public
FUsuario: TUsuarioModel;
end;
var
frEmprestimo: TfrEmprestimo;
implementation
uses uEmprestimoModel, uLivroModel;
{$R *.dfm}
{ TfrEmprestimo }
procedure TfrEmprestimo.AlimentaComboLivros;
begin
FEmprestimoController.AlimentaComboLivros(cbxLivro);
end;
procedure TfrEmprestimo.AlimentaComboUsuarios;
begin
FEmprestimoController.AlimentaComboUsuarios(cbxUsuario);
end;
procedure TfrEmprestimo.btnExcluirClick(Sender: TObject);
begin
inherited;
ExcluirRegistro();
end;
procedure TfrEmprestimo.btnGravarClick(Sender: TObject);
begin
inherited;
GravarRegistro();
end;
procedure TfrEmprestimo.btnIncluirClick(Sender: TObject);
begin
inherited;
IncluirRegistro();
end;
procedure TfrEmprestimo.btnPesquisarClick(Sender: TObject);
begin
inherited;
PesquisarRegistros();
end;
procedure TfrEmprestimo.dbgPadraoDblClick(Sender: TObject);
begin
inherited;
EditarRegistro();
end;
procedure TfrEmprestimo.EditarRegistro;
begin
if not (qryPadrao.FieldByName('codigo').AsInteger > 0) then
Exit;
edtCodigo.Text := qryPadrao.FieldByName('codigo').AsString;
edtDataRetirada.Text := qryPadrao.FieldByName('dataretirada').AsString;
edtDataVencimento.Text := qryPadrao.FieldByName('datavencimento').AsString;
edtDataDevolucao.Text := qryPadrao.FieldByName('datadevolucao').AsString;
cbxLivro.ItemIndex := cbxLivro.Items.IndexOfObject(
FEmprestimoController.RetornaObjetoLivro(qryPadrao.FieldByName('livro_codigo').AsInteger));
cbxUsuario.ItemIndex := cbxUsuario.Items.IndexOfObject(
FEmprestimoController.RetornaObjetoUsuario(qryPadrao.FieldByName('usuario_codigo').AsInteger));
pgcPadrao.TabIndex := 1;
AjustaVisibilidadeBotoes();
end;
function TfrEmprestimo.ExcluirRegistro: Boolean;
begin
FEmprestimoController.frMain := frMain;
FEmprestimoController.ExcluirRegistro(qryPadrao.FieldByName('CODIGO').AsInteger);
PesquisarRegistros();
end;
procedure TfrEmprestimo.FormCreate(Sender: TObject);
begin
inherited;
FEmprestimoController := TEmprestimoController.Create;
end;
function TfrEmprestimo.GravarRegistro: Boolean;
var LEmprestimo: TEmprestimoModel;
begin
if not ValidaCampos() then
Exit;
LEmprestimo := TEmprestimoModel.Create;
try
LEmprestimo.Codigo := StrToIntDef(edtCodigo.Text,0);
LEmprestimo.Livro := TLivroModel(cbxLivro.Items.Objects[cbxLivro.ItemIndex]);
LEmprestimo.Usuario := TUsuarioModel(cbxUsuario.Items.Objects[cbxUsuario.ItemIndex]);
LEmprestimo.DataRetirada := StrToDateDef(edtDataRetirada.Text,0);
LEmprestimo.DataVencimento := StrToDateDef(edtDataVencimento.Text,0);
LEmprestimo.DataDevolucao := StrToDateDef(edtDataDevolucao.Text,0);
FEmprestimoController.frMain := frMain;
if FEmprestimoController.GravarRegistro(LEmprestimo) then
begin
LimpaCampos();
ShowMessage('Registro incluído com sucesso.');
end;
finally
FreeAndNil(LEmprestimo);
end;
end;
procedure TfrEmprestimo.IncluirRegistro;
begin
LimpaCampos();
end;
procedure TfrEmprestimo.LimpaCampos;
begin
edtCodigo.Text := '';
if cbxUsuario.Items.Count > 0 then
cbxUsuario.ItemIndex := 0;
if cbxLivro.Items.Count > 0 then
cbxLivro.ItemIndex := 0;
edtDataRetirada.Text := '';
edtDataVencimento.Text := '';
edtDataDevolucao.Text := '';
end;
procedure TfrEmprestimo.PesquisarRegistros;
var LSQL: String;
LPesquisaComFiltro: Boolean;
begin
LSQL :=
'SELECT * FROM EMPRESTIMO '+
'INNER JOIN USUARIO ON (USUARIO.CODIGO = EMPRESTIMO.USUARIO_CODIGO) ';
LPesquisaComFiltro := Trim(edtPesquisar.Text) <> '';
if LPesquisaComFiltro then
LSQL := LSQL + 'WHERE UPPER(USUARIO.NOME) LIKE UPPER(:usuario_nome)';
if qryPadrao.Active then
qryPadrao.Close;
qryPadrao.SQL.Text := LSQL;
if LPesquisaComFiltro then
qryPadrao.ParamByName('usuario_nome').AsString := '%' + edtPesquisar.Text + '%';
qryPadrao.Open;
end;
function TfrEmprestimo.ValidaCampos: Boolean;
var LCamposPreechidos: Boolean;
begin
LCamposPreechidos :=
(Trim(edtDataRetirada.Text) <> '') and
(Trim(edtDataVencimento.Text) <> '') and
(cbxLivro.ItemIndex >= 0) and
(cbxUsuario.ItemIndex >= 0);
if not (Trim(edtDataRetirada.Text) <> '') then
ShowMessage('Preencha o campo data retirada');
if not (Trim(edtDataVencimento.Text) <> '') then
ShowMessage('Preencha o campo data vencimento');
if not (cbxLivro.ItemIndex >= 0) then
ShowMessage('Preencha o campo livro');
if not (cbxUsuario.ItemIndex >= 0) then
ShowMessage('Preencha o campo usuario');
Result := LCamposPreechidos;
end;
procedure TfrEmprestimo.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FEmprestimoController);
end;
procedure TfrEmprestimo.FormShow(Sender: TObject);
begin
inherited;
AlimentaComboUsuarios();
AlimentaComboLivros();
PesquisarRegistros();
end;
end.
|
unit FFindFileDlg;
(*====================================================================
Dialog box for find file options
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Spin, ExtCtrls, IniFiles,
UTypes, UApiTypes;
type
TFormSearchFileDlg = class(TForm)
RadioGroupSearch: TRadioGroup;
Label1: TLabel;
GroupBoxMaxLines: TGroupBox;
SpinEditMaxRecs: TSpinEdit;
Label4: TLabel;
ButtonOK: TButton;
ButtonCancel: TButton;
CheckBoxCaseSensitive: TCheckBox;
ComboBoxMask: TComboBox;
ButtonOptions: TButton;
ButtonHelp: TButton;
CheckBoxAddWildcards: TCheckBox;
ComboBoxScanDirLevel: TComboBox;
Label3: TLabel;
GroupBoxWhere: TGroupBox;
CheckBoxFileNames: TCheckBox;
CheckBoxFolderNames: TCheckBox;
CheckBoxDescriptions: TCheckBox;
CheckBoxPhrase: TCheckBox;
CheckBoxUseMoreOptions: TCheckBox;
CheckBoxStrictMask: TCheckBox;
CheckBoxDiskNames: TCheckBox;
procedure ButtonOKClick(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ButtonOptionsClick(Sender: TObject);
procedure ButtonHelpClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ComboBoxMaskChange(Sender: TObject);
public
DlgData: TSearchDlgData;
procedure RestoreDlgData (var DlgData: TSearchDlgData);
procedure SaveDlgData (var DlgData: TSearchDlgData);
procedure SaveToIni (var IniFile: TIniFile);
procedure LoadFromIni (var IniFile: TIniFile);
end;
var
FormSearchFileDlg: TFormSearchFileDlg;
implementation
uses
FMoreOptions, ULang;
{$R *.dfm}
//------------------------------------------------------------------------
procedure TFormSearchFileDlg.ButtonOKClick(Sender: TObject);
var
Found : boolean;
i : Integer;
begin
SaveDlgData(DlgData);
if ComboBoxMask.Text <> ''
then
begin
Found := false;
for i := 0 to pred(ComboBoxMask.Items.Count) do
if ComboBoxMask.Items.Strings[i] = ComboBoxMask.Text then
Found := true;
if not Found then ComboBoxMask.Items.Insert(0, ComboBoxMask.Text);
ModalResult := mrOk;
end
else
begin
Application.MessageBox(lsNoMaskEntered, lsCannotSearch, mb_OK);
ActiveControl := ComboBoxMask;
end;
end;
//------------------------------------------------------------------------
procedure TFormSearchFileDlg.ButtonCancelClick(Sender: TObject);
begin
RestoreDlgData(DlgData);
ModalResult := mrCancel;
end;
//------------------------------------------------------------------------
procedure TFormSearchFileDlg.FormShow(Sender: TObject);
begin
SaveDlgData(DlgData);
ActiveControl := ComboBoxMask;
{$ifndef DELPHI1}
SpinEditMaxRecs.MaxValue := 50000;
{$endif}
CheckBoxAddWildCards.Enabled := (Pos('*', ComboBoxMask.Text) = 0) and
(length(ComboBoxMask.Text) > 0);
CheckBoxPhrase.Enabled := (Pos(' ', ComboBoxMask.Text) <> 0) and
(Pos('"', ComboBoxMask.Text) = 0);
end;
//------------------------------------------------------------------------
// Restores the values in the controls from saved structure - used when the
// user presses Cancel
procedure TFormSearchFileDlg.RestoreDlgData (var DlgData: TSearchDlgData);
begin
with DlgData do
begin
ComboBoxMask.Text := Mask;
CheckBoxAddWildCards.Checked := AddWildCards;
CheckBoxPhrase.Checked := AsPhrase;
SpinEditMaxRecs.Value := MaxLines;
CheckBoxCaseSensitive.Checked := CaseSensitive;
CheckBoxStrictMask.Checked := StrictMask;
RadioGroupSearch.ItemIndex := Integer(SearchIn);
CheckBoxDiskNames.Checked := ScanDiskNames;
CheckBoxFileNames.Checked := ScanFileNames;
CheckBoxFolderNames.Checked := ScanDirNames;
CheckBoxDescriptions.Checked := ScanDesc;
ComboBoxScanDirLevel.ItemIndex := ScanDirLevel+1;
CheckBoxUseMoreOptions.Checked := UseMoreOptions;
end;
end;
//------------------------------------------------------------------------
// Puts the values from this dialog controls to a structure, used by the
// engine for searching
procedure TFormSearchFileDlg.SaveDlgData (var DlgData: TSearchDlgData);
begin
with DlgData do
begin
Mask := ComboBoxMask.Text;
if CheckBoxAddWildCards.Enabled
then AddWildCards := CheckBoxAddWildCards.Checked
else AddWildCards := false;
if CheckBoxPhrase.Enabled
then AsPhrase := CheckBoxPhrase.Checked
else AsPhrase := false;
MaxLines := SpinEditMaxRecs.Value;
{$ifdef DELPHI1}
if MaxLines > 16000 then MaxLines := 16000;
{$endif}
CaseSensitive := CheckBoxCaseSensitive.Checked;
StrictMask := CheckBoxStrictMask.Checked;
SearchIn := TSearchIn(RadioGroupSearch.ItemIndex);
ScanDiskNames := CheckBoxDiskNames.Checked;
ScanFileNames := CheckBoxFileNames.Checked;
ScanDirNames := CheckBoxFolderNames.Checked;
ScanDesc := CheckBoxDescriptions.Checked;
UseMoreOptions := CheckBoxUseMoreOptions.Checked;
if CheckBoxUseMoreOptions.Checked
then
begin
ExcludeMask := FormMoreOptions.ComboBoxExclude.Text;
DirMask := FormMoreOptions.ComboBoxDirMask.Text;
DateFrom := FormMoreOptions.DateFrom;
DateTo := FormMoreOptions.DateTo;
SizeFrom := FormMoreOptions.SizeFrom;
SizeTo := FormMoreOptions.SizeTo;
SortArr[1] := TSort(FormMoreOptions.RadioGroupKey1.ItemIndex);
SortArr[2] := TSort(FormMoreOptions.RadioGroupKey2.ItemIndex);
SortArr[3] := TSort(FormMoreOptions.RadioGroupKey3.ItemIndex);
MoreOptions := (DateFrom > 0) or (DateTo > 0) or
(SizeFrom > 0) or (SizeTo > 0) or
(ExcludeMask <> '');
SearchAsAnsi := FormMoreOptions.CheckBoxSearchAsAnsi.Checked;
SearchAsOem := FormMoreOptions.CheckBoxSearchAsOem.Checked;
end
else
begin
ExcludeMask := '';
DirMask := '';
DateFrom := 0;
DateTo := 0;
SizeFrom := 0;
SizeTo := 0;
SortArr[1] := soExt;
SortArr[2] := soKey;
SortArr[3] := soTime;
MoreOptions := false;
SearchAsAnsi := true;
SearchAsOem := false;
end;
ScanDirLevel := ComboBoxScanDirLevel.ItemIndex-1;
if ScanDirLevel < -1 then ScanDirLevel := -1;
end;
end;
//------------------------------------------------------------------------
// More options dialog
procedure TFormSearchFileDlg.ButtonOptionsClick(Sender: TObject);
begin
with FormMoreOptions do
if ShowModal = mrOK then
begin
CheckBoxUseMoreOptions.Checked := true;
end;
end;
//------------------------------------------------------------------------
procedure TFormSearchFileDlg.ButtonHelpClick(Sender: TObject);
begin
Application.HelpContext(230);
end;
//------------------------------------------------------------------------
procedure TFormSearchFileDlg.FormCreate(Sender: TObject);
begin
ComboBoxScanDirLevel.ItemIndex := 0;
end;
//------------------------------------------------------------------------
procedure TFormSearchFileDlg.ComboBoxMaskChange(Sender: TObject);
begin
CheckBoxAddWildCards.Enabled := (Pos('*', ComboBoxMask.Text) = 0) and
(length(ComboBoxMask.Text) > 0);
CheckBoxPhrase.Enabled := (Pos(' ', ComboBoxMask.Text) <> 0) and
(Pos('"', ComboBoxMask.Text) = 0);
end;
//------------------------------------------------------------------------
// Saves the values from this dialog box to an INI file
procedure TFormSearchFileDlg.SaveToIni(var IniFile: TIniFile);
const
Section = 'SearchDlg';
MaxItems = 15;
var
i: integer;
Items: integer;
begin
IniFile.WriteString (Section, 'Mask', ComboBoxMask.Text);
Items := ComboBoxMask.Items.Count;
if Items > MaxItems then Items := MaxItems;
for i := 1 to Items do
IniFile.WriteString (Section, 'Mask'+IntToStr(i), ComboBoxMask.Items.Strings[i-1]);
for i := Items+1 to MaxItems do
IniFile.WriteString (Section, 'Mask'+IntToStr(i), '');
IniFile.WriteInteger(Section, 'Search', RadioGroupSearch.ItemIndex);
IniFile.WriteBool (Section, 'DiskNames', CheckBoxDiskNames.Checked);
IniFile.WriteBool (Section, 'FileNames', CheckBoxFileNames.Checked);
IniFile.WriteBool (Section, 'SearchDirs', CheckBoxFolderNames.Checked);
IniFile.WriteBool (Section, 'SearchDesc', CheckBoxDescriptions.Checked);
IniFile.WriteBool (Section, 'AddWildcards', CheckBoxAddWildCards.Checked);
IniFile.WriteBool (Section, 'Phrase', CheckBoxPhrase.Checked);
IniFile.WriteBool (Section, 'CaseSensitive', CheckBoxCaseSensitive.Checked);
IniFile.WriteBool (Section, 'StrictMask', CheckBoxStrictMask.Checked);
IniFile.WriteInteger(Section, 'ScanDirLevel', ComboBoxScanDirLevel.ItemIndex);
IniFile.WriteInteger(Section, 'MaxRecs', SpinEditMaxRecs.Value);
IniFile.WriteBool (Section, 'UseMoreOptions', CheckBoxUseMoreOptions.Checked);
end;
//------------------------------------------------------------------------
// Loads the values for this dialog box from an INI file
procedure TFormSearchFileDlg.LoadFromIni(var IniFile: TIniFile);
const
Section = 'SearchDlg';
MaxItems = 15;
var
i: integer;
//Items: integer;
S : ShortString;
begin
ComboBoxMask.Text := IniFile.ReadString (Section, 'Mask', '');
for i := 1 to MaxItems do
begin
S := IniFile.ReadString (Section, 'Mask'+IntToStr(i), '');
if S <> ''
then ComboBoxMask.Items.Add(S)
else break;
end;
RadioGroupSearch.ItemIndex := IniFile.ReadInteger(Section, 'Search', 0);
CheckBoxDiskNames.Checked := IniFile.ReadBool (Section, 'DiskNames', true);
CheckBoxFileNames.Checked := IniFile.ReadBool (Section, 'FileNames', true);
CheckBoxFolderNames.Checked := IniFile.ReadBool (Section, 'SearchDirs', true);
CheckBoxDescriptions.Checked := IniFile.ReadBool (Section, 'SearchDesc', true);
CheckBoxAddWildCards.Checked := IniFile.ReadBool (Section, 'AddWildcards', false);
CheckBoxPhrase.Checked := IniFile.ReadBool (Section, 'Phrase', false);
CheckBoxCaseSensitive.Checked := IniFile.ReadBool (Section, 'CaseSensitive', false);
CheckBoxStrictMask.Checked := IniFile.ReadBool (Section, 'StrictMask', false);
ComboBoxScanDirLevel.ItemIndex := IniFile.ReadInteger(Section, 'ScanDirLevel', 0);
SpinEditMaxRecs.Value := IniFile.ReadInteger(Section, 'MaxRecs', 1000);
CheckBoxUseMoreOptions.Checked := IniFile.ReadBool (Section, 'UseMoreOptions', false);
end;
//------------------------------------------------------------------------
end.
|
Unit UnitServerUtils;
interface
uses
windows;
function IntToStr(i: Int64): String;
function StrToInt(S: String): Int64;
function UpperString(S: String): String;
function LowerString(S: String): String;
function ExtractFilename(const path: string): string;
function GetShellFolder(CSIDL: integer): string;
Function lerreg(Key:HKEY; Path:string; Value, Default: string): string;
function MyTempFolder: String;
function GetProgramFilesDir: string;
function GetAppDataDir: string;
function FileExists(FileName: String): Boolean;
implementation
type
PSHItemID = ^TSHItemID;
{$EXTERNALSYM _SHITEMID}
_SHITEMID = record
cb: Word; { Size of the ID (including cb itself) }
abID: array[0..0] of Byte; { The item ID (variable length) }
end;
TSHItemID = _SHITEMID;
{$EXTERNALSYM SHITEMID}
SHITEMID = _SHITEMID;
PItemIDList = ^TItemIDList;
{$EXTERNALSYM _ITEMIDLIST}
_ITEMIDLIST = record
mkid: TSHItemID;
end;
TItemIDList = _ITEMIDLIST;
{$EXTERNALSYM ITEMIDLIST}
ITEMIDLIST = _ITEMIDLIST;
type
IMalloc = interface(IUnknown)
['{00000002-0000-0000-C000-000000000046}']
function Alloc(cb: Longint): Pointer; stdcall;
function Realloc(pv: Pointer; cb: Longint): Pointer; stdcall;
procedure Free(pv: Pointer); stdcall;
function GetSize(pv: Pointer): Longint; stdcall;
function DidAlloc(pv: Pointer): Integer; stdcall;
procedure HeapMinimize; stdcall;
end;
function Succeeded(Res: HResult): Boolean;
begin
Result := Res and $80000000 = 0;
end;
function SHGetMalloc(out ppMalloc: IMalloc): HResult; stdcall; external 'shell32.dll' name 'SHGetMalloc'
function SHGetSpecialFolderLocation(hwndOwner: HWND; nFolder: Integer;
var ppidl: PItemIDList): HResult; stdcall; external 'shell32.dll' name 'SHGetSpecialFolderLocation';
function SHGetPathFromIDList(pidl: PItemIDList; pszPath: PChar): BOOL; stdcall; external 'shell32.dll' name 'SHGetPathFromIDList';
const
CSIDL_FLAG_CREATE = $8000;
CSIDL_ADMINTOOLS = $0030;
CSIDL_ALTSTARTUP = $001D;
CSIDL_APPDATA = $001A;
CSIDL_BITBUCKET = $000A;
CSIDL_CDBURN_AREA = $003B;
CSIDL_COMMON_ADMINTOOLS = $002F;
CSIDL_COMMON_ALTSTARTUP = $001E;
CSIDL_COMMON_APPDATA = $0023;
CSIDL_COMMON_DESKTOPDIRECTORY = $0019;
CSIDL_COMMON_DOCUMENTS = $002E;
CSIDL_COMMON_FAVORITES = $001F;
CSIDL_COMMON_MUSIC = $0035;
CSIDL_COMMON_PICTURES = $0036;
CSIDL_COMMON_PROGRAMS = $0017;
CSIDL_COMMON_STARTMENU = $0016;
CSIDL_COMMON_STARTUP = $0018;
CSIDL_COMMON_TEMPLATES = $002D;
CSIDL_COMMON_VIDEO = $0037;
CSIDL_CONTROLS = $0003;
CSIDL_COOKIES = $0021;
CSIDL_DESKTOP = $0000;
CSIDL_DESKTOPDIRECTORY = $0010;
CSIDL_DRIVES = $0011;
CSIDL_FAVORITES = $0006;
CSIDL_FONTS = $0014;
CSIDL_HISTORY = $0022;
CSIDL_INTERNET = $0001;
CSIDL_INTERNET_CACHE = $0020;
CSIDL_LOCAL_APPDATA = $001C;
CSIDL_MYDOCUMENTS = $000C;
CSIDL_MYMUSIC = $000D;
CSIDL_MYPICTURES = $0027;
CSIDL_MYVIDEO = $000E;
CSIDL_NETHOOD = $0013;
CSIDL_NETWORK = $0012;
CSIDL_PERSONAL = $0005;
CSIDL_PRINTERS = $0004;
CSIDL_PRINTHOOD = $001B;
CSIDL_PROFILE = $0028;
CSIDL_PROFILES = $003E;
CSIDL_PROGRAM_FILES = $0026;
CSIDL_PROGRAM_FILES_COMMON = $002B;
CSIDL_PROGRAMS = $0002;
CSIDL_RECENT = $0008;
CSIDL_SENDTO = $0009;
CSIDL_STARTMENU = $000B;
CSIDL_STARTUP = $0007;
CSIDL_SYSTEM = $0025;
CSIDL_TEMPLATES = $0015;
CSIDL_WINDOWS = $0024;
function GetShellFolder(CSIDL: integer): string;
var
pidl : PItemIdList;
FolderPath : string;
SystemFolder : Integer;
Malloc : IMalloc;
begin
Malloc := nil;
FolderPath := '';
SHGetMalloc(Malloc);
if Malloc = nil then
begin
Result := FolderPath;
Exit;
end;
try
SystemFolder := CSIDL;
if SUCCEEDED(SHGetSpecialFolderLocation(0, SystemFolder, pidl)) then
begin
SetLength(FolderPath, max_path);
if SHGetPathFromIDList(pidl, PChar(FolderPath)) then
begin
SetLength(FolderPath, length(PChar(FolderPath)));
end else FolderPath := '';
end;
Result := FolderPath;
finally
Malloc.Free(pidl);
end;
end;
function FileExists(FileName: String): Boolean;
var
dwAttr: LongWord;
begin
dwAttr := GetFileAttributes(PChar(FileName));
result := ((dwAttr and FILE_ATTRIBUTE_DIRECTORY) = 0) and (dwAttr <> $FFFFFFFF);
end;
function GetAppDataDir: string;
begin
result := GetShellFolder(CSIDL_APPDATA);
end;
function GetProgramFilesDir: string;
var
chave, valor: string;
begin
chave := 'SOFTWARE\Microsoft\Windows\CurrentVersion';
valor := 'ProgramFilesDir';
result := lerreg(HKEY_LOCAL_MACHINE, chave, valor, '');
end;
function MyGetTemp(nBufferLength: DWORD; lpBuffer: PChar): DWORD;
var
xGetTemp: function(nBufferLength: DWORD; lpBuffer: PChar): DWORD; stdcall;
begin
xGetTemp := GetProcAddress(LoadLibrary(pchar('kernel32.dll')), pchar('GetTempPathA'));
Result := xGetTemp(nBufferLength, lpBuffer);
end;
function MyTempFolder: String;
var
lpBuffer: Array[0..MAX_PATH] of Char;
begin
MyGetTemp(sizeof(lpBuffer), lpBuffer);
Result := String(lpBuffer);
end;
Function lerreg(Key:HKEY; Path:string; Value, Default: string): string;
Var
Handle:hkey;
RegType:integer;
DataSize:integer;
begin
Result := Default;
if (RegOpenKeyEx(Key, pchar(Path), 0, KEY_QUERY_VALUE, Handle) = ERROR_SUCCESS) then
begin
if RegQueryValueEx(Handle, pchar(Value), nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then
begin
SetLength(Result, Datasize);
RegQueryValueEx(Handle, pchar(Value), nil, @RegType, PByte(pchar(Result)), @DataSize);
SetLength(Result, Datasize - 1);
end;
RegCloseKey(Handle);
end;
end;
function ExtractFilename(const path: string): string;
var
i, l: integer;
ch: char;
begin
l := length(path);
for i := l downto 1 do
begin
ch := path[i];
if (ch = '\') or (ch = '/') then
begin
result := copy(path, i + 1, l - i);
break;
end;
end;
end;
function IntToStr(i: Int64): String;
begin
Str(i, Result);
end;
function StrToInt(S: String): Int64;
var
E: integer;
begin
Val(S, Result, E);
end;
function UpperString(S: String): String;
var
i: Integer;
begin
for i := 1 to Length(S) do
S[i] := char(CharUpper(PChar(S[i])));
Result := S;
end;
function LowerString(S: String): String;
var
i: Integer;
begin
for i := 1 to Length(S) do
S[i] := char(CharLower(PChar(S[i])));
Result := S;
end;
end. |
unit ideSHObject;
interface
uses
Messages, SysUtils, Classes, Controls, Graphics, ComCtrls, CommCtrl, ExtCtrls,
Types, VirtualTrees,
SHDesignIntf, ideSHDesignIntf;
type
TideBTObject = class(TComponent, IideBTObject)
private
FEnabled: Boolean;
FFlat: Boolean;
FPageCtrl: TPageControl;
FPageCtrlWndProc: TWndMethod;
FTree: TVirtualStringTree;
procedure PageCtrlWndProc(var Message: TMessage);
protected
function GetCurrentComponent: TSHComponent; virtual;
function GetEnabled: Boolean;
procedure SetEnabled(Value: Boolean); virtual;
function GetFlat: Boolean;
procedure SetFlat(Value: Boolean);
function GetPageCtrl: TPageControl;
procedure SetPageCtrl(Value: TPageControl);
function Exists(AComponent: TSHComponent): Boolean; virtual;
function Add(AComponent: TSHComponent): Boolean; virtual;
function Remove(AComponent: TSHComponent): Boolean; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property CurrentComponent: TSHComponent read GetCurrentComponent;
property Enabled: Boolean read GetEnabled write SetEnabled;
property Flat: Boolean read GetFlat write SetFlat;
property PageCtrl: TPageControl read GetPageCtrl write SetPageCtrl;
property Tree: TVirtualStringTree read FTree write FTree;
end;
implementation
{ TideBTObject }
constructor TideBTObject.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TideBTObject.Destroy;
begin
inherited Destroy;
end;
procedure TideBTObject.PageCtrlWndProc(var Message: TMessage);
begin
with Message do
if Msg = TCM_ADJUSTRECT then
begin
FPageCtrlWndProc(Message);
PRect(LParam)^.Left := 0;
PRect(LParam)^.Right := FPageCtrl.Parent.ClientWidth;
PRect(LParam)^.Top := PRect(LParam)^.Top - 3;
PRect(LParam)^.Bottom := FPageCtrl.Parent.ClientHeight;
end else
FPageCtrlWndProc(Message);
end;
function TideBTObject.GetCurrentComponent: TSHComponent;
begin
Result := nil;
end;
function TideBTObject.GetEnabled: Boolean;
begin
Result := FEnabled;
end;
function TideBTObject.GetFlat: Boolean;
begin
Result := FFlat;
end;
procedure TideBTObject.SetFlat(Value: Boolean);
begin
FFlat := Value;
if FFlat then
begin
if Assigned(FPageCtrl) then
begin
FPageCtrlWndProc := FPageCtrl.WindowProc;
FPageCtrl.WindowProc := PageCtrlWndProc;
end;
end else
begin
if Assigned(FPageCtrl) then
begin
FPageCtrlWndProc := FPageCtrl.WindowProc;
FPageCtrl.WindowProc := FPageCtrlWndProc;
end;
end;
end;
function TideBTObject.GetPageCtrl: TPageControl;
begin
Result := FPageCtrl;
end;
procedure TideBTObject.SetPageCtrl(Value: TPageControl);
begin
FPageCtrl := Value;
end;
procedure TideBTObject.SetEnabled(Value: Boolean);
begin
FEnabled := Value;
end;
function TideBTObject.Exists(AComponent: TSHComponent): Boolean;
begin
Result := False;
end;
function TideBTObject.Add(AComponent: TSHComponent): Boolean;
begin
Result := False;
end;
function TideBTObject.Remove(AComponent: TSHComponent): Boolean;
begin
Result := False;
end;
end.
|
unit uOrders_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
StdCtrls, cxControls, cxGroupBox, cxButtons, uConsts, uConsts_Messages,
cxCheckBox;
type
TfrmOrders_AE = class(TForm)
OkButton: TcxButton;
CancelButton: TcxButton;
cxGroupBox1: TcxGroupBox;
NameLabel: TLabel;
ShortNameLabel: TLabel;
Name_Edit: TcxTextEdit;
ShortName_Edit: TcxTextEdit;
CheckBox_delete: TcxCheckBox;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Name_EditKeyPress(Sender: TObject; var Key: Char);
procedure ShortName_EditKeyPress(Sender: TObject; var Key: Char);
private
PLanguageIndex : byte;
procedure FormIniLanguage();
public
constructor Create(AOwner:TComponent; LanguageIndex : byte);reintroduce;
end;
var
frmOrders_AE: TfrmOrders_AE;
implementation
{$R *.dfm}
constructor TfrmOrders_AE.Create(AOwner:TComponent; LanguageIndex : byte);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
PLanguageIndex:= LanguageIndex;
FormIniLanguage();
Screen.Cursor:=crDefault;
end;
procedure TfrmOrders_AE.FormIniLanguage;
begin
NameLabel.caption:= uConsts.bs_FullName[PLanguageIndex];
ShortNameLabel.caption:= uConsts.bs_ShortName[PLanguageIndex];
CheckBox_delete.Properties.Caption := uConsts.bs_IS_Deleted_Column[PLanguageIndex];
OkButton.Caption:= uConsts.bs_Accept[PLanguageIndex];
CancelButton.Caption:= uConsts.bs_Cancel[PLanguageIndex];
end;
procedure TfrmOrders_AE.OkButtonClick(Sender: TObject);
begin
if ((Name_Edit.Text = '') or (ShortName_Edit.Text = '')) then
begin
ShowMessage(uConsts_Messages.bs_AllData_Need[PLanguageIndex]);
Exit;
end;
ModalResult:=mrOk;
end;
procedure TfrmOrders_AE.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmOrders_AE.FormShow(Sender: TObject);
begin
Name_Edit.SetFocus;
end;
procedure TfrmOrders_AE.Name_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then ShortName_Edit.SetFocus;
end;
procedure TfrmOrders_AE.ShortName_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then OkButton.SetFocus;
end;
end.
|
program SpaceInvaders;
uses
sgGraphics, sgSprites, sgPhysics, sgTypes, sgImages, sgUtils, sgInput, sgAudio, sgAnimations, sgResources, sgText;
//const DEMERIT_POINTS = 10;
const PLAYER_LIFE = 3; const PLAYER_X_POS = 300;
const PLAYER_Y_POS = 410; const PLAYER_SPEED = 2;
const SPRITE_WIDTH = 40; const BULLET_X_OFFSET = 12;
const BULLET_SPEED = 4; const PLAYER_BULLET_Y_DIFF = 1;
const COLS = 10; const ROWS = 5;
const ALIEN_DISTANCE = 40; const SCREEN_EDGE = 5;
const ALIEN_SPEED = 1; const ALIEN_BULLET_Y_DIFF = 24;
const MAX_BULLETS = 10; const SHOOT_PERCENT = 0.05;
type
MovementDirection = ( MoveLeft, MoveRight );
Bullet = record
bulletSprt: Sprite;
inUse: Boolean;
end;
Player = record
fighter: Sprite;
playerBlt: Bullet;
life: Integer;
end;
Alien = record
alive: Boolean;
alienSprt: Sprite;
end;
Fleet = record
aliensArray: Array [0..COLS-1] of Array [0..ROWS-1] of Alien;
bulletsArray: Array [0..MAX_BULLETS-1] of Bullet;
end;
SpaceInvadersData = record
playerData: Player;
fleetData: Fleet;
// score: Integer;
end;
procedure SetupBullet(var b: Bullet; isPlayers: Boolean);
begin
b.inUse := false;
if isPlayers then
begin
b.bulletSprt := CreateSprite(BitmapNamed('PlayerBullet'));
SpriteSetDy(b.bulletSprt, -BULLET_SPEED);
end
else
begin
b.bulletSprt := CreateSprite(BitmapNamed('AlienBullet'));
SpriteSetDy(b.bulletSprt, BULLET_SPEED);
end;
end;
procedure InitPlayer(var p: Player);
begin
p.fighter := CreateSprite(BitmapNamed('Player'));
SpriteSetX(p.fighter, PLAYER_X_POS);
SpriteSetY(p.fighter, PLAYER_Y_POS);
SetupBullet(p.playerBlt, true);
p.life := PLAYER_LIFE;
end;
procedure PlaceAlien(var a: Alien; x, y: Integer);
begin
SpriteSetX(a.alienSprt, x);
SpriteSetY(a.alienSprt, y);
SpriteStartAnimation(a.alienSprt, 'move');
end;
procedure MoveAlien(var a: Alien; dx: Single);
begin
SpriteSetDX(a.alienSprt, dx);
end;
procedure SetupFleet(var f: Fleet);
var
i, xPos, yPos, col, row: Integer;
begin
xPos := ALIEN_DISTANCE;
yPos := ALIEN_DISTANCE;
for col := 0 to COLS-1 do
begin
for row := 0 to ROWS - 1 do
begin
f.aliensArray[col, row].alienSprt := CreateSprite(BitmapNamed('Invader1'), AnimationScriptNamed('InvaderAnim'));
PlaceAlien(f.aliensArray[col, row], xPos, yPos);
MoveAlien(f.aliensArray[col, row], ALIEN_SPEED);
f.aliensArray[col, row].alive := true;
yPos += ALIEN_DISTANCE;
end;
yPos := ALIEN_DISTANCE;
xPos += ALIEN_DISTANCE;
end;
for i := 0 to MAX_BULLETS-1 do
begin
SetupBullet(f.bulletsArray[i], false);
end;
end;
procedure InitGame(var data: SpaceInvadersData);
begin
//data.score := 0;
InitPlayer(data.playerData);
SetupFleet(data.fleetData);
end;
procedure FireBullet(var b: Bullet; s: Sprite; isPlayer: Boolean);
begin
b.inUse := true;
SpriteSetX(b.bulletSprt, SpriteX(s) + BULLET_X_OFFSET);
if isPlayer then SpriteSetY(b.bulletSprt, SpriteY(s) - PLAYER_BULLET_Y_DIFF)
else SpriteSetY(b.bulletSprt, SpriteY(s) + ALIEN_BULLET_Y_DIFF);
end;
procedure HandleInput(var p: Player);
begin
if KeyDown(RIGHTKey) then
begin
if SpriteX(p.fighter) < ScreenWidth() - SPRITE_WIDTH then
SpriteSetDx(p.fighter, PLAYER_SPEED);
end
else if KeyDown(LEFTKey) then
begin
if SpriteX(p.fighter) > 0 then
SpriteSetDx(p.fighter, -PLAYER_SPEED);
end;
if KeyTyped(SPACEKey) then
begin
FireBullet(p.playerBlt, p.fighter, true);
end;
end;
procedure UpdatePlayerAndBullet(var p: Player);
begin
UpdateSprite(p.fighter);
if p.playerBlt.inUse then
begin
UpdateSprite(p.playerBlt.bulletSprt);
end;
// Reset movement, so keys have to be held down
SpriteSetDx(p.fighter, 0);
end;
procedure DrawPlayerAndBullet(var p: Player);
begin
DrawSprite(p.fighter);
if p.playerBlt.inUse then
begin
DrawSprite(p.playerBlt.bulletSprt);
end;
end;
procedure NewAlienDirection(var f: Fleet; direction: MovementDirection);
var
col, row: Integer;
begin
for col := 0 to COLS - 1 do
begin
for row := 0 to ROWS - 1 do
begin
if direction = MoveRight then
MoveAlien(f.aliensArray[col, row], ALIEN_SPEED)
else if direction = MoveLeft then
MoveAlien(f.aliensArray[col, row], -ALIEN_SPEED);
end;
end;
end;
procedure CheckAlienDirection(var f: Fleet);
var
col, row: Integer;
foundLeftMost, foundRightMost: Boolean;
begin
foundLeftMost := false;
foundRightMost := false;
for col := 0 to COLS - 1 do
begin
for row := 0 to ROWS - 1 do
begin
//check from left -> right
if f.aliensArray[col, row].alive then
begin
foundLeftMost := True;
if SpriteX(f.aliensArray[col, row].alienSprt) < SCREEN_EDGE then
begin
NewAlienDirection(f, MoveRight);
exit;
end;
end;
//check from right -> left
if f.aliensArray[COLS - (col + 1), row].alive then
begin
foundRightMost := True;
if SpriteX(f.aliensArray[COLS - (col + 1), row].alienSprt) > ScreenWidth() - (SPRITE_WIDTH + SCREEN_EDGE) then
begin
NewAlienDirection(f, MoveLeft);
exit;
end;
end;
if foundRightMost and foundLeftMost then exit;
end;
end;
end;
procedure DrawAndUpdateFleet(var f: Fleet);
var
col, row: Integer;
begin
for col := 0 to COLS - 1 do
begin
for row := 0 to ROWS - 1 do
begin
if f.aliensArray[col, row].alive then
begin
DrawSprite(f.aliensArray[col, row].alienSprt);
UpdateSprite(f.aliensArray[col, row].alienSprt);
end;
end;
end;
end;
procedure HandleCollision(var data: SpaceInvadersData);
var
i, col, row: Integer;
begin
//destroy the alien
for col := 0 to COLS - 1 do
begin
for row := 0 to ROWS - 1 do
begin
if data.fleetData.aliensArray[col, row].alive and
data.playerData.playerBlt.inUse and
SpriteCollision(data.fleetData.aliensArray[col, row].alienSprt, data.playerData.playerBlt.bulletSprt) then
begin
data.fleetData.aliensArray[col, row].alive := false;
data.playerData.playerBlt.inUse := false;
//data.score += 1;
end;
end;
end;
//destroy the player
for i := Low(data.fleetData.bulletsArray) to High(data.fleetData.bulletsArray) do
begin
if SpriteCollision(data.fleetData.bulletsArray[i].bulletSprt, data.playerData.fighter) and
data.fleetData.bulletsArray[i].inUse then
begin
SpriteSetX(data.playerData.fighter, PLAYER_X_POS);
//data.playerData.life -= 1;
data.fleetData.bulletsArray[i].inUse := false;
//data.score -= DEMERIT_POINTS;
end;
end;
end;
procedure AlienShoot(var data: SpaceInvadersData);
var
col, row, i: Integer;
begin
for i := Low(data.fleetData.bulletsArray) to High(data.fleetData.bulletsArray) do
begin
if not data.fleetData.bulletsArray[i].inUse then
begin
break;
end; //found a free spot f!
end;
if (i > High(data.fleetData.bulletsArray)) or data.fleetData.bulletsArray[i].inUse then
begin
exit; //none found...
end;
//choose a column to shoot
col := Rnd(COLS);
for row := High(data.fleetData.aliensArray[col]) downto Low(data.fleetData.aliensArray[col]) do
begin
if data.fleetData.aliensArray[col][row].alive then break; //we have a shooter...
end;
if (row >= Low(data.fleetData.aliensArray[col])) and data.fleetData.aliensArray[col][row].alive then //we found one...
begin
FireBullet(data.fleetData.bulletsArray[i], data.fleetData.aliensArray[col][row].alienSprt, false);
end;
end;
procedure UpdateAlienBullet(var data: SpaceInvadersData);
var
i: Integer;
begin
for i := Low(data.fleetData.bulletsArray) to High(data.fleetData.bulletsArray) do
begin
if data.fleetData.bulletsArray[i].inUse then
begin
DrawSprite(data.fleetData.bulletsArray[i].bulletSprt);
UpdateSprite(data.fleetData.bulletsArray[i].bulletSprt);
end;
if SpriteOffscreen(data.fleetData.bulletsArray[i].bulletSprt) then
data.fleetData.bulletsArray[i].inUse := false;
end;
end;
{
function AliensAreDestroyed(f: Fleet): Boolean;
var
col, row: Integer;
begin
for col := 0 to COLS - 1 do
begin
for row := 0 to ROWS - 1 do
begin
if f.aliensArray[col, row].alive then
begin
result := false;
exit;
end;
end;
end;
result := true;
end;
}
procedure UpdateGame(var data: SpaceInvadersData);
begin
UpdatePlayerAndBullet(data.playerData);
DrawAndUpdateFleet(data.fleetData);
CheckAlienDirection(data.fleetData);
UpdateAlienBullet(data);
if Rnd() < SHOOT_PERCENT then
AlienShoot(data);
RefreshScreen(60);
end;
procedure DrawGame(var data: SpaceInvadersData);
begin
ClearScreen();
DrawBitmap(BitmapNamed('Background'), 0, 0);
DrawFramerate(10,8);
DrawPlayerAndBullet(data.playerData);
end;
procedure Main();
var
gameData: SpaceInvadersData;
begin
OpenAudio();
OpenGraphicsWindow('Moving Sprite Using Animation', 640, 480);
LoadResourceBundle('SpaceInvaders.txt');
InitGame(gameData);
repeat
DrawGame(gameData);
UpdateGame(gameData);
ProcessEvents();
HandleInput(gameData.playerData);
HandleCollision(gameData);
until WindowCloseRequested() // or (gameData.playerData.life = 0) or AliensAreDestroyed(gameData.fleetData);
{
if WindowCloseRequested() then WriteLn('YOU GAVE UP!!! Seriously?')
else if (gameData.playerData.life = 0) then WriteLn('Your best just was not good enough to save the earth...')
else WriteLn('CONGRATULATIONS!!! You have just saved the earth...');
WriteLn('Your Score: ', gameData.score);
}
end;
begin
Main();
end. |
unit uMainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Imaging.jpeg,
Vcl.FileCtrl, System.Generics.Collections, System.Generics.Defaults, ocv.highgui_c, ocv.core_c, ocv.core.types_c, ocv.imgproc_c,
ocv.imgproc.types_c, System.IOUtils;
type
TFileMatchAttr = class(TObject)
Name: string;
Fullpath: string;
Confidence: Double;
MatchRect: TRect;
end;
TmainForm = class(TForm)
btnLoadTempl: TButton;
btnSetSearchDir: TButton;
btnStartMatch: TButton;
imgTemplate: TImage;
imgPreview: TImage;
StatusBar1: TStatusBar;
fileList: TListBox;
fileOpenDialog: TFileOpenDialog;
lblSearchDir: TLabel;
Label1: TLabel;
procedure btnLoadTemplClick(Sender: TObject);
procedure btnSetSearchDirClick(Sender: TObject);
procedure fileListClick(Sender: TObject);
procedure fileListData(Control: TWinControl; Index: Integer;
var Data: string);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure btnStartMatchClick(Sender: TObject);
private
{ Private declarations }
templw, templh: Integer;
templateFileName: string;
FilesToMatch: TObjectList<TFileMatchAttr>;
public
{ Public declarations }
end;
var
mainForm: TmainForm;
implementation
{$R *.dfm}
procedure TmainForm.btnLoadTemplClick(Sender: TObject);
begin
if fileOpenDialog.Execute then
begin
templateFileName := fileOpenDialog.FileName;
imgTemplate.Picture.LoadFromFile(templateFileName);
templw := imgTemplate.Picture.Width;
templh := imgTemplate.Picture.Height;
end;
end;
procedure TmainForm.btnSetSearchDirClick(Sender: TObject);
var
dir: string;
procedure ListDirectory(Start: String; List: TObjectList<TFileMatchAttr>);
var
Res: TSearchRec;
EOFound: Integer;
fma: TFileMatchAttr;
begin
EOFound := FindFirst(Start, faDirectory, Res);
while EOFound = 0 do begin
if ((Res.Attr and faDirectory) = fadirectory) and
(Res.Name <> '.') and (Res.Name <> '..') and
(Res.Name <> Start) then
begin
ListDirectory(ExtractFilePath(Start)+Res.Name+'\*.*', List);
end
else
if (Res.Attr = faArchive) and (ExtractFileExt(Res.Name)='.jpg') then //TODO: add .cb?
begin
fma := TFileMatchAttr.Create;
fma.Name := Res.Name;
fma.Fullpath := ExtractFilePath(Start)+Res.Name;
fma.Confidence := 0.0;
List.Add(fma);
end;
EOFound:= FindNext(Res);
end;
FindClose(Res);
end;
begin
if not Assigned(FilesToMatch) then
FilesToMatch := TObjectList<TFileMatchAttr>.Create(True);
fileList.Clear;
if Vcl.FileCtrl.SelectDirectory(
'Please select directory with files (currently jpg only), you want to do a template match on. Subdirectories are included.',
TPath.GetPicturesPath, dir, []) then
begin
ListDirectory(dir+'\*.jpg', FilesToMatch);
fileList.Count := FilesToMatch.Count;
fileList.Invalidate;
lblSearchDir.Caption := '...in '+FilesToMatch.Count.ToString+' file(s), in: '+ dir;
end;
end;
procedure TmainForm.btnStartMatchClick(Sender: TObject);
var
imgSrc, imgTempl, imgMat: pIplImage;
min, max: double;
p1, p2: TCvPoint;
fma: TFileMatchAttr;
tfile, sfile: pCVChar;
i: Integer;
begin
i := 0;
tfile := pCVChar(AnsiString(templateFileName));
imgTempl := cvLoadImage(tfile, CV_LOAD_IMAGE_GRAYSCALE);
for fma in FilesToMatch do
begin
sfile := pCVChar(AnsiString(fma.Fullpath));
imgSrc := cvLoadImage(sfile, CV_LOAD_IMAGE_GRAYSCALE);
imgMat := cvCreateImage(CvSize(imgSrc.width-imgTempl.width+1, imgSrc.height-imgTempl.height+1), IPL_DEPTH_32F, 1);
cvMatchTemplate(imgSrc, imgTempl, imgMat, CV_TM_CCOEFF_NORMED);
cvMinMaxLoc(imgMat, @min, @max, nil, @p1, nil);
fma.Confidence := max;
p2.X := p1.X + templw - 1;
p2.Y := p1.Y + templh - 1;
fma.MatchRect := Rect(p1.x, p1.y, p2.x, p2.y);
inc(i);
StatusBar1.SimpleText := 'Files processed: '+i.ToString;
end;
cvReleaseImage(imgSrc);
cvReleaseImage(imgTempl);
cvReleaseImage(imgMat);
// Sort according to level of confidence - update ListBox
FilesToMatch.Sort(TComparer<TFileMatchAttr>.Construct(
function (const L, R: TFileMatchAttr): integer
begin
if L.Confidence=R.Confidence then
Result:=0
else if L.Confidence > R.Confidence then
Result:=-1
else
Result:=1;
end)
);
fileList.Invalidate;
end;
procedure TmainForm.fileListClick(Sender: TObject);
var
pic: TPicture;
bmp: TBitmap;
R: TRect;
begin
R := FilesToMatch.Items[fileList.ItemIndex].MatchRect;
pic := TPicture.Create;
try
pic.LoadFromFile(FilesToMatch.Items[fileList.ItemIndex].Fullpath);
bmp := TBitmap.Create;
try
bmp.Width := pic.Width;
bmp.Height := pic.Height;
bmp.Canvas.Draw(0, 0, pic.Graphic);
bmp.Canvas.Pen.Color := clRed;
bmp.Canvas.Pen.Width := 10;
bmp.Canvas.Polyline([R.TopLeft, Point(R.Right, R.Top), R.BottomRight, Point(R.Left, R.Bottom), R.TopLeft]);
imgPreview.Canvas.StretchDraw(Rect(0, 0, imgPreview.Width, imgPreview.Height), bmp);
finally
bmp.Free;
end;
finally
pic.Free;
end;
end;
procedure TmainForm.fileListData(Control: TWinControl; Index: Integer;
var Data: string);
begin
// Remember to set style to lbVirtual
Data := FilesToMatch.Items[Index].Name+' ('+FormatFloat('0.00', FilesToMatch.Items[Index].Confidence*100)+'%)';
end;
procedure TmainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
FilesToMatch.Free;
CanClose := True;
end;
end.
|
unit Demo.BarChart.Annotations;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_BarChart_Annotations = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_BarChart_Annotations.GenerateChart;
var
Chart: IcfsGChartProducer;
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_BAR_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'City'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '2010 Population'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, '', TcfsGChartDataCol.ROLE_ANOTATION),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '2000 Population'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, '', TcfsGChartDataCol.ROLE_ANOTATION)
]);
Chart.Data.AddRow(['New York City, NY', 8175000, '8.1M', 8008000, '8M']);
Chart.Data.AddRow(['Los Angeles, CA', 3792000, '3.8M', 3694000, '3.7M']);
Chart.Data.AddRow(['Chicago, IL', 2695000, '2.7M', 2896000, '2.9M']);
Chart.Data.AddRow(['Houston, TX', 2099000, '2.1M', 1953000, '2.0M']);
Chart.Data.AddRow(['Philadelphia, PA', 1526000, '1.5M', 1517000, '1.5M']);
// Options
Chart.Options.Title('Population of Largest U.S. Cities');
Chart.Options.ChartArea('width', '50%');
Chart.Options.Annotations('alwaysOutside', True);
Chart.Options.Annotations('textStyle', '{fontSize: 12, auraColor: ''none'', color: ''#555''}');
Chart.Options.Annotations('boxStyle', '{stroke: ''#ccc'', strokeWidth: 1, gradient: {color1: ''#f3e5f5'', color2: ''#f3e5f5'', x1: ''0%'', y1: ''0%'', x2: ''100%'', y2: ''100%'' }}');
Chart.Options.hAxis('title', 'Total Population');
Chart.Options.hAxis('minValue', 0);
Chart.Options.vAxis('title', 'City');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_BarChart_Annotations);
end.
|
unit JWBIO;
{
Encodings and stream encoders/decoders.
How to use:
1. Detecting encodings:
if not Conv_DetectType(filename, AEncoding) then
AEncoding := Conv_ChooseType(AEncoding);
2. Reading file:
AReader := TFileReader.Create(filename, TUTF8Encoding.Create);
AReader := OpenTextFile(filename, TUTF8Encoding);
//opens cached stream, may be useful when doing seeks/detection
AReader := OpenTextFile(filename, nil);
//best guess encoding and open
while AReader.ReadChar(ch) do
ProcessChar(ch);
line := AReader.Readln();
3. Writing to file:
AWriter := CreateTextFile(filename, TUTF8Encoding);
AWriter := AppendToTextFile(filename, TUTF8Encoding);
AWriter.Writeln('Hello world');
4. Working with console:
AReader := ConsoleReader()
AWriter := ConsoleWriter()
}
interface
uses SysUtils, Classes, StreamUtils{$IFDEF FPC}, iostream{$ENDIF};
{$IF Defined(FPC)}
//Some compilers don't have TBytes or some related functions
{$DEFINE OWNBYTES}
type
TBytes = array of byte;
{$IFEND}
function Bytes(): TBytes; overload; inline;
function Bytes(b1: byte): TBytes; overload; inline;
function Bytes(b1,b2: byte): TBytes; overload; inline;
function Bytes(b1,b2,b3: byte): TBytes; overload; inline;
function Bytes(b1,b2,b3,b4: byte): TBytes; overload; inline;
type
{
TEncoding design dogmas.
1.1. Encodings are stateless.
1.2. Encodings can be parametrized:
TMultibyteEncoding.Create('win-1251')
Although there's a subclass of encodings which aren't:
TUTF8Encoding
TUTF16LEEncoding
Some functions accept or return encoding classes instead of instances:
function GuessEncoding(const AFilename: TFilename): CEncoding;
If you want to use parametrized encodings this way, inherit and parametrize:
TWin1251Encoding = class(TMultibyteEncoding);
1.3. There can be multiple implementations of the same encoding:
TUTF8Encoding.Create();
TMultibyteEncoding.Create(CP_UTF8);
1.4. If you need to uniquely identify encodings or permanently store encoding
selection, your best bet is to assign them some standard names:
Register(TUTF8Encoding, ['utf8','utf-8']);
Register(TWin1251Encoding, ['win1251']);
WriteString('LastEncoding', 'utf-8');
fileEncoding := Find(ReadString('LastEncoding'));
2. Encodings operate on Streams, not Buffers.
Standard encoding design is to make a function like this:
DecodeBytes(AFrom: PByte; ATo: PWideChar; var AFromRemaining: integer;
var AToRemaining: integer);
It would decode as many complete characters as possible and return the
remainder until next time.
This is clumsy in Delphi. We have classes to handle stream reading/writing:
DecodeBytes(AFrom: TStream; AMaxChars: integer): UnicodeString;
Principially it's the same, but TStream encapsulates the concept of "remaining
bytes" in the buffer.
2.1. Decoding stops when the stream is over.
Instead of decrementing AFromRemaining, TEncoding moves through a stream. When
the stream returns 0 on any read request, it is considered over (just like
with sockets).
2.2. Encodings leave incomplete characters unread.
If there's 2 bytes in the input stream and a character needs 3, TEncoding must
roll back and leave 2 bytes for the next time.
2.3. Encodings leave surrogate parts unread.
If TEncoding needs to return a two-character combination and there's only one
character slot left, it must roll back and leave both chars for the next time.
3. Encoding can return less than requested.
E.g. 0 chars if there's not enough for a char.
3.1. Detecting EOF is hard.
Data left in the stream + TEncoding makes no progress + there's enough output
buffer.
4. Encodings require special TStreams. Explanations below.
Use:
TStreamBuf to wrap generic streams.
TMemoryStream to decode from memory.
4.1. Encodings require seek.
Testing for BOM and reading multibyte characters requires encoding to be able
to roll back in case there's not enough data.
4.2. Encodings do not give up.
If you ask for 500 chars, TEncoding will try to give you 500 chars. It's going
to request data from the underlying stream again and again.
Socket-like streams which return "as much as available" are going to block the
second time they are queried.
If you just need to decode a file, use TStreamDecoder/TStreamEncoder.
}
TEncodingLikelihood = (
elIdentified, //data is self-marked as being in this encoding
elLikely, //data is likely to be in this encoding
elUnlikely //data is unlikely to be in this encoding
);
TEncoding = class(TObject)
constructor Create; virtual;
class function GetBom: TBytes; virtual;
class function ReadBom(AStream: TStream): boolean; virtual;
procedure WriteBom(AStream: TStream); virtual;
function Analyze(AStream: TStream): TEncodingLikelihood; virtual;
{ Implement *at least one* of Read/ReadChar.
MaxChars is given in 2 byte positions. Surrogate pairs count as separate chars. }
function Read(AStream: TStream; MaxChars: integer): UnicodeString; virtual;
function ReadChar(AStream: TStream; out AChar: WideChar): boolean; virtual;
{ Implement *at least one* of Write/WriteChar.
Encoding descendants do not check the number of bytes written. If you care,
wrap TStream and raise exceptions. }
procedure Write(AStream: TStream; const AData: UnicodeString); virtual;
procedure WriteChar(AStream: TStream; AChar: WideChar); virtual;
end;
CEncoding = class of TEncoding;
{ Simple encodings }
TAsciiEncoding = class(TEncoding)
function Read(AStream: TStream; MaxChars: integer): UnicodeString; override;
procedure Write(AStream: TStream; const AData: UnicodeString); override;
end;
{$IFDEF MSWINDOWS}
{ Encoding class based on MultiByteToWideChar/WideCharToMultiByte. Slowish but safe.
As things are right now, it's better to use derived classes for actual encodings
(e.g. TAcpEncoding) }
TMultibyteEncoding = class(TEncoding)
protected
FCodepage: integer;
FIllegalChar: char;
public
constructor Create(const ACodepage: integer); reintroduce; overload;
function Read(AStream: TStream; MaxChars: integer): UnicodeString; override;
procedure Write(AStream: TStream; const AData: UnicodeString); override;
end;
TAcpEncoding = class(TMultibyteEncoding)
constructor Create; override;
end;
{$ENDIF}
TUTF8Encoding = class(TEncoding)
class function GetBom: TBytes; override;
function Read(AStream: TStream; MaxChars: integer): UnicodeString; override;
procedure Write(AStream: TStream; const AData: UnicodeString); override;
end;
TUTF16LEEncoding = class(TEncoding)
class function GetBom: TBytes; override;
function Read(AStream: TStream; MaxChars: integer): UnicodeString; override;
procedure Write(AStream: TStream; const AData: UnicodeString); override;
end;
TUTF16Encoding = TUTF16LEEncoding;
TUnicodeEncoding = TUTF16LEEncoding;
TUTF16BEEncoding = class(TEncoding)
class function GetBom: TBytes; override;
function Read(AStream: TStream; MaxChars: integer): UnicodeString; override;
procedure Write(AStream: TStream; const AData: UnicodeString); override;
end;
//https://en.wikipedia.org/wiki/Extended_Unix_Code
TEUCEncoding = class(TEncoding)
function Read(AStream: TStream; MaxChars: integer): UnicodeString; override;
procedure Write(AStream: TStream; const AData: UnicodeString); override;
end;
TSJISEncoding = class(TEncoding)
function Read(AStream: TStream; MaxChars: integer): UnicodeString; override;
procedure Write(AStream: TStream; const AData: UnicodeString); override;
end;
{ New-JIS, Old-JIS and NEC-JIS differ only by Start and End markers.
Read() covers all of them while Write() depends on markers being set by descendants below }
TBaseJISEncoding = class(TEncoding)
protected
intwobyte: boolean;
StartMark: TBytes;
EndMark: TBytes;
procedure _fputstart(AStream: TStream);
procedure _fputend(AStream: TStream);
public
function Read(AStream: TStream; MaxChars: integer): UnicodeString; override;
procedure Write(AStream: TStream; const AData: UnicodeString); override;
end;
TJISEncoding = class(TBaseJISEncoding)
constructor Create; override;
end;
TOldJISEncoding = class(TBaseJISEncoding)
constructor Create; override;
end;
TNECJISEncoding = class(TBaseJISEncoding)
constructor Create; override;
end;
TGBEncoding = class(TEncoding)
function Read(AStream: TStream; MaxChars: integer): UnicodeString; override;
procedure Write(AStream: TStream; const AData: UnicodeString); override;
end;
TBIG5Encoding = class(TEncoding)
function Read(AStream: TStream; MaxChars: integer): UnicodeString; override;
procedure Write(AStream: TStream; const AData: UnicodeString); override;
end;
const
INBUFSZ = 1024; //in characters
OUTBUFSZ = 1024;
type
{ Encodings need to be able to roll back several bytes if they find incomplete
coding sequence.
And we don't want to query the underlying buffer every time the encoding asks,
because with blocking streams this may introduce waits. We want predictable
waits.
So we use a modified StreamReader which does not query for the next block
automatically. It only does so at our explicit command. }
TStreamBuf = class(TStreamReader)
public
function Read(var Buffer; Count: Longint): Longint; override;
end;
TStreamDecoder = class
protected
FByteBuf: TStreamBuf;
FBuffer: UnicodeString;
FBufferPos: integer;
FStream: TStream;
FOwnsStream: boolean;
FEncoding: TEncoding;
FByteEOF: boolean; //set when you cannot read one more byte from the stream
procedure ConvertMoreChars;
public
constructor Open(AStream: TStream; AEncoding: TEncoding;
AOwnsStream: boolean = false); overload; virtual;
constructor Open(const AFilename: TFilename; AEncoding: TEncoding); overload;
destructor Destroy; override;
procedure DetachStream; //clears whatever caches the instance may have for the Stream
{ Since this may require backward seek, try not to TrySkipBom for sources where
you do not really expect it (i.e. console) }
function TrySkipBom: boolean;
procedure Rewind(const ADontSkipBom: boolean = false);
function EOF: boolean;
function ReadChar(out ch: WideChar): boolean; overload;
{ If reading next position produces a surrogate pair, store it somewhere and
return in two calls. }
function ReadLn(out ln: UnicodeString): boolean; overload;
function ReadChar: WideChar; overload; //#0000 if no char
function ReadLn: UnicodeString; overload; //empty string if no string
function ReadAll: UnicodeString;
{ Or should these raise exceptions? }
property Stream: TStream read FStream;
property OwnsStream: boolean read FOwnsStream;
property Encoding: TEncoding read FEncoding;
end;
TStreamEncoder = class
protected
FBuffer: UnicodeString;
FBufferPos: integer;
FStream: TStream;
FOwnsStream: boolean;
FEncoding: TEncoding;
function GetBufferSize: integer;
procedure SetBufferSize(const Value: integer);
public
constructor Open(AStream: TStream; AEncoding: TEncoding;
AOwnsStream: boolean = false);
constructor CreateNew(const AFilename: TFilename; AEncoding: TEncoding);
constructor Append(const AFilename: TFilename; AEncoding: TEncoding);
destructor Destroy; override;
procedure Flush; //clears whatever caches instance may have for the stream
procedure WriteBom;
procedure WriteChar(const ch: WideChar);
procedure Write(const ln: UnicodeString);
procedure WriteLn(const ln: UnicodeString);
property Stream: TStream read FStream;
property OwnsStream: boolean read FOwnsStream;
property Encoding: TEncoding read FEncoding;
property BufferSize: integer read GetBufferSize write SetBufferSize;
end;
CStreamEncoder = class of TStreamDecoder;
function Conv_DetectType(AStream: TStream): CEncoding; overload;
function Conv_DetectType(AStream: TStream; out AEncoding: CEncoding): boolean; overload;
function Conv_DetectType(const AFilename: TFilename): CEncoding; overload;
function Conv_DetectType(const AFilename: TFilename; out AEncoding: CEncoding): boolean; overload;
function OpenStream(const AStream: TStream; AOwnsStream: boolean; AEncoding: CEncoding = nil): TStreamDecoder;
function WriteToStream(const AStream: TStream; AOwnsStream: boolean; AEncoding: CEncoding): TStreamEncoder;
function OpenTextFile(const AFilename: TFilename; AEncoding: CEncoding = nil): TStreamDecoder; inline;
function CreateTextFile(const AFilename: TFilename; AEncoding: CEncoding): TStreamEncoder;
function AppendToTextFile(const AFilename: TFilename; AEncoding: CEncoding = nil): TStreamEncoder;
//Finds a class by it's name. Good to store encoding selection in a permanent way.
function FindEncodingByClassName(const AClassName: string): CEncoding;
function FindEncodingByName(AName: string): CEncoding;
//Compares binary data in files
function CompareStreams(const AStream1, AStream2: TStream): boolean;
function CompareFiles(const AFilename1, AFilename2: TFilename): boolean;
{ Compatibility functions }
function AnsiFileReader(const AFilename: TFilename): TStreamDecoder;
function UnicodeFileReader(const AFilename: TFilename): TStreamDecoder;
function ConsoleReader(AEncoding: TEncoding = nil): TStreamDecoder;
function UnicodeStreamReader(AStream: TStream; AOwnsStream: boolean = false): TStreamDecoder;
function FileReader(const AFilename: TFilename): TStreamDecoder; inline; //->Unicode on Unicode, ->Ansi on Ansi
function AnsiFileWriter(const AFilename: TFilename): TStreamEncoder;
function UnicodeFileWriter(const AFilename: TFilename): TStreamEncoder;
function ConsoleWriter(AEncoding: TEncoding = nil): TStreamEncoder;
function ErrorConsoleWriter(AEncoding: TEncoding = nil): TStreamEncoder;
function UnicodeStreamWriter(AStream: TStream; AOwnsStream: boolean = false): TStreamEncoder;
function FileWriter(const AFilename: TFilename): TStreamEncoder; inline; //->Unicode on Unicode, ->Ansi on Ansi
{ Misc useful functions }
function GetLineCount(AText: TStreamDecoder): integer;
implementation
uses {$IFDEF MSWINDOWS}Windows,{$ENDIF} JWBConvertTbl;
{ Various helpers }
//Swaps bytes in a word
function _swapw(const w: word): word; inline;
begin
Result :=
(w and $00FF) shl 8 +
(w and $FF00) shr 8;
{ or:
(w mod $100) shl 8 +
(w div $100);
dunno which is faster }
end;
{$IFDEF OWNBYTES}
function Bytes(): TBytes;
begin
SetLength(Result, 0);
end;
function Bytes(b1: byte): TBytes;
begin
SetLength(Result, 1);
Result[0] := b1;
end;
function Bytes(b1,b2: byte): TBytes;
begin
SetLength(Result, 2);
Result[0] := b1;
Result[1] := b2;
end;
function Bytes(b1,b2,b3: byte): TBytes;
begin
SetLength(Result, 3);
Result[0] := b1;
Result[1] := b2;
Result[2] := b3;
end;
function Bytes(b1,b2,b3,b4: byte): TBytes;
begin
SetLength(Result, 4);
Result[0] := b1;
Result[1] := b2;
Result[2] := b3;
Result[3] := b4;
end;
{$ELSE}
function Bytes(): TBytes;
begin
Result := TBytes.Create();
end;
function Bytes(b1: byte): TBytes;
begin
Result := TBytes.Create(b1);
end;
function Bytes(b1,b2: byte): TBytes;
begin
Result := TBytes.Create(b1,b2);
end;
function Bytes(b1,b2,b3: byte): TBytes;
begin
Result := TBytes.Create(b1,b2,b3);
end;
function Bytes(b1,b2,b3,b4: byte): TBytes;
begin
Result := TBytes.Create(b1,b2,b3,b4);
end;
{$ENDIF}
{ Encoding }
constructor TEncoding.Create;
begin
inherited; { Inherit in descendants to initialize encoding }
end;
class function TEncoding.GetBom: TBytes;
begin
Result := Bytes();
end;
{ Reads out any of the BOMs supported by this encoding and returns true,
or returns false and returns AStream to the previous position.
Avoid calling for streams which do not support seeking when BOM is not really
expected. }
class function TEncoding.ReadBom(AStream: TStream): boolean;
var BOM: TBytes;
data: TBytes;
read_sz: integer;
i: integer;
begin
BOM := GetBOM();
if Length(BOM)<=0 then begin
Result := false;
exit;
end;
{ Default implementation just checks for the main BOM }
SetLength(data, Length(BOM));
read_sz := AStream.Read(data[0], Length(data));
Result := true;
for i := 0 to Length(data)-1 do
if BOM[i]<>data[i] then begin
Result := false;
break;
end;
if not Result then
AStream.Seek(-read_sz, soCurrent);
end;
procedure TEncoding.WriteBom(AStream: TStream);
var BOM: TBytes;
begin
BOM := GetBOM();
if Length(BOM)>0 then
AStream.Write(BOM[0], Length(BOM));
end;
function TEncoding.Analyze(AStream: TStream): TEncodingLikelihood;
begin
{ Default implementation only tests for BOM }
if ReadBom(AStream) then
Result := elIdentified
else
Result := elUnlikely;
end;
function TEncoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
while MaxChars>0 do begin
if not ReadChar(AStream, Result[pos]) then break;
Inc(pos);
Dec(MaxChars);
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
function TEncoding.ReadChar(AStream: TStream; out AChar: WideChar): boolean;
var s: UnicodeString;
begin
s := Read(AStream, 1);
Result := Length(s)>=1;
if Result then AChar := s[1];
end;
procedure TEncoding.Write(AStream: TStream; const AData: UnicodeString);
var i: integer;
begin
for i := 1 to Length(AData) do
WriteChar(AStream, AData[i]);
end;
procedure TEncoding.WriteChar(AStream: TStream; AChar: WideChar);
begin
Write(AStream, AChar);
end;
procedure _fwrite1(AStream: TStream; const b: byte); inline;
begin
AStream.Write(b, 1);
end;
procedure _fwrite2(AStream: TStream; const w: word); inline;
begin
AStream.Write(w, 2);
end;
procedure _fwrite3(AStream: TStream; const dw: cardinal); inline;
begin
AStream.Write(dw, 3);
end;
procedure _fwrite4(AStream: TStream; const dw: cardinal); inline;
begin
AStream.Write(dw, 4);
end;
{ Stream buffer }
function TStreamBuf.Read(var Buffer; Count: Longint): Longint;
var pbuf: PByte;
begin
if Count=0 then begin
Result := 0;
exit;
end;
//The most common case
if Count <= rem then begin
Move(ptr^, Buffer, Count);
Inc(ptr, Count);
Inc(adv, Count);
Dec(rem, Count);
Inc(FBytesRead, Count);
Result := Count;
exit;
end;
//Read first part
pbuf := @Buffer;
if rem > 0 then begin
Move(ptr^, pbuf^, rem);
Inc(ptr, rem);
Inc(adv, rem);
Result := rem;
rem := 0;
end else
Result := 0;
//That was all the data we have, sorry
Inc(FBytesRead, Result);
end;
{ Stream decoder }
constructor TStreamDecoder.Open(AStream: TStream; AEncoding: TEncoding;
AOwnsStream: boolean = false);
begin
inherited Create();
FStream := AStream;
FOwnsStream := AOwnsStream;
FByteBuf := TStreamBuf.Create(AStream, false);
FByteBuf.ChunkSize := 1024;
FByteEOF := false;
FEncoding := AEncoding;
Self.TrySkipBom;
end;
constructor TStreamDecoder.Open(const AFilename: TFilename; AEncoding: TEncoding);
var fs: TFileStream;
begin
fs := TFileStream.Create(AFilename, fmOpenRead);
Self.Open(fs, AEncoding, {OwnsStream=}true);
end;
destructor TStreamDecoder.Destroy;
begin
FreeAndNil(FByteBuf);
if FOwnsStream then
FreeAndNil(FStream)
else
DetachStream; //only restore position if we have to
FreeAndNil(FEncoding);
inherited;
end;
{ Reads more data and convert more characters. }
procedure TStreamDecoder.ConvertMoreChars;
var new_sz: integer;
new_chunk: UnicodeString;
bytes_read: integer;
bytes_rem: integer;
begin
{
Stream --> ByteBuf --> CharBuf [Buffer]
1. ByteBuf overflows if TEncoding never converts anything, no matter how big
chunk of bytes it's given.
2. CharBuf overflows if someone calls ConvertMoreChars without reading those
out.
In both cases, no harm done but no data flows further. ReadChar may be stuck
calling us again and again.
}
//Read more data from the stream. We immediately convert the data, so there
//should be close to no previous data in ByteBuf.
bytes_read := FByteBuf.UpdateChunk;
bytes_rem := FByteBuf.ChunkBytesRemaining;
//Convert all the available data
new_sz := INBUFSZ-(Length(FBuffer)-FBufferPos);
if new_sz<=0 then exit;
new_chunk := FEncoding.Read(FByteBuf, new_sz);
//New chunk may be empty if not enough bytes for a single char has arrived
FBuffer := copy(FBuffer, FBufferPos+1, MaxInt)
+ new_chunk;
FBufferPos := 0;
{ ByteEOF means that 1. stream is EOF, 2. byte buffer is empty or contains only
unparsable remainder.
Test for 1? UpdateChunk produces no data.
Test for 2? TEncoding eats no bytes.
Complications: 1. ByteBuf overflow => UpdateChunk runs empty, 2. CharBuf
overflow => TEncoding eats no bytes even though it could.
Solutions: 2. Less than 2 empty chars => skip ByteEOF detection until someone
reads those out.
1. => condition satisfied (if 2? is also true, we're stuck forever, so EOF) }
if (bytes_read=0) {for whatever reason, mb overflow}
and (new_sz>=2) {there was enough space for any char/surrogate}
and (FByteBuf.ChunkBytesRemaining>=bytes_rem) {and no bytes was read}
then
FByteEOF := true;
end;
procedure TStreamDecoder.DetachStream;
begin
{ Unfortunately there's no way now to know how many bytes we should roll back
to position stream where we logically are (in characters). }
end;
function TStreamDecoder.TrySkipBom: boolean;
begin
Result := FEncoding.ReadBom(Stream);
end;
procedure TStreamDecoder.Rewind(const ADontSkipBom: boolean);
begin
Stream.Seek(0, soBeginning);
FBufferPos := Length(FBuffer)+1;
FByteEOF := false;
if not ADontSkipBom then
TrySkipBom;
end;
{ True if there *already was* at least one ReadChar() which resulted in False,
and no subsequent calls can be expected to succeed.
Should not return true even if we're at EOF until someone tries to ReadChar()
and finds it. }
function TStreamDecoder.EOF: boolean;
begin
Result := FByteEOF and (FBufferPos>=Length(FBuffer));
end;
{ Reads another character from the stream or returns False to indicate that
no more are available. }
function TStreamDecoder.ReadChar(out ch: WideChar): boolean;
begin
while FBufferPos>=Length(FBuffer) do begin
if FByteEOF then begin
Result := false;
exit;
end;
ConvertMoreChars;
end;
Inc(FBufferPos);
ch := FBuffer[FBufferPos];
Result := true;
end;
{ Reads until next CRLF or the end of the stream.
Last line always ends with the stream. If the file ends in CRLF, it'll be
returned as a last, empty line.
To reproduce the content when saving, always write last line without CRLF.
As an exception, empty file is thought to have no lines. }
function TStreamDecoder.ReadLn(out ln: UnicodeString): boolean;
var ch: WideChar;
begin
ln := '';
Result := not EOF; //there may be no more characters, but at least we haven't found that out yet
while ReadChar(ch) do begin
{ Maybe a more thorough CRLF/CR/LF handling is needed }
if ch=#$000D then begin
//ignore
end else
if ch=#$000A then
break
else
ln := ln + ch;
end;
end;
function TStreamDecoder.ReadChar: WideChar;
begin
if not ReadChar(Result) then
Result := #0000;
end;
function TStreamDecoder.ReadLn: UnicodeString;
begin
if not ReadLn(Result) then
Result := '';
end;
function TStreamDecoder.ReadAll: UnicodeString;
var ch: WideChar;
begin
Result := '';
while ReadChar(ch) do
Result := Result + ch;
end;
{ Stream encoder }
constructor TStreamEncoder.Open(AStream: TStream; AEncoding: TEncoding;
AOwnsStream: boolean = false);
begin
inherited Create();
FStream := AStream;
FOwnsStream := AOwnsStream;
FEncoding := AEncoding;
SetLength(FBuffer, OUTBUFSZ);
FBufferPos := 0;
end;
constructor TStreamEncoder.CreateNew(const AFilename: TFilename; AEncoding: TEncoding);
var fs: TFileStream;
begin
fs := TFileStream.Create(AFilename, fmCreate);
Self.Open(fs,AEncoding,{OwnsStream=}true);
end;
constructor TStreamEncoder.Append(const AFilename: TFilename; AEncoding: TEncoding);
var fs: TFileStream;
begin
fs := TFileStream.Create(AFilename, fmCreate);
fs.Seek(0,soFromEnd);
Self.Open(fs,AEncoding,{OwnsStream=}true);
end;
destructor TStreamEncoder.Destroy;
begin
Flush();
if FOwnsStream then
FreeAndNil(FStream);
FreeAndNil(FEncoding);
inherited;
end;
function TStreamEncoder.GetBufferSize: integer;
begin
Result := Length(FBuffer);
end;
procedure TStreamEncoder.SetBufferSize(const Value: integer);
begin
Flush;
SetLength(FBuffer, Value);
end;
procedure TStreamEncoder.Flush;
begin
if FBufferPos>=Length(FBuffer) then
FEncoding.Write(FStream, FBuffer)
else
if FBufferPos>0 then
FEncoding.Write(FStream, copy(FBuffer, 1, FBufferPos));
FBufferPos := 0;
end;
procedure TStreamEncoder.WriteBom;
begin
Flush;
FEncoding.WriteBom(FStream);
end;
procedure TStreamEncoder.WriteChar(const ch: WideChar);
begin
if Length(FBuffer)<=0 then
FEncoding.WriteChar(FStream, ch)
else begin
Inc(FBufferPos);
FBuffer[FBufferPos] := ch;
if FBufferPos>=Length(FBuffer) then
Flush();
end;
end;
procedure TStreamEncoder.Write(const ln: UnicodeString);
var fst: integer;
begin
if ln='' then exit;
if Length(FBuffer)>0 then begin
//Whatever fits into buffer
fst := Length(FBuffer)-FBufferPos;
if fst>Length(ln) then fst := Length(ln);
Move(ln[1], FBuffer[FBufferPos+1], fst*SizeOf(WideChar));
Inc(FBufferPos, fst);
if FBufferPos>=Length(FBuffer) then
Flush();
Inc(fst);
end else
fst := 1;
//Remainder
if fst<Length(ln)+1 then
FEncoding.Write(FStream, copy(ln, fst, MaxInt));
end;
{ Writes a line with CRLF in the end.
Note that if you've read the lines with ReadLn, to reproduce the file content,
last line has to be written without CRLF. See ReadLn. }
procedure TStreamEncoder.WriteLn(const ln: UnicodeString);
begin
Write(ln+#$000D+#$000A);
end;
{ Simple encodings }
function TAsciiEncoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var pos: integer;
ac: AnsiChar;
begin
SetLength(Result, MaxChars);
pos := 1;
while (MaxChars>0) and (AStream.Read(ac,1)=1) do begin
Result[pos] := WideChar(ac);
Inc(pos);
Dec(MaxChars);
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TAsciiEncoding.Write(AStream: TStream; const AData: UnicodeString);
var i: integer;
ch: AnsiChar;
begin
for i := 1 to Length(AData) do begin
ch := AnsiChar(AData[i]);
AStream.Write(ch, 1);
end;
end;
{$IFDEF MSWINDOWS}
{ A note on parametrized encodings:
They will work, but not with any special code which assumes one encoding == one type.
You also cannot rely on comparisons like "if Encoding1==Encoding2". }
constructor TMultibyteEncoding.Create(const ACodepage: integer);
begin
inherited Create;
FCodepage := ACodepage;
FIllegalChar := '?';
end;
{ Hold on to your seats guys, this is going to be slow!
CP_* encodings on Windows can be multibyte and MultiByteToWideChar does not
return the number of bytes it used (only the number of *resulting* chars).
To know where to start next time we expand sample byte by byte, until there's
enough bytes for MultiByteToWideChar to produce one char.
Both Multibyte and Wide encodings can have surrogate characters, so we have
to be ready to receive more than one char position. If there's not enough
space in Char buffer, we roll back and leave it for next time.
If there are invalid characters, they are ignored and MBWC produces no chars.
This is problematic, as we will continue increasing sample size without
producing a character. Eventually we will run out of Bytes and return with no
progress made, the caller will keep all the data and run out of buffer
Therefore, we need to stop at some point and declare the position "invalid".
With WideChars it's easy: surrogates longer than 2 chars don't exist. With
Multibyte UTF-8 can go for as long as 7 chars, so we'll settle at eight.
Note that we may not notice invalid char if MBWC encounters another valid char
while at the same 8 bytes. No way around this. We cannot test for
ERROR_NO_UNICODE_TRANSLATION because incomplete sequences result in the same. }
function TMultibyteEncoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var i, pos, conv: integer;
inp: array[0..7] of AnsiChar;
outp: array[0..1] of WideChar;
found: boolean;
begin
SetLength(Result, MaxChars);
conv := 0;
pos := 1;
while MaxChars>0 do begin
i := 0;
found := false;
while i<Length(inp) do begin
if AStream.Read(inp[i],1)<>1 then begin
AStream.Seek(-(i-1),soFromCurrent);
break;
end;
conv := MultiByteToWideChar(FCodepage, 0, @inp[0], i+1, @outp[0], Length(outp));
if conv>=1 then begin
found := true;
break;
end;
Inc(i);
end;
if i>=Length(inp) then begin
Result[pos] := FIllegalChar;
AStream.Seek(-(i-1), soCurrent); //start with the next char
continue;
end;
if (not found) or (conv>MaxChars) then begin
//not enough bytes, or
//want to write surrogate and not enough space
if i>0 then AStream.Seek(-i, soCurrent); //maybe next time
break;
end;
for i := 0 to conv-1 do begin
Result[pos] := outp[i];
Inc(pos);
Dec(MaxChars);
end;
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TMultibyteEncoding.Write(AStream: TStream; const AData: UnicodeString);
var buf: AnsiString;
written: integer;
begin
if Length(AData)=0 then exit;
SetLength(buf, Length(AData)*7); //there aren't any encodings with more than 7 byte chars
written := WideCharToMultiByte(FCodepage, 0, PWideChar(AData), Length(AData), PAnsiChar(buf), Length(buf), nil, nil);
if written=0 then
RaiseLastOsError();
AStream.Write(buf[1], written);
end;
constructor TAcpEncoding.Create;
begin
inherited Create(CP_ACP);
end;
{$ENDIF}
class function TUTF8Encoding.GetBOM: TBytes;
begin
Result := Bytes($EF, $BB, $BF);
end;
function TUTF8Encoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var b: array[0..5] of byte;
{ Thought of making it packed record ( b0,b1,b2,b3,b4,b5: byte; ) for speed,
but the assembly is identical. }
chno: integer;
pc: PWideChar;
i: integer;
begin
SetLength(Result, MaxChars);
if MaxChars=0 then exit;
pc := PWideChar(Result);
while MaxChars>0 do begin
if AStream.Read(b[0],1)<>1 then break;
chno := 0;
i := 0;
if (b[0] and UTF8_MASK1)=UTF8_VALUE1 then begin
//Most common case, single-byte char
pc^ := WideChar(b[0]);
end else
if (b[0] and UTF8_MASK2)=UTF8_VALUE2 then begin
i := AStream.Read(b[1],1);
if i<>1 then begin
AStream.Seek(-(i+1),soFromCurrent);
break;
end;
pc^ := WideChar( (b[0] and $1f) shl 6
+ (b[1] and $3f));
end else
if (b[0] and UTF8_MASK3)=UTF8_VALUE3 then begin
i := AStream.Read(b[1],2);
if i<>2 then begin
AStream.Seek(-(i+1),soFromCurrent);
break;
end;
pc^ := WideChar((b[0] and $0f) shl 12
+ (b[1] and $3f) shl 6
+ (b[2] and $3f));
end else
if (b[0] and UTF8_MASK4)=UTF8_VALUE4 then
begin
i := AStream.Read(b[1],3);
if i<>3 then begin
AStream.Seek(-(i+1),soFromCurrent);
break;
end;
chno := (b[0] and $0f) shl 18
+ (b[1] and $3f) shl 12
+ (b[2] and $3f) shl 6
+ (b[3] and $3f);
//will be stored below
end else
if (b[0] and UTF8_MASK5)=UTF8_VALUE5 then
begin
i := AStream.Read(b[1],4);
if i<>4 then begin
AStream.Seek(-(i+1),soFromCurrent);
break;
end;
chno := (b[0] and $0f) shl 24
+ (b[1] and $3f) shl 18
+ (b[2] and $3f) shl 12
+ (b[3] and $3f) shl 6
+ (b[4] and $3f);
end else
if (b[0] and UTF8_MASK6)=UTF8_VALUE4 then
begin
i := AStream.Read(b[1],5);
if i<>5 then begin
AStream.Seek(-(i+1),soFromCurrent);
break;
end;
chno := (b[0] and $0f) shl 30
+ (b[1] and $3f) shl 24
+ (b[2] and $3f) shl 18
+ (b[3] and $3f) shl 12
+ (b[4] and $3f) shl 6
+ (b[5] and $3f);
end else
//Broken, unsupported character, probably a remnant of a surrogate. Skip it.
Dec(pc);
//Store complicated characters by setting their chno insteead
if chno=0 then begin
Inc(pc);
Dec(MaxChars);
end
else begin
if chno<$10000 then begin
pc^ := WideChar(chno);
Inc(pc);
Dec(MaxChars);
end else
if MaxChars<2 then begin
AStream.Seek(-(i+1),soFromCurrent);
break;
end else
begin
chno := chno-$10000;
pc[0] := WideChar(UTF16_LEAD + chno shr 10);
pc[1] := WideChar(UTF16_TRAIL + chno and $03FF);
Inc(pc, 2);
Dec(MaxChars, 2);
end;
end;
end;
if MaxChars>0 then
SetLength(Result, Length(Result)-MaxChars);
end;
procedure TUTF8Encoding.Write(AStream: TStream; const AData: UnicodeString);
var i: integer;
w: integer;
begin
for i := 1 to Length(AData) do begin
w := Word(AData[i]);
//TODO: UTF16 surrogates
if (w and UTF8_WRITE1)=0 then
_fwrite1(AStream, w mod 256)
else
if (w and UTF8_WRITE2)=0 then
_fwrite2(AStream,
(UTF8_VALUE2 or (w shr 6))
+ (UTF8_VALUEC or (w and $3f)) shl 8
)
else
//TODO: Write 3,4,5-byte sequences when needed
_fwrite3(AStream,
(UTF8_VALUE3 or (w shr 12))
+ (UTF8_VALUEC or ((w shr 6) and $3f)) shl 8
+ (UTF8_VALUEC or (w and $3f)) shl 16
);
end;
end;
class function TUTF16LEEncoding.GetBOM: TBytes;
begin
Result := Bytes($FF, $FE);
end;
function TUTF16LEEncoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var read_sz: integer;
begin
SetLength(Result, MaxChars);
read_sz := AStream.Read(Result[1], MaxChars*SizeOf(WideChar));
if read_sz<MaxChars*SizeOf(WideChar) then
SetLength(Result, read_sz div SizeOf(WideChar));
end;
procedure TUTF16LEEncoding.Write(AStream: TStream; const AData: UnicodeString);
begin
if AData<>'' then
AStream.Write(AData[1], Length(AData)*SizeOf(WideChar));
end;
class function TUTF16BEEncoding.GetBOM: TBytes;
begin
Result := Bytes($FE, $FF);
end;
function TUTF16BEEncoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var read_sz: integer;
i: integer;
begin
SetLength(Result, MaxChars);
read_sz := AStream.Read(Result[1], MaxChars*SizeOf(WideChar));
if read_sz<MaxChars*SizeOf(WideChar) then
SetLength(Result, read_sz div SizeOf(WideChar));
for i := 1 to Length(Result) do
Result[i] := WideChar(_swapw(Word(Result[i])));
end;
procedure TUTF16BEEncoding.Write(AStream: TStream; const AData: UnicodeString);
var i: integer;
begin
for i := 1 to Length(AData) do
_fwrite2(AStream, _swapw(Word(AData[i])));
end;
{ Wakan encodings }
const IS_EUC=1;
IS_HALFKATA=2;
IS_SJIS1=3;
IS_SJIS2=4;
IS_MARU=5;
IS_NIGORI=6;
IS_JIS=7;
JIS_NL=10; // New Line char.
JIS_CR=13; // Carrage Return.
JIS_ESC=27; // Escape.
JIS_SS2=$8E; //EUC-JP 2-byte sequence start
JIS_SS3=$8F; //EUC-JP 3-byte sequence start
type TUTFArray=array[0..3] of byte;
function SJIS2JIS(w:word):word;
var b1,b2,adjust, rowOffset, cellOffset:byte;
begin
b1:=w div 256;
b2:=w mod 256;
if b2<159 then adjust:=1 else adjust:=0;
if b1<160 then rowOffset:=112 else rowOffset:=176;
if adjust=1 then begin if b2>127 then cellOffset:=32 else cellOffset:=31 end else cellOffset:=126;
b1 := ((b1-rowOffset) shl 1) - adjust;
b2 := b2-cellOffset;
result:=b1*256+b2;
end;
function JIS2SJIS(w:word):word;
var b1,b2,b1n:byte;
begin
b1:=w div 256;
b2:=w mod 256;
if b1 mod 2<>0 then begin if b2>95 then b2:=b2+32 else b2:=b2+31 end else b2:=b2+126;
b1n:=((b1+1) shr 1);
if b1<95 then b1n:=b1n+112 else b1n:=b1n+176;
result:=b1n*256+b2;
end;
function JIS2Unicode(w:word):word;
begin
result:=0;//default case
case w of
$0000..$007e:result:=w; // ascii
$0080..$00ff:result:=Table_ExtASCII[w-128];
$2330..$237a:result:=w-$2330+$ff10; // japanese ASCII
$2421..$2473:result:=w-$2421+$3041; // hiragana
$2521..$2576:result:=w-$2521+$30a1; // katakana
$2621..$2658:if w<=$2631 then result:=w-$2621+$0391 else
if w<=$2638 then result:=w-$2621+$0392 else
if w< $2641 then result:=0 else
if w<=$2651 then result:=w-$2621+$0391 else
if w<=$2658 then result:=w-$2621+$0392; // greek
$2721..$2771:if w<=$2726 then result:=w-$2721+$0410 else
if w= $2727 then result:=$0401 else
if w<=$2741 then result:=w-$2722+$0410 else
if w< $2751 then result:=0 else
if w<=$2756 then result:=w-$2751+$0430 else
if w= $2757 then result:=$0451 else
if w<=$2771 then result:=w-$2752+$0430; // cyrillic
$3021..$7426:if ((w and $7f)<$21) or ((w and $7f)>$7e) then result:=0 else
result:=Table_Kanji[((w-$3021) div 256)*94+((w-$3021) mod 256)]; // kanji
$2121..$217e:result:=Table_Misc[w-$2121];
$2221..$227e:result:=Table_Misc[w-$2221+94];
$2821..$2840:result:=Table_Misc[w-$2821+94+94];
end;
end;
function Unicode2UTF(ch:word):TUTFArray;
begin
if (ch and UTF8_WRITE1)=0 then
begin
result[0]:=1;
result[1]:=ch;
exit;
end;
if (ch and UTF8_WRITE2)=0 then
begin
result[0]:=2;
result[1]:=(UTF8_VALUE2 or (ch shr 6));
result[2]:=(UTF8_VALUEC or (ch and $3f));
end;
result[0]:=3;
result[1]:=UTF8_VALUE3 or (ch shr 12);
result[2]:=UTF8_VALUEC or ((ch shr 6) and $3f);
result[3]:=UTF8_VALUEC or (ch and $3f);
end;
function Unicode2JIS(w:word):word;
var i:integer;
begin
result:=0;
case w of
$0000..$007e:result:=w; // Ascii
$3041..$3093:result:=w-$3041+$2421; // Hiragana
$30a1..$30f6:result:=w-$30a1+$2521; // Katakana
$0391..$03c9:if w<=$03a1 then result:=w-$0391+$2621 else
if w= $03a2 then result:=0 else
if w<=$03a9 then result:=w-$0392+$2621 else
if w< $03b1 then result:=0 else
if w<=$03c1 then result:=w-$0391+$2621 else
if w= $03c2 then result:=0 else
if w<=$03c9 then result:=w-$0392+$2621; // greek
$0401 :result:=$2727;
$0451 :result:=$2757;
$0410..$044f:if w<=$0415 then result:=w-$0410+$2721 else
if w<=$042f then result:=w-$0416+$2728 else
if w<=$0435 then result:=w-$0430+$2751 else
if w<=$044f then result:=w-$0436+$2758; // cyrillic
$ff10..$ff5a:result:=w-$ff10+$2330;
$feff :result:=w;
$fffe :result:=w;
end;
if result<>0 then exit;
for i:=0 to NUMBER_KANJIUNICODE-1 do if Table_Kanji[i]=w then
begin
result:=i div 94;
result:=(((result+$30) shl 8) or (i-result*94)+$21);
exit;
end;
for i:=0 to NUMBER_MISCUNICODE-1 do if Table_Misc[i]=w then
begin
case i div 94 of
0:result:=$2121+i;
1:result:=$2221+i-94;
2:result:=$2821+i-94-94;
end;
exit;
end;
for i:=0 to NUMBER_EXTUNICODE-1 do if Table_ExtASCII[i]=w then
begin
result:=i+$80;
exit;
end;
result:=0;
end;
function UTF2Unicode(b1,b2,b3,b4:byte;var inc:byte):word;
begin
if (b1 and UTF8_MASK1)=UTF8_VALUE1 then
begin
result:=b1;
inc:=1;
exit;
end else if (b1 and UTF8_MASK2)=UTF8_VALUE2 then
begin
result:=((b1 and $1f) shl 6) or (b2 and $3f);
inc:=2;
exit;
end else if (b1 and UTF8_MASK3)=UTF8_VALUE3 then
begin
result:=((b1 and $0f) shl 12) or ((b2 and $3f) shl 6) or (b3 and $3f);
inc:=3;
exit;
end else if (b1 and UTF8_MASK4)=UTF8_VALUE4 then
begin
result:=$ffff;
inc:=4;
end else begin
Result:=b1; //because we don't know what else to do
inc:=1;
end;
end;
function _is(b:word;cl:byte):boolean;
begin
case cl of
IS_EUC:result:=(b>=$A1) and (b<=$FE);
IS_HALFKATA:result:=(b>=161) and (b<=223);
IS_SJIS1:result:=((b>=129) and (b<=159)) or ((b>=224) and (b<=239));
IS_SJIS2:result:=(b>=64) and (b<=252);
IS_MARU:result:=(b>=202) and (b<=206);
IS_NIGORI:result:=((b>=182) and (b<=196)) or ((b>=202) and (b<=206)) or (b=179);
IS_JIS:result:=(b and $7f00)>0;
else result:=false;
end;
end;
function TEUCEncoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var b1, b2: byte;
pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
while MaxChars>0 do begin
if AStream.Read(b1,1)<>1 then break;
if _is(b1,IS_EUC) then begin
if AStream.Read(b2,1)<>1 then begin
AStream.Seek(-1,soFromCurrent);
break;
end;
Result[pos] := WideChar(JIS2Unicode((b1*256+b2) and $7f7f));
end else
Result[pos] := WideChar(b1);
Inc(pos);
Dec(MaxChars);
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TEUCEncoding.Write(AStream: TStream; const AData: UnicodeString);
var i: integer;
w: word;
begin
for i := 1 to Length(AData) do begin
w := Unicode2JIS(Word(AData[i]));
if _is(w,IS_JIS) then
_fwrite2(AStream,
((w shr 8) or $80)
+ ((w mod 256) or $80) shl 8
)
else if (w and $80)>0 then
_fwrite2(AStream,
JIS_SS2
+ (w and $7f) shl 8
)
else
_fwrite1(AStream, w);
end;
end;
function TSJISEncoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var b1, b2: byte;
pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
while MaxChars>0 do begin
if AStream.Read(b1,1)<>1 then break;
if _is(b1,IS_SJIS1) then begin
if AStream.Read(b2,1)<>1 then begin
AStream.Seek(-1,soFromCurrent);
break;
end;
if _is(b2,IS_SJIS2) then
Result[pos] := WideChar(JIS2Unicode(SJIS2JIS(b1*256+b2)))
else
Result[pos] := WideChar(JIS2Unicode(b1*256+b2));
end else
Result[pos] := WideChar(b1);
Inc(pos);
Dec(MaxChars);
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TSJISEncoding.Write(AStream: TStream; const AData: UnicodeString);
var i: integer;
w: word;
begin
for i := 1 to Length(AData) do begin
w:=Unicode2JIS(Word(AData[i]));
if _is(w,IS_JIS) then
begin
w:=jis2sjis(w);
_fwrite2(AStream, _swapw(w));
end else
_fwrite1(AStream, w);
end;
end;
function TBaseJISEncoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var b1, b2: byte;
inp_intwobyte: boolean;
pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
inp_intwobyte := false;
while true do begin
if AStream.Read(b1,1)<>1 then break;
if b1=JIS_ESC then
begin
if AStream.Read(b2,1)<>1 then begin
AStream.Seek(-1,soFromCurrent);
break;
end;
if (b2=ord('$')) or (b2=ord('(')) then AStream.Read(b1,1); //don't care about the result
if (b2=ord('K')) or (b2=ord('$')) then inp_intwobyte:=true else inp_intwobyte:=false;
//Do not exit, continue to the next char
end else begin
if (b1=JIS_NL) or (b1=JIS_CR) then
Result[pos] := WideChar(b1)
else begin
if AStream.Read(b2,1)<>1 then begin
AStream.Seek(-1,soFromCurrent);
break;
end;
if inp_intwobyte then
Result[pos] := WideChar(JIS2Unicode(b1*256+b2))
else
Result[pos] := WideChar(b1);
end;
Inc(pos);
Dec(MaxChars);
if MaxChars<=0 then break;
end;
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TBaseJISEncoding.Write(AStream: TStream; const AData: UnicodeString);
var i: integer;
w: word;
begin
for i := 1 to Length(AData) do begin
w := Word(AData[i]);
if (w=13) or (w=10) then
begin
_fputend(AStream);
_fwrite1(AStream, w);
end else
begin
w:=Unicode2JIS(w);
if _is(w,IS_JIS) then
begin
_fputstart(AStream);
_fwrite2(AStream, _swapw(w));
end else begin
_fputend(AStream);
_fwrite1(AStream, w);
end;
end;
end;
end;
procedure TBaseJISEncoding._fputstart(AStream: TStream);
begin
if intwobyte then exit;
intwobyte:=true;
AStream.Write(StartMark[0], Length(StartMark));
end;
procedure TBaseJISEncoding._fputend(AStream: TStream);
begin
if not intwobyte then exit;
intwobyte:=false;
AStream.Write(EndMark[0], Length(EndMark));
end;
constructor TJISEncoding.Create;
begin
inherited;
StartMark := Bytes(JIS_ESC, ord('$'), ord('B'));
EndMark := Bytes(JIS_ESC, ord('('), ord('J'));
end;
constructor TOldJISEncoding.Create;
begin
inherited;
StartMark := Bytes(JIS_ESC, ord('$'), ord('@'));
EndMark := Bytes(JIS_ESC, ord('('), ord('J'));
end;
constructor TNECJISEncoding.Create;
begin
inherited;
StartMark := Bytes(JIS_ESC, ord('K'));
EndMark := Bytes(JIS_ESC, ord('H'));
end;
function TGBEncoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var b1, b2: byte;
pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
while MaxChars>0 do begin
if AStream.Read(b1,1)<>1 then break;
if (b1>=$a1) and (b1<=$fe) then
begin
if AStream.Read(b2,1)<>1 then begin
AStream.Seek(-1,soFromCurrent);
break;
end;
if (b2>=$a1) and (b2<=$fe) then
Result[pos] := WideChar(Table_GB[(b1-$a0)*96+(b2-$a0)])
else
Result[pos] := WideChar(b1*256+b2);
end else
Result[pos] := WideChar(b1);
Inc(pos);
Dec(MaxChars);
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TGBEncoding.Write(AStream: TStream; const AData: UnicodeString);
var i,j: integer;
w: word;
begin
for j := 1 to Length(AData) do begin
w := Word(AData[j]);
if w<128 then
_fwrite1(AStream, byte(w))
else
begin
for i:=0 to 96*96-1 do if Table_GB[i]=w then begin
_fwrite2(AStream,
(i mod 96+$a0) shl 8
+ (i div 96+$a0)
);
exit;
end;
_fwrite2(AStream,
(w mod 256) shl 8
+ (w div 256)
);
end;
end;
end;
function TBIG5Encoding.Read(AStream: TStream; MaxChars: integer): UnicodeString;
var b1, b2: byte;
pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
while MaxChars>0 do begin
if AStream.Read(b1,1)<>1 then break;
if (b1>=$a1) and (b1<=$fe) then
begin
if AStream.Read(b2,1)<>1 then begin
AStream.Seek(-1,soFromCurrent);
break;
end;
if (b2>=$40) and (b2<=$7f) then
Result[pos] := WideChar(Table_Big5[(b1-$a0)*160+(b2-$40)])
else
if (b2>=$a1) and (b2<=$fe) then
Result[pos] := WideChar(Table_Big5[(b1-$a0)*160+(b2-$a0)])
else
Result[pos] := WideChar(b1*256+b2);
end else
Result[pos] := WideChar(b1);
Inc(pos);
Dec(MaxChars);
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TBIG5Encoding.Write(AStream: TStream; const AData: UnicodeString);
var i, j: integer;
w: word;
begin
for j := 1 to Length(AData) do begin
w := Word(AData[j]);
if w<128 then
_fwrite1(AStream, byte(w))
else
begin
for i:=0 to 96*160-1 do if Table_GB[i]=w then begin
_fwrite2(AStream,
(i mod 96+$a0) shl 8
+ (i div 96+$a0)
);
exit;
end;
_fwrite2(AStream, _swapw(w));
end;
end;
end;
function Conv_DetectType(AStream: TStream): CEncoding;
begin
if not Conv_DetectType(AStream, Result) then
Result := nil;
end;
{ Detects file encoding. Returns true if it's truly detected (i.e. through BOM),
or false if it's a best guess. }
function Conv_DetectType(AStream: TStream; out AEncoding: CEncoding): boolean;
var i,b,j:integer;
w: word;
eucsjis:boolean;
asciionly:boolean;
failed_le, failed_be: boolean;
begin
AStream.Seek(0, soBeginning);
AEncoding := nil;
Result := false;
if TUTF16LEEncoding.ReadBom(AStream) then begin
AEncoding := TUTF16LEEncoding;
Result := true;
exit;
end;
if TUTF16BEEncoding.ReadBom(AStream) then begin
AEncoding := TUTF16BEEncoding;
Result := true;
exit;
end;
if TUTF8Encoding.ReadBom(AStream) then begin
AEncoding := TUTF8Encoding;
Result := true;
exit;
end;
{ UTF16LE/BE first try }
failed_le:=false;
failed_be:=false;
eucsjis:=true;
while (AStream.Read(w, 2)=2) and not (failed_be and failed_le) do
begin
if Unicode2JIS(w)=0 then failed_le:=true;
if Unicode2JIS(_swapw(w))=0 then failed_be:=true;
if (w and $8080)<>$8080 then eucsjis:=false;
end;
if eucsjis then
AEncoding:=nil
else
if failed_be and not failed_le then
AEncoding := TUTF16LEEncoding
else
if failed_le and not failed_be then
AEncoding := TUTF16BEEncoding;
if AEncoding<>nil then exit;
AStream.Seek(0, soBeginning);
asciionly:=true;
AEncoding := TUTF8Encoding;
i := 0; //zero higher bytes
while (AStream.Read(i, 1)=1) and (AEncoding=TUTF8Encoding) do
begin
b:=0;
if (i and UTF8_MASK1)=UTF8_VALUE1 then b:=0 else
if (i and UTF8_MASK2)=UTF8_VALUE2 then b:=1 else
if (i and UTF8_MASK3)=UTF8_VALUE3 then b:=2 else
if (i and UTF8_MASK4)=UTF8_VALUE4 then b:=3 else AEncoding:=nil;
if b>0 then asciionly:=false;
for j:=0 to b-1 do
begin
if AStream.Read(i, 1)=1 then //else do not drop the encoding, tolerate missing bytes, stream might have been cut short
if (i and $c0)<>$80 then AEncoding:=nil;
end;
end;
if asciionly then AEncoding:=nil;
if AEncoding<>nil then exit;
AStream.Seek(0, soBeginning);
AEncoding := TAsciiEncoding;
eucsjis:=false;
i:=0;
while (AEncoding = TAsciiEncoding) or ((AEncoding=nil) and eucsjis) do
begin
if AStream.Read(i, 1)<>1 then break;
if i=JIS_ESC then
begin
if AStream.Read(i, 1)<>1 then i:=-1;
if i=ord('$') then
begin
if AStream.Read(i, 1)<>1 then i:=-1;
if i=ord('B') then AEncoding:=TJISEncoding;
if i=ord('@') then AEncoding:=TOldJISEncoding;
end else
if i=ord('K') then AEncoding:=TNECJISEncoding;
end else
//EUC 9E+* 2-byte or 9F+*+* 3-byte sequence
if i=JIS_SS2 then begin
if AStream.Read(i, 1)<>1 then i:=-1;
if (i>=$A1) and (i<=$DF) then begin
AEncoding:=nil;
eucsjis:=true;
end else
if (i>=$40) and (i<=$FC) and (i<>$7F) then
AEncoding:=TSJISEncoding;
end else
//EUC 9F+*+* 3-byte sequence
if i=JIS_SS3 then begin
if AStream.Read(i, 1)<>1 then i:=-1;
if (i>=$A1) and (i<=$DF) then begin
if AStream.Read(i, 1)<>1 then i:=-1;
if (i>=$A1) and (i<=$DF) then begin
AEncoding:=nil;
eucsjis:=true;
end;
end else
if (i>=$40) and (i<=$FC) and (i<>$7F) then
AEncoding:=TSJISEncoding;
end else
//Shift-JIS first byte range
if (i>=$81) and (i<=$9F) then
AEncoding:=TSJISEncoding
else
//Single byte half-width kana, both in EUC and Shift-JIS
if (i>=$A1) and (i<=$DF) then begin
if AStream.Read(i, 1)<>1 then i:=-1;
if (i>=240) and (i<=254) then AEncoding:=TEUCEncoding
else if (i>=161) and (i<=223) then begin
AEncoding:=nil;
eucsjis:=true;
end
else if (i>=224) and (i<=239) then
begin
AEncoding:=nil;
eucsjis:=true;
while ((i>=64) and (AEncoding=nil) and eucsjis) do
begin
if i>=129 then
begin
if (i<=141) or ((i>=143) and (i<=159)) then AEncoding:=TSJISEncoding else
if (i>=253) and (i<=254) then AEncoding:=TEUCEncoding;
end;
if AStream.Read(i, 1)<>1 then break;
end;
end else if i<=159 then AEncoding:=TSJISEncoding;
end else
//Shift-JIS: unused as first byte; EUC: possible
if (i>=$F0) and (i<=$FE) then
AEncoding := TEUCEncoding
else
//Shift-JIS first byte range
if (i>=$E0) and (i<=$EF) then begin
if AStream.Read(i, 1)<>1 then i:=-1;
if ((i>=64) and (i<=126)) or ((i>=128) and (i<=160)) then AEncoding:=TSJISEncoding
else if (i>=253) and (i<=254) then AEncoding:=TEUCEncoding
else if (i>=161) and (i<=252) then begin
AEncoding:=nil;
eucsjis:=true;
end;
end;
end;
if (AEncoding=nil) and eucsjis then
AEncoding:=TSJISEncoding;
end;
function Conv_DetectType(const AFilename: TFilename): CEncoding;
var fsr: TStreamReader;
begin
fsr := TStreamReader.Create(
TFileStream.Create(AFilename, fmOpenRead), true);
try
Result := Conv_DetectType(fsr);
finally
FreeAndNil(fsr);
end;
end;
function Conv_DetectType(const AFilename: TFilename; out AEncoding: CEncoding): boolean;
var fsr: TStreamReader;
begin
fsr := TStreamReader.Create(
TFileStream.Create(AFilename, fmOpenRead), true);
try
Result := Conv_DetectType(fsr, AEncoding);
finally
FreeAndNil(fsr);
end;
end;
function OpenStream(const AStream: TStream; AOwnsStream: boolean; AEncoding: CEncoding): TStreamDecoder;
var fsr: TStreamReader;
begin
fsr := TStreamReader.Create(AStream, AOwnsStream);
try
if AEncoding=nil then
if not Conv_DetectType(fsr, AEncoding) and (AEncoding=nil) {not even a best guess} then
AEncoding := TAsciiEncoding;
fsr.Seek(0, soBeginning);
Result := TStreamDecoder.Open(fsr, AEncoding.Create, {OwnsStream=}true);
except
FreeAndNil(fsr);
raise;
end;
end;
function WriteToStream(const AStream: TStream; AOwnsStream: boolean; AEncoding: CEncoding): TStreamEncoder;
var fsr: TStreamWriter;
begin
fsr := TStreamWriter.Create(AStream, AOwnsStream);
try
Result := TStreamEncoder.Open(fsr, AEncoding.Create, {OwnsStream=}true);
except
FreeAndNil(fsr);
raise;
end;
end;
function OpenTextFile(const AFilename: TFilename; AEncoding: CEncoding = nil): TStreamDecoder;
begin
Result := OpenStream(
TFileStream.Create(AFilename, fmOpenRead or fmShareDenyNone),
{OwnsStream=}true,
AEncoding
);
end;
function CreateTextFile(const AFilename: TFilename; AEncoding: CEncoding): TStreamEncoder;
var fsr: TStreamWriter;
begin
fsr := TStreamWriter.Create(
TFileStream.Create(AFilename, fmCreate),
{OwnsStream=}true
);
try
Result := TStreamEncoder.Open(fsr, AEncoding.Create, {OwnsStream=}true);
except
FreeAndNil(fsr);
raise;
end;
end;
function AppendToTextFile(const AFilename: TFilename; AEncoding: CEncoding = nil): TStreamEncoder;
var fsr: TStreamWriter;
begin
fsr := TStreamWriter.Create(
TFileStream.Create(AFilename, fmOpenReadWrite), //read is for encoding detection
{OwnsStream=}true
);
try
if AEncoding=nil then
//Conv_DetectType by filename since TStreamWriter cannot read
if not Conv_DetectType(AFilename, AEncoding) and (AEncoding=nil) {not even a best guess} then
AEncoding := TAsciiEncoding;
fsr.Seek(0, soEnd);
Result := TStreamEncoder.Open(fsr, AEncoding.Create, {OwnsStream=}true);
except
FreeAndNil(fsr);
raise;
end;
end;
//Finds a class by it's name. Good to store encoding selection in a permanent way.
function FindEncodingByClassName(const AClassName: string): CEncoding;
begin
//Stupid for now
if AClassName='TAsciiEncoding' then
Result := TAsciiEncoding
else
{$IFDEF MSWINDOWS}
if AClassName='TAcpEncoding' then
Result := TAcpEncoding
else
{$ENDIF}
if AClassName='TUTF8Encoding' then
Result := TUTF8Encoding
else
if AClassName='TUTF16LEEncoding' then
Result := TUTF16LEEncoding
else
if AClassName='TUTF16BEEncoding' then
Result := TUTF16BEEncoding
else
if AClassName='TEUCEncoding' then
Result := TEUCEncoding
else
if AClassName='TSJISEncoding' then
Result := TSJISEncoding
else
if AClassName='TJISEncoding' then
Result := TJISEncoding
else
if AClassName='TOldJISEncoding' then
Result := TOldJISEncoding
else
if AClassName='TNECJISEncoding' then
Result := TNECJISEncoding
else
if AClassName='TGBEncoding' then
Result := TGBEncoding
else
if AClassName='TBIG5Encoding' then
Result := TBIG5Encoding
else
Result := nil;
end;
function FindEncodingByName(AName: string): CEncoding;
begin
AName := LowerCase(AName);
if AName='ascii' then
Result := TAsciiEncoding
else
if (AName='ansi')
or (AName='acp') then
Result := TAcpEncoding
else
if (AName='utf8')
or (AName='utf-8') then
Result := TUTF8Encoding
else
if (AName='utf16')
or (AName='utf-16')
or (AName='utf16le')
or (AName='utf16-le') then
Result := TUTF16LEEncoding
else
if (AName='utf16be')
or (AName='utf16-be') then
Result := TUTF16BEEncoding
else
if AName='euc' then
Result := TEUCEncoding
else
if AName='jis' then
Result := TJISEncoding
else
if (AName='sjis')
or (AName='shiftjis')
or (AName='shift-jis') then
Result := TSJISEncoding
else
if AName='gb' then
Result := TGBEncoding
else
if AName='big5' then
Result := TBIG5Encoding
else
Result := nil;
end;
{ Compares binary data in streams }
function CompareStreams(const AStream1, AStream2: TStream): boolean;
var
b1, b2: byte;
r1, r2: boolean;
begin
{ Can be easily made somewhat faster by reading in dwords and comparing
only the number of bytes read (e.g. case 1: 2: 3: 4: if (d1 & $000F) == etc.) }
Result := true;
while true do begin
r1 := (AStream1.Read(b1,1)=1);
r2 := (AStream2.Read(b2,1)=1);
if r1 xor r2 then
Result := false;
if b1<>b2 then
Result := false;
if (not r1) or (not Result) then //not Result => diff; not r1 => both over
break;
end;
end;
function CompareFiles(const AFilename1, AFilename2: TFilename): boolean;
var f1, f2: TStream;
begin
f1 := nil;
f2 := nil;
try
f1 := TStreamReader.Create(
TFileStream.Create(AFilename1, fmOpenRead),
true
);
f2 := TStreamReader.Create(
TFileStream.Create(AFilename2, fmOpenRead),
true
);
Result := CompareStreams(f1, f2);
finally
FreeAndNil(f2);
FreeAndNil(f1);
end;
end;
{ Compatibility functions }
function AnsiFileReader(const AFilename: TFilename): TStreamDecoder;
begin
{$IFDEF MSWINDOWS}
Result := OpenTextFile(AFilename, TAcpEncoding);
{$ELSE}
Result := OpenTextFile(AFilename, TAsciiEncoding);
{$ENDIF}
end;
function UnicodeFileReader(const AFilename: TFilename): TStreamDecoder;
begin
Result := OpenTextFile(AFilename, TUnicodeEncoding);
end;
function ConsoleReader(AEncoding: TEncoding = nil): TStreamDecoder;
var AStream: TStream;
{$IFDEF MSWINDOWS}
AInputHandle: THandle;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
AInputHandle := GetStdHandle(STD_INPUT_HANDLE);
AStream := THandleStream.Create(AInputHandle);
{$ELSE}
{$IFDEF FPC}
AStream := TIOStream.Create(iosInput);
{$ELSE}
raise Exception.Create('Console reader not supported on this platform/compiler.');
{$ENDIF}
{$ENDIF}
if AEncoding=nil then begin
{$IFDEF MSWINDOWS}
{ If our outputs are redirected, we *really* do not know what to expect, so we
default to UTF8 (allows for ASCII and interoperability).
But if we are sure we're reading from console, we may optimize and use the
console CP. }
if GetFileType(AInputHandle)=FILE_TYPE_CHAR then
AEncoding := TMultibyteEncoding.Create(GetConsoleOutputCP())
else
AEncoding := TUTF8Encoding.Create();
{$ELSE}
AEncoding := TUTF8Encoding.Create();
{$ENDIF}
end;
Result := TStreamDecoder.Open(
AStream,
AEncoding,
{OwnsStream=}true
);
end;
function UnicodeStreamReader(AStream: TStream; AOwnsStream: boolean = false): TStreamDecoder;
begin
Result := TStreamDecoder.Open(AStream, TUnicodeEncoding.Create, AOwnsStream);
end;
function FileReader(const AFilename: TFilename): TStreamDecoder;
begin
{$IFDEF UNICODE}
Result := UnicodeFileReader(AFilename);
{$ELSE}
Result := AnsiFileReader(AFilename);
{$ENDIF}
end;
function AnsiFileWriter(const AFilename: TFilename): TStreamEncoder;
begin
{$IFDEF MSWINDOWS}
Result := CreateTextFile(AFilename, TAcpEncoding);
{$ELSE}
Result := CreateTextFile(AFilename, TAsciiEncoding);
{$ENDIF}
end;
function UnicodeFileWriter(const AFilename: TFilename): TStreamEncoder;
begin
Result := CreateTextFile(AFilename, TUnicodeEncoding);
end;
function ConsoleWriter(AEncoding: TEncoding): TStreamEncoder;
var AStream: TStream;
{$IFDEF MSWINDOWS}
AOutputHandle: THandle;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
AOutputHandle := GetStdHandle(STD_OUTPUT_HANDLE);
AStream := THandleStream.Create(AOutputHandle);
{$ELSE}
{$IFDEF FPC}
AStream := TIOStream.Create(iosOutput);
{$ELSE}
raise Exception.Create('Console writer not supported on this platform/compiler.');
{$ENDIF}
{$ENDIF}
if AEncoding=nil then begin
{$IFDEF MSWINDOWS}
{ If our outputs are redirected, we *really* do not know which codepage to
output in, so we use UTF8 as default.
But if we are sure we're printing to console, we may optimize and use the
console CP. }
if GetFileType(AOutputHandle)=FILE_TYPE_CHAR then
AEncoding := TMultibyteEncoding.Create(GetConsoleOutputCP())
else
AEncoding := TUTF8Encoding.Create();
{$ELSE}
AEncoding := TUTF8Encoding.Create();
{$ENDIF}
end;
Result := TStreamEncoder.Open(
AStream,
AEncoding,
{OwnsStream=}true
);
end;
{ Same, but writes to ErrOutput }
function ErrorConsoleWriter(AEncoding: TEncoding): TStreamEncoder;
var AStream: TStream;
{$IFDEF MSWINDOWS}
AOutputHandle: THandle;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
AOutputHandle := GetStdHandle(STD_ERROR_HANDLE);
AStream := THandleStream.Create(AOutputHandle);
{$ELSE}
{$IFDEF FPC}
AStream := TIOStream.Create(iosError);
{$ELSE}
raise Exception.Create('Console writer not supported on this platform/compiler.');
{$ENDIF}
{$ENDIF}
if AEncoding=nil then begin
{$IFDEF MSWINDOWS}
{ See comments for ConsoleWriter() }
if GetFileType(AOutputHandle)=FILE_TYPE_CHAR then
AEncoding := TMultibyteEncoding.Create(GetConsoleOutputCP())
else
AEncoding := TUTF8Encoding.Create();
{$ELSE}
AEncoding := TUTF8Encoding.Create();
{$ENDIF}
end;
Result := TStreamEncoder.Open(
AStream,
AEncoding,
{OwnsStream=}true
);
end;
function UnicodeStreamWriter(AStream: TStream; AOwnsStream: boolean = false): TStreamEncoder;
begin
Result := TStreamEncoder.Open(AStream, TUnicodeEncoding.Create, AOwnsStream);
end;
function FileWriter(const AFilename: TFilename): TStreamEncoder;
begin
{$IFDEF UNICODE}
Result := UnicodeFileWriter(AFilename);
{$ELSE}
Result := AnsiFileWriter(AFilename);
{$ENDIF}
end;
{ Reads out everything there is in the file and counts lines. Do not forget to
rewind later. Do not do with Console, TCP and other non-rewindable streams.
Avoid counting lines beforehand where possible, prefer just parsing for however
much lines there is. }
function GetLineCount(AText: TStreamDecoder): integer;
var ln: UnicodeString;
begin
Result := 0;
while AText.ReadLn(ln) do
Inc(Result);
end;
end.
|
unit UTipe;
interface
const
NMAX = 100;
HARGAUPGRADE = 1000;
type DaftarPerintah=record
Isi : array[1..NMAX] of string;
Neff:integer;
end;
type UserInput = record
Perintah:string;
Neff:integer;
Opsi:array[1..NMAX]of string;
end;
type Tabel = record
Isi : array[1..NMAX] of array[1..NMAX] of string;
NKol : integer;
NBar : integer;
end;
type UkuranTabel = record
Ukuran : array[1..NMAX] of integer;
Kolom : integer;
end;
type Tanggal = record
Hari : integer;
Bulan : integer;
Tahun : integer;
end;
type BahanMentah = record
Nama:string;
Harga:longint;
Kadaluarsa:integer;
end;
type BahanOlahan = record
Nama:string;
Harga:longint;
JumlahBahan:integer;
Bahan:array[1..10] of string;
end;
type DaftarBahanMentah = record
Isi:array[1..NMAX] of BahanMentah;
Neff:integer;
end;
type DaftarBahanOlahan = record
Isi:array[1..NMAX] of BahanOlahan;
Neff:integer;
end;
type InventoriBahanMentah = record
Isi:array[1..NMAX] of BahanMentah;
Jumlah:array[1..NMAX] of integer;
TanggalBeli:array[1..NMAX] of Tanggal;
Sorted:boolean;
Total:integer;
Neff:integer;
end;
type InventoriBahanOlahan = record
Isi:array[1..NMAX] of BahanOlahan;
Jumlah:array[1..NMAX] of integer;
TanggalBuat:array[1..NMAX] of Tanggal;
Sorted:boolean;
Total:integer;
Neff:integer;
end;
type Resep = record
Nama:string;
Harga:longint;
JumlahBahan:integer;
Bahan:array[1..20] of string;
end;
type DaftarResep = record
Isi:array[1..NMAX]of Resep;
Neff:integer;
Sorted:boolean;
end;
type Simulasi = record
Nomor:integer;
Tanggal:Tanggal;
JumlahHidup:integer;
Energi:integer;
Kapasitas:integer;
BeliMentah:integer;
BuatOlahan:integer;
JualOlahan:integer;
JualResep:integer;
Pemasukan:longint;
Pengeluaran:longint;
TotalUang:longint;
end;
type DaftarSimulasi = record
Isi:array[1..NMAX]of Simulasi;
Neff:integer;
end;
implementation
end.
|
unit pangoft2lib;
interface
uses glib, pangolib, fontconfiglib, freetypelib;
(* Pango
* pangofc-font.h: Base fontmap type for fontconfig-based backends
*
* Copyright (C) 2003 Red Hat Software
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*)
//#define PANGO_TYPE_FC_FONT (pango_fc_font_get_type ())
//#define PANGO_FC_FONT(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_FC_FONT, PangoFcFont))
//#define PANGO_IS_FC_FONT(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_FC_FONT))
//#if defined(PANGO_ENABLE_ENGINE) || defined(PANGO_ENABLE_BACKEND)
(**
* PANGO_RENDER_TYPE_FC:
*
* A string constant used to identify shape engines that work
* with the fontconfig based backends. See the @engine_type field
* of #PangoEngineInfo.
**)
const
PANGO_RENDER_TYPE_FC = 'PangoRenderFc';
//#ifdef PANGO_ENABLE_BACKEND
//#define PANGO_FC_FONT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), PANGO_TYPE_FC_FONT, PangoFcFontClass))
//#define PANGO_IS_FC_FONT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), PANGO_TYPE_FC_FONT))
//#define PANGO_FC_FONT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), PANGO_TYPE_FC_FONT, PangoFcFontClass))
type
(**
* PangoFcFont:
*
* #PangoFcFont is a base class for font implementations
* using the Fontconfig and FreeType libraries and is used in
* conjunction with #PangoFcFontMap. When deriving from this
* class, you need to implement all of its virtual functions
* other than shutdown() along with the get_glyph_extents()
* virtual function from #PangoFont.
**)
PPangoFcFont = ^PangoFcFont;
_PangoFcFont = record
parent_instance: PangoFont;
font_pattern: PFcPattern; (* fully resolved pattern *)
fontmap: PPangoFontMap; (* associated map *)
priv: gpointer; (* used internally *)
matrix: TPangoMatrix; (* used internally *)
description: PPangoFontDescription;
metrics_by_lang: PGSList;
is_hinted: guint; // : 1; todo
is_transformed: guint;// : 1; todo
end;
PangoFcFont = _PangoFcFont;
(**
* PangoFcFontClass:
* @lock_face: Returns the FT_Face of the font and increases
* the reference count for the face by one.
* @unlock_face: Decreases the reference count for the
* FT_Face of the font by one. When the count is zero,
* the #PangoFcFont subclass is allowed to free the
* FT_Face.
* @has_char: Return %TRUE if the the font contains a glyph
* corresponding to the specified character.
* @get_glyph: Gets the glyph that corresponds to the given
* Unicode character.
* @get_unknown_glyph: Gets the glyph that should be used to
* display an unknown-glyph indication for the specified
* Unicode character.
* May be %NULL.
* @shutdown: Performs any font-specific shutdown code that
* needs to be done when pango_fc_font_map_shutdown is called.
* May be %NULL.
*
* Class structure for #PangoFcFont.
**)
PPangoFcFontClass = ^PangoFcFontClass;
_PangoFcFontClass = record
(*< private >*)
parent_class: PangoFontClass;
(*< public >*)
lock_face: function(font: PPangoFcFont): FT_Face; cdecl;
unlock_face: procedure(font: PPangoFcFont); cdecl;
has_char: function(font: PPangoFcFont; wc: gunichar): gboolean; cdecl;
get_glyph: function(font: PPangoFcFont; wc: gunichar): guint; cdecl;
get_unknown_glyph: function(font: PPangoFcFont; wc: gunichar): PangoGlyph; cdecl;
shutdown: procedure(font: PPangoFcFont); cdecl;
(*< private >*)
(* Padding for future expansion *)
_pango_reserved1: procedure;
_pango_reserved2: procedure;
_pango_reserved3: procedure;
_pango_reserved4: procedure;
end;
PangoFcFontClass = _PangoFcFontClass;
//#endif (* PANGO_ENABLE_BACKEND *)
function pango_fc_font_has_char(font: PPangoFcFont; wc: gunichar): gboolean; cdecl;
function pango_fc_font_get_glyph(font: PPangoFcFont; wc: gunichar): guint; cdecl;
//#ifndef PANGO_DISABLE_DEPRECATED
function pango_fc_font_get_unknown_glyph(font: PPangoFcFont; wc: gunichar): PangoGlyph; cdecl;
//#endif (* PANGO_DISABLE_DEPRECATED *)
procedure pango_fc_font_kern_glyphs(font: PPangoFcFont; glyphs: PPangoGlyphString); cdecl;
//#endif (* PANGO_ENABLE_ENGINE || PANGO_ENABLE_BACKEND *)
function pango_fc_font_get_type: GType; cdecl;
function pango_fc_font_lock_face(font: PPangoFcFont): FT_Face; cdecl;
procedure pango_fc_font_unlock_face(font: PPangoFcFont); cdecl;
(* Pango
* pangofc-decoder.h: Custom encoders/decoders on a per-font basis.
*
* Copyright (C) 2004 Red Hat Software
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*)
//#define PANGO_TYPE_FC_DECODER (pango_fc_decoder_get_type())
//#define PANGO_FC_DECODER(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_FC_DECODER, PangoFcDecoder))
//#define PANGO_IS_FC_DECODER(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_FC_DECODER))
type
(**
* PangoFcDecoder:
*
* #PangoFcDecoder is a virtual base class that implementations will
* inherit from. It's the interface that is used to define a custom
* encoding for a font. These objects are created in your code from a
* function callback that was originally registered with
* pango_fc_font_map_add_decoder_find_func(). Pango requires
* information about the supported charset for a font as well as the
* individual character to glyph conversions. Pango gets that
* information via the #get_charset and #get_glyph callbacks into your
* object implementation.
*
* Since: 1.6
**)
PPangoFcDecoder = ^PangoFcDecoder;
_PangoFcDecoder = record
(*< private >*)
parent_instance: GObject;
end;
PangoFcDecoder = _PangoFcDecoder;
(**
* PangoFcDecoderClass:
* @get_charset: This returns an #FcCharset given a #PangoFcFont that
* includes a list of supported characters in the font. The
* #FcCharSet that is returned should be an internal reference to your
* code. Pango will not free this structure. It is important that
* you make this callback fast because this callback is called
* separately for each character to determine Unicode coverage.
* @get_glyph: This returns a single #PangoGlyph for a given Unicode
* code point.
*
* Class structure for #PangoFcDecoder.
*
* Since: 1.6
**)
PPangoFcDecoderClass = ^PangoFcDecoderClass;
_PangoFcDecoderClass = record
(*< private >*)
parent_class: GObjectClass;
(* vtable - not signals *)
(*< public >*)
get_charset: function(decoder: PPangoFcDecoder; fcfont: PPangoFcFont): PFcCharSet; cdecl;
get_glyph: function(decoder: PPangoFcDecoder; fcfont: PPangoFcFont; wc: guint32): PangoGlyph; cdecl;
(*< private >*)
(* Padding for future expansion *)
_pango_reserved1: procedure;
_pango_reserved2: procedure;
_pango_reserved3: procedure;
_pango_reserved4: procedure;
end;
PangoFcDecoderClass = _PangoFcDecoderClass;
//#define PANGO_FC_DECODER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), PANGO_TYPE_FC_DECODER, PangoFcDecoderClass))
//#define PANGO_IS_FC_DECODER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), PANGO_TYPE_FC_DECODER))
//#define PANGO_FC_DECODER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), PANGO_TYPE_FC_DECODER, PangoFcDecoderClass))
function pango_fc_decoder_get_type: GType; cdecl;
function pango_fc_decoder_get_charset(decoder: PPangoFcDecoder; fcfont: PPangoFcFont): PFcCharSet; cdecl;
function pango_fc_decoder_get_glyph(decoder: PPangoFcDecoder; fcfont: PPangoFcFont; wc: guint32): PangoGlyph; cdecl;
(* Pango
* pangofc-fontmap.h: Base fontmap type for fontconfig-based backends
*
* Copyright (C) 2003 Red Hat Software
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*)
//#ifdef PANGO_ENABLE_BACKEND
(**
* PangoFcFontsetKey:
*
* An opaque structure containing all the information needed for
* loading a fontset with the PangoFc fontmap.
*
* Since: 1.24
**)
type
PPangoFcFontsetKey = ^PangoFcFontsetKey;
_PangoFcFontsetKey = record
end;
PangoFcFontsetKey = _PangoFcFontsetKey;
function pango_fc_fontset_key_get_language(const key: PPangoFcFontsetKey): PPangoLanguage; cdecl;
function pango_fc_fontset_key_get_description(const key: PPangoFcFontsetKey): PPangoFontDescription; cdecl;
function pango_fc_fontset_key_get_matrix(const key: PPangoFcFontsetKey): PPangoMatrix; cdecl;
function pango_fc_fontset_key_get_absolute_size(const key: PPangoFcFontsetKey): double; cdecl;
function pango_fc_fontset_key_get_resolution(const key: PPangoFcFontsetKey): double; cdecl;
function pango_fc_fontset_key_get_context_key(const key: PPangoFcFontsetKey): gpointer; cdecl;
(**
* PangoFcFontKey:
*
* An opaque structure containing all the information needed for
* loading a font with the PangoFc fontmap.
*
* Since: 1.24
**)
type
PPangoFcFontKey = ^PangoFcFontKey;
_PangoFcFontKey = record
end;
PangoFcFontKey = _PangoFcFontKey;
function pango_fc_font_key_get_pattern(const key: PPangoFcFontKey): PFcPattern; cdecl;
function pango_fc_font_key_get_matrix(const key: PPangoFcFontKey): PPangoMatrix; cdecl;
function pango_fc_font_key_get_context_key(const key: PPangoFcFontKey): gpointer; cdecl;
(*
* PangoFcFontMap
*)
//#define PANGO_TYPE_FC_FONT_MAP (pango_fc_font_map_get_type ())
//#define PANGO_FC_FONT_MAP(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_FC_FONT_MAP, PangoFcFontMap))
//#define PANGO_IS_FC_FONT_MAP(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_FC_FONT_MAP))
type
PPangoFcFontMapPrivate = ^PangoFcFontMapPrivate;
_PangoFcFontMapPrivate = record end;
PangoFcFontMapPrivate = _PangoFcFontMapPrivate;
(**
* PangoFcFontMap:
*
* #PangoFcFontMap is a base class for font map implementations
* using the Fontconfig and FreeType libraries. To create a new
* backend using Fontconfig and FreeType, you derive from this class
* and implement a new_font() virtual function that creates an
* instance deriving from #PangoFcFont.
**)
PPangoFcFontMap = ^PangoFcFontMap;
_PangoFcFontMap = record
parent_instance: PangoFontMap;
priv: PPangoFcFontMapPrivate;
end;
PangoFcFontMap = _PangoFcFontMap;
(**
* PangoFcFontMapClass:
* @default_substitute: Substitutes in default values for
* unspecified fields in a #FcPattern. This will be called
* prior to creating a font for the pattern. May be %NULL.
* Deprecated in favor of @font_key_substitute().
* @new_font: Creates a new #PangoFcFont for the specified
* pattern of the appropriate type for this font map. The
* @pattern argument must be passed to the "pattern" property
* of #PangoFcFont when you call g_object_new(). Deprecated
* in favor of @create_font().
* @get_resolution: Gets the resolution (the scale factor
* between logical and absolute font sizes) that the backend
* will use for a particular fontmap and context. @context
* may be null.
* @context_key_get: Gets an opaque key holding backend
* specific options for the context that will affect
* fonts created by create_font(). The result must point to
* persistant storage owned by the fontmap. This key
* is used to index hash tables used to look up fontsets
* and fonts.
* @context_key_copy: Copies a context key. Pango uses this
* to make a persistant copy of the value returned from
* @context_key_get.
* @context_key_free: Frees a context key copied with
* @context_key_copy.
* @context_key_hash: Gets a hash value for a context key
* @context_key_equal: Compares two context keys for equality.
* @fontset_key_substitute: Substitutes in default values for
* unspecified fields in a #FcPattern. This will be called
* prior to creating a font for the pattern. May be %NULL.
* (Since: 1.24)
* @create_font: Creates a new #PangoFcFont for the specified
* pattern of the appropriate type for this font map using
* information from the font key that is passed in. The
* @pattern member of @font_key can be retrieved using
* pango_fc_font_key_get_pattern() and must be passed to
* the "pattern" property of #PangoFcFont when you call
* g_object_new(). If %NULL, new_font() is used.
* (Since: 1.24)
*
* Class structure for #PangoFcFontMap.
**) PPangoFcFontMapClass = ^PangoFcFontMapClass;
_PangoFcFontMapClass = record
(*< private >*)
parent_class: PangoFontMapClass;
(*< public >*)
(* Deprecated in favor of fontset_key_substitute *)
default_substitute: procedure(fontmap: PPangoFcFontMap; pattern: PFcPattern); cdecl;
(* Deprecated in favor of create_font *)
new_font: function(fontmap: PPangoFcFontMap; pattern: PFcPattern): PPangoFcFont; cdecl;
get_resolution: function(fcfontmap: PPangoFcFontMap; context: PPangoContext): double; cdecl;
context_key_get: function(fcfontmap: PPangoFcFontMap; context: PPangoContext): gconstpointer; cdecl;
context_key_copy: function(fcfontmap: PPangoFcFontMap; key: gconstpointer): gpointer; cdecl;
context_key_free: procedure(fcfontmap: PPangoFcFontMap; key: gpointer); cdecl;
context_key_hash: function(fcfontmap: PPangoFcFontMap; key: gconstpointer): guint32; cdecl;
context_key_equal: function(fcfontmap: PPangoFcFontMap; key_a: gconstpointer; key_b: gconstpointer): gboolean; cdecl;
fontset_key_substitute: procedure(fontmap: PPangoFcFontMap; fontsetkey: PPangoFcFontsetKey; pattern: PFcPattern); cdecl;
create_font: function(fontmap: PPangoFcFontMap; fontkey: PPangoFcFontKey): PPangoFcFont; cdecl;
(*< private >*)
(* Padding for future expansion *)
_pango_reserved1: procedure;
_pango_reserved2: procedure;
_pango_reserved3: procedure;
_pango_reserved4: procedure;
end;
PangoFcFontMapClass = _PangoFcFontMapClass;
//#ifdef PANGO_ENABLE_BACKEND
//#define PANGO_FC_FONT_MAP_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), PANGO_TYPE_FC_FONT_MAP, PangoFcFontMapClass))
//#define PANGO_IS_FC_FONT_MAP_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), PANGO_TYPE_FC_FONT_MAP))
//#define PANGO_FC_FONT_MAP_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), PANGO_TYPE_FC_FONT_MAP, PangoFcFontMapClass))
function pango_fc_font_map_create_context(fcfontmap: PPangoFcFontMap): PPangoContext; cdecl;
procedure pango_fc_font_map_shutdown(fcfontmap: PPangoFcFontMap); cdecl;
function pango_fc_font_map_get_type: GType; cdecl;
procedure pango_fc_font_map_cache_clear(fcfontmap: PPangoFcFontMap); cdecl;
(**
* PangoFcDecoderFindFunc:
* @pattern: a fully resolved #FcPattern specifying the font on the system
* @user_data: user data passed to pango_fc_font_map_add_decoder_find_func()
*
* Callback function passed to pango_fc_font_map_add_decoder_find_func().
*
* Return value: a new reference to a custom decoder for this pattern,
* or %NULL if the default decoder handling should be used.
**)
type
PangoFcDecoderFindFunc = function(pattern: PFcPattern; user_data: gpointer): PPangoFcDecoder; cdecl;
procedure pango_fc_font_map_add_decoder_find_func(fcfontmap: PPangoFcFontMap; findfunc: PangoFcDecoderFindFunc; user_data: gpointer; dnotify: GDestroyNotify); cdecl;
function pango_fc_font_description_from_pattern(pattern: PFcPattern; include_size: gboolean): PPangoFontDescription; cdecl;
(**
* PANGO_FC_GRAVITY:
*
* String representing a fontconfig property name that Pango sets on any
* fontconfig pattern it passes to fontconfig if a #PangoGravity other
* than %PangoGravitySouth is desired.
*
* The property will have a #PangoGravity value as a string, like "east".
* This can be used to write fontconfig configuration rules to choose
* different fonts for horizontal and vertical writing directions.
*
* Since: 1.20
*)
const
PANGO_FC_GRAVITY = 'pangogravity';
(**
* PANGO_FC_VERSION:
*
* String representing a fontconfig property name that Pango sets on any
* fontconfig pattern it passes to fontconfig.
*
* The property will have an integer value equal to what
* pango_version() returns.
* This can be used to write fontconfig configuration rules that only affect
* certain pango versions (or only pango-using applications, or only
* non-pango-using applications).
*
* Since: 1.20
*)
PANGO_FC_VERSION = 'pangoversion';
(**
* PANGO_FC_PRGNAME:
*
* String representing a fontconfig property name that Pango sets on any
* fontconfig pattern it passes to fontconfig.
*
* The property will have a string equal to what
* g_get_prgname() returns.
* This can be used to write fontconfig configuration rules that only affect
* certain applications.
*
* Since: 1.24
*)
PANGO_FC_PRGNAME = 'pangoprgname';
(* Pango
* pangoft2.h:
*
* Copyright (C) 1999 Red Hat Software
* Copyright (C) 2000 Tor Lillqvist
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*)
//#ifndef PANGO_DISABLE_DEPRECATED
PANGO_RENDER_TYPE_FT2 = 'PangoRenderFT2';
//#endif
//#define PANGO_TYPE_FT2_FONT_MAP (pango_ft2_font_map_get_type ())
//#define PANGO_FT2_FONT_MAP(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_FT2_FONT_MAP, PangoFT2FontMap))
//#define PANGO_FT2_IS_FONT_MAP(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_FT2_FONT_MAP))
type
PPangoFT2FontMap = ^PangoFT2FontMap;
_PangoFT2FontMap = record end;
PangoFT2FontMap = _PangoFT2FontMap;
PangoFT2SubstituteFunc = procedure(pattern: PFcPattern; data: gpointer); cdecl;
(* Calls for applications *)
procedure pango_ft2_render(bitmap: PFT_Bitmap; font: PPangoFont; glyphs: PPangoGlyphString; x: gint; y: gint); cdecl;
procedure pango_ft2_render_transformed(bitmap: PFT_Bitmap; const matrix: PPangoMatrix; font: PPangoFont; glyphs: PPangoGlyphString; x: Integer; y: Integer); cdecl;
procedure pango_ft2_render_layout_line(bitmap: PFT_Bitmap; line: PPangoLayoutLine; x: Integer; y: Integer); cdecl;
procedure pango_ft2_render_layout_line_subpixel(bitmap: PFT_Bitmap; line: PPangoLayoutLine; x: Integer; y: Integer); cdecl;
procedure pango_ft2_render_layout(bitmap: PFT_Bitmap; layout: PPangoLayout; x: Integer; y: Integer); cdecl;
procedure pango_ft2_render_layout_subpixel(bitmap: PFT_Bitmap; layout: PPangoLayout; x: Integer; y: Integer); cdecl;
function pango_ft2_font_map_get_type: GType; cdecl;
function pango_ft2_font_map_new: PPangoFontMap; cdecl;
procedure pango_ft2_font_map_set_resolution(fontmap: PPangoFT2FontMap; dpi_x: double; dpi_y: double); cdecl;
procedure pango_ft2_font_map_set_default_substitute(fontmap: PPangoFT2FontMap; func: PangoFT2SubstituteFunc; data: gpointer; notify: GDestroyNotify); cdecl;
procedure pango_ft2_font_map_substitute_changed(fontmap: PPangoFT2FontMap); cdecl;
//#ifndef PANGO_DISABLE_DEPRECATED
function pango_ft2_font_map_create_context(fontmap: PPangoFT2FontMap): PPangoContext; cdecl;
//#endif
(* API for rendering modules
*)
//#ifndef PANGO_DISABLE_DEPRECATED
function pango_ft2_get_context(dpi_x: double; dpi_y: double): PPangoContext ; cdecl;
function pango_ft2_font_map_for_display: PPangoFontMap; cdecl;
procedure pango_ft2_shutdown_display; cdecl;
function pango_ft2_get_unknown_glyph(font: PPangoFont): PangoGlyph; cdecl;
function pango_ft2_font_get_kerning(font: PPangoFont; left: PangoGlyph; right: PangoGlyph): Integer; cdecl;
function pango_ft2_font_get_face(font: PPangoFont): FT_Face; cdecl;
function pango_ft2_font_get_coverage(font: PPangoFont; language: PPangoLanguage): PPangoCoverage; cdecl;
//#endif (* PANGO_DISABLE_DEPRECATED *)
(* Pango
* pango-ot.h:
*
* Copyright (C) 2000,2007 Red Hat Software
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*)
type
PPangoOTTag = ^PangoOTTag;
PangoOTTag = guint32;
//#define PANGO_OT_TAG_MAKE(c1,c2,c3,c4) ((PangoOTTag) FT_MAKE_TAG (c1, c2, c3, c4))
//#define PANGO_OT_TAG_MAKE_FROM_STRING(s) (PANGO_OT_TAG_MAKE(((const char *) s)[0], \
// ((const char *) s)[1], \
// ((const char *) s)[2], \
// ((const char *) s)[3]))
PPangoOTInfo = ^PangoOTInfo;
_PangoOTInfo = record end;
PangoOTInfo = _PangoOTInfo;
PPangoOTBuffer = ^PangoOTBuffer;
_PangoOTBuffer = record end;
PangoOTBuffer = _PangoOTBuffer;
(* Note that this must match HB_GlyphItem *)
PPangoOTGlyph = ^PangoOTGlyph;
_PangoOTGlyph = record
glyph: guint;
properties: guint;
cluster: guint;
component: gushort;
ligID: gushort;
property_cache: gushort; (* Internal *)
end;
PangoOTGlyph = _PangoOTGlyph;
PPangoOTRuleset = ^PangoOTRuleset;
_PangoOTRuleset = record end;
PangoOTRuleset = _PangoOTRuleset;
PPangoOTFeatureMap = ^PangoOTFeatureMap;
_PangoOTFeatureMap = record
feature_name: array[0..4] of AnsiChar;
property_bit: gulong;
end;
PangoOTFeatureMap = _PangoOTFeatureMap;
PPangoOTRulesetDescription = ^PangoOTRulesetDescription;
_PangoOTRulesetDescription = record
script: PangoScript;
language: PPangoLanguage;
static_gsub_features: PPangoOTFeatureMap;
n_static_gsub_features: guint;
static_gpos_features: PPangoOTFeatureMap;
n_static_gpos_features: guint;
other_features: PPangoOTFeatureMap;
n_other_features: guint;
end;
PangoOTRulesetDescription = _PangoOTRulesetDescription;
PangoOTTableType = (
PANGO_OT_TABLE_GSUB,
PANGO_OT_TABLE_GPOS
);
const
PANGO_OT_ALL_GLYPHS : guint = $FFFF;
PANGO_OT_NO_FEATURE : guint = $FFFF;
PANGO_OT_NO_SCRIPT : guint = $FFFF;
PANGO_OT_DEFAULT_LANGUAGE: guint = $FFFF;
//#define PANGO_OT_TAG_DEFAULT_SCRIPT PANGO_OT_TAG_MAKE ('D', 'F', 'L', 'T')
//#define PANGO_OT_TAG_DEFAULT_LANGUAGE PANGO_OT_TAG_MAKE ('d', 'f', 'l', 't')
//#define PANGO_TYPE_OT_INFO (pango_ot_info_get_type ())
//#define PANGO_OT_INFO(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_OT_INFO, PangoOTInfo))
//#define PANGO_IS_OT_INFO(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_OT_INFO))
function pango_ot_info_get_type: GType; cdecl;
//#define PANGO_TYPE_OT_RULESET (pango_ot_ruleset_get_type ())
//#define PANGO_OT_RULESET(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_OT_RULESET, PangoOTRuleset))
//#define PANGO_IS_OT_RULESET(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_OT_RULESET))
function pango_ot_ruleset_get_type: GType; cdecl;
function pango_ot_info_get(face: FT_Face): PPangoOTInfo; cdecl;
function pango_ot_info_find_script(info: PPangoOTInfo; table_type: PangoOTTableType; script_tag: PangoOTTag; script_index: Pguint): gboolean; cdecl;
function pango_ot_info_find_language(info: PPangoOTInfo; table_type: PangoOTTableType; script_index: guint; language_tag: PangoOTTag; language_index: Pguint; required_feature_index: Pguint): gboolean; cdecl;
function pango_ot_info_find_feature(info: PPangoOTInfo; table_type: PangoOTTableType; feature_tag: PangoOTTag; script_index: guint; language_index: guint; feature_index: Pguint): gboolean; cdecl;
function pango_ot_info_list_scripts(info: PPangoOTInfo; table_type: PangoOTTableType): PPangoOTTag; cdecl;
function pango_ot_info_list_languages(info: PPangoOTInfo; table_type: PangoOTTableType; script_index: guint; language_tag: PangoOTTag): PPangoOTTag; cdecl;
function pango_ot_info_list_features(info: PPangoOTInfo; table_type: PangoOTTableType; tag: PangoOTTag; script_index: guint; language_index: guint): PPangoOTTag; cdecl;
function pango_ot_buffer_new(font: PPangoFcFont): PPangoOTBuffer; cdecl;
procedure pango_ot_buffer_destroy(buffer: PPangoOTBuffer); cdecl;
procedure pango_ot_buffer_clear(buffer: PPangoOTBuffer); cdecl;
procedure pango_ot_buffer_set_rtl(buffer: PPangoOTBuffer; rtl: gboolean); cdecl;
procedure pango_ot_buffer_add_glyph(buffer: PPangoOTBuffer; glyph: guint; properties: guint; cluster: guint); cdecl;
procedure pango_ot_buffer_get_glyphs(const buffer: PPangoOTBuffer; var glyphs: PPangoOTGlyph; var n_glyphs: Integer); cdecl;
procedure pango_ot_buffer_output(const buffer: PPangoOTBuffer; glyphs: PPangoGlyphString); cdecl;
procedure pango_ot_buffer_set_zero_width_marks(buffer: PPangoOTBuffer; zero_width_marks: gboolean); cdecl;
function pango_ot_ruleset_get_for_description(info: PPangoOTInfo; const desc: PPangoOTRulesetDescription): PPangoOTRuleset; cdecl;
function pango_ot_ruleset_new(info: PPangoOTInfo): PPangoOTRuleset; cdecl;
function pango_ot_ruleset_new_for(info: PPangoOTInfo; script: PangoScript; language: PPangoLanguage): PPangoOTRuleset; cdecl;
function pango_ot_ruleset_new_from_description(info: PPangoOTInfo; const desc: PPangoOTRulesetDescription): PPangoOTRuleset; cdecl;
procedure pango_ot_ruleset_add_feature(ruleset: PPangoOTRuleset; table_type: PangoOTTableType; feature_index: guint; property_bit: gulong); cdecl;
function pango_ot_ruleset_maybe_add_feature(ruleset: PPangoOTRuleset; table_type: PangoOTTableType; feature_tag: PangoOTTag; property_bit: gulong): gboolean; cdecl;
function pango_ot_ruleset_maybe_add_features(ruleset: PPangoOTRuleset; table_type: PangoOTTableType; const features: PPangoOTFeatureMap; n_features: guint): guint; cdecl;
function pango_ot_ruleset_get_feature_count(const ruleset: PPangoOTRuleset; n_gsub_features: Pguint; n_gpos_features: Pguint): guint; cdecl;
procedure pango_ot_ruleset_substitute(const ruleset: PPangoOTRuleset; buffer: PPangoOTBuffer); cdecl;
procedure pango_ot_ruleset_position(const ruleset: PPangoOTRuleset; buffer: PPangoOTBuffer); cdecl;
function pango_ot_tag_to_script(script_tag: PangoOTTag): PangoScript; cdecl;
function pango_ot_tag_from_script(script: PangoScript): PangoOTTag; cdecl;
function pango_ot_tag_to_language(language_tag: PangoOTTag): PPangoLanguage; cdecl;
function pango_ot_tag_from_language(language: PPangoLanguage): PangoOTTag; cdecl;
function pango_ot_ruleset_description_hash(const desc: PPangoOTRulesetDescription): guint; cdecl;
function pango_ot_ruleset_description_equal(const desc1: PPangoOTRulesetDescription; const desc2: PPangoOTRulesetDescription): gboolean; cdecl;
function pango_ot_ruleset_description_copy(const desc: PPangoOTRulesetDescription): PPangoOTRulesetDescription; cdecl;
procedure pango_ot_ruleset_description_free(desc: PPangoOTRulesetDescription); cdecl;
//#endif (* PANGO_ENABLE_ENGINE *)
implementation
const
PANGO_FT_LIB = 'libpangoft2-1.0-0.dll';
function pango_fc_font_has_char(font: PPangoFcFont; wc: gunichar): gboolean; cdecl; external PANGO_FT_LIB;
function pango_fc_font_get_glyph(font: PPangoFcFont; wc: gunichar): guint; cdecl; external PANGO_FT_LIB;
function pango_fc_font_get_unknown_glyph(font: PPangoFcFont; wc: gunichar): PangoGlyph; cdecl; external PANGO_FT_LIB;
procedure pango_fc_font_kern_glyphs(font: PPangoFcFont; glyphs: PPangoGlyphString); cdecl; external PANGO_FT_LIB;
function pango_fc_font_get_type: GType; cdecl; external PANGO_FT_LIB;
function pango_fc_font_lock_face(font: PPangoFcFont): FT_Face; cdecl; external PANGO_FT_LIB;
procedure pango_fc_font_unlock_face(font: PPangoFcFont); cdecl; external PANGO_FT_LIB;
function pango_fc_decoder_get_type: GType; cdecl; external PANGO_FT_LIB;
function pango_fc_decoder_get_charset(decoder: PPangoFcDecoder; fcfont: PPangoFcFont): PFcCharSet; cdecl; external PANGO_FT_LIB;
function pango_fc_decoder_get_glyph(decoder: PPangoFcDecoder; fcfont: PPangoFcFont; wc: guint32): PangoGlyph; cdecl; external PANGO_FT_LIB;
function pango_fc_fontset_key_get_language(const key: PPangoFcFontsetKey): PPangoLanguage; cdecl; external PANGO_FT_LIB;
function pango_fc_fontset_key_get_description(const key: PPangoFcFontsetKey): PPangoFontDescription; cdecl; external PANGO_FT_LIB;
function pango_fc_fontset_key_get_matrix(const key: PPangoFcFontsetKey): PPangoMatrix; cdecl; external PANGO_FT_LIB;
function pango_fc_fontset_key_get_absolute_size(const key: PPangoFcFontsetKey): double; cdecl; external PANGO_FT_LIB;
function pango_fc_fontset_key_get_resolution(const key: PPangoFcFontsetKey): double; cdecl; external PANGO_FT_LIB;
function pango_fc_fontset_key_get_context_key(const key: PPangoFcFontsetKey): gpointer; cdecl; external PANGO_FT_LIB;
function pango_fc_font_key_get_pattern(const key: PPangoFcFontKey): PFcPattern; cdecl; external PANGO_FT_LIB;
function pango_fc_font_key_get_matrix(const key: PPangoFcFontKey): PPangoMatrix; cdecl; external PANGO_FT_LIB;
function pango_fc_font_key_get_context_key(const key: PPangoFcFontKey): gpointer; cdecl; external PANGO_FT_LIB;
function pango_fc_font_map_create_context(fcfontmap: PPangoFcFontMap): PPangoContext; cdecl; external PANGO_FT_LIB;
procedure pango_fc_font_map_shutdown(fcfontmap: PPangoFcFontMap); cdecl; external PANGO_FT_LIB;
function pango_fc_font_map_get_type: GType; cdecl; external PANGO_FT_LIB;
procedure pango_fc_font_map_cache_clear(fcfontmap: PPangoFcFontMap); cdecl; external PANGO_FT_LIB;
procedure pango_fc_font_map_add_decoder_find_func(fcfontmap: PPangoFcFontMap; findfunc: PangoFcDecoderFindFunc; user_data: gpointer; dnotify: GDestroyNotify); cdecl; external PANGO_FT_LIB;
function pango_fc_font_description_from_pattern(pattern: PFcPattern; include_size: gboolean): PPangoFontDescription; cdecl; external PANGO_FT_LIB;
procedure pango_ft2_render(bitmap: PFT_Bitmap; font: PPangoFont; glyphs: PPangoGlyphString; x: gint; y: gint); cdecl; external PANGO_FT_LIB;
procedure pango_ft2_render_transformed(bitmap: PFT_Bitmap; const matrix: PPangoMatrix; font: PPangoFont; glyphs: PPangoGlyphString; x: Integer; y: Integer); cdecl; external PANGO_FT_LIB;
procedure pango_ft2_render_layout_line(bitmap: PFT_Bitmap; line: PPangoLayoutLine; x: Integer; y: Integer); cdecl; external PANGO_FT_LIB;
procedure pango_ft2_render_layout_line_subpixel(bitmap: PFT_Bitmap; line: PPangoLayoutLine; x: Integer; y: Integer); cdecl; external PANGO_FT_LIB;
procedure pango_ft2_render_layout(bitmap: PFT_Bitmap; layout: PPangoLayout; x: Integer; y: Integer); cdecl; external PANGO_FT_LIB;
procedure pango_ft2_render_layout_subpixel(bitmap: PFT_Bitmap; layout: PPangoLayout; x: Integer; y: Integer); cdecl; external PANGO_FT_LIB;
function pango_ft2_font_map_get_type: GType; cdecl; external PANGO_FT_LIB;
function pango_ft2_font_map_new: PPangoFontMap; cdecl; external PANGO_FT_LIB;
procedure pango_ft2_font_map_set_resolution(fontmap: PPangoFT2FontMap; dpi_x: double; dpi_y: double); cdecl; external PANGO_FT_LIB;
procedure pango_ft2_font_map_set_default_substitute(fontmap: PPangoFT2FontMap; func: PangoFT2SubstituteFunc; data: gpointer; notify: GDestroyNotify); cdecl; external PANGO_FT_LIB;
procedure pango_ft2_font_map_substitute_changed(fontmap: PPangoFT2FontMap); cdecl; external PANGO_FT_LIB;
function pango_ft2_font_map_create_context(fontmap: PPangoFT2FontMap): PPangoContext; cdecl; external PANGO_FT_LIB;
function pango_ft2_get_context(dpi_x: double; dpi_y: double): PPangoContext ; cdecl; external PANGO_FT_LIB;
function pango_ft2_font_map_for_display: PPangoFontMap; cdecl; external PANGO_FT_LIB;
procedure pango_ft2_shutdown_display; cdecl; external PANGO_FT_LIB;
function pango_ft2_get_unknown_glyph(font: PPangoFont): PangoGlyph; cdecl; external PANGO_FT_LIB;
function pango_ft2_font_get_kerning(font: PPangoFont; left: PangoGlyph; right: PangoGlyph): Integer; cdecl; external PANGO_FT_LIB;
function pango_ft2_font_get_face(font: PPangoFont): FT_Face; cdecl; external PANGO_FT_LIB;
function pango_ft2_font_get_coverage(font: PPangoFont; language: PPangoLanguage): PPangoCoverage; cdecl; external PANGO_FT_LIB;
function pango_ot_info_get_type: GType; cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_get_type: GType; cdecl; external PANGO_FT_LIB;
function pango_ot_info_get(face: FT_Face): PPangoOTInfo; cdecl; external PANGO_FT_LIB;
function pango_ot_info_find_script(info: PPangoOTInfo; table_type: PangoOTTableType; script_tag: PangoOTTag; script_index: Pguint): gboolean; cdecl; external PANGO_FT_LIB;
function pango_ot_info_find_language(info: PPangoOTInfo; table_type: PangoOTTableType; script_index: guint; language_tag: PangoOTTag; language_index: Pguint; required_feature_index: Pguint): gboolean; cdecl; external PANGO_FT_LIB;
function pango_ot_info_find_feature(info: PPangoOTInfo; table_type: PangoOTTableType; feature_tag: PangoOTTag; script_index: guint; language_index: guint; feature_index: Pguint): gboolean; cdecl; external PANGO_FT_LIB;
function pango_ot_info_list_scripts(info: PPangoOTInfo; table_type: PangoOTTableType): PPangoOTTag; cdecl; external PANGO_FT_LIB;
function pango_ot_info_list_languages(info: PPangoOTInfo; table_type: PangoOTTableType; script_index: guint; language_tag: PangoOTTag): PPangoOTTag; cdecl; external PANGO_FT_LIB;
function pango_ot_info_list_features(info: PPangoOTInfo; table_type: PangoOTTableType; tag: PangoOTTag; script_index: guint; language_index: guint): PPangoOTTag; cdecl; external PANGO_FT_LIB;
function pango_ot_buffer_new(font: PPangoFcFont): PPangoOTBuffer; cdecl; external PANGO_FT_LIB;
procedure pango_ot_buffer_destroy(buffer: PPangoOTBuffer); cdecl; external PANGO_FT_LIB;
procedure pango_ot_buffer_clear(buffer: PPangoOTBuffer); cdecl; external PANGO_FT_LIB;
procedure pango_ot_buffer_set_rtl(buffer: PPangoOTBuffer; rtl: gboolean); cdecl; external PANGO_FT_LIB;
procedure pango_ot_buffer_add_glyph(buffer: PPangoOTBuffer; glyph: guint; properties: guint; cluster: guint); cdecl; external PANGO_FT_LIB;
procedure pango_ot_buffer_get_glyphs(const buffer: PPangoOTBuffer; var glyphs: PPangoOTGlyph; var n_glyphs: Integer); cdecl; external PANGO_FT_LIB;
procedure pango_ot_buffer_output(const buffer: PPangoOTBuffer; glyphs: PPangoGlyphString); cdecl; external PANGO_FT_LIB;
procedure pango_ot_buffer_set_zero_width_marks(buffer: PPangoOTBuffer; zero_width_marks: gboolean); cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_get_for_description(info: PPangoOTInfo; const desc: PPangoOTRulesetDescription): PPangoOTRuleset; cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_new(info: PPangoOTInfo): PPangoOTRuleset; cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_new_for(info: PPangoOTInfo; script: PangoScript; language: PPangoLanguage): PPangoOTRuleset; cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_new_from_description(info: PPangoOTInfo; const desc: PPangoOTRulesetDescription): PPangoOTRuleset; cdecl; external PANGO_FT_LIB;
procedure pango_ot_ruleset_add_feature(ruleset: PPangoOTRuleset; table_type: PangoOTTableType; feature_index: guint; property_bit: gulong); cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_maybe_add_feature(ruleset: PPangoOTRuleset; table_type: PangoOTTableType; feature_tag: PangoOTTag; property_bit: gulong): gboolean; cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_maybe_add_features(ruleset: PPangoOTRuleset; table_type: PangoOTTableType; const features: PPangoOTFeatureMap; n_features: guint): guint; cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_get_feature_count(const ruleset: PPangoOTRuleset; n_gsub_features: Pguint; n_gpos_features: Pguint): guint; cdecl; external PANGO_FT_LIB;
procedure pango_ot_ruleset_substitute(const ruleset: PPangoOTRuleset; buffer: PPangoOTBuffer); cdecl; external PANGO_FT_LIB;
procedure pango_ot_ruleset_position(const ruleset: PPangoOTRuleset; buffer: PPangoOTBuffer); cdecl; external PANGO_FT_LIB;
function pango_ot_tag_to_script(script_tag: PangoOTTag): PangoScript; cdecl; external PANGO_FT_LIB;
function pango_ot_tag_from_script(script: PangoScript): PangoOTTag; cdecl; external PANGO_FT_LIB;
function pango_ot_tag_to_language(language_tag: PangoOTTag): PPangoLanguage; cdecl; external PANGO_FT_LIB;
function pango_ot_tag_from_language(language: PPangoLanguage): PangoOTTag; cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_description_hash(const desc: PPangoOTRulesetDescription): guint; cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_description_equal(const desc1: PPangoOTRulesetDescription; const desc2: PPangoOTRulesetDescription): gboolean; cdecl; external PANGO_FT_LIB;
function pango_ot_ruleset_description_copy(const desc: PPangoOTRulesetDescription): PPangoOTRulesetDescription; cdecl; external PANGO_FT_LIB;
procedure pango_ot_ruleset_description_free(desc: PPangoOTRulesetDescription); cdecl; external PANGO_FT_LIB;
end. |
procedure calculateFibbonacci(n : Integer);
var first, second, next, i : Integer;
begin
first := 1;
second := 1;
Write(first , ', ' , second , ', ');
for i := 1 to n-2 do
begin
next := first + second;
if n-2 = i then Write(next)
else Write(next , ', ');
first := second;
second := next;
end;
end;
// Function test
calculateFibbonacci(5)
|
unit SQLite3;
{
Simplified interface for SQLite.
Updated for Sqlite 3 by Tim Anderson (tim@itwriting.com)
Note: NOT COMPLETE for version 3, just minimal functionality
Adapted from file created by Pablo Pissanetzky (pablo@myhtpc.net)
which was based on SQLite.pas by Ben Hochstrasser (bhoc@surfeu.ch)
}
{$IFDEF FPC}
{$MODE DELPHI}
{$H+} (* use AnsiString *)
{$PACKENUM 4} (* use 4-byte enums *)
{$PACKRECORDS C} (* C/C++-compatible record packing *)
{$ELSE}
{$MINENUMSIZE 4} (* use 4-byte enums *)
{$ENDIF}
interface
var
merdadll: string;
// Return values for sqlite3_exec() and sqlite3_step()
const
SQLITE_OK = 0; // Successful result
(* beginning-of-error-codes *)
SQLITE_ERROR = 1; // SQL error or missing database
SQLITE_INTERNAL = 2; // An internal logic error in SQLite
SQLITE_PERM = 3; // Access permission denied
SQLITE_ABORT = 4; // Callback routine requested an abort
SQLITE_BUSY = 5; // The database file is locked
SQLITE_LOCKED = 6; // A table in the database is locked
SQLITE_NOMEM = 7; // A malloc() failed
SQLITE_READONLY = 8; // Attempt to write a readonly database
SQLITE_INTERRUPT = 9; // Operation terminated by sqlite3_interrupt()
SQLITE_IOERR = 10; // Some kind of disk I/O error occurred
SQLITE_CORRUPT = 11; // The database disk image is malformed
SQLITE_NOTFOUND = 12; // (Internal Only) Table or record not found
SQLITE_FULL = 13; // Insertion failed because database is full
SQLITE_CANTOPEN = 14; // Unable to open the database file
SQLITE_PROTOCOL = 15; // Database lock protocol error
SQLITE_EMPTY = 16; // Database is empty
SQLITE_SCHEMA = 17; // The database schema changed
SQLITE_TOOBIG = 18; // Too much data for one row of a table
SQLITE_CONSTRAINT = 19; // Abort due to contraint violation
SQLITE_MISMATCH = 20; // Data type mismatch
SQLITE_MISUSE = 21; // Library used incorrectly
SQLITE_NOLFS = 22; // Uses OS features not supported on host
SQLITE_AUTH = 23; // Authorization denied
SQLITE_FORMAT = 24; // Auxiliary database format error
SQLITE_RANGE = 25; // 2nd parameter to sqlite3_bind out of range
SQLITE_NOTADB = 26; // File opened that is not a database file
SQLITE_ROW = 100; // sqlite3_step() has another row ready
SQLITE_DONE = 101; // sqlite3_step() has finished executing
SQLITE_INTEGER = 1;
SQLITE_FLOAT = 2;
SQLITE_TEXT = 3;
SQLITE_BLOB = 4;
SQLITE_NULL = 5;
SQLITE_UTF8 = 1;
SQLITE_UTF16 = 2;
SQLITE_UTF16BE = 3;
SQLITE_UTF16LE = 4;
SQLITE_ANY = 5;
SQLITE_STATIC {: TSQLite3Destructor} = Pointer(0);
SQLITE_TRANSIENT {: TSQLite3Destructor} = Pointer(-1);
type
TSQLiteDB = Pointer;
TSQLiteResult = ^PAnsiChar;
TSQLiteStmt = Pointer;
type
PPAnsiCharArray = ^TPAnsiCharArray;
TPAnsiCharArray = array[0 .. (MaxInt div SizeOf(PAnsiChar))-1] of PAnsiChar;
type
TSQLiteExecCallback = function(UserData: Pointer; NumCols: integer; ColValues:
PPAnsiCharArray; ColNames: PPAnsiCharArray): integer; cdecl;
TSQLiteBusyHandlerCallback = function(UserData: Pointer; P2: integer): integer; cdecl;
//function prototype for define own collate
TCollateXCompare = function(UserData: pointer; Buf1Len: integer; Buf1: pointer;
Buf2Len: integer; Buf2: pointer): integer; cdecl;
{
function SQLite3_Open(filename: PAnsiChar; var db: TSQLiteDB): integer; cdecl; external SQLiteDLL name 'sqlite3_open';
function SQLite3_Close(db: TSQLiteDB): integer; cdecl; external SQLiteDLL name 'sqlite3_close';
function SQLite3_Exec(db: TSQLiteDB; SQLStatement: PAnsiChar; CallbackPtr: TSQLiteExecCallback; UserData: Pointer; var ErrMsg: PAnsiChar): integer; cdecl; external SQLiteDLL name 'sqlite3_exec';
function SQLite3_Version(): PAnsiChar; cdecl; external SQLiteDLL name 'sqlite3_libversion';
function SQLite3_ErrMsg(db: TSQLiteDB): PAnsiChar; cdecl; external SQLiteDLL name 'sqlite3_errmsg';
function SQLite3_ErrCode(db: TSQLiteDB): integer; cdecl; external SQLiteDLL name 'sqlite3_errcode';
procedure SQlite3_Free(P: PAnsiChar); cdecl; external SQLiteDLL name 'sqlite3_free';
function SQLite3_GetTable(db: TSQLiteDB; SQLStatement: PAnsiChar; var ResultPtr: TSQLiteResult; var RowCount: Cardinal; var ColCount: Cardinal; var ErrMsg: PAnsiChar): integer; cdecl; external SQLiteDLL name 'sqlite3_get_table';
procedure SQLite3_FreeTable(Table: TSQLiteResult); cdecl; external SQLiteDLL name 'sqlite3_free_table';
function SQLite3_Complete(P: PAnsiChar): boolean; cdecl; external SQLiteDLL name 'sqlite3_complete';
function SQLite3_LastInsertRowID(db: TSQLiteDB): int64; cdecl; external SQLiteDLL name 'sqlite3_last_insert_rowid';
procedure SQLite3_Interrupt(db: TSQLiteDB); cdecl; external SQLiteDLL name 'sqlite3_interrupt';
procedure SQLite3_BusyHandler(db: TSQLiteDB; CallbackPtr: TSQLiteBusyHandlerCallback; UserData: Pointer); cdecl; external SQLiteDLL name 'sqlite3_busy_handler';
procedure SQLite3_BusyTimeout(db: TSQLiteDB; TimeOut: integer); cdecl; external SQLiteDLL name 'sqlite3_busy_timeout';
function SQLite3_Changes(db: TSQLiteDB): integer; cdecl; external SQLiteDLL name 'sqlite3_changes';
function SQLite3_TotalChanges(db: TSQLiteDB): integer; cdecl; external SQLiteDLL name 'sqlite3_total_changes';
function SQLite3_Prepare(db: TSQLiteDB; SQLStatement: PAnsiChar; nBytes: integer; var hStmt: TSqliteStmt; var pzTail: PAnsiChar): integer; cdecl; external SQLiteDLL name 'sqlite3_prepare';
function SQLite3_Prepare_v2(db: TSQLiteDB; SQLStatement: PAnsiChar; nBytes: integer; var hStmt: TSqliteStmt; var pzTail: PAnsiChar): integer; cdecl; external SQLiteDLL name 'sqlite3_prepare_v2';
function SQLite3_ColumnCount(hStmt: TSqliteStmt): integer; cdecl; external SQLiteDLL name 'sqlite3_column_count';
function SQLite3_ColumnName(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar; cdecl; external SQLiteDLL name 'sqlite3_column_name';
function SQLite3_ColumnDeclType(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar; cdecl; external SQLiteDLL name 'sqlite3_column_decltype';
function SQLite3_Step(hStmt: TSqliteStmt): integer; cdecl; external SQLiteDLL name 'sqlite3_step';
function SQLite3_DataCount(hStmt: TSqliteStmt): integer; cdecl; external SQLiteDLL name 'sqlite3_data_count';
function SQLite3_ColumnBlob(hStmt: TSqliteStmt; ColNum: integer): pointer; cdecl; external SQLiteDLL name 'sqlite3_column_blob';
function SQLite3_ColumnBytes(hStmt: TSqliteStmt; ColNum: integer): integer; cdecl; external SQLiteDLL name 'sqlite3_column_bytes';
function SQLite3_ColumnDouble(hStmt: TSqliteStmt; ColNum: integer): double; cdecl; external SQLiteDLL name 'sqlite3_column_double';
function SQLite3_ColumnInt(hStmt: TSqliteStmt; ColNum: integer): integer; cdecl; external SQLiteDLL name 'sqlite3_column_int';
function SQLite3_ColumnText(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar; cdecl; external SQLiteDLL name 'sqlite3_column_text';
function SQLite3_ColumnType(hStmt: TSqliteStmt; ColNum: integer): integer; cdecl; external SQLiteDLL name 'sqlite3_column_type';
function SQLite3_ColumnInt64(hStmt: TSqliteStmt; ColNum: integer): Int64; cdecl; external SQLiteDLL name 'sqlite3_column_int64';
function SQLite3_Finalize(hStmt: TSqliteStmt): integer; cdecl; external SQLiteDLL name 'sqlite3_finalize';
function SQLite3_Reset(hStmt: TSqliteStmt): integer; cdecl; external SQLiteDLL name 'sqlite3_reset';
}
function SQLite3_Open(filename: PAnsiChar; var db: TSQLiteDB): integer; cdecl;
function SQLite3_Close(db: TSQLiteDB): integer; cdecl;
function SQLite3_Exec(db: TSQLiteDB; SQLStatement: PAnsiChar; CallbackPtr: TSQLiteExecCallback; UserData: Pointer; var ErrMsg: PAnsiChar): integer; cdecl;
function SQLite3_Version(): PAnsiChar; cdecl;
function SQLite3_ErrMsg(db: TSQLiteDB): PAnsiChar; cdecl;
function SQLite3_ErrCode(db: TSQLiteDB): integer; cdecl;
procedure SQlite3_Free(P: PAnsiChar); cdecl;
function SQLite3_GetTable(db: TSQLiteDB; SQLStatement: PAnsiChar; var ResultPtr: TSQLiteResult; var RowCount: Cardinal; var ColCount: Cardinal; var ErrMsg: PAnsiChar): integer; cdecl;
procedure SQLite3_FreeTable(Table: TSQLiteResult); cdecl;
function SQLite3_Complete(P: PAnsiChar): boolean; cdecl;
function SQLite3_LastInsertRowID(db: TSQLiteDB): int64; cdecl;
procedure SQLite3_Interrupt(db: TSQLiteDB); cdecl;
procedure SQLite3_BusyHandler(db: TSQLiteDB; CallbackPtr: TSQLiteBusyHandlerCallback; UserData: Pointer); cdecl;
procedure SQLite3_BusyTimeout(db: TSQLiteDB; TimeOut: integer); cdecl;
function SQLite3_Changes(db: TSQLiteDB): integer; cdecl;
function SQLite3_TotalChanges(db: TSQLiteDB): integer; cdecl;
function SQLite3_Prepare(db: TSQLiteDB; SQLStatement: PAnsiChar; nBytes: integer; var hStmt: TSqliteStmt; var pzTail: PAnsiChar): integer; cdecl;
function SQLite3_Prepare_v2(db: TSQLiteDB; SQLStatement: PAnsiChar; nBytes: integer; var hStmt: TSqliteStmt; var pzTail: PAnsiChar): integer; cdecl;
function SQLite3_ColumnCount(hStmt: TSqliteStmt): integer; cdecl;
function SQLite3_ColumnName(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar; cdecl;
function SQLite3_ColumnDeclType(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar; cdecl;
function SQLite3_Step(hStmt: TSqliteStmt): integer; cdecl;
function SQLite3_DataCount(hStmt: TSqliteStmt): integer; cdecl;
function SQLite3_ColumnBlob(hStmt: TSqliteStmt; ColNum: integer): pointer; cdecl;
function SQLite3_ColumnBytes(hStmt: TSqliteStmt; ColNum: integer): integer; cdecl;
function SQLite3_ColumnDouble(hStmt: TSqliteStmt; ColNum: integer): double; cdecl;
function SQLite3_ColumnInt(hStmt: TSqliteStmt; ColNum: integer): integer; cdecl;
function SQLite3_ColumnText(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar; cdecl;
function SQLite3_ColumnType(hStmt: TSqliteStmt; ColNum: integer): integer; cdecl;
function SQLite3_ColumnInt64(hStmt: TSqliteStmt; ColNum: integer): Int64; cdecl;
function SQLite3_Finalize(hStmt: TSqliteStmt): integer; cdecl;
function SQLite3_Reset(hStmt: TSqliteStmt): integer; cdecl;
//
// In the SQL strings input to sqlite3_prepare() and sqlite3_prepare16(),
// one or more literals can be replace by a wildcard "?" or ":N:" where
// N is an integer. These value of these wildcard literals can be set
// using the routines listed below.
//
// In every case, the first parameter is a pointer to the sqlite3_stmt
// structure returned from sqlite3_prepare(). The second parameter is the
// index of the wildcard. The first "?" has an index of 1. ":N:" wildcards
// use the index N.
//
// The fifth parameter to sqlite3_bind_blob(), sqlite3_bind_text(), and
//sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
//text after SQLite has finished with it. If the fifth argument is the
// special value SQLITE_STATIC, then the library assumes that the information
// is in static, unmanaged space and does not need to be freed. If the
// fifth argument has the value SQLITE_TRANSIENT, then SQLite makes its
// own private copy of the data.
//
// The sqlite3_bind_* routine must be called before sqlite3_step() after
// an sqlite3_prepare() or sqlite3_reset(). Unbound wildcards are interpreted
// as NULL.
//
type
TSQLite3Destructor = procedure(Ptr: Pointer); cdecl;
{
function sqlite3_bind_blob(hStmt: TSqliteStmt; ParamNum: integer; ptrData: pointer; numBytes: integer; ptrDestructor: TSQLite3Destructor): integer; cdecl; external SQLiteDLL name 'sqlite3_bind_blob';
function sqlite3_bind_text(hStmt: TSqliteStmt; ParamNum: integer; Text: PAnsiChar; numBytes: integer; ptrDestructor: TSQLite3Destructor): integer; cdecl; external SQLiteDLL name 'sqlite3_bind_text';
function sqlite3_bind_double(hStmt: TSqliteStmt; ParamNum: integer; Data: Double): integer; cdecl; external SQLiteDLL name 'sqlite3_bind_double';
function sqlite3_bind_int(hStmt: TSqLiteStmt; ParamNum: integer; Data: integer): integer; cdecl; external SQLiteDLL name 'sqlite3_bind_int';
function sqlite3_bind_int64(hStmt: TSqliteStmt; ParamNum: integer; Data: int64): integer; cdecl; external SQLiteDLL name 'sqlite3_bind_int64';
function sqlite3_bind_null(hStmt: TSqliteStmt; ParamNum: integer): integer; cdecl; external SQLiteDLL name 'sqlite3_bind_null';
function sqlite3_bind_parameter_index(hStmt: TSqliteStmt; zName: PAnsiChar): integer; cdecl; external SQLiteDLL name 'sqlite3_bind_parameter_index';
function sqlite3_enable_shared_cache(Value: integer): integer; cdecl; external SQLiteDLL name 'sqlite3_enable_shared_cache';
function SQLite3_create_collation(db: TSQLiteDB; Name: PAnsiChar; eTextRep: integer; UserData: pointer; xCompare: TCollateXCompare): integer; cdecl; external SQLiteDLL name 'sqlite3_create_collation';
}
function sqlite3_bind_blob(hStmt: TSqliteStmt; ParamNum: integer; ptrData: pointer; numBytes: integer; ptrDestructor: TSQLite3Destructor): integer; cdecl;
function sqlite3_bind_text(hStmt: TSqliteStmt; ParamNum: integer; Text: PAnsiChar; numBytes: integer; ptrDestructor: TSQLite3Destructor): integer; cdecl;
function sqlite3_bind_double(hStmt: TSqliteStmt; ParamNum: integer; Data: Double): integer; cdecl;
function sqlite3_bind_int(hStmt: TSqLiteStmt; ParamNum: integer; Data: integer): integer; cdecl;
function sqlite3_bind_int64(hStmt: TSqliteStmt; ParamNum: integer; Data: int64): integer; cdecl;
function sqlite3_bind_null(hStmt: TSqliteStmt; ParamNum: integer): integer; cdecl;
function sqlite3_bind_parameter_index(hStmt: TSqliteStmt; zName: PAnsiChar): integer; cdecl;
function sqlite3_enable_shared_cache(Value: integer): integer; cdecl;
function SQLite3_create_collation(db: TSQLiteDB; Name: PAnsiChar; eTextRep: integer; UserData: pointer; xCompare: TCollateXCompare): integer; cdecl;
function SQLiteFieldType(SQLiteFieldTypeCode: Integer): AnsiString;
function SQLiteErrorStr(SQLiteErrorCode: Integer): AnsiString;
implementation
uses
SysUtils,
windows;
function sqlite3_bind_blob(hStmt: TSqliteStmt; ParamNum: integer; ptrData: pointer; numBytes: integer; ptrDestructor: TSQLite3Destructor): integer;
var
xsqlite3_bind_blob: function(hStmt: TSqliteStmt; ParamNum: integer; ptrData: pointer; numBytes: integer; ptrDestructor: TSQLite3Destructor): integer; cdecl;
begin
xsqlite3_bind_blob := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_bind_blob'));
Result := xsqlite3_bind_blob(hStmt, ParamNum, ptrData, numBytes, ptrDestructor);
end;
function sqlite3_bind_text(hStmt: TSqliteStmt; ParamNum: integer; Text: PAnsiChar; numBytes: integer; ptrDestructor: TSQLite3Destructor): integer;
var
xsqlite3_bind_text: function(hStmt: TSqliteStmt; ParamNum: integer; Text: PAnsiChar; numBytes: integer; ptrDestructor: TSQLite3Destructor): integer; cdecl;
begin
xsqlite3_bind_text := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_bind_text'));
Result := xsqlite3_bind_text(hStmt, ParamNum, Text, numBytes, ptrDestructor);
end;
function sqlite3_bind_double(hStmt: TSqliteStmt; ParamNum: integer; Data: Double): integer;
var
xsqlite3_bind_double: function(hStmt: TSqliteStmt; ParamNum: integer; Data: Double): integer; cdecl;
begin
xsqlite3_bind_double := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_bind_double'));
Result := xsqlite3_bind_double(hStmt, ParamNum, Data);
end;
function sqlite3_bind_int(hStmt: TSqLiteStmt; ParamNum: integer; Data: integer): integer;
var
xsqlite3_bind_int: function(hStmt: TSqLiteStmt; ParamNum: integer; Data: integer): integer; cdecl;
begin
xsqlite3_bind_int := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_bind_int'));
Result := xsqlite3_bind_int(hStmt, ParamNum, Data);
end;
function sqlite3_bind_int64(hStmt: TSqliteStmt; ParamNum: integer; Data: int64): integer;
var
xsqlite3_bind_int64: function(hStmt: TSqliteStmt; ParamNum: integer; Data: int64): integer; cdecl;
begin
xsqlite3_bind_int64 := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_bind_int64'));
Result := xsqlite3_bind_int64(hStmt, ParamNum, Data);
end;
function sqlite3_bind_null(hStmt: TSqliteStmt; ParamNum: integer): integer;
var
xsqlite3_bind_null: function(hStmt: TSqliteStmt; ParamNum: integer): integer; cdecl;
begin
xsqlite3_bind_null := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_bind_null'));
Result := xsqlite3_bind_null(hStmt, ParamNum);
end;
function sqlite3_bind_parameter_index(hStmt: TSqliteStmt; zName: PAnsiChar): integer;
var
xsqlite3_bind_parameter_index: function(hStmt: TSqliteStmt; zName: PAnsiChar): integer; cdecl;
begin
xsqlite3_bind_parameter_index := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_bind_parameter_index'));
Result := xsqlite3_bind_parameter_index(hStmt, zName);
end;
function sqlite3_enable_shared_cache(Value: integer): integer;
var
xsqlite3_enable_shared_cache: function(Value: integer): integer; cdecl;
begin
xsqlite3_enable_shared_cache := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_enable_shared_cache'));
Result := xsqlite3_enable_shared_cache(Value);
end;
function SQLite3_create_collation(db: TSQLiteDB; Name: PAnsiChar; eTextRep: integer; UserData: pointer; xCompare: TCollateXCompare): integer;
var
xSQLite3_create_collation: function(db: TSQLiteDB; Name: PAnsiChar; eTextRep: integer; UserData: pointer; xCompare: TCollateXCompare): integer; cdecl;
begin
xSQLite3_create_collation := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_create_collation'));
Result := xSQLite3_create_collation(db, Name, eTextRep, UserData, xCompare);
end;
function SQLite3_Open(filename: PAnsiChar; var db: TSQLiteDB): integer;
var
xSQLite3_Open: function(filename: PAnsiChar; var db: TSQLiteDB): integer; cdecl;
begin
xSQLite3_Open := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_open'));
Result := xSQLite3_Open(filename, db);
end;
function SQLite3_Close(db: TSQLiteDB): integer;
var
xSQLite3_Close: function(db: TSQLiteDB): integer; cdecl;
begin
xSQLite3_Close := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_close'));
Result := xSQLite3_Close(db);
end;
function SQLite3_Exec(db: TSQLiteDB; SQLStatement: PAnsiChar; CallbackPtr: TSQLiteExecCallback; UserData: Pointer; var ErrMsg: PAnsiChar): integer;
var
xSQLite3_Exec: function(db: TSQLiteDB; SQLStatement: PAnsiChar; CallbackPtr: TSQLiteExecCallback; UserData: Pointer; var ErrMsg: PAnsiChar): integer; cdecl;
begin
xSQLite3_Exec := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_exec'));
Result := xSQLite3_Exec(db, SQLStatement, CallbackPtr, UserData, ErrMsg);
end;
function SQLite3_Version(): PAnsiChar;
var
xSQLite3_Version: function(): PAnsiChar; cdecl;
begin
xSQLite3_Version := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_libversion'));
Result := xSQLite3_Version();
end;
function SQLite3_ErrMsg(db: TSQLiteDB): PAnsiChar;
var
xSQLite3_ErrMsg: function(db: TSQLiteDB): PAnsiChar; cdecl;
begin
xSQLite3_ErrMsg := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_errmsg'));
Result := xSQLite3_ErrMsg(db);
end;
function SQLite3_ErrCode(db: TSQLiteDB): integer;
var
xSQLite3_ErrCode: function(db: TSQLiteDB): integer; cdecl;
begin
xSQLite3_ErrCode := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_errcode'));
Result := xSQLite3_ErrCode(db);
end;
procedure SQlite3_Free(P: PAnsiChar);
var
xSQlite3_Free: procedure(P: PAnsiChar); cdecl;
begin
xSQlite3_Free := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_free'));
xSQlite3_Free(P);
end;
function SQLite3_GetTable(db: TSQLiteDB; SQLStatement: PAnsiChar; var ResultPtr: TSQLiteResult; var RowCount: Cardinal; var ColCount: Cardinal; var ErrMsg: PAnsiChar): integer;
var
xSQLite3_GetTable: function(db: TSQLiteDB; SQLStatement: PAnsiChar; var ResultPtr: TSQLiteResult; var RowCount: Cardinal; var ColCount: Cardinal; var ErrMsg: PAnsiChar): integer; cdecl;
begin
xSQLite3_GetTable := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_get_table'));
Result := xSQLite3_GetTable(db, SQLStatement, ResultPtr, RowCount, ColCount, ErrMsg);
end;
procedure SQLite3_FreeTable(Table: TSQLiteResult);
var
xSQLite3_FreeTable: procedure(Table: TSQLiteResult); cdecl;
begin
xSQLite3_FreeTable := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_free_table'));
xSQLite3_FreeTable(Table);
end;
function SQLite3_Complete(P: PAnsiChar): boolean;
var
xSQLite3_Complete: function(P: PAnsiChar): boolean; cdecl;
begin
xSQLite3_Complete := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_complete'));
Result := xSQLite3_Complete(P);
end;
function SQLite3_LastInsertRowID(db: TSQLiteDB): int64;
var
xSQLite3_LastInsertRowID: function(db: TSQLiteDB): int64; cdecl;
begin
xSQLite3_LastInsertRowID := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_last_insert_rowid'));
Result := xSQLite3_LastInsertRowID(db);
end;
procedure SQLite3_Interrupt(db: TSQLiteDB);
var
xSQLite3_Interrupt: procedure(db: TSQLiteDB); cdecl;
begin
xSQLite3_Interrupt := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_interrupt'));
xSQLite3_Interrupt(db);
end;
procedure SQLite3_BusyHandler(db: TSQLiteDB; CallbackPtr: TSQLiteBusyHandlerCallback; UserData: Pointer);
var
xSQLite3_BusyHandler: procedure(db: TSQLiteDB; CallbackPtr: TSQLiteBusyHandlerCallback; UserData: Pointer); cdecl;
begin
xSQLite3_BusyHandler := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_busy_handler'));
xSQLite3_BusyHandler(db, CallbackPtr, UserData);
end;
procedure SQLite3_BusyTimeout(db: TSQLiteDB; TimeOut: integer);
var
xSQLite3_BusyTimeout: procedure(db: TSQLiteDB; TimeOut: integer); cdecl;
begin
xSQLite3_BusyTimeout := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_busy_timeout'));
xSQLite3_BusyTimeout(db, TimeOut);
end;
function SQLite3_Changes(db: TSQLiteDB): integer;
var
xSQLite3_Changes: function(db: TSQLiteDB): integer; cdecl;
begin
xSQLite3_Changes := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_changes'));
Result := xSQLite3_Changes(db);
end;
function SQLite3_TotalChanges(db: TSQLiteDB): integer;
var
xSQLite3_TotalChanges: function(db: TSQLiteDB): integer; cdecl;
begin
xSQLite3_TotalChanges := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_total_changes'));
Result := xSQLite3_TotalChanges(db);
end;
function SQLite3_Prepare(db: TSQLiteDB; SQLStatement: PAnsiChar; nBytes: integer; var hStmt: TSqliteStmt; var pzTail: PAnsiChar): integer;
var
xSQLite3_Prepare: function(db: TSQLiteDB; SQLStatement: PAnsiChar; nBytes: integer; var hStmt: TSqliteStmt; var pzTail: PAnsiChar): integer; cdecl;
begin
xSQLite3_Prepare := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_prepare'));
Result := xSQLite3_Prepare(db, SQLStatement, nBytes, hStmt, pzTail);
end;
function SQLite3_Prepare_v2(db: TSQLiteDB; SQLStatement: PAnsiChar; nBytes: integer; var hStmt: TSqliteStmt; var pzTail: PAnsiChar): integer;
var
xSQLite3_Prepare_v2: function(db: TSQLiteDB; SQLStatement: PAnsiChar; nBytes: integer; var hStmt: TSqliteStmt; var pzTail: PAnsiChar): integer; cdecl;
begin
xSQLite3_Prepare_v2 := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_prepare_v2'));
Result := xSQLite3_Prepare_v2(db, SQLStatement, nBytes, hStmt, pzTail);
end;
function SQLite3_ColumnCount(hStmt: TSqliteStmt): integer;
var
xSQLite3_ColumnCount: function(hStmt: TSqliteStmt): integer; cdecl;
begin
xSQLite3_ColumnCount := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_column_count'));
Result := xSQLite3_ColumnCount(hStmt);
end;
function SQLite3_ColumnName(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar;
var
xSQLite3_ColumnName: function(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar; cdecl;
begin
xSQLite3_ColumnName := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_column_name'));
Result := xSQLite3_ColumnName(hStmt, ColNum);
end;
function SQLite3_ColumnDeclType(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar;
var
xSQLite3_ColumnDeclType: function(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar; cdecl;
begin
xSQLite3_ColumnDeclType := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_column_decltype'));
Result := xSQLite3_ColumnDeclType(hStmt, ColNum);
end;
function SQLite3_Step(hStmt: TSqliteStmt): integer;
var
xSQLite3_Step: function(hStmt: TSqliteStmt): integer; cdecl;
begin
xSQLite3_Step := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_step'));
Result := xSQLite3_Step(hStmt);
end;
function SQLite3_DataCount(hStmt: TSqliteStmt): integer;
var
xSQLite3_DataCount: function(hStmt: TSqliteStmt): integer; cdecl;
begin
xSQLite3_DataCount := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_data_count'));
Result := xSQLite3_DataCount(hStmt);
end;
function SQLite3_ColumnBlob(hStmt: TSqliteStmt; ColNum: integer): pointer;
var
xSQLite3_ColumnBlob: function(hStmt: TSqliteStmt; ColNum: integer): pointer; cdecl;
begin
xSQLite3_ColumnBlob := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_column_blob'));
Result := xSQLite3_ColumnBlob(hStmt, ColNum);
end;
function SQLite3_ColumnBytes(hStmt: TSqliteStmt; ColNum: integer): integer;
var
xSQLite3_ColumnBytes: function(hStmt: TSqliteStmt; ColNum: integer): integer; cdecl;
begin
xSQLite3_ColumnBytes := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_column_bytes'));
Result := xSQLite3_ColumnBytes(hStmt, ColNum);
end;
function SQLite3_ColumnDouble(hStmt: TSqliteStmt; ColNum: integer): double;
var
xSQLite3_ColumnDouble: function(hStmt: TSqliteStmt; ColNum: integer): double; cdecl;
begin
xSQLite3_ColumnDouble := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_column_double'));
Result := xSQLite3_ColumnDouble(hStmt, ColNum);
end;
function SQLite3_ColumnInt(hStmt: TSqliteStmt; ColNum: integer): integer;
var
xSQLite3_ColumnInt: function(hStmt: TSqliteStmt; ColNum: integer): integer; cdecl;
begin
xSQLite3_ColumnInt := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_column_int'));
Result := xSQLite3_ColumnInt(hStmt, ColNum);
end;
function SQLite3_ColumnText(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar;
var
xSQLite3_ColumnText: function(hStmt: TSqliteStmt; ColNum: integer): PAnsiChar; cdecl;
begin
xSQLite3_ColumnText := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_column_text'));
Result := xSQLite3_ColumnText(hStmt, ColNum);
end;
function SQLite3_ColumnType(hStmt: TSqliteStmt; ColNum: integer): integer;
var
xSQLite3_ColumnType: function(hStmt: TSqliteStmt; ColNum: integer): integer; cdecl;
begin
xSQLite3_ColumnType := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_column_type'));
Result := xSQLite3_ColumnType(hStmt, ColNum);
end;
function SQLite3_ColumnInt64(hStmt: TSqliteStmt; ColNum: integer): Int64;
var
xSQLite3_ColumnInt64: function(hStmt: TSqliteStmt; ColNum: integer): Int64; cdecl;
begin
xSQLite3_ColumnInt64 := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_column_int64'));
Result := xSQLite3_ColumnInt64(hStmt, ColNum);
end;
function SQLite3_Finalize(hStmt: TSqliteStmt): integer;
var
xSQLite3_Finalize: function(hStmt: TSqliteStmt): integer; cdecl;
begin
xSQLite3_Finalize := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_finalize'));
Result := xSQLite3_Finalize(hStmt);
end;
function SQLite3_Reset(hStmt: TSqliteStmt): integer;
var
xSQLite3_Reset: function(hStmt: TSqliteStmt): integer; cdecl;
begin
xSQLite3_Reset := GetProcAddress(LoadLibrary(pchar(MerdaDLL)), pchar('sqlite3_reset'));
Result := xSQLite3_Reset(hStmt);
end;
function SQLiteFieldType(SQLiteFieldTypeCode: Integer): AnsiString;
begin
case SQLiteFieldTypeCode of
SQLITE_INTEGER: Result := 'Integer';
SQLITE_FLOAT: Result := 'Float';
SQLITE_TEXT: Result := 'Text';
SQLITE_BLOB: Result := 'Blob';
SQLITE_NULL: Result := 'Null';
else
Result := 'Unknown SQLite Field Type Code "' + IntToStr(SQLiteFieldTypeCode) + '"';
end;
end;
function SQLiteErrorStr(SQLiteErrorCode: Integer): AnsiString;
begin
case SQLiteErrorCode of
SQLITE_OK: Result := 'Successful result';
SQLITE_ERROR: Result := 'SQL error or missing database';
SQLITE_INTERNAL: Result := 'An internal logic error in SQLite';
SQLITE_PERM: Result := 'Access permission denied';
SQLITE_ABORT: Result := 'Callback routine requested an abort';
SQLITE_BUSY: Result := 'The database file is locked';
SQLITE_LOCKED: Result := 'A table in the database is locked';
SQLITE_NOMEM: Result := 'A malloc() failed';
SQLITE_READONLY: Result := 'Attempt to write a readonly database';
SQLITE_INTERRUPT: Result := 'Operation terminated by sqlite3_interrupt()';
SQLITE_IOERR: Result := 'Some kind of disk I/O error occurred';
SQLITE_CORRUPT: Result := 'The database disk image is malformed';
SQLITE_NOTFOUND: Result := '(Internal Only) Table or record not found';
SQLITE_FULL: Result := 'Insertion failed because database is full';
SQLITE_CANTOPEN: Result := 'Unable to open the database file';
SQLITE_PROTOCOL: Result := 'Database lock protocol error';
SQLITE_EMPTY: Result := 'Database is empty';
SQLITE_SCHEMA: Result := 'The database schema changed';
SQLITE_TOOBIG: Result := 'Too much data for one row of a table';
SQLITE_CONSTRAINT: Result := 'Abort due to contraint violation';
SQLITE_MISMATCH: Result := 'Data type mismatch';
SQLITE_MISUSE: Result := 'Library used incorrectly';
SQLITE_NOLFS: Result := 'Uses OS features not supported on host';
SQLITE_AUTH: Result := 'Authorization denied';
SQLITE_FORMAT: Result := 'Auxiliary database format error';
SQLITE_RANGE: Result := '2nd parameter to sqlite3_bind out of range';
SQLITE_NOTADB: Result := 'File opened that is not a database file';
SQLITE_ROW: Result := 'sqlite3_step() has another row ready';
SQLITE_DONE: Result := 'sqlite3_step() has finished executing';
else
Result := 'Unknown SQLite Error Code "' + IntToStr(SQLiteErrorCode) + '"';
end;
end;
function ColValueToStr(Value: PAnsiChar): AnsiString;
begin
if (Value = nil) then
Result := 'NULL'
else
Result := Value;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.