text stringlengths 14 6.51M |
|---|
unit uModelBillIntf;
interface
uses DBClient, uParamObject, uBaseInfoDef, uModelBaseIntf;
type
IModelBillOrder = interface(IModelBill) //单据-订单
['{2F34D9A2-B1C1-4DB8-99C9-7CE7D5D69AFC}']
end;
IModelBillBuy = interface(IModelBill) //单据-进货单
['{C2586F34-A232-4C40-A3C9-547C8BC66F12}']
end;
IModelBillSale = interface(IModelBill) //单据-销售单
['{8BE32B7F-DFA3-48B7-9687-51CE83C1BBBB}']
end;
IModelBillAllot = interface(IModelBill) //单据-调拨单
['{BC31588A-A43E-4A04-B20F-207D4AD3D24B}']
end;
IModelBillPRMoney = interface(IModelBill) //单据-收付款单
['{471C0095-2EB8-489C-8BBC-9ED0907BC4CA}']
function QryBalance(AInParam: TParamObject; ACds: TClientDataSet): Integer; //查询需要结算的单据
function SaveBalance(AParam: TParamObject): Integer; //保存,修改或删除结算的单据记录
end;
implementation
end.
|
(*
* DGL(The Delphi Generic Library)
*
* Copyright (c) 2004
* HouSisong@gmail.com
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*)
//------------------------------------------------------------------------------
// 例子 :值语义的TPairStrInt结构(Record)的容器
// 具现化的TPairStrInt类型的声明
// Create by HouSisong, 2005.03.27
//------------------------------------------------------------------------------
unit _DGL_String_IntegerRecord;
interface
uses
SysUtils;
//结构的容器的声明模版
{$I DGLCfg.inc_h}
type
TPairStrInt = record
Key : string;
Value : integer;
end;
_ValueType = TPairStrInt;
const
_NULL_Value:_ValueType=(Key:('');Value:(0));
function _HashValue(const Value:_ValueType) : Cardinal;{$ifdef _DGL_Inline} inline; {$endif}//Hash函数
{$define _DGL_Compare} //是否需要比较函数,可选
function _IsEqual(const a,b :_ValueType):boolean; {$ifdef _DGL_Inline} inline; {$endif}//result:=(a=b);
function _IsLess(const a,b :_ValueType):boolean; {$ifdef _DGL_Inline} inline; {$endif} //result:=(a<b); 默认排序准则
{$I DGL.inc_h}
type
TStrIntAlgorithms = _TAlgorithms;
IStrIntIterator = _IIterator;
IStrIntContainer = _IContainer;
IStrIntSerialContainer = _ISerialContainer;
IStrIntVector = _IVector;
IStrIntList = _IList;
IStrIntDeque = _IDeque;
IStrIntStack = _IStack;
IStrIntQueue = _IQueue;
IStrIntPriorityQueue = _IPriorityQueue;
IStrIntSet = _ISet;
IStrIntMultiSet = _IMultiSet;
TStrIntVector = _TVector;
TStrIntDeque = _TDeque;
TStrIntList = _TList;
TStrIntStack = _TStack;
TStrIntQueue = _TQueue;
TStrIntPriorityQueue = _TPriorityQueue;
TStrIntHashSet = _THashSet;
TStrIntHashMuitiSet = _THashMultiSet;
function Pair_StrInt(const Key:string;const Value:integer):_ValueType;
implementation
uses
HashFunctions;
{$I DGL.inc_pas}
function _HashValue(const Value :_ValueType):Cardinal;
begin
result:=HashValue_Str(Value.Key)*37+Cardinal(Value.Value);
end;
function Pair_StrInt(const Key:string;const Value:integer):_ValueType;
begin
result.Key:=Key;
result.Value:=Value;
end;
function _IsEqual(const a,b :_ValueType):boolean;
begin
result:=(a.Key=b.Key) and (a.Value=b.Value);
end;
function _IsLess(const a,b :_ValueType):boolean;
begin
if (a.Key=b.Key) then
result:=a.Value<b.Value
else
result:=a.Key<b.Key;
end;
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 Gauge;
interface
uses
SysUtils, Classes, FMX_Types, FMX_Objects, UITypes;
type
TiOSGauge = class(TCircle)
private
FMax: Double;
FMin: Double;
FMaxAngle: Double;
FValue: Double;
FMinAngle: Double;
FNeedleCenter: TCircle;
FNeedle: TRectangle;
FZeroAngle: Double;
FNeedleCenterColor: TAlphaColor;
FNeedleColor: TAlphaColor;
procedure SetMax(const Value: Double);
procedure SetMaxAngle(const Value: Double);
procedure SetMin(const Value: Double);
procedure SetMinAngle(const Value: Double);
procedure SetValue(const Value: Double);
procedure SetZeroAngle(const Value: Double);
procedure SetNeedleCenterColor(const Value: TAlphaColor);
procedure SetNeedleColor(const Value: TAlphaColor);
{ Private declarations }
protected
{ Protected declarations }
procedure Resize; override;
procedure UpdateNeedle;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
published
{ Published declarations }
property Value : Double read FValue write SetValue;
property Max : Double read FMax write SetMax;
property Min : Double read FMin write SetMin;
property MaxAngle : Double read FMaxAngle write SetMaxAngle;
property MinAngle : Double read FMinAngle write SetMinAngle;
property ZeroAngle : Double read FZeroAngle write SetZeroAngle;
property NeedleCenterColor : TAlphaColor read FNeedleCenterColor write SetNeedleCenterColor default TAlphaColorRec.Red;
property NeedleColor : TAlphaColor read FNeedleColor write SetNeedleColor default TAlphaColorRec.Red;
end;
procedure Register;
implementation
constructor TiOSGauge.Create(AOwner: TComponent);
begin
inherited;
FValue := 0;
FMax := 100;
FMin := 0;
FMaxAngle := 360;
FMinAngle := 0;
FWidth := 140;
FHeight := 140;
FNeedleCenterColor := TAlphaColorRec.Red;
FNeedleColor := TAlphaColorRec.Red;
FNeedleCenter := TCircle.Create(Self);
FNeedleCenter.Parent := Self;
FNeedleCenter.Width := 10;
FNeedleCenter.Height := 10;
FNeedleCenter.Position.X := FWidth/2-5;
FNeedleCenter.Position.Y := FHeight/2-5;
FNeedleCenter.Fill.Color := FNeedleCenterColor;
FNeedleCenter.Stored := False;
FNeedle := TRectangle.Create(Self);
FNeedle.Parent := FNeedleCenter;
FNeedle.Width := 4;
FNeedle.Height := FWidth/2*0.85;
FNeedle.Position.X := 3;
FNeedle.Position.Y := 6-FNeedle.Height;
FNeedle.Fill.Color := FNeedleColor;
FNeedle.Stored := False;
end;
procedure TiOSGauge.Resize;
begin
inherited;
FNeedleCenter.Position.X := FWidth/2-5;
FNeedleCenter.Position.Y := FHeight/2-5;
if FHeight < FWidth then
FNeedle.Height := FHeight/2*0.85
else
FNeedle.Height := FWidth/2*0.85;
FNeedle.Position.Y := 6-FNeedle.Height;
end;
procedure TiOSGauge.SetMax(const Value: Double);
begin
FMax := Value;
UpdateNeedle;
end;
procedure TiOSGauge.SetMaxAngle(const Value: Double);
begin
FMaxAngle := Value;
UpdateNeedle;
end;
procedure TiOSGauge.SetMin(const Value: Double);
begin
FMin := Value;
UpdateNeedle;
end;
procedure TiOSGauge.SetMinAngle(const Value: Double);
begin
FMinAngle := Value;
UpdateNeedle;
end;
procedure TiOSGauge.SetNeedleCenterColor(const Value: TAlphaColor);
begin
FNeedleCenterColor := Value;
FNeedleCenter.Fill.Color := Value;
end;
procedure TiOSGauge.SetNeedleColor(const Value: TAlphaColor);
begin
FNeedleColor := Value;
FNeedle.Fill.Color := Value;
end;
procedure TiOSGauge.SetValue(const Value: Double);
begin
FValue := Value;
if FValue < Min then
FValue := Min;
if FValue > Max then
FValue := Max;
UpdateNeedle;
end;
procedure TiOSGauge.SetZeroAngle(const Value: Double);
begin
FZeroAngle := Value;
UpdateNeedle;
end;
procedure TiOSGauge.UpdateNeedle;
begin
FNeedleCenter.RotationAngle := FZeroAngle+FValue*(FMaxAngle-FMinAngle)/(FMax-FMin);
end;
procedure Register;
begin
RegisterComponents('iOS', [TiOSGauge]);
end;
end.
|
namespace org.me.helloworld.manualui;
//Sample app by Brian Long (http://blong.com)
{
This example is a simple Android application with a button that displays a dialog
However there is no UI layout file - the (admittedly simple) UI is built up in code
}
interface
uses
java.util,
java.text,
android.os,
android.app,
android.util,
android.view,
android.content,
android.widget;
type
MainActivity = public class(Activity)
private
//Identify the dialog
const HelloDialog = 1;
var helloButton: Button;
protected
//Called the first time the dialog is displayed
method onCreateDialog(Id: Integer): Dialog; override;
//Called every time the dialog is displayed
method onPrepareDialog(Id: Integer; Dlg: Dialog); override;
public
method onCreate(savedInstanceState: Bundle); override;
end;
implementation
method MainActivity.onCreate(savedInstanceState: Bundle);
begin
inherited;
var mainLayout := new LinearLayout(Self);
//Make a linear layout that fills the screen and centres child views horizontally & vertically
mainLayout.Orientation := LinearLayout.VERTICAL;
mainLayout.LayoutParams := new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
mainLayout.Gravity := Gravity.CENTER_VERTICAL or Gravity.CENTER_HORIZONTAL;
//Make a button as tall.wide as its content dictates
helloButton := new Button(Self);
helloButton.Text := String[R.string.hello_button_text];
helloButton.LayoutParams := new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//Add button to the layout and make that our UI
mainLayout.addView(helloButton);
ContentView := mainLayout;
helloButton.OnClickListener := -> showDialog(HelloDialog);
end;
//This is called the first time the dialog is displayed
method MainActivity.onCreateDialog(Id: Integer): Dialog;
begin
Result := inherited;
if Id = HelloDialog then
begin
var builder := new AlertDialog.Builder(Self);
//Put a default message on the dialog (though this will be overwritten in onPrepareDialog)
builder.Message := R.string.hello_dialog_message;
//Don't allow Back to get rid of the dialog
builder.Cancelable := False;
//Set up the positive response button, which happens to be the only button
builder.setPositiveButton(R.string.hello_dialog_button_text, (s, a) -> (s as Dialog).dismiss);
//Make the dialog
Result := builder.&create;
//Do something when the dialog is dismissed - update the activity's button
Result.OnDismissListener := (d) -> begin helloButton.Text := String[R.string.hello_button_text_2] end;
end;
end;
//This is called every time the dialog is displayed
method MainActivity.onPrepareDialog(Id: Integer; Dlg: Dialog);
begin
if Id = HelloDialog then
begin
//Update the dialog's message
var msg := Dlg.findViewById(Android.R.id.message) as TextView;
if msg <> nil then
msg.Text := String[R.string.hello_dialog_message_2] + DateFormat.DateTimeInstance.format(new Date);
end
end;
end. |
unit uframeChrome;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
ExtCtrls, uCEFChromium, uCEFWindowParent, uCEFInterfaces, uCEFConstants,
unConfig, uCEFTypes, Dialogs;
type
TframeChrome = class(TFrame)
CEFWindowParent1: TCEFWindowParent;
Chromium1: TChromium;
Splitter1: TSplitter;
DevTools: TCEFWindowParent;
Timer1: TTimer;
procedure Chromium1AfterCreated(Sender: TObject;
const browser: ICefBrowser);
procedure Chromium1BeforeContextMenu(Sender: TObject;
const browser: ICefBrowser; const frame: ICefFrame;
const params: ICefContextMenuParams; const model: ICefMenuModel);
procedure Timer1Timer(Sender: TObject);
procedure Chromium1BeforeClose(Sender: TObject; const browser: ICefBrowser);
procedure Chromium1Close(Sender: TObject; const browser: ICefBrowser;
out Result: Boolean);
procedure Chromium1ProcessMessageReceived(Sender: TObject;
const browser: ICefBrowser; sourceProcess: TCefProcessId;
const message: ICefProcessMessage; out Result: Boolean);
procedure Chromium1ContextMenuCommand(Sender: TObject;
const browser: ICefBrowser; const frame: ICefFrame;
const params: ICefContextMenuParams; commandId: Integer;
eventFlags: Cardinal; out Result: Boolean);
procedure Chromium1BeforePopup(Sender: TObject; const browser: ICefBrowser;
const frame: ICefFrame; const targetUrl, targetFrameName: ustring;
targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean;
const popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo;
var client: ICefClient; var settings: TCefBrowserSettings;
var noJavascriptAccess, Result: Boolean);
procedure Chromium1BeforeBrowse(Sender: TObject; const browser: ICefBrowser;
const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean;
out Result: Boolean);
private
{ Private declarations }
FCaption: string;
FUrl: string;
FHeight: Integer;
FWidth: Integer;
FParentForm: TForm;
procedure BrowserCreatedMsg(var aMessage: TMessage);
message CEF_AFTERCREATED;
procedure ShowDevToolsMsg(var aMessage: TMessage);
message YS_BROWSER_APP_SHOWDEVTOOLS;
procedure HideDevToolsMsg(var aMessage: TMessage);
message YS_BROWSER_APP_HIDEDEVTOOLS;
procedure RefreshBrowse(var aMessage: TMessage);
message YS_BROWSER_APP_REFRESH;
procedure ShowForm(var aMessage: TMessage); message YS_BROWSER_APP_SHOW;
procedure ShowModalForm(var aMessage: TMessage);
message YS_BROWSER_APP_SHOWMODAL;
procedure BrowserDestroyMsg(var aMessage: TMessage); message CEF_DESTROY;
protected
procedure ShowDevTools(aPoint: TPoint); overload;
procedure ShowDevTools; overload;
procedure HideDevTools;
public
{ Public declarations }
FClosing: Boolean; // Set to True in the CloseQuery event.
FCanClose: Boolean; // Set to True in TChromium.OnBeforeClose
procedure setInfo(parentForm: TForm; url: string);
end;
implementation
{$R *.dfm}
{ TframeChrome }
uses
ufrmModal;
procedure TframeChrome.BrowserCreatedMsg(var aMessage: TMessage);
begin
Chromium1.LoadUrl(Self.FUrl);
end;
procedure TframeChrome.BrowserDestroyMsg(var aMessage: TMessage);
begin
CEFWindowParent1.Free;
end;
procedure TframeChrome.Chromium1AfterCreated(Sender: TObject;
const browser: ICefBrowser);
begin
if Chromium1.IsSameBrowser(browser) then
PostMessage(Handle, CEF_AFTERCREATED, 0, 0)
else
SendMessage(browser.Host.WindowHandle, WM_SETICON, 1,
application.Icon.Handle);
end;
procedure TframeChrome.Chromium1BeforeBrowse(Sender: TObject;
const browser: ICefBrowser; const frame: ICefFrame;
const request: ICefRequest; isRedirect: Boolean; out Result: Boolean);
begin
//ShowMessage(request.Url);
end;
procedure TframeChrome.Chromium1BeforeClose(Sender: TObject;
const browser: ICefBrowser);
begin
FCanClose := True;
PostMessage(Self.FParentForm.Handle, WM_CLOSE, 0, 0);
end;
procedure TframeChrome.Chromium1BeforeContextMenu(Sender: TObject;
const browser: ICefBrowser; const frame: ICefFrame;
const params: ICefContextMenuParams; const model: ICefMenuModel);
begin
// 非调试模式下,无右键菜单
if FDebug = 0 then
begin
model.Clear;
Exit;
end;
model.AddSeparator;
if DevTools.Visible then
model.AddItem(YS_BROWSER_CONTEXTMENU_HIDEDEVTOOLS, '关闭开发工具')
else
model.AddItem(YS_BROWSER_CONTEXTMENU_SHOWDEVTOOLS, '显示开发工具');
model.AddItem(YS_BROWSER_CONTEXTMENU_REFRESH, '刷新(&R)');
end;
procedure TframeChrome.Chromium1BeforePopup(Sender: TObject;
const browser: ICefBrowser; const frame: ICefFrame; const targetUrl,
targetFrameName: ustring; targetDisposition: TCefWindowOpenDisposition;
userGesture: Boolean; const popupFeatures: TCefPopupFeatures;
var windowInfo: TCefWindowInfo; var client: ICefClient;
var settings: TCefBrowserSettings; var noJavascriptAccess, Result: Boolean);
begin
//拦截链接行为,弹出新窗口
Self.FCaption := targetFrameName;
Self.FUrl := targetUrl;
if popupFeatures.widthSet = 1 then
Self.FWidth := popupFeatures.width
else
Self.FWidth := unConfig.FWidth;
if popupFeatures.heightSet = 1 then
Self.FHeight := popupFeatures.height
else
Self.FHeight := unConfig.FHeight;
if popupFeatures.dialog = 1 then//弹出窗口
PostMessage(Handle, YS_BROWSER_APP_SHOWMODAL, 0, 0)
else
PostMessage(Handle, YS_BROWSER_APP_SHOW, 0, 0);
Result := True;
end;
procedure TframeChrome.Chromium1Close(Sender: TObject;
const browser: ICefBrowser; out Result: Boolean);
begin
PostMessage(Handle, CEF_DESTROY, 0, 0);
Result := True;
end;
procedure TframeChrome.Chromium1ContextMenuCommand(Sender: TObject;
const browser: ICefBrowser; const frame: ICefFrame;
const params: ICefContextMenuParams; commandId: Integer;
eventFlags: Cardinal; out Result: Boolean);
var
TempParam: WParam;
begin
// 右键菜单响应
Result := false;
case commandId of
YS_BROWSER_CONTEXTMENU_HIDEDEVTOOLS:
PostMessage(Handle, YS_BROWSER_APP_HIDEDEVTOOLS, 0, 0);
YS_BROWSER_CONTEXTMENU_SHOWDEVTOOLS:
begin
TempParam := ((params.XCoord and $FFFF) shl 16) or
(params.YCoord and $FFFF);
PostMessage(Handle, YS_BROWSER_APP_SHOWDEVTOOLS, TempParam, 0);
end;
YS_BROWSER_CONTEXTMENU_REFRESH:
PostMessage(Handle, YS_BROWSER_APP_REFRESH, 0, 0);
end;
end;
procedure TframeChrome.Chromium1ProcessMessageReceived(Sender: TObject;
const browser: ICefBrowser; sourceProcess: TCefProcessId;
const message: ICefProcessMessage; out Result: Boolean);
begin
// 拓展消息响应
FUrl := message.ArgumentList.GetString(0);
FWidth := message.ArgumentList.GetInt(1);
FHeight := message.ArgumentList.GetInt(2);
if (message.Name = YS_BROWSER_EXTENSION_SHOW) then
PostMessage(Handle, YS_BROWSER_APP_SHOW, 0, 0)
else if (message.Name = YS_BROWSER_EXTENSION_SHOWMODAL) then
PostMessage(Handle, YS_BROWSER_APP_SHOWMODAL, 0, 0);
end;
procedure TframeChrome.HideDevTools;
begin
Chromium1.CloseDevTools(DevTools);
Splitter1.Visible := false;
DevTools.Visible := false;
DevTools.Width := 0;
end;
procedure TframeChrome.HideDevToolsMsg(var aMessage: TMessage);
begin
HideDevTools;
end;
procedure TframeChrome.RefreshBrowse(var aMessage: TMessage);
begin
Chromium1.ReloadIgnoreCache;
end;
procedure TframeChrome.setInfo(parentForm: TForm; url: string);
begin
Self.FParentForm := parentForm;
Self.FUrl := url;
Self.FCanClose := false;
Self.FClosing := false;
if not (Chromium1.CreateBrowser(CEFWindowParent1, '')) then
Timer1.Enabled := True;
end;
procedure TframeChrome.ShowDevTools;
var
TempPoint: TPoint;
begin
TempPoint.x := low(Integer);
TempPoint.y := low(Integer);
ShowDevTools(TempPoint);
end;
procedure TframeChrome.ShowDevTools(aPoint: TPoint);
begin
Splitter1.Visible := True;
DevTools.Visible := True;
DevTools.Width := Width div 4;
Chromium1.ShowDevTools(aPoint, DevTools);
end;
procedure TframeChrome.ShowDevToolsMsg(var aMessage: TMessage);
var
TempPoint: TPoint;
begin
TempPoint.x := (aMessage.WParam shr 16) and $FFFF;
TempPoint.y := aMessage.WParam and $FFFF;
ShowDevTools(TempPoint);
end;
procedure TframeChrome.ShowForm(var aMessage: TMessage);
begin
frmModal := TfrmModal.Create(Self.FCaption, Self.FUrl, Self.FWidth,
Self.FHeight);
frmModal.Show;
end;
procedure TframeChrome.ShowModalForm(var aMessage: TMessage);
var
frmModal1: TfrmModal;
begin
frmModal1 := TfrmModal.Create(Self.FCaption, Self.FUrl, Self.FWidth,
Self.FHeight);
frmModal1.ShowModal;
frmModal1.Free;
end;
procedure TframeChrome.Timer1Timer(Sender: TObject);
begin
TTimer(Sender).Enabled := false;
if not (Chromium1.CreateBrowser(CEFWindowParent1, '')) and not
(Chromium1.Initialized) then
TTimer(Sender).Enabled := True;
end;
end.
|
{
Compiler for tinypas. Everything is rolled in a single file.
}
program tinypascal;
uses
SysUtils;
const
_PROGRAM = 1;
_USES = 2;
_WHITE_SPACE = 3;
_NUMBER = 4;
_IDENTIFIER = 5;
_LBRACE = 6;
_RBRACE = 7;
_IF = 8;
_SEMICOLON = 9;
_BEGIN = 10;
_END = 11;
_THEN = 12;
_ELSE = 13;
_DOT = 14;
_AND = 15;
_OR = 16;
_PLUS = 17;
_MINUS = 18;
_MULT = 19;
_DIV = 20;
_FUNCTION = 21;
_PROCEDURE = 22;
_EQUAL = 23;
_ASSIGNMENT = 24;
_LESS_THAN = 25;
_MORE_THAN = 26;
{ Lexing-related values. }
var
yyinput: Text;
yyoutput: Text;
yytext: String;
yyunreadch: Char;
yytoken: Integer;
var
tok: integer;
{ Display a "user-friendly" error message. }
procedure error(s: String; s2: String);
begin
Write('[0;31;40m');
Write('Compilation error: ');
Write(s);
if s2 <> '' then
begin
Write(s2)
end;
Writeln('[0;37;40m');
Halt(-1);
end;
procedure yysetup;
begin
yyunreadch := #0;
yytoken := 0;
end;
{ Get a character from the file. Returns yyunreadch if it's defined. }
function Getch: Char;
var
c: Char;
begin
if yyunreadch = #0 then
Read(yyinput, c)
else
begin
c := yyunreadch;
yyunreadch := #0;
end;
exit(c);
end;
procedure Ungetc(c: Char);
begin
yyunreadch := c;
end;
{
As far as lexers go, this one is pretty slow because
it reads everything byte-by-byte.
}
function NextToken: integer;
var
c: Char;
fpos: Integer;
s: String; { Temporary string }
begin
yytext := '';
c := Getch();
while True do
begin
{ Ignore white space and comments }
if c = '{' then
begin
repeat
c := Getch();
until (c = '}');
c := Getch();
continue;
end
{ #9 and #10 are the Pascal notation for tab and \n, respectively. }
else if (c = ' ') or (c = #10) or (c = #09) then
begin
repeat
c := Getch();
until (c <> ' ') and (c <> #10) and (c <> #09);
continue;
end
else
break;
c := Getch();
end;
if c = ';' then
exit(_SEMICOLON)
else if c = '.' then
exit(_DOT)
else if c = '+' then
exit(_PLUS)
else if c = '-' then
exit(_MINUS)
else if c = '*' then
exit(_MULT)
else if c = '/' then
exit(_DIV)
else if c = ':' then
begin
c := Getch();
if c <> '=' then
error('expected :=, got ', yytext);
exit(_ASSIGNMENT)
end
else if (c >= '0') and (c <= '9') then
begin
yytext := '';
repeat
yytext := yytext + c;
c := Getch()
until (c < '0') or (c > '9');
{ We've read one character too many. Put it back. }
Ungetc(c);
exit(_NUMBER);
end
else if ((c >= 'a') and (c <= 'z')) or ((c >= 'A') and (c <= 'Z')) then
begin
repeat
yytext := yytext + c;
c := Getch();
until (c = ' ') or (c = #10) or (c = #09) or (c = ';') or (c = '.');
{ If we're here, we've read one character too far. Put it back. }
Ungetc(c);
{ Convert to lowercase for convenience }
yytext := Lowercase(yytext);
if CompareText(yytext, 'program') = 0 then
exit(_PROGRAM)
else if CompareText(yytext, 'uses') = 0 then
exit(_USES)
else if CompareText(yytext, 'if') = 0 then
exit(_IF)
else if CompareText(yytext, 'begin') = 0 then
exit(_BEGIN)
else if CompareText(yytext, 'end') = 0 then
exit(_END)
else
exit(_IDENTIFIER);
end;
end;
function yylex: Integer;
var
token: Integer;
begin
if yytoken = 0 then
token := nextToken()
else
begin
token := yytoken;
yytoken := 0;
end;
exit(token)
end;
procedure yyunread(token: Integer);
begin
yytoken := token
end;
{ I'm using the Pascal grammar from
http://www2.informatik.uni-halle.de/lehre/pascal/sprache/pas_bnf.html }
procedure pascal_program; Forward;
procedure code_block; Forward;
procedure statement_list; Forward;
procedure additive_expression; Forward;
procedure multiplicative_expression; Forward;
procedure emit(s: String; s2: String); Forward;
procedure pascal_program;
var
token: integer;
begin
token := yylex();
if token <> _PROGRAM then
begin
error('expecting PROGRAM statement, got: ', yytext)
end;
token := yylex();
if token <> _IDENTIFIER then
begin
error('expecting identifier, got: ', yytext)
end;
token := yylex();
if token <> _SEMICOLON then
begin
error('expecting semicolon, got: ', yytext)
end;
code_block();
token := yylex();
if token <> _DOT then
error('expecting dot, got: ', yytext);
end;
procedure code_block;
var
token: integer;
begin
token := yylex();
if token <> _BEGIN then
error('expecting BEGIN statement, got: ', yytext);
statement_list();
token := yylex();
if token <> _END then
error('expecting END statement, got: ', yytext);
end;
procedure statement_list;
var
token: integer;
begin
token := yylex();
if token = _IDENTIFIER then
begin
token := yylex();
if token = _ASSIGNMENT then
additive_expression()
else
error('expecting '':='', got: ', yytext);
end
else if token = _END then
begin
yyunread(token);
exit()
end
end;
procedure additive_expression;
var
token: integer;
begin
multiplicative_expression();
token := yylex();
{ The user typed a single number. Return. }
if (token = _SEMICOLON) or (token = _END) then
begin
yyunread(token);
exit()
end;
if (token = _PLUS) or (token = _MINUS) then
begin
additive_expression();
Emit('pop rbx', '');
Emit('pop rax', '');
if token = _PLUS then
Emit('add rax, rbx', '')
else if token = _MINUS then
Emit('sub rax, rbx', '');
{ Don't forget to push the result back on the stack }
Emit('push rax', '')
end
else
Error('unexpected token ', yytext)
end;
procedure multiplicative_expression;
var
token: integer;
begin
token := yylex();
if token <> _NUMBER then
Error('expecting number, got:', yytext);
Emit('mov rax', yytext);
Emit('push rax', '');
token := yylex();
{ The user typed a single number. Return. }
if token = _MULT then
begin
multiplicative_expression();
Emit('pop rbx', '');
Emit('pop rax', '');
Emit('imul rax, rbx', '');
Emit('push rax', '');
end
else
begin
yyunread(token);
exit()
end
end;
procedure emit_assembly_header;
begin
Writeln('; On MacOS X use something like /usr/local/bin/nasm -f macho64 file.asm && ld -macosx_version_min 10.7.0 -lSystem -o file file.o && ./file');
Writeln('; to compile. You may need to get nasm from homebrew.');
Writeln('global start');
Writeln('');
Writeln('section .text');
Writeln('start:');
Writeln('; setup the stack');
Writeln(' push rbp');
Writeln(' mov rbp, rsp');
end;
procedure emit_assembly_footer;
begin
Writeln(' ; call MacOS'' exit routine');
Writeln(' mov rax, 0x2000001');
Writeln(' mov rdi, 0');
Writeln(' syscall');
Writeln('; Over and out')
end;
{ Emit a line of assembly. }
procedure emit(s: String; s2: String);
begin
Write(' ');
Write(s);
if s2 <> '' then
begin
Write(', ');
Write(s2);
end;
Writeln('');
end;
begin
assign(yyinput, ParamStr(1));
reset(yyinput);
yysetup();
emit_assembly_header;
pascal_program();
emit_assembly_footer;
end.
|
unit InflatablesList_Manager_IO_00000009;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
AuxTypes,
InflatablesList_Manager_IO_00000008;
type
TILManager_IO_00000009 = class(TILManager_IO_00000008)
protected
procedure InitSaveFunctions(Struct: UInt32); override;
procedure InitLoadFunctions(Struct: UInt32); override;
procedure SaveList_00000009(Stream: TStream); virtual;
procedure LoadList_00000009(Stream: TStream); virtual;
end;
implementation
uses
SysUtils,
BinaryStreaming,
InflatablesList_Utils,
InflatablesList_Manager_IO;
procedure TILManager_IO_00000009.InitSaveFunctions(Struct: UInt32);
begin
If Struct = IL_LISTFILE_STREAMSTRUCTURE_00000009 then
begin
fFNSaveToStream := SaveList_00000009;
fFNSaveSortingSettings := SaveSortingSettings_00000008;
fFNSaveShopTemplates := SaveShopTemplates_00000008;
fFNSaveFilterSettings := SaveFilterSettings_00000008;
fFNSaveItems := SaveItems_00000008;
end
else inherited InitSaveFunctions(Struct);
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000009.InitLoadFunctions(Struct: UInt32);
begin
If Struct = IL_LISTFILE_STREAMSTRUCTURE_00000009 then
begin
fFNLoadFromStream := LoadList_00000009;
fFNLoadSortingSettings := LoadSortingSettings_00000008;
fFNLoadShopTemplates := LoadShopTemplates_00000008;
fFNLoadFilterSettings := LoadFilterSettings_00000008;
fFNLoadItems := LoadItems_00000008;
end
else
inherited InitLoadFunctions(Struct);
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000009.SaveList_00000009(Stream: TStream);
begin
Stream_WriteString(Stream,IL_FormatDateTime('yyyy-mm-dd-hh-nn-ss-zzz',Now));
fFNSaveSortingSettings(Stream);
fFNSaveShopTemplates(Stream);
fFNSaveFilterSettings(Stream);
fFNSaveItems(Stream);
Stream_WriteString(Stream,fNotes);
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000009.LoadList_00000009(Stream: TStream);
begin
Stream_ReadString(Stream); // discard time
fFNLoadSortingSettings(Stream);
fFNLoadShopTemplates(Stream);
fFNLoadFilterSettings(Stream);
fFNLoadItems(Stream);
fNotes := Stream_ReadString(Stream);
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Controller relacionado aos procedimentos de venda
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
******************************************************************************* }
unit VendaController;
interface
uses
Classes, SysUtils, EcfVendaCabecalhoVO, EcfVendaDetalheVO, md5,
VO, Controller, Biblioteca, EcfTotalTipoPagamentoVO;
type
TVendaController = class(TController)
private
public
class function ConsultaLista(pFiltro: String): TListaEcfVendaCabecalhoVO;
class function ConsultaObjeto(pFiltro: String): TEcfVendaCabecalhoVO;
class function VendaDetalhe(pFiltro: String): TEcfVendaDetalheVO;
class function ExisteVendaAberta: Boolean;
class function Insere(pObjeto: TEcfVendaCabecalhoVO): TEcfVendaCabecalhoVO;
class function InsereItem(pObjeto: TEcfVendaDetalheVO): TEcfVendaDetalheVO;
class function Altera(pObjeto: TEcfVendaCabecalhoVO): Boolean;
class function CancelaVenda(pObjeto: TEcfVendaCabecalhoVO): Boolean;
class function CancelaItemVenda(pObjeto: TEcfVendaDetalheVO): Boolean;
end;
implementation
uses T2TiORM, EcfMovimentoController, LogssController, ClienteVO, EcfFuncionarioVO,
ProdutoController;
var
ObjetoLocal: TEcfVendaCabecalhoVO;
class function TVendaController.ConsultaLista(pFiltro: String): TListaEcfVendaCabecalhoVO;
begin
try
ObjetoLocal := TEcfVendaCabecalhoVO.Create;
Result := TListaEcfVendaCabecalhoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True));
finally
ObjetoLocal.Free;
end;
end;
class function TVendaController.ConsultaObjeto(pFiltro: String): TEcfVendaCabecalhoVO;
var
Filtro: String;
begin
try
Result := TEcfVendaCabecalhoVO.Create;
Result := TEcfVendaCabecalhoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
if Assigned(Result) then
begin
//Exercício: crie o método para popular esses objetos automaticamente no T2TiORM
Result.EcfFuncionarioVO := TEcfFuncionarioVO(TT2TiORM.ConsultarUmObjeto(Result.EcfFuncionarioVO, 'ID='+IntToStr(Result.IdEcfFuncionario), True));
Result.EcfMovimentoVO := TEcfMovimentoController.ConsultaObjeto('ID='+IntToStr(Result.IdEcfMovimento));
Filtro := 'ID_ECF_VENDA_CABECALHO = ' + IntToStr(Result.Id);
Result.ListaEcfVendaDetalheVO := TListaEcfVendaDetalheVO(TT2TiORM.Consultar(TEcfVendaDetalheVO.Create, Filtro, True));
Result.ListaEcfTotalTipoPagamentoVO := TListaEcfTotalTipoPagamentoVO(TT2TiORM.Consultar(TEcfTotalTipoPagamentoVO.Create, Filtro, True));
end;
finally
end;
end;
class function TVendaController.VendaDetalhe(pFiltro: String): TEcfVendaDetalheVO;
begin
try
Result := TEcfVendaDetalheVO.Create;
Result := TEcfVendaDetalheVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
//Exercício: crie o método para popular esses objetos automaticamente no T2TiORM
Result.EcfProdutoVO := TProdutoController.ConsultaObjeto('ID='+IntToStr(Result.IdEcfProduto));
finally
end;
end;
class function TVendaController.ExisteVendaAberta: Boolean;
var
Filtro: String;
Retorno: TListaEcfVendaCabecalhoVO;
begin
try
ObjetoLocal := TEcfVendaCabecalhoVO.Create;
Filtro := 'STATUS_VENDA = ' + QuotedStr('A');
Retorno := TListaEcfVendaCabecalhoVO(TT2TiORM.Consultar(ObjetoLocal, Filtro, False));
Result := Assigned(Retorno);
finally
ObjetoLocal.Free;
end;
end;
class function TVendaController.Insere(pObjeto: TEcfVendaCabecalhoVO): TEcfVendaCabecalhoVO;
var
UltimoID: Integer;
begin
try
pObjeto.SerieEcf := Sessao.Configuracao.EcfImpressoraVO.Serie;
UltimoID := TT2TiORM.Inserir(pObjeto);
Result := ConsultaObjeto('ID=' + IntToStr(UltimoID));
finally
end;
end;
class function TVendaController.InsereItem(pObjeto: TEcfVendaDetalheVO): TEcfVendaDetalheVO;
var
UltimoID: Integer;
begin
try
if pObjeto.EcfProdutoVO.EcfIcmsSt = 'NN' then
pObjeto.EcfIcmsSt := 'N'
else if pObjeto.EcfProdutoVO.EcfIcmsSt = 'FF' then
pObjeto.EcfIcmsSt := 'F'
else if pObjeto.EcfProdutoVO.EcfIcmsSt = 'II' then
pObjeto.EcfIcmsSt := 'I'
else
begin
if copy(pObjeto.TotalizadorParcial, 3, 1) = 'S' then
pObjeto.EcfIcmsSt := copy(pObjeto.TotalizadorParcial, 4, 4)
else if copy(pObjeto.TotalizadorParcial, 3, 1) = 'T' then
pObjeto.EcfIcmsSt := copy(pObjeto.TotalizadorParcial, 4, 4)
else if pObjeto.TotalizadorParcial = 'Can-T' then
pObjeto.EcfIcmsSt := 'CANC'
else
begin
pObjeto.EcfIcmsSt := '1700';
end;
end;
pObjeto.Cancelado := 'N';
if (pObjeto.EcfProdutoVO.EcfIcmsSt = 'II') or (pObjeto.EcfProdutoVO.EcfIcmsSt = 'NN') then
pObjeto.TaxaICMS := 0;
pObjeto.SerieEcf := Sessao.Configuracao.EcfImpressoraVO.Serie;
FormatSettings.DecimalSeparator := '.';
pObjeto.HashRegistro := '0';
pObjeto.HashRegistro := MD5Print(MD5String(pObjeto.ToJSONString));
UltimoID := TT2TiORM.Inserir(pObjeto);
Result := VendaDetalhe('ID = ' + IntToStr(UltimoID));
finally
FormatSettings.DecimalSeparator := ',';
end;
end;
class function TVendaController.Altera(pObjeto: TEcfVendaCabecalhoVO): Boolean;
begin
try
FormatSettings.DecimalSeparator := '.';
pObjeto.HashRegistro := '0';
pObjeto.HashRegistro := MD5Print(MD5String(pObjeto.ToJSONString));
Result := TT2TiORM.Alterar(pObjeto);
TLogssController.AtualizarQuantidades;
finally
FormatSettings.DecimalSeparator := ',';
end;
end;
class function TVendaController.CancelaVenda(pObjeto: TEcfVendaCabecalhoVO): Boolean;
var
I: Integer;
begin
try
FormatSettings.DecimalSeparator := '.';
pObjeto.HashRegistro := '0';
pObjeto.HashRegistro := MD5Print(MD5String(pObjeto.ToJSONString));
Result := TT2TiORM.Alterar(pObjeto);
// Detalhes
for I := 0 to pObjeto.ListaEcfVendaDetalheVO.Count - 1 do
begin
pObjeto.ListaEcfVendaDetalheVO[I].TotalizadorParcial := 'Can-T';
pObjeto.ListaEcfVendaDetalheVO[I].Cancelado := 'S';
pObjeto.ListaEcfVendaDetalheVO[I].Ccf := pObjeto.Ccf;
pObjeto.ListaEcfVendaDetalheVO[I].Coo := pObjeto.Coo;
pObjeto.ListaEcfVendaDetalheVO[I].HashRegistro := '0';
pObjeto.ListaEcfVendaDetalheVO[I].HashRegistro := MD5Print(MD5String(pObjeto.ListaEcfVendaDetalheVO[I].ToJSONString));
Result := TT2TiORM.Alterar(pObjeto.ListaEcfVendaDetalheVO[I])
end;
// Pagamentos
for I := 0 to pObjeto.ListaEcfTotalTipoPagamentoVO.Count - 1 do
begin
pObjeto.ListaEcfTotalTipoPagamentoVO[I].Estorno := 'S';
pObjeto.ListaEcfTotalTipoPagamentoVO[I].HashRegistro := '0';
pObjeto.ListaEcfTotalTipoPagamentoVO[I].HashRegistro := MD5Print(MD5String(pObjeto.ListaEcfTotalTipoPagamentoVO[I].ToJSONString));
Result := TT2TiORM.Alterar(pObjeto.ListaEcfTotalTipoPagamentoVO[I])
end;
finally
FormatSettings.DecimalSeparator := ',';
end;
end;
class function TVendaController.CancelaItemVenda(pObjeto: TEcfVendaDetalheVO): Boolean;
begin
try
FormatSettings.DecimalSeparator := '.';
pObjeto.HashRegistro := '0';
pObjeto.HashRegistro := MD5Print(MD5String(pObjeto.ToJSONString));
Result := TT2TiORM.Alterar(pObjeto);
finally
FormatSettings.DecimalSeparator := ',';
end;
end;
end.
|
{ RRRRRR ReportBuilder Class Library BBBBB
RR RR BB BB
RRRRRR Digital Metaphors Corporation BB BB
RR RR BB BB
RR RR Copyright (c) 1996-2002 BBBBB }
unit rbReportExplorerForm;
interface
{$I ppIfDef.pas}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, ExtCtrls, Buttons, ComCtrls, ImgList, uSystemConst,
ppUtils, ppRptExp, ppForms, ppIniStorage, ppRptExpCommon, StdCtrls,
DBTables, Variants, ppDBPipe;
type
{@TppReportExplorerForm }
TrbReportExplorerForm = class(TppCustomReportExplorer)
sbrExplorer: TStatusBar;
pnlFolders: TPanel;
pnlFolderTitle: TPanel;
trvFolders: TTreeView;
pnlReports: TPanel;
pnlReportTitle: TPanel;
MainMenu: TMainMenu;
mniFile: TMenuItem;
mniFileOpen: TMenuItem;
mniFileNew: TMenuItem;
miN1: TMenuItem;
mniFileClose: TMenuItem;
mniView: TMenuItem;
mniViewStatusBar: TMenuItem;
N6: TMenuItem;
mniViewList: TMenuItem;
mniViewDetails: TMenuItem;
mniHelp: TMenuItem;
mniHelpAbout: TMenuItem;
mniViewToolbar: TMenuItem;
mniHelpTopics: TMenuItem;
N1: TMenuItem;
mniFileNewFolder: TMenuItem;
mniFileNewReport: TMenuItem;
N2: TMenuItem;
mniFileDelete: TMenuItem;
mniFileRename: TMenuItem;
mniFileLine2: TMenuItem;
mniFilePrint: TMenuItem;
mniFilePrintPreview: TMenuItem;
ImageList1: TImageList;
ppmReports: TPopupMenu;
ppmReportsView: TMenuItem;
N8: TMenuItem;
ppmReportsNewFolder: TMenuItem;
ppmReportsNewReport: TMenuItem;
ppmReportsViewList: TMenuItem;
ppmReportsViewDetails: TMenuItem;
ppmFolders: TPopupMenu;
MenuItem4: TMenuItem;
ppmFoldersNewFolder: TMenuItem;
ppmFoldersNewReport: TMenuItem;
ppmFoldersOpen: TMenuItem;
ppmFoldersLine2: TMenuItem;
ppmFoldersDelete: TMenuItem;
ppmFoldersRename: TMenuItem;
N10: TMenuItem;
ppmReportsDelete: TMenuItem;
ppmReportsRename: TMenuItem;
N5: TMenuItem;
tbrExplorer: TPanel;
spbUpOneLevel: TSpeedButton;
spbNewFolder: TSpeedButton;
spbNewReport: TSpeedButton;
spbPrint: TSpeedButton;
spbPrintPreview: TSpeedButton;
spbDelete: TSpeedButton;
spbViewList: TSpeedButton;
spbViewDetails: TSpeedButton;
Shape1: TShape;
Shape2: TShape;
splViews: TSplitter;
ppmReportsDesign: TMenuItem;
ppmReportsPrintPreview: TMenuItem;
ppmReportsPrint: TMenuItem;
ppmReportsOpen: TMenuItem;
N7: TMenuItem;
ppmReportsLine2: TMenuItem;
mniFileDesign: TMenuItem;
ImageList2: TImageList;
Splitter1: TSplitter;
mmHint: TMemo;
ppmReportsEditHint: TMenuItem;
procedure mniFilePrintClick(Sender: TObject);
procedure mniFilePrintPreviewClick(Sender: TObject);
procedure mniFileOpenClick(Sender: TObject);
procedure mniFileNewReportClick(Sender: TObject);
procedure mniFileDeleteClick(Sender: TObject);
procedure mniViewListClick(Sender: TObject);
procedure mniViewDetailsClick(Sender: TObject);
procedure mniViewToolbarClick(Sender: TObject);
procedure mniViewStatusBarClick(Sender: TObject);
procedure mniFileCloseClick(Sender: TObject);
procedure mniHelpAboutClick(Sender: TObject);
procedure mniHelpTopicsClick(Sender: TObject);
procedure mniFileNewFolderClick(Sender: TObject);
procedure trvFoldersEdited(Sender: TObject; Node: TTreeNode; var S: string);
procedure mniFileRenameClick(Sender: TObject);
procedure trvFoldersCollapsing(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean);
procedure spbUpOneLevelClick(Sender: TObject);
procedure trvFoldersDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
procedure trvFoldersDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure trvFoldersEditing(Sender: TObject; Node: TTreeNode; var AllowEdit: Boolean);
procedure ppmFoldersPopup(Sender: TObject);
procedure mniFileDesignClick(Sender: TObject);
procedure trvFoldersChange(Sender: TObject; Node: TTreeNode);
procedure ppmReportsEditHintClick(Sender: TObject);
private
sItem_ID: string;
FListView: TppItemList;
FReportExplorer: TppReportExplorer;
FSpeedButtons: TList;
FAllFoldersNode: TTreeNode;
FRecycleBinNode: TTreeNode;
procedure Design;
procedure EmptyRecycleBinClick(Sender: TObject);
procedure EnableFolderOptions;
procedure EnableItemOptions;
function FindDataInTreeView(aTreeView: TTreeView; aData: Integer): TTreeNode;
function FindNearestNode(aNode: TTreeNode): TTreeNode;
procedure FoldersSelectionChange;
procedure InitializeOptions;
procedure ListDoubleClickEvent(Sender: TObject);
procedure ListDragOverEvent(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
procedure ListFolderChangeEvent(Sender: TObject);
procedure ListRenameFolderEvent(Sender: TObject; aFolderId: Integer; const aNewName: string);
procedure ListSelectionChangeEvent(Sender: TObject);
procedure LoadStateInfo;
procedure OpenItem;
procedure Print;
procedure PrintPreview;
procedure SaveStateInfo;
procedure SelectFolder(aFolderId: Integer);
procedure SetViewStyle(Value: Boolean);
procedure SetViewToolbar(Value: Boolean);
procedure SetViewStatusBar(Value: Boolean);
procedure ShiftSpeedButtonsLeft(aSpeedButton: TSpeedButton);
procedure UpdateRecycleBin;
procedure UpdateStatusBar;
procedure UpdateTreeView;
procedure CopyReport(sItemID: string);
protected
procedure LanguageChanged; override;
function GetReportExplorer: TComponent; override;
procedure SetReportExplorer(aComponent: TComponent); override;
property AllFoldersNode: TTreeNode read FAllFoldersNode;
property ListView: TppItemList read FListView;
property RecycleBinNode: TTreeNode read FRecycleBinNode;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure CreateParams(var Params: TCreateParams); override;
procedure Initialize; override;
procedure Refresh; override;
end; {class, TppReportExplorerForm}
implementation
uses
ADODB, uEditHintFch, uDM;
{$R *.DFM}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.Create }
constructor TrbReportExplorerForm.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
FReportExplorer := nil;
FSpeedButtons := nil;
if (FListView = nil) then
begin
FListView := TppItemList.Create(Self);
FListView.Parent := pnlReports;
FListView.Align := alClient;
FListView.MultiSelect := True;
FListView.PopupMenu := ppmReports;
FListView.ViewStyle := vsList;
FListView.OnDoubleClick := ListDoubleClickEvent;
FListView.OnDragOver := ListDragOverEvent;
FListView.OnFolderChange := ListFolderChangeEvent;
FListView.OnRenameFolder := ListRenameFolderEvent;
FListView.OnSelectionChange := ListSelectionChangeEvent;
end;
end; {procedure, Create}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.Destroy }
destructor TrbReportExplorerForm.Destroy;
begin
FSpeedButtons.Free;
SaveStateInfo;
inherited Destroy;
end; {procedure, Destroy}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.CreateParams}
procedure TrbReportExplorerForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW;
end; {procedure, CreateParams}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.Initialize }
procedure TrbReportExplorerForm.Initialize;
begin
LoadStateInfo;
InitializeOptions;
UpdateTreeView;
SelectFolder(FListView.FolderId);
end; {procedure, Initialize}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.LanguageChanged }
procedure TrbReportExplorerForm.LanguageChanged;
var
lsMessage: string;
begin
ppmReportsOpen.Caption := ppLoadStr(511); {&Open}
ppmReportsNewFolder.Caption := ppLoadStr(558); {New &Folder}
ppmReportsNewReport.Caption := ppLoadStr(572); {New &Report}
ppmReportsDesign.Caption := ppLoadStr(185); {Design}
ppmReportsPrint.Caption := ppLoadStr(136); {&Print}
ppmReportsPrintPreview.Caption := ppLoadStr(576); {Print Pre&view}
ppmReportsView.Caption := ppLoadStr(155); {&View}
ppmReportsViewList.Caption := ppLoadStr(510); {&List}
ppmReportsViewDetails.Caption := ppLoadStr(508); {&Details}
ppmReportsDelete.Caption := ppLoadStr(124); {&Delete}
ppmReportsRename.Caption := ppLoadStr(542); {Re&name}
ppmFoldersOpen.Caption := ppLoadStr(511); {&Open}
ppmFoldersNewFolder.Caption := ppLoadStr(558); {New &Folder}
ppmFoldersNewReport.Caption := ppLoadStr(572); {New &Report}
ppmFoldersDelete.Caption := ppLoadStr(124); {&Delete}
ppmFoldersRename.Caption := ppLoadStr(542); {Rena&me}
spbUpOneLevel.Hint := ppLoadStr(589); {Up One Level}
spbNewFolder.Hint := ppLoadStr(545); {Create New Folder}
spbNewReport.Hint := ppLoadStr(571); {New Report}
spbPrint.Hint := ppLoadStr(575); {Print}
spbPrintPreview.Hint := ppLoadStr(577); {Print Preview}
spbDelete.Hint := ppLoadStr(547); {Delete}
spbViewList.Hint := ppLoadStr(566); {List}
spbViewDetails.Hint := ppLoadStr(549); {Details}
pnlFolderTitle.Caption := ppLoadStr(524); {All Folders}
FListView.LanguageIndex := LanguageIndex;
mniFile.Caption := ppLoadStr(131); {&File}
mniFileOpen.Caption := ppLoadStr(511); {&Open}
mniFileNew.Caption := ppLoadStr(133); {&New}
mniFileNewFolder.Caption := ppLoadStr(509); {&Folder}
mniFileNewReport.Caption := ppLoadStr(145); {&Report}
mniFileDesign.Caption := ppLoadStr(185); {Design}
mniFilePrint.Caption := ppLoadStr(136); {&Print}
mniFilePrintPreview.Caption := ppLoadStr(576); {Print Pre&view}
mniFileDelete.Caption := ppLoadStr(124); {&Delete}
mniFileRename.Caption := ppLoadStr(512); {&Rename}
mniFileClose.Caption := ppLoadStr(132); {&Close}
mniView.Caption := ppLoadStr(155); {&View}
mniViewToolbar.Caption := ppLoadStr(514); {&Toolbar}
mniViewStatusBar.Caption := ppLoadStr(513); {&Status Bar}
mniViewList.Caption := ppLoadStr(510); {&List}
mniViewDetails.Caption := ppLoadStr(508); {&Details}
mniHelp.Caption := ppLoadStr(142); {&Help}
mniHelpTopics.Caption := ppLoadStr(144); {&Help Topics}
mniHelpAbout.Caption := ppLoadStr(143); {&About}
{Contents of '<name>'}
lsMessage := ppLoadStr(544);
lsMessage := ppSetMessageParameters(lsMessage);
lsMessage := Format(lsMessage, [ppLoadStr(524)]); {'All Folders'}
pnlReportTitle.Caption := ' ' + lsMessage;
end; {procedure, LanguageChanged}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.InitializeOptions }
procedure TrbReportExplorerForm.InitializeOptions;
var
lbVisible: Boolean;
begin
{set visibilty based on open options}
mniFileDesign.Visible := (FReportExplorer.ItemAction <> iaOpenToDesign);
mniFilePrintPreview.Visible := (FReportExplorer.ItemAction <> iaOpenToPreview);
ppmReportsDesign.Visible := mniFileDesign.Visible;
ppmReportsPrintPreview.Visible := mniFilePrintPreview.Visible;
lbVisible := (ioAllowDesign in FReportExplorer.ItemOptions);
mniFileDesign.Visible := mniFileDesign.Visible and lbVisible;
ppmReportsDesign.Visible := ppmReportsDesign.Visible and lbVisible;
lbVisible := (ioAllowNew in FReportExplorer.ItemOptions);
mniFileNewReport.Visible := lbVisible;
spbNewReport.Visible := lbVisible;
ppmFoldersNewReport.Visible := lbVisible;
ppmReportsNewReport.Visible := lbVisible;
ShiftSpeedButtonsLeft(spbNewReport);
{set visibilty based on folder options}
lbVisible := (foAllowNew in FReportExplorer.FolderOptions);
mniFileNewFolder.Visible := lbVisible;
spbNewFolder.Visible := lbVisible;
ppmFoldersNewFolder.Visible := lbVisible;
ppmReportsNewFolder.Visible := lbVisible;
ShiftSpeedButtonsLeft(spbNewFolder);
if not (foAllowNew in FReportExplorer.FolderOptions) and
not (ioAllowNew in FReportExplorer.ItemOptions) then
mniFileNew.Visible := False;
ppmFoldersDelete.Visible := (foAllowDelete in FReportExplorer.FolderOptions);
if not (foAllowDelete in FReportExplorer.FolderOptions) and
not (ioAllowDelete in FReportExplorer.ItemOptions) then
begin
mniFileDelete.Visible := False;
spbDelete.Visible := False;
ppmReportsDelete.Visible := False;
ShiftSpeedButtonsLeft(spbDelete);
end;
ppmFoldersRename.Visible := (foAllowRename in FReportExplorer.FolderOptions);
if not (foAllowRename in FReportExplorer.FolderOptions) and
not (ioAllowRename in FReportExplorer.ItemOptions) then
begin
mniFileRename.Visible := False;
ppmReportsRename.Visible := False;
end;
end; {procedure, InitializeOptions}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.ShiftSpeedButtonsLeft }
procedure TrbReportExplorerForm.ShiftSpeedButtonsLeft(aSpeedButton: TSpeedButton);
var
liPosition: Integer;
lSpeedButton: TSpeedButton;
liIndex: Integer;
begin
if aSpeedButton.Visible then Exit;
if (FSpeedButtons = nil) then
begin
FSpeedButtons := TList.Create;
FSpeedButtons.Add(spbUpOneLevel);
FSpeedButtons.Add(spbNewFolder);
FSpeedButtons.Add(spbNewReport);
FSpeedButtons.Add(spbPrint);
FSpeedButtons.Add(spbPrintPreview);
FSpeedButtons.Add(spbDelete);
FSpeedButtons.Add(spbViewList);
FSpeedButtons.Add(spbViewDetails);
end;
liPosition := FSpeedButtons.IndexOf(aSpeedButton);
if (liPosition = -1) then Exit;
for liIndex := liPosition to FSpeedButtons.Count - 1 do
begin
lSpeedButton := TSpeedButton(FSpeedButtons[liIndex]);
lSpeedButton.Left := lSpeedButton.Left - aSpeedButton.Width;
end;
end; {function, ShiftSpeedButtonsLeft}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.GetReportExplorer }
function TrbReportExplorerForm.GetReportExplorer: TComponent;
begin
Result := FReportExplorer;
end; {function, GetReportExplorer}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.SetReportExplorer }
procedure TrbReportExplorerForm.SetReportExplorer(aComponent: TComponent);
begin
if not (aComponent is TppReportExplorer) then Exit;
FReportExplorer := TppReportExplorer(aComponent);
FListView.ReportExplorer := TppReportExplorer(aComponent);
end; {procedure, SetReportExplorer}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.LoadStateInfo }
procedure TrbReportExplorerForm.LoadStateInfo;
var
lIniStorage: TppIniStorage;
lScreenRes: TPoint;
liLeft: Integer;
liTop: Integer;
liWidth: Integer;
liHeight: Integer;
liWindowState: Integer;
begin
lIniStorage := TppIniStoragePlugIn.CreateInstance;
liLeft := lIniStorage.ReadInteger('Explorer Form Position', 'Left', -1);
if (liLeft = -1) then
begin
lIniStorage.Free;
Exit;
end;
SetFormSettingsRemembered(True);
{set initial size based on screen res}
lScreenRes := ppGetScreenRes;
{calc default screen size }
{set size based on 1024 x 768 }
liWidth := 790;
liHeight := 600;
if lScreenRes.X <> 1024 then
begin
liWidth := (liWidth * lScreenRes.X) div 1024;
liHeight := (Height * lScreenRes.Y) div 768;
end;
{default to center of screen}
liLeft := (Screen.Width - liWidth) div 2;
liTop := (Screen.Height - liHeight) div 2;
liWindowState := lIniStorage.ReadInteger('Explorer Form Position', 'WindowState', Ord(wsNormal));
{load positions from ini file}
if TWindowState(liWindowState) = wsNormal then
begin
liLeft := lIniStorage.ReadInteger('Explorer Form Position', 'Left', liLeft);
liTop := lIniStorage.ReadInteger('Explorer Form Position', 'Top', liTop);
liWidth := lIniStorage.ReadInteger('Explorer Form Position', 'Width', liWidth);
liHeight := lIniStorage.ReadInteger('Explorer Form Position', 'Height', liHeight);
end;
SetBounds(liLeft, liTop, liWidth, liHeight);
if TWindowState(liWindowState) <> wsMinimized then
WindowState := TWindowState(liWindowState);
SetViewStyle(lIniStorage.ReadBool('Explorer Form State', 'ViewList', True));
SetViewToolbar(lIniStorage.ReadBool('Explorer Form State', 'ViewToolbar', True));
SetViewStatusBar(lIniStorage.ReadBool('Explorer Form State', 'ViewStatusBar', True));
FListView.SortMode := lIniStorage.ReadInteger('Explorer Form State', 'SortMode', 1);
FListView.Columns[0].Width := lIniStorage.ReadInteger('Explorer Form State', 'ListViewColumn1Width', 250);
FListView.Columns[1].Width := lIniStorage.ReadInteger('Explorer Form State', 'ListViewColumn2Width', 120);
FListView.Columns[2].Width := lIniStorage.ReadInteger('Explorer Form State', 'ListViewColumn3Width', 100);
FListView.Columns[3].Width := lIniStorage.ReadInteger('Explorer Form State', 'ListViewColumn4Width', 140);
FListView.FolderId := lIniStorage.ReadInteger('Explorer Form State', 'Selected Folder', 0);
FListView.ItemName := lIniStorage.ReadString('Explorer Form State', 'Selected Item', '');
FReportExplorer.CurrentFolderId := FListView.FolderId;
FReportExplorer.CurrentItemName := FListView.ItemName;
lIniStorage.Free;
end; {procedure, LoadStateInfo}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.SaveStateInfo }
procedure TrbReportExplorerForm.SaveStateInfo;
var
lIniStorage: TppIniStorage;
begin
lIniStorage := TppIniStoragePlugIn.CreateInstance;
lIniStorage.WriteInteger('Explorer Form Position', 'WindowState', Ord(WindowState));
lIniStorage.WriteInteger('Explorer Form Position', 'Left', Left);
lIniStorage.WriteInteger('Explorer Form Position', 'Top', Top);
lIniStorage.WriteInteger('Explorer Form Position', 'Width', Width);
lIniStorage.WriteInteger('Explorer Form Position', 'Height', Height);
lIniStorage.WriteBool('Explorer Form State', 'ViewList', mniViewList.Checked);
lIniStorage.WriteBool('Explorer Form State', 'ViewToolbar', mniViewToolbar.Checked);
lIniStorage.WriteBool('Explorer Form State', 'ViewStatusBar', mniViewStatusBar.Checked);
lIniStorage.WriteInteger('Explorer Form State', 'SortMode', FListView.SortMode);
lIniStorage.WriteInteger('Explorer Form State', 'ListViewColumn1Width', FListView.Columns[0].Width);
lIniStorage.WriteInteger('Explorer Form State', 'ListViewColumn2Width', FListView.Columns[1].Width);
lIniStorage.WriteInteger('Explorer Form State', 'ListViewColumn3Width', FListView.Columns[2].Width);
lIniStorage.WriteInteger('Explorer Form State', 'ListViewColumn4Width', FListView.Columns[3].Width);
lIniStorage.WriteInteger('Explorer Form State', 'Selected Folder', FListView.FolderId);
lIniStorage.WriteString('Explorer Form State', 'Selected Item', FListView.ItemName);
lIniStorage.Free;
end; {procedure, SaveStateInfo}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniFileOpenClick }
procedure TrbReportExplorerForm.mniFileOpenClick(Sender: TObject);
begin
if (trvFolders.Focused) then
begin
if (trvFolders.Selected <> nil) and not (trvFolders.Selected.Expanded) then
trvFolders.Selected.Expanded := True;
end
else
OpenItem;
end; {procedure, mniFileOpenClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.OpenItem }
procedure TrbReportExplorerForm.OpenItem;
begin
case FReportExplorer.ItemAction of
iaOpenToDesign: Design;
iaOpenToPreview: PrintPreview;
end;
end; {procedure, OpenItem}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.Design }
procedure TrbReportExplorerForm.Design;
begin
if (FListView.FolderId = itRecycleBin) then Exit;
if (FListView.ItemType <> itReport) or (FListView.ItemName = '') then Exit;
Cursor := crHourGlass;
FListView.Cursor := crHourGlass;
try
FReportExplorer.Open(FListView.ItemName, FListView.FolderId);
finally
Cursor := crDefault;
FListView.Cursor := crDefault;
end;
end; {procedure, Design}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.Print }
procedure TrbReportExplorerForm.Print;
begin
if (FListView.ItemName = '') then Exit;
FReportExplorer.Print(FListView.ItemName, FListView.ItemId);
end; {procedure, Print}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.PrintPreview }
procedure TrbReportExplorerForm.PrintPreview;
begin
if (FListView.ItemName = '') then Exit;
FReportExplorer.PrintPreview(FListView.ItemName, FListView.ItemId);
end; {procedure, PrintPreview}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniFileDesignClick }
procedure TrbReportExplorerForm.mniFileDesignClick(Sender: TObject);
begin
if ppmReportsDesign.Caption = '&Copy...' then
begin
if Application.MessageBox('Copy Report?', 'MainRetail',
MB_ICONQUESTION + MB_YESNO) = 6 then
CopyReport(sItem_ID);
end
else
Design;
end; {procedure, mniFileDesignClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniFilePrintClick }
procedure TrbReportExplorerForm.mniFilePrintClick(Sender: TObject);
begin
Print;
end; {procedure, mniFilePrintClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniFilePrintPreviewClick }
procedure TrbReportExplorerForm.mniFilePrintPreviewClick(Sender: TObject);
begin
PrintPreview;
end; {procedure, mniFilePrintPreviewClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.Refresh }
procedure TrbReportExplorerForm.Refresh;
begin
UpdateTreeView;
SelectFolder(FReportExplorer.CurrentFolderId);
FListView.ItemName := FReportExplorer.CurrentItemName;
end; {procedure, Refresh}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniFileNewReportClick }
procedure TrbReportExplorerForm.mniFileNewReportClick(Sender: TObject);
var
liFolderId: Integer;
begin
if (trvFolders.Selected <> nil) then
liFolderId := Integer(trvFolders.Selected.Data)
else
liFolderId := itAllFolders;
FReportExplorer.New(liFolderId);
end; {procedure, mniFileNewReportClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniFileDeleteClick }
procedure TrbReportExplorerForm.mniFileDeleteClick(Sender: TObject);
var
lNode: TTreeNode;
lNewNode: TTreeNode;
liFolderId: Integer;
begin
lNode := trvFolders.Selected;
if (lNode = nil) then Exit;
if (trvFolders.Focused) then
begin
liFolderId := Integer(lNode.Data);
if (liFolderId = itRecycleBin) then Exit;
if (liFolderId = itAllFolders) then Exit;
if FReportExplorer.ConfirmDeleteFolder(lNode.Text) then
begin
if FReportExplorer.ChangeParentFolder(liFolderId, itRecycleBin) then
begin
lNewNode := FindNearestNode(lNode);
SelectFolder(Integer(lNewNode.Data));
lNode.Free;
end;
end;
end
else
FListView.DeleteSelection;
UpdateRecycleBin;
end; {procedure, mniFileDeleteClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniViewListClick }
procedure TrbReportExplorerForm.mniViewListClick(Sender: TObject);
begin
SetViewStyle(True);
end; {procedure, mniViewListClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniViewDetailsClick }
procedure TrbReportExplorerForm.mniViewDetailsClick(Sender: TObject);
begin
SetViewStyle(False);
end; {procedure, mniViewDetailsClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniViewToolbarClick }
procedure TrbReportExplorerForm.mniViewToolbarClick(Sender: TObject);
begin
SetViewToolbar(not (mniViewToolbar.Checked));
end; {procedure, mniViewToolbarClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniViewStatusBarClick }
procedure TrbReportExplorerForm.mniViewStatusBarClick(Sender: TObject);
begin
SetViewStatusBar(not (mniViewStatusBar.Checked));
end; {procedure, mniViewStatusBarClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniFileCloseClick }
procedure TrbReportExplorerForm.mniFileCloseClick(Sender: TObject);
begin
Close;
end; {procedure, mniFileCloseClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniHelpAboutClick }
procedure TrbReportExplorerForm.mniHelpAboutClick(Sender: TObject);
var
lAboutDlg: TppCustomAboutDialog;
lFormClass: TFormClass;
begin
lFormClass := ppGetFormClass(TppCustomAboutDialog);
lAboutDlg := TppCustomAboutDialog(lFormClass.Create(Self));
lAboutDlg.ShowModal;
lAboutDlg.Free;
end; {procedure, mniHelpAboutClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniHelpTopicsClick }
procedure TrbReportExplorerForm.mniHelpTopicsClick(Sender: TObject);
var
lsDelphiHelpFile: string;
lsDelphiPath: string;
begin
lsDelphiPath := ppGetDelphiPath;
if (lsDelphiPath = '') then Exit;
lsDelphiHelpFile := Application.HelpFile;
Application.HelpFile := lsDelphiPath + '\Help\RBuilder.HLP';
Application.HelpCommand(HELP_FINDER, 0);
Application.HelpFile := lsDelphiHelpFile;
end; {procedure, mniHelpTopicsClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.SetViewStyle }
procedure TrbReportExplorerForm.SetViewStyle(Value: Boolean);
begin
if Value then
begin
mniViewList.Checked := True;
ppmReportsViewList.Checked := True;
spbViewDetails.Down := False;
spbViewList.Down := True;
FListView.ViewStyle := vsList;
end
else
begin
mniViewDetails.Checked := True;
ppmReportsViewDetails.Checked := True;
spbViewList.Down := False;
spbViewDetails.Down := True;
FListView.ViewStyle := vsReport;
end;
end; {procedure, SetViewStyle}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.SetViewToolbar }
procedure TrbReportExplorerForm.SetViewToolbar(Value: Boolean);
begin
mniViewToolbar.Checked := Value;
tbrExplorer.Visible := Value;
end; {procedure, SetViewToolbar}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.SetViewStatusBar }
procedure TrbReportExplorerForm.SetViewStatusBar(Value: Boolean);
begin
mniViewStatusBar.Checked := Value;
sbrExplorer.Visible := Value;
end; {procedure, SetViewStatusBar}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniFileNewFolderClick }
procedure TrbReportExplorerForm.mniFileNewFolderClick(Sender: TObject);
var
lItem: TTreeNode;
lsName: string;
liFolderId: Integer;
begin
lItem := trvFolders.Selected;
if (lItem = nil) then Exit;
if (Integer(lItem.Data) = itRecycleBin) then Exit;
trvFolders.Items.BeginUpdate;
lsName := FReportExplorer.GetNewFolderName(Integer(lItem.Data));
{create the folder record}
if (trvFolders.Selected <> nil) then
FReportExplorer.AddFolder(Integer(trvFolders.Selected.Data), lsName, liFolderID)
else
FReportExplorer.AddFolder(itAllFolders, lsName, liFolderId);
{create the folder node}
lItem := trvFolders.Items.AddChild(trvFolders.Selected, lsName);
lItem.Data := TObject(liFolderID);
lItem.ImageIndex := 0;
lItem.SelectedIndex := 2;
{display the folder node}
if (lItem.Parent <> nil) then
lItem.Parent.Expand(False);
trvFolders.Selected := lItem;
trvFolders.Items.EndUpdate;
{put the node in edit mode}
trvFolders.Selected.EditText;
end; {procedure, mniFileNewFolderClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.trvFoldersEdited }
procedure TrbReportExplorerForm.trvFoldersEdited(Sender: TObject; Node: TTreeNode; var S: string);
begin
if FReportExplorer.ConfirmRenameFolder(Node.Text, S, Integer(Node.Parent.Data)) then
FReportExplorer.RenameFolder(Integer(Node.Data), S)
else
S := Node.Text;
end; {procedure, trvFoldersEdited}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.trvFoldersChange }
procedure TrbReportExplorerForm.trvFoldersChange(Sender: TObject; Node: TTreeNode);
begin
if (trvFolders.Selected <> nil) then
SelectFolder(Integer(trvFolders.Selected.Data));
end; {procedure, trvFoldersChange}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.mniFileRenameClick }
procedure TrbReportExplorerForm.mniFileRenameClick(Sender: TObject);
var
lNode: TTreeNode;
begin
if (trvFolders.Focused) then
begin
lNode := trvFolders.Selected;
if (lNode <> nil) and (Integer(lNode.Data) > itAllFolders) then
lNode.EditText;
end
else
FListView.RenameItem;
end; {procedure, mniFileRenameClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.trvFoldersCollapsing }
procedure TrbReportExplorerForm.trvFoldersCollapsing(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean);
begin
if (Integer(Node.Data) = itAllFolders) then
AllowCollapse := False;
end; {procedure, trvFoldersCollapsing}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.ListDoubleClickEvent }
procedure TrbReportExplorerForm.ListDoubleClickEvent(Sender: TObject);
begin
OpenItem;
end; {procedure, ListDoubleClickEvent}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.ListRenameFolderEvent }
procedure TrbReportExplorerForm.ListRenameFolderEvent(Sender: TObject; aFolderId: Integer; const aNewName: string);
var
lTreeNode: TTreeNode;
begin
lTreeNode := FindDataInTreeView(trvFolders, aFolderId);
lTreeNode.Text := aNewName;
end; {procedure, ListRenameFolderEvent}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.ListDragOverEvent }
procedure TrbReportExplorerForm.ListDragOverEvent(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
{enforce security: foAllowMove}
if not (foAllowMove in FReportExplorer.FolderOptions) and (FListView.ItemType = itFolder) then
Accept := False
else if not (ioAllowMove in FReportExplorer.ItemOptions) and (FListView.ItemType <> itFolder) then
Accept := False;
end; {procedure, ListDragOverEvent}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.FindDataInTreeView }
function TrbReportExplorerForm.FindDataInTreeView(aTreeView: TTreeView; aData: Integer): TTreeNode;
var
liIndex: Integer;
lTreeNode: TTreeNode;
begin
Result := nil;
if (aTreeView.Items.Count = 0) then Exit;
liIndex := 0;
lTreeNode := aTreeView.Items[liIndex];
while (liIndex < aTreeView.Items.Count) and (Integer(lTreeNode.Data) <> aData) do
begin
Inc(liIndex);
lTreeNode := aTreeView.Items[liIndex];
end;
Result := lTreeNode;
end; {procedure, FindDataInTreeView}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.ListFolderChangeEvent }
procedure TrbReportExplorerForm.ListFolderChangeEvent(Sender: TObject);
var
liID: Integer;
begin
liID := FListView.FolderId;
UpdateTreeView;
SelectFolder(liID);
end; {procedure, ListFolderChangeEvent}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.trvFoldersEditing }
procedure TrbReportExplorerForm.trvFoldersEditing(Sender: TObject; Node: TTreeNode; var AllowEdit: Boolean);
begin
if (Integer(Node.Data) = itAllFolders) or (Integer(Node.Data) = itRecycleBin) then
AllowEdit := False
else
AllowEdit := (foAllowRename in FReportExplorer.FolderOptions);
end; {procedure, trvFoldersEditing}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.spbUpOneLevelClick }
procedure TrbReportExplorerForm.spbUpOneLevelClick(Sender: TObject);
var
lItem: TTreeNode;
begin
lItem := trvFolders.Selected;
if (lItem.Parent <> nil) then
SelectFolder(Integer(lItem.Parent.Data));
end; {procedure, spbUpOneLevelClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.trvFoldersDragOver }
procedure TrbReportExplorerForm.trvFoldersDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
var
lItem: TTreeNode;
lSelected: TTreeNode;
lbDragAllowed: Boolean;
begin
Accept := False;
lSelected := trvFolders.Selected;
if (lSelected = nil) then Exit;
if (Source = trvFolders) and ((lSelected = FAllFoldersNode) or (lSelected = FRecycleBinNode)) then Exit;
lbDragAllowed := True;
{enforce security: foAllowMove}
if not (foAllowMove in FReportExplorer.FolderOptions) then
lbDragAllowed := ((Source = FListView) and (FListView.ItemType <> itFolder));
{enforce security: ioAllowMove}
if lbDragAllowed and not (ioAllowMove in FReportExplorer.ItemOptions) then
lbDragAllowed := ((Source = trvFolders) or (FListView.ItemType = itFolder));
if lbDragAllowed then
begin
lItem := trvFolders.GetNodeAt(X, Y);
if (Source = trvFolders) and (lItem <> nil) then
Accept := (lItem <> lSelected) and (lItem <> lSelected.Parent)
else
Accept := True;
end;
end; {procedure, trvFoldersDragOver}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.trvFoldersDragDrop }
procedure TrbReportExplorerForm.trvFoldersDragDrop(Sender, Source: TObject; X, Y: Integer);
var
lTargetItem: TTreeNode;
lSourceItem: TTreeNode;
lNewNode: TTreeNode;
liTargetFolderId: Integer;
liSourceFolderId: Integer;
liFolderId: Integer;
begin
lTargetItem := trvFolders.GetNodeAt(X, Y);
if (lTargetItem <> nil) then
begin
liTargetFolderId := Integer(lTargetItem.Data);
if (Source = trvFolders) then
begin
lSourceItem := trvFolders.Selected;
if (lSourceItem = nil) then Exit;
liSourceFolderId := Integer(lSourceItem.Data);
if FReportExplorer.ChangeParentFolder(liSourceFolderId, liTargetFolderId) then
begin
if (liTargetFolderId = itRecycleBin) then
begin
lNewNode := FindNearestNode(lSourceItem);
if (lNewNode <> nil) then
liFolderId := Integer(lNewNode.Data)
else
liFolderId := itAllFolders;
end
else
liFolderId := liSourceFolderId;
UpdateTreeView;
SelectFolder(liFolderId);
end;
end
else if (Source = FListView) then
begin
FListView.MoveSelectionToFolder(liTargetFolderId);
lSourceItem := trvFolders.Selected;
if (lSourceItem = nil) then Exit;
liSourceFolderId := Integer(lSourceItem.Data);
if (liTargetFolderId = itRecycleBin) then
UpdateRecycleBin
else if (liSourceFolderId = itRecycleBin) then
UpdateRecycleBin
end;
end;
end; {procedure, trvFoldersDragDrop}
{******************************************************************************
*
** R O U T I N E S
*
{******************************************************************************}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.FindNearestNode }
function TrbReportExplorerForm.FindNearestNode(aNode: TTreeNode): TTreeNode;
begin
Result := aNode.GetNextSibling;
if (Result <> nil) then Exit;
Result := aNode.GetPrevSibling;
if (Result <> nil) then Exit;
Result := aNode.Parent;
if (Result <> nil) then Exit;
Result := trvFolders.Items[0];
end; {function, FindNearestNode}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.SelectFolder }
procedure TrbReportExplorerForm.SelectFolder(aFolderId: Integer);
var
liIndex: Integer;
lItem: TTreeNode;
lItemFound: TTreeNode;
begin
trvFolders.Items.BeginUpdate;
liIndex := 0;
lItemFound := nil;
while (liIndex < trvFolders.Items.Count) do
begin
lItem := trvFolders.Items[liIndex];
if (Integer(lItem.Data) >= itAllFolders) then
lItem.ImageIndex := 0;
if (lItemFound = nil) and (Integer(lItem.Data) = aFolderId) then
lItemFound := lItem;
Inc(liIndex);
end;
if (lItemFound <> nil) then
begin
trvFolders.Selected := lItemFound;
if (Integer(lItemFound.Data) >= itAllFolders) then
lItemFound.ImageIndex := 2;
lItem := lItemFound.Parent;
while (lItem <> nil) do
begin
if not (lItem.Expanded) then
lItem.Expanded := True;
lItem.ImageIndex := 2;
lItem := lItem.Parent;
end;
FoldersSelectionChange;
end
else
trvFolders.Selected := trvFolders.Items[0];
FListView.FolderId := Integer(trvFolders.Selected.Data);
trvFolders.Items.EndUpdate;
UpdateStatusBar;
end; {procedure, SelectFolder}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.UpdateStatusBar }
procedure TrbReportExplorerForm.UpdateStatusBar;
var
lsMessage: string;
lTable: TTable;
begin
if (trvFolders.Focused) then
lsMessage := ppLoadStr(522) {<count> item(s)}
else
lsMessage := ppLoadStr(521); {<count> item(s) selected}
lsMessage := ppSetMessageParameters(lsMessage);
lsMessage := Format(lsMessage, [IntToStr(FListView.SelectionCount)]);
sbrExplorer.Panels[0].Text := lsMessage;
if (FListView.AllFolders) then
sbrExplorer.Panels[1].Text := ''
else if (FListView.SelectionSize = 0) then
sbrExplorer.Panels[1].Text := '0 ' + ppLoadStr(531) {bytes}
else
sbrExplorer.Panels[1].Text := IntToStr(FListView.SelectionSize div 1000) + ppLOadStr(565); {KB}
(** teste mostrando hint **)
mmHint.Lines.Clear;
if Assigned(FListView.Selected) then
begin
lTable := TTable(TppDBPipeline(FReportExplorer.ItemPipeline).DataSource.DataSet);
lTable.Locate('FolderId;Name',
VarArrayOf([FListView.FolderId, FListView.ItemName]), []);
mmHint.Lines.Append(lTable.FieldByName('Hint').AsString);
sItem_ID := lTable.FieldByName('ItemId').AsString;
if lTable.FieldByName('system').AsString = 'True' then
begin
spbDelete.Visible := False;
ppmReportsDesign.Caption := 'Copy...';
end
else
begin
spbDelete.Visible := True;
ppmReportsDesign.Caption := 'Design';
end;
end;
end; {procedure, UpdateStatusBar}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.FoldersSelectionChange }
procedure TrbReportExplorerForm.FoldersSelectionChange;
var
lsFolderName: string;
lItem: TTreeNode;
lsMessage: string;
begin
lItem := trvFolders.Selected;
if (lItem = nil) then Exit;
{get folder chain description}
lsFolderName := '';
while (lItem <> nil) and (Integer(lItem.Data) > itAllFolders) do
begin
if (lsFolderName <> '') then
lsFolderName := lItem.Text + '\' + lsFolderName
else
lsFolderName := lItem.Text;
lItem := lItem.Parent;
end;
if (lItem <> nil) and (lsFolderName = '') then
lsFolderName := lItem.Text;
{Contents of '<name>'}
lsMessage := ppLoadStr(544);
lsMessage := ppSetMessageParameters(lsMessage);
lsMessage := Format(lsMessage, [lsFolderName]);
pnlReportTitle.Caption := ' ' + lsMessage;
EnableFolderOptions;
end; {procedure, FoldersSelectionChange}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.ListSelectionChangeEvent }
procedure TrbReportExplorerForm.ListSelectionChangeEvent(Sender: TObject);
begin
UpdateStatusBar;
EnableItemOptions;
end; {procedure, ListSelectionChangeEvent}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.EnableFolderOptions }
procedure TrbReportExplorerForm.EnableFolderOptions;
var
liFolderId: Integer;
lItem: TTreeNode;
begin
lItem := trvFolders.Selected;
if (lItem = nil) then Exit;
liFolderId := Integer(lItem.Data);
{enable options}
if (liFolderId = itRecycleBin) then
begin
spbUpOneLevel.Enabled := False;
mniFileOpen.Enabled := False;
ppmFoldersOpen.Enabled := False;
mniFileNew.Enabled := False;
spbDelete.Enabled := False;
mniFileDelete.Enabled := False;
ppmFoldersDelete.Enabled := False;
mniFileRename.Enabled := False;
ppmFoldersRename.Enabled := False;
end
else if (liFolderId = itAllFolders) then
begin
spbUpOneLevel.Enabled := False;
mniFileOpen.Enabled := False;
ppmFoldersOpen.Enabled := False;
spbDelete.Enabled := False;
mniFileDelete.Enabled := False;
ppmFoldersDelete.Enabled := False;
mniFileRename.Enabled := False;
ppmFoldersRename.Enabled := False;
end
else
begin
spbUpOneLevel.Enabled := True;
mniFileOpen.Enabled := not (trvFolders.Selected.ImageIndex = 2);
ppmFoldersOpen.Enabled := not (trvFolders.Selected.ImageIndex = 2);
spbDelete.Enabled := True;
mniFileDelete.Enabled := True;
ppmFoldersDelete.Enabled := True;
mniFileRename.Enabled := True;
ppmFoldersRename.Enabled := True;
end;
if trvFolders.Focused then
begin
spbDelete.Enabled := spbDelete.Enabled and (foAllowDelete in FReportExplorer.FolderOptions);
mniFileDelete.Enabled := mniFileDelete.Enabled and (foAllowDelete in FReportExplorer.FolderOptions);
ppmFoldersDelete.Enabled := ppmFoldersDelete.Enabled and (foAllowDelete in FReportExplorer.FolderOptions);
mniFileRename.Enabled := mniFileRename.Enabled and (foAllowRename in FReportExplorer.FolderOptions);
ppmFoldersRename.Enabled := ppmFoldersRename.Enabled and (foAllowRename in FReportExplorer.FolderOptions);
end;
end; {procedure, EnableFolderOptions}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.EnableItemOptions }
procedure TrbReportExplorerForm.EnableItemOptions;
var
lbEnabled: Boolean;
liFolderId: Integer;
lItem: TTreeNode;
lbNewFolder: Boolean;
lbNewReport: Boolean;
begin
lItem := trvFolders.Selected;
if (lItem = nil) then Exit;
liFolderId := Integer(lItem.Data);
if (liFolderId = itRecycleBin) then
begin
lbEnabled := False;
lbNewFolder := False;
lbNewReport := False;
end
else
begin
lbEnabled := (FListView.Selected <> nil) and (FListView.ItemType <> itFolder);
lbNewFolder := (foAllowNew in FReportExplorer.FolderOptions);
lbNewReport := (ioAllowNew in FReportExplorer.ItemOptions);
end;
{assign new report, new folder}
spbNewFolder.Enabled := lbNewFolder;
spbNewReport.Enabled := lbNewReport;
mniFileNew.Enabled := True;
mniFileNewFolder.Enabled := lbNewFolder;
mniFileNewReport.Enabled := lbNewReport;
ppmFoldersNewFolder.Enabled := lbNewFolder;
ppmFoldersNewReport.Enabled := lbNewReport;
ppmReportsNewFolder.Enabled := lbNewFolder;
ppmReportsNewReport.Enabled := lbNewReport;
{assign properties which pertain to reports only}
spbPrint.Enabled := lbEnabled;
spbPrintPreview.Enabled := lbEnabled;
mniFileDesign.Enabled := lbEnabled and (ioAllowDesign in FReportExplorer.ItemOptions);
mniFilePrint.Enabled := lbEnabled;
mniFilePrintPreview.Enabled := lbEnabled;
ppmReportsOpen.Enabled := lbEnabled;
ppmReportsDesign.Enabled := lbEnabled and (ioAllowDesign in FReportExplorer.ItemOptions);
ppmReportsPrint.Enabled := lbEnabled;
ppmReportsPrintPreview.Enabled := lbEnabled;
ppmReportsDesign.Enabled := (TTable(TppDBPipeline(FReportExplorer.ItemPipeline).DataSource.DataSet).FieldByName('edit').AsString = 'True');
{assign properties which pertain to both reports and folders}
if FListView.Focused then
begin
mniFileOpen.Enabled := lbEnabled;
if (FListView.FoldersInSelection) then
begin
spbDelete.Enabled := (foAllowDelete in FReportExplorer.FolderOptions);
mniFileDelete.Enabled := (foAllowDelete in FReportExplorer.FolderOptions);
ppmReportsDelete.Enabled := (foAllowDelete in FReportExplorer.FolderOptions);
end
else
begin
spbDelete.Enabled := lbEnabled and (ioAllowDelete in FReportExplorer.ItemOptions);
mniFileDelete.Enabled := lbEnabled and (ioAllowDelete in FReportExplorer.ItemOptions);
ppmReportsDelete.Enabled := lbEnabled and (ioAllowDelete in FReportExplorer.ItemOptions);
end;
if (FListView.ItemType = itFolder) then
begin
mniFileRename.Enabled := (foAllowRename in FReportExplorer.FolderOptions);
ppmReportsRename.Enabled := (foAllowRename in FReportExplorer.FolderOptions);
end
else
begin
mniFileRename.Enabled := lbEnabled and (ioAllowRename in FReportExplorer.ItemOptions);
ppmReportsRename.Enabled := lbEnabled and (ioAllowRename in FReportExplorer.ItemOptions);
end;
end;
end; {procedure, EnableItemOptions}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.UpdateTreeView }
procedure TrbReportExplorerForm.UpdateTreeView;
var
liIndex: Integer;
lItems: TTreeNodes;
lItem: TTreeNode;
lFolders: TStringList;
lFolderNodes: TStringList;
lFolderInfo: TppFolderInfo;
liParentIndex: Integer;
lParentNode: TTreeNode;
begin
lFolders := TStringList.Create;
lFolderNodes := TStringList.Create;
FReportExplorer.GetFolders(lFolders);
lItems := trvFolders.Items;
lItems.BeginUpdate;
lItems.Clear;
{All Folders}
FAllFoldersNode := trvFolders.Items.AddObject(nil, ppLoadStr(524), TObject(itAllFolders));
FAllFoldersNode.ImageIndex := 0;
FAllFoldersNode.SelectedIndex := 2;
lFolderNodes.AddObject(IntToStr(itAllFolders), FAllFoldersNode);
{Recycle Bin}
if (ioAllowDelete in FReportExplorer.ItemOptions) then
begin
FRecycleBinNode := trvFolders.Items.AddObject(nil, ppLoadStr(578), TObject(itRecycleBin));
lFolderNodes.AddObject(IntToStr(itRecycleBin), FRecycleBinNode);
end
else
FRecycleBinNode := nil;
while (lFolders.Count > 0) do
begin
liIndex := 0;
lFolderInfo := TppFolderInfo(lFolders.Objects[liIndex]);
liParentIndex := lFolderNodes.IndexOf(IntToStr(lFolderInfo.ParentId));
while (liParentIndex = -1) and (liIndex < lFolders.Count - 1) do
begin
Inc(liIndex);
lFolderInfo := TppFolderInfo(lFolders.Objects[liIndex]);
liParentIndex := lFolderNodes.IndexOf(IntToStr(lFolderInfo.ParentId));
end;
if (liParentIndex <> -1) then
lParentNode := TTreeNode(lFolderNodes.Objects[liParentIndex])
else
lParentNode := FAllFoldersNode;
lItem := lItems.AddChild(lParentNode, lFolderInfo.Name);
lItem.Data := TObject(lFolderInfo.FolderId);
lItem.ImageIndex := 0;
lItem.SelectedIndex := 2;
lFolderNodes.AddObject(IntToStr(lFolderInfo.FolderId), lItem);
lFolderInfo.Free;
lFolders.Delete(liIndex);
end;
trvFolders.AlphaSort;
lItems.EndUpdate;
UpdateRecycleBin;
lFolders.Free;
lFolderNodes.Free;
FAllFoldersNode.Expanded := True;
end; {procedure, UpdateTreeView}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.UpdateRecycleBin }
procedure TrbReportExplorerForm.UpdateRecycleBin;
var
lItemNames: TStringList;
liIndex: Integer;
begin
if (FRecycleBinNode = nil) then Exit;
trvFolders.Items.BeginUpdate;
lItemNames := TStringList.Create;
FReportExplorer.GetItems(itRecycleBin, itAllFolders, lItemNames);
if (lItemNames.Count > 0) then
begin
FRecycleBinNode.ImageIndex := 1;
FRecycleBinNode.SelectedIndex := 1;
end
else
begin
FRecycleBinNode.ImageIndex := 3;
FRecycleBinNode.SelectedIndex := 3;
end;
for liIndex := 0 to lItemNames.Count - 1 do
lItemNames.Objects[liIndex].Free;
lItemNames.Free;
trvFolders.Items.EndUpdate;
end; {procedure, UpdateRecycleBin}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.EmptyRecycleBinClick }
procedure TrbReportExplorerForm.EmptyRecycleBinClick(Sender: TObject);
begin
FListView.EmptyRecycleBin;
UpdateTreeView;
end; {procedure, EmptyRecycleBinClick}
{------------------------------------------------------------------------------}
{ TppReportExplorerForm.ppmFoldersPopup }
procedure TrbReportExplorerForm.ppmFoldersPopup(Sender: TObject);
var
lNode: TTreeNode;
liFolderId: Integer;
lMenuItem: TMenuItem;
begin
lNode := trvFolders.Selected;
if (lNode = nil) then Exit;
liFolderId := Integer(lNode.Data);
if (liFolderId <> itRecycleBin) and (ppmFolders.Items[2].Tag = 595) then
ppmFolders.Items[2].Free
else if (liFolderId = itRecycleBin) then
begin
if (ppmFolders.Items[2].Tag <> 595) and (foAllowDelete in FReportExplorer.FolderOptions) then
begin
lMenuItem := TMenuItem.Create(Self);
lMenuItem.Tag := 595;
lMenuItem.Caption := ppLoadStr(595); {Empty Recycle &Bin}
lMenuItem.OnClick := EmptyRecycleBinClick;
ppmFolders.Items.Insert(2, lMenuItem);
end;
ppmFolders.Items[2].Enabled := (FRecycleBinNode.ImageIndex = 1);
end;
end; {procedure, ppmFoldersPopup}
procedure TrbReportExplorerForm.CopyReport(sItemID: string);
var
sNewReport,
sIDNextItem: string;
begin
sNewReport := 'Copy of ' + FListView.ItemName;
sIDNextItem := IntToStr(DM.GetNextID(MR_REP_ITEM_ID));
try
with DM.quFreeSQL do
begin
if Active then Close;
SQL.Clear;
SQL.Add('INSERT INTO rep_Item (itemid, folderid,name,size,itemtype,modified,deleted,template,Hint,system)');
SQL.Add('SELECT '+sIDNextItem+',folderid,' + QuotedStr(sNewReport) + ',size,itemtype,modified,deleted,template,Hint,0');
SQL.Add('FROM rep_item WHERE ');
SQL.Add('itemid = ' + sItemID);
ExecSQL;
end;
TppDBPipeline(FReportExplorer.ItemPipeline).DataSource.DataSet.Close;
TppDBPipeline(FReportExplorer.ItemPipeline).DataSource.DataSet.Open;
Refresh;
finally
end;
end;
procedure TrbReportExplorerForm.ppmReportsEditHintClick(Sender: TObject);
begin
EditHintFch.Start(sItem_ID);
EditHintFch.ShowModal;
TppDBPipeline(FReportExplorer.ItemPipeline).DataSource.DataSet.Refresh;
Refresh;
end;
{******************************************************************************
*
** I N I T I A L I Z A T I O N / F I N A L I Z A T I O N
*
{******************************************************************************}
initialization
ppRegisterForm(TppCustomReportExplorer, TrbReportExplorerForm);
finalization
ppUnRegisterForm(TppCustomReportExplorer);
end.
|
//Вводится последовательность из N элементов. Подсчитать количества положительных, отрицательных и нулевых элементов последовательности.
//Вывести исходную последовательность и результаты ее обработки
program lab_3_15;
var A: array of real;
n, i, k1, k2, k3: integer;
x: real;
begin
write('введите кол-во элементов: ');
readln(n);
setlength(A, n);
i:=0;
k1:=0;
k2:=0;
k3:=0;
while i < n do
begin
write('введите ', i+1, ' член последовательности: ');
readln(x);
A[i]:=x;
if x>0 then
k1:= k1+1;
if x<0 then
k3:= k3+1;
if x=0 then
k2:= k2+1;
i:=i+1;
end;
writeln(A);
writeln('положительных: ', k1);
writeln('раных 0: ', k2);
writeln('отрицательных: ', k3);
end. |
unit ULinkedListClass;
// defines a simple linked-list class using pointers
//for completion by students
interface
type
PLList=^TListNode; // a pointer to a node
TListNode= record // node definition:
data:string; // to hold the name
namescore:integer; //to hold the namescore
next:PLList; // to point to the next node
end;
TLList=class
private
Flength:integer;
FStart:PLList;
public
constructor Create;
destructor Destroy;override;
procedure Insert(s:String); //insert s into alphabetical order
function Delete(s:string):boolean; //remove s if it exists, return false if not found
function GetItem(n:integer):integer; //return nth item in list
function Empty:boolean;
property Start:PLList read FStart write FStart;
property Length:integer read FLength write FLength;
end;
implementation
{ TLList }
constructor TLList.Create;
begin
inherited;
Start:=nil;
FLength:=0;
end;
function getNScore(a:string):integer;
var
i,j:integer;
begin
j:=0;
for i := 1 to length(a) do
j:=j+ord(a[i])-64;
getNScore:=j;
end;
procedure TLList.Insert(s: String);
//insert s into list, maintaining alphabetical order
var current,newnode:PLlist;
begin
new(newnode); // create new node
newnode^.data:=s; // populate with string s
newnode^.namescore:=getNScore(s);
newnode^.next:=nil;
if FStart=nil then // special case: List is empty
FStart:=newnode //fill this in yourself
else
begin
if newnode^.data < FStart^.data then //special case: new node becomes start of list
begin
newnode^.next:=Fstart; //fill this in yourself
FStart:=newnode;
end
else //general case: insert new node in correct place
begin
current:=FStart; // make copy of start pointer
while (current^.next<> nil)
and (current^.next^.data<s) do // traverse until correct node is reached
current:=current^.next; //follow pointer to next node
newnode^.next:=current^.next; //set newnode's pointer to point to node after current
current^.next:=newnode;//change current's pointer to point to the new node
end;
end;
inc(FLength);
end;
function TLList.Delete(s: string): boolean;
//step through the list and remove the first item matching s, if one exists
//return false if no item removed, else return true
var
Current,scrap:PLList;
begin
if FStart=nil then result:=false
else
if FStart^.data=s then //special case: first item is to be removed
begin
scrap:=FStart;
FStart:=FStart^.next; //fill this in yourself
dispose(scrap);
dec(Flength);
result:=true;
end
else //general case
begin
Current:=FStart;
while (Current^.next<>nil) //traverse until end of list or match found
and (Current^.next^.data<>s) do
Current:=Current^.next;
if Current^.next=nil then result:=false //string not found
else //string found
begin
scrap:=Current^.next;
Current^.next:=Current^.next^.next;
dispose(scrap);
dec(FLength);
result:=true;
end;
end;
end;
destructor TLList.Destroy;
//destroy List by traversing list and releasing all nodes
//post condition: Startt=nil
var
scrap:PLList;
begin
while FStart<>nil do //loop until nil pointer is reached
begin
scrap:=FStart; //scrap now points to front node
FStart:=FStart^.next; //Start now points to next node
dispose(scrap); //former front node now released
end;
end;
function TLList.Empty: boolean;
//returns true if List is empty else false
begin
if FStart=nil then Empty:=true
else Empty:=false;
end;
function TLList.GetItem(n: integer): integer;
var
current:PLList;
nodenum:integer;
begin
if (FStart=nil) or (n>FLength) or (n<1) then result:=0 //deal with impossible requests
else
if n=1 then result:=FStart^.namescore //special case:first node required
else
begin
current:=Fstart; //general case
for nodenum:=1 to n-1 do //fill this in yourself
current:=current^.next; //start at the beginning
result:=current^.namescore; //follow the pointers to the nth node
end;
end;
end.
|
namespace com.example.android.accelerometerplay;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*}
interface
uses
java.util,
android.os,
android.app,
android.util,
android.content,
android.view,
android.hardware;
{*
* This is an example of using the accelerometer to integrate the device's
* acceleration to a position using the Verlet method. This is illustrated with
* a very simple particle system comprised of a few iron balls freely moving on
* an inclined wooden table. The inclination of the virtual table is controlled
* by the device's accelerometer.
*
* see SensorManager, SensorEvent and Sensor
*}
type
AccelerometerPlayActivity = public class(Activity)
private
var mSimulationView: SimulationView;
var mSensorManager: SensorManager;
var mPowerManager: PowerManager;
var mDisplay: Display;
var mWakeLock: PowerManager.WakeLock;
public
method onCreate(savedInstanceState: Bundle); override;
method onResume; override;
method onPause; override;
property SensorMgr: SensorManager read mSensorManager;
property DefaultDisplay: Display read mDisplay;
end;
implementation
method AccelerometerPlayActivity.onCreate(savedInstanceState: Bundle);
begin
inherited;
{
//Hide the regular activity title
RequestWindowFeature(Window.FEATURE_NO_TITLE);
//Hide the OS status bar
Window.SetFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
// Get an instance of the SensorManager
mSensorManager := SensorManager(SystemService[SENSOR_SERVICE]);
// Get an instance of the PowerManager
mPowerManager := PowerManager(SystemService[POWER_SERVICE]);
//Get the display object
mDisplay := WindowManager.DefaultDisplay;
// Create a bright wake lock
mWakeLock := mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, &Class.Name);
// instantiate our simulation view and set it as the activity's content
mSimulationView := new SimulationView(Self);
//Set activity content to be the custom-drawn view
ContentView := mSimulationView;
end;
method AccelerometerPlayActivity.onResume;
begin
inherited;
{
* when the activity is resumed, we acquire a wake-lock so that the
* screen stays on, since the user will likely not be fiddling with the
* screen or buttons.
}
mWakeLock.acquire;
// Start the simulation
mSimulationView.StartSimulation
end;
method AccelerometerPlayActivity.onPause;
begin
inherited;
{
* When the activity is paused, we make sure to stop the simulation,
* release our sensor resources and wake locks
}
// Stop the simulation
mSimulationView.StopSimulation;
// and release our wake-lock
mWakeLock.release
end;
end. |
Unit FillterForm;
Interface
Uses
Windows, Messages, SysUtils, Variants,
Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls,
Generics.Collections, RequestFilter, ExtCtrls,
ComCtrls
{$IFDEF FPC}
,ColorBox
{$ENDIF}
;
Type
EFilterComboboxType = (
fctType,
fctColumn,
fctOperator,
fctValue,
fctAction,
fctMax
);
TFilterFrm = Class (TForm)
UpperPanel: TPanel;
FilterTypeComboBox: TComboBox;
FilterColumnComboBox: TComboBox;
FilterOperatorComboBox: TComboBox;
NegateCheckBox: TCheckBox;
FilterValueComboBox: TComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
HighlightColorColorBox: TColorBox;
FilterActionComboBox: TComboBox;
Label5: TLabel;
Label4: TLabel;
LowerPanel: TPanel;
CloseButton: TButton;
OkButton: TButton;
FilterListView: TListView;
AddButton: TButton;
DeleteButton: TButton;
EnabledCheckBox: TCheckBox;
NextFilterComboBox: TComboBox;
UpButton: TButton;
DownButton: TButton;
Label6: TLabel;
NameEdit: TEdit;
ApplyButton: TButton;
EphemeralCheckBox: TCheckBox;
Procedure FormCreate(Sender: TObject);
procedure FilterTypeComboBoxChange(Sender: TObject);
procedure FilterColumnComboBoxChange(Sender: TObject);
procedure FilterActionComboBoxChange(Sender: TObject);
procedure CloseButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure FilterListViewData(Sender: TObject; Item: TListItem);
procedure DeleteButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure FilterListViewAdvancedCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage;
var DefaultDraw: Boolean);
procedure FilterListViewDblClick(Sender: TObject);
procedure FilterListViewDeletion(Sender: TObject; Item: TListItem);
procedure FilterListViewItemChecked(Sender: TObject; Item: TListItem);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure UpDownButtonClick(Sender: TObject);
procedure FilterListViewSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
Private
FFilterList : TObjectList<TRequestFilter>;
FCBs : Array [0..Ord(fctMax)-1] of TComboBox;
FCancelled : Boolean;
Procedure EnableCombobox(AType:EFilterComboboxType; AEnable:Boolean);
Procedure ShowNextFilters;
Public
Constructor Create(AOwner:TApplication; AFilterList:TObjectList<TRequestFilter>); Reintroduce;
Property FilterList : TObjectList<TRequestFilter> Read FFilterList;
Property Cancelled : Boolean Read FCancelled;
end;
Implementation
{$R *.DFM}
Uses
UITypes,
IniFiles,
IRPMonDll, IRPMonRequest, IRPRequest, FastIoRequest, Utils,
FileObjectNameXxxRequest, XXXDetectedRequests;
Constructor TFilterFrm.Create(AOwner:TApplication; AFilterList:TObjectList<TRequestFilter>);
Var
I : Integer;
n : WideString;
names : TStringList;
rf : TRequestFilter;
tmp : TRequestFilter;
begin
names := TStringList.Create;
FFilterList := TObjectList<TRequestFilter>.Create;
For rf In AFilterList Do
begin
n := '';
FFilterList.Add(rf.Copy);
If Assigned(rf.NextFilter) Then
n := rf.NextFilter.Name;
names.Add(n);
end;
For I := 0 To names.Count - 1 Do
begin
n := names[I];
rf := FFilterList[I];
If rf.Action = ffaPassToFilter Then
begin
tmp := TRequestFilter.GetByName(n, FFilterList);
If Assigned(tmp) Then
rf.AddNext(tmp);
end;
end;
names.Free;
Inherited Create(Application);
end;
Procedure TFilterFrm.ShowNextFilters;
Var
L : TListItem;
rf : TRequestFilter;
selectedIndex : Integer;
currentRF : TRequestFilter;
selectedRF : TRequestFilter;
begin
selectedIndex := -1;
selectedRF := Nil;
If NextFilterComboBox.ItemIndex <> -1 Then
selectedRF := NextFilterComboBox.Items.Objects[NextFilterComboBox.ItemIndex] As TRequestFilter;
NextFilterComboBox.Clear;
If NextFilterComboBox.Visible Then
begin
currentRF := Nil;
L := FilterListView.Selected;
If Assigned(L) Then
currentRF := FFilterList[L.Index];
For rf In FFilterList Do
begin
If (Assigned(currentRF)) And (rf.Name = currentRF.Name) Then
Continue;
If (rf.HasPredecessor) And (Assigned(currentRF)) And (currentRF.NextFilter = rf) Then
Continue;
If (Assigned(selectedRF)) And (selectedRF.Name = rf.Name) Then
selectedIndex := NextFilterComboBox.Items.Count;
NextFilterComboBox.Items.AddObject(rf.Name, rf);
end;
NextFilterComboBox.ItemIndex := selectedIndex;
end;
end;
Procedure TFilterFrm.UpDownButtonClick(Sender: TObject);
Var
L : TListItem;
index2 : Integer;
begin
L := FilterListView.Selected;
If Assigned(L) Then
begin
index2 := -1;
If Sender = UpButton Then
index2 := L.Index - 1
Else If Sender = DownButton Then
index2 := L.Index + 1;
FFilterList.Exchange(L.Index, index2);
FilterListViewData(FilterListView, L);
FilterListViewData(FilterListView, FilterListView.Items[index2]);
FilterListView.Selected := FilterListView.Items[index2];
end;
end;
Procedure TFilterFrm.FilterActionComboBoxChange(Sender: TObject);
Var
fa : EFilterAction;
c : TComboBox;
begin
c := (Sender As TComboBox);
fa := EFilterAction(c.ItemIndex);
NextFilterComboBox.Visible := (fa = ffaPassToFilter);
NextFilterComboBox.Enabled := (fa = ffaPassToFilter);
ShowNextFilters;
end;
Procedure TFilterFrm.FilterColumnComboBoxChange(Sender: TObject);
Var
I : Integer;
rt : ERequestType;
ct : ERequestListModelColumnType;
c : TComboBox;
tmp : TRequestFilter;
ss : TList<UInt64>;
st : TList<WideString>;
bm : Boolean;
ops : RequestFilterOperatorSet;
op : ERequestFilterOperator;
begin
c := (Sender As TComboBox);
EnableComboBox(fctOperator, c.ItemIndex <> -1);
EnableComboBox(fctValue, c.ItemIndex <> -1);
If FilterOperatorComboBox.Enabled Then
begin
rt := ERequestType(FilterTypeComboBox.Items.Objects[FilterTypeComboBox.ItemIndex]);
ct := ERequestListModelColumnType(FilterColumnComboBox.Items.Objects[FilterColumnComboBox.ItemIndex]);
FilterValueComboBox.Clear;
tmp := TRequestFilter.NewInstance(rt);
If Not tmp.SetCondition(ct, rfoAlwaysTrue, 0) Then
tmp.SetCondition(ct, rfoAlwaysTrue, '');
ss := TList<UInt64>.Create;
st := TList<WideString>.Create;
If tmp.GetPossibleValues(ss, st, bm) Then
begin
FilterValueComboBox.Style := csDropDown;
For I := 0 To ss.Count - 1 Do
FilterValueComboBox.AddItem(st[I], Pointer(ss[I]));
end
Else FilterValueComboBox.Style := csSimple;
FilterOperatorComboBox.Clear;
ops := tmp.SupportedOperators;
For op In ops Do
FilterOperatorComboBox.AddItem(RequestFilterOperatorNames[Ord(op)], Pointer(Ord(op)));
st.Free;
ss.Free;
tmp.Free;
end;
end;
Procedure TFilterFrm.FilterListViewAdvancedCustomDrawItem(
Sender: TCustomListView; Item: TListItem; State: TCustomDrawState;
Stage: TCustomDrawStage; var DefaultDraw: Boolean);
Var
f : TRequestFilter;
begin
With FilterListView.Canvas Do
begin
f := FFilterList[Item.Index];
If Item.Selected Then
begin
Brush.Color := clHighLight;
Font.Color := clHighLightText;
Font.Style := [fsBold];
end
Else begin
Font.Style := [];
If Not f.HasPredecessor Then
Font.Style := [fsBold];
Brush.Color := f.HighlightColor;
If ColorLuminanceHeur(f.HighlightColor) >= 1490 Then
Font.Color := ClBlack
Else Font.Color := ClWhite;
end;
If f.Ephemeral Then
Font.Style := Font.Style + [fsItalic];
end;
DefaultDraw := True;
end;
Procedure TFilterFrm.FilterListViewData(Sender: TObject; Item: TListItem);
Var
f : TRequestFilter;
nextFilterName : WideString;
begin
With Item Do
begin
f := FFilterList[Index];
Caption := f.Name;
SubItems.Clear;
SubItems.Add(FilterTypeComboBox.Items[Ord(f.RequestType)]);
SubItems.Add(f.ColumnName);
SubItems.Add(RequestFilterOperatorNames[Ord(f.Op)]);
If f.Negate Then
SubItems.Add('Yes')
Else SubItems.Add('No');
SubItems.Add(f.StringValue);
SubItems.Add(FilterActionComboBox.Items[Ord(f.Action)]);
nextFilterName := '<not applicable>';
If Assigned(f.NextFilter) Then
nextFilterName := f.NextFilter.Name;
SubItems.Add(nextFilterName);
Checked := f.Enabled;
end;
end;
Procedure TFilterFrm.FilterListViewDblClick(Sender: TObject);
Var
I : Integer;
f : TRequestFilter;
L : TListItem;
begin
L := FilterListView.Selected;
If Assigned(L) Then
begin
f := FFilterList[L.Index];
NameEdit.Text := f.Name;
FilterTypeComboBox.ItemIndex := Ord(f.RequestType);
FilterTypeComboBoxChange(FilterTypeComboBox);
FilterColumnComboBox.ItemIndex := FilterColumnComboBox.Items.IndexOf(f.ColumnName);
FilterColumnComboBoxChange(FilterColumnComboBox);
For I := 0 To FilterOperatorComboBox.Items.Count - 1 Do
begin
If ERequestFilterOperator(NativeUInt(FilterOperatorComboBox.Items.Objects[i])) = f.Op Then
begin
FilterOperatorComboBox.ItemIndex := I;
Break;
end;
end;
If FilterValueComboBox.Style <> csSimple Then
begin
For I := 0 To FilterValueComboBox.Items.Count - 1 Do
begin
If UInt64(FilterValueComboBox.Items.Objects[I]) = f.IntValue Then
begin
FilterValueComboBox.ItemIndex := I;
Break;
end;
end;
end
Else FilterValueComboBox.Text := f.StringValue;
FilterActionComboBox.ItemIndex := Ord(f.Action);
FilterActionComboBoxChange(FilterActionComboBox);
HighlightColorColorBox.Selected := f.HighlightColor;
NegateCheckBox.Checked := f.Negate;
EnabledCheckBox.Checked := f.Enabled;
EphemeralCheckBox.Checked := f.Ephemeral;
end;
end;
Procedure TFilterFrm.FilterListViewDeletion(Sender: TObject; Item: TListItem);
begin
FFilterList.Delete(Item.Index);
end;
Procedure TFilterFrm.FilterListViewItemChecked(Sender: TObject;
Item: TListItem);
Var
I : Integer;
f : TRequestFilter;
begin
f := FFilterList[Item.Index];
f.Enabled := Item.Checked;
For I := 0 To FilterListVIew.Items.Count - 1 Do
begin
If I = Item.Index Then
Continue;
FilterListView.Items[I].Checked := FFilterList[I].Enabled;
end;
end;
Procedure TFilterFrm.FilterListViewSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
DeleteButton.Enabled := (Assigned(Item)) And (Selected);
ApplyButton.Enabled := (Assigned(Item)) And (Selected);
UpButton.Enabled := ((Assigned(Item)) And (Selected) And (Item.Index > 0));
DownButton.Enabled := ((Assigned(Item)) And (Selected) And (Item.Index < FilterListView.Items.Count - 1));
end;
Procedure TFilterFrm.FilterTypeComboBoxChange(Sender: TObject);
Var
c : TComboBox;
dr : TDriverRequest;
rt : ERequestType;
ct : ERequestListModelColumnType;
v : WideString;
begin
c := (Sender As TComboBox);
EnableComboBox(fctColumn, c.ItemIndex <> -1);
If FilterColumnComboBox.Enabled Then
begin
rt := ERequestType(c.Items.Objects[c.ItemIndex]);
dr := TDriverRequest.CreatePrototype(rt);
FilterColumnComboBox.Clear;
If Assigned(dr) Then
begin
For ct := Low(ERequestListModelColumnType) To High(ERequestListModelColumnType) Do
begin
If dr.GetColumnValue(ct, v) Then
FilterColumnComboBox.AddItem(dr.GetColumnName(ct), Pointer(Ord(ct)));
end;
dr.Free;
end;
end;
end;
Procedure TFilterFrm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FilterListView.OnDeletion := Nil;
end;
Procedure TFilterFrm.FormCreate(Sender: TObject);
Var
L : TListItem;
bm : Boolean;
index : Integer;
ss : TList<UInt64>;
rf : TRequestFilter;
ts : TList<WideString>;
tmp : TRequestFilter;
tmpEnabled : Boolean;
I : ERequestType;
begin
FCBs[Ord(fctType)] := FilterTypeComboBox;
FCBs[Ord(fctColumn)] := FilterColumnComboBox;
FCBs[Ord(fctOperator)] := FilterOperatorComboBox;
FCBs[Ord(fctValue)] := FilterValueComboBox;
FCBs[Ord(fctAction)] := FilterActionComboBox;
EnableComboBox(fctColumn, False);
EnableComboBox(fctOperator, False);
EnableComboBox(fctValue, False);
ss := TList<UInt64>.Create;
ts := TList<WideString>.Create;
tmp := TRequestFilter.NewInstance(ertUndefined);
tmp.SetCondition(rlmctRequestType, rfoAlwaysTrue, 0);
tmp.GetPossibleValues(ss, ts, bm);
tmp.Free;
For I := Low(ERequestType) To High(ERequestType) Do
begin
tmp := TRequestFilter.NewInstance(I);
If Assigned(tmp) Then
begin
index := ss.IndexOf(Ord(I));
FilterTypeComboBox.AddItem(ts[Index], Pointer(ss[Index]));
tmp.Free;
end;
end;
ts.Free;
ss.Free;
FCancelled := True;
For rf In FFilterList Do
begin
tmpEnabled := rf.Enabled;
L := FilterListView.Items.Add;
FilterListViewData(FilterListView, L);
rf.Enabled := tmpEnabled;
L.Checked := rf.Enabled;
end;
FilterListViewSelectItem(FilterListView, Nil, False);
end;
Procedure TFilterFrm.FormDestroy(Sender: TObject);
begin
FFilterList.Free;
end;
Procedure TFilterFrm.OkButtonClick(Sender: TObject);
begin
FCancelled := False;
FFilterList.OwnsObjects := False;
Close;
end;
Procedure TFilterFrm.AddButtonClick(Sender: TObject);
Var
I : Integer;
L : TListItem;
modifyFilter : Boolean;
rt : ERequestType;
ct : ERequestListModelColumnType;
op : ERequestFilterOperator;
f : TRequestFilter;
existingFilter : TRequestFilter;
v : WideString;
fa : EFilterAction;
hc : TColor;
err : Cardinal;
passTarget : TRequestFilter;
newName : WideString;
begin
f := Nil;
L := Nil;
modifyFilter := (Sender = ApplyButton);
If modifyFilter Then
begin
L := FilterListView.Selected;
If Assigned(L) Then
f := FFilterList[L.Index];
end;
passTarget := Nil;
Try
If FilterTypeComboBox.ItemIndex = -1 Then
begin
ErrorMessage('Filter type is not selected');
Exit;
end;
If FilterColumnComboBox.ItemIndex = -1 Then
begin
ErrorMessage('Filtered column not selected');
Exit;
end;
If FilterOperatorComboBox.ItemIndex = -1 Then
begin
ErrorMessage('Filter condition operator not selected');
Exit;
end;
rt := ERequestType(FilterTypeComboBox.Items.Objects[FilterTypeComboBox.ItemIndex]);
ct := ERequestListModelColumnType(FilterColumnComboBox.Items.Objects[FilterColumnComboBox.ItemIndex]);
op := ERequestFilterOperator(FilterOperatorComboBox.Items.Objects[FilterOperatorComboBox.ItemIndex]);
fa := EFilterAction(FilterActionComboBox.ItemIndex);
If (fa = ffaPassToFilter) Then
begin
If (NextFilterComboBox.ItemIndex = -1) Then
begin
ErrorMessage('Target of the pass-to-filter action not selected');
Exit;
end;
passTarget := NextFilterComboBox.Items.Objects[NextFilterComboBox.ItemIndex] As TRequestFilter;
end;
hc := HighlightColorColorBox.Selected;
v := FilterValueComboBox.Text;
For I := 0 To FilterValueComboBox.Items.Count - 1 Do
begin
If (v = FilterValueComboBox.Items[I]) Then
begin
v := IntToStr(UInt64(FilterValueComboBox.Items.Objects[I]));
Break;
end;
end;
newName := NameEdit.Text;
If newName <> '' Then
begin
existingFilter := TRequestFilter.GetByName(newName, FFilterList);
If (Assigned(existingFilter)) And
((Not modifyFilter) Or (existingFilter <> f)) Then
begin
ErrorMessage('The filter is already present in the list');
Exit;
end;
end;
If Not modifyFilter Then
begin
f := TRequestFilter.NewInstance(rt);
If Not Assigned(f) Then
Exit;
end;
f.Name := newName;
If (Not modifyFilter) Or (f.Name = '') Then
f.GenerateName(FFilterList);
If Not f.SetCondition(ct, op, v) Then
begin
ErrorMessage('Unable to set filter condition, bad value of the constant');
Exit;
end;
f.Negate := NegateCheckBox.Checked;
err := f.SetAction(fa, hc);
If err <> 0 Then
begin
ErrorMessage(IntToStr(err));
Exit;
end;
If fa = ffaPassToFilter Then
begin
err := f.AddNext(passTarget);
If err <> 0 Then
begin
ErrorMessage(IntToStr(err));
Exit;
end;
end;
If Not modifyFilter Then
begin
FFilterList.Add(f);
L := FilterListVIew.Items.Add;
end;
f.Enabled := EnabledCheckBox.Checked;
f.Ephemeral := EphemeralCheckBox.Checked;
FilterListViewData(FilterListView, L);
f := Nil;
Finally
If (Not modifyFilter) And (Assigned(f)) Then
f.Free;
end;
end;
Procedure TFilterFrm.CloseButtonClick(Sender: TObject);
begin
Close;
end;
Procedure TFilterFrm.DeleteButtonClick(Sender: TObject);
Var
L : TListItem;
begin
L := FilterListView.Selected;
If Assigned(L) Then
L.Delete;
end;
Procedure TFilterFrm.EnableCombobox(AType:EFilterComboboxType; AEnable:Boolean);
Var
c : TComboBox;
begin
c := FCBs[Ord(AType)];
c.Enabled := AEnable;
Case c.Enabled Of
False : c.Color := clBtnFace;
True : c.Color := clWindow;
end;
end;
End.
|
unit Demo.Eval;
{ Eval example.
Evaluate an expression. }
interface
uses
Demo,
Duktape;
type
TDemoEval = class(TDemo)
private
class function NativeEval(const ADuktape: TDuktape;
const AUserData: Pointer): TdtResult; cdecl; static;
class function NativeToString(const ADuktape: TDuktape;
const AUserData: Pointer): TdtResult; cdecl; static;
public
procedure Run; override;
end;
implementation
{ TDemoEval }
class function TDemoEval.NativeEval(const ADuktape: TDuktape;
const AUserData: Pointer): TdtResult;
begin
ADuktape.Eval;
Result := TdtResult.HasResult;
end;
class function TDemoEval.NativeToString(const ADuktape: TDuktape;
const AUserData: Pointer): TdtResult;
begin
ADuktape.ToString(-1);
Result := TdtResult.HasResult;
end;
procedure TDemoEval.Run;
const
EXPRESSION = 'Math.sqrt(2.0)';
var
Res: String;
begin
Duktape.PushString(EXPRESSION);
Duktape.SafeCall(NativeEval, nil, 1, 1);
Duktape.SafeCall(NativeToString, nil, 1, 1);
Res := String(Duktape.GetString(-1));
Log(EXPRESSION + ' = ' + Res);
Duktape.Pop;
end;
initialization
TDemo.Register('Eval(Math.sqrt(2.0))', TDemoEval);
end.
|
unit Current_Filter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxCheckBox, StdCtrls, cxButtons,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxControls,
cxGroupBox, cxSpinEdit, cxDropDownEdit, GlobalSpr,
IBase, PackageLoad, ZTypes, Dates, FIBDatabase, pFIBDatabase, DB,
FIBDataSet, pFIBDataSet, ZMessages, ZProc, cxLabel, Unit_NumericConsts,
ActnList, ExtCtrls, cxCalendar, uCommonSP;
type TzCurrentFilter = record
Is_Smeta:boolean;
Is_Department:boolean;
Is_Man:boolean;
Is_VidOpl:boolean;
Is_KodSetup:boolean;
Is_OperationsFilter:boolean;
Is_Prikaz:boolean;
Id_smeta:integer;
Kod_Smeta:integer;
Name_Smeta:String;
Id_department:integer;
Kod_department:string[10];
Name_Department:String;
Id_man:integer;
Tn:integer;
FIO:string;
Id_VidOpl:integer;
Kod_VidOpl:integer;
Name_VidOpl:string;
Kod_Setup1:integer;
Kod_Setup2:integer;
Prikaz:string[50];
ModalResult:TModalResult;
end;
type
TfzCurrentFilter = class(TForm)
BoxSmeta: TcxGroupBox;
EditSmeta: TcxButtonEdit;
YesBtn: TcxButton;
CancelBtn: TcxButton;
BoxKodSetup: TcxGroupBox;
MonthesList1: TcxComboBox;
YearSpinEdit1: TcxSpinEdit;
CheckBoxKodSetup: TcxCheckBox;
CheckBoxDepartment: TcxCheckBox;
BoxDepartment: TcxGroupBox;
EditDepartment: TcxButtonEdit;
CheckBoxSmeta: TcxCheckBox;
CheckBoxIdMan: TcxCheckBox;
BoxIdMan: TcxGroupBox;
EditMan: TcxButtonEdit;
CheckBoxVidOpl: TcxCheckBox;
BoxVidOpl: TcxGroupBox;
EditVidOpl: TcxButtonEdit;
LabelManData: TcxLabel;
LabelVidOplData: TcxLabel;
LabelDepartmentData: TcxLabel;
LabelSmetaData: TcxLabel;
ActionList: TActionList;
Action1: TAction;
MonthesList2: TcxComboBox;
YearSpinEdit2: TcxSpinEdit;
cxLabel1: TcxLabel;
CheckBoxOperationsFilter: TcxCheckBox;
Bevel: TBevel;
CheckBoxPrikaz: TcxCheckBox;
BoxPrikaz: TcxGroupBox;
EditPrikaz: TcxMaskEdit;
DepDateEdit: TcxDateEdit;
DepDateLable: TcxLabel;
procedure CheckBoxKodSetupClick(Sender: TObject);
procedure CheckBoxDepartmentClick(Sender: TObject);
procedure CheckBoxSmetaClick(Sender: TObject);
procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure CancelBtnClick(Sender: TObject);
procedure k(Sender: TObject);
procedure EditManPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure CheckBoxVidOplClick(Sender: TObject);
procedure EditManExit(Sender: TObject);
procedure EditVidOplExit(Sender: TObject);
procedure EditVidOplPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditDepartmentExit(Sender: TObject);
procedure EditSmetaExit(Sender: TObject);
procedure Action1Execute(Sender: TObject);
procedure CheckBoxOperationsFilterClick(Sender: TObject);
procedure EditPrikazKeyPress(Sender: TObject; var Key: Char);
procedure CheckBoxPrikazClick(Sender: TObject);
procedure BoxKodSetupExit(Sender: TObject);
private
PParameter:TzCurrentFilter;
PDb_Handle:TISC_DB_HANDLE;
public
constructor Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TzCurrentFilter);reintroduce;
property Parameter:TzCurrentFilter read PParameter;
end;
function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TzCurrentFilter):TzCurrentFilter;stdcall;
implementation
{$R *.dfm}
function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TzCurrentFilter):TzCurrentFilter;stdcall;
var Filter:TfzCurrentFilter;
Res:TzCurrentFilter;
begin
Filter := TfzCurrentFilter.Create(AOwner,ADB_Handle,AParameter);
if Filter.ShowModal=mrYes then
Res:=Filter.Parameter
else Res:=AParameter;
Res.ModalResult:=Filter.ModalResult;
Filter.Free;
ViewFilter:=Res;
end;
constructor TfzCurrentFilter.Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TzCurrentFilter);
begin
inherited Create(AOwner);
PParameter:=AParameter;
PDb_Handle:=ADB_Handle;
//******************************************************************************
Caption := GetConst('Filter',tcForm);
CheckBoxKodSetup.Properties.Caption := GetConst('KodSetup',tcLabel);
CheckBoxDepartment.Properties.Caption := GetConst('Department',tcLabel);
CheckBoxVidOpl.Properties.Caption := GetConst('VidOpl',tcLabel);
CheckBoxSmeta.Properties.Caption := GetConst('Smeta',tcLabel);
CheckBoxIdMan.Properties.Caption := GetConst('IdMan',tcLabel);
CheckBoxPrikaz.Properties.Caption := GetConst('Prikaz',tcLabel);
CheckBoxOperationsFilter.Properties.Caption := GetConst('IsOperationFilter',tcLabel);
DepDateLable.Caption := GetConst('LocateDate',tcLabel);
YesBtn.Caption := GetConst('Yes',tcButton);
CancelBtn.Caption := GetConst('Cancel',tcButton);
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Hint := CancelBtn.Caption+' (Esc)';
MonthesList1.Properties.Items.Text := GetMonthList;
MonthesList2.Properties.Items.Text := GetMonthList;
//******************************************************************************
CheckBoxKodSetup.Checked := PParameter.Is_KodSetup;
CheckBoxDepartment.Checked := PParameter.Is_Department;
CheckBoxSmeta.Checked := PParameter.Is_Smeta;
CheckBoxIdMan.Checked := PParameter.Is_Man;
CheckBoxVidOpl.Checked := PParameter.Is_VidOpl;
CheckBoxOperationsFilter.Checked := PParameter.Is_OperationsFilter;
CheckBoxPrikaz.Checked := PParameter.Is_Prikaz;
BoxPrikaz.Enabled := CheckBoxPrikaz.Checked;
BoxKodSetup.Enabled := CheckBoxKodSetup.Checked;
BoxSmeta.Enabled := CheckBoxSmeta.Checked;
BoxDepartment.Enabled := CheckBoxDepartment.Checked;
BoxIdMan.Enabled := CheckBoxIdMan.Checked;
BoxVidOpl.Enabled := CheckBoxVidOpl.Checked;
LabelManData.Caption := PParameter.FIO;
LabelVidOplData.Caption := PParameter.Name_VidOpl;
LabelDepartmentData.Caption := PParameter.Name_Department;
LabelSmetaData.Caption := PParameter.Name_Smeta;
EditSmeta.Text := ifthen(PParameter.Kod_Smeta=0,'',IntToStr(PParameter.Kod_Smeta));
EditDepartment.Text := PParameter.Kod_department;
EditMan.Text := IfThen(PParameter.Tn=0,'',IntToStr(PParameter.Tn));
EditVidOpl.Text := IfThen(PParameter.Kod_VidOpl=0,'',IntToStr(PParameter.Kod_VidOpl));
//******************************************************************************
if PParameter.Kod_Setup1=0 then
PParameter.Kod_Setup1:=CurrentKodSetup(PDb_Handle);
YearSpinEdit1.Value := YearMonthFromKodSetup(PParameter.Kod_Setup1);
MonthesList1.ItemIndex := YearMonthFromKodSetup(PParameter.Kod_Setup1,False)-1;
if PParameter.Kod_Setup2=0 then
PParameter.Kod_Setup2:=CurrentKodSetup(PDb_Handle);
YearSpinEdit2.Value := YearMonthFromKodSetup(PParameter.Kod_Setup2);
MonthesList2.ItemIndex := YearMonthFromKodSetup(PParameter.Kod_Setup2,False)-1;
BoxKodSetup.OnExit(self);
end;
procedure TfzCurrentFilter.CheckBoxKodSetupClick(Sender: TObject);
begin
BoxKodSetup.Enabled := not BoxKodSetup.Enabled;
end;
procedure TfzCurrentFilter.CheckBoxDepartmentClick(Sender: TObject);
begin
BoxDepartment.Enabled := not BoxDepartment.Enabled;
end;
procedure TfzCurrentFilter.CheckBoxSmetaClick(Sender: TObject);
begin
BoxSmeta.Enabled := not BoxSmeta.Enabled;
end;
procedure TfzCurrentFilter.cxButtonEdit1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var sp: TSprav;
begin
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(PDb_Handle);
FieldValues['ShowStyle'] := 0;
FieldValues['Select'] := 1;
FieldValues['Actual_Date'] := DepDateEdit.EditValue;
Post;
end;
end;
sp.Show;
if sp.Output = nil then
ShowMessage('BUG: Output is NIL!!!')
else
if not sp.Output.IsEmpty then
begin
EditDepartment.Text := varToStrDef(sp.Output['DEPARTMENT_CODE'],'');
LabelDepartmentData.Caption := varToStrDef(sp.Output['NAME_FULL'],'');
PParameter.Id_department := sp.Output['ID_DEPARTMENT'];
PParameter.Kod_department := EditDepartment.Text;
PParameter.Name_Department := '('+EditDepartment.Text+') '+LabelDepartmentData.Caption;
// PParameter.IsDepSprav := True;
end;
sp.Free;
end;
{var Department:Variant;
begin
Department:=LoadDepartment(Self,PDB_Handle,zfsNormal);
if VarArrayDimCount(Department)> 0 then
if Department[0]<>NULL then
begin
PParameter.Id_department := Department[0];
PParameter.Name_Department := Department[1];
PParameter.Kod_department := Department[3];
LabelDepartmentData.Caption := PParameter.Name_Department;
EditDepartment.Text := PParameter.Kod_department;
end;
end;}
procedure TfzCurrentFilter.EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var Smeta:Variant;
begin
Smeta:=GetSmets(self,PDB_Handle,Date,psmSmet);
if VarArrayDimCount(Smeta)> 0 then
If Smeta[0]<>NULL then
begin
PParameter.Id_smeta := Smeta[0];
PParameter.Name_Smeta := Smeta[2];
PParameter.Kod_Smeta := Smeta[3];
EditSmeta.Text := IntToStr(PParameter.Kod_Smeta);
LabelSmetaData.Caption := PParameter.Name_Smeta;
end;
end;
procedure TfzCurrentFilter.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TfzCurrentFilter.k(Sender: TObject);
begin
BoxIdMan.Enabled := not BoxIdMan.Enabled;
end;
procedure TfzCurrentFilter.EditManPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var Man:Variant;
begin
Man:=LoadPeopleModal(Self,PDB_Handle);
if VarArrayDimCount(Man)> 0 then
If Man[0]<>NULL then
begin
PParameter.Id_man := Man[0];
PParameter.Tn := Man[4];
PParameter.FIO := VarToStr(Man[1])+' '+VarToStr(Man[2])+' '+VarToStr(Man[3]);
LabelManData.Caption := PParameter.FIO;
EditMan.Text := IntToStr(PParameter.Tn);
end;
end;
procedure TfzCurrentFilter.CheckBoxVidOplClick(Sender: TObject);
begin
BoxVidOpl.Enabled := CheckBoxVidOpl.Checked;
end;
procedure TfzCurrentFilter.EditManExit(Sender: TObject);
var man:Variant;
begin
if EditMan.Text<>'' then
begin
if StrToInt(EditMan.Text)=PParameter.Tn then Exit;
man:=ManByTn(StrToInt(EditMan.Text),PDb_Handle);
if VarArrayDimCount(man)>0 then
begin
PParameter.Id_man:=man[0];
PParameter.Tn:=man[1];
PParameter.FIO:=man[2];
LabelManData.Caption := PParameter.FIO;
end
else
EditMan.SetFocus;
end;
end;
procedure TfzCurrentFilter.EditVidOplExit(Sender: TObject);
var VidOpl:Variant;
begin
if EditVidOpl.Text<>'' then
begin
if StrToInt(EditVidOpl.Text)=PParameter.Kod_VidOpl then Exit;
VidOpl:=VoByKod(StrToInt(EditVidOpl.Text),date,PDb_Handle,ZCurrentVidOplProp);
if VarArrayDimCount(VidOpl)>0 then
begin
PParameter.Id_VidOpl:=VidOpl[0];
PParameter.Kod_VidOpl:=VidOPl[1];
PParameter.Name_VidOpl:=VidOpl[2];
LabelVidOplData.Caption := PParameter.Name_VidOpl;
end
else
EditVidOpl.SetFocus;
end;
end;
procedure TfzCurrentFilter.EditVidOplPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var VidOpl:Variant;
begin
VidOPl:=LoadVidOpl(self,
PDb_Handle,zfsModal,
ValueFieldZSetup(PDb_Handle,'ID_VO_PROP_CURRENT'),
ValueFieldZSetup(PDb_Handle,'Z_ID_SYSTEM'));
if VarArrayDimCount(VidOpl)>0 then
begin
PParameter.Id_VidOpl:=VidOpl[0];
PParameter.Kod_VidOpl:=VidOPl[2];
PParameter.Name_VidOpl:=VidOpl[1];
LabelVidOplData.Caption := PParameter.Name_VidOpl;
EditVidOpl.Text := IntToStr(PParameter.Kod_VidOpl);
end
else
EditVidOpl.SetFocus;
end;
procedure TfzCurrentFilter.EditDepartmentExit(Sender: TObject);
var Department:Variant;
begin
if EditDepartment.Text<>'' then
begin
if EditDepartment.Text=PParameter.Kod_department then Exit;
Department:=DepartmentByKod(EditDepartment.Text,PDb_Handle);
if VarArrayDimCount(Department)>0 then
begin
PParameter.Id_department:=Department[0];
PParameter.Kod_department:=Department[1];
PParameter.Name_Department:=Department[2];
LabelDepartmentData.Caption := PParameter.Name_Department;
end
else
EditDepartment.SetFocus;
end;
end;
procedure TfzCurrentFilter.EditSmetaExit(Sender: TObject);
var Smeta:Variant;
begin
if EditSmeta.Text<>'' then
begin
if StrToInt(EditSmeta.Text)=PParameter.Kod_Smeta then Exit;
Smeta:=SmetaByKod(StrToInt(EditSmeta.Text),PDb_Handle);
if VarArrayDimCount(Smeta)>0 then
begin
PParameter.Id_smeta:=Smeta[0];
PParameter.Kod_Smeta:=Smeta[1];
PParameter.Name_Smeta:=Smeta[2];
LabelSmetaData.Caption := PParameter.Name_Smeta;
end
else
EditSmeta.SetFocus;
end;
end;
procedure TfzCurrentFilter.Action1Execute(Sender: TObject);
begin
if PeriodToKodSetup(YearSpinEdit1.Value,MonthesList1.ItemIndex+1)>
PeriodToKodSetup(YearSpinEdit2.Value,MonthesList2.ItemIndex+1) then
begin
MonthesList1.SetFocus;
Exit;
end;
YesBtn.SetFocus;
PParameter.Prikaz := EditPrikaz.Text;
if PParameter.Id_smeta=0 then CheckBoxSmeta.Checked:=False;
if PParameter.Id_department=0 then CheckBoxDepartment.Checked:=False;
if PParameter.Id_man=0 then CheckBoxIdMan.Checked:=False;
if PParameter.Id_VidOpl=0 then CheckBoxVidOpl.Checked:=False;
if PParameter.Prikaz='' then CheckBoxPrikaz.Enabled:=False;
PParameter.Is_Department := CheckBoxDepartment.Checked;
PParameter.Is_Smeta := CheckBoxSmeta.Checked;
PParameter.Is_Man := CheckBoxIdMan.Checked;
PParameter.Is_VidOpl := CheckBoxVidOpl.Checked;
PParameter.Is_KodSetup := CheckBoxKodSetup.Checked;
PParameter.Is_OperationsFilter := CheckBoxOperationsFilter.Checked;
PParameter.Is_Prikaz:= CheckBoxPrikaz.Checked;
PParameter.Kod_Setup1:=PeriodToKodSetup(YearSpinEdit1.Value,MonthesList1.ItemIndex+1);
PParameter.Kod_Setup2:=PeriodToKodSetup(YearSpinEdit2.Value,MonthesList2.ItemIndex+1);
if (not PParameter.Is_Smeta) and
(not PParameter.Is_Department) and
(not PParameter.Is_VidOpl) and
(not PParameter.Is_KodSetup) and
(not PParameter.Is_Man) then
ZShowMessage(GetConst('Error',tcOtherConst),GetConst('NotInputDataError',tcOtherConst),mtWarning,[mbOK])
else ModalResult:=mrYes;
end;
procedure TfzCurrentFilter.CheckBoxOperationsFilterClick(Sender: TObject);
begin
PParameter.Is_OperationsFilter := CheckBoxOperationsFilter.Checked;
end;
procedure TfzCurrentFilter.EditPrikazKeyPress(Sender: TObject;
var Key: Char);
begin
if (Length(EditPrikaz.Text)=50) and
(key<>#7) and (Key<>#8) then Key:=#0;
end;
procedure TfzCurrentFilter.CheckBoxPrikazClick(Sender: TObject);
begin
BoxPrikaz.Enabled := not BoxPrikaz.Enabled;
end;
procedure TfzCurrentFilter.BoxKodSetupExit(Sender: TObject);
var minDate: TDate;
maxDate: TDate;
begin
maxDate := ConvertKodToDate(PeriodToKodSetup(YearSpinEdit2.Value,MonthesList2.ItemIndex+1)+1)-1;
minDate := ConvertKodToDate(PeriodToKodSetup(YearSpinEdit1.Value,MonthesList1.ItemIndex+1));
DepDateEdit.Date := maxDate;
DepDateEdit.Properties.MaxDate := maxDate;
DepDateEdit.Properties.MinDate := minDate;
end;
end.
|
unit UnitPropertyLoadGistogrammThread;
interface
uses
Windows,
Classes,
Graphics,
SysUtils,
uDBForm,
uMemory,
uBitmapUtils,
uDBGraphicTypes,
uDBThread,
uDBEntities,
uImageLoader;
type
TPropertyLoadGistogrammThreadOptions = record
FileName: string;
Password: string;
Owner: TDBForm;
SID: TGUID;
OnDone: TNotifyEvent;
end;
type
TPropertyLoadGistogrammThread = class(TDBThread)
private
{ Private declarations }
FOptions: TPropertyLoadGistogrammThreadOptions;
StrParam: string;
Data: THistogrammData;
protected
procedure Execute; override;
public
constructor Create(Options: TPropertyLoadGistogrammThreadOptions);
procedure GetCurrentpassword;
procedure SetGistogrammData;
procedure DoOnDone;
end;
implementation
uses
PropertyForm;
{ TPropertyLoadGistogrammThread }
constructor TPropertyLoadGistogrammThread.Create(Options: TPropertyLoadGistogrammThreadOptions);
begin
inherited Create(Options.Owner, False);
FreeOnTerminate := True;
FOptions := Options;
end;
procedure TPropertyLoadGistogrammThread.DoOnDone;
begin
if PropertyManager.IsPropertyForm(FOptions.Owner) then
if IsEqualGUID((FOptions.Owner as TPropertiesForm).SID, FOptions.SID) then
FOptions.OnDone(Self);
end;
procedure TPropertyLoadGistogrammThread.Execute;
var
Bitmap: TBitmap;
Info: TMediaItem;
ImageInfo: ILoadImageInfo;
begin
inherited;
try
Info := TMediaItem.CreateFromFile(FOptions.FileName);
try
if LoadImageFromPath(Info, -1, FOptions.Password, [ilfGraphic, ilfICCProfile, ilfEXIF, ilfPassword, ilfAskUserPassword], ImageInfo, 800, 800) then
begin
Bitmap := ImageInfo.GenerateBitmap(Info, 800, 800, pf24Bit, clNone, [ilboFreeGraphic, ilboApplyICCProfile]);
try
if Bitmap <> nil then
begin
Data := FillHistogramma(Bitmap);
Synchronize(SetGistogrammData);
end;
finally
F(Bitmap);
end;
end;
finally
F(Info);
end;
finally
Synchronize(DoOnDone);
end;
end;
procedure TPropertyLoadGistogrammThread.GetCurrentpassword;
begin
if PropertyManager.IsPropertyForm(fOptions.Owner) then
if IsEqualGUID((fOptions.Owner as TPropertiesForm).SID, FOptions.SID) then
StrParam := (fOptions.Owner as TPropertiesForm).FCurrentPass;
end;
procedure TPropertyLoadGistogrammThread.SetGistogrammData;
begin
if PropertyManager.IsPropertyForm(FOptions.Owner) then
if IsEqualGUID((FOptions.Owner as TPropertiesForm).SID, FOptions.SID) then
(FOptions.Owner as TPropertiesForm).GistogrammData := Data;
end;
end.
|
{-----------------------------------------------------------------------------
Least-Resistance Designer Library
The Initial Developer of the Original Code is Scott J. Miles
<sjmiles (at) turbophp (dot) com>.
Portions created by Scott J. Miles are
Copyright (C) 2005 Least-Resistance Software.
All Rights Reserved.
-------------------------------------------------------------------------------}
unit DesignSurface;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Graphics, Forms, ExtCtrls,
Contnrs;
type
TDesignSurface = class(TComponent)
private
FActive: Boolean;
FContainer: TWinControl;
FHintWin: THintWindow;
FOnChange: TNotifyEvent;
protected
function DesignKeyDown(inKeycode: Cardinal;
inShift: TShiftState): Boolean; virtual;
function DesignKeyUp(inKeycode: Cardinal;
inShift: TShiftState): Boolean; virtual;
function DesignMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer): Boolean; virtual;
function DesignMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer): Boolean; virtual;
function DesignMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer): Boolean; virtual;
function KeyHook(inKey, inFlags: Cardinal): Boolean;
function KeyMessage(inKeycode, inFlags: Cardinal): Boolean;
function MouseHook(inMsg: Cardinal; var inInfo: TMouseHookStruct): Boolean;
function MouseMessage(inMsg: Cardinal; const inPt: TPoint): Boolean;
procedure CreateHintWindow; virtual;
procedure InstallHooks;
procedure SetActive(const Value: Boolean); virtual;
procedure SetContainer(const Value: TWinControl); virtual;
procedure SetOnChange(const Value: TNotifyEvent); virtual;
procedure UninstallHooks;
procedure UpdateHint(const inHint: string); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Change; virtual;
property Active: Boolean read FActive write SetActive;
property HintWin: THintWindow read FHintWin write FHintWin;
published
property Container: TWinControl read FContainer write SetContainer;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
end;
implementation
uses
DesignHooks, DesignUtils;
{ TDesignSurface }
constructor TDesignSurface.Create(AOwner: TComponent);
begin
inherited;
CreateHintWindow;
end;
destructor TDesignSurface.Destroy;
begin
UninstallHooks;
inherited;
end;
procedure TDesignSurface.CreateHintWindow;
begin
HintWin := HintWindowClass.Create(Self);
HintWin.Brush.Color := clInfoBk;
end;
procedure TDesignSurface.SetOnChange(const Value: TNotifyEvent);
begin
FOnChange := Value;
end;
procedure TDesignSurface.Change;
begin
if Assigned(OnChange) then
OnChange(Self);
end;
procedure TDesignSurface.SetContainer(const Value: TWinControl);
begin
FContainer := Value;
end;
procedure TDesignSurface.SetActive(const Value: Boolean);
begin
FActive := Value;
if Active then
InstallHooks
else
UninstallHooks;
end;
procedure TDesignSurface.InstallHooks;
begin
if (Container = nil) and (Owner <> nil) and (Owner is TWinControl) then
Container := TWinControl(Owner);
TDesignHooks.InstallMouseHook(MouseHook);
TDesignHooks.InstallKeyHook(KeyHook);
end;
procedure TDesignSurface.UninstallHooks;
begin
TDesignHooks.RemoveMouseHook;
TDesignHooks.RemoveKeyHook;
end;
function TDesignSurface.MouseHook(inMsg: Cardinal;
var inInfo: TMouseHookStruct): Boolean;
var
target: TWinControl;
begin
Result := false;
case inMsg of
WM_MOUSEFIRST..WM_MOUSELAST:
begin
target := LrFindHandle(inInfo.hwnd, Container);
if (target <> nil) then
Result := MouseMessage(inMsg, Container.ScreenToClient(inInfo.pt));
end;
end;
end;
function TDesignSurface.KeyHook(inKey: Cardinal; inFlags: Cardinal): Boolean;
begin
Result := KeyMessage(inKey, inFlags);
end;
procedure TDesignSurface.UpdateHint(const inHint: string);
var
r: TRect;
begin
with FHintWin do
begin
r := Rect(-8, 0, Canvas.TextWidth(inHint), Canvas.TextHeight(inHint));
with Mouse.CursorPos do
OffsetRect(r, X + 20, Y + 20);
ActivateHint(r, inHint);
Update;
end;
if Assigned(Container) then
Container.Update;
end;
function TDesignSurface.MouseMessage(inMsg: Cardinal;
const inPt: TPoint): Boolean;
function GetKeyShift: TShiftState;
function IsKeyDown(inCode: Integer): Boolean;
begin
Result := Boolean(GetAsyncKeyState(inCode) shr 15);
end;
begin
Result := [];
if IsKeyDown(VK_SHIFT) then
Include(Result, ssShift);
if IsKeyDown(VK_CONTROL) then
Include(Result, ssCTRL);
end;
begin
case inMsg of
WM_LBUTTONDOWN:
Result := DesignMouseDown(Self, mbLeft, GetKeyShift, inPt.X, inPt.Y);
WM_LBUTTONUP:
begin
HintWin.ReleaseHandle;
Result := DesignMouseUp(Self, mbLeft, GetKeyShift, inPt.X, inPt.Y);
end;
WM_MOUSEMOVE:
Result := DesignMouseMove(Self, GetKeyShift, inPt.X, inPt.Y);
else Result := false;
end;
end;
function TDesignSurface.DesignMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean;
begin
Result := false;
end;
function TDesignSurface.DesignMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer): Boolean;
begin
Result := false;
end;
function TDesignSurface.DesignMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean;
begin
Result := false;
end;
function TDesignSurface.KeyMessage(inKeycode: Cardinal;
inFlags: Cardinal): Boolean;
var
shift: TShiftState;
begin
Result := false;
shift := KeyDataToShiftState(Longint(inFlags));
if Container.Focused then
if ((inFlags shr 16) and KF_UP) = KF_UP then
Result := DesignKeyUp(inKeycode, shift)
else
Result := DesignKeyDown(inKeycode, shift);
end;
function TDesignSurface.DesignKeyDown(inKeycode: Cardinal;
inShift: TShiftState): Boolean;
begin
Result := false;
end;
function TDesignSurface.DesignKeyUp(inKeycode: Cardinal;
inShift: TShiftState): Boolean;
begin
Result := false;
end;
end.
|
unit GetSecurityCenterInfo;
interface
uses
SysUtils,
Windows,
ActiveX,
ComObj,
Variants;
type
TSecurityCenterInfo = Class
companyName: string;
displayName: string;
enableOnAccessUIMd5Hash: String; //Uint8;
enableOnAccessUIParameters: String;
instanceGuid: String;
pathToEnableOnAccessUI: String;
pathToSignedProductExe: String;
pathToSignedReportingExe: String;
pathToUpdateUI: String;
enableUIMd5Hash: string;
enableUIParameters: string;
productState: String;
pathToEnableUI: string;
updateUIMd5Hash: String; //Uint8;
updateUIParameters: String;
versionNumber: String;
end;
type
TSecurityCenterProduct = (AntiVirusProduct, AntiSpywareProduct, FirewallProduct);
procedure GetSecInfo(SecurityCenterProduct: TSecurityCenterProduct; var SecurityCenterInfo: TSecurityCenterInfo);
implementation
type
OSVERSIONINFOEX = packed record
dwOSVersionInfoSize: DWORD;
dwMajorVersion: DWORD;
dwMinorVersion: DWORD;
dwBuildNumber: DWORD;
dwPlatformId: DWORD;
szCSDVersion: array[0..127] of Char;
wServicePackMajor: WORD;
wServicePackMinor: WORD;
wSuiteMask: WORD;
wProductType: BYTE;
wReserved: BYTE;
end;
DWORDLONG = UInt64;
const
VER_MINORVERSION = $0000001;
VER_MAJORVERSION = $0000002;
VER_SERVICEPACKMINOR = $0000010;
VER_SERVICEPACKMAJOR = $0000020;
VER_PRODUCT_TYPE = $0000080;
const
WmiRoot='root';
WmiClassSCProduct : array [TSecurityCenterProduct] of string = ('AntiVirusProduct','AntiSpywareProduct','FirewallProduct');
WmiNamespaceSCProduct : array [Boolean] of string = ('SecurityCenter','SecurityCenter2');
function VerSetConditionMask(dwlConditionMask: int64;dwTypeBitMask: DWORD; dwConditionMask: Byte): int64; stdcall; external kernel32;
{$IFDEF UNICODE}
function VerifyVersionInfo(var LPOSVERSIONINFOEX : OSVERSIONINFOEX;dwTypeMask: DWORD;dwlConditionMask: int64): BOOL; stdcall; external kernel32 name 'VerifyVersionInfoW';
{$ELSE}
function VerifyVersionInfo(var LPOSVERSIONINFOEX : OSVERSIONINFOEX;dwTypeMask: DWORD;dwlConditionMask: int64): BOOL; stdcall; external kernel32 name 'VerifyVersionInfoA';
{$ENDIF}
//verifies that the application is running on Windows 2000 Server or a later server, such as Windows Server 2003 or Windows Server 2008.
function Is_Win_Server : Boolean;
const
VER_NT_SERVER = $0000003;
VER_EQUAL = 1;
VER_GREATER_EQUAL = 3;
var
osvi : OSVERSIONINFOEX;
dwlConditionMask : DWORDLONG;
op : Integer;
begin
dwlConditionMask := 0;
op:=VER_GREATER_EQUAL;
ZeroMemory(@osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize := sizeof(OSVERSIONINFOEX);
osvi.dwMajorVersion := 5;
osvi.dwMinorVersion := 0;
osvi.wServicePackMajor := 0;
osvi.wServicePackMinor := 0;
osvi.wProductType := VER_NT_SERVER;
dwlConditionMask:=VerSetConditionMask( dwlConditionMask, VER_MAJORVERSION, op );
dwlConditionMask:=VerSetConditionMask( dwlConditionMask, VER_MINORVERSION, op );
dwlConditionMask:=VerSetConditionMask( dwlConditionMask, VER_SERVICEPACKMAJOR, op );
dwlConditionMask:=VerSetConditionMask( dwlConditionMask, VER_SERVICEPACKMINOR, op );
dwlConditionMask:=VerSetConditionMask( dwlConditionMask, VER_PRODUCT_TYPE, VER_EQUAL );
Result:=VerifyVersionInfo(osvi,VER_MAJORVERSION OR VER_MINORVERSION OR
VER_SERVICEPACKMAJOR OR VER_SERVICEPACKMINOR OR VER_PRODUCT_TYPE, dwlConditionMask);
end;
procedure GetSCProductInfo(SCProduct: TSecurityCenterProduct; var SecurityCenterInfo: TSecurityCenterInfo);
var
FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
osVerInfo : TOSVersionInfo;
begin
osVerInfo.dwOSVersionInfoSize:=SizeOf(TOSVersionInfo);
GetVersionEx(osVerInfo);
if (SCProduct=AntiSpywareProduct) and (osVerInfo.dwMajorVersion<6) then exit;
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer('localhost',Format('%s\%s',[WmiRoot,WmiNamespaceSCProduct[osVerInfo.dwMajorVersion>=6]]), '', '');
FWbemObjectSet:= FWMIService.ExecQuery(Format('SELECT * FROM %s',[WmiClassSCProduct[SCProduct]]),'WQL',0);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
while oEnum.Next(1, FWbemObject, iValue) = 0 do
begin
if osVerInfo.dwMajorVersion >= 6 then //windows vista or newer
begin
SecurityCenterInfo.displayName := SecurityCenterInfo.displayName + Format('%s',[FWbemObject.displayName]) + '|';// String
SecurityCenterInfo.instanceGuid := SecurityCenterInfo.instanceGuid + Format('%s',[FWbemObject.instanceGuid]) + '|';// String
SecurityCenterInfo.pathToSignedProductExe := SecurityCenterInfo.pathToSignedProductExe + Format('%s',[FWbemObject.pathToSignedProductExe]) + '|';// String
SecurityCenterInfo.pathToSignedReportingExe := SecurityCenterInfo.pathToSignedReportingExe + Format('%s',[FWbemObject.pathToSignedReportingExe]) + '|';// String
SecurityCenterInfo.productState := SecurityCenterInfo.productState + Format('%s',[FWbemObject.productState]) + '|';// Uint32
end else
begin
case SCProduct of
AntiVirusProduct :
begin
SecurityCenterInfo.companyName := SecurityCenterInfo.companyName + Format('%s',[FWbemObject.companyName]) + '|';// String
SecurityCenterInfo.displayName := SecurityCenterInfo.displayName + Format('%s',[FWbemObject.displayName]) + '|';// String
SecurityCenterInfo.enableOnAccessUIMd5Hash := SecurityCenterInfo.enableOnAccessUIMd5Hash + Format('%s',[FWbemObject.enableOnAccessUIMd5Hash]) + '|';// Uint8
SecurityCenterInfo.enableOnAccessUIParameters := SecurityCenterInfo.enableOnAccessUIParameters + Format('%s',[FWbemObject.enableOnAccessUIParameters]) + '|';// String
SecurityCenterInfo.instanceGuid := SecurityCenterInfo.instanceGuid + Format('%s',[FWbemObject.instanceGuid]) + '|';// String
SecurityCenterInfo.pathToEnableOnAccessUI := SecurityCenterInfo.pathToEnableOnAccessUI + Format('%s',[FWbemObject.pathToEnableOnAccessUI]) + '|';// String
//SecurityCenterInfo.pathToSignedProductExe := SecurityCenterInfo.pathToSignedProductExe + Format('%s',[FWbemObject.pathToSignedProductExe]) + '|';// String
//SecurityCenterInfo.pathToSignedReportingExe := SecurityCenterInfo.pathToSignedReportingExe + Format('%s',[FWbemObject.pathToSignedReportingExe]) + '|';// String
SecurityCenterInfo.pathToUpdateUI := SecurityCenterInfo.pathToUpdateUI + Format('%s',[FWbemObject.pathToUpdateUI]) + '|';// String
//SecurityCenterInfo.updateUIMd5Hash := SecurityCenterInfo.updateUIMd5Hash + Format('%s',[FWbemObject.updateUIMd5Hash]) + '|';// Uint8
//SecurityCenterInfo.updateUIParameters := SecurityCenterInfo.updateUIParameters + Format('%s',[FWbemObject.updateUIParameters]) + '|';// String
//SecurityCenterInfo.productState := SecurityCenterInfo.productState + Format('%s',[FWbemObject.productState]) + '|';// String
//SecurityCenterInfo.pathToEnableUI := SecurityCenterInfo.pathToEnableUI + Format('%s',[FWbemObject.pathToEnableUI]) + '|';// String
SecurityCenterInfo.updateUIMd5Hash := SecurityCenterInfo.updateUIMd5Hash + Format('%s',[FWbemObject.updateUIMd5Hash]) + '|';// String
SecurityCenterInfo.updateUIParameters := SecurityCenterInfo.updateUIParameters + Format('%s',[FWbemObject.updateUIParameters]) + '|';// String
SecurityCenterInfo.versionNumber := SecurityCenterInfo.versionNumber + Format('%s',[FWbemObject.versionNumber]) + '|';// String
SecurityCenterInfo.enableUIParameters := SecurityCenterInfo.enableUIParameters + Format('%s',[FWbemObject.enableUIParameters]) + '|';// String
SecurityCenterInfo.enableUIMd5Hash := SecurityCenterInfo.enableUIMd5Hash + Format('%s',[FWbemObject.enableUIMd5Hash]) + '|';// String
end;
FirewallProduct :
begin
SecurityCenterInfo.companyName := SecurityCenterInfo.companyName + Format('%s',[FWbemObject.companyName]) + '|';// String
SecurityCenterInfo.displayName := SecurityCenterInfo.displayName + Format('%s',[FWbemObject.displayName]) + '|';// String
//SecurityCenterInfo.enableOnAccessUIMd5Hash := SecurityCenterInfo.enableOnAccessUIMd5Hash + Format('%s',[FWbemObject.enableOnAccessUIMd5Hash]) + '|';// Uint8
//SecurityCenterInfo.enableOnAccessUIParameters := SecurityCenterInfo.enableOnAccessUIParameters + Format('%s',[FWbemObject.enableOnAccessUIParameters]) + '|';// String
SecurityCenterInfo.instanceGuid := SecurityCenterInfo.instanceGuid + Format('%s',[FWbemObject.instanceGuid]) + '|';// String
//SecurityCenterInfo.pathToEnableOnAccessUI := SecurityCenterInfo.pathToEnableOnAccessUI + Format('%s',[FWbemObject.pathToEnableOnAccessUI]) + '|';// String
//SecurityCenterInfo.pathToSignedProductExe := SecurityCenterInfo.pathToSignedProductExe + Format('%s',[FWbemObject.pathToSignedProductExe]) + '|';// String
//SecurityCenterInfo.pathToSignedReportingExe := SecurityCenterInfo.pathToSignedReportingExe + Format('%s',[FWbemObject.pathToSignedReportingExe]) + '|';// String
//SecurityCenterInfo.pathToUpdateUI := SecurityCenterInfo.pathToUpdateUI + Format('%s',[FWbemObject.pathToUpdateUI]) + '|';// String
//SecurityCenterInfo.updateUIMd5Hash := SecurityCenterInfo.updateUIMd5Hash + Format('%s',[FWbemObject.updateUIMd5Hash]) + '|';// Uint8
//SecurityCenterInfo.updateUIParameters := SecurityCenterInfo.updateUIParameters + Format('%s',[FWbemObject.updateUIParameters]) + '|';// String
//SecurityCenterInfo.productState := SecurityCenterInfo.productState + Format('%s',[FWbemObject.productState]) + '|';// String
SecurityCenterInfo.pathToEnableUI := SecurityCenterInfo.pathToEnableUI + Format('%s',[FWbemObject.pathToEnableUI]) + '|';// String
//SecurityCenterInfo.updateUIMd5Hash := SecurityCenterInfo.updateUIMd5Hash + Format('%s',[FWbemObject.updateUIMd5Hash]) + '|';// String
//SecurityCenterInfo.updateUIParameters := SecurityCenterInfo.updateUIParameters + Format('%s',[FWbemObject.updateUIParameters]) + '|';// String
SecurityCenterInfo.versionNumber := SecurityCenterInfo.versionNumber + Format('%s',[FWbemObject.versionNumber]) + '|';// String
SecurityCenterInfo.enableUIParameters := SecurityCenterInfo.enableUIParameters + Format('%s',[FWbemObject.enableUIParameters]) + '|';// String
SecurityCenterInfo.enableUIMd5Hash := SecurityCenterInfo.enableUIMd5Hash + Format('%s',[FWbemObject.enableUIMd5Hash]) + '|';// String
end;
end;
end;
FWbemObject:=Unassigned;
end;
end;
procedure GetSecInfo(SecurityCenterProduct: TSecurityCenterProduct; var SecurityCenterInfo: TSecurityCenterInfo);
var
TempStr: string;
begin
try
if Is_Win_Server then Exit;
CoInitialize(nil);
try
GetSCProductInfo(SecurityCenterProduct, SecurityCenterInfo);
finally
CoUninitialize;
end;
except
end;
end;
end.
|
unit DeviceIntegration;
interface
uses SysUtils, Dialogs, uXML, ProcessorInterface, uMRPinPad, uCreditCardFunction;
type
TDeviceIntegration = class(TInterfacedObject)
protected
FCashBack: Currency;
FexpDate: String;
Ftrack2: String;
FcardSwiped : WideString;
Fprocessor: IProcessor;
FPinPad: TMRPinPad;
FXMLResult : WideString; // XML answer from Server
FXMLServer : WideString; // XML Server
FXMLSent : WideString; // XML Sent
FXMLReceived : WideString; // XML Received Aprooved/Declined
FXMLContent : TXMLContent;
FAfterSucessfullSwipe : TAfterSucessfullSwipe;
FOnNeedSwipe : TNeedSwipeEvent;
FOnNeedTroutD : TNeedTroutDEvent;
function VerifyTransaction(): Boolean; virtual;
function VerifyServerConfig() : Boolean; virtual;
function MappingCardType(arg_cardType: String): String; virtual;
procedure SetPadType(arg_name: String); virtual;
end;
implementation
{ TDeviceIntegration }
function TDeviceIntegration.MappingCardType(arg_cardType: String): String;
begin
if ( lowercase(arg_cardtype) = 'visa' ) then begin
result := 'VISA';
end else if ( lowercase(arg_cardType) = 'm/c' ) then begin
result := 'MASTERCARD';
end else if ( lowercase(arg_cardType) = 'amex' ) then begin
result := 'AMEX';
end else if ( lowercase(arg_cardType) = 'dcvr' ) then begin
result := 'DISCOVER';
end else if ( lowercase(arg_cardType) = 'dclb' ) then begin
result := 'DINERS';
end else if ( lowercase(arg_cardType) = 'jcb' ) then begin
result := 'JCB';
end else if ( lowercase(arg_cardType) = 'debit' ) then begin
result := 'DEBIT';
end else begin
result := 'OTHER';
end;
end;
procedure TDeviceIntegration.SetPadType(arg_name: String);
begin
if ( ansipos('Ingenico', arg_name) > 0 ) then begin
Fprocessor.SetPadType('ISC250');
end else if ( ansipos('Verifone', arg_name) > 0 ) then begin
Fprocessor.SetPadType('VX805');
end;
end;
function TDeviceIntegration.VerifyTransaction(): Boolean;
var
AResult : String;
IResult : Integer;
trueCardtypeName: String;
begin
try
FXMLContent.XML := FXMLResult;
Result := False;
Fprocessor.SetMessage('');
//Indicates the outcome of the command:
//"Success" = command completed successfully
//"Error" = error processing command. Check DSIXReturnCode and TextResponse for additional info on error
AResult := FXMLContent.GetAttributeString('CmdStatus');
//Six digit return code which identifies the error type. See Section 3 on error codes for possible values
IResult := FXMLContent.GetAttributeInteger('DSIXReturnCode');
if (AResult = 'Approved') then
begin
Fprocessor.SetAuthCode(FXMLContent.GetAttributeString('AuthCode'));
Fprocessor.SetResultAcqRefData(FXMLContent.GetAttributeString('AcqRefData'));
Fprocessor.SetRefNo(FXMLContent.GetAttributeString('RefNo'));
Fprocessor.SetAcctNo(FXMLContent.GetAttributeString('AcctNo'));
Fprocessor.SetLastDigits(Copy(Trim(Fprocessor.GetAcctNo()), Length(Trim(Fprocessor.GetAcctNo())) - 3, 4));
Fprocessor.SetPurchase(FXMLcontent.GetAttributeDouble('Purchase'));
Fprocessor.SetAuthorize(FXMLContent.GetAttributeDouble('Authorize'));
Fprocessor.SetSequenceNo(FXMLContent.GetAttributeString('SequenceNo'));
// # true name from XML response
trueCardTypeName := FXMLContent.GetAttributeString('CardType');
// # name mapped to assign correct IdMeioPag
Fprocessor.SetCardType(mappingCardType(trueCardTypeName));
Fprocessor.SetEntryMethod(FXMlContent.GetAttributeString('EntryMethod'));
Fprocessor.SetAppLabel(FXMLContent.GetAttributeString('ApplicationLabel'));
// Antonio 2013 Oct 28, MR-80
if ( FXMLContent.GetAttributeString('TranCode') = 'Return' ) then begin
Fprocessor.SetPurchase(((-1) * Fprocessor.GetPurchase()));
Fprocessor.SetAuthorize(((-1) * Fprocessor.GetAuthorize()));
end;
Fprocessor.SetMessage(AResult);
Fprocessor.SetTransactionResult(ttrSuccessfull);
Result := True;
end
else
begin
// # see declined transaction and get info to receipt declined
if (AResult = 'Declined') then begin
Fprocessor.SetTransactionResult(ttrDeclined);
Fprocessor.SetAcctNo(FXMLContent.GetAttributeString('AcctNo'));
Fprocessor.SetLastDigits(Copy(Trim(Fprocessor.GetAcctNo()), Length(Trim(Fprocessor.GetAcctNo())) - 3, 4));
// # true name from XML response
trueCardTypeName := FXMLContent.GetAttributeString('CardType');
// # name mapped to assign correct IdMeioPag
Fprocessor.SetCardType(mappingCardType(trueCardTypeName));
Fprocessor.SetEntryMethod(FXMlContent.GetAttributeString('EntryMethod'));
// declined date time
Fprocessor.SetDateTransaction(FXMLContent.GetAttributeString('Date') + ' Time: ' + FXMLContent.GetAttributeString('Time'));
end else begin
Fprocessor.SetTransactionResult(ttrError);
end;
Fprocessor.SetTrancode(IntToStr(IResult));
Fprocessor.SetMessage('Code: ' + IntToStr(IResult));
//Indicates the source of the response: “Client” = generated by DSIClientX control
AResult := FXMLContent.GetAttributeString('ResponseOrigin');
//For Successful responses, this field contains the number of IP addresses that were stored. For other response codes, see Section 3 on Error Codes for values
AResult := FXMLContent.GetAttributeString('TextResponse');
Fprocessor.SetMessage(Fprocessor.GetMessage() + '. ' + AResult );
end;
except
on E: Exception do
begin
Fprocessor.SetTransactionResult(ttrException);
Result := False;
raise Exception.Create('Exception: ' + E.Message);
end;
end;
end;
function TDeviceIntegration.VerifyServerConfig: Boolean;
var
AResult : String;
IResult : Integer;
begin
try
FXMLContent.XML := FXMLResult;
// debugtofile('XML(connection) result from Mercury: ' + FXMLContent.xml);
Result := False;
AResult := '';
//Indicates the outcome of the command:
//“Success” = command completed successfully
//“Error” = error processing command. Check DSIXReturnCode and TextResponse for additional info on error
AResult := FXMLContent.GetAttributeString('CmdStatus');
//Six digit return code which identifies the error type. See Section 3 on error codes for possible values
IResult := FXMLContent.GetAttributeInteger('DSIXReturnCode');
if (AResult = 'Success') then
begin
Result := True;
Fprocessor.SetTransactionResult(ttrSuccessFull);
end
else
begin
Fprocessor.SetTransactionResult(ttrError);
//Indicates the source of the response: “Client” = generated by DSIClientX control
AResult := FXMLContent.GetAttributeString('ResponseOrigin');
//For Successful responses, this field contains the number of IP addresses that were stored. For other response codes, see Section 3 on Error Codes for values
AResult := FXMLContent.GetAttributeString('TextResponse');
Fprocessor.SetMessage(AResult);
result := true;
end;
except
on E: Exception do
begin
Fprocessor.SetTransactionResult(ttrException);
Result := False;
end;
end;
end;
end.
|
unit ContentMngr; //ContentManager
// Original code november 2002 Gerard Slurink
// May be distributed and modified freely
// Still under construction!
// Contains:
// TContentManager for access to zip-archive or similar content
// Use the global ContentManager instance that is created automatically
// Interface:
// - EnumFirstChild reads the archive and returns the first child of the given path
// which is the relative path in zip-archive
// - EnumNextChild assumes that EnumFirstChild has been called (not checked) and
// returns the next child or nil if no more children
// - Execute opens or executes the file specified in APath which is the full path
// in the archive, including the filename
// - GetContentInfo returns the info on the file specified in APath which is the full
// path in the archive, including the filename
// - Content for Max (default = 10) files is cached
//
// Made as general as possible, it should be easy to use for other formats.
// Modifications need to be made only in TContainer.Load and TContentManager.Execute and
// addfiles and deletefiles, and ..
// Ok, Ok, some more calls are being made to ZipMaster as more functinality is added
// I will see if i can take this out to a separeate object
// BTW ZipMaster is part of DelphiZip available at http://www.geocities.com/rjpeters_au/zipmaster.html
// TContentManager is not thread safe yet !
interface
uses
ZipMstr,
Classes, SysUtils, ShlObj, Windows, Controls, Forms, ShellApi,
VirtualPIDLTools,
Utilities;
type
TContentInfo = class
private
FirstChild: TContentInfo;
Next: TContentInfo;
public
Name: String;
IsFolder: Boolean;
HasFolders: Boolean;
CompressedSize: Integer;
UnCompressedSize: Integer;
Date: Integer;
Attributes: Word;
CRC: Integer;
end;
TContentTree = class
private
FRoot: TContentInfo;
FEnum: TContentInfo;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure AddNode(const APath: String; ANode: TContentInfo);
function Find(const APath: String): TContentInfo;
function GetFirstChild(const APath: String): TContentInfo;
function GetNextChild: TContentInfo;
// future methods to implement:
// procedure Delete(const APath: String);
// Procedure Rename(const oldPath, newPath: String)
end;
TContainer = class
private
FFileName: String;
ContentTree: TContentTree;
procedure Load(const FileName: String);
public
constructor Create;
destructor Destroy; override;
end;
TContentManager = class
private
FMax: Integer;
FCount: Integer;
FReplacePos: Integer; // must still think about this one
Containers: array of TContainer;
function GetContainer(const AFileName: String): TContainer;
procedure SetMax(value: Integer);
procedure ChangePath(Sender: TObject; var OldFileName: String; var IsChanged: Boolean);
public
constructor Create;
destructor Destroy; override;
procedure AddFiles(const AFileName, APath: String; AFileList: TStringList);
procedure DeleteFiles(const AFileName: String; AFileList: TStringList);
function EnumFirstChild(const AFileName, APath: String): TContentInfo;
function EnumNextChild(const AFileName: String): TContentInfo;
procedure Execute(const AFileName, APath: String);
procedure ExtractFiles(const AFileList: TStringList; const DestinationRoot: String);
function GetContentInfo(const AFileName, APath: String): TContentInfo;
procedure PrepareShellDrag(const AFileName, APath: String; AFileList: TStringList);
property Max: Integer read FMax write SetMax;
end;
var
ContentManager : TContentManager;
implementation
{------------------------------------------------------------------------------}
{ TContentTree }
{------------------------------------------------------------------------------}
// Tree data structure that can hold hierarchical information such as the structure
// of files in a (zip) archive (translates a list to a tree)
// Interface:
// Create a TContentNode and add it to the Tree with AddNode(path-to-node, node)
// path-to-node is the relatve path in zip-archive, without the filename
// Access with GetFirstChild/GetNextChild
// GetNextChild assumes that GetFirstChild has been called before (not checked)
// Can be used also without ContentManager
constructor TContentTree.Create;
begin
FRoot := TContentInfo.Create;
end;
{------------------------------------------------------------------------------}
destructor TContentTree.Destroy;
begin
Clear;
FRoot.Free;
inherited;
end;
{------------------------------------------------------------------------------}
procedure TContentTree.Clear;
procedure ClearContentsTree(node: TContentInfo);
begin
if node.FirstChild <> nil then
ClearContentsTree(node.FirstChild);
if node.Next <> nil then
ClearContentsTree(node.Next);
node.Free;
end;
begin
Assert(FRoot <> nil);
if FRoot.FirstChild <> nil then
ClearContentsTree(FRoot.FirstChild);
FRoot.FirstChild := nil;
FRoot.Next := nil;
end;
{------------------------------------------------------------------------------}
procedure SeverHead(const path: String; var head, rest: String);
const
delimiter = '\';
var
p: Integer;
begin
p := Pos(delimiter, path);
if p <> 0 then
begin
head := Copy(path, 1, p-1);
rest := Copy(path, p+1, MaxInt);
end
else begin
head := path;
rest := '';
end;
end;
{------------------------------------------------------------------------------}
procedure SeverTail(const path: String; var tail, rest: String);
const
delimiter = '\';
var
p: Integer;
begin
if rest[Length(rest)] = '\' then
SetLength(rest, Length(rest)-1);
p := Length(rest);
while (p > 0) and (rest[p] <> delimiter) do Dec(p);
if p > 0 then
begin
tail := Copy(rest, p+1, MaxInt);
rest := Copy(rest, 1, p - 1);
end
else begin
tail := rest;
rest := '';
end;
end;
{------------------------------------------------------------------------------}
procedure TContentTree.AddNode(const APath: String; ANode: TContentInfo);
function CreateBranch(const path: String): TContentInfo;
var
node: TContentInfo;
tail, rest: String;
begin
Result := ANode;
rest := path;
while rest <> '' do
begin
SeverTail(rest, tail, rest);
node := TContentInfo.Create;
node.Name := tail;
node.IsFolder := True;
node.FirstChild := Result;
node.HasFolders := False; //Result <> ANode;
Result := node;
end;
end;
procedure AddChild(parentNode: TContentInfo; const path: String);
// parentNode = head of list
var
node, current: TContentInfo;
head, rest: String;
begin
Assert(parentNode <> nil);
SeverHead(path, head, rest);
current := parentNode;
node := parentNode.FirstChild;
if head = '' then head := ANode.Name; // parentNode is direct parent
// we are looking for a match or for a place to insert
while (node <> nil) and (AnsiCompareStr(node.Name, head) < 0) do
begin
current := node;
node := node.Next;
end;
if (node = nil) or (not AnsiSameStr(node.Name, head)) then
begin
// no match - insert branch at current
node := CreateBranch(path);
if current = parentNode then
begin
node.Next := current.FirstChild;
current.FirstChild := node;
end
else begin
node.Next := current.Next;
current.Next := node;
end
end
else
AddChild(node, rest);
end;
begin
AddChild(FRoot, APath);
end;
{------------------------------------------------------------------------------}
function TContentTree.Find(const APath: String): TContentInfo;
function SearchSubContentsTree(parentNode: TContentInfo; path: String): TContentInfo;
var
node: TContentInfo;
head, rest: String;
begin
SeverHead(path, head, rest);
node := parentNode.FirstChild;
while (node <> nil) and (node.Name <> head) do node := node.Next;
if node <> nil then
begin
if rest = '' then
Result := node
else
Result := SearchSubContentsTree(node, rest)
end
else
Result := nil
end;
begin
if APath = '' then
Result := FRoot.FirstChild
else
Result := SearchSubContentsTree(FRoot, APath);
end;
{------------------------------------------------------------------------------}
function TContentTree.GetFirstChild(const APath: String): TContentInfo;
function SearchSubContentsTree(parentNode: TContentInfo; path: String): TContentInfo;
var
node: TContentInfo;
head, rest: String;
begin
SeverHead(path, head, rest);
node := parentNode.FirstChild;
while (node <> nil) and (node.Name <> head) do node := node.Next;
if node <> nil then
begin
if rest = '' then
Result := node.FirstChild
else
Result := SearchSubContentsTree(node, rest)
end
else
Result := nil
end;
begin
if APath = '' then
Result := FRoot.FirstChild
else
Result := SearchSubContentsTree(FRoot, APath);
FEnum := Result;
if FEnum <> nil then
FEnum := FEnum.Next;
end;
{------------------------------------------------------------------------------}
function TContentTree.GetNextChild: TContentInfo;
begin
Result := FEnum;
if FEnum <> nil then
FEnum := FEnum.Next;
end;
{------------------------------------------------------------------------------}
{ TContainer }
{------------------------------------------------------------------------------}
constructor TContainer.Create;
begin
ContentTree := TContentTree.Create;
end;
{------------------------------------------------------------------------------}
destructor TContainer.Destroy;
begin
ContentTree.Free;
end;
{------------------------------------------------------------------------------}
procedure TContainer.Load(const FileName: String);
var
i: Integer;
path : String;
ContentInfo: TContentInfo;
ZipMaster: TZipMaster;
begin
FFileName := FileName;
ContentTree.Clear;
ZipMaster := TZipMaster.Create(nil);
try
ZipMaster.ZipFileName := FFileName;
for i := 0 To Zipmaster.Count - 1 do
begin
ContentInfo := TContentInfo.Create;
ContentInfo.Name := ExtractFileName(ZipDirEntry(ZipMaster.ZipContents[i]^).FileName);
ContentInfo.IsFolder := False;
ContentInfo.HasFolders := False;
ContentInfo.CompressedSize := ZipDirEntry(ZipMaster.ZipContents[i]^).CompressedSize;
ContentInfo.UnCompressedSize := ZipDirEntry(ZipMaster.ZipContents[i]^).UncompressedSize;
ContentInfo.Date := ZipDirEntry(ZipMaster.ZipContents[i]^).DateTime;
ContentInfo.CRC := ZipDirEntry(ZipMaster.ZipContents[i]^).CRC32;
ContentInfo.Attributes := ZipDirEntry(ZipMaster.ZipContents[i]^).IntFileAttrib;
path := ExtractFilePath(ZipDirEntry(ZipMaster.ZipContents[i]^).FileName);
ContentTree.AddNode(path, ContentInfo);
end;
finally
zipMaster.Free;
end;
end;
{------------------------------------------------------------------------------}
{ TContentManager }
{------------------------------------------------------------------------------}
constructor TContentManager.Create;
begin
FMax := 10;
FCount := 0;
end;
{------------------------------------------------------------------------------}
destructor TContentManager.Destroy;
var i: Integer;
begin
for i := 0 to FCount -1 do
Containers[i].Free
end;
{------------------------------------------------------------------------------}
// stupid way to rename on add, but the only possible way with DelphiZip
var
droproot : String;
procedure TContentManager.ChangePath(Sender: TObject; var OldFileName: String; var IsChanged: Boolean);
begin
OldFileName := droproot + '\' + OldFileName;
IsChanged := True;
end;
{------------------------------------------------------------------------------}
procedure TContentManager.AddFiles(const AFileName, APath: String; AFileList: TStringList);
// we get zipfile, relative drop path in zip, dropped files
var
ZipMaster: TZipMaster;
commonRoot: String;
i: Integer;
begin
if AFileList.Count = 0 then Exit;
ZipMaster := TZipMaster.Create(nil);
try
ZipMaster.ZipFileName := AFileName;
// since toSiblingSelectConstraint is always true all files share the same root
// otherwhise we must determine the lowest common folder and add from there
commonRoot := ExtractFilePath(AFileList[0]);
// add relative paths
for i := 0 to AFileList.Count - 1 do
begin
if DirectoryExists(AFileList[i]) then
ZipMaster.FSpecArgs.Add(Copy(AFileList[i], Length(commonRoot)+1, MaxInt) + '\*.*')
else
ZipMaster.FSpecArgs.Add(Copy(AFileList[i], Length(commonRoot)+1, MaxInt));
end;
ZipMaster.RootDir := commonRoot;
ZipMaster.AddOptions := [AddDirNames, AddRecurseDirs];
if APath <> '' then
begin
droproot:= APath;
ZipMaster.OnSetNewName := ChangePath;
end;
ZipMaster.Add;
finally
ZipMaster.Free;
end;
// reread - no optimization, we have to get the details of the added files
i := 0;
while (i < FCount) and not (AnsiSameText(Containers[i].FFileName, AFileName)) do Inc(i);
Containers[i].Load(AFileName);
end;
{------------------------------------------------------------------------------}
procedure TContentManager.DeleteFiles(const AFileName: String; AFileList: TStringList);
var
ZipMaster: TZipMaster;
i: Integer;
begin
ZipMaster := TZipMaster.Create(nil);
try
ZipMaster.ZipFileName := AFileName;
for i := 0 to AFileList.Count - 1 do
begin
if self.EnumFirstChild(AFileName, AFileList[i]) <> nil then
ZipMaster.FSpecArgs.Add(AFileList[i] + '\*.*')
else
ZipMaster.FSpecArgs.Add(AFileList[i])
end;
ZipMaster.Delete;
finally
ZipMaster.Free
end;
// reread - could be optimized with a ContenTree.Delete method
i := 0;
while (i < FCount) and not (AnsiSameText(Containers[i].FFileName, AFileName)) do Inc(i);
Containers[i].Load(AFileName);
end;
{------------------------------------------------------------------------------}
function TContentManager.GetContainer(const AFileName: String): TContainer;
var i: Integer;
begin
i := 0;
while (i < FCount) and not (AnsiSameText(Containers[i].FFileName, AFileName)) do Inc(i);
// set some MRU info ?
// if no more room we can replace on mixed FIFO and/or MRU base
if i < FCount then
Result := Containers[i]
else begin
if FCount < FMax then
begin
Inc(FCount);
SetLength(Containers, FCount);
Containers[FCount-1] := TContainer.Create;
Containers[FCount-1].Load(AFileName);
Result := Containers[FCount-1];
end
else begin
Containers[FReplacePos].Load(AFileName);
Result := Containers[FReplacePos];
Inc(FReplacePos);
if FReplacePos = FMax Then
FReplacePos := 0;
end;
end;
end;
{------------------------------------------------------------------------------}
function TContentManager.EnumFirstChild(const AFileName, APath: String): TContentInfo;
begin
Result := GetContainer(AFileName).ContentTree.GetFirstChild(APath);
end;
{------------------------------------------------------------------------------}
function TContentManager.EnumNextChild(const AFileName: String): TContentInfo;
begin
Result := GetContainer(AFileName).ContentTree.GetNextChild;
end;
{------------------------------------------------------------------------------}
procedure TContentManager.Execute(const AFileName, APath: String);
var path: String;
begin
Screen.Cursor := crAppStart;
try
path := GetSystemTemp;
with TZipMaster.Create(nil) do
try
ZipFileName :=AFileName;
FSpecArgs.Clear;
FSpecArgs.Add(APath);
ExtrBaseDir := path;
ExtrOptions := [ExtrOverwrite]; // ExtrDirNames
Extract;
path := path + ExtractFileName(APath);
// make it readonly so user cannot edit it
FileSetAttr(path, faReadOnly);
// to cleanup on close:
// tempFiles.Add(path);
finally
Free;
end;
ShellExecute(Application.Handle, 'open', pChar(path), '', nil, SW_NORMAL);
finally
Screen.Cursor := crDefault;
end;
end;
{------------------------------------------------------------------------------}
procedure TContentManager.ExtractFiles(
const AFileList: TStringList; const DestinationRoot: String);
var ZipMaster: TZipMaster;
begin
ZipMaster := TZipMaster.Create(nil);
try
// we still must do some renaming ... (path trimming)
ZipMaster.FSpecArgs.Assign(AFileList);
ZipMaster.ExtrBaseDir := DestinationRoot;
ZipMaster.Extract;
finally
ZipMaster.Free;
end;
end;
{------------------------------------------------------------------------------}
function TContentManager.GetContentInfo(const AFileName, APath: String): TContentInfo;
begin
Result := GetContainer(AFileName).ContentTree.Find(APath);
end;
{------------------------------------------------------------------------------}
procedure TContentManager.PrepareShellDrag(const AFileName, APath: String; AFileList: TStringList);
var tempRoot, trimmedPath: String; p, i: Integer;
begin
// best would be to rename on extract but DelphiZip does not provide this possibility
// so we have rename after extraction
Screen.Cursor := crAppStart;
try
tempRoot := 'C:\temp\'; //GetSystemTemp;
with TZipMaster.Create(nil) do
try
ZipFileName := AFileName;
FSpecArgs.Assign(AFileList);
ExtrBaseDir := tempRoot;
ExtrOptions := [ExtrOverwrite, ExtrDirNames];
Extract;
for i := 0 to AFileList.count - 1 do
begin
p := Pos('\*.*', AFileList[i]);
if p > 0 then // it is a folder
begin
AFileList[i] := Copy(AFileList[i], 1, p-1);
trimmedPath := Copy(AFileList[i], Length(APath) + 1, MaxInt);
if APath <> '' then
MoveDirectory(tempRoot + AFileList[i], tempRoot + trimmedPath);
AFileList[i] := tempRoot + trimmedPath;
end
else begin
RenameFile(tempRoot + AFileList[i], ExtractFilename(AFileList[i]));
AFileList[i] := tempRoot + ExtractFilename(AFileList[i]);
end;
end;
if APath <> '' then
DeleteDirectory(tempRoot + APath);
// tempFiles.Add(path);
finally
Free;
end;
finally
Screen.Cursor := crDefault;
end;
end;
{------------------------------------------------------------------------------}
procedure TContentManager.SetMax(value: Integer);
begin
FMax := value;
if Length(Containers) > FMax then
SetLength(Containers, FMax);
end;
{------------------------------------------------------------------------------}
initialization
ContentManager := TContentManager.Create;
finalization
ContentManager.Free;
end.
|
unit Vector;
{$MODE Delphi}
//
// Vector calculations unit, (c) Roelof Oomen, 2007
//
// Coordinate system
//
// Cartesian
// z|
// | / y
// | /
// __________|/_________ x
// /|
// / |
// / |
//
//
// Spherical coordinates are defined as (r, psi, theta) with psi being
// the azimuth angle (0-360 degrees, in the x-y plane, counterclockwise)
// and theta the polar/zenith angle (0-180 degrees, angle with z-axis).
//
// Cylindrical coordinates are defined as (r, psi, h)
// where r is the radius (distance to the z-axis), h is the
// height, i.e. the Z-coordinate, and psi the angle with the x-axis in
// the x-y plane, counterclockwise.
//
// WARNING: The definitions of the spherical coordinates differ from many texts,
// (common: r, theta, phi).
//
interface
type
// Cartesian
TVectorC = record
private
function getR: double; //inline;
public
x,
y,
z : double;
property r : double read getR; // Length
procedure makeUnit; //inline;
function isUnit : boolean; //inline;
procedure InitC(x, y, z : Double);
procedure Null; //inline;
function isNull : boolean; //inline;
// Operator overloadings - Delphi 2005 and later
class operator Negative(a: TVectorC) : TVectorC; //inline; // Negate
class operator Add(a: TVectorC; b: TVectorC): TVectorC; //inline;
class operator Subtract(a: TVectorC; b: TVectorC) : TVectorC; //inline;
class operator Multiply(a: Double; b: TVectorC) : TVectorC; //inline; // Multiply a vector by a scalar
class operator Multiply(a: TVectorC; b: Double) : TVectorC; //inline; // Multiply a vector by a scalar
class operator Multiply(a: TVectorC; b: TVectorC) : Double; //inline; // Dot product!
class operator Divide(a: TVectorC; b: Double) : TVectorC; //inline;
class operator Equal(a: TVectorC; b: TVectorC) : Boolean; //inline;
end;
// Spherical
TVectorS = record
theta,
psi,
r : double;
procedure Null; //inline;
function isNull : boolean; //inline;
class operator Equal(a: TVectorS; b: TVectorS) : Boolean; //inline;
class operator Multiply(a: TVectorS; b: TVectorS) : Double; //inline; // Dot product!
class operator Implicit(a : TVectorS) : TVectorC; //inline;
class operator Explicit(a : TVectorS) : TVectorC; //inline;
// Forward declaration of TVectorS is not possible, so these two casts are placed here
class operator Implicit(a : TVectorC) : TVectorS; //inline;
class operator Explicit(a : TVectorC) : TVectorS; //inline;
end;
// Cylindrical
{ TVectorCyl = record
r,
psi,
h : double;
class operator Implicit(a : TVectorCyl) : TVectorS; //inline;
class operator Explicit(a : TVectorCyl) : TVectorS; //inline;
end; }
implementation
uses
math, sysutils, LCLIntf, LCLType;
{ *** TVector *************************************************************** }
class operator TVectorC.Add(a, b: TVectorC): TVectorC;
begin
result.x:=a.x+b.x;
result.y:=a.y+b.y;
result.z:=a.z+b.z;
end;
class operator TVectorC.Subtract(a, b: TVectorC): TVectorC;
begin
result.x:=a.x-b.x;
result.y:=a.y-b.y;
result.z:=a.z-b.z;
end;
class operator TVectorC.Divide(a: TVectorC; b: Double): TVectorC;
begin
result.x:=a.x/b;
result.y:=a.y/b;
result.z:=a.z/b;
end;
class operator TVectorC.Equal(a, b: TVectorC): Boolean;
begin
result:=(a.x=b.x) and (a.y=b.y) and (a.z=b.z);
end;
function TVectorC.getR: double;
begin
result:=sqrt(sqr(x)+sqr(y)+sqr(z));
end;
procedure TVectorC.InitC(x, y, z: Double);
begin
self.x:=x;
self.y:=y;
self.z:=z;
end;
class operator TVectorC.Multiply(a, b: TVectorC): Double;
begin
result:=a.x*b.x+a.y*b.y+a.z*b.z;
end;
class operator TVectorC.Multiply(a: Double; b: TVectorC): TVectorC;
begin
result.x:=a*b.x;
result.y:=a*b.y;
result.z:=a*b.z;
end;
class operator TVectorC.Multiply(a: TVectorC; b: Double): TVectorC;
begin
result.x:=b*a.x;
result.y:=b*a.y;
result.z:=b*a.z;
end;
class operator TVectorC.Negative(a: TVectorC): TVectorC;
begin
result.x:=-a.x;
result.y:=-a.y;
result.z:=-a.z;
end;
function TVectorC.isNull: boolean;
begin
if ( (x=0) and (y=0) and (z=0) ) then
result:=true
else
result:=false;
end;
function TVectorC.isUnit: boolean;
begin
// Compensate for very minor differences (rounding errors etc)
result:=( RoundTo(r,-12)=1 );
end;
procedure TVectorC.makeUnit;
var
r_i:Double;
begin
r_i:=r;
x:=x/r_i;
y:=y/r_i;
z:=z/r_i;
end;
procedure TVectorC.null;
begin
x:=0;
y:=0;
z:=0;
end;
{ TVectorS }
function TVectorS.isNull: boolean;
begin
if (theta=0) and (psi=0) and (r=0) then
result:=true
else
result:=false;
end;
class operator TVectorS.Multiply(a, b: TVectorS): Double;
var
ax, ay, az, bx, by, bz : double;
begin
//result:=cos(a.psi-b.psi)*sin(a.theta)*sin(b.theta)+cos(a.theta)*cos(b.theta);
ax:=a.r*sin(a.theta)*cos(a.psi);
ay:=a.r*sin(a.theta)*sin(a.psi);
az:=a.r*cos(a.theta);
bx:=b.r*sin(b.theta)*cos(b.psi);
by:=b.r*sin(b.theta)*sin(b.psi);
bz:=b.r*cos(b.theta);
result:=ax*bx+ay*by+az*bz;
end;
procedure TVectorS.Null;
begin
theta:=0;
psi:=0;
r:=0;
end;
class operator TVectorS.Equal(a, b: TVectorS): Boolean;
begin
//inherited;
result:=(a.theta=b.theta) and (a.psi=b.psi) and (a.r=b.r);
end;
class operator TVectorS.Explicit(a: TVectorS): TVectorC;
begin
result.x:=a.r*sin(a.theta)*cos(a.psi);
result.y:=a.r*sin(a.theta)*sin(a.psi);
result.z:=a.r*cos(a.theta);
end;
class operator TVectorS.Implicit(a: TVectorS): TVectorC;
begin
result.x:=a.r*sin(a.theta)*cos(a.psi);
result.y:=a.r*sin(a.theta)*sin(a.psi);
result.z:=a.r*cos(a.theta);
end;
class operator TVectorS.Implicit(a: TVectorC): TVectorS;
begin
result.r:=a.r;
result.theta := arccos(a.z/result.r); // Use result.r instead of a.r, because
// a.r is calculated for each call.
// ArcTan2(Y,X) calculates ArcTan(Y/X), and returns an angle in the correct quadrant.
result.psi := arctan2(a.y,a.x);
end;
class operator TVectorS.Explicit(a: TVectorC): TVectorS;
begin
result.r:=sqrt(sqr(a.x)+sqr(a.y)+sqr(a.z));
result.theta := arccos(a.z/result.r);
// ArcTan2(Y,X) calculates ArcTan(Y/X), and returns an angle in the correct quadrant.
result.psi := arctan2(a.y,a.x);
end;
{ TVectorCyl }
{
class operator TVectorCyl.Explicit(a: TVectorCyl): TVectorS;
begin
result.r:=sqrt(sqr(a.r)+sqr(a.h));
result.psi:=a.psi;
result.theta:=arctan(a.r/a.h);
end;
class operator TVectorCyl.Implicit(a: TVectorCyl): TVectorS;
begin
result.r:=sqrt(sqr(a.r)+sqr(a.h));
result.psi:=a.psi;
result.theta:=arctan2(a.r,a.h);
end;
}
end.
|
unit LrIDEController;
interface
uses
SysUtils, Classes, ActnList, ImgList, Controls, Dialogs,
PngImageList,
LrDocument;
type
TLrIDEControllerModule = class(TDataModule)
ActionList: TActionList;
PngImageList: TPngImageList;
LrOpenAction: TAction;
LrNewAction: TAction;
LrSaveAction: TAction;
LrSaveAsAction: TAction;
LrCloseAction: TAction;
LrCloseAllAction: TAction;
SaveDialog: TSaveDialog;
OpenDialog: TOpenDialog;
LrSaveOrSaveAsAction: TAction;
procedure LrSaveActionUpdate(Sender: TObject);
procedure LrSaveActionExecute(Sender: TObject);
procedure LrSaveAsActionExecute(Sender: TObject);
procedure LrCloseActionExecute(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure LrOpenActionExecute(Sender: TObject);
procedure LrSaveAsActionUpdate(Sender: TObject);
procedure LrCloseAllActionExecute(Sender: TObject);
procedure LrCloseActionUpdate(Sender: TObject);
private
{ Private declarations }
FDocumentTypes: TStringList;
FNewActions: TList;
protected
function BuildFileFilter: string;
function CreateDocument(const inExt: string): TLrDocument;
function GetControllers(inIndex: Integer): TLrDocumentController;
function GetDocument: TLrDocument;
function GetNewActionsList: TList;
procedure CreateNewActions;
procedure DocumentChange(inSender: TObject);
procedure RegisterController(inController: TLrDocumentController);
public
{ Public declarations }
function CloseAllDocuments: Boolean;
function NewDocument(const inExt: string): TLrDocument;
procedure OpenDocument(const inFilename: string);
procedure RegisterDocument(inControllerClass: TLrDocumentControllerClass);
procedure SaveDocumentAs;
property Controllers[inIndex: Integer]: TLrDocumentController
read GetControllers;
property Document: TLrDocument read GetDocument;
property NewActionsList: TList read GetNewActionsList;
end;
var
LrIDEControllerModule: TLrIDEControllerModule;
implementation
uses
LrOpenDocumentsController;
{$R *.dfm}
procedure TLrIDEControllerModule.DataModuleCreate(Sender: TObject);
begin
FDocumentTypes := TStringList.Create;
LrOpenDocuments := TLrOpenDocumentsController.Create;
end;
procedure TLrIDEControllerModule.DataModuleDestroy(Sender: TObject);
begin
FDocumentTypes.Free;
end;
procedure TLrIDEControllerModule.RegisterController(
inController: TLrDocumentController);
begin
inController.OnChange := DocumentChange;
FDocumentTypes.AddObject(inController.GetExt, inController);
end;
procedure TLrIDEControllerModule.RegisterDocument(
inControllerClass: TLrDocumentControllerClass);
begin
RegisterController(inControllerClass.Create);
end;
function TLrIDEControllerModule.GetControllers(
inIndex: Integer): TLrDocumentController;
begin
Result := TLrDocumentController(FDocumentTypes.Objects[inIndex]);
end;
procedure TLrIDEControllerModule.CreateNewActions;
var
i: Integer;
a: TAction;
begin
FNewActions := TList.Create;
for i := 0 to Pred(FDocumentTypes.Count) do
begin
a := TAction.Create(Self);
a.Category := 'new';
a.Caption := 'New ' + Controllers[i].GetDescription;
a.Tag := i;
FNewActions.Add(a);
end;
end;
function TLrIDEControllerModule.GetNewActionsList: TList;
begin
if FNewActions = nil then
CreateNewActions;
Result := FNewActions;
end;
procedure TLrIDEControllerModule.DocumentChange(inSender: TObject);
begin
LrOpenDocuments.Change;
end;
function TLrIDEControllerModule.GetDocument: TLrDocument;
begin
Result := LrOpenDocuments.Current;
end;
function TLrIDEControllerModule.CreateDocument(
const inExt: string): TLrDocument;
var
i: Integer;
begin
i := FDocumentTypes.IndexOf(inExt);
if (i < 0) then
Result := nil
else
Result := Controllers[i].New;
end;
function TLrIDEControllerModule.NewDocument(const inExt: string): TLrDocument;
begin
Result := CreateDocument(inExt);
LrOpenDocuments.AddDocument(Result);
end;
procedure TLrIDEControllerModule.OpenDocument(const inFilename: string);
var
d: TLrDocument;
begin
d := CreateDocument(ExtractFileExt(inFilename));
if d <> nil then
begin
d.Open(inFilename);
LrOpenDocuments.AddDocument(d);
end;
end;
procedure TLrIDEControllerModule.SaveDocumentAs;
function GetSaveFilter: string;
begin
with Document.Controller do
Result := GetDescription + ' (*' + GetExt + ')|*' + GetExt + '|';
end;
begin
with SaveDialog do
begin
DefaultExt := Document.Controller.GetExt;
Filter := GetSaveFilter;
Filename := Document.Filename;
if Execute then
Document.SaveAs(Filename);
end;
end;
function TLrIDEControllerModule.CloseAllDocuments: Boolean;
begin
Result := LrOpenDocuments.CloseAll;
end;
function TLrIDEControllerModule.BuildFileFilter: string;
var
i: Integer;
e, exts: string;
begin
Result := '';
exts := '';
with FDocumentTypes do
for i := 0 to Pred(Count) do
begin
e := '*' + Strings[i];
if (exts <> '') then
exts := exts + ';';
exts := exts + e;
Result := Result + Format('%s (%s)|%1:s|',
[ Controllers[i].GetDescription, e ]);
end;
Result := Format('IDE Documents (%s)|%0:s|', [ exts ]) + Result;
end;
procedure TLrIDEControllerModule.LrOpenActionExecute(Sender: TObject);
begin
with OpenDialog do
begin
Filter := BuildFileFilter;
if Execute then
OpenDocument(Filename);
end;
end;
procedure TLrIDEControllerModule.LrSaveActionUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := Document.Modified;
end;
procedure TLrIDEControllerModule.LrSaveActionExecute(Sender: TObject);
begin
if Document.Untitled then
SaveDocumentAs
else
Document.Save;
end;
procedure TLrIDEControllerModule.LrSaveAsActionUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := true;
end;
procedure TLrIDEControllerModule.LrSaveAsActionExecute(Sender: TObject);
begin
SaveDocumentAs;
end;
procedure TLrIDEControllerModule.LrCloseActionUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := LrOpenDocuments.Count > 0;
end;
procedure TLrIDEControllerModule.LrCloseActionExecute(Sender: TObject);
begin
LrOpenDocuments.CloseCurrent;
end;
procedure TLrIDEControllerModule.LrCloseAllActionExecute(Sender: TObject);
begin
CloseAllDocuments;
end;
end.
|
// ***************************************************************************
//
// cfs.GCharts: Google Chart Producer
// cfsCharts is a Delphi library of components to generate Charts in uniGUI Framework using the Google Charts API
//
// Copyright (c) 2021 Josep Pagès
//
// https://github.com/JosepPages7/Delphi-GCharts
//
//
// ***************************************************************************
//
// 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 cfs.GCharts;
interface
uses
System.SysUtils,
System.Classes,
System.Variants,
Generics.Collections,
Data.DB;
type
TcfsJSCode = string;
TcfsGChartDataType = (gcdtString, gcdtNumber, gcdtBoolean, gcdtDate, gcdtDateTime, gcdtTimeOfDay);
TcfsGChartDataCol = record
private
public
const ROLE_ANOTATION = 'annotation';
const ROLE_ANOTATION_TEXT = 'annotationText';
const ROLE_CERTAINTY = 'certainty';
const ROLE_EMPHASIS = 'emphasis';
const ROLE_INTERVAL = 'interval';
const ROLE_SCOPE = 'scope';
const ROLE_STYLE = 'style';
const ROLE_TOOLTIP = 'tooltip';
const ROLE_DOMAIN = 'domain';
public
Id: string;
DataType: TcfsGChartDataType;
DisplayLabel: string;
Role: string;
class function Create(const DataType: TcfsGChartDataType; const DisplayLabel: string = ''; const Role: string = ''; const Id: string = ''): TcfsGChartDataCol; static;
end;
TcfsGChartData = class;
IcfsGChartData = interface
['{3B9A70D3-08F7-4BEA-8D91-A74EF6436C5B}']
procedure Clear;
procedure BeginDefineColumns;
procedure EndDefineColumns;
procedure DefineColumns(const Columns: array of TcfsGChartDataCol);
procedure AssignFromDataSet(SourceDataSet: TDataSet);
procedure Assign(Source: TcfsGChartData); overload;
procedure Assign(Source: IcfsGChartData); overload;
procedure AddColum(Col: TcfsGChartDataCol); overload;
procedure AddColum(const DataType: TcfsGChartDataType; const DisplayLabel: string = ''; const Role: string = ''; const Id: string = ''); overload;
procedure AddRow(const Values: TArray<Variant>); overload;
procedure AddRow; overload;
procedure SetValue(const ColIndex: Integer; Value: Variant; const FormattedValue: string = ''); overload;
function GetValue(const RowIndex, ColIndex: Integer): Variant;
function GetFormatedValue(const RowIndex, ColIndex: Integer): Variant;
function ToJSDataTable: TcfsJSCode;
function GetColumns: TList<TcfsGChartDataCol>;
property Columns: TList<TcfsGChartDataCol> read GetColumns;
end;
TcfsGChartDataRow = class
private
FValues: TList<Variant>;
FFormatedValues: TList<Variant>;
public
constructor Create;
destructor Destroy; override;
property Values: TList<Variant> read FValues;
property FormatedValues: TList<Variant> read FFormatedValues;
end;
TcfsGChartData = class(TInterfacedObject, IcfsGChartData)
strict private
FData: TObjectList<TcfsGChartDataRow>;
FColumns: TList<TcfsGChartDataCol>;
FDefiningColumns: Boolean;
function GetColumns: TList<TcfsGChartDataCol>;
procedure CheckRowIndex(RowIndex: Integer);
procedure CheckColIndex(ColIndex: Integer);
procedure CheckDataSetActive;
procedure CreateInternalData;
function AddInternalDataRow: TcfsGChartDataRow;
protected
const JS_TRUE = 'true';
const JS_FALSE = 'false';
private
protected
class function VariantIsNull(const Value: Variant): Boolean; static;
class function BooleanToJS(const Value: Boolean): TcfsJSCode; static;
class function DateToJS(Value: TDate): TcfsJSCode; static;
class function DateTimeToJS(Value: TDateTime): TcfsJSCode; static;
class function NumberToJS(Value: Extended): TcfsJSCode; static;
class function StringToQuotedJS(const Value: string): TcfsJSCode; static;
class function StringToUnquotedJS(const Value: string): TcfsJSCode; static;
class function TimeToJS(Value: TDateTime): TcfsJSCode; static;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure BeginDefineColumns;
procedure EndDefineColumns;
procedure DefineColumns(const Columns: array of TcfsGChartDataCol);
procedure AssignFromDataSet(SourceDataSet: TDataSet);
procedure Assign(Source: TcfsGChartData); overload;
procedure Assign(Source: IcfsGChartData); overload;
procedure AddColum(Col: TcfsGChartDataCol); overload;
procedure AddColum(const DataType: TcfsGChartDataType; const DisplayLabel: string= ''; const Role: string = ''; const Id: string = ''); overload;
procedure AddRowValues(const Values: TArray<Variant>); overload;
procedure AddRow(const Values: TArray<Variant>); overload;
procedure AddRow; overload;
procedure SetValue(const ColIndex: Integer; Value: Variant; const FormattedValue: string = '');
function GetValue(const RowIndex, ColIndex: Integer): Variant;
function GetFormatedValue(const RowIndex, ColIndex: Integer): Variant;
function ToJSDataTable: TcfsJSCode;
property Columns: TList<TcfsGChartDataCol> read GetColumns;
end;
TcfsGChartOptions = class
strict private
FOptionsList: TStringList;
function VariantToStr(const OptionName: string; const Value: Variant): string;
class procedure RemoveLastComma(var Value: string); static;
public
constructor Create;
destructor Destroy; override;
class function TextStyleToJSObject(const Color: string; const FontSize: Integer; Bold: Boolean; Italic: Boolean; const FontName: string = '';
const AuraColor: string = ''; const Opacity: Extended = 1): TcfsJSCode; static;
class function ArrayOfStringToJS(const Values: TArray<TcfsJSCode>): TcfsJSCode; static;
class function ArrayOfStringToJSArrayOfObjects(const Values: TArray<TcfsJSCode>): TcfsJSCode; static;
class function ArrayOfStringToJSObjectWithNestedObjects(const Values: TArray<TcfsJSCode>): TcfsJSCode; static;
function ToJSCode: TcfsJSCode;
procedure Clear;
procedure SetAsUnquotedStr(const Name, Value: string);
procedure SetAsQuotedStr(const Name, Value: string);
procedure SetAsFloat(const Name: string; Value: Extended);
procedure SetAsInteger(const Name: string; Value: Integer);
procedure SetAsBoolean(const Name: string; Value: Boolean);
procedure SetAsVariant(const Name: string; const Value: Variant);
procedure SetAsJSCode(const Name: string; JSCode: TcfsJSCode);
procedure SetAsObject(const ObjectName, OptionName, Value: string);
procedure SetAsArrayOfStrings(const ObjectName: string; Values: TArray<TcfsJSCode>);
procedure SetAsArrayOfJSCode(const ObjectName: string; Values: TArray<TcfsJSCode>);
procedure SetAsArrayOfObjects(const ObjectName: string; Values: TArray<TcfsJSCode>);
procedure SetAsObjectWithNestedObjects(const ObjectName: string; Values: TArray<TcfsJSCode>);
procedure AllowHtml(const Value: Boolean);
procedure Animation(const SubOptionName: string; const Value: Variant);
procedure Annotations(const SubOptionName: string; const Value: Variant);
procedure Axes(const SubOptionName: string; const Value: Variant);
procedure Bar(const SubOptionName: string; const Value: Variant);
procedure BoxStyle(const SubOptionName: string; const Value: Variant);
procedure Bubble(const SubOptionName: string; const Value: Variant);
procedure BackgroundColor(const Value: string); overload;
procedure BackgroundColor(const SubOptionName: string; const Value: Variant); overload;
procedure Calendar(const SubOptionName: string; const Value: Variant);
procedure Candlestick(const SubOptionName: string; const Value: Variant);
procedure ChartArea(const SubOptionName: string; const Value: Variant);
procedure ColorAxis(const SubOptionName: string; const Value: Variant);
procedure Colors(const Values: TArray<string>);
procedure Crosshair(const SubOptionName: string; const Value: Variant);
procedure CurveType(const Value: string);
procedure DefaultColor(const Value: string);
procedure DatalessRegionColor(const Value: string);
procedure DataOpacity(const Value: Extended);
procedure Diff(const SubOptionName: string; const Value: Variant);
procedure DisplayAnnotations(const Value: Boolean);
procedure DisplayMode(const Value: string);
procedure DateFormat(const Value: string);
procedure EnableInteractivity(const Value: Boolean);
procedure FontName(const Value: string);
procedure FontSize(const Value: Word);
procedure Gantt(const SubOptionName: string; const Value: Variant);
procedure HAxis(const SubOptionName: string; const Value: Variant);
procedure Height(const Value: Variant);
procedure Histogram(const SubOptionName: string; const Value: Variant);
procedure Interval(const SubOptionName: string; const Value: Variant);
procedure Intervals(const SubOptionName: string; const Value: Variant);
procedure InterpolateNulls(Value: Variant);
procedure Is3D(const Value: Boolean);
procedure IsStacked(const Value: Boolean); overload;
procedure IsStacked(const Value: string); overload;
procedure Legend(const SubOptionName: string; const Value: Variant);
procedure LineWidth(const Value: Extended);
procedure NoDataPattern(const SubOptionName: string; const Value: Variant);
procedure PieHole(const Value: Extended);
procedure PieSliceText(const Value: string);
procedure PieSliceTextStyle(const Value: Variant);
procedure PieStartAngle(const Value: Extended);
procedure PointShape(const Value: string);
procedure PointSize(const Value: Integer);
procedure Region(const Value: string);
procedure RedFrom(const Value: Integer);
procedure RedTo(const Value: Integer);
procedure YellowFrom(const Value: Integer);
procedure YellowTo(const Value: Integer);
procedure MinorTicks(const Value: Integer);
procedure Series(const Values: TArray<TcfsJSCode>);
procedure SeriesType(const Value: string);
procedure SizeAxis(const SubOptionName: string; const Value: Variant);
procedure Slices(const Values: TArray<TcfsJSCode>);
procedure Subtitle(const Value: string);
procedure Title(const Value: string);
procedure TitleTextStyle(const Value: Variant);
procedure TrendLines(const Values: TArray<TcfsJSCode>);
procedure Timeline(const SubOptionName: string; const Value: Variant);
procedure Tooltip(const SubOptionName: string; const Value: Variant);
procedure VAxes(const Values: TArray<TcfsJSCode>);
procedure VAxis(const SubOptionName: string; const Value: Variant);
procedure Width(const Value: Variant);
end;
IcfsGChartProducer = interface
['{A7141427-7308-458F-A1D0-228CA38E1C5F}']
function GenerateJSCode(const ChartId: string; AddSelectEvent: Boolean = False; const JSAjaxRequest: string = ''; const JSName: string = ''): TcfsJSCode;
function GetClassChartType: string;
function GetData: TcfsGChartData;
function GetOldData: TcfsGChartData;
function GetOptions: TcfsGChartOptions;
function GetLibraryLanguage: string;
function GetLibraryMapsApiKey: string;
function GetLibraryPackage: string;
function GetLibrarySafeLoad: Boolean;
function GetLibraryVersion: string;
function GetScripCodeAfterCallDraw: string;
function GetScripCodeBeforeCallDraw: string;
procedure SetScripCodeAfterCallDraw(const Value: string);
procedure SetScripCodeBeforeCallDraw(const Value: string);
procedure SetLibraryLanguage(const Value: string);
procedure SetLibraryMapsApiKey(const Value: string);
procedure SetLibraryPackage(const Value: string);
procedure SetLibrarySafeLoad(const Value: Boolean);
procedure SetLibraryVersion(const Value: string);
procedure SetClassChartType(const Value: string);
property ClassChartType: string read GetClassChartType write SetClassChartType;
property Data: TcfsGChartData read GetData;
property OldData: TcfsGChartData read GetOldData;
property LibraryVersion: string read GetLibraryVersion write SetLibraryVersion;
property LibraryPackage: string read GetLibraryPackage write SetLibraryPackage;
property LibraryLanguage: string read GetLibraryLanguage write SetLibraryLanguage;
property LibraryMapsApiKey: string read GetLibraryMapsApiKey write SetLibraryMapsApiKey;
property LibrarySafeLoad: Boolean read GetLibrarySafeLoad write SetLibrarySafeLoad;
property ScripCodeBeforeCallDraw: string read GetScripCodeBeforeCallDraw write SetScripCodeBeforeCallDraw;
property ScripCodeAfterCallDraw: string read GetScripCodeAfterCallDraw write SetScripCodeAfterCallDraw;
property Options: TcfsGChartOptions read GetOptions;
end;
TcfsGChartProducer = class(TInterfacedObject, IcfsGChartProducer)
strict private
FClassChartType: string;
FData: TcfsGChartData;
FOldData: TcfsGChartData;
FOptions: TcfsGChartOptions;
FLibraryPackage: string;
FLibraryLanguage: string;
FLibraryVersion: string;
FLibraryMapsApiKey: string;
FLibrarySafeLoad: Boolean;
FScripCodeAfterCallDraw: string;
FScripCodeBeforeCallDraw: string;
function GetClassChartType: string;
function GetData: TcfsGChartData;
function GetOptions: TcfsGChartOptions;
procedure SetClassChartType(const Value: string);
function GetOldData: TcfsGChartData;
function GetLibraryLanguage: string;
function GetLibraryMapsApiKey: string;
function GetLibraryPackage: string;
function GetLibrarySafeLoad: Boolean;
function GetLibraryVersion: string;
function GetScripCodeAfterCallDraw: string;
function GetScripCodeBeforeCallDraw: string;
procedure SetLibraryLanguage(const Value: string);
procedure SetLibraryMapsApiKey(const Value: string);
procedure SetLibraryPackage(const Value: string);
procedure SetLibrarySafeLoad(const Value: Boolean);
procedure SetLibraryVersion(const Value: string);
procedure SetScripCodeAfterCallDraw(const Value: string);
procedure SetScripCodeBeforeCallDraw(const Value: string);
protected
public
const PREFIX_DRAW_CHART_FUNCTION_NAME = 'draw';
const LIBRARY_VERSION_CURRENT = 'current';
const LIBRARY_VERSION_UPCOMING = 'upcoming';
const CLASS_ANNOTATION_CHART = 'AnnotationChart';
const CLASS_AREA_CHART = 'AreaChart';
const CLASS_BAR_CHART = 'BarChart';
const CLASS_MATERIAL_BAR_CHART = 'Bar';
const CLASS_COLUMN_CHART = 'ColumnChart';
const CLASS_MATERIAL_COLUMN_CHART = 'Column';
const CLASS_CALENDAR_CHART = 'Calendar';
const CLASS_BUBBLE_CHART = 'BubbleChart';
const CLASS_CANDLESTICK_CHART = 'CandlestickChart';
const CLASS_COMBO_CHART = 'ComboChart';
const CLASS_GANTT_CHART = 'Gantt';
const CLASS_GAUGE_CHART = 'Gauge';
const CLASS_GEO_CHART = 'GeoChart';
const CLASS_HISTOGRAM_CHART = 'Histogram';
const CLASS_LINE_CHART = 'LineChart';
const CLASS_MATERIAL_LINE_CHART = 'Line';
const CLASS_ORG_CHART = 'OrgChart';
const CLASS_PIE_CHART = 'PieChart';
const CLASS_SANKEY_CHART = 'Sankey';
const CLASS_SCATTER_CHART = 'ScatterChart';
const CLASS_MATERIAL_SCATTER_CHART = 'Scatter';
const CLASS_STEPPED_AREA_CHART = 'SteppedAreaChart';
const CLASS_TABLE_CHART = 'Table';
const CLASS_TIMELINE_CHART = 'Timeline';
const CLASS_TREE_MAP_CHART = 'TreeMap';
const CLASS_WORD_TREE_CHART = 'WordTree';
const PACKAGE_ANNOTATION_CHART = 'annotationchart';
const PACKAGE_CORE_CHART = 'corechart';
const PACKAGE_MATERIAL_BAR ='bar';
const PACKAGE_CALENDAR = 'calendar';
const PACKAGE_GANTT = 'gantt';
const PACKAGE_GAUGE = 'gauge';
const PACKAGE_GEO_CHART = 'geochart';
const PACKAGE_SANKEY = 'sankey';
const PACKAGE_MATERIAL_LINE = 'line';
const PACKAGE_ORG_CHART = 'orgchart';
const PACKAGE_MATERIAL_SCATTER = 'scatter';
const PACKAGE_TABLE = 'table';
const PACKAGE_TIMELINE = 'timeline';
const PACKAGE_TREE_MAP = 'treemap';
const PACKAGE_WORD_TREE = 'wordtree';
public
constructor Create;
destructor Destroy; override;
function GenerateJSCode(const ChartId: string; AddSelectEvent: Boolean = False; const JSAjaxRequest: string = ''; const JSName: string = ''): TcfsJSCode;
property ClassChartType: string read GetClassChartType write SetClassChartType;
property Data: TcfsGChartData read GetData;
property OldData: TcfsGChartData read GetOldData;
property LibraryVersion: string read GetLibraryVersion write SetLibraryVersion;
property LibraryPackage: string read GetLibraryPackage write SetLibraryPackage;
property LibraryLanguage: string read GetLibraryLanguage write SetLibraryLanguage;
property LibrarySafeLoad: Boolean read GetLibrarySafeLoad write SetLibrarySafeLoad;
property LibraryMapsApiKey: string read GetLibraryMapsApiKey write SetLibraryMapsApiKey;
property Options: TcfsGChartOptions read GetOptions;
property ScripCodeBeforeCallDraw: string read GetScripCodeBeforeCallDraw write SetScripCodeBeforeCallDraw;
property ScripCodeAfterCallDraw: string read GetScripCodeAfterCallDraw write SetScripCodeAfterCallDraw;
end;
implementation
uses
System.DateUtils;
type
TGChartPackageAndType = record
ClassChartType: string;
Package: string;
MaterialDesign: Boolean;
end;
const
GChartPackagesAndTypes : array[0..25] of TGChartPackageAndType =
(
(ClassChartType: TcfsGChartProducer.CLASS_AREA_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_BAR_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_COLUMN_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_LINE_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_PIE_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_SCATTER_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_MATERIAL_BAR_CHART; Package: TcfsGChartProducer.PACKAGE_MATERIAL_BAR; MaterialDesign: True),
(ClassChartType: TcfsGChartProducer.CLASS_MATERIAL_COLUMN_CHART; Package: TcfsGChartProducer.PACKAGE_MATERIAL_BAR; MaterialDesign: True),
(ClassChartType: TcfsGChartProducer.CLASS_MATERIAL_SCATTER_CHART; Package: TcfsGChartProducer.PACKAGE_MATERIAL_SCATTER; MaterialDesign: True),
(ClassChartType: TcfsGChartProducer.CLASS_MATERIAL_LINE_CHART; Package: TcfsGChartProducer.PACKAGE_MATERIAL_LINE; MaterialDesign: True),
(ClassChartType: TcfsGChartProducer.CLASS_BUBBLE_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_CANDLESTICK_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_COMBO_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_HISTOGRAM_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_STEPPED_AREA_CHART; Package: TcfsGChartProducer.PACKAGE_CORE_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_ANNOTATION_CHART; Package: TcfsGChartProducer.PACKAGE_ANNOTATION_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_CALENDAR_CHART; Package: TcfsGChartProducer.PACKAGE_CALENDAR; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_GANTT_CHART; Package: TcfsGChartProducer.PACKAGE_GANTT; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_GAUGE_CHART; Package: TcfsGChartProducer.PACKAGE_GAUGE; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_GEO_CHART; Package: TcfsGChartProducer.PACKAGE_GEO_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_ORG_CHART; Package: TcfsGChartProducer.PACKAGE_ORG_CHART; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_TABLE_CHART; Package: TcfsGChartProducer.PACKAGE_TABLE; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_TIMELINE_CHART; Package: TcfsGChartProducer.PACKAGE_TIMELINE; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_TREE_MAP_CHART; Package: TcfsGChartProducer.PACKAGE_TREE_MAP; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_SANKEY_CHART; Package: TcfsGChartProducer.PACKAGE_SANKEY; MaterialDesign: False),
(ClassChartType: TcfsGChartProducer.CLASS_WORD_TREE_CHART; Package: TcfsGChartProducer.PACKAGE_WORD_TREE; MaterialDesign: False)
) ;
{ TcfsGChartDataCol }
class function TcfsGChartDataCol.Create(const DataType: TcfsGChartDataType; const DisplayLabel: string = ''; const Role: string = ''; const Id: string = ''): TcfsGChartDataCol;
begin
Result.Id := Id.Trim;
Result.DataType := DataType;
Result.DisplayLabel := DisplayLabel;
Result.Role := Role.Trim;
end;
{ TcfsGChartDataRow }
constructor TcfsGChartDataRow.Create;
begin
FValues := TList<Variant>.Create;
FFormatedValues := TList<Variant>.Create;
end;
destructor TcfsGChartDataRow.Destroy;
begin
FValues.Free;
FFormatedValues.Free;
inherited;
end;
{ TcfsGChartData }
constructor TcfsGChartData.Create;
begin
FColumns := TList<TcfsGChartDataCol>.Create;
FData := TObjectList<TcfsGChartDataRow>.Create;
end;
destructor TcfsGChartData.Destroy;
begin
FColumns.Free;
FData.Free;
inherited;
end;
procedure TcfsGChartData.Clear;
begin
FColumns.Clear;
FData.Clear;
end;
procedure TcfsGChartData.BeginDefineColumns;
begin
Clear;
FDefiningColumns := True;
end;
procedure TcfsGChartData.EndDefineColumns;
begin
FDefiningColumns := False;
CreateInternalData;
end;
class function TcfsGChartData.BooleanToJS(const Value: Boolean): TcfsJSCode;
begin
if Value then
Result := JS_TRUE
else
Result := JS_FALSE;
end;
class function TcfsGChartData.NumberToJS(Value: Extended): string;
function FormatSettingsJSNumeric: TFormatSettings;
begin
Result.ThousandSeparator := ',';
Result.DecimalSeparator := '.';
Result.NegCurrFormat := 0;
end;
begin
Result := Format('%g', [Value], FormatSettingsJSNumeric);
end;
procedure TcfsGChartData.DefineColumns(const Columns: array of TcfsGChartDataCol);
var
Col: TcfsGChartDataCol;
begin
Clear;
for Col in Columns do
FColumns.Add(Col);
EndDefineColumns;
end;
procedure TcfsGChartData.AddColum(Col: TcfsGChartDataCol);
begin
if not FDefiningColumns then
raise Exception.Create(ClassName + ': Not in DefiningColumns State');
FColumns.Add(Col);
end;
procedure TcfsGChartData.AddColum(const DataType: TcfsGChartDataType; const DisplayLabel: string = ''; const Role: string = ''; const Id: string = '');
var
Col: TcfsGChartDataCol;
begin
Col.Id := Id.Trim;
Col.DataType := DataType;
Col.DisplayLabel := DisplayLabel;
Col.Role := Role.Trim;
AddColum(Col);
end;
function TcfsGChartData.GetColumns: TList<TcfsGChartDataCol>;
begin
Result := FColumns;
end;
function TcfsGChartData.GetFormatedValue(const RowIndex, ColIndex: Integer): Variant;
begin
CheckRowIndex(RowIndex);
CheckColIndex(ColIndex);
Result := FData[RowIndex].FValues[ColIndex];
end;
function TcfsGChartData.GetValue(const RowIndex, ColIndex: Integer): Variant;
begin
CheckRowIndex(RowIndex);
CheckColIndex(ColIndex);
Result := FData[RowIndex].FFormatedValues[ColIndex];
end;
class function TcfsGChartData.DateToJS(Value: TDate): string;
var
yy, mm, dd: Word;
begin
// JavaScript Date object (zero-based month)
DecodeDate(Value, yy, mm, dd);
Result := Format('new Date(%d,%d,%d)', [yy, mm-1, dd]);
end;
class function TcfsGChartData.DateTimeToJS(Value: TDateTime): string;
var
yy, mm, dd, hh, nn, ss, ms: Word;
begin
// JavaScript DateTime object (zero-based month)
if TimeOf(Value) = 0 then // no Time
Result := DateToJS(Value)
else if DateOf(Value) = 0 then // no Date
begin
DecodeDateTime(Value, yy, mm, dd, hh, nn, ss, ms);
Result := Format('new Date(0,0,0,%d,%d,%d)', [hh, nn, ss]);
end
else
begin
DecodeDateTime(Value, yy, mm, dd, hh, nn, ss, ms);
Result := Format('new Date(%d,%d,%d,%d,%d,%d)', [yy, mm-1, dd, hh, nn, ss]);
end;
end;
class function TcfsGChartData.TimeToJS(Value: TDateTime): string;
var
hh, nn, ss, ms: Word;
begin
DecodeTime(Value,hh, nn, ss, ms);
Result := Format('[%d,%d,%d,%d]', [hh, nn, ss, ms]);
end;
class function TcfsGChartData.VariantIsNull(const Value: Variant): Boolean;
begin
Result := VarIsClear(Value) or VarIsNull(Value) or (VarCompareValue(Value, Unassigned) = vrEqual);
end;
function TcfsGChartData.ToJSDataTable: TcfsJSCode;
function GetDataType(DataType: TcfsGChartDataType): string;
begin
case DataType of
gcdtNumber: Result := 'number';
gcdtBoolean: Result := 'boolean';
gcdtDate: Result := 'date';
gcdtDateTime: Result := 'datetime';
gcdtTimeOfDay: Result := 'timeofday';
else
Result := 'string';
end;
end;
function VariantToStr(DataType: TcfsGChartDataType; const Value: Variant): TcfsJSCode;
begin
Result := '';
if VariantIsNull(Value) then
Exit;
case DataType of
gcdtString: Result := StringToQuotedJS(Value);
gcdtNumber: Result := NumberToJS(Value);
gcdtBoolean: Result := BooleanToJS(Value);
gcdtDate: Result := DateTimeToJS(Value);
gcdtDateTime: Result := DateTimeToJS(Value);
gcdtTimeOfDay: Result := TimeToJS(Value);
end;
end;
var
I: Integer;
DataTable: TStringBuilder;
Row: TcfsGChartDataRow;
Col: TcfsGChartDataCol;
begin
CheckDataSetActive;
DataTable := TStringBuilder.Create;
try
// Titles Row
DataTable.Append('[');
for I := 0 to FColumns.Count -1 do
begin
if I > 0 then
DataTable.Append(',');
Col := FColumns[I];
if Col.DisplayLabel.Trim.IsEmpty and Col.Id.IsEmpty and Col.Role.IsEmpty then
DataTable.Append(Format('{type: %s}', [QuotedStr(GetDataType(Col.DataType))]))
else if Col.Role.IsEmpty and Col.Id.IsEmpty then
DataTable.Append(Format('{label: %s, type: %s}', [TcfsGChartData.StringToQuotedJS(Col.DisplayLabel), QuotedStr(GetDataType(Col.DataType)) ]))
else
DataTable.Append(Format('{label: %s, id: %s, type: %s, role: %s}', [TcfsGChartData.StringToQuotedJS(Col.DisplayLabel), TcfsGChartData.StringToQuotedJS(Col.Id), QuotedStr(GetDataType(Col.DataType)),
QuotedStr(Col.Role) ]));
end;
DataTable.Append(']');
// Data Rows
for Row in FData do
begin
DataTable.Append(',[');
for I := 0 to FColumns.Count -1 do
begin
if I > 0 then
DataTable.Append(',');
Col := FColumns[I];
if VariantIsNull(Row.FValues[I]) then
DataTable.Append('null')
else
begin
if not VariantIsNull(Row.FormatedValues[I]) and (Row.FormatedValues[I] <> '') then
DataTable.Append(Format('{v: %s, f: %s}', [VariantToStr(Col.DataType, Row.FValues[I]), TcfsGChartData.StringToQuotedJS(Row.FormatedValues[I]) ]))
else
DataTable.Append(VariantToStr(Col.DataType, Row.FValues[I]))
end;
end;
DataTable.Append(']');
end;
Result := DataTable.ToString;
finally
DataTable.Free;
end;
end;
procedure TcfsGChartData.AssignFromDataSet(SourceDataSet: TDataSet);
function GetDataType(Field: TField): TcfsGChartDataType;
begin
if Field is TNumericField then
Result := TcfsGChartDataType.gcdtNumber
else if ( (Field is TDateField) ) then
Result := TcfsGChartDataType.gcdtDate
else if ( (Field is TDateTimeField) or (Field is TSQLTimeStampField) ) then
Result := TcfsGChartDataType.gcdtDateTime
else if (Field is TBooleanField) then
Result := TcfsGChartDataType.gcdtBoolean
else if (Field is TTimeField) then
Result := TcfsGChartDataType.gcdtTimeOfDay
else
Result := TcfsGChartDataType.gcdtString;
end;
var
I: Integer;
F: TField;
Col: TcfsGChartDataCol;
begin
if not Assigned(SourceDataSet) then
raise Exception.Create(ClassName + ': SourceDataSet is nil');
if not SourceDataSet.Active then
raise Exception.Create(ClassName + ': SourceDataSet is not Active');
Clear;
// Create Columns
for F in SourceDataSet.Fields do
begin
Col := TcfsGChartDataCol.Create(GetDataType(F), F.DisplayLabel);
FColumns.Add(Col);
end;
CreateInternalData;
// Copy Data
SourceDataSet.DisableControls;
try
SourceDataSet.First;
while not SourceDataSet.eof do
begin
AddInternalDataRow;
for I := 0 to SourceDataSet.FieldCount - 1 do
SetValue(I, SourceDataSet.Fields[I].Value, SourceDataSet.Fields[I].DisplayText);
SourceDataSet.Next;
end;
finally
SourceDataSet.EnableControls;
end;
end;
procedure TcfsGChartData.CreateInternalData;
begin
FData.Clear;
end;
procedure TcfsGChartData.AddRow(const Values: TArray<Variant>);
begin
AddRowValues(Values);
end;
procedure TcfsGChartData.AddRow;
begin
CheckDataSetActive;
AddRowValues([]);
end;
function TcfsGChartData.AddInternalDataRow: TcfsGChartDataRow;
var
I: Integer;
begin
CheckDataSetActive;
Result := TcfsGChartDataRow.Create;
FData.Add(Result);
for I := 0 to FColumns.Count -1 do
begin
Result.FValues.Add(Null);
Result.FormatedValues.Add(Null);
end;
end;
procedure TcfsGChartData.AddRowValues(const Values: TArray<Variant>);
var
R: TcfsGChartDataRow;
V: Variant;
ColIndex: Integer;
begin
R := AddInternalDataRow;
ColIndex := 0;
for V in Values do
begin
CheckColIndex(ColIndex);
R.FValues[ColIndex] := V;
Inc(ColIndex);
end;
end;
procedure TcfsGChartData.Assign(Source: IcfsGChartData);
begin
Assign(Source as TcfsGChartData);
end;
procedure TcfsGChartData.Assign(Source: TcfsGChartData);
var
I: Integer;
Sour: TcfsGChartDataCol;
Dest: TcfsGChartDataCol;
DestRow: TcfsGChartDataRow;
SourRow: TcfsGChartDataRow;
begin
if (Source = nil) or (Source = Self) then
raise Exception.Create(ClassName + ': Assign Error');
Clear;
BeginDefineColumns;
for Sour in Source.Columns do
begin
Dest := TcfsGChartDataCol.Create(Sour.DataType, Sour.DisplayLabel, Sour.Role, Sour.Id);
AddColum(Dest);
end;
EndDefineColumns;
// Copy Source Data
for SourRow in Source.FData do
begin
DestRow := AddInternalDataRow;
for I := 0 to Source.Columns.Count - 1 do
begin
DestRow.Values[I] := SourRow.Values[I];
if not VariantIsNull(SourRow.FormatedValues[I]) then
DestRow.FormatedValues[I] := SourRow.FormatedValues[I];
end;
end;
end;
procedure TcfsGChartData.CheckColIndex(ColIndex: Integer);
begin
if (ColIndex < 0) or (ColIndex > FColumns.Count -1) then
raise Exception.Create(ClassName + ': ColIndex out range');
end;
procedure TcfsGChartData.CheckDataSetActive;
begin
if FDefiningColumns then
raise Exception.Create(ClassName + ': DefiningColumns State is Active. Please call "EndDefineColumns" procedure to Add Data');
if FColumns.Count = 0 then
raise Exception.Create(ClassName + ': Has not Columns');
end;
procedure TcfsGChartData.CheckRowIndex(RowIndex: Integer);
begin
if (RowIndex < 0) or (RowIndex > FData.Count - 1) then
raise Exception.Create(ClassName + ': RowIndex out range');
end;
procedure TcfsGChartData.SetValue(const ColIndex: Integer; Value: Variant; const FormattedValue: string = '');
var
R: TcfsGChartDataRow;
begin
CheckColIndex(ColIndex);
CheckDataSetActive;
if FData.Count = 0 then
raise Exception.Create(ClassName + ': Has not Active Row');
R := FData[FData.Count - 1];
R.FValues[ColIndex] := Value;
if not FormattedValue.IsEmpty then
R.FFormatedValues[ColIndex] := FormattedValue;
end;
class function TcfsGChartData.StringToQuotedJS(const Value: string): TcfsJSCode;
const
SINGLE_QUOTE = '''';
begin
Result := SINGLE_QUOTE + StringReplace(Value, SINGLE_QUOTE, '\' + SINGLE_QUOTE, [rfReplaceAll]) + SINGLE_QUOTE;
end;
class function TcfsGChartData.StringToUnquotedJS(const Value: string): TcfsJSCode;
begin
Result := TcfsGChartData.StringToUnquotedJS(Value);
end;
{ TcfsGChartOptions }
constructor TcfsGChartOptions.Create;
begin
FOptionsList := TStringList.Create;
FOptionsList.Duplicates := TDuplicates.dupError;
FOptionsList.CaseSensitive := False;
FOptionsList.Sorted := False;
end;
destructor TcfsGChartOptions.Destroy;
begin
FOptionsList.Free;
inherited;
end;
procedure TcfsGChartOptions.Clear;
begin
FOptionsList.Clear;
end;
function TcfsGChartOptions.ToJSCode: TcfsJSCode;
var
I, Count: Integer;
N, V: string;
SB: TStringBuilder;
IsObject: Boolean;
begin
Result := '';
if FOptionsList.Count = 0 then
Exit;
SB := TStringBuilder.Create;
try
Count := 0;
for I := 0 to FOptionsList.Count - 1 do
begin
V := FOptionsList.ValueFromIndex[I];
if not V.IsEmpty then
begin
if Count > 0 then
SB.Append(',');
IsObject := False;
N := FOptionsList.Names[I];
if N.StartsWith('{') then
IsObject := True;
if IsObject then
SB.Append(Copy(N, 2) + ':{' + V + '}')
else
SB.Append(N + ':' + V);
Inc(Count);
end;
end;
Result := SB.ToString;
finally
SB.Free;
end;
end;
procedure TcfsGChartOptions.CurveType(const Value: string);
begin
SetAsQuotedStr('curveType', Value);
end;
procedure TcfsGChartOptions.DefaultColor(const Value: string);
begin
SetAsQuotedStr('defaultColor', Value);
end;
procedure TcfsGChartOptions.DatalessRegionColor(const Value: string);
begin
SetAsQuotedStr('datalessRegionColor', Value);
end;
procedure TcfsGChartOptions.DataOpacity(const Value: Extended);
begin
SetAsFloat('dataOpacity', Value);
end;
procedure TcfsGChartOptions.SetAsUnquotedStr(const Name, Value: string);
begin
SetAsJSCode(Name, Value);
end;
procedure TcfsGChartOptions.SetAsQuotedStr(const Name, Value: string);
begin
SetAsJSCode(Name, TcfsGChartData.StringToQuotedJS(Value));
end;
procedure TcfsGChartOptions.SizeAxis(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('sizeAxis', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.SetAsFloat(const Name: string; Value: Extended);
begin
SetAsJSCode(Name, TcfsGChartData.NumberToJS(Value));
end;
procedure TcfsGChartOptions.SetAsInteger(const Name: string; Value: Integer);
begin
SetAsJSCode(Name, Value.ToString);
end;
procedure TcfsGChartOptions.Series(const Values: TArray<TcfsJSCode>);
begin
SetAsArrayOfJSCode('series', Values);
end;
procedure TcfsGChartOptions.SeriesType(const Value: string);
begin
SetAsQuotedStr('seriesType', Value);
end;
procedure TcfsGChartOptions.DateFormat(const Value: string);
begin
SetAsQuotedStr('dateFormat', Value);
end;
procedure TcfsGChartOptions.SetAsArrayOfStrings(const ObjectName: string; Values: TArray<TcfsJSCode>);
begin
SetAsJSCode(ObjectName, ArrayOfStringToJS(Values));
end;
procedure TcfsGChartOptions.SetAsArrayOfJSCode(const ObjectName: string; Values: TArray<TcfsJSCode>);
begin
if High(Values) < 0 then
Exit;
if (Values[0].Trim <> '') and CharInSet(Values[0].TrimLeft[1], ['0'..'9']) then // Check if first chart is númeric so I interpret that is and object with nested objects
SetAsObjectWithNestedObjects(ObjectName, Values)
else // is an array of objects
SetAsArrayOfObjects(ObjectName, Values);
end;
procedure TcfsGChartOptions.SetAsArrayOfObjects(const ObjectName: string; Values: TArray<TcfsJSCode>);
begin
SetAsJSCode(ObjectName, ArrayOfStringToJSArrayOfObjects(Values));
end;
procedure TcfsGChartOptions.SetAsObjectWithNestedObjects(const ObjectName: string; Values: TArray<TcfsJSCode>);
begin
SetAsJSCode(ObjectName, ArrayOfStringToJSObjectWithNestedObjects(Values));
end;
procedure TcfsGChartOptions.SetAsBoolean(const Name: string; Value: Boolean);
begin
SetAsJSCode(Name, TcfsGChartData.BooleanToJS(Value));
end;
procedure TcfsGChartOptions.SetAsVariant(const Name: string; const Value: Variant);
begin
SetAsJSCode(Name, VariantToStr(Name, Value));
end;
procedure TcfsGChartOptions.SetAsJSCode(const Name: string; JSCode: TcfsJSCode);
begin
if JSCode.Trim.IsEmpty then
Exit
else
FOptionsList.Values[Name] := JSCode;
end;
procedure TcfsGChartOptions.SetAsObject(const ObjectName, OptionName, Value: string);
var
ObjectNameEx: string;
V: string;
OV: string;
begin
//if Value.Trim.IsEmpty then
//Exit;
if ObjectName.Trim.IsEmpty then
raise Exception.Create(ClassName + ': ObjectName is empty');
ObjectNameEx := '{' + ObjectName;
OV := OptionName + ':' + Value;
V := FOptionsList.Values[ObjectNameEx];
if V.IsEmpty then
begin
FOptionsList.Values[ObjectNameEx] := OV;
end
else
begin
FOptionsList.Values[ObjectNameEx] := V + ',' + OV;
end;
end;
function TcfsGChartOptions.VariantToStr(const OptionName: string; const Value: Variant): string;
function VariantIsNull(const Value: Variant): Boolean;
begin
Result := VarIsClear(Value) or VarIsNull(Value) or (VarCompareValue(Value, Unassigned) = vrEqual);
end;
var
basicType: Integer;
s: string;
begin
Result := '';
if VariantIsNull(Value) then
Exit;
basicType := VarType(Value) and VarTypeMask;
case basicType of
varEmpty : Exit;
varNull : Exit;
varShortInt : Result := Value;
varSmallInt : Result := Value;
varInteger : Result := Value;
varSingle : Result := TcfsGChartData.NumberToJS(Value);
varDouble : Result := TcfsGChartData.NumberToJS(Value);
varCurrency : Result := TcfsGChartData.NumberToJS(Value);
varDate : Result := TcfsGChartData.DateTimeToJS(Value);
varBoolean : Result := TcfsGChartData.BooleanToJS(Value);
varByte : Result := Value;
varWord : Result := Value;
varUInt32 : Result := Value;
varInt64 : Result := Value;
varString, varUString :
begin
s := Value;
if s.TrimLeft.StartsWith('{') then
Result := Value
else if s.TrimLeft.StartsWith('[') then
Result := Value
else
Result := TcfsGChartData.StringToQuotedJS(Value);
end
else
raise Exception.Create(ClassName + '.' + OptionName + ': Value Incorrect');
end;
end;
procedure TcfsGChartOptions.Timeline(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('timeline', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.Tooltip(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('tooltip', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.TrendLines(const Values: TArray<TcfsJSCode>);
begin
SetAsArrayOfJSCode('trendlines', Values);
end;
procedure TcfsGChartOptions.Diff(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('diff', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.DisplayAnnotations(const Value: Boolean);
begin
SetAsBoolean('displayAnnotations', Value);
end;
procedure TcfsGChartOptions.DisplayMode(const Value: string);
begin
SetAsQuotedStr('displayMode', Value);
end;
procedure TcfsGChartOptions.EnableInteractivity(const Value: Boolean);
begin
SetAsBoolean('enableInteractivity', Value)
end;
procedure TcfsGChartOptions.VAxes(const Values: TArray<TcfsJSCode>);
begin
SetAsArrayOfJSCode('vAxes', Values);
end;
procedure TcfsGChartOptions.VAxis(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('vAxis', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.Width(const Value: Variant);
begin
SetAsVariant('width', Value);
end;
procedure TcfsGChartOptions.HAxis(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('hAxis', SubOptionName, VariantToStr(SubOptionName, Value));
end;
class function TcfsGChartOptions.TextStyleToJSObject(const Color: string; const FontSize: Integer; Bold: Boolean; Italic: Boolean; const FontName: string = '';
const AuraColor: string = ''; const Opacity: Extended = 1): TcfsJSCode;
var
s: string;
begin
Result := '';
s := '';
if not Color.Trim.IsEmpty then
s := s + 'color:' + Color.QuotedString + ',';
if not FontName.Trim.IsEmpty then
s := s + 'fontName:' + FontName.QuotedString + ',';
if FontSize <> 0 then
s := s + 'fontSize:' + FontSize.ToString + ',';
s := s + 'bold:' + TcfsGChartData.BooleanToJS(Bold) + ',';
s := s + 'italic:' + TcfsGChartData.BooleanToJS(Italic) + ',';
if not AuraColor.Trim.IsEmpty then
s := s + 'auraColor:' + AuraColor.QuotedString + ',';
if Opacity <> 1 then
s := s + 'opacity:' + TcfsGChartData.NumberToJS(Opacity);
if s <> '' then
begin
RemoveLastComma(s);
Result := '{' + s + '}';
end;
end;
procedure TcfsGChartOptions.Title(const Value: string);
begin
SetAsQuotedStr('title', Value);
end;
procedure TcfsGChartOptions.TitleTextStyle(const Value: Variant);
begin
SetAsVariant('titleTextStyle', Value);
end;
procedure TcfsGChartOptions.Subtitle(const Value: string);
begin
SetAsQuotedStr('subtitle', Value);
end;
procedure TcfsGChartOptions.AllowHtml(const Value: Boolean);
begin
SetAsBoolean('allowHtml', Value);
end;
procedure TcfsGChartOptions.Animation(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('animation', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.Annotations(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('annotations', SubOptionName, VariantToStr(SubOptionName, Value));
end;
class function TcfsGChartOptions.ArrayOfStringToJS(const Values: TArray<TcfsJSCode>): string;
var
s: string;
v: string;
begin
s := '[';
if Length(Values) > 0 then
begin
for v in Values do
s := s + TcfsGChartData.StringToQuotedJS(v) + ',';
RemoveLastComma(s);
end;
s := s + ']';
Result := s;
end;
class function TcfsGChartOptions.ArrayOfStringToJSArrayOfObjects(const Values: TArray<TcfsJSCode>): TcfsJSCode;
var
s: string;
v: string;
begin
s := '[';
if Length(Values) > 0 then
begin
for v in Values do
s := s + '{' + v + '},';
RemoveLastComma(s);
end;
s := s + ']';
Result := s;
end;
class function TcfsGChartOptions.ArrayOfStringToJSObjectWithNestedObjects(const Values: TArray<TcfsJSCode>): TcfsJSCode;
var
s: string;
v: string;
begin
s := '{';
if Length(Values) > 0 then
begin
for v in Values do
s := s + v + ',';
RemoveLastComma(s);
end;
s := s + '}';
Result := s;
end;
procedure TcfsGChartOptions.Axes(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('axes', SubOptionName, Value);
end;
procedure TcfsGChartOptions.BackgroundColor(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('backgroundColor', SubOptionName, Value);
end;
procedure TcfsGChartOptions.BackgroundColor(const Value: string);
begin
SetAsQuotedStr('backgroundColor', Value);
end;
procedure TcfsGChartOptions.Bar(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('bar', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.BoxStyle(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('boxStyle', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.Bubble(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('bubble', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.Calendar(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('calendar', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.Candlestick(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('candlestick', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.ChartArea(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('chartArea', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.ColorAxis(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('colorAxis', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.Colors(const Values: TArray<string>);
begin
SetAsArrayOfStrings('colors', Values);
end;
procedure TcfsGChartOptions.Crosshair(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('crosshair', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.FontName(const Value: string);
begin
SetAsQuotedStr('fontName', Value);
end;
procedure TcfsGChartOptions.FontSize(const Value: Word);
begin
SetAsInteger('fontSize', Value);
end;
procedure TcfsGChartOptions.RedFrom(const Value: Integer);
begin
SetAsInteger('redFrom', Value);
end;
procedure TcfsGChartOptions.RedTo(const Value: Integer);
begin
SetAsInteger('redTo', Value);
end;
procedure TcfsGChartOptions.Region(const Value: string);
begin
SetAsQuotedStr('region', Value);
end;
procedure TcfsGChartOptions.YellowFrom(const Value: Integer);
begin
SetAsInteger('yellowFrom', Value);
end;
procedure TcfsGChartOptions.YellowTo(const Value: Integer);
begin
SetAsInteger('yellowTo', Value);
end;
procedure TcfsGChartOptions.MinorTicks(const Value: Integer);
begin
SetAsInteger('minorTicks', Value);
end;
procedure TcfsGChartOptions.Gantt(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('gantt', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.Height(const Value: Variant);
begin
SetAsVariant('height', Value);
end;
procedure TcfsGChartOptions.Histogram(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('histogram', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.Interval(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('interval', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.Intervals(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('intervals', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.InterpolateNulls(Value: Variant);
begin
SetAsJSCode('interpolateNulls', VariantToStr('interpolateNulls', Value));
end;
procedure TcfsGChartOptions.Is3D(const Value: Boolean);
begin
SetAsBoolean('is3D', Value);
end;
procedure TcfsGChartOptions.IsStacked(const Value: Boolean);
begin
SetAsBoolean('isStacked', Value);
end;
procedure TcfsGChartOptions.IsStacked(const Value: string);
begin
SetAsQuotedStr('isStacked', Value);
end;
procedure TcfsGChartOptions.Legend(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('legend', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.LineWidth(const Value: Extended);
begin
SetAsFloat('lineWidth', Value);
end;
procedure TcfsGChartOptions.NoDataPattern(const SubOptionName: string; const Value: Variant);
begin
SetAsObject('noDataPattern', SubOptionName, VariantToStr(SubOptionName, Value));
end;
procedure TcfsGChartOptions.PieHole(const Value: Extended);
begin
SetAsFloat('pieHole', Value);
end;
procedure TcfsGChartOptions.PieSliceText(const Value: string);
begin
SetAsQuotedStr('pieSliceText', Value);
end;
procedure TcfsGChartOptions.PieSliceTextStyle(const Value: Variant);
begin
SetAsVariant('pieSliceTextStyle', Value);
end;
procedure TcfsGChartOptions.PieStartAngle(const Value: Extended);
begin
SetAsFloat('pieStartAngle', Value);
end;
procedure TcfsGChartOptions.PointShape(const Value: string);
begin
SetAsQuotedStr('pointShape', Value);
end;
procedure TcfsGChartOptions.PointSize(const Value: Integer);
begin
SetAsInteger('pointSize', Value);
end;
class procedure TcfsGChartOptions.RemoveLastComma(var Value: string);
begin
Delete(Value, Length(Value), 1);
end;
procedure TcfsGChartOptions.Slices(const Values: TArray<TcfsJSCode>);
begin
SetAsArrayOfJSCode('slices', Values);
end;
{ TcfsGChartProducer }
constructor TcfsGChartProducer.Create;
begin
FData := TcfsGChartData.Create;
FOptions := TcfsGChartOptions.Create;
LibrarySafeLoad := True;
end;
destructor TcfsGChartProducer.Destroy;
begin
FOptions.Free;
FData.Free;
if Assigned(FOldData) then
FOldData.Free;
inherited;
end;
function TcfsGChartProducer.GenerateJSCode(const ChartId: string; AddSelectEvent: Boolean = False; const JSAjaxRequest: string = ''; const JSName: string = ''): string;
var
Id, T: string;
SB: TStringBuilder;
MaterialDesign: Boolean;
procedure AddLibray;
var
I: Integer;
Package: string;
Language: string;
MapsApiKey: string;
LoadMode: string;
LibVers: string;
begin
LibVers := FLibraryVersion.Trim;
if LibVers.IsEmpty then
LibVers := TcfsGChartProducer.LIBRARY_VERSION_CURRENT;
MaterialDesign := False;
Package := FLibraryPackage.Trim;
if Package.IsEmpty then
begin
// Find Chart Library and if it uses Material Design
for I := Low(GChartPackagesAndTypes) to High(GChartPackagesAndTypes) do
begin
if SameText(GChartPackagesAndTypes[I].ClassChartType, ClassChartType) then
begin
Package := GChartPackagesAndTypes[I].Package;
MaterialDesign := GChartPackagesAndTypes[I].MaterialDesign;
Break;
end;
end;
end;
if Package.IsEmpty then
raise Exception.Create(ClassName + ': LibraryPackage can''t be empty');
Language := '';
if FLibraryLanguage <> '' then
Language := ', ' + QuotedStr('language') + ':' + FLibraryLanguage.QuotedString;
MapsApiKey := '';
if not FLibraryMapsApiKey.IsEmpty then
begin
if SameText(Package, PACKAGE_GEO_CHART) then
MapsApiKey := ', ' + QuotedStr('mapsApiKey') + ':' + FLibraryMapsApiKey.QuotedString;
end;
if LibrarySafeLoad and SameText(LibVers, TcfsGChartProducer.LIBRARY_VERSION_CURRENT) then
begin
LibVers := '';
LoadMode := 'google.charts.safeLoad';
end
else
begin
LibVers := FLibraryVersion.QuotedString('"') + ',';
LoadMode := 'google.charts.load';
end;
SB.Append(LoadMode + '(' + LibVers + '{packages:[' + Package.QuotedString + ']' + Language + MapsApiKey+ '}).then(' + PREFIX_DRAW_CHART_FUNCTION_NAME + Id + ');');
end;
procedure AppendSelectEvent;
begin
SB.Append('google.visualization.events.addListener(chart, ''select'', selectHandler);');
SB.Append('function selectHandler() {');
SB.Append('var selectedItem = chart.getSelection()[0];');
SB.Append('var itemRow="";');
SB.Append('var itemColumn="";');
SB.Append('var itemValue="";');
SB.Append('var itemCategory="";');
SB.Append('if (selectedItem) {');
SB.Append('itemRow = selectedItem.row;');
SB.Append('itemColumn = selectedItem.column;');
SB.Append('if (selectedItem.row != null && selectedItem.column != null) {');
SB.Append('itemValue = data.getValue(selectedItem.row, selectedItem.column);');
SB.Append('itemCategory = data.getValue(selectedItem.row, 0);');
SB.Append('} else if (selectedItem.row != null) {');
SB.Append('itemValue = data.getValue(selectedItem.row, 0);');
SB.Append('} else if (selectedItem.column != null) {');
SB.Append('itemValue = data.getValue(0, selectedItem.column);');
SB.Append('}');
SB.Append('if (itemValue instanceof Date){itemValue=itemValue.toISOString()};');
SB.Append('if (itemCategory instanceof Date){itemCategory=itemCategory.toISOString()};');
SB.Append('if (itemColumn == null){itemColumn=""};');
SB.Append('if (itemRow == null){itemRow=""};');
SB.Append('}');
//SB.Append(' alert("itemRow=" + itemRow + ";itemColumn=" + itemColumn + ";itemValue=" + itemValue + ";itemCategory=" + itemCategory);');
SB.Append(JSAjaxRequest + Format('(%s, "chartSelect", ["chartId="+' + '"' + Id + '"' + ', "itemRow="+itemRow, "itemColumn="+itemColumn, "itemValue="+itemValue, "itemCategory="+itemCategory]);', [JSName]));
SB.Append('}');
end;
var
DrawDataVarName: string;
begin
Id := ChartId.Trim;
if not IsValidIdent(Id) then
raise Exception.Create(ClassName + ': Invalid CanvasChart Name');
T := FClassChartType.Trim;
if T.IsEmpty then
raise Exception.Create(ClassName + ': ClassChartType can''t be empty');
SB := TStringBuilder.Create;
try
AddLibray;
SB.Append('function ' + PREFIX_DRAW_CHART_FUNCTION_NAME + Id + '(){');
SB.Append('if (document.getElementById("' + Id + '") === null) {alert("chart div not found: ' + Id + '");};');
if MaterialDesign then
SB.Append('var chart = new google.charts.' + T + '(document.getElementById("' + Id + '"));')
else
SB.Append('var chart = new google.visualization.' + T + '(document.getElementById("' + Id + '"));');
if Assigned(FOldData) then
begin
SB.Append('var oldData = google.visualization.arrayToDataTable([' + FOldData.ToJSDataTable + ']);');
SB.Append('var newData = google.visualization.arrayToDataTable([' + FData.ToJSDataTable + ']);');
SB.Append('var data = chart.computeDiff(oldData, newData);');
end
else
begin
SB.Append('var data = google.visualization.arrayToDataTable([' + FData.ToJSDataTable + ']);');
end;
SB.Append('var options = {' + Options.ToJSCode + '};');
// SB.Append('google.visualization.events.addListener(chart, ''error'', function (err) {');
// SB.Append('alert(err.message);');
// SB.Append('console.log(err.id, err.message);');
// SB.Append('google.visualization.errors.removeError(err.id);');
// SB.Append('google.visualization.errors.removeAll(container);');
// SB.Append('});');
DrawDataVarName := 'data';
if not FScripCodeBeforeCallDraw.IsEmpty then
begin
SB.Append(FScripCodeBeforeCallDraw);
// Look for use of DataView object in ScripCodeBeforeCallDraw
if Pos('DATAVIEW', FScripCodeBeforeCallDraw.ToUpper) > 0 then
DrawDataVarName := 'view';
end;
if MaterialDesign then
SB.Append('chart.draw(' + DrawDataVarName + ', google.charts.' + T + '.convertOptions(options));')
else
SB.Append('chart.draw(' + DrawDataVarName + ', options);');
SB.Append(FScripCodeAfterCallDraw);
if AddSelectEvent then
AppendSelectEvent;
SB.Append('}');
Result := SB.ToString;
finally
SB.Free;
end;
end;
function TcfsGChartProducer.GetClassChartType: string;
begin
Result := FClassChartType;
end;
function TcfsGChartProducer.GetOldData: TcfsGChartData;
begin
if not Assigned(FOldData) then
FOldData := TcfsGChartData.Create;
Result := FOldData;
end;
function TcfsGChartProducer.GetData: TcfsGChartData;
begin
Result := FData;
end;
function TcfsGChartProducer.GetLibraryLanguage: string;
begin
Result := FLibraryLanguage;
end;
function TcfsGChartProducer.GetLibraryMapsApiKey: string;
begin
Result := FLibraryMapsApiKey;
end;
function TcfsGChartProducer.GetLibraryPackage: string;
begin
Result := FLibraryPackage;
end;
function TcfsGChartProducer.GetLibrarySafeLoad: Boolean;
begin
Result := FLibrarySafeLoad;
end;
function TcfsGChartProducer.GetLibraryVersion: string;
begin
Result := FLibraryVersion;
end;
function TcfsGChartProducer.GetOptions: TcfsGChartOptions;
begin
Result := FOptions;
end;
function TcfsGChartProducer.GetScripCodeAfterCallDraw: string;
begin
Result := FScripCodeAfterCallDraw;
end;
function TcfsGChartProducer.GetScripCodeBeforeCallDraw: string;
begin
Result := FScripCodeBeforeCallDraw;
end;
procedure TcfsGChartProducer.SetClassChartType(const Value: string);
begin
FClassChartType := Value;
end;
procedure TcfsGChartProducer.SetLibraryLanguage(const Value: string);
begin
FLibraryLanguage := Value;
end;
procedure TcfsGChartProducer.SetLibraryMapsApiKey(const Value: string);
begin
FLibraryMapsApiKey := Value;
end;
procedure TcfsGChartProducer.SetLibraryPackage(const Value: string);
begin
FLibraryPackage := Value;
end;
procedure TcfsGChartProducer.SetLibrarySafeLoad(const Value: Boolean);
begin
FLibrarySafeLoad := Value;
end;
procedure TcfsGChartProducer.SetLibraryVersion(const Value: string);
begin
FLibraryVersion := Value;
end;
procedure TcfsGChartProducer.SetScripCodeAfterCallDraw(const Value: string);
begin
FScripCodeAfterCallDraw := Value;
end;
procedure TcfsGChartProducer.SetScripCodeBeforeCallDraw(const Value: string);
begin
FScripCodeBeforeCallDraw := Value;
end;
end.
|
unit uWinList;
interface
uses Classes ,windows,SysUtils,DBClient,DB,Dialogs ,ShellAPI,Forms,IMCode;
type
//TFindListType = (fwFindDirectory,fwFindWindows,fwFindProgram);
TFindListType = (fwFindDirectory,fwFindWindows,fwFor1000copy);
TFindList = class(TClientDataset)
protected
procedure Init ;virtual;
public
constructor Create (O : TComponent);override ;
procedure DoFilter (S : String;Exactly:Boolean = false);virtual;
procedure CancelFilter (S : String);virtual;
procedure Fill(Argument:String);virtual;abstract;
procedure DoRun ;virtual ;abstract ;
end;
TAllWindows = class(TFindList)
procedure Fill(Argument:String);override;
procedure DoRun ;override ;
end;
TAllDirectory = class(TFindList)
procedure Fill(Argument:String);override;
procedure DoRun ;override ;
end;
TFor1000copy = class(TFindList)
procedure Fill(Argument:String);override;
procedure DoRun ;override ;
end;
TFindListFactory = class
private
AllWindows : TFindList ;
AllDirectory: TFindList ;
For1000copy: TFindList;
function GetFor1000copy: TFindList;
public
constructor Create;reintroduce ;
destructor Destroy ;override ;
function GetFindList(Value : TFindListType): TFindList;
end;
implementation
{ TAllWindows }
function TFindListFactory.GetFor1000copy:TFindList;
var
F:TField;
begin
if not Assigned(For1000copy) then begin
For1000copy := TFor1000copy.Create (nil);
{
F := TStringField.Create(nil);
F.Size := 255 ;
F.FieldName := 'key';
F.DataSet := For1000copy ;
F := TStringField.Create(nil);
F.FieldName := 'value';
F.Size := 255 ;
F.DataSet := For1000copy ;
For1000copy.CreateDataSet ;
}
For1000copy.Append;
For1000copy.FieldByName('key').asString := 'Name';
For1000copy.FieldByName('value').asString := 'Liu Chuanjun';
For1000copy.Post ;
For1000copy.Append;
For1000copy.FieldByName('key').asString := 'Blog';
For1000copy.FieldByName('value').asString := '1000copy.spaces.live.com';
For1000copy.Post ;
For1000copy.Append;
For1000copy.FieldByName('key').asString := 'Email';
For1000copy.FieldByName('value').asString := '1000copy@gmail.com';
For1000copy.Post ;
end;
Result := For1000copy ;
end;
procedure TAllWindows.DoRun;
begin
SetForegroundWindow(fieldByName('key').AsInteger);
end;
procedure TAllWindows.Fill(Argument: String);
function EnumWindowsFunc(Handle: THandle; cds: TClientDataSet): boolean ; stdcall;
var Caption: array[0..256] of Char;
var
i : integer ;
sl : TStringList;
begin
sl := TStringList.Create ;
try
sl.Add('Default IME');
sl.Add('SpyHideBy Sanrex@163.com');
sl.Add('DDE Server Window');
sl.Add('M');
sl.Add('GPY_UI');
sl.Add('GDI+ Window');
sl.Add('SysFader');
if GetWindowText(Handle, Caption, SizeOf(Caption)-1) <> 0 then
begin
//if pos('Default IME',Caption) = 0 then// not found substr in caption
if sl.IndexOf(Caption)=-1 then
begin
cds.Append ;
cds.FieldByName('key').AsInteger := Handle ;
cds.FieldByName('value').AsString := String( Caption) ;
cds.Post ;
end;
Application.ProcessMessages;
end;
Result :=True;
cds.First;
finally
sl.Free ;
end;
end;
begin
while not Eof do
Delete ;
EnumWindows(@EnumWindowsFunc, LParam(Self));
end;
{ TAllDirectory }
procedure TAllDirectory.DoRun;
begin
inherited;
//ShowMessage(fieldByName('key').AsString);
ShellExecute(0,nil,PChar(fieldByName('key').AsString),nil,nil,SW_SHOWNORMAL);
{
我们一般使用 ShellExecute 来打开一个文件或者目录,也可以用其来打开一个IE窗口、
打印窗等等。现在很多软件在打开文件所在目录的同时都会贴心的把该文件选中,
比如 FlashGet,BitComet。//打开目录并选定文件
ShellExecute(NULL, _T("open"), _T("Explorer.exe"), _T(" /select,") + filePath, NULL, SW_SHOWDEFAULT);
}
end;
function GetFixDisk:string ;
var
i,len : Integer ;
A : Array [0..255] of char ;
B : String ;
sl :TStringList ;
begin
FillChar(A,255,#0);
len := GetLogicalDriveStrings(255,A);
sl := TStringList.Create ;
try
for I := 0 to len -1 do
if A[I] = #0 then begin
if (b <> '') and (GetDriveType(PChar(b)) = DRIVE_FIXED) then
sl.Add(b);
b := '';
end else
b := b + A[I] ;
Result := sl.CommaText ;
finally
sl.Free ;
end;
end;
procedure TAllDirectory.Fill(Argument: String);
procedure DeleteLastChar(var S:string);
begin
S := Copy(S,1,Length(S)-1);
end;
function GetLastChar(S:string):String;
begin
Result := Copy(S,Length(S),1);
end;
function GetLastDir(S:string):String;
var
i :Integer ;
begin
if GetLastChar(S) ='\' then
DeleteLastChar(S);
i := Length(s);
while i > 0 do
begin
if Copy(S,i,1) ='\' then begin
Result := Copy(S,i+1,Length(s));
Exit;
end;
Dec(i);
end;
Result := s ;
end;
procedure FillDir(s:String;var Dataset :TAllDirectory);
var
temPath:String;
sr:TSearchRec;
begin
temPath:=s+'\*.*';
if SysUtils.FindFirst(temPath,faAnyFile,sr)=0 then
repeat
if (sr.Name='.') or (sr.Name='..') then continue
else
//if (sr.Attr and faDirectory)=sr.Attr then
// 上面这个方法是delphi给的例子,但是找不到program files 之类的17属性的目录
// 下面是我试验处理的。
if ((sr.Attr and faDirectory)= faDirectory)
and ((sr.Attr and faHidden)<> faHidden)
then
begin
Dataset.Append;
Dataset.FieldByName('key').asString := s+sr.name;
Dataset.FieldByName('value').asString := getPyString(GetLastDir(s+sr.name));
Dataset.Post ;
Application.ProcessMessages;
FillDir(s+sr.Name+'\',Dataset);
end;
until SysUtils.FindNext(sr)<>0 ;
SysUtils.FindClose(sr);
Dataset.First;
end;
var
sl :TStringList;
i : Integer ;
begin
sl := TStringList.Create ;
try
sl.CommaText := GetFixDisk;
//sl.CommaText := 'F:\'; //just for test
for i := 0 to sl.Count -1 do
FillDir(sl.Strings[i],Self);
finally
sl.Free ;
end;
end;
constructor TFindListFactory.Create;
begin
inherited;
AllWindows := nil ;
AllDirectory:= nil ;
For1000copy := nil ;
end;
destructor TFindListFactory.Destroy;
begin
FreeAndNil(AllWindows);
FreeAndNil(AllDirectory);
FreeAndNil(For1000copy);
inherited;
end;
function TFindListFactory.GetFindList(Value : TFindListType): TFindList;
begin
if Value = fwFindWindows then begin
if not Assigned(AllWindows) then begin
AllWindows := TAllWindows.Create (nil);
AllWindows.Fill('');
end;
Result := AllWindows;
end
else if Value = fwFindDirectory then begin
if not Assigned(AllDirectory) then begin
AllDirectory := TAllDirectory.Create (nil);
AllDirectory.Fill('');
end;
Result := AllDirectory;
end
else if Value = fwFor1000copy then
//ShowMessage('not yet implement!');
Result := GetFor1000copy;
end;
{ TFindList }
procedure TFindList.CancelFilter(S: String);
begin
Self.Filtered := False;
end;
constructor TFindList.Create(O: TComponent);
begin
inherited;
Init ;
end;
procedure TFindList.DoFilter(S: String;Exactly:Boolean = false);
begin
FilterOptions := [foCaseInsensitive];
if Exactly then
Filter := 'value ='''+S+''''
else
Filter := 'value like ''%'+S+'%''';
Filtered := True ;
end;
procedure TFindList.Init;
var
F :TStringField ;
begin
F := TStringField.Create(nil);
F.Size := 255 ;
F.FieldName := 'key';
F.DataSet := Self ;
F := TStringField.Create(nil);
F.FieldName := 'value';
F.Size := 255 ;
F.DataSet := Self ;
CreateDataSet ;
end;
{ TFor1000copy }
procedure TFor1000copy.DoRun;
begin
inherited;
end;
procedure TFor1000copy.Fill(Argument: String);
var f : TField ;
begin
inherited;
end;
end.
|
program questao9;
{
Autor: Hugo Deiró Data: 02/06/2012
- Este programa converte uma temperatura em Fahrenheit para Celcius
Fórmula: C = (5*(F-32))/9.
}
var
fahrenheit : real;
begin
write('Insira uma temperatura em Fahrenheit: ');
readln(fahrenheit);
writeln;
writeln(fahrenheit:6:2,'°F = ',(5*(fahrenheit-32))/9:6:2,'°C');
end.
|
//FPC 2.6.2
program HelloWorld;
begin
writeln('Hello World');
end.
|
unit uFrmScaleInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uPai, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, uBalanca;
type
TFrmScaleInfo = class(TFrmPai)
btnOK: TButton;
tmrScale: TTimer;
GroupBox2: TGroupBox;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
lblStatus: TLabel;
pnlCodigo: TPanel;
pnlValUnit: TPanel;
pnlTara: TPanel;
pnlCont: TPanel;
pnlValTot: TPanel;
pnlLiquido: TPanel;
lbBruto: TLabel;
lbProdutc: TLabel;
Label1: TLabel;
lbValorTotal: TLabel;
procedure btCloseClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure tmrScaleTimer(Sender: TObject);
private
FResult : Double;
FScaleStatus : Integer;
FSellingPrice : Currency;
FBalanca : TBalanca;
function FormatScaleResult(AResult : Double): Double;
public
function Start(ABalanca : TBalanca; AProduct : String; ASellingPrice : Currency) : Double;
end;
implementation
uses uNumericFunctions;
{$R *.dfm}
{ TFrmScaleInfo }
function TFrmScaleInfo.Start(ABalanca: TBalanca;
AProduct : String; ASellingPrice : Currency): Double;
begin
FBalanca := ABalanca;
FResult := 0;
lbProdutc.Caption := AProduct;
FSellingPrice := ASellingPrice;
if FBalanca.InitializeScale then
tmrScale.Enabled := True;
ShowModal;
tmrScale.Enabled := False;
FBalanca.FinalizeScale;
Result := FResult;
end;
procedure TFrmScaleInfo.btCloseClick(Sender: TObject);
begin
inherited;
FResult := 0;
Close;
end;
procedure TFrmScaleInfo.btnOKClick(Sender: TObject);
begin
inherited;
if FScaleStatus = BAL_PESO_ESTAVEL then
begin
FResult := FormatScaleResult(FBalanca.GetScaleModelValue);
Close;
end;
end;
procedure TFrmScaleInfo.tmrScaleTimer(Sender: TObject);
var
sMSG, sMascara : String;
dVaule : Double;
begin
inherited;
FScaleStatus := FBalanca.GetScaleStatus(sMSG);
lblStatus.Caption := sMSG;
if FScaleStatus in [BAL_PESO_VARIANDO, BAL_PESO_ESTAVEL] then
begin
dVaule := FBalanca.GetScaleModelValue;
lbBruto.Caption := FormatFloat('0.#####', FormatScaleResult(dVaule));
if dVaule > 0 then
lbValorTotal.Caption := FormatFloat('0.00', FormatScaleResult(dVaule) * FSellingPrice)
else
lbValorTotal.Caption := '';
{
pnlTara.Caption := FormatFloat(sMascara, FBalanca.GetScaleValue(BAL_PESO_TARA));
pnlLiquido.Caption := FormatFloat(sMascara, FBalanca.GetScaleValue(BAL_PESO_LIQ));
pnlCont.Caption := FloatToStr(FBalanca.GetScaleValue(BAL_COUN_PASS));
pnlCodigo.Caption := FloatToStr(FBalanca.GetScaleValue(BAL_COD_BAL));
pnlValUnit.Caption := FloatToStr(FBalanca.GetScaleValue(BAL_VALOR_MONETARIO_KG));
pnlValTot.Caption := FloatToStr(FBalanca.GetScaleValue(BAL_VALOR_MONETARIO_TOTAL));
}
end
else
begin
lbBruto.Caption := '---------';
pnlTara.Caption := '---------';
pnlLiquido.Caption := '---------';
pnlCont.Caption := '---------';
pnlCodigo.Caption := '---------';
pnlValUnit.Caption := '---------';
pnlValTot.Caption := '---------';
end;
end;
function TFrmScaleInfo.FormatScaleResult(AResult: Double): Double;
var
sResult : String;
begin
sResult := FormatFloat('0.####', (AResult/FBalanca.GetDecimalValue));
Result := StrToFloat(sResult);
end;
end.
|
unit sp_Product_Add;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons,
ExtCtrls, cxCheckBox, cxRadioGroup, cxControls, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, cxButtonEdit;
type
Tsp_Product_Add_Form = class(TForm)
Label1: TLabel;
NameEdit: TcxTextEdit;
KindRadioGroup: TcxRadioGroup;
LevelRadioGroup: TcxRadioGroup;
Bevel1: TBevel;
CancelButton: TcxButton;
OkButton: TcxButton;
CheckBox1: TcxCheckBox;
CheckBox2: TcxCheckBox;
CheckBox3: TcxCheckBox;
CheckBox4: TcxCheckBox;
Bevel2: TBevel;
NameUnitMeasLabel: TLabel;
NameUnitMeasEdit: TcxButtonEdit;
NameDepartmentEdit: TcxButtonEdit;
NameDepartmentLabel: TLabel;
procedure KindRadioGroupPropertiesChange(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure NameUnitMeasEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure NameDepartmentEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
id_unit_meas : integer;
id_Department : integer;
is_Edit : boolean; // Признак того, что форма открыта в режиме редактирования или добавления
destructor Destroy; override;
end;
var
sp_Product_Add_Form: Tsp_Product_Add_Form;
implementation
{$R *.dfm}
uses sp_Product, tagBaseTypes, {uDepartmentsMain,} tagSYS_Options, fpop_PackageLoader;
procedure Tsp_Product_Add_Form.KindRadioGroupPropertiesChange(
Sender: TObject);
begin
if KindRadioGroup.ItemIndex = 0 then begin
if is_Edit then Caption := 'Змінити тип продукції' else Caption := 'Додати тип продукції';
Label1.Caption := 'Назва типу продукції';
CheckBox1.Visible := False;
CheckBox2.Visible := False;
CheckBox3.Visible := False;
CheckBox4.Visible := False;
Bevel2.Visible := False;
NameUnitMeasEdit.Visible := False;
NameUnitMeasLabel.Visible := False;
NameDepartmentEdit.Visible := True;
NameDepartmentLabel.Visible := True;
NameDepartmentEdit.Left := NameUnitMeasEdit.Left;
NameDepartmentEdit.Top := NameUnitMeasEdit.Top;
NameDepartmentLabel.Left := NameUnitMeasLabel.Left;
NameDepartmentLabel.Top := NameUnitMeasLabel.Top;
Height := 250;
end
else begin
if is_Edit then Caption := 'Змінити продукцію' else Caption := 'Додати продукцію';
Label1.Caption := 'Назва продукції';
CheckBox1.Visible := True;
CheckBox2.Visible := True;
CheckBox3.Visible := True;
CheckBox4.Visible := True;
Bevel2.Visible := True;
NameUnitMeasEdit.Visible := True;
NameUnitMeasLabel.Visible := True;
NameDepartmentEdit.Visible := False;
NameDepartmentLabel.Visible := False;
Height := 329;
end;
if is_Edit then Exit;
if sp_product_form.TreeList.FocusedNode = nil then begin
KindRadioGroup.ItemIndex := 0;
LevelRadioGroup.ItemIndex := 0;
end
else if not VarIsNull(sp_product_form.TreeList.FocusedNode.Values[1]) then begin
LevelRadioGroup.ItemIndex := 0;
end;
end;
procedure Tsp_Product_Add_Form.OkButtonClick(Sender: TObject);
begin
if NameEdit.Text = '' then begin
if KindRadioGroup.ItemIndex = 0 then ShowMessage('Заповніть поле із назвою типу продукції')
else if KindRadioGroup.ItemIndex = 1 then ShowMessage('Заповніть поле із назвою продукції');
Exit;
end;
if (KindRadioGroup.ItemIndex = 1) and (NameUnitMeasEdit.Text = '') then begin
ShowMessage('Оберіть одиницю виміру продукції!');
Exit;
end;
if (KindRadioGroup.ItemIndex = 0) and (NameDepartmentEdit.Text = '') then begin
ShowMessage('Оберіть підрозділ типу продукції!');
Exit;
end;
ModalResult := mrOk;
end;
procedure Tsp_Product_Add_Form.NameUnitMeasEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
i, o : TSpravParams;
begin
i := TSpravParams.Create;
o := TSpravParams.Create;
i.Values['DataBase'] := Integer((Owner as Tsp_Product_Form).Database.Handle);
i.Values['ReadTransaction'] := Integer((Owner as Tsp_Product_Form).ReadTransaction.Handle);
i.Values['WriteTransaction'] := Integer((Owner as Tsp_Product_Form).WTransaction.Handle);
i.Values['FormStyle'] := fsNormal;
LoadSprav('FPOP\ini_unit_meas.bpl', Self, i, o);
if o['ModalResult'] = mrOk then begin
id_unit_meas := o.Values['ID_UNIT_MEAS'];
NameUnitMeasEdit.Text := o.Values['NAME_UNIT_MEAS'];
end;
end;
destructor Tsp_Product_Add_Form.Destroy;
begin
sp_Product_Add_Form := nil;
inherited;
end;
procedure Tsp_Product_Add_Form.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure Tsp_Product_Add_Form.NameDepartmentEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
//var
// sp: TDepartmentsSprav;
begin
// создать справочник
{ sp := TDepartmentsSprav.Create;
if sp <> nil then begin
// заполнить входные параметры
with sp.Input do begin
Append;
FieldValues['DBHandle'] := Integer(DM.Database.Handle);
// модальный показ
FieldValues['ShowStyle'] := 0;
// единичная выборка
FieldValues['Select'] := 1;
FieldValues['Root_Department'] := 2612;
FieldValues['Actual_Date'] := Date;
Post;
end;
end;
// показать справочник и проанализировать результат (выбор одного подр.)
sp.Show;
if sp.Output = nil then ShowMessage('Ошибка!: Выходные параметры пусты!!!')
else
if not sp.Output.IsEmpty then begin
Id_Department := sp.Output['Id_Department'];
if not VarIsNull(sp.Output['Name_Short']) then NameDepartmentEdit.Text := sp.Output['Name_Short'];
end;
sp.Free;}
end;
procedure Tsp_Product_Add_Form.FormShow(Sender: TObject);
begin
if NameDepartmentEdit.Text = '' then begin
NameDepartmentEdit.Text := SYS_DEF_NAME_DEPARTMENT;
id_Department := SYS_DEF_ID_DEPARTMENT;
end;
end;
end.
|
unit cmtwriter;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Windows, sqlite3conn, sqldb, sqlite3ds, rtfutil, LazFileUtils;
const
NUM_BIBLE_REFS: Integer = 32357;
type
TOnLog = procedure(msg: String) of object;
TOnProgress = procedure(perc1, perc2: Integer) of object;
TCmtWriter = class(TObject)
FOnLog: TOnLog;
FOnProgress: TOnProgress;
procedure open();
procedure close();
procedure addVerseRef(bi, ci, fvi, tvi: Integer; fileName, data: String);
procedure buildCommentaryRecords();
property OnLog: TOnLog read FOnLog write FOnLog;
property OnProgress: TOnProgress read FOnProgress write FOnProgress;
private
conn: TSQLite3Connection;
tx: TSQLTransaction;
procedure createDBFile(filename: String);
procedure buildTopic(tid, bi, ci, vi: Integer);
procedure writeTopic(tid: Integer; tdata: String);
procedure compactDB();
public
end;
implementation
procedure TCmtWriter.buildCommentaryRecords();
var
qVerses: TSQLQuery;
tid, count: Integer;
begin
tx.CommitRetaining;
qVerses := TSQLQuery.Create(conn);
qVerses.DataBase := conn;
qVerses.Transaction := tx;
qVerses.SQL.Text := 'SELECT * FROM bible_refs ORDER BY bi, ci, fvi';
qVerses.UniDirectional := True;
qVerses.Open();
count := 0;
while not qVerses.EOF do
begin
tid := qVerses.FieldByName('topic_id').AsInteger;
buildTopic(tid, qVerses.FieldByName('bi').AsInteger, qVerses.FieldByName('ci').AsInteger, qVerses.FieldByName('fvi').AsInteger);
count := count + 1;
if (count mod 1000 = 0) then
tx.CommitRetaining;
if Assigned(FOnProgress) then FOnProgress(-1, (count*100 div NUM_BIBLE_REFS));
qVerses.Next
end;
qVerses.Close;
end;
procedure TCmtWriter.buildTopic(tid, bi, ci, vi: Integer);
var
qRefs: TSQLQuery;
tdata, bookname, currentBook: String;
begin
qRefs := TSQLQuery.Create(conn);
qRefs.Database := conn;
qRefs.Transaction := tx;
qRefs.SQL.Text := 'SELECT * FROM tmp_comm WHERE bi=:bi AND ci=:ci AND fvi >= :vi AND tvi <= :vi ORDER BY fileName';
qRefs.Params.ParamByName('bi').AsInteger := bi;
qRefs.Params.ParamByName('ci').AsInteger := ci;
qRefs.Params.ParamByName('vi').AsInteger := vi;
qRefs.UniDirectional := True;
qRefs.Open();
tdata := createTopicHeader();
currentBook := '';
while not qRefs.EOF do
begin
bookname := qRefs.FieldByName('fileName').AsString;
if (currentBook <> bookname) then
begin
tdata := tdata + createBookHeader(bookname);
currentBook := bookname;
end;
tdata := tdata + qRefs.FieldByName('data').AsString;
qRefs.Next;
end;
qRefs.Close;
qRefs.Free;
tdata := tdata + createTopicFooter();
writeTopic(tid, tdata);
end;
procedure TCmtWriter.writeTopic(tid: Integer; tdata: String);
var
q: TSQLQuery;
begin
q := TSQLQuery.Create(conn);
q.SQLConnection := conn;
q.Transaction := tx;
q.SQL.Text := 'UPDATE content SET data=:data WHERE topic_id=:tid;';
q.Params.ParamByName('tid').AsInteger := tid;
q.Params.ParamByName('data').AsString := tdata;
q.ExecSQL;
q.Close;
q.Free;
end;
procedure TCmtWriter.addVerseRef(bi, ci, fvi, tvi: Integer; fileName, data: String);
var
q: TSQLQuery;
begin
q := TSQLQuery.Create(conn);
q.SQLConnection := conn;
q.Transaction := tx;
q.SQL.Text := 'INSERT INTO tmp_comm (bi, ci, fvi, tvi, fileName, data) VALUES (:bi, :ci, :fvi, :tvi, :fn, :data);';
q.Params.ParamByName('bi').AsInteger := bi;
q.Params.ParamByName('ci').AsInteger := ci;
q.Params.ParamByName('fvi').AsInteger := fvi;
q.Params.ParamByName('tvi').AsInteger := tvi;
q.Params.ParamByName('fn').AsString := fileName;
q.Params.ParamByName('data').AsString := data;
q.ExecSQL;
q.Close;
q.Free;
end;
procedure TCmtWriter.open();
begin
createDBFile('index.cmt.twm');
conn := TSQLite3Connection.Create(nil);
tx := TSQLTransaction.Create(conn);
conn.Transaction := tx;
conn.DatabaseName := 'index.cmt.twm';
tx.StartTransaction;
conn.ExecuteDirect('CREATE TABLE tmp_comm (bi INTEGER, ci INTEGER, fvi INTEGER, tvi INTEGER, fileName TEXT, data TEXT);');
conn.ExecuteDirect('CREATE INDEX BibleRef ON tmp_comm (bi, ci, fvi, tvi);');
tx.CommitRetaining;
end;
procedure TCmtWriter.close();
begin
conn.ExecuteDirect('DROP TABLE tmp_comm;');
conn.ExecuteDirect('DELETE FROM content WHERE length(data) <= '+IntToStr(Length(createTopicHeader()+createTopicFooter())));
conn.ExecuteDirect('DELETE FROM content_search WHERE topic_id NOT IN (SELECT topic_id FROM content)');
conn.ExecuteDirect('DELETE FROM bible_refs WHERE topic_id NOT IN (SELECT topic_id FROM content)');
tx.Commit;
tx.Free;
conn.Free;
compactDB();
end;
procedure TCmtWriter.compactDB();
var
tmpDataset: TSqlite3Dataset;
begin
tmpDataset := TSqlite3Dataset.Create(nil);
tmpDataset.FileName:='index.cmt.twm';
tmpDataset.ExecSQL('VACUUM;');
tmpDataset.Free;
end;
procedure TCmtWriter.createDBFile(filename: String);
var
S: TResourceStream;
F: TFileStream;
begin
if (FileExists(filename)) then
DeleteFileUTF8(filename);
if (FileExists(filename+'-journal')) then
DeleteFileUTF8(filename+'-journal');
S := TResourceStream.Create(HInstance, 'TEMPLATE_INDEX', RT_RCDATA);
try
F := TFileStream.Create(filename, fmCreate);
try
F.CopyFrom(S, S.Size);
finally
F.Free;
end;
finally
S.Free;
end;
end;
end.
|
unit uFormEditObject;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, uDBForm;
type
TFormEditObject = class(TDBForm)
CbColor: TColorBox;
lbColor: TLabel;
LbNoteText: TLabel;
MemText: TMemo;
BtnOk: TButton;
BtnCancel: TButton;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure LoadLanguage;
protected
{ Protected declarations }
function GetFormID: string; override;
public
{ Public declarations }
end;
var
FormEditObject: TFormEditObject;
implementation
{$R *.dfm}
procedure TFormEditObject.FormCreate(Sender: TObject);
const
ColorCount = 3;
Colors: array [1 .. ColorCount] of TColor = (clGreen, clred, clblue);
var
I: Integer;
begin
LoadLanguage;
for I := 1 to High(Colors) do
CbColor.AddItem(ColorToString(Colors[I]), TObject(Colors[I]));
end;
function TFormEditObject.GetFormID: string;
begin
Result := 'EditObject';
end;
procedure TFormEditObject.LoadLanguage;
begin
BeginTranslate;
try
finally
EndTranslate;
end;
end;
end.
|
unit UCRCS;
//------------------------------------------------------------------------------
// модуль посчёта различных контрольных сумм
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
//------------------------------------------------------------------------------
//! подсчёт байтового XOR
//------------------------------------------------------------------------------
function CRCXOR(
const AData: Pointer;
const ALen: Integer
): Byte;
//------------------------------------------------------------------------------
//! подсчёт CRC8 - общий вариант
//------------------------------------------------------------------------------
function CRC8(
const AData: Pointer;
const ALen: Integer;
const AInitVal: Byte;
const APolynomial: Byte
): Byte;
//------------------------------------------------------------------------------
//! подсчёт CRC8 - стандарт
//------------------------------------------------------------------------------
function CRC8Std(
const AData: Pointer;
const ALen: Integer
): Byte;
//------------------------------------------------------------------------------
//! подсчёт CRC16 - общий вариант
//------------------------------------------------------------------------------
function CRC16(
const AData: Pointer;
const ALen: Integer;
const AInitVal: Word;
const APolynomial: Word
): Word;
//------------------------------------------------------------------------------
//! подсчёт CRC16 - стандарт
//------------------------------------------------------------------------------
function CRC16Std(
const AData: Pointer;
const ALen: Integer
): Word;
//------------------------------------------------------------------------------
//! подсчёт CRC16 - виалон-IPS
//------------------------------------------------------------------------------
function CRC16WialonIPS(
const AData: Pointer;
const ALen: Integer
): Word;
//------------------------------------------------------------------------------
implementation
function CRCXOR(
const AData: Pointer;
const ALen: Integer
): Byte;
var
//!
Here: PByte;
//!
I: Integer;
//------------------------------------------------------------------------------
begin
Here := AData;
Result := 0;
for I := 1 to ALen do
begin
Result := Result xor Here^;
Inc(Here);
end;
end;
function CRC8(
const AData: Pointer;
const ALen: Integer;
const AInitVal: Byte;
const APolynomial: Byte
): Byte;
var
//!
Here: PByte;
//!
I, J: Integer;
//------------------------------------------------------------------------------
begin
Here := AData;
Result := AInitVal;
for I := 1 to ALen do
begin
Result := Result xor Here^;
for J := 1 to 8 do
begin
if ((Result and $80) <> 0) then
Result := (Result shl 1) xor APolynomial
else
Result := Result shl 1;
end;
Inc(Here);
end;
end;
function CRC8Std(
const AData: Pointer;
const ALen: Integer
): Byte;
begin
Result := CRC8(AData, ALen, $ff, $31);
end;
function CRC16(
const AData: Pointer;
const ALen: Integer;
const AInitVal: Word;
const APolynomial: Word
): Word;
var
//!
Here: PByte;
//!
I, J: Integer;
//------------------------------------------------------------------------------
begin
Here := AData;
Result := AInitVal;
for I := 1 to ALen do
begin
Result := Result xor (Word(Here^) shl 8);
for J := 1 to 8 do
begin
if ((Result and $8000) <> 0) then
Result := (Result shl 1) xor APolynomial
else
Result := Result shl 1;
end;
Inc(Here);
end;
end;
function CRC16Std(
const AData: Pointer;
const ALen: Integer
): Word;
begin
Result := CRC16(AData, ALen, $ffff, $1021);
end;
function CRC16WialonIPS(
const AData: Pointer;
const ALen: Integer
): Word;
const
WialonIPSCRC16: array [0..255] of Word = (
$0000,$C0C1,$C181,$0140,$C301,$03C0,$0280,$C241, $C601,$06C0,$0780,$C741,$0500,$C5C1,$C481,$0440,
$CC01,$0CC0,$0D80,$CD41,$0F00,$CFC1,$CE81,$0E40, $0A00,$CAC1,$CB81,$0B40,$C901,$09C0,$0880,$C841,
$D801,$18C0,$1980,$D941,$1B00,$DBC1,$DA81,$1A40, $1E00,$DEC1,$DF81,$1F40,$DD01,$1DC0,$1C80,$DC41,
$1400,$D4C1,$D581,$1540,$D701,$17C0,$1680,$D641, $D201,$12C0,$1380,$D341,$1100,$D1C1,$D081,$1040,
$F001,$30C0,$3180,$F141,$3300,$F3C1,$F281,$3240, $3600,$F6C1,$F781,$3740,$F501,$35C0,$3480,$F441,
$3C00,$FCC1,$FD81,$3D40,$FF01,$3FC0,$3E80,$FE41, $FA01,$3AC0,$3B80,$FB41,$3900,$F9C1,$F881,$3840,
$2800,$E8C1,$E981,$2940,$EB01,$2BC0,$2A80,$EA41, $EE01,$2EC0,$2F80,$EF41,$2D00,$EDC1,$EC81,$2C40,
$E401,$24C0,$2580,$E541,$2700,$E7C1,$E681,$2640, $2200,$E2C1,$E381,$2340,$E101,$21C0,$2080,$E041,
$A001,$60C0,$6180,$A141,$6300,$A3C1,$A281,$6240, $6600,$A6C1,$A781,$6740,$A501,$65C0,$6480,$A441,
$6C00,$ACC1,$AD81,$6D40,$AF01,$6FC0,$6E80,$AE41, $AA01,$6AC0,$6B80,$AB41,$6900,$A9C1,$A881,$6840,
$7800,$B8C1,$B981,$7940,$BB01,$7BC0,$7A80,$BA41, $BE01,$7EC0,$7F80,$BF41,$7D00,$BDC1,$BC81,$7C40,
$B401,$74C0,$7580,$B541,$7700,$B7C1,$B681,$7640, $7200,$B2C1,$B381,$7340,$B101,$71C0,$7080,$B041,
$5000,$90C1,$9181,$5140,$9301,$53C0,$5280,$9241, $9601,$56C0,$5780,$9741,$5500,$95C1,$9481,$5440,
$9C01,$5CC0,$5D80,$9D41,$5F00,$9FC1,$9E81,$5E40, $5A00,$9AC1,$9B81,$5B40,$9901,$59C0,$5880,$9841,
$8801,$48C0,$4980,$8941,$4B00,$8BC1,$8A81,$4A40, $4E00,$8EC1,$8F81,$4F40,$8D01,$4DC0,$4C80,$8C41,
$4400,$84C1,$8581,$4540,$8701,$47C0,$4680,$8641, $8201,$42C0,$4380,$8341,$4100,$81C1,$8081,$4040);
var
//!
Here: PByte;
//!
I: Integer;
//------------------------------------------------------------------------------
begin
Result := 0;
Here := AData;
for I := 1 to ALen do
begin
Result := (Result shr 8) xor WialonIPSCRC16[Lo(Result) xor Here^];
Inc(Here);
end;
end;
end.
|
unit utility; { DPL 2004-03-22 }
{ uninitialized variable correction in function grep; RDT 2022-07-27 }
{ Utilities, mainly aids to parsing }
interface
function equalsIgnoreCase(s1, s2: string): boolean;
function startsWithIgnoreCase(s1, s2: string): boolean;
function endsWith(s1, s2: string): boolean;
function startsWithBracedWord (P: string): boolean;
function GetNextWord (var s: string; Delim, Term: char): string;
function NextWord (s: string; Delim, Term: char): string;
function wordCount (s: string): integer;
function plural (n: integer): string;
function curtail (var s: string; c: char): integer;
{ Remove last character if it equals c and return its position;
otherwise return 0 }
function toString(n: integer): string;
procedure trim(var s: string);
function digit(c: char): integer;
function match(source, pattern: string): boolean;
function translate(source, pattern, target: string): string;
procedure grep(var source, pattern, target: string);
{ See Implementation for what this currently does. }
implementation uses strings;
const blank = ' '; dummy = #0;
function wordCount (s: string): integer;
var i, n: integer;
begin if length(s)=0 then
begin wordCount:=0; exit; end;
if s[1]=blank then n:=0 else n:=1;
for i:=1 to length(s)-1 do
if (s[i]=blank) and (s[i+1]<>blank) then inc(n);
wordCount:=n;
end;
function GetNextWord (var s: string; Delim, Term: char): string;
{ A delimiter is a character that separates words, but forms no part
of them. A terminator is a character that appears at the end of
a word. }
var n, start, last: integer;
begin last:=length(s); n:=1;
while (n<=last) and (s[n] = Delim) do inc(n);
start:=n;
while (n<=last) and not (s[n] in [Delim,Term]) do inc(n);
if (n<=last) and (s[n] = Term) then inc(n);
GetNextWord:=substr(s,start,n-start);
while (n<=last) and (s[n] = Delim) do inc(n);
predelete(s,n-1);
end;
function NextWord (s: string; Delim, Term: char): string;
begin NextWord:=GetNextWord(s,Delim,Term); end;
function plural (n: integer): string;
begin if n=1 then plural:='' else plural:='s'; end;
function curtail (var s: string; c: char): integer;
var l: integer;
begin l:=length(s); curtail:=0;
if s[l]=c then begin shorten(s,l-1); curtail:=l; end;
end;
function toString(n: integer): string;
var s: string;
begin str(n,s); toString:=s; end;
function digit(c: char): integer;
begin digit:=ord(c)-ord('0'); end;
function equalsIgnoreCase(s1, s2: string): boolean;
begin toUpper(s1); toUpper(s2); equalsIgnoreCase:=s1=s2;
end;
function startsWithIgnoreCase(s1, s2: string): boolean;
begin toUpper(s1); toUpper(s2); startsWithIgnoreCase:=startsWith(s1,s2);
end;
function startsWithBracedWord (P: string): boolean;
var w: string;
begin w := getNextWord(P,blank,dummy);
startsWithBracedWord := (w[1]='{') and (w[length(w)]='}');
end;
procedure trim(var s: string);
var k: integer;
begin k:=posnot(blank,s);
if k>1 then predelete(s,k-1) else if k=0 then s:='';
end;
function endsWith(s1, s2: string): boolean;
var l1, l2: integer;
begin l1:=length(s1); l2:=length(s2);
if l1<l2 then begin endsWith:=false; exit end;
predelete(s1,l1-l2); endsWith:=s1=s2
end;
{--- Match/Replace package --- }
{ Search and replace. Stops when pattern no longer matches source.
Pattern wildcards:
? Any single character
* Any string
# An unsigned integer
## A signed integer
### A signed number maybe with a decimal part
Pattern metacharacters:
\x where x is any character, stands for that character
Target wildcards
\0 to \9 Value of corresponding source wildcard
Target metacharacters
\ When not followed by 0..9 or \, stands for itself
\\ Backslash
}
procedure grep(var source, pattern, target: string);
var p1, p2: array[0..9] of integer;
i, j, p, s, t, index, reg: integer;
product: string;
trigger, matching: boolean;
procedure remember(s1, s2: integer);
begin if index>9 then halt(9999);
p1[index] := s1; p2[index] := s2; s := s2+1; inc(index)
end;
procedure matchnum;
var allowsign, allowpoint, quit: boolean;
s0: integer;
begin allowsign := false; allowpoint := false; matching := false; s0 := s;
if p<length(pattern) then if pattern[p+1]='#' then
begin inc(p); allowsign := true;
if p<length(pattern) then if pattern[p+1]='#' then
begin inc(p); allowpoint := true end
end;
if allowsign and ((source[s]='-') or (source[s]='+')) then
begin inc(s); if s>length(source) then exit end;
quit := false;
while (not quit) and (s<=length(source)) do
begin if source[s]='.' then if not allowpoint then quit := true else
begin inc(s); allowpoint := false end;
if (source[i]>='0') and (source[i]<='9') then
begin inc(s); matching := true end
else quit := true
end;
if matching then remember(s0,s-1)
end;
procedure matchmeta;
begin if p<length(pattern) then inc(p);
if source[s]=pattern[p] then begin inc(s); inc(p) end
else matching := false
end;
procedure subgrep;
begin matching := true;
if pattern[p]='*' then begin remember(s,length(source)); inc(p) end
else if pattern[p]='?' then begin remember(s,s); inc(p) end
else if pattern[p]='#' then matchnum
else if pattern[p]='\' then matchmeta
else if source[s]=pattern[p] then begin inc(s); inc(p) end
else matching := false
end;
begin
index := 0; s := 1; p := 1;
for i:=0 to 9 do begin p1[i]:=1; p2[i]:=0 end;
matching := true; { added by RDT 2022-07-27 }
while matching and (p<=length(pattern)) and (s<=length(source)) do subgrep;
product := ''; trigger := false;
for t:=1 to length(target) do if trigger then
begin reg := digit(target[t]); if (reg>=0) and (reg<=9) then
for j:=p1[reg] to p2[reg] do product := product + source[j]
else if target[t]='\' then product := product + '\'
else product := product + '\' + target[t];
trigger := false
end
else if (target[t]='\') and (t<length(target)) then trigger := true
else product := product + target[t];
source := substr(source,s,length(source));
pattern := substr(pattern,p,length(pattern));
target := product
end;
{ "match" tests whether the source matches the pattern exactly }
function match(source, pattern: string): boolean;
const target: string = '';
begin grep(source, pattern, target);
match := (source='') and (pattern='')
end;
{ "translate" replaces the pattern by the target in the source. }
function translate(source, pattern, target: string): string;
begin grep(source, pattern, target); translate := target;
end;
end.
|
namespace RemObjects.Elements.EUnit;
interface
uses
RemObjects.Elements.EUnit.Reflections;
type
Assert = public partial static class {$IF NOUGAT}mapped to Object{$ENDIF}
private
method TypeToString(aType: NativeType): String;
public
method Throws(Action: AssertAction; Message: String := nil);
method Throws(Action: AssertAction; OfType: NativeType; Message: String := nil);
method DoesNotThrows(Action: AssertAction; Message: String := nil);
method Catch(Action: AssertAction; Message: String := nil): Exception;
end;
implementation
class method Assert.TypeToString(aType: NativeType): String;
begin
if aType = nil then
exit nil;
exit new TypeReference(aType).Name;
end;
class method Assert.Throws(Action: AssertAction; Message: String := nil);
begin
var Ex := ExceptionHelper.CatchException(Action);
FailIf(Ex = nil, coalesce(Message, AssertMessages.NoException));
end;
class method Assert.Throws(Action: AssertAction; OfType: NativeType; Message: String := nil);
begin
var Ex := ExceptionHelper.CatchException(Action);
FailIf(Ex = nil, coalesce(Message, AssertMessages.NoException));
FailIfNot(typeOf(Ex) = OfType, TypeToString(typeOf(Ex)), TypeToString(OfType), coalesce(Message, AssertMessages.NotEqual));
end;
class method Assert.DoesNotThrows(Action: AssertAction; Message: String := nil);
begin
var Ex := ExceptionHelper.CatchException(Action);
FailIf(Ex <> nil, TypeToString(typeOf(Ex)), nil, coalesce(Message, AssertMessages.UnexpectedException));
end;
class method Assert.Catch(Action: AssertAction; Message: String := nil): Exception;
begin
var Ex := ExceptionHelper.CatchException(Action);
FailIf(Ex = nil, coalesce(Message, AssertMessages.NoException));
exit Ex;
end;
end. |
{
@abstract Implements routines that help you internationalize menus.
If you use runtime language switch the short cut text of menu items do
not change. This is because VCL stores the initial resource string in an array
and if you change the language the array still holds the resource strings in
default language. This unit makes the array to change it value after a language switch.
The unit does not expose any functions but you just add this into your project.
@longCode(#
implementation
uses
NtMenu;
#)
See @italic(Samples\Delphi\VCL\Menu) sample to see how to use the unit.
This unit can translste the shortcut only on 32-bit projects.
On 64-bit platform it does nothing.
}
unit NtMenu;
{$I NtVer.inc}
interface
implementation
uses
Windows, Classes, Consts, Menus, SysUtils, NtLocalization;
type
TMenuKeyCap =
(
mkcBkSp,
mkcTab,
mkcEsc,
mkcEnter,
mkcSpace,
mkcPgUp,
mkcPgDn,
mkcEnd,
mkcHome,
mkcLeft,
mkcUp,
mkcRight,
mkcDown,
mkcIns,
mkcDel,
mkcShift,
mkcCtrl,
mkcAlt
);
function MenuKeyCaps(value: TMenuKeyCap): String;
begin
case value of
mkcBkSp: Result := SmkcBkSp;
mkcTab: Result := SmkcTab;
mkcEsc: Result := SmkcEsc;
mkcEnter: Result := SmkcEnter;
mkcSpace: Result := SmkcSpace;
mkcPgUp: Result := SmkcPgUp;
mkcPgDn: Result := SmkcPgDn;
mkcEnd: Result := SmkcEnd;
mkcHome: Result := SmkcHome;
mkcLeft: Result := SmkcLeft;
mkcUp: Result := SmkcUp;
mkcRight: Result := SmkcRight;
mkcDown: Result := SmkcDown;
mkcIns: Result := SmkcIns;
mkcDel: Result := SmkcDel;
mkcShift: Result := SmkcShift;
mkcCtrl: Result := SmkcCtrl;
mkcAlt: Result := SmkcAlt;
else
Result := '';
end;
end;
function GetSpecialName(ShortCut: TShortCut): String;
var
scanCode: Integer;
keyName: array[0..255] of Char;
begin
Result := '';
scanCode := MapVirtualKey(WordRec(shortCut).Lo, 0) shl 16;
if scanCode <> 0 then
begin
GetKeyNameText(scanCode, keyName, SizeOf(keyName));
Result := keyName;
end;
end;
function ShortCutToText(shortCut: TShortCut): String;
var
key: Byte;
name: String;
begin //FI:C101
key := LoByte(Word(shortCut));
case key of
$08, $09:
name := MenuKeyCaps(TMenuKeyCap(Ord(mkcBkSp) + key - $08));
$0D:
name := MenuKeyCaps(mkcEnter);
$1B:
name := MenuKeyCaps(mkcEsc);
$20..$28:
name := MenuKeyCaps(TMenuKeyCap(Ord(mkcSpace) + key - $20));
$2D..$2E:
name := MenuKeyCaps(TMenuKeyCap(Ord(mkcIns) + key - $2D));
$30..$39:
name := Chr(key - $30 + Ord('0'));
$41..$5A:
name := Chr(key - $41 + Ord('A'));
$60..$69:
name := Chr(key - $60 + Ord('0'));
$70..$87:
name := 'F' + IntToStr(key - $6F);
else
name := GetSpecialName(shortCut);
end;
if name <> '' then
begin
Result := '';
if shortCut and scShift <> 0 then
Result := Result + MenuKeyCaps(mkcShift);
if shortCut and scCtrl <> 0 then
Result := Result + MenuKeyCaps(mkcCtrl);
if shortCut and scAlt <> 0 then
Result := Result + MenuKeyCaps(mkcAlt);
Result := Result + name;
end
else
Result := '';
end;
function TextToShortCut(text: String): TShortCut; //FI:O801
function CompareFront(var text: String; const front: String): Boolean;
begin
Result := False;
if (Length(text) >= Length(front)) and (AnsiStrLIComp(PChar(text), PChar(front), Length(front)) = 0) then
begin
Result := True;
Delete(text, 1, Length(Front));
end;
end;
var
key: TShortCut;
shift: TShortCut;
begin
Result := 0;
shift := 0;
while True do
begin
if CompareFront(Text, MenuKeyCaps(mkcShift)) then
shift := shift or scShift
else if CompareFront(Text, '^') then
shift := shift or scCtrl
else if CompareFront(Text, MenuKeyCaps(mkcCtrl)) then
shift := shift or scCtrl
else if CompareFront(Text, MenuKeyCaps(mkcAlt)) then
shift := shift or scAlt
else
Break;
end;
if text = '' then
Exit;
for key := $08 to $255 do
if AnsiCompareText(text, ShortCutToText(key)) = 0 then
begin
Result := key or shift;
Exit;
end;
end;
var
ShortCutToTextCode: TNtProcedureData;
TextToShortCutCode: TNtProcedureData;
initialization
TNtMap.RemapProcedure(@Menus.ShortCutToText, @ShortCutToText, ShortCutToTextCode);
TNtMap.RemapProcedure(@Menus.TextToShortCut, @TextToShortCut, TextToShortCutCode);
end.
|
unit Ils.Stat.Sender;
interface
uses
blcksock, SysUtils ;
type
TIlsStatSender = class
protected
FSock: TUDPBlockSocket;
public
// procedure Send(AHost: string; AMessage: string); overload;
procedure Send(AMessage: string); //overload;
constructor Create(AHost: string);
destructor Destroy; override;
end;
const
CIlsStatPort = 11111;
CSOTest = 'Test';
CSONovacomRecv = 'NovacomRecv';
CSOWialonRecv = 'WialonRecv';
CSOMintransRecv = 'MintransRecv';
CSONavtelecomRecv = 'NavtelecomRecv';
CSORusAgroTaxiRecv = 'RusAgroTaxiRecv';
CSORuptelaRecv = 'RuptelaRecv';
CSOWialonIPS2Repl = 'WialonIPS2Repl';
CSOKafkaSplit = 'KafkaSplit';
CSOKafkaWebPrxy = 'KafkaWebPrxy';
CSOTranslationEdit = 'TranslationEdit';
implementation
{ TIlsStatSender }
constructor TIlsStatSender.Create(AHost: string);
begin
FSock := TUDPBlockSocket.Create;
FSock.Connect(AHost, IntToStr(CIlsStatPort));
end;
destructor TIlsStatSender.Destroy;
begin
FSock.Free;
end;
//procedure TIlsStatSender.Send(AHost: string; AMessage: string);
//begin
// FSock.SendString(AnsiString(AMessage));
//end;
procedure TIlsStatSender.Send(AMessage: string);
begin
FSock.SendString(AnsiString(AMessage));
end;
end.
|
unit ModflowRCH_WriterUnit;
interface
uses SysUtils, Classes, Contnrs, CustomModflowWriterUnit, ScreenObjectUnit,
ModflowBoundaryUnit, ModflowPackageSelectionUnit, OrderedCollectionUnit,
ModflowCellUnit, PhastModelUnit, ModflowBoundaryDisplayUnit;
Type
TModflowRCH_Writer = class(TCustomTransientArrayWriter)
private
NPRCH: integer;
NRCHOP: integer;
FRchPackage: TRchPackageSelection;
procedure WriteDataSet1;
procedure WriteDataSet2;
procedure WriteDataSets3And4;
procedure WriteDataSets5To8;
procedure WriteCells(CellList: TValueCellList; const DataSetIdentifier,
VariableIdentifiers: string);
protected
function CellType: TValueCellType; override;
function Prefix: string; override;
class function Extension: string; override;
function GetBoundary(ScreenObject: TScreenObject): TModflowBoundary;
override;
function Package: TModflowPackageSelection; override;
function ParameterType: TParameterType; override;
procedure WriteStressPeriods(const VariableIdentifiers, DataSetIdentifier,
DS5, D7PNameIname, D7PName: string); override;
procedure Evaluate; override;
public
procedure WriteFile(const AFileName: string);
procedure UpdateDisplay(TimeLists: TModflowBoundListOfTimeLists);
end;
implementation
uses RbwParser, ModflowUnitNumbers, ModflowTransientListParameterUnit,
frmErrorsAndWarningsUnit, DataSetUnit, ModflowRchUnit, GoPhastTypes,
frmProgressUnit, Forms, Windows;
resourcestring
StrNoRechargeDefined = 'No recharge defined';
StrTheRechargePackage = 'The recharge package is active but no recharge ha' +
's been defined for any stress period.';
StrWritingRCHPackage = 'Writing RCH Package input.';
// StrWritingDataSet0 = ' Writing Data Set 0.';
// StrWritingDataSet1 = ' Writing Data Set 1.';
// StrWritingDataSet2 = ' Writing Data Set 2.';
// StrWritingDataSets3and4 = ' Writing Data Sets 3 and 4.';
// StrWritingDataSets5to8 = ' Writing Data Sets 5 to 8.';
StrWritingStressP = ' Writing Stress Period %d';
// ErrorRoot = 'One or more %s parameters have been eliminated '
// + 'because there are no cells associated with them.';
StrNoParametersHaveB = 'No parameters have been defined for the Recharge p' +
'ackage for the following Stress periods.';
{ TModflowRCH_Writer }
function TModflowRCH_Writer.CellType: TValueCellType;
begin
result := TRch_Cell;
end;
procedure TModflowRCH_Writer.Evaluate;
var
ScreenObjectIndex: Integer;
ScreenObject: TScreenObject;
Boundary: TRchBoundary;
begin
inherited;
for ScreenObjectIndex := 0 to Model.ScreenObjectCount - 1 do
begin
ScreenObject := Model.ScreenObjects[ScreenObjectIndex];
if ScreenObject.Deleted then
begin
Continue;
end;
if not ScreenObject.UsedModels.UsesModel(Model) then
begin
Continue;
end;
Boundary := ScreenObject.ModflowRchBoundary;
if Boundary <> nil then
begin
Boundary.GetRechargeLayerCells(FLayers, Model);
Boundary.RechargeLayers.ClearBoundaries(Model);
end;
end;
end;
class function TModflowRCH_Writer.Extension: string;
begin
result := '.rch';
end;
function TModflowRCH_Writer.GetBoundary(
ScreenObject: TScreenObject): TModflowBoundary;
begin
result := ScreenObject.ModflowRchBoundary;
end;
function TModflowRCH_Writer.Package: TModflowPackageSelection;
begin
result := Model.ModflowPackages.RchPackage;
end;
function TModflowRCH_Writer.ParameterType: TParameterType;
begin
result := ptRCH;
end;
function TModflowRCH_Writer.Prefix: string;
begin
result := 'R'
end;
procedure TModflowRCH_Writer.UpdateDisplay(
TimeLists: TModflowBoundListOfTimeLists);
var
List: TValueCellList;
ParameterValues: TList;
ParametersUsed: TStringList;
TimeIndex: Integer;
Comment: string;
ParamDefArrays: TList;
RechRateTimes: TModflowBoundaryDisplayTimeList;
RechLayerTimes: TModflowBoundaryDisplayTimeList;
RechRateArray: TModflowBoundaryDisplayDataArray;
RechLayerArray: TModflowBoundaryDisplayDataArray;
DefArrayList: TList;
Index: Integer;
ATimeList: TModflowBoundaryDisplayTimeList;
const
D7PNameIname = '';
D7PName = '';
begin
if not Package.IsSelected then
begin
UpdateNotUsedDisplay(TimeLists);
Exit;
end;
// ParameterValues := TValueCellList.Create(CellType);
ParameterValues := TList.Create;
try
Evaluate;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
ClearTimeLists(Model);
ParamDefArrays := TObjectList.Create;
try
EvaluateParameterDefinitions(ParamDefArrays, StrOneOrMoreSParam,
Model.ModflowPackages.RchPackage.AssignmentMethod);
NPRCH := ParameterCount;
NRCHOP := Ord(Model.ModflowPackages.RchPackage.LayerOption) + 1;
RechRateTimes := TimeLists[0];
RechLayerTimes := TimeLists[1];
Comment := '# Data Set 8: IRCH';
if Values.Count = 0 then
begin
SetTimeListsUpToDate(TimeLists);
Exit;
end;
for TimeIndex := 0 to Values.Count - 1 do
begin
RechRateArray := RechRateTimes[TimeIndex]
as TModflowBoundaryDisplayDataArray;
if RechLayerTimes = nil then
begin
RechLayerArray := nil;
end
else
begin
RechLayerArray := RechLayerTimes[TimeIndex]
as TModflowBoundaryDisplayDataArray;
end;
ParametersUsed := TStringList.Create;
try
RetrieveParametersForStressPeriod(D7PNameIname, D7PName, TimeIndex,
ParametersUsed, ParameterValues, True);
List := Values[TimeIndex];
// List.CheckRestore;
if NPRCH = 0 then
begin
// data set 6
AssignTransient2DArray(RechRateArray, 0, List, 0, rdtDouble,
Model.ModflowPackages.RchPackage.AssignmentMethod);
end
else
begin
// data set 7
DefArrayList := ParamDefArrays[TimeIndex];
UpdateTransient2DArray(RechRateArray, DefArrayList);
end;
Model.AdjustDataArray(RechRateArray);
RechRateArray.CacheData;
// Data set 8
if RechLayerArray <> nil then
begin
if (Model.ModflowPackages.RchPackage.
LayerOption = loSpecified)
and not Model.ModflowPackages.RchPackage.
TimeVaryingLayers and (ParameterCount > 0) then
begin
RetrieveParametersForStressPeriod(D7PNameIname, D7PName, 0,
ParametersUsed, ParameterValues, True);
List := Values[0];
end;
UpdateLayerDisplay(List, ParameterValues, TimeIndex,
RechLayerArray);
RechLayerArray.CacheData;
end;
List.Cache;
finally
ParametersUsed.Free;
end;
end;
for Index := 0 to TimeLists.Count - 1 do
begin
ATimeList := TimeLists[Index];
if ATimeList <> nil then
begin
ATimeList.SetUpToDate(True);
end;
end;
finally
ParamDefArrays.Free;
end;
finally
ParameterValues.Free;
end;
end;
procedure TModflowRCH_Writer.WriteDataSet1;
begin
NPRCH := ParameterCount;
if NPRCH > 0 then
begin
WriteString('PARAMETER');
WriteInteger(NPRCH);
WriteString(' # PARAMETER NPRCH');
NewLine;
end;
end;
procedure TModflowRCH_Writer.WriteDataSet2;
var
IRCHCB: integer;
begin
NRCHOP := Ord(Model.ModflowPackages.RchPackage.LayerOption) + 1;
GetFlowUnitNumber(IRCHCB);
WriteInteger(NRCHOP);
WriteInteger(IRCHCB);
WriteString(' # DataSet 2: NRCHOP IRCHCB');
NewLine
end;
procedure TModflowRCH_Writer.WriteDataSets3And4;
const
DS3 = ' # Data Set 3: PARNAM PARTYP Parval NCLU';
DS3Instances = ' INSTANCES NUMINST';
DS4A = ' # Data Set 4a: INSTNAM';
DataSetIdentifier = 'Data Set 4b:';
VariableIdentifiers = 'Condfact';
begin
WriteParameterDefinitions(DS3, DS3Instances, DS4A, DataSetIdentifier,
VariableIdentifiers, StrOneOrMoreSParam, FRchPackage.AssignmentMethod,
FRchPackage.MultiplierArrayNames, FRchPackage.ZoneArrayNames);
end;
procedure TModflowRCH_Writer.WriteDataSets5To8;
const
D7PName = ' # Data Set 7: PARNAM IRCHPF';
D7PNameIname = ' # Data Set 7: PARNAM Iname IRCHPF';
DS5 = ' # Data Set 5: INRECH INIRCH';
DataSetIdentifier = 'Data Set 6:';
VariableIdentifiers = 'RECH';
begin
WriteStressPeriods(VariableIdentifiers, DataSetIdentifier, DS5,
D7PNameIname, D7PName);
end;
procedure TModflowRCH_Writer.WriteFile(const AFileName: string);
begin
// OutputDebugString('SAMPLING ON');
if not Package.IsSelected then
begin
Exit
end;
FRchPackage := Package as TRchPackageSelection;
if Model.PackageGeneratedExternally(StrRCH) then
begin
Exit;
end;
// if Model.ModelSelection = msModflow2015 then
// begin
// Abbreviation := 'RCH8';
// end
// else
// begin
// Abbreviation := StrRCH;
// end;
FRchPackage.MultiplierArrayNames.Clear;
FRchPackage.ZoneArrayNames.Clear;
FNameOfFile := FileName(AFileName);
WriteToNameFile(StrRCH, Model.UnitNumbers.UnitNumber(StrRCH),
FNameOfFile, foInput, Model);
Evaluate;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
ClearTimeLists(Model);
OpenFile(FileName(AFileName));
try
frmProgressMM.AddMessage(StrWritingRCHPackage);
frmProgressMM.AddMessage(StrWritingDataSet0);
WriteDataSet0;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSet1);
WriteDataSet1;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSet2);
WriteDataSet2;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSets3and4);
WriteDataSets3And4;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSets5to8);
WriteDataSets5To8;
finally
CloseFile;
// Clear;
end;
// OutputDebugString('SAMPLING OFF');
end;
procedure TModflowRCH_Writer.WriteCells(CellList: TValueCellList;
const DataSetIdentifier, VariableIdentifiers: string);
var
DefaultValue: double;
DataType: TRbwDataType;
DataTypeIndex: integer;
Comment: string;
Dummy: TDataArray;
begin
DefaultValue := 0;
DataType := rdtDouble;
DataTypeIndex := 0;
Comment := DataSetIdentifier + ' ' + VariableIdentifiers;
WriteTransient2DArray(Comment, DataTypeIndex, DataType,
DefaultValue, CellList, Model.ModflowPackages.RchPackage.AssignmentMethod,
True, Dummy, VariableIdentifiers);
end;
procedure TModflowRCH_Writer.WriteStressPeriods(const VariableIdentifiers,
DataSetIdentifier, DS5, D7PNameIname, D7PName: string);
var
NP: Integer;
RechRateList, PriorRechRateList: TValueCellList;
ParameterValues: TValueCellList;
ParamIndex: Integer;
ParametersUsed: TStringList;
TimeIndex: Integer;
INRECH, INIRCH: Integer;
Comment: string;
begin
inherited;
frmErrorsAndWarnings.BeginUpdate;
try
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrNoParametersHaveB);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrNoRechargeDefined);
ParameterValues := TValueCellList.Create(CellType);
try
ParameterValues.OwnsObjects := False;
Comment := '# Data Set 8: IRCH';
if Values.Count = 0 then
begin
frmErrorsAndWarnings.AddError(Model, StrNoRechargeDefined,
StrTheRechargePackage);
end;
for TimeIndex := 0 to Values.Count - 1 do
begin
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(Format(StrWritingStressP, [TimeIndex+1]));
ParametersUsed := TStringList.Create;
try
RetrieveParametersForStressPeriod(D7PNameIname, D7PName, TimeIndex,
ParametersUsed, ParameterValues, True);
NP := ParametersUsed.Count;
RechRateList := Values[TimeIndex];
// data set 5;
if NPRCH > 0 then
begin
INRECH := NP;
end
else
begin
if (TimeIndex > 0) then
begin
PriorRechRateList := Values[TimeIndex-1];
if PriorRechRateList.AreRealValuesIdentical(RechRateList, 0) then
begin
INRECH := -1;
// RechRateList.Cache;
end
else
begin
INRECH := 1;
end;
PriorRechRateList.Cache;
end
else
begin
INRECH := 1;
end;
end;
INIRCH := 1;
WriteInteger(INRECH);
WriteInteger(INIRCH);
WriteString(DS5 + ' Stress period ' + IntToStr(TimeIndex+1));
NewLine;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
if INRECH > 0 then
begin
if NPRCH = 0 then
begin
// data set 6
WriteCells(RechRateList, DataSetIdentifier, VariableIdentifiers);
end
else
begin
// data set 7
if ParametersUsed.Count = 0 then
begin
frmErrorsAndWarnings.AddError(Model, StrNoParametersHaveB,
IntToStr(TimeIndex+1));
end;
for ParamIndex := 0 to ParametersUsed.Count - 1 do
begin
WriteString(ParametersUsed[ParamIndex]);
NewLine;
end;
end;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
RechRateList.Cache;
Exit;
end;
end;
// Data set 8
WriteLayerSelection(RechRateList, ParameterValues, TimeIndex, Comment, 'IRCH');
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
RechRateList.Cache;
Exit;
end;
if TimeIndex = Values.Count - 1 then
begin
RechRateList.Cache;
end;
finally
ParametersUsed.Free;
end;
end;
finally
ParameterValues.Free;
end;
finally
frmErrorsAndWarnings.EndUpdate;
end;
end;
end.
|
unit uSistema;
interface
uses
System.IniFiles;
type
TSistema = class
private
class var fIniSistema : TIniFile;
public
class procedure SetUltimoAcesso(Usuario: String);
class function GetUltimoAcesso : String;
class function GetUsuarioAcesso : String;
end;
implementation
uses
Vcl.Forms, System.SysUtils;
{ TSistema }
class function TSistema.GetUltimoAcesso: String;
begin
fIniSistema := TIniFile.Create(ExtractFilePath(Application.ExeName)+'config.ini');
try
result := 'Último acesso: '+fIniSistema.ReadString('ACESSO','DATA','');
finally
FreeAndNil(fIniSistema);
end;
end;
class function TSistema.GetUsuarioAcesso: String;
begin
fIniSistema := TIniFile.Create(ExtractFilePath(Application.ExeName)+'config.ini');
try
result := fIniSistema.ReadString('ACESSO','USUARIO','');
finally
FreeAndNil(fIniSistema);
end;
end;
class procedure TSistema.SetUltimoAcesso(Usuario: String);
begin
fIniSistema := TIniFile.Create(ExtractFilePath(Application.ExeName)+'config.ini');
try
fIniSistema.WriteString('ACESSO','USUARIO',Usuario);
fIniSistema.WriteString('ACESSO','DATA',DateTimeToStr(now));
finally
FreeAndNil(fIniSistema);
end;
end;
end.
|
unit WarodaiTemplates;
{
Обработка шаблонов и примеров.
Шаблоны:
~にする мариновать в мисо;
Примеры:
味の抜けた безвкусный;
}
interface
uses Warodai, FastArray;
{$INCLUDE 'Warodai.inc'}
{ Возвращает номер символа подстановки в шаблоне или 0 }
function FindTemplate(const ln: string): integer;
{
Некоторые шаблоны содержат перевод на этой же строчке - это локальные шаблоны:
~する поднимать [большой] шум
~にする мариновать в мисо;
Другие содержат только шаблон, например:
~にする
Такие шаблоны потенциально значат, что дальнейшие записи переводов относятся
уже не к главное статье, а к модифицированной шаблоном.
}
function IsOpenTemplate(const ln: string): boolean;
type
TTemplateList = array of string;
{
Находит в строке шаблон или список шаблонов, удаляет их и возвращает отдельно.
False => в строке нет шаблона.
Некоторые правила содержат несколько шаблонов сразу:
~たる, ~とした <i>см.</i> <a href="#1-046-1-45">ばくばく</a>.
Предпочтительнее для разных (грам.) слов иметь разные статьи, поэтому мы считаем
это за два раздельных шаблона.
Правила могут содержать опциональные блоки:
~[の] абстрактный;
Или альтернативные блоки:
~とした(とし)
Бывает даже несколько вариантов в блоке:
[…を, …に]~する томиться, тосковать, вздыхать [о ком-чём-л.].
Всё это мы считаем за разновидности одного шаблона - см. ниже GenerateTemplateVariants()
}
function ExtractTemplate(var ln: string; out t_p: TTemplateList): boolean;
{ Преобразует слово согласно шаблону.
В принципе шаблон один, но иногда в нём встречается не совсем кана (напр. ~的),
и мы это учитываем }
function ApplyTemplateKanji(const templ: string; const word: string): string;
function ApplyTemplateKana(const templ: string; const word: string): string;
{
Из одного шаблона мы генерируем список его фиксированных вариантов.
Для шаблона будет создана отдельная статья, в которой будут указаны все
получившиеся комбинации всех вариантов кандзи и каны статьи с вариантами шаблона.
Можно было бы поступить как с запятыми, и сделать из опциональных блоков
тоже отдельные шаблоны, но похоже, что обычно варианты в квадратных скобках
ближе к одному шаблону, чем к разным.
}
type
TTemplateVariants = TArray<string>;
PTemplateVariants = ^TTemplateVariants;
procedure GenerateTemplateVariants(const templ: string; tvars: PTemplateVariants);
{
Некоторые шаблоны не нужно применять, поскольку они означают определённое
грамматическое употребление:
ほうそう【包装】(хо:со:)〔2-504-1-29〕
упаковка; обёртка;
~する упаковывать; обёртывать.
Вместо этого в новой статье нужно выставить грамматический флаг.
Часто эту статью можно даже объединить с главной:
ある限り [あるかぎり] /(n) (1) all (there is)/(exp,n-adv) (2) as long as there is/
Дальше идёт список таких шаблонов.
}
type
TTemplateMarkerMapping = record
t: string; //template
m: string; //markers, через запятую
end;
PTemplateMarkerMapping = ^TTemplateMarkerMapping;
const
TEMPL_MARK: array[0..7] of TTemplateMarkerMapping = (
(t: '~する'; m: 'vs'),
(t: '~した'; m: ''),
(t: '~の'; m: ''),
(t: '~なる'; m: ''),
(t: ''; m: ''),
(t: ''; m: ''),
(t: ''; m: ''),
(t: ''; m: '')
);
{
Разбирает строку в форме примера:
埃を浴びる быть покрытым пылью, быть в пыли;
喝采を浴びて под гром аплодисментов;
Вынимает из неё сам пример и кладёт в expr. Оставляет в строке перевод.
Возвращает false, если пример не был найден.
Выполняет некоторые проверки на целостность этого вхождения.
}
function ExtractExample(var ln: string; out expr: string): boolean;
implementation
uses SysUtils, UniStrUtils, JWBStrings, WcExceptions;
{
Разбор шаблонов.
}
function FindTemplate(const ln: string): integer;
begin
Result := pos('~', ln);
end;
{ True, если наличие указанного символа относит слово к шаблону }
function IsTrueTemplateChar(const ch: char): boolean;
begin
Result := IsKana(ch) or IsKanji(ch)
or IsCJKSymbolOrPunctuation(ch)
or IsFullWidthCharacter(ch)
or (ch='~') //сама подстановка
end;
{ True, если указанный символ не разрывает шаблона }
function IsSupplementalTemplateChar(const ch: char): boolean;
begin
Result :=
(ch='[') or (ch=']') //необязательные части шаблона
or (ch='(') or (ch=')') //альтернативные варианты шаблона
or (ch='…') //обозначает "какое-нибудь слово"
or (ch=',') //перечисление [a, b], хотя и не поддерживаем пока
or (ch='!');
end;
function IsTemplateChar(const ch: char): boolean;
begin
Result := IsTrueTemplateChar(ch)
or IsSupplementalTemplateChar(ch);
end;
function IsOpenTemplate(const ln: string): boolean;
var i: integer;
begin
i := FindTemplate(ln);
if i<=0 then begin
Result := false;
exit;
end;
Inc(i);
while IsTemplateChar(ln[i]) or (ln[i]=' ') do
Inc(i);
Result := (ln[i]=#00);
end;
function ExtractTemplate(var ln: string; out t_p: TTemplateList): boolean;
var i_start, i_end, i_tmp: integer;
w_true: boolean;
t: string;
br_round,
br_square: integer;
begin
i_start := FindTemplate(ln);
if i_start<=0 then begin
Result := false;
exit;
end;
//Находим начало шаблона
//Тут мы не будем особо аккуратными, т.к. в целом шаблоны должны идти с начала строки.
//Поэтому можно не опасаться случайно откусить лишнего.
Dec(i_start);
while (i_start>0) and (IsTemplateChar(ln[i_start]) or (ln[i_start]=' ')) do
Dec(i_start);
Inc(i_start);
if i_start>1 then begin
//Иногда матчатся вещи типа "см. асдбсд~". Это не темплейты, но и падать не надо.
Result := false;
exit;
end;
br_round := 0; //глубина круглых скобок -- поддерживаем не больше 1 любых
br_square := 0; //глубина квадратных
i_end := i_start;
while ln[i_end]=' ' do Inc(i_end);
repeat
//i_end указывает на первый непробельный символ слова
//Проматываем следующий блок до пробела или совсем стрёмного символа
w_true := false;
i_tmp := i_end;
repeat
if ln[i_tmp]='[' then begin
if (br_round>0) or (br_square>0) then
raise ETemplateParsingException.Create('Broken brackets');
Inc(br_square);
end else
if ln[i_tmp]=']' then begin
if (br_round>0) or (br_square<1) then
raise ETemplateParsingException.Create('Broken brackets');
Dec(br_square);
end else
if ln[i_tmp]='(' then begin
if (br_round>0) or (br_square>0) then
raise ETemplateParsingException.Create('Broken brackets');
Inc(br_round);
end else
if ln[i_tmp]=')' then begin
if (br_round<0) or (br_square>0) then
raise ETemplateParsingException.Create('Broken brackets');
Dec(br_round);
end else
if (ln[i_tmp]=',') or (ln[i_tmp]=' ') then begin
if (br_round<=0) and (br_square<=0) then
break;
//else treat as a normal supplemental char
end else
if IsTrueTemplateChar(ln[i_tmp]) then
w_true := true
else
if not IsSupplementalTemplateChar(ln[i_tmp]) then
break;
Inc(i_tmp);
until false;
//Теперь мы либо на запятой, либо на первом символе слова, который не относится к шаблону
//Хотя вообще говоря, шаблон со словом стыковаться не должен.
if not w_true then //шаблонные символы не были найдены -- слово разрывает шаблон
break;
//Все скобки в пределах годного блока должны быть закрыты
if br_round > 0 then
raise ETemplateParsingException.Create('Non-matched () brackets');
if br_square > 0 then
raise ETemplateParsingException.Create('Non-matched [] brackets');
if ln[i_tmp]=',' then begin
Inc(i_tmp);
if ln[i_tmp]<>' ' then
//По идее должно быть
raise ETemplateParsingException.Create('No space after comma');
Dec(i_tmp);
end else
if ln[i_tmp]=' ' then begin
//nothing
end else begin
//Шаблон стыкуется со словом! В очередном слове шаблонные символы найдены,
//но потом найдены и разрывающие шаблон.
//Сделаем-ка для порядка ошибку. Так не должно быть.
raise ETemplateParsingException.Create('Template word merged with normal word');
end;
//Копируем и проверяем найденное
t := copy(ln, i_end, i_tmp-i_end);
if FindTemplate(t)<=0 then
raise ETemplateParsingException.Create('No ~ in a template block');
//Эти вещи пока не поддерживаем, так что лучше в корявом виде в словарь их не класть
if pos('(',t)>0 then
raise ETemplateParsingException.Create('Alternative template parts -- unsupported');
if countc(t,'[')>1 then //поддерживаем макс. 1
raise ETemplateParsingException.Create('Multiple optional template parts -- unsupported');
//Троеточие на данный момент с краёв убираем, а в центре заменяем на ~,
//а вообще надо посмотреть, как это сделано в стандартном едикте
case pos('…',t) of
0: begin end;
1: delete(t,1,1);
//else raise ETemplateParsingException.Create('Partial expression templates > 1 -- unsupported'); //TODO: restore
end;
//Добавляем
SetLength(t_p, Length(t_p)+1);
t_p[Length(t_p)-1] := t;
//Проматываем пробелы
i_end := i_tmp;
if ln[i_end]=',' then //макс. 1 запятую (обработанную)
Inc(i_end);
while ln[i_end]=' ' do Inc(i_end);
until false;
//Удаляем вместе с пробелами по обе стороны
Dec(i_start);
while (i_start>0) and (ln[i_start]=' ') do
Dec(i_start);
Inc(i_start);
if i_start<>1 then begin
raise EInsideTemplate.Create('Template is not the first thing in the line');
Result:=false;
exit;
end;
//А в i_end пробелы и так промотаны
delete(ln, i_start, i_end-i_start);
{
Не делаем этого, т.к. кандзи и кана могут остаться в строке легальным образом -- например, в форме "см. также".
Вместо этого мы проверим на кандзи и кану перед самым добавлением.
if EvalChars(ln) and (EV_KANA or EV_KANJI) <> 0 then
raise EKanjiKanaLeft.Create('Kanji or kana left in string after doing ExtractTemplate');
}
Result := true;
end;
procedure SplitTemplate(const t: string; out t_p: TTemplateList);
var parts: TStringArray;
i: integer;
begin
parts := SplitStr(PWideChar(t), ',');
SetLength(t_p, Length(parts));
for i := 0 to Length(parts) - 1 do
t_p[i] := Trim(parts[i]);
end;
{ Из множественного шаблона типа "строка [опциональная часть]" делаем набор фиксированных.
Поддерживается только одна опциональная часть. }
procedure GenerateTemplateVariants(const templ: string; tvars: PTemplateVariants);
var po, pc: integer;
begin
tvars^.Clear;
po := pos('[', templ);
if po<=0 then begin
tvars^.Add(templ);
exit;
end;
pc := pos(']', templ);
Assert(pc>po);
if pos(',', copy(templ,po+1,pc-po-1))>0 then
raise ETemplateParsingException.Create('Multiple options for a template part -- unsupported');
tvars^.Add(copy(templ, 1, po-1)+copy(templ,pc+1,Length(templ)-pc));
tvars^.Add(copy(templ, 1, po-1)+copy(templ,po+1,pc-po-1)+copy(templ,pc+1,Length(templ)-pc))
end;
function ApplyTemplateKanji(const templ: string; const word: string): string;
begin
if templ='' then
Result := word
else
Result := repl(templ, '~', word);
end;
function ApplyTemplateKana(const templ: string; const word: string): string;
var templ_kana: string;
begin
//Бывает, что в темплейте указаны некоторые общие кандзи
templ_kana := repl(templ, '的', 'てき');
Result := ApplyTemplateKanji(templ_kana, word); //базовая замена
end;
{
Примеры.
1. Могут содержать японскую пунктуацию:
あっ、鍵を忘れた ах, я забыл ключ!;
2. Могут содержать подсказки по чтению:
あっという間/マ/に в мгновение ока; не успел и ахнуть, как…
3. Может быть несколько с одним переводом
ああいった, ああした такой;
4. Могут содержать латинские буквы, цифры:
A君の死を聞き哀惜措く能わず
5. Могут предваряться словом "связ.:" или ромбиком:
связ.: ああいった, ああした такой;
◇ああいった, ああした такой;
}
{ True, если наличие указанного символа относит слово к шаблону }
function IsTrueExampleChar(const ch: char): boolean;
begin
Result := IsKana(ch) or IsKanji(ch)
or IsCJKSymbolOrPunctuation(ch)
or IsFullWidthCharacter(ch)
or (ch='…') //обозначает "какое-нибудь слово"
or (ch='◇'); //иногда встречается, вырезаем
end;
function IsSupplementalExampleChar(const ch: char): boolean;
begin
Result :=
(ch=',')
or (ch='/') //с помощью этих символов пишется чтение
or (ch='[') or (ch=']') //необязательные части шаблона
or (ch='(') or (ch=')') //альтернативный вариант записи
or CharIsLatinSymbol(ch)
or IsDigit(ch);
end;
{ True, если указанный символ не разрывает шаблона. }
function IsExampleChar(const ch: char): boolean;
begin
Result := IsTrueExampleChar(ch)
or IsSupplementalExampleChar(ch);
end;
{ Вынимает заголовок примера из строки -- ср. ExtractTemplate! }
function ExtractExample(var ln: string; out expr: string): boolean;
var i_start, i_end, i_tmp: integer;
w_true: boolean;
intro_len: integer; //длина удаляемого известного вступления в начале
begin
i_start := 1;
//В начале бывает мусорное "связ.:", которое всё портит
if copy(ln, i_start, 6)='связ.:' then begin
Inc(i_start, 6);
while (i_start<=Length(ln)) and (ln[i_start]=' ') do
Inc(i_start);
end;
//Всё, что было до этого - вводная
intro_len := i_start-1;
i_end := i_start-1;
//Находим конец шаблона. Тут нужно быть осторожными. Откусываем по словам.
Inc(i_end);
repeat
//i_end указывает на первый непробельный символ слова
//Проматываем следующее слово
w_true := false;
i_tmp := i_end;
repeat
if IsTrueExampleChar(ln[i_tmp]) then
w_true := true
else
if not IsSupplementalExampleChar(ln[i_tmp]) then
break;
Inc(i_tmp);
until false;
//Теперь мы либо на пробеле, либо на первом символе слова, который не относится к шаблону
//Хотя вообще говоря, шаблон со словом стыковаться не должен.
if not w_true then //шаблонные символы не были найдены -- слово разрывает шаблон
break;
//Единственный символ, которому допускается прерывать нас - пробел
if ln[i_tmp]<>' ' then begin
//Шаблон стыкуется со словом! В очередном слове шаблонные символы найдены,
//но потом найдены и разрывающие шаблон.
//Сделаем-ка для порядка ошибку. Так не должно быть.
raise ETemplateParsingException.Create('Example word merged with normal word');
end;
//Проматываем пробелы
i_end := i_tmp;
while ln[i_end]=' ' do Inc(i_end);
until false;
Dec(i_end); //вернулись на последний пробел
if i_end<=0 then begin
Result := false;
exit;
end;
//Отматываем пробелы и копируем
i_tmp := i_end;
while (ln[i_tmp]=' ') do Dec(i_tmp);
expr := copy(ln, i_start, i_tmp-i_start+1);
//В начале примеров иногда встречаются мусорные ромбики
if (Length(expr)>0) and (expr[1]='◇') then
delete(expr, 1, 1);
//Удаляем вместе с пробелами по обе стороны
Dec(i_start);
while (i_start>0) and (ln[i_start]=' ') do
Dec(i_start);
Inc(i_start);
if i_start>1+intro_len {can be less, if we overeat spaces} then begin
raise EInsideTemplate.Create('Example is not the first thing in the line');
Result:=false;
exit;
end;
//А в i_end пробелы и так промотаны
delete(ln, 1, i_end-i_start+1);
{
Не делаем этого -- см. комментарий в ExtractTemplate.
if EvalChars(ln) and (EV_KANA or EV_KANJI) <> 0 then
raise EKanjiKanaLeft.Create('Kanji or kana left in string after doing ExtractExample');
}
//Примеры на наличие (скобок), [опциональных частей] и запятых не проверяем.
//Запятые в примерах очень даже допустимы, а скобки и прочее - всё равно примеры
//пишутся в неформальном виде. Разбираться с ними можно будет потом, по готовому файлу.
Result := true;
end;
end.
|
unit IdWebsocketServer;
interface
uses
IdServerWebsocketHandling, IdServerSocketIOHandling, IdServerWebsocketContext,
IdHTTPServer, IdContext, IdCustomHTTPServer, Classes, IdIOHandlerWebsocket, IdGlobal, IdServerIOHandler;
type
TWebsocketMessageText = procedure(const AContext: TIdServerWSContext; const aText: string) of object;
TWebsocketMessageBin = procedure(const AContext: TIdServerWSContext; const aData: TStream) of object;
TIdWebsocketServer = class(TIdHTTPServer)
private
FSocketIO: TIdServerSocketIOHandling_Ext;
FOnMessageText: TWebsocketMessageText;
FOnMessageBin: TWebsocketMessageBin;
FWriteTimeout: Integer;
FUseSSL: boolean;
function GetSocketIO: TIdServerSocketIOHandling;
procedure SetWriteTimeout(const Value: Integer);
function GetIOHandler: TIdServerIOHandler;
protected
procedure Startup; override;
procedure DetermineSSLforPort(APort: TIdPort; var VUseSSL: Boolean);
procedure DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo); override;
procedure ContextCreated(AContext: TIdContext); override;
procedure ContextDisconnected(AContext: TIdContext); override;
procedure WebsocketChannelRequest(const AContext: TIdServerWSContext; aType: TWSDataType; const aStrmRequest, aStrmResponse: TMemoryStream);
public
procedure AfterConstruction; override;
destructor Destroy; override;
procedure SendMessageToAll(const aBinStream: TStream);overload;
procedure SendMessageToAll(const aText: string);overload;
property OnMessageText: TWebsocketMessageText read FOnMessageText write FOnMessageText;
property OnMessageBin : TWebsocketMessageBin read FOnMessageBin write FOnMessageBin;
property IOHandler: TIdServerIOHandler read GetIOHandler write SetIOHandler;
property SocketIO: TIdServerSocketIOHandling read GetSocketIO;
published
property WriteTimeout: Integer read FWriteTimeout write SetWriteTimeout default 2000;
property UseSSL: boolean read FUseSSL write FUseSSL;
end;
implementation
uses
IdServerIOHandlerWebsocket, IdStreamVCL, Windows, IdWinsock2, IdSSLOpenSSL, IdSSL, IdThread; //, idIOHandler, idssl;
{ TIdWebsocketServer }
procedure TIdWebsocketServer.AfterConstruction;
begin
inherited;
FSocketIO := TIdServerSocketIOHandling_Ext.Create;
ContextClass := TIdServerWSContext;
FWriteTimeout := 2 * 1000; //2s
end;
procedure TIdWebsocketServer.ContextCreated(AContext: TIdContext);
begin
inherited ContextCreated(AContext);
(AContext as TIdServerWSContext).OnCustomChannelExecute := Self.WebsocketChannelRequest;
//default 2s write timeout
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms740532(v=vs.85).aspx
AContext.Connection.Socket.Binding.SetSockOpt(SOL_SOCKET, SO_SNDTIMEO, Self.WriteTimeout);
end;
procedure TIdWebsocketServer.ContextDisconnected(AContext: TIdContext);
begin
FSocketIO.FreeConnection(AContext);
inherited;
end;
destructor TIdWebsocketServer.Destroy;
begin
inherited;
FSocketIO.Free;
end;
procedure TIdWebsocketServer.DetermineSSLforPort(APort: TIdPort; var VUseSSL: Boolean);
begin
VUseSSL := IOHandler.InheritsFrom(TIdServerIOHandlerSSLBase);
end;
procedure TIdWebsocketServer.DoCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
(AContext as TIdServerWSContext).OnCustomChannelExecute := Self.WebsocketChannelRequest;
(AContext as TIdServerWSContext).SocketIO := FSocketIO;
if not TIdServerWebsocketHandling.ProcessServerCommandGet(AContext as TIdServerWSContext, ARequestInfo, AResponseInfo) then
inherited DoCommandGet(AContext, ARequestInfo, AResponseInfo);
end;
function TIdWebsocketServer.GetIOHandler: TIdServerIOHandler;
begin
Result := inherited IOHandler;
if Result = nil then
begin
if UseSSL then
begin
Result := TIdServerIOHandlerWebsocketSSL.Create(Self);
with Result as TIdServerIOHandlerWebsocketSSL do
begin
//note: custom certificate files must be set by user, e.g. in datamodule OnCreate:
//FHttpServer := TIdWebsocketServer.Create;
//FHttpServer.UseSSL := True;
//with FHttpServer.IOHandler as TIdServerIOHandlerWebsocketSSL do
// SSLOptions.RootCertFile := 'root.cer';
// SSLOptions.CertFile := 'your_cert.cer';
// SSLOptions.KeyFile := 'key.pem';
SSLOptions.Method := sslvTLSv1_2;
SSLOptions.Mode := sslmServer;
OnQuerySSLPort := DetermineSSLforPort;
end;
end
else
Result := TIdServerIOHandlerWebsocket.Create(Self);
inherited IOHandler := Result;
end;
end;
function TIdWebsocketServer.GetSocketIO: TIdServerSocketIOHandling;
begin
Result := FSocketIO;
end;
procedure TIdWebsocketServer.SendMessageToAll(const aText: string);
var
l: TList;
ctx: TIdServerWSContext;
i: Integer;
begin
l := Self.Contexts.LockList;
try
for i := 0 to l.Count - 1 do
begin
ctx := TIdServerWSContext(l.Items[i]);
Assert(ctx is TIdServerWSContext);
if ctx.WebsocketImpl.IsWebsocket and
not ctx.IsSocketIO
then
ctx.IOHandler.Write(aText);
end;
finally
Self.Contexts.UnlockList;
end;
end;
procedure TIdWebsocketServer.SetWriteTimeout(const Value: Integer);
begin
FWriteTimeout := Value;
end;
procedure TIdWebsocketServer.Startup;
begin
inherited;
end;
procedure TIdWebsocketServer.WebsocketChannelRequest(
const AContext: TIdServerWSContext; aType: TWSDataType; const aStrmRequest,
aStrmResponse: TMemoryStream);
var s: string;
begin
if aType = wdtText then
begin
with TStreamReader.Create(aStrmRequest) do
begin
s := ReadToEnd;
Free;
end;
if Assigned(OnMessageText) then
OnMessageText(AContext, s)
end
else if Assigned(OnMessageBin) then
OnMessageBin(AContext, aStrmRequest)
end;
procedure TIdWebsocketServer.SendMessageToAll(const aBinStream: TStream);
var
l: TList;
ctx: TIdServerWSContext;
i: Integer;
bytes: TIdBytes;
begin
l := Self.Contexts.LockList;
try
TIdStreamHelperVCL.ReadBytes(aBinStream, bytes);
for i := 0 to l.Count - 1 do
begin
ctx := TIdServerWSContext(l.Items[i]);
Assert(ctx is TIdServerWSContext);
if ctx.WebsocketImpl.IsWebsocket and
not ctx.IsSocketIO
then
ctx.IOHandler.Write(bytes);
end;
finally
Self.Contexts.UnlockList;
end;
end;
end.
|
unit TestUPlanoContasVO;
interface
uses
TestFramework, SysUtils, Atributos, UUnidadeVO, UCondominioVO, Generics.Collections,
UGenericVO, Classes, Constantes, UPessoasVO, UPlanoContasVO;
type
TestTPlanoContasVO = class(TTestCase)
strict private
FPlanoContasVO: TPlanoContasVO;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestValidarCamposObrigatorios;
procedure TestValidarCamposObrigatoriosN„oEncontrado;
end;
implementation
procedure TestTPlanoContasVO.SetUp;
begin
FPlanoContasVO := TPlanoContasVO.Create;
end;
procedure TestTPlanoContasVO.TearDown;
begin
FPlanoContasVO.Free;
FPlanoContasVO := nil;
end;
procedure TestTPlanoContasVO.TestValidarCamposObrigatorios;
var
PlanoContas : TPlanoContasVO;
begin
PlanoContas := TPlanoContasVo.Create;
PlanoContas.dsConta := 'Conta Caixa';
PlanoContas.nrClassificacao := '1.1.10.001';
try
PlanoContas.ValidarCamposObrigatorios;
check(true,'Sucesso!');
except on E: Exception do
Check(false,'Erro');
end;
end;
procedure TestTPlanoContasVO.TestValidarCamposObrigatoriosN„oEncontrado;
var
PlanoContas : TPlanoContasVO;
begin
PlanoContas := TPlanoContasVo.Create;
PlanoContas.dsConta := 'Conta Caixa';
PlanoContas.nrClassificacao := '';
try
PlanoContas.ValidarCamposObrigatorios;
check(false,'Erro!');
except on E: Exception do
Check(true,'Sucesso');
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTPlanoContasVO.Suite);
end.
|
PROGRAM balancedtree;
TYPE
Node = ^NodeRec;
NodeRec = RECORD
value: INTEGER;
left, right: Node;
END;
Tree = Node;
PROCEDURE InitTree (VAR t: Tree);
BEGIN
t:= NIL;
END;
PROCEDURE InitArray (VAR arr: ARRAY OF Node);
VAR count : INTEGER;
BEGIN
FOR count := 1 TO High(arr) DO
arr[count] := NIL;
END;
FUNCTION NewNode (value: INTEGER): Node;
VAR
n: Node;
BEGIN
New(n);
n^.value := value;
n^.left := NIL;
n^.right := NIL;
NewNode := n;
END;
(* Insert nodes recursive *)
PROCEDURE InsertRec (VAR t: Tree; n: Node);
BEGIN
IF t= NIL THEN BEGIN
t := n;
END
ELSE BEGIN
IF n^.value < t^.value THEN
InsertRec(t^.left, n)
ELSE
InsertRec(t^.right, n)
END;
END;
(* Adds a node to the Array *)
PROCEDURE AddToArray(VAR arr : ARRAY OF Node; n : Node);
VAR count : INTEGER;
BEGIN
count := 0;
WHILE (arr[count] <> NIL) AND (count <= High(arr)) DO
count := count + 1;
IF count <= High(arr) THEN
arr[count] := n
ELSE
WriteLn('Array already full!');
END;
(* Adds Nodes to the Array, sorted *)
PROCEDURE SaveTreeInOrder (t: Tree; VAR b_array : ARRAY OF Node);
BEGIN
IF t <> NIL THEN
BEGIN
SaveTreeInOrder(t^.left, b_array);
AddToArray(b_array, t);
SaveTreeInOrder(t^.right, b_array);
END;
END;
(* Sets the left & right pointer of all Elements in the array to NIL *)
PROCEDURE CleanArray(VAR b_array : ARRAY OF Node);
VAR count : INTEGER;
BEGIN
FOR count := 0 TO High(b_array) DO
BEGIN
IF b_array[Count] <> NIL THEN
BEGIN
b_array[count]^.left := NIL;
b_array[count]^.right := NIL;
END;
END;
END;
(* Count the nodes in a tree *)
PROCEDURE CountNodes (t: Tree; VAR count : INTEGER);
BEGIN
IF t <> NIL THEN
BEGIN
CountNodes(t^.left, count);
count := count + 1;
CountNodes(t^.right, count);
END;
END;
(* Returns the height of the tree *)
FUNCTION Height(t: Tree) : INTEGER;
VAR
hl, hr: INTEGER;
BEGIN
IF t = NIL THEN
Height := 0
ELSE BEGIN
hl := Height (t^.left);
hr := Height (t^.right);
IF hl > hr THEN
Height := 1 + hl
ELSE
Height := 1 + hr;
END;
END;
FUNCTION CalculateHalf(i : LONGINT): INTEGER;
BEGIN
IF i/2 = i DIV 2 THEN
CalculateHalf := Round(i / 2 )
ELSE
CalculateHalf := (i DIV 2) + 1;
END;
(* write values of the array to the console *)
PROCEDURE PrintArray(b_array: ARRAY OF Node);
VAR count : INTEGER;
BEGIN
WriteLn('Array:');
FOR count := 0 TO High(b_array) DO
BEGIN
IF b_array[count] = NIL THEN
Write('NIL ')
ELSE
Write(b_array[count]^.value, ' ');
END;
WriteLn;
END;
(* Balance the tree so the height of the tree will be reduced*)
PROCEDURE Balance(VAR t: Tree);
VAR
c, length : INTEGER;
pos : LONGINT;
b_array : ARRAY OF Node;
t_temp : Tree;
BEGIN
IF t <> NIL THEN
BEGIN
WriteLn('Balancing....');
c := 0;
CountNodes(t,c);
SetLength(b_array, c);
InitArray(b_array);
InitTree(t_temp);
SaveTreeInOrder(t, b_array);
PrintArray(b_array);
WriteLn('Old height: ', Height(t));
(* Has to be done after height function because the pointer left & right are
set to NIL in cleanarray (the height after that will be 1) *)
CleanArray(b_array);
length := High(b_array)+1;
pos := length;
WHILE pos > 2 DO
BEGIN
pos := CalculateHalf(pos);
InsertRec(t_temp, b_array[pos-1]);
b_array[pos-1] := NIL;
END;
pos := CalculateHalf(length);
WHILE pos < length-1 DO
BEGIN
pos := pos + CalculateHalf(length - pos);
InsertRec(t_temp, b_array[pos-1]);
b_array[pos-1] := NIL;
END;
FOR pos := 0 TO High(b_array) DO
BEGIN
IF b_array[pos] <> NIL THEN
BEGIN
InsertRec(t_temp, b_array[pos]);
b_array[pos] := NIL;
END;
END;
t := t_temp;
b_array := NIL;
t_temp := NIL;
WriteLn('New height: ', Height(t));
END;
END;
PROCEDURE DisposeTree(VAR t: Tree);
BEGIN
IF t <> NIL THEN BEGIN
DisposeTree(t^.left);
DisposeTree(t^.right);
Dispose(t);
t := NIL;
END;
END;
VAR
t : Tree;
BEGIN
WriteLn(chr(205),chr(205),chr(185),' Binary Tree ',chr(204),chr(205),chr(205));
InitTree(t);
InsertRec(t,NewNode(1));
InsertRec(t,NewNode(2));
InsertRec(t,NewNode(3));
InsertRec(t,NewNode(4));
InsertRec(t,NewNode(5));
InsertRec(t,NewNode(6));
InsertRec(t,NewNode(7));
InsertRec(t,NewNode(8));
InsertRec(t,NewNode(9));
Balance(t);
DisposeTree(t);
WriteLn(#13#10, '---- new tree ----', #13#10);
InitTree(t);
InsertRec(t,NewNode(1));
InsertRec(t,NewNode(2));
InsertRec(t,NewNode(3));
InsertRec(t,NewNode(4));
InsertRec(t,NewNode(5));
InsertRec(t,NewNode(6));
InsertRec(t,NewNode(7));
InsertRec(t,NewNode(8));
InsertRec(t,NewNode(9));
InsertRec(t,NewNode(10));
InsertRec(t,NewNode(11));
InsertRec(t,NewNode(12));
InsertRec(t,NewNode(13));
InsertRec(t,NewNode(14));
InsertRec(t,NewNode(15));
InsertRec(t,NewNode(16));
InsertRec(t,NewNode(17));
InsertRec(t,NewNode(18));
InsertRec(t,NewNode(19));
Balance(t);
DisposeTree(t);
WriteLn(#13#10, '---- new tree ----', #13#10);
InitTree(t);
InsertRec(t,NewNode(1));
InsertRec(t,NewNode(1));
InsertRec(t,NewNode(1));
InsertRec(t,NewNode(1));
InsertRec(t,NewNode(1));
InsertRec(t,NewNode(1));
InsertRec(t,NewNode(1));
InsertRec(t,NewNode(1));
InsertRec(t,NewNode(1));
Balance(t);
END. |
unit uXMLUtils;
interface
uses
XMLDoc, XmlIntf;
type
TXMLUtils = class
private
FXML: IXMLDocument;
FRootNode: IXMLNode;
public
property XML: IXMLDocument read FXML write FXML;
constructor Create(rootName: string);
function AddElement(ElemName: string; ElemValue: string = ''): IXMLNode; overload;
function AddElement(ParentNode: IXMLNode; ElemName, ElemValue: string): IXMLNode; overload;
function AddNode(NodeName: string): IXMLNode;
function AddAttribute(Node: IXMLNode; AttrName: string; AttrValue: string = ''): IXMLNode;
function XMLText(Formatted: Boolean = False): string;
end;
const
cFormattedXML = True;
implementation
{ TXMLUtils }
constructor TXMLUtils.Create(rootName: string);
var
node: IXMLNode;
begin
FXML := NewXMLDocument;
FRootNode := FXML.AddChild(rootName);
end;
function TXMLUtils.XMLText(Formatted: Boolean = False) : string;
begin
Result := FXML.XML.Text;
if Formatted then
Result := FormatXMLData(Result);
end;
function TXMLUtils.AddElement(ElemName: string; ElemValue: string = ''): IXMLNode;
var
node: IXMLNode;
begin
Result := FRootNode.AddChild(ElemName);
if ElemValue <> '' then
Result.NodeValue := ElemValue;
end;
function TXMLUtils.AddElement(ParentNode: IXMLNode; ElemName, ElemValue: string): IXMLNode;
begin
Result := ParentNode.AddChild(ElemName);
Result.NodeValue := ElemValue;
end;
function TXMLUtils.AddNode(NodeName: string): IXMLNode;
begin
Result := FXML.CreateElement(NodeName, '');
end;
function TXMLUtils.AddAttribute(Node: IXMLNode; AttrName: string; AttrValue: string = ''): IXMLNode;
begin
Node.Attributes[AttrName] := AttrValue;
Result := Node;
end;
end.
|
unit DAW.View.DeviceEdit;
interface
uses
DAW.Model.Device.New,
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.StdCtrls,
FMX.Edit,
FMX.Layouts,
FMX.Controls.Presentation;
type
TViewDeviceEdit = class(TForm)
lblName: TLabel;
lytName: TLayout;
edtName: TEdit;
lytIP: TLayout;
lblIP: TLabel;
edtIP: TEdit;
lytDialogActions: TLayout;
btnOk: TButton;
btnCancel: TButton;
private
{ Private declarations }
procedure FillUI(ADevice: TdawDevice);
procedure UItoModel(var ADevice: TdawDevice);
public
{ Public declarations }
class function Edit(var ADevice: TdawDevice): Boolean;
end;
var
ViewDeviceEdit: TViewDeviceEdit;
implementation
{$R *.fmx}
{ TViewDeviceEdit }
class function TViewDeviceEdit.Edit(var ADevice: TdawDevice): Boolean;
var
LForm: TViewDeviceEdit;
LModalResult: TModalResult;
begin
LForm := TViewDeviceEdit.Create(nil);
try
LForm.FillUI(ADevice);
LModalResult := LForm.ShowModal;
Result := IsPositiveResult(LModalResult);
if Result then
begin
LForm.UItoModel(ADevice);
end;
finally
LForm.Free;
end;
end;
procedure TViewDeviceEdit.FillUI(ADevice: TdawDevice);
begin
edtName.Text := ADevice.Name;
edtIP.Text := ADevice.IP;
end;
procedure TViewDeviceEdit.UItoModel(var ADevice: TdawDevice);
begin
ADevice.Name := edtName.Text;
ADevice.IP := edtIP.Text;
end;
end.
|
unit ibSHProcedure;
interface
uses
SysUtils, Classes, Contnrs, Menus,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibBTProcedure = class(TibBTDBObject, IibSHProcedure)
private
FParamsExt: TStrings;
FReturnsExt: TStrings;
FHeaderDDL: TStrings;
FParamList: TComponentList;
FReturnList: TComponentList;
function GetCanExecute: Boolean;
function GetParamsExt: TStrings;
function GetReturnsExt: TStrings;
function GetHeaderDDL: TStrings;
function GetParam(Index: Integer): IibSHProcParam;
function GetReturn(Index: Integer): IibSHProcParam;
procedure Execute;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Refresh; override;
property CanExecute: Boolean read GetCanExecute;
property ParamsExt: TStrings read GetParamsExt;
property ReturnsExt: TStrings read GetReturnsExt;
property HeaderDDL: TStrings read GetHeaderDDL;
published
property Description;
property Params;
property Returns;
property OwnerName;
end;
TibSHProcedureToolbarAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHProcedureToolbarAction_Execute = class(TibSHProcedureToolbarAction)
end;
implementation
uses
ibSHConsts, ibSHSQLs, ActnList;
{ TibBTProcedure }
constructor TibBTProcedure.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FParamsExt := TStringList.Create;
FReturnsExt := TStringList.Create;
FHeaderDDL := TStringList.Create;
FParamList := TComponentList.Create;
FReturnList := TComponentList.Create;
end;
destructor TibBTProcedure.Destroy;
begin
FParamsExt.Free;
FReturnsExt.Free;
FHeaderDDL.Free;
FParamList.Free;
FReturnList.Free;
inherited Destroy;
end;
procedure TibBTProcedure.Refresh;
begin
FParamsExt.Clear;
FReturnsExt.Clear;
FParamList.Clear;
FReturnList.Clear;
inherited Refresh;
end;
function TibBTProcedure.GetCanExecute: Boolean;
begin
Result := State in [csSource, csAlter];
end;
function TibBTProcedure.GetParamsExt: TStrings;
begin
Result := FParamsExt;
end;
function TibBTProcedure.GetReturnsExt: TStrings;
begin
Result := FReturnsExt;
end;
function TibBTProcedure.GetHeaderDDL: TStrings;
begin
Result := FHeaderDDL;
end;
function TibBTProcedure.GetParam(Index: Integer): IibSHProcParam;
begin
Assert(Index <= Pred(Params.Count), 'Index out of bounds');
Supports(CreateParam(FParamList, IibSHProcParam, Index), IibSHProcParam, Result);
end;
function TibBTProcedure.GetReturn(Index: Integer): IibSHProcParam;
begin
Assert(Index <= Pred(Returns.Count), 'Index out of bounds');
Supports(CreateParam(FReturnList, IibSHProcParam, Index), IibSHProcParam, Result);
end;
procedure TibBTProcedure.Execute;
var
vCodeNormalizer: IibSHCodeNormalizer;
vExecutionSQL: string;
S: string;
I: Integer;
vComponent: TSHComponent;
vSQLEditorForm: IibSHSQLEditorForm;
function GetNormalizeName(const ACaption: string): string;
begin
if Assigned(vCodeNormalizer) then
Result := vCodeNormalizer.MetadataNameToSourceDDL(BTCLDatabase, ACaption)
else
Result := ACaption;
end;
begin
if CanExecute and Assigned(Designer.CurrentComponent) then
begin
Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer);
if Params.Count > 0 then
begin
for I := 0 to Pred(Params.Count) do
S := S + Format(':%s, ' , [GetNormalizeName(Params[I])]);
Delete(S, Length(S) - 1, 2);
vExecutionSQL := Format('%s(%s)', [GetNormalizeName(Caption), S]);
end
else
vExecutionSQL := GetNormalizeName(Caption);
if Returns.Count > 0 then
vExecutionSQL := Format('SELECT * FROM %s', [vExecutionSQL])
else
vExecutionSQL := Format('EXECUTE PROCEDURE %s', [vExecutionSQL]);
vComponent := Designer.FindComponent(Designer.CurrentComponent.OwnerIID, IibSHSQLEditor);
if not Assigned(vComponent) then
vComponent := Designer.CreateComponent(Designer.CurrentComponent.OwnerIID, IibSHSQLEditor, '');
if Assigned(vComponent) then
begin
Designer.ChangeNotification(vComponent, SCallSQLText, opInsert);
if vComponent.GetComponentFormIntf(IibSHSQLEditorForm, vSQLEditorForm) then
begin
vSQLEditorForm.InsertStatement(vExecutionSQL);
Designer.JumpTo(InstanceIID, IibSHSQLEditor, vComponent.Caption);
end;
end;
end;
end;
{ TibSHProcedureToolbarAction }
constructor TibSHProcedureToolbarAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallToolbar;
Caption := '-';
if Self is TibSHProcedureToolbarAction_Execute then Tag := 1;
case Tag of
1:
begin
Caption := Format('%s', ['Execute Procedure']);
ShortCut := TextToShortCut('Ctrl+F9');
end;
end;
if Tag <> 0 then Hint := Caption;
end;
function TibSHProcedureToolbarAction.SupportComponent(
const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHProcedure);
end;
procedure TibSHProcedureToolbarAction.EventExecute(Sender: TObject);
begin
case Tag of
// Execute
1: if Supports(Designer.CurrentComponent, IibSHProcedure) and
(Designer.CurrentComponent as IibSHProcedure).CanExecute then
(Designer.CurrentComponent as IibSHProcedure).Execute;
end;
end;
procedure TibSHProcedureToolbarAction.EventHint(var HintStr: String;
var CanShow: Boolean);
begin
end;
procedure TibSHProcedureToolbarAction.EventUpdate(Sender: TObject);
begin
if Assigned(Designer.CurrentComponentForm) and
Supports(Designer.CurrentComponent, IibSHProcedure) and
(AnsiSameText(Designer.CurrentComponentForm.CallString, SCallSourceDDL) or
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallAlterDDL)) then
begin
Visible := True;
case Tag of
// Execute
1: Enabled := (Designer.CurrentComponent as IibSHProcedure).CanExecute;
end;
end else
begin
Visible := False;
Enabled := False;
end;
end;
end.
|
unit GLDBendParamsFrame;
interface
uses
Classes, Controls, Forms, ComCtrls, StdCtrls, GL, GLDTypes,
GLDSystem, GLDAxisFrame, GLDModifyLimitEffectFrame, GLDUpDown;
type
TGLDBendParamsFrame = class(TFrame)
GB_Bend: TGroupBox;
L_Angle: TLabel;
E_Angle: TEdit;
UD_Angle: TGLDUpDown;
F_Axis: TGLDAxisFrame;
F_LimitEffect: TGLDModifyLimitEffectFrame;
procedure ValueChangeUD(Sender: TObject);
procedure AxisChange(Sender: TObject);
procedure EditEnter(Sender: TObject);
private
FDrawer: TGLDDrawer;
procedure SetDrawer(Value: TGLDDrawer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
function HaveBend: GLboolean;
function GetParams: TGLDBendParams;
procedure SetParams(const Params: TGLDBendParams);
procedure SetParamsFrom(Source: TPersistent);
procedure ApplyParams;
property Drawer: TGLDDrawer read FDrawer write SetDrawer;
end;
implementation
{$R *.dfm}
uses
SysUtils, GLDConst, GLDX, GLDModify;
constructor TGLDBendParamsFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDrawer := nil;
F_Axis.OnAxisChange := Self.AxisChange;
end;
function TGLDBendParamsFrame.HaveBend: GLboolean;
begin
Result := False;
if Assigned(FDrawer) and
Assigned(FDrawer.EditedModify) and
(FDrawer.EditedModify is TGLDBend) then
Result := True;
end;
function TGLDBendParamsFrame.GetParams: TGLDBendParams;
begin
if HaveBend then
with TGLDBend(FDrawer.EditedModify) do
Result.Center := Center.Vector3f
else Result.Center := GLD_VECTOR3F_ZERO;
Result.Angle := UD_Angle.Position;
Result.Axis := F_Axis.Axis;
Result.LimitEffect := F_LimitEffect.CB_LimitEffect.Checked;
Result.UpperLimit := F_LimitEffect.UD_UpperLimit.Position;
Result.LowerLimit := F_LimitEffect.UD_LowerLimit.Position;
end;
procedure TGLDBendParamsFrame.SetParams(const Params: TGLDBendParams);
begin
E_Angle.Text := FloatToStrF(Params.Angle, ffGeneral, 4, 4);
F_Axis.Axis := Params.Axis;
F_LimitEffect.SetParams(Params.LimitEffect, Params.UpperLimit, Params.LowerLimit);
end;
procedure TGLDBendParamsFrame.SetParamsFrom(Source: TPersistent);
begin
if Assigned(Source) and (Source is TGLDBend) then
SetParams(TGLDBend(Source).Params);
end;
procedure TGLDBendParamsFrame.ApplyParams;
begin
if HaveBend then
TGLDBend(FDrawer.EditedModify).Params := GetParams;
end;
procedure TGLDBendParamsFrame.ValueChangeUD(Sender: TObject);
begin
if HaveBend then
with TGLDTwist(FDrawer.EditedModify) do
if Sender = UD_Angle then
Angle := UD_Angle.Position else
if Sender = F_LimitEffect.CB_LimitEffect then
LimitEffect := F_LimitEffect.CB_LimitEffect.Checked else
if Sender = F_LimitEffect.UD_UpperLimit then
UpperLimit := F_LimitEffect.UD_UpperLimit.Position else
if Sender = F_LimitEffect.UD_LowerLimit then
LowerLimit := F_LimitEffect.UD_LowerLimit.Position;
end;
procedure TGLDBendParamsFrame.AxisChange(Sender: TObject);
begin
if HaveBend then
with TGLDTwist(FDrawer.EditedModify) do
Axis := F_Axis.Axis;
end;
procedure TGLDBendParamsFrame.EditEnter(Sender: TObject);
begin
ApplyParams;
end;
procedure TGLDBendParamsFrame.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and
(Operation = opRemove) then FDrawer := nil;
inherited Notification(AComponent, Operation);
end;
procedure TGLDBendParamsFrame.SetDrawer(Value: TGLDDrawer);
begin
FDrawer := Value;
if Assigned(FDrawer) then
SetParamsFrom(FDrawer.EditedModify);
end;
end.
|
unit uRDM;
interface
uses
SysUtils, Classes, uRORemoteService, uROClient, uROWinInetHttpChannel,
uROBinMessage;
const
ClientCfgFile = 'WMPJ.Cfg';
type
TDMWMServer = class(TDataModule)
ROMessage: TROBinMessage;
ROChannel: TROWinInetHTTPChannel;
RORemoteService: TRORemoteService;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DMWMServer: TDMWMServer;
implementation
uses IniFiles;
{$R *.dfm}
procedure TDMWMServer.DataModuleCreate(Sender: TObject);
var
aFilePath, aServerAddr: string;
aIni: TIniFile;
aPort: Integer;
begin
aFilePath := ExtractFilePath(ParamStr(0)) + ClientCfgFile;
if not FileExists(aFilePath) then
begin
FileCreate(aFilePath)
end;
aIni := TIniFile.Create(aFilePath);
try
aServerAddr := aIni.ReadString('Server', 'ServerAddr', '127.0.0.1');
aIni.WriteString('Server', 'ServerAddr', aServerAddr);
aPort := aIni.ReadInteger('Server', 'Port', 8099);
aIni.WriteInteger('Server', 'Port', aPort);
// ROChannel.TargetURL := 'http://localhost:8098/BIN';
ROChannel.TargetURL := 'http://' + Trim(aServerAddr) + ':' + IntToStr(aPort) + '/BIN';
finally
aIni.Free;
end;
end;
end.
|
{
Slim Services and EventLog support for Windows
Author: Wanderlan Santos dos Anjos, wanderlan.anjos@gmail.com
Date: jun-2008
License: <extlink http://www.opensource.org/licenses/bsd-license.php>BSD</extlink>
}
unit Services;
interface
uses
{$IFDEF FPC}Windows{$ELSE}WinSvc{$ENDIF}, Classes;
{$R *.res}
type
TFuncBool = function : boolean; // Procedural type to stop and start functions, used in <link TService.Run, Run> method.
TEventType = (EventError = 1, EventWarning = 2, EventInformation = 4); // Event severity
// Implements Windows Service with <link TService.ReportEventLog, report EventLog> support
TService = class
private
FName : pchar;
FDescription,
FParamStr : string;
FManager,
FService : SC_Handle;
FTimeout,
FExitCode,
FParamCount : integer;
FSource : THandle;
FStatus : TServiceStatus;
FStopEvent : THandle;
FReportStartStop : boolean;
FStatusHandle : Service_Status_Handle;
FServiceThreads : array[0..10] of TThread;
FMaxThreads : integer;
FServiceBegin,
FServiceEnd : TFuncBool;
procedure StopNow;
function GetName : string;
function ReportNoError(Estado : integer) : boolean;
function ReportServiceStatus(CurrentState, Win32ExitCode, CheckPoint, WaitHint: integer): boolean;
public
constructor Create(ServiceName : string; Description : string = '');
destructor Destroy; override;
function GetServiceError: integer;
function GetServiceErrorMessage: string;
function GetState : cardinal;
function Install : boolean;
function Uninstall : boolean;
procedure Insert(Exec: string);
procedure Delete;
function Run(ServThreads : array of TThread; ServBegin : TFuncBool = nil; ServEnd : TFuncBool = nil) : boolean;
function Exists : boolean;
function Stop : integer;
function Start : integer;
function ReportStart : boolean;
function ReportStop : boolean;
procedure ReportEventLog(EventType : TEventType; EventCode : word; Message : string);
procedure Reset;
property Timeout : integer read FTimeout write FTimeout; // Time before to generate an error. Default 20000 milliseconds
property ExitCode : integer read FExitCode write FExitCode; // Exit code to return to Service Manager
property Name : string read GetName; // Service Name
property ParamStr : string read FParamStr; // Parameter list passed when the service was started
property ParamCount : integer read FParamCount; // Number of parameters passed when the service was started
end;
var
Service : TService; // Global var, use it to initialize a service
implementation
uses
{$IFNDEF FPC}Windows,{$ENDIF} SysUtils, Registry;
function TService.GetName : string;
begin
Result := string(FName);
end;
// Closes service handle
procedure TService.Reset;
begin
CloseServiceHandle(FService);
FService := 0;
end;
// Returns if service is initialized
function TService.Exists : boolean;
begin
Result := FService <> 0;
end;
{
Installs a service.
@param Exec Executable file with path
@exception RaiseLastOSError if not succeded
@see Install
@see Delete
}
procedure TService.Insert(Exec : string);
begin
FService := CreateService(FManager, FName, FName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL, pchar(Exec), nil, nil, nil, nil, nil);
if not Exists then RaiseLastOSError;
with TRegistry.Create do begin
Access := KEY_ALL_ACCESS;
RootKey := HKey_Local_Machine;
OpenKey('\SYSTEM\CurrentControlSet\Services\EventLog\Application\' + FName, true);
WriteString('EventMessageFile', Exec);
OpenKey('\SYSTEM\CurrentControlSet\Services\' + FName, true);
WriteString('Description', FDescription);
Free;
end;
end;
{
Installs a service using command line. In command line use \<application\> -INSTALL to install a service
@return True if succeded else False
@see Insert
@see Uninstall
}
function TService.Install : boolean;
begin
if FindCmdLineSwitch('INSTALL', ['-', '/'], true) and (FService = 0) then begin
Insert(system.ParamStr(0));
Result := true;
end
else
Result := false
end;
{
Uninstalls a service.
@exception RaiseLastOSError if not succeded
@see Insert
@see Uninstall
}
procedure TService.Delete;
begin
if not Exists then RaiseLastOSError;
if not DeleteService(FService) then RaiseLastOSError;
with TRegistry.Create do begin
Access := KEY_ALL_ACCESS;
RootKey := HKey_Local_Machine;
DeleteKey('\SYSTEM\CurrentControlSet\Services\EventLog\Application\' + FName);
Free;
end;
end;
{
Uninstalls a service using command line. In command line use \<application\> -UNINSTALL to uninstall a service
@return True if succeded else False
@see Delete
@see Install
}
function TService.Uninstall : boolean;
begin
if FindCmdLineSwitch('UNINSTALL', ['-', '/'], true) then begin
Delete;
Result := true;
end
else
Result := false
end;
// Returns last error code
function TService.GetServiceError : integer;
begin
Result := GetLastError;
if Result = 0 then Result := -1
end;
// Returns last error message
function TService.GetServiceErrorMessage : string;
begin
Result := SysErrorMessage(GetServiceError)
end;
{
Stops the service
@return 0 if succeeded else last error code
}
function TService.Stop : integer;
begin
Result := 0;
if Exists then begin
if not ControlService(FService, SERVICE_CONTROL_STOP, FStatus) then Result := GetLastError;
end
else
Result := GetServiceError;
end;
{
Starts the service
@return 0 if succeeded else last error code
}
function TService.Start : integer;
const
Param : PAnsiChar = nil;
begin
Result := 0;
if FService = 0 then FService := OpenService(FManager, FName, SERVICE_ALL_ACCESS);
if Exists then begin
if not StartServiceA(FService, 0, Param) then Result := GetServiceError;
end
else
Result := GetServiceError;
end;
function TService.GetState : cardinal;
begin
if QueryServiceStatus(FService, FStatus) then
Result := FStatus.dwCurrentState
else
Result := 77;
end;
{
Writes an event log.
@param EventType
@param EventCode User code
@param Message User message
}
procedure TService.ReportEventLog(EventType : TEventType; EventCode : word; Message : string);
var
Mensagem : pchar;
begin
Mensagem := pchar(Message);
ReportEvent(FSource, word(EventType), 1000 + EventCode, 0, nil, 1, 0, @Mensagem, nil);
end;
// StopNow can be used within the service to stop the service
procedure TService.StopNow;
begin
SetLastError(0);
SetEvent(FStopEvent)
end;
function TService.ReportServiceStatus(CurrentState, Win32ExitCode, CheckPoint, WaitHint : integer) : boolean;
begin
SetLastError(0);
with FStatus do begin
dwServiceType := SERVICE_WIN32_OWN_PROCESS;
dwServiceSpecificExitCode := 0;
// Desabilita requisições até o serviço estar startado
if CurrentState = SERVICE_START_PENDING then
dwControlsAccepted := 0
else
dwControlsAccepted := SERVICE_ACCEPT_STOP + SERVICE_ACCEPT_PAUSE_CONTINUE;
dwCurrentState := CurrentState;
dwCheckPoint := CheckPoint;
dwWaitHint := WaitHint;
if ExitCode = 0 then
dwWin32ExitCode := Win32ExitCode
else begin
dwWin32ExitCode := ERROR_SERVICE_SPECIFIC_ERROR;
dwServiceSpecificExitCode := ExitCode;
end;
// Manda o status do service para o service manager.
Result := SetServiceStatus(FStatusHandle, FStatus);
if not Result then StopNow;
end;
end;
function TService.ReportNoError(Estado : integer) : boolean;
begin
Result := ReportServiceStatus(Estado, NO_ERROR, 0, 0)
end;
// Reports that the service is in start pending status. Use it when to initialize a service.
function TService.ReportStart : boolean;
const
ChkPoint : integer = 0;
begin
Result := false;
if FReportStartStop and Exists then begin
inc(ChkPoint);
Result := ReportServiceStatus(SERVICE_START_PENDING, NO_ERROR, ChkPoint, Timeout);
end;
end;
// Reports that the service is in stop pending status. Use it when to stop a service
function TService.ReportStop : boolean;
const
ChkPoint : integer = 0;
begin
Result := false;
if FReportStartStop and Exists then begin
inc(ChkPoint);
Result := ReportServiceStatus(SERVICE_STOP_PENDING, NO_ERROR, ChkPoint, Timeout);
end;
end;
// Is called by Windows Server Manager
procedure ServController(Command : integer); stdcall;
var
I : integer;
begin
with Service do
case Command of
SERVICE_CONTROL_PAUSE: if FStatus.dwCurrentState = SERVICE_RUNNING then begin
for I := 0 to FMaxThreads do
FServiceThreads[I].Suspend;
ReportNoError(SERVICE_PAUSED);
end;
SERVICE_CONTROL_CONTINUE: if FStatus.dwCurrentState = SERVICE_PAUSED then begin
for I := 0 to FMaxThreads do
FServiceThreads[I].Resume;
ReportNoError(SERVICE_RUNNING);
end;
SERVICE_CONTROL_STOP: begin
FReportStartStop := true;
ReportStop;
// Request all threads to terminate
for I := 0 to FMaxThreads do
FServiceThreads[I].Terminate;
// Wait to termination and free them
for I := 0 to FMaxThreads do
with FServiceThreads[I] do begin
WaitFor;
Free;
end;
ReportStop;
StopNow;
end;
else
ReportNoError(SERVICE_RUNNING);
end;
end;
{
Starts the service, telling Service Manager each step of the process,
then resumes the service threads, waits the stop event and back to
StartServiceCtrlDispatcher in RunService
}
procedure ServiceMain(ArgC : integer; ArgV : pchar); stdcall;
var
I : integer;
InitOk : boolean;
begin
with Service do begin
FParamCount := ArgC;
FParamStr := strpas(ArgV);
SetLastError(0);
FStatusHandle := RegisterServiceCtrlHandler(FName, @ServController);
if FStatusHandle <> 0 then begin
if ReportStart then begin
// Cria o evento que irá sinalizar o fim do service
SetLastError(0);
FStopEvent := CreateEvent(nil, true, false, nil);
if FStopEvent <> 0 then begin
// Roda a rotina de inicialização do Service
InitOk := true;
if @FServiceBegin <> nil then InitOk := FServiceBegin;
if InitOk then begin
ReportStart;
FReportStartStop := false;
// Starta as threads do service
for I := 0 to FMaxThreads do
FServiceThreads[I].Resume;
ReportEventLog(EventInformation, 0, 'Started');
if ReportNoError(SERVICE_RUNNING) then
// Espera indefinidamente até o StopEvent ocorrer
WaitForSingleObject(FStopEvent, INFINITE);
FReportStartStop := true;
ReportStop;
// Desaloca as Threads
for I := 0 to FMaxThreads do
FServiceThreads[I].Terminate;
ReportEventLog(EventInformation, 1, 'Stopped');
ReportStop;
SetLastError(0);
if @FServiceEnd <> nil then FServiceEnd; // Roda a rotina de finalização
end;
CloseHandle(FStopEvent);
end;
end;
ReportServiceStatus(SERVICE_STOPPED, GetLastError, 0, 0);
end;
end;
end;
{
Runs a service. Calls StartServiceCtrlDispatcher to register a main service thread.
When the API returns, the service was stopped, then halt.
@param
@param ServBegin Function called before to start the service. It should return true if initializing was Ok.
@param ServEnd Function called after to stop the service.
}
function TService.Run(ServThreads : array of TThread; ServBegin : TFuncBool = nil; ServEnd : TFuncBool = nil) : boolean;
var
ServTable : array[0..1] of TServiceTableEntry;
I : integer;
begin
FServiceBegin := ServBegin;
FServiceEnd := ServEnd;
FMaxThreads := high(ServThreads);
for I := 0 to FMaxThreads do
FServiceThreads[I] := ServThreads[I];
fillchar(ServTable, sizeof(ServTable), 0);
with ServTable[0] do begin
lpServiceName := FName;
lpServiceProc := @ServiceMain
end;
SetLastError(0);
Result := StartServiceCtrlDispatcher({$IFDEF FPC}@{$ENDIF}ServTable[0])
end;
{
Creates a new service, but not installs it. Use <link TService.Insert> to install.
@param ServiceName to show in Service Manager
@param Description to show in Service Manager
}
constructor TService.Create(ServiceName : string; Description : string = '');
begin
inherited Create;
FName := pchar(ServiceName);
FDescription := Description;
FSource := OpenEventLog(nil, FName);
FManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if FManager = 0 then RaiseLastOSError;
FService := OpenService(FManager, FName, SERVICE_ALL_ACCESS);
FTimeout := 20000;
FReportStartStop := true;
end;
// Frees a service but not uninstalls it. Use <link TService.Delete> method to uninstall.
destructor TService.Destroy;
begin
CloseServiceHandle(FService);
CloseEventLog(FSource);
CloseServiceHandle(FManager);
end;
end.
|
//=============================================================================
// sgNamedIndexCollection.pas
//=============================================================================
//
// This private SwinGame library unit is responsible for managing named
// collections of indexes.
//
// This can be used to track names of resources in an array -- though the two
// need to be kept in sync (ensure add/remove update both).
//
//=============================================================================
unit sgNamedIndexCollection;
interface
uses sgBackendTypes, sgTypes; //TODO: Remove sgTypes when removed StringArray
/// Get the name of the value at index idx.
///
function NameAt(const col: NamedIndexCollection; idx: Integer): String;
/// Get the index of the specified name.
///
function IndexOf(const col: NamedIndexCollection;const name: String): Integer;
/// The number of names in the collection
///
function NameCount(const col: NamedIndexCollection): Integer;
function NamesOf(const col: NamedIndexCollection): StringArray;
function HasName(const col: NamedIndexCollection;const name: String): Boolean;
/// Add a new name to the index. Returns the index of the added element or
/// -1 if the add fails.
///
function AddName(var col: NamedIndexCollection;const name: String): Integer;
//adds more than one name delimited by ',' i.e. name1,name2..
Procedure AddNamesToCollection(var col: NamedIndexCollection;const names: String);
/// returns names in an index collection in the following manner: name1,name2...
function NamedIndexCollectionNameList(const list:NamedIndexCollection):String;
procedure InitNamedIndexCollection(var col: NamedIndexCollection;const names: StringArray); overload;
procedure InitNamedIndexCollection(var col: NamedIndexCollection); overload;
procedure RemoveName(var col: NamedIndexCollection; idx: Longint); overload;
function RemoveName(var col: NamedIndexCollection;const name: String): Longint; overload;
procedure FreeNamedIndexCollection(var col: NamedIndexCollection);
procedure RemoveAllNamesInCollection(var col: NamedIndexCollection);
implementation
uses sgShared, stringhash, sgSharedUtils, StrUtils;
function NameAt(const col: NamedIndexCollection;idx: Integer): String;
begin
if (idx >= Low(col.names)) and (idx <= High(col.names)) then
result := col.names[idx]
else
result := '';
end;
function NamedIndexCollectionNameList(const list:NamedIndexCollection):String;
var
i : Longint;
begin
result:=NameAt(list,0);
for i:=1 to NameCount(list)-1 do
begin
result+=','+NameAt(list, i);
end;
end;
function IndexOf(const col: NamedIndexCollection;const name: String): Integer;
var
hash: TStringHash;
begin
hash := TStringHash(col.ids);
if assigned(hash) and hash.containsKey(name) then
result := TIntegerContainer(hash.values[name]).Value
else
result := -1;
end;
function NameCount(const col: NamedIndexCollection): Integer;
begin
result := Length(col.names);
end;
function NamesOf(const col: NamedIndexCollection): StringArray;
begin
result := col.names;
end;
function HasName(const col: NamedIndexCollection;const name: String): Boolean;
var
hash: TStringHash;
begin
result := false;
hash := TStringHash(col.ids);
if not assigned(hash) then exit;
result := hash.containsKey(name);
end;
function AddName(var col: NamedIndexCollection;const name: String): Integer;
var
hash: TStringHash;
begin
hash := TStringHash(col.ids);
if assigned(hash) then
begin
if hash.containsKey(name) then begin RaiseException('Error: Adding ' + name + ' to the name collection twice.'); exit; end;
SetLength(col.names, Length(col.names) + 1); // Add to the names array
result := High(col.names); // Record the index of the added name
col.names[result] := name; // Store the name in the names array
hash.setValue(name, TIntegerContainer.Create(result)); // Store this idx in the hashtable
end
else
result := -1; // Failed to add return -1 idx
end;
procedure AddNamesToCollection(var col: NamedIndexCollection;const names: String);
var
i, namesLength:Longint;
begin
if Length(names) = 0 then exit;
//number of names = ,'s + 1 (commas + 1)
namesLength := CountDelimiter(names, ',') + 1;
//WriteLn('Reading ', namesLength, ' names from ', names);
for i := 1 to namesLength do
begin
AddName(col, ExtractDelimited(i,names,[',']));
end;
end;
function RemoveName(var col: NamedIndexCollection;const name: String): Longint; overload;
begin
result := IndexOf(col, name);
RemoveName(col, result);
end;
procedure RemoveName(var col: NamedIndexCollection; idx: Longint); overload;
var
hash: TStringHash;
name: String;
i: Integer;
begin
// WriteLn('remove name');
hash := TStringHash(col.ids);
if not Assigned(hash) then exit;
name := NameAt(col, idx);
// WriteLn(name);
hash.remove(name).Free();
for i := idx to High(col.names) - 1 do
begin
// WriteLn(i);
col.names[i] := col.names[i + 1];
TIntegerContainer(hash.values[col.names[i]]).Value := i;
end;
// WriteLn('length: ', Length(col.names));
SetLength(col.names, Length(col.names) - 1);
end;
procedure InitNamedIndexCollection(var col: NamedIndexCollection;const names: StringArray); overload;
var
hash: TStringHash;
i: Integer;
begin
// WriteLn('here');
hash := TStringHash.Create(False, 1024); //Create the hash locally and store in col.ids
col.ids := hash;
SetLength(col.names, Length(names));
for i := Low(names) to High(names) do
begin
col.names[i] := names[i];
hash.setValue(names[i], TIntegerContainer.Create(i));
end;
end;
procedure InitNamedIndexCollection(var col: NamedIndexCollection); overload;
var
names: Array of String;
begin
SetLength(names, 0);
InitNamedIndexCollection(col, names);
end;
procedure FreeNamedIndexCollection(var col: NamedIndexCollection);
var
hash: TStringHash;
begin
hash := TStringHash(col.ids);
if assigned(hash) then
begin
hash.DeleteAll();
hash.Free();
end;
col.ids := nil;
end;
procedure RemoveAllNamesInCollection(var col: NamedIndexCollection);
var
i : LongInt;
begin
for i := 0 to NameCount(col) - 1 do
RemoveName(col, i);
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.AddInOptions;
interface
uses
ToolsApi,
Vcl.Forms,
DPM.IDE.AddInOptionsFrame,
Spring.Container,
DPM.Core.Logging,
DPM.Core.Configuration.Interfaces,
DPM.IDE.Options;
type
TDPMAddinOptions = class(TInterfacedObject, INTAAddInOptions)
private
FConfigManager : IConfigurationManager;
FLogger : ILogger;
FFrame : TDPMOptionsFrame;
FIDEOptions : IDPMIDEOptions;
protected
procedure DialogClosed(Accepted : Boolean);
procedure FrameCreated(AFrame : TCustomFrame);
function GetArea : string;
function GetCaption : string;
function GetFrameClass : TCustomFrameClass;
function GetHelpContext : Integer;
function IncludeInIDEInsight : Boolean;
function ValidateContents : Boolean;
public
constructor Create(const container : TContainer);
end;
implementation
{ TDPMAddinOptions }
constructor TDPMAddinOptions.Create(const container : TContainer);
begin
FConfigManager := container.Resolve<IConfigurationManager>;
FLogger := container.Resolve<ILogger>;
FIDEOptions := container.Resolve<IDPMIDEOptions>;
end;
procedure TDPMAddinOptions.DialogClosed(Accepted : Boolean);
begin
if Accepted then
FFrame.SaveSettings;
end;
procedure TDPMAddinOptions.FrameCreated(AFrame : TCustomFrame);
begin
FFrame := TDPMOptionsFrame(AFrame);
FFrame.Configure(FConfigManager, FIDEOptions, FLogger);
FFrame.LoadSettings;
end;
function TDPMAddinOptions.GetArea : string;
begin
result := '';
end;
function TDPMAddinOptions.GetCaption : string;
begin
result := 'DPM Package Manager';
end;
function TDPMAddinOptions.GetFrameClass : TCustomFrameClass;
begin
result := TDPMOptionsFrame;
end;
function TDPMAddinOptions.GetHelpContext : Integer;
begin
result := -1;
end;
function TDPMAddinOptions.IncludeInIDEInsight : Boolean;
begin
result := true;
end;
function TDPMAddinOptions.ValidateContents : Boolean;
begin
result := FFrame.Validate;
end;
end.
|
unit rtti_serializer_uXmlStore;
interface
uses
rtti_broker_iBroker, DOM, XMLRead, XMLWrite,
SysUtils, xpath, fgl, rtti_broker_uData;
const
cSID = 'SID';
cRefID = 'refid';
cValue = 'Value';
cRoot = 'root';
cStoreSettings = 'storesettings';
cLastSid = 'lastsid';
cMemo = 'memo';
type
{ TXmlStore }
TXmlStore = class(TInterfacedObject, IRBStore, IRBDataQuery)
private type
{ TLoadCache }
TLoadCache = class
private type
TCache = specialize TFPGMap<integer, TObject>;
private
fCache: TCache;
public
constructor Create;
destructor Destroy; override;
procedure Add(AID: integer; AObject: TObject);
procedure Remove(AID: integer);
function Find(AID: integer): TObject;
end;
TSID = string;
{ TStoreCache }
TStoreCache = class
private type
TSIDCache = specialize TFPGMap<TSID, TObject>;
TObjCache = specialize TFPGMap<Pointer, TSID>;
private
fSIDCache: TSIDCache;
fObjCache: TObjCache;
public
constructor Create;
destructor Destroy; override;
function FindObject(const ASID: TSID): TObject;
function FindSID(const AObject: TObject): TSID;
procedure Add(const ASID: TSID; const AObject: TObject);
procedure Remove(const ASID: TSID); overload;
procedure Remove(const AObject: TObject); overload;
end;
{ TSIDManager }
TSIDManager = class
private
fLast: integer;
function GetStoreSettingsElement(ADoc: TXMLDocument): TDOMElement;
public
procedure Load(ADoc: TXMLDocument);
procedure Save(ADoc: TXMLDocument);
function New: TSID;
end;
private
const
cListItemTag = 'i';
cListItemNilTag = 'n';
private
fFactory: IRBFactory;
fFile: string;
fDoc: TXMLDocument;
fLoadCache: TLoadCache;
fStoreCache: TStoreCache;
fSIDMgr: TSIDManager;
function GetDoc: TXMLDocument;
function GetDataClassEl(const ADataClassName: string; ACanCreate: Boolean): TDOMElement;
class function FindElement(const AContextEl: TDOMElement; const AXPath: string): TDOMElement;
function FindStoreElForSID(const ADataClassEl: TDOMElement; const ASID: TSID): TDOMElement; overload;
function FindStoreElForSID(const ASID: TSID): TDOMElement; overload;
function GetDataStoreElForSID(const ADataClassEl: TDOMElement; const ASID: TSID): TDOMElement; overload;
function GetDataStoreElForSID(const ASID: TSID): TDOMElement; overload;
function FindStoreElForName(const ADataClassEl: TDOMElement; const AName: string): TDOMElement; overload;
function FindStoreElForName(const AName: string): TDOMElement; overload;
function GetDataStoreElForName(const ADataClassEl: TDOMElement; const AName: string): TDOMElement; overload;
function GetDataStoreElForName(const AName: string): TDOMElement; overload;
//save
procedure SaveDataItemValue(AStoreEl: TDOMElement; const AName, AValue: string);
procedure SaveDataItemMemo(AStoreEl: TDOMElement; const AName, AValue: string);
procedure SaveDataItemObject(AStoreEl: TDOMElement; const AName: string;
const AValue: TObject; AIsReference: Boolean);
procedure SaveDataList(AStoreEl: TDOMElement; ADataItem: IRBDataItem);
procedure SaveData(AStoreEl: TDOMElement; AData: IRBData);
//load
function LoadDataItemValue(AStoreEl: TDOMElement; const AName: string): string;
function LoadDataItemMemo(AStoreEl: TDOMElement; const AName: string): string;
function LoadDataItemObject(AStoreEl: TDOMElement; const ADataItem: IRBDataItem): TObject;
procedure LoadDataList(AStoreEl: TDOMElement; ADataItem: IRBDataItem);
procedure LoadData(AStoreEl: TDOMElement; AData: IRBData);
protected
property Doc: TXMLDocument read GetDoc;
public
constructor Create(AFactory: IRBFactory; const AFile: string);
constructor Create;
destructor Destroy; override;
procedure AfterConstruction; override;
// IRBStore
procedure Save(AData: TObject);
procedure Save(AData: IRBData);
function Load(const AClass: string; const AProperty, AValue: string): TObject;
function LoadList(const AClass: string): IRBDataList;
procedure Flush;
procedure Delete(AData: TObject);
procedure Delete(AData: IRBData);
// IRBDataQuery
function Retrive(const AClass: string): IRBDataList;
published
property Factory: IRBFactory read fFactory write fFactory;
property XMLFile: string read fFile write fFile;
end;
implementation
type
{ EXMLStore }
EXMLStore = class(Exception)
public
class procedure ClassNotExists(const AClass: string);
class procedure ClassForSIDNotExists(const ASID: string);
class procedure ClassForNameNotExists(const AName: string);
class procedure ObjectNotExists(const AClass, AName: string); overload;
class procedure ObjectNotExists(const AClass: string; AID: integer); overload;
class procedure MoreObjectWithNameExists(const AClass, AName: string); overload;
class procedure MoreObjectWithNameExists(const AClass: string; AID: integer); overload;
class procedure CannotAddItemWithoutSIDToList(const AClass: string);
class procedure CannotFindReferencedSID(const AOwner: string; ASID: string);
end;
{ TXmlStore.TSIDManager }
function TXmlStore.TSIDManager.GetStoreSettingsElement(ADoc: TXMLDocument): TDOMElement;
begin
Result := FindElement(ADoc.DocumentElement, './' + cStoreSettings);
if Result = nil then
begin
Result := ADoc.CreateElement(cStoreSettings);
ADoc.DocumentElement.AppendChild(Result);
end;
end;
procedure TXmlStore.TSIDManager.Load(ADoc: TXMLDocument);
var
mEl: TDOMElement;
begin
mEl := GetStoreSettingsElement(ADoc);
fLast := StrToIntDef(mEl.AttribStrings[cLastSid], 1);
end;
procedure TXmlStore.TSIDManager.Save(ADoc: TXMLDocument);
var
mEl: TDOMElement;
begin
mEl := GetStoreSettingsElement(ADoc);
mEl.AttribStrings[cLastSid] := IntToStr(fLast);
end;
function TXmlStore.TSIDManager.New: TSID;
begin
inc(fLast);
Result := IntToStr(fLast);
end;
{ TXmlStore.TStoreCache }
constructor TXmlStore.TStoreCache.Create;
begin
fSIDCache := TSIDCache.Create;
fObjCache := TObjCache.Create;
end;
destructor TXmlStore.TStoreCache.Destroy;
begin
FreeAndNil(fSIDCache);
FreeAndNil(fObjCache);
inherited Destroy;
end;
function TXmlStore.TStoreCache.FindObject(const ASID: TSID): TObject;
var
mIndex: integer;
begin
mIndex := fSIDCache.IndexOf(ASID);
if mIndex = -1 then
Result := nil
else
Result := fSIDCache.Data[mIndex];
end;
function TXmlStore.TStoreCache.FindSID(const AObject: TObject): TSID;
var
mIndex: integer;
begin
mIndex := fObjCache.IndexOf(AObject);
if mIndex = -1 then
Result := ''
else
Result := fObjCache.Data[mIndex];
end;
procedure TXmlStore.TStoreCache.Add(const ASID: TSID; const AObject: TObject);
begin
fSIDCache.Add(ASID, AObject);
fObjCache.Add(AObject, ASID);
end;
procedure TXmlStore.TStoreCache.Remove(const ASID: TSID);
var
mIndex: integer;
mObj: TObject;
begin
mIndex := fSIDCache.IndexOf(ASID);
if mIndex <> -1 then
begin
mObj := fSIDCache.Data[mIndex];
fSIDCache.Delete(mIndex);
mIndex := fObjCache.IndexOf(mObj);
if mIndex <> -1 then
begin
fObjCache.Delete(mIndex);
end;
mObj.Free;
end;
end;
procedure TXmlStore.TStoreCache.Remove(const AObject: TObject);
var
mIndex: integer;
mSID: TSID;
begin
mIndex := fObjCache.IndexOf(AObject);
if mIndex <> -1 then
begin
mSID := fObjCache.Data[mIndex];
fObjCache.Delete(mIndex);
mIndex := fSIDCache.IndexOf(mSID);
if mIndex <> -1 then
begin
fSIDCache.Delete(mIndex);
end;
end;
AObject.Free;
end;
{ TXmlStore.TLoadCache }
constructor TXmlStore.TLoadCache.Create;
begin
fCache := TCache.Create;
end;
destructor TXmlStore.TLoadCache.Destroy;
begin
FreeAndNil(fCache);
inherited Destroy;
end;
procedure TXmlStore.TLoadCache.Add(AID: integer; AObject: TObject);
begin
fCache.Add(AID, AObject);
end;
procedure TXmlStore.TLoadCache.Remove(AID: integer);
begin
fCache.Remove(AID);
end;
function TXmlStore.TLoadCache.Find(AID: integer): TObject;
var
mIndex: integer;
begin
Result := nil;
mIndex := fCache.IndexOf(AID);
if mIndex <> -1 then
Result := fCache.Data[mIndex];
end;
{ EXMLStore }
class procedure EXMLStore.ClassNotExists(const AClass: string);
begin
raise EXMLStore.CreateFmt('Class %s not found in store', [AClass]);
end;
class procedure EXMLStore.ClassForSIDNotExists(const ASID: string);
begin
raise EXMLStore.CreateFmt('Cannot find class for SID %s', [ASID]);
end;
class procedure EXMLStore.ClassForNameNotExists(const AName: string);
begin
raise EXMLStore.CreateFmt('Cannot find class for Name %s', [AName]);
end;
class procedure EXMLStore.ObjectNotExists(const AClass, AName: string);
begin
raise EXMLStore.CreateFmt('Object %s.%s not found in store', [AClass, AName]);
end;
class procedure EXMLStore.ObjectNotExists(const AClass: string; AID: integer);
begin
raise EXMLStore.CreateFmt('Object %s.%d not found in store', [AClass, AID]);
end;
class procedure EXMLStore.MoreObjectWithNameExists(const AClass, AName: string);
begin
raise EXMLStore.CreateFmt('Object %s.%s exists more then once in store', [AClass, AName]);
end;
class procedure EXMLStore.MoreObjectWithNameExists(const AClass: string;
AID: integer);
begin
raise EXMLStore.CreateFmt('Object %s.%d exists more then once in store', [AClass, AID]);
end;
class procedure EXMLStore.CannotAddItemWithoutSIDToList(const AClass: string);
begin
raise EXMLStore.CreateFmt('Object of class %s do not have SID stored - cannot add to list', [AClass]);
end;
class procedure EXMLStore.CannotFindReferencedSID(const AOwner: string;
ASID: string);
begin
raise EXMLStore.CreateFmt('Object %s refer to not exists SID %s', [AOwner, ASID]);
end;
{ TXmlStore }
function TXmlStore.GetDoc: TXMLDocument;
begin
if fDoc = nil then
begin
if (fFile <> '') and FileExists(fFile) then
ReadXMLFile(fDoc, fFile);
if fDoc = nil then
begin
fDoc := TXMLDocument.Create;
fDoc.AppendChild(fDoc.CreateElement(cRoot));
end;
fSIDMgr.Load(fDoc);
end;
Result := fDoc;
end;
procedure TXmlStore.SaveData(AStoreEl: TDOMElement; AData: IRBData);
var
i: integer;
mObjStoreEl: TDOMElement;
begin
for i := 0 to AData.Count - 1 do
begin
if AData[i].IsListCounter then
Continue;
if AData[i].IsNotStored then
Continue;
if AData[i].IsList then
SaveDataList(AStoreEl, AData[i])
else
if AData[i].IsObject then
begin
if AData[i].AsObject <> nil then
begin
mObjStoreEl := Doc.CreateElement(AData[i].Name);
AStoreEl.AppendChild(mObjStoreEl);
SaveDataItemObject(mObjStoreEl, AData[i].Name, AData[i].AsObject, AData[i].IsReference);
end;
end
else if AData[i].IsMemo then
begin
SaveDataItemMemo(AStoreEl, AData[i].Name, AData[i].AsPersist);
end
else
begin
SaveDataItemValue(AStoreEl, AData[i].Name, AData[i].AsPersist);
end;
end;
end;
procedure TXmlStore.LoadData(AStoreEl: TDOMElement; AData: IRBData);
var
i: integer;
mObjStoreEl: TDOMElement;
begin
for i := 0 to AData.Count - 1 do
begin
if AData[i].IsListCounter then
Continue;
if AData[i].IsList then
LoadDataList(AStoreEl, AData[i])
else
if AData[i].IsObject then
begin
mObjStoreEl := AStoreEl.FindNode(AData[i].Name) as TDOMElement;
if mObjStoreEl = nil then
Continue;
AData[i].AsObject := LoadDataItemObject(mObjStoreEl, AData[i]);
end
else
if AData[i].IsMemo then
begin
AData[i].AsPersist := LoadDataItemMemo(AStoreEl, AData[i].Name);
end
else
begin
AData[i].AsPersist := LoadDataItemValue(AStoreEl, AData[i].Name);
end;
end;
end;
function TXmlStore.LoadDataItemValue(AStoreEl: TDOMElement; const AName: string): string;
begin
Result := AStoreEl.AttribStrings[AName];
end;
function TXmlStore.LoadDataItemMemo(AStoreEl: TDOMElement; const AName: string
): string;
var
mStoreEl: TDOMElement;
mMemoNode: TDOMCDATASection;
begin
Result := '';
mStoreEl := FindElement(AStoreEl, './' + cMemo);
if mStoreEl = nil then
Exit;
mMemoNode := mStoreEl.ChildNodes[0] as TDOMCDATASection;
Result := mMemoNode.TextContent;
end;
function TXmlStore.LoadDataItemObject(AStoreEl: TDOMElement; const ADataItem: IRBDataItem): TObject;
var
mSID: TSID;
mRefStoreEl: TDOMElement;
mData: IRBData;
begin
Result := nil;
if ADataItem.IsReference then
begin
if AStoreEl.AttribStrings[cRefID] <> '' then
begin
mSID := AStoreEl.AttribStrings[cRefID];
if mSID = '' then
Exit;
Result := fStoreCache.FindObject(mSID);
if Result = nil then
begin
mRefStoreEl := FindStoreElForSID(mSID);
if mRefStoreEl = nil then
EXMLStore.CannotFindReferencedSID(AStoreEl.NodeName, mSID);
Result := fFactory.CreateObject(mRefStoreEl.ParentNode.NodeName);
if Supports(Result, IRBData) then
mData := Result as IRBData
else begin
mData := TRBData.Create(Result);
end;
LoadData(mRefStoreEl, mData);
fStoreCache.Add(mSID, Result);
end;
end;
end
else
begin
Result := fFactory.CreateObject(ADataItem.ClassName);
LoadData(AStoreEl, Result as IRBData);
end;
end;
procedure TXmlStore.LoadDataList(AStoreEl: TDOMElement; ADataItem: IRBDataItem);
var
mStoreEl: TDOMElement;
mStoreItemEl: TDOMElement;
i: integer;
begin
Assert(ADataItem.IsList);
mStoreEl := AStoreEl.FindNode(ADataItem.Name) as TDOMElement;
if mStoreEl = nil then
Exit;
ADataItem.ListCount := mStoreEl.ChildNodes.Count;
for i := 0 to mStoreEl.ChildNodes.Count - 1 do
begin
mStoreItemEl := mStoreEl.ChildNodes[i] as TDOMElement;
if ADataItem.IsObject then
begin
// only when ID is stored, otherwise is nil
if mStoreItemEl.NodeName = cListItemNilTag then
ADataItem.AsObjectList[i] := nil
else
ADataItem.AsObjectList[i] := LoadDataItemObject(mStoreItemEl, ADataItem);
end
else
ADataItem.AsPersistList[i] := LoadDataItemValue(mStoreItemEl, cValue);
end;
end;
function TXmlStore.GetDataClassEl(const ADataClassName: string;
ACanCreate: Boolean): TDOMElement;
begin
Result := Doc.DocumentElement.FindNode(ADataClassName) as TDOMElement;
if Result = nil then
begin
if ACanCreate then
begin
Result := Doc.CreateElement(ADataClassName);
Doc.DocumentElement.AppendChild(Result);
end
else
EXMLStore.ClassNotExists(ADataClassName);
end;
end;
class function TXmlStore.FindElement(const AContextEl: TDOMElement;
const AXPath: string): TDOMElement;
var
mXPV: TXPathVariable;
begin
mXPV := EvaluateXPathExpression(AXPath, AContextEl);
case mXPV.AsNodeSet.Count of
0: Result := nil;
1: Result := TDOMElement(mXPV.AsNodeSet[0]);
else
EXMLStore.MoreObjectWithNameExists(AContextEl.NodeName, AXPath);
end;
end;
function TXmlStore.GetDataStoreElForSID(const ADataClassEl: TDOMElement;
const ASID: TSID): TDOMElement;
begin
Result := FindStoreElForSID(ADataClassEl, ASID);
if Result = nil then
EXMLStore.ClassForSIDNotExists(ASID);
end;
function TXmlStore.FindStoreElForSID(const ASID: TSID): TDOMElement;
begin
Result := FindElement(Doc.DocumentElement, '//*[@SID=''' + ASID + ''']');
end;
function TXmlStore.FindStoreElForSID(const ADataClassEl: TDOMElement;
const ASID: TSID): TDOMElement;
begin
Result := FindElement(ADataClassEl, './*[@SID=''' + ASID + ''']');
end;
function TXmlStore.GetDataStoreElForSID(const ASID: TSID): TDOMElement;
begin
Result := FindStoreElForSID(ASID);
if Result = nil then
EXMLStore.ClassForSIDNotExists(ASID);
end;
function TXmlStore.FindStoreElForName(const ADataClassEl: TDOMElement;
const AName: string): TDOMElement;
begin
Result := FindElement(ADataClassEl, './*[@Name=''' + AName + ''']');
end;
function TXmlStore.FindStoreElForName(const AName: string): TDOMElement;
begin
Result := FindElement(Doc.DocumentElement, '//*[@Name=''' + AName + ''']');
end;
function TXmlStore.GetDataStoreElForName(const ADataClassEl: TDOMElement;
const AName: string): TDOMElement;
begin
Result := FindStoreElForName(ADataClassEl, AName);
if Result = nil then
EXMLStore.ClassForNameNotExists(AName);
end;
function TXmlStore.GetDataStoreElForName(const AName: string): TDOMElement;
begin
Result := FindStoreElForName(AName);
if Result = nil then
EXMLStore.ClassForNameNotExists(AName);
end;
function TXmlStore.LoadList(const AClass: string): IRBDataList;
var
mClassEl: TDOMElement;
mStoreEl: TDOMElement;
i: integer;
mObj: TObject;
mSID: TSID;
mData: IRBData;
begin
Result := TRBDataList.Create;
mClassEl := GetDataClassEl(AClass, True);
for i := 0 to mClassEl.ChildNodes.Count - 1 do
begin
mStoreEl := mClassEl.ChildNodes[i] as TDOMElement;
mSID := mStoreEl.AttribStrings[cSID];
if mSID = '' then
EXMLStore.CannotAddItemWithoutSIDToList(AClass);
mObj := fStoreCache.FindObject(mSID);
if mObj = nil then
begin
mObj := fFactory.CreateObject(AClass);
if Supports(mObj, IRBData) then
mData := mObj as IRBData
else begin
mData := TRBData.Create(mObj);
end;
LoadData(mStoreEl, mData);
fStoreCache.Add(mSID, mObj);
end;
Result.Add(mObj);
end;
end;
function TXmlStore.Load(const AClass: string; const AProperty, AValue: string): TObject;
var
mStoreEl: TDOMElement;
mData: IRBData;
mSID: TSID;
begin
Result := nil;
mStoreEl := FindElement(Doc.DocumentElement, './' + AClass + '[@' + AProperty + '=''' + AValue + '''');
if mStoreEl <> nil then begin
mSID := mStoreEl.AttribStrings[cSID];
if mSID = '' then
EXMLStore.CannotAddItemWithoutSIDToList(AClass);
Result := fStoreCache.FindObject(mSID);
if Result = nil then
begin
Result := fFactory.CreateObject(AClass);
if Supports(Result, IRBData) then
mData := Result as IRBData
else begin
mData := TRBData.Create(Result);
end;
LoadData(mStoreEl, mData);
fStoreCache.Add(mSID, Result);
end;
end;
end;
procedure TXmlStore.SaveDataItemValue(AStoreEl: TDOMElement; const AName,
AValue: string);
begin
if AValue <> '' then
AStoreEl.AttribStrings[AName] := AValue;
end;
procedure TXmlStore.SaveDataItemMemo(AStoreEl: TDOMElement; const AName,
AValue: string);
var
mStoreEl: TDOMElement;
mMemoNode: TDOMCDATASection;
begin
if AValue <> '' then
begin
mStoreEl := Doc.CreateElement(cMemo);
mStoreEl.AttribStrings[AName] := '';
AStoreEl.AppendChild(mStoreEl);
mMemoNode := Doc.CreateCDATASection(AValue);
mStoreEl.AppendChild(mMemoNode);
end;
end;
procedure TXmlStore.SaveDataItemObject(AStoreEl: TDOMElement;
const AName: string; const AValue: TObject; AIsReference: Boolean);
var
mSID: TSID;
begin
if AIsReference then
begin
if AValue <> nil then
begin
mSID := fStoreCache.FindSID(AValue);
SaveDataItemValue(AStoreEl, cRefID, mSID);
end;
end
else
begin
if AValue <> nil then
SaveData(AStoreEl, AValue as IRBData);
end;
end;
procedure TXmlStore.SaveDataList(AStoreEl: TDOMElement; ADataItem: IRBDataItem);
var
mStoreEl: TDOMElement;
mStoreItemEl: TDOMElement;
i: integer;
begin
Assert(ADataItem.IsList);
if ADataItem.ListCount = 0 then
Exit;
mStoreEl := Doc.CreateElement(ADataItem.Name);
AStoreEl.AppendChild(mStoreEl);
for i := 0 to ADataItem.ListCount - 1 do
begin
// create element for store list item
if ADataItem.IsObject and (ADataItem.AsObjectList[i] = nil) then
begin
mStoreItemEl := Doc.CreateElement(cListItemNilTag);
mStoreEl.AppendChild(mStoreItemEl);
end else begin
mStoreItemEl := Doc.CreateElement(cListItemTag);
mStoreEl.AppendChild(mStoreItemEl);
// store data
if ADataItem.IsObject then
SaveDataItemObject(mStoreItemEl, ADataItem.Name, ADataItem.AsObjectList[i], ADataItem.IsReference)
else
SaveDataItemValue(mStoreItemEl, cValue, ADataItem.AsPersistList[i]);
end;
end;
end;
procedure TXmlStore.Save(AData: IRBData);
var
mClassEl: TDOMElement;
mStoreEl: TDOMElement;
mSID: TSID;
mIsNew: Boolean;
begin
mSID := fStoreCache.FindSID(AData.UnderObject);
mIsNew := False;
if mSID = '' then
begin
mSID := fSIDMgr.New;
mIsNew := True;
end;
mClassEl := GetDataClassEl(AData.ClassName, True);
mStoreEl := FindStoreElForSID(mClassEl, mSID);
// when store, remove old data and create all new
if mStoreEl <> nil then
begin
mStoreEl.ParentNode.DetachChild(mStoreEl);
mStoreEl.Free;
end;
mStoreEl := Doc.CreateElement(cListItemTag);
mClassEl.AppendChild(mStoreEl);
mStoreEl.AttribStrings[cSID] := mSID;
//
SaveData(mStoreEl, AData);
if mIsNew then
fStoreCache.Add(mSID, AData.UnderObject);
end;
procedure TXmlStore.Flush;
begin
fSIDMgr.Save(Doc);
WriteXMLFile(Doc, fFile);
end;
procedure TXmlStore.Delete(AData: TObject);
begin
if Supports(AData, IRBData) then
Delete(AData as IRBData)
else begin
Delete(TRBData.Create(AData));
end;
end;
procedure TXmlStore.Delete(AData: IRBData);
var
mClassEl: TDOMElement;
mStoreEl: TDOMElement;
mSID: TSID;
begin
mSID := fStoreCache.FindSID(AData.UnderObject);
if mSID = '' then
begin
// without SID - not stored
Exit;
end;
mClassEl := GetDataClassEl(AData.ClassName, True);
mStoreEl := FindStoreElForSID(mClassEl, mSID);
// remove data
if mStoreEl = nil then
raise EXMLStore.CreateFmt('Delete - no element find for %s[%s]', [AData.ClassName, mSID]);
mStoreEl.ParentNode.DetachChild(mStoreEl);
mStoreEl.Free;
end;
function TXmlStore.Retrive(const AClass: string): IRBDataList;
begin
Result := LoadList(AClass);
end;
constructor TXmlStore.Create(AFactory: IRBFactory; const AFile: string);
begin
fFactory := AFactory;
fFile := AFile;
Create;
end;
constructor TXmlStore.Create;
begin
// GetDoc;
end;
destructor TXmlStore.Destroy;
begin
Flush;
FreeAndNil(fSIDMgr);
FreeAndNil(fLoadCache);
FreeAndNil(fStoreCache);
inherited Destroy;
end;
procedure TXmlStore.AfterConstruction;
begin
inherited AfterConstruction;
fLoadCache := TLoadCache.Create;
fStoreCache := TStoreCache.Create;
fSIDMgr := TSIDManager.Create;
end;
procedure TXmlStore.Save(AData: TObject);
begin
if Supports(AData, IRBData) then
Save(AData as IRBData)
else begin
Save(TRBData.Create(AData));
end;
end;
end.
|
unit FRepair;
(*====================================================================
Progress window for repairing the database. Implements the repair in the
Run procedure
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
Windows
{$ELSE}
LCLIntf, LCLType, LMessages, ComCtrls, ExtCtrls,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ATGauge,
UTypes, UApiTypes;
type
{ TFormRepair }
TFormRepair = class(TForm)
//Gauge : TPanel;
ButtonCancel: TButton;
Gauge: TGauge;
LabelInfo : TLabel;
procedure FormCreate(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
CanRun : boolean;
public
SrcDBaseHandle : PDBaseHandle;
TarDBaseHandle : PDBaseHandle;
TarDatabaseName: ShortString;
SrcDatabaseName: ShortString;
StopIt : boolean;
procedure Run(var Info); message WM_User + 110;
end;
var
FormRepair: TFormRepair;
implementation
uses
UAPi, UExceptions, FSettings, ULang;
{$R *.dfm}
//-----------------------------------------------------------------------------
// dummy callback
function IsTheLastCPB (FName: ShortString): boolean; far;
begin
IsTheLastCPB := true;
end;
//-----------------------------------------------------------------------------
// dummy callback
function HowToContinue (FName: ShortString): word; far;
begin
HowToContinue := 0;
end;
//-----------------------------------------------------------------------------
// callback - sets the new text in the progress info
procedure NewLineToIndicator (Line: ShortString); far;
begin
FormRepair.LabelInfo.Caption := Line;
Application.ProcessMessages;
end;
//-----------------------------------------------------------------------------
// callback - adds text to the text in the progress info
procedure AppendLineToIndicator (Line: ShortString); far;
begin
FormRepair.LabelInfo.Caption := FormRepair.LabelInfo.Caption + Line;
Application.ProcessMessages;
end;
//-----------------------------------------------------------------------------
// callback - updates progress gauge
procedure UpdateProgressIndicator (Phase, Progress: Integer); far;
begin
if (FormRepair.Gauge.Progress <> Progress) then
FormRepair.Gauge.Progress := Progress;
Application.ProcessMessages;
end;
//-----------------------------------------------------------------------------
// callback - returns true if the user presses Cancel
function AbortScan: boolean; far;
begin
AbortScan := FormRepair.StopIt;
end;
//=============================================================================
procedure TFormRepair.FormShow(Sender: TObject);
begin
LabelInfo.Caption := lsScannningDatabase;
StopIt := false;
CanRun := true;
Application.ProcessMessages;
// this causes executing the Run procedure after the form is displayed
PostMessage(Self.Handle, WM_User + 110, 0, 0);
end;
//-----------------------------------------------------------------------------
// Makes the repair of the database
procedure TFormRepair.Run (var Info);
var
MsgCaption, MsgText: array[0..256] of char;
sMessage: ShortString;
begin
if not CanRun then exit;
CanRun := false;
StrPCopy(MsgCaption, lsDatabaseRepair);
LabelInfo.Caption := lsRepairingIndex;
try
if not QI_OpenDatabase(SrcDatabaseName, true, SrcDBaseHandle, sMessage) then
begin
Application.MessageBox(StrPCopy(MsgText, lsSourceDBase +
SrcDatabaseName + lsCannotBeOpened + #13#10 + sMessage),
MsgCaption, mb_OK or mb_IconStop);
ModalResult := mrCancel;
exit;
end;
if not QI_CreateDatabase(TarDatabaseName) then
begin
Application.MessageBox(StrPCopy(MsgText, lsTargetDBase +
TarDatabaseName + lsCannotBeCreated),
MsgCaption, mb_OK or mb_IconStop);
QI_CloseDatabase(SrcDBaseHandle, false);
ModalResult := mrCancel;
exit;
end;
if not QI_OpenDatabase(TarDatabaseName, false, TarDBaseHandle, sMessage) then
begin
Application.MessageBox(StrPCopy(MsgText, lsTargetDBase +
TarDatabaseName + lsCannotBeOpened + #13#10 + sMessage),
MsgCaption, mb_OK or mb_IconStop);
QI_CloseDatabase(SrcDBaseHandle, false);
ModalResult := mrCancel;
exit;
end;
QI_RegisterCallbacks (IsTheLastCPB,
HowToContinue, NewLineToIndicator,
AppendLineToIndicator,
UpdateProgressIndicator,
AbortScan);
QI_CopyDatabase(SrcDBaseHandle, TarDBaseHandle,
true, {whole database}
false, {do not check duplicates}
true); {copy local options}
QI_UnregisterCallBacks;
//iErrorCounter := QI_GetErrorCounter(SrcDBaseHandle);
QI_CloseDatabase(SrcDBaseHandle, false);
QI_CloseDatabase(TarDBaseHandle, false);
finally
ModalResult := mrOk;
end;
end;
//-----------------------------------------------------------------------------
procedure TFormRepair.FormCreate(Sender: TObject);
begin
CanRun := false;
end;
//-----------------------------------------------------------------------------
procedure TFormRepair.ButtonCancelClick(Sender: TObject);
begin
StopIt := true;
end;
//-----------------------------------------------------------------------------
end.
|
unit layers_unt;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxPC, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxEdit, cxTextEdit, cxVGrid,
cxInplaceContainer, dxDockControl, dxDockPanel, Vcl.ExtCtrls, dxBar, cxClasses,
Vcl.Buttons, Vcl.ImgList, cxCheckComboBox, cxCheckGroup, cxBarEditItem,
Vcl.ComCtrls, cxCustomData, cxTL, cxTLdxBarBuiltInMenu,
layer_unt, dataunt;
type
MLayers = object
procedure InitData;
procedure ReloadData;
procedure ProcessChildren(N: TcxTreeListNode; Recurse: Boolean);
procedure CheckChanged(Sender: TcxCustomTreeList;
ANode: TcxTreeListNode; AState: TcxCheckBoxState);
public
{ Public declarations }
list : array of LayerC;
total : integer;
selected : LayerC;
end;
var Layers : MLayers;
implementation
uses Main;
function AddNode(AParent: TcxTreeListNode; const AValues: Array of Variant; AImageIndex: Integer; enabled : boolean; checked : boolean): TcxTreeListNode;
begin
Result := mainform.tlLayers.AddChild(AParent);
Result.AssignValues(AValues);
Result.CheckGroupType := ncgCheckGroup;
//Result.Imageindex := AImageIndex;
Result.CheckGroupType := ncgCheckGroup;
Result.Expanded := true;
Result.Expand(true);
Result.Enabled := enabled;
Result.Checked := checked;
end;
procedure MLayers.CheckChanged(Sender: TcxCustomTreeList;
ANode: TcxTreeListNode; AState: TcxCheckBoxState);
var s : string;
sTemp :string;
nTemp : integer;
layer : LayerC;
layer_n, j : integer;
begin
layer_n := 0;
{if not busy_create then
begin }
if (ANode.Texts[0] <> '') and (ANode.Texts[0] <> 'Layers') then
begin
layer_n := layer.get_place_by_name(ANode.Texts[0], true);
layer := list[layer_n];
layer.active := AState = Cbschecked;
for j:=1 to dbase.Lines.no do
dbase.lines.line[j].switch_active(Dbase.Lines.active);
for j:=1 to dbase.circles.no do
dbase.circles.circle[j].switch_active(Dbase.circles.active);
end;
end;
procedure MLayers.InitData;
var
ARootNode, AChildNode, ASalesMarketingNode: TcxTreeListNode;
ANode: TcxTreeListNode;
AValues: Array of Variant;
node, childnode : TcxTreeListNode;
i, line_total, points_total : integer;
sTitle: String;
grp: TcxTreeListNode;
begin
mainform.tlLayers.Clear;
//ARootNode := AddNode(nil, ['Layers'], 8, true, true);
for i := 1 to Layers.total do
begin
AChildNode := AddNode(nil, [Layers.list[i].name], 1, true, true);
end;
mainform.tlLayers.FullCollapse;
mainform.tlLayers.Root[0].Expanded := True;
end;
procedure MLayers.ProcessChildren(N: TcxTreeListNode; Recurse: Boolean);
var I: Integer;
val : array of variant;
s : string;
begin
s := N.Texts[0];
for I := 0 to N.Count - 1 do
begin
// ... To do something
if Recurse and N.HasChildren then
ProcessChildren(N[I], Recurse);
end;
end;
procedure MLayers.ReloadData;
var I: Integer;
begin
with mainform.tlLayers do
for I := 0 to Count - 1 do
begin
// ... To do something
ProcessChildren(Items[I], True);
end;
end;
end.
|
namespace MetroSearchApplication;
interface
uses
System,
System.Collections.Generic,
System.IO,
System.Linq,
Windows.Foundation,
Windows.Foundation.Collections,
Windows.UI.Xaml,
Windows.UI.Xaml.Controls,
Windows.UI.Xaml.Controls.Primitives,
Windows.UI.Xaml.Data,
Windows.UI.Xaml.Input,
Windows.UI.Xaml.Media,
Windows.UI.Xaml.Navigation,
Windows.ApplicationModel.Search;
type
MainPage = partial class(Page)
private
_searchPane: SearchPane;
suggestionList: array of System.String := ['Oxygene for .NET', 'Oxygene for Java', 'Data Abstract for .NET', 'Data Abstract for Delphi', 'Data Abstract for Xcode', 'Data Abstract for Java', 'RemObjects SDK for Java', 'RemObjects SDK for Delphi', 'RemObjects SDK for .NET', 'RemObjects SDK for Xcode'];
protected
public
constructor;
method UpdateSearchQuery(queryText: String);
method OnQuerySubmitted(sender: Object; args: SearchPaneQuerySubmittedEventArgs);
method OnQueryChanged(sender: Object; args: SearchPaneQueryChangedEventArgs);
method OnSearchPaneSuggestionsRequested(sender: Object; args: SearchPaneSuggestionsRequestedEventArgs);
method OnSearchPaneResultSuggestionChosen(sender: Object; args: SearchPaneResultSuggestionChosenEventArgs);
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected
method OnNavigatedTo(e: NavigationEventArgs); override;
end;
implementation
constructor MainPage;
begin
InitializeComponent();
_searchPane := SearchPane.GetForCurrentView;
_searchPane.QuerySubmitted += new TypedEventHandler<SearchPane, SearchPaneQuerySubmittedEventArgs>(OnQuerySubmitted);
_searchPane.QueryChanged += new TypedEventHandler<SearchPane, SearchPaneQueryChangedEventArgs>(OnQueryChanged);
_searchPane.SuggestionsRequested += new TypedEventHandler<SearchPane, SearchPaneSuggestionsRequestedEventArgs>(OnSearchPaneSuggestionsRequested);
_searchPane.ResultSuggestionChosen += new TypedEventHandler<SearchPane, SearchPaneResultSuggestionChosenEventArgs>(OnSearchPaneResultSuggestionChosen);
end;
method MainPage.OnNavigatedTo(e: NavigationEventArgs);
begin
end;
method MainPage.UpdateSearchQuery(queryText: String);
begin
SearchQuery.Text := "Search Activation: " + queryText;
end;
/// <summary>
/// Search pane query to local app is submitted and displays query results
/// </summary>
/// <param name="sender">This is the UI object sender</param>
/// <param name="args">This is the argument for QuerySubbmitted event. Contains QueryText, Language, etc.</param>
method MainPage.OnQuerySubmitted(sender: Object; args: SearchPaneQuerySubmittedEventArgs);
begin
SearchQuery.Text := "Query submitted: " + args.QueryText;
end;
/// <summary>
/// Search pane query to local app is changing to give app an opportunity to display realtime results
/// </summary>
/// <param name="sender">This is the UI object sender</param>
/// <param name="args">This is the argument for QueryChanged event. Contains QueryText, Language, etc.</param>
method MainPage.OnQueryChanged(sender: Object; args: SearchPaneQueryChangedEventArgs);
begin
SearchQuery.Text := "Current query text: " + args.QueryText;
end;
/// <summary>
/// Search pane displays suggestions from a static local list
/// </summary>
/// <param name="sender">This is the UI object sender</param>
/// <param name="args">This is the argument for OnSearchPaneSuggestionsRequested event</param>
method MainPage.OnSearchPaneSuggestionsRequested(sender: Object; args: SearchPaneSuggestionsRequestedEventArgs);
begin
for each suggestion: String in suggestionList do
begin
if (suggestion.IndexOf(args.QueryText, StringComparison.CurrentCultureIgnoreCase) > -1) then
args.Request.SearchSuggestionCollection.AppendQuerySuggestion(suggestion);
if (args.Request.SearchSuggestionCollection.Size >= 5) then
break;
end;
end;
/// <summary>
/// Rich suggestion is selected in search pane
/// </summary>
/// <param name="sender">This is the UI object sender</param>
/// <param name="args">This is the argument for ResultSuggestionChosen event</param>
method MainPage.OnSearchPaneResultSuggestionChosen(sender: Object; args: SearchPaneResultSuggestionChosenEventArgs);
begin
SearchQuery.Text := "Result Suggestion Selected: " + args.Tag;
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 uCEFRequestContextHandler;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefRequestContextHandlerProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF} function: ICefCookieManager;
TCefRequestContextHandlerRef = class(TCefBaseRefCountedRef, ICefRequestContextHandler)
protected
procedure OnRequestContextInitialized(const request_context: ICefRequestContext);
function GetCookieManager: ICefCookieManager;
function OnBeforePluginLoad(const mimeType, pluginUrl: ustring; isMainFrame : boolean; const topOriginUrl: ustring; const pluginInfo: ICefWebPluginInfo; pluginPolicy: PCefPluginPolicy): Boolean;
public
class function UnWrap(data: Pointer): ICefRequestContextHandler;
end;
TCefRequestContextHandlerOwn = class(TCefBaseRefCountedOwn, ICefRequestContextHandler)
protected
procedure OnRequestContextInitialized(const request_context: ICefRequestContext);
function GetCookieManager: ICefCookieManager; virtual;
function OnBeforePluginLoad(const mimeType, pluginUrl: ustring; isMainFrame : boolean; const topOriginUrl: ustring; const pluginInfo: ICefWebPluginInfo; pluginPolicy: PCefPluginPolicy): Boolean; virtual;
public
constructor Create; virtual;
end;
TCefFastRequestContextHandler = class(TCefRequestContextHandlerOwn)
protected
FProc: TCefRequestContextHandlerProc;
function GetCookieManager: ICefCookieManager; override;
public
constructor Create(const proc: TCefRequestContextHandlerProc); reintroduce;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFCookieManager, uCEFWebPluginInfo, uCEFRequestContext;
// TCefRequestContextHandlerOwn
procedure cef_request_context_handler_on_request_context_initialized(self: PCefRequestContextHandler; request_context: PCefRequestContext); stdcall;
begin
TCefRequestContextHandlerOwn(CefGetObject(self)).OnRequestContextInitialized(TCefRequestContextRef.UnWrap(request_context));
end;
function cef_request_context_handler_get_cookie_manager(self: PCefRequestContextHandler): PCefCookieManager; stdcall;
begin
Result := CefGetData(TCefRequestContextHandlerOwn(CefGetObject(self)).GetCookieManager());
end;
function cef_request_context_handler_on_before_plugin_load(self: PCefRequestContextHandler;
const mime_type, plugin_url : PCefString;
is_main_frame : integer;
const top_origin_url: PCefString;
plugin_info: PCefWebPluginInfo;
plugin_policy: PCefPluginPolicy): Integer; stdcall;
begin
with TCefRequestContextHandlerOwn(CefGetObject(self)) do
Result := Ord(OnBeforePluginLoad(CefString(mime_type),
CefString(plugin_url),
(is_main_frame <> 0),
CefString(top_origin_url),
TCefWebPluginInfoRef.UnWrap(plugin_info),
plugin_policy));
end;
constructor TCefRequestContextHandlerOwn.Create;
begin
CreateData(SizeOf(TCefRequestContextHandler));
with PCefRequestContextHandler(FData)^ do
begin
on_request_context_initialized := cef_request_context_handler_on_request_context_initialized;
get_cookie_manager := cef_request_context_handler_get_cookie_manager;
on_before_plugin_load := cef_request_context_handler_on_before_plugin_load;
end;
end;
procedure TCefRequestContextHandlerOwn.OnRequestContextInitialized(const request_context: ICefRequestContext);
begin
end;
function TCefRequestContextHandlerOwn.GetCookieManager: ICefCookieManager;
begin
Result:= nil;
end;
function TCefRequestContextHandlerOwn.OnBeforePluginLoad(const mimeType, pluginUrl : ustring;
isMainFrame : boolean;
const topOriginUrl: ustring;
const pluginInfo: ICefWebPluginInfo;
pluginPolicy: PCefPluginPolicy): Boolean;
begin
Result := False;
end;
// TCefRequestContextHandlerRef
procedure TCefRequestContextHandlerRef.OnRequestContextInitialized(const request_context: ICefRequestContext);
begin
PCefRequestContextHandler(FData).on_request_context_initialized(FData, CefGetData(request_context));
end;
function TCefRequestContextHandlerRef.GetCookieManager: ICefCookieManager;
begin
Result := TCefCookieManagerRef.UnWrap(PCefRequestContextHandler(FData).get_cookie_manager(FData));
end;
function TCefRequestContextHandlerRef.OnBeforePluginLoad(const mimeType, pluginUrl : ustring;
isMainFrame : boolean;
const topOriginUrl: ustring;
const pluginInfo: ICefWebPluginInfo;
pluginPolicy: PCefPluginPolicy): Boolean;
var
mt, pu, ou: TCefString;
begin
mt := CefString(mimeType);
pu := CefString(pluginUrl);
ou := CefString(topOriginUrl);
Result := PCefRequestContextHandler(FData).on_before_plugin_load(FData, @mt, @pu, ord(isMainFrame), @ou, CefGetData(pluginInfo), pluginPolicy) <> 0;
end;
class function TCefRequestContextHandlerRef.UnWrap(data: Pointer): ICefRequestContextHandler;
begin
if (data <> nil) then
Result := Create(data) as ICefRequestContextHandler
else
Result := nil;
end;
// TCefFastRequestContextHandler
constructor TCefFastRequestContextHandler.Create(const proc: TCefRequestContextHandlerProc);
begin
FProc := proc;
inherited Create;
end;
function TCefFastRequestContextHandler.GetCookieManager: ICefCookieManager;
begin
Result := FProc();
end;
end.
|
//******************************************************************************
// Пакет для добавленя, изменения, удаления данных о свойствах людей
// параметры: ID - идентификатор, если добавление, то идентификатор человека, иначе
// идентификатор свойства человека.
//******************************************************************************
unit Invalid_Ctrl_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, StdCtrls, cxButtons, cxCalendar,
cxTextEdit, cxMaskEdit, cxContainer, cxEdit, cxLabel, ExtCtrls,
cxControls, cxGroupBox,ZMessages, ZProc,
Unit_ZGlobal_Consts, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase,
pFIBDatabase, DB, FIBDataSet, pFIBDataSet, ZTypes, IBase, ActnList, Invalid_Ctrl_DM;
type
TFSp_Invalid_Control = class(TForm)
IdentificationBox: TcxGroupBox;
PeopleLabel: TcxLabel;
PeopleEdit: TcxMaskEdit;
PeriodBox: TcxGroupBox;
YesBtn: TcxButton;
CancelBtn: TcxButton;
Bevel1: TBevel;
NoteLabel: TcxLabel;
DateBegLabel: TcxLabel;
DateBeg: TcxDateEdit;
DateEndLabel: TcxLabel;
DateEnd: TcxDateEdit;
Actions: TActionList;
ActionYes: TAction;
NoteEdit: TcxMaskEdit;
procedure CancelBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ActionYesExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure NoteEditKeyPress(Sender: TObject; var Key: Char);
private
Ins_Id_Man:LongWord;
PParameter:TZCtrlWithHistoryParam;
DM:TDM_Ctrl;
PLanguageIndex:Byte;
public
constructor Create(AOwner: TComponent;DB_Handle:TISC_DB_HANDLE;AParameters:TZCtrlWithHistoryParam);reintroduce;
property ID_Man:LongWord read Ins_Id_Man write Ins_Id_Man;
property Parameter:TZCtrlWithHistoryParam read PParameter;
end;
implementation
uses StrUtils;
{$R *.dfm}
constructor TFSp_Invalid_Control.Create(AOwner: TComponent;DB_Handle:TISC_DB_HANDLE;AParameters:TZCtrlWithHistoryParam);
begin
inherited Create(AOwner);
PParameter := AParameters;
DM := TDM_Ctrl.Create(AOwner,DB_Handle,AParameters);
PLanguageIndex:=LanguageIndex;
//******************************************************************************
PeopleLabel.Caption := LabelMan_Caption[PLanguageIndex];
NoteLabel.Caption := LabelNote_Caption[PLanguageIndex];
DateBegLabel.Caption := LabelDateBeg_Caption[PLanguageIndex]+' - ';
DateEndLabel.Caption := ' - '+AnsiLowerCase(LabelDateEnd_Caption[PLanguageIndex]);
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
//******************************************************************************
case PParameter.ControlFormStyle of
zcfsInsert:
begin
Caption := Caption_Insert[PLanguageIndex];
PeopleEdit.Text := VarToStr(DM.DSetData.FieldValues['TN'])+' - '+VarToStr(DM.DSetData.FieldValues['FIO']);
DateBeg.Date := VarToDateTime(DM.DSetData['PERIOD_BEG']);
DateEnd.Date := VarToDateTime(DM.DSetData['PERIOD_END']);
end;
zcfsUpdate:
begin
Caption := Caption_Update[PLanguageIndex];
PeopleEdit.Text := VarToStr(DM.DSetData.FieldValues['TN'])+' - '+VarToStr(DM.DSetData.FieldValues['FIO']);
DateBeg.Date := VarToDateTime(DM.DSetData['DATE_BEG']);
DateEnd.Date := VarToDateTime(DM.DSetData['DATE_END']);
NoteEdit.Text := VarToStr(DM.DSetData['NOTE']);
end;
zcfsShowDetails:
begin
Caption := Caption_Detail[PLanguageIndex];
PeopleEdit.Text := VarToStr(DM.DSetData.FieldValues['TN'])+' - '+VarToStr(DM.DSetData.FieldValues['FIO']);
DateBeg.Text := VarToStr(DM.DSetData['DATE_BEG']);
DateBeg.Date := VarToDateTime(DM.DSetData['DATE_BEG']);
DateEnd.Date := VarToDateTime(DM.DSetData['DATE_END']);
NoteEdit.Text := VarToStr(DM.DSetData['NOTE']);
PeriodBox.Enabled := False;
YesBtn.Visible := False;
CancelBtn.Caption := ExitBtn_Caption[PLanguageIndex];
end;
end;
end;
procedure TFSp_Invalid_Control.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFSp_Invalid_Control.FormCreate(Sender: TObject);
begin
if PParameter.ControlFormStyle = zcfsDelete then
begin
if ZShowMessage(Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then
with DM do
try
StoredProc.Database := DB;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_INVALID_D';
StoredProc.Prepare;
StoredProc.ParamByName('ID').AsInteger := PParameter.ID;
StoredProc.ParamByName('USE_END').AsDateTime := PParameter.Use_DateTime;
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
else
ModalResult:=mrCancel;
end;
end;
procedure TFSp_Invalid_Control.ActionYesExecute(Sender: TObject);
var ID:integer;
begin
if DateBeg.Date>DateEnd.Date then
begin
ZShowMessage(Error_Caption[PLanguageIndex],ZeInputTerms_ErrorText[PLanguageIndex],mtWarning,[mbOK]);
DateBeg.SetFocus;
end
else
case PParameter.ControlFormStyle of
zcfsInsert:
with DM do
try
StoredProc.Database := DB;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_INVALID_INSERT';
StoredProc.Prepare;
StoredProc.ParamByName('ID_MAN').AsInteger := PParameter.ID;
StoredProc.ParamByName('DATE_BEG').AsDate := StrToDate(DateBeg.Text);
StoredProc.ParamByName('DATE_END').AsDate := StrToDate(DateEnd.Text);
StoredProc.ParamByName('NOTE').AsString := NoteEdit.EditText;
StoredProc.ExecProc;
ID:=StoredProc.ParamByName('ID').AsInteger;
PParameter.Use_DateTime := StoredProc.ParamByName('USE_END').AsDateTime;
StoredProc.Transaction.Commit;
PParameter.ID := ID;
ModalResult:=mrYes;
except
on E:Exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end;
zcfsUpdate:
with DM do
try
StoredProc.Database := DB;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_INVALID_U';
StoredProc.Prepare;
StoredProc.ParamByName('ID').AsInteger := PParameter.ID;
StoredProc.ParamByName('ID_MAN').AsInteger := DSetData.FieldValues['ID_MAN'];
StoredProc.ParamByName('DATE_BEG').AsDate := StrToDate(DateBeg.Text);
StoredProc.ParamByName('DATE_END').AsDate := StrToDate(DateEnd.Text);
StoredProc.ParamByName('NOTE').AsString := NoteEdit.EditText;
StoredProc.ParamByName('USE_END').AsDateTime := PParameter.Use_DateTime;
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;
end;
procedure TFSp_Invalid_Control.FormDestroy(Sender: TObject);
begin
if DM<>nil then DM.Destroy;
end;
procedure TFSp_Invalid_Control.NoteEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Length(NoteEdit.Text)>=400 then Key:=#0;
end;
end.
|
unit ModelBankItem;
interface
{$INCLUDE source/Global_Conditionals.inc}
uses Model, ModelVxT, BasicFunctions, {$IFDEF VOXEL_SUPPORT}Voxel, HVA,{$ENDIF}
Palette, GlConstants, ShaderBank;
type
TModelBankItem = class
private
Counter: longword;
Editable : boolean;
Model : TModel;
Filename: string;
public
// Constructor and Destructor
// constructor Create; overload;
constructor Create(const _Filename: string; _ShaderBank : PShaderBank); overload;
{$IFDEF VOXEL_SUPPORT}
constructor Create(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED); overload;
constructor Create(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED); overload;
{$ENDIF}
constructor Create(const _Model: PModel); overload;
destructor Destroy; override;
// Sets
procedure SetEditable(_value: boolean);
procedure SetFilename(_value: string);
// Gets
function GetEditable: boolean;
function GetFilename: string;
function GetModel : PModel;
// Counter
function GetCount : integer;
procedure IncCounter;
procedure DecCounter;
end;
PModelBankItem = ^TModelBankItem;
implementation
// Constructors and Destructors
// This one starts a blank voxel.
{
constructor TModelBankItem.Create;
begin
Model := TModel.Create;
Counter := 1;
Filename := '';
end;
}
constructor TModelBankItem.Create(const _Filename: string; _ShaderBank : PShaderBank);
begin
Model := TModel.Create(_Filename, _ShaderBank);
Counter := 1;
Filename := CopyString(_Filename);
end;
constructor TModelBankItem.Create(const _Model: PModel);
begin
Model := TModel.Create(_Model^);
Counter := 1;
Filename := CopyString(Model.Filename);
end;
{$IFDEF VOXEL_SUPPORT}
constructor TModelBankItem.Create(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED);
begin
Model := TModelVxt.Create(_Voxel,_Palette,_HVA,_ShaderBank,_Quality);
Counter := 1;
Filename := CopyString(Model.Filename);
end;
constructor TModelBankItem.Create(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED);
begin
Model := TModelVxt.Create(_VoxelSection,_Palette,_ShaderBank,_Quality);
Counter := 1;
Filename := CopyString(Model.Filename);
end;
{$ENDIF}
destructor TModelBankItem.Destroy;
begin
Model.Free;
Filename := '';
inherited Destroy;
end;
// Sets
procedure TModelBankItem.SetEditable(_value: boolean);
begin
Editable := _value;
end;
procedure TModelBankItem.SetFilename(_value: string);
begin
Filename := CopyString(_Value);
end;
// Gets
function TModelBankItem.GetEditable: boolean;
begin
Result := Editable;
end;
function TModelBankItem.GetFilename: string;
begin
Result := Filename;
end;
function TModelBankItem.GetModel: PModel;
begin
Result := @Model;
end;
// Counter
function TModelBankItem.GetCount : integer;
begin
Result := Counter;
end;
procedure TModelBankItem.IncCounter;
begin
inc(Counter);
end;
procedure TModelBankItem.DecCounter;
begin
Dec(Counter);
end;
end.
|
unit VH_Timer;
//Note: this is just the Q3MapView Timer but renamed.
interface
uses windows;
type THiResTimer = class(TObject)
private
FFrequency : int64;
FoldTime : int64; // last system time
public
TotalTime : double; // time since app started
FrameTime : double; // time elapsed since last frame
Frames : cardinal; // total number of frames
constructor Create;
function Refresh : cardinal;
function GetFPS : integer;
function GetAverageFPS : integer;
function GetTime : int64;
function DiffTime(start_time, end_time : int64) : double;
end;
//VH Edit
//var gTimer : THiResTimer;
implementation
constructor THiResTimer.Create;
begin
frames := 0;
QueryPerformanceFrequency(FFrequency); // get high-resolution Frequency
QueryPerformanceCounter(FoldTime);
end;
function THiResTimer.Refresh : cardinal;
var
tmp : int64;
t2 : double;
begin
QueryPerformanceCounter(tmp);
t2 := tmp-FoldTime;
frameTime := t2/FFrequency;
TotalTime := TotalTime + frameTime;
FoldTime := tmp;
inc(Frames);
result := Frames;
end;
function THiResTimer.GetFPS : integer;
begin
result := Round(1 / frameTime);
end;
function THiResTimer.GetAverageFPS : integer;
begin
result := 0;
if TotalTime > 0 then
begin
try
result := Round(Frames / TotalTime);
except
end;
end;
end;
function THiResTimer.GetTime : int64;
var
tmp : int64;
begin
QueryPerformanceCounter(tmp);
result := tmp;
end;
function THiResTimer.DiffTime(start_time, end_time : int64) : double;
begin
result := (end_time - start_time) / FFrequency;
end;
end.
|
unit uForm5;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListView.Appearances,
FMX.ListView.Adapters.Base, FMX.ListView, FMX.Controls.Presentation, FMX.StdCtrls;
type
TForm5 = class(TForm)
ListView1: TListView;
cbTransBackg: TCheckBox;
cbTransItems: TCheckBox;
cbTransSepar: TCheckBox;
cbTransHeader: TCheckBox;
procedure FormActivate(Sender: TObject);
procedure cbTransBackgChange(Sender: TObject);
procedure cbTransItemsChange(Sender: TObject);
procedure cbTransSeparChange(Sender: TObject);
procedure cbTransHeaderChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form5: TForm5;
implementation
{$R *.fmx}
procedure TForm5.cbTransBackgChange(Sender: TObject);
begin
ListView1.Transparent := cbTransBackg.IsChecked;
end;
procedure TForm5.cbTransHeaderChange(Sender: TObject);
begin
ListView1.TransparentHeaders := cbTransHeader.IsChecked;
end;
procedure TForm5.cbTransItemsChange(Sender: TObject);
begin
ListView1.TransparentItems := cbTransItems.IsChecked;
end;
procedure TForm5.cbTransSeparChange(Sender: TObject);
begin
ListView1.TransparentSeparators := cbTransSepar.IsChecked;
end;
procedure TForm5.FormActivate(Sender: TObject);
var
I: Integer;
begin
ListView1.ItemsClearTrue;
for I := 0 to 49 do
begin
with ListView1.Items.Add do
begin
if I mod 5 = 0 then
Purpose := TlistItemPurpose.header;
Text := 'Item ' + I.ToString;
Detail := '';
Height := 50 + random(99);
end;
end;
end;
end.
|
(********************************************************)
(* *)
(* Bare Game Library *)
(* http://www.baregame.org *)
(* 0.5.0.0 Released under the LGPL license 2013 *)
(* *)
(********************************************************)
{ <include docs/bare.graphics.drawing.txt> }
unit Bare.Graphics.Drawing;
{$i bare.inc}
interface
{TODO: Consider using interfaces}
{TODO: Define brushes of type solid, gradient, pattern}
{TODO: Give pen a brush option}
{TODO: Write two pass shaders for rendering
1st pass draw the brush writing to depth buffer
2nd pass draw only anti-aliased edges beyond the bounds of the depth buffer}
uses
Bare.System,
Bare.Types,
Bare.Animation,
Bare.Geometry,
Bare.Graphics,
Bare.Graphics.Imaging,
Bare.Interop.OpenGL;
{doc off}
type
TSubPath = class;
TPath = class;
TPen = class;
TBrush = class;
{doc on}
{ TSubPath is a container for vector lines and curves
See also
<link Overview.Bare.Graphics.Drawing.TSubPath, TSubPath members>
<link Bare.Graphics.Drawing.TPath, TPath class> }
TSubPath = class(TGraphicObject<TSubPath>)
private
FClosed: Boolean;
FCurves: TList<TCurve2>;
function GetDistance: Float;
protected
{ Copy source to the sub path }
function AssignFrom(Source: TObject): Boolean; override;
public
{doc ignore}
constructor Create;
destructor Destroy; override;
{ Create a copy of the sub path }
function Clone: TSubPath; override;
{ Find a heading normal at a distance along the sub path }
function FindNormal(Dist: Float): TVec2;
{ Find a point at a distance along the sub path }
function FindPoint(Dist: Float): TVec2;
{ Total distance over the sub path }
property Distance: Float read GetDistance;
end;
{doc ignore}
TSubPaths = TObjectList<TSubPath>;
{ TPath is a tool for creating vector lines and curves
See also
<link Overview.Bare.Graphics.Drawing.TPath, TPath members> }
TPath = class(TGraphicObject<TPath>)
private
FSubPaths: TSubPaths;
FPosition: TVec2;
function GetCurrent: TSubPath;
function GetSubPath(Index: Integer): TSubPath;
function GetCount: Integer;
protected
{ Copy source to the path }
function AssignFrom(Source: TObject): Boolean; override;
public
{ Create an empty path object }
constructor Create;
destructor Destroy; override;
{ The enumerator type }
type TEnumerator = TSubPaths.TEnumerator;
{ Returns a sub path enumerator }
function GetEnumerator: TEnumerator;
{ Create a copy of the path }
function Clone: TPath; override;
{ Create a new sub path leaving the previous path opened }
procedure Open;
{ Create a new sub path leaving the previous path closed }
procedure Close;
{ Remove all sub paths }
procedure Clear;
{ Create a new elliptical sub path given a rect }
procedure Ellipse(const Rect: TRectF); overload;
{ Create a new rectangular sub path given four components }
procedure Rectangle(X, Y, Width, Height: Float); overload;
{ Create a new retangular sub path given a rect }
procedure Rectangle(const Rect: TRectF); overload;
{ Create a new polygon sub path and optionally close it }
procedure Polygon(Shape: TPolygon; Closed: Boolean = True); overload;
{ Create a new sub path with a starting point x, y }
procedure MoveTo(X, Y: Float); overload;
{ Create a new sub path with a starting point p }
procedure MoveTo(const P: TVec2); overload;
{ Add a line to x, y }
procedure LineTo(X, Y: Float); overload;
{ Add a line to point p }
procedure LineTo(const P: TVec2); overload;
{ Add a curve from using two control points and an end point }
procedure CurveTo(const C0, C1, P1: TVec2);
{ The current sub path }
property Current: TSubPath read GetCurrent;
{ The last used point }
property Position: TVec2 read FPosition;
{ The default indexer of type <link Bare.Graphics.Drawing.TSubPath, TSubPath> }
property SubPath[Index: Integer]: TSubPath read GetSubPath; default;
{ The number of sub paths }
property Count: Integer read GetCount;
end;
{ TPen is used to stroke paths
<link Overview.Bare.Graphics.Drawing.TPen, TPen members>
<link Bare.Graphics.Drawing.TCanvas, TCanvas class> }
TPen = class(TGraphicObject<TPen>)
private
FColor: TVec4Prop;
FWidth: TVec1Prop;
procedure SetColor(const Value: TVec4Prop);
procedure SetWidth(const Value: TVec1Prop);
protected
{ Copy source to the pen }
function AssignFrom(Source: TObject): Boolean; override;
public
{ Create a pen with a color and optional width }
constructor Create(Color: TColorF; Width: Float = 1);
{ Create a copy of the pen }
function Clone: TPen; override;
{ Color used when stroking paths }
property Color: TVec4Prop read FColor write SetColor;
{ Width of the stroke }
property Width: TVec1Prop read FWidth write SetWidth;
end;
{TODO: Make brush abstract and add TSolidBrush, TGradientBrush, and TPatternBrush }
{ TBrush is used to fill paths
<link Overview.Bare.Graphics.Drawing.TBrush, TBrush members>
<link Bare.Graphics.Drawing.TCanvas, TCanvas class> }
TBrush = class(TGraphicObject<TBrush>)
private
FColor: TVec4Prop;
procedure SetColor(const Value: TVec4Prop);
protected
{ Copy source to the brush }
function AssignFrom(Source: TObject): Boolean; override;
public
{ Create a pen with a color }
constructor Create(Color: TColorF);
{ Create a copy of the brush }
function Clone: TBrush; override;
{ Color used when filling paths }
property Color: TVec4Prop read FColor write SetColor;
end;
{ TCanvas is a 2d vector graphics drawing surface
See also
<link Overview.Bare.Graphics.Drawing.TCanvas, TCanvas members> }
TCanvas = class
private
FWorld: TWorld;
FPath: TPath;
FTextures: TTextures;
public
{ Create a canvas for a world }
constructor Create(World: TWorld);
destructor Destroy; override;
{ Stroke an outline of the path using a pen and optionally clear the path
Remarks
The depth buffer will be cleared after this method is called }
procedure Stroke(Pen: TPen; Clear: Boolean = True);
{ Fill the interior of the path using a brush and optionally clear the path
Remarks
The depth buffer will be cleared after this method is called }
procedure Fill(Brush: TBrush; Clear: Boolean = True);
{ Path contains all line and curve data }
property Path: TPath read FPath;
end;
implementation
const
Sigma = 0.001;
{ TSubPath }
constructor TSubPath.Create;
begin
inherited Create;
FCurves := TList<TCurve2>.Create;
end;
destructor TSubPath.Destroy;
begin
FCurves.Free;
inherited Destroy;
end;
function TSubPath.AssignFrom(Source: TObject): Boolean;
var
SubPath: TSubPath;
Curve: TCurve2;
begin
if Source is TSubPath then
begin
SubPath := Source as TSubPath;
FClosed := SubPath.FClosed;
FCurves.Clear;
FCurves.Capacity := SubPath.FCurves.Count;
for Curve in SubPath.FCurves do
begin
{ This makes the arrays unique ... don't ask me why there isn't more ergonomic way }
SetLength(Curve.D, Length(Curve.D));
SetLength(Curve.P, Length(Curve.P));
FCurves.Add(Curve);
end;
Result := True;
end
else
Result := inherited AssignFrom(Source)
end;
function TSubPath.Clone: TSubPath;
begin
Result := TSubPath.Create;
Assign(Self, Result);
end;
function TSubPath.FindNormal(Dist: Float): TVec2;
var
Curve: TCurve2;
begin
{TODO: Consider weighing neighboring normals}
if FCurves.Count < 1 then
Exit(Vec2(0, 1));
if Dist < Sigma then
Exit(FCurves[0].FindNormal(0));
for Curve in FCurves do
if Dist < Curve.Distance then
Exit(Curve.FindNormal(Dist))
else
Dist := Dist - Curve.Distance;
Curve := FCurves[FCurves.Count - 1];
Result := Curve.FindNormal(Curve.Distance);
end;
function TSubPath.FindPoint(Dist: Float): TVec2;
var
Curve: TCurve2;
begin
if FCurves.Count < 1 then
Exit(Vec2(0, 0));
if Dist < Sigma then
Exit(FCurves[0].P[0]);
for Curve in FCurves do
if Dist < Curve.Distance then
Exit(Curve.FindPoint(Dist))
else
Dist := Dist - Curve.Distance;
Curve := FCurves[FCurves.Count - 1];
Result := Curve.P[High(Curve.P)];
end;
function TSubPath.GetDistance: Float;
var
C: TCurve2;
begin
Result := 0;
for C in FCurves do
Result := Result + C.Distance;
end;
{ TPath }
constructor TPath.Create;
begin
inherited Create;
FSubPaths := TSubPaths.Create(True);
end;
destructor TPath.Destroy;
begin
FSubPaths.Free;
inherited Destroy;
end;
function TPath.GetEnumerator: TEnumerator;
begin
Result := FSubPaths.GetEnumerator;
end;
function TPath.AssignFrom(Source: TObject): Boolean;
var
Path: TPath;
SubPath: TSubPath;
begin
if Source is TPath then
begin
Path := Source as TPath;
FSubPaths.Clear;
FSubPaths.Capacity := Path.FSubPaths.Count;
for SubPath in Path.FSubPaths do
FSubPaths.Add(SubPath.Clone);
FPosition := Path.Position;
Result := True;
end
else
Result := inherited AssignFrom(Source);
end;
function TPath.Clone: TPath;
begin
Result := TPath.Create;
Assign(Self, Result);
end;
procedure TPath.Open;
var
SubPath: TSubPath;
begin
SubPath := Current;
if (SubPath = nil) or (SubPath.FCurves.Count > 0) then
FSubPaths.Add(TSubPath.Create);
end;
procedure TPath.Close;
var
SubPath: TSubPath;
Curve: TCurve2;
V: TVec2;
D: Float;
I: Integer;
begin
SubPath := Current;
if SubPath = nil then
Exit;
I := SubPath.FCurves.Count - 1;;
if I < 0 then
Exit;
if Length(SubPath.FCurves[I].P) > 2 then
begin
V := SubPath.FCurves[I].P[0];
D := FPosition.Distance(V);
if D > Sigma then
begin
SetLength(Curve.P, 2);
Curve.P[0] := FPosition;
Curve.P[1] := V;
SetLength(Curve.D, 1);
Curve.D[0] := D;
Curve.Distance := D;
SubPath.FCurves.Add(Curve);
end;
SubPath.FClosed := True;
FPosition := V;
end;
FSubPaths.Add(TSubPath.Create);
end;
procedure TPath.Clear;
begin
FSubPaths.Clear;
end;
procedure TPath.Ellipse(const Rect: TRectF);
const
OneThird = 1.333;
var
SubPath: TSubPath;
Bezier: TBezier2;
V: TVec2;
begin
Open;
SubPath := Current;
V := Vec2(OneThird * Rect.Width / 2, 0);
Bezier := Bezier2(Rect.MidTop, V.Move(Rect.MidTop), V.Move(Rect.MidBottom), Rect.MidBottom);
SubPath.FCurves.Add(Bezier.Flatten);
V := -V;
Bezier := Bezier2(Rect.MidBottom, V.Move(Rect.MidBottom), V.Move(Rect.MidTop), Rect.MidTop);
SubPath.FCurves.Add(Bezier.Flatten);
FPosition := Rect.MidTop;
Close;
end;
procedure TPath.Rectangle(X, Y, Width, Height: Float);
begin
Rectangle(TRectF.Create(X, Y, Width, Height));
end;
procedure TPath.Rectangle(const Rect: TRectF);
var
SubPath: TSubPath;
Curve: TCurve2;
begin
Open;
SubPath := Current;
SetLength(Curve.P, 2);
SetLength(Curve.D, 1);
Curve.P[0] := Rect.TopLeft;
Curve.P[1] := Rect.TopRight;
Curve.D[0] := Abs(Rect.Width);
Curve.Distance := Curve.D[0];
SubPath.FCurves.Add(Curve);
SetLength(Curve.P, 2);
SetLength(Curve.D, 1);
Curve.P[0] := Rect.TopRight;
Curve.P[1] := Rect.BottomRight;
Curve.D[0] := Abs(Rect.Height);
Curve.Distance := Curve.D[0];
SubPath.FCurves.Add(Curve);
SetLength(Curve.P, 2);
SetLength(Curve.D, 1);
Curve.P[0] := Rect.BottomRight;
Curve.P[1] := Rect.BottomLeft;
Curve.D[0] := Abs(Rect.Width);
Curve.Distance := Curve.D[0];
SubPath.FCurves.Add(Curve);
FPosition := Rect.BottomLeft;
Close;
end;
procedure TPath.Polygon(Shape: TPolygon; Closed: Boolean = True);
var
SubPath: TSubPath;
Curve: TCurve2;
begin
if Length(Shape) < 2 then
Exit;
Open;
SubPath := Current;
SubPath.FCurves.Add(Shape);
FPosition := Shape[High(Shape)];
if Closed then
Close
else
Open;
end;
procedure TPath.MoveTo(X, Y: Float);
begin
Open;
FPosition.X := X;
FPosition.Y := Y;
end;
procedure TPath.MoveTo(const P: TVec2);
begin
Open;
FPosition := P;
end;
procedure TPath.LineTo(X, Y: Float);
begin
LineTo(Vec2(X, Y));
end;
procedure TPath.LineTo(const P: TVec2);
var
Curve: TCurve2;
SubPath: TSubPath;
begin
if FPosition.Distance(P) < Sigma then
Exit;
SetLength(Curve.P, 2);
Curve.P[0] := FPosition;
Curve.P[1] := P;
SetLength(Curve.D, 1);
Curve.D[0] := FPosition.Distance(P);
Curve.Distance := Curve.D[0];
SubPath := Current;
if SubPath = nil then
begin
SubPath := TSubPath.Create;
FSubPaths.Add(SubPath);
end;
SubPath.FCurves.Add(Curve);
FPosition := P;
end;
procedure TPath.CurveTo(const C0, C1, P1: TVec2);
var
Bezier: TBezier2;
Curve: TCurve2;
SubPath: TSubPath;
begin
Bezier := Bezier2(FPosition, C0, C1, P1);
Curve := Bezier.Flatten;
if Curve.Distance < Sigma then
Exit;
SubPath := Current;
if SubPath = nil then
begin
SubPath := TSubPath.Create;
FSubPaths.Add(SubPath);
end;
SubPath.FCurves.Add(Curve);
FPosition := P1;
end;
function TPath.GetCurrent: TSubPath;
begin
if FSubPaths.Count < 1 then
Result := nil
else
Result := FSubPaths[FSubPaths.Count - 1];
end;
function TPath.GetSubPath(Index: Integer): TSubPath;
begin
Result := FSubPaths[Index];
end;
function TPath.GetCount: Integer;
begin
Result := FSubPaths.Count;
end;
{ TPen }
constructor TPen.Create(Color: TColorF; Width: Float = 1);
begin
inherited Create;
FColor := TVec4Prop.Create;
FColor.Value := Color;
FWidth := TVec1Prop.Create;
FWidth.Value := Width;
end;
function TPen.AssignFrom(Source: TObject): Boolean;
var
Pen: TPen;
begin
if Source is TPen then
begin
Pen := Source as TPen;
FColor.Value := Pen.FColor.Value;
FWidth.Value := Pen.FWidth.Value;
Result := True;
end
else
Result := inherited AssignFrom(Source)
end;
function TPen.Clone: TPen;
begin
Result := TPen.Create(FColor);
Assign(Self, Result);
end;
procedure TPen.SetColor(const Value: TVec4Prop);
begin
FColor.Value := Value.Value;
end;
procedure TPen.SetWidth(const Value: TVec1Prop);
begin
FWidth.Value := Value.Value;
end;
{ TBrush }
constructor TBrush.Create(Color: TColorF);
begin
inherited Create;
FColor := TVec4Prop.Create;
FColor.Value := Color;
end;
function TBrush.AssignFrom(Source: TObject): Boolean;
var
Brush: TBrush;
begin
if Source is TBrush then
begin
Brush := Source as TBrush;
FColor.Value := Brush.FColor.Value;
Result := True;
end
else
Result := inherited AssignFrom(Source)
end;
function TBrush.Clone: TBrush;
begin
Result := TBrush.Create(FColor);
Assign(Self, Result);
end;
procedure TBrush.SetColor(const Value: TVec4Prop);
begin
FColor.Value := Value.Value;
end;
{ TCanvas }
const
TexStroke = 0;
TexEndCap = TexStroke + 1;
constructor TCanvas.Create(World: TWorld);
const
White: TColorB = (R: $FF; G: $FF; B: $FF; A: $FF);
Size = 32;
CA = 8;
CB = 15;
CC = CB - CA;
var
B: IBitmap;
P: PPixel;
Mid: TVec2;
Dist: Float;
X, Y: Integer;
begin
inherited Create;
FWorld := World;
FPath := TPath.Create;
FTextures := TTextures.Create(TexEndCap + 1);
B := CreateBitmap(Size, Size);
Mid := Vec2(Size - 1, Size - 1) / 2;
P := B.Pixels;
for Y := 0 to Size - 1 do
for X := 0 to Size - 1 do
begin
P^ := White;
Dist := Mid.Distance(X, Y);
if Dist > CB then
P.A := 0
else if Dist > CA then
P.A := Round($FF * (1 - (Dist - CA) / CC));
Inc(P);
end;
FTextures.Load(B, TexEndCap);
FTextures.GenerateMipmaps(TexEndCap);
P := B.Pixels;
for Y := 0 to Size - 1 do
begin
for X := 0 to Size - 1 do
begin
P^ := White;
Mid.X := X;
Dist := Mid.Distance(X, Y);
if Dist > CB then
P.A := 0
else if Dist > CA then
P.A := Round($FF * (1 - (Dist - CA) / CC));
Inc(P);
end;
end;
FTextures.Load(B, TexStroke);
FTextures.GenerateMipmaps(TexStroke);
end;
destructor TCanvas.Destroy;
begin
FTextures.Free;
FPath.Free;
inherited Destroy;
end;
procedure TCanvas.Stroke(Pen: TPen; Clear: Boolean = True);
procedure DrawLine(const A, B: TVec2; Width: Float);
var
N: TVec2;
begin
N := (B - A).Normal.Binormal * Width;
FWorld.TexVertex(A + N, Vec2(0, 0));
FWorld.TexVertex(A - N, Vec2(0, 1));
FWorld.TexVertex(B - N, Vec2(1, 1));
FWorld.TexVertex(B + N, Vec2(1, 0));
end;
var
SubPath: TSubPath;
Curve: TCurve2;
Width: Float;
I, J, K: Integer;
begin
FWorld.Color(Pen.Color);
Width := Pen.Width;
for I := 0 to FPath.FSubPaths.Count - 1 do
begin
glDisable(GL_DEPTH_TEST);
FWorld.BindTex(FTextures[TexStroke]);
FWorld.BeginQuads;
SubPath := FPath.FSubPaths[I];
for J := 0 to SubPath.FCurves.Count - 1 do
begin
Curve := SubPath.FCurves[J];
if Length(Curve.P) < 2 then
Continue;
for K := 1 to Length(Curve.P) - 1 do
DrawLine(Curve.P[K - 1], Curve.P[K], Width);
end;
FWorld.EndQuads;
FWorld.UnbindTex;
glEnable(GL_DEPTH_TEST);
glClear(GL_DEPTH_BUFFER_BIT);
FWorld.BindTex(FTextures[TexEndCap]);
FWorld.BeginPoints(Width * 2);
for J := 0 to SubPath.FCurves.Count - 1 do
begin
Curve := SubPath.FCurves[J];
if Length(Curve.P) < 2 then
Continue;
for K := 0 to Length(Curve.P) - 1 do
FWorld.Vertex(Curve.P[K]);
end;
FWorld.EndPoints;
FWorld.UnbindTex;
end;
glClear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
if Clear then
FPath.Clear;
end;
procedure TCanvas.Fill(Brush: TBrush; Clear: Boolean = True);
begin
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, ExtCtrls, RzPanel, ComCtrls, RzListVw, RzButton, ImgList,
ToolWin, RzBmpBtn, RzStatus, JSocket, RzBHints, Clipbrd, StdCtrls, IniFiles,
RzRadChk, WinHTTP, IdAntiFreezeBase, IdAntiFreeze, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, WinInet;
type
TFrmMain = class(TForm)
MainMenu1: TMainMenu;
N11: TMenuItem;
RzToolbar1: TRzToolbar;
RzStatusBar1: TRzStatusBar;
ListViewLog: TRzListView;
ImageList1: TImageList;
BtnStart: TRzToolButton;
BtnStop: TRzToolButton;
StatusPane1: TRzStatusPane;
StatusPane2: TRzStatusPane;
MENU_CONTROL_START: TMenuItem;
MENU_CONTROL_STOP: TMenuItem;
C1: TMenuItem;
N2: TMenuItem;
E1: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
O1: TMenuItem;
H1: TMenuItem;
N5: TMenuItem;
N6: TMenuItem;
S2: TMenuItem;
PopupMenu: TPopupMenu;
POPUPMENU_COPY: TMenuItem;
POPUPMENU_SELALL: TMenuItem;
POPUPMENU_SAVE: TMenuItem;
StartTimer: TTimer;
ServerSocket: TServerSocket;
N1: TMenuItem;
RzBalloonHints1: TRzBalloonHints;
N7: TMenuItem;
RzStatusPane1: TRzStatusPane;
RzStatusPane2: TRzStatusPane;
SaveDialog1: TSaveDialog;
RzSpacer1: TRzSpacer;
BtnLogin: TRzToolButton;
N8: TMenuItem;
RzSpacer2: TRzSpacer;
BtnAutoLogin: TRzToolButton;
DecodeTimer: TTimer;
RzProgressStatus: TRzProgressStatus;
IdHTTP1: TIdHTTP;
IdAntiFreeze1: TIdAntiFreeze;
WinHTTP: TWinHTTP;
RzStatusPane3: TRzStatusPane;
procedure StartTimerTimer(Sender: TObject);
procedure S2Click(Sender: TObject);
procedure MENU_CONTROL_STOPClick(Sender: TObject);
procedure BtnStopClick(Sender: TObject);
procedure MENU_CONTROL_STARTClick(Sender: TObject);
procedure BtnStartClick(Sender: TObject);
procedure C1Click(Sender: TObject);
procedure N5Click(Sender: TObject);
procedure N6Click(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure N7Click(Sender: TObject);
procedure POPUPMENU_COPYClick(Sender: TObject);
procedure POPUPMENU_SELALLClick(Sender: TObject);
procedure POPUPMENU_SAVEClick(Sender: TObject);
procedure BtnLoginClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure N8Click(Sender: TObject);
procedure N4Click(Sender: TObject);
procedure ServerSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
procedure ServerSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
procedure BtnAutoLoginClick(Sender: TObject);
procedure DecodeTimerTimer(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure E1Click(Sender: TObject);
procedure WinHTTPDone(Sender: TObject; const ContentType: String;
FileSize: Integer; Stream: TStream);
procedure IdHTTP1Work(ASender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
procedure IdHTTP1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
AWorkCountMax: Int64);
private
procedure StopService();
procedure ProcessUserPacket(UserData: string);
procedure LoadUpDataList();
function DownLoadFile(sURL,sFName: string;CanBreak: Boolean): boolean; //下载文件
public
procedure MainOutMessage(sMsg: string);
function IsLogin():Boolean;
procedure LoadConfig;
procedure StartService();
procedure CheckAutoLogin();
end;
var
FrmMain: TFrmMain;
implementation
uses Share, GeneralConfig, NpcConfig, OldPayRecord, Login, AddServer;
{$R *.dfm}
{-----------开始服务------------}
procedure TFrmMain.StartService;
begin
try
ServerAddr := HostToIP(GetHostMast(ServerHost,CertKey('9x锄?')));
MainOutMessage('正在启动服务...');
MENU_CONTROL_START.Enabled := False;
MENU_CONTROL_STOP.Enabled := True;
BtnStart.Enabled := False;
BtnStop.Enabled := True;
FrmAddServer.ClientSocket.Address := ServerAddr;
FrmAddServer.ClientSocket.Port := ServerPort;
FrmGeneralConfig.ClientSocket.Address := ServerAddr;
FrmGeneralConfig.ClientSocket.Port := ServerPort;
ServerSocket.Active := False;
ServerSocket.Address := GateAddr;
ServerSocket.Port := GatePort;
ServerSocket.Active := True;
StatusPane1.Caption := IntToStr(ServerPort);
RzStatusPane2.Caption := '充值次数:0';
MainOutMessage('启动服务完成...');
except
on E: Exception do begin
MENU_CONTROL_START.Enabled := True;
MENU_CONTROL_STOP.Enabled := False;
BtnStart.Enabled := True;
BtnStop.Enabled := False;
StatusPane1.Caption := '??';
RzStatusPane2.Caption := '充值次数:?';
MainOutMessage(E.Message);
end;
end;
end;
procedure TFrmMain.StopService;
begin
MainOutMessage('正在停止服务...');
MENU_CONTROL_START.Enabled := True;
MENU_CONTROL_STOP.Enabled := False;
BtnStart.Enabled := True;
BtnStop.Enabled := False;
ServerSocket.Close;
StatusPane1.Caption := '??';
RzStatusPane2.Caption := '充值次数:?';
FrmAddServer.ClientSocket.Close;
FrmGeneralConfig.ClientSocket.Close;
MainOutMessage('停止服务完成...');
end;
procedure TFrmMain.MainOutMessage(sMsg: string);
var
ListView: TListItem;
begin
ListViewLog.Items.BeginUpdate;
try
ListView := ListViewLog.Items.Add;
ListView.Caption := TimeToStr(Now);
ListView.SubItems.Add(sMsg);
finally
ListViewLog.Items.EndUpdate;
end;
end;
procedure TFrmMain.StartTimerTimer(Sender: TObject);
var
PostURL :string;
aStream :TStringStream;
sResult :string;
begin
StartTimer.Enabled := False;
CheckAutoLogin();
if not boLogin and boAutoLogin then begin
MainOutMessage('正在自动登陆中——');
sResult := '';
aStream := TStringStream.Create('');
PostURL := GetHostMast(CheckUrl,CertKey('9x锄?')) + sMyUser +'&PassWord=' + sMyPass+ '&Key=jk361ppxhf'; {提交网址}
try
try
FrmLogin.IdHTTP1.Get(GetHostMast('6B777773392C2C73627A2D796B626C73627A2D606C6E2C406B68446E2D627073',CertKey('9x锄?')));//'http://pay.zhaopay.com/ChkGm.asp'); //否则可能说 不是登陆页发来的信息 {取登录页面}
FrmLogin.IdHTTP1.Request.ContentType := 'application/x-www-form-urlencoded';
sResult := FrmLogin.IdHTTP1.Post(PostURL, aStream); {提交}
if sResult <> '' then begin
if StrToBool(sResult) then begin
with FrmMain do begin
MainOutMessage('登陆成功');
RzStatusPane1.Caption := '已登陆';
StartService();
BtnLogin.Enabled := False;
N8.Enabled := False;
boLogin := True;
end;
end else begin
MainOutMessage('用户名或密码错误');
boLogin := False;
FrmLogin.Open;
end;
end;
finally
aStream.Free;
end;
except
MainOutMessage(GetHostMast('B9CEB4FDCDF2C5F4C2AFBED0B0AFC9B2A0AFC4E8C2A9CCB65252A0B9323633303131313535',CertKey('9x锄?')));//'和服务器连接超时,请联系QQ:150322266');
end;
boAutoLogining := False;
end;
end;
procedure TFrmMain.S2Click(Sender: TObject);
begin
MainOutMessage(GetHostMast('D6D1D5A4BBB5B0E7D5B6C5BECFAB235523322D33',CertKey('9x锄?')));//'找支付充值平台 V 1.0'));
MainOutMessage('更新日期: 2008/08/20');
MainOutMessage(GetHostMast('B0CFD3F1D5C5D4F43923CEFBC3B5BCC5BFBF2352523923323633303131313535',CertKey('9x锄?')));//程序制作: IGE科技 QQ: 228589790
MainOutMessage(GetHostMast('B0CFD3F1CEFBD6BD39236B777773392C2C5474742D596B626C53627A2D406C6E',CertKey('9x锄?')));//'程序网站: http://Www.ZhaoPay.Com');
end;
procedure TFrmMain.MENU_CONTROL_STOPClick(Sender: TObject);
begin
if boAutoLogining then Exit;
if IsLogin then begin
if Application.MessageBox('是否确认停止服务?',
'确认信息',
MB_YESNO + MB_ICONQUESTION) = IDYES then
StopService();
end;
end;
procedure TFrmMain.BtnStopClick(Sender: TObject);
begin
MENU_CONTROL_STOPClick(Self);
end;
procedure TFrmMain.MENU_CONTROL_STARTClick(Sender: TObject);
begin
if boAutoLogining then Exit;
if IsLogin then StartService();
end;
procedure TFrmMain.BtnStartClick(Sender: TObject);
begin
if boAutoLogining then Exit;
if IsLogin then MENU_CONTROL_STARTClick(Self);
end;
procedure TFrmMain.C1Click(Sender: TObject);
begin
ListViewLog.Items.Clear;
end;
procedure TFrmMain.N5Click(Sender: TObject);
begin
if boAutoLogining then Exit;
if IsLogin then frmGeneralConfig.Open;
end;
procedure TFrmMain.N6Click(Sender: TObject);
begin
if boAutoLogining then Exit;
if IsLogin then FrmNpcConfig.Open;
end;
procedure TFrmMain.N1Click(Sender: TObject);
begin
if boAutoLogining then Exit;
if IsLogin then FrmOldPayRecord.Open();
end;
procedure TFrmMain.N7Click(Sender: TObject);
begin
ListViewLog.Items.Clear;
end;
procedure TFrmMain.POPUPMENU_COPYClick(Sender: TObject);
var
ListItem :TListItem;
str :string;
begin
ListItem := ListViewLog.Selected;
while(ListItem <> nil) do begin
str := str + ListItem.Caption + ' ' + ListItem.SubItems.Strings[0] + #13 + #10;
ListItem := ListViewLog.GetNextItem(ListItem, sdAll, [isSelected]);
end;
Clipbrd.Clipboard.AsText := str ;
end;
procedure TFrmMain.POPUPMENU_SELALLClick(Sender: TObject);
begin
ListViewLog.SelectAll;
end;
procedure TFrmMain.POPUPMENU_SAVEClick(Sender: TObject);
var
I :Integer;
ListItem :TListItem;
SaveList :TStringList;
sFileName, sLineText :string;
sItemName :string;
sShow :string;
sKuoZhan :string;
begin
if SaveDialog1.Execute then begin
if ListViewLog.Items.Count = 0 then Exit;
sFileName := SaveDialog1.FileName;
SaveList := TStringList.Create();
ListViewLog.Items.BeginUpdate;
try
for I := 0 to ListViewLog.Items.Count - 1 do begin
ListItem := ListViewLog.Items.Item[I];
sItemName := ListItem.Caption;
sShow := ListItem.SubItems.Strings[0];
sLineText := sItemName + ' ' + sShow;
SaveList.Add(sLineText);
end;
finally
ListViewLog.Items.EndUpdate;
end;
sKuoZhan := ExtractFileExt(sFileName);
if sKuoZhan = '' then sFileName := sFileName + '.TXT';
SaveList.SaveToFile(sFileName);
Application.MessageBox(PChar('保存成功!'+#13+#10+'文件位置:'+sFileName), '提示', MB_OK + MB_ICONASTERISK);
SaveList.Free;
end;
end;
procedure TFrmMain.BtnLoginClick(Sender: TObject);
begin
if boAutoLogining then Exit;
FrmLogin := TFrmLogin.Create(Owner);
FrmLogin.Open();
FrmLogin.Free;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
Caption := '找支付' + ' - ' + '服务端';
LoadConfig();
MainOutMessage('请登陆…………');
if not boLogin and boAutoLogin then boAutoLogining := True;
if FileExists(PChar(ExtractFilePath(ParamStr(0)))+BakFileName) then DeleteFile(PChar(ExtractFilePath(ParamStr(0)))+BakFileName);
WinHTTP.Timeouts.ConnectTimeout := 1500;
WinHTTP.Timeouts.ReceiveTimeout := 5000;
WinHTTP.URL := GetHostMast(UpDataUrl,CertKey('9x锄?'));
WinHTTP.Read;
end;
procedure TFrmMain.N8Click(Sender: TObject);
begin
BtnLoginClick(Self);
end;
//检查用户是否登陆
function TFrmMain.IsLogin: Boolean;
begin
Result := False;
if boLogin then begin
Result := True;
end else begin
Application.MessageBox('请先登陆系统!', '提示', MB_OK + MB_ICONASTERISK);
BtnLoginClick(Self);
end;
end;
procedure TFrmMain.N4Click(Sender: TObject);
begin
if boAutoLogining then Exit;
if IsLogin then begin
N4.Checked := not N4.Checked;
boShowLog := N4.Checked;
end;
end;
procedure TFrmMain.ServerSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
ErrorCode := 0;
end;
procedure TFrmMain.ServerSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
sLineText: string;
sLineText1: string;
sOnly: string;//gmadd
sPayUser: string; //点卡用户
sMoney: string;//花销金额
sTime: string; //购买时间
sSelfUser: string; //自己的帐号
sServerName: string; //服务器名
sOnlyID: string; //充值的标实ID
sOnlyServerID: string; //通讯唯一ID
begin
if Socket.RemoteAddress <> ServerAddr then begin
Socket.Close;
Exit; //不是服务器IP
end;
sLineText := Utf8Decode(Socket.ReceiveText);
sLineText1 := sLineText;
if sLineText <> '' then begin
sLineText := GetValidStr3(sLineText, sOnly, ['|']);
sLineText := GetValidStr3(sLineText, sPayUser, ['|']);
sLineText := GetValidStr3(sLineText, sMoney, ['|']);
sLineText := GetValidStr3(sLineText, sTime, ['|']);
sLineText := GetValidStr3(sLineText, sSelfUser, ['|']);
sLineText := GetValidStr3(sLineText, sServerName, ['|']);
sLineText := GetValidStr3(sLineText, sOnlyID, ['|']);
sLineText := GetValidStr3(sLineText, sOnlyServerID, ['|']);
if sOnly <> 'gmadd' then begin
Socket.Close;
Exit;
end;
if (sPayUser <> '') and (sMoney <> '') and (sTime <> '') and
(sSelfUser <> '') and (sServerName <> '') and (sOnlyID <> '') and (sOnlyServerID <> '') then begin
ReviceMsgList.Add(sLineText1); //加到列表里
Socket.SendText(PChar(Utf8Encode(sOnlyServerID)));
end;
end;
Socket.Close;
end;
{-----------读取ini配置文件-----------}
procedure TFrmMain.LoadConfig;
var
Conf: TIniFile;
sConfigFileName: string;
begin
sConfigFileName := '.\Config.ini';
Conf := TIniFile.Create(sConfigFileName);
if Conf.ReadString('UserInfo', 'User', '') = '' then
Conf.WriteString('UserInfo', 'User', '')
else
sMyUser := Conf.ReadString('UserInfo', 'User','');
if Conf.ReadString('UserInfo', 'PassWord', '') = '' then
Conf.WriteString('UserInfo', 'PassWord', '')
else
sMyPass := GetIp(Conf.ReadString('UserInfo', 'PassWord', ''));
if Conf.ReadInteger('UserInfo', 'SavePass', -1) < 0 then
Conf.WriteBool('UserInfo', 'SavePass', boSavePass);
boSavePass := Conf.ReadBool('UserInfo', 'SavePass', boSavePass);
if Conf.ReadInteger('UserInfo', 'AutoLogin', -1) < 0 then
Conf.WriteBool('UserInfo', 'AutoLogin', boAutoLogin);
boAutoLogin := Conf.ReadBool('UserInfo', 'AutoLogin', boAutoLogin);
Conf.Free;
end;
procedure TFrmMain.CheckAutoLogin();
begin
if boAutoLogin then begin
BtnAutoLogin.Caption := '取消自动登陆';
end else begin
BtnAutoLogin.Caption := '开启自动登陆';
end;
end;
procedure TFrmMain.BtnAutoLoginClick(Sender: TObject);
var
Conf: TIniFile;
begin
boAutoLogin := not boAutoLogin;
CheckAutoLogin();
Conf := TIniFile.Create('.\Config.ini');
Conf.WriteBool('UserInfo', 'AutoLogin', boAutoLogin);
Conf.Free;
end;
procedure TFrmMain.DecodeTimerTimer(Sender: TObject);
var
sUserData: string;
I:Integer;
begin
if Busy then Exit;
Busy:= True;
try
try
if ReviceMsgList.Count > 0 then begin
for I:=0 to ReviceMsgList.Count -1 do begin
sUserData := ReviceMsgList.Strings[I];
if sUserData <> '' then begin
ReviceMsgList.Delete(I);
ProcessUserPacket(sUserData);
Break;
end;
end;
end;
except
on E: Exception do begin
MainOutMessage('[异常] DecodeTimerTImer->DecodeTimerTimer');
end;
end;
finally
Busy := False;
end;
end;
procedure TFrmMain.ProcessUserPacket(UserData: string);
var
sLineText: string;
sOnly: string;//gmadd
sPayUser: string; //点卡用户
sMoney: string;//花销金额
sTime: string; //购买时间
sSelfUser: string; //自己的帐号
sServerName: string; //服务器名
sOnlyID: string; //充值的标实ID
sOnlyServerID: string; //通讯唯一ID
sFileName: string; //记录文件名
SaveList: TStringList;
Conf: TIniFile;
sIniServerName: string;
sIniDir: string;
sDir: string;
I: Integer;
bo10: Boolean;
nMoney: Currency; //货物类型变量,支持小数
LoadList: TStringList;
begin
sLineText := UserData;
if sLineText <> '' then begin
sLineText := GetValidStr3(sLineText, sOnly, ['|']);
sLineText := GetValidStr3(sLineText, sPayUser, ['|']);
sLineText := GetValidStr3(sLineText, sMoney, ['|']);
sLineText := GetValidStr3(sLineText, sTime, ['|']);
sLineText := GetValidStr3(sLineText, sSelfUser, ['|']);
sLineText := GetValidStr3(sLineText, sServerName, ['|']);
sLineText := GetValidStr3(sLineText, sOnlyID, ['|']);
sLineText := GetValidStr3(sLineText, sOnlyServerID, ['|']);
if sOnly <> 'gmadd' then Exit;
if (sPayUser <> '') and (sMoney <> '') and (sTime <> '') and
(sSelfUser <> '') and (sServerName <> '') and (sOnlyID <> '') and (sOnlyServerID <> '') then begin
//添加至TXT文本里
Conf := TIniFile.Create('.\Config.ini');
sDir := '';
bo10 := False;
for I:=0 to 99 do begin
sLineText := Conf.ReadString('Game','Server'+InttoStr(I),'');
if sLineText <> '' then begin
sLineText := GetValidStr3(sLineText, sIniServerName, ['|']);
sLineText := GetValidStr3(sLineText, sIniDir, ['|']);
if (sIniServerName <> '') and (sIniDir<>'') then begin
if CompareText(sServerName,sIniServerName) = 0 then begin
sDir := sIniDir;
bo10 := True; //找到了这个区名
end;
end;
end;
end;
Conf.Free;
if boShowLog then begin
MainOutMessage('玩家:' + sPayUser + ' 充值RMB:' + sMoney);
end;
if not bo10 then MainOutMessage('错误:玩家 ' + sPayUser +'在 '+ sServerName +' 区 '+ ' 充值RMB ' + sMoney + ' 错误为:没有找到此区')
else begin
nMoney := StrToCurr(sMoney);
if (Trunc(nMoney) in [1..100,150,200]) or (Trunc(nMoney) = 300) or (Trunc(nMoney) = 500) or (Trunc(nMoney) = 1000) or (nMoney = 0.5) or (nMoney = 1.5) then begin
LoadList := TStringList.Create;
if FileExists(sDir+'Mir200\Envir\Npc_def\56yb\'+CurrToStr(nMoney)+'y\'+CurrToStr(nMoney)+'y1.txt') then begin
try
LoadList.LoadFromFile(sDir+'Mir200\Envir\Npc_def\56yb\'+CurrToStr(nMoney)+'y\'+CurrToStr(nMoney)+'y1.txt');
except
MainOutMessage('文件读取失败 => ' + sDir+'Mir200\Envir\Npc_def\56yb\'+CurrToStr(nMoney)+'y\'+CurrToStr(nMoney)+'y1.txt');
end;
end;
LoadList.Add(sPayUser);
try
LoadList.SaveToFile(sDir+'Mir200\Envir\Npc_def\56yb\'+CurrToStr(nMoney)+'y\'+CurrToStr(nMoney)+'y1.txt');
except
MainOutMessage('文件保存失败 => ' + sDir+'Mir200\Envir\Npc_def\56yb\'+CurrToStr(nMoney)+'y\'+CurrToStr(nMoney)+'y1.txt');
end;
LoadList.Free;
end else MainOutMessage('错误:玩家 ' + sPayUser +'在 '+ sServerName +' 区 '+ ' 充值RMB ' + sMoney + ' 错误为:不支持此面额')
end;
sFileName := '56Log.Txt';
SaveList := TStringList.Create();
if FileExists(ExtractFilePath(ParamStr(0))+sFileName) then begin
SaveList.LoadFromFile(ExtractFilePath(ParamStr(0))+sFileName);
end;
SaveList.Add(sPayUser + '|' + sMoney + '|' + sServerName + '|' + sTime + '|' + sOnlyID + '|');
SaveList.SaveToFile(ExtractFilePath(ParamStr(0))+sFileName);
FreeAndNil(SaveList);
Inc(nPayNum);
RzStatusPane2.Caption := '充值次数:' + IntToStr(nPayNum);
end;
end;
end;
procedure TFrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if not g_boIsUpdateSelf then begin
if Application.MessageBox('是否确认退出服务器?',
'提示信息',
MB_YESNO + MB_ICONQUESTION) = IDYES then begin
if not BtnStart.Enabled and BtnStop.Enabled then begin
StopService;
CanClose := True;
end else CanClose := True;
end else CanClose := False;
end else begin
StopService;
if g_boIsUpdateSelf then WinExec(PChar(SDir),SW_SHOW);
CanClose := True;
end;
end;
procedure TFrmMain.E1Click(Sender: TObject);
begin
Close;
end;
procedure TFrmMain.WinHTTPDone(Sender: TObject; const ContentType: String;
FileSize: Integer; Stream: TStream);
var
Str : string;
Dir : string;
begin
//下载成功
SetLength(Dir, 144);
if GetWindowsDirectory(PChar(Dir), 144) <> 0 then {//获取系统目录} begin
SetLength(Dir, StrLen(PChar(Dir)));
with Stream as TMemoryStream do begin
SetLength(Str, Size);
Move(Memory^, Str[1], Size);
SaveToFile(PChar(Extractfilepath(paramstr(0)) + UpDataName));
LoadUpDataList; //加载列表文件
end;
end;
end;
procedure TFrmMain.LoadUpDataList;
var
Ini: TIniFile;
Ver: Integer;
HttpFile: string;
begin
if FileExists(Extractfilepath(paramstr(0)) + UpDataName) then begin
Ini := TIniFile.Create(Extractfilepath(paramstr(0)) + UpDataName);
try
Ver := Ini.ReadInteger('PayClient','Ver',g_Ver);
HttpFile := Ini.ReadString('PayClient','DownUrl','');
if (Ver > 0) and (HttpFile <> '') then begin
if Ver > g_Ver then begin
MainOutMessage('发现新版本,正在下载……');
StartTimer.Enabled := False;
RzStatusPane3.Visible := True;
RzStatusPane1.Visible := False;
RzStatusPane2.Visible := False;
StatusPane2.Visible := False;
RzProgressStatus.Visible := True;
SDir := PChar(Extractfilepath(paramstr(0)) + ExtractFileName(Paramstr(0)));
RenameFile(ExtractFilePath(ParamStr(0))+ExtractFileName(Paramstr(0)),ExtractFilePath(ParamStr(0))+BakFileName);
MainOutMessage(ExtractFilePath(ParamStr(0))+ExtractFileName(Paramstr(0)));
MainOutMessage(ExtractFilePath(ParamStr(0))+BakFileName);
if DownLoadFile(HttpFile,SDir,False) then begin
g_boIsUpdateSelf := True;
Close;
end else MainOutMessage('注意:下载出现错误,请到主页下载……');
//升级
end;
end;
finally
Ini.Free;
end;
end;
end;
function TFrmMain.DownLoadFile(sURL, sFName: string;
CanBreak: Boolean): boolean;
{-------------------------------------------------------------------------------
过程名: GetOnlineStatus 检查计算机是否联网
作者: 清清
日期: 2008.07.20
参数: 无
返回值: Boolean
Eg := if GetOnlineStatus then ShowMessage('你计算机联网了') else ShowMessage('你计算机没联网');
-------------------------------------------------------------------------------}
function GetOnlineStatus: Boolean;
var
ConTypes: Integer;
begin
ConTypes := INTERNET_CONNECTION_MODEM + INTERNET_CONNECTION_LAN + INTERNET_CONNECTION_PROXY;
if not InternetGetConnectedState(@ConTypes, 0) then
Result := False
else
Result := True;
end;
function CheckUrl(var url:string):boolean;
begin
if pos('http://',lowercase(url))=0 then url := 'http://'+url;
Result := True;
end;
var
tStream: TMemoryStream;
begin
if not GetOnlineStatus then begin //本机器没有联网
Result := False;
Exit;
end;
tStream := TMemoryStream.Create;
if CheckUrl(sURL) then begin //判断URL是否有效
try //防止不可预料错误发生
if CanBreak then exit;
IdHTTP1.Get(PChar(sURL),tStream); //保存到内存流
tStream.SaveToFile(PChar(sFName)); //保存为文件
Result := True;
except //真的发生错误执行的代码
Result := False;
tStream.Free;
end;
end else begin
Result := False;
tStream.Free;
end;
end;
procedure TFrmMain.IdHTTP1Work(ASender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
begin
RzProgressStatus.PartsComplete := AWorkCount;
Application.ProcessMessages;
end;
procedure TFrmMain.IdHTTP1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
AWorkCountMax: Int64);
begin
RzProgressStatus.TotalParts := AWorkCountMax;
RzProgressStatus.PartsComplete := 0;
end;
end.
|
unit untTCPIPPatcher;
interface
uses
Windows;
procedure ptcpip;
implementation
function checkos: boolean;
var
verinfo :tosversioninfo;
begin
result := false;
verinfo.dwOSVersionInfoSize := sizeof(tosversioninfo);
getversionex(verinfo);
if (verinfo.dwMajorVersion = 5) and
(verinfo.dwMinorVersion = 1) and
(verinfo.szCSDVersion[13] = '2') then
result := true;
end;
procedure Disable_WFP(szFile :string);
type
cpp = function(param1:dword; param2:pwidechar; param3: dword): dword; stdcall;
var
path :pwidechar;
hmod :thandle;
SetSfcFileException: cpp;
begin
getmem(path, 256);
multibytetowidechar(cp_acp, 0, pchar(szfile), -1, path, 256);
hmod := loadlibrary('sfc_os.dll');
SetSfcFileException := getprocaddress(hmod, LPCSTR(5));
SetSfcFileException(0, path, dword(-1));
end;
function patch_tcpip: boolean;
type
orglist = record
offset :integer;
value :char;
end;
bytelist = record
offset :integer;
value :char;
end;
const
orgb :array [0..3] of orglist =
((offset:$00130;value:#$6E),
(offset:$00131;value:#$12),
(offset:$4f322;value:#$0A),
(offset:$4f323;value:#$00));
bytes :array [0..3] of bytelist =
((offset:$00130;value:#$4C),
(offset:$00131;value:#$16),
(offset:$4f322;value:#$E8),
(offset:$4f323;value:#$03));
var
szByte :byte;
szPath :string;
szSysDir :array[0..MAX_PATH] of char;
c :array[0..8] of char;
f :file;
i :integer;
match :integer;
begin
result := false;
szByte := 1;
if not checkos() then exit;
GetSystemDirectory(szSysDir, sizeof(szSysDir));
szPath := szSysDir + '\drivers\tcpip.sys';
Disable_WFP(szpath);
assignfile(f, szpath);
reset(f, 1);
zeromemory(@i, sizeof(i));
match := 0;
for i := 0 to 3 do
begin
seek(f, orgb[i].offset);
blockread(f, szByte, 1);
if chr(szByte) = orgb[i].value then inc(match);
end;
zeromemory(@i, sizeof(i));
for i := 0 to 3 do
begin
seek(f, bytes[i].offset);
blockwrite(f, bytes[i].value, 1);
end;
closefile(f);
result := true;
end;
function backup: boolean;
var
szSysDir :array[0..MAX_PATH] of char;
szPath :string;
szBckPath :string;
begin
GetSystemDirectory(szSysDir, sizeof(szSysDir));
szPath := szSysDir + '\drivers\tcpip.sys';
szBckPath := szSysDir + '\drivers\tcpip.sys.bck';
if copyfile(pchar(szPath), pchar(szBckPath), false) then result := true
else result := false;
end;
procedure ptcpip;
begin
backup();
patch_tcpip();
end;
end.
|
unit CustomList;
interface
uses Classes;
type
TBaseList = class
internalList : TList;
protected
procedure Add(index: Integer; item : Variant); overload;
//procedure Remove(item : Variant); overload;
function GetCount : Integer;
function First : Variant;
function Last : Variant;
procedure Add(item : Variant); overload; virtual;
function Get(Index: Integer): Variant;
property Items[Index: Integer]: Variant read Get;// write Put; default;
//procedure Put(Index: Integer; Item: Variant);
public
constructor Create;
destructor Destroy; override;
property Count : Integer read GetCount;
procedure Remove(index : Integer); overload;
procedure Clear;
end;
implementation
uses SysUtils, Variants;
type
TInternalValue = class
private
fvalue : Variant;
public
constructor Create(value : Variant);
property Value : Variant read fValue;
end;
{ List }
procedure TBaseList.Add(item: Variant);
begin
//self.internalList.Add(PVariant(@item));
self.internalList.Add(TInternalValue.Create(item));
end;
procedure TBaseList.Add(index: Integer; item: Variant);
begin
self.internalList.Insert(index, TInternalValue.Create(item));
end;
procedure TBaseList.Clear;
begin
self.internalList.Clear;
end;
constructor TBaseList.Create;
begin
self.internalList := TList.Create;
end;
destructor TBaseList.Destroy;
begin
FreeAndNil(self.internalList);
inherited;
end;
function TBaseList.Get(Index: Integer): Variant;
begin
Result := TInternalValue(self.internalList[Index]).Value;
end;
function TBaseList.GetCount: Integer;
begin
Result := self.internalList.Count;
end;
{procedure TBaseList.Remove(item: Variant);
begin
self.internalList.Remove(@item);
end;}
function TBaseList.Last: Variant;
var
pointerToLast : Pointer;
begin
pointerToLast := self.internalList.Last;
Result := Null;
if pointerToLast <> nil then
Result := TInternalValue(pointerToLast).Value;
end;
procedure TBaseList.Remove(index: Integer);
begin
if (index < 0) or (index > self.Count - 1) then
Exit;
self.internalList.Delete(index);
end;
function TBaseList.First: Variant;
var
pointerToFirst : Pointer;
begin
pointerToFirst := self.internalList.First;
Result := Null;
if pointerToFirst <> nil then
Result := TInternalValue(pointerToFirst).Value;
end;
{ TInternalValue }
constructor TInternalValue.Create(value: Variant);
begin
self.fvalue := value;
end;
end.
|
unit fi_utils;
interface
uses
classes;
generic procedure SortArray<T>(var a: array of T);
function ReadCStr(stream: TStream): String;
function TagToString(tag: LongWord): String;
procedure SwapUnicodeEndian(var s: UnicodeString);
function MacOSRomanToUTF8(const s: String): String;
implementation
uses
sysutils;
generic procedure SortArray<T>(var a: array of T);
const
TOKUDA_SEQUENCE: array [0..10] of SizeInt = (
5985, 2660, 1182, 525, 233, 103, 46, 20, 9, 4, 1);
var
gap,
i,
j: SizeInt;
tmp: T;
begin
for gap in TOKUDA_SEQUENCE do
for i := gap to High(a) do
begin
tmp := a[i];
j := i;
while (j >= gap) and (a[j - gap] > tmp) do
begin
a[j] := a[j - gap];
Dec(j, gap);
end;
a[j] := tmp;
end;
end;
function ReadCStr(stream: TStream): String;
var
b: Byte;
begin
result := '';
while TRUE do
begin
b := stream.ReadByte;
if b = 0 then
break;
result := result + Char(b);
end;
end;
function TagToString(tag: LongWord): String;
begin
SetLength(result, SizeOf(tag));
{$IFDEF ENDIAN_LITTLE}
tag := SwapEndian(tag);
{$ENDIF}
Move(tag, result[1], SizeOf(tag));
result := TrimRight(result);
end;
procedure SwapUnicodeEndian(var s: UnicodeString);
var
i: SizeInt;
begin
for i := 1 to Length(s) do
s[i] := WideChar(SwapEndian(Word(s[i])));
end;
const
MAX_ASCII = 127;
// https://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/ROMAN.TXT
MAC_OS_ROMAN_TO_UTF8: array [0..255 - (MAX_ASCII + 1)] of String = (
#195#132,
#195#133,
#195#135,
#195#137,
#195#145,
#195#150,
#195#156,
#195#161,
#195#160,
#195#162,
#195#164,
#195#163,
#195#165,
#195#167,
#195#169,
#195#168,
#195#170,
#195#171,
#195#173,
#195#172,
#195#174,
#195#175,
#195#177,
#195#179,
#195#178,
#195#180,
#195#182,
#195#181,
#195#186,
#195#185,
#195#187,
#195#188,
#226#128#160,
#194#176,
#194#162,
#194#163,
#194#167,
#226#128#162,
#194#182,
#195#159,
#194#174,
#194#169,
#226#132#162,
#194#180,
#194#168,
#226#137#160,
#195#134,
#195#152,
#226#136#158,
#194#177,
#226#137#164,
#226#137#165,
#194#165,
#194#181,
#226#136#130,
#226#136#145,
#226#136#143,
#207#128,
#226#136#171,
#194#170,
#194#186,
#206#169,
#195#166,
#195#184,
#194#191,
#194#161,
#194#172,
#226#136#154,
#198#146,
#226#137#136,
#226#136#134,
#194#171,
#194#187,
#226#128#166,
#194#160,
#195#128,
#195#131,
#195#149,
#197#146,
#197#147,
#226#128#147,
#226#128#148,
#226#128#156,
#226#128#157,
#226#128#152,
#226#128#153,
#195#183,
#226#151#138,
#195#191,
#197#184,
#226#129#132,
#226#130#172,
#226#128#185,
#226#128#186,
#239#172#129,
#239#172#130,
#226#128#161,
#194#183,
#226#128#154,
#226#128#158,
#226#128#176,
#195#130,
#195#138,
#195#129,
#195#139,
#195#136,
#195#141,
#195#142,
#195#143,
#195#140,
#195#147,
#195#148,
#239#163#191,
#195#146,
#195#154,
#195#155,
#195#153,
#196#177,
#203#134,
#203#156,
#194#175,
#203#152,
#203#153,
#203#154,
#194#184,
#203#157,
#203#155,
#203#135
);
function MacOSRomanToUTF8(const s: String): String;
var
c: Char;
b: Byte;
begin
result := '';
for c in s do
begin
b := Byte(c);
if b <= MAX_ASCII then
result := result + c
else
result := result + MAC_OS_ROMAN_TO_UTF8[b - (MAX_ASCII + 1)];
end;
end;
end.
|
namespace com.example.android.snake;
// Extra functionality added by Brian Long (htt://blong.com)
// Supports screen swipe gestures to enhance the original game
// that required a D-Pad
interface
uses
android.util,
android.view;
type
SnakeGestureListener = public class(GestureDetector.SimpleOnGestureListener)
// swipe gesture constants
const SWIPE_MIN_DISTANCE = 120;
const SWIPE_THRESHOLD_VELOCITY = 200;
var mView: View;
public
constructor(v: View);
method onDown(&event: MotionEvent): Boolean; override;
method onFling(e1: MotionEvent; e2: MotionEvent; velocityX: Single; velocityY: Single): Boolean; override;
end;
implementation
constructor SnakeGestureListener(v: View);
begin
inherited constructor;
mView := v
end;
method SnakeGestureListener.onFling(e1: MotionEvent; e2: MotionEvent; velocityX: Single; velocityY: Single): Boolean;
begin
try
if (e1.X - e2.X > SWIPE_MIN_DISTANCE) and (Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) then
mView.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT,
new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT))
else
if (e2.X - e1.X > SWIPE_MIN_DISTANCE) and (Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) then
mView.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT,
new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT))
else
if (e1.Y - e2.Y > SWIPE_MIN_DISTANCE) and (Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) then
mView.onKeyDown(KeyEvent.KEYCODE_DPAD_UP,
new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP))
else
if (e2.Y - e1.Y > SWIPE_MIN_DISTANCE) and (Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) then
mView.onKeyDown(KeyEvent.KEYCODE_DPAD_DOWN,
new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN))
except
on e: Exception do
e.printStackTrace
end;
exit true
end;
method SnakeGestureListener.onDown(&event: MotionEvent): Boolean;
begin
exit true;
end;
end. |
unit uStopWatch;
{
TStopWatch Implementation By Zarko Gajic
http://delphi.about.com/od/windowsshellapi/a/delphi-high-performance-timer-tstopwatch.htm
}
interface
uses
Winapi.Windows, System.SysUtils, System.DateUtils;
type
TStopWatch = class
private
fFrequency: TLargeInteger;
fIsRunning: boolean;
fIsHighResolution: boolean;
fStartCount, fStopCount: TLargeInteger;
procedure SetTickStamp(var lInt: TLargeInteger);
function GetElapsedTicks: TLargeInteger;
function GetElapsedMilliseconds: TLargeInteger;
function GetElapsed: string;
public
constructor Create(const startOnCreate: boolean = false);
procedure Start;
procedure Stop;
property IsHighResolution: boolean read fIsHighResolution;
property ElapsedTicks: TLargeInteger read GetElapsedTicks;
property ElapsedMilliseconds: TLargeInteger read GetElapsedMilliseconds;
property Elapsed: string read GetElapsed;
property IsRunning: boolean read fIsRunning;
end;
implementation
constructor TStopWatch.Create(const startOnCreate: boolean = false);
begin
inherited Create;
fIsRunning := false;
fIsHighResolution := QueryPerformanceFrequency(fFrequency);
if NOT fIsHighResolution then
fFrequency := MSecsPerSec;
if startOnCreate then
Start;
end;
function TStopWatch.GetElapsedTicks: TLargeInteger;
begin
result := fStopCount - fStartCount;
end;
procedure TStopWatch.SetTickStamp(var lInt: TLargeInteger);
begin
if fIsHighResolution then
QueryPerformanceCounter(lInt)
else
lInt := MilliSecondOf(Now);
end;
function TStopWatch.GetElapsed: string;
var
dt: TDateTime;
begin
dt := ElapsedMilliseconds / MSecsPerSec / SecsPerDay;
result := Format('%d days, %s', [trunc(dt), FormatDateTime('hh:nn:ss.z',
Frac(dt))]);
end;
function TStopWatch.GetElapsedMilliseconds: TLargeInteger;
begin
result := (MSecsPerSec * (fStopCount - fStartCount)) div fFrequency;
end;
procedure TStopWatch.Start;
begin
SetTickStamp(fStartCount);
fIsRunning := true;
end;
procedure TStopWatch.Stop;
begin
SetTickStamp(fStopCount);
fIsRunning := false;
end;
end.
|
unit FileSystemHelper;
interface
// Writes a given text to a given file
function WriteToFile(filePath, text : String) : Boolean;
// Combines all given parts in a path
function CombinePath(pathParts : array of string) : String;
// Creates directory if it doesn't exist
function CreateDirectory(directoryPath : String) : Boolean;
implementation
uses SysUtils;
function WriteToFile(filePath, text : String) : Boolean;
var
f : TextFile;
begin
AssignFile(f, filePath);
Result := False;
try
if FileExists(filePath) then
Append(f)
else
Rewrite(f);
except on e : Exception do
begin
// TODO: Write log?
Exit;
end;
end;
try
Write(f, text);
except on e : Exception do
begin
// TODO Write log?
Close(f);
Exit;
end;
end;
Close(f);
Result := True;
end;
function CombinePath(pathParts : array of string) : String;
var
i : Integer;
begin
Result := '';
for i := 0 to Length(pathParts) - 1 do
begin
if pathParts[i] <> '' then
Result := IncludeTrailingPathDelimiter(Result + pathParts[i]);
end;
if Result <> '' then
Result := ExcludeTrailingPathDelimiter(Result);
end;
function CreateDirectory(directoryPath : String) : Boolean;
begin
Result := False;
try
if not DirectoryExists(directoryPath) and not CreateDir(directoryPath) then
begin
// TODO: Write log
Exit;
end;
Result := True;
except on e : Exception do
begin
// TODO: Write log
end;
end;
end;
end.
|
unit Model.Usuario;
interface
uses System.Classes, Model.Mapper, Model.Access, Model.TableNames,
System.Generics.Collections;
type
TUsuario = class(TBaseModel)
private
FIdUsuario: Integer;
FIdPerfil: Integer;
FCodigo: Integer;
FNomeUsuario: string;
FLogin: string;
FSenha: string;
FDataExclusao: TDateTime;
public
property IdUsuario: Integer read FIdUsuario write FIdUsuario;
property IdPerfil: Integer read FIdPerfil write FIdPerfil;
property Codigo: Integer read FCodigo write FCodigo;
property NomeUsuario: string read FNomeUsuario write FNomeUsuario;
property Login: string read FLogin write FLogin;
property Senha: string read FSenha write FSenha;
property DataExclusao: TDateTime read FDataExclusao write FDataExclusao;
procedure Read(Reader: IReader); override;
procedure Write(Writer: IWriter); override;
end;
TPerfil = class(TBaseModel)
private
FIdPerfil: Integer;
FDescricao: string;
public
property IdPerfil: Integer read FIdPerfil write FIdPerfil;
property Descricao: string read FDescricao write FDescricao;
procedure Read(Reader: IReader); override;
procedure Write(Writer: IWriter); override;
end;
TRotina = class(TBaseModel)
private
FIdRotina: Integer;
FCodigo: string;
public
property IdRotina: Integer read FIdRotina write FIdRotina;
property Codigo: string read FCodigo write FCodigo;
procedure Read(Reader: IReader); override;
procedure Write(Writer: IWriter); override;
end;
TPerfilRotina = class(TBaseModel)
private
FIdPerfil: Integer;
FIdRotina: Integer;
public
property IdPerfil: Integer read FIdPerfil write FIdPerfil;
property IdRotina: Integer read FIdRotina write FIdRotina;
procedure Read(Reader: IReader); override;
procedure Write(Writer: IWriter); override;
end;
implementation
uses
System.Variants, ZDataSet;
{ TUsuario }
procedure TUsuario.Read(Reader: IReader);
begin
FIdUsuario := Reader.ReadInteger(USUARIO_ID, 0);
FIdPerfil := Reader.ReadInteger(USUARIO_IDPERFIL, 0);
FCodigo := Reader.ReadInteger(USUARIO_CODIGO, 0);
FNomeUsuario := Reader.ReadString(USUARIO_NOME, '');
FLogin := Reader.ReadString(USUARIO_LOGIN, '');
FSenha := Reader.ReadString(USUARIO_SENHA, '');
FDataExclusao := Reader.ReadDateTime(USUARIO_DATAEXCLUSAO, 0);
end;
procedure TUsuario.Write(Writer: IWriter);
begin
if FIdUsuario = 0 then
Writer.WriteInteger(USUARIO_ID, VarNull)
else
Writer.WriteInteger(USUARIO_ID, FIdUsuario);
if FIdPerfil = 0 then
Writer.WriteInteger(USUARIO_IDPERFIL, VarNull)
else
Writer.WriteInteger(USUARIO_IDPERFIL, FIdPerfil);
if FDataExclusao = 0 then
Writer.WriteDateTime(USUARIO_DATAEXCLUSAO, VarNull)
else
Writer.WriteDateTime(USUARIO_DATAEXCLUSAO, FDataExclusao);
Writer.WriteInteger(USUARIO_CODIGO, FCodigo);
Writer.WriteString(USUARIO_NOME, FNomeUsuario);
Writer.WriteString(USUARIO_LOGIN, FLogin);
Writer.WriteString(USUARIO_SENHA, FSenha);
end;
{ TPerfil }
procedure TPerfil.Read(Reader: IReader);
begin
FIdPerfil := Reader.ReadInteger(PERFIL_ID, 0);
FDescricao := Reader.ReadString(PERFIL_DESCRICAO, '');
end;
procedure TPerfil.Write(Writer: IWriter);
begin
if FIdPerfil = 0 then
Writer.WriteInteger(PERFIL_ID, VarNull)
else
Writer.WriteInteger(PERFIL_ID, FIdPerfil);
Writer.WriteString(PERFIL_DESCRICAO, FDescricao);
end;
{ TRotina }
procedure TRotina.Read(Reader: IReader);
begin
FIdRotina := Reader.ReadInteger(ROTINA_ID, 0);
FCodigo := Reader.ReadString(ROTINA_CODIGO, '');
end;
procedure TRotina.Write(Writer: IWriter);
begin
if FIdRotina = 0 then
Writer.WriteInteger(ROTINA_ID, VarNull)
else
Writer.WriteInteger(ROTINA_ID, FIdRotina);
Writer.WriteString(ROTINA_CODIGO, FCodigo);
end;
{ TPerfilRotina }
procedure TPerfilRotina.Read(Reader: IReader);
begin
FIdPerfil := Reader.ReadInteger(PERFILROTINAS_IDPERFIL, 0);
FIdRotina := Reader.ReadInteger(PERFILROTINAS_IDROTINA, 0);
end;
procedure TPerfilRotina.Write(Writer: IWriter);
begin
Writer.WriteInteger(PERFILROTINAS_IDPERFIL, FIdPerfil);
Writer.WriteInteger(PERFILROTINAS_IDROTINA, FIdRotina);
end;
end.
|
unit uTemplateReceipt15; {текстовый пункт}
interface
uses SysUtils,
Classes,
Dialogs,
ibase,
DB,
FIBDatabase,
pFIBDatabase,
FIBDataSet,
pFIBDataSet,
Forms;
function GetTemplateString(hConnection: TISC_DB_HANDLE; id_session, id_item : Int64): String; stdcall;
exports GetTemplateString;
implementation
function GetTemplateString(hConnection: TISC_DB_HANDLE; id_session, id_item : Int64): String; stdcall;
var szResult, s : String; // Строка для формирования результирующей строки
fdbTemplateReceipt : TpFIBDatabase; // База
ftrTemplateReceipt : TpFIBTransaction; // Транзакция
fdsTemplateReceipt : TpFIBDataSet; // Датасэт
// l : integer;
begin
try
fdbTemplateReceipt := TpFIBDatabase.Create(NIL);
ftrTemplateReceipt := TpFIBTransaction.Create(NIL);
fdsTemplateReceipt := TpFIBDataSet.Create(nil);
fdbTemplateReceipt.SQLDialect := 3;
fdbTemplateReceipt.Handle := hConnection;
fdsTemplateReceipt := TpFIBDataSet.Create(nil);
ftrTemplateReceipt.DefaultDatabase := fdbTemplateReceipt;
fdbTemplateReceipt.DefaultTransaction := ftrTemplateReceipt;
fdsTemplateReceipt.Database := fdbTemplateReceipt;
fdsTemplateReceipt.Transaction := ftrTemplateReceipt;
ftrTemplateReceipt.StartTransaction;
szResult := '';
s := '';
fdsTemplateReceipt.SQLs.SelectSQL.Text := 'SELECT parametr_name, parametr_value ' +
'FROM up_dt_order_item_body ' +
'WHERE id_session = ' + IntToStr(id_session);
fdsTemplateReceipt.Open;
// Номер пункта
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'TEXT_NUM_ITEM_1', []) then
s := s + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '.';
// Номер подпункта
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'TEXT_NUM_SUB_ITEM_1', []) then
if fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsInteger <> 0 then
s := s + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '.';
fdsTemplateReceipt.Close;
fdsTemplateReceipt.SQLs.SelectSQL.Text := 'select body from UP_DT_TEXT_DATA_INST where ID_ORDER_ITEM= ' + IntToStr(id_item);
fdsTemplateReceipt.Open;
if not fdsTemplateReceipt.FBN('BODY').IsNull then
begin
// szResult := s + ' ' + trim(fdsTemplateReceipt.FBN('BODY').AsString);
if Pos(s, fdsTemplateReceipt.FBN('BODY').AsString)=1
then
begin
szResult := trim(fdsTemplateReceipt.FBN('BODY').AsString);
end
else
begin
szResult := s + ' ' + trim(fdsTemplateReceipt.FBN('BODY').AsString);
end;
end;
{ if Pos(s, fdsTemplateReceipt.FBN('BODY').AsString)=1
then
begin
szResult := trim(fdsTemplateReceipt.FBN('BODY').AsString);
end
else
begin
szResult := s + ' ' + trim(fdsTemplateReceipt.FBN('BODY').AsString);
end;
end;}
ftrTemplateReceipt.Rollback;
// Удаление динамически созданных компонент
fdsTemplateReceipt.Free;
ftrTemplateReceipt.Free;
fdbTemplateReceipt.Free;
except on Error: Exception do begin
MessageDlg('Неможливо зформувати шаблон: '+#10#13+Error.Message, mtError, [mbOk], 0);
// szResult := '';
end;
end;
Result := szResult;
end;
end.
|
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
Messanger
Small library for thread-safe intraprocess communication.
©František Milt 2018-10-22
Version 1.2.3
Notes:
- do not create instance of class TMessangerEndpoint directly by calling
its constructor, instead use method(s) TMessanger.CreateEndpoint
- manage creation of all endpoints in one thread (a thread that is managing
TMessanger instance) and then pass them to threads that needs them, do
not create endpoints from other threads
- on the other hand, free endpoints from threads that are using them, never
free them from thread that is managing TMessanger instance
- before freeing TMessanger instance, make sure all endpoints are freed from
their respective threads, otherwise an exception will be raised when
TMessanger instance is freed
- use synchronous messages only when really necessary, bulk of the
communication should be asynchronous
- do not send synchronous messages from event handlers - it is possible as
long as synchronous dispatch is not active (in that case, send function
will fail), but discouraged
Dependencies:
AuxTypes - github.com/ncs-sniper/Lib.AuxTypes
AuxClasses - github.com/ncs-sniper/Lib.AuxClasses
MemVector - github.com/ncs-sniper/Lib.MemVector
WinSyncObjs - github.com/ncs-sniper/Lib.WinSyncObjs
StrRect - github.com/ncs-sniper/Lib.StrRect
===============================================================================}
unit Messanger;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Windows, SysUtils, Classes,
AuxTypes, AuxClasses, MemVector, WinSyncObjs;
type
TMsgrEndpointID = UInt16; PMsgrEndpointID = ^TMsgrEndpointID;
TMsgrPriority = Int32; PMsgrPriority = ^TMsgrPriority;
TMsgrTimeStamp = Int64; PMsgrTimeStamp = ^TMsgrTimeStamp;
TMsgrParam = PtrInt; PMsgrParam = ^TMsgrParam;
TMsgrOpaque = Pointer; PMsgrOpaque = ^TMsgrOpaque;
TMsgrMessage = packed record
Sender: TMsgrEndpointID;
Target: TMsgrEndpointID;
Priority: TMsgrPriority;
TimeStamp: TMsgrTimeStamp;
Parameter1: TMsgrParam;
Parameter2: TMsgrParam;
Parameter3: TMsgrParam;
Parameter4: TMsgrParam;
Reserved: TMsgrOpaque;
end;
PMsgrMessage = ^TMsgrMessage;
const
MSGR_ID_BROADCAST = TMsgrEndpointID(High(TMsgrEndpointID));
MSGR_PRIORITY_MINIMAL = TMsgrPriority(-100000);
MSGR_PRIORITY_EXTREME_LOW = TMsgrPriority(-10000);
MSGR_PRIORITY_VERY_LOW = TMsgrPriority(-1000);
MSGR_PRIORITY_LOW = TMsgrPriority(-100);
MSGR_PRIORITY_BELOW_NORMAL = TMsgrPriority(-10);
MSGR_PRIORITY_NORMAL = TMsgrPriority(0);
MSGR_PRIORITY_ABOVE_NORMAL = TMsgrPriority(10);
MSGR_PRIORITY_HIGH = TMsgrPriority(100);
MSGR_PRIORITY_VERY_HIGH = TMsgrPriority(1000);
MSGR_PRIORITY_EXTREME_HIGH = TMsgrPriority(10000);
MSGR_PRIORITY_ABSOLUTE = TMsgrPriority(100000);
MSGR_PRIORITY_MIN = MSGR_PRIORITY_MINIMAL;
MSGR_PRIORITY_MAX = MSGR_PRIORITY_ABSOLUTE;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMsgrMessageVector }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TMsgrMessageVector - declaration }
{==============================================================================}
type
TMsgrMessageVector = class(TMemVector)
protected
Function GetItem(Index: Integer): TMsgrMessage; virtual;
procedure SetItem(Index: Integer; Value: TMsgrMessage); virtual;
Function ItemCompare(Item1,Item2: Pointer): Integer; override;
public
constructor Create; overload;
constructor Create(Memory: Pointer; Count: Integer); overload;
Function First: TMsgrMessage; reintroduce;
Function Last: TMsgrMessage; reintroduce;
Function IndexOf(Item: TMsgrMessage): Integer; reintroduce;
Function Add(Item: TMsgrMessage): Integer; reintroduce;
procedure Insert(Index: Integer; Item: TMsgrMessage); reintroduce;
Function Remove(Item: TMsgrMessage): Integer; reintroduce;
Function Extract(Item: TMsgrMessage): TMsgrMessage; reintroduce;
property Items[Index: Integer]: TMsgrMessage read GetItem write SetItem; default;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMsgrBufferedMessagesVector }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TMsgrBufferedMessagesVector - declaration }
{==============================================================================}
TMsgrBufferedMessageVector = class(TMsgrMessageVector)
protected
Function ItemCompare(Item1,Item2: Pointer): Integer; override;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMessangerEndpoint }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TMessangerEndpoint - declaration }
{==============================================================================}
TMsgrDispatchFlag = (mdfRemoveMessage,mdfStopTraversing,mdfAutoCycle,
mdfUndeliveredMessage,mdfBufferedMessage,
mdfSynchronousMessage,mdfSynchronousDispatch);
TMsgrDispatchFlags = set of TMsgrDispatchFlag;
TMsgrWaitResult = (mwrNewMessage,mwrTimeOut,mwrError);
TMsgrSyncMsgsWaiters = packed record
Outgoing: THandle;
Incoming: THandle;
end;
TMsgrMessageEvent = procedure(Sender: TObject; Msg: TMsgrMessage; var Flags: TMsgrDispatchFlags) of object;
TMessanger = class; // forward declaration
TMessangerEndpoint = class(TCustomObject)
private
fEndpointID: TMsgrEndpointID;
fMessanger: TMessanger;
fAutoBuffSend: Boolean;
fAutoCycle: Boolean;
fSynchronousDispatch: Boolean;
// synchronizers
fIncomingSynchronizer: TCriticalSection; // protects vector of incoming messages
fIncomingMsgsWaiter: TEvent; // used for waiting for new incoming messages
fIncomingSyncMsgsWaiter: TEvent; // indicates incoming synchronous message
fOutgoingSyncMsgsWaiter: TEvent; // used for waiting on sent synchronous messages
fSyncMsgsWaiters: TMsgrSyncMsgsWaiters; // for use in WaitForMultipleObjects
// vectors
fIncomingMessages: TMsgrMessageVector;
fReceivedMessages: TMsgrMessageVector;
fBufferedMessages: TMsgrBufferedMessageVector;
fUndeliveredMessages: TMsgrMessageVector; // used to store undelivered buffered messages
// events
fOnMessageTraversing: TMsgrMessageEvent;
fOnUndeliveredMessage: TMsgrMessageEvent;
fOnDestroying: TNotifyEvent;
Function GetMessageCount: Integer;
Function GetMessage(Index: Integer): TMsgrMessage;
protected
procedure AddMessages(Messages: PMsgrMessage; Count: Integer); virtual; // called from other thread (sender)
procedure SynchronousDispatch; virtual;
procedure UndeliveredDispatch(Msg: TMsgrMessage; BufferedMessage: Boolean = False); virtual;
public
constructor Create(EndpointID: TMsgrEndpointID; Messanger: TMessanger);
destructor Destroy; override;
Function SendMessage(TargetID: TMsgrEndpointID; P1,P2,P3,P4: TMsgrParam; Priority: TMsgrPriority = MSGR_PRIORITY_NORMAL): Boolean; overload; virtual;
Function SendMessage(Msg: TMsgrMessage): Boolean; overload; virtual;
Function SendMessageAndWait(TargetID: TMsgrEndpointID; P1,P2,P3,P4: TMsgrParam; Priority: TMsgrPriority = MSGR_PRIORITY_NORMAL): Boolean; overload; virtual;
Function SendMessageAndWait(Msg: TMsgrMessage): Boolean; overload; virtual;
procedure BufferMessage(TargetID: TMsgrEndpointID; P1,P2,P3,P4: TMsgrParam; Priority: TMsgrPriority = MSGR_PRIORITY_NORMAL); overload; virtual;
procedure BufferMessage(Msg: TMsgrMessage); overload; virtual;
procedure SendBufferedMessages; virtual;
Function WaitForNewMessage(TimeOut: DWORD): TMsgrWaitResult; virtual;
procedure FetchMessages; virtual;
Function TraverseMessages: Boolean; virtual;
procedure Cycle(MessageWaitTimeOut: DWORD); virtual;
procedure AutoCycle(MessageWaitTimeOut: DWORD); virtual;
procedure ClearMessages; virtual;
property Messages[Index: Integer]: TMsgrMessage read GetMessage;
property EndpointID: TMsgrEndpointID read fEndpointID;
property AutoBuffSend: Boolean read fAutoBuffSend write fAutoBuffSend;
property MessageCount: Integer read GetMessageCount;
property OnMessageTraversing: TMsgrMessageEvent read fOnMessageTraversing write fOnMessageTraversing;
property OnUndeliveredMessage: TMsgrMessageEvent read fOnUndeliveredMessage write fOnUndeliveredMessage;
property OnDestroying: TNotifyEvent read fOnDestroying write fOnDestroying;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMessanger }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TMessanger - declaration }
{==============================================================================}
TMsgrEndpoints = array of TMessangerEndpoint;
TMessanger = class(TCustomObject)
private
fEndpoints: TMsgrEndpoints;
fSynchronizer: TMultiReadExclusiveWriteSynchronizer;
Function GetEndpointCapacity: Integer;
Function GetEndpointCount: Integer;
Function GetEndpoint(Index: Integer): TMessangerEndpoint;
protected
procedure RemoveEndpoint(EndpointID: TMsgrEndpointID); virtual;
Function SendMessage(Msg: TMsgrMessage): Boolean; virtual;
procedure SendBufferedMessages(Messages,Undelivered: TMsgrMessageVector); virtual;
public
constructor Create(EndpointCapacity: TMsgrEndpointID = 1024);
destructor Destroy; override;
Function IDAvailable(EndpointID: TMsgrEndpointID): Boolean; virtual;
Function CreateEndpoint: TMessangerEndpoint; overload; virtual;
Function CreateEndpoint(EndpointID: TMsgrEndpointID): TMessangerEndpoint; overload; virtual;
property Endpoints[Index: Integer]: TMessangerEndpoint read GetEndpoint;
property EndpointCapacity: Integer read GetEndpointCapacity;
property EndpointCount: Integer read GetEndpointCount;
end;
{==============================================================================}
{ Auxiliary functions - declaration }
{==============================================================================}
Function GetTimeStamp: TMsgrTimeStamp;
Function BuildMessage(Sender, Target: TMsgrEndpointID; Priority: TMsgrPriority; TimeStamp: TMsgrTimeStamp; P1,P2,P3,P4: TMsgrParam): TMsgrMessage;
implementation
{==============================================================================}
{ Auxiliary functions - implementation }
{==============================================================================}
Function GetTimeStamp: TMsgrTimeStamp;
begin
Result := 0;
If not QueryPerformanceCounter(Result) then
raise Exception.CreateFmt('GetTimeStamp: Cannot obtain time stamp (0x%.8x).',[GetLastError]);
end;
//------------------------------------------------------------------------------
Function BuildMessage(Sender, Target: TMsgrEndpointID; Priority: TMsgrPriority; TimeStamp: TMsgrTimeStamp; P1,P2,P3,P4: TMsgrParam): TMsgrMessage;
begin
Result.Sender := Sender;
Result.Target := Target;
Result.Priority := Priority;
Result.TimeStamp := TimeStamp;
Result.Parameter1 := P1;
Result.Parameter2 := P2;
Result.Parameter3 := P3;
Result.Parameter4 := P4;
Result.Reserved := nil;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMsgrMessageVector }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TMsgrMessageVector - implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMsgrMessageVector - protected methods }
{------------------------------------------------------------------------------}
Function TMsgrMessageVector.GetItem(Index: Integer): TMsgrMessage;
begin
Result := TMsgrMessage(GetItemPtr(Index)^);
end;
//------------------------------------------------------------------------------
procedure TMsgrMessageVector.SetItem(Index: Integer; Value: TMsgrMessage);
begin
SetItemPtr(Index,@Value);
end;
//------------------------------------------------------------------------------
Function TMsgrMessageVector.ItemCompare(Item1,Item2: Pointer): Integer;
var
AssignMask: Byte;
begin
If Assigned(TMsgrMessage(Item1^).Reserved) then
AssignMask := 1
else
AssignMask := 0;
If Assigned(TMsgrMessage(Item2^).Reserved) then
AssignMask := AssignMask or 2;
case AssignMask of
1: Result := -1; // first is assigned, second is not => change order
2: Result := +1; // first in not assigned, second is => keep order
else
{0,3} // both are assigned or not assigned, decide upon other parameters
Result := TMsgrMessage(Item2^).Priority - TMsgrMessage(Item1^).Priority;
If TMsgrMessage(Item2^).TimeStamp < TMsgrMessage(Item1^).TimeStamp then
Inc(Result)
else If TMsgrMessage(Item2^).TimeStamp > TMsgrMessage(Item1^).TimeStamp then
Dec(Result);
end;
end;
{------------------------------------------------------------------------------}
{ TMsgrMessageVector - public methods }
{------------------------------------------------------------------------------}
constructor TMsgrMessageVector.Create;
begin
inherited Create(SizeOf(TMsgrMessage));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TMsgrMessageVector.Create(Memory: Pointer; Count: Integer);
begin
inherited Create(Memory,Count,SizeOf(TMsgrMessage));
end;
//------------------------------------------------------------------------------
Function TMsgrMessageVector.First: TMsgrMessage;
begin
Result := TMsgrMessage(inherited First^);
end;
//------------------------------------------------------------------------------
Function TMsgrMessageVector.Last: TMsgrMessage;
begin
Result := TMsgrMessage(inherited Last^);
end;
//------------------------------------------------------------------------------
Function TMsgrMessageVector.IndexOf(Item: TMsgrMessage): Integer;
begin
Result := inherited IndexOf(@Item);
end;
//------------------------------------------------------------------------------
Function TMsgrMessageVector.Add(Item: TMsgrMessage): Integer;
begin
Result := inherited Add(@Item);
end;
//------------------------------------------------------------------------------
procedure TMsgrMessageVector.Insert(Index: Integer; Item: TMsgrMessage);
begin
inherited Insert(Index,@Item);
end;
//------------------------------------------------------------------------------
Function TMsgrMessageVector.Remove(Item: TMsgrMessage): Integer;
begin
Result := inherited Remove(@Item);
end;
//------------------------------------------------------------------------------
Function TMsgrMessageVector.Extract(Item: TMsgrMessage): TMsgrMessage;
begin
Result := TMsgrMessage(inherited Extract(@Item)^);
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMsgrBufferedMessagesVector }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TMsgrBufferedMessagesVector - implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMsgrBufferedMessagesVector - protected methods }
{------------------------------------------------------------------------------}
Function TMsgrBufferedMessageVector.ItemCompare(Item1,Item2: Pointer): Integer;
begin
Result := TMsgrMessage(Item2^).Target - TMsgrMessage(Item1^).Target;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMessangerEndpoint }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TMessangerEndpoint - implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMessangerEndpoint - pivate methods }
{------------------------------------------------------------------------------}
Function TMessangerEndpoint.GetMessageCount: Integer;
begin
Result := fReceivedMessages.Count;
end;
//------------------------------------------------------------------------------
Function TMessangerEndpoint.GetMessage(Index: Integer): TMsgrMessage;
begin
If (Index >= fReceivedMessages.LowIndex) and (Index <= fReceivedMessages.HighIndex) then
Result := fReceivedMessages[Index]
else
raise Exception.CreateFmt('TMessangerEndpoint.GetMessage: Index (%d) out of bounds.',[Index]);
end;
{------------------------------------------------------------------------------}
{ TMessangerEndpoint - protected methods }
{------------------------------------------------------------------------------}
procedure TMessangerEndpoint.AddMessages(Messages: PMsgrMessage; Count: Integer);
begin
fIncomingSynchronizer.Enter;
try
fIncomingMessages.Append(Messages,Count);
fIncomingMsgsWaiter.SetEvent;
If (Count = 1) and Assigned(Messages^.Reserved) then
fIncomingSyncMsgsWaiter.SetEvent;
finally
fIncomingSynchronizer.Leave;
end;
end;
//------------------------------------------------------------------------------
procedure TMessangerEndpoint.SynchronousDispatch;
var
i: Integer;
Flags: TMsgrDispatchFlags;
begin
fSynchronousDispatch := True;
try
FetchMessages;
For i := fReceivedMessages.HighIndex downto fReceivedMessages.LowIndex do
If Assigned(fReceivedMessages[i].Reserved) then
begin
// prepare flags
Flags := [mdfSynchronousMessage,mdfSynchronousDispatch];
If fAutoCycle then Include(Flags,mdfAutoCycle);
// call event
If Assigned(fOnMessageTraversing) then
fOnMessageTraversing(Self,fReceivedMessages[i],Flags); // <<<
// process output flags
fAutoCycle := fAutoCycle and (mdfAutoCycle in Flags);
TEvent(fReceivedMessages[i].Reserved).SetEvent;
fReceivedMessages.Delete(i);
end;
finally
fSynchronousDispatch := False;
end;
end;
//------------------------------------------------------------------------------
procedure TMessangerEndpoint.UndeliveredDispatch(Msg: TMsgrMessage; BufferedMessage: Boolean = False);
var
Flags: TMsgrDispatchFlags;
begin
If Assigned(fOnUndeliveredMessage) then
begin
// prepare flags
Flags := [mdfUndeliveredMessage];
If Assigned(Msg.Reserved) then Include(Flags,mdfSynchronousMessage);
If BufferedMessage then Include(Flags,mdfBufferedMessage);
If fAutoCycle then Include(Flags,mdfAutoCycle);
// call event
fOnUndeliveredMessage(Self,Msg,Flags);
// process output flags
fAutoCycle := fAutoCycle and (mdfAutoCycle in Flags);
end;
end;
{------------------------------------------------------------------------------}
{ TMessangerEndpoint - public methods }
{------------------------------------------------------------------------------}
constructor TMessangerEndpoint.Create(EndpointID: TMsgrEndpointID; Messanger: TMessanger);
begin
inherited Create;
fEndpointID := EndpointID;
fMessanger := Messanger;
fAutoBuffSend := False;
fAutoCycle := False;
fSynchronousDispatch := False;
// synchronizers
fIncomingSynchronizer := TCriticalSection.Create;
fIncomingMsgsWaiter := TEvent.Create(nil,False,False,'');
fIncomingSyncMsgsWaiter := TEvent.Create(nil,False,False,'');
fOutgoingSyncMsgsWaiter := TEvent.Create(nil,True,False,'');
fSyncMsgsWaiters.Outgoing := fOutgoingSyncMsgsWaiter.Handle;
fSyncMsgsWaiters.Incoming := fIncomingSyncMsgsWaiter.Handle;
// vectors
fIncomingMessages := TMsgrMessageVector.Create;
fReceivedMessages := TMsgrMessageVector.Create;
fBufferedMessages := TMsgrBufferedMessageVector.Create;
fUndeliveredMessages := TMsgrMessageVector.Create;
end;
//------------------------------------------------------------------------------
destructor TMessangerEndpoint.Destroy;
begin
fMessanger.RemoveEndpoint(fEndpointID);
If Assigned(fOnDestroying) then
fOnDestroying(Self);
FetchMessages;
ClearMessages;
// vectors
fUndeliveredMessages.Free;
fBufferedMessages.Free;
fReceivedMessages.Free;
fIncomingMessages.Free;
// synchronizers
fOutgoingSyncMsgsWaiter.Free;
fIncomingSyncMsgsWaiter.Free;
fIncomingMsgsWaiter.Free;
fIncomingSynchronizer.Free;
inherited;
end;
//------------------------------------------------------------------------------
Function TMessangerEndpoint.SendMessage(TargetID: TMsgrEndpointID; P1,P2,P3,P4: TMsgrParam; Priority: TMsgrPriority = MSGR_PRIORITY_NORMAL): Boolean;
begin
Result := SendMessage(BuildMessage(fEndpointID,TargetID,Priority,GetTimeStamp,P1,P2,P3,P4));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
Function TMessangerEndpoint.SendMessage(Msg: TMsgrMessage): Boolean;
begin
If fAutoBuffSend then
SendBufferedMessages;
Msg.Reserved := nil;
Result := fMessanger.SendMessage(Msg);
If not Result then
UndeliveredDispatch(Msg);
end;
//------------------------------------------------------------------------------
Function TMessangerEndpoint.SendMessageAndWait(TargetID: TMsgrEndpointID; P1,P2,P3,P4: TMsgrParam; Priority: TMsgrPriority = MSGR_PRIORITY_NORMAL): Boolean;
begin
Result := SendMessageAndWait(BuildMessage(fEndpointID,TargetID,Priority,GetTimeStamp,P1,P2,P3,P4));
end;
//------------------------------------------------------------------------------
Function TMessangerEndpoint.SendMessageAndWait(Msg: TMsgrMessage): Boolean;
var
ContinueWaiting: Boolean;
begin
Result := False;
If fAutoBuffSend then
SendBufferedMessages;
If not fSynchronousDispatch and (Msg.Target <> MSGR_ID_BROADCAST) then
begin
Msg.Reserved := Pointer(fOutgoingSyncMsgsWaiter);
fOutgoingSyncMsgsWaiter.ResetEvent;
ContinueWaiting := True;
If fMessanger.SendMessage(Msg) then
while ContinueWaiting do
case WaitForMultipleObjects(2,Addr(fSyncMsgsWaiters),False,INFINITE) of
WAIT_OBJECT_0: begin
Result := True;
ContinueWaiting := False;
end;
WAIT_OBJECT_0 + 1: SynchronousDispatch;
else
ContinueWaiting := False;
end
end;
If not Result then
UndeliveredDispatch(Msg);
end;
//------------------------------------------------------------------------------
procedure TMessangerEndpoint.BufferMessage(TargetID: TMsgrEndpointID; P1,P2,P3,P4: TMsgrParam; Priority: TMsgrPriority = MSGR_PRIORITY_NORMAL);
begin
BufferMessage(BuildMessage(fEndpointID,TargetID,Priority,GetTimeStamp,P1,P2,P3,P4));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
procedure TMessangerEndpoint.BufferMessage(Msg: TMsgrMessage);
begin
Msg.Reserved := nil;
fBufferedMessages.Add(Msg);
end;
//------------------------------------------------------------------------------
procedure TMessangerEndpoint.SendBufferedMessages;
var
i: Integer;
begin
If fBufferedMessages.Count > 0 then
begin
fBufferedMessages.Sort;
fMessanger.SendBufferedMessages(fBufferedMessages,fUndeliveredMessages);
fBufferedMessages.Clear;
end;
For i := fUndeliveredMessages.LowIndex to fUndeliveredMessages.HighIndex do
UndeliveredDispatch(fUndeliveredMessages[i],True);
fUndeliveredMessages.Clear;
end;
//------------------------------------------------------------------------------
Function TMessangerEndpoint.WaitForNewMessage(TimeOut: DWORD): TMsgrWaitResult;
begin
case fIncomingMsgsWaiter.WaitFor(TimeOut) of
wrTimeOut: Result := mwrTimeOut;
wrSignaled: Result := mwrNewMessage;
else
Result := mwrError;
end;
end;
//------------------------------------------------------------------------------
procedure TMessangerEndpoint.FetchMessages;
begin
fIncomingSynchronizer.Enter;
try
fReceivedMessages.Append(fIncomingMessages);
fIncomingMessages.Clear;
finally
fIncomingSynchronizer.Leave;
end;
fReceivedMessages.Sort;
end;
//------------------------------------------------------------------------------
Function TMessangerEndpoint.TraverseMessages: Boolean;
var
i: Integer;
Flags: TMsgrDispatchFlags;
begin
Result := True;
If Assigned(fOnMessageTraversing) then
begin
For i := fReceivedMessages.HighIndex downto fReceivedMessages.LowIndex do
begin
// prepare flags
Flags := [mdfRemoveMessage];
If Assigned(fReceivedMessages[i].Reserved) then Include(Flags,mdfSynchronousMessage);
If fAutoCycle then Include(Flags,mdfAutoCycle);
// call event
fOnMessageTraversing(Self,fReceivedMessages[i],Flags); // <<<
// process output flags
fAutoCycle := fAutoCycle and (mdfAutoCycle in Flags);
If mdfRemoveMessage in Flags then
begin
If Assigned(fReceivedMessages[i].Reserved) then
TEvent(fReceivedMessages[i].Reserved).SetEvent;
fReceivedMessages.Delete(i);
end;
If mdfStopTraversing in Flags then
begin
Result := False;
Break{i};
end;
end;
end
else ClearMessages;
end;
//------------------------------------------------------------------------------
procedure TMessangerEndpoint.Cycle(MessageWaitTimeOut: DWORD);
begin
If WaitForNewMessage(MessageWaitTimeOut) = mwrNewMessage then
begin
FetchMessages;
TraverseMessages;
end;
end;
//------------------------------------------------------------------------------
procedure TMessangerEndpoint.AutoCycle(MessageWaitTimeOut: DWORD);
begin
If not fAutoCycle then
begin
fAutoCycle := True;
while fAutoCycle do
Cycle(MessageWaitTimeOut);
end;
end;
//------------------------------------------------------------------------------
procedure TMessangerEndpoint.ClearMessages;
var
i: Integer;
begin
For i := fReceivedMessages.LowIndex to fReceivedMessages.HighIndex do
If Assigned(fReceivedMessages[i].Reserved) then
TEvent(fReceivedMessages[i].Reserved).SetEvent;
fReceivedMessages.Clear;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMessanger }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TMessanger - implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMessanger - private methods }
{------------------------------------------------------------------------------}
Function TMessanger.GetEndpointCapacity: Integer;
begin
Result := Length(fEndpoints);
end;
//------------------------------------------------------------------------------
Function TMessanger.GetEndpointCount: Integer;
var
i: Integer;
begin
fSynchronizer.BeginRead;
try
Result := 0;
For i := Low(fEndpoints) to High(fEndpoints) do
If Assigned(fEndpoints[i]) then Inc(Result);
finally
fSynchronizer.EndRead;
end;
end;
//------------------------------------------------------------------------------
Function TMessanger.GetEndpoint(Index: Integer): TMessangerEndpoint;
begin
Result := nil;
fSynchronizer.BeginRead;
try
If (Index >= Low(fEndpoints)) and (Index <= High(fEndpoints)) then
Result := fEndpoints[Index]
else
raise Exception.CreateFmt('TMessanger.GetEndpoint: Index (%d) out of bounds.',[Index]);
finally
fSynchronizer.EndRead;
end;
end;
{------------------------------------------------------------------------------}
{ TMessanger - protected methods }
{------------------------------------------------------------------------------}
procedure TMessanger.RemoveEndpoint(EndpointID: TMsgrEndpointID);
begin
fSynchronizer.BeginWrite;
try
If EndpointID <= High(fEndpoints) then
fEndpoints[EndpointID] := nil
else
raise Exception.CreateFmt('TMessanger.RemoveEndpoint: EndpointID (%d) out of bounds.',[EndpointID]);
finally
fSynchronizer.EndWrite;
end;
end;
//------------------------------------------------------------------------------
Function TMessanger.SendMessage(Msg: TMsgrMessage): Boolean;
var
i: Integer;
begin
Result := False;
fSynchronizer.BeginRead;
try
If Msg.Target = MSGR_ID_BROADCAST then
begin
For i := Low(fEndpoints) to High(fEndpoints) do
If Assigned(fEndpoints[i]) then
begin
fEndpoints[i].AddMessages(@Msg,1);
Result := True;
end;
end
else
begin
If Msg.Target <= High(fEndpoints) then
If Assigned(fEndpoints[Msg.Target]) then
begin
fEndpoints[Msg.Target].AddMessages(@Msg,1);
Result := True;
end;
end;
finally
fSynchronizer.EndRead;
end;
end;
//------------------------------------------------------------------------------
procedure TMessanger.SendBufferedMessages(Messages,Undelivered: TMsgrMessageVector);
var
i: Integer;
StartIdx: Integer;
Count: Integer;
Function DoSending(Start,Cnt: Integer): Boolean;
var
ii: Integer;
begin
Result := False;
If Messages[Start].Target = MSGR_ID_BROADCAST then
begin
For ii := Low(fEndpoints) to High(fEndpoints) do
If Assigned(fEndpoints[ii]) then
begin
fEndpoints[ii].AddMessages(Messages.Pointers[Start],Cnt);
Result := True;
end;
end
else
begin
If Messages[Start].Target <= High(fEndpoints) then
If Assigned(fEndpoints[Messages[Start].Target]) then
begin
fEndpoints[Messages[Start].Target].AddMessages(Messages.Pointers[Start],Cnt);
Result := True;
end;
end;
end;
begin
If Messages.Count > 0 then
begin
fSynchronizer.BeginRead;
try
StartIdx := Messages.LowIndex;
while StartIdx <= Messages.HighIndex do
begin
Count := 1;
For i := Succ(StartIdx) to Messages.HighIndex do
If Messages[StartIdx].Target = Messages[i].Target then
Inc(Count)
else
Break{i};
If not DoSending(StartIdx,Count) then
Undelivered.Append(Messages.Pointers[StartIdx],Count);
StartIdx := StartIdx + Count;
end;
finally
fSynchronizer.EndRead;
end;
end;
end;
{------------------------------------------------------------------------------}
{ TMessanger - public methods }
{------------------------------------------------------------------------------}
constructor TMessanger.Create(EndpointCapacity: TMsgrEndpointID = 1024);
begin
inherited Create;
// High(TMsgrEndpointID) = $FFFF(65535) is reserved for broadcast
If EndpointCapacity < High(TMsgrEndpointID) then
SetLength(fEndpoints,EndpointCapacity)
else
raise Exception.CreateFmt('TMessanger.Create: Required capacity (%d) is too high.',[EndpointCapacity]);
fSynchronizer := TMultiReadExclusiveWriteSynchronizer.Create;
end;
//------------------------------------------------------------------------------
destructor TMessanger.Destroy;
begin
If EndpointCount > 0 then
raise Exception.Create('TMessanger.Destroy: Not all endpoints were freed.');
fSynchronizer.Free;
inherited;
end;
//------------------------------------------------------------------------------
Function TMessanger.IDAvailable(EndpointID: TMsgrEndpointID): Boolean;
begin
fSynchronizer.BeginRead;
try
If EndpointID <= High(fEndpoints) then
Result := not Assigned(fEndpoints[EndpointID])
else
Result := False;
finally
fSynchronizer.EndRead;
end;
end;
//------------------------------------------------------------------------------
Function TMessanger.CreateEndpoint: TMessangerEndpoint;
var
i,Idx: Integer;
begin
Result := nil;
fSynchronizer.BeginWrite;
try
Idx := -1;
For i := Low(fEndpoints) to High(fEndpoints) do
If not Assigned(fEndpoints[i]) then
begin
Idx := i;
Break {For i};
end;
If Idx >= 0 then
begin
Result := TMessangerEndpoint.Create(TMsgrEndpointID(Idx),Self);
fEndpoints[Idx] := Result;
end
else raise Exception.Create('TMessanger.CreateEndpoint: No endpoint slot available.');
finally
fSynchronizer.EndWrite;
end;
end;
//------------------------------------------------------------------------------
Function TMessanger.CreateEndpoint(EndpointID: TMsgrEndpointID): TMessangerEndpoint;
begin
Result := nil;
fSynchronizer.BeginWrite;
try
If EndpointID <= High(fEndpoints) then
begin
If not Assigned(fEndpoints[EndpointID]) then
begin
Result := TMessangerEndpoint.Create(EndpointID,Self);
fEndpoints[EndpointID] := Result;
end
else raise Exception.CreateFmt('TMessanger.CreateEndpoint: Requested endpoint ID (%d) is already taken.',[EndpointID]);
end
else raise Exception.CreateFmt('TMessanger.CreateEndpoint: Requested endpoint ID (%d) is not allocated.',[EndpointID]);
finally
fSynchronizer.EndWrite;
end;
end;
end.
|
unit KanaConvTests;
{ Requires Hepburn.roma, Kiriji - Polivanov.roma, PinYin.rpy.
JWBIO must be tested beforehand. }
interface
uses SysUtils, Classes, TestFramework, JWBIO, JWBStrings, KanaConv;
type
TConvTableTest = class(TTestCase)
protected
FTableNames: TStringArray;
FConv: TRomajiTranslator;
public
constructor Create(const ATableNames: array of string); reintroduce;
function GetName: string; override;
function TableDir: string;
procedure SetUp; override;
procedure TearDown; override;
procedure RunTestFile(const AFilename: string);
published
procedure RunTests;
end;
TKanaTableTest = class(TConvTableTest)
public
procedure SetUp; override;
end;
TBopomofoTableTest = class(TConvTableTest)
public
procedure SetUp; override;
end;
TConvTableSuite = class(TTestSuite)
protected
FTableNames: TStringArray;
public
constructor Create(TestClass: TTestCaseClass; ATableNames: array of string);
procedure AddTest(ATest: ITest); override;
end;
implementation
uses TestingCommon;
constructor TConvTableTest.Create(const ATableNames: array of string);
var i: integer;
begin
inherited Create('RunTests');
SetLength(FTableNames, Length(ATableNames));
for i := 0 to Length(ATableNames)-1 do
FTableNames[i] := ATableNames[Low(ATableNames) + i];
end;
function TConvTableTest.GetName: string;
var i: integer;
begin
Result := '';
for i := 0 to Length(FTableNames)-1 do
Result := Result + ExtractFilename(FTableNames[i]) + ', ';
if Result <> '' then
SetLength(Result, Length(Result)-2)
else
Result := '[ empty ]';
end;
function TConvTableTest.TableDir: string;
begin
Result := AppFolder;
end;
procedure TConvTableTest.Setup;
var i: integer;
begin
//FConv must be created in descendants
for i := 0 to Length(FTableNames)-1 do
FConv.LoadFromFile(TableDir+'\'+ExtractFilename(FTableNames[i]));
end;
procedure TConvTableTest.Teardown;
begin
FreeAndNil(FConv);
end;
procedure TConvTableTest.RunTests;
var i: integer;
begin
for i := 0 to Length(FTableNames)-1 do
RunTestFile(FTableNames[i]+'.txt');
end;
procedure TConvTableTest.RunTestFile(const AFilename: string);
var inp: TStreamDecoder;
ln: string;
i_ln: integer;
i_pos: integer;
lp,rp: string;
cmp: string;
begin
inp := OpenTextFile(AFilename);
try
i_ln := -1;
while inp.ReadLn(ln) do begin
Inc(i_ln);
ln := Trim(ln);
if (ln='') or (ln[1]='#') then continue;
i_pos := pos('=',ln);
Assert(i_pos>0, 'Invalid test case file: '+AFilename+'. '
+'Error at line '+IntToStr(i_ln)+': no "=".');
lp := copy(ln,1,i_pos-1);
rp := copy(ln,i_pos+1,MaxInt);
Assert(Length(lp)>0, 'Invalid test case file: '+AFilename+'. '
+'Error at line '+IntToStr(i_ln)+': empty left part.');
if EvalChar(lp[1]) in [EC_KATAKANA, EC_HIRAGANA, EC_BOPOMOFO] then
cmp := FConv.KanaToRomaji(lp,[])
else
cmp := ConvertBopomofo(FConv.RomajiToKana(lp,[]));
Check(SameText(rp, cmp),
'Error in '+AFilename+'@'+IntToStr(i_ln)+': '+lp+' -> '+cmp+', '
+'expected '+rp+'.');
end;
finally
FreeAndNil(inp);
end;
end;
procedure TKanaTableTest.Setup;
begin
FConv := TKanaTranslator.Create;
inherited;
end;
procedure TBopomofoTableTest.Setup;
begin
FConv := TPinyinTranslator.Create;
inherited;
end;
constructor TConvTableSuite.Create(TestClass: TTestCaseClass;
ATableNames: array of string);
var i: integer;
ATableList: string;
begin
SetLength(FTableNames, Length(ATableNames));
ATableList := '[';
for i := 0 to Length(ATableNames)-1 do begin
FTableNames[i] := ATableNames[Low(ATableNames) + i];
ATableList := ATableList + FTableNames[i] + ', ';
end;
SetLength(ATableList, Length(ATableList)-2);
ATableList := ATableList + ']';
inherited Create(TestClass.ClassName+' '+ATableList);
AddTests(testClass);
end;
procedure TConvTableSuite.AddTest(ATest: ITest);
begin
inherited;
//Parametrize
if ATest is TConvTableTest then
(ATest as TConvTableTest).FTableNames := FTableNames;
end;
function KanaConvTestSuite: ITestSuite;
var ASuite: TTestSuite;
fname, rawName: string;
begin
ASuite := TTestSuite.Create('KanaConv');
// Load all .txt files from test case dir
for fname in FileList(TestCasesDir+'\kanaconv', '*.txt') do begin
rawName := ChangeFileExt(fname, ''); //strip .txt
if ExtractFileExt(rawName)='.rpy' then
ASuite.AddTest(TBopomofoTableTest.Create([rawName]))
else
ASuite.AddTest(TKanaTableTest.Create([rawName]))
end;
Result := ASuite;
end;
initialization
RegisterTest(KanaConvTestSuite);
end.
|
unit MT5.RetCode;
interface
{$SCOPEDENUMS ON}
type
TMTRetCodeType = (
// --- successfully codes
MT_RET_OK = 0, // ok
MT_RET_OK_NONE = 1, // ok; no data
// --- common errors
MT_RET_ERROR = 2, // Common error
MT_RET_ERR_PARAMS = 3, // Invalid parameters
MT_RET_ERR_DATA = 4, // Invalid data
MT_RET_ERR_DISK = 5, // Disk error
MT_RET_ERR_MEM = 6, // Memory error
MT_RET_ERR_NETWORK = 7, // Network error
MT_RET_ERR_PERMISSIONS = 8, // Not enough permissions
MT_RET_ERR_TIMEOUT = 9, // Operation timeout
MT_RET_ERR_CONNECTION = 10, // No connection
MT_RET_ERR_NOSERVICE = 11, // Service is not available
MT_RET_ERR_FREQUENT = 12, // Too frequent requests
MT_RET_ERR_NOTFOUND = 13, // Not found
MT_RET_ERR_PARTIAL = 14, // Partial error
MT_RET_ERR_SHUTDOWN = 15, // Server shutdown in progress
MT_RET_ERR_CANCEL = 16, // Operation has been canceled
MT_RET_ERR_DUPLICATE = 17, // Duplicate data
// --- authentication retcodes
MT_RET_AUTH_CLIENT_INVALID = 1000, // Invalid terminal type
MT_RET_AUTH_ACCOUNT_INVALID = 1001, // Invalid account
MT_RET_AUTH_ACCOUNT_DISABLED = 1002, // Account disabled
MT_RET_AUTH_ADVANCED = 1003, // Advanced authorization necessary
MT_RET_AUTH_CERTIFICATE = 1004, // Certificate required
MT_RET_AUTH_CERTIFICATE_BAD = 1005, // Invalid certificate
MT_RET_AUTH_NOTCONFIRMED = 1006, // Certificate is not confirmed
MT_RET_AUTH_SERVER_INTERNAL = 1007, // Attempt to connect to non-access server
MT_RET_AUTH_SERVER_BAD = 1008, // Server isn't authenticated
MT_RET_AUTH_UPDATE_ONLY = 1009, // Only updates available
MT_RET_AUTH_CLIENT_OLD = 1010, // Client has old version
MT_RET_AUTH_MANAGER_NOCONFIG = 1011, // Manager account doesn't have manager config
MT_RET_AUTH_MANAGER_IPBLOCK = 1012, // IP address unallowed for manager
MT_RET_AUTH_GROUP_INVALID = 1013, // Group is not initialized (server restart neccesary)
MT_RET_AUTH_CA_DISABLED = 1014, // Certificate generation disabled
MT_RET_AUTH_INVALID_ID = 1015, // Invalid or disabled server id [check server's id]
MT_RET_AUTH_INVALID_IP = 1016, // Unallowed address [check server's ip address]
MT_RET_AUTH_INVALID_TYPE = 1017, // Invalid server type [check server's id and type]
MT_RET_AUTH_SERVER_BUSY = 1018, // Server is busy
MT_RET_AUTH_SERVER_CERT = 1019, // Invalid server certificate
MT_RET_AUTH_ACCOUNT_UNKNOWN = 1020, // Unknown account
MT_RET_AUTH_SERVER_OLD = 1021, // Old server version
MT_RET_AUTH_SERVER_LIMIT = 1022, // Server cannot be connected due to license limitation
MT_RET_AUTH_MOBILE_DISABLED = 1023, // Mobile connection aren't allowed in server license
// --- config management retcodes
MT_RET_CFG_LAST_ADMIN = 2000, // Last admin config deleting
MT_RET_CFG_LAST_ADMIN_GROUP = 2001, // Last admin group cannot be deleted
MT_RET_CFG_NOT_EMPTY = 2003, // Accounts or trades in group
MT_RET_CFG_INVALID_RANGE = 2004, // Invalid accounts or trades ranges
MT_RET_CFG_NOT_MANAGER_LOGIN = 2005, // Manager account is not from manager group
MT_RET_CFG_BUILTIN = 2006, // Built-in protected config
MT_RET_CFG_DUPLICATE = 2007, // Configuration duplicate
MT_RET_CFG_LIMIT_REACHED = 2008, // Configuration limit reached
MT_RET_CFG_NO_ACCESS_TO_MAIN = 2009, // Invalid network configuration
MT_RET_CFG_DEALER_ID_EXIST = 2010, // Dealer with same ID exists
MT_RET_CFG_BIND_ADDR_EXIST = 2011, // Bind address already exists
MT_RET_CFG_WORKING_TRADE = 2012, // Attempt to delete working trade server
// --- client management retcodes
MT_RET_USR_LAST_ADMIN = 3001, // Last admin account deleting
MT_RET_USR_LOGIN_EXHAUSTED = 3002, // Logins range exhausted
MT_RET_USR_LOGIN_PROHIBITED = 3003, // Login reserved at another server
MT_RET_USR_LOGIN_EXIST = 3004, // Account already exists
MT_RET_USR_SUICIDE = 3005, // Attempt of self-deletion
MT_RET_USR_INVALID_PASSWORD = 3006, // Invalid account password
MT_RET_USR_LIMIT_REACHED = 3007, // Users limit reached
MT_RET_USR_HAS_TRADES = 3008, // Account has open trades
MT_RET_USR_DIFFERENT_SERVERS = 3009, // Attempt to move account to different server
MT_RET_USR_DIFFERENT_CURRENCY = 3010, // Attempt to move account to different currency group
MT_RET_USR_IMPORT_BALANCE = 3011, // Account balance import error
MT_RET_USR_IMPORT_GROUP = 3012, // Account import with invalid group
// --- trades management retcodes
MT_RET_TRADE_LIMIT_REACHED = 4001, // Orders or deals limit reached
MT_RET_TRADE_ORDER_EXIST = 4002, // Order already exists
MT_RET_TRADE_ORDER_EXHAUSTED = 4003, // Orders range exhausted
MT_RET_TRADE_DEAL_EXHAUSTED = 4004, // Deals range exhausted
MT_RET_TRADE_MAX_MONEY = 4005, // Money limit reached
// --- report generation retcodes
MT_RET_REPORT_SNAPSHOT = 5001, // Base snapshot error
MT_RET_REPORT_NOTSUPPORTED = 5002, // Method doesn't support for this report
MT_RET_REPORT_NODATA = 5003, // No report data
MT_RET_REPORT_TEMPLATE_BAD = 5004, // Bad template
MT_RET_REPORT_TEMPLATE_END = 5005, // End of template (template success processed)
MT_RET_REPORT_INVALID_ROW = 5006, // Invalid row size
MT_RET_REPORT_LIMIT_REPEAT = 5007, // Tag repeat limit reached
MT_RET_REPORT_LIMIT_REPORT = 5008, // Report size limit reached
// --- price history reports retcodes
MT_RET_HST_SYMBOL_NOTFOUND = 6001, // Symbol not found; try to restart history server
// --- trade request retcodes
MT_RET_REQUEST_INWAY = 10001, // Request on the way
MT_RET_REQUEST_ACCEPTED = 10002, // Request accepted
MT_RET_REQUEST_PROCESS = 10003, // Request processed
MT_RET_REQUEST_REQUOTE = 10004, // Request Requoted
MT_RET_REQUEST_PRICES = 10005, // Request Prices
MT_RET_REQUEST_REJECT = 10006, // Request rejected
MT_RET_REQUEST_CANCEL = 10007, // Request canceled
MT_RET_REQUEST_PLACED = 10008, // Order from requestplaced
MT_RET_REQUEST_DONE = 10009, // Request executed
MT_RET_REQUEST_DONE_PARTIAL = 10010, // Request executed partially
MT_RET_REQUEST_ERROR = 10011, // Request common error
MT_RET_REQUEST_TIMEOUT = 10012, // Request timeout
MT_RET_REQUEST_INVALID = 10013, // Invalid request
MT_RET_REQUEST_INVALID_VOLUME = 10014, // Invalid volume
MT_RET_REQUEST_INVALID_PRICE = 10015, // Invalid price
MT_RET_REQUEST_INVALID_STOPS = 10016, // Invalid stops or price
MT_RET_REQUEST_TRADE_DISABLED = 10017, // Trade disabled
MT_RET_REQUEST_MARKET_CLOSED = 10018, // Market closed
MT_RET_REQUEST_NO_MONEY = 10019, // Not enough money
MT_RET_REQUEST_PRICE_CHANGED = 10020, // Price changed
MT_RET_REQUEST_PRICE_OFF = 10021, // No prices
MT_RET_REQUEST_INVALID_EXP = 10022, // Invalid order expiration
MT_RET_REQUEST_ORDER_CHANGED = 10023, // Order has been changed already
MT_RET_REQUEST_TOO_MANY = 10024, // Too many trade requests
MT_RET_REQUEST_NO_CHANGES = 10025, // Request doesn't contain changes
MT_RET_REQUEST_AT_DISABLED_SERVER = 10026, // AutoTrading disabled by server
MT_RET_REQUEST_AT_DISABLED_CLIENT = 10027, // AutoTrading disabled by client
MT_RET_REQUEST_LOCKED = 10028, // Request locked by dealer
MT_RET_REQUEST_FROZED = 10029, // Order or position frozen
MT_RET_REQUEST_INVALID_FILL = 10030, // Unsupported filling mode
MT_RET_REQUEST_CONNECTION = 10031, // No connection
MT_RET_REQUEST_ONLY_REAL = 10032, // Allowed for real accounts only
MT_RET_REQUEST_LIMIT_ORDERS = 10033, // Orders limit reached
MT_RET_REQUEST_LIMIT_VOLUME = 10034, // Volume limit reached
// --- dealer retcodes
MT_RET_REQUEST_RETURN = 11000, // Request returned in queue
MT_RET_REQUEST_DONE_CANCEL = 11001, // Request partially filled; remainder has been canceled
MT_RET_REQUEST_REQUOTE_RETURN = 11002, // Request requoted and returned in queue with new prices
// --- API retcodes
MT_RET_ERR_NOTIMPLEMENT = 12000, // Not implement yet
MT_RET_ERR_NOTMAIN = 12001, // Operation must be performed on main server
MT_RET_ERR_NOTSUPPORTED = 12002, // Command doesn't supported
MT_RET_ERR_DEADLOCK = 12003, // Operation canceled due possible deadlock
MT_RET_ERR_LOCKED = 12004 // Operation on locked entity
);
TMTRetCode = class
private
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
class function GetError(AError: TMTRetCodeType): string;
end;
implementation
{ TMTRetCode }
class function TMTRetCode.GetError(AError: TMTRetCodeType): string;
begin
case AError of
TMTRetCodeType.MT_RET_OK:
Result := 'ok';
TMTRetCodeType.MT_RET_OK_NONE:
Result := 'ok; no data';
TMTRetCodeType.MT_RET_ERROR:
Result := 'Common error';
TMTRetCodeType.MT_RET_ERR_PARAMS:
Result := 'Invalid parameters';
TMTRetCodeType.MT_RET_ERR_DATA:
Result := 'Invalid data';
TMTRetCodeType.MT_RET_ERR_DISK:
Result := 'Disk error';
TMTRetCodeType.MT_RET_ERR_MEM:
Result := 'Memory error';
TMTRetCodeType.MT_RET_ERR_NETWORK:
Result := 'Network error';
TMTRetCodeType.MT_RET_ERR_PERMISSIONS:
Result := 'Not enough permissions';
TMTRetCodeType.MT_RET_ERR_TIMEOUT:
Result := 'Operation timeout';
TMTRetCodeType.MT_RET_ERR_CONNECTION:
Result := 'No connection';
TMTRetCodeType.MT_RET_ERR_NOSERVICE:
Result := 'Service is not available';
TMTRetCodeType.MT_RET_ERR_FREQUENT:
Result := 'Too frequent requests';
TMTRetCodeType.MT_RET_ERR_NOTFOUND:
Result := 'Not found';
TMTRetCodeType.MT_RET_ERR_PARTIAL:
Result := 'Partial error';
TMTRetCodeType.MT_RET_ERR_SHUTDOWN:
Result := 'Server shutdown in progress';
TMTRetCodeType.MT_RET_ERR_CANCEL:
Result := 'Operation has been canceled';
TMTRetCodeType.MT_RET_ERR_DUPLICATE:
Result := 'Duplicate data';
// ---
TMTRetCodeType.MT_RET_AUTH_CLIENT_INVALID:
Result := 'Invalid terminal type';
TMTRetCodeType.MT_RET_AUTH_ACCOUNT_INVALID:
Result := 'Invalid account';
TMTRetCodeType.MT_RET_AUTH_ACCOUNT_DISABLED:
Result := 'Account disabled';
TMTRetCodeType.MT_RET_AUTH_ADVANCED:
Result := 'Advanced authorization necessary';
TMTRetCodeType.MT_RET_AUTH_CERTIFICATE:
Result := 'Certificate required';
TMTRetCodeType.MT_RET_AUTH_CERTIFICATE_BAD:
Result := 'Invalid certificate';
TMTRetCodeType.MT_RET_AUTH_NOTCONFIRMED:
Result := 'Certificate is not confirmed';
TMTRetCodeType.MT_RET_AUTH_SERVER_INTERNAL:
Result := 'Attempt to connect to non-access server';
TMTRetCodeType.MT_RET_AUTH_SERVER_BAD:
Result := 'Server is not authenticated';
TMTRetCodeType.MT_RET_AUTH_UPDATE_ONLY:
Result := 'Only updates available';
TMTRetCodeType.MT_RET_AUTH_CLIENT_OLD:
Result := 'Client has old version';
TMTRetCodeType.MT_RET_AUTH_MANAGER_NOCONFIG:
Result := 'Manager account does not have manager config';
TMTRetCodeType.MT_RET_AUTH_MANAGER_IPBLOCK:
Result := 'IP address unallowed for manager';
TMTRetCodeType.MT_RET_AUTH_GROUP_INVALID:
Result := 'Group is not initialized (server restart neccesary)';
TMTRetCodeType.MT_RET_AUTH_CA_DISABLED:
Result := 'Certificate generation disabled';
TMTRetCodeType.MT_RET_AUTH_INVALID_ID:
Result := 'Invalid or disabled server id [check servers id]';
TMTRetCodeType.MT_RET_AUTH_INVALID_IP:
Result := 'Unallowed address [check servers ip address]';
TMTRetCodeType.MT_RET_AUTH_INVALID_TYPE:
Result := 'Invalid server type [check servers id and type]';
TMTRetCodeType.MT_RET_AUTH_SERVER_BUSY:
Result := 'Server is busy';
TMTRetCodeType.MT_RET_AUTH_SERVER_CERT:
Result := 'Invalid server certificate';
TMTRetCodeType.MT_RET_AUTH_ACCOUNT_UNKNOWN:
Result := 'Unknown account';
TMTRetCodeType.MT_RET_AUTH_SERVER_OLD:
Result := 'Old server version';
TMTRetCodeType.MT_RET_AUTH_SERVER_LIMIT:
Result := 'Server cannot be connected due to license limitation';
TMTRetCodeType.MT_RET_AUTH_MOBILE_DISABLED:
Result := 'Mobile connection are not allowed in server license ';
// ---
TMTRetCodeType.MT_RET_CFG_LAST_ADMIN:
Result := 'Last admin config deleting';
TMTRetCodeType.MT_RET_CFG_LAST_ADMIN_GROUP:
Result := 'Last admin group cannot be deleted';
TMTRetCodeType.MT_RET_CFG_NOT_EMPTY:
Result := 'Accounts or trades in group';
TMTRetCodeType.MT_RET_CFG_INVALID_RANGE:
Result := 'Invalid accounts or trades ranges';
TMTRetCodeType.MT_RET_CFG_NOT_MANAGER_LOGIN:
Result := 'Manager account is not from manager group';
TMTRetCodeType.MT_RET_CFG_BUILTIN:
Result := 'Built-in protected config';
TMTRetCodeType.MT_RET_CFG_DUPLICATE:
Result := 'Configuration duplicate';
TMTRetCodeType.MT_RET_CFG_LIMIT_REACHED:
Result := 'Configuration limit reached';
TMTRetCodeType.MT_RET_CFG_NO_ACCESS_TO_MAIN:
Result := 'Invalid network configuration';
TMTRetCodeType.MT_RET_CFG_DEALER_ID_EXIST:
Result := 'Dealer with same ID exists';
TMTRetCodeType.MT_RET_CFG_BIND_ADDR_EXIST:
Result := 'Bind address already exists';
TMTRetCodeType.MT_RET_CFG_WORKING_TRADE:
Result := 'Attempt to delete working trade server';
// ---
TMTRetCodeType.MT_RET_USR_LAST_ADMIN:
Result := 'Last admin account deleting';
TMTRetCodeType.MT_RET_USR_LOGIN_EXHAUSTED:
Result := 'Logins range exhausted';
TMTRetCodeType.MT_RET_USR_LOGIN_PROHIBITED:
Result := 'Login reserved at another server';
TMTRetCodeType.MT_RET_USR_LOGIN_EXIST:
Result := 'Account already exists';
TMTRetCodeType.MT_RET_USR_SUICIDE:
Result := 'Attempt of self-deletion';
TMTRetCodeType.MT_RET_USR_INVALID_PASSWORD:
Result := 'Invalid account password';
TMTRetCodeType.MT_RET_USR_LIMIT_REACHED:
Result := 'Users limit reached';
TMTRetCodeType.MT_RET_USR_HAS_TRADES:
Result := 'Account has open trades';
TMTRetCodeType.MT_RET_USR_DIFFERENT_SERVERS:
Result := 'Attempt to move account to different server';
TMTRetCodeType.MT_RET_USR_DIFFERENT_CURRENCY:
Result := 'Attempt to move account to different currency group';
TMTRetCodeType.MT_RET_USR_IMPORT_BALANCE:
Result := 'Account balance import error';
TMTRetCodeType.MT_RET_USR_IMPORT_GROUP:
Result := 'Account import with invalid group';
// ---
TMTRetCodeType.MT_RET_TRADE_LIMIT_REACHED:
Result := 'Orders or deals limit reached';
TMTRetCodeType.MT_RET_TRADE_ORDER_EXIST:
Result := 'Order already exists';
TMTRetCodeType.MT_RET_TRADE_ORDER_EXHAUSTED:
Result := 'Orders range exhausted';
TMTRetCodeType.MT_RET_TRADE_DEAL_EXHAUSTED:
Result := 'Deals range exhausted';
TMTRetCodeType.MT_RET_TRADE_MAX_MONEY:
Result := 'Money limit reached';
// ---
TMTRetCodeType.MT_RET_REPORT_SNAPSHOT:
Result := 'Base snapshot error';
TMTRetCodeType.MT_RET_REPORT_NOTSUPPORTED:
Result := 'Method does not support for this report ';
TMTRetCodeType.MT_RET_REPORT_NODATA:
Result := 'No report data';
TMTRetCodeType.MT_RET_REPORT_TEMPLATE_BAD:
Result := 'Bad template';
TMTRetCodeType.MT_RET_REPORT_TEMPLATE_END:
Result := 'End of template (template success processed)';
TMTRetCodeType.MT_RET_REPORT_INVALID_ROW:
Result := 'Invalid row size';
TMTRetCodeType.MT_RET_REPORT_LIMIT_REPEAT:
Result := 'Tag repeat limit reached';
TMTRetCodeType.MT_RET_REPORT_LIMIT_REPORT:
Result := 'Report size limit reached';
// ---
TMTRetCodeType.MT_RET_HST_SYMBOL_NOTFOUND:
Result := 'Symbol not found; try to restart history server';
// ---
TMTRetCodeType.MT_RET_REQUEST_INWAY:
Result := 'Request on the way';
TMTRetCodeType.MT_RET_REQUEST_ACCEPTED:
Result := 'Request accepted';
TMTRetCodeType.MT_RET_REQUEST_PROCESS:
Result := 'Request processed';
TMTRetCodeType.MT_RET_REQUEST_REQUOTE:
Result := 'Request Requoted';
TMTRetCodeType.MT_RET_REQUEST_PRICES:
Result := 'Request Prices';
TMTRetCodeType.MT_RET_REQUEST_REJECT:
Result := 'Request rejected';
TMTRetCodeType.MT_RET_REQUEST_CANCEL:
Result := 'Request canceled';
TMTRetCodeType.MT_RET_REQUEST_PLACED:
Result := 'Order from requestplaced';
TMTRetCodeType.MT_RET_REQUEST_DONE:
Result := 'Request executed';
TMTRetCodeType.MT_RET_REQUEST_DONE_PARTIAL:
Result := 'Request executed partially';
TMTRetCodeType.MT_RET_REQUEST_ERROR:
Result := 'Request common error';
TMTRetCodeType.MT_RET_REQUEST_TIMEOUT:
Result := 'Request timeout';
TMTRetCodeType.MT_RET_REQUEST_INVALID:
Result := 'Invalid request';
TMTRetCodeType.MT_RET_REQUEST_INVALID_VOLUME:
Result := 'Invalid volume';
TMTRetCodeType.MT_RET_REQUEST_INVALID_PRICE:
Result := 'Invalid price';
TMTRetCodeType.MT_RET_REQUEST_INVALID_STOPS:
Result := 'Invalid stops or price';
TMTRetCodeType.MT_RET_REQUEST_TRADE_DISABLED:
Result := 'Trade disabled';
TMTRetCodeType.MT_RET_REQUEST_MARKET_CLOSED:
Result := 'Market closed';
TMTRetCodeType.MT_RET_REQUEST_NO_MONEY:
Result := 'Not enough money';
TMTRetCodeType.MT_RET_REQUEST_PRICE_CHANGED:
Result := 'Price changed';
TMTRetCodeType.MT_RET_REQUEST_PRICE_OFF:
Result := 'No prices';
TMTRetCodeType.MT_RET_REQUEST_INVALID_EXP:
Result := 'Invalid order expiration';
TMTRetCodeType.MT_RET_REQUEST_ORDER_CHANGED:
Result := 'Order has been changed already';
TMTRetCodeType.MT_RET_REQUEST_TOO_MANY:
Result := 'Too many trade requests';
TMTRetCodeType.MT_RET_REQUEST_NO_CHANGES:
Result := 'Request does not contain changes ';
TMTRetCodeType.MT_RET_REQUEST_AT_DISABLED_SERVER:
Result := 'AutoTrading disabled by server';
TMTRetCodeType.MT_RET_REQUEST_AT_DISABLED_CLIENT:
Result := 'AutoTrading disabled by client';
TMTRetCodeType.MT_RET_REQUEST_LOCKED:
Result := 'Request locked by dealer';
TMTRetCodeType.MT_RET_REQUEST_FROZED:
Result := 'Order or position frozen';
TMTRetCodeType.MT_RET_REQUEST_INVALID_FILL:
Result := 'Unsupported filling mode';
TMTRetCodeType.MT_RET_REQUEST_CONNECTION:
Result := 'No connection';
TMTRetCodeType.MT_RET_REQUEST_ONLY_REAL:
Result := 'Allowed for real accounts only';
TMTRetCodeType.MT_RET_REQUEST_LIMIT_ORDERS:
Result := 'Orders limit reached';
TMTRetCodeType.MT_RET_REQUEST_LIMIT_VOLUME:
Result := 'Volume limit reached';
// ---
TMTRetCodeType.MT_RET_REQUEST_RETURN:
Result := 'Request returned in queue';
TMTRetCodeType.MT_RET_REQUEST_DONE_CANCEL:
Result := 'Request partially filled; remainder has been canceled';
TMTRetCodeType.MT_RET_REQUEST_REQUOTE_RETURN:
Result := 'Request requoted and returned in queue with new prices';
// ---
TMTRetCodeType.MT_RET_ERR_NOTIMPLEMENT:
Result := 'Not implement yet';
TMTRetCodeType.MT_RET_ERR_NOTMAIN:
Result := 'Operation must be performed on main server';
TMTRetCodeType.MT_RET_ERR_NOTSUPPORTED:
Result := 'Command does not supported ';
TMTRetCodeType.MT_RET_ERR_DEADLOCK:
Result := 'Operation canceled due possible deadlock';
TMTRetCodeType.MT_RET_ERR_LOCKED:
Result := 'Operation on locked entity';
end;
end;
end.
|
UNIT TETRIS_PIECE;
INTERFACE
CONST
TETRIS_PIECE_VOID = 0;
TETRIS_PIECE_L = 1;
TETRIS_PIECE_Z = 2;
TETRIS_PIECE_S = 3;
TETRIS_PIECE_Q = 4;
TETRIS_PIECE_RL = 5;
TETRIS_PIECE_T = 6;
TETRIS_PIECE_I = 7;
TYPE
arrpiece = ARRAY[1 .. 4] OF ARRAY[1 .. 4] OF integer;
TTauTetrisPiece = CLASS
PRIVATE
_rep: arrpiece;
_tip: integer;
_x : integer;
_y : integer;
_rot: integer;
PROCEDURE ResetPiece();
PUBLIC
CONSTRUCTOR Create(t: integer);
DESTRUCTOR Destroy(); OVERRIDE;
PROCEDURE Rot(d: integer);
PROCEDURE MoveOffX(a: integer);
PROCEDURE MoveOffY(a: integer);
PROCEDURE SetOffX(a: integer);
PROCEDURE SetOffY(a: integer);
PROCEDURE SetRot(a: integer);
FUNCTION GetTip(): integer;
FUNCTION GetRep(): arrpiece;
FUNCTION GetOffX(): integer;
FUNCTION GetOffY(): integer;
FUNCTION GetRot(): integer;
END;
IMPLEMENTATION
CONSTRUCTOR TTauTetrisPiece.Create(t: integer);
BEGIN
_rot := 0;
_x := 0;
_y := 0;
_tip := t;
CASE t OF
TETRIS_PIECE_L:
BEGIN
_rep[1][1] := 1; _rep[1][2] := 0; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 0; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 1; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
TETRIS_PIECE_RL:
BEGIN
_rep[1][1] := 0; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 0; _rep[2][2] := 1; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 1; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
TETRIS_PIECE_S:
BEGIN
_rep[1][1] := 0; _rep[1][2] := 1; _rep[1][3] := 1; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 1; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
TETRIS_PIECE_Z:
BEGIN
_rep[1][1] := 1; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 0; _rep[2][2] := 1; _rep[2][3] := 1; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
TETRIS_PIECE_I:
BEGIN
_rep[1][1] := 1; _rep[1][2] := 0; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 0; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 1; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
TETRIS_PIECE_Q:
BEGIN
_rep[1][1] := 1; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 1; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
TETRIS_PIECE_T:
BEGIN
_rep[1][1] := 1; _rep[1][2] := 1; _rep[1][3] := 1; _rep[1][4] := 0;
_rep[2][1] := 0; _rep[2][2] := 1; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
END;
END;
DESTRUCTOR TTauTetrisPiece.Destroy();
BEGIN
END;
PROCEDURE TTauTetrisPiece.Rot(d: integer);
BEGIN
_rot := _rot + d;
IF (_rot < 0) THEN
BEGIN
_rot := 3;
END;
IF (_rot > 3) THEN
BEGIN
_rot := 0;
END;
ResetPiece();
END;
PROCEDURE TTauTetrisPiece.ResetPiece();
BEGIN
IF (_tip = TETRIS_PIECE_L) THEN
BEGIN
IF (_rot = 0) THEN
BEGIN
_rep[1][1] := 1; _rep[1][2] := 0; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 0; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 1; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF (_rot = 1) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 0; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 1; _rep[2][3] := 1; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF (_rot = 2) THEN
BEGIN
_rep[1][1] := 1; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 0; _rep[2][2] := 1; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 1; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF (_rot = 3) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 0; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 0; _rep[2][2] := 0; _rep[2][3] := 1; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 1; _rep[3][3] := 1; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
END
ELSE IF (_tip = TETRIS_PIECE_RL) THEN
BEGIN
IF (_rot = 0) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 0; _rep[2][2] := 1; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 1; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF (_rot = 1) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 0; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 0; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 1; _rep[3][3] := 1; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF (_rot = 2) THEN
BEGIN
_rep[1][1] := 1; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 0; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF (_rot = 3) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 0; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 1; _rep[2][3] := 1; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 0; _rep[3][3] := 1; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
END
ELSE IF (_tip = TETRIS_PIECE_T) THEN
BEGIN
IF (_rot = 0) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 0; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 1; _rep[2][3] := 1; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 1; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF (_rot = 1) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 1; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 1; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF (_rot = 2) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 1; _rep[2][3] := 1; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF (_rot = 3) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 0; _rep[2][2] := 1; _rep[2][3] := 1; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 1; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
END
ELSE IF (_tip = TETRIS_PIECE_S) THEN
BEGIN
IF ((_rot = 0) OR (_rot = 2)) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 1; _rep[1][3] := 1; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 1; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF ((_rot = 1) OR (_rot = 3)) THEN
BEGIN
_rep[1][1] := 1; _rep[1][2] := 0; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 1; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 1; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
END
ELSE IF (_tip = TETRIS_PIECE_Z) THEN
BEGIN
IF ((_rot = 0) OR (_rot = 2)) THEN
BEGIN
_rep[1][1] := 1; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 0; _rep[2][2] := 1; _rep[2][3] := 1; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF ((_rot = 1) OR (_rot = 3)) THEN
BEGIN
_rep[1][1] := 0; _rep[1][2] := 1; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 1; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
END
ELSE IF (_tip = TETRIS_PIECE_I) THEN
BEGIN
IF ((_rot = 0) OR (_rot = 2)) THEN
BEGIN
_rep[1][1] := 1; _rep[1][2] := 0; _rep[1][3] := 0; _rep[1][4] := 0;
_rep[2][1] := 1; _rep[2][2] := 0; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 1; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 1; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END
ELSE IF ((_rot = 1) OR (_rot = 3)) THEN
BEGIN
_rep[1][1] := 1; _rep[1][2] := 1; _rep[1][3] := 1; _rep[1][4] := 1;
_rep[2][1] := 0; _rep[2][2] := 0; _rep[2][3] := 0; _rep[2][4] := 0;
_rep[3][1] := 0; _rep[3][2] := 0; _rep[3][3] := 0; _rep[3][4] := 0;
_rep[4][1] := 0; _rep[4][2] := 0; _rep[4][3] := 0; _rep[4][4] := 0;
END;
END
ELSE IF (_tip = TETRIS_PIECE_Q) THEN
BEGIN
END;
END;
PROCEDURE TTauTetrisPiece.MoveOffX(a: integer);
BEGIN
_x := _x + a;
END;
PROCEDURE TTauTetrisPiece.MoveOffY(a: integer);
BEGIN
_y := _y + a;
END;
PROCEDURE TTauTetrisPiece.SetOffX(a: integer);
BEGIN
_x := a;
END;
PROCEDURE TTauTetrisPiece.SetOffY(a: integer);
BEGIN
_y := a;
END;
PROCEDURE TTauTetrisPiece.SetRot(a: integer);
BEGIN
_rot := a;
ResetPiece();
END;
FUNCTION TTauTetrisPiece.GetTip(): integer;
BEGIN
GetTip := _tip;
END;
FUNCTION TTauTetrisPiece.GetRep(): arrpiece;
BEGIN
GetRep := _rep;
END;
FUNCTION TTauTetrisPiece.GetOffX(): integer;
BEGIN
GetOffX := _x;
END;
FUNCTION TTauTetrisPiece.GetOffY(): integer;
BEGIN
GetOffY := _y;
END;
FUNCTION TTauTetrisPiece.GetRot(): integer;
BEGIN
GetRot := _rot;
END;
END.
|
unit Objekt.SendMail;
interface
uses
SysUtils, Classes,
IdMessage, IdPOP3, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase,
IdMessageClient, IdSMTPBase, IdSMTP, Vcl.StdCtrls, IdIOHandler,
IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdGlobal,
IdSASlLogin, IdUserPassProvider;
type
TMailErrorEvent=procedure(Sender: TObject; aError: string) of object;
type
TSendMail = class(TObject)
private
fSmtp: TIdSMTP;
fMsg: TIdMessage;
fIOHandler: TIdSSLIOHandlerSocketOpenSSL;
fMeineEmail: string;
fMeinPasswort: string;
fBetreff: string;
fNachricht: string;
fEMailAdresse: string;
fMeinUsername: string;
fOnMailError: TMailErrorEvent;
fHost: string;
fPort: Integer;
fSSLVersion: Integer;
fAuthType: Integer;
fUseTLS: Integer;
fSASLLogin: TIdSASLLogin;
fUserPassProvider: TIdUserPassProvider;
fOnAfterConnect: TNotifyEvent;
fOnBevorSend: TNotifyEvent;
fOnAfterSend: TNotifyEvent;
fOnBevorConnect: TNotifyEvent;
procedure VersendeEMail;
function IdSMTPAuthenticationType: TIdSMTPAuthenticationType;
function IdSSLVersion: TIdSSLVersion;
function IdUseTLS: TIdUseTLS;
procedure SetSendParam;
public
constructor Create;
destructor Destroy; override;
property MeineEMail: string read fMeineEmail write fMeineEMail;
property MeinPasswort: string read fMeinPasswort write fMeinPasswort;
property MeinUsername: string read fMeinUsername write fMeinUsername;
property Betreff: string read fBetreff write fBetreff;
property Nachricht: string read fNachricht write fNachricht;
property EMailAdresse: string read fEMailAdresse write fEMailAdresse;
property Host: string read fHost write fHost;
property Port: Integer read fPort write fPort;
property OnMailError: TMailErrorEvent read fOnMailError write fOnMailError;
procedure SendenUeberWebDe;
procedure SendenUeberGMail;
procedure SendenUeberExchange;
procedure Senden;
property UseTLS: Integer read fUseTLS write fUseTLS;
property AuthType: Integer read fAuthType write fAuthType;
property SSLVersion: Integer read fSSLVersion write fSSLVersion;
property OnBevorConnect: TNotifyEvent read fOnBevorConnect write fOnBevorConnect;
property OnAfterConnect: TNotifyEvent read fOnAfterConnect write fOnAfterConnect;
property OnBevorSend: TNotifyEvent read fOnBevorSend write fOnBevorSend;
property OnAfterSend: TNotifyEvent read fOnAfterSend write fOnAfterSend;
end;
implementation
{ TSendMail }
uses
VCL.Dialogs;
constructor TSendMail.Create;
begin
inherited;
FSmtp := TIdSMTP.Create(nil);
FMsg := TIdMessage.Create(nil);
FIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
FSmtp.IOHandler := FIOHandler;
FMeineEmail := '';
FMeinPasswort := '';
FBetreff := '';
FNachricht := '';
FEMailAdresse := '';
fHost := '';
fOnMailError := nil;
fPort := 0;
fUseTLS := 0;
fAuthType := 0;
fSSLVersion := 0;
fSASLLogin := nil;
fUserPassProvider := nil;
end;
destructor TSendMail.Destroy;
begin
FreeAndNil(FSmtp);
FreeAndNil(FMsg);
FreeAndNil(FIOHandler);
if fSASLLogin <> nil then
FreeAndNil(fSASLLogin);
if fUserPassProvider <> nil then
FreeAndNil(fUserPassProvider);
inherited;
end;
procedure TSendMail.SendenUeberGMail;
begin
Fsmtp.Host := 'smtp.gmail.com';
Fsmtp.Password := FMeinPasswort;
Fsmtp.Port := 587;
Fsmtp.UseTLS := utUseExplicitTLS;
Fsmtp.Username := FMeineEmail;
FIOHandler.Destination := 'smtp.gmail.com:587';
FIOHandler.Host := 'smtp.gmail.com';
FIOHandler.MaxLineAction := maException;
FIOHandler.Port := 587;
FIOHandler.SSLOptions.Method := ssLvTlSv1;
FIOHandler.SSLOptions.Mode := sslmUnassigned;
FIOHandler.SSLOptions.VerifyMode := [];
FIOHandler.SSLOptions.VerifyDepth := 0;
fsmtp.IOHandler := fIOHandler;
VersendeEMail;
end;
procedure TSendMail.SendenUeberWebDe;
begin
Fsmtp.Host := 'smtp.web.de';
Fsmtp.Password := FMeinPasswort;
Fsmtp.Port := 587;
Fsmtp.UseTLS := utUseExplicitTLS;
Fsmtp.Username := FMeineEmail;
FIOHandler.Destination := 'smtp.web.de:587';
FIOHandler.Host := 'smtp.web.de';
FIOHandler.MaxLineAction := maException;
FIOHandler.Port := 587;
FIOHandler.SSLOptions.Method := ssLvTlSv1;
FIOHandler.SSLOptions.Mode := sslmUnassigned;
FIOHandler.SSLOptions.VerifyMode := [];
FIOHandler.SSLOptions.VerifyDepth := 0;
fsmtp.IOHandler := fIOHandler;
VersendeEMail;
end;
procedure TSendMail.Senden;
begin
Fsmtp.Host := fHost;
Fsmtp.Password := FMeinPasswort;
Fsmtp.Username := FMeinUsername;
Fsmtp.Port := fPort;
Fsmtp.AuthType := IdSMTPAuthenticationType;
Fsmtp.UseTLS := IdUseTLS;
{
fsmtp.SASLMechanisms.Clear;
fIOHandler.MaxLineAction := maException;
fIOHandler.Port := fPort;
fIOHandler.SSLOptions.Method := IdSSLVersion;
fIOHandler.SSLOptions.Mode := sslmUnassigned;
fIOHandler.SSLOptions.VerifyMode := [];
fIOHandler.SSLOptions.VerifyDepth := 0;
}
SetSendParam;
//fsmtp.IOHandler := fIOHandler;
VersendeEMail;
end;
procedure TSendMail.SetSendParam;
begin
fSmtp.SASLMechanisms.Clear;
if (fUseTLS = 0) and (fIOHandler <> nil) then
FreeAndNil(fIOHandler);
if (fUseTLS = 0) and (fIOHandler = nil) then
exit;
if fIOHandler = nil then
fIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
fSmtp.IOHandler := fIOHandler;
TIdSSLIOHandlerSocketOpenSSL(fSmtp.IOHandler).SSLOptions.Method := IdSSLVersion;
fSmtp.UseTLS := IdUseTLS;
fSmtp.AuthType := IdSMTPAuthenticationType;
if IdSMTPAuthenticationType = satSASL then
begin
if fSASLLogin = nil then
fSASLLogin := TIdSASLLogin.Create(nil);
if fUserPassProvider = nil then
fUserPassProvider := TIdUserPassProvider.Create(fSASLLogin);
fSASLLogin.UserPassProvider := fUserPassProvider;
fUserPassProvider.Username := fSmtp.Username;
fUserPassProvider.Password := fSmtp.Password;
fSmtp.SASLMechanisms.Add.SASL := fSASLLogin;
end;
end;
procedure TSendMail.SendenUeberExchange;
begin
//Fsmtp.Host := 'exchange.ass-systemhaus.de';
//Fsmtp.Host := '172.16.10.11';
Fsmtp.Host := fHost;
Fsmtp.Password := FMeinPasswort;
Fsmtp.Username := FMeinUsername;
Fsmtp.Port := 25;
Fsmtp.AuthType := satDefault;
Fsmtp.UseTLS := utNoTLSSupport;
fsmtp.SASLMechanisms.Clear;
FSmtp.IOHandler := nil;
VersendeEMail;
end;
procedure TSendMail.VersendeEMail;
begin
FMsg.From.Address := FMeineEmail;
FMsg.Recipients.EMailAddresses := FEMailAdresse;
FMsg.Body.Add(FNachricht);
FMsg.Subject := FBetreff;
try
if Assigned(fOnBevorConnect) then
fOnBevorConnect(Self);
Fsmtp.Connect;
if Assigned(fOnAfterConnect) then
fOnAfterConnect(Self);
//if IdSMTPAuthenticationType = satSASL then
// fSmtp.Authenticate;
//if not fsmtp.Authenticate then
// MessageDlg('Autenticate fehlgeschlagen', mtError, [mbOk], 0);
if Assigned(fOnBevorSend) then
fOnBevorSend(Self);
Fsmtp.Send(FMsg);
if Assigned(fOnAfterSend) then
fOnAfterSend(Self);
Fsmtp.Disconnect;
except
on E: Exception do
begin
if Assigned(fOnMailError) then
fOnMailError(Self, e.Message);
end;
end;
end;
function TSendMail.IdSMTPAuthenticationType: TIdSMTPAuthenticationType;
begin
Result := satDefault;
case fAuthType of
0 : Result := satNone;
1 : Result := satDefault;
2 : Result := satSASL;
end;
end;
function TSendMail.IdSSLVersion: TIdSSLVersion;
begin
Result := sslvTLSv1;
case fSSLVersion of
0: Result := sslvSSLv2;
1: Result := sslvSSLv23;
2: Result := sslvSSLv3;
3: Result := sslvTLSv1;
4: Result := sslvTLSv1_1;
5: Result := sslvTLSv1_2;
end;
end;
function TSendMail.IdUseTLS: TIdUseTLS;
begin
Result := utUseExplicitTLS;
case fUseTLS of
0: Result := utNoTLSSupport;
1: Result := utUseImplicitTLS;
2: Result := utUseRequireTLS;
3: Result := utUseExplicitTLS;
end;
end;
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils,
VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes,
VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps, Vcl.ExtCtrls,
Vcl.DBCtrls, Data.DB, AdvGlowButton, Modules.Database, System.Generics.Collections, Classes.StormTrack;
type
TFrmMain = class(TForm)
Panel1: TPanel;
cbYears: TDBLookupComboBox;
cbStorms: TDBLookupComboBox;
btnShow: TAdvGlowButton;
dsYears: TDataSource;
dsNames: TDataSource;
Map: TTMSFNCMaps;
procedure cbYearsClick(Sender: TObject);
procedure btnShowClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FTrack: TObjectList<TStormTrack>;
FDbController: TDbController;
procedure ShowTrack( AId: String );
function ColorForSpeed( ASpeed: Integer ):TColor;
public
{ Public declarations }
property DbController: TDbController read FDbController write FDbController;
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
procedure TFrmMain.btnShowClick(Sender: TObject);
begin
ShowTrack( cbStorms.KeyValue );
end;
procedure TFrmMain.cbYearsClick(Sender: TObject);
begin
DbController.OpenStorms( cbYears.KeyValue );
end;
function TFrmMain.ColorForSpeed(ASpeed: Integer): TColor;
begin
if ASpeed >= 157 then
begin
Result := RGB(255,96,96);
end
else
begin
if ASpeed >= 130 then
begin
Result := RGB( 255, 143, 32 );
end
else
begin
if ASpeed >= 111 then
begin
Result := RGB( 255, 193, 64 );
end
else
begin
if ASpeed >= 96 then
begin
Result := RGB( 255, 231, 117 );
end
else
begin
if ASpeed >= 74 then
begin
Result := RGB( 255,255,204);
end
else
begin
Result := RGB(200,253,253);
end;
end;
end;
end;
end;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
FTrack := TObjectList<TStormTrack>.Create;
FDbController := TDbController.Create(nil);
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
begin
FTrack.Free;
FDbController.Free;
end;
procedure TFrmMain.ShowTrack(AId: String);
var
LPoly: TTMSFNCMapsPolyline;
LCoords: TTMSFNCMapsCoordinateRecArray;
LTrackItem: TStormTrack;
LLastColor,
LColor: TColor;
LSpeed:Integer;
begin
// just coordinates
FTrack.Clear;
DbController.GetTrack( AId, FTrack );
Map.BeginUpdate;
try
Map.Clear;
SetLength( LCoords, 2 );
LCoords[0].Latitude := 0;
LCoords[0].Longitude := 0;
LLastColor := RGB(200,253,253);
for LTrackItem in FTrack do
begin
LCoords[1].Latitude := LCoords[0].Latitude;
LCoords[1].Longitude := LCoords[0].Longitude;
LCoords[0].Latitude := LTrackItem.Latitude;
LCoords[0].Longitude := LTrackItem.Longitude;
if (LCoords[1].Longitude <> 0) AND (LCoords[1].Latitude <> 0) then
begin
LPoly := Map.AddPolyline(LCoords, False);
LSpeed := LTrackItem.Wind;
if LSpeed > 0 then
begin
LColor := ColorForSpeed( LSpeed );
end
else
begin
LColor := LLastColor;
end;
LPoly.StrokeColor := LColor;
LPoly.StrokeOpacity := 1;
LPoly.StrokeWidth := 5;
LPoly.DataObject := LTrackItem;
LLastColor := LColor;
end;
end;
Map.ZoomToBounds( CreateBounds( Map.Polylines.ToCoordinateArray ) );
finally
Map.EndUpdate;
end;
end;
end.
|
unit PmHelper;
// CBcdStr: 显示的BCD字符串,1字节显示为2个字符
// BcdStr: 内部的BCD字符串,1字节2位
// CStr: 显示的字符串,1字节显示为2个字符
// BinStr: 内部的字符串
interface
uses
SysUtils, DateUtils;
type
TPmData16 = class
private
FMinute: Byte;
FDay: Byte;
FHour: Byte;
FSecond: Byte;
function GetValue: AnsiString;
procedure SetValue(const Value: AnsiString);
procedure SetDay(const Value: Byte);
procedure SetHour(const Value: Byte);
procedure SetMinute(const Value: Byte);
procedure SetSecond(const Value: Byte);
public
property Value: AnsiString read GetValue write SetValue;
property Day: Byte read FDay write SetDay;
property Hour: Byte read FHour write SetHour;
property Minute: Byte read FMinute write SetMinute;
property Second: Byte read FSecond write SetSecond;
procedure SetTime(const dt: TDateTime);
function CStr: AnsiString;
end;
implementation
uses uBCDHelper;
{ TPmData16 }
function TPmData16.CStr: AnsiString;
begin
Result := IntToStr(self.FDay)+'日'+IntToStr(self.FHour)+'时'+
IntToStr(self.FMinute)+'分'+IntToStr(self.FSecond)+'秒';
end;
function TPmData16.GetValue: AnsiString;
begin
Result := TBcdHelper.Int2BCDString(FSecond,1)+
TBcdHelper.Int2BCDString(FMinute,1)+
TBcdHelper.Int2BCDString(FHour,1)+
TBcdHelper.Int2BCDString(Day,1);
end;
procedure TPmData16.SetDay(const Value: Byte);
begin
FDay := Value;
end;
procedure TPmData16.SetHour(const Value: Byte);
begin
FHour := Value;
end;
procedure TPmData16.SetMinute(const Value: Byte);
begin
FMinute := Value;
end;
procedure TPmData16.SetSecond(const Value: Byte);
begin
FSecond := Value;
end;
procedure TPmData16.SetTime(const dt: TDateTime);
var
AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond :word;
begin
DecodeDateTime(dt, AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond);
FDay := Aday;
FHour := AHour;
FMinute := AMinute;
FSecond :=ASecond;
end;
procedure TPmData16.SetValue(const Value: AnsiString);
begin
if Length(Value)=4 then
begin
FSecond := TBcdHelper.Bcd2Int(Copy(Value,1,1));
FMinute := TBcdHelper.Bcd2Int(Copy(Value,2,1));
FHour := TBcdHelper.Bcd2Int(Copy(Value,3,1));
FDay := TBcdHelper.Bcd2Int(Copy(Value,4,1));
end
else
raise Exception.Create('Data_16数据格式必须为4字节');
end;
end.
|
unit Render;
interface
uses Windows, dglOpenGL, RenderEnvironment, BasicFunctions;
type
TRender = class
private
FPSCap : longword;
FirstRC : HGLRC;
ShaderDirectory: string;
FIsOpenCLAllowed, FEnableOpenCL: boolean;
// Misc
procedure ForceFPS;
public
Environment: PRenderEnvironment;
// Constructors;
constructor Create(const _ShaderDirectory: string);
destructor Destroy; override;
procedure ClearAllEnvironments;
// Render
procedure Render;
// Sets
procedure SetFPS(_FPS: longword);
procedure SetEnableOpenCL(_value: boolean);
// Adds and Removes.
function AddEnvironment(_Handle : THandle; _width, _height : longword): PRenderEnvironment;
procedure RemoveEnvironment(var _Environment: PRenderEnvironment);
// Properties
property IsOpenCLAllowed: boolean read FIsOpenCLAllowed;
property EnableOpenCL: boolean read FEnableOpenCL write SetEnableOpenCL;
end;
implementation
uses OpenCLLauncher;
constructor TRender.Create(const _ShaderDirectory: string);
var
OCL: TOpenCLLauncher;
begin
InitOpenGL;
FirstRC := 0;
ShaderDirectory := CopyString(_ShaderDirectory);
Environment := nil;
// OpenCL support starts here
try
OCL := TOpenCLLauncher.Create;
OCL.Free;
FIsOpenCLAllowed := true;
except;
FIsOpenCLAllowed := false;
end;
FEnableOpenCL := FIsOpenCLAllowed;
end;
destructor TRender.Destroy;
begin
ClearAllEnvironments;
inherited Destroy;
end;
// Sets
procedure TRender.SetFPS(_FPS: longword);
begin
FPSCap := _FPS;
ForceFPS;
end;
procedure TRender.SetEnableOpenCL(_value: boolean);
begin
FEnableOpenCL := _value and FIsOpenCLAllowed;
end;
// Adds
function TRender.AddEnvironment(_Handle : THandle; _width, _height : longword): PRenderEnvironment;
var
NewEnvironment,CurrentEnvironment : PRenderEnvironment;
begin
new(NewEnvironment);
NewEnvironment^ := TRenderEnvironment.Create(_Handle,FirstRC,_width,_height,ShaderDirectory);
if Environment = nil then
begin
Environment := NewEnvironment;
FirstRC := NewEnvironment^.RC;
end
else
begin
CurrentEnvironment := Environment;
while CurrentEnvironment^.Next <> nil do
CurrentEnvironment := CurrentEnvironment^.Next;
CurrentEnvironment^.Next := NewEnvironment;
end;
ForceFPS;
Result := NewEnvironment;
end;
// Removes
procedure TRender.RemoveEnvironment(var _Environment : PRenderEnvironment);
var
PreviousEnvironment : PRenderEnvironment;
begin
if Environment = nil then exit; // Can't delete from an empty list.
if _Environment <> nil then
begin
// Check if it is the first element.
if _Environment = Environment then
begin
Environment := _Environment^.Next;
if Environment <> nil then
begin
FirstRC := Environment^.RC;
end
else
begin
FirstRC := 0;
end;
end
else // It could be inside the list, but it's not the first.
begin
PreviousEnvironment := Environment;
while (PreviousEnvironment^.Next <> nil) and (PreviousEnvironment^.Next <> _Environment) do
begin
PreviousEnvironment := PreviousEnvironment^.Next;
end;
if PreviousEnvironment^.Next = _Environment then
begin
PreviousEnvironment^.Next := _Environment^.Next;
end
else // nil -- not from this list.
exit;
end;
// If it has past this stage, the element is valid and was part of the list.
// Now we dispose the camera.
_Environment^.Free;
_Environment := nil;
end;
end;
procedure TRender.ClearAllEnvironments;
var
MyEnvironment,NextEnvironment : PRenderEnvironment;
begin
MyEnvironment := Environment;
while MyEnvironment <> nil do
begin
NextEnvironment := MyEnvironment^.Next;
RemoveEnvironment(MyEnvironment);
MyEnvironment := NextEnvironment;
end;
end;
procedure TRender.Render;
var
CurrentEnv : PRenderEnvironment;
begin
CurrentEnv := Environment;
while CurrentEnv <> nil do
begin
CurrentEnv^.Render;
CurrentEnv := CurrentEnv^.Next;
end;
end;
// Misc
procedure TRender.ForceFPS;
var
Frequency: int64;
DesiredTimeRate : int64;
CurrentEnv : PRenderEnvironment;
begin
QueryPerformanceFrequency(Frequency); // get high-resolution Frequency
DesiredTimeRate := Round(Frequency / FPSCap);
CurrentEnv := Environment;
while CurrentEnv <> nil do
begin
CurrentEnv^.DesiredTimeRate := DesiredTimeRate;
CurrentEnv := CurrentEnv^.Next;
end;
end;
end.
|
{*************************************************************
Author: Stéphane Vander Clock (SVanderClock@Arkadia.com)
www: http://www.arkadia.com
EMail: SVanderClock@Arkadia.com
product: Common RFC functions
Version: 3.05
Description: Common functions to work with RFC standards. especialy
to convert RFC date time string to TDateTime.
Legal issues: Copyright (C) 1999-2005 by Arkadia Software Engineering
This software is provided 'as-is', without any express
or implied warranty. In no event will the author be
held liable for any damages arising from the use of
this software.
Permission is granted to anyone to use this software
for any purpose, including commercial applications,
and to alter it and redistribute it freely, subject
to the following restrictions:
1. The origin of this software must not be
misrepresented, you must not claim that you wrote
the original software. If you use this software in
a product, an acknowledgment in the product
documentation would be appreciated but is not
required.
2. Altered source versions must be plainly marked as
such, and must not be misrepresented as being the
original software.
3. This notice may not be removed or altered from any
source distribution.
4. You must register this software by sending a picture
postcard to the author. Use a nice stamp and mention
your name, street address, EMail address and any
comment you like to say.
Know bug :
History :
Link : http://www.rfc.net/
Please send all your feedback to SVanderClock@Arkadia.com
**************************************************************}
unit AlFcnRFC;
interface
uses Windows,
Classes;
function ALGmtDateTimeToRfc822Str(const aValue: TDateTime): String;
function ALDateTimeToRfc822Str(const aValue: TDateTime): String;
Function ALTryRfc822StrToGMTDateTime(const S: string; out Value: TDateTime): Boolean;
function ALRfc822StrToGMTDateTime(const s: String): TDateTime;
const
CAlRfc822DaysOfWeek: array[1..7] of string = (
'Sun',
'Mon',
'Tue',
'Wed',
'Thu',
'Fri',
'Sat'
);
CALRfc822MonthNames: array[1..12] of string = (
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
);
implementation
Uses SYsUtils,
SysConst,
AlFcnString;
{*********************************************************************}
{aValue is a GMT TDateTime - result is "Sun, 06 Nov 1994 08:49:37 GMT"}
function ALGMTDateTimeToRfc822Str(const aValue: TDateTime): String;
var aDay, aMonth, aYear: Word;
begin
DecodeDate(
aValue,
aYear,
aMonth,
aDay
);
Result := Format(
'%s, %.2d %s %.4d %s %s',
[
CAlRfc822DaysOfWeek[DayOfWeek(aValue)],
aDay,
CAlRfc822MonthNames[aMonth],
aYear,
FormatDateTime('hh":"nn":"ss', aValue),
'GMT'
]
);
end;
{***********************************************************************}
{aValue is a Local TDateTime - result is "Sun, 06 Nov 1994 08:49:37 GMT"}
function ALDateTimeToRfc822Str(const aValue: TDateTime): String;
{--------------------------------------------}
function InternalCalcTimeZoneBias : TDateTime;
const Time_Zone_ID_DayLight = 2;
var TZI: TTimeZoneInformation;
TZIResult: Integer;
aBias : Integer;
begin
TZIResult := GetTimeZoneInformation(TZI);
if TZIResult = -1 then Result := 0
else begin
if TZIResult = Time_Zone_ID_DayLight then aBias := TZI.Bias + TZI.DayLightBias
else aBias := TZI.Bias + TZI.StandardBias;
Result := EncodeTime(Abs(aBias) div 60, Abs(aBias) mod 60, 0, 0);
if aBias < 0 then Result := -Result;
end;
end;
begin
Result := ALGMTDateTimeToRfc822Str(aValue + InternalCalcTimeZoneBias);
end;
{************************************************************}
{Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
the function allow also date like "Sun, 06-Nov-1994 08:49:37 GMT"
to be compatible with cookies field (http://wp.netscape.com/newsref/std/cookie_spec.html)}
Function ALTryRfc822StrToGMTDateTime(const S: string; out Value: TDateTime): Boolean;
Var P: Integer;
ADateStr : String;
aLst: TstringList;
aMonthLabel: String;
aFormatSettings: TformatSettings;
{----------------------------------------------------------}
Function MonthWithLeadingChar(const AMonth: String): String;
Begin
If Length(AMonth) = 1 then result := '0' + AMonth
else result := aMonth;
end;
Begin
ADateStr := S; //'Wdy, DD-Mon-YYYY HH:MM:SS GMT'
P := AlPos(', ',ADateStr);
If P > 0 then delete(ADateStr,1,P + 1) //'DD-Mon-YYYY HH:MM:SS GMT'
else Begin
Result := False;
Exit;
end;
ADateStr := trim(
AlStringReplace(
ADateStr,
' GMT',
'',
[RfIgnoreCase]
)
); //'DD-Mon-YYYY HH:MM:SS'
ADateStr := AlStringReplace(ADateStr, '-', ' ',[RfReplaceall]); //'DD Mon YYYY HH:MM:SS'
While Alpos(' ',ADateStr) > 0 do ADateStr := AlStringReplace(ADateStr,' ',' ',[RfReplaceAll]); //'DD Mon YYYY HH:MM:SS'
Alst := TstringList.create;
Try
Alst.Text := AlStringReplace(ADateStr,' ',#13#10,[RfReplaceall]);
If Alst.Count <> 4 then begin
Result := False;
Exit;
end;
aMonthLabel := trim(Alst[1]);
P := 1;
While (p <= 12) and (not sameText(CAlRfc822MonthNames[P],aMonthLabel)) do inc(P);
If P > 12 then begin
Result := False;
Exit;
end;
ADateStr := trim(Alst[0]) + '/' + MonthWithLeadingChar(inttostr(P)) + '/' + trim(Alst[2]) + ' ' + trim(Alst[3]); //'DD/MM/YYYY HH:MM:SS'
GetLocaleFormatSettings(GetSystemDefaultLCID,aFormatSettings);
aFormatSettings.DateSeparator := '/';
aFormatSettings.TimeSeparator := ':';
aFormatSettings.ShortDateFormat := 'dd/mm/yyyy';
aFormatSettings.ShortTimeFormat := 'hh:nn:zz';
Result := TryStrToDateTime(ADateStr,Value,AformatSettings);
finally
aLst.free;
end;
end;
{*************************************************************}
{Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
the function allow also date like "Sun, 06-Nov-1994 08:49:37 GMT"
to be compatible with cookies field (http://wp.netscape.com/newsref/std/cookie_spec.html)}
function ALRfc822StrToGMTDateTime(const s: String): TDateTime;
Begin
if not ALTryRfc822StrToGMTDateTime(S, Result) then
raise EConvertError.CreateResFmt(@SInvalidDateTime, [S]);
end;
end.
|
//*******************************************************************************************************
// 哈尔滨新中新电子股份有限公司版权所有,2003.6
//
// TPEAPI.H
//
// 第三方接口(TPE) 函数和数据结构定义
//
// For( Delphi) 2003.11.04
//
//*******************************************************************************************************
unit tpeapi;
interface
type
//紧缩结构编译
{$A-}
//*******************************************************************************************************************
//类型定义
UINT = Cardinal ;
LINT = int64;
LONG = integer;
TArrayTime = Array[0..13] of char;
TArrayName = Array[0..15] of char;
TArrayPersonID = Array[0..17] of char;
TArrayPassword = Array[0..7 ] of BYTE;
TArrayAccessControl = Array[0..15] of BYTE;
TArrayCertCode = Array[0..17] of char;
TArrayCreditCardNo = Array[0..23] of char;
TArrayTel = Array[0..47] of char;
TArrayEmail = Array[0..47] of char;
TArrayPostalCode = Array[0..5 ] of char;
TArrayPostalAddr = Array[0..99] of char;
TArrayFileName = Array[0..15] of char;
//*******************************************************************************************************************
//白名单通知
tagWhiteListCallBack = record
AccountNo : UINT ; //帐号
CardNo : UINT ; //卡号
Condition : UINT ; //状态
Balance : LONG ; //余额
Depart : LINT ; //部门
Identi : WORD ; //身份
end;
PtagWhiteListCallBack = ^ tagWhiteListCallBack;
//白名单
tagWhiteListRec = record
AccountNo : UINT ; //帐号
CardNo : UINT ; //卡号
Condition : UINT ; //状态
Balance : LONG ; //余额
Depart : LINT ; //部门
Identi : WORD ; //身份
Sign : BYTE ; //签名
end;
PtagWhiteListRec = ^tagWhiteListRec;
//流水通知结构
tagNodeNotifyInfo = record
CurrentCentralNo :UINT ;
end;
PtagNodeNotifyInfo = ^tagNodeNotifyInfo;
//流水通知应答
tagNodeNotifyInfoRes = record
NotiyfWait : UINT ;
end;
PtagNodeNotifyInfoRes = ^ tagNodeNotifyInfoRes;
//**************************************************调帐*****************************************************************
//基本帐户调帐申请
tagTPE_GetAccountReq = record
//按帐号.卡号
AccountNo : UINT;
CardNo : UINT;
//是否需要密码
reqflagPassword : BYTE;
Password : TArrayPassword ;
//返回标志
resflagAccountNo : BYTE;
resflagCardNo : BYTE;
resflagCondition : BYTE;
resflagBalance : BYTE;
resflagCreateTime : BYTE;
resflagExpireDate : BYTE;
resflagName : BYTE;
resflagPersonID : BYTE;
resflagPassword : BYTE;
resflagAccessControl : BYTE;
resflagBirthday : BYTE;
resflagDepart : BYTE;
resflagIdenti : BYTE;
resflagNation : BYTE;
resflagCertType : BYTE;
resflagCertCode : BYTE;
resflagCreditCardNo : BYTE;
resflagTransferLimit : BYTE;
resflagTransferMoney : BYTE;
resflagTel : BYTE;
resflagEmail : BYTE;
resflagPostalCode : BYTE;
resflagPostalAddr : BYTE;
resflagFile : BYTE;
resflagComment : BYTE;
resflagExtend : BYTE;
resflagUpdateTime : BYTE;
END;
PtagTPE_GetAccountReq = ^tagTPE_GetAccountReq;
//基本帐户调帐应答
tagTPE_GetAccountRes = record
RetValue : integer; //返回值
AccountNo : UINT ; //帐号
CardNo : UINT ; //卡号
Condition : UINT ; //状态
Balance : LONG ; //余额
CreateTime : TArrayTime; //开户时间
ExpireDate : TArrayTime; //有效期
Name : TArrayName; //姓名
PersonID : TArrayPersonID; //身份证号
Password : TArrayPassword; //密码
AccessControl : TArrayAccessControl;//访问控制
Birthday : TArrayTime; //出生时间
Depart : LINT; //部分编号
Identi : WORD ; //身份编号
Nation : WORD ; //民族编号
CertType : BYTE ; //证件类型
CertCode : TArrayCertCode; //证件号码
CreditCardNo : TArrayCreditCardNo; //银行卡号
TransferLimit : LONG ; //转帐限额
TransferMoney : LONG ; //转帐金额
Tel : TArrayTel; //电话
Email : TArrayEmail; //email
PostalCode : TArrayPostalCode; //邮政编码
PostalAddr : TArrayPostalAddr; //邮政通信地址
FileNamePicture : TArrayFileName ; //照片文件名称
FileNameFinger : TArrayFileName ; //指纹
FileNameAudio : TArrayFileName ; //声音
Comment : array[0..119] of char;//注释
ExtendLen : integer; //扩展信息长度
Extend : Array[0..254] of byte;//扩展信息
UpdateTime : TArrayTime; //最后更新时刻
end;
PtagTPE_GetAccountRes = ^tagTPE_GetAccountRes;
//对应关系调帐申请
tagTPE_GetRelationReq = record
JoinNode : UINT ; //节点
JoinCardHolder : Array[0..23] of char; //对应关系卡/帐号
reqflagJoinPassword : BYTE; //密码标志
JoinPassword : Array[0..7 ] of BYTE; //对应关系密码
//返回标志
resflagAccountNo : BYTE;
resflagCardNo : BYTE;
resflagCondition : BYTE;
resflagBalance : BYTE;
resflagCreateTime : BYTE;
resflagExpireDate : BYTE;
resflagName : BYTE;
resflagPersonID : BYTE;
resflagPassword : BYTE;
resflagAccessControl : BYTE;
resflagBirthday : BYTE;
resflagDepart : BYTE;
resflagIdenti : BYTE;
resflagNation : BYTE;
resflagCertType : BYTE;
resflagCertCode : BYTE;
resflagCreditCardNo : BYTE;
resflagTransferLimit : BYTE;
resflagTransferMoney : BYTE;
resflagTel : BYTE;
resflagEmail : BYTE;
resflagPostalCode : BYTE;
resflagPostalAddr : BYTE;
resflagFile : BYTE;
resflagComment : BYTE;
resflagExtend : BYTE;
resflagUpdateTime : BYTE;
resflagJoinIndex : BYTE;
resflagJoinNode : BYTE;
resflagJoinCardHolder: BYTE;
resflagJoinPassword : BYTE;
resflagJoinCondition : BYTE;
resflagJoinComment : BYTE;
resflagJoinUpdateTime: BYTE;
end;
PtagTPE_GetRelationReq = ^tagTPE_GetRelationReq;
//对应关系调帐应答
tagTPE_GetRelationRes = record
RetValue : integer;
AccountNo : UINT;
CardNo : UINT;
Condition : UINT;
Balance : LONG;
CreateTime : TArrayTime;
ExpireDate : TArrayTime;
Name : TArrayName;
PersonID : TArrayPersonID;
Password : TArrayPassword;
AccessControl : TArrayAccessControl;
Birthday : TArrayTime;
Depart : LINT ;
Identi : WORD;
Nation : WORD;
CertType : BYTE;
CertCode : TArrayCertCode;
CreditCardNo : TArrayCreditCardNo;
TransferLimit : LONG;
TransferMoney : LONG;
Tel : TArrayTel;
Email : TArrayEmail;
PostalCode : TArrayPostalCode;
PostalAddr : TArrayPostalAddr;
FileNamePicture : TArrayFileName;
FileNameFinger : TArrayFileName;
FileNameAudio : TArrayFileName;
Comment : Array[0..119] of char;
ExtendLen : integer;
Extend : Array[0..254] of byte;
UpdateTime : TArrayTime;
JoinIndex : UINT ; //帐号
JoinNode : UINT ; //节点号
JoinCardHolder : Array[0..23] of char; //对应关系帐.卡号
JoinPassword : TArrayPassword; //对应关系密码
JoinCondition : UINT; //对应关系帐户状态
JoinComment : Array[0..119] of char; //注释
JoinUpdateTime : TArrayTime; //最后更新时刻
end;
PtagTPE_GetRelationRes = ^tagTPE_GetRelationRes;
//******************************************************查询*************************************************************
//标准帐户查询
tagTPE_QueryStdAccountReq = record
reqflagAccountNoRange : byte;
reqflagCondition : byte;
reqflagBalanceRange : byte;
reqflagCreateTimeRange: byte;
reqflagExpireDateRange: byte;
reqflagName : byte;
reqflagPersonID : byte;
reqflagBirthdayRange : byte;
reqflagDepart : byte;
reqflagIdenti : byte;
reqflagNation : byte;
reqflagTel : byte;
reqflagEmail : byte;
AccountNoRange : Array[0.. 1] of UINT;
Condition : Array[0.. 1] of UINT;
BalanceRange : Array[0.. 1] of LONG;
CreateTimeRange : Array[0..27] of char;
ExpireDateRange : Array[0..27] of char;
Name : TArrayName;
PersonID : TArrayPersonID;
BirthdayRange : Array[0..27] of char;
Depart : LINT ;
Identi : WORD ;
Nation : WORD ;
Tel : TArrayTel;
Email : TArrayEmail;
//返回标志
resflagCardNo : BYTE;
resflagCondition : BYTE;
resflagBalance : BYTE;
resflagCreateTime : BYTE;
resflagExpireDate : BYTE;
resflagName : BYTE;
resflagPersonID : BYTE;
resflagPassword : BYTE;
resflagAccessControl : BYTE;
resflagBirthday : BYTE;
resflagDepart : BYTE;
resflagIdenti : BYTE;
resflagNation : BYTE;
resflagCertType : BYTE;
resflagCertCode : BYTE;
resflagCreditCardNo : BYTE;
resflagTransferLimit : BYTE;
resflagTransferMoney : BYTE;
resflagTel : BYTE;
resflagEmail : BYTE;
resflagPostalCode : BYTE;
resflagPostalAddr : BYTE;
resflagFile : BYTE;
resflagComment : BYTE;
resflagExtend : BYTE;
resflagUpdateTime : BYTE;
end;
PtagTPE_QueryStdAccountReq = ^tagTPE_QueryStdAccountReq;
//通用帐户查询应答控制结构体
tagTPE_QueryResControl = record
ResRecCount : integer;
pRes : pointer;
end;
PtagTPE_QueryResControl = ^tagTPE_QueryResControl;
//通用帐户查询返回记录
tagTPE_QueryStdAccountRes = tagTPE_GetAccountRes;
//通用查询
tagTPE_QueryGeneralAccountReq = record
SQL : Array[0..4095] of char;
//返回标志
resflagCardNo : BYTE;
resflagCondition : BYTE;
resflagBalance : BYTE;
resflagCreateTime : BYTE;
resflagExpireDate : BYTE;
resflagName : BYTE;
resflagPersonID : BYTE;
resflagBirthday : BYTE;
resflagDepart : BYTE;
resflagIdenti : BYTE;
resflagNation : BYTE;
resflagCertType : BYTE;
resflagCertCode : BYTE;
resflagCreditCardNo : BYTE;
resflagTransferLimit: BYTE;
resflagTransferMoney: BYTE;
resflagTel : BYTE;
resflagEmail : BYTE;
resflagPostalCode : BYTE;
resflagPostalAddr : BYTE;
resflagFile : BYTE;
resflagComment : BYTE;
resflagExtend : BYTE;
resflagUpdateTime : BYTE;
end;
PtagTPE_QueryGeneralAccountReq = ^tagTPE_QueryGeneralAccountReq;
tagTPE_QueryGeneralAccountRes = tagTPE_QueryStdAccountRes;
PtagTPE_QueryGeneralAccountRes= ^tagTPE_QueryGeneralAccountRes;
//查询对应关系
tagTPE_QueryRelationReq = record
reqflagRangeJoinIndex : byte;
reqflagJoinNode : byte;
reqflagRangeJoinCardHolder : byte;
reqfalgRangeJoinCondition : byte;
RangeJoinIndex : Array[0..1] of UINT;
JoinNode : UINT;
RangeJoinCardHolder : Array[0..1,0..23] of char;
RangeJoinCondition : Array[0..1] of UINT;
//返回标志
resflagJoinIndex : byte;
resflagJoinNode : byte;
resflagJoinCardHolder : byte;
resflagJoinPassword : byte;
resflagJoinCondition : byte;
resflagJoinComment : byte;
resflagJoinUpdateTime : byte;
end;
PtagTPE_QueryRelationReq = ^tagTPE_QueryRelationReq;
//查询对应关系应答
tagTPE_QueryRelationRes = record
RetValue : integer;
JoinIndex : UINT ;
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char;
JoinPassword : TArrayPassword;
JoinCondition : UINT;
JoinComment : Array[0..119] of char;
JoinUpdateTime : TArrayTime;
end;
PtagTPE_QueryRelationRes = ^tagTPE_QueryRelationRes;
//**********************************************************入帐*********************************************************
// tagTPE_FlowNetLog = record //检索一个人的优先级:帐号>卡号>对应关系,过渡条件:帐号=0-->卡号=0-->对应
//入帐流水应答
tagTPE_FlowRes = record
RecordError : INTEGER ;
CenterNo : UINT ;
OccurNode : UINT ;
OccurIdNo : UINT ;
OccurInfo : UINT ;
end;
PtagTPE_FlowRes = ^tagTPE_FlowRes;
//建立对应关系
tagTPE_FlowBuildRelationReq = record
OccurIdNo : UINT;
OccurTime : TArrayTime;
TranOper : WORD ;
AccountNo : UINT ;
CardNo : UINT ;
reqflagJoinPassword : byte;
reqflagJoinCondition: byte;
reqflagJoinComment : byte;
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char;
JoinPassword : TArrayPassword;
JoinCondition : UINT ;
JoinComment : Array[0..119] of char;
end;
PtagTPE_FlowBuildRelationReq = ^tagTPE_FlowBuildRelationReq;
tagTPE_FlowBuildRelationRes = tagTPE_FlowRes;
PtagTPE_FlowBuildRelationRes = ^tagTPE_FlowBuildRelationRes;
//取消对应关系
tagTPE_FlowCancelRelationReq = record
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char;
end;
PtagTPE_FlowCancelRelationReq = ^tagTPE_FlowCancelRelationReq;
tagTPE_FlowCancelRelationRes = tagTPE_FlowRes;
PtagTPE_FlowCancelRelationRes = ^ tagTPE_FlowCancelRelationRes;
//挂失/解挂
tagTPE_LostReq = record
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
ReqAccountNo : UINT ;
ReqCardNo : UINT ;
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char;
Operation : BYTE; //1 挂失, 2 解挂
end;
PtagTPE_LostReq = ^tagTPE_LostReq;
tagTPE_LostRes = tagTPE_FlowRes;
PtagTPE_LostRes = ^tagTPE_LostRes;
//入帐----更新基本帐户申请
tagTPE_FlowUpdateAccountReq = record
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
ReqAccountNo : UINT ;
ReqCardNo : UINT ;
JoinNode : UINT ;
JoinCardHolder : Array [0..23] of char;
reqflagCardNo : BYTE;
reqflagCondition : BYTE;
reqflagExpireDate : BYTE;
reqflagName : BYTE;
reqflagPersonID : BYTE;
reqflagPassword : BYTE;
reqflagAccessControl : BYTE;
reqflagBirthday : BYTE;
reqflagDepart : BYTE;
reqflagIdenti : BYTE;
reqflagNation : BYTE;
reqflagCertType : BYTE;
reqflagCertCode : BYTE;
reqflagCreditCardNo : BYTE;
reqflagTransferLimit : BYTE;
reqflagTransferMoney : BYTE;
reqflagTel : BYTE;
reqflagEmail : BYTE;
reqflagPostalCode : BYTE;
reqflagPostalAddr : BYTE;
reqflagComment : BYTE;
reqflagExtend : BYTE;
CardNo : UINT ;
Condition : Array[0..1] of UINT ;
ExpireDate : TArrayTime;
Name : TArrayName;
PersonID : TArrayPersonID;
Password : TArrayPassword;
AccessControl : TArrayAccessControl;
Birthday : TArrayTime;
Depart : LINT;
Identi : WORD ;
Nation : WORD ;
CertType : BYTE ;
CertCode : TArrayCertCode;
CreditCardNo : TArrayCreditCardNo;
TransferLimit : LONG ;
TransferMoney : LONG ;
Tel : TArrayTel;
Email : TArrayEmail;
PostalCode : TArrayPostalCode;
PostalAddr : TArrayPostalAddr;
Comment : Array[0..119] of char;
ExtendLen : integer;
Extend : Array[0..254] of char;
end;
PtagTPE_FlowUpdateAccountReq = ^tagTPE_FlowUpdateAccountReq;
tagTPE_FlowUpdateAccountRes = tagTPE_FlowRes ;
PtagTPE_FlowUpdateAccountRes = ^tagTPE_FlowUpdateAccountRes;
//入帐----更新对应关系申请
tagTPE_FlowUpdateRelationReq = record
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char;
reqflagJoinPassword : byte;
reqflagJoinCondition : byte;
reqflagJoinComment : byte;
JoinPassword : TArrayPassword;
JoinCondition : Array[0..1] of UINT;
JoinComment : Array[0..119] of char;
end;
PtagTPE_FlowUpdateRelationReq = ^tagTPE_FlowUpdateRelationReq;
tagTPE_FlowUpdateRelationRes = tagTPE_FlowRes;
PtagTPE_FlowUpdateRelationRes = tagTPE_FlowUpdateRelationRes;
//入帐----余额变更申请
tagTPE_FlowCostReq = record
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
CostType : WORD ;
AccountNo : UINT ;
CardNo : UINT ;
JoinNode : UINT ;
JoinCardHolder : Array[0..23]of char;
TransMoney : LONG ;
LinkOccurNode : UINT ; //只有FLOW_TYPE_BALANCEEXTRA时有效
LinkOccurIdNo : UINT ;
ExtraInfoLen : integer;
ExtraInfo : Array[0..1199] of byte;
end;
PtagTPE_FlowCostReq = ^tagTPE_FlowCostReq;
tagTPE_FlowCostBaseReq = record
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
CostType : WORD ;
AccountNo : UINT ;
CardNo : UINT ;
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char;
TransMoney : LONG ;
LinkOccurNode : UINT ;
LinkOccurIdNo : UINT ;
ExtraInfoLen : integer;
end;
tagTPE_FlowCostRes = tagTPE_FlowRes;
PtagTPE_FlowCostRes = ^tagTPE_FlowCostRes;
//************************************对帐******************************************************************************
tagTPE_CheckByTimeReq = record//对帐,按时间
GathNode : Array[0..127] of BYTE;
GathType : Array[0..31 ] of BYTE;
FmTime : TArrayTime;
ToTime : TArrayTime;
end;
PtagTPE_CheckByTimeReq = ^tagTPE_CheckByTimeReq;
tagTPE_CheckByTimeRes = record
GathNode : Array [0..127] of UINT ;
GathType : Array [0..31 ] of BYTE;
FmTime : TArrayTime;
ToTime : TArrayTime;
OccurTimes : UINT ;
Balance : LINT ;
end;
PtagTPE_CheckByTimeRes = ^tagTPE_CheckByTimeRes;
tagTPE_CheckBySnReq = record//对帐,按流水号
GathNode : UINT ;
GathType : Array [0..31] of BYTE ;
FmSn : UINT ;
ToSn : UINT ;
end;
PtagTPE_CheckBySnReq = ^tagTPE_CheckBySnReq;
tagTPE_CheckBySnRes = record
GathNode : UINT ;
GathType : Array[0..31]of byte;
FmSn : UINT ;
ToSn : UINT ;
OccurTimes:UINT ;
Balance : LINT ;
end;
PtagTPE_CheckBySnRes = ^tagTPE_CheckBySnRes;
tagTPE_CheckByDetailReq = record//对明细
GathNode : UINT ;
GathType : Array[0..31] of BYTE ;
FmSn : UINT ;
ToSn : UINT ;
end;
PtagTPE_CheckByDetailReq = ^tagTPE_CheckByDetailReq;
tagTPE_CheckByDetailRes = record
GathNode : UINT ;
GathType : Array[0..31] of BYTE;
FmSn : UINT ;
ToSn : UINT ;
MapLen : UINT ;
Map : Array[0..4095]of BYTE ;
end;
PtagTPE_CheckByDetailRes = ^tagTPE_CheckByDetailRes;
//*******************************************在线报文*************************************************************************
//申请当前最大流水号
tagTPE_OnLineGetMaxSnRes = record
RetValue : integer ;
MaxSn : UINT ;
end;
PtagTPE_OnLineGetMaxSnRes = ^tagTPE_OnLineGetMaxSnRes;
//*******************************************配置报文*************************************************************************
//配置日志
tagTPE_ConfigEnumLogReq = record
RangeConfOrder : Array[0..1] of UINT ;
RangeConfigTime: Array[0..1]of TArrayTime;
ConfType : Array[0..31]of BYTE;
end;
PtagTPE_ConfigEnumLogReq = ^tagTPE_ConfigEnumLogReq;
tagTPE_DeptLog = record
DeptNo : Array[0..1] of LINT;
Code : Array[0..1,0..15] of char;
Name : Array[0..1,0..63] of char;
end;
tagTPE_IdentiLog = record
IdentiNo : Array[0..1] of WORD ;
Code : Array[0..1,0..15] of char ;
Name : Array[0..1,0..63] of char ;
OverDraft : integer; //透支限额
Deposit : integer; //押金
ManageCoef : integer; //管理费系数
FeeCreate : integer; //开户手续费
FeeDelete : integer; //撤户手续费
FeeChange : integer; //换卡手续费
FeeLost : integer ; //挂失手续费
FeeTransfer : integer; //转帐手续费
Blank : Array[0..31] of byte;
Link : Array[0..95] of byte;
end;
tagTPE_NationLog = record
NationNo : Array[0..1] of WORD ;
Code : Array[0..1,0..15] of char ;
Name : Array[0..1,0..63] of char;
end;
tagTPE_CertLog = record
CertNo : Array[0..1] of BYTE;
Name : Array[0..1,0..63] of char;
end;
tagTPE_ConfigLogRec = record
case integer of
1: ( DeptLog : tagTPE_DeptLog );
2: ( IdentiLog : tagTPE_IdentiLog );
3: ( NationLog : tagTPE_NationLog );
4: ( CertLog : tagTPE_CertLog );
5: ( Blank : Array[0..483] of char;);
end;
PtagTPE_ConfigLogRec = ^ tagTPE_ConfigLogRec;
tagTPE_ConfigLog = record
ConfOrder : UINT ;
ConfType : UINT ;
ConfTime : TArrayTime;
ConfControl : UINT ;
ConfOper : WORD ;
ConfInfo : tagTPE_ConfigLogRec ;
end;
PtagTPE_ConfigLog = ^ tagTPE_ConfigLog;
//枚举部门
tagTPE_ConfigEnumDeptReq = record
RangeDept : Array[0..1] of LINT;
Depth : BYTE ;
end;
PtagTPE_ConfigEnumDeptReq = ^tagTPE_ConfigEnumDeptReq;
tagTPE_ConfigDeptRec = record
DeptNo : LINT ;
Code : Array[0..15] of char;
Name : Array[0..63] of char;
end;
PtagTPE_ConfigDeptRec = ^tagTPE_ConfigDeptRec;
//枚举身份
tagTPE_ConfigEnumIdentiReq = record
RangeIdenti : Array[0..1] of WORD ;
end;
PtagTPE_ConfigEnumIdentiReq = ^tagTPE_ConfigEnumIdentiReq;
tagTPE_ConfigIdentiRec = record
IdentiNo : WORD ;
Code : Array[0..15] of char;
Name : Array[0..63] of char;
OverDraft: integer;
end;
PtagTPE_ConfigIdentiRec = ^tagTPE_ConfigIdentiRec;
tagTPE_ConfigIdentiRecEx = record
IdentiNo : WORD ;
Code : Array[0..15] of char;
Name : Array[0..63] of char;
OverDraft: integer; //透支限额
Deposit: integer; //押金
ManageCoef: integer; //管理费系数
FeeCreate: integer; //开户手续费
FeeDelete: integer; //撤户手续费
FeeChange: integer; //换卡手续费
FeeLost: integer ; //挂失手续费
FeeTransfer: integer; //转帐手续费
Blank : Array[0..31] of byte;
Link : Array[0..95] of byte;
end;
PtagTPE_ConfigIdentiRecEx = ^tagTPE_ConfigIdentiRecEx;
//枚举民族
tagTPE_ConfigEnumNationReq = record
RangeNationNo : Array[0..1] of WORD;
end;
PtagTPE_ConfigEnumNationReq = ^tagTPE_ConfigEnumNationReq;
tagTPE_ConfigNationRec = record
NationNo : WORD ;
Code : Array[0..15] of char;
Name : Array[0..63] of char;
end;
PtagTPE_ConfigNationRec = ^tagTPE_ConfigNationRec;
//枚举证件
tagTPE_ConfigEnumCertReq = record
RangeCertNo : Array[0..1] of BYTE ;
end;
PtagTPE_ConfigEnumCertReq = ^tagTPE_ConfigEnumCertReq;
tagTPE_ConfigCertRec = record
CertNo : BYTE ;
Name : Array[0..47] of char;
end;
PtagTPE_ConfigCertRec = ^tagTPE_ConfigCertRec;
//枚举卡片申请
tagTPE_ConfigEnumCardReq = record
RangeCardTypeNo : Array[0..1] of BYTE;
end;
PtagTPE_ConfigEnumCardReq = ^tagTPE_ConfigEnumCardReq;
//枚举卡片结果记录
tagTPE_ConfigCardRec = record
CardTypeNo : BYTE;
Name : Array[0..31] of char;
Price : LONG ;
Extend : Array[0..63] of BYTE ;
end;
PtagTPE_ConfigCardRec = ^tagTPE_ConfigCardRec;
////////////////////////////管理报文////////////////////////////////////////////////////////////////////////////
//签到
tagTPE_ManageOperLoginReq = record
OperNo : WORD ;
OperType : WORD ;
OperName : Array[0..15] of char;
Password : Array[0..7] of BYTE ;
OperCardNo : UINT ;
end;
PtagTPE_ManageOperLoginReq = ^ tagTPE_ManageOperLoginReq;
tagTPE_ManageOperLoginRes = record
Retvalue : integer ;
end;
PtagTPE_ManageOperLoginRes = ^ tagTPE_ManageOperLoginRes;
//签退
tagTPE_ManageOperLogoutReq = record
OperNo : WORD ;
end;
PtagTPE_ManageOperLogoutReq = ^ tagTPE_ManageOperLogoutReq;
tagTPE_ManageOperLogoutRes = record
Retvalue : integer;
end;
PtagTPE_ManageOperLogoutRes = ^tagTPE_ManageOperLogoutRes;
////////////////////////////////////////////////////////////////////////////////////////////////////////
////流水查询
tagTPE_QueryFlowByCenterReq = record//按中心序号
ReqFlag : BYTE; //=1全部, ==0 部分满足条件的记录
FromCentralNo : UINT ;
ToCentralNo : UINT ;
reqflagAccountNo : BYTE;
reqflagCardNo : BYTE;
reqflagJoin : BYTE;
reqflagOccurNode : BYTE;
reqflagTransType : BYTE;
reqflagRangeOccurTime : BYTE;
AccountNo : UINT ;
CardNo : UINT ;
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char;
OccurNode : Array[0..127]of BYTE ;
TransType : Array[0..31] of UINT ;
RangeOccurTime : Array[0..1] of TArrayTime;
end;
PtagTPE_QueryFlowByCenterReq = ^tagTPE_QueryFlowByCenterReq;
PtagTPE_QueryFlowRes_Open = ^ tagTPE_QueryFlowRes_Open;
tagTPE_QueryFlowByNodeReq = record//按节点序号
ReqFlag : BYTE; //=1全部, ==0 部分满足条件的记录
OccurNode : UINT ;
FromOccurNo : UINT ;
ToOccurNo : UINT ;
reqflagAccountNo : BYTE;
reqflagCardNo : BYTE;
reqflagJoin : BYTE;
reqflagRangeOccurTime : BYTE;
reqflagTransType : BYTE;
AccountNo : UINT ;
CardNo : UINT ;
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char;
RangeOccurTime : Array[0..1] of TArrayTime;
TransType : Array[0..31]of BYTE;
end;
PtagTPE_QueryFlowByNodeReq = ^tagTPE_QueryFlowByNodeReq;
tagTPE_QueryFlowBySQLReq = record//通用
SQL : Array[0..4095] of char;
end;
PtagTPE_QueryFlowBySQLReq = ^tagTPE_QueryFlowBySQLReq;
tagTPE_QueryFlowRes_Open = record//开户流水
CenterNo : UINT ;
OccurNode : UINT ;
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
resflagCondition : BYTE;
resflagBalance : BYTE;
resflagCreateTime : BYTE;
resflagExpireDate : BYTE;
resflagName : BYTE;
resflagPersonID : BYTE;
resflagPassword : BYTE;
resflagAccessControl: BYTE;
resflagBirthday : BYTE;
resflagDepart : BYTE;
resflagIdenti : BYTE;
resflagNation : BYTE;
resflagCertType : BYTE;
resflagCertCode : BYTE;
resflagCreditCardNo : BYTE;
resflagTransferLimit: BYTE;
resflagTransferMoney: BYTE;
resflagTel : BYTE;
resflagEmail : BYTE;
resflagPostalCode : BYTE;
resflagPostalAddr : BYTE;
resflagComment : BYTE;
resflagExtend : BYTE;
resflagUpdateTime : BYTE;
AccountNo : UINT ;
CardNo : UINT ;
Condition : UINT ;
Balance : LONG ;
CreateTime : TArrayTime;
ExpireDate : TArrayTime;
Name : TArrayName;
PersonID : TArrayPersonID;
Password : TArrayPassword;
AccessControl : TArrayAccessControl;
Birthday : TArrayTime;
Depart : LINT ;
Identi : WORD ;
Nation : WORD ;
CertType : BYTE ;
CertCode : TArrayCertCode;
CreditCardNo : TArrayCreditCardNo;
TransferLimit : LONG ;
TransferMoney : LONG ;
Tel : TArrayTel;
Email : TArrayEmail;
PostalCode : Array[0..5 ] of char;
PostalAddr : Array[0..99] of char;
Comment : Array[0..119]of char;
ExtendLen : integer ;
Extend : Array[0..254]of BYTE ;
UpdateTime : TArrayTime;
end;
//PtagTPE_QueryFlowRes_Open = ^tagTPE_QueryFlowRes_Open;
tagTPE_QueryFlowRes_Close = tagTPE_QueryFlowRes_Open;
tagTPE_QueryFlowRes_UpdateAccount = record//更新帐户
CenterNo : UINT ;
OccurNode : UINT ;
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
resflagCondition : BYTE;
resflagCreateTime : BYTE;
resflagExpireDate : BYTE;
resflagName : BYTE;
resflagPersonID : BYTE;
resflagPassword : BYTE;
resflagAccessControl: BYTE;
resflagBirthday : BYTE;
resflagDepart : BYTE;
resflagIdenti : BYTE;
resflagNation : BYTE;
resflagCertType : BYTE;
resflagCertCode : BYTE;
resflagCreditCardNo : BYTE;
resflagTransferLimit: BYTE;
resflagTransferMoney: BYTE;
resflagTel : BYTE;
resflagEmail : BYTE;
resflagPostalCode : BYTE;
resflagPostalAddr : BYTE;
resflagComment : BYTE;
resflagExtend : BYTE;
resflagUpdateTime : BYTE;
AccountNo : UINT ;
CardNo : UINT ;
Condition : Array[0..1] of UINT ;
CreateTime : TArrayTime;
ExpireDate : TArrayTime;
Name : TArrayName;
PersonID : TArrayPersonID;
Password : TArrayPassword;
AccessControl : TArrayAccessControl;
Birthday : TArrayTime;
Depart : LINT ;
Identi : WORD ;
Nation : WORD ;
CertType : BYTE ;
CertCode : TArrayCertCode;
CreditCardNo : TArrayCreditCardNo;
TransferLimit : LONG ;
TransferMoney : LONG ;
Tel : TArrayTel;
Email : TArrayEmail;
PostalCode : Array[0..5] of char;
PostalAddr : Array[0..99] of char;
Comment : Array[0..119]of char;
ExtendLen : integer ;
Extend : Array[0..254]of BYTE ;
UpdateTime : TArrayTime;
end;
PtagTPE_QueryFlowRes_UpdateAccount = ^ tagTPE_QueryFlowRes_UpdateAccount;
tagTPE_QueryFlowRes_BuildRelation = record
CenterNo : UINT ;
OccurNode : UINT ;
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
AccountNo : UINT; //按帐号建立
CardNo : UINT; //按卡号建立
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char ;
resflagJoinPassword : BYTE;
resflagJoinCondition : BYTE;
resflagJoinComment : BYTE;
JoinPassword : TArrayPassword;
JoinCondition : UINT ;
JoinComment : Array[0..119] of char;
end;
tagTPE_QueryFlowRes_UpdateRelation = record
CenterNo : UINT ;
OccurNode : UINT ;
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
AccountNo : UINT; //按帐号建立
CardNo : UINT; //按卡号建立
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char ;
resflagJoinPassword : BYTE;
resflagJoinCondition : BYTE;
resflagJoinComment : BYTE;
JoinPassword : TArrayPassword;
JoinCondition : Array[0..1] of UINT ;
JoinComment : Array[0..119] of char;
end;
tagTPE_QueryFlowRes_CancelRelation = tagTPE_QueryFlowRes_BuildRelation;
tagTPE_QueryFlowRes_Cost = record
CenterNo : UINT ;
OccurNode : UINT ;
OccurIdNo : UINT ;
OccurTime : TArrayTime;
TranOper : WORD ;
AccountNo : UINT; //按帐号建立
CardNo : UINT; //按卡号建立
JoinNode : UINT ;
JoinCardHolder : Array[0..23] of char ;
CostType : WORD ;
TransMoney : LONG ;
Balance : LONG ;
LinkOccurNode : UINT ;
LinkOccurIdNo : UINT ;
ExtendLen : integer;
end;
/////////////////////////////////////////////////////////////////////////////////////
//验证密码
tagTPE_CheckPassword = record
PlainPassword : TArrayPassword;
CypherPassword : TArrayPassword;
end;
PtagTPE_CheckPassword = ^tagTPE_CheckPassword;
/////////////////////////////////////////////////////////////////////////////////////
tagTPE_TransferFileReq = record
Action : BYTE; //1 下载,2上传
FileFlag : BYTE; //0 载入内存,1:生成文件
FileName : Array[0..254] of char;
end;
PtagTPE_TransferFileReq = ^ tagTPE_TransferFileReq;
tagTPE_TransferFileRes = record
RetValue : integer;
Len : integer;
pFileData: pointer;
end;
PtagTPE_TransferFileRes = ^ tagTPE_TransferFileRes;
//*********************************定义互调函数类型************************************************************
CallBackFunction_WHITELIST = function ( pRec: PtagWhiteListCallBack ):integer;stdcall;
CallBackFunction_NODENOTIFY = function ( pRec: tagNodeNotifyInfo ; pRes : PtagNodeNotifyInfoRes ):integer;stdcall;
//*********************************接口函数定义***************************************************************
function TPE_StartTPE(): Integer; stdcall; external 'TPE.DLL' name 'TPE_StartTPE'; //启动TPE服务
function TPE_StopTPE() : Integer; stdcall; external 'TPE.DLL' name 'TPE_StopTPE'; //停止TPE服务
function TPE_SetCallBack_WhiteList ( pFun : CallBackFunction_WHITELIST) : Integer; stdcall; external 'TPE.DLL' name 'TPE_SetCallBack_WhiteList' ; //设定白名单同步回调函数
function TPE_SetCallBack_NodeNotify( pFun : CallBackFunction_NODENOTIFY): Integer; stdcall; external 'TPE.DLL' name 'TPE_SetCallBack_NodeNotify'; //设定流水同步通知回调函数
//function TPE_StartNotify ( ) : Integer; stdcall; external 'TPE.DLL' name 'TPE_StartNotify' ; //开始通知
//function TPE_StopNotify ( ) : Integer; stdcall; external 'TPE.DLL' name 'TPE_StopNotify' ; //停止通知
function TPE_StartWLNotify(): Integer; stdcall; external 'TPE.DLL' name 'TPE_StartWLNotify' ; //开始白名单通知回调
function TPE_StopWLNotify() : Integer; stdcall; external 'TPE.DLL' name 'TPE_StopWLNotify' ; //停止白名单通知回调
function TPE_WaitForData ( milliseconds : integer ) : Integer; stdcall; external 'TPE.DLL' name 'TPE_WaitForData';//等待数据
//取数据
function TPE_GetData ( pMessageCode : PCardinal;
pCustomSn : PCardinal;
pTPERet : PInteger ;
pBuf : Pointer ;
BufLen : integer ;
pRetLen : Pinteger
): Integer; stdcall; external 'TPE.DLL' name 'TPE_GetData';
//按卡号或帐号调帐
function TPE_GetAccount ( CustomSn : Cardinal ;
pReq : PtagTPE_GetAccountReq;
pRes : PtagTPE_GetAccountRes;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_GetAccount';
//按卡片序列号调帐
function TPE_GetAccountByCardSerial ( CustomSn : Cardinal ;
pReq : PtagTPE_GetAccountReq;
pRes : PtagTPE_GetAccountRes;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_GetAccountByCardSerial';
//按对应关系调帐
function TPE_GetAccountByRelation( CustomSn : Cardinal ;
pReq : PtagTPE_GetRelationReq ;
pRes : PtagTPE_GetRelationRes ;
bSync : integer
): Integer; stdcall; external 'TPE.DLL' name 'TPE_GetAccountByRelation';
//查询帐户,标准
function TPE_QueryStdAccount ( CustomSn : Cardinal ;
pReq : PtagTPE_QueryStdAccountReq ;
pResControl : PtagTPE_QueryResControl ;
bSync : integer
): Integer; stdcall; external 'TPE.DLL' name 'TPE_QueryStdAccount';
//查询帐户,通用
function TPE_QueryGeneralAccount ( CustomSn : Cardinal ;
pReq : PtagTPE_QueryGeneralAccountReq ;
pResControl: PtagTPE_QueryResControl;
bSync : integer
): Integer; stdcall; external 'TPE.DLL' name 'TPE_QueryGeneralAccount';
function TPE_QueryRelation ( CustomSn : Cardinal ;
pReq : tagTPE_QueryRelationReq ;
pResControl: tagTPE_QueryResControl ;
bSync : integer
): Integer; stdcall; external 'TPE.DLL' name 'TTPE_QueryRelation';
//查询流水
//查询流水返回结构pResData 结构:(流水类型+流水数据)*N
//按中心流水序号
function TPE_QueryFlowByCenter (
CustomSn : Cardinal ;
pReq : PtagTPE_QueryFlowByCenterReq ;
pResControl : PtagTPE_QueryResControl;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_QueryFlowByCenter';
//按节点流水序号
function TPE_QueryFlowByNode (
CustomSn : Cardinal ;
pReq : PtagTPE_QueryFlowByNodeReq;
pResControl : PtagTPE_QueryResControl ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_QueryFlowByNode';
//按SQL自定义
function TPE_QueryFlowBySQL (
CustomSn : Cardinal ;
pReq : PtagTPE_QueryFlowBySQLReq ;
pResControl : PtagTPE_QueryResControl ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_QueryFlowBySQL';
//入帐流水
//建立对应关系
function TPE_FlowBuildRelation (
CustomSn : Cardinal ;
pReq : PtagTPE_FlowBuildRelationReq;
pRes : PtagTPE_FlowBuildRelationRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_FlowBuildRelation';
//取消对应关系
function TPE_FlowCancelRelation (
CustomSn : Cardinal ;
pReq : PtagTPE_FlowCancelRelationReq ;
pRes : PtagTPE_FlowCancelRelationRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_FlowCancelRelation';
//更新帐户信息
function TPE_FlowUpdateAccount (
CustomSn : Cardinal ;
pReq : PtagTPE_FlowUpdateAccountReq ;
pRes : PtagTPE_FlowUpdateAccountRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_FlowUpdateAccount';
//更新对应关系
function TPE_FlowUpdateRelation (
CustomSn : Cardinal ;
pReq : PtagTPE_FlowUpdateRelationReq ;
pRes : PtagTPE_FlowUpdateRelationRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_FlowUpdateRelation';
//消费,余额变更
function TPE_FlowCost (
CustomSn : Cardinal ;
pReq : PtagTPE_FlowCostReq ;
FlowCount : integer ;
pRes : PtagTPE_FlowCostRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_FlowCost';
//挂失解挂
function TPE_Lost (
CustomSn : Cardinal ;
pReq : PtagTPE_LostReq ;
pRes : PtagTPE_LostRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_Lost';
//对帐
function TPE_CheckBySn (
CustomSn : Cardinal ;
pReq : PtagTPE_CheckBySnReq ;
pRes : PtagTPE_CheckBySnRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_CheckBySn';
//对帐
function TPE_CheckByTime (
CustomSn : Cardinal ;
pReq : PtagTPE_CheckByTimeReq ;
pRes : PtagTPE_CheckByTimeRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_CheckByTime';
//对帐
function TPE_CheckByDetail (
CustomSn : Cardinal ;
pReq : PtagTPE_CheckByDetailReq ;
pRes : PtagTPE_CheckByDetailRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_CheckByDetail';
//取流水号
function TPE_OnLineGetMaxSn (
CustomSn : Cardinal ;
pRes : PtagTPE_OnLineGetMaxSnRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_OnLineGetMaxSn';
//枚举配置日志
function TPE_ConfigEnumLog (
CustomSn : Cardinal ;
pReq : PtagTPE_ConfigEnumLogReq ;
pResControl : PtagTPE_QueryResControl;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_ConfigEnumLog';
//枚举部门
function TPE_ConfigEnumDept (
CustomSn : Cardinal ;
pReq : PtagTPE_ConfigEnumDeptReq ;
pResControl : PtagTPE_QueryResControl ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_ConfigEnumDept';
//枚举身份
function TPE_ConfigEnumIdenti (
CustomSn : Cardinal ;
pReq : ptagTPE_ConfigEnumIdentiReq ;
pResControl : PtagTPE_QueryResControl ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_ConfigEnumIdenti';
//枚举身份扩展
function TPE_ConfigEnumIdentiEx(
CustomSn : Cardinal ;
pReq : ptagTPE_ConfigEnumIdentiReq ;
pResControl : PtagTPE_QueryResControl ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_ConfigEnumIdentiEx';
//枚举民族
function TPE_ConfigEnumNation (
CustomSn : Cardinal ;
pReq : PtagTPE_ConfigEnumNationReq;
pResControl : PtagTPE_QueryResControl ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_ConfigEnumNation';
//枚举证件类型
function TPE_ConfigEnumCert (
CustomSn : Cardinal ;
pReq : PtagTPE_ConfigEnumCertReq ;
pResControl : PtagTPE_QueryResControl ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_ConfigEnumCert';
//操作员登录
function TPE_ManageOperLogin (
CustomSn : Cardinal ;
pReq : PtagTPE_ManageOperLoginReq ;
pRes : PtagTPE_ManageOperLoginRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_ManageOperLogin';
//枚举签退
function TPE_ManageOperLogout (
CustomSn : Cardinal ;
pReq : PtagTPE_ManageOperLogoutReq ;
pRes : PtagTPE_ManageOperLogoutRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_ManageOperLogout';
//内存释放
function TPE_Free ( pData : pointer): Integer; stdcall; external 'TPE.DLL' name 'TPE_Free';
//获得本机节点
function TPE_GetLocalNode() : Integer; stdcall; external 'TPE.DLL' name 'TPE_GetLocalNode';
//获得网络状态
function TPE_GetNetState () : Integer; stdcall; external 'TPE.DLL' name 'TPE_GetNetState';
//取白名单
function TPE_GetWL( pRec : PtagWhiteListRec ) : Integer; stdcall; external 'TPE.DLL' name 'TPE_GetWL';
//取节点编号
function TPE_GetLocalNodeSn ( pSn : pCardinal ) : Integer; stdcall; external 'TPE.DLL' name 'TPE_GetLocalNodeSn';
//下载全部白名单
function TPE_DownloadAllWL( ) : Integer; stdcall; external 'TPE.DLL' name 'TPE_DownloadAllWL';
//校验密码
function TPE_CheckPassword( pPwd : PtagTPE_CheckPassword ): Integer; stdcall; external 'TPE.DLL' name 'TPE_CheckPassword';
//传输文件
function TPE_TransferFile (
CustomSn : Cardinal ;
pReq : PtagTPE_TransferFileReq ;
pRes : PtagTPE_TransferFileRes ;
bSync : integer
) : Integer; stdcall; external 'TPE.DLL' name 'TPE_TransferFile';
const
//定义TPE返回值
TPE_ERROR_UNPACK = -5 ; //解包错误
TPE_ERROR_PARAMETER = -4 ; //入口参数错误
TPE_ERROR_INTERNAL = -3 ; //内部错误,
TPE_ERROR_NETFAIL = -2 ; //网络故障,可能已经断网(socket错误等)
TPE_ERROR_UNREACHABLE = -1 ; //后台不可达
// 0 //成功
TPE_ERROR_TIMEOUT = 1 ; //超时
TPE_ERROR_NODATA = 2 ; //没有数据
TPE_ERROR_LESSBUFFERLEN = 3 ; //缓冲区太小
//CONDITION字段一些标志位定义
CONDITION_MASK_CLOSE = $00000002 ;
CONDITION_MASK_FREEZE = $00000004 ;
CONDITION_MASK_LOST = $00000008 ;
CONDITION_MASK_AUTOTRANS = $00000010 ;
CONDITION_MASK_SELFTRANS = $00000020 ;
implementation
end.
|
// Windows API GUI definitions
unit Windows;
interface
const
WS_OVERLAPPEDWINDOW = $CF0000;
SW_SHOWDEFAULT = 10;
MB_OK = 0;
MB_OKCANCEL = 1;
WM_PAINT = $000F;
WM_MOUSEMOVE = $0200;
WM_DESTROY = $0002;
MK_LBUTTON = $0001;
MK_RBUTTON = $0002;
COLOR_WINDOW = 5;
IDC_ARROW = 32512;
type
WNDCLASSA = record
style: LongInt;
lpfnWndProc: Pointer;
cbClsExtra: Integer;
cbWndExtra: Integer;
hInstance: LongInt;
hIcon: LongInt;
hCursor: LongInt;
hbrBackground: LongInt;
lpszMenuName: PChar;
lpszClassName: PChar;
end;
POINT = record
x: LongInt;
y: LongInt;
end;
RECT = record
left: LongInt;
top: LongInt;
right: LongInt;
bottom: LongInt;
end;
MSG = record
hwnd: LongInt;
message: LongInt;
wParam: LongInt;
lParam: LongInt;
time: LongInt;
pt: POINT;
lPrivate: LongInt;
end;
PAINTSTRUCT = record
hdc: LongInt;
fErase: Integer;
rcPaint: RECT;
fRestore: Integer;
fIncUpdate: Integer;
rgbReserved: array [0..31] of Byte;
end;
function GetModuleHandleA(lpModuleName: Pointer): LongInt stdcall; external 'KERNEL32.DLL';
function MessageBoxA(hWnd: LongInt; lpText, lpCaption: PChar;
uType: LongInt): Integer stdcall; external 'USER32.DLL';
function LoadCursorA(hInstance: LongInt; lpCursorName: Pointer): LongInt stdcall; external 'USER32.DLL';
function RegisterClassA(var lpWndClass: WNDCLASSA): Integer stdcall; external 'USER32.DLL';
function CreateWindowExA(dwExStyle: LongInt;
lpClassName: PChar;
lpWindowName: PChar;
dwStyle: LongInt;
X: Integer;
Y: Integer;
nWidth: Integer;
nHeight: Integer;
hWndParent: LongInt;
hMenu: LongInt;
hInstance: LongInt;
lpParam: Pointer): LongInt stdcall; external 'USER32.DLL';
function ShowWindow(hWnd: LongInt; nCmdShow: Integer): Integer stdcall; external 'USER32.DLL';
function GetMessageA(var lpMsg: MSG; hWnd: LongInt;
wMsgFilterMin, wMsgFilterMax: Integer): Integer stdcall; external 'USER32.DLL';
function TranslateMessage(var lpMsg: MSG): Integer stdcall; external 'USER32.DLL';
function DispatchMessageA(var lpMsg: MSG): Integer stdcall; external 'USER32.DLL';
function DefWindowProcA(hWnd, uMsg, wParam, lParam: LongInt): Integer stdcall; external 'USER32.DLL';
function BeginPaint(hWnd: LongInt; var lpPaint: PAINTSTRUCT): LongInt stdcall; external 'USER32.DLL';
procedure EndPaint(hWnd: LongInt; var lpPaint: PAINTSTRUCT) stdcall; external 'USER32.DLL';
procedure FillRect(hDC: LongInt; var lprc: RECT; hbr: LongInt) stdcall; external 'USER32.DLL';
procedure InvalidateRect(hWnd: LongInt; lpRect: Pointer; bErase: Integer) stdcall; external 'USER32.DLL';
procedure Ellipse(hDC: LongInt; left, top, right, bottom: Integer) stdcall; external 'GDI32.DLL';
procedure PostQuitMessage(nExitCode: Integer) stdcall; external 'USER32.DLL';
implementation
end.
|
{*************************************************************
Author: Stéphane Vander Clock (SVanderClock@Arkadia.com)
EMail: http://www.arkadia.com
SVanderClock@Arkadia.com
product: TALMultiPartMixedAttachment
TALMultiPartMixedAttachments
TAlMultiPartMixedStream
TALMultipartMixedEncoder
Version: 3.05
Description: MultiPart Mixed function to encode stream for Email Body
in mime multipart/mixed format. the best way to add some
Attachments to any email content.
Legal issues: Copyright (C) 2005 by Stéphane Vander Clock
This software is provided 'as-is', without any express
or implied warranty. In no event will the author be
held liable for any damages arising from the use of
this software.
Permission is granted to anyone to use this software
for any purpose, including commercial applications,
and to alter it and redistribute it freely, subject
to the following restrictions:
1. The origin of this software must not be
misrepresented, you must not claim that you wrote
the original software. If you use this software in
a product, an acknowledgment in the product
documentation would be appreciated but is not
required.
2. Altered source versions must be plainly marked as
such, and must not be misrepresented as being the
original software.
3. This notice may not be removed or altered from any
source distribution.
4. You must register this software by sending a picture
postcard to the author. Use a nice stamp and mention
your name, street address, EMail address and any
comment you like to say.
Know bug :
History :
Link : http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/7a18a98b-3a18-45b2-83a9-28a8f4099970.asp
http://www.ietf.org/rfc/rfc2646.txt
Please send all your feedback to SVanderClock@Arkadia.com
**************************************************************}
unit ALMultiPartMixedParser;
interface
uses Classes,
SysUtils,
Contnrs,
HTTPApp;
type
{-Single multipart attachment Object-------}
TALMultiPartMixedAttachment = class(TObject)
private
FContentType: string;
FFileName: string;
FFileData: TStream;
public
constructor Create;
destructor Destroy; override;
procedure LoadFromFile(aFileName: string);
procedure SaveToFile(SaveAsFile: string);
procedure SaveToStream(Stream: TStream);
property ContentType: string read FContentType write FContentType;
property FileName: string read FFileName write FFileName;
property FileData: TStream read FFileData;
end;
{--List Of multipart Objects--------------------}
TALMultiPartMixedAttachments = class(TObjectList)
private
protected
function GetItem(Index: Integer): TALMultiPartMixedAttachment;
procedure SetItem(Index: Integer; AObject: TALMultiPartMixedAttachment);
public
Function Add: TALMultiPartMixedAttachment; overload;
function Add(AObject: TALMultiPartMixedAttachment): Integer; overload;
function Remove(AObject: TALMultiPartMixedAttachment): Integer;
function IndexOf(AObject: TALMultiPartMixedAttachment): Integer;
procedure Insert(Index: Integer; AObject: TALMultiPartMixedAttachment);
property Items[Index: Integer]: TALMultiPartMixedAttachment read GetItem write SetItem; default;
end;
{--TAlMultiPartMixedStream-------------------}
TAlMultiPartMixedStream = class(TMemoryStream)
private
FBoundary: string;
FTopHeaderContentType: string;
function GenerateUniqueBoundary: string;
public
procedure AddInlineText(const ContentType, Text: string);
procedure AddAttachment(const FileName, ContentType: string; FileData: TStream); overload;
procedure AddAttachment(const FileName, ContentType: string); overload;
procedure CloseBoundary;
constructor Create;
property Boundary: string read FBoundary;
property TopHeaderContentType: string read FTopHeaderContentType;
end;
{--TALMultipartMixedEncoder-------------}
TALMultipartMixedEncoder = class(TObject)
private
FContentStream: TStream;
public
constructor Create;
destructor Destroy; override;
procedure Encode(InlineText, InlineTextContentType: String; Attachments: TALMultiPartMixedAttachments);
property ContentStream: TStream read FContentStream;
end;
implementation
uses AlFcnString,
AlFcnMime;
//////////////////////////////////////////////////////////////////
////////// TALMultiPartMixedAttachment //////////////////////////
//////////////////////////////////////////////////////////////////
{*********************************************}
constructor TALMultiPartMixedAttachment.Create;
begin
inherited;
FFileData := TMemoryStream.Create;
end;
{*********************************************}
destructor TALMultiPartMixedAttachment.Destroy;
begin
FFileData.Free;
inherited;
end;
{*******************************************************************}
procedure TALMultiPartMixedAttachment.LoadFromFile(aFileName: string);
begin
TmemoryStream(FileData).LoadFromFile(aFileName);
FileName := aFileName;
ContentType := ALGetDefaultMIMEContentTypeFromExt(ExtractfileExt(aFileName));
end;
{******************************************************************}
procedure TALMultiPartMixedAttachment.SaveToFile(SaveAsFile: string);
begin
TMemoryStream(FFileData).SaveToFile(SaveAsFile);
end;
{******************************************************************}
procedure TALMultiPartMixedAttachment.SaveToStream(Stream: TStream);
begin
FileData.Position := 0;
TMemoryStream(FFileData).SaveToStream(Stream);
Stream.Position := 0;
end;
//////////////////////////////////////////////////////////////////
////////// TALMultiPartMixedAttachments ////////////////////////
//////////////////////////////////////////////////////////////////
{***************************************************************************************}
function TALMultiPartMixedAttachments.Add(AObject: TALMultiPartMixedAttachment): Integer;
begin
Result := inherited Add(AObject);
end;
{*********************************************************************}
function TALMultiPartMixedAttachments.Add: TALMultiPartMixedAttachment;
begin
Result := TALMultiPartMixedAttachment.Create;
Try
add(result);
except
Result.Free;
raise;
end;
end;
{*****************************************************************************************}
function TALMultiPartMixedAttachments.GetItem(Index: Integer): TALMultiPartMixedAttachment;
begin
Result := TALMultiPartMixedAttachment(inherited Items[Index]);
end;
{*******************************************************************************************}
function TALMultiPartMixedAttachments.IndexOf(AObject: TALMultiPartMixedAttachment): Integer;
begin
Result := inherited IndexOf(AObject);
end;
{**************************************************************************************************}
procedure TALMultiPartMixedAttachments.Insert(Index: Integer; AObject: TALMultiPartMixedAttachment);
begin
inherited Insert(Index, AObject);
end;
{******************************************************************************************}
function TALMultiPartMixedAttachments.Remove(AObject: TALMultiPartMixedAttachment): Integer;
begin
Result := inherited Remove(AObject);
end;
{***************************************************************************************************}
procedure TALMultiPartMixedAttachments.SetItem(Index: Integer; AObject: TALMultiPartMixedAttachment);
begin
inherited Items[Index] := AObject;
end;
///////////////////////////////////////////////////////////////////////////////////////
////////// TAlMultiPartMixedStream ////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
{*****************************************}
constructor TAlMultiPartMixedStream.Create;
begin
inherited;
FBoundary := GenerateUniqueBoundary;
FTopHeaderContentType := 'multipart/mixed; boundary="' + FBoundary + '"';
end;
{**********************************************************************************}
procedure TAlMultiPartMixedStream.AddAttachment(const FileName, ContentType: string;
FileData: TStream);
var sFormFieldInfo: string;
Buffer: String;
iSize: Int64;
begin
If Position > 0 then sFormFieldInfo := #13#10
else sFormFieldInfo := #13#10 +
'This is a multi-part message in MIME format.'+ #13#10 +
#13#10;
iSize := FileData.Size;
sFormFieldInfo := sFormFieldInfo + Format(
'--' + Boundary + #13#10 +
'Content-Type: %s; name="%s"' + #13#10 +
'Content-Transfer-Encoding: base64' + #13#10 +
'Content-Disposition: attachment; filename="%s"' + #13#10 +
#13#10,
[ContentType, ExtractFileName(FileName), ExtractFileName(FileName)]
);
Write(Pointer(sFormFieldInfo)^, Length(sFormFieldInfo));
FileData.Position := 0;
SetLength(Buffer, iSize);
FileData.Read(Buffer[1], iSize);
Buffer := ALMimeBase64EncodeString(Buffer) + #13#10;
Write(Buffer[1], length(Buffer));
end;
{***********************************************************************************}
procedure TAlMultiPartMixedStream.AddAttachment(const FileName, ContentType: string);
var FileStream: TFileStream;
begin
FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
AddAttachment(FileName, ContentType, FileStream);
finally
FileStream.Free;
end;
end;
{*******************************************************************************}
procedure TAlMultiPartMixedStream.AddInlineText(const ContentType, Text: string);
var sFormFieldInfo: string;
begin
If Position > 0 then sFormFieldInfo := #13#10
else sFormFieldInfo := #13#10 +
'This is a multi-part message in MIME format.' + #13#10 +
#13#10;
sFormFieldInfo := sFormFieldInfo + Format(
'--' + Boundary + #13#10 +
'Content-Type: %s' + #13#10 +
#13#10 +
Text,
[ContentType]
);
Write(Pointer(sFormFieldInfo)^, Length(sFormFieldInfo));
end;
{**************************************************************}
function TAlMultiPartMixedStream.GenerateUniqueBoundary: string;
begin
Result := '---------------------------' + FormatDateTime('mmddyyhhnnsszzz', Now);
end;
{**********************************************}
procedure TAlMultiPartMixedStream.CloseBoundary;
var sFormFieldInfo: string;
begin
sFormFieldInfo := #13#10 +
'--' + Boundary + '--' + #13#10;
Write(Pointer(sFormFieldInfo)^, Length(sFormFieldInfo));
end;
////////////////////////////////////////////////////////////////////////////////////
////////// TALMultipartMixedEncoder ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
{******************************************}
constructor TALMultipartMixedEncoder.Create;
begin
FContentStream := TAlMultiPartMixedStream.Create;
end;
{******************************************}
destructor TALMultipartMixedEncoder.Destroy;
begin
FContentStream.Free;
inherited;
end;
{***************************************************}
procedure TALMultipartMixedEncoder.Encode(InlineText,
InlineTextContentType: String;
Attachments: TALMultiPartMixedAttachments);
Var i: Integer;
begin
with TAlMultiPartMixedStream(FcontentStream) do begin
Clear;
AddInlineText(InlineTextContentType, InlineText);
If assigned(Attachments) then
For i := 0 to Attachments.Count - 1 do
With Attachments[i] do
AddAttachment(
FileName,
ContentType,
FileData
);
end;
end;
end.
|
unit UDDesignControls;
interface
uses
Windows, Forms, Controls, Buttons, Classes, ExtCtrls, UCrpe32;
type
TCrpeDesignControlsDlg = class(TForm)
pnlBBar: TPanel;
pnlBBar2: TPanel;
sbOpen: TSpeedButton;
sbClose: TSpeedButton;
sbDiscardSavedData: TSpeedButton;
sbQuickPreview: TSpeedButton;
sbPreview: TSpeedButton;
sbPrint: TSpeedButton;
sbExport: TSpeedButton;
sbCloseWindow: TSpeedButton;
sbFirst: TSpeedButton;
sbPrevious: TSpeedButton;
sbNext: TSpeedButton;
sbLast: TSpeedButton;
sbCancel: TSpeedButton;
sbZoom: TSpeedButton;
procedure sbOpenClick(Sender: TObject);
procedure sbCloseClick(Sender: TObject);
procedure sbDiscardSavedDataClick(Sender: TObject);
procedure sbQuickPreviewClick(Sender: TObject);
procedure sbPreviewClick(Sender: TObject);
procedure sbPrintClick(Sender: TObject);
procedure sbExportClick(Sender: TObject);
procedure sbCloseWindowClick(Sender: TObject);
procedure sbFirstClick(Sender: TObject);
procedure sbPreviousClick(Sender: TObject);
procedure sbNextClick(Sender: TObject);
procedure sbLastClick(Sender: TObject);
procedure sbCancelClick(Sender: TObject);
procedure sbZoomClick(Sender: TObject);
procedure SetButtonState(BtnSet: integer; OnOff: boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
end;
var
CrpeDesignControlsDlg: TCrpeDesignControlsDlg;
bDesignControls : boolean;
implementation
uses SysUtils, Dialogs;
{$R *.DFM}
{******************************************************************************}
{ Class TCrpeDesignControlsDlg }
{******************************************************************************}
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.FormCreate(Sender: TObject);
begin
bDesignControls := True;
end;
{------------------------------------------------------------------------------}
{ sbOpenClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbOpenClick(Sender: TObject);
var
dlgOpen : TOpenDialog;
OnOff : boolean;
begin
{Redraw dialog}
Refresh;
{Create OpenFile dialog}
dlgOpen := TOpenDialog.Create(Application);
dlgOpen.FileName := '*.rpt';
dlgOpen.Title := 'Choose a Crystal Report...';
dlgOpen.Filter := 'Report Files (*.rpt) | *.rpt';
dlgOpen.DefaultExt := 'rpt';
dlgOpen.Options := dlgOpen.Options + [ofPathMustExist, ofFileMustExist];
try
if dlgOpen.Execute then
begin
Refresh;
Cr.ReportName := dlgOpen.FileName;
SetButtonState(1,True);
end;
finally
dlgOpen.Free;
end; { Protected Res Block }
{Check ReportName}
OnOff := Trim(Cr.ReportName) <> '';
SetButtonState(1,OnOff);
end;
{------------------------------------------------------------------------------}
{ sbCloseClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbCloseClick(Sender: TObject);
begin
Cr.CloseWindow;
Cr.CloseJob;
{Cr.ReportName := '';}
SetButtonState(0,False);
end;
{------------------------------------------------------------------------------}
{ sbRetrieveClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbDiscardSavedDataClick(Sender: TObject);
begin
Cr.DiscardSavedData;
end;
{------------------------------------------------------------------------------}
{ sbQuickPreviewClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbQuickPreviewClick(Sender: TObject);
var
OnOff : boolean;
begin
{Redraw dialog}
Refresh;
{Check ReportName}
OnOff := Trim(Cr.ReportName) <> '';
SetButtonState(1, OnOff);
{Execute}
if OnOff then
begin
{If a Window is open already, Refresh}
if (Cr.ReportWindowHandle > 0) then
begin
Screen.Cursor := crHourglass;
try
Cr.Refresh;
except
Screen.Cursor := crDefault;
raise;
end;
Screen.Cursor := crDefault;
end
{If a Window is not open, Preview}
else
begin
Screen.Cursor := crHourglass;
try
Cr.Execute;
except
Screen.Cursor := crDefault;
raise;
end;
Screen.Cursor := crDefault;
end;
end;
{Check for Window}
OnOff := (Cr.ReportWindowHandle > 0);
SetButtonState(2, OnOff);
{Check for PrintEnded}
SetButtonState(3,(not Cr.PrintEnded));
end;
{------------------------------------------------------------------------------}
{ sbPreviewClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbPreviewClick(Sender: TObject);
var
oTmp : TCrOutput;
OnOff : boolean;
begin
{Store current values}
oTmp := Cr.Output;
{Set new values}
Cr.Output := toWindow;
{Redraw dialog}
Refresh;
{Check ReportName}
OnOff := Trim(Cr.ReportName) <> '';
SetButtonState(1, OnOff);
{Execute}
if OnOff then
begin
{If a Child Window is open already, close it}
if (Cr.WindowParent <> nil) and (Cr.ReportWindowHandle > 0) then
Cr.CloseWindow;
Screen.Cursor := crHourglass;
try
Cr.Execute;
except
Screen.Cursor := crDefault;
raise;
end;
Screen.Cursor := crDefault;
end;
{Reset values}
Cr.Output := oTmp;
{Check for Window}
OnOff := (Cr.ReportWindowHandle > 0);
SetButtonState(2, OnOff);
{Check for PrintEnded}
SetButtonState(3,(not Cr.PrintEnded));
end;
{------------------------------------------------------------------------------}
{ sbPrintClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbPrintClick(Sender: TObject);
var
oTmp : TCrOutput;
OnOff : boolean;
begin
{Store current values}
oTmp := Cr.Output;
{Set new values}
Cr.Output := toPrinter;
{Redraw dialog}
Refresh;
{Check ReportName}
OnOff := Trim(Cr.ReportName) <> '';
SetButtonState(1, OnOff);
{Execute}
if OnOff then
begin
Screen.Cursor := crHourglass;
try
Cr.Execute;
except
Screen.Cursor := crDefault;
raise;
end;
Screen.Cursor := crDefault;
end;
{Reset values}
Cr.Output := oTmp;
{Check for Window}
OnOff := (Cr.ReportWindowHandle > 0);
SetButtonState(2, OnOff);
{Check for PrintEnded}
SetButtonState(3,(not Cr.PrintEnded));
end;
{------------------------------------------------------------------------------}
{ sbExportClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbExportClick(Sender: TObject);
var
oTmp : TCrOutput;
bTmp : boolean;
OnOff : boolean;
begin
{Store current values}
oTmp := Cr.Output;
bTmp := Cr.ExportOptions.PromptForOptions;
{Set values}
Cr.ExportOptions.PromptForOptions := True;
Cr.Output := toExport;
{Redraw dialog}
Refresh;
{Check ReportName}
OnOff := Trim(Cr.ReportName) <> '';
SetButtonState(1,OnOff);
{Execute}
if OnOff then
begin
Screen.Cursor := crHourglass;
try
Cr.Execute;
except
Screen.Cursor := crDefault;
raise;
end;
Screen.Cursor := crDefault;
end;
{Reset values}
Cr.Output := oTmp;
Cr.ExportOptions.PromptForOptions := bTmp;
{Check for Window}
OnOff := (Cr.ReportWindowHandle > 0);
SetButtonState(2,OnOff);
{Check for PrintEnded}
SetButtonState(3,(not Cr.PrintEnded));
end;
{------------------------------------------------------------------------------}
{ sbCloseWindowClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbCloseWindowClick(Sender: TObject);
var
OnOff : boolean;
begin
OnOff := (Cr.ReportWindowHandle > 0);
if OnOff then
Cr.CloseWindow;
OnOff := (Cr.ReportWindowHandle > 0);
SetButtonState(2,OnOff);
SetButtonState(3,(not Cr.PrintEnded));
end;
{------------------------------------------------------------------------------}
{ sbStartPageClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbFirstClick(Sender: TObject);
var
OnOff : boolean;
begin
OnOff := (Cr.ReportWindowHandle > 0);
if OnOff then
begin
Cr.Pages.First;
SetButtonState(3,(not Cr.PrintEnded));
end;
SetButtonState(2,OnOff);
end;
{------------------------------------------------------------------------------}
{ sbPreviousPageClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbPreviousClick(Sender: TObject);
var
OnOff : boolean;
begin
OnOff := (Cr.ReportWindowHandle > 0);
if OnOff then
begin
Cr.Pages.Previous;
SetButtonState(3,(not Cr.PrintEnded));
end;
SetButtonState(2,OnOff);
end;
{------------------------------------------------------------------------------}
{ sbNextPageClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbNextClick(Sender: TObject);
var
OnOff : boolean;
begin
OnOff := (Cr.ReportWindowHandle > 0);
if OnOff then
begin
Cr.Pages.Next;
SetButtonState(3,(not Cr.PrintEnded));
end;
SetButtonState(2,OnOff);
end;
{------------------------------------------------------------------------------}
{ sbLastPageClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbLastClick(Sender: TObject);
var
OnOff : boolean;
begin
OnOff := (Cr.ReportWindowHandle > 0);
if OnOff then
begin
Cr.Pages.Last;
SetButtonState(3,(not Cr.PrintEnded));
end;
SetButtonState(2,OnOff);
end;
{------------------------------------------------------------------------------}
{ sbCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbCancelClick(Sender: TObject);
var
OnOff : boolean;
begin
if Cr.PrintEnded = False then
Cr.CancelJob;
SetButtonState(3, False);
OnOff := (Cr.ReportWindowHandle > 0);
SetButtonState(2, OnOff);
end;
{------------------------------------------------------------------------------}
{ sbZoomClick }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.sbZoomClick(Sender: TObject);
var
OnOff : boolean;
begin
OnOff := (Cr.ReportWindowHandle > 0);
if OnOff then
Cr.WindowZoom.NextLevel;
SetButtonState(2, OnOff);
end;
{------------------------------------------------------------------------------}
{ SetButtonState }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.SetButtonState(BtnSet: integer; OnOff: boolean);
var
cnt : integer;
begin
case BtnSet of
{All buttons}
0: begin
for cnt := 0 to (ComponentCount - 1) do
begin
if (Components[cnt] is TSpeedButton) and
(TSpeedButton(Components[cnt]).Name <> 'sbOpen') then
begin
if TSpeedButton(Components[cnt]).Enabled <> OnOff then
TSpeedButton(Components[cnt]).Enabled := OnOff;
end;
end;
end;
{Top row only}
1: begin
for cnt := 0 to (ComponentCount - 1) do
begin
if (Components[cnt] is TSpeedButton) and
(TSpeedButton(Components[cnt]).Parent = pnlBBar) and
(TSpeedButton(Components[cnt]).Name <> 'sbOpen') then
begin
if TSpeedButton(Components[cnt]).Enabled <> OnOff then
TSpeedButton(Components[cnt]).Enabled := OnOff;
end;
end;
end;
{Bottom row only: window/paging (not Cance)}
2: begin
for cnt := 0 to (ComponentCount - 1) do
begin
if (Components[cnt] is TSpeedButton) and
(TSpeedButton(Components[cnt]).Parent = pnlBBar2) and
(TSpeedButton(Components[cnt]).Name <> 'sbCancel') then
begin
if TSpeedButton(Components[cnt]).Enabled <> OnOff then
TSpeedButton(Components[cnt]).Enabled := OnOff;
end;
end;
end;
{Cancel button}
3: if sbCancel.Enabled <> OnOff then
sbCancel.Enabled := OnOff;
end;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeDesignControlsDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
bDesignControls := False;
Release;
end;
end.
|
unit URepositorioProduto;
interface
uses
UProduto
, UUnidadeMedida
, URepositorioUnidadeMedida
, UGrupoProduto
, URepositorioGrupoProduto
, UFamiliaProduto
, URepositorioFamiliaProduto
, UEntidade
, UMarca
, URepositorioMarca
, URepositorioDB
, SqlExpr
;
type
TRepositorioProduto = class(TRepositorioDB<TPRODUTO>)
private
FRepositorioUnidadeMedida : TRepositorioUnidadeMedida;
FRepositorioGrupoProduto : TRepositorioGRUPOPRODUTO;
FRepositorioFamiliaProduto: TRepositorioFAMILIAPRODUTO;
FRepositorioMarca : TRepositorioMarca;
public
constructor Create;
destructor Destroy; override;
procedure AtribuiDBParaEntidade(const coPRODUTO: TPRODUTO); override;
procedure AtribuiEntidadeParaDB(const coPRODUTO: TPRODUTO;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
, DB
, SysUtils
;
{ TRepositorioProduto }
procedure TRepositorioProduto.AtribuiDBParaEntidade(const coPRODUTO: TPRODUTO);
begin
inherited;
with FSQLSelect do
begin
coPRODUTO.DESCRICAO := FieldByName(FLD_PRODUTO_DESCRICAO).AsString;
coPRODUTO.UNIDADEMEDIDA := TUNIDADEMEDIDA(
FRepositorioUnidadeMedida.Retorna(FieldByName(FLD_PRODUTO_UNIDADE_MEDIDA).AsInteger));
coPRODUTO.GRUPOPRODUTO := TGRUPOPRODUTO(
FRepositorioGrupoProduto.Retorna(FieldByName(FLD_PRODUTO_GRUPO_PRODUTO).AsInteger));
if FieldByName(FLD_PRODUTO_MARCA).AsInteger >= 0 then
coPRODUTO.MARCA := TMarca(FRepositorioMarca.Retorna(FieldByName(FLD_PRODUTO_MARCA).AsInteger))
else
coPRODUTO.MARCA.ID := -1;
if FieldByName(FLD_PRODUTO_QTDE_MINIMA).AsInteger >= 0 then
coPRODUTO.QUANTIDADE_MINIMA := FieldByName(FLD_PRODUTO_QTDE_MINIMA).AsInteger
else
coPRODUTO.QUANTIDADE_MINIMA := 0;
if FieldByName(FLD_PRODUTO_QTDE_MAXIMA).AsInteger >= 0 then
coPRODUTO.QUANTIDADE_MAXIMA := FieldByName(FLD_PRODUTO_QTDE_MAXIMA).AsInteger
else
coPRODUTO.QUANTIDADE_MAXIMA := 0;
if FieldByName(FLD_PRODUTO_TAMANHO).AsInteger >= 0 then
coPRODUTO.TAMANHO := FieldByName(FLD_PRODUTO_QTDE_MAXIMA).AsInteger
else
coPRODUTO.TAMANHO := 0;
end;
end;
procedure TRepositorioProduto.AtribuiEntidadeParaDB(const coPRODUTO: TPRODUTO;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_PRODUTO_DESCRICAO).AsString := coPRODUTO. DESCRICAO;
ParamByName(FLD_PRODUTO_UNIDADE_MEDIDA).AsInteger := coPRODUTO.UNIDADEMEDIDA.ID;
ParamByName(FLD_PRODUTO_GRUPO_PRODUTO).AsInteger := coPRODUTO.GRUPOPRODUTO.ID;
if coPRODUTO.MARCA.ID > 0 then
ParamByName(FLD_PRODUTO_MARCA).AsInteger := coPRODUTO.MARCA.ID
else
begin
ParamByName(FLD_PRODUTO_MARCA).DataType := ftInteger;
ParamByName(FLD_PRODUTO_MARCA).Bound := True;
ParamByName(FLD_PRODUTO_MARCA).Clear;
end;
if coPRODUTO.QUANTIDADE_MINIMA > 0 then
ParamByName(FLD_PRODUTO_QTDE_MINIMA).AsInteger := coPRODUTO.QUANTIDADE_MINIMA
else
begin
ParamByName(FLD_PRODUTO_QTDE_MINIMA).DataType := ftInteger;
ParamByName(FLD_PRODUTO_QTDE_MINIMA).Bound := True;
ParamByName(FLD_PRODUTO_QTDE_MINIMA).Clear;
end;
if coPRODUTO.QUANTIDADE_MAXIMA > 0 then
ParamByName(FLD_PRODUTO_QTDE_MAXIMA).AsInteger := coPRODUTO.QUANTIDADE_MAXIMA
else
begin
ParamByName(FLD_PRODUTO_QTDE_MAXIMA).DataType := ftInteger;
ParamByName(FLD_PRODUTO_QTDE_MAXIMA).Bound := True;
ParamByName(FLD_PRODUTO_QTDE_MAXIMA).Clear;
end;
if coPRODUTO.TAMANHO > 0 then
ParamByName(FLD_PRODUTO_TAMANHO).AsInteger := coPRODUTO.TAMANHO
else
begin
ParamByName(FLD_PRODUTO_TAMANHO).DataType := ftInteger;
ParamByName(FLD_PRODUTO_TAMANHO).Bound := True;
ParamByName(FLD_PRODUTO_TAMANHO).Clear;
end;
end;
end;
constructor TRepositorioProduto.Create;
begin
inherited Create(TPRODUTO, TBL_PRODUTO, FLD_ENTIDADE_ID, STR_PRODUTO);
FRepositorioUnidadeMedida := TRepositorioUnidadeMedida.Create;
FRepositorioGrupoProduto := TRepositorioGrupoProduto.Create;
FRepositorioFamiliaProduto := TRepositorioFamiliaProduto.Create;
FRepositorioMarca := TRepositorioMarca.Create;
end;
destructor TRepositorioProduto.Destroy;
begin
FreeAndNil(FRepositorioUnidadeMedida);
FreeAndNil(FRepositorioGrupoProduto);
FreeAndNil(FRepositorioFamiliaProduto);
FreeAndNil(FRepositorioMarca);
inherited;
end;
end.
|
unit constants;
interface
const
int1 = 0;
hex1 = $FF;
hex2 = -$0F1F;
oct1 = &15;
oct2 = -&22344;
bin1 = %11011;
bin2 = -%00101011;
real1 = 1.02;
real2 = 4.2323402e-2;
real3 = -123.054542E-2;
real4 = -167.102e42;
real5 = 1E17;
real6 = -6E22;
real7 = 4E-12;
real8 = 8.005E-45;
real9 = 1.<error>;</error>
real10 = <error>.</error>02<error>;</error>
implementation
end. |
PROGRAM WorkWithQueryString(INPUT, OUTPUT);
USES
DOS;
FUNCTION GetQueryStringParameter(Key: STRING): STRING;
VAR
first_name, last_name, age: STRING;
BEGIN
WRITELN('Content-Type: text/plain');
WRITELN;
Name := GetEnv('QUERY_STRING');
END;
BEGIN {WorkWithQueryString}
WRITELN('First Name: ', GetQueryStringParameter('first_name'));
WRITELN('Last Name: ', GetQueryStringParameter('last_name'));
WRITELN('Age: ', GetQueryStringParameter('age'))
END. {WorkWithQueryString}
|
unit uSimpleRenderer;
interface
uses
Classes, Dialogs, Math, Controls, ExtCtrls, SysUtils, Graphics,
Types, Forms, uMinesClasses;
type
TMinesRenderer=class
Mines : TMines;
Panel : TPanel;
PanelList : TList;
PanelsUpdated : integer;
LastFocusPanel : TPanel;
SquareSizeX, SquareSizeY : integer;
constructor Create(Mines : TMines; Panel : TPanel);
procedure Clear;
procedure Prepare;
procedure Render(OnlyChanged : boolean);
// THE EVENTS!
procedure SquarePanelClick(Sender: TObject);
procedure SquarePanelMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure SquarePanelRightClick(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
procedure SquarePanelMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure SquarePanelDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
end;
implementation
{ TMinesRenderer }
procedure TMinesRenderer.Clear;
var
i : integer;
begin
for i := 0 to PanelList.Count-1 do
TPanel(PanelList[i]).Free;
PanelList.Clear;
end;
constructor TMinesRenderer.Create(Mines: TMines; Panel: TPanel);
begin
self.Mines := Mines;
self.Panel := Panel;
PanelList := TList.Create;
SquareSizeX := 16;
SquareSizeY := 16;
end;
procedure TMinesRenderer.Prepare;
var
i : integer;
Square : TSquare;
sPanel : TPanel;
maxRight, maxBottom : integer;
begin
Panel.Hide;
try
Clear;
maxRight := 0;
maxBottom := 0;
for i := 0 to Mines.SquareList.Count-1 do
begin
Square := Mines.SquareList[i];
sPanel := TPanel.Create(Panel);
PanelList.Add(sPanel);
sPanel.Left := Square.X * SquareSizeX+2;
sPanel.Width := SquareSizeX;
sPanel.Top := Square.Y * SquareSizeY+2;
sPanel.Height := SquareSizeY;
sPanel.Parent := Panel;
sPanel.Font.Style := [fsBold];
sPanel.Font.Name := 'System';
Square.Data := sPanel;
sPanel.Tag := integer(Square);
// EVENTS
//sPanel.OnClick := SquarePanelClick;
sPanel.OnMouseUp := SquarePanelMouseUp;
sPanel.OnContextPopup := SquarePanelRightClick;
sPanel.OnMouseMove := SquarePanelMouseMove;
sPanel.OnDragOver := SquarePanelDragOver;
sPanel.DragMode := dmAutomatic;
maxRight := max(maxRight, sPanel.Left+sPanel.Width);
maxBottom := max(maxBottom, sPanel.Top+sPanel.Height);
end;
Panel.Width := maxRight+2;
Panel.Height := maxBottom+2;
finally
Panel.Show;
end;
end;
procedure TMinesRenderer.Render(OnlyChanged : boolean);
procedure StandardSetting(Panel : TPanel);
begin
Panel.BevelOuter := bvRaised;
Panel.Caption := '';
Panel.BevelWidth := 2;
end;
var
i : integer;
Square : TSquare;
sPanel : TPanel;
begin
PanelsUpdated := 0;
for i := 0 to Mines.SquareList.Count-1 do
begin
Square := Mines.SquareList[i];
if OnlyChanged and not Square.Changed then
continue;
inc(PanelsUpdated);
sPanel := TPanel(Square.Data);
case Square.Status of
ssHidden :
begin
StandardSetting(sPanel);
end;
ssFlag :
begin
StandardSetting(sPanel);
sPanel.Caption := 'F';
end;
ssQuestion :
begin
StandardSetting(sPanel);
sPanel.Caption := '?';
end;
ssRevealed :
begin
sPanel.BevelOuter := bvNone;
{ sPanel.BorderWidth := 1;
sPanel.BorderStyle := bsSingle;
sPanel.Ctl3D := false;//}
if Square.NeighbouringMines>0 then
begin
if Square.NeighbouringMines=1 then
sPanel.Font.Color := clBlue;
if Square.NeighbouringMines=2 then
sPanel.Font.Color := clGreen;
if Square.NeighbouringMines=3 then
sPanel.Font.Color := clRed;
if Square.NeighbouringMines=4 then
sPanel.Font.Color := clNavy;
if Square.NeighbouringMines=5 then
sPanel.Font.Color := clTeal;
if Square.NeighbouringMines=6 then
sPanel.Font.Color := clTeal;
if Square.NeighbouringMines=7 then
sPanel.Font.Color := clTeal;
if Square.NeighbouringMines=8 then
sPanel.Font.Color := clTeal;
sPanel.Caption := IntToStr(Square.NeighbouringMines);
end;
end;
ssExploded :
begin
sPanel.BevelOuter := bvNone;
sPanel.Font.Color := clRed;
sPanel.Caption := 'X';
end;
ssErrorFlag :
begin
sPanel.Font.Color := clRed;
sPanel.Caption := 'f';
end;
end;
if Square.Signalled then
sPanel.BevelOuter := bvNone;
Square.Changed := false;
end;
end;
procedure TMinesRenderer.SquarePanelClick(Sender: TObject);
var
Square : TSquare;
sPanel : TPanel;
begin
sPanel := TPanel(Sender);
Square := TSquare(sPanel.Tag);
Square.ClickedReveal(True);
Render(true);
end;
procedure TMinesRenderer.SquarePanelDragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
begin
// This is needed to allow the user to shift around the cursor while clicked
TControl(Sender).EndDrag(false);
end;
procedure TMinesRenderer.SquarePanelMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
Square : TSquare;
sPanel : TPanel;
begin
sPanel := TPanel(Sender);
Square := TSquare(sPanel.Tag);
//if LastFocusPanel <> sPanel then
begin
LastFocusPanel := sPanel;
Mines.TurnOfSignals;
if ssLeft in Shift then
begin
if not (ssShift in Shift) then
Square.Signal
else
Square.SignalWide;
end;
Render(true);
Application.ProcessMessages;
end;
end;
procedure TMinesRenderer.SquarePanelMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Square : TSquare;
sPanel : TPanel;
begin
Mines.TurnOfSignals;
if Button = mbLeft then
begin
sPanel := TPanel(Sender);
Square := TSquare(sPanel.Tag);
if ssShift in Shift then
Square.ClickedRevealWide
else
Square.ClickedReveal(True);
Render(true);
end;
end;
procedure TMinesRenderer.SquarePanelRightClick(Sender: TObject;
MousePos: TPoint; var Handled: Boolean);
var
Square : TSquare;
sPanel : TPanel;
begin
Handled := true;
sPanel := TPanel(Sender);
Square := TSquare(sPanel.Tag);
Square.ClickedFlag;
Render(true);
end;
end.
|
unit TB97Tlwn;
{
Toolbar97
Copyright (C) 1998-2004 by Jordan Russell
http://www.jrsoftware.org/
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
TToolWindow97
$jrsoftware: tb97/Source/TB97Tlwn.pas,v 1.3 2004/02/23 22:53:00 jr Exp $
}
interface
{$I TB97Ver.inc}
uses
Windows, Classes, Controls, TB97;
type
{ TToolWindow97 }
TToolWindow97 = class(TCustomToolWindow97)
private
FMinClientWidth, FMinClientHeight: Integer;
FBarHeight, FBarWidth: Integer;
function GetClientAreaWidth: Integer;
procedure SetClientAreaWidth (Value: Integer);
function GetClientAreaHeight: Integer;
procedure SetClientAreaHeight (Value: Integer);
procedure SetClientAreaSize (AWidth, AHeight: Integer);
protected
procedure GetBarSize (var ASize: Integer; const DockType: TDockType); override;
procedure GetMinimumSize (var AClientWidth, AClientHeight: Integer); override;
function OrderControls (CanMoveControls: Boolean; PreviousDockType: TDockType;
DockingTo: TDock97): TPoint; override;
procedure SizeChanging (const AWidth, AHeight: Integer); override;
public
constructor Create (AOwner: TComponent); override;
procedure ReadPositionData (const ReadIntProc: TPositionReadIntProc;
const ReadStringProc: TPositionReadStringProc; const ExtraData: Pointer); override;
procedure WritePositionData (const WriteIntProc: TPositionWriteIntProc;
const WriteStringProc: TPositionWriteStringProc; const ExtraData: Pointer); override;
published
property ActivateParent;
property BorderStyle;
property Caption;
property Color;
property CloseButton;
property CloseButtonWhenDocked;
property ClientAreaHeight: Integer read GetClientAreaHeight write SetClientAreaHeight;
property ClientAreaWidth: Integer read GetClientAreaWidth write SetClientAreaWidth;
property DefaultDock;
property DockableTo;
property DockedTo;
property DockMode;
property DockPos;
property DockRow;
property DragHandleStyle;
property FloatingMode;
property Font;
property FullSize;
property HideWhenInactive;
property LastDock;
property MinClientHeight: Integer read FMinClientHeight write FMinClientHeight default 32;
property MinClientWidth: Integer read FMinClientWidth write FMinClientWidth default 32;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property Resizable;
property ShowCaption;
property ShowHint;
property TabOrder;
property UseLastDock;
property Version;
property Visible;
property OnClose;
property OnCloseQuery;
property OnDragDrop;
property OnDragOver;
property OnDockChanged;
property OnDockChanging;
property OnDockChangingEx;
property OnDockChangingHidden;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMove;
property OnRecreated;
property OnRecreating;
property OnResize;
property OnVisibleChanged;
end;
implementation
const
{ Constants for TToolWindow97-specific registry values. Do not localize! }
rvClientWidth = 'ClientWidth';
rvClientHeight = 'ClientHeight';
{ TToolWindow97 }
constructor TToolWindow97.Create (AOwner: TComponent);
begin
inherited;
FMinClientWidth := 32;
FMinClientHeight := 32;
{ Initialize the client size to 32x32 }
SetBounds (Left, Top, 32, 32);
end;
procedure TToolWindow97.ReadPositionData (const ReadIntProc: TPositionReadIntProc;
const ReadStringProc: TPositionReadStringProc; const ExtraData: Pointer);
begin
inherited;
{ Restore ClientAreaWidth/ClientAreaHeight variables }
if Resizable then
SetClientAreaSize (ReadIntProc(Name, rvClientWidth, FBarWidth, ExtraData),
ReadIntProc(Name, rvClientHeight, FBarHeight, ExtraData));
end;
procedure TToolWindow97.WritePositionData (const WriteIntProc: TPositionWriteIntProc;
const WriteStringProc: TPositionWriteStringProc; const ExtraData: Pointer);
begin
inherited;
{ Write values of FBarWidth/FBarHeight }
WriteIntProc (Name, rvClientWidth, FBarWidth, ExtraData);
WriteIntProc (Name, rvClientHeight, FBarHeight, ExtraData);
end;
procedure TToolWindow97.GetMinimumSize (var AClientWidth, AClientHeight: Integer);
begin
AClientWidth := FMinClientWidth;
AClientHeight := FMinClientHeight;
end;
procedure TToolWindow97.SizeChanging (const AWidth, AHeight: Integer);
begin
FBarWidth := AWidth;
if Parent <> nil then Dec (FBarWidth, Width - ClientWidth);
FBarHeight := AHeight;
if Parent <> nil then Dec (FBarHeight, Height - ClientHeight);
end;
procedure TToolWindow97.GetBarSize (var ASize: Integer; const DockType: TDockType);
begin
if DockType <> dtLeftRight then
ASize := FBarHeight
else
ASize := FBarWidth;
end;
function TToolWindow97.OrderControls (CanMoveControls: Boolean;
PreviousDockType: TDockType; DockingTo: TDock97): TPoint;
begin
Result.X := FBarWidth;
Result.Y := FBarHeight;
end;
function TToolWindow97.GetClientAreaWidth: Integer;
begin
if Parent = nil then
Result := Width
else
Result := ClientWidth;
end;
procedure TToolWindow97.SetClientAreaWidth (Value: Integer);
begin
SetClientAreaSize (Value, ClientAreaHeight);
end;
function TToolWindow97.GetClientAreaHeight: Integer;
begin
if Parent = nil then
Result := Height
else
Result := ClientHeight;
end;
procedure TToolWindow97.SetClientAreaHeight (Value: Integer);
begin
SetClientAreaSize (ClientAreaWidth, Value);
end;
procedure TToolWindow97.SetClientAreaSize (AWidth, AHeight: Integer);
var
Client: TRect;
begin
if Parent = nil then
SetBounds (Left, Top, AWidth, AHeight)
else begin
Client := GetClientRect;
SetBounds (Left, Top, Width - Client.Right + AWidth,
Height - Client.Bottom + AHeight);
end;
end;
end.
|
unit Datapar.Model.Main;
interface
uses
Datapar.Conexao,
Datapar.Conexao.Factory;
type
TDataparModelMain = class
private
{ Private declarations }
fModoConexao: TDataparModoConexao;
fProvider: TDataparProvider;
protected
function getInstance: TDataparQuery;
public
{ Public declarations }
constructor Create;
end;
var
DMConexao: TDataparModelMain;
implementation
constructor TDataparModelMain.Create;
begin
fModoConexao := mcDOA;
fProvider := TDataparProvider.create('DATAPAR.DESENV.COM','geo_colonial','supergeo_colonial','Oracle');
end;
function TDataparModelMain.getInstance: TDataparQuery;
begin
Result := TDataparFactory.CreateInstance(fModoConexao,fProvider);
end;
end.
|
unit Magento.GalleryContent;
interface
uses
Magento.Interfaces, System.JSON, IdCoderMIME;
type
TMagentoMediaGaleryContent = class (TInterfacedObject, iMagentoMediaGaleryContent)
private
FParent : iMagentoMediaGalleryEntries;
FJSON : TJSONObject;
FJSONArray : TJSONArray;
function Base64_Encoding(FileName : String) : String;
public
constructor Create(Parent : iMagentoMediaGalleryEntries);
destructor Destroy; override;
class function New(Parent : iMagentoMediaGalleryEntries) : iMagentoMediaGaleryContent;
function Base64EncodedData(value : String) : iMagentoMediaGaleryContent; //passar somente o caminho da imagem
function &Type(value : string) : iMagentoMediaGaleryContent;//passar o tipo da imagem png,gif,bpm e jpeg(jpg)
function Name(value : String) : iMagentoMediaGaleryContent;
function &End : iMagentoMediaGalleryEntries;
end;
implementation
uses
System.Classes, System.SysUtils;
{ TMagentoMediaGaleryContent }
function TMagentoMediaGaleryContent.Base64EncodedData(
value: String): iMagentoMediaGaleryContent;
begin
Result := Self;
FJSON.AddPair('base64EncodedData', Base64_Encoding(value));
end;
function TMagentoMediaGaleryContent.&End: iMagentoMediaGalleryEntries;
begin
FJSONArray.Add(FJSON);
FParent.Content(FJSON);
Result := FParent;
end;
function TMagentoMediaGaleryContent.&Type(
value: string): iMagentoMediaGaleryContent;
begin
Result := Self;
FJSON.AddPair('type',value);
end;
function TMagentoMediaGaleryContent.Base64_Encoding(FileName: String): String;
var
stream: TFileStream;
base64: TIdEncoderMIME;
output: string;
begin
Result := 'Error';
if (FileExists(FileName)) then
begin
try
base64 := TIdEncoderMIME.Create(nil);
stream := TFileStream.Create(FileName, fmOpenRead);
output := TIdEncoderMIME.EncodeStream(stream);
stream.Free;
base64.Free;
if not(output = '') then
Result := output
except
raise Exception.Create('Error convert image');
end;
end;
end;
constructor TMagentoMediaGaleryContent.Create(Parent : iMagentoMediaGalleryEntries);
begin
FParent := Parent;
FJSON := TJSONObject.Create;
FJSONArray := TJSONArray.Create;
end;
destructor TMagentoMediaGaleryContent.Destroy;
begin
inherited;
end;
function TMagentoMediaGaleryContent.Name(
value: String): iMagentoMediaGaleryContent;
begin
Result := Self;
FJSON.AddPair('name', value);
end;
class function TMagentoMediaGaleryContent.New(Parent : iMagentoMediaGalleryEntries) : iMagentoMediaGaleryContent;
begin
Result := self.Create(Parent);
end;
end.
|
(*
* FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*)
unit ufrmAbout;
interface
uses
LCLIntf, LCLType,SysUtils, Classes, Graphics, Controls, Forms,
StdCtrls, Buttons, ComCtrls, ExtCtrls, uLanguage, uIniFile;
type
{ TfrmAbout }
TfrmAbout = class(TForm)
Button1: TButton;
PageControl1: TPageControl;
Panel1: TPanel;
tsDescription: TTabSheet;
tsCharacteristic: TTabSheet;
Memo2: TMemo;
Memo1: TMemo;
tsCredits: TTabSheet;
Memo3: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure Memo3Change(Sender: TObject);
procedure PageControl1Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmAbout: TfrmAbout;
implementation
{$R *.lfm}
procedure TfrmAbout.FormActivate(Sender: TObject);
begin
//frmAbout.Caption := LNG_STRINGS[28];
//tsDescription.Caption := LNG_STRINGS[56];
//tsCharacteristic.Caption := LNG_STRINGS[81];
//tsCredits.Caption := LNG_STRINGS[80];
end;
procedure TfrmAbout.Memo3Change(Sender: TObject);
begin
end;
procedure TfrmAbout.PageControl1Change(Sender: TObject);
begin
end;
procedure TfrmAbout.Button1Click(Sender: TObject);
begin
Close;
end;
end.
|
Unit UnitBytesSize;
interface
uses
windows;
function BytesSize(size: int64): string;
function HertzSize(size: int64): string;
implementation
type
TFormatSettings = record
CurrencyFormat: Byte;
NegCurrFormat: Byte;
ThousandSeparator: Char;
DecimalSeparator: Char;
CurrencyDecimals: Byte;
DateSeparator: Char;
TimeSeparator: Char;
ListSeparator: Char;
CurrencyString: string;
ShortDateFormat: string;
LongDateFormat: string;
TimeAMString: string;
TimePMString: string;
ShortTimeFormat: string;
LongTimeFormat: string;
ShortMonthNames: array[1..12] of string;
LongMonthNames: array[1..12] of string;
ShortDayNames: array[1..7] of string;
LongDayNames: array[1..7] of string;
TwoDigitYearCenturyWindow: Word;
end;
TFloatRec = packed record
Exponent: Smallint;
Negative: Boolean;
Digits: array[0..20] of Char;
end;
var
ThousandSeparator: Char;
DecimalSeparator: Char;
TwoDigitYearCenturyWindow: Word = 50;
type
TFloatValue = (fvExtended, fvCurrency);
TFloatFormat = (ffGeneral, ffExponent, ffFixed, ffNumber, ffCurrency);
const
Const1E18Lo = $0A7640000;
Const1E18Hi = $00DE0B6B3;
FCon1E18: Extended = 1E18;
DCon10: Integer = 10;
mC0 = $0100;
mC3 = $4000;
procedure PutExponent;
// Store exponent
// In AL = Exponent character ('E' or 'e')
// AH = Positive sign character ('+' or 0)
// BL = Zero indicator
// ECX = Minimum number of digits (0..4)
// EDX = Exponent
// EDI = Destination buffer
asm
PUSH ESI
{$IFDEF PIC}
PUSH EAX
PUSH ECX
CALL GetGOT
MOV ESI,EAX
POP ECX
POP EAX
{$ELSE}
XOR ESI,ESI
{$ENDIF}
STOSB
OR BL,BL
JNE @@0
XOR EDX,EDX
JMP @@1
@@0: OR EDX,EDX
JGE @@1
MOV AL,'-'
NEG EDX
JMP @@2
@@1: OR AH,AH
JE @@3
MOV AL,AH
@@2: STOSB
@@3: XCHG EAX,EDX
PUSH EAX
MOV EBX,ESP
@@4: XOR EDX,EDX
DIV [ESI].DCon10
ADD DL,'0'
MOV [EBX],DL
INC EBX
DEC ECX
OR EAX,EAX
JNE @@4
OR ECX,ECX
JG @@4
@@5: DEC EBX
MOV AL,[EBX]
STOSB
CMP EBX,ESP
JNE @@5
POP EAX
POP ESI
end;
procedure FloatToDecimal(var Result: TFloatRec; const Value;
ValueType: TFloatValue; Precision, Decimals: Integer);
var
StatWord: Word;
Exponent: Integer;
Temp: Double;
BCDValue: Extended;
SaveGOT: Pointer;
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV EBX,EAX
MOV ESI,EDX
{$IFDEF PIC}
PUSH ECX
CALL GetGOT
POP ECX
MOV SaveGOT,EAX
{$ELSE}
MOV SaveGOT,0
{$ENDIF}
CMP CL,fvExtended
JE @@1
CALL @@CurrToDecimal
JMP @@Exit
@@1: CALL @@ExtToDecimal
JMP @@Exit
// Convert Extended to decimal
@@ExtToDecimal:
MOV AX,[ESI].Word[8]
MOV EDX,EAX
AND EAX,7FFFH
JE @@ed1
CMP EAX,7FFFH
JNE @@ed10
// check for special values (INF, NAN)
TEST [ESI].Word[6],8000H
JZ @@ed2
// any significand bit set = NAN
// all significand bits clear = INF
CMP dword ptr [ESI], 0
JNZ @@ed0
CMP dword ptr [ESI+4], 80000000H
JZ @@ed2
@@ed0: INC EAX
@@ed1: XOR EDX,EDX
@@ed2: MOV [EBX].TFloatRec.Digits.Byte,0
JMP @@ed31
@@ed10: FLD TBYTE PTR [ESI]
SUB EAX,3FFFH
IMUL EAX,19728
SAR EAX,16
INC EAX
MOV Exponent,EAX
MOV EAX,18
SUB EAX,Exponent
FABS
PUSH EBX
MOV EBX,SaveGOT
CALL FPower10
POP EBX
FRNDINT
MOV EDI,SaveGOT
FLD [EDI].FCon1E18
FCOMP
FSTSW StatWord
FWAIT
TEST StatWord,mC0+mC3
JE @@ed11
FIDIV [EDI].DCon10
INC Exponent
@@ed11: FBSTP BCDValue
LEA EDI,[EBX].TFloatRec.Digits
MOV EDX,9
FWAIT
@@ed12: MOV AL,BCDValue[EDX-1].Byte
MOV AH,AL
SHR AL,4
AND AH,0FH
ADD AX,'00'
STOSW
DEC EDX
JNE @@ed12
XOR AL,AL
STOSB
@@ed20: MOV EDI,Exponent
ADD EDI,Decimals
JNS @@ed21
XOR EAX,EAX
JMP @@ed1
@@ed21: CMP EDI,Precision
JB @@ed22
MOV EDI,Precision
@@ed22: CMP EDI,18
JAE @@ed26
CMP [EBX].TFloatRec.Digits.Byte[EDI],'5'
JB @@ed25
@@ed23: MOV [EBX].TFloatRec.Digits.Byte[EDI],0
DEC EDI
JS @@ed24
INC [EBX].TFloatRec.Digits.Byte[EDI]
CMP [EBX].TFloatRec.Digits.Byte[EDI],'9'
JA @@ed23
JMP @@ed30
@@ed24: MOV [EBX].TFloatRec.Digits.Word,'1'
INC Exponent
JMP @@ed30
@@ed26: MOV EDI,18
@@ed25: MOV [EBX].TFloatRec.Digits.Byte[EDI],0
DEC EDI
JS @@ed32
CMP [EBX].TFloatRec.Digits.Byte[EDI],'0'
JE @@ed25
@@ed30: MOV DX,[ESI].Word[8]
@@ed30a:
MOV EAX,Exponent
@@ed31: SHR DX,15
MOV [EBX].TFloatRec.Exponent,AX
MOV [EBX].TFloatRec.Negative,DL
RET
@@ed32: XOR EDX,EDX
JMP @@ed30a
@@DecimalTable:
DD 10
DD 100
DD 1000
DD 10000
// Convert Currency to decimal
@@CurrToDecimal:
MOV EAX,[ESI].Integer[0]
MOV EDX,[ESI].Integer[4]
MOV ECX,EAX
OR ECX,EDX
JE @@cd20
OR EDX,EDX
JNS @@cd1
NEG EDX
NEG EAX
SBB EDX,0
@@cd1: XOR ECX,ECX
MOV EDI,Decimals
OR EDI,EDI
JGE @@cd2
XOR EDI,EDI
@@cd2: CMP EDI,4
JL @@cd4
MOV EDI,4
@@cd3: INC ECX
SUB EAX,Const1E18Lo
SBB EDX,Const1E18Hi
JNC @@cd3
DEC ECX
ADD EAX,Const1E18Lo
ADC EDX,Const1E18Hi
@@cd4: MOV Temp.Integer[0],EAX
MOV Temp.Integer[4],EDX
FILD Temp
MOV EDX,EDI
MOV EAX,4
SUB EAX,EDX
JE @@cd5
MOV EDI,SaveGOT
FIDIV @@DecimalTable.Integer[EDI+EAX*4-4]
@@cd5: FBSTP BCDValue
LEA EDI,[EBX].TFloatRec.Digits
FWAIT
OR ECX,ECX
JNE @@cd11
MOV ECX,9
@@cd10: MOV AL,BCDValue[ECX-1].Byte
MOV AH,AL
SHR AL,4
JNE @@cd13
MOV AL,AH
AND AL,0FH
JNE @@cd14
DEC ECX
JNE @@cd10
JMP @@cd20
@@cd11: MOV AL,CL
ADD AL,'0'
STOSB
MOV ECX,9
@@cd12: MOV AL,BCDValue[ECX-1].Byte
MOV AH,AL
SHR AL,4
@@cd13: ADD AL,'0'
STOSB
MOV AL,AH
AND AL,0FH
@@cd14: ADD AL,'0'
STOSB
DEC ECX
JNE @@cd12
MOV EAX,EDI
LEA ECX,[EBX].TFloatRec.Digits[EDX]
SUB EAX,ECX
@@cd15: MOV BYTE PTR [EDI],0
DEC EDI
CMP BYTE PTR [EDI],'0'
JE @@cd15
MOV EDX,[ESI].Integer[4]
SHR EDX,31
JMP @@cd21
@@cd20: XOR EAX,EAX
XOR EDX,EDX
MOV [EBX].TFloatRec.Digits.Byte[0],AL
@@cd21: MOV [EBX].TFloatRec.Exponent,AX
MOV [EBX].TFloatRec.Negative,DL
RET
@@Exit:
POP EBX
POP ESI
POP EDI
end;
function FloatToText(BufferArg: PChar; const Value; ValueType: TFloatValue;
Format: TFloatFormat; Precision, Digits: Integer;
const FormatSettings: TFormatSettings): Integer;
var
Buffer: Cardinal;
FloatRec: TFloatRec;
SaveGOT: Integer;
DecimalSep: Char;
ThousandSep: Char;
CurrencyStr: Pointer;
CurrFmt: Byte;
NegCurrFmt: Byte;
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV Buffer,EAX
{$IFDEF PIC}
PUSH ECX
CALL GetGOT
MOV SaveGOT,EAX
POP ECX
{$ENDIF}
MOV EAX,FormatSettings
MOV AL,[EAX].TFormatSettings.DecimalSeparator
MOV DecimalSep,AL
MOV EAX,FormatSettings
MOV AL,[EAX].TFormatSettings.ThousandSeparator
MOV ThousandSep,AL
MOV EAX,FormatSettings
MOV EAX,[EAX].TFormatSettings.CurrencyString
MOV CurrencyStr,EAX
MOV EAX,FormatSettings
MOV AL,[EAX].TFormatSettings.CurrencyFormat
MOV CurrFmt,AL
MOV EAX,FormatSettings
MOV AL,[EAX].TFormatSettings.NegCurrFormat
MOV NegCurrFmt,AL
MOV SaveGOT,0
MOV EAX,19
CMP CL,fvExtended
JNE @@2
MOV EAX,Precision
CMP EAX,2
JGE @@1
MOV EAX,2
@@1: CMP EAX,18
JLE @@2
MOV EAX,18
@@2: MOV Precision,EAX
PUSH EAX
MOV EAX,9999
CMP Format,ffFixed
JB @@3
MOV EAX,Digits
@@3: PUSH EAX
LEA EAX,FloatRec
CALL FloatToDecimal
MOV EDI,Buffer
MOVZX EAX,FloatRec.Exponent
SUB EAX,7FFFH
CMP EAX,2
JAE @@4
MOV ECX, EAX
CALL @@PutSign
LEA ESI,@@INFNAN[ECX+ECX*2]
ADD ESI,SaveGOT
MOV ECX,3
REP MOVSB
JMP @@7
@@4: LEA ESI,FloatRec.Digits
MOVZX EBX,Format
CMP BL,ffExponent
JE @@6
CMP BL,ffCurrency
JA @@5
MOVSX EAX,FloatRec.Exponent
CMP EAX,Precision
JLE @@6
@@5: MOV BL,ffGeneral
@@6: LEA EBX,@@FormatVector[EBX*4]
ADD EBX,SaveGOT
MOV EBX,[EBX]
ADD EBX,SaveGOT
CALL EBX
@@7: MOV EAX,EDI
SUB EAX,Buffer
POP EBX
POP ESI
POP EDI
JMP @@Exit
@@FormatVector:
DD @@PutFGeneral
DD @@PutFExponent
DD @@PutFFixed
DD @@PutFNumber
DD @@PutFCurrency
@@INFNAN: DB 'INFNAN'
// Get digit or '0' if at end of digit string
@@GetDigit:
LODSB
OR AL,AL
JNE @@a1
MOV AL,'0'
DEC ESI
@@a1: RET
// Store '-' if number is negative
@@PutSign:
CMP FloatRec.Negative,0
JE @@b1
MOV AL,'-'
STOSB
@@b1: RET
// Convert number using ffGeneral format
@@PutFGeneral:
CALL @@PutSign
MOVSX ECX,FloatRec.Exponent
XOR EDX,EDX
CMP ECX,Precision
JG @@c1
CMP ECX,-3
JL @@c1
OR ECX,ECX
JG @@c2
MOV AL,'0'
STOSB
CMP BYTE PTR [ESI],0
JE @@c6
MOV AL,DecimalSep
STOSB
NEG ECX
MOV AL,'0'
REP STOSB
JMP @@c3
@@c1: MOV ECX,1
INC EDX
@@c2: LODSB
OR AL,AL
JE @@c4
STOSB
LOOP @@c2
LODSB
OR AL,AL
JE @@c5
MOV AH,AL
MOV AL,DecimalSep
STOSW
@@c3: LODSB
OR AL,AL
JE @@c5
STOSB
JMP @@c3
@@c4: MOV AL,'0'
REP STOSB
@@c5: OR EDX,EDX
JE @@c6
XOR EAX,EAX
JMP @@PutFloatExpWithDigits
@@c6: RET
// Convert number using ffExponent format
@@PutFExponent:
CALL @@PutSign
CALL @@GetDigit
MOV AH,DecimalSep
STOSW
MOV ECX,Precision
DEC ECX
@@d1: CALL @@GetDigit
STOSB
LOOP @@d1
MOV AH,'+'
@@PutFloatExpWithDigits:
MOV ECX,Digits
CMP ECX,4
JBE @@PutFloatExp
XOR ECX,ECX
// Store exponent
// In AH = Positive sign character ('+' or 0)
// ECX = Minimum number of digits (0..4)
@@PutFloatExp:
MOV AL,'E'
MOV BL, FloatRec.Digits.Byte
MOVSX EDX,FloatRec.Exponent
DEC EDX
CALL PutExponent
RET
// Convert number using ffFixed or ffNumber format
@@PutFFixed:
@@PutFNumber:
CALL @@PutSign
// Store number in fixed point format
@@PutNumber:
MOV EDX,Digits
CMP EDX,18
JB @@f1
MOV EDX,18
@@f1: MOVSX ECX,FloatRec.Exponent
OR ECX,ECX
JG @@f2
MOV AL,'0'
STOSB
JMP @@f4
@@f2: XOR EBX,EBX
CMP Format,ffFixed
JE @@f3
MOV EAX,ECX
DEC EAX
MOV BL,3
DIV BL
MOV BL,AH
INC EBX
@@f3: CALL @@GetDigit
STOSB
DEC ECX
JE @@f4
DEC EBX
JNE @@f3
MOV AL,ThousandSep
TEST AL,AL
JZ @@f3
STOSB
MOV BL,3
JMP @@f3
@@f4: OR EDX,EDX
JE @@f7
MOV AL,DecimalSep
TEST AL,AL
JZ @@f4b
STOSB
@@f4b: JECXZ @@f6
MOV AL,'0'
@@f5: STOSB
DEC EDX
JE @@f7
INC ECX
JNE @@f5
@@f6: CALL @@GetDigit
STOSB
DEC EDX
JNE @@f6
@@f7: RET
// Convert number using ffCurrency format
@@PutFCurrency:
XOR EBX,EBX
MOV BL,CurrFmt.Byte
MOV ECX,0003H
CMP FloatRec.Negative,0
JE @@g1
MOV BL,NegCurrFmt.Byte
MOV ECX,040FH
@@g1: CMP BL,CL
JBE @@g2
MOV BL,CL
@@g2: ADD BL,CH
LEA EBX,@@MoneyFormats[EBX+EBX*4]
ADD EBX,SaveGOT
MOV ECX,5
@@g10: MOV AL,[EBX]
CMP AL,'@'
JE @@g14
PUSH ECX
PUSH EBX
CMP AL,'$'
JE @@g11
CMP AL,'*'
JE @@g12
STOSB
JMP @@g13
@@g11: CALL @@PutCurSym
JMP @@g13
@@g12: CALL @@PutNumber
@@g13: POP EBX
POP ECX
INC EBX
LOOP @@g10
@@g14: RET
// Store currency symbol string
@@PutCurSym:
PUSH ESI
MOV ESI,CurrencyStr
TEST ESI,ESI
JE @@h1
MOV ECX,[ESI-4]
REP MOVSB
@@h1: POP ESI
RET
// Currency formatting templates
@@MoneyFormats:
DB '$*@@@'
DB '*$@@@'
DB '$ *@@'
DB '* $@@'
DB '($*)@'
DB '-$*@@'
DB '$-*@@'
DB '$*-@@'
DB '(*$)@'
DB '-*$@@'
DB '*-$@@'
DB '*$-@@'
DB '-* $@'
DB '-$ *@'
DB '* $-@'
DB '$ *-@'
DB '$ -*@'
DB '*- $@'
DB '($ *)'
DB '(* $)'
@@Exit:
end;
function FloatToTextFmt(Buf: PChar; const Value; ValueType: TFloatValue;
Format: PChar): Integer;
var
Buffer: Pointer;
ThousandSep: Boolean;
DecimalSep: Char;
ThousandsSep: Char;
Scientific: Boolean;
Section: Integer;
DigitCount: Integer;
DecimalIndex: Integer;
FirstDigit: Integer;
LastDigit: Integer;
DigitPlace: Integer;
DigitDelta: Integer;
FloatRec: TFloatRec;
SaveGOT: Pointer;
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV Buffer,EAX
MOV EDI,EDX
MOV EBX,ECX
{$IFDEF PIC}
CALL GetGOT
MOV SaveGOT,EAX
MOV ECX,[EAX].OFFSET DecimalSeparator
MOV CL,[ECX].Byte
MOV DecimalSep,CL
MOV ECX,[EAX].OFFSET ThousandSeparator
MOV CL,[ECX].Byte
MOV ThousandsSep,CL
{$ELSE}
MOV SaveGOT,0
MOV AL,DecimalSeparator
MOV DecimalSep,AL
MOV AL,ThousandSeparator
MOV ThousandsSep,AL
{$ENDIF}
MOV ECX,2
CMP BL,fvExtended
JE @@1
MOV EAX,[EDI].Integer
OR EAX,[EDI].Integer[4]
JE @@2
MOV ECX,[EDI].Integer[4]
SHR ECX,31
JMP @@2
@@1: MOVZX EAX,[EDI].Word[8]
OR EAX,[EDI].Integer[0]
OR EAX,[EDI].Integer[4]
JE @@2
MOVZX ECX,[EDI].Word[8]
SHR ECX,15
@@2: CALL @@FindSection
JE @@5
CALL @@ScanSection
MOV EAX,DigitCount
MOV EDX,9999
CMP Scientific,0
JNE @@3
SUB EAX,DecimalIndex
MOV EDX,EAX
MOV EAX,18
@@3: PUSH EAX
PUSH EDX
LEA EAX,FloatRec
MOV EDX,EDI
MOV ECX,EBX
CALL FloatToDecimal
MOV AX,FloatRec.Exponent
CMP AX,8000H
JE @@5
CMP AX,7FFFH
JE @@5
CMP BL,fvExtended
JNE @@6
CMP AX,18
JLE @@6
CMP Scientific,0
JNE @@6
@@5: PUSH ffGeneral
PUSH 15
PUSH 0
MOV EAX,Buffer
MOV EDX,EDI
MOV ECX,EBX
CALL FloatToText
JMP @@Exit
@@6: CMP FloatRec.Digits.Byte,0
JNE @@7
MOV ECX,2
CALL @@FindSection
JE @@5
CMP ESI,Section
JE @@7
CALL @@ScanSection
@@7: CALL @@ApplyFormat
JMP @@Exit
// Find format section
// In ECX = Section index
// Out ESI = Section offset
// ZF = 1 if section is empty
@@FindSection:
MOV ESI,Format
JECXZ @@fs2
@@fs1: LODSB
CMP AL,"'"
JE @@fs4
CMP AL,'"'
JE @@fs4
OR AL,AL
JE @@fs2
CMP AL,';'
JNE @@fs1
LOOP @@fs1
MOV AL,byte ptr [ESI]
OR AL,AL
JE @@fs2
CMP AL,';'
JNE @@fs3
@@fs2: MOV ESI,Format
MOV AL,byte ptr [ESI]
OR AL,AL
JE @@fs3
CMP AL,';'
@@fs3: RET
@@fs4: MOV AH,AL
@@fs5: LODSB
CMP AL,AH
JE @@fs1
OR AL,AL
JNE @@fs5
JMP @@fs2
// Scan format section
@@ScanSection:
PUSH EBX
MOV Section,ESI
MOV EBX,32767
XOR ECX,ECX
XOR EDX,EDX
MOV DecimalIndex,-1
MOV ThousandSep,DL
MOV Scientific,DL
@@ss1: LODSB
@@ss2: CMP AL,'#'
JE @@ss10
CMP AL,'0'
JE @@ss11
CMP AL,'.'
JE @@ss13
CMP AL,','
JE @@ss14
CMP AL,"'"
JE @@ss15
CMP AL,'"'
JE @@ss15
CMP AL,'E'
JE @@ss20
CMP AL,'e'
JE @@ss20
CMP AL,';'
JE @@ss30
OR AL,AL
JNE @@ss1
JMP @@ss30
@@ss10: INC EDX
JMP @@ss1
@@ss11: CMP EDX,EBX
JGE @@ss12
MOV EBX,EDX
@@ss12: INC EDX
MOV ECX,EDX
JMP @@ss1
@@ss13: CMP DecimalIndex,-1
JNE @@ss1
MOV DecimalIndex,EDX
JMP @@ss1
@@ss14: MOV ThousandSep,1
JMP @@ss1
@@ss15: MOV AH,AL
@@ss16: LODSB
CMP AL,AH
JE @@ss1
OR AL,AL
JNE @@ss16
JMP @@ss30
@@ss20: LODSB
CMP AL,'-'
JE @@ss21
CMP AL,'+'
JNE @@ss2
@@ss21: MOV Scientific,1
@@ss22: LODSB
CMP AL,'0'
JE @@ss22
JMP @@ss2
@@ss30: MOV DigitCount,EDX
CMP DecimalIndex,-1
JNE @@ss31
MOV DecimalIndex,EDX
@@ss31: MOV EAX,DecimalIndex
SUB EAX,ECX
JLE @@ss32
XOR EAX,EAX
@@ss32: MOV LastDigit,EAX
MOV EAX,DecimalIndex
SUB EAX,EBX
JGE @@ss33
XOR EAX,EAX
@@ss33: MOV FirstDigit,EAX
POP EBX
RET
// Apply format string
@@ApplyFormat:
CMP Scientific,0
JE @@af1
MOV EAX,DecimalIndex
XOR EDX,EDX
JMP @@af3
@@af1: MOVSX EAX,FloatRec.Exponent
CMP EAX,DecimalIndex
JG @@af2
MOV EAX,DecimalIndex
@@af2: MOVSX EDX,FloatRec.Exponent
SUB EDX,DecimalIndex
@@af3: MOV DigitPlace,EAX
MOV DigitDelta,EDX
MOV ESI,Section
MOV EDI,Buffer
LEA EBX,FloatRec.Digits
CMP FloatRec.Negative,0
JE @@af10
CMP ESI,Format
JNE @@af10
MOV AL,'-'
STOSB
@@af10: LODSB
CMP AL,'#'
JE @@af20
CMP AL,'0'
JE @@af20
CMP AL,'.'
JE @@af10
CMP AL,','
JE @@af10
CMP AL,"'"
JE @@af25
CMP AL,'"'
JE @@af25
CMP AL,'E'
JE @@af30
CMP AL,'e'
JE @@af30
CMP AL,';'
JE @@af40
OR AL,AL
JE @@af40
@@af11: STOSB
JMP @@af10
@@af20: CALL @@PutFmtDigit
JMP @@af10
@@af25: MOV AH,AL
@@af26: LODSB
CMP AL,AH
JE @@af10
OR AL,AL
JE @@af40
STOSB
JMP @@af26
@@af30: MOV AH,[ESI]
CMP AH,'+'
JE @@af31
CMP AH,'-'
JNE @@af11
XOR AH,AH
@@af31: MOV ECX,-1
@@af32: INC ECX
INC ESI
CMP [ESI].Byte,'0'
JE @@af32
CMP ECX,4
JB @@af33
MOV ECX,4
@@af33: PUSH EBX
MOV BL,FloatRec.Digits.Byte
MOVSX EDX,FloatRec.Exponent
SUB EDX,DecimalIndex
CALL PutExponent
POP EBX
JMP @@af10
@@af40: MOV EAX,EDI
SUB EAX,Buffer
RET
// Store formatted digit
@@PutFmtDigit:
CMP DigitDelta,0
JE @@fd3
JL @@fd2
@@fd1: CALL @@fd3
DEC DigitDelta
JNE @@fd1
JMP @@fd3
@@fd2: INC DigitDelta
MOV EAX,DigitPlace
CMP EAX,FirstDigit
JLE @@fd4
JMP @@fd7
@@fd3: MOV AL,[EBX]
INC EBX
OR AL,AL
JNE @@fd5
DEC EBX
MOV EAX,DigitPlace
CMP EAX,LastDigit
JLE @@fd7
@@fd4: MOV AL,'0'
@@fd5: CMP DigitPlace,0
JNE @@fd6
MOV AH,AL
MOV AL,DecimalSep
STOSW
JMP @@fd7
@@fd6: STOSB
CMP ThousandSep,0
JE @@fd7
MOV EAX,DigitPlace
CMP EAX,1
JLE @@fd7
MOV DL,3
DIV DL
CMP AH,1
JNE @@fd7
MOV AL,ThousandsSep
TEST AL,AL
JZ @@fd7
STOSB
@@fd7: DEC DigitPlace
RET
@@exit:
POP EBX
POP ESI
POP EDI
end;
function FormatFloat(const Format: string; Value: Extended): string;
var
Buffer: array[0..255] of Char;
begin
SetString(Result, Buffer, FloatToTextFmt(Buffer, Value, fvExtended,
PChar(Format)));
end;
function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer): Integer;
begin
if AValue then
Result := ATrue
else
Result := AFalse;
end;
function BytesSize(size: int64): string;
const
sizes: Array [0..6] of String = ('bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB');
var
i: integer;
tmp: real;
begin
tmp := size;
for i := Low(sizes) to High(sizes) do
begin
if tmp >= 1000 then
tmp := tmp / 1024
else break;
end;
Result := Copy(FormatFloat('0.00', tmp), 1, IfThen(tmp >= 100, 3, 4)) + #32 + sizes[i];
end;
function HertzSize(size: int64): string;
const
sizes: Array [0..6] of String = ('Hz', 'kHz', 'MHz', 'GHz', 'THz', 'PHz', 'EHz');
var
i: integer;
tmp: real;
begin
tmp := size;
for i := Low(sizes) to High(sizes) do
begin
if tmp >= 1000 then
tmp := tmp / 1024
else break;
end;
Result := Copy(FormatFloat('0.00', tmp), 1, IfThen(tmp >= 100, 3, 4)) + #32 + sizes[i];
end;
function GetLocaleChar(Locale, LocaleType: Integer; Default: Char): Char;
var
Buffer: array[0..1] of Char;
begin
if GetLocaleInfo(Locale, LocaleType, Buffer, 2) > 0 then
Result := Buffer[0] else
Result := Default;
end;
procedure GetFormatSettings;
var
HourFormat, TimePrefix, TimePostfix: string;
DefaultLCID: Integer;
begin
DefaultLCID := GetThreadLocale;
ThousandSeparator := GetLocaleChar(DefaultLCID, LOCALE_STHOUSAND, ',');
DecimalSeparator := GetLocaleChar(DefaultLCID, LOCALE_SDECIMAL, '.');
TimePrefix := '';
TimePostfix := '';
end;
begin
GetFormatSettings;
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit uUseful;
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils, Forms, Controls, Dialogs, ComCtrls;
type
IEldeanProgress = interface(IUnknown)
['{E446EEFB-DABB-4AD9-BE49-104A6F265CB4}']
procedure Tick;
end;
TEldeanProgress = class(TInterfacedObject,IEldeanProgress)
public
constructor Create(Text : string; Max : integer); reintroduce;
destructor Destroy; override;
procedure Tick;
private
P : TProgressBar;
F : TForm;
AbortNext : boolean;
end;
TBrowseForFolderDialog = class
private
FTitle,FPath : string;
public
property Title: string read FTitle write FTitle;
function Execute: Boolean;
property Path: string read FPath write FPath;
end;
function MakeTempDir : string;
implementation
var
RecentOpenFolderPath : string;
constructor TEldeanProgress.Create(Text: string; Max: integer);
begin
F := TForm.Create(Application.MainForm);
F.BorderIcons := [];
F.BorderStyle := bsDialog;
F.Caption := Text;
F.ClientHeight := 22;
F.ClientWidth := 390;
F.Position := poScreenCenter;
P := TProgressBar.Create(F);
P.Parent := F;
P.Align := alTop;
P.Height := 22;
P.Max := Max;
P.Step := 1;
P.Smooth := True;
F.Show;
end;
destructor TEldeanProgress.Destroy;
begin
FreeAndNil(F);
inherited;
end;
procedure TEldeanProgress.Tick;
begin
if AbortNext then
Abort;
P.StepIt;
Application.ProcessMessages;
end;
function TBrowseForFolderDialog.Execute: Boolean;
var
F : TSelectDirectoryDialog;
begin
F := TSelectDirectoryDialog.Create(Application.MainForm);
if Length(FPath) > 0 then
F.InitialDir := FPath
else
F.InitialDir := RecentOpenFolderPath;
F.Title := Title;
if F.Execute then
begin
FPath := f.FileName;
RecentOpenFolderPath := FPath;
Result := True;
end
else
Result := False;
F.Free;
end;
var
CleanUp : TStringList;
function MakeTempDir : string;
var
TempPath : string;
I : integer;
Ok : boolean;
begin
TempPath := GetTempDir(false);
Ok := False;
for I := 0 to 50 do
begin
Result := TempPath + 'Essmodel' + IntToStr(I);
if not DirectoryExists(Result) then
begin
MkDir( Result );
Ok := True;
Result := Result;
CleanUp.Add(Result);
Break;
end;
end;
if not Ok then
raise Exception.Create('Failed to create temp directory');
end;
procedure DoCleanUp;
var
I : integer;
DirInfo: TSearchRec;
Res: integer;
S : string;
begin
for I := 0 to CleanUp.Count-1 do
begin
S := CleanUp[I];
if Pos('Essmodel',S)=0 then
Continue; //Safety
Res := SysUtils.FindFirst(S + '\*.*', 0, DirInfo);
while Res = 0 do
begin
SysUtils.DeleteFile(S + '\' + DirInfo.Name);
Res := SysUtils.FindNext(DirInfo);
end;
SysUtils.FindClose(DirInfo);
RemoveDir(S);
end;
end;
initialization
CleanUp := TStringList.Create;
finalization
DoCleanUp;
CleanUp.Free;
end.
|
unit frmGameUnit;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
System.Generics.Collections, System.IOUtils, System.Actions,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Objects, FMX.Layouts,
FMX.Ani, FMX.StdCtrls, FMX.Effects, FMX.TabControl,
FMX.ActnList, FMX.ListBox, FMX.Edit;
resourcestring
cYourScoreWas = 'Your score was %d points';
const
cHallOfFameFileName = 'Hall.txt';
cInitialInterval = 500;
cTransitionAnimation = 0.2;
cFallAnimation = 0.1;
cRowCount = 9;
cColCount = 9;
cMinToMatch = 3;
cCellPoints = 50;
cMaxScores = 11;
cMaxTimeMultiplier = 3;
type
TJewels = (jEmpty, jEmerald, jRuby, jPearl, jDiamond, jSapphire, jAmber, jAmethyst);
TTextType = (ttScore, ttMultiplier);
const
cJewels: array[Low(TJewels) .. High(TJewels)] of string =
('Empty',
'Emerald',
'Ruby',
'Pearl',
'Diamond',
'Sapphire',
'Amber',
'Amethyst'
);
type
TBoardArray = array[0 .. cColCount - 1, 0 .. cRowCount - 1] of TJewels;
type
TCell = class(TImage)
public
X, Y: Byte;
VerticalAnimation, HorizontalAnimation: TFloatAnimation;
SelectionEffect: TFloatAnimation;
end;
TCellList = TList<TCell>;
type
TfrmGame = class(TForm)
MainLayout: TLayout;
imPearl: TImage;
imDiamond: TImage;
imEmerald: TImage;
imRuby: TImage;
Button1: TButton;
imBackground: TImage;
btnShuffle: TButton;
imSapphire: TImage;
imAmber: TImage;
imAmethyst: TImage;
lblScore: TLabel;
lblScoreTitle: TLabel;
lblTimeTitle: TLabel;
barTime: TProgressBar;
timerCountDown: TTimer;
StatusLayout: TLayout;
lblGameOver: TLabel;
lblShuffing: TLabel;
btnPlay: TButton;
aniShuffle: TFloatAnimation;
ShufflingEffect: TGlowEffect;
AniShufflingGlow: TFloatAnimation;
GameOverEffect: TGlowEffect;
BoardLayout: TLayout;
BottomLayout: TLayout;
TabControl: TTabControl;
tiGame: TTabItem;
tiHall: TTabItem;
ActionList: TActionList;
acToHall: TChangeTabAction;
acToGame: TChangeTabAction;
Label1: TLabel;
lblName09: TLabel;
lblName02: TLabel;
lblName03: TLabel;
lblName04: TLabel;
lblName05: TLabel;
lblName06: TLabel;
lblName07: TLabel;
lblName08: TLabel;
lblScore07: TLabel;
lblScore08: TLabel;
lblScore02: TLabel;
lblScore03: TLabel;
lblScore01: TLabel;
lblScore09: TLabel;
lblScore06: TLabel;
lblScore10: TLabel;
lblScore05: TLabel;
lblScore04: TLabel;
lblName10: TLabel;
lblName01: TLabel;
lblHallOfFame: TLabel;
HallOfFameGlowEffect: TGlowEffect;
HallOfFameGlowAnimation: TFloatAnimation;
lblScore00: TLabel;
lblName00: TLabel;
pnPlay: TPanel;
tiNewHiScore: TTabItem;
lblYouMadeIt: TLabel;
lblPrompt: TLabel;
lblYourScore: TLabel;
Panel1: TPanel;
ebName: TEdit;
Panel2: TPanel;
btnSave: TButton;
acToNewScore: TChangeTabAction;
procedure FormCreate(Sender: TObject);
procedure DoImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
procedure DoImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure DoImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure DoMouseLeave(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure btnShuffleClick(Sender: TObject);
procedure timerCountDownTimer(Sender: TObject);
procedure btnPlayClick(Sender: TObject);
procedure aniShuffleFinish(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TabControlChange(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
{ Private declarations }
fCellWidth: Single;
fCellHeight: Single;
fDragging: Boolean;
fCellList: TCellList;
fScore: Cardinal;
fConsecutiveFalls: Integer;
fMultiplierShown: Boolean;
fSimultaneousMatches: Integer;
fInit: Boolean;
fDebug: Boolean;
fMoving: Boolean;
fSelected: TPoint;
fTarget: TPoint;
FOnFinish: TNotifyEvent;
fFallingCells: Integer;
fWorkingArray,
fJewels: TBoardArray;
fTesting: Boolean;
fScoreAnimationList: TList<TFloatAnimation>;
fHallOfFame: TStringList;
fLastName: string;
fTimeMultiplier: Single;
procedure AddScore(const aName: string; aScore: Cardinal; Sort: Boolean = False);
procedure SetOnFinish(const Value: TNotifyEvent);
procedure InitGame;
procedure InitLevel(aLevel: Integer);
procedure RefreshBoard;
procedure RefreshCellImage(i, j: Byte);
function SelectionAvailable: Boolean;
procedure SwitchCells(aSource, aTarget: TPoint);
function ValidateMovement(aSource, aTarget: TPoint; RestoreMovement: Boolean = True): Boolean;
procedure DoMove(aSource, aTarget: TPoint);
procedure MatchCells;
function CheckHorizontal(i, j: Integer): Integer;
function CheckVertical(i, j: Integer): Integer;
procedure FallCells;
function SameMatrices: Boolean;
procedure DumpMatrix;
procedure RestoreMatrix;
procedure FillBoard;
function RandomCell: TJewels;
procedure CompleteMovement;
function CheckAvailables: Boolean;
procedure Shuffle;
function CheckMovements(i, j: Byte): Boolean;
procedure DoFinishSourceAnimation(Sender: TObject);
procedure SetScore(const Value: Cardinal);
procedure KillHorizontal(i, j, aCount: Integer);
procedure KillVertical(i, j, aCount: Integer);
procedure CreateTextAnimation(i, j: Integer; const aValue: string; aTextType: TTextType);
procedure DoTextFinish(Sender: TObject);
procedure GameOver;
procedure SetTime(const Value: Single);
procedure SetMaxTime(const Value: Single);
function GetCellByPos(i, j: Byte): TCell; overload;
function GetCellByPos(aCell: TPoint): TCell; overload;
procedure StartSwitchAnimation(aSource, aTarget: TPoint; Reverse: Boolean);
procedure StartFallingAnimation(aSource: TPoint);
procedure ClearSelection;
procedure ClearTarget;
function GetMaxTime: Single;
function GetTime: Single;
procedure SwitchImageCoordinates(aSource, aTarget: TPoint);
procedure DoFinishFallingAnimation(Sender: TObject);
procedure StartCellFalling;
procedure MoveToTopAndFall(aSource: TPoint);
function ImageFor(aCellType: TJewels): TImage;
procedure RandomBoard;
procedure UpdateScore(i, j: Byte; aScore: Cardinal);
function CheckMatches: Boolean;
procedure SwitchSelectionEffectOn(aSelected: TPoint; Enabled: Boolean);
function AdjacentCells(aCell, anotherCell: TPoint): Boolean;
procedure InitializeScoreAnimation;
procedure RefreshScores;
procedure DefaultHallOfFame;
function GetHallOfFameFileName: string;
function CheckForHiScore: Boolean;
procedure SaveScores;
procedure SortScores;
property Score: Cardinal read FScore write SetScore;
property Time: Single read GetTime write SetTime;
property MaxTime: Single read GetMaxTime write SetMaxTime;
public
{ Public declarations }
property OnFinish: TNotifyEvent read FOnFinish write SetOnFinish;
end;
var
FrmGame: TFrmGame;
implementation
{$R *.fmx}
uses
System.Math;
{ TfrmGame }
function SortBackwards(aList: TStringList; Index1, Index2: Integer): Integer;
begin
Result := - AnsiCompareText(aList[Index1], aList[Index2]);
end;
{$REGION 'Initialization'}
procedure TfrmGame.FormCreate(Sender: TObject);
begin
{$IFDEF MSWINDOWS}
BorderStyle := TFmxFormBorderStyle.bsSizeable;
{$ENDIF}
fScore := 0;
fTesting := False;
fDebug := True;
fMoving := False;
imBackground.Width := ClientWidth;
imBackground.Height := ClientHeight;
lblShuffing.Visible := False;
lblGameOver.Visible := False;
fHallOfFame := TStringList.Create;
try
fHallOfFame.LoadFromFile(GetHallOfFameFilename);
except
DefaultHallOfFame;
SortScores;
SaveScores;
end;
InitGame;
end;
procedure TfrmGame.InitGame;
var
c: Single;
i, j: Byte;
lCell: TCell;
lSelectionEffect: TGlowEffect;
lSelectionAnimation: TFloatAnimation;
lLabel: TLabel;
function CreateAnimation(aLabel: TLabel): TFloatAnimation;
begin
Result := TFloatAnimation.Create(aLabel);
Result.AutoReverse := False;
Result.Enabled := False;
Result.AnimationType := TAnimationType.atIn;
Result.Loop := False;
Result.Inverse := False;
Result.StopValue := aLabel.Position.Y;
Result.StartValue := Result.StopValue + TControl(aLabel.Parent).Height; // To be sure that it starts from outside
Result.PropertyName := 'Position.Y';
Result.StartFromCurrent := False;
Result.Parent := aLabel;
end;
begin
fInit := True;
fLastName := 'None';
ClearSelection;
ClearTarget;
fCellList := TCellList.Create;
BoardLayout.BeginUpdate;
c := Min(BoardLayout.Height / cRowCount, Boardlayout.Width / cColCount);
fCellWidth := c;
fCellHeight := c;
BoardLayout.Width := fCellWidth * cColCount;
BoardLayout.Height := fCellHeight * cRowCount;
BoardLayout.Position.X := (MainLayout.Width / 2) - (BoardLayout.Width / 2);
BoardLayout.Position.Y := (MainLayout.Height / 2) - (BoardLayout.Height / 2);
fScoreAnimationList := TList<TFloatAnimation>.Create;
try
for i := 0 to cMaxScores - 1 do
begin
lLabel := TLabel(Self.FindComponent(Format('lblName%.2d', [i])));
if Assigned(lLabel) then
fScoreAnimationList.Add(CreateAnimation(lLabel));
lLabel := TLabel(Self.FindComponent(Format('lblScore%.2d', [i])));
if Assigned(lLabel) then
fScoreAnimationList.Add(CreateAnimation(lLabel));
end;
for i := 0 to cColCount - 1 do
for j := 0 to cRowCount - 1 do
begin
lCell := TCell.Create(BoardLayout);
lCell.Parent := BoardLayout;
lCell.X := i;
lCell.Y := j;
lCell.Width := fCellWidth;
lCell.Height := fCellHeight;
lCell.WrapMode := TImageWrapMode.iwStretch;
lCell.Position.X := i * lCell.Width;
lCell.Position.Y := j * lCell.Height;
lCell.OnMouseDown := DoImageMouseDown;
lCell.OnMouseUp := DoImageMouseUp;
lCell.OnMouseMove := DoImageMouseMove;
lCell.OnMouseLeave := DoMouseLeave;
fCellList.Add(lCell);
lCell.HorizontalAnimation := TFloatAnimation.Create(lCell);
lCell.HorizontalAnimation.Parent := lCell;
lCell.HorizontalAnimation.PropertyName := 'Position.X';
lCell.HorizontalAnimation.StartValue := lCell.Position.X;
lCell.HorizontalAnimation.StopValue := lCell.Position.X;
lCell.HorizontalAnimation.Duration := cTransitionAnimation;
lCell.VerticalAnimation := TFloatAnimation.Create(lCell);
lCell.VerticalAnimation.Parent := lCell;
lCell.VerticalAnimation.PropertyName := 'Position.Y';
lCell.VerticalAnimation.StartValue := lCell.Position.X;
lCell.VerticalAnimation.StopValue := lCell.Position.X;
lCell.VerticalAnimation.Duration := cTransitionAnimation;
lSelectionEffect := TGlowEffect.Create(lCell);
lSelectionEffect.Parent := lCell;
lSelectionEffect.GlowColor := TAlphaColorRec.Red;
lSelectionEffect.Softness := 0.2;
lSelectionEffect.Opacity := 0;
lSelectionAnimation := TFloatAnimation.Create(lCell);
lSelectionAnimation.Parent := lSelectionEffect;
lSelectionAnimation.PropertyName := 'Opacity';
lSelectionAnimation.StopValue := 1;
lCell.SelectionEffect := lSelectionAnimation;
end;
finally
BoardLayout.EndUpdate;
end;
fInit := False;
if (TabControl.ActiveTab <> tiHall) then
TabControl.ActiveTab := tiHall
else
InitializeScoreAnimation;
end;
procedure TfrmGame.InitLevel(aLevel: Integer);
begin
pnPlay.Visible := False;
lblGameOver.Visible := False;
lblShuffing.Visible := False;
RandomBoard;
fInit := True;
CompleteMovement;
fInit := False;
fMoving := False;
RefreshBoard;
Score := 0;
MaxTime := 60;
fTimeMultiplier := 1;
Time := MaxTime;
timerCountDown.Interval := cInitialInterval;
timerCountDown.Enabled := True;
end;
procedure TfrmGame.FormDestroy(Sender: TObject);
begin
fCellList.DisposeOf;
fScoreAnimationList.DisposeOf;
fHallOfFame.DisposeOf;
end;
{$ENDREGION}
{$REGION 'Hall Of Fame'}
procedure TfrmGame.InitializeScoreAnimation;
var
lFloatAnimation: TFloatAnimation;
begin
RefreshScores;
for lFloatAnimation in fScoreAnimationList do
begin
lFloatAnimation.Duration := (Random(1500) / 1000) + 1;
lFloatAnimation.Enabled := True;
lFloatAnimation.Start;
end;
end;
procedure TfrmGame.SaveScores;
begin
fHallOfFame.SaveToFile(GetHallOfFameFilename);
end;
procedure TfrmGame.btnSaveClick(Sender: TObject);
begin
AddScore(ebName.Text, Score, True);
SaveScores;
RefreshScores;
acToHall.ExecuteTarget(Self);
end;
procedure TfrmGame.SortScores;
begin
fHallOfFame.CustomSort(SortBackwards);
end;
procedure TfrmGame.AddScore(const aName: string; aScore: Cardinal; Sort: Boolean);
begin
fHallOfFame.Add(Format('%.10d=%s', [aScore, aName]));
if Sort then
SortScores;
// Delete values in excess
while (fHallOfFame.Count > cMaxScores) do
fHallOfFame.Delete(cMaxScores);
end;
procedure TfrmGame.DefaultHallOfFame;
var
n: Integer;
function RandomName: string;
const
NameCount = 8;
Names: array[0..NameCount] of string = (
'Benito',
'Pablo',
'Fran',
'Juan',
'Eva',
'Minguez',
'Adrian',
'Miguel',
'Ernest'
);
begin
Result := Names[Random(NameCount + 1)];
end;
begin
for n := 0 to cMaxScores do
begin
AddScore(RandomName, Random(10000));
end;
end;
function TfrmGame.GetHallOfFameFileName: string;
begin
Result := IncludeTrailingPathDelimiter(System.IOUtils.TPath.GetHomePath) +
cHallOfFameFileName;
end;
function TfrmGame.CheckForHiScore: Boolean;
var
n: Integer;
lScore: Cardinal;
begin
for n := 0 to cMaxScores - 1 do
begin
lScore := StrToIntDef(fHallOfFame.Names[n], 0);
if (Score > lScore) then
begin
acToNewScore.ExecuteTarget(Self);
Exit(True);
end;
end;
Result := False;
end;
procedure TfrmGame.RefreshScores;
var
n: Integer;
lblLabel: TLabel;
begin
for n := 0 to cMaxScores do
begin
lblLabel := TLabel(FindComponent(Format('lblName%.2d', [n])));
if Assigned(lblLabel) then
lblLabel.Text := fHallOfFame.ValueFromIndex[n];
lblLabel := TLabel(FindComponent(Format('lblScore%.2d', [n])));
if Assigned(lblLabel) then
lblLabel.Text := IntToStr(StrToIntDef(fHallOfFame.Names[n], 0));
end;
end;
{$ENDREGION}
function TfrmGame.SelectionAvailable: Boolean;
begin
Result := not ((fSelected.X = -1) or (fSelected.Y = -1));
end;
procedure TfrmGame.SwitchCells(aSource: TPoint; aTarget: TPoint);
var
lJewel: TJewels;
begin
lJewel := fJewels[aSource.X, aSource.Y];
fJewels[aSource.X, aSource.Y] := fJewels[aTarget.X, aTarget.Y];
fJewels[aTarget.X, aTarget.Y] := lJewel;
SwitchImageCoordinates(aSource, aTarget);
end;
procedure TfrmGame.GameOver;
begin
if not fMoving then
begin
timerCountdown.Enabled := False;
timerCountDown.Interval := cInitialInterval;
fTimeMultiplier := 1;
lblGameOver.Visible := True;
fMoving := True; // to avoid moving while game over
if not CheckForHiScore then
acToHall.ExecuteTarget(Self);
end
else
// There's a movement in process, give an additional pulse in case the movement provides additional time
Time := Time + 1;
end;
procedure TfrmGame.timerCountDownTimer(Sender: TObject);
begin
Time := Time - ((timerCountdown.Interval / 1000) * FTimeMultiplier);
if (Time = 0) then
GameOver;
end;
procedure TfrmGame.CompleteMovement;
begin
if not SameMatrices or fInit then
begin
// Fill the board
repeat
if fMultiplierShown then
Inc(fConsecutiveFalls);
fMultiplierShown := False;
repeat
DumpMatrix;
FallCells;
FillBoard;
until SameMatrices;
DumpMatrix;
MatchCells;
until SameMatrices;
end;
end;
function TfrmGame.ValidateMovement(aSource, aTarget: TPoint; RestoreMovement: Boolean): Boolean;
begin
if (aSource.X >= 0) and (aSource.X < cColCount) and
(aSource.Y >= 0) and (aSource.Y < cRowCount) and
(aTarget.X >= 0) and (aTarget.X < cColCount) and
(aTarget.Y >= 0) and (aTarget.Y < cRowCount) then
begin
fMultiplierShown := False;
fConsecutiveFalls := 1;
// Try movement
SwitchCells(aSource, aTarget);
// Try match
DumpMatrix;
MatchCells;
// Changed?
Result := not SameMatrices;
if Result and RestoreMovement or not Result then
begin
// Restore movement if Invalid or Valid but RestoreMovement was True
RestoreMatrix;
// Restore movement
SwitchCells(aSource, aTarget);
end;
end
else
Result := False;
end;
procedure TfrmGame.ClearTarget;
begin
fTarget := Point(-1, -1);
end;
procedure TfrmGame.ClearSelection;
begin
fSelected := Point(-1, -1);
end;
procedure TfrmGame.DoFinishSourceAnimation(Sender: TObject);
begin
DoMove(fSelected, fTarget);
ClearSelection;
ClearTarget;
end;
procedure TfrmGame.SwitchImageCoordinates(aSource, aTarget: TPoint);
var
lSelected, lTarget: TCell;
lX, lY: Byte;
begin
if not fInit then
begin
lSelected := GetCellByPos(aSource);
lTarget := GetCellByPos(aTarget);
lX := lSelected.X; lY := lSelected.Y;
lSelected.X := lTarget.X; lSelected.Y := lTarget.Y;
lTarget.X := lX; lTarget.Y := lY;
end;
end;
procedure TfrmGame.DoMove(aSource, aTarget: TPoint);
begin
SwitchSelectionEffectOn(aSource, False);
if ValidateMovement(aSource, aTarget, False) then
begin
fConsecutiveFalls := 1;
StartCellFalling;
end
else
begin
// Invalid movement, move cells to where they were before
StartSwitchAnimation(aSource, aTarget, True);
fMoving := False;
end;
end;
function TfrmGame.CheckMovements(i, j: Byte): Boolean;
begin
Result := ValidateMovement(Point(i, j), Point(i, j + 1), True) or
ValidateMovement(Point(i, j), Point(i, j - 1), True) or
ValidateMovement(Point(i, j), Point(i + 1, j), True) or
ValidateMovement(Point(i, j), Point(i - 1, j), True);
end;
function TfrmGame.CheckMatches: Boolean;
begin
DumpMatrix;
fTesting := True;
MatchCells;
fTesting := False;
Result := not SameMatrices;
RestoreMatrix;
end;
function TfrmGame.CheckAvailables: Boolean;
var
i: Integer;
j: Integer;
begin
Result := False;
fTesting := True;
try
for i := 0 to cColCount - 1 do
begin
for j := 0 to cRowCount - 1 do
begin
if CheckMovements(i, j) then
Exit(True);
end;
end;
finally
fTesting := False;
end;
end;
{$REGION 'Falling Cells'}
procedure TfrmGame.DoFinishFallingAnimation(Sender: TObject);
var
i, j: Integer;
lCell: TCell;
begin
Dec(fFallingCells);
if (fFallingCells = 0) then
begin
// Update Matrix
for i := 0 to cColCount - 1 do
begin
for j := cRowCount - 2 downto 0 do
if (fJewels[i, j] <> jEmpty) and (fJewels[i, j + 1] = jEmpty) then
begin
SwitchCells(Point(i, j), Point(i, j + 1));
end;
if (fJewels[i, 0] = jEmpty) then
begin
lCell := GetCellByPos(i, 0);
fJewels[i, 0] := TJewels(lCell.Tag);
end;
end;
// Something felt, repeat
StartCellFalling;
end;
end;
procedure TfrmGame.StartFallingAnimation(aSource: TPoint);
var
lSource: TCell;
lAniSource: TFloatAnimation;
begin
Inc(fFallingCells);
lSource := GetCellByPos(aSource);
lAniSource := lSource.VerticalAnimation;
lAniSource.StartValue := lSource.Position.Y;
lAniSource.StopValue := lSource.Position.Y + fCellHeight;
lAniSource.Inverse := False;
lAniSource.OnFinish := DoFinishFallingAnimation;
lAniSource.Duration := cFallAnimation;
lAniSource.Start;
end;
procedure TfrmGame.MoveToTopAndFall(aSource: TPoint);
var
lSource: TCell;
lAniSource: TFloatAnimation;
lJewel: TJewels;
begin
Inc(fFallingCells);
// Move empty square to the top for incoming cells
lSource := GetCellByPos(aSource.X, aSource.Y);
lJewel := RandomCell;
lSource.Tag := Integer(lJewel);
lAniSource := lSource.VerticalAnimation;
lAniSource.StopValue := 0;
lAniSource.StartValue := 0 - fCellHeight;
// Move image to its starting place before refreshing will avoid flickering
lSource.Position.Y := lAniSource.StartValue;
// lSource.Y := 0;
{$IFDEF VER250}
lSource.Bitmap.Assign(ImageFor(lJewel).Bitmap);
{$ELSE}
lSource.MultiResBitmap.Assign(ImageFor(lJewel).MultiResBitmap);
{$ENDIF}
// RefreshCellImage(aSource.X, aSource.Y);
lAniSource.Inverse := False;
lAniSource.OnFinish := DoFinishFallingAnimation;
lAniSource.Duration := cFallAnimation;
lAniSource.Start;
end;
procedure TfrmGame.StartCellFalling;
var
i, j, n: Integer;
lSame: Boolean;
lPromoted: Boolean;
begin
lSame := False;
repeat
// Only increment fall count if a multiplier was shown (this means there were a match in previous fall)
if fMultiplierShown then
begin
Inc(fConsecutiveFalls);
fMultiplierShown := False;
end;
DumpMatrix;
fFallingCells := 0;
for i := 0 to cColCount - 1 do
begin
for j := cRowCount - 2 downto 0 do
begin
if (fWorkingArray[i, j] <> jEmpty) and (fWorkingArray[i, j + 1] = jEmpty) then
begin
lPromoted := False;
// Move make the whole column fall
for n := 0 to j do
if (fWorkingArray[i, n] = jEmpty) and not lPromoted then
begin
// Move empty cell to top
MoveToTopAndFall(Point(i, n));
lPromoted := True;
end
else
StartFallingAnimation(Point(i, n));
if not lPromoted then
// Move empty cell to top
MoveToTopAndFall(Point(i, j + 1));
Break;
end;
if (j = 0) and (fWorkingArray[i, 0] = jEmpty) then
begin
// If first cell is empty move it to top
MoveToTopAndFall(Point(i, 0));
end;
end;
end;
if (fFallingCells = 0) then
begin
// Nothing felt, check matches
DumpMatrix;
// Check matches
MatchCells;
// If not matches
lSame := SameMatrices;
if lSame then
begin
// Check availability
if not CheckAvailables then
// If not, shuffle
Shuffle // This will make SameMatrices be false
end;
end;
// Repeat StartCellFalling while fFallingCells <> 0 (this means there are falling cells)
// / or SameMatrices when fFallingCells = 0, which mean
// / that there were matches or shuffles after a falling and need to check matches again
until (fFallingCells > 0) or ((fFallingCells = 0) and lSame);
fMoving := not (lSame and (fFallingCells = 0));
end;
{$ENDREGION}
procedure TFrmGame.StartSwitchAnimation(aSource, aTarget: TPoint; Reverse: Boolean);
var
lSource, lTarget: TCell;
lAniSource, lAniTarget: TFloatAnimation;
begin
lSource := GetCellByPos(aSource);
lTarget := GetCellByPos(aTarget);
if not Reverse then
begin
fMoving := True;
if (aSource.X = aTarget.X) then
begin
// Vertical animation
lAniSource := lSource.VerticalAnimation;
lAniTarget := lTarget.VerticalAnimation;
lAniSource.StartValue := lSource.Position.Y;
lAniSource.StopValue := lTarget.Position.Y;
lAniTarget.StartValue := lTarget.Position.Y;
lAniTarget.StopValue := lSource.Position.Y;
end
else
begin
// Horizontal animation
lAniSource := lSource.HorizontalAnimation;
lAniTarget := lTarget.HorizontalAnimation;
lAniSource.StartValue := lSource.Position.X;
lAniSource.StopValue := lTarget.Position.X;
lAniTarget.StartValue := lTarget.Position.X;
lAniTarget.StopValue := lSource.Position.X;
end;
lAniSource.Inverse := False;
lAniTarget.Inverse := False;
lAniSource.OnFinish := DoFinishSourceAnimation;
lAniTarget.OnFinish := nil;
end
else
begin
if (aSource.X = aTarget.X) then
begin
// Vertical animation
lAniSource := lSource.VerticalAnimation;
lAniTarget := lTarget.VerticalAnimation;
end
else
begin
lAniSource := lSource.HorizontalAnimation;
lAniTarget := lTarget.HorizontalAnimation;
end;
lAniSource.Inverse := True;
lAniTarget.Inverse := True;
lAniSource.OnFinish := nil;
lAniTarget.OnFinish := nil;
end;
lAniSource.Duration := cTransitionAnimation;
lAniTarget.Duration := cTransitionAnimation;
lAniSource.Start;
lAniTarget.Start;
end;
{$REGION 'CellPos'}
function TfrmGame.AdjacentCells(aCell, anotherCell: TPoint): Boolean;
begin
Result :=
((Abs(aCell.X - anotherCell.X) = 1) and (aCell.Y - anotherCell.Y = 0)) or
((Abs(aCell.Y - anotherCell.Y) = 1) and (aCell.X - anotherCell.X = 0));
end;
function TfrmGame.GetCellByPos(aCell: TPoint): TCell;
begin
Result := GetCellByPos(aCell.X, aCell.Y);
end;
function TfrmGame.GetCellByPos(i, j: Byte): TCell;
var
lCell: TCell;
begin
Result := nil;
if (i < cColCount) and (j < cRowCount) then
begin
for lCell in fCellList do
if (lCell.X = i) and (lCell.Y = j) then
begin
Result := lCell;
Break;
end;
end;
end;
function TfrmGame.ImageFor(aCellType: TJewels): TImage;
begin
case aCellType of
jPearl: Result := imPearl;
jEmerald: Result := imEmerald;
jDiamond: Result := imDiamond;
jRuby: Result:= imRuby;
jSapphire: Result := imSapphire;
jAmber: Result := imAmber;
jAmethyst: Result := imAmethyst;
else
Result := nil;
end;
end;
procedure TfrmGame.RefreshCellImage(i, j: Byte);
var
lImage: TImage;
lCell: TCell;
begin
if not fInit and not fTesting then
begin
lImage := ImageFor(fJewels[i, j]);
lCell := GetCellByPos(i, j);
LCell.Position.X := i * fCellWidth;
LCell.Position.Y := j * fCellHeight;
if Assigned(lImage) then
{$IFDEF VER250}
lCell.Bitmap.Assign(lImage.Bitmap)
{$ELSE}
lCell.MultiResBitmap.Assign(lImage.MultiResBitmap)
{$ENDIF}
else
{$IFDEF VER250}
lCell.Bitmap.SetSize(0, 0);
{$ELSE}
lCell.MultiResBitmap.Clear;
{$ENDIF}
end;
end;
procedure TfrmGame.RefreshBoard;
var
i, j: Byte;
begin
if SelectionAvailable then
SwitchSelectionEffectOn(fSelected, False);
for i := 0 to cColCount - 1 do
for j := 0 to cRowCount - 1 do
RefreshCellImage(i, j);
end;
function TfrmGame.RandomCell: TJewels;
begin
Result := TJewels(Random(Integer(High(TJewels))) + 1);
end;
procedure TfrmGame.RandomBoard;
var
i, j: Byte;
begin
for i := 0 to cColCount - 1 do
for j := 0 to cRowCount - 1 do
fJewels[i, j] := RandomCell;
end;
{$ENDREGION}
{$REGION 'Mouse handling'}
procedure TfrmGame.DoMouseLeave(Sender: TObject);
begin
//
end;
procedure TfrmGame.DoImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
var
lCell: TPoint;
begin
lCell.X := TCell(Sender).X;
lCell.Y := TCell(Sender).Y;
if fDragging and SelectionAvailable then
begin
Label1.Text := Format('dragging %s (%d, %d) over %s (%d, %d)', [cJewels[fJewels[fSelected.X, fSelected.Y]], fSelected.x, fSelected.y, cJewels[fJewels[lCell.X, lCell.Y]], lCell.X, lCell.Y]);
if not fMoving and AdjacentCells(fSelected, lCell) then
begin
fTarget := lCell;
StartSwitchAnimation(fSelected, fTarget, False);
end;
end
else
begin
label1.Text := Format('%s (%d, %d)', [cJewels[fJewels[lCell.X, lCell.Y]], lCell.X, lCell.Y]);
end;
end;
procedure TfrmGame.DoImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
lCell: TCell;
begin
if not fMoving then
begin
Label1.Text := Format('Clicked %d, %d', [fSelected.X, fSelected.Y]);
lCell := TCell(Sender);
if not SelectionAvailable then
begin
fSelected.X := Trunc(lCell.X);
fSelected.Y := Trunc(lCell.Y);
ClearTarget;
SwitchSelectionEffectOn(fSelected, True);
end
else
begin
// Something is selected
SwitchSelectionEffectOn(fSelected, False);
if (fSelected.X = lCell.X) and (fSelected.Y = lCell.Y) then
// If the selected cell and the clicked cell is the same, then unselect
ClearSelection
else
begin
if AdjacentCells(fSelected, Point(LCell.X, lCell.Y)) then
begin
// Cells are adjacent, make movement
fTarget.X := lCell.X;
fTarget.Y := lCell.Y;
StartSwitchAnimation(fSelected, fTarget, False);
end
else
begin
// Not adjacents, Mark selected as current
ClearTarget;
fSelected.X := lCell.X;
fSelected.Y := lCell.Y;
SwitchSelectionEffectOn(fSelected, True);
end;
end;
end;
end;
fDragging := True;
end;
procedure TfrmGame.DoImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
fDragging := False;
// Label1.Text := Format('dropped %d, %d', [fSelected.x, fSelected.y]);
// if not TargetAvailable then
// ClearSelection;
end;
{$ENDREGION}
procedure TfrmGame.SwitchSelectionEffectOn(aSelected: TPoint; Enabled: Boolean);
var
lSelected: TCell;
begin
lSelected := GetCellByPos(aSelected);
lSelected.SelectionEffect.Inverse := not Enabled;
if Enabled then
begin
lSelected.SelectionEffect.Duration := 2;
lSelected.SelectionEffect.StartValue := 0.8;
lSelected.SelectionEffect.Loop := True;
lSelected.SelectionEffect.AutoReverse := True;
end
else
begin
lSelected.SelectionEffect.Loop := False;
lSelected.SelectionEffect.Duration := 0.2;
lSelected.SelectionEffect.StartValue := 0;
lSelected.SelectionEffect.AutoReverse := False;
end;
lSelected.SelectionEffect.Start;
end;
procedure TfrmGame.TabControlChange(Sender: TObject);
begin
if (TabControl.ActiveTab = tiHall) then
begin
HallOfFameGlowAnimation.Enabled := True;
pnPlay.Visible := True;
InitializeScoreAnimation;
end
else
begin
HallOfFameGlowAnimation.Enabled := False;
if (TabControl.ActiveTab = tiHall) then
begin
lblYourScore.Text := Format(cYourScoreWas, [Score]);
end;
end;
end;
function TfrmGame.GetMaxTime: Single;
begin
Result := barTime.Max;
end;
function TfrmGame.GetTime: Single;
begin
Result := barTime.Value;
end;
procedure TfrmGame.SetMaxTime(const Value: Single);
begin
barTime.Max := Value;
end;
procedure TfrmGame.SetOnFinish(const Value: TNotifyEvent);
begin
FOnFinish := Value;
end;
procedure TfrmGame.SetTime(const Value: Single);
begin
barTime.Value := Min(Value, MaxTime);
end;
procedure TfrmGame.SetScore(const Value: Cardinal);
var
lDif: Cardinal;
begin
if not fInit and not fTesting then
begin
lDif := Value - FScore;
Time := Time + (lDif div cCellPoints);
FScore := Value;
lblScore.Text := IntToStr(FScore);
fTimeMultiplier := Min(fTimeMultiplier + (lDif / 10000), cMaxTimeMultiplier);
// 10000 means that time will run x2 at 10.000 points
end;
end;
procedure TfrmGame.aniShuffleFinish(Sender: TObject);
begin
lblShuffing.Visible := False;
end;
procedure TfrmGame.btnPlayClick(Sender: TObject);
begin
InitLevel(0);
acToGame.ExecuteTarget(Self);
end;
procedure TfrmGame.Button1Click(Sender: TObject);
begin
RefreshBoard;
end;
procedure TfrmGame.btnShuffleClick(Sender: TObject);
begin
Shuffle;
end;
procedure TfrmGame.Shuffle;
var
n: Integer;
begin
label1.Text := 'Shuffling, no more matches available';
lblShuffing.Visible := True;
n := 0;
repeat
SwitchCells(
Point(Random(cColCount), Random(cRowCount)),
Point(Random(cColCount), Random(cRowCount))
);
Inc(n); /// Initial shuffling /// Shuffling if not availables or matches in board
until (n > cColCount * cRowCount - 1) and CheckAvailables and not CheckMatches;
aniShuffle.Start;
AniShufflingGlow.Start;
RefreshBoard;
end;
procedure TfrmGame.FillBoard;
var
i: Integer;
begin
for i := 0 to cColCount - 1 do
if (fJewels[i, 0] = jEmpty) then
begin
fJewels[i, 0] := RandomCell;
RefreshCellImage(i, 0);
end;
end;
procedure TfrmGame.FallCells;
var
i, j: Integer;
begin
for i := 0 to cColCount - 1 do
for j := cRowCount - 2 downto 0 do
if (fJewels[i, j + 1] = jEmpty) then
SwitchCells(Point(i, j), Point(i, j + 1));
end;
function TfrmGame.SameMatrices: Boolean;
var
i, j: Integer;
begin
for i := 0 to cColCount - 1 do
for j := 0 to cRowCount - 1 do
if (fWorkingArray[i, j] <> fJewels[i, j]) then
Exit(False);
Result := True;
end;
procedure TfrmGame.DumpMatrix;
var
i, j: Integer;
begin
for i := 0 to cColCount - 1 do
for j := 0 to cRowCount - 1 do
fWorkingArray[i, j] := fJewels[i, j];
end;
procedure TfrmGame.RestoreMatrix;
var
i, j: Integer;
begin
for i := 0 to cColCount - 1 do
for j := 0 to cRowCount - 1 do
fJewels[i, j] := fWorkingArray[i, j];
end;
procedure TfrmGame.DoTextFinish(Sender: TObject);
begin
if (Sender is TfmxObject) and Assigned(TFmxObject(Sender).Parent) and (TFmxObject(Sender).Parent is TText) then
begin
TFmxObject(Sender).Parent.DisposeOf;
end;
end;
procedure TfrmGame.CreateTextAnimation(i, j: Integer; Const aValue: string; aTextType: TTextType);
var
lText: TText;
lEffect: TGlowEffect;
lAni: TFloatAnimation;
begin
lText := TText.Create(nil);
lText.Parent := BoardLayout;
lText.Text := aValue;
lText.WordWrap := False;
lText.AutoSize := True;
lText.Position.X := i * fCellWidth;
lText.Position.Y := j * fCellHeight;
lText.HitTest := False;
lText.Font.Style := [TFontStyle.fsBold];
lText.BringToFront;
lEffect := TGlowEffect.Create(lText);
lEffect.Parent := lText;
lAni := TFloatAnimation.Create(lText);
lAni.Parent := lText;
lAni.PropertyName := 'Position.Y';
lAni.StartValue := lText.Position.Y;
lAni.StopValue := lAni.StartValue - fCellHeight;
lAni.OnFinish := DoTextFinish;
case aTextType of
ttScore:
begin
lText.Font.Size := 15;
lText.Color := TAlphaColorRec.White;
lEffect.GlowColor := TAlphaColorRec.Black;
lEffect.Softness := 0;
lAni.Duration := 2;
end;
ttMultiplier:
begin
lText.Font.Size := 30;
lText.Color := TAlphaColorRec.Magenta;
lEffect.GlowColor := TAlphaColorRec.Black;
lEffect.Softness := 0;
lAni.Duration := 4;
lText.BringToFront;
end;
end;
lAni.Start;
end;
procedure TfrmGame.UpdateScore(i, j: Byte; aScore: Cardinal);
begin
if (aScore > 0) then
begin
Score := Score + aScore;
CreateTextAnimation(i, j, IntToStr(aScore), ttScore);
if not fMultiplierShown then
begin
if (fConsecutiveFalls > 1) then
CreateTextAnimation(i + 1, j - 1, 'x'+IntToStr(fConsecutiveFalls), ttMultiplier);
fMultiplierShown := True;
end;
end;
end;
{$REGION 'Matching'}
procedure TfrmGame.KillVertical(i, j, aCount: Integer);
var
n: Integer;
lScore: Integer;
begin
// Check if there's something to kill -> it can be previously killed by a longer match
if (fJewels[i, j] <> jEmpty) then
begin
lScore := 0;
for n := j to j + aCount - 1 do
begin
if not fInit and not fTesting then
lScore := lScore + cCellPoints * fConsecutiveFalls;
fJewels[i, n] := jEmpty;
RefreshCellImage(i, n);
end;
UpdateScore(i, j, lScore);
Inc(fSimultaneousMatches);
end;
end;
procedure TfrmGame.KillHorizontal(i, j, aCount: Integer);
var
n: Integer;
lScore: Integer;
begin
// Check if there's something to kill -> it can be previously killed by a longer match
if (fJewels[i, j] <> jEmpty) then
begin
lScore := 0;
for n := i to i + aCount - 1 do
begin
if not fInit and not fTesting then
lScore := lScore + cCellPoints * fConsecutiveFalls;
fJewels[n, j] := jEmpty;
RefreshCellImage(n, j);
end;
UpdateScore(i, j, lScore);
Inc(fSimultaneousMatches);
end;
end;
function TfrmGame.CheckVertical(i, j: Integer): Integer;
var
lJewel: TJewels;
begin
lJewel := fWorkingArray[i, j];
Result := 1;
while (j + Result < cRowCount) and (fWorkingArray[i, j + Result] = lJewel) do
Inc(Result);
end;
function TfrmGame.CheckHorizontal(i, j: Integer): Integer;
var
lJewel: TJewels;
begin
lJewel := fWorkingArray[i, j];
Result := 1;
while (i + Result < cColCount) and (fWorkingArray[i + Result, j] = lJewel) do
Inc(Result);
end;
procedure TfrmGame.MatchCells;
var
i, j: Integer;
lCount: Integer;
begin
fSimultaneousMatches := 0;
for i := 0 to cColCount - 1 do
for j := 0 to cRowCount - 1 do
if (fWorkingArray[i, j] <> jEmpty) then
begin
lCount := CheckVertical(i, j);
if (lCount >= cMinToMatch) then
KillVertical(i, j, lCount);
lCount := CheckHorizontal(i, j);
if (lCount >= cMinToMatch) then
KillHorizontal(i, j, lCount);
end;
end;
{$ENDREGION}
initialization
Randomize;
finalization
end.
|
program iBeta;
uses crt;
{--------------------------------------------------------------------------------------}
const
{boutons servant aux mouvements et actions du curseur}
UP = 'z';
DOWN = 's';
LEFT = 'q';
RIGHT = 'd';
{Barre espace, pour cliquer}
CLIC = chr(32);
{Bouton ESCAPE, pour quitter}
QUIT = chr(27);
{taille de l'interface}
XMAX = 50;
YMAX = 20;
{--------------------------------------------------------------------------------------}
type
Limits = array[0..3] of integer;
Str128 = string[128];
tColors = integer;
Button = record
{x et y qui delimitent le bouton}
delimitation : Limits;
{etat du bouton. True = actif et False = inactif}
status : boolean;
{color la couleur du tableau colors que revet le bouton.}
color: integer;
{contient l'intitule du bouton}
headline : Str128;
end;
tButtons = array[0..18] of Button;
{--------------------------------------------------------------------------------------}
procedure fullBackground;
var
i,j: integer;
Begin
for i := 1 to XMAX do begin
for j := 1 to YMAX do begin
gotoXY(i,j);
write(' ');
TextBackground(White);
end;
end;
End;
procedure cursor;
var
key: char;
i,j: integer;
Begin
i:= 5;
j:= 5;
gotoXY(i,j);
key:= ' ';
while not (key = QUIT) do begin
if keypressed then begin
key:= readkey;
case key of
UP : if j > 1 then j:= j-1;
DOWN : if j < YMAX then j:= j+1;
LEFT : if i > 1 then i:= i-1;
RIGHT : if i < XMAX then i:= i+1;
CLIC : begin textColor(Black); write('a'); end;
end;
end;
gotoXY(i,j);
end;
end;
{--------------------------------------------------------------------------------------}
BEGIN
clrscr;
fullBackground;
testCrt;
cursor;
clrscr;
end. |
unit Fornecedor.Model;
interface
uses Fornecedor.Model.Interf, TPAGFORNECEDOR.Entidade.Model,
ormbr.container.objectset.interfaces, ormbr.Factory.interfaces;
type
TFornecedorModel = class(TInterfacedObject, IFornecedorModel)
private
FConexao: IDBConnection;
FEntidade: TTPAGFORNECEDOR;
FDao: IContainerObjectSet<TTPAGFORNECEDOR>;
public
constructor Create;
destructor Destroy; override;
class function New: IFornecedorModel;
function Entidade(AValue: TTPAGFORNECEDOR): IFornecedorModel; overload;
function Entidade: TTPAGFORNECEDOR; overload;
function DAO: IContainerObjectSet<TTPAGFORNECEDOR>;
end;
implementation
{ TFornecedorModel }
uses FacadeController, ormbr.container.objectset;
constructor TFornecedorModel.Create;
begin
FConexao := TFacadeController.New.ConexaoController.conexaoAtual;
FDao := TContainerObjectSet<TTPAGFORNECEDOR>.Create(FConexao, 1);
end;
function TFornecedorModel.DAO: IContainerObjectSet<TTPAGFORNECEDOR>;
begin
Result := FDao;
end;
destructor TFornecedorModel.Destroy;
begin
inherited;
end;
function TFornecedorModel.Entidade(AValue: TTPAGFORNECEDOR): IFornecedorModel;
begin
Result := Self;
FEntidade := AValue;
end;
function TFornecedorModel.Entidade: TTPAGFORNECEDOR;
begin
Result := FEntidade;
end;
class function TFornecedorModel.New: IFornecedorModel;
begin
Result := Self.Create;
end;
end.
|
unit ConnectionStore;
interface
uses
SysUtils, Classes, Forms,
ADODB, Db,
dcfdes, dcsystem, dcdsgnstuff,
ThComponent, ThDataConnection, TpPersistComponent;
type
// TTpConnectionString = string;
//
TConnectionStore = class(TTpPersistComponent)
private
FConnectionStrings: TStringList;
FFilename: string;
protected
procedure SetConnectionStrings(const Value: TStringList);
procedure SetFilename(const Value: string);
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
procedure Add(const inName, inConnectionString: string);
procedure Save;
property Filename: string read FFilename write SetFilename;
published
property ConnectionStrings: TStringList read FConnectionStrings
write SetConnectionStrings;
end;
var
ConnectionConfigFolder: string;
function NeedConnectionStore: TConnectionStore;
implementation
const
cConnectionStoreFilename = 'connections.turbophp.cfg';
var
Connections: TConnectionStore;
function NeedConnectionStore: TConnectionStore;
begin
if Connections = nil then
begin
Connections := TConnectionStore.Create(nil);
Connections.Filename := ConnectionConfigFolder + cConnectionStoreFilename;
end;
Result := Connections
end;
{ TConnectionStore }
constructor TConnectionStore.Create(inOwner: TComponent);
begin
inherited;
FConnectionStrings := TStringList.Create;
FConnectionStrings.Duplicates := dupIgnore;
end;
destructor TConnectionStore.Destroy;
begin
FConnectionStrings.Free;
inherited;
end;
procedure TConnectionStore.SetConnectionStrings(const Value: TStringList);
begin
FConnectionStrings.Assign(Value);
end;
procedure TConnectionStore.SetFilename(const Value: string);
begin
FFilename := Value;
LoadFromFile(FFilename);
end;
procedure TConnectionStore.Add(const inName, inConnectionString: string);
begin
if FConnectionStrings.IndexOfName(inName) < 0 then
begin
FConnectionStrings.Add(inName + '=' + inConnectionString);
Save;
end;
end;
procedure TConnectionStore.Save;
begin
SaveToFile(FFilename);
end;
end.
|
uses easycrt,easygdi;
{
This program shows you how to use a memory bmp as a buffer for graphics.
First, it creates a blank bmp in memory that is the same size as the
EasyCRT window.
Then, instead of drawing to the screen, it draws to the memory bmp it created
After that it uses the copybmp command to copy the bmp onto the screen.
Drawing using this technique can have some advantages. The most important one
is that it will completely eliminate screen flicker. Normally when you animate
something, you have to erase it after every step before you can draw the next
step. It is this erasing and redrawing which causes flicker. When you do everything
in memory the user never sees the erasing step and there is no flicker.
The disadvantage of using this technique is that it is slower and it uses up more
computer resources. It is also very much affected by the windows screen settings.
It will run much slower in 24 bit color mode than in 8 bit or 16 bit color.
You can change these settings under Control Panel | Display | Settings | Colors
if you want to experiment.
In this program you get to see it both ways. To run it using the buffer technique, set
the usebuffer constant (below) to true. To see it drawn directly to the screen set
usebuffer to false. You can also observe the effects of changing the delay time.
}
const NumberOfPoints = 5; { number of points in the shape }
maxvelocity = 20; { maximum speed of a point }
usebuffer = true; { use buffer }
delaytime = 30; { # of milliseconds to delay between frames }
type tPointsInMotion = record { position of points }
position,velocity: array [1..NumberOfPoints] of points;
end;
var theshape: tPointsInMotion; { position of points }
i,j,k:integer; { scratch variables }
buffer:bmp; { buffer bmp variable }
begin
randomize; { randomizes random numbers }
initwincrt; { opens easyscrt window }
settitle('Shape Demo');
if usebuffer then { creates a buffer is usebuffer is true }
buffer := makeblankbmp(CRT,getwidth(CRT),getheight(CRT))
else
buffer := CRT;
for i := 1 to NumberOfPoints do { sets random initial positions and speeds }
begin
theshape.position[i].x := random(getwidth(buffer));
theshape.position[i].y := random(getheight(buffer));
theshape.velocity[i].x := random(maxvelocity*2+1)-maxvelocity;
theshape.velocity[i].y := random(maxvelocity*2+1)-maxvelocity;
end;
repeat
for i := 1 to NumberOfPoints do { updates points }
with theshape do
begin
inc(position[i].x,velocity[i].x);
if (position[i].x > getwidth(buffer)) or (position[i].x < 0) then
velocity[i].x := velocity[i].x * -1;
inc(position[i].y,velocity[i].y);
if (position[i].y > getheight(buffer)) or (position[i].y < 0) then
velocity[i].y := velocity[i].y * -1;
end;
setpen(buffer,color[-1],solid,0); { erases last frame }
setbrush(buffer,color[0],color[0],solid);
box(buffer,0,0,getwidth(buffer),getheight(buffer),0,0);
setpen(buffer,color[9],solid,3); { draws new shape }
setbrush(buffer,color[12],color[0],grid);
shape(buffer,theshape.position,numberofpoints,alternate);
if usebuffer then copybmp(buffer,CRT,0,0); { copies buffer to screen }
delay(delaytime); { delays between frames }
until ldown or rdown or keypressed; { repeats until button pressed }
if usebuffer then killbmp(buffer); { destroys buffer bmp }
donewincrt; { closes easycrt window }
end. |
unit ibSHFunction;
interface
uses
SysUtils, Classes, Contnrs,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibBTFunction = class(TibBTDBObject, IibSHFunction)
private
FParamList: TComponentList;
FEntryPoint: string;
FModuleName: string;
FReturnsArgument: Integer;
function GetParam(Index: Integer): IibSHFuncParam;
function GetEntryPoint: string;
procedure SetEntryPoint(Value: string);
function GetModuleName: string;
procedure SetModuleName(Value: string);
function GetReturnsArgument: Integer;
procedure SetReturnsArgument(Value: Integer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Refresh; override;
published
property Description;
property Params;
property Returns;
property EntryPoint: string read GetEntryPoint {write SetEntryPoint};
property ModuleName: string read GetModuleName {write SetModuleName};
end;
implementation
uses
ibSHConsts, ibSHSQLs;
{ TibBTFunction }
constructor TibBTFunction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FParamList := TComponentList.Create;
end;
destructor TibBTFunction.Destroy;
begin
FParamList.Free;
inherited Destroy;
end;
procedure TibBTFunction.Refresh;
begin
FParamList.Clear;
inherited Refresh;
end;
function TibBTFunction.GetParam(Index: Integer): IibSHFuncParam;
begin
if FReturnsArgument = 0 then
Assert(Index <= Params.Count, 'Index out of bounds')
else
Assert(Index <= Pred(Params.Count), 'Index out of bounds');
Supports(CreateParam(FParamList, IibSHDomain, Index), IibSHFuncParam, Result);
end;
function TibBTFunction.GetEntryPoint: string;
begin
Result := FEntryPoint;
end;
procedure TibBTFunction.SetEntryPoint(Value: string);
begin
FEntryPoint := Value;
end;
function TibBTFunction.GetModuleName: string;
begin
Result := FModuleName;
end;
procedure TibBTFunction.SetModuleName(Value: string);
begin
FModuleName := Value;
end;
function TibBTFunction.GetReturnsArgument: Integer;
begin
Result := FReturnsArgument;
end;
procedure TibBTFunction.SetReturnsArgument(Value: Integer);
begin
FReturnsArgument := Value;
end;
end.
|
unit uUtils;
interface
uses
Windows, Messages, SysUtils, Variants;
function GetComputerName: string;
implementation
const
NERR_Success = 0;
function NetWkstaGetInfo(ServerName: LPWSTR; Level: DWORD;
BufPtr: Pointer): Longint; stdcall;
external 'netapi32.dll' Name 'NetWkstaGetInfo';
//function ProcessIdToSessionId(dwProcessId: DWORD;var pSessionId: DWORD): BOOL; stdcall; external kernel32 name 'ProcessIdToSessionId';
type
WKSTA_INFO_100 = record
wki100_platform_id: DWORD;
wki100_computername: LPWSTR;
wki100_langroup: LPWSTR;
wki100_ver_major: DWORD;
wki100_ver_minor: DWORD;
end;
LPWKSTA_INFO_100 = ^WKSTA_INFO_100;
_USER_INFO_0 = record
usri0_name: LPWSTR;
end;
function GetNetParam(AParam: Integer): string;
var
PBuf: LPWKSTA_INFO_100;
Res: LongInt;
begin
Result := '';
Res := NetWkstaGetInfo(nil, 100, @PBuf);
if Res = NERR_Success then
begin
case AParam of
0: Result := string(PBuf^.wki100_computername);
1: Result := string(PBuf^.wki100_langroup);
end;
end;
end;
function GetComputerName: string;
begin
Result := GetNetParam(0);
end;
function GetDomainName: string;
begin
Result := GetNetParam(1);
end;
{
function GetPCSystemName : WideString;
var
lpBuf : PWideChar;
nSi : DWORD;
begin
Result := '';
nSi := (1024 + 2) * SizeOf(WideChar);
GetMem(lpBuf, nSi);
try
if GetComputerNameW(lpBuf, nSi) then Result := lpBuf;
finally
FreeMem(lpBuf);
end;
end;
function GetPCClientName : WideString;
var
nProcessID, nSessionID : DWORD;
nByteCount : DWORD;
acNameBuff : Pointer;
tmpName : WideString;
begin
// Lokaler HostName
Result := GetPCSystemName;
nProcessID := GetCurrentProcessId;
nSessionID := 0;
//PROCESS_QUERY_INFORMATION wird benotigt fur ProcessIdToSessionID "SeDebugPrivilege"
// SessionID von aktueller ProcessID
if ProcessIdToSessionID( nProcessID, nSessionID) then begin
// Wenn in einer Session..
if nSessionID > 0 then begin
// Session ClientName
if WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, nSessionId, WTSClientName, acNameBuff, nByteCount) then begin
try
tmpName := PWideChar(acNameBuff);
// Da bei Vista kein Name vorhanden ist, auf Leerstring prufen!
if tmpName <> '' then
result := tmpName;
finally
WTSFreeMemory(acNameBuff);
end;
end;
end;
end;
end; }
{function GetLocalPCName: String;
var
Buffer: array [0..63] of AnsiChar;
i: Integer;
GInitData: TWSADATA;
begin
Result := '';
WSAStartup($101, GInitData);
GetHostName(Buffer, SizeOf(Buffer));
Result:=Buffer;
WSACleanup;
end; }
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmCaptionButtons
Purpose : Allows for new caption bar buttons to be defined.
Date : 06-18-1998
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmCaptionButtons;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, extctrls,
imglist;
type
TrmCaptionButtonStyle = (cbsButton, cbsSpacer);
TrmCaptionButtonItem = class(TCollectionItem)
private
fimageindex: integer;
fStyle: TrmCaptionButtonStyle;
fwidth: integer;
fcaption: string;
fvisible: boolean;
fEnabled: boolean;
procedure setimageindex(value: integer);
procedure SetStyle(value: TrmCaptionButtonStyle);
procedure setwidth(value: integer);
function GetRect: TRect;
function GetCapBtnRect: TRect;
procedure SetCaption(value: string);
procedure SetVisible(value: boolean);
procedure SetEnabled(const Value: boolean);
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
procedure hide;
procedure show;
property ButtonRect: trect read GetRect;
property CapBtnRect: TRect read GetCapBtnRect;
published
property Enabled : boolean read fEnabled write SetEnabled default true;
property ImageIndex: integer read fimageindex write setimageindex default -1;
property Style: TrmCaptionButtonStyle read fstyle write setStyle default cbsbutton;
property Width: integer read fwidth write setwidth default 5;
property Caption: string read fcaption write setcaption;
property Visible: boolean read fvisible write setvisible default true;
end;
TrmCaptionButtonsCollection = class(TCollection)
private
FOwner: TPersistent;
function GetItem(Index: Integer): TrmCaptionButtonItem;
procedure SetItem(Index: Integer; Value: TrmCaptionButtonItem);
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent);
function Add: TrmCaptionButtonItem;
function ExcludeBtnRgn(R: TRect): TRect;
function GetCaptionRect: TRect;
function ButtonsRect: TRect;
property Items[Index: Integer]: TrmCaptionButtonItem read GetItem write SetItem; default;
end;
TrmCaptionButtonClick = procedure(ButtonIndex: integer) of object;
TrmCaptionButtons = class(TComponent)
private
{ Private declarations }
fbuttons: TrmCaptionButtonsCollection;
fimages: TCustomImageList;
FImageChangeLink: TChangeLink;
ffont: TFont;
fCanvas: TCanvas;
OldWndProc: TFarProc;
NewWndProc: Pointer;
fPaintButtons: boolean;
paintingbutton: boolean;
fvisible: boolean;
fncButtonID: integer;
fncmousedown: boolean;
fncmousedownrect: trect;
fCapBtnClick: TrmCaptionButtonClick;
function calcPoint(x, y: integer): tpoint;
procedure SetVisible(value: boolean);
procedure SetFont(value: TFont);
procedure CMTextChanged(var msg: TMessage); message CM_TextChanged;
function GetOwnerAsForm: TForm;
procedure SetImages(const Value: TCustomImagelist);
procedure ImageListChange(Sender: TObject);
protected
{ Protected declarations }
procedure PaintButtons(pt: tpoint);
function BtnEnabled(pt:TPoint):boolean;
procedure HookWndProc(var WorkMsg: TMessage);
procedure HookWin;
procedure UnhookWin;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
{ Public declarations }
constructor create(AOwner: TComponent); override;
destructor destroy; override;
procedure updatecaption;
procedure Show;
procedure Hide;
published
{ Published declarations }
property Buttons: TrmCaptionButtonsCollection read fbuttons write fbuttons;
property Visible: boolean read fvisible write SetVisible default true;
property Images: TCustomImagelist read fimages write SetImages;
property Font: TFont read ffont write Setfont;
property OnClick: TrmCaptionButtonClick read fCapBtnClick write fCapBtnClick;
end;
implementation
uses rmGlobalComponentHook;
{ TrmCaptionButtonItem }
constructor TrmCaptionButtonItem.Create(Collection: TCollection);
begin
fimageindex := -1;
fvisible := true;
fEnabled := true;
inherited Create(Collection);
end;
procedure TrmCaptionButtonItem.Assign(Source: TPersistent);
begin
if Source is TrmCaptionButtonItem then
begin
imageindex := TrmCaptionButtonItem(Source).imageindex;
Exit;
end;
inherited Assign(Source);
end;
procedure TrmCaptionButtonItem.setimageindex(value: integer);
begin
fimageindex := value;
Changed(False);
end;
procedure TrmCaptionButtonItem.SetStyle(value: TrmCaptionButtonStyle);
begin
fstyle := value;
changed(false);
end;
procedure TrmCaptionButtonItem.setwidth(value: integer);
begin
fwidth := value;
changed(false);
end;
function TrmCaptionButtonItem.GetCapBtnRect: TRect;
var
r: trect;
loop: integer;
begin
with TrmCaptionButtonsCollection(collection) do
begin
r := buttonsrect;
for loop := index - 1 downto 0 do
if items[loop].visible then r.left := r.left + items[loop].width;
r.right := r.left + items[index].width;
r.top := r.top + 2;
r.bottom := r.bottom - 2;
result := r;
end;
end;
function TrmCaptionButtonItem.GetRect: TRect;
var
r: trect;
loop: integer;
begin
with TrmCaptionButtonsCollection(collection) do
begin
r := excludebtnrgn(GetCaptionrect);
r := rect(0, 0, 0, r.bottom - r.top);
for loop := 0 to index - 1 do
if items[loop].visible then r.left := r.left + items[loop].width;
r.right := r.left + items[index].width;
r.top := r.top + 2;
r.bottom := r.bottom - 2;
result := r;
end;
end;
procedure TrmCaptionButtonItem.setCaption(value: string);
begin
fcaption := value;
changed(false);
end;
procedure TrmCaptionButtonItem.setvisible(value: boolean);
begin
fvisible := value;
changed(false);
end;
procedure TrmCaptionButtonItem.hide;
begin
fvisible := false;
changed(false);
end;
procedure TrmCaptionButtonItem.show;
begin
fvisible := true;
changed(false);
end;
procedure TrmCaptionButtonItem.SetEnabled(const Value: boolean);
begin
fEnabled := Value;
changed(false);
end;
{ TrmCaptionButtonsCollection }
constructor TrmCaptionButtonsCollection.Create(AOwner: TPersistent);
begin
inherited Create(TrmCaptionButtonItem);
fOwner := AOwner;
end;
function TrmCaptionButtonsCollection.Add: TrmCaptionButtonItem;
begin
Result := TrmCaptionButtonItem(inherited Add);
end;
function TrmCaptionButtonsCollection.GetItem(Index: Integer): TrmCaptionButtonItem;
begin
Result := TrmCaptionButtonItem(inherited GetItem(Index));
end;
function TrmCaptionButtonsCollection.GetOwner: TPersistent;
begin
Result := fOwner;
end;
procedure TrmCaptionButtonsCollection.SetItem(Index: Integer; Value: TrmCaptionButtonItem);
begin
inherited SetItem(Index, Value);
end;
function TrmCaptionButtonsCollection.ExcludeBtnRgn(R: TRect): TRect;
var
BtnWidth: integer;
BS: TFormBorderStyle;
BI: TBorderIcons;
begin
BS := TForm(GetOwner).BorderStyle;
if BS = bsNone then exit;
BtnWidth := GetSystemMetrics(SM_CXSIZE);
if BS in [bsToolWindow, bsSizeToolWin] then
begin
R.Right := R.Right - GetSystemMetrics(SM_CXSMSIZE) - 2; { close icon only }
result := r;
exit;
end;
BI := TForm(GetOwner).BorderIcons;
if (biSystemMenu in BI)
then R.Right := R.Right - BtnWidth - 2; { close icon - this is OS dependant }
if ((BS <> bsDialog) and ((biMinimize in BI) or (biMaximize in BI)))
then R.Right := R.Right - 2 * BtnWidth; { minimise and maximise icon }
if ((BS = bsDialog) and (biHelp in BI))
then R.Right := R.Right - BtnWidth - 2 { help icon }
else R.Right := R.Right - 2;
result := r;
end;
function TrmCaptionButtonsCollection.GetCaptionRect: TRect;
var
BS: TFormBorderStyle;
begin
BS := TForm(GetOwner).BorderStyle;
{ if we have no border style, then just set the rectangle empty. }
if BS = bsNone then
begin
SetRectEmpty(Result);
exit;
end;
GetWindowRect(TForm(GetOwner).handle, Result);
{ Convert rect from screen (absolute) to client (0 based) coordinates. }
OffsetRect(Result, -Result.Left, -Result.Top);
{ Shrink rectangle to allow for window border. We let Windows paint the border. }
{ this catches drawing MDI minimised windows caption bars in Win95 }
if ((GetWindowLong(TForm(GetOwner).handle, GWL_STYLE) and WS_MINIMIZE) <> 0)
then InflateRect(Result, -GetSystemMetrics(SM_CXFIXEDFRAME),
-GetSystemMetrics(SM_CYFIXEDFRAME))
else
case BS of
bsToolWindow, bsSingle, bsDialog:
InflateRect(Result, -GetSystemMetrics(SM_CXFIXEDFRAME),
-GetSystemMetrics(SM_CYFIXEDFRAME));
bsSizeToolWin, bsSizeable:
InflateRect(Result, -GetSystemMetrics(SM_CXSIZEFRAME),
-GetSystemMetrics(SM_CYSIZEFRAME));
end;
{ Set the appropriate height of caption bar. }
if BS in [bsToolWindow, bsSizeToolWin] then
Result.Bottom := Result.Top + GetSystemMetrics(SM_CYSMCAPTION) - 1
else
Result.Bottom := Result.Top + GetSystemMetrics(SM_CYCAPTION) - 1;
end; { GetTitleBarRect }
function TrmCaptionButtonsCollection.ButtonsRect: TRect;
var
r: trect;
loop: integer;
begin
r := excludebtnrgn(GetCaptionrect);
r.left := r.right;
for loop := 0 to count - 1 do
if items[loop].visible then r.left := r.left - items[loop].width;
result := r;
end;
{ TrmCaptionButtons }
constructor TrmCaptionButtons.create(AOwner: TComponent);
begin
inherited create(AOwner);
OldWndProc := nil;
NewWndProc := nil;
fcanvas := tcanvas.create;
fbuttons := TrmCaptionButtonsCollection.create(Aowner);
fncmousedown := false;
fncmousedownrect := rect(0, 0, 0, 0);
fPaintButtons := true;
fvisible := true;
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := ImageListChange;
FFont := TFont.create;
ffont.assign(GetOwnerAsForm.Font);
HookWin;
end;
destructor TrmCaptionButtons.destroy;
begin
UnHookWin;
fbuttons.free;
fcanvas.free;
ffont.free;
inherited;
end;
procedure TrmCaptionButtons.HookWin;
begin
if csdesigning in componentstate then exit;
if not assigned(NewWndProc) then
begin
OldWndProc := TFarProc(GetWindowLong(GetOwnerAsForm.Handle, GWL_WNDPROC));
{$ifdef D6_or_higher}
NewWndProc := Classes.MakeObjectInstance(HookWndProc);
{$else}
NewWndProc := MakeObjectInstance(HookWndProc);
{$endif}
SetWindowLong(GetOwnerAsForm.Handle, GWL_WNDPROC, LongInt(NewWndProc));
PushOldProc(GetOwnerAsForm, OldWndProc);
end;
end; { HookWin }
procedure TrmCaptionButtons.UnhookWin;
begin
if csdesigning in componentstate then exit;
if assigned(NewWndProc) then
begin
SetWindowLong(GetOwnerAsForm.Handle, GWL_WNDPROC, LongInt(PopOldProc(GetOwnerAsForm)));
if assigned(NewWndProc) then
{$ifdef D6_or_higher}
Classes.FreeObjectInstance(NewWndProc);
{$else}
FreeObjectInstance(NewWndProc);
{$endif}
oldWndProc := nil;
NewWndProc := nil;
end;
end; { UnHookWin }
function TrmCaptionButtons.calcPoint(x, y: integer): tpoint;
var
wp: tpoint;
begin
with GetOwnerAsForm do
case WindowState of
wsnormal: wp := point(x - left, y - top);
wsMaximized: wp := point(x, y);
wsMinimized: wp := point(x - left, y - top);
end;
if GetOwnerAsForm.left < 0 then inc(wp.x, abs(GetOwnerAsForm.left));
if GetOwnerAsForm.top < 0 then inc(wp.y, abs(GetOwnerAsForm.top));
result := wp;
end;
procedure TrmCaptionButtons.HookWndProc(var WorkMsg: TMessage);
var
xpos, ypos: integer;
wp: tpoint;
myMsg: Cardinal;
oldBtnID : integer;
begin
with WorkMsg do
begin
MyMsg := msg;
case MyMsg of
WM_DESTROY:
begin
Result := CallWindowProc(OldWndProc, GetOwnerAsForm.handle, WorkMsg.Msg, WorkMsg.wParam, WorkMsg.lParam);
UnHookWin;
UpdateCaption;
exit;
end;
WM_ERASEBKGND:
if paintingbutton then
begin
result := 0;
exit;
end;
WM_NCLBUTTONDBLCLK:
begin
xpos := TWMNCLButtonDown(WorkMsg).xcursor;
ypos := TWMNCLButtonDown(WorkMsg).ycursor;
wp := calcPoint(xpos, ypos);
if (fvisible) and ptinrect(fButtons.ButtonsRect, wp) then
begin
if BtnEnabled(wp) then
begin
fncmousedown := true;
PaintButtons(wp);
end;
result := 0;
exit;
end
end;
wm_nchittest:
begin
Result := CallWindowProc(OldWndProc, GetOwnerAsForm.handle, MyMsg, wParam, lParam);
if result = htCaption then
begin
xpos := twmncHitTest(WorkMsg).xpos;
ypos := twmncHitTest(WorkMsg).ypos;
wp := GetOwnerAsForm.screentoclient(calcPoint(xpos, ypos));
if (fvisible) and ptinrect(fButtons.ButtonsRect, wp) and (fNCMouseDown) then
begin
if fNCButtonId <> -1 then PaintButtons(point(-1, -1));
result := 0;
exit;
end;
end
else
begin
PaintButtons(point(-1, -1));
end;
end;
WM_NCLButtonDown:
begin
xpos := TWMNCLButtonDown(WorkMsg).xcursor;
ypos := TWMNCLButtonDown(WorkMsg).ycursor;
wp := calcPoint(xpos, ypos);
if (fvisible) and ptinrect(fButtons.ButtonsRect, wp) then
begin
if BtnEnabled(wp) then
begin
fncmousedown := true;
PaintButtons(wp);
end;
result := 0;
exit;
end
end;
WM_NCMouseMove:
begin
xpos := TWMNCLButtonDown(WorkMsg).xcursor;
ypos := TWMNCLButtonDown(WorkMsg).ycursor;
wp := calcPoint(xpos, ypos);
if (fvisible) and ptinrect(fncMouseDownRect, wp) and (fNCMouseDown) then
begin
if fNCButtonId = -1 then PaintButtons(wp);
result := 0;
exit;
end;
if (fNCButtonId <> -1) then PaintButtons(point(-1, -1));
end;
WM_NCLButtonUp:
begin
xpos := TWMNCLButtonUp(WorkMsg).xcursor;
ypos := TWMNCLButtonUp(WorkMsg).ycursor;
wp := calcPoint(xpos, ypos);
if (fvisible) and ptinrect(fncMouseDownRect, wp) and (fNCMouseDown) then
begin
OldBtnID := fncButtonID;
fncmousedown := false;
Result := 0;
PaintButtons(point(-1, -1));
if assigned(fCapBtnClick) then
fCapBtnClick(OldBtnID);
exit;
end;
fncmousedown := false;
end;
end;
Result := CallWindowProc(OldWndProc, (Owner as TForm).handle, MyMsg, wParam, lParam);
case MyMsg of
WM_NCPAINT: PaintButtons(point(-1, -1));
WM_NCACTIVATE: PaintButtons(point(-1, -1));
WM_MouseMove: if (fNCButtonId <> -1) then PaintButtons(point(-1, -1));
WM_LButtonUp: if fncmousedown then
begin
fncmousedown := false;
PaintButtons(point(-1, -1));
end;
end;
end;
end; { HookWndProc }
procedure TrmCaptionButtons.PaintButtons(pt: tpoint);
var
btnrect: trect;
loop: integer;
x, y: integer;
bmp: TBitmap;
tc1, tc2, bc1, bc2: TColor;
// xadj, yadj: integer;
wItem : TrmCaptionButtonItem;
wDrawFlags : UInt;
wBtnDown : boolean;
begin
if (fPaintButtons = false) or (fvisible = false) then exit;
PaintingButton := true;
bmp := tbitmap.create;
fcanvas.handle := getwindowdc(GetOwnerAsForm.handle);
try
btnrect := fbuttons.buttonsrect;
bmp.Width := btnrect.Right - btnrect.left;
bmp.height := btnrect.bottom - btnrect.top;
bmp.Canvas.CopyRect(rect(0, 0, bmp.width, bmp.height), fcanvas, btnrect);
bmp.canvas.font.assign(font);
fNCbuttonID := -1;
wDrawFlags := DT_VCenter or DT_CENTER or DT_NOPREFIX or DT_SINGLELINE;
for loop := 0 to fbuttons.count - 1 do
begin
wItem := fbuttons[loop];
if wItem.style = cbsbutton then
begin
btnrect := wItem.ButtonRect;
bmp.canvas.brush.Color := clbtnface;
bmp.canvas.FillRect(btnrect);
if ptinrect(wItem.CapBtnRect, pt) then
begin
tc1 := cl3dDkShadow;
tc2 := clbtnShadow;
bc1 := clbtnhighlight;
bc2 := cl3dlight;
fNCbuttonID := loop;
fncmousedownrect := wItem.CapBtnRect;
wBtnDown := true;
end
else
begin
tc1 := clbtnhighlight;
tc2 := cl3dlight;
bc1 := cl3dDkShadow;
bc2 := clbtnShadow;
wBtnDown := false;
end;
frame3d(bmp.canvas, btnrect, tc1, bc1, 1);
frame3d(bmp.canvas, btnrect, tc2, bc2, 1);
if assigned(fimages) and (wItem.imageindex <> -1) then
begin
y := btnrect.top + ((btnrect.bottom - btnrect.top) shr 1) - (fimages.height shr 1);
x := btnrect.left + ((btnrect.right - btnrect.left) shr 1) - (fimages.width shr 1);
inc(x);
inc(y);
end
else
begin
y := btnrect.top + ((btnrect.bottom - btnrect.top) shr 1) - (bmp.canvas.textheight(fbuttons[loop].caption) shr 1);
x := btnrect.left + ((btnrect.right - btnrect.left) shr 1) - (bmp.canvas.textwidth(fbuttons[loop].caption) shr 1);
end;
if assigned(fimages) and (wItem.imageindex <> -1) then
begin
if wBtnDown then
fimages.Draw(bmp.canvas, x, y, wItem.imageindex)
else
fimages.Draw(bmp.canvas, x-1, y-1, wItem.imageindex);
end
else
begin
bmp.Canvas.brush.Style := bsClear;
if not wbtnDown then
OffsetRect(btnrect, -1, -1);
try
if wItem.enabled then
DrawText(bmp.Canvas.handle, pchar(wItem.Caption), length(wItem.Caption), btnRect, wDrawFlags)
else
begin
bmp.Canvas.Font.Color := clBtnHighlight;
try
DrawText(bmp.Canvas.handle, pchar(wItem.Caption), length(wItem.Caption), btnRect, wDrawFlags);
bmp.Canvas.Font.Color := clBtnShadow;
OffsetRect(btnrect, -1, -1);
DrawText(bmp.Canvas.handle, pchar(wItem.Caption), length(wItem.Caption), btnRect, wDrawFlags);
OffsetRect(btnrect, 1, 1);
finally
bmp.canvas.font.color := clBtnText;
end
end;
finally
if not wBtnDown then
OffsetRect(btnrect, 1, 1);
bmp.Canvas.brush.Style := bsSolid;
end;
end;
end;
end;
btnrect := fbuttons.buttonsrect;
fcanvas.draw(btnrect.left, btnrect.top, bmp);
finally
bmp.free;
if fcanvas.handle <> 0 then
releasedc(GetOwnerAsForm.handle, fcanvas.handle);
fcanvas.handle := 0;
PaintingButton := false;
end;
end;
procedure TrmCaptionButtons.updatecaption;
begin
try
fPaintButtons := false;
SetWindowPos(GetOwnerAsForm.handle, 0, 0, 0, 0, 0,
SWP_FRAMECHANGED or SWP_DRAWFRAME or
SWP_NOZORDER or SWP_NOMOVE or SWP_NOSIZE);
fPaintButtons := true;
SetWindowPos(GetOwnerAsForm.handle, 0, 0, 0, 0, 0,
SWP_FRAMECHANGED or SWP_DRAWFRAME or
SWP_NOZORDER or SWP_NOMOVE or SWP_NOSIZE);
except
//Do Nothing
end;
end;
procedure TrmCaptionButtons.Show;
begin
fvisible := true;
updatecaption;
end;
procedure TrmCaptionButtons.Hide;
begin
fvisible := false;
updatecaption;
end;
procedure TrmCaptionButtons.SetVisible(value: boolean);
begin
case value of
true: show;
false: hide;
end;
end;
procedure TrmCaptionButtons.SetFont(value: Tfont);
begin
ffont.assign(value);
PaintButtons(Point(-1,-1));
end;
procedure TrmCaptionButtons.CMTextChanged(var msg: TMessage);
begin
inherited;
PaintButtons(point(-1, -1));
end;
function TrmCaptionButtons.GetOwnerAsForm: TForm;
begin
if (owner is TForm) then
begin
result := TForm(Owner);
if not result.handleallocated then
result.handleneeded;
end
else
result := nil;
end;
procedure TrmCaptionButtons.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if operation = opremove then
begin
if (AComponent = Images) then
Images := nil;
end;
end;
procedure TrmCaptionButtons.SetImages(const Value: TCustomImagelist);
begin
if Images <> nil then
Images.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if Images <> nil then
begin
Images.RegisterChanges(FImageChangeLink);
Images.FreeNotification(Self);
end;
if Not (csdestroying in componentstate) then
PaintButtons(point(-1,-1));
end;
procedure TrmCaptionButtons.ImageListChange(Sender: TObject);
begin
PaintButtons(point(-1,-1));
end;
function TrmCaptionButtons.BtnEnabled(pt: TPoint): boolean;
var
loop : integer;
begin
result := false;
for loop := 0 to fbuttons.Count-1 do
begin
if ptinrect(fbuttons.Items[loop].CapBtnRect, pt) then
begin
Result := fbuttons.Items[loop].Enabled;
break;
end;
end;
end;
end.
|
unit ThShapeItem;
interface
uses
System.Generics.Collections,
GR32, GR32_Polygons, GR32_VectorUtils, clipper,
DMX.DesignPattern,
ThTypes, ThUtils, ThClasses,
ThItem;
type
TThShapeItemClass = class of TThShapeItem;
TThShapeItemFactory = class(TClassFactory<string, TThShapeItemClass>)
public
class function GetShapeItem(AId: string; AStyle: IThDrawStyle): TThShapeItem;
end;
TThRectItem = class(TThFaceShapeItem)
protected
function RectToPolyPoly(ARect: TFloatRect): TThPolyPoly; override;
end;
TThRoundRectItem = class(TThFaceShapeItem)
protected
function RectToPolyPoly(ARect: TFloatRect): TThPolyPoly; override;
end;
TThLineItem = class(TThLineShapeItem)
protected
function PointToPolyPoly(AFromPoint, AToPoint: TFloatPoint): TThPolyPoly; override;
end;
TThElbowLineItem = class(TThLineItem)
end;
implementation
uses
System.Math,
GR32_Geometry;
procedure RegisterItems;
begin
TThShapeItemFactory.Instance.Regist('Rect', TThRectItem);
TThShapeItemFactory.Instance.Regist('RoundRect', TThRoundRectItem);
TThShapeItemFactory.Instance.Regist('Line', TThLineItem);
end;
{ TThShapeItemFactory }
class function TThShapeItemFactory.GetShapeItem(AId: string; AStyle: IThDrawStyle): TThShapeItem;
var
Cls: TThShapeItemClass;
begin
Cls := Instance.GetClass(AId);
if not Assigned(Cls) then
Exit(nil);
Result := Cls.Create;
Result.SetStyle(AStyle);
end;
{ TThRectItem }
function TThRectItem.RectToPolyPoly(ARect: TFloatRect): TThPolyPoly;
var
Poly: TThPoly;
begin
Poly := Rectangle(ARect);
Result := PolyPolygon(Poly);
end;
{ TThRoundRectItem }
function TThRoundRectItem.RectToPolyPoly(ARect: TFloatRect): TThPolyPoly;
var
Poly: TThPoly;
begin
if ARect.Width <= ARect.Height * 2 then
ARect.Width := ARect.Height * 2;
Poly := RoundRect(ARect, Max(Abs(ARect.Bottom - ARect.Top), 1) / 2);
Result := PolyPolygon(Poly);
end;
{ TThLineItem }
function GetArrowPoints(APt1, APt2: TFloatPoint; ASize: Single): TThPoly;
var
UnitVec, UnitNorm: TFloatPoint;
TipPoint: TFloatPoint;
begin
SetLength(Result, 3);
UnitVec := GetUnitVector(APt1, APt2);
TipPoint := OffsetPoint(APt1, UnitVec.X * ASize, UnitVec.Y * ASize);
UnitNorm := GetUnitNormal(TipPoint, APt1);
Result[0] := APt1;
Result[1] := OffsetPoint(TipPoint, UnitNorm.X * ASize/2, UnitNorm.Y * ASize/2);
Result[2] := OffsetPoint(TipPoint, -UnitNorm.X * ASize/2, -UnitNorm.Y * ASize/2);
end;
function TThLineItem.PointToPolyPoly(AFromPoint,
AToPoint: TFloatPoint): TThPolyPoly;
var
Poly, ArrowPts: TThPoly;
PolyPath: TPath;
PolyPolyPath: TPaths;
begin
ArrowPts := GetArrowPoints(ToPoint, FromPoint, 20);
with TClipper.Create do
try
Poly := BuildPolyline([AFromPoint, AToPoint], BorderWidth, jsRound, esRound);
PolyPath := AAFloatPoint2AAPoint(Poly, 3);
AddPath(PolyPath, ptSubject, True);
Poly := BuildPolyline([ArrowPts[0], ArrowPts[1]], BorderWidth, jsRound, esRound);
PolyPath := AAFloatPoint2AAPoint(Poly, 3);
AddPath(PolyPath, ptClip, True);
Poly := BuildPolyline([ArrowPts[0], ArrowPts[2]], BorderWidth, jsRound, esRound);
PolyPath := AAFloatPoint2AAPoint(Poly, 3);
AddPath(PolyPath, ptClip, True);
Execute(ctUnion, PolyPolyPath, pftNonZero);
finally
Free;
end;
Result := AAPoint2AAFloatPoint(PolyPolyPath, 3);
end;
initialization
RegisterItems;
finalization
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.