text stringlengths 14 6.51M |
|---|
{**********************************************}
{ TGanttSeries (derived from TPointSeries) }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit GanttCh;
{$I TeeDefs.inc}
interface
{ TGanttSeries is a Chart Series derived from TPointSeries.
Each point in the series is drawn as a Gantt horizontal bar.
Each point has a Start and End values that are used to draw the Gantt bar
with its corresponding screen length in the horizontal plane. }
Uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
Classes,
{$IFDEF CLX}
QGraphics,
{$ELSE}
Graphics,
{$ENDIF}
Chart, Series, TeEngine, TeCanvas;
type
TGanttSeries=class(TPointSeries)
private
{ The Gantt Start values are implicit stored in XValues }
FEndValues : TChartValueList; { <-- Gantt bar's End values storage }
FNextTask : TChartValueList; { <-- Used to connect lines }
Function GetConnectingPen:TChartPen;
Function GetStartValues:TChartValueList;
Procedure SetConnectingPen(Value:TChartPen);
Procedure SetEndValues(Value:TChartValueList);
Procedure SetNextTask(Value:TChartValueList);
Procedure SetStartValues(Value:TChartValueList);
protected
Procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); override; { <-- to add random end values }
Function ClickedPointer( ValueIndex,tmpX,tmpY:Integer;
x,y:Integer):Boolean; override;
procedure DrawValue(ValueIndex:Integer); override; { <-- main draw method }
Procedure DrawMark(ValueIndex:Integer; Const St:String; APosition:TSeriesMarkPosition); override;
class Function GetEditorClass:String; override;
Procedure PrepareForGallery(IsEnabled:Boolean); override;
public
Constructor Create(AOwner: TComponent); override;
Function AddGantt(Const AStart,AEnd,AY:Double;
Const AXLabel:String=''):Integer;
Function AddGanttColor( Const AStart,AEnd,AY:Double;
Const AXLabel:String='';
AColor:TColor=clTeeColor):Integer;
Function AddXY(Const AXValue,AYValue:Double; Const ALabel:String='';
AColor:TColor=clTeeColor):Integer; override;
Procedure Assign(Source:TPersistent); override;
Function IsValidSourceOf(Value:TChartSeries):Boolean; override;
Function MaxXValue:Double; override; { <-- adds end values }
published
property ColorEachPoint default True;
property ConnectingPen:TChartPen read GetConnectingPen write SetConnectingPen;
property StartValues:TChartValueList read GetStartValues write SetStartValues;
property EndValues:TChartValueList read FEndValues write SetEndValues;
property NextTask:TChartValueList read FNextTask write SetNextTask;
end;
implementation
Uses {$IFDEF CLX}
QDialogs,
{$ELSE}
Dialogs,
{$ENDIF}
Math, SysUtils, TeeProcs, TeeConst;
type
TValueListAccess=class(TChartValueList);
{ TGanttSeries }
Constructor TGanttSeries.Create(AOwner: TComponent);
Begin
inherited;
SetHorizontal;
ClickableLine:=False; { only allow click on Pointer (Gantt Bar) }
CalcVisiblePoints:=False; { draw all points }
XValues.Name:=TeeMsg_ValuesGanttStart;
TValueListAccess(XValues).InitDateTime(True);
ColorEachPoint:=True;
FEndValues :=TChartValueList.Create(Self,TeeMsg_ValuesGanttEnd);
TValueListAccess(FEndValues).InitDateTime(True);
FNextTask :=TChartValueList.Create(Self,TeeMsg_ValuesGanttNextTask);
Pointer.Style:=psRectangle; { <-- a Horizontal Gantt Bar (by default) }
end;
Procedure TGanttSeries.SetEndValues(Value:TChartValueList);
Begin
SetChartValueList(FEndValues,Value); { standard method }
end;
Procedure TGanttSeries.SetNextTask(Value:TChartValueList);
Begin
SetChartValueList(TChartValueList(FNextTask),Value); { standard method }
end;
Procedure TGanttSeries.SetConnectingPen(Value:TChartPen);
Begin
LinePen.Assign(Value);
end;
{ Helper method, special to Gantt bar series }
Function TGanttSeries.AddGanttColor( Const AStart,AEnd,AY:Double;
Const AXLabel:String;
AColor:TColor ):Integer;
begin
FEndValues.TempValue:=AEnd;
result:=AddXY(AStart,AY,AXLabel,AColor);
end;
{ Helper method, special to Gantt bar series }
Function TGanttSeries.AddGantt( Const AStart,AEnd,AY:Double;
Const AXLabel:String):Integer;
Begin
result:=AddGanttColor(AStart,AEnd,AY,AXLabel);
end;
Procedure TGanttSeries.AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False);
Function GanttSampleStr(Index:Integer):String;
begin
Case Index of
0: result:=TeeMsg_GanttSample1;
1: result:=TeeMsg_GanttSample2;
2: result:=TeeMsg_GanttSample3;
3: result:=TeeMsg_GanttSample4;
4: result:=TeeMsg_GanttSample5;
5: result:=TeeMsg_GanttSample6;
6: result:=TeeMsg_GanttSample7;
7: result:=TeeMsg_GanttSample8;
8: result:=TeeMsg_GanttSample9;
else
result:=TeeMsg_GanttSample10;
end;
end;
Const NumGanttSamples=10;
Var Added : Integer;
t : Integer;
tmpY : Integer;
tt : Integer;
tmpStartTask : TDateTime;
tmpEndTask : TDateTime;
Begin
{ some sample values to see something at design mode }
for t:=0 to Math.Min( NumValues-1, NumGanttSamples+RandomValue(20) ) do
begin
tmpStartTask:=Date+t*3+RandomValue(5);
tmpEndTask:=tmpStartTask+9+RandomValue(16);
tmpY:=(t mod 10);
Added:=AddGantt( tmpStartTask, // Start
tmpEndTask, // End
tmpY, // Y value
GanttSampleStr(tmpY) // some sample label text
);
// Connect Gantt points:
for tt:=0 to Added-1 do
if (NextTask.Value[tt]=-1) and (tmpStartTask>EndValues.Value[tt]) then
begin
NextTask.Value[tt]:=Added;
break;
end;
end;
end;
Function TGanttSeries.ClickedPointer( ValueIndex,tmpX,tmpY:Integer;
x,y:Integer):Boolean;
begin
result:=(x>=tmpX) and (x<=CalcXPosValue(EndValues.Value[ValueIndex])) and
(Abs(tmpY-Y)<Pointer.VertSize);
end;
procedure TGanttSeries.DrawValue(ValueIndex:Integer);
var x1 : Integer;
x2 : Integer;
Y : Integer;
tmpHalfHorizSize: Integer;
HalfWay : Integer;
tmpNextTask : Integer;
xNext : Integer;
YNext : Integer;
tmpStyle : TSeriesPointerStyle;
Begin
// This overrided method is the main paint for Gantt bar points.
if Pointer.Visible then
with ParentChart.Canvas do
Begin
Pointer.PrepareCanvas(ParentChart.Canvas,ValueColor[ValueIndex]);
X1:=CalcXPos(ValueIndex);
X2:=CalcXPosValue(EndValues.Value[ValueIndex]);
tmpHalfHorizSize:=(x2-x1) div 2;
Y:=CalcYPos(ValueIndex);
if Assigned(OnGetPointerStyle) then
tmpStyle:=OnGetPointerStyle(Self,ValueIndex)
else
tmpStyle:=Pointer.Style;
Pointer.DrawPointer( ParentChart.Canvas,
ParentChart.View3D,
x1+tmpHalfHorizSize,
Y,
tmpHalfHorizSize,
Pointer.VertSize,
ValueColor[ValueIndex],tmpStyle);
if ConnectingPen.Visible then
Begin
tmpNextTask:=Round(NextTask.Value[ValueIndex]);
if (tmpNextTask>=0) and (tmpNextTask<Count) then
Begin
AssignVisiblePen(ConnectingPen);
Brush.Style:=bsClear;
XNext:=CalcXPos(tmpNextTask);
HalfWay:=X2+((XNext-X2) div 2);
YNext:=CalcYPos(tmpNextTask);
LineWithZ(X2,Y,HalfWay,Y,MiddleZ);
LineTo3D(HalfWay,YNext,MiddleZ);
LineTo3D(XNext,YNext,MiddleZ);
End;
end;
end;
end;
Function TGanttSeries.MaxXValue:Double;
Begin
result:=Math.Max(inherited MaxXValue,FEndValues.MaxValue);
end;
Procedure TGanttSeries.DrawMark( ValueIndex:Integer; Const St:String;
APosition:TSeriesMarkPosition);
Begin
With APosition do
begin
Inc(LeftTop.X,(CalcXPosValue(EndValues.Value[ValueIndex])-ArrowFrom.X) div 2);
Inc(LeftTop.Y,Height div 2);
end;
inherited;
End;
Function TGanttSeries.GetStartValues:TChartValueList;
Begin
result:=XValues;
end;
Procedure TGanttSeries.SetStartValues(Value:TChartValueList);
Begin
SetXValues(Value);
end;
Procedure TGanttSeries.PrepareForGallery(IsEnabled:Boolean);
begin
inherited;
ColorEachPoint:=IsEnabled;
Pointer.VertSize:=3;
Pointer.Gradient.Visible:=True;
end;
class Function TGanttSeries.GetEditorClass:String;
begin
result:='TGanttSeriesEditor'; { <-- dont translate ! }
end;
Procedure TGanttSeries.Assign(Source:TPersistent);
begin
if Source is TGanttSeries then
ConnectingPen:=TGanttSeries(Source).ConnectingPen;
inherited;
end;
Function TGanttSeries.IsValidSourceOf(Value:TChartSeries):Boolean;
begin
result:=Value is TGanttSeries; { Only Gantt can be assigned to Gantt }
end;
function TGanttSeries.GetConnectingPen: TChartPen;
begin
result:=LinePen;
end;
function TGanttSeries.AddXY(const AXValue, AYValue: Double;
const ALabel: String; AColor: TColor): Integer;
begin
NextTask.TempValue:=-1;
result:=inherited AddXY(AXValue,AYValue,ALabel,AColor);
end;
initialization
RegisterTeeSeries(TGanttSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryGantt,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryStandard,1);
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.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.
//
unit RN_SampleInterfaces;
interface
uses Math, OpenGL, StrUtils, SysUtils,
RN_Helper, RN_Recast, RN_DebugDraw;
// These are example implementations of various interfaces used in Recast and Detour.
type
/// Recast build context.
TBuildContext = class(TrcContext)
private
m_startTime: array [TrcTimerLabel] of Int64;
m_accTime: array [TrcTimerLabel] of Integer;
const MAX_MESSAGES = 1000;
var
m_messages: array [0..MAX_MESSAGES-1] of string;
m_messageCount: Integer;
//const TEXT_POOL_SIZE = 8000;
//var
//m_textPool: array [0..TEXT_POOL_SIZE-1] of Char;
//m_textPoolSize: Integer;
protected
/// Virtual functions for custom implementations.
///@
procedure doResetLog(); override;
procedure doLog(category: TrcLogCategory; msg: string); override;
procedure doResetTimers(); override;
procedure doStartTimer(const &label: TrcTimerLabel); override;
procedure doStopTimer(const &label: TrcTimerLabel); override;
function doGetAccumulatedTime(const &label: TrcTimerLabel): Integer; override;
///@
public
/// Dumps the log to stdout.
procedure dumpLog(format: string);
/// Returns number of log messages.
function getLogCount: Integer;
/// Returns log message text.
function getLogText(const i: Integer): string;
end;
/// OpenGL debug draw implementation.
TDebugDrawGL = class(TduDebugDraw)
public
procedure depthMask(state: Boolean); override;
procedure texture(state: Boolean); override;
procedure &begin(prim: TduDebugDrawPrimitives; size: Single = 1.0); override;
procedure vertex(const pos: PSingle; color: Cardinal); override;
procedure vertex(const x,y,z: Single; color: Cardinal); override;
procedure vertex(const pos: PSingle; color: Cardinal; uv: PSingle); override;
procedure vertex(const x,y,z: Single; color: Cardinal; u,v: Single); override;
procedure &end(); override;
end;
{/// stdio file implementation.
TFileIO = class(TduFileIO)
private
FILE* m_fp;
int m_mode;
public
FileIO();
virtual ~FileIO();
bool openForWrite(const char* path);
bool openForRead(const char* path);
virtual bool isWriting() const;
virtual bool isReading() const;
virtual bool write(const void* ptr, const size_t size);
virtual bool read(void* ptr, const size_t size);
end;}
implementation
uses RN_PerfTimer;
////////////////////////////////////////////////////////////////////////////////////////////////////
// Virtual functions for custom implementations.
procedure TBuildContext.doResetLog();
begin
m_messageCount := 0;
//m_textPoolSize := 0;
end;
procedure TBuildContext.doLog(category: TrcLogCategory; msg: string);
const Cat: array [TrcLogCategory] of String = ('','W','E');
begin
if (msg = '') then Exit;
if (m_messageCount >= MAX_MESSAGES) then
Exit;
// Store message
m_messages[m_messageCount] := cat[category] + ' ' + msg;
Inc(m_messageCount);
end;
procedure TBuildContext.doResetTimers();
var i: TrcTimerLabel;
begin
for i := Low(TrcTimerLabel) to High(TrcTimerLabel) do
m_accTime[i] := -1;
end;
procedure TBuildContext.doStartTimer(const &label: TrcTimerLabel);
begin
m_startTime[&label] := getPerfTime();
end;
procedure TBuildContext.doStopTimer(const &label: TrcTimerLabel);
var endTime: Int64; deltaTime: Integer;
begin
endTime := getPerfTime();
deltaTime := Integer(endTime - m_startTime[&label]);
if (m_accTime[&label] = -1) then
m_accTime[&label] := deltaTime
else
Inc(m_accTime[&label], deltaTime);
end;
function TBuildContext.doGetAccumulatedTime(const &label: TrcTimerLabel): Integer;
begin
Result := m_accTime[&label];
end;
procedure TBuildContext.dumpLog(format: string);
begin
{// Print header.
va_list ap;
va_start(ap, format);
vprintf(format, ap);
va_end(ap);
printf("\n");
// Print messages
const int TAB_STOPS[4] := begin 28, 36, 44, 52 end;;
for (int i := 0; i < m_messageCount; ++i)
begin
const char* msg := m_messages[i]+1;
int n := 0;
while ( *msg)
begin
if ( *msg == '\t')
begin
int count := 1;
for (int j := 0; j < 4; ++j)
begin
if (n < TAB_STOPS[j])
begin
count := TAB_STOPS[j] - n;
break;
end;
end;
while (--count)
begin
putchar(' ');
n++;
end;
end;
else
begin
putchar( *msg);
n++;
end;
msg++;
end;
putchar('\n');
end;}
end;
function TBuildContext.getLogCount: Integer;
begin
Result := m_messageCount;
end;
function TBuildContext.getLogText(const i: Integer): string;
begin
Result := m_messages[i];
end;
////////////////////////////////////////////////////////////////////////////////////////////////////
{class GLCheckerTexture
begin
unsigned int m_texId;
public:
GLCheckerTexture() : m_texId(0)
begin
end;
~GLCheckerTexture()
begin
if (m_texId != 0)
glDeleteTextures(1, &m_texId);
end;
void bind()
begin
if (m_texId == 0)
begin
// Create checker pattern.
const unsigned int col0 := duRGBA(215,215,215,255);
const unsigned int col1 := duRGBA(255,255,255,255);
static const int TSIZE := 64;
unsigned int data[TSIZE*TSIZE];
glGenTextures(1, &m_texId);
glBindTexture(GL_TEXTURE_2D, m_texId);
int level := 0;
int size := TSIZE;
while (size > 0)
begin
for (int y := 0; y < size; ++y)
for (int x := 0; x < size; ++x)
data[x+y*size] := (x==0 || y==0) ? col0 : col1;
glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA, size,size, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
size /= 2;
level++;
end;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
end;
else
begin
glBindTexture(GL_TEXTURE_2D, m_texId);
end;
end;
end;;
GLCheckerTexture g_tex;}
procedure TDebugDrawGL.depthMask(state: Boolean);
begin
if state then
glDepthMask(GL_TRUE)
else
glDepthMask(GL_FALSE);
end;
procedure TDebugDrawGL.texture(state: Boolean);
begin
if (state) then
begin
glEnable(GL_TEXTURE_2D);
//todo: g_tex.bind();
end
else
begin
glDisable(GL_TEXTURE_2D);
end;
end;
procedure TDebugDrawGL.&begin(prim: TduDebugDrawPrimitives; size: Single);
begin
case prim of
DU_DRAW_POINTS: begin
glPointSize(size);
glBegin(GL_POINTS);
end;
DU_DRAW_LINES: begin
glLineWidth(size);
glBegin(GL_LINES);
end;
DU_DRAW_TRIS:
glBegin(GL_TRIANGLES);
DU_DRAW_QUADS:
glBegin(GL_QUADS);
end;
end;
procedure TDebugDrawGL.vertex(const pos: PSingle; color: Cardinal);
begin
glColor4ubv(PGLubyte(@color));
{$IFDEF SWAP_XZY}
{$POINTERMATH ON}
glVertex3f(pos^, (pos+2)^, (pos+1)^);
{$POINTERMATH OFF}
{$ENDIF}
{$IFNDEF SWAP_XZY}
glVertex3fv(PGLfloat(pos));
{$ENDIF}
end;
procedure TDebugDrawGL.vertex(const x,y,z: Single; color: Cardinal);
begin
glColor4ubv(PGLubyte(@color));
{$IFDEF SWAP_XZY}
{$POINTERMATH ON}
glVertex3f(x,z,y);
{$POINTERMATH OFF}
{$ENDIF}
{$IFNDEF SWAP_XZY}
glVertex3f(x,y,z);
{$ENDIF}
end;
procedure TDebugDrawGL.vertex(const pos: PSingle; color: Cardinal; uv: PSingle);
begin
glColor4ubv(PGLubyte(@color));
glTexCoord2fv(PGLfloat(uv));
{$IFDEF SWAP_XZY}
{$POINTERMATH ON}
glVertex3f(pos^, (pos+2)^, (pos+1)^);
{$POINTERMATH OFF}
{$ENDIF}
{$IFNDEF SWAP_XZY}
glVertex3fv(PGLfloat(pos));
{$ENDIF}
end;
procedure TDebugDrawGL.vertex(const x,y,z: Single; color: Cardinal; u,v: Single);
begin
glColor4ubv(PGLubyte(@color));
glTexCoord2f(u,v);
{$IFDEF SWAP_XZY}
{$POINTERMATH ON}
glVertex3f(x,z,y);
{$POINTERMATH OFF}
{$ENDIF}
{$IFNDEF SWAP_XZY}
glVertex3f(x,y,z);
{$ENDIF}
end;
procedure TDebugDrawGL.&end();
begin
glEnd();
glLineWidth(1.0);
glPointSize(1.0);
end;
{////////////////////////////////////////////////////////////////////////////////////////////////////
FileIO::FileIO() :
m_fp(0),
m_mode(-1)
begin
end;
FileIO::~FileIO()
begin
if (m_fp) fclose(m_fp);
end;
bool FileIO::openForWrite(const char* path)
begin
if (m_fp) return false;
m_fp := fopen(path, "wb");
if (!m_fp) return false;
m_mode := 1;
return true;
end;
bool FileIO::openForRead(const char* path)
begin
if (m_fp) return false;
m_fp := fopen(path, "rb");
if (!m_fp) return false;
m_mode := 2;
return true;
end;
bool FileIO::isWriting() const
begin
return m_mode == 1;
end;
bool FileIO::isReading() const
begin
return m_mode == 2;
end;
bool FileIO::write(const void* ptr, const size_t size)
begin
if (!m_fp || m_mode != 1) return false;
fwrite(ptr, size, 1, m_fp);
return true;
end;
bool FileIO::read(void* ptr, const size_t size)
begin
if (!m_fp || m_mode != 2) return false;
size_t readLen := fread(ptr, size, 1, m_fp);
return readLen == 1;
end;}
end.
|
unit uProgressTemplate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;
type
TProgressCallback = procedure (InProgressOverall, InProgressCurrent: TProgressBar) of Object;
type
TfrmProgressForm = class(TForm)
Label1: TLabel;
pbOverall: TProgressBar;
Label2: TLabel;
pbCurrent: TProgressBar;
private
{ Private declarations }
public
{ Public declarations }
end;
procedure ShowProgress(InCallback: TProgressCallback);
implementation
{$R *.dfm}
procedure ShowProgress(InCallback: TProgressCallback);
var
LWindowList: TTaskWindowList;
LSaveFocusState: TFocusState;
LProgressForm: TfrmProgressForm;
begin
LProgressForm := TfrmProgressForm.Create(NIL);
try
LSaveFocusState := SaveFocusState;
Screen.SaveFocusedList.Insert(0, Screen.FocusedForm);
Application.ModalStarted;
LWindowList := DisableTaskWindows(0);
Screen.FocusedForm := LProgressForm;
SendMessage(LProgressForm.Handle, CM_ACTIVATE, 0, 0);
LProgressForm.Show;
InCallback(LProgressForm.pbOverall, LProgressForm.pbCurrent);
EnableTaskWindows(LWindowList);
RestoreFocusState(LSaveFocusState);
finally
Application.ModalFinished;
FreeAndNil(LProgressForm);
end;
end;
end.
|
unit Main_Frm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Vcl.Forms,
System.Classes, Vcl.Graphics, System.ImageList, Vcl.ImgList, Vcl.Controls,
Vcl.Dialogs, System.Actions, Vcl.ActnList, System.Win.Registry, Data.DB,
System.DateUtils, System.IOUtils, Winapi.ShellApi, System.Types,
Base_Frm, BaseLayout_Frm, VBProxyClass, VBCommonValues, CommonFunctions, CommonValues,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore,
dxSkinsDefaultPainters, cxImageList, dxLayoutLookAndFeels, cxClasses, cxStyles,
dxLayoutContainer, dxLayoutControl, dxScreenTip, dxCustomHint, cxHint,
dxSkinsForm, cxNavigator, cxDBNavigator, dxBar, dxStatusBar, cxCustomData,
cxFilter, cxData, cxDataStorage, cxEdit, dxDateRanges, cxDBData, cxGridLevel,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxCurrencyEdit,
cxGridBandedTableView, cxGridDBBandedTableView, cxGrid, cxDBLookupComboBox,
cxTextEdit, cxCheckBox, cxCalendar, CommonMethods, cxContainer, Vcl.ComCtrls,
dxCore, cxDateUtils, cxDropDownEdit, cxMaskEdit, cxLookupEdit, cxDBLookupEdit,
dxBarExtItems, cxBarEditItem, cxMemo, Vcl.Menus, dxScrollbarAnnotations,
dxRibbonSkins, dxRibbonCustomizationForm, dxRibbon, dxPrnDev, dxPrnDlg,
cxGridExportLink, cxDataUtils;
type
TMainFrm = class(TBaseLayoutFrm)
barManager: TdxBarManager;
barToolbar: TdxBar;
docToolbar: TdxBarDockControl;
litToolbar: TdxLayoutItem;
btnExit: TdxBarLargeButton;
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainFrm: TMainFrm;
implementation
{$R *.dfm}
uses
TT_DM,
VBBase_DM,
MsgDialog_Frm,
RUtils,
Progress_Frm;
end.
|
unit MasterMind.Presenter;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
interface
uses
MasterMind.API;
type
TMasterMindPresenter = class(TInterfacedObject, IGamePresenter)
private
FCodeSelector: ICodeSelector;
FEvaluator: IGuessEvaluator;
FView: IGameView;
FCodeToBeGuessed: TMasterMindCode;
FPreviousGuesses: TPreviousGuesses;
procedure ClearPreviousGuesses;
procedure AddGuess(const EvaluatedGuess: TEvaluatedGuess);
procedure EvaluateGuess(const Guess: TMasterMindCode);
function GuessWasCorrect: Boolean;
procedure RequestNextGuessOrEndGameIfNecassary;
public
constructor Create(const CodeSelector: ICodeSelector; const Evaluator: IGuessEvaluator; const View: IGameView);
procedure NewGame;
function GetCodeToBeGuessed: TMasterMindCode;
procedure TakeGuess(const Guess: TMasterMindCode);
end;
implementation
constructor TMasterMindPresenter.Create(const CodeSelector: ICodeSelector; const Evaluator: IGuessEvaluator; const View: IGameView);
begin
inherited Create;
FCodeSelector := CodeSelector;
FEvaluator := Evaluator;
FView := View;
end;
procedure TMasterMindPresenter.NewGame;
begin
ClearPreviousGuesses;
FCodeToBeGuessed := FCodeSelector.SelectNewCode;
FView.ShowGuesses(FPreviousGuesses);
FView.StartRequestGuess(FPreviousGuesses);
end;
function TMasterMindPresenter.GetCodeToBeGuessed: TMasterMindCode;
begin
Result := FCodeToBeGuessed;
end;
procedure TMasterMindPresenter.ClearPreviousGuesses;
begin
SetLength(FPreviousGuesses, 0);
end;
procedure TMasterMindPresenter.TakeGuess(const Guess: TMasterMindCode);
begin
EvaluateGuess(Guess);
FView.ShowGuesses(FPreviousGuesses);
RequestNextGuessOrEndGameIfNecassary;
end;
procedure TMasterMindPresenter.AddGuess(const EvaluatedGuess: TEvaluatedGuess);
begin
SetLength(FPreviousGuesses, Length(FPreviousGuesses) + 1);
FPreviousGuesses[High(FPreviousGuesses)] := EvaluatedGuess;
end;
procedure TMasterMindPresenter.EvaluateGuess(const Guess: TMasterMindCode);
var
EvaluatedGuess: TEvaluatedGuess;
begin
EvaluatedGuess.GuessedCode := Guess;
EvaluatedGuess.GuessResult := FEvaluator.EvaluateGuess(FCodeToBeGuessed, Guess);
AddGuess(EvaluatedGuess);
end;
procedure TMasterMindPresenter.RequestNextGuessOrEndGameIfNecassary;
begin
if GuessWasCorrect then
FView.ShowPlayerWinsMessage(FPreviousGuesses)
else if Length(FPreviousGuesses) = MAX_GUESSES then
FView.ShowPlayerLosesMessage(FPreviousGuesses)
else
FView.StartRequestGuess(FPreviousGuesses);
end;
function TMasterMindPresenter.GuessWasCorrect: Boolean;
var
Hint: TMasterMindHint;
begin
Result := True;
for Hint in FPreviousGuesses[High(FPreviousGuesses)].GuessResult do
if Hint <> mmhCorrect then
Exit(False);
end;
end. |
unit uGMV_Patient;
interface
uses
Classes, StdCtrls,ExtCtrls
;
type
TMessageLevel = (mlError, mlInfo, mlWarning, mlSecurity);
type
TPatient = class(TObject)
private
FDFN: string;
FIdentifiers: TList;
FMessages: TList;
FSensitive: Boolean;
FSex,
FDOB,
FName,
FSSN,
FAge:String;
FLocationName:String;
FLocationID:String;
procedure SetSensitive(NewVal: Boolean);
public
constructor Create;
constructor CreatePatientByDFN(aDFN:String);
destructor Destroy; override;
// published
property DFN: string read FDFN write FDFN;
property Identifiers: TList read FIdentifiers write FIdentifiers;
property Messages: TList read FMessages write FMessages;
property Sensitive: Boolean read FSensitive write SetSensitive;
property Name: String read FName;
property SSN: String read FSSN;
property Age: String read FAge;
property DOB: String read FDOB;
property LocationName: String read FLocationName;
property LocationID: String read FLocationID;
end;
type
TPtIdentifier = class(TObject)
private
FCaption: string;
FDisplayNonSensitive: string;
FDisplaySensitive: string;
FDisplayLabel: TLabel;
public
constructor Create;
destructor Destroy; override;
// published
property Caption: string
read FCaption write FCaption;
property DisplayNonSensitive: string
read FDisplayNonSensitive write FDisplayNonSensitive;
property DisplaySensitive: string
read FDisplaySensitive write FDisplaySensitive;
property DisplayLabel: TLabel
read FDisplayLabel write FDisplayLabel;
end;
type
TPtMessage = class(TObject)
protected
FLevel: TMessageLevel;
FHeader: string;
FText: TStringList;
FPanel: TPanel;
public
constructor Create(Level: TMessageLevel; HeaderText: string);
destructor Destroy; override;
property MessageLevel: TMessageLevel
read FLevel write FLevel;
property Header: string
read FHeader write FHeader;
property Text: TStringList
read FText write FText;
property Panel: TPanel
read FPanel write FPanel;
end;
implementation
uses
SysUtils
, uGMV_Common
, uGMV_Utils
, uGMV_Engine;
//* TPtMessage *//
constructor TPtMessage.Create(Level: TMessageLevel; HeaderText: string);
begin
FText := TStringList.Create;
FLevel := Level;
FHeader := HeaderText;
end;
destructor TPtMessage.Destroy;
begin
FText.Clear;
FText.free;
end;
//* TPtIdentifier *//
constructor TPtIdentifier.Create;
begin
inherited Create;
end;
destructor TPtIdentifier.Destroy;
begin
inherited Destroy;
end;
//* TPatient *//
constructor TPatient.Create;
begin
inherited Create;
FIdentifiers := TList.Create;
FMessages := TList.Create;
end;
constructor TPatient.CreatePatientByDFN(aDFN:String);
var
i: Integer;
PtID: TPtIdentifier;
PtMsg: TPtMessage;
S: String;
SL: TStringList;
begin
inherited Create;
FIdentifiers := TList.Create;
FMessages := TList.Create;
Sensitive := False;
SL := getPatientInfo(aDFN);
try
{Build the Patient Identifiers}
i := 0;
while i < SL.Count do
begin
s := SL[i];
if Piece(s, '^', 1) = '$$PTID' then
begin
PtId := TPtIdentifier.Create;
PtId.Caption := TitleCase(Piece(s, '^', 2));
PtId.DisplayNonSensitive := Piece(s, '^', 3);
PtId.DisplaySensitive := Piece(s, '^', 4);
if PtId.DisplaySensitive = '' then
PtId.DisplaySensitive := PtId.DisplayNonSensitive;
if PtId.Caption = 'Sex' then FSex := PtId.DisplayNonSensitive;
if PtId.Caption = 'Name' then FName := PtId.DisplayNonSensitive;
if PtId.FCaption = 'Social Security Number' then FSSN := PtId.DisplayNonSensitive;
if PtId.Caption = 'Date Of Birth' then
begin
FAge := PtId.DisplayNonSensitive;
FDOB := PtId.DisplaySensitive;
end;
if PtId.Caption = 'Ward Location' then // 050104 zzzzzzandria
begin
FLocationName := PtId.DisplayNonSensitive;
FLocationID := Piece(s,'^',4);
// zzzzzzandria 2008-02-27 -------------------------------------
if FLocationID = '' then
begin
s := getHospitalLocationByID(aDFN);
if s <> '' then
FLocationID := s;
end;
// zzzzzzandria 2008-02-27 -------------------------------------
end;
FIdentifiers.Add(ptId);
end;
inc(i);
end;
{Load any messages}
i := 0;
while i < SL.Count - 1 do
begin
if Piece(SL[i], '^', 1) = '$$MSGHDR' then
begin
case StrToIntDef(Piece(SL[i], '^', 2), -1) of
0: PtMsg := TPtMessage.Create(mlError, Piece(SL[i], '^', 3));
1: PtMsg := TPtMessage.Create(mlInfo, Piece(SL[i], '^', 3));
2: PtMsg := TPtMessage.Create(mlWarning, Piece(SL[i], '^', 3));
3:
begin
PtMsg := TPtMessage.Create(mlSecurity, Piece(SL[i], '^', 3));
Sensitive := True;
end;
else
PtMsg := TPtMessage.Create(mlInfo, Piece(SL[i], '^', 3));
end;
inc(i);
while (i < SL.Count - 1) and
(Piece(SL[i], '^', 1) <> '$$MSGEND') do
begin
ptMsg.Text.Add(SL[i]);
inc(i);
end;
FMessages.Add(PtMsg);
end;
inc(i);
end;
except
end;
SL.Free;
end;
destructor TPatient.Destroy;
begin
while FIdentifiers.Count > 0 do
begin
TPtIdentifier(FIdentifiers[0]).free;
FIdentifiers.Delete(0);
end;
FIdentifiers.free;
while FMessages.Count > 0 do
begin
TPtMessage(FMessages[0]).free;
FMessages.Delete(0);
end;
FMessages.free;
inherited Destroy;
end;
procedure TPatient.SetSensitive(NewVal: Boolean);
var
i: Integer;
begin
FSensitive := NewVal;
for i := 0 to Self.FIdentifiers.Count - 1 do
with TPtIdentifier(Self.FIdentifiers[i]) do
case NewVal of
True: DisplayLabel.Caption := DisplaySensitive;
False: DisplayLabel.Caption := DisplayNonSensitive;
end;
end;
end.
|
unit DMHelper.View.Pages.Main;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.Controls.Presentation,
FMX.StdCtrls,
FMX.Objects,
FMX.Layouts,
Router4D.Interfaces;
type
TfrmMainPage = class(TForm, iRouter4DComponent)
layoutMain: TLayout;
recMain: TRectangle;
lblPageName: TLabel;
private
{ Private declarations }
public
{ Public declarations }
function Render : TFMXObject;
procedure unRender;
end;
var
frmMainPage: TfrmMainPage;
implementation
{$R *.fmx}
{ TfrmMainPage }
function TfrmMainPage.Render: TFMXObject;
begin
Result := layoutMain;
end;
procedure TfrmMainPage.unRender;
begin
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSHosting.EdgeListeners;
{$HPPEMIT LINKUNIT}
interface
uses System.SysUtils, System.Classes, System.Generics.Collections,
EMSHosting.EdgeService;
type
TEMSEdgeListenerFactory = class
protected
function DoCreateListener(const AOwner: TComponent; const AProtocolName: string): TEMSEdgeListener; virtual; abstract;
public
function CreateListener(const AOwner: TComponent; const AProtocolName: string): TEMSEdgeListener;
end;
TEMSEdgeListenerFactories = class
private
class var FInstance: TEMSEdgeListenerFactories;
public type
TProtocolPair = TPair<string, TEMSEdgeListenerFactory>;
private
FUnitNames: TDictionary<string, string>;
FItems: TDictionary<string, TEMSEdgeListenerFactory>;
function GetNames: TArray<string>;
public
constructor Create;
destructor Destroy; override;
procedure Add(const AProtocolName, AUnitName: string; const AFactory: TEMSEdgeListenerFactory);
procedure Remove(const AName: string);
function TryGetFactory(const AName: string; out AFactory: TEMSEdgeListenerFactory): Boolean;
function TryGetUnitName(const AName: string; out AUnitName: string): Boolean;
property Names: TArray<string> read GetNames;
class property Instance: TEMSEdgeListenerFactories read FInstance;
end;
implementation
{ TEMSEdgeListenerFactories }
procedure TEMSEdgeListenerFactories.Add(const AProtocolName, AUnitName: string;
const AFactory: TEMSEdgeListenerFactory);
begin
FItems.Add(AProtocolName, AFactory);
FUnitNames.Add(AProtocolName, AUnitName);
end;
constructor TEMSEdgeListenerFactories.Create;
begin
FUnitNames := TDictionary<string, string>.Create;
FItems := TObjectDictionary<string, TEMSEdgeListenerFactory>.Create([doOwnsValues]);
end;
destructor TEMSEdgeListenerFactories.Destroy;
begin
FItems.Free;
FUnitNames.Free;
inherited;
end;
function TEMSEdgeListenerFactories.GetNames: TArray<string>;
begin
Result := FItems.Keys.ToArray;
end;
procedure TEMSEdgeListenerFactories.Remove(const AName: string);
begin
FItems.Remove(AName);
FUnitNames.Remove(AName);
end;
function TEMSEdgeListenerFactories.TryGetFactory(const AName: string;
out AFactory: TEMSEdgeListenerFactory): Boolean;
begin
Result := FItems.TryGetValue(AName, AFactory);
end;
function TEMSEdgeListenerFactories.TryGetUnitName(const AName: string;
out AUnitName: string): Boolean;
begin
Result := FUnitNames.TryGetValue(AName, AUnitName);
end;
{ TEMSEdgeListenerFactory }
function TEMSEdgeListenerFactory.CreateListener(const AOwner: TComponent;
const AProtocolName: string): TEMSEdgeListener;
begin
Result := DoCreateListener(AOwner, AProtocolName);
end;
initialization
TEMSEdgeListenerFactories.FInstance := TEMSEdgeListenerFactories.Create;
finalization
FreeAndNil(TEMSEdgeListenerFactories.FInstance);
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ Copyright(c) 2012-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit VisualizationServicesAPI;
interface
uses
System.SysUtils, System.Classes, System.Generics.Collections, Winapi.Windows,
DesignIntf, ToolsAPI, Vcl.Graphics;
type
TVGPropertyNames = class
const
ModelSettingsSection = 'Module Settings';
ActiveLayerNames = 'ActiveLayerNames';
EditingLayerName = 'EditingLayerName';
ModelLayerNames = 'ModelLayerNames';
Unknown = 'Unknown';
Name = 'Name';
DisplayName = 'DisplayName';
Kind = 'Kind';
LinkDir = 'LinkDir';
Coordinates = 'Coordinates';
MetaData = 'Metadata';
BgColor ='BackgroundColor';
FgColor = 'ForegroundColor';
FooterColor = 'FooterColor';
ExplicitSubNodes = 'ExplicitSubNodes';
NodeLayerNames = 'LayerNames';
Visible = 'Visible';
end;
TVGMenuContext = class
const
Unknown = 'UnknownContext';
RightClick = 'RightClickContext';
CreateLink = 'CreateLinkContext';
end;
TVGDirection = (vdUnknown, vdRightToLeft, vdLeftToRight, vdBidirectional);
TVGElementKind = (vkUnknown, vkNode, vkSubNode, vkLink);
TVGRouteValue = (vrRouteAllowed, vrRouteDisallowed, vrRouteOptions);
TVGRouteIDValuePair = TPair<Integer, TVGRouteValue>;
TVGPersistentIDPair = TPair<TPersistent, Integer>;
IVGModel = Interface;
IVGElement = Interface
['{4813A017-C549-4CC1-997A-BC995A39A046}']
function ToStr: string;
function GetModel: IVGModel;
property Model: IVGModel read GetModel;
function GetDisplayName: string;
function GetLayerNames: TArray<string>;
procedure SetLayerNames(ANames: TArray<string>);
procedure RemoveLayerName(const AName: string);
procedure AddLayerName(const AName: string);
function GetName: string;
function GetId: Integer;
function GetComponent: TComponent;
function GetKind: TVGElementKind;
property DisplayName: string read GetDisplayName;
property LayerNames: TArray<string> read GetLayerNames write SetLayerNames;
property Name: string read GetName;
property Id: Integer read GetId;
property Kind: TVGElementKind read GetKind;
property Component: TComponent read GetComponent;
function IsLink: Boolean;
function IsNode: Boolean;
function IsSubNode: Boolean;
function IsCaption: Boolean;
function IsElementKind(const AKind: TVGElementKind): Boolean;
function IsExternal: Boolean;
End;
IVGLink = Interface(IVGElement)
['{F08902EA-CED2-4F41-AE32-ED6803A90C56}']
function GetLeftNodeId: Integer;
function GetLeftSubNodeId: Integer;
function GetRightNodeId: Integer;
function GetRightSubNodeId: Integer;
property LeftNodeId: Integer read GetLeftNodeId;
property LeftSubNodeId: Integer read GetLeftSubNodeId;
property RightNodeId: Integer read GetRightNodeId;
property RightSubNodeId: Integer read GetRightSubNodeId;
function Direction: TVGDirection;
End;
IVGSubNode = Interface(IVGElement)
['{E014B935-3D98-4B6A-8DCA-74A35E331747}']
function GetPersistent: TPersistent;
function GetProperty: string;
property PropertyName: string read GetProperty;
property Persistent: TPersistent read GetPersistent;
End;
IVGCaption = Interface(IVGElement)
['{99E30750-6366-4824-9D75-FF308EF7EACE}']
function GetEmbedded: TComponent;
property Embedded: TComponent read GetEmbedded;
End;
IVGNode = Interface(IVGElement)
['{602A8704-B020-40C8-B689-2F1E2F64CA44}']
procedure SetDisplayName(const AName: string);
procedure SetName(const AName: string);
End;
IVGElementEnumerator = interface
['{FB21362B-BDFA-4297-A0A3-EF3A2F501FF3}']
procedure First;
function GetCurrent: IVGElement;
function MoveNext: Boolean;
property Current: IVGElement read GetCurrent;
end;
IVGMenuItem = Interface
['{F3ACC26B-C4F1-4656-B3CA-A968D68A033D}']
function CategoryName: string;
function CaptionName: string;
function ShortcutKey: string;
function Enabled: Boolean;
procedure Execute;
End;
IVGShortcutItem = Interface
['{760738D6-9108-4A43-B0A5-E17F84A30158}']
function GetImageIndex: Integer;
function GetHint: string;
function GetEnabled: Boolean;
procedure Execute;
End;
IVGModule = Interface;
IVGModel210 = Interface
['{7527CE30-FAC1-4D52-8153-7717F8A30BAE}']
// Returns a string representiaton of the current cached model
function ToStr: string;
function GetModule: IVGModule;
function GetShortcuts: TArray<IVGShortcutItem>;
function ElementCount: Integer;
function GetElementIDs: TArray<Integer>;
function GetComponents: TArray<TComponent>;
function GetNodeCount: Integer;
function GetNodeID(const AIndex: Integer): Integer;
function GetSubNodeParentID(const ASubNodeID: Integer): Integer;
function GetSubNodeCount(const ANodeID: Integer): Integer;
function GetSubNodeID(const ANodeID: Integer; const AIndex: Integer): Integer;
function GetEmbeddedID(const ANodeID: Integer): TArray<Integer>;
function GetLinkCount: Integer;
function GetLinkID(const AIndex: Integer): Integer;
function GetLinkSourceID(const ALinkID: Integer): Integer;
function GetLinkDestinationID(const ALinkID: Integer): Integer;
function GetProperty(const AElementID: Integer; const AProperty: string): string;
procedure SetProperty(const AElementId: Integer; const AProperty: string; const APropertyValue: string);
function FindElement(const AElementID: Integer): IVGElement;
//Ids for all Node, SubNode, or Link elements
function FindElementIds(const AComponent: TComponent): TArray<Integer>; overload;
//Links components may have multiple links with unique IDs
function FindLinkIds(const AComponent: TComponent): TArray<Integer>;
function FindNodeId(const AComponent: TComponent): Integer; overload;
function FindNodeId(const ADisplayName: string): Integer; overload;
function FindSubNodeId(const ANode: TComponent; const ASubNodeName: string): Integer; overload;
function FindSubNodeId(const APersistent: TPersistent): Integer; overload;
function FindPersistent(AComponent: TComponent; APersistent: TArray<TPersistent>): TArray<TVGPersistentIDPair>; overload;
function FindPersistent(APersistent: TArray<TPersistent>): TArray<TVGPersistentIDPair>; overload;
function IsSubNodeMember(const ANode: TComponent; const ASubNodeName: string): Integer;
function IsLinkType(const AComponent: TComponent): Boolean;
function CanAddLink(const ASrcID, ADestID: Integer): TVGRouteValue;
function CanAddLinks(const ASrcID: Integer; ADestIDs: TArray<Integer>): TArray<TVGRouteIDValuePair>;
function CanRerouteLink(const ALinkID, AFromElementID, AToElementID: Integer): TVGRouteValue;
procedure RerouteLink(const ALinkID, AFromElementID, AToElementID: Integer);
procedure AddLink(const ASrcID, ADestID: Integer);
function IsLinked(const ANode: TComponent): Boolean; overload;
function IsLinked(const ANode: TComponent; const ASubNodeName: string): Boolean; overload;
function GetLinks(const ANode: TComponent): TArray<Integer>; overload;
function GetLinks(const ANode: TComponent; const ASubNodeName: string): TArray<Integer>; overload;
function IsElementVisible(AElementID: Integer): Boolean;
function IsDefaultVisible(AElementID: Integer): Boolean;
procedure ShowElement(const AElementID: Integer; APersist: Boolean);
procedure HideElement(const AElementID: Integer; APersist: Boolean);
procedure RestoreDefaultVisibility(const AElementID: Integer);
procedure AddLayerName(const AName: string);
procedure RemoveLayerName(const AName: string);
function GetLayerNames: TArray<string>;
procedure SetActiveLayerNames(ANames: TArray<string>);
function GetActiveLayerNames: TArray<string>;
procedure SetEditingLayerName(const AName: string);
function GetEditingLayerName: string;
procedure FooterClicked(const ANodeID: Integer);
procedure SelectBindableDestination(const ASourceSubNodeId, ADestinationNodeId: Integer);
function GetMenuItems(const AParentOrigin: TPoint; const AMenuContext: string; const AContextIDs: TArray<Integer>): TArray<IVGMenuItem>;
// Check whether the cached model is out of sync with its module designer
//function NeedsReload: Boolean;
// Check if the model contains changes in its delta for updating the drawing
function IsModified: Boolean;
procedure Loaded;
procedure Prepare;
function GetAddedCount: Integer;
function GetAddedElementID(const AIndex: Integer): Integer;
function GetRemovedCount: Integer;
function GetRemovedElementID(const AIndex: Integer): Integer;
function GetChangedCount: Integer;
function GetChangedElementID(const AIndex: Integer): Integer;
procedure AddElement(const AComponent: TComponent);
procedure RemoveElement(const AComponent: TComponent);
procedure ElementChanged(const AComponent: TComponent); overload;
procedure ElementChanged(const AElementId: Integer); overload;
procedure ElementAdded(const AElement: IVGElement);
procedure ElementRemoved(const AElementId: Integer);
procedure ColorChanged(const AElementId: Integer);
procedure ElementsSelected(AElemIds: TArray<Integer>);
procedure SelectElements(AElemIds: TArray<Integer>);
procedure ElementHovered(const AElementId: Integer);
procedure InitNewLink(AElementId: Integer; SelectForBinding: Boolean);
procedure InitRerouteLink(const ALinkId, ASrcId, ADestId: Integer);
function SelectedElements: TArray<Integer>;
procedure AddSubNode(const ANode: TComponent; const ASubNodeName: string; const APersistent: TPersistent; const IsPersisted: Boolean);
procedure RemoveSubNode(const ANode: TComponent; const ASubNodeName: string);
End;
IVGModel = Interface(IVGModel210)
['{14E1FBF7-442E-4DD7-B3CC-7CFA59B935D6}']
function IsElementSelected(AElementID: Integer): Boolean;
End;
IVGDataAdmin = Interface
['{EF2B1AE6-9592-41A3-B605-D549262FA4A9}']
function GetConfigData: TStrings;
procedure SetConfigData(const AData: TStrings);
function GetFileName: string;
function UpdateProperty(const ASectionName: string; const AProperty: string; APropertyValue: string): Boolean;
function GetProperty(const ASectionName, AProperty, ADefault: string): string;
procedure ClearProperty(const ASectionName: string; const AProperty: string);
procedure RenameSection(const AOldSectionName, ANewSectionName: string);
procedure SaveChanges;
property FileName: string read GetFileName;
property ConfigData: TStrings read GetConfigData write SetConfigData;
End;
// Every module (with a designer) opened will need one of these
// each module will probably have one IVGModel
IVGModule190 = Interface
['{4634A103-2379-46DD-9ACA-6C2B4BDD4848}']
function Designer: IDesigner;
function HasDesigner: Boolean;
procedure ModuleModified;
procedure ModuleSaved;
procedure ModuleBeforeRename(const AOldName, ANewName: string);
procedure ModuleBeforeSave;
procedure ModuleRenamed(const ANewName: string);
procedure DesignerActivated;
procedure DesignerClosed;
function HasComponent(const AModel: IVGModel; const AComponent: TComponent): Boolean;
procedure ComponentRenamed(const AComponent: TComponent; const ANewName: string);
procedure ComponentChanged(const AComponent: TComponent);
procedure ComponentAdded(const AComponent: TComponent);
procedure ComponentRemoved(const AComponent: TComponent);
procedure ComponentsSelected(AComponents: TArray<TPersistent>);
procedure ExternalComponentChanged(const AComponent: TComponent);
procedure ExternalComponentRenamed(const AComponent: TComponent; const ANewName: string);
procedure ExternalComponentAdded(const AComponent: TComponent);
procedure ExternalComponentRemoved(const AComponent: TComponent);
function GetProperty(const AName: string; const AProperty: string; const ADefault: string): string;
procedure SetProperty(const AName: string; const AProperty: string; const APropertyValue: string);
procedure ClearProperty(const AName: string; const AProperty: string);
// To be called before model is about to be updated/loaded/refreshed
procedure Prepare;
// To be called after model is updated/loaded/refreshed
procedure Loaded;
function GetAddedCount: Integer;
function GetAddedElementID(const AIndex: Integer): Integer;
function GetRemovedCount: Integer;
function GetRemovedElementID(const AIndex: Integer): Integer;
function GetChangedCount: Integer;
function GetChangedElementID(const AIndex: Integer): Integer;
function IsModified: Boolean;
function GetModel: IVGModel;
function LockSelection: Boolean;
procedure UnlockSelection;
function GetDataAdmin: IVGDataAdmin;
// This reloads the module in its current state
procedure Reload;
// This instantiates a new model based on the current module
function MakeModel: IVGModel;
function GetPairedId(const AObject: TObject): Integer; overload;
function GetPairedId(const AComponent: TComponent; const AMember: string): Integer; overload;
function FindPairedSubNode(const AElementId: Integer): TPair<TObject,string>;
End;
IVGModule = Interface(IVGModule190)
['{829CF722-6B2E-4812-B43D-9269999035D5}']
function LockDesignerSelection: Boolean;
procedure UnlockDesignerSelection;
End;
// The handler specifies graph specific details like file extension and
// creates a IVGModule for every unit
IVGHandler = Interface
['{7F7F3B6A-57DF-4E56-8ECF-AB6993E5AE11}']
function GetGraphIdentifier: string;
function GetGraphFileExtension: string;
function AddModule(const ADesigner: IDesigner; const ASourceModule: IOTAModule): IVGModule;
function GetModule(const ADesigner: IDesigner): IVGModule;
procedure RemoveModule(const ADesigner: IDesigner);
function GetModules: TArray<IVGModule>;
function GetCurrentModule: IVGModule;
procedure SetCurrentModule(const AModule: IVGModule);
property CurrentModule: IVGModule read GetCurrentModule write SetCurrentModule;
End;
IVGDrawing = Interface
['{95F5ABCC-5920-4E7C-9B92-7A716ED0D352}']
procedure LayoutNodes;
procedure RecolorModel(AElements: TArray<Integer>);
procedure UpdateDrawing;
function GetActiveLayers: TArray<string>;
procedure SetEditLayer(const ALayerName: string);
function GetEditLayer: string;
property EditLayer: string read GetEditLayer write SetEditLayer;
function AddNewLayer: string;
procedure ActivateLayer(const ALayerName: string);
procedure DeactivateLayer(const ALayerName: string);
procedure RefreshLayers;
function GetActiveDesigner: string;
procedure SetActiveDesigner(const ALayerName: string);
procedure HideElement(const AElementId: Integer);
procedure ShowElement(const AElementId: Integer);
procedure ScrollToElement(const AElementId: Integer);
function AddImage(const ABitmap: TBitmap): Integer;
procedure InitNewLink(const ASrcId: Integer);
// used to determine or change active views of the drawing if any (blank is default)
property ActiveLayers: TArray<string> read GetActiveLayers;
property ActiveDesigner: string read GetActiveDesigner write SetActiveDesigner;
End;
IVisualizationService = Interface
['{66C2DF99-87FD-41D9-9894-21D14D256F7A}']
procedure DeleteGroup(const AGroupNum: Integer);
procedure RegisterDrawingControl(const ADrawing: IInterface);
procedure UnregisterDrawingControl(const ADrawing: IInterface);
function GetDrawingControl: IVGDrawing;
procedure FocusDrawing;
// for supporting custom graph plugins like LiveBindings graph
procedure RegisterGraphHandler(const AGraphHandler: IVGHandler);
procedure UnregisterGraphHandler(const AGraphHandler: IVGHandler);
function ActiveGraph: IVGHandler;
procedure ActivateGraph(const AGraphHandlerId: string);
procedure ClearActiveGraph;
function GetGraphIds: TArray<string>;
// for graph plugins to call when they would like to activate a new
// model for drawing. for example, on form activation, this can be
// pushed for the current form. otherwise, it can be done on other
// scenarios as needed
procedure ActivateModule(const AModule: IVGModule);
// used to retrieve active model showing if any
function ActiveModel: IVGModel;
function VGDirToLBDir(const ALinkDir: TVGDirection): string;
function VGElementKindToLBPropertyValue(const AElementKind: TVGElementKind): string;
function GetActive: Boolean;
procedure SetActive(AValue: Boolean);
property Active: Boolean read GetActive write SetActive;
End;
function VisualizationService: IVisualizationService;
implementation
function VisualizationService: IVisualizationService;
begin
Supports(BorlandIDEServices, IVisualizationService, Result);
end;
end.
|
unit uQTZHelper;
interface
uses
SysUtils, Classes, Generics.Collections, IdHttp, IdURI, uGlobal, JSON;
type
TQTZHelper = class
private
class function HttpGet(url: string): string;
class function DecodeJSON<T>(jsonStr: string): T; static;
public
class function GetVehInfo(hphm, hpzl: string): string; static;
class function GetAlarmList(pageIndex, pageSize: integer): TList<TAlarm>; static;
class var QTZUrl: string;
end;
const
token = '9CC0E31FD9F648519AC79239B018F1A6';
implementation
{ TQTZHelper }
class function TQTZHelper.HttpGet(url: string): string;
var
http: TIdHttp;
begin
result := '';
http := TIdHttp.Create(nil);
http.Request.UserAgent := 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
try
result := http.Get(url);
except
on e: exception do
begin
logger.Error('[TQTZHelper.HttpGet]' + e.Message + url.Substring(0, 50));
end;
end;
http.Free;
end;
class function TQTZHelper.DecodeJSON<T>(jsonStr: string): T;
begin
end;
class function TQTZHelper.GetAlarmList(pageIndex, pageSize: integer): TList<TAlarm>;
var
s, a: string;
body: TJSONArray;
json, head, code, veh: TJSONValue;
alarm: TAlarm;
begin
result := TList<TAlarm>.Create;
if QTZUrl = '' then exit;
s := QTZUrl + 'GetAlarmVehicle?token='+token+'&pagesize='+pageSize.ToString+'¤tpage=' + pageIndex.ToString;
s := HttpGet(s);
if s = '' then
exit;
try
json := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(s), 0);
head := json.GetValue<TJSONValue>('head');
code := head.GetValue<TJSONValue>('code');
if code.Value = '1' then
begin
body := json.GetValue<TJSONArray>('body');
for veh in body do
begin
alarm.HPHM := veh.GetValue<TJSONValue>('hphm').Value;
alarm.HPZL := veh.GetValue<TJSONValue>('hpzl').Value;
alarm.BKLX := veh.GetValue<TJSONValue>('bklx').Value;
result.Add(alarm);
end;
end;
json.Free;
except
on e: exception do
begin
logger.Error('TQTZHelper.GetAlarmList' + e.Message);
end;
end;
end;
class function TQTZHelper.GetVehInfo(hphm, hpzl: string): string;
var
s: string;
begin
result := '';
if QTZUrl = '' then exit;
s := QTZUrl + 'GetVehInfo?token='+token+'&hphm=' + hphm + '&hpzl=' + hpzl;
s := TIdURI.URLDecode(s);
result := HttpGet(s);
end;
end.
|
unit ai;
interface
uses engine;
function generateMove(gameBoard : boardElements; isFirstMoving: boolean;
currentArmy : army) : order;
implementation
{ zwraca minimum z dwóch wartości }
function min(x:Integer; y: Integer): Integer;
begin
if x < y then min := x else min := y;
end;
function generateMove(gameBoard : boardElements; isFirstMoving: boolean;
currentArmy : army) : order;
{ sprawdza, jakie jednostki są w zasięgu strzału i generuje rozkaz strzału
do tej, której może zabrać najwięcej punktów życia }
var
newOrder : order;
chosenEnemy : army = nil;
candidate : army = nil;
health1, health2, damage1, damage2 : Integer; { zmienne pomocnicze }
begin
new(newOrder);
if isFirstMoving then
candidate := gameBoard^.secondArmies
else
candidate := gameBoard^.firstArmies;
while candidate <> nil do begin
if chosenEnemy <> nil then begin
health1 := chosenEnemy^.health;
damage1 := computeDamage(currentArmy, chosenEnemy);
end else begin
health1 := 0;
damage1 := 0;
end;
health2 := candidate^.health;
damage2 := computeDamage(currentArmy, candidate);
{ jeśli można tej jednostce zadać więcej obrażeń, niż aktualnemu "zwycięzcy"
i ta jednoska jest w zasięgu }
if (min(health1, damage1) < min(health2, damage2)) and
canAttackArmy(currentArmy, candidate) then
{ zmień zwycięzcę }
chosenEnemy := candidate;
candidate := candidate^.nextArmy;
end;
{ nie ma w zasięgu jednostki, której można zadać obrażenia }
if chosenEnemy = nil then
newOrder^.kind := SKIP
else begin
newOrder^.armyToAttack := chosenEnemy;
newOrder^.destPos := chosenEnemy^.pos;
newOrder^.kind := ATTACK;
end;
generateMove := newOrder;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
{/*
* mirror.c - This program demonstrate a mirror reflection.
* (An obedient version :)
*
* Takehiko Terada (terada@sgi.co.jp)
* 1997/09/09
* 1997/09/17 ver 0.2 some bug fix(add scalef(-1))
* (Thanks to Ishikawa-san@CSK)
* 1997/09/17 ver 0.3 fix the lookat bug
* 1997/10/17 ver 0.4 fix the front-back face bug
* (Thanks to Yamaho-san@Hitachi)
*/}
unit frmMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC : HDC;
hrc : HGLRC;
procedure InitializeRC;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
Angle : GLfloat = 0;
time : LongInt;
implementation
uses DGLUT;
{$R *.DFM}
{=======================================================================
Процедура инициализации источника цвета}
procedure TfrmGL.InitializeRC;
const
mat_specular : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 1.0);
light_position : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 0.0);
mat_shininess = 50.0;
begin
glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular);
glMaterialf (GL_FRONT, GL_SHININESS, mat_shininess);
glLightfv(GL_LIGHT0, GL_POSITION, @light_position);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
end;
{=======================================================================
Отрисовка картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
a, b : GLfloat;
begin
BeginPaint(Handle, ps);
{/*
* Normal view
*/}
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(45.0, ClientWidth / ClientHeight, 0.1, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
gluLookAt(0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glRotatef(Angle, 0.0, 1.0, 0.0);
glCallList(1);
glPopMatrix;
{/*
* Mirror view
*/}
glDisable(GL_LIGHTING);
glViewport(ClientWidth shr 2, ClientHeight-(ClientHeight shr 2), ClientWidth shr 1, ClientHeight shr 3);
glEnable(GL_SCISSOR_TEST);
glScissor(ClientWidth shr 2, ClientHeight-(ClientHeight shr 2), ClientWidth shr 1, ClientHeight shr 3);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
//* Why 1.001 ? Just a tips, don't mind. :-) */
glOrtho(-1.001, 1.001, -1.001, 1.001, -1.001, 1.001);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex3i(-1, 1, 1);
glVertex3i( 1, 1, 1);
glVertex3i( 1,-1, 1);
glVertex3i(-1,-1, 1);
glEnd;
glLoadIdentity;
a := (ClientWidth shr 1) / (ClientHeight shr 3);
b := (ClientHeight shr 3)/ (ClientWidth shr 1);
gluPerspective(45.0*b, a, 0.1, 100.0);
//* You can change these parameters if you want a real result. */
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
gluLookAt( 0.0, 0.0,-1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glEnable(GL_LIGHTING);
glScalef(-1.0, 1.0, 1.0);
glFrontFace(GL_CW);
glPushMatrix;
glRotatef(Angle, 0.0, 1.0, 0.0);
glCallList(1);
glPopMatrix;
glFrontFace(GL_CCW);
glDisable(GL_SCISSOR_TEST);
SwapBuffers(DC);
EndPaint(Handle, ps);
Angle := Angle + 0.25 * (GetTickCount - time) * 360 / 1000;
If Angle >= 360.0 then Angle := 0.0;
time := GetTickCount;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
InitializeRC;
glNewList(2, GL_COMPILE);
glutSolidCube(1.0);
glEndList;
glNewList(1, GL_COMPILE);
glPushMatrix;
glTranslatef(3.0, 0.0, 0.0);
glColor3f(0.0, 1.0, 0.0);
glCallList(2);
glPopMatrix;
glPushMatrix;
glTranslatef(-3.0, 0.0, 0.0);
glColor3f(1.0, 0.0, 0.0);
glCallList(2);
glPopMatrix;
glPushMatrix;
glTranslatef(0.0, 0.0, 3.0);
glColor3f(0.0, 0.0, 1.0);
glCallList(2);
glPopMatrix;
glPushMatrix;
glTranslatef(0.0, 0.0,-3.0);
glColor3f(1.0, 1.0, 1.0);
glCallList(2);
glPopMatrix;
glEndList;
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_CULL_FACE);
time := GetTickCount;
end;
{=======================================================================
Установка формата пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
glDeleteLists (1, 2);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close
end;
end.
|
unit SettingsUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons;
type
TSettingsForm = class(TForm)
FontNameCombo: TComboBox;
OkSettingsButton: TButton;
FontLabel: TLabel;
TimesLabel: TLabel;
OriginLabel: TLabel;
FontSizeLabel: TLabel;
PixelsPerQuadrantLabel: TLabel;
FontSizeEdit: TEdit;
PixelsPerQuadrantEdit: TEdit;
PixelsPerQuadrantFakeEdit: TEdit;
CenterRadio: TRadioButton;
TopLeftRadio: TRadioButton;
RealSizeCheckBox: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure PixelsPerQuadrantEditChange(Sender: TObject);
procedure AllowOnlyNumbersKeyPress(Sender: TObject; var Key: Char);
procedure OkSettingsButtonClick(Sender: TObject);
procedure RealSizeCheckBoxClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
SettingsForm: TSettingsForm;
implementation
{$R *.dfm}
uses MainUnit;
procedure TSettingsForm.FormCreate(Sender: TObject);
begin
FontNameCombo.Items.AddStrings(Screen.Fonts);
FontSizeEdit.Text := IntToStr(MainForm.CodeEditor.Font.Size);
FontNameCombo.ItemIndex := FontNameCombo.Items.IndexOf(MainForm.CodeEditor.Font.Name);
end;
procedure TSettingsForm.FormShow(Sender: TObject);
begin
OkSettingsButton.SetFocus;
end;
procedure TSettingsForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Ord(Key) = VK_RETURN then
begin
Key := #0; // prevent beeping
OkSettingsButton.Click;
end;
end;
procedure TSettingsForm.PixelsPerQuadrantEditChange(Sender: TObject);
begin
PixelsPerQuadrantFakeEdit.Text := PixelsPerQuadrantEdit.Text;
end;
procedure TSettingsForm.RealSizeCheckBoxClick(Sender: TObject);
begin
PixelsPerQuadrantEdit.Enabled := not RealSizeCheckBox.Checked;
end;
procedure TSettingsForm.AllowOnlyNumbersKeyPress(Sender: TObject; var Key: Char);
begin
if Ord(Key) <> VK_BACK then
if not ((Key >= '0') and (Key <= '9')) then
begin
Beep;
Key := #0;
end;
end;
procedure TSettingsForm.OkSettingsButtonClick(Sender: TObject);
var
PixelsPerQuadrantSide: Integer;
begin
MainForm.SetRealSize(RealSizeCheckBox.Checked);
MainForm.SetCenterOrigin(CenterRadio.Checked);
if PixelsPerQuadrantEdit.Text <> '' then
begin
PixelsPerQuadrantSide := StrToInt(PixelsPerQuadrantEdit.Text);
if MainForm.FPixelsPerQuadrantSide <> PixelsPerQuadrantSide then
MainForm.ResizeGrid(PixelsPerQuadrantSide);
end;
if FontSizeEdit.Text <> '' then
MainForm.CodeEditor.Font.Size := StrToInt(FontSizeEdit.Text);
if FontNameCombo.Text <> '' then
MainForm.CodeEditor.Font.Name := FontNameCombo.Text;
Close;
end;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program LCS2X;
Uses Math;
Const
maxNM =1500;
Var
n,m,res,t :SmallInt;
A,B :Array[1..maxNM] of LongInt;
D :Array[0..maxNM] of SmallInt;
procedure Enter;
var
i :LongInt;
begin
Read(n,m);
for i:=1 to n do Read(A[i]);
for i:=1 to m do Read(B[i]);
end;
procedure Optimize;
var
i,j :LongInt;
count,tmp :SmallInt;
begin
res:=0;
for i:=0 to m do D[i]:=0;
for i:=1 to n do
begin
count:=0; tmp:=0;
for j:=1 to m do
begin
if (A[i]=B[j]) then count:=tmp+1;
if (A[i]>=2*B[j]) then tmp:=Max(tmp,D[j]);
if (A[i]=B[j]) then
begin
res:=Max(res,count);
D[j]:=Max(D[j],count);
end;
end;
end;
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Read(t);
repeat
Dec(t);
Enter;
Optimize;
WriteLn(res);
until (t=0);
Close(Input); Close(Output);
End. |
unit amqp.privt;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses AMQP.Types;
type
Tbint = record
case integer of
0: (i: uint32_t);
1: (c: array[0..3] of Byte);
end;
function is_bigendian: bool;
function amqp_offset(data: PByte; offset : size_t): PByte;
function amqp_rpc_reply_error( status : Tamqp_status_enum):Tamqp_rpc_reply;
procedure amqp_e8(Aval : uint8_t; Adata: Pointer);
procedure amqp_e16(Aval : uint16_t;Adata: Pointer);
procedure amqp_e32(val : uint32_t;data: Pointer);
procedure amqp_e64(val : uint64_t; data: Pointer);
function amqp_encode_n(bits: Byte; encoded : Tamqp_bytes;offset : Psize_t; input : uint64_t):integer;
function amqp_encode_bytes(encoded : Tamqp_bytes;offset : Psize_t; input : Tamqp_bytes):integer;
function amqp_d8(data: Pointer):uint8_t;
function amqp_d16(data: Pointer):uint16_t;
function amqp_d32(data: Pointer):uint32_t;
function amqp_d64(data: Pointer):uint64_t;
function amqp_decode_8(encoded: Tamqp_bytes; offset: Psize_t; out output: uint8_t): int;
function amqp_decode_16(encoded: Tamqp_bytes; offset: Psize_t; out output: uint16_t): int;
function amqp_decode_32(encoded: Tamqp_bytes; offset: Psize_t; out output: uint32_t): int;
function amqp_decode_64(encoded: Tamqp_bytes; offset: Psize_t; out output: uint64_t): int;
function amqp_decode_bytes(encoded : Tamqp_bytes;offset : Psize_t; out output : Tamqp_bytes; len : size_t):integer;
implementation
function amqp_offset(data: PByte; offset : size_t): PByte;
begin
Inc(data , offset);
Result := data;
end;
function amqp_rpc_reply_error( status : Tamqp_status_enum):Tamqp_rpc_reply;
var
reply : Tamqp_rpc_reply;
begin
reply.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
reply.library_error := Int(status);
Result := reply;
end;
function amqp_decode_bytes(encoded : Tamqp_bytes;offset : Psize_t; out output : Tamqp_bytes; len : size_t):integer;
var
o : size_t;
begin
o := offset^;
offset^ := o + len;
if offset^ <= encoded.len then
begin
output.bytes := amqp_offset(encoded.bytes, o);
output.len := len;
Exit(1);
end
else
Exit(0);
end;
function amqp_d32(data: Pointer):uint32_t;
var
val : uint32_t;
begin
memcpy(@val, data, sizeof(val));
if not is_bigendian then
begin
val := ((val and $FF000000) shr 24) or ((val and $00FF0000) shr 8) or
((val and $0000FF00) shl 8) or ((val and $000000FF) shl 24);
end;
Result := val;
end;
procedure amqp_e64(val : uint64; data: Pointer);
begin
if not is_bigendian then
begin
val := ((val and 18374686479671623680) shr 56) or
((val and 71776119061217280) shr 40) or
((val and 280375465082880) shr 24) or
((val and 1095216660480) shr 8 ) or
((val and 4278190080) shl 8 ) or
((val and 16711680) shl 24) or
((val and 65280) shl 40) or
((val and 255) shl 56);
end;
memcpy(data, @val, sizeof(val));
end;
function amqp_d64(data: Pointer):uint64_t;
var
val : uint64_t;
begin
memcpy(@val, data, sizeof(val));
if not is_bigendian then
begin
val := ((val and 18374686479671623680) shr 56) or
((val and 71776119061217280) shr 40) or
((val and 280375465082880) shr 24) or
((val and 1095216660480) shr 8 ) or
((val and 4278190080) shl 8 ) or
((val and 16711680) shl 24) or
((val and 65280) shl 40) or
((val and 255) shl 56);
end;
Result := val;
end;
function amqp_d16(data: Pointer):uint16_t;
var
val : uint16_t;
begin
memcpy(@val, data, sizeof(val));
if not is_bigendian then
val := ((val and $FF00) shr 8) or ((val and $00FF) shl 8);
Result := val;
end;
function amqp_d8(data: Pointer):uint8_t;
var
val : uint8_t;
begin
memcpy(@val, data, sizeof(val));
Result := val;
end;
function amqp_encode_bytes(encoded : Tamqp_bytes;offset : Psize_t; input : Tamqp_bytes):integer;
var
o : size_t;
begin
o := offset^;
{ The memcpy below has undefined behavior if the input is nil. It is valid
* for a 0-length amqp_bytes_t to have .bytes = nil. Thus we should check
* before encoding.
}
if input.len = 0 then
Exit(1);
offset^ := o + input.len;
if offset^ <= encoded.len then
begin
memcpy(amqp_offset(encoded.bytes, o), input.bytes, input.len);
Exit(1);
end
else
Exit(0);
end;
function amqp_decode_8(encoded: Tamqp_bytes; offset: Psize_t; out output: uint8_t): int;
var
o : size_t;
begin
o := offset^;
offset^ := o + 1;//Round(8 / 8);
if offset^ <= encoded.len then
begin
output := amqp_d8(amqp_offset(encoded.bytes, o));
Exit(1);
end;
Result := 0;
end;
function amqp_decode_16(encoded: Tamqp_bytes; offset: Psize_t; out output: uint16_t): int;
var
o : size_t;
begin
o := offset^;
offset^ := o + 2;//Round(16 / 8);
if offset^ <= encoded.len then
begin
output := amqp_d16(amqp_offset(encoded.bytes, o));
Exit(1);
end;
Result := 0;
end;
function amqp_decode_32(encoded: Tamqp_bytes; offset: Psize_t; out output: uint32_t): int;
var
o : size_t;
begin
o := offset^;
offset^ := o + 32 DIV 8;
if offset^ <= encoded.len then
begin
output := amqp_d32(amqp_offset(encoded.bytes, o));
Exit(1);
end;
Result := 0;
end;
function amqp_decode_64(encoded: Tamqp_bytes; offset: Psize_t; out output: uint64_t): int;
var
o : size_t;
begin
o := offset^;
offset^ := o + 8;//Round(64 / 8);
if offset^ <= encoded.len then
begin
output := amqp_d64(amqp_offset(encoded.bytes, o));
Exit(1);
end;
Result := 0;
end;
function amqp_encode_n(bits: Byte; encoded : Tamqp_bytes;offset : Psize_t; input : uint64_t):integer;
var
o : size_t;
begin
o := offset^;
offset^ := o + bits div 8;
if offset^ <= encoded.len then
begin
case bits of
8:
amqp_e8(input, amqp_offset(encoded.bytes, o));
16:
amqp_e16(input, amqp_offset(encoded.bytes, o));
32:
amqp_e32(input, amqp_offset(encoded.bytes, o));
64:
amqp_e64(input, amqp_offset(encoded.bytes, o));
end;
Exit( 1);
end;
Exit( 0);
end;
procedure amqp_e8(Aval : uint8_t; Adata: Pointer);
begin
memcpy(Adata, @Aval, sizeof(Aval));
end;
procedure amqp_e16(Aval : uint16;Adata: Pointer);
begin
if not is_bigendian() then
begin
Aval := ((Aval and uint32_t($FF00)) shr uint32_t(8)) or ((Aval and uint32_t($00FF)) shl uint32_t(8));
end;
memcpy(Adata, @Aval, sizeof(Aval));
end;
procedure amqp_e32(val : uint32;data: Pointer);
begin
if not is_bigendian then
begin
val := ((val and UInt32($FF000000)) shr UInt32(24)) or ((val and UInt32($00FF0000)) shr UInt32(8)) or
((val and UInt32($0000FF00)) shl UInt32(8)) or ((val and UInt32($000000FF)) shl UInt32(24));
end;
memcpy(data, @val, sizeof(val));
end;
function is_bigendian: bool;
var
bint: Tbint;
begin
bint.i := $01020304;
Result := Ord(bint.c[0]) = 1;
end;
initialization
end.
|
unit oci_unit;
interface
uses
sysutils, windows;
const
OCI_HTYPE_ENV = 1; // environment handle
OCI_HTYPE_ERROR = 2; // error handle
OCI_SUCCESS = 0; // maps to SQL_SUCCESS of SAG CLI
OCI_ERROR = -1; // maps to SQL_ERROR
OCI_SUCCESS_WITH_INFO = 1; // maps to SQL_SUCCESS_WITH_INFO
OCI_DEFAULT = $00; // the default value for parameters and attributes
OCI_OBJECT = $02; // the application is in object environment
OCI_NUMBER_SIZE = 22;
dllOK = 0;
dllNoFile = 1; // No dll file found
type
sb4 = LongInt;
ub4 = LongInt;
sword = Integer;
uword = Integer;
ub1 = Byte;
OCINumber = record
OCINumberPart: array[0..OCI_NUMBER_SIZE] of ub1;
end;
OCIEnv = pointer; // OCI environment handle
OCIError = pointer; // OCI error handle
var
HDLL: THandle;
OCIDLL: String = ''; // Name of OCI DLL
InitOCILog: String = ''; // InitOCI logging
OCIHandleAlloc:
function(parenth:pointer;
var hndlpp:pointer;
htype: ub4;
xtramem_sz: Integer;
usrmempp: pointer): sword; cdecl;
OCIHandleFree:
function(hndlp: pointer;
hType: ub4): sword; cdecl;
OCIErrorGet:
function(hndlp: pointer;
recordno: ub4;
sqlstate: PAnsiChar;
var errcodep: sb4;
bufp: PAnsiChar;
bufsiz: ub4;
eType: ub4): sword; cdecl;
OCIEnvCreate:
function(var envhp: OCIEnv;
mode: ub4;
ctxp: Pointer;
malocfp: Pointer;
ralocfp: Pointer;
mfreefp: Pointer;
xtramemsz: Integer;
usrmempp: Pointer): sword; cdecl;
OCINumberFromReal:
function(errhp: OCIError;
rnum: Pointer;
rnum_length: uword;
number: Pointer): sword; cdecl;
OCITerminate:
function(mode: ub4): sword; cdecl;
procedure InitOCI;
function DLLInit: Integer;
procedure DLLExit;
implementation
procedure InitOCI;
var Error: Integer;
oraclehome: string;
begin
oraclehome := GetEnvironmentVariable('ORACLE_HOME');
if oraclehome = '' then
OCIDLL := 'oci.dll'
else
OCIDLL := oraclehome + '\oci.dll';
Error := DLLInit;
if Error <> dllOK then
begin
DLLExit;
raise Exception.Create('Initialization error: ' + OCIDLL);
end
else
InitOCILog := 'oci.dll forced to ' + OCIDLL;
end;
function DLLInit:Integer;
begin
Result := dllOK;
HDLL := LoadLibrary(PChar(OCIDLL));
if HDLL <> 0 then
begin
OCIHandleAlloc := GetProcAddress(HDLL, 'OCIHandleAlloc');
OCIEnvCreate := GetProcAddress(HDLL, 'OCIEnvCreate');
OCINumberFromReal := GetProcAddress(HDLL, 'OCINumberFromReal');
OCIHandleFree := GetProcAddress(HDLL, 'OCIHandleFree');
OCITerminate := GetProcAddress(HDLL, 'OCITerminate');
OCIErrorGet := GetProcAddress(HDLL, 'OCIErrorGet');
end
else
Result := dllNoFile;
end;
procedure DLLExit;
begin
if HDLL <> 0 then FreeLibrary(HDLL);
end;
end.
|
unit uController.Pessoa;
interface
uses System.SysUtils, System.Classes,
uController.Interfaces, uDAO.Interfaces, uModel.Interfaces,
uDAO.Pessoa, uModel.Pessoa, Data.DB;
type
TPessoaController = class(TInterfacedObject, iPessoaController)
private
FModel: iPessoaModel;
FDao: iPessoaDAO;
FDataSource: TDataSource;
public
constructor Create(aDataSource: TDataSource);
destructor Destroy; override;
class function New(aDataSource: TDataSource = nil): iPessoaController;
function Model: iPessoaModel;
function get: iPessoaController; overload;
function get(pID: Integer): iPessoaController; overload;
function Delete: Boolean;
function Save: Boolean;
end;
implementation
{ TPessoaController }
constructor TPessoaController.Create(aDataSource: TDataSource);
begin
FDataSource := aDataSource;
FModel := TPessoaModel.New;
FDao := TPessoaDAO.New;
end;
destructor TPessoaController.Destroy;
begin
inherited;
end;
class function TPessoaController.New(aDataSource: TDataSource): iPessoaController;
begin
Result := Self.Create(aDataSource);
end;
function TPessoaController.get: iPessoaController;
begin
Result := Self;
FDao.Get(FModel.Id, FModel);
end;
function TPessoaController.get(pID: Integer): iPessoaController;
begin
Result := Self;
if Assigned(FDataSource) then
FDataSource.DataSet := FDao.Get(pID);
end;
function TPessoaController.Model: iPessoaModel;
begin
Result := FModel;
end;
function TPessoaController.Save: Boolean;
begin
Result := FDao.Save(FModel);
end;
function TPessoaController.Delete: Boolean;
begin
Result := FDao.Delete(FModel.Id);
end;
end.
|
unit UFrmCadEstado;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCadastro, StdCtrls, ComCtrls, UEstado, UCtrlEstado, UCrtlPais, UPais, UFrmConPais,
sGroupBox, Buttons, sBitBtn, sLabel, Mask, sMaskEdit, sCustomComboEdit,
sTooledit, sEdit, UComuns, UValidacao;
type
TFrmCadEstado = class(TFrmCadastro)
lbl_IdEstado: TsLabel;
lbl_Estado: TsLabel;
lbl_UF: TsLabel;
lbl_IdPais: TsLabel;
lbl_Pais: TsLabel;
lbl_DataCadastro: TsLabel;
lbl_DataUltAlteracao: TsLabel;
edt_IdEstado: TsEdit;
edt_Estado: TsEdit;
edt_UF: TsEdit;
edt_IdPais: TsEdit;
edt_Pais: TsEdit;
edt_DataCadastro: TsDateEdit;
edt_DataUltAlteracao: TsDateEdit;
btn_Buscar: TsBitBtn;
procedure btn_SalvarClick(Sender: TObject);
procedure btn_SairClick(Sender: TObject);
procedure edt_IdPaisExit(Sender: TObject);
procedure edt_IdPaisKeyPress(Sender: TObject; var Key: Char);
procedure btn_BuscarClick(Sender: TObject);
private
UmEstado : Estado;
umaCtrlEstado : CtrlEstado;
umFrmConPais : TFrmConPais;
public
procedure ConhecaObj(vEstado: Estado; vCtrlEstado : CtrlEstado);
procedure HabilitaCampos;
procedure LimpaCampos;
procedure CarregaObj;
end;
var
FrmCadEstado: TFrmCadEstado;
implementation
{$R *.dfm}
{ TFrmCadEstado }
procedure TFrmCadEstado.btn_BuscarClick(Sender: TObject);
begin
inherited;
umFrmConPais := TFrmConPais.Create(nil);
umFrmConPais.ConhecaObj(umEstado.getumPais);
umFrmConPais.btn_Sair.Caption := 'Selecionar';
umFrmConPais.ShowModal;
self.edt_IdPais.Text := inttostr(umEstado.getumPais.getId);
self.edt_Pais.Text := umEstado.getumPais.getDescricao;
end;
procedure TFrmCadEstado.btn_SairClick(Sender: TObject);
begin
inherited;
self.HabilitaCampos;
end;
procedure TFrmCadEstado.btn_SalvarClick(Sender: TObject);
var dataAtual : TDateTime;
msg: string;
begin
inherited;
dataAtual := Date;
if edt_Estado.Text = '' then
begin
ShowMessage('Campo Estado não pode estar em branco!');
edt_Estado.SetFocus;
end
else
if ((not validarUF(edt_UF.Text)and (edt_Pais.Text = 'BRASIL') OR (edt_Pais.Text = 'BRAZIL'))) then
begin
ShowMessage('UF do estado inválida!');
end
else
if edt_Pais.Text = '' then
begin
ShowMessage('Campo País não pode estar em branco!');
edt_IdPais.SetFocus;
end
else
if self.btn_Salvar.Caption = 'Salvar' then
begin
UmEstado.setDescricao(edt_Estado.Text);
UmEstado.setUF(edt_UF.Text);
UmEstado.getUmPais.setId(StrToInt(edt_IdPais.Text));
UmEstado.getUmPais.setDescricao(edt_Pais.Text);
UmEstado.setDataCadastro(edt_DataCadastro.Date);
if self.edt_DataUltAlteracao.Date <> dataAtual then
UmEstado.setDataAlteracao(dataAtual);
msg := umaCtrlEstado.Salvar(UmEstado);
if Copy(msg,0,4) = 'Esse' then
begin
ShowMessage(msg);
edt_Estado.SetFocus;
end
else
begin
if Copy(msg,0,16) = 'Ocorreu um erro!' then
Application.MessageBox(PChar(msg), 'Erro!', MB_OK + MB_ICONSTOP)
else
ShowMessage(msg);
Close;
end;
end
else
begin
if self.btn_Salvar.Caption = 'Excluir' then
begin
msg := umaCtrlEstado.Excluir(UmEstado);
showmessage(msg);
close;
end;
end;
end;
procedure TFrmCadEstado.CarregaObj;
begin
self.edt_IdEstado.Text := inttostr(umEstado.getId);
self.edt_Estado.Text := umEstado.getDescricao;
self.edt_UF.Text := umEstado.getUF;
self.edt_IdPais.Text := inttostr(umEstado.getumPais.getId);
self.edt_Pais.Text := umEstado.getumPais.getDescricao;
self.edt_DataCadastro.Date := umEstado.getDataCadastro;
self.edt_DataUltAlteracao.Date := umEstado.getDataAlteracao;
end;
procedure TFrmCadEstado.ConhecaObj(vEstado: Estado; vCtrlEstado: CtrlEstado);
begin
umEstado := vEstado;
umaCtrlEstado := vCtrlEstado;
self.HabilitaCampos;
self.LimpaCampos;
end;
procedure TFrmCadEstado.edt_IdPaisExit(Sender: TObject);
var umaCtrlPais : CtrlPais;
umPais : Pais;
begin
inherited;
if Self.edt_IdPais.Text <> '' then
begin
// umEstado := Estado.CrieObjeto;
Self.edt_Pais.Clear;
umaCtrlPais := CtrlPais.CrieObjeto;
umEstado.getUmPais.setId(StrToInt(Self.edt_IdPais.Text));
umEstado.getUmPais.setDescricao(Self.edt_Pais.Text);
if not umaCtrlPais.Buscar(umEstado.getUmPais) then
begin
MessageDlg('Nenhum registro encontrado!', mtInformation, [mbOK], 0);
self.edt_IdPais.Clear;
self.edt_Pais.Clear;
end
else
begin
umaCtrlPais.Carrega(umEstado.getumPais);
Self.edt_IdPais.Text := IntToStr(UmEstado.getUmPais.getId);
Self.edt_Pais.Text := UmEstado.getUmPais.getDescricao;
end;
umPais := Pais.CrieObjeto;
umaCtrlPais.Buscar(umPais);
end
else
begin
self.edt_IdPais.Clear;
self.edt_Pais.Clear;
end;
end;
procedure TFrmCadEstado.edt_IdPaisKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
CampoNumero(Sender,Key);
end;
procedure TFrmCadEstado.HabilitaCampos;
begin
Self.btn_Salvar.Caption := 'Salvar';
self.edt_Estado.Enabled := True;
self.edt_UF.Enabled := True;
Self.edt_IdPais.Enabled := True;
Self.btn_Buscar.Enabled := True;
end;
procedure TFrmCadEstado.LimpaCampos;
var dataAtual : TDateTime;
begin
dataAtual := Date;
Self.edt_IdEstado.Clear;
Self.edt_Estado.Clear;
Self.edt_UF.Clear;
self.edt_IdPais.Clear;
self.edt_Pais.Clear;
Self.edt_DataCadastro.Date := dataAtual;
Self.edt_DataUltAlteracao.Date :=dataAtual;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit ExpertsRepository;
interface
uses ToolsAPI, SysUtils, Windows;
type
TExpertsRepositoryWizard = class(TNotifierObject, IOTAWizard, IOTARepositoryWizard,
IOTAFormWizard, IOTARepositoryWizard60)
private
FComment: string;
FName: string;
FID: string;
FPage: string;
FAuthor: string;
private
{ IOTAWizard }
function GetName: string;
function GetIDString: string;
{ IOTARepositoryWizard }
function GetAuthor: string;
function GetComment: string;
function GetGlyph: Cardinal;
function GetState: TWizardState;
{ IOTARepositoryWizard60 }
function GetDesigner: string;
protected
function GetPage: string; virtual;
{ IOTAWizard }
procedure Execute; virtual;
function LoadIcon: Cardinal; virtual;
public
constructor Create(const AComment, AName, AID,
APage, AAuthor: string);
end;
TExpertsRepositoryModuleWizard = class(TExpertsRepositoryWizard, IOTANotifier, IOTAWizard,
IOTARepositoryWizard, IOTARepositoryWizard80, IOTAFormWizard, IOTARepositoryWizard160)
private
FPersonality: string;
FPlatforms,
FFrameworks: TArray<string>;
private
function GetIDString: string;
{ IOTARepositoryWizard80 }
function GetDesigner: string;
function GetGalleryCategory: IOTAGalleryCategory;
function GetPersonality: string;
{ IOTARepositoryWizard160 }
function GetFrameworkTypes: TArray<string>;
function GetPlatforms: TArray<string>;
public
constructor Create(const APersonality, AComment, AName, AID,
APage, AAuthor: string); overload;
constructor Create(const APersonality, AComment, AName, AID,
APage, AAuthor: string; const PlatformNames, FrameworkNames: TArray<string>); overload;
property Personality: string read FPersonality;
end;
TExpertsRepositoryProjectWizard = class(TNotifierObject, IOTANotifier, IOTAWizard,
IOTARepositoryWizard, IOTAProjectWizard, IOTARepositoryWizard80, IOTARepositoryWizard160)
private
FPersonality: string;
FComment: string;
FName: string;
FID: string;
FPage: string;
FAuthor: string;
FPlatforms,
FFrameworks: TArray<string>;
private
{ IOTAWizard }
function GetIDString: string;
function GetName: string;
{ IOTARepositoryWizard }
function GetAuthor: string;
function GetComment: string;
function GetGlyph: Cardinal;
function GetState: TWizardState;
{ IOTARepositoryWizard80 }
function GetGalleryCategory: IOTAGalleryCategory;
function GetPersonality: string;
function GetDesigner: string;
{ IOTARepositoryWizard160 }
function GetFrameworkTypes: TArray<string>;
function GetPlatforms: TArray<string>;
protected
function GetPage: string; virtual;
{ IOTAWizard }
procedure Execute; virtual;
function LoadIcon: Cardinal; virtual;
public
destructor Destroy; override;
constructor Create(const APersonality, AComment, AName, AID,
APage, AAuthor: string); overload;
constructor Create(const APersonality, AComment, AName, AID,
APage, AAuthor: string; const PlatformNames, FrameworkNames: TArray<string>); overload;
property Personality: string read FPersonality;
end;
TExpertsRepositoryProjectWizardWithProc = class(TExpertsRepositoryProjectWizard)
private
FExecuteProc: TProc;
FLoadIcon: TFunc<Cardinal>;
protected
procedure Execute; override;
function LoadIcon: Cardinal; override;
public
constructor Create(const APersonality, AComment, AName, AID, APage, AAuthor: string; AExecuteProc: TProc;
ALoadIcon: TFunc<Cardinal>); overload;
constructor Create(const APersonality, AComment, AName, AID, APage, AAuthor: string; AExecuteProc: TProc;
ALoadIcon: TFunc<Cardinal>; const PlatformNames, FrameworkNames: TArray<string>); overload;
end;
TExpertsRepositoryModuleWizardWithProc = class(TExpertsRepositoryModuleWizard)
private
FExecuteProc: TProc;
FLoadIcon: TFunc<Cardinal>;
protected
procedure Execute; override;
function LoadIcon: Cardinal; override;
public
constructor Create(const APersonality, AComment, AName, AID, APage, AAuthor: string; AExecuteProc: TProc;
ALoadIcon: TFunc<Cardinal>); overload;
constructor Create(const APersonality, AComment, AName, AID, APage, AAuthor: string; AExecuteProc: TProc;
ALoadIcon: TFunc<Cardinal>; const PlatformNames, FrameworkNames: TArray<string>); overload;
end;
// Can be executed when no project is open
TExpertsRepositoryFileWizard = class(TExpertsRepositoryModuleWizard,
IOTAFormWizard100)
private
function IsVisible(Project: IOTAProject): Boolean;
end;
TExpertsRepositoryFileWizardWithProc = class(TExpertsRepositoryFileWizard)
private
FExecuteProc: TProc;
FLoadIcon: TFunc<Cardinal>;
protected
procedure Execute; override;
function LoadIcon: Cardinal; override;
public
constructor Create(const APersonality, AComment, AName, AID, APage, AAuthor: string; AExecuteProc: TProc;
ALoadIcon: TFunc<Cardinal>);
end;
implementation
uses
Classes, ExpertsResStrs;
{ TDSServerModuleWizard }
{ TExpertsRepositoryProjectWizard }
constructor TExpertsRepositoryProjectWizard.Create(const APersonality: string;
const AComment, AName, AID, APage, AAuthor: string);
begin
FPersonality := APersonality;
FComment := AComment;
FName := AName;
FID := AID;
FPage := APage;
FAuthor := AAuthor;
inherited Create;
end;
constructor TExpertsRepositoryProjectWizard.Create(const APersonality, AComment,
AName, AID, APage, AAuthor: string; const PlatformNames,
FrameworkNames: TArray<string>);
begin
Create(APersonality, AComment, AName, AID, APage, AAuthor);
FPlatforms := PlatformNames;
FFrameworks := FrameworkNames;
end;
destructor TExpertsRepositoryProjectWizard.Destroy;
begin
inherited Destroy;
end;
function TExpertsRepositoryProjectWizard.GetName: string;
begin
Result := FName;
end;
function TExpertsRepositoryProjectWizard.GetAuthor: string;
begin
Result := FAuthor;
end;
function TExpertsRepositoryProjectWizard.GetComment: string;
begin
Result := FComment;
end;
function TExpertsRepositoryProjectWizard.GetPage: string;
begin
Result := FPage;
end;
function TExpertsRepositoryProjectWizard.GetGlyph: Cardinal;
begin
// Result := LoadIcon(HInstance, PWideChar(FIcon));
Result := LoadIcon;
end;
function TExpertsRepositoryProjectWizard.GetState: TWizardState;
begin
Result := [];
end;
function TExpertsRepositoryProjectWizard.LoadIcon: Cardinal;
begin
Result := 0;
end;
function TExpertsRepositoryProjectWizard.GetIDString: string;
begin
Result := FID + '.' + Personality // do not localize
end;
procedure TExpertsRepositoryProjectWizard.Execute;
begin
Assert(False); // Must be implemented by descendent
end;
function TExpertsRepositoryProjectWizard.GetDesigner: string;
begin
Result := dVCL;
end;
function TExpertsRepositoryProjectWizard.GetFrameworkTypes: TArray<string>;
begin
Result := FFrameworks;
end;
function TExpertsRepositoryProjectWizard.GetGalleryCategory: IOTAGalleryCategory;
begin
Result := nil;
end;
function TExpertsRepositoryProjectWizard.GetPersonality: string;
begin
Result := Personality;
end;
function TExpertsRepositoryProjectWizard.GetPlatforms: TArray<string>;
begin
Result := FPlatforms;
end;
{ TExpertsRepositoryProjectWizardWithProc }
constructor TExpertsRepositoryProjectWizardWithProc.Create(
const APersonality, AComment, AName, AID, APage, AAuthor: string; AExecuteProc: TProc;
ALoadIcon: TFunc<Cardinal>);
begin
FExecuteProc := AExecuteProc;
FLoadIcon := ALoadIcon;
inherited Create(APersonality, AComment, AName, AID,
APage, AAuthor);
end;
constructor TExpertsRepositoryProjectWizardWithProc.Create(const APersonality,
AComment, AName, AID, APage, AAuthor: string; AExecuteProc: TProc;
ALoadIcon: TFunc<Cardinal>; const PlatformNames,
FrameworkNames: TArray<string>);
begin
FExecuteProc := AExecuteProc;
FLoadIcon := ALoadIcon;
inherited Create(APersonality, AComment, AName, AID,
APage, AAuthor, PlatformNames, FrameworkNames);
end;
procedure TExpertsRepositoryProjectWizardWithProc.Execute;
begin
if Assigned(FExecuteProc) then
FExecuteProc
else
raise Exception.Create(rsNotImplemented);
end;
function TExpertsRepositoryProjectWizardWithProc.LoadIcon: Cardinal;
begin
if Assigned(FLoadIcon) then
Result := FLoadIcon
else
Result := 0;
end;
{ TExpertsRepositoryFileWizard }
constructor TExpertsRepositoryWizard.Create(
const AComment, AName, AID, APage, AAuthor: string);
begin
FComment := AComment;
FName := AName;
FID := AID;
FPage := APage;
FAuthor := AAuthor;
inherited Create;
end;
function TExpertsRepositoryWizard.GetName: string;
begin
Result := FName;
end;
function TExpertsRepositoryWizard.GetAuthor: string;
begin
Result := FAuthor;
end;
function TExpertsRepositoryWizard.GetComment: string;
begin
Result := FComment;
end;
function TExpertsRepositoryWizard.GetPage: string;
begin
Result := FPage;
end;
function TExpertsRepositoryWizard.GetGlyph: Cardinal;
begin
Result := LoadIcon;
end;
function TExpertsRepositoryWizard.GetIDString: string;
begin
Result := FID;
end;
function TExpertsRepositoryWizard.GetState: TWizardState;
begin
Result := [wsEnabled];
end;
function TExpertsRepositoryWizard.LoadIcon: Cardinal;
begin
Result := 0;
end;
procedure TExpertsRepositoryWizard.Execute;
begin
Assert(False); // Must be implemented by descendent
end;
function TExpertsRepositoryWizard.GetDesigner: string;
begin
Result := dAny;
end;
{ TExpertsRepositoryFileWizard }
function TExpertsRepositoryFileWizard.IsVisible(Project: IOTAProject): Boolean;
begin
Result := True; // Always visible
end;
{ TExpertsRepositoryModuleWizard }
constructor TExpertsRepositoryModuleWizard.Create(const APersonality: string;
const AComment, AName, AID, APage, AAuthor: string);
begin
FPersonality := APersonality;
inherited Create(AComment, AName, AID, APage, AAuthor);
end;
constructor TExpertsRepositoryModuleWizard.Create(const APersonality, AComment,
AName, AID, APage, AAuthor: string; const PlatformNames,
FrameworkNames: TArray<string>);
begin
Create(APersonality, AComment, AName, AID, APage, AAuthor);
FPlatforms := PlatformNames;
FFrameworks := FrameworkNames;
end;
function TExpertsRepositoryModuleWizard.GetIDString: string;
begin
Result := FID + '.' + Personality // do not localize
end;
function TExpertsRepositoryModuleWizard.GetPersonality: string;
begin
Result := Personality;
end;
function TExpertsRepositoryModuleWizard.GetPlatforms: TArray<string>;
begin
Result := FPlatforms;
end;
function TExpertsRepositoryModuleWizard.GetDesigner: string;
begin
Result := dVCL;
end;
function TExpertsRepositoryModuleWizard.GetFrameworkTypes: TArray<string>;
begin
Result := FFrameworks;
end;
function TExpertsRepositoryModuleWizard.GetGalleryCategory: IOTAGalleryCategory;
begin
Result := nil;
end;
{ TExpertsRepositoryModuleWizardWithProc }
constructor TExpertsRepositoryModuleWizardWithProc.Create(
const APersonality, AComment, AName, AID, APage, AAuthor: string; AExecuteProc: TProc;
ALoadIcon: TFunc<Cardinal>);
begin
FExecuteProc := AExecuteProc;
FLoadIcon := ALoadIcon;
inherited Create(APersonality, AComment, AName, AID,
APage, AAuthor);
end;
constructor TExpertsRepositoryModuleWizardWithProc.Create(const APersonality,
AComment, AName, AID, APage, AAuthor: string; AExecuteProc: TProc;
ALoadIcon: TFunc<Cardinal>; const PlatformNames,
FrameworkNames: TArray<string>);
begin
FExecuteProc := AExecuteProc;
FLoadIcon := ALoadIcon;
inherited Create(APersonality, AComment, AName, AID,
APage, AAuthor, PlatformNames, FrameworkNames);
end;
procedure TExpertsRepositoryModuleWizardWithProc.Execute;
begin
if Assigned(FExecuteProc) then
FExecuteProc
else
raise Exception.Create(rsNotImplemented);
end;
function TExpertsRepositoryModuleWizardWithProc.LoadIcon: Cardinal;
begin
if Assigned(FLoadIcon) then
Result := FLoadIcon
else
Result := 0;
end;
{ TExpertsRepositoryFileWizardWithProc }
constructor TExpertsRepositoryFileWizardWithProc.Create(
const APersonality, AComment, AName, AID, APage, AAuthor: string; AExecuteProc: TProc;
ALoadIcon: TFunc<Cardinal>);
begin
FExecuteProc := AExecuteProc;
FLoadIcon := ALoadIcon;
inherited Create(APersonality, AComment, AName, AID,
APage, AAuthor);
end;
procedure TExpertsRepositoryFileWizardWithProc.Execute;
begin
if Assigned(FExecuteProc) then
FExecuteProc
else
raise Exception.Create(rsNotImplemented);
end;
function TExpertsRepositoryFileWizardWithProc.LoadIcon: Cardinal;
begin
if Assigned(FLoadIcon) then
Result := FLoadIcon
else
Result := 0;
end;
end.
|
unit Ths.Erp.Database.Table.SysGridDefaultOrderFilter;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TSysGridDefaultOrderFilter = class(TTable)
private
FKey: TFieldDB;
FValue: TFieldDB;
FIsOrder: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property Key: TFieldDB read FKey write FKey;
Property Value: TFieldDB read FValue write FValue;
Property IsOrder: TFieldDB read FIsOrder write FIsOrder;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TSysGridDefaultOrderFilter.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'sys_grid_default_order_filter';
SourceCode := '1';
FKey := TFieldDB.Create('key', ftString, '');
FValue := TFieldDB.Create('value', ftString, '');
FIsOrder := TFieldDB.Create('is_order', ftBoolean, 0);
end;
procedure TSysGridDefaultOrderFilter.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FKey.FieldName,
TableName + '.' + FValue.FieldName,
TableName + '.' + FIsOrder.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FKey.FieldName).DisplayLabel := 'KEY';
Self.DataSource.DataSet.FindField(FValue.FieldName).DisplayLabel := 'VALUE';
Self.DataSource.DataSet.FindField(FIsOrder.FieldName).DisplayLabel := 'ORDER?';
end;
end;
end;
procedure TSysGridDefaultOrderFilter.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FKey.FieldName,
TableName + '.' + FValue.FieldName,
TableName + '.' + FIsOrder.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FKey.Value := FormatedVariantVal(FieldByName(FKey.FieldName).DataType, FieldByName(FKey.FieldName).Value);
FValue.Value := FormatedVariantVal(FieldByName(FValue.FieldName).DataType, FieldByName(FValue.FieldName).Value);
FIsOrder.Value := FormatedVariantVal(FieldByName(FIsOrder.FieldName).DataType, FieldByName(FIsOrder.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TSysGridDefaultOrderFilter.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FKey.FieldName,
FValue.FieldName,
FIsOrder.FieldName
]);
NewParamForQuery(QueryOfInsert, FKey);
NewParamForQuery(QueryOfInsert, FValue);
NewParamForQuery(QueryOfInsert, FIsOrder);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TSysGridDefaultOrderFilter.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FKey.FieldName,
FValue.FieldName,
FIsOrder.FieldName
]);
NewParamForQuery(QueryOfUpdate, FKey);
NewParamForQuery(QueryOfUpdate, FValue);
NewParamForQuery(QueryOfUpdate, FIsOrder);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TSysGridDefaultOrderFilter.Clone():TTable;
begin
Result := TSysGridDefaultOrderFilter.Create(Database);
Self.Id.Clone(TSysGridDefaultOrderFilter(Result).Id);
FKey.Clone(TSysGridDefaultOrderFilter(Result).FKey);
FValue.Clone(TSysGridDefaultOrderFilter(Result).FValue);
FIsOrder.Clone(TSysGridDefaultOrderFilter(Result).FIsOrder);
end;
end.
|
{$mode objfpc}
{$m+}
program TreeTraversalDFS;
type
Nd = ^Node;
Node = record
data : integer;
L, R, P : Nd; { Left, right, parent }
end;
StackNode = record
val : Nd;
next : ^StackNode;
end;
LinkedListStack = class
private
top : ^StackNode;
public
function pop(): Nd;
procedure push(i : Nd);
end;
function LinkedListStack.pop() : Nd;
begin
if top = nil then
begin
pop := nil;
end
else
begin
pop := top^.val;
top := top^.next;
end;
end;
procedure LinkedListStack.push(i : Nd);
var
A : ^StackNode;
begin
new(A);
A^.val := i;
A^.next := top;
top := A;
end;
procedure Traverse1Inorder(Root: Nd);
begin
if Root <> nil then
begin
Traverse1Inorder(Root^.L);
writeln(Root^.data);
Traverse1Inorder(Root^.R);
end;
end;
procedure Traverse1Preorder(Root: Nd);
begin
if Root <> nil then
begin
writeln(Root^.data);
Traverse1Preorder(Root^.L);
Traverse1Preorder(Root^.R);
end;
end;
procedure Traverse1Postorder(Root: Nd);
begin
if Root <> nil then
begin
Traverse1Postorder(Root^.L);
Traverse1Postorder(Root^.R);
writeln(Root^.data);
end;
end;
procedure Traverse2PreorderRight(Root: Nd);
var
LStack : LinkedListStack;
L : Nd;
begin
LStack := LinkedListStack.Create();
L := Root;
while L <> nil do
begin
writeln(L^.data);
if L^.L <> nil then
LStack.push(L^.L);
if L^.R <> nil then
LStack.push(L^.R);
L := LStack.pop();
end;
end;
procedure Traverse2Preorder(Root: Nd);
var
LStack : LinkedListStack;
L : Nd;
begin
LStack := LinkedListStack.Create();
L := Root;
while L <> nil do
begin
writeln(L^.data);
if L^.R <> nil then
LStack.push(L^.R);
if L^.L <> nil then
LStack.push(L^.L);
L := LStack.pop();
end;
end;
var
A, B, C, D, E, F, G, H, I, J : Nd;
begin
new(A); A^.data := 1;
new(B); B^.data := 2;
new(C); C^.data := 3;
new(D); D^.data := 4;
new(E); E^.data := 5;
new(F); F^.data := 6;
new(G); G^.data := 7;
new(H); H^.data := 8;
new(I); I^.data := 9;
new(J); J^.data :=10;
A^.L := B;
A^.R := C;
B^.L := D;
B^.R := E;
C^.L := H;
D^.L := J;
D^.R := F;
H^.R := I;
{* tree structure:
A
B C
D E H
J F I*}
writeln('--traverse 1--');
writeln('inorder:');
Traverse1Inorder(A);
writeln('preorder:');
Traverse1Preorder(A);
writeln('postorder:');
Traverse1Postorder(A);
writeln('--traverse 2 with stack--');
writeln('preorder:');
Traverse2Preorder(A);
writeln('preorder from right:');
Traverse2PreorderRight(A);
end.
|
unit Partition;
interface
uses
Windows, SysUtils,
OSFile, Getter.PartitionExtent;
type
TPartition = class(TOSFile)
private
PartitionExtentList: TPartitionExtentList;
PartitionLengthReadWrite: TLargeInteger;
function GetPartitionLengthOrRequestAndReturn: TLargeInteger;
procedure AddThisEntryToPartitionLength(
PartitionExtentEntry: TPartitionExtentEntry);
procedure SetPartitionLengthFromPartitionExtentList;
function RequestPartitionExtentList: TPartitionExtentList;
procedure RequestPartitionLength;
public
property PartitionLengthInByte: TLargeInteger
read GetPartitionLengthOrRequestAndReturn;
function GetPartitionExtentList: TPartitionExtentList;
end;
implementation
function TPartition.RequestPartitionExtentList: TPartitionExtentList;
var
PartitionExtentGetter: TPartitionExtentGetter;
begin
PartitionExtentGetter := TPartitionExtentGetter.Create(
GetPathOfFileAccessing);
result := PartitionExtentGetter.GetPartitionExtentList;
FreeAndNil(PartitionExtentGetter);
end;
procedure TPartition.AddThisEntryToPartitionLength
(PartitionExtentEntry: TPartitionExtentEntry);
begin
PartitionLengthReadWrite :=
PartitionLengthReadWrite +
PartitionExtentEntry.ExtentLength;
end;
procedure TPartition.SetPartitionLengthFromPartitionExtentList;
var
PartitionExtentEntry: TPartitionExtentEntry;
PartitionExtentListToGetLength: TPartitionExtentList;
begin
PartitionLengthReadWrite := 0;
PartitionExtentListToGetLength := RequestPartitionExtentList;
for PartitionExtentEntry in PartitionExtentListToGetLength do
AddThisEntryToPartitionLength(PartitionExtentEntry);
FreeAndNil(PartitionExtentListToGetLength);
end;
procedure TPartition.RequestPartitionLength;
begin
SetPartitionLengthFromPartitionExtentList;
end;
function TPartition.GetPartitionLengthOrRequestAndReturn: TLargeInteger;
begin
if PartitionLengthReadWrite = 0 then
RequestPartitionLength;
exit(PartitionLengthReadWrite);
end;
function TPartition.GetPartitionExtentList: TPartitionExtentList;
begin
if PartitionExtentList = nil then
PartitionExtentList := RequestPartitionExtentList;
result := PartitionExtentList;
end;
end.
|
unit Vigilante.Controller.Compilacao.Impl;
interface
uses
System.Generics.Collections, Data.DB, FireDac.Comp.Client, Vigilante.Compilacao.Model,
Vigilante.Controller.Compilacao, Vigilante.Compilacao.Observer,
Vigilante.DataSet.Compilacao, Vigilante.View.URLDialog,
Vigilante.Controller.Base.Impl, Module.ValueObject.URL,
Module.DataSet.VigilanteBase, Vigilante.Controller.Mediator;
type
TCompilacaoController = class(TControllerBase<ICompilacaoModel>, ICompilacaoController)
private
FDataSet: TCompilacaoDataSet;
FMediator: IControllerMediator;
procedure CarregarDadosCompilacao;
procedure SalvarDadosBuild;
protected
function GetDataSet: TCompilacaoDataSet;
function GetDataSetInterno: TVigilanteDataSetBase<ICompilacaoModel>; override;
public
constructor Create(const AMediator: IControllerMediator);
destructor Destroy; override;
procedure BuscarAtualizacoes; override;
procedure AdicionarOuAtualizar(const ACompilacao: ICompilacaoModel);
procedure VisualizadoPeloUsuario(const AID: TGUID); override;
function PodeNotificarUsuario(const AID: TGUID): boolean; override;
property DataSet: TCompilacaoDataSet read FDataSet;
end;
implementation
{ TBuildController }
uses
System.SysUtils, System.Classes, System.Threading, ContainerDI,
Vigilante.Compilacao.Service, Vigilante.Aplicacao.SituacaoBuild,
Vigilante.Build.Observer.Impl, Vigilante.Compilacao.Observer.Impl,
Vigilante.Module.GerenciadorDeArquivoDataSet;
constructor TCompilacaoController.Create(const AMediator: IControllerMediator);
begin
FDataSet := TCompilacaoDataSet.Create(nil);
CarregarDadosCompilacao;
FMediator := AMediator;
FMediator.AdicionarController(Self, tcCompilacao);
end;
destructor TCompilacaoController.Destroy;
begin
SalvarDadosBuild;
FreeAndNil(FDataSet);
FMediator.RemoverController(tcCompilacao);
inherited;
end;
procedure TCompilacaoController.CarregarDadosCompilacao;
var
_gerenciadorArquivosDataSet: IGerenciadorDeArquivoDataSet;
begin
_gerenciadorArquivosDataSet := CDI.Resolve<IGerenciadorDeArquivoDataSet>([DataSet]);
if not _gerenciadorArquivosDataSet.CarregarArquivo(QualifiedClassName) then
DataSet.CreateDataSet;
end;
procedure TCompilacaoController.SalvarDadosBuild;
var
_gerenciadorArquivosDataSet: IGerenciadorDeArquivoDataSet;
begin
_gerenciadorArquivosDataSet := CDI.Resolve<IGerenciadorDeArquivoDataSet>([DataSet]);
_gerenciadorArquivosDataSet.SalvarArquivo(QualifiedClassName);
end;
procedure TCompilacaoController.VisualizadoPeloUsuario(const AID: TGUID);
begin
inherited;
if not DataSet.LocalizarPorID(AID) then
Exit;
DataSet.Edit;
DataSet.Atualizar := False;
DataSet.Post;
end;
procedure TCompilacaoController.AdicionarOuAtualizar(const ACompilacao: ICompilacaoModel);
begin
DataSet.Importar(ACompilacao);
end;
procedure TCompilacaoController.BuscarAtualizacoes;
var
_service: ICompilacaoService;
_dataSet: TCompilacaoDataSet;
_compilacao: ICompilacaoModel;
_compilacaoOriginal: ICompilacaoModel;
begin
inherited;
if DataSet.IsEmpty then
Exit;
if DataSet.State in dsEditModes then
Exit;
_dataSet := TCompilacaoDataSet.Create(nil);
try
_dataSet.CloneCursor(DataSet);
_dataSet.ApenasAtualizaveis();
_dataSet.First;
while not _dataSet.Eof do
begin
_service := CDI.Resolve<ICompilacaoService>;
_compilacaoOriginal := _dataSet.ExportarRegistro;
_compilacao := _service.AtualizarCompilacao(_compilacaoOriginal);
if not Assigned(_compilacao) then
Exit;
if not _compilacaoOriginal.Equals(_compilacao) then
_dataSet.Importar(_compilacao);
_dataSet.Next;
end;
finally
FreeAndNil(_dataSet);
end;
end;
function TCompilacaoController.PodeNotificarUsuario(const AID: TGUID): boolean;
begin
Result := False;
if not inherited then
Exit;
Result := DataSet.Atualizar;
end;
function TCompilacaoController.GetDataSet: TCompilacaoDataSet;
begin
Result := FDataSet;
end;
function TCompilacaoController.GetDataSetInterno: TVigilanteDataSetBase<ICompilacaoModel>;
begin
Result := GetDataSet;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit VirtIntf deprecated;
interface
type
TInterface = class
private
FRefCount: Longint;
public
constructor Create;
procedure Free;
function AddRef: Longint; virtual; stdcall;
function Release: Longint; virtual; stdcall;
function GetVersion: Integer; virtual; stdcall;
end;
function ReleaseException: string;
implementation
uses System.SysUtils;
{ TInterface }
constructor TInterface.Create;
begin
inherited Create;
FRefCount := 1;
end;
procedure TInterface.Free;
begin
if Self <> nil then Release;
end;
function TInterface.AddRef: Longint;
begin
Inc(FRefCount);
Result := FRefCount;
end;
function TInterface.Release: Longint;
begin
Dec(FRefCount);
Result := FRefCount;
if FRefCount = 0 then Destroy;
end;
function TInterface.GetVersion: Integer;
begin
Result := 3;
end;
{ Exception handling }
function ReleaseException: string;
begin
Result := Exception(ExceptObject).Message;
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ TDataItems editor dialog (Table Structure) }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit VCLBI.Editor.Items;
interface
{
Editor dialog to modify the structure of a TDataItem that is in "Table" mode.
Also a BIGrid in read-write mode to enable adding, modifying and removing
rows.
}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes,
System.Types,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
BI.DataItem, Vcl.ExtCtrls, VCLBI.DataControl, VCLBI.Grid,
VCLBI.GridForm;
type
TItemsEditor = class(TForm)
PanelButtons: TPanel;
Panel1: TPanel;
BOK: TButton;
Panel2: TPanel;
GroupBox1: TGroupBox;
LBFields: TListBox;
PanelGrid: TPanel;
Panel3: TPanel;
Label24: TLabel;
Label25: TLabel;
LDuplicateName: TLabel;
CBKind: TComboBox;
EName: TEdit;
Panel4: TPanel;
SBAddField: TSpeedButton;
SBRemoveField: TSpeedButton;
Panel5: TPanel;
SBUpField: TSpeedButton;
SBDownField: TSpeedButton;
Splitter1: TSplitter;
procedure FormShow(Sender: TObject);
procedure CBKindChange(Sender: TObject);
procedure ENameChange(Sender: TObject);
procedure LBFieldsClick(Sender: TObject);
procedure LBFieldsDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure LBFieldsDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure SBRemoveFieldClick(Sender: TObject);
procedure SBUpFieldClick(Sender: TObject);
procedure SBAddFieldClick(Sender: TObject);
procedure SBDownFieldClick(Sender: TObject);
private
{ Private declarations }
IGrid : TBIGridForm;
Items : TDataItems;
function DataOf(const AIndex:Integer):TDataItem;
function SelectedField:TDataItem;
function SelectedItems:TDataItems;
procedure SwapFields(const A,B:Integer);
class function Valid(const AItems:TDataItems):Boolean; static;
public
{ Public declarations }
class function Embedd(const AOwner:TComponent; const AParent:TWinControl;
const AItems:TDataItems):TItemsEditor; static;
class function Edit(const AOwner:TComponent;
const AItems:TDataItems):Boolean; static;
procedure Refresh(const AItems:TDataItems);
end;
implementation
|
{===============================================================================
Copyright(c) 2012, 北京北研兴电力仪表有限责任公司
All rights reserved.
错误接线,解析元件进出电压电流单元
+ TWE_DIAGRAM 接线图
===============================================================================}
unit U_WE_ORGAN;
interface
uses U_DIAGRAM_TYPE, SysUtils, Classes, U_WIRING_ERROR, xFunction;
type
/// <summary>
/// 向量线
/// </summary>
TVECTOR_LINE = class
private
FLineName: string;
FLineAngle: Double;
FIsVirtualLine: Boolean;
public
/// <summary>
/// 线名称
/// </summary>
property LineName : string read FLineName write FLineName;
/// <summary>
/// 线角度0-360°,0°为竖直向上方向
/// </summary>
property LineAngle: Double read FLineAngle write FLineAngle;
/// <summary>
/// 是否为虚拟线
/// </summary>
property IsVirtualLine: Boolean read FIsVirtualLine write FIsVirtualLine;
constructor Create( sLineName: string=''; dLineAngle: Double = 0 );
end;
type
/// <summary>
/// 电压线
/// </summary>
TVECTOR_LINES = class
private
FLines: TStringList;
public
/// <summary>
/// 向量线列表
/// </summary>
property Lines : TStringList read FLines write FLines;
/// <summary>
/// 根据线名称获取线对象
/// </summary>
function GetLine(sLineName:string) : TVECTOR_LINE;
constructor Create;
destructor Destroy; override;
end;
var
VectorLines : TVECTOR_LINES;
type
/// <summary>
/// 进出元件电流类型
/// </summary>
TI_TYPE = (itNot,itIa, itIb, itIc, itIn);
type
/// <summary>
/// 参数类型
/// </summary>
TPARAM_TYPE = (ptNot, // 无参数
pt1_2 // 二分之一
);
type
/// <summary>
/// 元件类
/// </summary>
TWE_ORGAN = class
private
FUParam: TPARAM_TYPE;
FIParam: TPARAM_TYPE;
FUOutType: string;
FIOutType: string;
FUInType: string;
FIInType: string;
FUAngle: Double;
FIAngle: Double;
function GetItype: string;
function GetUType: string;
procedure SetIAngle(const Value: Double);
procedure SetUAngle(const Value: Double);
function ResetAngle( dAngle : Double ) : Double;
public
/// <summary>
/// 电压参数
/// </summary>
property UParam : TPARAM_TYPE read FUParam write FUParam;
/// <summary>
/// 元件电压进端类型
/// </summary>
property UInType : string read FUInType write FUInType;
/// <summary>
/// 元件电压出端类型
/// </summary>
property UOutType : string read FUOutType write FUOutType;
/// <summary>
/// 电流参数
/// </summary>
property IParam : TPARAM_TYPE read FIParam write FIParam;
/// <summary>
/// 元件电流进端类型
/// </summary>
property IInType : string read FIInType write FIInType;
/// <summary>
/// 元件电流出端类型
/// </summary>
property IOutType : string read FIOutType write FIOutType;
/// <summary>
/// 电压类型
/// </summary>
property UType : string read GetUType;
/// <summary>
/// 电流类型
/// </summary>
property IType : string read GetItype;
/// <summary>
/// 电压线角度(画向量图时计算)
/// </summary>
property UAngle : Double read FUAngle write SetUAngle;
/// <summary>
/// 电流线角度(画向量图时计算,不包括φ角)
/// </summary>
property IAngle : Double read FIAngle write SetIAngle;
/// <summary>
/// 电流反向
/// </summary>
procedure IReverse;
constructor Create;
end;
/// <summary>
/// 解析错误类型到元件进出
/// </summary>
/// <param name="ADtype">接线类型</param>
/// <param name="WiringError">设置的错误</param>
/// <param name="AOrgans">有功/多功能元件列表</param>
/// <param name="ROrgans">无功元件列表</param>
procedure AnalysisOrgan( ADtype:TDiagramType; WiringError: TWIRING_ERROR;
AOrgans, ROrgans : TStringList );
implementation
procedure AnalysisOrgan( ADtype:TDiagramType; WiringError: TWIRING_ERROR;
AOrgans, ROrgans : TStringList );
// ABC断相数量
function GetUBreakCount : Integer;
begin
Result := 0;
if WiringError.UaBroken or WiringError.UsaBroken then
Inc(Result);
if WiringError.UbBroken or WiringError.UsbBroken then
Inc(Result);
if WiringError.UcBroken or WiringError.UscBroken then
Inc(Result);
end;
procedure Analysis3L4;
function GetCurInOut(AInOut : TWE_PHASE_LINE_TYPE) : string;
begin
case AInOut of
plA: Result := 'I_a';
plB: Result := 'I_b';
plC: Result := 'I_c';
plN: Result := 'I_n';
end;
end;
function IsBroken(nPhase:Integer ):Boolean;
begin
Result := False;
case nPhase of
1: Result := WiringError.UaBroken or WiringError.UsaBroken;
2: Result := WiringError.UbBroken or WiringError.UsbBroken;
3: Result := WiringError.UcBroken or WiringError.UscBroken;
end;
end;
// 找第三边
function GetLastPhase( s: string ):string;
begin
if (Pos('a', s) = 0) then
Result := 'U_a'
else if (Pos('b', s) = 0) then
Result := 'U_b'
else
Result := 'U_c'
end;
// 断一相
procedure BreakOne;
function GetStr : string;
begin
if WiringError.UbBroken or WiringError.UsbBroken then
Result := 'U_b'
else if WiringError.UcBroken or WiringError.UscBroken then
Result := 'U_c'
else
Result := 'U_a';
end;
var
k : Integer;
sPhase : string;
begin
for k := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[k]) do
begin
sPhase := GetLastPhase(UInType+UOutType);
if sPhase = GetStr then
begin
UParam := ptNot;
end
else
begin
if UInType = GetStr then
begin
UParam := ptNot;
UInType := UOutType;
end
else
begin
UParam := pt1_2;
UOutType := sPhase;
end;
end;
end;
end;
end;
var
AOrgan : TWE_ORGAN;
j: Integer;
begin
ClearStringList(ROrgans);
for j := 0 to 1 do
begin
AOrgan := TWE_ORGAN.Create;
ROrgans.AddObject(IntToStr(j+1), AOrgan);
end;
{电压部分}
// 默认
TWE_ORGAN(ROrgans.Objects[0]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[0]).UInType := 'U_b';
TWE_ORGAN(ROrgans.Objects[0]).UOutType := 'U_c';
TWE_ORGAN(ROrgans.Objects[1]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[1]).UInType := 'U_a';
TWE_ORGAN(ROrgans.Objects[1]).UOutType := 'U_c';
// PT极性反
if WiringError.PT1Reverse then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'b','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'b','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'c','b', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'c','b', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','c', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
if WiringError.PT2Reverse then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'a','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'a','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'c','a', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'c','a', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','c', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
// 电压相序
case WiringError.USequence of
stABC: ;
stACB:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'b','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'b','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'c','b', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'c','b', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','c', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
stBAC:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'a','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'a','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'b','a', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'b','a', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','b', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','b', [rfReplaceAll]);
end;
end;
end;
stBCA:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'a','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'a','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'c','a', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'c','a', [rfReplaceAll]);
UInType := StringReplace(UInType, 'b','c', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'b','c', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','b', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','b', [rfReplaceAll]);
end;
end;
end;
stCAB:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'a','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'a','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'b','a', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'b','a', [rfReplaceAll]);
UInType := StringReplace(UInType, 'c','b', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'c','b', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','c', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
stCBA:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'a','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'a','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'c','a', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'c','a', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','c', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
end;
// ABC断一相
if GetUBreakCount = 1 then
begin
BreakOne;
end
// ABC断两相或断三相
else if GetUBreakCount > 1 then
begin
with WiringError do
begin
if IsBroken(1) and IsBroken(2) and (not IsBroken(3)) then
begin
TWE_ORGAN(ROrgans.Objects[0]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[0]).UInType := 'U_c';
TWE_ORGAN(ROrgans.Objects[0]).UOutType := 'U_c';
TWE_ORGAN(ROrgans.Objects[1]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[1]).UInType := 'U_c';
TWE_ORGAN(ROrgans.Objects[1]).UOutType := 'U_c';
end
else if IsBroken(1) and IsBroken(3) and (not IsBroken(2)) then
begin
TWE_ORGAN(ROrgans.Objects[0]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[0]).UInType := 'U_b';
TWE_ORGAN(ROrgans.Objects[0]).UOutType := 'U_b';
TWE_ORGAN(ROrgans.Objects[1]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[1]).UInType := 'U_b';
TWE_ORGAN(ROrgans.Objects[1]).UOutType := 'U_b';
end
else if IsBroken(2) and IsBroken(3) and (not IsBroken(1)) then
begin
TWE_ORGAN(ROrgans.Objects[0]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[0]).UInType := 'U_a';
TWE_ORGAN(ROrgans.Objects[0]).UOutType := 'U_a';
TWE_ORGAN(ROrgans.Objects[1]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[1]).UInType := 'U_a';
TWE_ORGAN(ROrgans.Objects[1]).UOutType := 'U_a';
end
else
begin
TWE_ORGAN(ROrgans.Objects[0]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[0]).UInType := '';
TWE_ORGAN(ROrgans.Objects[0]).UOutType := '';
TWE_ORGAN(ROrgans.Objects[1]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[1]).UInType := '';
TWE_ORGAN(ROrgans.Objects[1]).UOutType := '';
end;
end;
end;
{电流部分}
// 默认
TWE_ORGAN(ROrgans.Objects[0]).IInType := 'I_a';
TWE_ORGAN(ROrgans.Objects[0]).IOutType := 'I_n';
TWE_ORGAN(ROrgans.Objects[1]).IInType := 'I_c';
TWE_ORGAN(ROrgans.Objects[1]).IOutType := 'I_n';
// 电流元件进出
TWE_ORGAN(ROrgans.Objects[0]).IInType := GetCurInOut(WiringError.I1In);
TWE_ORGAN(ROrgans.Objects[0]).IOutType := GetCurInOut(WiringError.I1Out);
TWE_ORGAN(ROrgans.Objects[1]).IInType := GetCurInOut(WiringError.I2In);
TWE_ORGAN(ROrgans.Objects[1]).IOutType := GetCurInOut(WiringError.I2Out);
// CT反接
if WiringError.CT1Reverse then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('a', IType) > 0 then
IReverse;
end;
end;
end;
if WiringError.CT2Reverse then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('c', IType) > 0 then
IReverse;
end;
end;
end;
// 电流短路
if WiringError.IaBroken or WiringError.CT1Short then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('a', IType) > 0 then
begin
IInType := 'I_n';
IOutType := 'I_n';
end;
end;
end;
end;
if WiringError.IbBroken or WiringError.CT2Short then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('c', IType) > 0 then
begin
IInType := 'I_n';
IOutType := 'I_n';
end;
end;
end;
end;
end;
procedure Analysis4_NoPT_L6;
// 找第三边
function GetLastPhase( s: string ):string;
begin
if (Pos('a', s) = 0) then
Result := 'U_a'
else if (Pos('b', s) = 0) then
Result := 'U_b'
else
Result := 'U_c'
end;
// 断一相
procedure BreakOne;
function GetStr : string;
begin
if (WiringError.UbBroken) or (WiringError.UsbBroken) then
Result := 'U_b'
else if (WiringError.UcBroken) or (WiringError.UscBroken) then
Result := 'U_c'
else
Result := 'U_a';
end;
var
k : Integer;
sPhase : string;
begin
for k := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[k]) do
begin
sPhase := GetLastPhase(UInType+UOutType);
if sPhase = GetStr then
begin
UParam := ptNot;
end
else
begin
UParam := pt1_2;
if UInType = GetStr then
UInType := sPhase
else
UOutType := sPhase;
end;
end;
end;
end;
var
AOrgan : TWE_ORGAN;
j: Integer;
begin
ClearStringList(ROrgans);
for j := 0 to 2 do
begin
AOrgan := TWE_ORGAN.Create;
ROrgans.AddObject(IntToStr(j+1), AOrgan);
end;
{电压部分}
// 默认
TWE_ORGAN(ROrgans.Objects[0]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[0]).UInType := 'U_b';
TWE_ORGAN(ROrgans.Objects[0]).UOutType := 'U_c';
TWE_ORGAN(ROrgans.Objects[1]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[1]).UInType := 'U_c';
TWE_ORGAN(ROrgans.Objects[1]).UOutType := 'U_a';
TWE_ORGAN(ROrgans.Objects[2]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[2]).UInType := 'U_a';
TWE_ORGAN(ROrgans.Objects[2]).UOutType := 'U_b';
// 电压相序
case WiringError.USequence of
stABC: ;
stACB:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
// s := UInType
UInType := StringReplace(UInType, 'b','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'b','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'c','b', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'c','b', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','c', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
stBAC:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'a','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'a','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'b','a', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'b','a', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','b', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','b', [rfReplaceAll]);
end;
end;
end;
stBCA:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'a','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'a','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'c','a', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'c','a', [rfReplaceAll]);
UInType := StringReplace(UInType, 'b','c', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'b','c', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','b', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','b', [rfReplaceAll]);
end;
end;
end;
stCAB:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'a','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'a','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'b','a', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'b','a', [rfReplaceAll]);
UInType := StringReplace(UInType, 'c','b', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'c','b', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','c', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
stCBA:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
UInType := StringReplace(UInType, 'a','temp', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'a','temp', [rfReplaceAll]);
UInType := StringReplace(UInType, 'c','a', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'c','a', [rfReplaceAll]);
UInType := StringReplace(UInType, 'temp','c', [rfReplaceAll]);
UOutType := StringReplace(UOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
end;
// ABC断一相
if GetUBreakCount = 1 then
begin
BreakOne;
end
// ABC断两相或断三相
else if GetUBreakCount > 1 then
begin
with WiringError do
begin
if UaBroken and UbBroken and (not UcBroken) then
begin
TWE_ORGAN(ROrgans.Objects[0]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[0]).UInType := 'U_c';
TWE_ORGAN(ROrgans.Objects[0]).UOutType := 'U_c';
TWE_ORGAN(ROrgans.Objects[1]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[1]).UInType := 'U_c';
TWE_ORGAN(ROrgans.Objects[1]).UOutType := 'U_c';
TWE_ORGAN(ROrgans.Objects[2]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[2]).UInType := 'U_c';
TWE_ORGAN(ROrgans.Objects[2]).UOutType := 'U_c';
end
else if UaBroken and UcBroken and (not UbBroken) then
begin
TWE_ORGAN(ROrgans.Objects[0]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[0]).UInType := 'U_b';
TWE_ORGAN(ROrgans.Objects[0]).UOutType := 'U_b';
TWE_ORGAN(ROrgans.Objects[1]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[1]).UInType := 'U_b';
TWE_ORGAN(ROrgans.Objects[1]).UOutType := 'U_b';
TWE_ORGAN(ROrgans.Objects[2]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[2]).UInType := 'U_b';
TWE_ORGAN(ROrgans.Objects[2]).UOutType := 'U_b';
end
else if UbBroken and UcBroken and (not UaBroken) then
begin
TWE_ORGAN(ROrgans.Objects[0]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[0]).UInType := 'U_a';
TWE_ORGAN(ROrgans.Objects[0]).UOutType := 'U_a';
TWE_ORGAN(ROrgans.Objects[1]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[1]).UInType := 'U_a';
TWE_ORGAN(ROrgans.Objects[1]).UOutType := 'U_a';
TWE_ORGAN(ROrgans.Objects[2]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[2]).UInType := 'U_a';
TWE_ORGAN(ROrgans.Objects[2]).UOutType := 'U_a';
end
else
begin
TWE_ORGAN(ROrgans.Objects[0]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[0]).UInType := '';
TWE_ORGAN(ROrgans.Objects[0]).UOutType := '';
TWE_ORGAN(ROrgans.Objects[1]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[1]).UInType := '';
TWE_ORGAN(ROrgans.Objects[1]).UOutType := '';
TWE_ORGAN(ROrgans.Objects[2]).UParam := ptNot;
TWE_ORGAN(ROrgans.Objects[2]).UInType := '';
TWE_ORGAN(ROrgans.Objects[2]).UOutType := '';
end;
end;
end;
//PT极性反
if WiringError.PT1Reverse then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if (Pos('a',UInType) > 0) and ((Pos('-',UInType) <= 0)) then
UInType := '-U_a';
if (Pos('a',UOutType) > 0 ) and (Pos(' - ',UOutType) <= 0 ) then
UOutType := '-U_a';
end;
end;
end
else
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('a',UInType) > 0 then
UInType := 'U_a';
if (Pos('a',UOutType) > 0 ) then
UOutType := 'U_a';
end;
end;
end;
if WiringError.PT2Reverse then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if (Pos('b',UInType) > 0) and (Pos('-',UInType) <= 0) then
UInType := '-U_b';
if (Pos('b',UOutType) > 0 ) and (Pos('-',UOutType) <= 0) then
UOutType := '-U_b';
end;
end;
end
else
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('b',UInType) > 0 then
UInType := 'U_b';
if (Pos('b',UOutType) > 0 ) then
UOutType := 'U_b';
end;
end;
end;
if WiringError.PT3Reverse then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if (Pos('c',UInType) > 0 ) and (Pos('-',UInType) <= 0) then
UInType := '-U_c';
if (Pos('c',UOutType) > 0 ) and (Pos('-',UOutType) <= 0 ) then
UOutType := '-U_c';
end;
end
end
else
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('c',UInType) > 0 then
UInType := 'U_c';
if (Pos('c',UOutType) > 0 ) then
UOutType := 'U_c';
end;
end;
end;
{电流部分}
// 默认
TWE_ORGAN(ROrgans.Objects[0]).IInType := 'I_a';
TWE_ORGAN(ROrgans.Objects[0]).IOutType := 'I_n';
TWE_ORGAN(ROrgans.Objects[1]).IInType := 'I_b';
TWE_ORGAN(ROrgans.Objects[1]).IOutType := 'I_n';
TWE_ORGAN(ROrgans.Objects[2]).IInType := 'I_c';
TWE_ORGAN(ROrgans.Objects[2]).IOutType := 'I_n';
// 电流相序
case WiringError.ISequence of
stACB:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
IInType := StringReplace(IInType, 'b','temp', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'b','temp', [rfReplaceAll]);
IInType := StringReplace(IInType, 'c','b', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'c','b', [rfReplaceAll]);
IInType := StringReplace(IInType, 'temp','c', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
stBAC:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
IInType := StringReplace(IInType, 'a','temp', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'a','temp', [rfReplaceAll]);
IInType := StringReplace(IInType, 'b','a', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'b','a', [rfReplaceAll]);
IInType := StringReplace(IInType, 'temp','b', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'temp','b', [rfReplaceAll]);
end;
end;
end;
stBCA:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
IInType := StringReplace(IInType, 'a','temp', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'a','temp', [rfReplaceAll]);
IInType := StringReplace(IInType, 'c','a', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'c','a', [rfReplaceAll]);
IInType := StringReplace(IInType, 'b','c', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'b','c', [rfReplaceAll]);
IInType := StringReplace(IInType, 'temp','b', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'temp','b', [rfReplaceAll]);
end;
end;
end;
stCAB:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
IInType := StringReplace(IInType, 'a','temp', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'a','temp', [rfReplaceAll]);
IInType := StringReplace(IInType, 'b','a', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'b','a', [rfReplaceAll]);
IInType := StringReplace(IInType, 'c','b', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'c','b', [rfReplaceAll]);
IInType := StringReplace(IInType, 'temp','c', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
stCBA:
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
IInType := StringReplace(IInType, 'a','temp', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'a','temp', [rfReplaceAll]);
IInType := StringReplace(IInType, 'c','a', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'c','a', [rfReplaceAll]);
IInType := StringReplace(IInType, 'temp','c', [rfReplaceAll]);
IOutType := StringReplace(IOutType, 'temp','c', [rfReplaceAll]);
end;
end;
end;
end;
// CT反接
if WiringError.CT1Reverse then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('a', IType) > 0 then
IReverse;
end;
end;
end;
if WiringError.CT2Reverse then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('b', IType) > 0 then
IReverse;
end;
end;
end;
if WiringError.CT3Reverse then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('c', IType) > 0 then
IReverse;
end;
end;
end;
// 电流短路
if WiringError.IaBroken or WiringError.CT1Short then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('a', IType) > 0 then
begin
IInType := 'I_n';
IOutType := 'I_n';
end;
end;
end;
end;
if WiringError.IbBroken or WiringError.CT2Short then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('b', IType) > 0 then
begin
IInType := 'I_n';
IOutType := 'I_n';
end;
end;
end;
end;
if WiringError.IcBroken or WiringError.CT3Short then
begin
for j := 0 to ROrgans.Count - 1 do
begin
with TWE_ORGAN(ROrgans.Objects[j]) do
begin
if Pos('c', IType) > 0 then
begin
IInType := 'I_n';
IOutType := 'I_n';
end;
end;
end;
end;
end;
begin
if not Assigned(WiringError) then
Exit;
// 解析有功元件状态
if Assigned(AOrgans) then
begin
end;
// 解析无功元件状态
if Assigned(ROrgans) then
begin
case ADtype of
dt3CTClear: ;
dt3M,
dt3L4: Analysis3L4;
dt4M_NoPT,
dt4M_PT: Analysis4_NoPT_L6;
dt4_PT_CT_CLear: ;
dt4_PT_L6,
dt4_NoPT_L6: Analysis4_NoPT_L6;
dt4Direct: ;
end;
end;
end;
{ TWE_ORGAN }
constructor TWE_ORGAN.Create;
begin
FUParam := ptNot;
FIParam := ptNot;
end;
function TWE_ORGAN.GetItype: string;
begin
if FIInType = 'I_n' then
Result := FIOutType
else
Result := FIInType;
end;
function TWE_ORGAN.GetUType: string;
var
sUOut: string;
begin
if FUInType = 'U_n' then
Result := '-'
else
Result := StringReplace(FUInType, '-', '', []);
if Pos('U', FUOutType)> 0 then
sUOut := StringReplace(FUOutType, '-', '', []);
Result := Result + StringReplace(sUOut,'U','',[rfReplaceAll]);
end;
procedure TWE_ORGAN.IReverse;
var
s : string;
begin
s := IInType;
FIInType := FIOutType;
FIOutType := s;
end;
function TWE_ORGAN.ResetAngle(dAngle: Double): Double;
begin
if dAngle >= 360 then
begin
dAngle := dAngle - 360;
Result := ResetAngle(dAngle);
end
else if dAngle < 0 then
begin
dAngle := dAngle + 360;
Result := ResetAngle(dAngle);
end
else
Result := dAngle;
end;
procedure TWE_ORGAN.SetIAngle(const Value: Double);
begin
FIAngle := ResetAngle(Value);
end;
procedure TWE_ORGAN.SetUAngle(const Value: Double);
begin
FUAngle := ResetAngle(Value);
end;
{ TVECTOR_LINE }
constructor TVECTOR_LINE.Create(sLineName: string; dLineAngle: Double);
begin
FLineName := sLineName;
FLineAngle := dLineAngle;
FIsVirtualLine:= False;
end;
{ TVECTOR_LINES }
constructor TVECTOR_LINES.Create;
function CreateLine( sLName: string; dLineAngle: Double):TVECTOR_LINE;
begin
Result := TVECTOR_LINE.Create(sLName, dLineAngle);
end;
begin
FLines := TStringList.Create;
FLines.AddObject('', CreateLine('U_a', 90));
FLines.AddObject('', CreateLine('U_b', 330));
FLines.AddObject('', CreateLine('U_c', 210));
FLines.AddObject('', CreateLine('-U_a', 270));
FLines.AddObject('', CreateLine('-U_b', 150));
FLines.AddObject('', CreateLine('-U_c', 30));
FLines.AddObject('', CreateLine('I_a', 90));
FLines.AddObject('', CreateLine('I_b', 330));
FLines.AddObject('', CreateLine('I_c', 210));
end;
destructor TVECTOR_LINES.Destroy;
begin
ClearStringList(FLines);
FLines.Free;
inherited;
end;
function TVECTOR_LINES.GetLine(sLineName: string): TVECTOR_LINE;
var
i: Integer;
begin
Result := nil;
for i := 0 to FLines.Count - 1 do
begin
if TVECTOR_LINE(FLines.Objects[i]).LineName = Trim(sLineName) then
begin
Result := TVECTOR_LINE(FLines.Objects[i]);
Break;
end;
end;
end;
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit RequestImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
EnvironmentIntf,
RequestIntf,
ListIntf,
KeyValueTypes;
type
(*!------------------------------------------------
* basic class having capability as
* HTTP request
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-----------------------------------------------*)
TRequest = class(TInterfacedObject, IRequest)
private
webEnvironment : ICGIEnvironment;
queryParams : IList;
cookieParams : IList;
bodyParams : IList;
function getContentLength(const env : ICGIEnvironment) : integer;
procedure clearParams(const params : IList);
procedure initParamsFromString(
const data : string;
const hashInst : IList
);
procedure initPostBodyParamsFromStdInput(
const env : ICGIEnvironment;
const body : IList
);
procedure initBodyParamsFromStdInput(
const env : ICGIEnvironment;
const body : IList
);
procedure initQueryParamsFromEnvironment(
const env : ICGIEnvironment;
const query : IList
);
procedure initCookieParamsFromEnvironment(
const env : ICGIEnvironment;
const cookies : IList
);
procedure initParamsFromEnvironment(
const env : ICGIEnvironment;
const query : IList;
const cookies : IList;
const body : IList
);
(*!------------------------------------------------
* get single query param value by its name
*-------------------------------------------------
* @param string key name of key
* @param string defValue default value to use if key
* does not exist
* @return string value
*------------------------------------------------*)
function getParam(
const src :IList;
const key: string;
const defValue : string = ''
) : string;
public
constructor create(
const env : ICGIEnvironment;
const query : IList;
const cookies : IList;
const body : IList
);
destructor destroy(); override;
(*!------------------------------------------------
* get single query param value by its name
*-------------------------------------------------
* @param string key name of key
* @param string defValue default value to use if key
* does not exist
* @return string value
*------------------------------------------------*)
function getQueryParam(const key: string; const defValue : string = '') : string;
(*!------------------------------------------------
* get all query params
*-------------------------------------------------
* @return array of TKeyValue
*------------------------------------------------*)
function getQueryParams() : IList;
(*!------------------------------------------------
* get single cookie param value by its name
*-------------------------------------------------
* @param string key name of key
* @param string defValue default value to use if key
* does not exist
* @return string value
*------------------------------------------------*)
function getCookieParam(const key: string; const defValue : string = '') : string;
(*!------------------------------------------------
* get all query params
*-------------------------------------------------
* @return array of TKeyValue
*------------------------------------------------*)
function getCookieParams() : IList;
(*!------------------------------------------------
* get request body data
*-------------------------------------------------
* @param string key name of key
* @param string defValue default value to use if key
* does not exist
* @return string value
*------------------------------------------------*)
function getParsedBodyParam(const key: string; const defValue : string = '') : string;
(*!------------------------------------------------
* get all request body data
*-------------------------------------------------
* @return array of TKeyValue
*------------------------------------------------*)
function getParsedBodyParams() : IList;
(*!------------------------------------------------
* test if current request is comming from AJAX request
*-------------------------------------------------
* @return true if ajax request
*------------------------------------------------*)
function isXhr() : boolean;
end;
implementation
uses
sysutils,
UrlHelpersImpl,
EInvalidRequestImpl;
resourcestring
sErrInvalidContentLength = 'Invalid content length';
constructor TRequest.create(
const env : ICGIEnvironment;
const query : IList;
const cookies : IList;
const body : IList
);
begin
webEnvironment := env;
queryParams := query;
cookieParams := cookies;
bodyParams := body;
initParamsFromEnvironment(
webEnvironment,
queryParams,
cookieParams,
bodyParams
);
end;
destructor TRequest.destroy();
begin
inherited destroy();
clearParams(queryParams);
clearParams(cookieParams);
clearParams(bodyParams);
webEnvironment := nil;
queryParams := nil;
cookieParams := nil;
bodyParams := nil;
end;
procedure TRequest.clearParams(const params : IList);
var i, len : integer;
param : PKeyValue;
begin
len := params.count();
for i:= len-1 downto 0 do
begin
param := params.get(i);
dispose(param);
params.delete(i);
end;
end;
procedure TRequest.initParamsFromString(
const data : string;
const hashInst : IList
);
var arrOfQryStr, keyvalue : TStringArray;
i, len, lenKeyValue : integer;
param : PKeyValue;
begin
arrOfQryStr := data.split(['&']);
len := length(arrOfQryStr);
for i:= 0 to len-1 do
begin
keyvalue := arrOfQryStr[i].split('=');
lenKeyValue := length(keyvalue);
if (lenKeyValue = 2) then
begin
new(param);
param^.key := keyvalue[0];
param^.value := (keyvalue[1]).urlDecode();
hashInst.add(param^.key, param);
end;
end;
end;
procedure TRequest.initQueryParamsFromEnvironment(
const env : ICGIEnvironment;
const query : IList
);
begin
initParamsFromString(env.queryString(), query);
end;
procedure TRequest.initCookieParamsFromEnvironment(
const env : ICGIEnvironment;
const cookies : IList
);
begin
initParamsFromString(env.httpCookie(), cookies);
end;
function TRequest.getContentLength(const env : ICGIEnvironment) : integer;
begin
try
result := strToInt(env.contentLength());
except
on e:EConvertError do
begin
raise EInvalidRequest.create(sErrInvalidContentLength);
end;
end;
end;
procedure TRequest.initPostBodyParamsFromStdInput(
const env : ICGIEnvironment;
const body : IList
);
var contentLength, ctr : integer;
contentType, bodyStr : string;
ch : char;
param : PKeyValue;
begin
//read STDIN
contentLength := getContentLength(env);
ctr := 0;
setLength(bodyStr, contentLength);
while (ctr < contentLength) do
begin
read(ch);
bodyStr[ctr+1] := ch;
inc(ctr);
end;
contentType := env.contentType();
if ((contentType = 'application/x-www-form-urlencoded') or
(contentType = 'multipart/form-data')) then
begin
initParamsFromString(bodyStr, body);
end else
begin
//if POST but different contentType save it as it is
//with its contentType as key
new(param);
param^.key := contentType;
param^.value := bodyStr;
body.add(param^.key, param);
end;
end;
procedure TRequest.initBodyParamsFromStdInput(
const env : ICGIEnvironment;
const body : IList
);
var method : string;
begin
method := env.requestMethod();
if (method = 'POST') then
begin
initPostBodyParamsFromStdInput(env, body);
end;
end;
procedure TRequest.initParamsFromEnvironment(
const env : ICGIEnvironment;
const query : IList;
const cookies : IList;
const body : IList
);
begin
initQueryParamsFromEnvironment(env, query);
initCookieParamsFromEnvironment(env, cookies);
initBodyParamsFromStdInput(env, bodyParams);
end;
(*!------------------------------------------------
* get single param value by its name
*-------------------------------------------------
* @param IList src hash list instance
* @param string key name of key
* @param string defValue default value to use if key
* does not exist
* @return string value
*------------------------------------------------*)
function TRequest.getParam(
const src : IList;
const key: string;
const defValue : string = ''
) : string;
var qry : PKeyValue;
begin
qry := src.find(key);
if (qry = nil) then
begin
result := defValue;
end else
begin
result := qry^.value;
end;
end;
(*!------------------------------------------------
* get single query param value by its name
*-------------------------------------------------
* @param string key name of key
* @param string defValue default value to use if key
* does not exist
* @return string value
*------------------------------------------------*)
function TRequest.getQueryParam(const key: string; const defValue : string = '') : string;
begin
result := getParam(queryParams, key, defValue);
end;
(*!------------------------------------------------
* get all request query strings data
*-------------------------------------------------
* @return list of request query string parameters
*------------------------------------------------*)
function TRequest.getQueryParams() : IList;
begin
result := queryParams;
end;
(*!------------------------------------------------
* get single cookie param value by its name
*-------------------------------------------------
* @param string key name of key
* @param string defValue default value to use if key
* does not exist
* @return string value
*------------------------------------------------*)
function TRequest.getCookieParam(const key: string; const defValue : string = '') : string;
begin
result := getParam(cookieParams, key, defValue);
end;
(*!------------------------------------------------
* get all request cookie data
*-------------------------------------------------
* @return list of request cookies parameters
*------------------------------------------------*)
function TRequest.getCookieParams() : IList;
begin
result := cookieParams;
end;
(*!------------------------------------------------
* get request body data
*-------------------------------------------------
* @param string key name of key
* @param string defValue default value to use if key
* does not exist
* @return string value
*------------------------------------------------*)
function TRequest.getParsedBodyParam(const key: string; const defValue : string = '') : string;
begin
result := getParam(bodyParams, key, defValue);
end;
(*!------------------------------------------------
* get all request body data
*-------------------------------------------------
* @return list of request body parameters
*------------------------------------------------*)
function TRequest.getParsedBodyParams() : IList;
begin
result := bodyParams;
end;
(*!------------------------------------------------
* test if current request is coming from AJAX request
*-------------------------------------------------
* @return true if ajax request false otherwise
*------------------------------------------------*)
function TRequest.isXhr() : boolean;
begin
result := (webEnvironment.env('HTTP_X_REQUESTED_WITH') = 'XMLHttpRequest');
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Math.Averagers.Abstract;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes,
{$ELSE}
Classes,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf,
ADAPT.Collections.Intf,
ADAPT.Math.Common.Intf,
ADAPT.Math.Averagers.Intf;
{$I ADAPT_RTTI.inc}
type
TADAverager<T> = class abstract(TADObject, IADAverager<T>)
protected
procedure CheckSorted(const ASeries: IADListReader<T>); overload;
procedure CheckSorted(const ASortedState: TADSortedState); overload;
public
function CalculateAverage(const ASeries: IADListReader<T>): T; overload; virtual; abstract;
function CalculateAverage(const ASeries: Array of T; const ASortedState: TADSortedState): T; overload; virtual; abstract;
end;
implementation
{ TADAverager<T> }
procedure TADAverager<T>.CheckSorted(const ASeries: IADListReader<T>);
begin
CheckSorted(ASeries.SortedState);
end;
procedure TADAverager<T>.CheckSorted(const ASortedState: TADSortedState);
begin
if ASortedState <> ssSorted then
raise EADMathAveragerListNotSorted.Create('Series MUST be Sorted.');
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.ADSDef;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Phys.ADSWrapper;
type
// TFDPhysADSConnectionDefParams
// Generated for: FireDAC ADS driver
TFDADSServerTypes = (stNone, stRemote, stLocal, stInternet);
TFDADSProtocol = (prNone, prUDP, prIPX, prTCPIP, prTLS);
TFDADSCharacterSet = (csANSI, csOEM);
TFDADSCompress = (cmNone, cmInternet, cmAlways, cmNever);
TFDADSLocking = (lcNone, lcProprietary, lcCompatible);
/// <summary> TFDPhysADSConnectionDefParams class implements FireDAC ADS driver specific connection definition class. </summary>
TFDPhysADSConnectionDefParams = class(TFDConnectionDefParams)
private
function GetDriverID: String;
procedure SetDriverID(const AValue: String);
function GetAlias: String;
procedure SetAlias(const AValue: String);
function GetServerTypes: TFDADSServerTypes;
procedure SetServerTypes(const AValue: TFDADSServerTypes);
function GetProtocol: TFDADSProtocol;
procedure SetProtocol(const AValue: TFDADSProtocol);
function GetServer: String;
procedure SetServer(const AValue: String);
function GetPort: Integer;
procedure SetPort(const AValue: Integer);
function GetCharacterSet: TFDADSCharacterSet;
procedure SetCharacterSet(const AValue: TFDADSCharacterSet);
function GetCompress: TFDADSCompress;
procedure SetCompress(const AValue: TFDADSCompress);
function GetTableType: TADSTableType;
procedure SetTableType(const AValue: TADSTableType);
function GetTablePassword: String;
procedure SetTablePassword(const AValue: String);
function GetLocking: TFDADSLocking;
procedure SetLocking(const AValue: TFDADSLocking);
function GetADSAdvanced: String;
procedure SetADSAdvanced(const AValue: String);
function GetMetaDefCatalog: String;
procedure SetMetaDefCatalog(const AValue: String);
function GetMetaCurCatalog: String;
procedure SetMetaCurCatalog(const AValue: String);
published
property DriverID: String read GetDriverID write SetDriverID stored False;
property Alias: String read GetAlias write SetAlias stored False;
property ServerTypes: TFDADSServerTypes read GetServerTypes write SetServerTypes stored False;
property Protocol: TFDADSProtocol read GetProtocol write SetProtocol stored False;
property Server: String read GetServer write SetServer stored False;
property Port: Integer read GetPort write SetPort stored False;
property CharacterSet: TFDADSCharacterSet read GetCharacterSet write SetCharacterSet stored False default csANSI;
property Compress: TFDADSCompress read GetCompress write SetCompress stored False;
property TableType: TADSTableType read GetTableType write SetTableType stored False default ttDefault;
property TablePassword: String read GetTablePassword write SetTablePassword stored False;
property Locking: TFDADSLocking read GetLocking write SetLocking stored False;
property ADSAdvanced: String read GetADSAdvanced write SetADSAdvanced stored False;
property MetaDefCatalog: String read GetMetaDefCatalog write SetMetaDefCatalog stored False;
property MetaCurCatalog: String read GetMetaCurCatalog write SetMetaCurCatalog stored False;
end;
implementation
uses
FireDAC.Stan.Consts;
// TFDPhysADSConnectionDefParams
// Generated for: FireDAC ADS driver
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetDriverID: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_DriverID];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetDriverID(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetAlias: String;
begin
Result := FDef.AsString[S_FD_ConnParam_ADS_Alias];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetAlias(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_ADS_Alias] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetServerTypes: TFDADSServerTypes;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_ADS_ServerTypes];
if CompareText(s, '') = 0 then
Result := stNone
else if CompareText(s, 'Remote') = 0 then
Result := stRemote
else if CompareText(s, 'Local') = 0 then
Result := stLocal
else if CompareText(s, 'Internet') = 0 then
Result := stInternet
else
Result := stNone;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetServerTypes(const AValue: TFDADSServerTypes);
const
C_ServerTypes: array[TFDADSServerTypes] of String = ('', 'Remote', 'Local', 'Internet');
begin
FDef.AsString[S_FD_ConnParam_ADS_ServerTypes] := C_ServerTypes[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetProtocol: TFDADSProtocol;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_ADS_Protocol];
if CompareText(s, '') = 0 then
Result := prNone
else if CompareText(s, 'UDP') = 0 then
Result := prUDP
else if CompareText(s, 'IPX') = 0 then
Result := prIPX
else if CompareText(s, 'TCPIP') = 0 then
Result := prTCPIP
else if CompareText(s, 'TLS') = 0 then
Result := prTLS
else
Result := prNone;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetProtocol(const AValue: TFDADSProtocol);
const
C_Protocol: array[TFDADSProtocol] of String = ('', 'UDP', 'IPX', 'TCPIP', 'TLS');
begin
FDef.AsString[S_FD_ConnParam_ADS_Protocol] := C_Protocol[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetServer: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_Server];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetServer(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_Server] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetPort: Integer;
begin
Result := FDef.AsInteger[S_FD_ConnParam_Common_Port];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetPort(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Common_Port] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetCharacterSet: TFDADSCharacterSet;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_Common_CharacterSet];
if CompareText(s, 'ANSI') = 0 then
Result := csANSI
else if CompareText(s, 'OEM') = 0 then
Result := csOEM
else
Result := csANSI;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetCharacterSet(const AValue: TFDADSCharacterSet);
const
C_CharacterSet: array[TFDADSCharacterSet] of String = ('ANSI', 'OEM');
begin
FDef.AsString[S_FD_ConnParam_Common_CharacterSet] := C_CharacterSet[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetCompress: TFDADSCompress;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_ADS_Compress];
if CompareText(s, '') = 0 then
Result := cmNone
else if CompareText(s, 'Internet') = 0 then
Result := cmInternet
else if CompareText(s, 'Always') = 0 then
Result := cmAlways
else if CompareText(s, 'Never') = 0 then
Result := cmNever
else
Result := cmNone;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetCompress(const AValue: TFDADSCompress);
const
C_Compress: array[TFDADSCompress] of String = ('', 'Internet', 'Always', 'Never');
begin
FDef.AsString[S_FD_ConnParam_ADS_Compress] := C_Compress[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetTableType: TADSTableType;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_ADS_TableType];
if CompareText(s, 'Default') = 0 then
Result := ttDefault
else if CompareText(s, 'CDX') = 0 then
Result := ttCDX
else if CompareText(s, 'VFP') = 0 then
Result := ttVFP
else if CompareText(s, 'ADT') = 0 then
Result := ttADT
else if CompareText(s, 'NTX') = 0 then
Result := ttNTX
else
Result := ttDefault;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetTableType(const AValue: TADSTableType);
const
C_TableType: array[TADSTableType] of String = ('Default', 'CDX', 'VFP', 'ADT', 'NTX');
begin
FDef.AsString[S_FD_ConnParam_ADS_TableType] := C_TableType[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetTablePassword: String;
begin
Result := FDef.AsString[S_FD_ConnParam_ADS_TablePassword];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetTablePassword(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_ADS_TablePassword] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetLocking: TFDADSLocking;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_ADS_Locking];
if CompareText(s, '') = 0 then
Result := lcNone
else if CompareText(s, 'Proprietary') = 0 then
Result := lcProprietary
else if CompareText(s, 'Compatible') = 0 then
Result := lcCompatible
else
Result := lcNone;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetLocking(const AValue: TFDADSLocking);
const
C_Locking: array[TFDADSLocking] of String = ('', 'Proprietary', 'Compatible');
begin
FDef.AsString[S_FD_ConnParam_ADS_Locking] := C_Locking[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetADSAdvanced: String;
begin
Result := FDef.AsString[S_FD_ConnParam_ADS_ADSAdvanced];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetADSAdvanced(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_ADS_ADSAdvanced] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetMetaDefCatalog: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetMetaDefCatalog(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSConnectionDefParams.GetMetaCurCatalog: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysADSConnectionDefParams.SetMetaCurCatalog(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog] := AValue;
end;
end.
|
unit AConfigRelatorios;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
StdCtrls, Buttons, Componentes1, ExtCtrls, PainelGradiente, FileCtrl,
ComCtrls, ImgList,IniFiles;
type
TFConfigRelatorios = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
BGravar: TBitBtn;
DirectoryListBox1: TDirectoryListBox;
LRelatorios: TListView;
Label1: TLabel;
ImageList1: TImageList;
Label2: TLabel;
BCancelar: TBitBtn;
BAbrir: TBitBtn;
OpenDialog1: TOpenDialog;
DriveComboBox1: TDriveComboBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BGravarClick(Sender: TObject);
procedure LRelatoriosClick(Sender: TObject);
procedure DirectoryListBox1Change(Sender: TObject);
procedure BCancelarClick(Sender: TObject);
procedure BAbrirClick(Sender: TObject);
private
{ Private declarations }
VprRelatorios, VprConfiguracoes : TStringList;
VprCancelado : Boolean;
procedure CarregaListaRelatorios;
procedure MarcaDesmarcaGrupo(VpaGrupo : String;VpaEstado : Boolean);
function RetornaConfiguracoes : TStringList;
procedure AbrirArquivo(VpaNomArquivo : String);
public
{ Public declarations }
Function RetornaRelatorios : TStringlist;
end;
var
FConfigRelatorios: TFConfigRelatorios;
implementation
uses APrincipal, FunString;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFConfigRelatorios.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
VprRelatorios := TStringList.Create;
VprConfiguracoes := TStringList.Create;
CarregaListaRelatorios;
VprCancelado := False;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFConfigRelatorios.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
VprRelatorios.Free;
VprConfiguracoes.free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
eventos das configuracoes
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{*********** configura os relatorios e retorna um String list *****************}
function TFConfigRelatorios.RetornaRelatorios : TStringlist;
begin
ShowModal;
if not VprCancelado then
result := RetornaConfiguracoes
else
result := TStringList.create;
end;
{******************** grava as configuracoes dos relatorios *******************}
function TFConfigRelatorios.RetornaConfiguracoes : TStringList;
var
VpfLaco, VpfQtdLinhas : Integer;
VpfLinha, VpfNomeSecaoIni : String;
begin
result := TStringList.Create;
result.Clear;
//adicona a secao do ini
result.Add('[RELATORIOS]');
//joga o nome do item em uma variavel para quando quiser mudar o nome do item é só alterar aqui
VpfNomeSecaoIni := 'INSTALAR';
VpfQtdLinhas := 1;
//Carrega a primeira secao para a linha
VpfLinha := VpfNomeSecaoIni+ Inttostr(VpfQtdLinhas) +'=';
for VpfLaco := 0 to LRelatorios.Items.Count -1 do
begin
// o conteudo do item pode ter no máximo 256 caracteres que é o que o wise aceito.
if Length(Vpflinha) > 240 then
begin
//adiciona o item
result.Add(VpfLinha);
//cria um novo item
inc(VpfQtdLinhas);
VpfLinha := VpfNomeSecaoIni+ Inttostr(VpfQtdLinhas)+'=';
end;
//se o item está marcado adicoina a linha
if LRelatorios.Items[VpfLaco].Checked Then
if LRelatorios.Items[VpfLaco].SubItems.Strings[0] = 'ITEM' THEN
VpfLinha := VpfLinha + LRelatorios.Items[VpfLaco].SubItems.Strings[2];
end;
//adiciona o item
result.Add(VpfLinha);
//informa a qtd de itens
result.Add('QTD='+ IntToStr(VpfQtdLinhas));
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
eventos da lista
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{****************** inicializa a lista de relatorios **************************}
procedure TFConfigRelatorios.CarregaListaRelatorios;
var
VpfLaco : Integer;
VpfNo : TListItem;
VpfGrupoAtual, VpfLinha : String;
begin
try
LRelatorios.ReadOnly := false;
LRelatorios.Items.Clear;
VprRelatorios.Clear;
VprRelatorios.LoadFromFile(DirectoryListBox1.Directory+ '\Relatorios.Txt');
VpfGrupoAtual := '';
for VpfLaco := 0 To VprRelatorios.Count - 1 do
begin
if VpfGrupoAtual <> copy(VprRelatorios.Strings[VpfLaco],2,2) Then
begin
VpfGrupoAtual := copy(VprRelatorios.Strings[VpfLaco],2,2);
VpfNo := LRelatorios.Items.Add;
VpfNo.ImageIndex := -1;
VpfNo.Caption := '----------------------'+copy(VprRelatorios.Strings[VpfLaco],2,2)+'---------------------';
VpfNo.SubItems.Add('GRUPO');
VpfNo.SubItems.Add(VpfGrupoAtual);
VpfNo.SubItems.Add(' ');
end;
VpfNo := LRelatorios.Items.Add;
VpfNo.ImageIndex := 0;
VpfLinha := copy(DeletaEspacoD(VprRelatorios.Strings[VpfLaco]),11,length(VprRelatorios.Strings[VpfLaco])-16);
VpfNo.Caption := SubstituiStr(DeletaEspaco(VpfLinha),'_', ' ');
//cria o dado que identifica o tipo e o codigo do relatorio.
VpfNo.SubItems.Add('ITEM');
VpfNo.SubItems.Add(VpfGrupoAtual);
VpfNo.SubItems.Add(copy(DeletaEspacoD(VprRelatorios.Strings[VpfLaco]),length(VprRelatorios.Strings[VpfLaco])-4,5));
end;
except
end;
LRelatorios.ReadOnly := true;
end;
{********************* marca desmarca os grupos *******************************}
procedure TFConfigRelatorios.MarcaDesmarcaGrupo(VpaGrupo : String;VpaEstado : Boolean);
var
Vpflaco : Integer;
begin
for VpfLaco := 0 to LRelatorios.Items.Count - 1 do
begin
if LRelatorios.Items[VpfLaco].SubItems.Strings[1] = VpaGrupo Then
LRelatorios.Items[VpfLaco].Checked := VpaEstado;
end;
end;
{***************************** abri o arquivo *********************************}
procedure TFConfigRelatorios.AbrirArquivo(VpaNomArquivo : String);
var
VpfQtdIni, VpfLaco, VpfLacoAux1,VpfLacoAux2 : Integer;
VpfAquivoIni : TIniFile;
VpfLinha, VpfItem : String;
begin
//verifica se existem items na lista e se o nome nao esta vazio
if (LRelatorios.Items.Count = 0) or (DeletaEspaco(VpaNomArquivo) = '') then
exit;
//desmarca todos os relatorios
for Vpflaco := 0 to LRelatorios.Items.Count - 1 do
LRelatorios.Items[Vpflaco].Checked := false;
VpfAquivoIni := TIniFile.Create(VpaNomArquivo);
//recupera a qtd de iten que possui o ini
VpfQtdIni := VpfAquivoIni.ReadInteger('RELATORIOS','QTD',0);
For VpfLaco := 1 to VpfQtdIni do
begin
//recupera o item
VpfLinha := DeletaEspaco(VpfAquivoIni.ReadString('RELATORIOS','INSTALAR'+IntToStr(VpfLaco),''));
for Vpflacoaux1 := 1 to (length(Vpflinha) div 5) do
begin
//pega um relatorio do item
VpfItem := copy(vpflinha,((VpflacoAux1 - 1)*5)+1,5);
for VpflacoAux2 := 0 to LRelatorios.Items.Count - 1 do
//procura o relatorio na lista de relatorios
if LRelatorios.Items[VpflacoAux2].SubItems.Strings[2] = VpfItem then
begin
LRelatorios.Items[VpflacoAux2].Checked := true;
//se achou vai para o proximo
break;
end;
end;
end;
VpfAquivoIni.Free;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
eventos diversos
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{*********************** fecha o formulario corrente **************************}
procedure TFConfigRelatorios.BGravarClick(Sender: TObject);
begin
VprCancelado := false;
Close;
end;
{***************** quando se da um clique nos relatorios **********************}
procedure TFConfigRelatorios.LRelatoriosClick(Sender: TObject);
begin
if LRelatorios.Selected <> nil then
begin
LRelatorios.Selected.Checked := not LRelatorios.Selected.Checked;
if LRelatorios.Selected.SubItems.Strings[0] ='GRUPO' Then
MarcaDesmarcaGrupo(LRelatorios.Selected.SubItems.Strings[1],LRelatorios.Selected.Checked);
end;
end;
{****************** quando é alterado o diretorio corrente ********************}
procedure TFConfigRelatorios.DirectoryListBox1Change(Sender: TObject);
begin
CarregaListaRelatorios;
end;
{******************* cancela as configuracoes do usuario **********************}
procedure TFConfigRelatorios.BCancelarClick(Sender: TObject);
begin
VprCancelado := true;
Close;
end;
procedure TFConfigRelatorios.BAbrirClick(Sender: TObject);
begin
if OpenDialog1.Execute Then
AbrirArquivo(OpenDialog1.FileName);
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFConfigRelatorios]);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.ShareMem;
interface
{$IFDEF MEMORY_DIAG}
type
TBlockEnumProc = function (Block: Pointer): Boolean;
{$ENDIF}
function SysGetMem(Size: NativeInt): Pointer;
function SysFreeMem(P: Pointer): Integer;
function SysReallocMem(P: Pointer; Size: NativeInt): Pointer;
function SysAllocMem(Size: NativeInt): Pointer;
function SysRegisterExpectedMemoryLeak(P: Pointer): Boolean;
function SysUnregisterExpectedMemoryLeak(P: Pointer): Boolean;
function GetHeapStatus: THeapStatus;
function GetAllocMemCount: Integer;
function GetAllocMemSize: Integer;
procedure DumpBlocks;
procedure HeapAddRef;
procedure HeapRelease;
{$IFDEF MEMORY_DIAG}
function InitBlockMarking: Boolean;
function MarkBlocks: Integer;
function GetMarkedBlocks(MarkID: Integer; Proc: TBlockEnumProc): Boolean;
{$ENDIF}
implementation
{$IFDEF GLOBALALLOC}
uses Windows;
{$ENDIF}
{$IFDEF MEMORY_DIAG}
type
TInitBlockMarking = function: Boolean;
TMarkBlocks = function: Integer;
TGetMarkedBlocks = function (MarkID: Integer; Proc: TBlockEnumProc): Boolean;
var
MMHandle: Integer = 0;
SysInitBlockMarking: TInitBlockMarking = nil;
SysMarkBlocks: TMarkBlocks = nil;
SysGetMarkedBlocks: TGetMarkedBlocks = nil;
{$ENDIF}
var
{Need access to the shared memory manager structure to be able to call the
default AllocMem and leak registration handlers for borlndmm.dll libraries
that do not implement these functions.}
SharedMemoryManager: TMemoryManagerEx;
const
DelphiMM = 'borlndmm.dll';
function SysGetMem(Size: NativeInt): Pointer; external DelphiMM name '@Borlndmm@SysGetMem$qqri';
function SysFreeMem(P: Pointer): Integer; external DelphiMM name '@Borlndmm@SysFreeMem$qqrpv';
function SysReallocMem(P: Pointer; Size: NativeInt): Pointer; external DelphiMM name '@Borlndmm@SysReallocMem$qqrpvi';
function GetHeapStatus: THeapStatus; external DelphiMM;
function GetAllocMemCount: Integer; external DelphiMM;
function GetAllocMemSize: Integer; external DelphiMM;
procedure DumpBlocks; external DelphiMM;
function GetModuleHandle(lpModuleName: PChar): Integer; stdcall;
{$IFDEF UNICODE}
external 'kernel32.dll' name 'GetModuleHandleW';
{$ELSE}
external 'kernel32.dll' name 'GetModuleHandleA';
{$ENDIF}
function GetProcAddress(hModule: Integer; lpProcName: PAnsiChar): Pointer; stdcall;
external 'kernel32.dll' name 'GetProcAddress';
{$IFDEF MEMORY_DIAG}
procedure InitMMHandle;
begin
if MMHandle = 0 then MMHandle := GetModuleHandle(DelphiMM);
end;
function InitBlockMarking: Boolean;
begin
InitMMHandle;
if @SysInitBlockMarking = nil then
@SysInitBlockMarking := GetProcAddress(MMHandle, 'InitBlockMarking');
if @SysInitBlockMarking <> nil then
Result := SysInitBlockMarking
else Result := False;
end;
function MarkBlocks: Integer;
begin
InitMMHandle;
if @SysMarkBlocks = nil then
@SysMarkBlocks := GetProcAddress(MMHandle, 'MarkBlocks');
if @SysMarkBlocks <> nil then
Result := SysMarkBlocks
else Result := -1;
end;
function GetMarkedBlocks(MarkID: Integer; Proc: TBlockEnumProc): Boolean;
begin
InitMMHandle;
if @SysGetMarkedBlocks = nil then
@SysGetMarkedBlocks := GetProcAddress(MMHandle, 'GetMarkedBlocks');
if @SysGetMarkedBlocks <> nil then
Result := SysGetMarkedBlocks(MarkID, Proc)
else Result := False;
end;
{$ENDIF}
{$IFDEF GLOBALALLOC}
function xSysGetMem(Size: NativeInt): Pointer;
begin
Result := GlobalAllocPtr(HeapAllocFlags, Size);
end;
function xSysFreeMem(P: Pointer): Integer;
begin
Result := GlobalFreePtr(P);
end;
function xSysReallocMem(P: Pointer; Size: NativeInt): Pointer;
begin
Result := GlobalReallocPtr(P, Size, 0);
end;
{$ENDIF}
procedure HeapAddRef;
var
MM: Integer;
Proc: procedure;
begin
MM := GetModuleHandle(DelphiMM);
Proc := GetProcAddress(MM, '@Borlndmm@HeapAddRef$qqrv');
if Assigned(Proc) then
Proc;
end;
procedure HeapRelease;
var
MM: Integer;
Proc: procedure;
begin
MM := GetModuleHandle(DelphiMM);
Proc := GetProcAddress(MM, '@Borlndmm@HeapRelease$qqrv');
if Assigned(Proc) then
Proc;
end;
{The default AllocMem implementation - for older borlndmm.dll libraries that do
not implement this themselves.}
function DefaultAllocMem(Size: NativeInt): Pointer;
begin
Result := SysGetMem(Size);
if (Result <> nil) then
FillChar(Result^, Size, 0);
end;
{The default (do nothing) leak registration function for backward compatibility
with older borlndmm.dll libraries.}
function DefaultRegisterAndUnregisterExpectedMemoryLeak(P: Pointer): boolean;
begin
Result := False;
end;
function SysAllocMem(Size: NativeInt): Pointer;
begin
{Indirect call, because the library may not implement this functionality}
Result := SharedMemoryManager.AllocMem(Size);
end;
function SysRegisterExpectedMemoryLeak(P: Pointer): Boolean;
begin
{Indirect call, because the library may not implement this functionality}
Result := SharedMemoryManager.RegisterExpectedMemoryLeak(P);
end;
function SysUnregisterExpectedMemoryLeak(P: Pointer): Boolean;
begin
{Indirect call, because the library may not implement this functionality}
Result := SharedMemoryManager.UnregisterExpectedMemoryLeak(P);
end;
procedure InitMemoryManager;
var
ProcAddr: Pointer;
MM: Integer;
begin
// force a static reference to borlndmm.dll, so we don't have to LoadLibrary
SharedMemoryManager.GetMem := SysGetMem;
MM := GetModuleHandle(DelphiMM);
{$IFDEF GLOBALALLOC}
SharedMemoryManager.GetMem := xSysGetMem;
SharedMemoryManager.FreeMem := xSysFreeMem;
SharedMemoryManager.ReallocMem := xSysReallocMem;
{$ELSE}
SharedMemoryManager.GetMem := GetProcAddress(MM,'@Borlndmm@SysGetMem$qqri');
SharedMemoryManager.FreeMem := GetProcAddress(MM,'@Borlndmm@SysFreeMem$qqrpv');
SharedMemoryManager.ReallocMem := GetProcAddress(MM, '@Borlndmm@SysReallocMem$qqrpvi');
// Cannot assume that the functions below are implemented. Default handlers are set in initialization section.
ProcAddr := GetProcAddress(MM,'@Borlndmm@SysAllocMem$qqri');
if ProcAddr <> nil then
SharedMemoryManager.AllocMem := ProcAddr;
ProcAddr := GetProcAddress(MM,'@Borlndmm@SysRegisterExpectedMemoryLeak$qqrpi');
if ProcAddr <> nil then
SharedMemoryManager.RegisterExpectedMemoryLeak := ProcAddr;
ProcAddr := GetProcAddress(MM, '@Borlndmm@SysUnregisterExpectedMemoryLeak$qqrpi');
if ProcAddr <> nil then
SharedMemoryManager.UnregisterExpectedMemoryLeak := ProcAddr;
{$ENDIF}
SetMemoryManager(SharedMemoryManager);
end;
initialization
{Set the default handlers for older borlndmm.dll libraries that do not
implement the extended memory manager functionality}
SharedMemoryManager.AllocMem := DefaultAllocMem;
SharedMemoryManager.RegisterExpectedMemoryLeak :=
DefaultRegisterAndUnregisterExpectedMemoryLeak;
SharedMemoryManager.UnregisterExpectedMemoryLeak :=
DefaultRegisterAndUnregisterExpectedMemoryLeak;
HeapAddRef;
if not IsMemoryManagerSet then
InitMemoryManager;
finalization
HeapRelease;
end.
|
unit Test.Script;
interface
uses Windows, TestFrameWork, GMGlobals, Classes, GMSQLQuery, ConnParamsStorage, SysUtils;
type
TScriptTest = class(TTestCase)
private
qpg, qscript: TGMSQLQuery;
params: TZConnectionParams;
procedure RunScript;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure RunScript_TwoTimes();
end;
implementation
const test_db_name = 'gm_db_for_unit_test_1029384756';
{ TScriptTest }
procedure TScriptTest.RunScript();
begin
qscript.Close();
qscript.SQL.LoadFromFile('..\DB\pg_gm_db.sql');
qscript.ExecSQL();
end;
procedure TScriptTest.RunScript_TwoTimes;
begin
RunScript();
RunScript();
Check(true);
end;
procedure TScriptTest.SetUp;
begin
inherited;
params := GlobalSQLConnectionParams();
params.Database := 'postgres';
params.Login := 'postgres';
params.Password := '123';
qpg := TGMSQLQuery.Create(params);
qpg.SQL.Text := 'select * from pg_database where datname = ' + QuotedStr(test_db_name);
qpg.Open();
if not qpg.Eof then
qpg.Execute('drop database ' + test_db_name);
qpg.Execute('create database ' + test_db_name);
qpg.Execute('GRANT ALL ON DATABASE ' + test_db_name + ' TO GROUP "GM_Admin" WITH GRANT OPTION');
params.Database := test_db_name;
qscript := TGMSQLQuery.Create(params);
end;
procedure TScriptTest.TearDown;
begin
inherited;
qscript.Free();
qpg.Execute('drop database ' + test_db_name);
qpg.Free();
end;
initialization
RegisterTest('Script', TScriptTest.Suite);
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLTypes<p>
Defines vector types for geometry only aiming to imply
compatibility of GLScene for Delphi with C+Builder.
Do not include any other units in uses clause <p>
<b>History : </b><font size=-1><ul>
<li>25/04/15 - PW - Added 2D/3D vector and matrix arrays
<li>01/11/13 - PW - Fixed XE5 error: E2376 static can only be used on non-virtual class methods
<li>12/12/12 - PW - Added TGLVector's and TGLMatrix's types
<li>11/11/11 - PW - Creation. Defined TGLPoint, TGLPolygon and TGLPolyhedron types
</ul>
}
unit GLTypes;
interface
//-----------------------
//Point types
//-----------------------
type
PGLPoint2D = ^TGLPoint2D;
TGLPoint2D = record
X: Single;
Y: Single;
public
function Create(X, Y : Single): TGLPoint2D;
procedure SetPosition(const X, Y : Single);
function Add(const APoint2D: TGLPoint2D): TGLPoint2D;
function Length: Single; //distance to origin
function Distance(const APoint2D : TGLPoint2D) : Single;
procedure Offset(const ADeltaX, ADeltaY : Single);
end;
PGLPoint3D = ^TGLPoint3D;
TGLPoint3D = record
X: Single;
Y: Single;
Z: Single;
public
function Create(X, Y, Z: Single): TGLPoint3D;
procedure SetPosition(const X, Y, Z : Single);
function Add(const AGLPoint3D: TGLPoint3D): TGLPoint3D;
function Length: Single; //distance to origin
function Distance(const APoint3D : TGLPoint3D) : Single;
procedure Offset(const ADeltaX, ADeltaY, ADeltaZ : Single);
end;
//Point Arrays
TGLPoint2DArray = array of TGLPoint2D;
TGLPoint3DArray = array of TGLPoint3D;
//-----------------------
//Polygon types
//-----------------------
TGLPolygon2D = TGLPoint2DArray;
TGLPolygon3D = TGLPoint3DArray;
const
ClosedPolygon2D: TGLPoint2D = (X: $FFFF; Y: $FFFF);
ClosedPolygon3D: TGLPoint3D = (X: $FFFF; Y: $FFFF; Z: $FFFF);
//-----------------------
//Polyhedron types
//-----------------------
type
TGLPolyhedron = array of TGLPolygon3D;
//-----------------------
// Vector types
//-----------------------
TGLVector2DType = array [0..1] of Single;
TGLVector3DType = array [0..2] of Single;
TGLVector2D = record
private
function Norm: Single;
public
function Create(const AX, AY, AW : Single): TGLVector2D;
function Add(const AVector2D: TGLVector2D): TGLVector2D;
function Length: Single;
case Integer of
0: (V: TGLVector2DType;);
1: (X: Single;
Y: Single;
W: Single;)
end;
TGLVector3D = record
private
function Norm: Single;
public
function Create(const AX, AY, AZ, AW : Single): TGLVector3D;
function Add(const AVector3D: TGLVector3D): TGLVector3D;
function Length: Single;
case Integer of
0: (V: TGLVector3DType;);
1: (X: Single;
Y: Single;
Z: Single;
W: Single;)
end;
//Vector Arrays
TGLVector2DArray = array of TGLVector2D;
TGLVector3DArray = array of TGLVector3D;
//-----------------------
// Matrix types
//-----------------------
TGLMatrix2DType = array[0..3] of TGLVector2D;
{.$NODEFINE TGLMatrix2DType}
{.$HPPEMIT END OPENNAMESPACE}
{.$HPPEMIT END 'typedef TGLVector2D TGLMatrix2DArray[4];'}
{.$HPPEMIT END CLOSENAMESPACE}
TGLMatrix3DType = array[0..3] of TGLVector3D;
{.$NODEFINE TGLMatrix3DType}
{.$HPPEMIT END OPENNAMESPACE}
{.$HPPEMIT END 'typedef TGLVector3D TGLMatrix3DType[4];'}
{.$HPPEMIT END CLOSENAMESPACE}
TGLMatrix2D = record
private
public
case Integer of
0: (M: TGLMatrix2DType;);
1: (e11, e12, e13: Single;
e21, e22, e23: Single;
e31, e32, e33: Single);
end;
TGLMatrix3D = record
private
public
case Integer of
0: (M: TGLMatrix3DType;);
1: (e11, e12, e13, e14: Single;
e21, e22, e23, e24: Single;
e31, e32, e33, e34: Single;
e41, e42, e43, e44: Single);
end;
//Matrix Arrays
TGLMatrix2DArray = array of TGLMatrix2D;
TGLMatrix3DArray = array of TGLMatrix3D;
//--------------------------
// Mesh simple record types
//--------------------------
type
TGLMesh2DVertex = packed record
X, Y: Single;
NX, NY: Single;
tU, tV: Single;
end;
TGLMesh3DVertex = packed record
X, Y, Z: Single;
NX, NY, NZ: Single;
tU, tV: Single;
end;
TGLMesh2D = array of TGLMesh2DVertex;
TGLMesh3D = array of TGLMesh3DVertex;
//--------------------------
// Quaternion record types
//--------------------------
type
TGLQuaternion = record
ImPart: TGLVector3D;
RePart: Single;
end;
TGLQuaternionArray = array of TGLQuaternion;
type
TGLBox = record
ALeft, ATop, ANear, ARight, ABottom, AFar: Single;
end;
//---------------------------------------------------------------
//---------------------------------------------------------------
//---------------------------------------------------------------
implementation
//---------------------------------------------------------------
//---------------------------------------------------------------
//---------------------------------------------------------------
{ TGLPoint2D }
//
function TGLPoint2D.Create(X, Y : Single): TGLPoint2D;
begin
Result.X := X;
Result.Y := Y;
end;
procedure TGLPoint2D.SetPosition(const X, Y: Single);
begin
Self.X := X;
Self.Y := Y;
end;
function TGLPoint2D.Length: Single;
begin
Result := Sqrt(Self.X * Self.X + Self.Y * Self.Y);
end;
function TGLPoint2D.Add(const APoint2D: TGLPoint2D): TGLPoint2D;
begin
Result.SetPosition(Self.X + APoint2D.X, Self.Y + APoint2D.Y);
end;
function TGLPoint2D.Distance(const APoint2D: TGLPoint2D): Single;
begin
Result := Sqrt(Sqr(Self.X - APoint2D.X) + Sqr(Self.Y - APoint2D.Y));
end;
procedure TGLPoint2D.Offset(const ADeltaX, ADeltaY: Single);
begin
Self.X := Self.X + ADeltaX;
Self.Y := Self.Y + ADeltaY;
end;
{ TGLPoint3D }
//
function TGLPoint3D.Create(X, Y, Z: Single): TGLPoint3D;
begin
Result.X := X;
Result.Y := Y;
Result.Z := Z;
end;
function TGLPoint3D.Add(const AGLPoint3D: TGLPoint3D): TGLPoint3D;
begin
Result.X := Self.X + AGLPoint3D.X;
Result.Y := Self.Y + AGLPoint3D.Y;
Result.Z := Self.Z + AGLPoint3D.Z;
end;
function TGLPoint3D.Distance(const APoint3D: TGLPoint3D): Single;
begin
Result := Self.Length - APoint3D.Length;
end;
function TGLPoint3D.Length: Single;
begin
Result := Sqrt(Self.X * Self.X + Self.Y * Self.Y + Self.Z * Self.Z);
end;
procedure TGLPoint3D.Offset(const ADeltaX, ADeltaY, ADeltaZ: Single);
begin
Self.X := Self.X + ADeltaX;
Self.Y := Self.Y + ADeltaY;
Self.Z := Self.Z + ADeltaZ;
end;
procedure TGLPoint3D.SetPosition(const X, Y, Z: Single);
begin
Self.X := X;
Self.Y := Y;
Self.Z := Z;
end;
{ TGLVector2D }
//
function TGLVector2D.Create(const AX, AY, AW: Single): TGLVector2D;
begin
Result.X := AX;
Result.Y := AY;
Result.W := AW;
end;
function TGLVector2D.Add(const AVector2D: TGLVector2D): TGLVector2D;
begin
Result.X := Self.X + AVector2D.X;
Result.Y := Self.Y + AVector2D.Y;
Result.W := 1.0;
end;
function TGLVector2D.Length: Single;
begin
Result := Sqrt(Self.Norm);
end;
function TGLVector2D.Norm: Single;
begin
Result := (Self.X * Self.X) + (Self.Y * Self.Y);
end;
{ TGLVector3D }
//
function TGLVector3D.Create(const AX, AY, AZ, AW: Single): TGLVector3D;
begin
Result.X := AX;
Result.Y := AY;
Result.Z := AZ;
Result.W := AW;
end;
function TGLVector3D.Add(const AVector3D: TGLVector3D): TGLVector3D;
begin
Result.X := Self.X + AVector3D.X;
Result.Y := Self.Y + AVector3D.Y;
Result.Z := Self.Z + AVector3D.Z;
Result.W := 1.0;
end;
function TGLVector3D.Norm: Single;
begin
Result := (Self.X * Self.X) + (Self.Y * Self.Y) + (Self.Z * Self.Z);
end;
function TGLVector3D.Length: Single;
begin
Result := Sqrt(Self.Norm);
end;
end.
|
unit ncaStrings;
interface
resourcestring
rsSemPermissaoAlterar = 'Você não tem permissão para alterar essa informação';
rsConfirmaExclusao = 'Confirma a exclusão de';
rsDescrObrig = 'É necessário informar a descrição (nome do produto)';
rsCodObrig = 'É necessário informar um código para o produto';
rsPrecoObrig = 'É necessário informar o preço de venda do produto';
rsCodRepetido = 'Já existe um produto cadastrado com esse código';
rsItens = 'itens';
rsItem = 'item';
rsEmailObrigatorio = 'É necessário informar o e-mail para o caso do usuário esquecer sua senha';
rsEmailDif = 'E-mails diferentes. O campo de E-mail e Confirmar E-mail devem conter endereços idênticos';
rsConfirmaExclusaoTrib = 'Deseja realmente apagar a taxa';
rsSomenteAdmin = 'Essa operação é restrita a usuários com direito de administrador do programa Nex';
rsConfirmaTribPadrao = 'Definir %s como padrão?';
rsPadrao = 'Padrão';
rsGrupo = 'Grupo';
rsNomeTribNecessario = 'É necessário informar um nome para essa taxa';
rsMarcarTaxa = 'É necessário marcar as taxas que fazem parte desse grupo';
rsInformarPerc = 'É necessário informar o percentual dessa taxa';
rsValor = 'Valor';
rsCaixa = 'Caixa';
rsConferirMeioPagto = 'Conferir Meio de Pagamento';
rsEstoque = 'Estoque';
rsNome = 'Nome';
rsBairro = 'Bairro';
rsCidade = 'Cidade';
rsCEP = 'CEP';
rsTelefone = 'Telefone';
rsCelular = 'Celular';
rsDocID = 'Num.Ident.';
rsDesconto = 'Desconto';
rsSexo = 'Sexo';
rsTel = 'Telefone';
rsPai = 'Pai';
rsCPF = 'CPF';
rsCNPJ = 'CNPJ';
rsRG = 'RG';
rsIE = 'I.E.';
rsCPF_CNPJ = 'CPF/CNPJ';
rsRG_IE = 'RG/I.E.';
rsFornecedorRepetido = 'Esse fornecedor já está na lista!';
rsFornecedor = 'Fornecedor';
implementation
end.
|
{*******************************************************}
{ }
{ 异步任务处理模式 }
{ }
{ 版权所有 (C) 2016 YangYxd }
{ }
{*******************************************************}
unit UI.Async;
interface
uses
{$IFDEF MSWINDOWS} ActiveX, {$ENDIF}
Classes, SysUtils;
type
TAsync = class;
TExecuteEvent = procedure (Async: TAsync) of object;
TExecuteEventA = reference to procedure (Async: TAsync);
TAsyncThread = class(TThread)
protected
FAsync: TAsync;
procedure Execute; override;
end;
/// <summary>
/// 异步任务处理
/// </summary>
TAsync = class(TObject)
private
function GetComInitialized: Boolean;
protected
FExec: TExecuteEvent;
FExecA: TExecuteEventA;
FComplete: TExecuteEvent;
FCompleteA: TExecuteEventA;
FData: Pointer;
FDataInterface: IInterface;
FMessage: string;
FTag: NativeInt;
{$IFDEF MSWINDOWS}
FComInitialized: Boolean;
{$ENDIF}
protected
function IsNeedExecute: Boolean;
function IsNeedExecuteComplete: Boolean;
procedure DoExecute;
procedure DoExecuteComplete;
public
destructor Destroy; override;
/// <summary>
/// 开始执行
/// </summary>
procedure Execute(); virtual;
procedure Start();
/// <summary>
/// 异步执行过程 (非线程安全)
/// </summary>
function SetExecute(AValue: TExecuteEvent): TAsync; overload;
function SetExecute(AValue: TExecuteEventA): TAsync; overload;
/// <summary>
/// 异步执行完成后需要执行的过程 (线程安全)
/// </summary>
function SetExecuteComplete(AValue: TExecuteEvent): TAsync; overload;
function SetExecuteComplete(AValue: TExecuteEventA): TAsync; overload;
function SetData(const Data: Pointer): TAsync;
function SetDataInterface(const Data: IInterface): TAsync;
function SetMessage(const Data: string): TAsync;
function SetTag(Value: NativeInt): TAsync;
/// <summary>
/// Windows 平台, 需要 Com 支持时调用以实现线程 Com 初始化
/// </summary>
procedure ComNeeded(AInitFlags: Cardinal = 0);
property Data: Pointer read FData write FData;
property DataInterface: IInterface read FDataInterface write FDataInterface;
property Message: string read FMessage write FMessage;
property Tag: NativeInt read FTag write FTag;
property ComInitialized: Boolean read GetComInitialized;
end;
implementation
var
FAsyncRef: Integer = 0; // 异步任务计数器
{ TAsync }
procedure TAsync.ComNeeded(AInitFlags: Cardinal);
begin
{$IFDEF MSWINDOWS}
if not ComInitialized then begin
if AInitFlags = 0 then
CoInitialize(nil)
else
CoInitializeEx(nil, AInitFlags);
FComInitialized := True;
end;
{$ENDIF}
end;
destructor TAsync.Destroy;
begin
{$IFDEF MSWINDOWS}
if ComInitialized then
CoUninitialize;
{$ENDIF}
FDataInterface := nil;
inherited Destroy;
end;
procedure TAsync.DoExecute;
begin
if Assigned(FExecA) then
FExecA(Self)
else if Assigned(FExec) then
FExec(Self);
end;
procedure TAsync.DoExecuteComplete;
begin
if Assigned(FCompleteA) then
FCompleteA(Self)
else if Assigned(FComplete) then
FComplete(Self);
end;
procedure TAsync.Execute;
var
FThread: TAsyncThread;
begin
FThread := TAsyncThread.Create(True);
FThread.FreeOnTerminate := True;
FThread.FAsync := Self;
FThread.Start;
end;
function TAsync.GetComInitialized: Boolean;
begin
{$IFDEF MSWINDOWS}
Result := FComInitialized;
{$ELSE}
Result := True;
{$ENDIF}
end;
function TAsync.IsNeedExecute: Boolean;
begin
Result := Assigned(FExec) or Assigned(FExecA);
end;
function TAsync.IsNeedExecuteComplete: Boolean;
begin
Result := Assigned(FComplete) or Assigned(FCompleteA);
end;
function TAsync.SetData(const Data: Pointer): TAsync;
begin
Result := Self;
FData := Data;
end;
function TAsync.SetDataInterface(const Data: IInterface): TAsync;
begin
Result := Self;
FDataInterface := Data;
end;
function TAsync.SetExecute(AValue: TExecuteEvent): TAsync;
begin
Result := Self;
FExec := AValue;
end;
function TAsync.SetExecute(AValue: TExecuteEventA): TAsync;
begin
Result := Self;
FExecA := AValue;
end;
function TAsync.SetExecuteComplete(AValue: TExecuteEvent): TAsync;
begin
Result := Self;
FComplete := AValue;
end;
function TAsync.SetExecuteComplete(AValue: TExecuteEventA): TAsync;
begin
Result := Self;
FCompleteA := AValue;
end;
function TAsync.SetMessage (const Data: string): TAsync;
begin
Result := Self;
FMessage := Data;
end;
function TAsync.SetTag(Value: NativeInt): TAsync;
begin
Result := Self;
FTag := Value;
end;
procedure TAsync.Start;
begin
AtomicIncrement(FAsyncRef);
Execute;
end;
{ TAsyncThread }
procedure TAsyncThread.Execute;
begin
if Assigned(FAsync) then begin
try
try
// 先执行异步任务
FAsync.DoExecute;
except
end;
try
// 然后执行同步任务
if FAsync.IsNeedExecuteComplete then
Synchronize(Self, FAsync.DoExecuteComplete);
except
end;
finally
FAsync.DisposeOf;
FAsync := nil;
AtomicDecrement(FAsyncRef);
end;
end;
end;
// 等待所有线程关闭
procedure WaitAsyncFinish(const ATimeout: Cardinal = 5000);
var
T: Cardinal;
begin
T := TThread.GetTickCount;
while AtomicDecrement(FAsyncRef) >= 0 do begin
AtomicIncrement(FAsyncRef);
Sleep(20);
if TThread.GetTickCount - T > ATimeout then
Break;
end;
end;
initialization
finalization
WaitAsyncFinish();
end.
|
{$i deltics.unicode.inc}
unit Deltics.Unicode.Exceptions;
interface
uses
Classes,
SysUtils,
Deltics.Unicode.BOM,
Deltics.Unicode.Types;
type
EUnicode = class(Exception)
public
constructor Create(const aMessage: String; const aArgs: array of const); overload;
end;
EUnicodeDataloss = class(EUnicode);
EUnicodeRequiresMultibyte = class(EUnicode);
EUnicodeOrphanSurrogate = class(EUnicode);
EInvalidCodepoint = class(EUnicode)
public
constructor Create(const aCodepoint: Codepoint); overload;
end;
EInvalidSurrogate = class(EUnicode);
EInvalidHiSurrogate = class(EInvalidSurrogate);
EInvalidLoSurrogate = class(EInvalidSurrogate);
EInvalidEncoding = class(EUnicode); // An operation expecting a specific encoding encountered an incorrect encoding
EMoreData = class(EUnicode); // Data was provided but the requested operation needs more data
ENoData = class(EUnicode); // Data was expected/required but none was provided
implementation
uses
Deltics.Unicode;
{ EUnicode }
constructor EUnicode.Create(const aMessage: String;
const aArgs: array of const);
begin
inherited CreateFmt(aMessage, aArgs);
end;
{ EInvalidCodepoint }
constructor EInvalidCodepoint.Create(const aCodepoint: Codepoint);
begin
inherited Create('%s is not a valid codepoint', [Unicode.Ref(aCodepoint)]);
end;
end.
|
unit ncDebito;
{
ResourceString: Dario 12/03/13
}
interface
uses
SysUtils,
DB,
Classes,
Windows,
ClasseCS,
ncEspecie,
ncClassesBase;
type
TncItemDebito = class
private
function GetString: String;
procedure SetString(const Value: String);
public
idID : Integer;
idTran : Cardinal;
idCaixa : Cardinal;
idDataHora : TDateTime;
idDataCompra: TDateTime;
idTipoItem : Byte;
idItemID : Cardinal;
idItemPos : Byte;
idTotal : Currency;
idDesconto : Currency;
idPago : Currency;
idCancelado : Boolean;
_Operacao : Byte;
constructor Create;
procedure Limpa;
procedure AssignFrom(B: TncItemDebito);
function Igual(B: TncItemDebito): Boolean;
function ValorPagar: Currency;
procedure SaveToITran(D: TDataset);
procedure LoadFromITran(D: TDataset);
procedure LoadFromDebito(D: TDataset);
property AsString: String
read GetString write SetString;
end;
TncItensDebito = class
private
FItens : TList;
function GetItem(I: Integer): TncItemDebito;
function GetString: String;
procedure SetString(Value: String);
public
constructor Create;
destructor Destroy; override;
procedure Remove(IME: TncItemDebito);
procedure Delete(aIndex: Integer);
procedure Limpa;
function Count: Integer;
function NewItem: TncItemDebito;
function GetItemByID(aID: Integer): TncItemDebito;
function GetItemByTran(aTran: Integer): TncItemDebito;
property Itens[I: Integer]: TncItemDebito
read GetItem; Default;
property AsString: String
read GetString write SetString;
end;
TncDebito = class (TClasseCS)
private
FID : Integer;
FUID : TGuid;
FDataHora : TDateTime;
FCliente : Integer;
FFunc : String;
FTotal : Currency;
FDesconto : Currency;
FDescPerc : Double;
FDescPorPerc : Boolean;
FPago : Currency;
FObs : String;
FCancelado : Boolean;
FCanceladoPor: String;
FCanceladoEm : TDateTime;
FCaixa : Integer;
FNomeCliente : String;
FOperacao : Byte;
FRecibo : Boolean;
FPagEspecies : TncPagEspecies;
FItens : TncItensDebito;
FPagEsp: TncPagEspecies;
function GetStrItens: String;
procedure SetStrItens(const Value: String);
procedure SetCaixa(const Value: Integer);
procedure SetCancelado(const Value: Boolean);
procedure SetID(const Value: Integer);
function GetPagEspStr: String;
procedure SetPagEspStr(const Value: String);
function GetUID: String;
procedure SetUID(const Value: String);
protected
function GetChave: Variant; override;
public
constructor Create;
destructor Destroy; override;
procedure Limpa;
procedure SalvaDescPago;
function NativeGuid: TGuid;
procedure CreateGuid;
property PagEsp: TncPagEspecies read FPagEsp;
property Itens: TncItensDebito read FItens;
published
property ID : Integer
read FID write SetID;
property UID : String
read GetUID write SetUID;
property DataHora : TDateTime
read FDataHora write FDataHora;
property Cliente : Integer
read FCliente write FCliente;
property Func : String
read FFunc write FFunc;
property Total : Currency
read FTotal write FTotal;
property Desconto : Currency
read FDesconto write FDesconto;
property DescPerc: Double
read FDescPerc write FDescPerc;
property DescPorPerc: Boolean
read FDescPorPerc write FDescPorPerc;
property Pago : Currency
read FPago write FPago;
property Obs : String
read FObs write FObs;
property Cancelado : Boolean
read FCancelado write SetCancelado;
property CanceladoPor : String
read FCanceladoPor write FCanceladoPor;
property CanceladoEm : TDateTime
read FCanceladoEm write FCanceladoEm;
property Caixa : Integer
read FCaixa write SetCaixa;
property NomeCliente : String
read FNomeCliente write FNomeCliente;
property Operacao: Byte
read FOperacao write FOperacao;
property Recibo : Boolean
read FRecibo write FRecibo;
property PagEspStr: String
read GetPagEspStr write SetPagEspStr;
property StrItens: String
read GetStrItens write SetStrItens;
end;
implementation
uses ncGuidUtils;
{ TncItemDebito }
procedure TncItemDebito.AssignFrom(B: TncItemDebito);
begin
idID := B.idID;
idTran := B.idTran;
idCaixa := B.idCaixa;
idDataHora := B.idDataHora;
idDataCompra:= B.idDataCompra;
idTipoItem := B.idTipoItem;
idItemID := B.idItemID;
idItemPos := B.idItemPos;
idTotal := B.idTotal;
idDesconto := B.idDesconto;
idPago := B.idPago;
idCancelado := B.idCancelado;
_Operacao := B._Operacao;
end;
constructor TncItemDebito.Create;
begin
Limpa;
end;
function TncItemDebito.GetString: String;
begin
Result :=
IntToStr(idID) + sFlddelim(classid_TncItemDebito) +
IntToStr(idTran) + sFlddelim(classid_TncItemDebito) +
IntToStr(idCaixa) + sFldDelim(classid_TncItemDebito) +
GetDTStr(idDataHora) + sFldDelim(classid_TncItemDebito) +
GetDTStr(idDataCompra) + sFldDelim(classid_TncItemDebito) +
IntToStr(idTipoItem) + sFldDelim(classid_TncItemDebito) +
IntToStr(idItemID) + sFldDelim(classid_TncItemDebito) +
IntToStr(idItemPos) + sFldDelim(classid_TncItemDebito) +
FloatParaStr(idTotal) + sFldDelim(classid_TncItemDebito) +
FloatParaStr(idDesconto) + sFldDelim(classid_TncItemDebito) +
FloatParaStr(idPago) + sFldDelim(classid_TncItemDebito) +
BoolStr[idCancelado] + sFldDelim(classid_TncItemDebito) +
IntToStr(_Operacao) + sFldDelim(classid_TncItemDebito);
end;
function TncItemDebito.Igual(B: TncItemDebito): Boolean;
begin
Result := False;
if idID <> B.idID then Exit;
if idTran <> B.idTran then Exit;
if idCaixa <> B.idCaixa then Exit;
if idDataHora <> B.idDataHora then Exit;
if idDataCompra <> B.idDataCompra then Exit;
if idTipoItem <> B.idTipoItem then Exit;
if idItemID <> B.idItemID then Exit;
if idItemPos <> B.idItemPos then Exit;
if idTotal <> B.idTotal then Exit;
if idDesconto <> B.idDesconto then Exit;
if idPago <> B.idPago then Exit;
if idCancelado <> B.idCancelado then Exit;
Result := True;
end;
procedure TncItemDebito.Limpa;
begin
idID := -1;
idTran := 0;
idCaixa := 0;
idDataHora := 0;
idDataCompra := 0;
idTipoItem := 0;
idItemID := 0;
idItemPos := 0;
idTotal := 0;
idDesconto := 0;
idPago := 0;
idCancelado := False;
_Operacao := osNenhuma;
end;
procedure TncItemDebito.LoadFromDebito(D: TDataset);
begin
idID := -1;
idTran := 0;
idCaixa := 0;
idDataHora := 0;
idDataCompra := 0;
idTipoItem := D.FieldByName('Tipo').AsInteger;
idItemID := D.FieldByName('ID').AsInteger;
idDataCompra := D.FieldByName('Data').AsDateTime;
idItemPos := 0;
idTotal := D.FieldByName('Valor').AsCurrency; // do not localize
idDesconto := 0;
idPago := 0;
idCancelado := False;
end;
procedure TncItemDebito.LoadFromITran(D: TDataset);
begin
idID := D.FieldByName('ID').AsInteger; // do not localize
idTran := D.FieldByName('Tran').AsInteger; // do not localize
idCaixa := D.FieldByName('Caixa').AsInteger; // do not localize
idDataHora := D.FieldByName('DataHora').AsDateTime; // do not localize
idTipoItem := D.FieldByName('TipoItem').AsInteger; // do not localize
idItemID := D.FieldByName('ItemID').AsInteger; // do not localize
idItemPos := D.FieldByName('ItemPos').AsInteger; // do not localize
idTotal := D.FieldByName('Total').AsCurrency; // do not localize
idDesconto := D.FieldByName('Desconto').AsCurrency; // do not localize
idPago := D.FieldByName('Pago').AsCurrency; // do not localize
idCancelado := D.FieldByName('Cancelado').AsBoolean; // do not localize
end;
procedure TncItemDebito.SaveToITran(D: TDataset);
begin
D.FieldByName('Tran').AsInteger := idTran; // do not localize
D.FieldByName('Caixa').AsInteger := idCaixa ; // do not localize
D.FieldByName('Sessao').AsInteger := 0; // do not localize
D.FieldByName('DataHora').AsDateTime := idDataHora; // do not localize
D.FieldByName('TipoTran').AsInteger := trPagDebito; // do not localize
D.FieldByName('TipoItem').AsInteger := idTipoItem; // do not localize
D.FieldByName('ItemID').AsInteger := idItemID; // do not localize
D.FieldByName('ItemPos').AsInteger := idItemPos; // do not localize
D.FieldByName('Total').AsCurrency := idTotal; // do not localize
D.FieldByName('Desconto').AsCurrency := idDesconto; // do not localize
D.FieldByName('Pago').AsCurrency := idPago; // do not localize
D.FieldByName('Cancelado').AsBoolean := idCancelado; // do not localize
end;
procedure TncItemDebito.SetString(const Value: String);
var
S, Str: String;
I64 : Int64;
function pCampo: String;
begin
Result := GetNextStrDelim(S, classid_TncItemDebito);
end;
begin
S := Value;
idID := StrToIntDef(pCampo, -1);
idTran := StrToIntDef(pCampo, 0);
idCaixa := StrToIntDef(pCampo, 0);
idDataHora := DTFromStr(pCampo);
idDataCompra := DTFromStr(pCampo);
idTipoItem := StrToIntDef(pCampo, 0);
Str := pCampo;
I64 := StrToInt64Def(Str, 0);
idItemID := I64;
idItemPos := StrToIntDef(pCampo, 0);
idTotal := StrParaFloat(pCampo);
idDesconto := StrParaFloat(pCampo);
idPago := StrParaFloat(pCampo);
idCancelado := (pCampo = BoolStr[True]);
_Operacao := StrToIntDef(pCampo, 0);
end;
function TncItemDebito.ValorPagar: Currency;
begin
Result := idTotal - idDesconto;
end;
{ TncItensDebito }
function TncItensDebito.Count: Integer;
begin
Result := FItens.Count;
end;
constructor TncItensDebito.Create;
begin
FItens := TList.Create;
end;
procedure TncItensDebito.Delete(aIndex: Integer);
begin
FItens.Delete(aIndex);
end;
destructor TncItensDebito.Destroy;
begin
Limpa;
FItens.Free;
inherited;
end;
function TncItensDebito.GetItem(I: Integer): TncItemDebito;
begin
Result := TncItemDebito(FItens[I]);
end;
function TncItensDebito.GetItemByID(aID: Integer): TncItemDebito;
var i: Integer;
begin
for i := 0 to Count-1 do
if aID = Itens[I].idID then begin
Result := Itens[i];
Exit;
end;
Result := nil;
end;
function TncItensDebito.GetItemByTran(aTran: Integer): TncItemDebito;
var i: Integer;
begin
for i := 0 to Count-1 do
if aTran = Itens[I].idTran then begin
Result := Itens[i];
Exit;
end;
Result := nil;
end;
function TncItensDebito.GetString: String;
var i: Integer;
begin
Result := '';
for I := 0 to Count - 1 do
Result := Result + Itens[i].AsString + sListaDelim(classid_TncItensDebito);
end;
procedure TncItensDebito.Limpa;
begin
while Count>0 do begin
Itens[0].Free;
FItens.Delete(0);
end;
end;
function TncItensDebito.NewItem: TncItemDebito;
begin
Result := TncItemDebito.Create;
FItens.Add(Result);
end;
procedure TncItensDebito.Remove(IME: TncItemDebito);
begin
FItens.Remove(IME);
end;
procedure TncItensDebito.SetString(Value: String);
var S: String;
begin
while GetNextListItem(Value, S, classid_TncItensDebito) do
NewItem.AsString := S;
end;
{ TncDebito }
constructor TncDebito.Create;
begin
inherited;
FItens := TncItensDebito.Create;
FPagEsp := TncPagEspecies.Create;
Limpa;
end;
procedure TncDebito.CreateGuid;
begin
FUID := TGuidEx.NewGuid;
end;
destructor TncDebito.Destroy;
begin
Limpa;
FPagEsp.Free;
FItens.Free;
inherited;
end;
function TncDebito.GetChave: Variant;
begin
Result := FID;
end;
function TncDebito.GetPagEspStr: String;
begin
Result := FPagEsp.AsString;
end;
function TncDebito.GetStrItens: String;
begin
Result := FItens.AsString;
end;
function TncDebito.GetUID: String;
begin
Result := TGuidEx.ToString(FUID);
end;
procedure TncDebito.Limpa;
begin
FID := -1;
FUID := TGuidEx.EmptyGuid;
FDataHora := 0;
FCliente := 0;
FFunc := '';
FTotal := 0;
FDesconto := 0;
FDescperc := 0;
FDescPorPerc := False;
FPago := 0;
FObs := '';
FCancelado := False;
FCanceladoPor:= '';
FCanceladoEm := 0;
FCaixa := 0;
FNomeCliente := '';
FOperacao := osNenhuma;
FRecibo := False;
FItens.Limpa;
FPagEsp.Clear;
end;
function TncDebito.NativeGuid: TGuid;
begin
Result := FUID;
end;
procedure TncDebito.SalvaDescPago;
var
vPago, vDesc : Currency;
I : Integer;
begin
vPago := Pago;
vDesc := Desconto;
for I := 0 to Itens.Count - 1 do
with Itens[I] do begin
if vDesc>idTotal then begin
idDesconto := idTotal;
vDesc := vDesc - idTotal;
end else begin
idDesconto := vDesc;
vDesc := 0;
end;
if vPago>=ValorPagar then
idPago := ValorPagar else
idPago := vPago;
vPago := vPago - idPago;
end;
end;
procedure TncDebito.SetCaixa(const Value: Integer);
var i: Integer;
begin
FCaixa := Value;
for I := 0 to Itens.Count - 1 do
Itens[I].idCaixa := Value;
end;
procedure TncDebito.SetCancelado(const Value: Boolean);
var I: Integer;
begin
FCancelado := Value;
for I := 0 to Itens.Count - 1 do
Itens[I].idCancelado := Value;
end;
procedure TncDebito.SetID(const Value: Integer);
var
I: Integer;
begin
FID := Value;
for I := 0 to Itens.Count - 1 do
Itens[I].idTran := Value;
end;
procedure TncDebito.SetPagEspStr(const Value: String);
begin
FPagEsp.AsString := Value;
end;
procedure TncDebito.SetStrItens(const Value: String);
begin
FItens.AsString := Value;
end;
procedure TncDebito.SetUID(const Value: String);
begin
FUID := TGuidEx.FromString(Value);
end;
end.
|
(* ukeys.pas -- (c) 1989 by Tom Swan *)
unit ukeys;
interface
uses crt;
function getKey : char;
function keyWaiting : Boolean;
procedure pushKey( ch : char );
implementation
const
NULL = #0; { ASCII NULL character }
pushedChar : char = NULL; { Saved char from pushKey procedure }
{ ----- Return next keyboard or pushed character. }
function getKey : char;
begin
if pushedChar <> NULL then
begin
getKey := pushedChar;
pushedChar := NULL;
end else
getKey := ReadKey;
end;
{ ----- Return true if a character is waiting to be read. }
function keyWaiting : Boolean;
begin
keyWaiting := keypressed or ( pushedChar <> NULL );
end; { keyWaiting }
{ ----- Push a character back "into" the keyboard. }
procedure pushKey( ch : char );
begin
pushedChar := ch;
end;
end.
|
{===============================================================================
Copyright(c) 2007-2009, 北京北研兴电力仪表有限责任公司
All rights reserved.
错误接线,向量图绘制单元
+ TWE_PHASE_MAP 向量图绘制
+ TWE_PHASE_MAP_COLOR 色彩索引
===============================================================================}
unit U_WE_PHASE_MAP;
interface
uses SysUtils, Classes, Windows, Graphics, U_WE_EQUATION_DRAW, U_WE_EQUATION,
U_WIRING_ERROR, U_WE_EQUATION_MATH, U_WE_EXPRESSION, system.UITypes, System.Types;
type
/// <summary>
/// 色彩索引
/// </summary>
TWE_PHASE_MAP_COLOR = record
Background : Integer; // 向量图 底色
DotLine : Integer; // 向量图 虚轴颜色
PhaseLine : Integer; // 向量图 三线 相线颜色
PhaseAB : Integer; // 向量图 三线 第一元件
PhaseCB : Integer; // 向量图 三线 第二元件
PhaseA : Integer; // 向量图 四线 第一元件
PhaseB : Integer; // 向量图 四线 第二元件
PhaseC : Integer; // 向量图 四线 第三元件
EquationBackground : Integer; // 公式 底色
EquationFont : Integer; // 公式 字体颜色
end;
var
PhaseMapColor : TWE_PHASE_MAP_COLOR;
type
/// <summary>
/// 向量图
/// </summary>
TWE_PHASE_MAP = class( TComponent )
private
FMapCenter : TPoint;
FCanvas : TCanvas;
FRect : TRect;
FMapColor : TWE_PHASE_MAP_COLOR;
FUnitStep : Integer;
FPenWidth : Integer;
FEquationDraw : TWE_EQUATION_DRAW;
FUIAngle: Double;
FDefMapColor: TWE_PHASE_MAP_COLOR;
procedure SetUIAngle(const Value: Double);
procedure SetDefMapColor(const Value: TWE_PHASE_MAP_COLOR);
protected
/// <summary>
/// 画背景
/// </summary>
procedure DrawBackground( AHasCrossLine, AHasBorder : Boolean );
/// <summary>
/// 画矢量线
/// </summary>
procedure DrawLine( APen : TPen; APos : TPoint; ALen, AAngle : Double;
AHasArrow : Boolean; ASign : string );
/// <summary>
/// 画角度
/// </summary>
procedure DrawAngle( APen : TPen; APos : TPoint;
ARadius, AStartAngle, AEndAngle : Double; AHasArrow : Boolean; ASign : string );
/// <summary>
/// 画箭头
/// </summary>
procedure DrawArrow( APen : TPen; APos : TPoint; AAngle : Double );
protected
/// <summary>
/// 角度转换, 公式和画图的角度不同,需要转换
/// </summary>
function CovAngle( AValue : Double ) : Double;
/// <summary>
/// 画独立元件
/// </summary>
procedure DrawSingleEquation( APhaseEquation : TWE_PHASE_EXPRESSION;
APen : TPen; APos : TPoint; AAngleRadius : Double );
/// <summary>
/// 画向量图
/// </summary>
procedure DrawPhase3Map( AEquation : TWE_EQUATION );
procedure DrawPhase4Map( AEquation : TWE_EQUATION );
procedure DrawPhase2Map( AEquation : TWE_EQUATION );
public
/// <summary>
/// 画布
/// </summary>
property Canvas : TCanvas read FCanvas write FCanvas;
/// <summary>
/// 绘图的区域
/// </summary>
property Rect : TRect read FRect write FRect;
/// <summary>
/// 颜色索引
/// </summary>
property MapColor : TWE_PHASE_MAP_COLOR read FMapColor write FMapColor;
/// <summary>
/// 默认颜色索引
/// </summary>
property DefMapColor : TWE_PHASE_MAP_COLOR read FDefMapColor write SetDefMapColor;
/// <summary>
/// 单位长度
/// </summary>
property UnitStep : Integer read FUnitStep write FUnitStep;
/// <summary>
/// 画笔宽度
/// </summary>
property PenWidth : Integer read FPenWidth write FPenWidth;
/// <summary>
/// UI夹角
/// </summary>
property UIAngle : Double read FUIAngle write SetUIAngle;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>
/// 绘制向量图
/// </summary>
procedure DrawPhaseMap( AEquation : TWE_EQUATION ; sCaption : string='');
end;
implementation
{ TWE_PHASE_MAP }
function TWE_PHASE_MAP.CovAngle(AValue: Double): Double;
begin
if AValue >= -90 then
Result := (90 - AValue) / 180 * Pi
else
Result := (- AValue - 270) / 180 * Pi;
end;
constructor TWE_PHASE_MAP.Create(AOwner: TComponent);
begin
inherited;
FEquationDraw := TWE_EQUATION_DRAW.Create( nil );
with FDefMapColor do
begin
Background := clWhite ;
DotLine := $00D1D1D1;
PhaseLine := $005E5E5E;
PhaseAB := $003D9DFE;
PhaseCB := clRed ;
PhaseA := $003D9DFE;
PhaseB := $00009700;
PhaseC := clRed ;
EquationBackground := clWhite ;
EquationFont := clBlack ;
end;
FMapColor := FDefMapColor;
// PhaseMapColor := FDefMapColor;
FUIAngle := 20;
end;
destructor TWE_PHASE_MAP.Destroy;
begin
FEquationDraw.Free;
inherited;
end;
procedure TWE_PHASE_MAP.DrawAngle(APen: TPen; APos: TPoint; ARadius,
AStartAngle, AEndAngle: Double; AHasArrow: Boolean; ASign: string);
var
apPoint : array of TPoint;
// pSign : TPoint;
dAngle : Double;
i : Integer;
pO : TPoint;
begin
if AStartAngle > AEndAngle then
begin
dAngle := AStartAngle;
AStartAngle := AEndAngle;
AEndAngle := dAngle;
end;
SetLength(apPoint, 0);
pO := APos;
if AEndAngle - AStartAngle < Pi then
begin
for i := Round(AStartAngle * 90) to Round(AEndAngle * 90) do
begin
SetLength(apPoint, Length(apPoint)+1);
apPoint[High(apPoint)].X := pO.X + Round(ARadius * FUnitStep * Sin(i / 90));
apPoint[High(apPoint)].Y := pO.Y - Round(ARadius * FUnitStep * Cos(i / 90));
end;
end
else
begin
for i := Round(AEndAngle * 90) to Round(Pi * 90) do
begin
SetLength(apPoint, Length(apPoint)+1);
apPoint[High(apPoint)].X := pO.X + Round(ARadius * FUnitStep * Sin(i / 90));
apPoint[High(apPoint)].Y := pO.Y - Round(ARadius * FUnitStep * Cos(i / 90));
end;
for i := Round(- Pi * 90) to Round(AStartAngle * 90) do
begin
SetLength(apPoint, Length(apPoint)+1);
apPoint[High(apPoint)].X := pO.X + Round(ARadius * FUnitStep * Sin(i / 90));
apPoint[High(apPoint)].Y := pO.Y - Round(ARadius * FUnitStep * Cos(i / 90));
end;
end;
// 画曲线
with FCanvas do
begin
Pen := APen;
Polyline(apPoint);
end;
// 画箭头
if AHasArrow then
begin
if AEndAngle - AStartAngle < Pi then
begin
if Length(apPoint) > 2000 / FUnitStep then
begin
DrawArrow( APen, apPoint[0], AStartAngle - Pi/2 );
DrawArrow( APen, apPoint[High(apPoint)], AEndAngle + Pi/2 );
end;
end
else
begin
if Length(apPoint) > 2000 / FUnitStep then
begin
DrawArrow( APen, apPoint[0], AEndAngle - Pi / 2 );
DrawArrow( APen, apPoint[High(apPoint)], AStartAngle + Pi/2 );
end;
end;
end;
// // 确定标注的位置
// if AEndAngle - AStartAngle < Pi then
// begin
// dAngle := (AEndAngle + AStartAngle) / 2;
// end
// else
// begin
// dAngle := Pi - (AEndAngle + AStartAngle) / 2;
// end;
// if FUnitStep < 100 then
// begin
// if dAngle > 3 * Pi / 4 then
// begin
// pSign.X := pSign.X - 4 * (Length(ASign) - 2);
// pSign.Y := pSign.Y + 3;
// end
// else if dAngle > Pi / 2 then
// begin
// pSign.X := pSign.X + 5;
// pSign.Y := pSign.Y - 5;
// end
// else if dAngle > Pi / 4 then
// begin
// pSign.X := pSign.X + 5 ;
// pSign.Y := pSign.Y - 15;
// end
// else if dAngle > - Pi / 4 then
// begin
// pSign.X := pSign.X - 3 * (Length(ASign) - 2);
// pSign.Y := pSign.Y - 20;
// end
// else if dAngle > - Pi / 2 then
// begin
// pSign.X := pSign.X - 8 * (Length(ASign) - 2);
// pSign.Y := pSign.Y - 10;
// end
// else if dAngle > - 3 * Pi / 4 then
// begin
// pSign.X := pSign.X - 9 * (Length(ASign) - 2);
// pSign.Y := pSign.Y - 7;
// end
// else if dAngle > - Pi then
// begin
// pSign.X := pSign.X - 6 * (Length(ASign) - 2);
// pSign.Y := pSign.Y + 5;
// end;
// end
// else
// begin
// if dAngle > 3 * Pi / 4 then
// begin
// pSign.X := pSign.X - 4 * (Length(ASign) - 2);
// pSign.Y := pSign.Y + 3;
// end
// else if dAngle > Pi / 2 then
// begin
// pSign.X := pSign.X + 3;
// pSign.Y := pSign.Y - 1;
// end
// else if dAngle > Pi / 4 then
// begin
// pSign.X := pSign.X + 5 ;
// pSign.Y := pSign.Y - 15;
// end
// else if dAngle > - Pi / 4 then
// begin
// pSign.X := pSign.X - 3 * (Length(ASign) - 2);
// pSign.Y := pSign.Y - 25;
// end
// else if dAngle > - Pi / 2 then
// begin
// pSign.X := pSign.X - 10 * (Length(ASign) - 2);
// pSign.Y := pSign.Y - 18;
// end
// else if dAngle > - 3 * Pi / 4 then
// begin
// pSign.X := pSign.X - 11 * (Length(ASign) - 2);
// pSign.Y := pSign.Y - 5;
// end
// else if dAngle > - Pi then
// begin
// pSign.X := pSign.X - 6 * (Length(ASign) - 2);
// pSign.Y := pSign.Y + 5;
// end;
// end;
end;
procedure TWE_PHASE_MAP.DrawArrow(APen: TPen; APos: TPoint; AAngle: Double);
var
pArw : TPoint;
dPosX, dPosY : Double;
begin
with FCanvas do
begin
Pen := APen;
// 确定箭头大小
if FUnitStep / 30 > 2 then
dPosX := - FUnitStep / 30
else
dPosX := -2;
dPosY := dPosX * 2;
pArw.X := APos.X + Round(dPosY * Sin(AAngle) + dPosX * Cos(AAngle));
pArw.Y := APos.Y - Round(dPosY * Cos(AAngle) - dPosX * Sin(AAngle));
Polyline( [ APos, pArw ] );
dPosX := - dPosX;
pArw.X := APos.X + Round(dPosY * Sin(AAngle) + dPosX * Cos(AAngle));
pArw.Y := APos.Y - Round(dPosY * Cos(AAngle) - dPosX * Sin(AAngle));
Polyline( [ APos, pArw ] );
end;
end;
procedure TWE_PHASE_MAP.DrawBackground(AHasCrossLine, AHasBorder: Boolean);
var
pO, pLen : TPoint;
begin
if not Assigned( FCanvas ) then
Exit;
with FCanvas do
begin
Brush.Color := FMapColor.Background;
Brush.Style := bsSolid;
FillRect( FRect );
// 画交叉坐标,田字格
if AHasCrossLine then
begin
Pen.Color := FMapColor.DotLine;
Pen.Style := psDot;
Pen.Width := FPenWidth;
pO.X := ( FRect.Right + FRect.Left ) div 2;
pO.Y := ( FRect.Bottom + FRect.Top ) div 2;
pLen := Point( Round( 0.9 * ( FRect.Right - FRect.Left ) / 2 ),
Round( 0.9 * ( FRect.Bottom - FRect.Top ) / 2 ) );
Rectangle( pO.X - pLen.X, pO.Y - pLen.Y, pO.X + pLen.X, pO.Y + pLen.Y );
MoveTo( pO.X - pLen.X, pO.Y );
LineTo( pO.X + pLen.X, pO.Y );
MoveTo( pO.X, pO.Y - pLen.Y );
LineTo( pO.X, pO.Y + pLen.Y );
end;
// 画边界
if AHasBorder then
begin
Pen.Color := FMapColor.DotLine;
Pen.Style := psSolid;
Pen.Width := FPenWidth;
Brush.Style := bsClear;
Rectangle( FRect );
end;
end;
end;
procedure TWE_PHASE_MAP.DrawLine(APen: TPen; APos: TPoint; ALen, AAngle: Double;
AHasArrow: Boolean; ASign: string);
var
pEnd : TPoint;
pArw : TPoint;
begin
// 计算 终点 位置
pEnd.X := APos.X + Round( FUnitStep * ALen * Sin( AAngle ) );
pEnd.Y := APos.Y - Round( FUnitStep * ALen * Cos( AAngle ) );
// 画线
with FCanvas do
begin
Pen := APen;
Polyline( [ APos, pEnd ] );
// 画箭头
if AHasArrow then
DrawArrow( APen, pEnd, AAngle );
end;
if ASign <> '' then
begin
if AAngle > 3 * Pi / 4 then // 第四相线
begin
pArw.X := pEnd.X + FUnitStep div 15;
pArw.Y := pEnd.Y - FUnitStep div 10;
end
else if AAngle > Pi / 2 then
begin
pArw.X := pEnd.X + FUnitStep div 15;
pArw.Y := pEnd.Y - FUnitStep div 8;
end
else if AAngle > Pi / 4 then // 第一相线
begin
pArw.X := pEnd.X + FUnitStep div 15;
pArw.Y := pEnd.Y - FUnitStep div 10;
end
else if AAngle > 0 then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 30 );
pArw.Y := pEnd.Y - Round( FUnitStep / 3.5 );
end
else if AAngle > - Pi / 4 then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 30 );
pArw.Y := pEnd.Y - Round( FUnitStep / 3.5 );
end
else if AAngle > - Pi / 2.5 then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
pArw.Y := pEnd.Y - FUnitStep div 8;
end
else if AAngle > - Pi / 2 then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
pArw.Y := pEnd.Y - FUnitStep div 8;
end
else if AAngle > - 3 * Pi / 4 then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
pArw.Y := pEnd.Y - FUnitStep div 8;
end
else if AAngle > - Pi then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
pArw.Y := pEnd.Y + FUnitStep div 15;
end;
FEquationDraw.DrawText( FCanvas, pArw, ASign, APen.Color,
FMapColor.Background, FUnitStep / 75 );
end;
end;
procedure TWE_PHASE_MAP.DrawPhase2Map(AEquation: TWE_EQUATION);
begin
FCanvas.Pen.Style := psSolid;
FCanvas.Pen.Width := FPenWidth;
FCanvas.Pen.Color := FMapColor.PhaseA;
DrawSingleEquation( AEquation.GetPhaseEquation( 0 ), FCanvas.Pen, FMapCenter, 0.3 );
end;
procedure TWE_PHASE_MAP.DrawPhase3Map( AEquation : TWE_EQUATION );
begin
// 画 线电压
with FCanvas do
begin
Pen.Style := psSolid;
Pen.Color := FMapColor.PhaseLine;
Pen.Width := FPenWidth;
DrawLine( Pen, FMapCenter, 1, CovAngle(90) , True, DotVar( 'U' ) + SuffixVar( C_EQ_SIGN_A ) );
DrawLine( Pen, FMapCenter, 1, CovAngle(-30) , True, DotVar( 'U' ) + SuffixVar( C_EQ_SIGN_B ) );
DrawLine( Pen, FMapCenter, 1, CovAngle(-150), True, DotVar( 'U' ) + SuffixVar( C_EQ_SIGN_C ) );
end;
FCanvas.Pen.Color := FMapColor.PhaseAB;
DrawSingleEquation( AEquation.GetPhaseEquation( 0 ), FCanvas.Pen, FMapCenter, 0.3 );
FCanvas.Pen.Color := FMapColor.PhaseCB;
DrawSingleEquation( AEquation.GetPhaseEquation( 1 ), FCanvas.Pen, FMapCenter, 0.4 );
end;
procedure TWE_PHASE_MAP.DrawPhase4Map( AEquation : TWE_EQUATION );
begin
FCanvas.Pen.Style := psSolid;
FCanvas.Pen.Width := FPenWidth;
FCanvas.Pen.Color := FMapColor.PhaseA;
DrawSingleEquation( AEquation.GetPhaseEquation( 0 ), FCanvas.Pen, FMapCenter, 0.3 );
FCanvas.Pen.Color := FMapColor.PhaseB;
DrawSingleEquation( AEquation.GetPhaseEquation( 1 ), FCanvas.Pen, FMapCenter, 0.4 );
FCanvas.Pen.Color := FMapColor.PhaseC;
DrawSingleEquation( AEquation.GetPhaseEquation( 2 ), FCanvas.Pen, FMapCenter, 0.5 );
end;
procedure TWE_PHASE_MAP.DrawPhaseMap(AEquation: TWE_EQUATION; sCaption : string);
begin
FUIAngle := AEquation.UIAngle;
// 初始化变量
FMapCenter.X := ( FRect.Right + FRect.Left ) div 2;
FMapCenter.Y := ( FRect.Bottom + FRect.Top ) div 2;
FUnitStep := ( FRect.Right - FRect.Left ) div 5;
FPenWidth := FUnitStep div 100;
if FUnitStep = 0 then
Exit;
MapColor := PhaseMapColor;
// 画背景及坐标
DrawBackground( True, False );
FCanvas.Font.Size := Round( FUnitStep /8 );
FCanvas.Font.Name := '宋体';
FCanvas.Font.Style := [];
FCanvas.Font.Color := clBlack;
FCanvas.TextOut(FRect.Right-90, FRect.Top+30, sCaption);
if AEquation.WiringError.PhaseType = ptThree then
DrawPhase3Map( AEquation )
else if (AEquation.WiringError.PhaseType = ptFour) or
(AEquation.WiringError.PhaseType = ptFourPT) then
DrawPhase4Map( AEquation )
else if AEquation.WiringError.PhaseType = ptSingle then
begin
DrawPhase2Map( AEquation )
end;
end;
procedure TWE_PHASE_MAP.DrawSingleEquation(APhaseEquation: TWE_PHASE_EXPRESSION;
APen : TPen; APos: TPoint; AAngleRadius: Double);
var
dOU, dOI : Double;
dLen : Double;
begin
if not Assigned( APhaseEquation ) then
Exit;
with APhaseEquation do
begin
dOU := CovAngle( AngleU );
dOI := CovAngle( AngleI - FUIAngle );
// 画电压
if ExpressU <> EmptyStr then
begin
if Pos( C_EQ_SIGN_SQRT3_2, ExpressU) > 0 then
dLen := 1.5
else if Pos( C_EQ_SIGN_1_2, ExpressU) > 0 then
dLen := 0.866
else if Pos(C_EQ_SIGN_SQRT3, ExpressU) > 0 then
dLen := 2.2
else
begin
if Length( ExpressU ) > 3 then
dLen := 1.732
else
dLen := 1.5;
end;
DrawLine( APen, APos, dLen, dOU, True,
StringReplace( ExpressUT, 'U', DotVar( 'U' ), [] ) );
end;
// 画电流
if ExpressI <> EmptyStr then
begin
dLen := 1;
if ( Pos('_a_c', ExpressI) > 0 ) or ( Pos('_c_a', ExpressI) > 0 ) then
dLen := dLen * 1.732;
if Pos( C_EQ_SIGN_1_2, ExpressI ) > 0 then
dLen := dLen / 2;
if Pos('2I', ExpressI ) > 0 then
dLen := dLen * 2;
DrawLine( APen, APos, dLen, dOI, True,
StringReplace( ExpressIT, 'I', DotVar( 'I' ), [] ) );
end;
// 画角度
if ( ExpressU <> EmptyStr ) and ( ExpressI <> EmptyStr ) then
DrawAngle( APen, APos, AAngleRadius, dOU, dOI, True, ExpressO );
end;
end;
procedure TWE_PHASE_MAP.SetDefMapColor(const Value: TWE_PHASE_MAP_COLOR);
begin
FDefMapColor := Value;
end;
procedure TWE_PHASE_MAP.SetUIAngle(const Value: Double);
begin
FUIAngle := Value;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, libpq_fe, PostgresClasses;
type
TForm1 = class(TForm)
Panel1: TPanel;
ButtonConnect: TButton;
ButtonPrepare: TButton;
ButtonGetData: TButton;
Memo1: TMemo;
ButtonGetParamData: TButton;
ButtonSetData: TButton;
ButtonClear: TButton;
ButtonCreateTable: TButton;
procedure ButtonConnectClick(Sender: TObject);
procedure ButtonGetDataClick(Sender: TObject);
procedure ButtonGetParamDataClick(Sender: TObject);
procedure ButtonPrepareClick(Sender: TObject);
procedure ButtonClearClick(Sender: TObject);
procedure ButtonSetDataClick(Sender: TObject);
procedure ButtonCreateTableClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure ButtonGetPreparedParamData(Sender: TObject);
function CheckIsConnected: boolean;
{ Private declarations }
public
{ Public declarations }
procedure AddToLog(const str: string);
end;
var
Form1: TForm1;
iPQ: IPostgres;
QueryStmt: IPostgresStmt;
const
LINE_WRAP = #$d#$a;
QUERY_PREPARED = 'select * from sample where id = $1';
implementation
uses Unit2;
{$R *.dfm}
procedure TForm1.AddToLog(const str: string);
begin
Memo1.Lines.Add(str);
end;
//Postgres still thinking all we have Motorola CPU, can be used ntohl or htonl etc instead for binary params
function bswap(v: dword):dword;
asm
bswap eax
end;
function TForm1.CheckIsConnected: boolean;
begin
result:= iPQ <> nil;
if not(result) then begin
AddToLog('not connected');
exit;
end;
result:= iPQ.IsConnected;
if not(result) then
AddToLog('not connected');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Randomize;
end;
procedure TForm1.ButtonConnectClick(Sender: TObject);
begin
FormConnParams.ShowModal;
if FormConnParams.ModalResult <> mrOK then exit;
iPQ:= TPostgres.Create('', '', FormConnParams.EditDatabase.Text, FormConnParams.EditLogin.Text, FormConnParams.EditPassword.Text);
if iPQ.Connect then
AddToLog('connected')
else AddToLog(iPQ.LastErrorString);
end;
procedure TForm1.ButtonCreateTableClick(Sender: TObject);
var
pq: IPostgresQuery;
const
QUERY = 'CREATE TABLE sample ' + LINE_WRAP +
'(id serial, ' + LINE_WRAP +
'name varchar(50) default NULL, ' + LINE_WRAP +
'i_data bytea, ' + LINE_WRAP +
'CONSTRAINT id_pkey PRIMARY KEY (id))';
begin
if not(CheckIsConnected) then exit;
AddToLog(LINE_WRAP + 'creating table "sample"');
iPQ.Lock;
try
pq:= iPQ.ExecQuery(QUERY);
if pq = nil then exit;
if pq.Status <> PGRES_COMMAND_OK then
AddToLog(iPQ.GetError);
finally
iPQ.Unlock;
end;
end;
procedure TForm1.ButtonSetDataClick(Sender: TObject);
var
i, j: integer;
pq: IPostgresQuery;
p: TParam;
stuff: array[0..$F]of byte;
const
QUERY = 'insert into sample (name, i_data) values ($1, $2) returning id';
begin
if not(CheckIsConnected) then exit;
AddToLog(LINE_WRAP + 'filling table "sample"');
p.nParams:= 2;
p.paramTypes:= nil;
setlength(p.paramValues, p.nParams);
setlength(p.paramLengths, p.nParams);
setlength(p.paramFormats, p.nParams);
for i := 0 to p.nParams - 1 do
p.paramFormats[i]:= 1;
p.resultFormat:= 1;
name:= '';
for i := 0 to 10 do begin
name:= name + char($41 + i);
p.paramValues[0]:= PChar(name);
p.paramLengths[0]:= length(name);
for j := low(stuff) to high(stuff) do
stuff[j]:= random($FF);
p.paramValues[1]:= @stuff;
p.paramLengths[1]:= sizeof(stuff);
iPQ.Lock;
try
pq:= iPQ.ExecQueryParams(QUERY, @p);
if pq = nil then exit;
if pq.Status <> PGRES_TUPLES_OK then begin
AddToLog(iPQ.GetError);
exit;
end;
if pq.RecordCount <= 0 then exit;
AddToLog('added id = ' + IntToHex(bswap(PInteger(pq.Value[0, 0])^), 4));
finally
iPQ.Unlock;
end;
end;
end;
procedure TForm1.ButtonPrepareClick(Sender: TObject);
var
p: TParam;
begin
if not(CheckIsConnected) then exit;
AddToLog(LINE_WRAP + 'preparing ' + QUERY_PREPARED);
iPQ.Lock;
try
p.nParams:= 0;
p.paramTypes:= nil;
QueryStmt:= iPQ.Prepare(QUERY_PREPARED, 'StmtGetInfo', @p);
if QueryStmt = nil then exit;
if QueryStmt.Status <> PGRES_COMMAND_OK then begin
AddToLog(iPQ.GetError);
exit;
end;
finally
iPQ.Unlock;
end;
end;
procedure TForm1.ButtonGetDataClick(Sender: TObject);
var
pq: IPostgresQuery;
i, j: integer;
temp: string;
const
QUERY = 'select * from sample';
begin
if not(CheckIsConnected) then exit;
AddToLog(LINE_WRAP + QUERY);
iPQ.Lock;
try
pq:= iPQ.ExecQuery(QUERY);
if pq = nil then exit;
if pq.Status <> PGRES_TUPLES_OK then begin
AddToLog(iPQ.GetError);
exit;
end;
for i := 0 to pq.RecordCount - 1 do begin
temp:= '';
for j := 0 to pq.FieldCount - 1 do
temp:= temp + pq.Value[i, j] + #9;
AddToLog(temp);
end;
finally
iPQ.Unlock;
end;
end;
procedure TForm1.ButtonGetParamDataClick(Sender: TObject);
var
pq: IPostgresQuery;
i, j, value, len: integer;
temp: string;
p: TParam;
stuff: array[0..$F]of byte;
const
QUERY = 'select * from sample where id = $1';
begin
if not(CheckIsConnected) then exit;
value:= bswap(integer(random(high(stuff))));
p.nParams:= 1;
p.paramTypes:= nil;
setlength(p.paramValues, p.nParams);
p.paramValues[0]:= @value;
setlength(p.paramLengths, p.nParams);
p.paramLengths[0]:= sizeof(value);
setlength(p.paramFormats, p.nParams);
p.paramFormats[0]:= 1;
p.resultFormat:= 1;
AddToLog(LINE_WRAP + QUERY + ' result');
iPQ.Lock;
try
pq:= iPQ.ExecQueryParams(QUERY, @p);
if pq = nil then exit;
if pq.Status <> PGRES_TUPLES_OK then begin
AddToLog(iPQ.GetError);
exit;
end;
for i := 0 to pq.RecordCount - 1 do begin
AddToLog('id = ' + IntToStr(bswap(PInteger(pq.Value[0, 0])^)));
AddToLog('name = ' + pq.Value[0, 1]);
len:= pq.ValueLen[0, 2];
if len > sizeof(stuff) then len:= sizeof(stuff);
move(pq.Value[0, 2]^, stuff, len);
temp:= '';
for j := 0 to len - 1 do
temp:= temp + IntToHex(stuff[j], 2);
AddToLog(temp);
end;
finally
iPQ.Unlock;
end;
ButtonGetParamData.OnClick:= ButtonGetPreparedParamData;
end;
procedure TForm1.ButtonGetPreparedParamData(Sender: TObject);
var
pq: IPostgresQuery;
i, j, value, len: integer;
temp: string;
p: TParam;
stuff: array[0..$F]of byte;
begin
if not(CheckIsConnected) then exit;
if QueryStmt = nil then begin
AddToLog('prepare query first!');
exit;
end;
value:= bswap(integer(random(high(stuff))));
p.nParams:= 1;
p.paramTypes:= nil;
setlength(p.paramValues, p.nParams);
p.paramValues[0]:= @value;
setlength(p.paramLengths, p.nParams);
p.paramLengths[0]:= sizeof(value);
setlength(p.paramFormats, p.nParams);
p.paramFormats[0]:= 1;
p.resultFormat:= 1;
AddToLog(LINE_WRAP + 'prepared ' + QUERY_PREPARED + ' result');
iPQ.Lock;
try
pq:= iPQ.ExecQueryPrepared(QueryStmt.StmtName, @p);
if pq = nil then exit;
if pq.Status <> PGRES_TUPLES_OK then begin
AddToLog(iPQ.GetError);
exit;
end;
for i := 0 to pq.RecordCount - 1 do begin
AddToLog('id = ' + IntToStr(bswap(PInteger(pq.Value[0, 0])^)));
AddToLog('name = ' + pq.Value[0, 1]);
len:= pq.ValueLen[0, 2];
if len > sizeof(stuff) then len:= sizeof(stuff);
move(pq.Value[0, 2]^, stuff, len);
temp:= '';
for j := 0 to len - 1 do
temp:= temp + IntToHex(stuff[j], 2);
AddToLog(temp);
end;
finally
iPQ.Unlock;
end;
ButtonGetParamData.OnClick:= ButtonGetParamDataClick;
end;
procedure TForm1.ButtonClearClick(Sender: TObject);
var
pq: IPostgresQuery;
const
QUERY = 'drop table sample';
begin
if not(CheckIsConnected) then exit;
AddToLog(LINE_WRAP + 'cleanup ' + QUERY);
iPQ.Lock;
try
pq:= iPQ.ExecQuery(QUERY);
if pq = nil then exit;
if pq.Status <> PGRES_COMMAND_OK then begin
AddToLog(iPQ.GetError);
exit;
end;
finally
iPQ.Unlock;
end;
end;
end.
|
unit rhlGrindahl256;
interface
uses
rhlCore;
type
{ TrhlGrindahl256 }
TrhlGrindahl256 = class(TrhlHash)
private
const
ROWS = 4;
COLUMNS = 13;
BLANK_ROUNDS = 8;
SIZE = (ROWS * COLUMNS) div 4;
s_master_table: array[0..255] of DWord = (
$c66363a5,$f87c7c84,$ee777799,$f67b7b8d,$fff2f20d,$d66b6bbd,$de6f6fb1,$91c5c554,
$60303050,$02010103,$ce6767a9,$562b2b7d,$e7fefe19,$b5d7d762,$4dababe6,$ec76769a,
$8fcaca45,$1f82829d,$89c9c940,$fa7d7d87,$effafa15,$b25959eb,$8e4747c9,$fbf0f00b,
$41adadec,$b3d4d467,$5fa2a2fd,$45afafea,$239c9cbf,$53a4a4f7,$e4727296,$9bc0c05b,
$75b7b7c2,$e1fdfd1c,$3d9393ae,$4c26266a,$6c36365a,$7e3f3f41,$f5f7f702,$83cccc4f,
$6834345c,$51a5a5f4,$d1e5e534,$f9f1f108,$e2717193,$abd8d873,$62313153,$2a15153f,
$0804040c,$95c7c752,$46232365,$9dc3c35e,$30181828,$379696a1,$0a05050f,$2f9a9ab5,
$0e070709,$24121236,$1b80809b,$dfe2e23d,$cdebeb26,$4e272769,$7fb2b2cd,$ea75759f,
$1209091b,$1d83839e,$582c2c74,$341a1a2e,$361b1b2d,$dc6e6eb2,$b45a5aee,$5ba0a0fb,
$a45252f6,$763b3b4d,$b7d6d661,$7db3b3ce,$5229297b,$dde3e33e,$5e2f2f71,$13848497,
$a65353f5,$b9d1d168,$00000000,$c1eded2c,$40202060,$e3fcfc1f,$79b1b1c8,$b65b5bed,
$d46a6abe,$8dcbcb46,$67bebed9,$7239394b,$944a4ade,$984c4cd4,$b05858e8,$85cfcf4a,
$bbd0d06b,$c5efef2a,$4faaaae5,$edfbfb16,$864343c5,$9a4d4dd7,$66333355,$11858594,
$8a4545cf,$e9f9f910,$04020206,$fe7f7f81,$a05050f0,$783c3c44,$259f9fba,$4ba8a8e3,
$a25151f3,$5da3a3fe,$804040c0,$058f8f8a,$3f9292ad,$219d9dbc,$70383848,$f1f5f504,
$63bcbcdf,$77b6b6c1,$afdada75,$42212163,$20101030,$e5ffff1a,$fdf3f30e,$bfd2d26d,
$81cdcd4c,$180c0c14,$26131335,$c3ecec2f,$be5f5fe1,$359797a2,$884444cc,$2e171739,
$93c4c457,$55a7a7f2,$fc7e7e82,$7a3d3d47,$c86464ac,$ba5d5de7,$3219192b,$e6737395,
$c06060a0,$19818198,$9e4f4fd1,$a3dcdc7f,$44222266,$542a2a7e,$3b9090ab,$0b888883,
$8c4646ca,$c7eeee29,$6bb8b8d3,$2814143c,$a7dede79,$bc5e5ee2,$160b0b1d,$addbdb76,
$dbe0e03b,$64323256,$743a3a4e,$140a0a1e,$924949db,$0c06060a,$4824246c,$b85c5ce4,
$9fc2c25d,$bdd3d36e,$43acacef,$c46262a6,$399191a8,$319595a4,$d3e4e437,$f279798b,
$d5e7e732,$8bc8c843,$6e373759,$da6d6db7,$018d8d8c,$b1d5d564,$9c4e4ed2,$49a9a9e0,
$d86c6cb4,$ac5656fa,$f3f4f407,$cfeaea25,$ca6565af,$f47a7a8e,$47aeaee9,$10080818,
$6fbabad5,$f0787888,$4a25256f,$5c2e2e72,$381c1c24,$57a6a6f1,$73b4b4c7,$97c6c651,
$cbe8e823,$a1dddd7c,$e874749c,$3e1f1f21,$964b4bdd,$61bdbddc,$0d8b8b86,$0f8a8a85,
$e0707090,$7c3e3e42,$71b5b5c4,$cc6666aa,$904848d8,$06030305,$f7f6f601,$1c0e0e12,
$c26161a3,$6a35355f,$ae5757f9,$69b9b9d0,$17868691,$99c1c158,$3a1d1d27,$279e9eb9,
$d9e1e138,$ebf8f813,$2b9898b3,$22111133,$d26969bb,$a9d9d970,$078e8e89,$339494a7,
$2d9b9bb6,$3c1e1e22,$15878792,$c9e9e920,$87cece49,$aa5555ff,$50282878,$a5dfdf7a,
$038c8c8f,$59a1a1f8,$09898980,$1a0d0d17,$65bfbfda,$d7e6e631,$844242c6,$d06868b8,
$824141c3,$299999b0,$5a2d2d77,$1e0f0f11,$7bb0b0cb,$a85454fc,$6dbbbbd6,$2c16163a
);
var
s_table_0,
s_table_1,
s_table_2,
s_table_3: array[0..255] of DWord;
m_state: array[0..SIZE - 1] of DWord;
m_temp: array[0..SIZE - 1] of DWord;
procedure InjectMsg(a_full_process: Boolean);
protected
procedure UpdateBlock(const AData); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlGrindahl256 }
procedure TrhlGrindahl256.InjectMsg(a_full_process: Boolean);
var
u: array[0..SIZE - 1] of DWord;
begin
m_state[SIZE - 1] := m_state[SIZE - 1] xor $01;
if (a_full_process) then
begin
m_temp[0] :=
s_table_0[Byte(m_state[12] shr 24)] xor
s_table_1[Byte(m_state[11] shr 16)] xor
s_table_2[Byte(m_state[9] shr 8)] xor
s_table_3[Byte(m_state[3])];
end;
m_temp[1] :=
s_table_0[Byte(m_state[0] shr 24)] xor
s_table_1[Byte(m_state[12] shr 16)] xor
s_table_2[Byte(m_state[10] shr 8)] xor
s_table_3[Byte(m_state[4])];
m_temp[2] :=
s_table_0[Byte(m_state[1] shr 24)] xor
s_table_1[Byte(m_state[0] shr 16)] xor
s_table_2[Byte(m_state[11] shr 8)] xor
s_table_3[Byte(m_state[5])];
m_temp[3] :=
s_table_0[Byte(m_state[2] shr 24)] xor
s_table_1[Byte(m_state[1] shr 16)] xor
s_table_2[Byte(m_state[12] shr 8)] xor
s_table_3[Byte(m_state[6])];
m_temp[4] :=
s_table_0[Byte(m_state[3] shr 24)] xor
s_table_1[Byte(m_state[2] shr 16)] xor
s_table_2[Byte(m_state[0] shr 8)] xor
s_table_3[Byte(m_state[7])];
m_temp[5] :=
s_table_0[Byte(m_state[4] shr 24)] xor
s_table_1[Byte(m_state[3] shr 16)] xor
s_table_2[Byte(m_state[1] shr 8)] xor
s_table_3[Byte(m_state[8])];
m_temp[6] :=
s_table_0[Byte(m_state[5] shr 24)] xor
s_table_1[Byte(m_state[4] shr 16)] xor
s_table_2[Byte(m_state[2] shr 8)] xor
s_table_3[Byte(m_state[9])];
m_temp[7] :=
s_table_0[Byte(m_state[6] shr 24)] xor
s_table_1[Byte(m_state[5] shr 16)] xor
s_table_2[Byte(m_state[3] shr 8)] xor
s_table_3[Byte(m_state[10])];
m_temp[8] :=
s_table_0[Byte(m_state[7] shr 24)] xor
s_table_1[Byte(m_state[6] shr 16)] xor
s_table_2[Byte(m_state[4] shr 8)] xor
s_table_3[Byte(m_state[11])];
m_temp[9] :=
s_table_0[Byte(m_state[8] shr 24)] xor
s_table_1[Byte(m_state[7] shr 16)] xor
s_table_2[Byte(m_state[5] shr 8)] xor
s_table_3[Byte(m_state[12])];
m_temp[10] :=
s_table_0[Byte(m_state[9] shr 24)] xor
s_table_1[Byte(m_state[8] shr 16)] xor
s_table_2[Byte(m_state[6] shr 8)] xor
s_table_3[Byte(m_state[0])];
m_temp[11] :=
s_table_0[Byte(m_state[10] shr 24)] xor
s_table_1[Byte(m_state[9] shr 16)] xor
s_table_2[Byte(m_state[7] shr 8)] xor
s_table_3[Byte(m_state[1])];
m_temp[12] :=
s_table_0[Byte(m_state[11] shr 24)] xor
s_table_1[Byte(m_state[10] shr 16)] xor
s_table_2[Byte(m_state[8] shr 8)] xor
s_table_3[Byte(m_state[2])];
Move(m_temp, u, SizeOf(m_temp));
Move(m_state, m_temp, SizeOf(m_state));
Move(u, m_state, SizeOf(u));
end;
procedure TrhlGrindahl256.UpdateBlock(const AData);
var
x: DWord absolute AData;
begin
m_state[0] := SwapEndian(x);
InjectMsg(false);
end;
constructor TrhlGrindahl256.Create;
procedure CalcTable(i: Integer; var tab);
var
atab: array[0..0] of DWord absolute tab;
j: Integer;
begin
for j := 0 to 255 do
atab[j] := RorDWord(s_master_table[j], i*8);
end;
begin
HashSize := 32;
BlockSize := 4;
Move(s_master_table, s_table_0, SizeOf(s_master_table));
CalcTable(1, s_table_1);
CalcTable(2, s_table_2);
CalcTable(3, s_table_3);
end;
procedure TrhlGrindahl256.Init;
begin
inherited Init;
FillChar(m_state, SizeOf(m_state), 0);
FillChar(m_temp, SizeOf(m_temp), 0);
end;
procedure TrhlGrindahl256.Final(var ADigest);
var
padding_size: DWord;
msg_length: QWord;
pad: TBytes;
i: Integer;
begin
padding_size := 3 * BlockSize - (FProcessedBytes mod BlockSize);
msg_length := (FProcessedBytes div ROWS) + 1;
SetLength(pad, padding_size);
pad[0] := $80;
msg_length := SwapEndian(msg_length);
Move(msg_length, pad[padding_size-8], SizeOf(msg_length));
UpdateBytes(pad[0], padding_size - BlockSize);
Move(pad[padding_size - BlockSize], m_state[0], 4);
m_state[0] := SwapEndian(m_state[0]);
for i := 0 to BLANK_ROUNDS do
InjectMsg(true);
i := HashSize div ROWS;
ConvertDWordsToBytesSwapOrder(m_state[COLUMNS - i], i, ADigest);
end;
end.
|
unit ugraphic;
{$mode objfpc}{$H+}{$INLINE ON} {$MODESWITCH ADVANCEDRECORDS}
interface
//I'll use SDL2 because I can.
uses
Classes, SysUtils, SDL2, utexture, Math;
type
TColorRGB = record
r, g, b: UInt8;
constructor Create(red, green, blue: UInt8);
end;
const
CHAR_SIZE = 12;
KEY_UP = SDLK_UP;
KEY_DOWN = SDLK_DOWN;
KEY_LEFT = SDLK_LEFT;
KEY_RIGHT = SDLK_RIGHT;
RGB_Black : TColorRGB = (r: 0; g: 0; b: 0);
RGB_Red : TColorRGB = (r: 255; g: 0; b: 0);
RGB_Green : TColorRGB = (r: 0; g: 255; b: 0);
RGB_Blue : TColorRGB = (r: 0; g: 0; b: 255);
RGB_Cyan : TColorRGB = (r: 0; g: 255; b: 255);
RGB_Magenta : TColorRGB = (r: 255; g: 0; b: 255);
RGB_Yellow : TColorRGB = (r: 255; g: 255; b: 0);
RGB_White : TColorRGB = (r: 255; g: 255; b: 255);
RGB_Gray : TColorRGB = (r: 128; g: 128; b: 128);
RGB_Grey : TColorRGB = (r: 192; g: 192; b: 192);
RGB_Maroon : TColorRGB = (r: 128; g: 0; b: 0);
RGB_Darkgreen : TColorRGB = (r: 0; g: 128; b: 0);
RGB_Navy : TColorRGB = (r: 0; g: 0; b: 128);
RGB_Teal : TColorRGB = (r: 0; g: 128; b: 128);
RGB_Purple : TColorRGB = (r: 128; g: 0; b: 128);
var
screen_width,
screen_height : integer;
window : PSDL_Window;
renderer : PSDL_Renderer;
event : TSDL_Event;
scr : PSDL_Texture;
font : PSDL_Surface;
inkeys : PUInt8;
pFormat,
bgFormat : PSDL_PixelFormat;
pixels : PUInt32;
pitch : UInt32;
font_tex : PSDL_Texture;
VSyncFlag : Boolean;
FontPath : Pchar;
//TODO clean up that shit
procedure FinishGraphicModule; inline;
function getTicks: UInt64; inline;
procedure delay (ms: UInt32); inline;
operator / (color: TColorRGB; a: integer) res : TColorRGB;
procedure screen(width, height:integer; fullscreen:boolean; window_name:string);
procedure readKeys;
function keyDown(key: TSDL_KeyCode): boolean; overload;
function keyDown(key: TSDL_ScanCode): boolean; overload;
function done(quit_if_esc, delay: boolean): boolean; overload;
function done: boolean; inline; overload;
//procedure SetTextureColorMod(Tex: PTexture; R, G, B: UInt8);
procedure verLine(x, y1, y2: integer; color: TColorRGB);
procedure DrawTexStripe(DrawX, y1, y2: integer; TexCoordX: double; Tex: PTexture); overload;
procedure DrawTexStripe(DrawX, y1, y2: integer; TexCoordX: double; Tex: PTexture; Side: boolean); overload;
procedure lock;
procedure unlock;
procedure pSet(x, y: integer; color: TColorRGB);
procedure drawRect(x1, y1, x2, y2: integer; color: TColorRGB);
procedure redraw; inline;
procedure cls(color: TColorRGB); overload;
procedure cls; inline; overload;
procedure initFont(APath: PChar);
procedure writeText(text: string; x, y:integer);
implementation
//TColorRGB stuff first
constructor TColorRGB.Create(red, green, blue: UInt8);
begin
r := red;
g := green;
b := blue;
end;
operator / (color: TColorRGB; a: integer) res : TColorRGB;
begin
if (a <= 0) then exit(color);
Result := TColorRGB.Create(color.r div a, color.g div a, color.b div a); // seems shitty, need to fix it
end;
//exit program
procedure FinishGraphicModule; inline;
begin
SDL_SetRenderTarget(renderer, nil);
SDL_DestroyTexture(scr);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit;
halt(1);
end;
//getTicks from SDL
function GetTicks: UInt64; inline;
begin
Result := SDL_GetTicks;
end;
//delays program
procedure delay (ms: UInt32); inline;
begin
SDL_Delay(ms);
end;
//Screen() -- that's init of SDL
procedure screen(width, height:integer; fullscreen:boolean; window_name:string);
var
RENDER_FLAGS : UInt32;
begin
RENDER_FLAGS := SDL_RENDERER_ACCELERATED or (SDL_RENDERER_PRESENTVSYNC and (UInt8(VSyncFlag) shl 2)); //HW accel + VSync
screen_width := width;
screen_height := height;
if not fullscreen then
window := SDL_CreateWindow(PChar(window_name), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN)
else
window := SDL_CreateWindow(PChar(window_name), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
if window = nil then
begin
writeln('Window error: ', SDL_GetError);
FinishGraphicModule;
end;
renderer := SDL_CreateRenderer(window, -1, RENDER_FLAGS);
if renderer = nil then
begin
writeln('Renderer error: ', SDL_GetError);
FinishGraphicModule;
end;
if fullscreen then
begin
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, PChar('linear'));
if SDL_RenderSetLogicalSize(renderer, screen_width, screen_height)<>0 then
writeln('logical size error: ', SDL_GetError);
end;
pFormat := SDL_AllocFormat(SDL_GetWindowPixelFormat(window));
bgFormat := SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888);
scr := SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, width, height);
SDL_SetTextureBlendMode(scr, SDL_BLENDMODE_BLEND);
initFont(FontPath);
end;
//Reads keys to array.
procedure readKeys;
begin
inkeys := SDL_GetKeyboardState(nil);
end;
//KeyDown events check.
function keyDown(key: TSDL_KeyCode): boolean; overload;
var scancode: TSDL_ScanCode;
begin
scancode := SDL_GetScancodeFromKey(key);
Result := inkeys[scancode] <> 0;
end;
function keyDown(key: TSDL_ScanCode): boolean; overload;
begin
Result := inkeys[key] <> 0;
end;
//checking if we have received exit event
function done(quit_if_esc, delay: boolean): boolean;
begin
//quit_if_esc does not work!
if delay then SDL_Delay(3); //do NOT set it on 2 or less
readKeys;
while SDL_PollEvent(@event)<>0 do
begin
if (event.type_ = SDL_QUITEV) then exit(true);
if (quit_if_esc and keyDown(SDL_SCANCODE_ESCAPE)) then exit(true);
end;
Result := false;
end;
function done: boolean; inline; overload;
begin
Result := done(true, true);
end;
//modifies color palette of texture
procedure SetTextureColorMod(Tex: PTexture; R, G, B: UInt8);
begin
SDL_SetTextureColorMod(Tex^.RawTexture, R, G, B);
end;
//vertical line
procedure verLine(x, y1, y2: integer; color: TColorRGB);
var dy1, dy2: integer;
begin
dy1 := max(0, y1);
dy2 := min(screen_height - 1, y2);
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255);
SDL_RenderDrawLine(renderer, x, dy1, x, dy2);
end;
//draws a stripe from texture
procedure DrawTexStripe(DrawX, y1, y2: integer; TexCoordX: double; Tex: PTexture); overload;
var
src, dst: TSDL_Rect;
begin
src.x := SInt32(Trunc(TexCoordX * double(Tex^.Width)));
src.y := 0;
src.w := 1;
src.h := Tex^.Height;
dst.x := DrawX;
dst.y := y1;
dst.w := 1;
dst.h := y2-y1+1;
SDL_RenderCopy(renderer, Tex^.RawTexture, @src, @dst);
end;
procedure DrawTexStripe(DrawX, y1, y2: integer; TexCoordX: double; Tex: PTexture; Side: boolean); overload;
begin
if Side then
SDL_SetTextureColorMod(Tex^.RawTexture, 127, 127, 127);
DrawTexStripe(DrawX,y1,y2,TexCoordX,Tex);
SDL_SetTextureColorMod(Tex^.RawTexture, 255, 255, 255);
end;
//lock screen overlay in order to be able to draw pixel-by-pixel
procedure lock;
var bgColor, i: UInt32;
begin
SDL_LockTexture(scr, nil, @pixels, @pitch);
bgColor := SDL_MapRGBA(bgFormat, 255, 255, 255, 0); //transparent
for i:=0 to screen_width*screen_height-1 do
pixels[i] := bgColor;
end;
//unlock screen overlay to finally draw changes
procedure unlock;
begin
SDL_UnlockTexture(scr);
SDL_RenderCopy(renderer, scr, nil, nil);
end;
//set pixel
procedure pSet(x, y: integer; color: TColorRGB);
var
pColor, pixelpos: UInt32;
begin
if (x < 0) or (y < 0) or (x >= screen_width) or (y >= screen_height) then exit;
//SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255);
//SDL_RenderDrawPoint(renderer, x, y);
pColor := SDL_MapRGBA(bgFormat, color.r, color.g, color.b, 255);
pixelpos := screen_width*y+x;
pixels[pixelpos] := pColor;
end;
//draw rectangular
procedure drawRect(x1, y1, x2, y2: integer; color: TColorRGB);
var r: TSDL_Rect;
begin
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255);
r.x := x1; r.y := y1; r.w := x2-x1; r.h := y2-y1;
SDL_RenderFillRect(renderer,@r);
end;
//redraw the frame.
procedure redraw; inline;
begin
SDL_RenderPresent(renderer);
end;
//clear screen.
procedure cls(color: TColorRGB); overload;
begin
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255);
SDL_RenderClear(renderer);
end;
procedure cls; inline; overload;
begin
cls(RGB_Black);
end;
//init font to make it usable
procedure initFont(APath: PChar);
begin
// TODO LOAD FONTS FROM FILE
font := SDL_LoadBMP(APath);
if font = nil then
begin
writeln('Can''t get the font file. ');
exit;
end;
SDL_ConvertSurfaceFormat(font, SDL_PIXELFORMAT_RGB24, 0);
SDL_SetColorKey(font, 1, SDL_MapRGB(font^.format, 0, 0, 0)); //make transparent bg
font_tex := SDL_CreateTextureFromSurface(renderer,font); // we need this for RenderCopy
end;
// write text
procedure writeText(text: string; x, y:integer);
var
len, i, row_cnt: integer;
char_code: byte;
selection, char_rect: TSDL_Rect;
begin
//TODO \n support
len := CHAR_SIZE * Length(text);
row_cnt := font^.w div CHAR_SIZE;
//if ((x < 0) or ((x+len) > screen_width) or (y < 0) or ((y+CHAR_SIZE) > screen_height)) then
// exit; // if our text is too big then we don't work
selection.w := CHAR_SIZE;
selection.h := CHAR_SIZE;
char_rect.w := CHAR_SIZE;
char_rect.h := CHAR_SIZE;
char_rect.y := y;
for i:=1 to Length(text) do
begin
char_code := ord(text[i]); // getting char code...
selection.y := (char_code div row_cnt)*CHAR_SIZE; // and then we get our
selection.x := (char_code mod row_cnt)*CHAR_SIZE; // char location on font
char_rect.x := x + (i-1)*CHAR_SIZE; // move next char of string to the right
SDL_RenderCopy(renderer,font_tex,@selection,@char_rect); // and then we copy our char from font
end;
//SDL_DestroyTexture(font_tex); // prevent memory leak
end;
initialization
FontPath := './res/fonts/good_font.bmp';
VSyncFlag := false;
end.
|
{$MODE OBJFPC}
program Task;
const
InputFile = 'BRICKS.INP';
OutputFile = 'BRICKS.OUT';
var
fi, fo: TextFile;
g, y, m, n: Int64;
sum, prod: Int64;
low, middle, high: Int64;
begin
AssignFile(fi, InputFile); Reset(fi);
AssignFile(fo, OutputFile); Rewrite(fo);
try
ReadLn(fi, g, y);
sum := g div 2 + 2;
prod := g + y;
low := 0; high := sum div 2;
while low <= high do
begin
middle := (low + high) div 2;
m := middle;
n := sum - m;
if (m > prod div n + 1) or (m * n >= prod) then high := middle - 1
else low := middle + 1;
end;
m := low;
n := sum - m;
WriteLn(fo, m, ' ', n);
finally
CloseFile(fi); CloseFile(fo);
end;
end.
|
unit LoanClassAdvance;
interface
type
TAdvanceMethod = (amNone,amUponRelease,amPreset);
TLoanClassAdvance = class
private
FInterest: integer;
FPrincipal: integer;
FAdvanceMethod: TAdvanceMethod;
FIncludePrincipal: boolean;
function GetNumberOfMonths: integer;
public
property Interest: integer read FInterest write FInterest;
property Principal: integer read FPrincipal write FPrincipal;
property NumberOfMonths: integer read GetNumberOfMonths;
property AdvanceMethod: TAdvanceMethod read FAdvanceMethod write FAdvanceMethod;
property IncludePrincipal: boolean read FIncludePrincipal write FIncludePrincipal;
end;
implementation
{ TLoanClassAdvance }
function TLoanClassAdvance.GetNumberOfMonths: integer;
begin
if FInterest > 0 then Result := FInterest
else Result := FPrincipal;
end;
end.
|
unit IconChanger;
interface
{$WARNINGS OFF}
uses
Windows, Classes, SysUtils, Graphics;
procedure ChangeIcon(FileName, IconFile, ResName:string);
//FileName: is the exefile that you would to patch
//IconFile: all icons found in the iconfile will be added
//ResName: is the name of the IconGroup that you add to the file
implementation
resourcestring
SInvalidFileName = 'Invalide filename %s';
type
TNewHeader = record
idReserved:WORD;
idType:WORD;
idCount:WORD;
end;
TResDirHeader = packed record
bWidth:Byte;
bHeight:Byte;
bColorCount:Byte;
bReserved:Byte;
wPlanes:WORD;
wBitCount:WORD;
lBytesInRes:Longint;
end;
TIconFileResDirEntry = packed record
DirHeader:TResDirHeader;
lImageOffset:Longint;
end;
TIconResDirEntry = packed record
DirHeader:TResDirHeader;
wNameOrdinal:WORD;
end;
PIconResDirGrp = ^TIconResDirGrp;
TIconResDirGrp = packed record
idHeader:TNewHeader;
idEntries:array[0..0] of TIconResDirEntry;
end;
PIconFileResGrp = ^TIconFileResDirGrp;
TIconFileResDirGrp = packed record
idHeader:TNewHeader;
idEntries:array[0..0] of TIconFileResDirEntry;
end;
TBeginUpdateRes=function(pFileName: PChar; bDeleteExistingResources: BOOL): THandle; stdcall;
TUpdateRes=function(hUpdate: THandle; lpType, lpName: PChar;
wLanguage: Word; lpData: Pointer; cbData: DWORD): BOOL; stdcall;
TEndUpdateRes=function(hUpdate: THandle; fDiscard: BOOL): BOOL; stdcall;
function MakeLangID:WORD;
begin
Result:=(SUBLANG_ENGLISH_US shl 10) or LANG_ENGLISH;
end;
procedure CheckFileName(Value:string);
begin
if (Trim(Value) = EmptyStr) or (not FileExists(Value)) then
raise Exception.Create(Format(SInvalidFileName, [Value]));
end;
procedure ChangeIcon(FileName, IconFile, ResName:string);
var
I:Integer;
Group:Pointer;
Header:TNewHeader;
FileGrp:PIconFileResGrp;
IconGrp:PIconResDirGrp;
IconGrpSize,
FileGrpSize:Integer;
Icon:TIcon;
Stream:TMemoryStream;
hUpdateRes:THandle;
begin
CheckFileName(FileName);
hUpdateRes:=BeginUpdateResource(PChar(FileName), False);
Win32Check(hUpdateRes <> 0);
CheckFileName(IconFile);
Icon:=TIcon.Create;
Icon.LoadFromFile(IconFile);
Stream:=TMemoryStream.Create;
try
Icon.SaveToStream(Stream);
finally
Icon.Free;
end;
Stream.Position:=0;
Stream.Read(Header, SizeOf(Header));
FileGrpSize := SizeOf(TIconFileResDirGrp) + (Header.idCount - 1) * SizeOf(TIconFileResDirEntry);
IconGrpSize := SizeOf(TIconResDirGrp) + (Header.idCount - 1) * SizeOf(TIconResDirEntry);
GetMem(FileGrp, FileGrpSize);GetMem(IconGrp, IconGrpSize);
Stream.Position:=0;
Stream.Read(FileGrp^, FileGrpSize);//loading icongroup
Group:=nil;
try
for I:=0 to FileGrp^.idHeader.idCount - 1 do //building icongroup from loaded entries
begin
with IconGrp^ do
begin
idHeader:=FileGrp^.idHeader;
idEntries[I].DirHeader:=FileGrp^.idEntries[I].DirHeader;
idEntries[I].wNameOrdinal:=I;//fixing Ordinals
end;
with FileGrp^.idEntries[I] do
begin
Stream.Seek(lImageOffset, soFromBeginning);
ReallocMem(Group, DirHeader.lBytesInRes);
Stream.Read(Group^, DirHeader.lBytesInRes);
Win32Check(UpdateResource(hUpdateRes,RT_ICON,PChar(MakeIntResource(I)),
MakeLangID, Group, DirHeader.lBytesInRes));
end;
end;//for
Win32Check(UpdateResource(hUpdateRes,RT_GROUP_ICON, PChar(ResName),
MakeLangID, IconGrp, IconGrpSize));//adding the icongroup
Win32Check(EndUpdateResource(hUpdateRes, False));
finally
Stream.Free;
FreeMem(FileGrp);
FreeMem(IconGrp);
FreeMem(Group);
end;//try
end;
var
hLib:HMODULE;
BeginUpdateRes:TBeginUpdateRes;
UpdateRes:TUpdateRes;
EndUpdateRes:TEndUpdateRes;
procedure GetFunctions(hLib:HMODULE);
begin
@BeginUpdateRes:=GetProcAddress(hLib,'BeginUpdateResourceA');
@UpdateRes:=GetProcAddress(hLib,'UpdateResourceA');
@EndUpdateRes:=GetProcAddress(hLib,'EndUpdateResourceA');
end;
initialization
if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then
hLib:=LoadLibrary('unicows.dll') //for win9x
else
hLib:=GetModuleHandle('Kernel32.dll');//assuming Kernel32 is mapped
if hLib > 0 then GetFunctions(hLib);
finalization
if GetModuleHandle('unicows.dll') > 0 then
FreeLibrary(hLib);
end.
|
unit untEasyRWIniMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, untEasyEdit, untEasyEditExt, untEasyMemo,
untEasyButtons, untEasyLabel;
type
TfrmEasyRWIniMain = class(TForm)
edtFileName: TEasyFileNameEdit;
MemContext: TEasyMemo;
btnExit: TEasyBitButton;
btnSave: TEasyBitButton;
edtSeed: TEasyMaskEdit;
EasyLabel1: TEasyLabel;
EasyLabel2: TEasyLabel;
procedure btnExitClick(Sender: TObject);
procedure edtFileNameDialogExit(Sender: TObject; ExitOK: Boolean);
procedure btnSaveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
IniFileName: string;
procedure ReadIniFile(AFileName, ASeed: string);
procedure WriteIniFile(AFileName, ASeed: string);
public
{ Public declarations }
end;
var
frmEasyRWIniMain: TfrmEasyRWIniMain;
implementation
uses untEasyUtilRWIni;
{$R *.dfm}
procedure TfrmEasyRWIniMain.btnExitClick(Sender: TObject);
begin
Close;
end;
procedure TfrmEasyRWIniMain.edtFileNameDialogExit(Sender: TObject;
ExitOK: Boolean);
begin
if Trim(edtFileName.FileName) = '' then Exit;
if Trim(edtSeed.Text) = '' then
begin
Application.MessageBox('请输入打开文件密码!', '提示', MB_OK +
MB_ICONWARNING);
edtFileName.FileName := '';
Exit;
end;
IniFileName := edtFileName.FileName;
if FileExists(IniFileName) then
ReadIniFile(IniFileName, edtSeed.Text);
end;
procedure TfrmEasyRWIniMain.ReadIniFile(AFileName, ASeed: string);
var
Ini : TEasyXorIniFile;
Sections,
Values : TStrings;
I, J : Integer;
begin
Ini := nil;
Sections := nil;
Values := nil;
MemContext.Lines.Clear;
try
Ini := TEasyXorIniFile.Create(IniFileName, ASeed);
Sections := TStringList.Create;
Values := TStringList.Create;
Ini.ReadSections(Sections);
for I := 0 to Sections.Count - 1 do
begin
MemContext.Lines.Add('[' + Sections[I] + ']');
Ini.ReadSection(Sections[I], Values);
for J := 0 to Values.Count - 1 do
MemContext.Lines.Add(Values[J] + '=' + Ini.ReadString(Sections[I], Values[J], ''));
end;
finally
Sections.Free;
Ini.Free;
Values.Free;
end;
end;
procedure TfrmEasyRWIniMain.WriteIniFile(AFileName, ASeed: string);
var
Ini: TEasyXorIniFile;
begin
Ini := TEasyXorIniFile.Create(IniFileName, ASeed);
try
ini.SetStrings(MemContext.Lines);
if not FileExists(AFileName) then
Ini.SaveToFile(AFileName)
else
begin
if Application.MessageBox('文件已存在,是否覆盖?', '提示', MB_OKCANCEL +
MB_ICONQUESTION) = IDOK then
begin
ini.SaveToFile(AFileName);
Application.MessageBox(PChar('保存成功!'), '提示', MB_OK +
MB_ICONINFORMATION);
end;
end;
finally
Ini.Free;
end;
end;
procedure TfrmEasyRWIniMain.btnSaveClick(Sender: TObject);
begin
if Trim(edtSeed.Text) = '' then
begin
Application.MessageBox('请输入打开文件密码!', '提示', MB_OK +
MB_ICONWARNING);
Exit;
end;
if FileExists(edtFileName.FileName) then
WriteIniFile(edtFileName.FileName, edtSeed.Text);
end;
procedure TfrmEasyRWIniMain.FormCreate(Sender: TObject);
begin
edtFileName.InitialDir := ParamStr(0);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXDataExpressMetaDataProvider;
interface
uses
Data.DBXCommon,
Data.DBXCommonTable,
Data.DBXMetaDataProvider,
Data.DBXMetaDataCommandFactory
;
type
TDBXDataExpressMetaDataProvider = class(TDBXMetaDataProvider)
private
FConnection: TDBXConnection;
public
constructor Create(); overload;
constructor Create(Connection: TDBXConnection); overload;
public
procedure Open();
property Connection: TDBXConnection read FConnection write FConnection;
end;
TDBXDataExpressProviderWriteableContext = class(TDBXDataExpressProviderContext)
private
FTransaction: TDBXTransaction;
public
function CreateTableStorage(const CollectionName: UnicodeString;
const Columns: TDBXValueTypeArray): TDBXTable; override;
function CreateRowStorage(const CollectionName: UnicodeString;
const Columns: TDBXValueTypeArray): TDBXTableRow; override;
procedure StartTransaction; override;
procedure StartSerializedTransaction; override;
procedure Commit; override;
procedure Rollback; override;
end;
implementation
uses
Data.DBXMetaDataWriter,
Data.DBXMetaDataReader,
Data.DBXMetaDataWriterFactory,
Data.DBXDBReaders
;
{ TDBXDataExpressMetaDataProvider }
constructor TDBXDataExpressMetaDataProvider.Create;
begin
inherited;
end;
constructor TDBXDataExpressMetaDataProvider.Create(Connection: TDBXConnection);
begin
Inherited Create;
FConnection := Connection;
end;
procedure TDBXDataExpressMetaDataProvider.Open;
var
NewWriter: TDBXMetaDataWriter;
Context: TDBXDataExpressProviderContext;
Reader: TDBXMetaDataReader;
begin
if FConnection.ConnectionProperty[TDBXPropertyNames.DriverName] = 'Odbc' then
NewWriter := TDBXMetaDataWriterFactory.CreateWriter('Odbc')
else
NewWriter := TDBXMetaDataWriterFactory.CreateWriter(FConnection.ProductName);
Context := TDBXDataExpressProviderWriteableContext.Create;
Context.Connection := FConnection;
Context.UseAnsiStrings := TDBXProviderContext.UseAnsiString(FConnection.ProductName);
Context.RemoveIsNull := True;
NewWriter.Context := Context;
Reader := NewWriter.MetaDataReader;
Reader.Context := Context;
Reader.Version := FConnection.ProductVersion;
Writer := NewWriter;
end;
{ TDBXDataExpressProviderWriteableContext }
function TDBXDataExpressProviderWriteableContext.CreateTableStorage(const CollectionName: UnicodeString; const Columns: TDBXValueTypeArray): TDBXTable;
begin
Result := TDBXMemoryTable.Create;
Result.DBXTableName := CollectionName;
Result.Columns := Columns;
end;
function TDBXDataExpressProviderWriteableContext.CreateRowStorage(const CollectionName: UnicodeString; const Columns: TDBXValueTypeArray): TDBXTableRow;
var
Storage: TDBXTable;
begin
Storage := CreateTableStorage(CollectionName, Columns);
Storage.Insert;
Storage.Post;
Result := Storage;
end;
procedure TDBXDataExpressProviderWriteableContext.StartTransaction;
begin
FTransaction := FConnection.BeginTransaction;
end;
procedure TDBXDataExpressProviderWriteableContext.StartSerializedTransaction;
begin
FTransaction := FConnection.BeginTransaction(TDBXIsolations.Serializable);
end;
procedure TDBXDataExpressProviderWriteableContext.Commit;
begin
FConnection.CommitFreeAndNil(FTransaction);
end;
procedure TDBXDataExpressProviderWriteableContext.Rollback;
begin
FConnection.RollbackFreeAndNil(FTransaction);
end;
end.
|
unit MSAAConstants;
interface
const
DISPID_ACC_PARENT = -5000;
DISPID_ACC_CHILDCOUNT = -5001;
DISPID_ACC_CHILD = -5002;
DISPID_ACC_NAME = -5003;
DISPID_ACC_VALUE = -5004;
DISPID_ACC_DESCRIPTION = -5005;
DISPID_ACC_ROLE = -5006;
DISPID_ACC_STATE = -5007;
DISPID_ACC_HELP = -5008;
DISPID_ACC_HELPTOPIC = -5009;
DISPID_ACC_KEYBOARDSHORTCUT = -5010;
DISPID_ACC_FOCUS = -5011;
DISPID_ACC_SELECTION = -5012;
DISPID_ACC_DEFAULTACTION = -5013;
DISPID_ACC_SELECT = -5014;
DISPID_ACC_LOCATION = -5015;
DISPID_ACC_NAVIGATE = -5016;
DISPID_ACC_HITTEST = -5017;
DISPID_ACC_DODEFAULTACTION = -5018;
NAVDIR_MIN = $0;
NAVDIR_UP = $1;
NAVDIR_DOWN = $2;
NAVDIR_LEFT = $3;
NAVDIR_RIGHT = $4;
NAVDIR_NEXT = $5;
NAVDIR_PREVIOUS = $6;
NAVDIR_FIRSTCHILD = $7;
NAVDIR_LASTCHILD = $8;
NAVDIR_MAX = $9;
SELFLAG_NONE = $0;
SELFLAG_TAKEFOCUS = $1;
SELFLAG_TAKESELECTION = $2;
SELFLAG_EXTENDSELECTION = $4;
SELFLAG_ADDSELECTION = $8;
SELFLAG_REMOVESELECTION = $10;
SELFLAG_VALID = $1F;
STATE_SYSTEM_NORMAL = $0;
STATE_SYSTEM_UNAVAILABLE = $1;
STATE_SYSTEM_SELECTED = $2;
STATE_SYSTEM_FOCUSED = $4;
STATE_SYSTEM_PRESSED = $8;
STATE_SYSTEM_CHECKED = $10;
STATE_SYSTEM_MIXED = $20;
STATE_SYSTEM_INDETERMINATE = STATE_SYSTEM_MIXED;
STATE_SYSTEM_READONLY = $40;
STATE_SYSTEM_HOTTRACKED = $80;
STATE_SYSTEM_DEFAULT = $100;
STATE_SYSTEM_EXPANDED = $200;
STATE_SYSTEM_COLLAPSED = $400;
STATE_SYSTEM_BUSY = $800;
STATE_SYSTEM_FLOATING = $1000;
STATE_SYSTEM_MARQUEED = $2000;
STATE_SYSTEM_ANIMATED = $4000;
STATE_SYSTEM_INVISIBLE = $8000;
STATE_SYSTEM_OFFSCREEN = $10000;
STATE_SYSTEM_SIZEABLE = $20000;
STATE_SYSTEM_MOVEABLE = $40000;
STATE_SYSTEM_SELFVOICING = $80000;
STATE_SYSTEM_FOCUSABLE = $100000;
STATE_SYSTEM_SELECTABLE = $200000;
STATE_SYSTEM_LINKED = $400000;
STATE_SYSTEM_TRAVERSED = $800000;
STATE_SYSTEM_MULTISELECTABLE = $1000000;
STATE_SYSTEM_EXTSELECTABLE = $2000000;
STATE_SYSTEM_ALERT_LOW = $4000000;
STATE_SYSTEM_ALERT_MEDIUM = $8000000;
STATE_SYSTEM_ALERT_HIGH = $10000000;
STATE_SYSTEM_PROTECTED = $20000000;
STATE_SYSTEM_VALID = $3FFFFFFF;
ROLE_SYSTEM_TITLEBAR = $1;
ROLE_SYSTEM_MENUBAR = $2;
ROLE_SYSTEM_SCROLLBAR = $3;
ROLE_SYSTEM_GRIP = $4;
ROLE_SYSTEM_SOUND = $5;
ROLE_SYSTEM_CURSOR = $6;
ROLE_SYSTEM_CARET = $7;
ROLE_SYSTEM_ALERT = $8;
ROLE_SYSTEM_WINDOW = $9;
ROLE_SYSTEM_CLIENT = $A;
ROLE_SYSTEM_MENUPOPUP = $B;
ROLE_SYSTEM_MENUITEM = $C;
ROLE_SYSTEM_TOOLTIP = $D;
ROLE_SYSTEM_APPLICATION = $E;
ROLE_SYSTEM_DOCUMENT = $F;
ROLE_SYSTEM_PANE = $10;
ROLE_SYSTEM_CHART = $11;
ROLE_SYSTEM_DIALOG = $12;
ROLE_SYSTEM_BORDER = $13;
ROLE_SYSTEM_GROUPING = $14;
ROLE_SYSTEM_SEPARATOR = $15;
ROLE_SYSTEM_TOOLBAR = $16;
ROLE_SYSTEM_STATUSBAR = $17;
ROLE_SYSTEM_TABLE = $18;
ROLE_SYSTEM_COLUMNHEADER = $19;
ROLE_SYSTEM_ROWHEADER = $1A;
ROLE_SYSTEM_COLUMN = $1B;
ROLE_SYSTEM_ROW = $1C;
ROLE_SYSTEM_CELL = $1D;
ROLE_SYSTEM_LINK = $1E;
ROLE_SYSTEM_HELPBALLOON = $1F;
ROLE_SYSTEM_CHARACTER = $20;
ROLE_SYSTEM_LIST = $21;
ROLE_SYSTEM_LISTITEM = $22;
ROLE_SYSTEM_OUTLINE = $23;
ROLE_SYSTEM_OUTLINEITEM = $24;
ROLE_SYSTEM_PAGETAB = $25;
ROLE_SYSTEM_PROPERTYPAGE = $26;
ROLE_SYSTEM_INDICATOR = $27;
ROLE_SYSTEM_GRAPHIC = $28;
ROLE_SYSTEM_STATICTEXT = $29;
ROLE_SYSTEM_TEXT = $2A;
ROLE_SYSTEM_PUSHBUTTON = $2B;
ROLE_SYSTEM_CHECKBUTTON = $2C;
ROLE_SYSTEM_RADIOBUTTON = $2D;
ROLE_SYSTEM_COMBOBOX = $2E;
ROLE_SYSTEM_DROPLIST = $2F;
ROLE_SYSTEM_PROGRESSBAR = $30;
ROLE_SYSTEM_DIAL = $31;
ROLE_SYSTEM_HOTKEYFIELD = $32;
ROLE_SYSTEM_SLIDER = $33;
ROLE_SYSTEM_SPINBUTTON = $34;
ROLE_SYSTEM_DIAGRAM = $35;
ROLE_SYSTEM_ANIMATION = $36;
ROLE_SYSTEM_EQUATION = $37;
ROLE_SYSTEM_BUTTONDROPDOWN = $38;
ROLE_SYSTEM_BUTTONMENU = $39;
ROLE_SYSTEM_BUTTONDROPDOWNGRID = $3A;
ROLE_SYSTEM_WHITESPACE = $3B;
ROLE_SYSTEM_PAGETABLIST = $3C;
ROLE_SYSTEM_CLOCK = $3D;
CHILDID_SELF = 0;
//=== Property GUIDs (used by annotation interfaces)
PROPID_ACC_NAME: TGUID = (D1:$608d3df8; D2:$8128; D3:$4aa7; D4:($a4, $28, $f5, $5e, $49, $26, $72, $91));
PROPID_ACC_VALUE: TGUID = (D1:$123fe443; D2:$211a; D3:$4615; D4:($95, $27, $c4, $5a, $7e, $93, $71, $7a));
PROPID_ACC_DESCRIPTION: TGUID = (D1:$4d48dfe4; D2:$bd3f; D3:$491f; D4:($a6, $48, $49, $2d, $6f, $20, $c5, $88));
PROPID_ACC_ROLE: TGUID = (D1:$cb905ff2; D2:$7bd1; D3:$4c05; D4:($b3, $c8, $e6, $c2, $41, $36, $4d, $70));
PROPID_ACC_STATE: TGUID = (D1:$a8d4d5b0; D2:$0a21; D3:$42d0; D4:($a5, $c0, $51, $4e, $98, $4f, $45, $7b));
PROPID_ACC_HELP: TGUID = (D1:$c831e11f; D2:$44db; D3:$4a99; D4:($97, $68, $cb, $8f, $97, $8b, $72, $31));
PROPID_ACC_KEYBOARDSHORTCUT: TGUID = (D1:$7d9bceee; D2:$7d1e; D3:$4979; D4:($93, $82, $51, $80, $f4, $17, $2c, $34));
PROPID_ACC_HELPTOPIC: TGUID = (D1:$787d1379; D2:$8ede; D3:$440b; D4:($8a, $ec, $11, $f7, $bf, $90, $30, $b3));
PROPID_ACC_FOCUS: TGUID = (D1:$6eb335df; D2:$1c29; D3:$4127; D4:($b1, $2c, $de, $e9, $fd, $15, $7f, $2b));
PROPID_ACC_SELECTION: TGUID = (D1:$b99d073c; D2:$d731; D3:$405b; D4:($90, $61, $d9, $5e, $8f, $84, $29, $84));
PROPID_ACC_PARENT: TGUID = (D1:$474c22b6; D2:$ffc2; D3:$467a; D4:($b1, $b5, $e9, $58, $b4, $65, $73, $30));
PROPID_ACC_NAV_UP: TGUID = (D1:$016e1a2b; D2:$1a4e; D3:$4767; D4:($86, $12, $33, $86, $f6, $69, $35, $ec));
PROPID_ACC_NAV_DOWN: TGUID = (D1:$031670ed; D2:$3cdf; D3:$48d2; D4:($96, $13, $13, $8f, $2d, $d8, $a6, $68));
PROPID_ACC_NAV_LEFT: TGUID = (D1:$228086cb; D2:$82f1; D3:$4a39; D4:($87, $05, $dc, $dc, $0f, $ff, $92, $f5));
PROPID_ACC_NAV_RIGHT: TGUID = (D1:$cd211d9f; D2:$e1cb; D3:$4fe5; D4:($a7, $7c, $92, $0b, $88, $4d, $09, $5b));
PROPID_ACC_NAV_PREV: TGUID = (D1:$776d3891; D2:$c73b; D3:$4480; D4:($b3, $f6, $07, $6a, $16, $a1, $5a, $f6));
PROPID_ACC_NAV_NEXT: TGUID = (D1:$1cdc5455; D2:$8cd9; D3:$4c92; D4:($a3, $71, $39, $39, $a2, $fe, $3e, $ee));
PROPID_ACC_NAV_FIRSTCHILD: TGUID = (D1:$cfd02558; D2:$557b; D3:$4c67; D4:($84, $f9, $2a, $09, $fc, $e4, $07, $49));
PROPID_ACC_NAV_LASTCHILD: TGUID = (D1:$302ecaa5; D2:$48d5; D3:$4f8d; D4:($b6, $71, $1a, $8d, $20, $a7, $78, $32));
PROPID_ACC_ROLEMAP: TGUID = (D1:$f79acda2; D2:$140d; D3:$4fe6; D4:($89, $14, $20, $84, $76, $32, $82, $69));
PROPID_ACC_VALUEMAP: TGUID = (D1:$da1c3d79; D2:$fc5c; D3:$420e; D4:($b3, $99, $9d, $15, $33, $54, $9e, $75));
PROPID_ACC_STATEMAP: TGUID = (D1:$43946c5e; D2:$0ac0; D3:$4042; D4:($b5, $25, $07, $bb, $db, $e1, $7f, $a7));
PROPID_ACC_DESCRIPTIONMAP: TGUID = (D1:$1ff1435f; D2:$8a14; D3:$477b; D4:($b2, $26, $a0, $ab, $e2, $79, $97, $5d));
PROPID_ACC_DODEFAULTACTION: TGUID = (D1:$1ba09523; D2:$2e3b; D3:$49a6; D4:($a0, $59, $59, $68, $2a, $3c, $48, $fd));
implementation
end.
|
{ *********************************************************** }
{ * TForge Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2016 * }
{ *********************************************************** }
unit tfRC4;
{$I TFL.inc}
interface
uses
tfTypes;
type
PRC4Algorithm = ^TRC4Algorithm;
TRC4Algorithm = record
private type
PState = ^TState;
TState = record
S: array[0..255] of Byte;
I, J: Byte;
end;
private
{$HINTS OFF} // -- inherited fields begin --
// from tfRecord
FVTable: Pointer;
FRefCount: Integer;
// from tfStreamCipher
FValidKey: Boolean;
// -- inherited fields end --
FState: TState;
{$HINTS ON}
public
class function Release(Inst: PRC4Algorithm): Integer; stdcall; static;
class function ExpandKey(Inst: PRC4Algorithm; Key: PByte; KeySize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetBlockSize(Inst: PRC4Algorithm): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function DuplicateKey(Inst: PRC4Algorithm; var Key: PRC4Algorithm): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class procedure DestroyKey(Inst: PRC4Algorithm);{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function RandBlock(Inst: PRC4Algorithm; Data: PByte): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
end;
function GetRC4Algorithm(var A: PRC4Algorithm): TF_RESULT;
implementation
uses tfRecords, tfBaseCiphers;
const
RC4VTable: array[0..16] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TRC4Algorithm.Release,
@TRC4Algorithm.DestroyKey,
@TRC4Algorithm.DuplicateKey,
@TRC4Algorithm.ExpandKey,
@TBaseStreamCipher.SetKeyParam,
@TBaseStreamCipher.GetKeyParam,
@TRC4Algorithm.GetBlockSize,
@TBaseStreamCipher.Encrypt,
@TBaseStreamCipher.Decrypt,
@TBaseStreamCipher.EncryptBlock,
@TBaseStreamCipher.EncryptBlock,
@TBaseStreamCipher.GetRand,
@TRC4Algorithm.RandBlock,
@TBaseStreamCipher.RandCrypt,
@TBaseStreamCipher.GetIsBlockCipher
);
function GetRC4Algorithm(var A: PRC4Algorithm): TF_RESULT;
var
Tmp: PRC4Algorithm;
begin
try
Tmp:= AllocMem(SizeOf(TRC4Algorithm));
Tmp^.FVTable:= @RC4VTable;
Tmp^.FRefCount:= 1;
if A <> nil then TRC4Algorithm.Release(A);
A:= Tmp;
Result:= TF_S_OK;
except
Result:= TF_E_OUTOFMEMORY;
end;
end;
{ TRC4Algorithm }
procedure BurnKey(Inst: PRC4Algorithm); inline;
var
BurnSize: Integer;
begin
BurnSize:= SizeOf(TRC4Algorithm)
- Integer(@PRC4Algorithm(nil)^.FValidKey);
FillChar(Inst.FValidKey, BurnSize, 0);
end;
class function TRC4Algorithm.Release(Inst: PRC4Algorithm): Integer;
begin
if Inst.FRefCount > 0 then begin
Result:= tfDecrement(Inst.FRefCount);
if Result = 0 then begin
BurnKey(Inst);
FreeMem(Inst);
end;
end
else
Result:= Inst.FRefCount;
end;
class procedure TRC4Algorithm.DestroyKey(Inst: PRC4Algorithm);
begin
BurnKey(Inst);
end;
class function TRC4Algorithm.DuplicateKey(Inst: PRC4Algorithm;
var Key: PRC4Algorithm): TF_RESULT;
begin
Result:= GetRC4Algorithm(Key);
if Result = TF_S_OK then begin
Key.FValidKey:= Inst.FValidKey;
Key.FState:= Inst.FState;
end;
end;
class function TRC4Algorithm.ExpandKey(Inst: PRC4Algorithm; Key: PByte;
KeySize: Cardinal): TF_RESULT;
var
I: Cardinal;
J, Tmp: Byte;
begin
I:= 0;
repeat
Inst.FState.S[I]:= I;
Inc(I);
until I = 256;
I:= 0;
J:= 0;
repeat
J:= J + Inst.FState.S[I] + Key[I mod KeySize];
Tmp:= Inst.FState.S[I];
Inst.FState.S[I]:= Inst.FState.S[J];
Inst.FState.S[J]:= Tmp;
Inc(I);
until I = 256;
Inst.FState.I:= 0;
Inst.FState.J:= 0;
Inst.FValidKey:= True;
Result:= TF_S_OK;
end;
class function TRC4Algorithm.GetBlockSize(Inst: PRC4Algorithm): Integer;
begin
Result:= 1;
end;
class function TRC4Algorithm.RandBlock(Inst: PRC4Algorithm; Data: PByte): TF_RESULT;
var
Tmp: Byte;
State: PState;
begin
State:= @Inst.FState;
Inc(State.I);
Tmp:= State.S[State.I];
State.J:= State.J + Tmp;
State.S[State.I]:= State.S[State.J];
State.S[State.J]:= Tmp;
Tmp:= Tmp + State.S[State.I];
Data^:= State.S[Tmp];
Result:= TF_S_OK;
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ TDataCollectionItem (Collection Item) }
{ Copyright (c) 2015-2017 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit BI.CollectionItem;
interface
{
TDataCollectionItem is a derived class of TCollectionItem.
It can be used to create custom TCollection classes where each item
can reference to a TDataItem and / or a TDataProvider.
For example, TBIQuery and TBIWorkflow components use this class for their
collections.
}
uses
{System.}Classes, BI.DataItem, BI.Expression;
type
TDataCollectionItem=class(TCollectionItem)
private
FName : String;
FOnChange: TNotifyEvent;
procedure AddNotify;
function GetData: TDataItem;
procedure InternalSetProvider(const Value: TComponent);
function LoadOrigin:TDataItem;
procedure Notify(const AEvent:TBIEvent);
procedure NotifyDataDestroy(const AEvent:TBIEvent);
function Origin:String;
procedure ReadOrigin(Reader: TReader);
procedure RemoveNotify;
procedure SetDataDirect(const Value: TDataItem);
procedure WriteOrigin(Writer: TWriter);
protected
FData : TDataItem;
FProvider : TComponent;
IOrigin : String;
IUpdating : Integer;
procedure BeginUpdate; inline;
procedure Changed; virtual;
procedure DefineProperties(Filer: TFiler); override;
procedure EndUpdate;
function GetDisplayName:String; override;
procedure Loaded; virtual;
function Owner:TComponent; virtual;
procedure SetData(const Value: TDataItem); virtual;
procedure SetProvider(const Value: TComponent); virtual;
procedure ValidateData(const AData:TDataItem); virtual;
public
Destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Data:TDataItem read GetData write SetData;
property Name:String read FName write FName;
property Provider:TComponent read FProvider write SetProvider;
property OnChange:TNotifyEvent read FOnChange write FOnChange;
end;
implementation
|
unit Unit16;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls;
type
TForm16 = class(TForm)
ListBox1: TListBox;
Label1: TLabel;
LabeledEdit1: TLabeledEdit;
ComboBox1: TComboBox;
Label2: TLabel;
Label3: TLabel;
DateTimePicker1: TDateTimePicker;
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form16: TForm16;
implementation
{$R *.dfm}
procedure TForm16.Button2Click(Sender: TObject);
begin
ListBox1.Clear;
LabeledEdit1.Clear;
ComboBox1.Clear;
DateTimePicker1.Date:=Date;
Form16.Visible:=False;
end;
procedure TForm16.Button1Click(Sender: TObject);
begin
if LabeledEdit1.Text='' then
begin
ShowMessage('Вы не вписали номер документа!');
Exit;
end;
if (ComboBox1.Items.Strings[ComboBox1.ItemIndex]<>'') then
ListBox1.Items.Append('"'+ComboBox1.Items.Strings[ComboBox1.ItemIndex]+'","'+LabeledEdit1.Text+'","'+datetostr(DateTimePicker1.Date)+'"')
else ShowMessage('Вы не выбрали тип документа!');
end;
procedure TForm16.Button3Click(Sender: TObject);
var f:TextFile;
i:integer;
begin
if ListBox1.Count>0 then
try
AssignFile(f,'getdocp.f');
Rewrite(f);
for i:=0 to ListBox1.Count-1 do
Writeln(f,ListBox1.Items.Strings[i]);
CloseFile(f);
ShowMessage('Запрос отправлен! Подключитесь к интернету для получения документов.');
ShowMessage('Документы будут помещены в C:\Инвентаризация\');
ListBox1.Clear;
LabeledEdit1.Clear;
ComboBox1.Clear;
DateTimePicker1.Date:=Date;
Form16.Visible:=False;
except
ShowMessage('Нет доступа к диску!');
end else
ShowMessage('Вы не заполнили список для запроса!');
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit BindingGraphResStrs;
interface
resourcestring
sInvalidNodeIndex = 'Node index %d is not valid.';
sInvalidOwner = 'The owner of this entity is not the current graph.';
sUnattachedGraphView = 'The graph must have a graph view to which is attached.';
implementation
end.
|
unit SIP_RingList;
interface
uses Classes,DB, SyncObjs;
type
TSIPAddress=class(TCriticalSection)
private
FStatus: String;
FReport: String;
procedure SetStatus(const Value: String);
public
Phone,
DTMF,
MobilePhone,
HomePhone,
OrganisationName,
DivisionName,
PersonName,
PositionName,
Site,
EMail,
Code,
RingGroupName,
Address1,
Address2:String;
Tick:Int64;
ID:Integer;
RetryBusy,RetryBusyRoute,RetryFailDTMF:Integer;
DelayBusy,DelayBusyRoute,DelayFailDTMF:Integer;
RingSequence:String;
ActivePhone:String;
TryCount:Integer;
StatusTime:TDateTime;
ResultSIP,ResultMail,ResultSMS:String;
function Method:String;
function SucceedMethod:String;
function ObjectName:String;
property Status:String read FStatus write SetStatus;
procedure AddReport(const S:String);
function SucceedState:String;
end;
TSIPRingList=class(TThreadList)
private
Counter:Integer;
public
procedure Add(Q:TDataSet);
procedure AddAddress(A:TSIPAddress;Delay:Cardinal);
function Get:TSIPAddress;
function Count:Integer;
function Status(Prefix:String;IDPrefix:String;Journal:Boolean;AutoState:Boolean):String;
destructor Destroy;override;
end;
implementation
uses Windows,Util, SysUtils, SIP_Monitor;
{ TSIPCallList }
procedure TSIPRingList.Add(Q:TDataSet);
var A:TSIPAddress;
function Field(const S:String):String;
var F:TField;
begin
F:=Q.FindField(S);
if F<>nil then
Result:=F.AsString
else
Result:='';
end;
begin
if (Field('Phone')='') and (Field('MobilePhone')='') and (Field('HomePhone')='') then Exit;
A:=TSIPAddress.Create;
A.ID:=InterlockedIncrement(Counter);
A.Phone:=Field('Phone');
A.MobilePhone:=Field('MobilePhone');
A.HomePhone:=Field('HomePhone');
A.DTMF:=Field('DTMF');
A.Code:=Field('Code');
A.RingGroupName:=Field('RingGroupName');
A.OrganisationName:=Field('OrganisationName');
A.DivisionName:=Field('DivisionName');
A.PositionName:=Field('PositionName');
A.PersonName:=Field('PersonName');
A.email:=Field('email');
A.site:=Field('site');
A.address1:=Field('address1');
A.address2:=Field('address2');
A.TryCount:=1;
A.Tick:=0;
AddAddress(A,0);
end;
procedure TSIPRingList.AddAddress;
var
B:TSIPAddress;
L:TList;
I:Integer;
begin
if (Delay=0) then
inherited Add(A)
else
begin
A.Tick:=GetTick64+Delay*1000;
L:=LockList;
try
if L.Count=0 then
L.Add(A)
else
for I := L.Count - 1 downto 0 do
begin
B:=L[I];
if (I=0) or (A.Tick>=B.Tick) then
begin
L.Insert(I,A);
Break;
end;
end;
finally
UnlockList;
end;
end;
end;
function TSIPRingList.Count: Integer;
var L:TList;
begin
L:=LockList;
try
Result:=L.Count;
finally
UnlockList
end;
end;
destructor TSIPRingList.Destroy;
var A:TSIPAddress;
L:TList;
I: Integer;
begin
L:=LockList;
try
for I := 0 to L.Count - 1 do
begin
A:=L.Items[I];
A.Free;
end;
L.Clear;
finally
UnlockList;
end;
inherited;
end;
function TSIPRingList.Get;
var A:TSIPAddress;
L:TList;
begin
L:=LockList;
try
if L.Count>0 then
begin
A:=L.Items[0];
if (A.Tick>GetTick64) then
begin
Result:=nil;
Exit;
end;
L.Delete(0);
Result:=A;
end else
begin
Result:=nil;
end;
finally
UnlockList;
end;
end;
function TSIPRingList.Status;
var A:TSIPAddress;
L:TList;
I:Integer;
begin
Result:='';
L:=LockList;
try
for I := 0 to L.Count - 1 do
begin
A:=L.Items[I];
if I>0 then Result:=Result+',{' else Result:=Result+'{';
Result:=Result+Prefix;
if AutoState then
Result:=Result+',"state":"'+A.SucceedState+'",';
Result:=Result+'"try":'+IntToStr(A.TryCount)+',';
Result:=Result+'"status":'+StrEscape(A.Status)+',';
if A.StatusTime>0 then
Result:=Result+'"statustime":'+StrEscape(FormatDateTime('yyyy-mm-dd hh:nn:ss',A.StatusTime))+',';
{if A.Data<>'' then
Result:=Result+'"data":'+StrEscape(A.Data)+',';}
Result:=Result+'"resultsip":'+StrEscape(A.ResultSIP)+',';
Result:=Result+'"resultsms":'+StrEscape(A.ResultSMS)+',';
Result:=Result+'"resultmail":'+StrEscape(A.ResultMail)+',';
if Journal then
Result:=Result+'"journal":'+StrEscape(A.FReport)+',';
Result:=Result+'"id":'+StrEscape(IDPrefix+IntToStr(A.ID))+',';
Result:=Result+'"phone":'+StrEscape(A.Phone)+',';
Result:=Result+'"mobilephone":'+StrEscape(A.MobilePhone)+',';
Result:=Result+'"homephone":'+StrEscape(A.HomePhone)+',';
Result:=Result+'"code":'+StrEscape(A.Code)+',';
Result:=Result+'"ringgroupname":'+StrEscape(A.RingGroupName)+',';
Result:=Result+'"organisationname":'+StrEscape(A.OrganisationName)+',';
Result:=Result+'"divisionname":'+StrEscape(A.DivisionName)+',';
Result:=Result+'"positionname":'+StrEscape(A.positionname)+',';
Result:=Result+'"personname":'+StrEscape(A.personname)+',';
Result:=Result+'"email":'+StrEscape(A.email)+',';
Result:=Result+'"site":'+StrEscape(A.site)+',';
Result:=Result+'"address1":'+StrEscape(A.address1)+',';
Result:=Result+'"address2":'+StrEscape(A.address2);
Result:=Result+'}';
end;
finally
UnlockList;
end;
end;
{ TSIPAddress }
procedure TSIPAddress.AddReport(const S: String);
begin
Enter;
try
if FReport<>'' then FReport:=FReport+#13#10;
FReport:=FReport+FormatDateTime('yyyy-mm-dd hh:nn:ss ',Now)+S;
finally
Leave;
end;
end;
function TSIPAddress.Method: String;
begin
Result:='';
if RingSequence='' then
begin
Result:='служ. тел.';
end else
case RingSequence[1] of
'1':Result:='служ. тел.';
'2':Result:='дом. тел.';
'3':Result:='моб. тел.';
's':Result:='SMS';
'm':Result:='EMail';
end;
end;
function TSIPAddress.ObjectName: String;
procedure Add(const S:String);
begin
if S<>'' then
begin
if Result<>'' then Result:=Result+', ';
Result:=Result+S;
end;
end;
begin
Result:='';
Add(OrganisationName);
Add(DivisionName);
Add(PositionName);
end;
procedure TSIPAddress.SetStatus(const Value: String);
begin
FStatus := Value;
StatusTime:=Now;
end;
function TSIPAddress.SucceedMethod: String;
begin
Result:='';
if RingSequence='' then
begin
Result:='succeedwork';
end else
case RingSequence[1] of
'1':Result:='succeedwork';
'2':Result:='succeedhome';
'3':Result:='succeedmobile';
's':Result:='fail';
'm':Result:='fail';
end;
end;
function TSIPAddress.SucceedState: String;
begin
if SameText(ResultSIP,'fail') or SameText(ResultSIP,'') then
Result:='алтернативно оповестени'
else
Result:='успешно оповестени';
end;
end.
|
{
Serial communication port (UART). In Windows it COM-port, real or virtual.
In Linux it /dev/ttyS or /dev/ttyUSB. Also, Linux use file /var/FLock/LCK..ttyS for port FLocking
(C) Sergey Bodrov, 2012-2018
Properties:
Port - port name (COM1, /dev/ttyS01)
BaudRate - data excange speed
DataBits - default 8 (5 for Baudot code, 7 for true ASCII)
Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N
StopBits - (stb1, stb15, stb2), default stb1
FlowControl - (sfcNone, sfcSend, sfcReady, sfcSoft) default sfcNone
sfcSend - SEND signal pair CTS/RTS, used for hardware flow control
sfcReady - READY signal pair DTR/DSR, used for modem control
sfcSoft - software flow control XON/XOFF byte ($11 for resume and $13 for pause transmission)
MinDataBytes - minimal bytes count in buffer for triggering event OnDataAppear
Methods:
Open() - Opens port. As parameter it use port initialization string:
InitStr = 'Port,BaudRate,DataBits,Parity,StopBits,SoftFlow,HardFlow'
Port - COM port name (COM1, /dev/ttyS01)
BaudRate - connection speed (50..4000000 bits per second), default 9600
DataBits - default 8
Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N
StopBits - (1, 1.5, 2) default 0
SoftFlow - Enable XON/XOFF handshake, default 0
HardFlow - Enable CTS/RTS handshake, default 0
Events:
OnOpen - Triggered after sucсessful connection.
OnClose - Triggered after disconnection.
Roles:
Data Terminal Equipment (DTE) - computer terminal
Data Circuit-terminating Equipment (DCE) - modem, peripreral device
}
unit DataPortUART;
interface
uses
SysUtils, Classes, DataPort;
type
TSerialStopBits = (stb1, stb15, stb2);
TSerialFlowControl = (sfcNone, sfcSend, sfcReady, sfcSoft);
TModemStatus = record
{ RTS (Request to send) signal (w) - DTE requests the DCE prepare to transmit data. }
{ RTR (Ready To Receive) (w) - DTE is ready to receive data from DCE. If in use, RTS is assumed to be always asserted. }
RTS: Boolean;
{ CTS (Clear to send) signal (r) - DCE is ready to accept data from the DTE. }
CTS: boolean;
{ DTR (Data Terminal Ready) signal (w) - DTE is ready to receive, initiate, or continue a call. }
DTR: Boolean;
{ DSR (Data Set Ready) signal (r) - DCE is ready to receive and send data. }
DSR: Boolean;
{ Data Carrier Detect (r) - DCE is receiving a carrier from a remote DCE. }
Carrier: Boolean;
{ Ring Indicator (r) - DCE has detected an incoming ring signal on the telephone line. }
Ring: Boolean;
end;
{ TDataPortUART - serial DataPort }
TDataPortUART = class(TDataPort)
private
FOnModemStatus: TNotifyEvent;
FOnDataAppearUnsafe: TNotifyEvent;
procedure SetHardFlow(AValue: Boolean);
procedure SetSoftFlow(AValue: Boolean);
protected
FReadDataStr: AnsiString;
{$ifdef FPC}
FLock: TSimpleRWSync;
{$else}
FLock: TMultiReadExclusiveWriteSynchronizer;
{$endif}
FPort: string;
FBaudRate: Integer;
FDataBits: Integer;
FParity: AnsiChar;
FStopBits: TSerialStopBits;
FFlowControl: TSerialFlowControl;
FSoftFlow: Boolean;
FHardFlow: Boolean;
FMinDataBytes: Integer;
FHalfDuplex: Boolean;
FModemStatus: TModemStatus;
procedure SetBaudRate(AValue: Integer); virtual;
procedure SetDataBits(AValue: Integer); virtual;
procedure SetParity(AValue: AnsiChar); virtual;
procedure SetStopBits(AValue: TSerialStopBits); virtual;
procedure SetFlowControl(AValue: TSerialFlowControl); virtual;
procedure OnIncomingMsgHandler(Sender: TObject; const AMsg: string); virtual;
procedure OnErrorHandler(Sender: TObject; const AMsg: string); virtual;
procedure OnConnectHandler(Sender: TObject); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
{ Open serial DataPort
InitStr = 'Port,BaudRate,DataBits,Parity,StopBits,SoftFlow,HardFlow'
Port - COM port name (COM1, /dev/tty01)
BaudRate - connection speed (50..4000000 bits per second), default 9600
DataBits - default 8
Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N
StopBits - (1, 1.5, 2)
SoftFlow - Enable XON/XOFF handshake, default 0
HardFlow - Enable CTS/RTS handshake, default 0 }
procedure Open(const AInitStr: string = ''); override;
function Pull(ASize: Integer = MaxInt): AnsiString; override;
function Peek(ASize: Integer = MaxInt): AnsiString; override;
function PeekSize(): Cardinal; override;
{ Get modem wires status (DSR,CTS,Ring,Carrier) }
function GetModemStatus(): TModemStatus; virtual;
{ Set DTR (Data Terminal Ready) signal }
procedure SetDTR(AValue: Boolean); virtual;
{ Set RTS (Request to send) signal }
procedure SetRTS(AValue: Boolean); virtual;
{ Modem wires status }
property ModemStatus: TModemStatus read FModemStatus;
published
{ Serial port name (COM1, /dev/ttyS01) }
property Port: string read FPort write FPort;
{ BaudRate - connection speed (50..4000000 bits per second), default 9600 }
property BaudRate: Integer read FBaudRate write SetBaudRate;
{ DataBits - default 8 (5 for Baudot code, 7 for true ASCII) }
property DataBits: Integer read FDataBits write SetDataBits;
{ Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N }
property Parity: AnsiChar read FParity write SetParity;
{ StopBits - (stb1, stb15, stb2), default stb1 }
property StopBits: TSerialStopBits read FStopBits write SetStopBits;
{ Flow control - (sfcNone, sfcRTS, sfcDTR, sfcXON) default sfcNone
sfcSend - SEND signal pair CTS/RTS, used for hardware flow control
sfcReady - READY signal pair DTR/DSR, used for modem control
sfcSoft - software flow control XON/XOFF byte ($11 for resume and $13 for pause transmission) }
property FlowControl: TSerialFlowControl read FFlowControl write SetFlowControl;
{ deprecated, set to False and use FlowControl }
property SoftFlow: Boolean read FSoftFlow write SetSoftFlow; {$ifdef FPC}deprecated;{$endif}
{ deprecated, set to False and use FlowControl }
property HardFlow: Boolean read FHardFlow write SetHardFlow; {$ifdef FPC}deprecated;{$endif}
{ Minimum bytes in incoming buffer to trigger OnDataAppear }
property MinDataBytes: Integer read FMinDataBytes write FMinDataBytes;
{ Use half-duplex for send and receive data }
property HalfDuplex: Boolean read FHalfDuplex write FHalfDuplex;
property Active;
property OnDataAppear;
property OnError;
property OnOpen;
property OnClose;
{ Triggered when modem status changed }
property OnModemStatus: TNotifyEvent read FOnModemStatus write FOnModemStatus;
{ Triggered when data appeared (not thread-safe, called from inner thread!) }
property OnDataAppearUnsafe: TNotifyEvent read FOnDataAppearUnsafe write FOnDataAppearUnsafe;
end;
function ExtractFirstWord(var s: string; const delimiter: string = ' '): string;
implementation
function ExtractFirstWord(var s: string; const delimiter: string = ' '): string;
var
i: Integer;
begin
Result := '';
i := Pos(delimiter, s);
if i > 0 then
begin
Result := Copy(s, 1, i - 1);
s := Copy(s, i + 1, maxint);
end
else
begin
Result := s;
s := '';
end;
end;
{ TDataPortUART }
constructor TDataPortUART.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{$ifdef FPC}
FLock := TSimpleRWSync.Create();
{$else}
FLock := TMultiReadExclusiveWriteSynchronizer.Create();
{$endif}
FPort := 'COM1';
FBaudRate := 9600;
FDataBits := 8;
FParity := 'N';
FStopBits := stb1;
FFlowControl := sfcNone;
FMinDataBytes := 1;
FActive := False;
//Self.slReadData := TStringList.Create();
FReadDataStr := '';
end;
procedure TDataPortUART.Open(const AInitStr: string = '');
var
s, ss: string;
begin
ss := AInitStr;
// Port
s := ExtractFirstWord(ss, ',');
if s <> '' then
FPort := s;
// BaudRate
s := ExtractFirstWord(ss, ',');
FBaudRate := StrToIntDef(s, FBaudRate);
// DataBits
s := ExtractFirstWord(ss, ',');
FDataBits := StrToIntDef(s, FDataBits);
// Parity
s := ExtractFirstWord(ss, ',');
if s <> '' then
FParity := s[1];
if Pos(FParity, 'NOEMSnoems') = 0 then
FParity := 'N';
// StopBits
s := ExtractFirstWord(ss, ',');
if s = '1' then
FStopBits := stb1
else if s = '1.5' then
FStopBits := stb15
else if s = '2' then
FStopBits := stb2;
FFlowControl := sfcNone;
// SoftFlow
s := ExtractFirstWord(ss, ',');
if s = '1' then
FFlowControl := sfcSoft;
// HardFlow
s := ExtractFirstWord(ss, ',');
if s = '1' then
FFlowControl := sfcSend;
// don't inherits Open() - OnOpen event will be after successfull connection
end;
destructor TDataPortUART.Destroy();
begin
FreeAndNil(FLock);
inherited Destroy();
end;
procedure TDataPortUART.OnIncomingMsgHandler(Sender: TObject; const AMsg: string);
begin
if AMsg <> '' then
begin
if FLock.BeginWrite then
begin
FReadDataStr := FReadDataStr + AMsg;
FLock.EndWrite;
if Length(FReadDataStr) >= MinDataBytes then
begin
if Assigned(OnDataAppearUnsafe) then
OnDataAppearUnsafe(Self);
if Assigned(OnDataAppear) then
OnDataAppear(Self);
end;
end;
end
else
begin
FModemStatus := GetModemStatus();
if Assigned(OnModemStatus) then
OnModemStatus(Self);
end;
end;
procedure TDataPortUART.OnErrorHandler(Sender: TObject; const AMsg: string);
begin
FActive := False;
if (AMsg <> '') and Assigned(OnError) then
OnError(Self, AMsg)
else if Assigned(OnClose) then
OnClose(Self);
end;
procedure TDataPortUART.OnConnectHandler(Sender: TObject);
begin
FActive := True;
if Assigned(OnOpen) then
OnOpen(Self);
end;
function TDataPortUART.Peek(ASize: Integer): AnsiString;
begin
FLock.BeginRead();
try
Result := Copy(FReadDataStr, 1, ASize);
finally
FLock.EndRead();
end;
end;
function TDataPortUART.PeekSize(): Cardinal;
begin
FLock.BeginRead();
try
Result := Cardinal(Length(FReadDataStr));
finally
FLock.EndRead();
end;
end;
function TDataPortUART.GetModemStatus(): TModemStatus;
begin
Result := FModemStatus;
end;
procedure TDataPortUART.SetDTR(AValue: Boolean);
begin
FModemStatus.DTR := AValue;
end;
procedure TDataPortUART.SetRTS(AValue: Boolean);
begin
FModemStatus.RTS := AValue;
end;
function TDataPortUART.Pull(ASize: Integer): AnsiString;
begin
Result := '';
if FLock.BeginWrite() then
begin
try
Result := Copy(FReadDataStr, 1, ASize);
Delete(FReadDataStr, 1, ASize);
finally
FLock.EndWrite();
end;
end;
end;
procedure TDataPortUART.SetHardFlow(AValue: Boolean);
begin
FHardFlow := AValue;
if FHardFlow then
FFlowControl := sfcSend;
end;
procedure TDataPortUART.SetSoftFlow(AValue: Boolean);
begin
FSoftFlow := AValue;
if FSoftFlow then
FFlowControl := sfcSoft;
end;
procedure TDataPortUART.SetBaudRate(AValue: Integer);
begin
FBaudRate := AValue;
end;
procedure TDataPortUART.SetDataBits(AValue: Integer);
begin
if (AValue < 5) or (AValue > 9) then
Exit;
FDataBits := AValue;
end;
procedure TDataPortUART.SetFlowControl(AValue: TSerialFlowControl);
begin
FFlowControl := AValue;
end;
procedure TDataPortUART.SetParity(AValue: AnsiChar);
begin
if Pos(AValue, 'NOEMSnoems') > 0 then
FParity := AValue;
end;
procedure TDataPortUART.SetStopBits(AValue: TSerialStopBits);
begin
FStopBits := AValue;
end;
end.
|
{ Demonstrates FreeNotication to safely link to controls in other forms
through form linking and demonstrates preventing a component from being used
in form inheritence }
unit DemoLbl;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TDemoLabel = class(TGraphicControl)
private
FFocusControl: TWinControl;
procedure SetFocusControl(Value: TWinControl);
procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
published
property Caption;
property Color;
property FocusControl: TWinControl read FFocusControl write SetFocusControl;
property Font;
property ParentColor;
property ParentFont;
end;
procedure Register;
implementation
{ TDemoLabel }
constructor TDemoLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FComponentStyle := FComponentStyle - [csInheritable];
end;
procedure TDemoLabel.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FFocusControl) then
FFocusControl := nil;
end;
procedure TDemoLabel.SetFocusControl(Value: TWinControl);
begin
FFocusControl := Value;
{ Calling FreeNotification ensures that this component will receive an
opRemove when Value is either removed from its owner or when it is
destroyed. }
Value.FreeNotification(Value);
end;
procedure TDemoLabel.Paint;
var
Rect: TRect;
begiN
Rect := ClientRect;
Canvas.Font := Font;
Canvas.Brush.Color := Color;
Canvas.FillRect(Rect);
DrawText(Canvas.Handle, PChar(Caption), Length(Caption), Rect,
DT_EXPANDTABS or DT_WORDBREAK or DT_LEFT);
end;
procedure TDemoLabel.CMDialogChar(var Message: TCMDialogChar);
begin
if (FFocusControl <> nil) and Enabled and
IsAccel(Message.CharCode, Caption) then
with FFocusControl do
if CanFocus then
begin
SetFocus;
Message.Result := 1;
end;
end;
procedure TDemoLabel.CMTextChanged(var Message: TMessage);
begin
inherited;
Invalidate;
end;
procedure Register;
begin
RegisterComponents('Samples', [TDemoLabel]);
end;
end.
|
// This is the parent RDM. All access to the server is done through
// this RDM. The property ChildDM was added to the type library, and
// is of type IChildDM. In this example, IChildDM descends from
// IBaseDM, which in turn descends from IAppServer. Using this
// technique, you can add common properties to the IBaseDM interface.
//
// Also note that you must take care to have your children RDM use
// their data-access components in a thread-safe manner. For the BDE,
// this means having a separate SessionName for each connection.
// As each parent RDM is created in a new thread, and the
// TSession.AutoSessionName property is set to true on this RDM,
// we will pass the session name to the children RDM so that they
// may use BDE datasets.
unit uDM1;
interface
uses
Windows, Messages, SysUtils, Classes, ComServ, ComObj, VCLCom, DataBkr,
DBClient, ShareServer_TLB, StdVcl, DBTables;
type
TMainRDM = class(TRemoteDataModule, IMainRDM)
Session1: TSession;
private
{ Private declarations }
protected
class procedure UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); override;
function Get_ChildDM: IChildRDM; safecall;
function MainMethod: WideString; safecall;
function Get_Session: Integer; safecall;
public
{ Public declarations }
end;
implementation
uses
uDM2;
{$R *.DFM}
class procedure TMainRDM.UpdateRegistry(Register: Boolean; const ClassID, ProgID: string);
begin
if Register then
begin
inherited UpdateRegistry(Register, ClassID, ProgID);
EnableSocketTransport(ClassID);
EnableWebTransport(ClassID);
end else
begin
DisableSocketTransport(ClassID);
DisableWebTransport(ClassID);
inherited UpdateRegistry(Register, ClassID, ProgID);
end;
end;
function TMainRDM.Get_ChildDM: IChildRDM;
begin
Result := FChildRDMFactory.CreateComObject(nil) as IChildRDM;
Result.MainDM := Self;
Result.SessionName := Session1.SessionName;
end;
function TMainRDM.MainMethod: WideString;
begin
Result := 'Calling MainMethod';
end;
function TMainRDM.Get_Session: Integer;
begin
Result := Integer(Session1);
end;
initialization
TComponentFactory.Create(ComServer, TMainRDM,
Class_MainRDM, ciMultiInstance, tmApartment);
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program QBSEQ;
Uses Math;
Const
maxN =1000;
maxK =50;
Var
n :Integer;
k,x,y :Byte;
A :Array[1..maxN] of Integer;
F :Array[0..1,0..maxK] of Integer;
procedure Enter;
var
i :Integer;
begin
Read(n,k);
for i:=1 to n do
begin
Read(A[i]); A[i]:=A[i] mod k;
end;
end;
function Sub(i,j :Integer) :Integer;
var
tmp :Integer;
begin
tmp:=i-j;
if (tmp<0) then Inc(tmp,k);
Sub:=tmp;
end;
procedure Optimize;
var
i :Integer;
j :Byte;
begin
for i:=1 to k-1 do F[0,i]:=-n-1;
F[0,0]:=0;
x:=0; y:=1;
for i:=1 to n do
begin
for j:=0 to k-1 do
F[y,j]:=Max(F[x,j],F[x,Sub(j,A[i])]+1);
x:=1-x; y:=1-y;
end;
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Enter;
Optimize;
Write(F[x,0]);
Close(Input); Close(Output);
End. |
unit ACalendarioBase;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
BotaoCadastro, StdCtrls, Buttons, Db, DBTables, Tabela, CBancoDados,
Componentes1, ExtCtrls, PainelGradiente, Mask, DBCtrls, ComCtrls, Grids,
DBGrids, DBKeyViolation, DBClient;
type
TFCalendarioBase = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
CalendarioBase: TRBSQL;
BFechar: TBitBtn;
CalendarioBaseDATBASE: TDateField;
DataCalendarioBase: TDataSource;
GridIndice1: TGridIndice;
BGerar: TBitBtn;
Label1: TLabel;
Label2: TLabel;
EDatInicio: TCalendario;
EDatFim: TCalendario;
CGerarSabado: TCheckBox;
CGerarDomingo: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure EDatInicioExit(Sender: TObject);
procedure BGerarClick(Sender: TObject);
procedure GridIndice1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
procedure AtualizaConsulta;
public
{ Public declarations }
end;
var
FCalendarioBase: TFCalendarioBase;
implementation
uses APrincipal, FunSql, FunData, ConstMsg;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFCalendarioBase.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
EDatInicio.datetime := PrimeiroDiaMes(date);
EDatFim.dateTime := UltimoDiaMes(date);
AtualizaConsulta;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFCalendarioBase.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
CalendarioBase.close;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFCalendarioBase.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFCalendarioBase.AtualizaConsulta;
begin
AdicionaSQLAbreTabela(CalendarioBase,'Select * from CALENDARIOBASE'+
' Where ' +SQLTextoDataEntreAAAAMMDD('DATBASE',EDatInicio.Datetime,EDatFim.DateTime,false)+
' order by DATBASE');
end;
{******************************************************************************}
procedure TFCalendarioBase.EDatInicioExit(Sender: TObject);
begin
AtualizaConsulta;
end;
{******************************************************************************}
procedure TFCalendarioBase.BGerarClick(Sender: TObject);
var
Vpfdata, VpfDatFim : TDateTime;
begin
Vpfdata := date;
if EntraData('Mês a ser gerado','Informe o Mês : ',Vpfdata) then
begin
Vpfdata := PrimeiroDiaMes(VpfData);
VpfDatFim := UltimoDiaMes(VpfData);
while VpfData <= VpfDatFim do
begin
if (CGerarSabado.Checked or (DiaSemanaNumerico(Vpfdata) <>7) ) and
(CGerarDomingo.Checked or (DiaSemanaNumerico(VpfData) <>1)) then
begin
CalendarioBase.Insert;
CalendarioBaseDATBASE.AsDateTime := VpfData;
try
CalendarioBase.Post;
except
end;
end;
Vpfdata := IncDia(vpfData,1);
end;
AtualizaConsulta;
end;
end;
{******************************************************************************}
procedure TFCalendarioBase.GridIndice1KeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (key = 46) then
if CalendarioBase.State = dsbrowse then
if Confirmacao(CT_DeletarItem) then
CalendarioBase.Delete;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFCalendarioBase]);
end.
|
{ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: QuickReport 3.0 for Delphi 3.0/4.0/5.0/6.0 ::
:: ::
:: Example reports project ::
:: ::
:: Copyright (c) 1995-1999 QuSoft AS ::
:: All Rights Reserved ::
:: ::
:: web: http://www.qusoft.com fax: +47 22 41 74 91 ::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: }
unit mdmain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, quickrpt, Db, DBTables, printers, qrextra, QRExport,
qrprntr;
const
Composite_Description = 'The composite control can be used to link several'+
' reports together as a single report.';
type
TfrmQR3Demo = class(TForm)
QRTextFilter1: TQRTextFilter;
QRCSVFilter1: TQRCSVFilter;
QRHTMLFilter1: TQRHTMLFilter;
QRCompositeReport1: TQRCompositeReport;
Label1: TLabel;
VersionLbl: TLabel;
Label3: TLabel;
GroupBox1: TGroupBox;
rbCreateList: TRadioButton;
btnPreview: TButton;
btnPrint: TButton;
rbMasterDetail: TRadioButton;
Description: TMemo;
OpenDialog1: TOpenDialog;
cbPreview: TComboBox;
Label4: TLabel;
rbExprMemo: TRadioButton;
rbImage: TRadioButton;
rbBasicMD: TRadioButton;
btnFilters: TButton;
rbComposite: TRadioButton;
Label5: TLabel;
rbNeedData: TRadioButton;
rbFormLetter: TRadioButton;
btnExport: TButton;
SaveDialog1: TSaveDialog;
rbAbout: TRadioButton;
rbGrouping: TRadioButton;
Image2: TImage;
procedure CreateList(Sender: TObject);
procedure QRCompositeReport1AddReports(Sender: TObject);
procedure btnCRClick(Sender: TObject);
procedure rbCreateListClick(Sender: TObject);
procedure rbMasterDetailClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure btnPreviewClick(Sender: TObject);
procedure rbExprMemoClick(Sender: TObject);
procedure rbImageClick(Sender: TObject);
procedure rbBasicMDClick(Sender: TObject);
procedure btnFiltersClick(Sender: TObject);
procedure rbCompositeClick(Sender: TObject);
procedure rbNeedDataClick(Sender: TObject);
procedure rbFormLetterClick(Sender: TObject);
procedure btnExportClick(Sender: TObject);
procedure rbAboutClick(Sender: TObject);
procedure rbGroupingClick(Sender: TObject);
private
{ Private declarations }
FReport : TCustomQuickRep;
CreateListReport : TQuickRep;
procedure SetReport(Value : TCustomQuickRep);
public
{ Public declarations }
property Report : TCustomQuickRep read FReport write SetReport;
end;
var
frmQR3Demo: TfrmQR3Demo;
implementation
uses mdrpt, exprmemo, image, basicmd, needdata, frmltr,
history, grouping;
{$R *.dfm}
procedure TfrmQR3Demo.SetReport(Value : TCustomQuickRep);
begin
FReport := Value;
if Value <> nil then
if Value = TCustomQuickRep(QRCompositeReport1) then
Description.Lines.Text := Composite_Description
else
Description.Lines.Assign(Report.Description);
end;
procedure TfrmQR3Demo.CreateList(Sender: TObject);
var
aReport : TCustomQuickRep;
SomeFields: TStringList;
MyTable: TTable;
nIdx: integer;
begin
{ Create a table on the fly, this example uses a table from the demo database }
MyTable := TTable.Create(self);
{ create the list of fields to output from the table }
SomeFields := TStringList.Create;
with MyTable do
begin
DatabaseName := 'DBDEMOS';
TableName := 'COUNTRY.DB';
ReadOnly := True;
Active := True;
// For this example, we will pull the field names from the table
// If you wanted to only use some of the fields, you would edit
// this list.
for nIdx := 0 to FieldCount - 1 do
SomeFields.Add(Fields[nIdx].FieldName);
end;
// If you didn't create the report, you must set the report object to nil
// before calling QRCreateList
areport := nil;
{ Build the report }
// If you change the displaywidth, it will be reflecte in the created
// report
with MyTable.Fields[1] do
DisplayWidth := DisplayWidth div 2;
// create the report
QRCreateList(aReport, nil, MyTable, 'Country Listing', SomeFields);
// Make the column header's font use bold attribute
aReport.Bands.ColumnHeaderBand.Font.Style := [fsBold];
// Now adjust the spacing of the fields. There isn't any reason to
// do this, this is just to show how to access the controls on the
// report.
for nIdx := 0 to aReport.Bands.ColumnHeaderBand.ControlCount -1 do
if aReport.Bands.ColumnHeaderBand.Controls[nIdx] is TQRPrintable then
with TQRPrintable(aReport.Bands.ColumnHeaderBand.Controls[nIdx]) do
Left := Left - (5 * nIdx);
for nIdx := 0 to aReport.Bands.DetailBand.ControlCount -1 do
if aReport.Bands.DetailBand.Controls[nIdx] is TQRPrintable then
with TQRPrintable(aReport.Bands.DetailBand.Controls[nIdx]) do
Left := Left - (5 * nIdx);
{ You can change the report objects before calling the report }
// areport.page.orientation := poLandscape;
{preview or print the report}
if sender = btnPreview then
begin
case cbPreview.ItemIndex of
0: areport.preview;
1: areport.previewModal;
2: areport.previewModeless;
end;
end
else if sender = btnPrint then
areport.print;
{ all done, free the objects }
aReport.Free;
MyTable.Free;
SomeFields.Free;
end;
procedure TfrmQR3Demo.QRCompositeReport1AddReports(Sender: TObject);
begin
// The OnAddReports event is called by the CompositeReport
// to add the reports to list of reports
with QRCompositeReport1.Reports do
begin
Add(frmMasterDetail.QuickRep1);
Add(frmBasicMD.QuickRep1);
Add(frmImageRpt.QuickRep1);
end;
end;
procedure TfrmQR3Demo.btnCRClick(Sender: TObject);
begin
QRCompositeReport1.Preview;
end;
procedure TfrmQR3Demo.rbCreateListClick(Sender: TObject);
begin
Report := CreateListReport;
end;
procedure TfrmQR3Demo.rbMasterDetailClick(Sender: TObject);
begin
Report := frmMasterDetail.QuickRep1;
end;
procedure TfrmQR3Demo.FormCreate(Sender: TObject);
var i: integer;
begin
// Get the current QuickReport version number from
// the qrprntr unit
i := pos(' ', cQRName);
if i >=0 then
VersionLbl.Caption := 'Version' + copy(cQRName, i, 99);
// Create the report object used by the QRCreateList() function
CreateListReport := TQuickRep.Create(self);
CreateListReport.Description.Text := 'Example of how to call the QRCreateList function';
cbPreview.ItemIndex := 0;
end;
procedure TfrmQR3Demo.FormActivate(Sender: TObject);
begin
if Description.Lines.Count = 0 then
begin
rbCreateListClick(Self);
rbCreateList.Checked := True;
end;
end;
procedure TfrmQR3Demo.btnPreviewClick(Sender: TObject);
begin
// This code is more complicated than what you would
// typically need to run a report. Most of this code
// is to handle the selection of the various types of
// reports.
if report <> nil then
begin
if report = CreateListReport then
CreateList(Sender)
else if report = TCustomQuickRep(QRCompositeReport1) then
begin
if sender = btnPreview then
QRCompositeReport1.preview
else
QRCompositeReport1.print;
end
else
begin
if sender = btnPreview then
begin
case cbPreview.ItemIndex of
0: report.preview;
1: report.previewModal;
2: report.previewModeless;
end;
end
else if sender = btnPrint then
report.print;
end;
end;
end;
procedure TfrmQR3Demo.rbExprMemoClick(Sender: TObject);
begin
Report := frmExprmemo.QuickRep1;
end;
procedure TfrmQR3Demo.rbImageClick(Sender: TObject);
begin
Report := frmImageRpt.QuickRep1;
end;
procedure TfrmQR3Demo.rbBasicMDClick(Sender: TObject);
begin
Report := frmBasicMD.QuickRep1;
end;
procedure TfrmQR3Demo.btnFiltersClick(Sender: TObject);
begin
MessageDlg('When an export filter control is dropped on a form, it''s added to all of the previews',mtInformation, [mbok], 0);
end;
procedure TfrmQR3Demo.rbCompositeClick(Sender: TObject);
begin
Report := TCustomQuickRep(QRCompositeReport1);
end;
procedure TfrmQR3Demo.rbNeedDataClick(Sender: TObject);
begin
Report := frmNeedData.QuickRep1;
end;
procedure TfrmQR3Demo.rbFormLetterClick(Sender: TObject);
begin
Report := frmFormLetter.QuickRep1;
end;
// The following code show how to explicitly call an export
// filter without going through the preview
procedure TfrmQR3Demo.btnExportClick(Sender: TObject);
begin
btnExport.Enabled := False;
with SaveDialog1 do
begin
if Execute then
begin
frmFormLetter.QuickRep1.ExportToFilter(TQRCommaSeparatedFilter.Create(FileName));
{
Other filters:
HTML: TQRHTMLDocumentFilter
ASCII: TQRAsciiExportFilter
CSV: TQRCommaSeparatedFilter
In Professional Version:
RTF: TQRRTFExportFilter
WMF: TQRWMFExportFilter
Excel: TQRXLSFilter
}
end;
end;
btnExport.Enabled := True;
end;
procedure TfrmQR3Demo.rbAboutClick(Sender: TObject);
begin
Report := frmHistory.QuickRep1;
end;
procedure TfrmQR3Demo.rbGroupingClick(Sender: TObject);
begin
Report := frmGrouping.QuickRep1;
end;
end.
|
unit PSVFormat;
// If you make any changes to this file be sure to send update to gothi at PS2Savetools.
interface
type
titleArray = array[0..19] of AnsiChar;
THeader = record
magic : array[0..3] of AnsiChar;
unknown1 : integer; //always 0x00000000?
Signature : array [0..39] of byte; //digital signature
unknown2 : integer; //always 0x00000000?
unknown3 : integer; //always 0x00000000?
unknown4 : integer; //always 0x0000002C in PS2, 0x00000014 in PS1. Perhaps size of following section including next int...
saveType : integer; //0x00000002 appears to be PS2, 0x00000001 is PS1?
end;
PTHeader = ^THeader;
TPS2Header = record
unknown6 : integer; //related to amount of icons? Possibly 2 words or even 4 bytes.
sysPos : integer; //location in file of icon.sys
sysSize : integer; //icon.sys size
icon1Pos : integer; //position of 1st icon
icon1Size : integer; //size of 1st icon
icon2Pos : integer; //position of 2nd icon
icon2Size : integer; //size of 2nd icon
icon3Pos : integer; //position of 3rd icon
icon3Size : integer; //size of 3rd icon
numberOfFiles : integer;
end;
PTPS2Header = ^TPS2Header;
TPS2MainDirInfo = record
CreateReserved: byte;
CreateSeconds : byte;
CreateMinutes : byte;
CreateHours : byte;
CreateDays : byte;
CreateMonths: byte;
CreateYear : word;
ModReserved: byte;
ModSeconds : byte;
ModMinutes : byte;
ModHours : byte;
ModDays : byte;
ModMonths: byte;
ModYear : word;
filesize : integer;
attribute : integer; //(8427 dir)
filename : array[0..31] of AnsiChar;
end;
PTPS2MainDirInfo = ^TPS2MainDirInfo;
TPS2FileInfo = record
CreateReserved: byte;
CreateSeconds : byte;
CreateMinutes : byte;
CreateHours : byte;
CreateDays : byte;
CreateMonths: byte;
CreateYear : word;
ModReserved: byte;
ModSeconds : byte;
ModMinutes : byte;
ModHours : byte;
ModDays : byte;
ModMonths: byte;
ModYear : word;
filesize : integer;
attribute : integer; //(8497 file)
filename : array[0..31] of AnsiChar;
//alt format
//filename : array[0..23] of char;
//unknown1 : integer; //constant in first entry, unique to ps2 in others?
//unknown2 : integer; //constant per entry?
positionInFile : integer;
end;
PTPS2FileInfo = ^TPS2FileInfo;
TPS1Header = record
saveSize : integer;
startOfSaveData : integer;
unknown1 : integer; //always 0x00020000 (512). Block size?
unknown2 : integer; //always 0x00000000?
unknown3 : integer; //always 0x00000000?
unknown4 : integer; //always 0x00000000?
unknown5 : integer; //always 0x00000000?
dataSize : integer; //save size repeated?
unknown7 : integer; //always 0x00000000?
prodCode : titleArray;
unknown8 : integer; //always 0x00000000?
unknown9 : integer; //always 0x00000000?
unknown10 : integer; //always 0x00000000?
end;
PTPS1Header = ^TPS1Header;
TPS1MCSHeader = record
magic : integer; // = 81;
dataSize : integer;
positionInCard : word; // = $FFFF;
prodCode : titleArray;
filler : array[0..96] of byte;
end;
PTPS1MCSHeader = ^TPS1MCSHeader;
TPS1FileInfo = record
magic : array [0..1] of AnsiChar;
iconDisplay : byte;
blocksUsed : byte;
title : array [0..31] of wideChar;
end;
PTPS1FileInfo = ^TPS1FileInfo;
implementation
end.
|
unit ProClientThread_Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, WinSock, u_CommBag, u_Comm;
type
TProClientThread = class(TThread)
private
FRecvBuf: TByteArray;
FClient: TSocket;
FClientIP, FInfo: string;
function SendMsg(const OrdNum, CMD: Byte; const Data; const DataLen: Word): Boolean;
function SendErrMsg(const OrdNum: Byte; const ErrorCode: Integer; const Msg: string): Boolean;
procedure UpdateActiveTime;
procedure AddDataList;
procedure SyncAddDataList(const Info: string);
public
procedure Execute; override;
constructor Create(CreateSuspended: Boolean);
property ClientSocket: TSocket read FClient write FClient;
property ClientIP: string read FClientIP write FClientIP;
end;
implementation
constructor TProClientThread.Create(CreateSuspended: Boolean);
begin
FreeOnTerminate := True;
inherited Create(CreateSuspended);
FClient := INVALID_Socket;
FClientIP := '';
FInfo := '';
FillChar(FRecvBuf, SizeOf(TByteArray), 0);
end;
procedure TProClientThread.AddDataList();
begin
_AddDataList(ThreadID, FClientIP, FInfo);
end;
procedure TProClientThread.SyncAddDataList(const Info: string);
begin
FInfo := Info;
Synchronize(AddDataList);
end;
function TProClientThread.SendMsg(const OrdNum, CMD: Byte; const Data; const DataLen: Word): Boolean;
var
sendLen: integer;
SendCB: TCommBag;
begin
SendCB := GetCommBag(OrdNum, CMD, Data, DataLen);
sendLen := SendBag(FClient, SendCB);
Result := (sendLen > 0);
end;
function TProClientThread.SendErrMsg(const OrdNum: Byte; const ErrorCode: Integer; const Msg: string): Boolean;
var
EI: TErrorInfo;
begin
EI.ErrorCode := ErrorCode;
EI.Msg := Msg;
Result := SendMsg(OrdNum, CMD_Error, EI, SizeOf(TErrorInfo));
end;
procedure TProClientThread.Execute;
var
fds: TFDSet;
readLen: integer;
RecvCB: TCommBag;
SvrTime: TDateTime;
UI: TUserInfo;
CI: TCarInfo;
IOR: TInOutRec;
IsSendSucc: Boolean;
timeout: TTimeVal;
rt: Integer;
rtStr: string;
DataFlag: Integer;
IsCheckSucc: Boolean;
begin
IsSendSucc := False;
SyncAddDataList('建立连接...');
while (not Terminated) do
begin
FD_ZERO(fds);
FD_SET(FClient, fds);
//int maxfdp是一个整数值,是指集合中所有文件描述符的范围,即所有文件描述符的最大值加1
//,不能错!在Windows中这个参数的值无所谓,可以设置不正确??
timeout.tv_sec := _ActiveTimeOut;
timeout.tv_usec := 0;
if (select(FClient + 1, @fds, nil, nil, @timeout) <= 0) then
begin
SyncAddDataList('活动超时,强制断开连接!');
Break;
end;
if (not FD_ISSET(FClient, fds)) then Break;
//接受数据,<=0 网络中断了,通常客户端主动断开
readLen := recv(FClient, FRecvBuf, SizeOf(TByteArray), 0);
if readLen <= 0 then Break;
try
//解析数据
if not ParseCommBag(@FRecvBuf, readLen, RecvCB) then
begin
SyncAddDataList('非法数据包,强制断开连接!');
Break;
end;
//处理指令
case RecvCB.CMD of
CMD_SvrTime: begin
SvrTime := Now;
IsSendSucc := SendMsg(RecvCB.OrdNum, RecvCB.CMD, SvrTime, SizeOf(SvrTime));
end;
CMD_User: begin
if RecvCB.DataLen <> SizeOf(TUserInfo) then Break;
Move(RecvCB.Data^, UI, RecvCB.DataLen);
_GetUserInfo(UI, rt, rtStr);
if rt > 0 then
begin
IsSendSucc := SendMsg(RecvCB.OrdNum, RecvCB.CMD, UI, SizeOf(TUserInfo));
SyncAddDataList(Format('OneIC:%s,%d,%d,%s', [UI.FullCardNum, UI.UserType, rt, UI.UserName]));
end
else
begin
IsSendSucc := SendErrMsg(RecvCB.OrdNum, rt, rtStr);
SyncAddDataList(Format('OneIC:%s,%d,%d,%s', [UI.FullCardNum, UI.UserType, rt, rtStr]));
end;
end;
CMD_Car: begin
if RecvCB.DataLen <> SizeOf(TCarInfo) then Break;
Move(RecvCB.Data^, CI, RecvCB.DataLen);
_GetCarInfo(CI, rt, rtStr);
if rt > 0 then
begin
IsSendSucc := SendMsg(RecvCB.OrdNum, RecvCB.CMD, CI, SizeOf(TCarInfo));
SyncAddDataList(Format('MES:%s,%s,%d,%s,%s', [CI.VIN, CI.RFID, rt, CI.EngineNum, CI.ProjectNum]));
end
else
begin
IsSendSucc := SendErrMsg(RecvCB.OrdNum, rt, rtStr);
SyncAddDataList(Format('MES:%s,%s,%d,%s', [CI.VIN, CI.RFID, rt, rtStr]));
end;
end;
CMD_InOutRec: begin
if RecvCB.DataLen <> SizeOf(TInOutRec) then Break;
Move(RecvCB.Data^, IOR, RecvCB.DataLen);
//以服务器时间为准
IOR.RecTime := Now();
IsCheckSucc := _SaveInOutRec(IOR, DataFlag, rt, rtStr);
if (IsCheckSucc and (rt > 0)) then
IsSendSucc := SendMsg(RecvCB.OrdNum, RecvCB.CMD, IOR, SizeOf(TInOutRec))
else
IsSendSucc := SendErrMsg(RecvCB.OrdNum, rt, rtStr);
//同步显示
SyncAddDataList(Format('MES:%d,%d,%s,%s,%s,%s,%d,%s', [
IOR.PDANum, IOR.DirectionFlag,
FormatDateTime('YYYY-MM-DD hh:nn:ss', IOR.RecTime),
IOR.Driver.UserName, IOR.Car.VIN, IOR.Guard.UserName,
rt, rtStr]));
end;
else
begin
rt := -1;
rtStr := '无效的指令!';
IsSendSucc := SendErrMsg(RecvCB.OrdNum, rt, rtStr);
end;
end;
_CS.Enter;
try
_PI.TID := ThreadID;
_PI.IP := FClientIP;
Synchronize(UpdateActiveTime);
if not IsSendSucc then
begin
SyncAddDataList('发送数据失败,通讯异常!');
Break; //异常退出
end;
finally
_CS.Leave;
end;
finally
if Assigned(RecvCB.Data) then
FreeMem(RecvCB.Data, RecvCB.DataLen);
end;
end;
SyncAddDataList('断开连接!');
end;
procedure TProClientThread.UpdateActiveTime();
var
Value: string;
begin
Value := FormatDateTime('yyyy-mm-dd hh:nn:ss', Now);
_UpdatePDAList(3, Value);
end;
end.
|
unit MComboBox;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, StdCtrls;
type TMComboBox = class(TComboBox)
private
fRegExpr : string;
fValid : boolean;
procedure SetRegExpr(const AValue: string);
procedure SetValid(const AValue: boolean);
public
constructor create(aOwner : TComponent); override;
property IsValid : boolean read fValid write SetValid;
procedure EditingDone; override;
published
property RegExpr : string read fRegExpr write SetRegExpr;
end;
procedure Register;
implementation
uses RegExpr,Graphics;
procedure Register;
begin
RegisterComponents('xPL Components',[TMComboBox]);
end;
procedure TMComboBox.SetRegExpr(const AValue: string);
begin
if aValue = fRegExpr then exit;
fRegExpr := aValue;
end;
procedure TMComboBox.EditingDone;
begin
inherited;
if RegExpr='' then exit;
with TRegExpr.Create do try
Expression := RegExpr;
IsValid := Exec(Text);
finally
free;
end;
end;
procedure TMComboBox.SetValid(const AValue: boolean);
begin
fValid := aValue;
if fValid then Self.Color := clWindow else Self.Color := clRed;
end;
constructor TMComboBox.create(aOwner : TComponent);
begin
inherited;
RegExpr := '';
end;
end.
|
unit udomtest_init;
interface
uses
// DELPHI VCL
System.Classes,
// NTX
ntxTestResult
// TESTLIB
{$IFDEF TEST_DATA}
, udomtest_data
{$ENDIF}
;
type
{$IFDEF TEST_DATA}
TTestDataType = TMicroDomTestData;
{$ENDIF}
TTestProc = procedure(trs: TntxTestResults
{$IFDEF TEST_DATA}; td: TTestDataType{$ENDIF});
Tudom_TestListItem = class(TObject)
private
m_name: string;
m_proc: TTestProc;
public
constructor Create(const AName: string; AProc: TTestProc);
destructor Destroy; override;
end;
Tudom_TestList = class(TList)
private
m_only: Boolean; // wenn True, werden nur die Testprozeduren mit 'Only' registriert
procedure FreeItems;
function GetItems(idx: integer): Tudom_TestListItem;
public
constructor Create;
destructor Destroy; override;
procedure Run(trs: TntxTestResults
{$IFDEF TEST_DATA}; td: {$ENDIF});
procedure AddTest(const nm: string; proc: TTestProc);
function Only(const nm: string; proc: TTestProc): Tudom_TestList;
property Items[idx: integer]: Tudom_TestListItem read GetItems; default;
end;
function RegisterTest(const nm: string; proc: TTestProc): Tudom_TestList; overload;
function RegisterTest: Tudom_TestList; overload;
var
RegisteredTests: Tudom_TestList = nil;
implementation
uses
// DELPHI VCL
System.SysUtils, WinApi.Windows;//, Win.Registry, WinApi.Windows, Vcl.Controls,
// TESTLIB
//PLZ_Func;
{ Es gibt zwei Möglichkeit, die Testprozedur zu registrieren:
1) im Normalmodus - RegisterTest(<name>, <procedure>)
2) im Only-Modus - RegisterTest.Only(<name>, <procedure>)
}
function RegisterTest: Tudom_TestList; overload;
begin
if not Assigned(RegisteredTests) then
RegisteredTests:=Tudom_TestList.Create;
Result:=RegisteredTests;
end;
function RegisterTest(const nm: string; proc: TTestProc): Tudom_TestList; overload;
begin
Result:=RegisterTest;
// Wenn die Liste sich nicht im Only-Modus befindet
if not Result.m_only then
Result.AddTest(nm, proc);
end;
{ Tudom_TestListItem }
constructor Tudom_TestListItem.Create(const AName: string; AProc: TTestProc);
begin
inherited Create;
m_name:=AName;
m_proc:=AProc;
end;
destructor Tudom_TestListItem.Destroy;
begin
m_proc:=nil;
m_name:='';
inherited Destroy;
end;
{ Tudom_TestList }
constructor Tudom_TestList.Create;
begin
inherited Create;
end;
destructor Tudom_TestList.Destroy;
begin
FreeItems;
inherited Destroy;
end;
procedure Tudom_TestList.FreeItems;
var
i: integer;
item: TObject;
begin
for i:=0 to Count-1 do
begin
item:=inherited Items[i];
inherited Items[i]:=nil;
item.Free;
end;
end;
function Tudom_TestList.GetItems(idx: integer): Tudom_TestListItem;
begin
Result:=Tudom_TestListItem(inherited Items[idx]);
end;
procedure Tudom_TestList.AddTest(const nm: string; proc: TTestProc);
var
newitem: Tudom_TestListItem;
begin
newitem:=Tudom_TestListItem.Create(nm, proc);
Add(newitem);
end;
function Tudom_TestList.Only(const nm: string;
proc: TTestProc): Tudom_TestList;
begin
if not m_only then
begin
FreeItems;
Clear;
m_only:=true;
end;
AddTest(nm, proc);
Result:=Self;
end;
{*******************************************************************************
Tudom_TestList.Run - 23.03.20 19:37
by: JL
Die Prozedur ruft alle registrierten Testprozeduren auf.
********************************************************************************}
procedure Tudom_TestList.Run(trs: TntxTestResults
{$IFDEF TEST_DATA}; td: TTestDataType{$ENDIF});
var
i: integer;
item: Tudom_TestListItem;
s: string;
begin
// Wenn RegisterTest nie aufgerufen wurde, dann bleibt die Liste nicht
// initialisiert.
if Self=nil then
Exit;
for i:=0 to Count-1 do
begin
item:=Items[i];
if Assigned(item) and Assigned(item.m_proc) then
begin
s:=Format('[TestList] Call test %s', [item.m_name]);
OutputDebugString(PChar(s));
try
item.m_proc(trs{$IFDEF TEST_DATA}, td{$ENDIF});
except
on e: Exception do
begin
s:=Format('[TestList] Exception %s in test %s. Message is ''%s''',
[e.ClassName, item.m_name, e.Message]);
OutputDebugString(PChar(s));
end;
end;
end;
end;
end; {Tudom_TestList.Run}
initialization
finalization
FreeAndNil(RegisteredTests);
end.
|
unit JAScreen;
{$mode objfpc}{$H+}
interface
uses
{FPC} math,
{Amiga} Exec, Intuition, AGraphics, Utility, GadTools, picasso96api, cybergraphics,
{JA} JATypes, JALog;
type
TJAScreenProperties = record
API : TJAGraphicsAPI;
Width : UInt16;
Height : UInt16;
Depth : UInt16;
Title : string;
end;
TJAScreen = record
Properties : TJAScreenProperties;
Screen : pScreen;
VisualInfo : pointer;
DrawInfo : pDrawInfo;
ExistingScreen : boolean;
end;
PJAScreen = ^TJAScreen;
const
JAScreenPropertiesDefault : TJAScreenProperties = (
API : JAGraphicsAPI_Auto;
Width : 320;
Height : 200;
Depth : 5;
Title : 'JAScreen');
function JAScreenCreate(AScreenProperties : TJAScreenProperties; AExistingScreen : pScreen) : PJAScreen;
function JAScreenDestroy(AScreen : PJAScreen) : boolean;
implementation
function JAScreenCreate(AScreenProperties : TJAScreenProperties; AExistingScreen : pScreen) : PJAScreen;
var
DisplayID : UInt16;
NewMode : UInt16;
begin
Result := PJAScreen(JAMemGet(SizeOf(TJAScreen)));
Result^.Properties := AScreenProperties;
if AExistingScreen=nil then
begin
Result^.ExistingScreen := false;
case AScreenProperties.API of
JAGraphicsAPI_Intuition :
begin
Log('JAScreenCreate','Creating Intuition Screen [%s] [%dx%dx%d]',[AScreenProperties.Title,AScreenProperties.Width,AScreenProperties.Height, round(power(2,AScreenProperties.Depth))]);
Result^.Screen := OpenScreenTags(nil,[
SA_Width, AScreenProperties.Width,
SA_Height, AScreenProperties.Height,
SA_Depth, AScreenProperties.Depth,
SA_Title, AsTag(pchar(Result^.Properties.Title)),
//SA_LikeWorkbench,lTRUE,
SA_FullPalette, lfalse,
SA_SharePens, ltrue, {we're managing the pens ourselves, leave slots unallocated}
SA_Pens, -1,
{TODO : this determines our resolution for lores / hires ec}
SA_DisplayID, LORES_KEY,
//SA_DisplayID, EXTRAHALFBRITE_KEY, {320x200 NTSC}
//SA_DisplayID, HIRESEHB_KEY, {640x200 NTSC}
//SA_DisplayID, HIRESEHBLACE_KEY, {640x400 NTSC}
TAG_END]);
// NewMode := CoerceMode(@Result^.Screen^.ViewPort, NTSC_MONITOR_ID, AVOID_FLICKER);
if Result=nil then
begin
Log('JAScreenCreate','Failed To Create Intuition Screen');
JAMemFree(Result, SizeOf(TJAScreen));
exit(nil);
end;
end;
JAGraphicsAPI_Picasso :
begin
{DisplayID := p96BestModeIDTags([
P96BIDTAG_NominalWidth, AScreenProperties.Width,
P96BIDTAG_NominalHeight, AScreenProperties.Height,
P96BIDTAG_Depth, AScreenProperties.Depth,
P96BIDTAG_FormatsAllowed, RGBFF_HICOLOR or RGBFF_TRUECOLOR,//RGBFF_CLUT or RGBFF_R8G8B8,
TAG_DONE]);}
Log('JAScreenCreate','Creating Picasso Screen [%s] [%dx%dx%d]',[AScreenProperties.Title,AScreenProperties.Width,AScreenProperties.Height, round(power(2,AScreenProperties.Depth))]);
Result^.Screen := p96OpenScreenTags([
P96SA_Width, AScreenProperties.Width,
P96SA_Height, AScreenProperties.Height,
//P96SA_DisplayID, DisplayID,
//P96SA_RGBFormat, RGBFF_R8G8B8,//RGBFF_CLUT,
//SA_DisplayID, EXTRAHALFBRITE_KEY,
P96SA_Depth, AScreenProperties.Depth,
P96SA_Title, AsTag(pchar(@AScreenProperties.Title)),
SA_FullPalette, lfalse,
P96SA_SharePens, ltrue, {we're managing the pens ourself, leave slots unallocated}
P96SA_Pens, -1,
//P96SA_AutoScroll, lTRUE,
//P96SA_Pens, AsTag(@Pens),
TAG_DONE]);
if Result=nil then
begin
Log('JAScreenCreate','Failed To Create Picasso Screen');
JAMemFree(Result, SizeOf(TJAScreen));
exit(nil);
end;
end;
end;
end else
begin
Log('JAScreenCreate','Attaching to Existing Screen [%s] [%dx%dx%d]',[AExistingScreen^.Title,AExistingScreen^.Width,AExistingScreen^.Height, round(power(2, AExistingScreen^.Bitmap.Depth))]);
Result^.ExistingScreen := true;
{copy over existing screen properties}
Result^.Screen := AExistingScreen;
Result^.Properties.Title := AExistingScreen^.Title;
Result^.Properties.Width := AExistingScreen^.Width;
Result^.Properties.Height := AExistingScreen^.Height;
end;
{get visual and draw info for the screen}
Result^.VisualInfo := GetVisualInfoA(Result^.Screen, nil); {get screen visualinfo}
Result^.DrawInfo := GetScreenDrawInfo(Result^.Screen); {get screen drawinfo}
{update/copy screen depth}
Result^.Properties.Depth := Result^.DrawInfo^.dri_depth;
end;
function JAScreenDestroy(AScreen : PJAScreen) : boolean;
begin
if AScreen=nil then exit(false);
{free visual and draw info}
FreeScreenDrawInfo(AScreen^.Screen, AScreen^.DrawInfo);
FreeVisualInfo(AScreen^.VisualInfo);
if not AScreen^.ExistingScreen then
begin
case AScreen^.Properties.API of
JAGraphicsAPI_Intuition :
begin
Log('JAScreenDestroy','Destroying Intuition Screen [%s]',[AScreen^.Properties.Title]);
CloseScreen(AScreen^.Screen);
end;
JAGraphicsAPI_Picasso :
begin
Log('JAScreenDestroy','Destroying Picasso Screen [%s]',[AScreen^.Properties.Title]);
p96CloseScreen(AScreen^.Screen);
end;
end;
end else
Log('JAScreenDestroy','Detaching From Existing Screen [%s]',[AScreen^.Properties.Title]);
{Free Strings}
SetLength(AScreen^.Properties.Title, 0);
{Free Memory}
JAMemFree(AScreen, SizeOf(TJAScreen));
Result := true;
end;
end.
|
unit Ths.Erp.Database.Table.AyarStkStokGrubu;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table,
Ths.Erp.Database.Table.AyarStkStokGrubuTuru,
Ths.Erp.Database.Table.AyarVergiOrani,
Ths.Erp.Database.Table.HesapKarti;
type
TAyarStkStokGrubu = class(TTable)
private
FAyarStkStokGrubuTuruID: TFieldDB;
FGrup: TFieldDB;
FAlisHesabi: TFieldDB;
FAlisIadeHesabi: TFieldDB;
FSatisHesabi: TFieldDB;
FSatisIadeHesabi: TFieldDB;
FIhracatHesabi: TFieldDB;
FHammaddeHesabi: TFieldDB;
FMamulHesabi: TFieldDB;
FKDVOrani: TFieldDB;
FIsIskontoAktif: TFieldDB;
FIskontoSatis: TFieldDB;
FIskontoMudur: TFieldDB;
FIsSatisFiyatiniKullan: TFieldDB;
FIsMaliyetAnalizFarkliDB: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property AyarStkStokGrubuTuruID: TFieldDB read FAyarStkStokGrubuTuruID write FAyarStkStokGrubuTuruID;
Property Grup: TFieldDB read FGrup write FGrup;
Property AlisHesabi: TFieldDB read FAlisHesabi write FAlisHesabi;
Property AlisIadeHesabi: TFieldDB read FAlisIadeHesabi write FAlisIadeHesabi;
Property SatisHesabi: TFieldDB read FSatisHesabi write FSatisHesabi;
Property SatisIadeHesabi: TFieldDB read FSatisIadeHesabi write FSatisIadeHesabi;
Property IhracatHesabi: TFieldDB read FIhracatHesabi write FIhracatHesabi;
Property HammaddeHesabi: TFieldDB read FHammaddeHesabi write FHammaddeHesabi;
Property MamulHesabi: TFieldDB read FMamulHesabi write FMamulHesabi;
Property KDVOrani: TFieldDB read FKDVOrani write FKDVOrani;
Property IsIskontoAktif: TFieldDB read FIsIskontoAktif write FIsIskontoAktif;
Property IskontoSatis: TFieldDB read FIskontoSatis write FIskontoSatis;
Property IskontoMudur: TFieldDB read FIskontoMudur write FIskontoMudur;
Property IsSatisFiyatiniKullan: TFieldDB read FIsSatisFiyatiniKullan write FIsSatisFiyatiniKullan;
Property IsMaliyetAnalizFarkliDB: TFieldDB read FIsMaliyetAnalizFarkliDB write FIsMaliyetAnalizFarkliDB;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TAyarStkStokGrubu.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'ayar_stk_stok_grubu';
SourceCode := '1000';
FAyarStkStokGrubuTuruID := TFieldDB.Create('ayar_stk_stok_grubu_turu_id', ftInteger, 0, 0, True);
FAyarStkStokGrubuTuruID.FK.FKTable := TAyarStkStokGrubuTuru.Create(OwnerDatabase);
FAyarStkStokGrubuTuruID.FK.FKCol := TFieldDB.Create(TAyarStkStokGrubuTuru(FAyarStkStokGrubuTuruID.FK.FKTable).StokGrubuTur.FieldName, TAyarStkStokGrubuTuru(FAyarStkStokGrubuTuruID.FK.FKTable).StokGrubuTur.FieldType, '');
FGrup := TFieldDB.Create('grup', ftString, '');
FAlisHesabi := TFieldDB.Create('alis_hesabi', ftString, '', 0, True);
FAlisHesabi.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FAlisHesabi.FK.FKCol := TFieldDB.Create(THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldName, THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldType, '');
FAlisIadeHesabi := TFieldDB.Create('alis_iade_hesabi', ftString, '', 0, True);
FAlisIadeHesabi.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FAlisIadeHesabi.FK.FKCol := TFieldDB.Create(THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldName, THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldType, '');
FSatisHesabi := TFieldDB.Create('satis_hesabi', ftString, '', 0, True);
FSatisHesabi.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FSatisHesabi.FK.FKCol := TFieldDB.Create(THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldName, THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldType, '');
FSatisIadeHesabi := TFieldDB.Create('satis_iade_hesabi', ftString, '', 0, True);
FSatisIadeHesabi.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FSatisIadeHesabi.FK.FKCol := TFieldDB.Create(THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldName, THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldType, '');
FIhracatHesabi := TFieldDB.Create('ihracat_hesabi', ftString, '', 0, True);
FIhracatHesabi.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FIhracatHesabi.FK.FKCol := TFieldDB.Create(THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldName, THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldType, '');
FHammaddeHesabi := TFieldDB.Create('hammadde_hesabi', ftString, '', 0, True);
FHammaddeHesabi.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FHammaddeHesabi.FK.FKCol := TFieldDB.Create(THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldName, THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldType, '');
FMamulHesabi := TFieldDB.Create('mamul_hesabi', ftString, '', 0, True);
FMamulHesabi.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FMamulHesabi.FK.FKCol := TFieldDB.Create(THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldName, THesapKarti(FAlisHesabi.FK.FKTable).HesapKodu.FieldType, '');
FKDVOrani := TFieldDB.Create('kdv_orani', ftInteger, 0, 0, True);
FKDVOrani.FK.FKTable := TAyarVergiOrani.Create(OwnerDatabase);
FKDVOrani.FK.FKCol := TFieldDB.Create(TAyarVergiOrani(FKDVOrani.FK.FKTable).VergiOrani.FieldName, TAyarVergiOrani(FKDVOrani.FK.FKTable).VergiOrani.FieldType, '');
FIsIskontoAktif := TFieldDB.Create('is_iskonto_aktif', ftBoolean, False, 0, False);
FIskontoSatis := TFieldDB.Create('iskonto_satis', ftFloat, 0, 0, False);
FIskontoMudur := TFieldDB.Create('iskonto_mudur', ftFloat, 0, 0, False);
FIsSatisFiyatiniKullan := TFieldDB.Create('is_satis_fiyatini_kullan', ftBoolean, False);
FIsMaliyetAnalizFarkliDB := TFieldDB.Create('is_maliyet_analiz_farkli_db', ftBoolean, False);
end;
procedure TAyarStkStokGrubu.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FAyarStkStokGrubuTuruID.FieldName,
ColumnFromIDCol(FAyarStkStokGrubuTuruID.FK.FKCol.FieldName, FAyarStkStokGrubuTuruID.FK.FKTable.TableName, FAyarStkStokGrubuTuruID.FieldName, FAyarStkStokGrubuTuruID.FK.FKCol.FieldName, TableName),
getRawDataByLang(TableName, FGrup.FieldName),
TableName + '.' + FAlisHesabi.FieldName,
TableName + '.' + FAlisIadeHesabi.FieldName,
TableName + '.' + FSatisHesabi.FieldName,
TableName + '.' + FSatisIadeHesabi.FieldName,
TableName + '.' + FIhracatHesabi.FieldName,
TableName + '.' + FHammaddeHesabi.FieldName,
TableName + '.' + FMamulHesabi.FieldName,
TableName + '.' + FKDVOrani.FieldName,
TableName + '.' + FIsIskontoAktif.FieldName,
TableName + '.' + FIskontoSatis.FieldName,
TableName + '.' + FIskontoMudur.FieldName,
TableName + '.' + FIsSatisFiyatiniKullan.FieldName,
TableName + '.' + FIsMaliyetAnalizFarkliDB.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FAyarStkStokGrubuTuruID.FieldName).DisplayLabel := 'Tür ID';
Self.DataSource.DataSet.FindField(FAyarStkStokGrubuTuruID.FK.FKCol.FieldName).DisplayLabel := 'Tür';
Self.DataSource.DataSet.FindField(FGrup.FieldName).DisplayLabel := 'Grup';
Self.DataSource.DataSet.FindField(FAlisHesabi.FieldName).DisplayLabel := 'Alış Hesabı';
Self.DataSource.DataSet.FindField(FAlisIadeHesabi.FieldName).DisplayLabel := 'Alış İade Hesabı';
Self.DataSource.DataSet.FindField(FSatisHesabi.FieldName).DisplayLabel := 'Satış Hesabı';
Self.DataSource.DataSet.FindField(FSatisIadeHesabi.FieldName).DisplayLabel := 'Satış İade Hesabı';
Self.DataSource.DataSet.FindField(FIhracatHesabi.FieldName).DisplayLabel := 'İhracat Hesabı';
Self.DataSource.DataSet.FindField(FHammaddeHesabi.FieldName).DisplayLabel := 'Hammadde Hesabı';
Self.DataSource.DataSet.FindField(FMamulHesabi.FieldName).DisplayLabel := 'Mamül Hesabı';
Self.DataSource.DataSet.FindField(FKDVOrani.FieldName).DisplayLabel := 'KDV Oranı';
Self.DataSource.DataSet.FindField(FIsIskontoAktif.FieldName).DisplayLabel := 'İskonto Aktif?';
Self.DataSource.DataSet.FindField(FIskontoSatis.FieldName).DisplayLabel := 'İskonto Satış';
Self.DataSource.DataSet.FindField(FIskontoMudur.FieldName).DisplayLabel := 'İskonto Müdür';
Self.DataSource.DataSet.FindField(FIsSatisFiyatiniKullan.FieldName).DisplayLabel := 'Satış Fiyatını Kullan?';
Self.DataSource.DataSet.FindField(FIsMaliyetAnalizFarkliDB.FieldName).DisplayLabel := 'Maliyet Analiz Farklı DB?';
end;
end;
end;
procedure TAyarStkStokGrubu.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FAyarStkStokGrubuTuruID.FieldName,
ColumnFromIDCol(FAyarStkStokGrubuTuruID.FK.FKCol.FieldName, FAyarStkStokGrubuTuruID.FK.FKTable.TableName, FAyarStkStokGrubuTuruID.FieldName, FAyarStkStokGrubuTuruID.FK.FKCol.FieldName, TableName),
getRawDataByLang(TableName, FGrup.FieldName),
TableName + '.' + FAlisHesabi.FieldName,
TableName + '.' + FAlisIadeHesabi.FieldName,
TableName + '.' + FSatisHesabi.FieldName,
TableName + '.' + FSatisIadeHesabi.FieldName,
TableName + '.' + FIhracatHesabi.FieldName,
TableName + '.' + FHammaddeHesabi.FieldName,
TableName + '.' + FMamulHesabi.FieldName,
TableName + '.' + FKDVOrani.FieldName,
TableName + '.' + FIsIskontoAktif.FieldName,
TableName + '.' + FIskontoSatis.FieldName,
TableName + '.' + FIskontoMudur.FieldName,
TableName + '.' + FIsSatisFiyatiniKullan.FieldName,
TableName + '.' + FIsMaliyetAnalizFarkliDB.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FAyarStkStokGrubuTuruID.Value := FormatedVariantVal(FieldByName(FAyarStkStokGrubuTuruID.FieldName).DataType, FieldByName(FAyarStkStokGrubuTuruID.FieldName).Value);
FAyarStkStokGrubuTuruID.FK.FKCol.Value := FormatedVariantVal(FieldByName(FAyarStkStokGrubuTuruID.FK.FKCol.FieldName).DataType, FieldByName(FAyarStkStokGrubuTuruID.FK.FKCol.FieldName).Value);
FGrup.Value := FormatedVariantVal(FieldByName(FGrup.FieldName).DataType, FieldByName(FGrup.FieldName).Value);
FAlisHesabi.Value := FormatedVariantVal(FieldByName(FAlisHesabi.FieldName).DataType, FieldByName(FAlisHesabi.FieldName).Value);
FAlisIadeHesabi.Value := FormatedVariantVal(FieldByName(FAlisIadeHesabi.FieldName).DataType, FieldByName(FAlisIadeHesabi.FieldName).Value);
FSatisHesabi.Value := FormatedVariantVal(FieldByName(FSatisHesabi.FieldName).DataType, FieldByName(FSatisHesabi.FieldName).Value);
FSatisIadeHesabi.Value := FormatedVariantVal(FieldByName(FSatisIadeHesabi.FieldName).DataType, FieldByName(FSatisIadeHesabi.FieldName).Value);
FIhracatHesabi.Value := FormatedVariantVal(FieldByName(FIhracatHesabi.FieldName).DataType, FieldByName(FIhracatHesabi.FieldName).Value);
FHammaddeHesabi.Value := FormatedVariantVal(FieldByName(FHammaddeHesabi.FieldName).DataType, FieldByName(FHammaddeHesabi.FieldName).Value);
FMamulHesabi.Value := FormatedVariantVal(FieldByName(FMamulHesabi.FieldName).DataType, FieldByName(FMamulHesabi.FieldName).Value);
FKDVOrani.Value := FormatedVariantVal(FieldByName(FKDVOrani.FieldName).DataType, FieldByName(FKDVOrani.FieldName).Value);
FIsIskontoAktif.Value := FormatedVariantVal(FieldByName(FIsIskontoAktif.FieldName).DataType, FieldByName(FIsIskontoAktif.FieldName).Value);
FIskontoSatis.Value := FormatedVariantVal(FieldByName(FIskontoSatis.FieldName).DataType, FieldByName(FIskontoSatis.FieldName).Value);
FIskontoMudur.Value := FormatedVariantVal(FieldByName(FIskontoMudur.FieldName).DataType, FieldByName(FIskontoMudur.FieldName).Value);
FIsSatisFiyatiniKullan.Value := FormatedVariantVal(FieldByName(FIsSatisFiyatiniKullan.FieldName).DataType, FieldByName(FIsSatisFiyatiniKullan.FieldName).Value);
FIsMaliyetAnalizFarkliDB.Value := FormatedVariantVal(FieldByName(FIsMaliyetAnalizFarkliDB.FieldName).DataType, FieldByName(FIsMaliyetAnalizFarkliDB.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TAyarStkStokGrubu.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FAyarStkStokGrubuTuruID.FieldName,
FGrup.FieldName,
FAlisHesabi.FieldName,
FAlisIadeHesabi.FieldName,
FSatisHesabi.FieldName,
FSatisIadeHesabi.FieldName,
FIhracatHesabi.FieldName,
FHammaddeHesabi.FieldName,
FMamulHesabi.FieldName,
FKDVOrani.FieldName,
FIsIskontoAktif.FieldName,
FIskontoSatis.FieldName,
FIskontoMudur.FieldName,
FIsSatisFiyatiniKullan.FieldName,
FIsMaliyetAnalizFarkliDB.FieldName
]);
NewParamForQuery(QueryOfInsert, FAyarStkStokGrubuTuruID);
NewParamForQuery(QueryOfInsert, FGrup);
NewParamForQuery(QueryOfInsert, FAlisHesabi);
NewParamForQuery(QueryOfInsert, FAlisIadeHesabi);
NewParamForQuery(QueryOfInsert, FSatisHesabi);
NewParamForQuery(QueryOfInsert, FSatisIadeHesabi);
NewParamForQuery(QueryOfInsert, FIhracatHesabi);
NewParamForQuery(QueryOfInsert, FHammaddeHesabi);
NewParamForQuery(QueryOfInsert, FMamulHesabi);
NewParamForQuery(QueryOfInsert, FKDVOrani);
NewParamForQuery(QueryOfInsert, FIsIskontoAktif);
NewParamForQuery(QueryOfInsert, FIskontoSatis);
NewParamForQuery(QueryOfInsert, FIskontoMudur);
NewParamForQuery(QueryOfInsert, FIsSatisFiyatiniKullan);
NewParamForQuery(QueryOfInsert, FIsMaliyetAnalizFarkliDB);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TAyarStkStokGrubu.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FAyarStkStokGrubuTuruID.FieldName,
FGrup.FieldName,
FAlisHesabi.FieldName,
FAlisIadeHesabi.FieldName,
FSatisHesabi.FieldName,
FSatisIadeHesabi.FieldName,
FIhracatHesabi.FieldName,
FHammaddeHesabi.FieldName,
FMamulHesabi.FieldName,
FKDVOrani.FieldName,
FIsIskontoAktif.FieldName,
FIskontoSatis.FieldName,
FIskontoMudur.FieldName,
FIsSatisFiyatiniKullan.FieldName,
FIsMaliyetAnalizFarkliDB.FieldName
]);
NewParamForQuery(QueryOfUpdate, FAyarStkStokGrubuTuruID);
NewParamForQuery(QueryOfUpdate, FGrup);
NewParamForQuery(QueryOfUpdate, FAlisHesabi);
NewParamForQuery(QueryOfUpdate, FAlisIadeHesabi);
NewParamForQuery(QueryOfUpdate, FSatisHesabi);
NewParamForQuery(QueryOfUpdate, FSatisIadeHesabi);
NewParamForQuery(QueryOfUpdate, FIhracatHesabi);
NewParamForQuery(QueryOfUpdate, FHammaddeHesabi);
NewParamForQuery(QueryOfUpdate, FMamulHesabi);
NewParamForQuery(QueryOfUpdate, FKDVOrani);
NewParamForQuery(QueryOfUpdate, FIsIskontoAktif);
NewParamForQuery(QueryOfUpdate, FIskontoSatis);
NewParamForQuery(QueryOfUpdate, FIskontoMudur);
NewParamForQuery(QueryOfUpdate, FIsSatisFiyatiniKullan);
NewParamForQuery(QueryOfUpdate, FIsMaliyetAnalizFarkliDB);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TAyarStkStokGrubu.Clone():TTable;
begin
Result := TAyarStkStokGrubu.Create(Database);
Self.Id.Clone(TAyarStkStokGrubu(Result).Id);
FAyarStkStokGrubuTuruID.Clone(TAyarStkStokGrubu(Result).FAyarStkStokGrubuTuruID);
FGrup.Clone(TAyarStkStokGrubu(Result).FGrup);
FAlisHesabi.Clone(TAyarStkStokGrubu(Result).FAlisHesabi);
FAlisIadeHesabi.Clone(TAyarStkStokGrubu(Result).FAlisIadeHesabi);
FSatisHesabi.Clone(TAyarStkStokGrubu(Result).FSatisHesabi);
FSatisIadeHesabi.Clone(TAyarStkStokGrubu(Result).FSatisIadeHesabi);
FIhracatHesabi.Clone(TAyarStkStokGrubu(Result).FIhracatHesabi);
FHammaddeHesabi.Clone(TAyarStkStokGrubu(Result).FHammaddeHesabi);
FMamulHesabi.Clone(TAyarStkStokGrubu(Result).FMamulHesabi);
FKDVOrani.Clone(TAyarStkStokGrubu(Result).FKDVOrani);
FKDVOrani.Clone(TAyarStkStokGrubu(Result).FKDVOrani);
FIsIskontoAktif.Clone(TAyarStkStokGrubu(Result).FIsIskontoAktif);
FIskontoSatis.Clone(TAyarStkStokGrubu(Result).FIskontoSatis);
FIskontoMudur.Clone(TAyarStkStokGrubu(Result).FIskontoMudur);
FIsSatisFiyatiniKullan.Clone(TAyarStkStokGrubu(Result).FIsSatisFiyatiniKullan);
FIsMaliyetAnalizFarkliDB.Clone(TAyarStkStokGrubu(Result).FIsMaliyetAnalizFarkliDB);
end;
end.
|
unit untSysShell;
interface
uses
Windows, SysUtils, Variants, Classes;
//设置屏幕分辨率如1024X768
function SetScreen(x,y: Word): Boolean; stdcall;
function CreateShortcut(Exe:string; Lnk:string = ''; Dir:string = '';
ID:Integer = -1):Boolean; stdcall;
implementation
uses
ShlObj, ActiveX, ComObj;
function SetScreen(x,y: Word): Boolean;
var
DevMode: TDeviceMode;
begin
Result := EnumDisplaySettings(nil, 0, DevMode);
if Result then
begin
DevMode.dmFields := DM_PELSWIDTH or DM_PELSHEIGHT;
DevMode.dmPelsWidth := x;
DevMode.dmPelsHeight := y;
Result := ChangeDisplaySettings(DevMode, 0) = DISP_CHANGE_SUCCESSFUL;
end;
end;
{函数说明:}
{第一个参数是要建立快捷方式的文件, 这是必须的; 其他都是可选参数}
{第二个参数是快捷方式名称, 缺省使用参数一的文件名}
{第三个参数是指定目的文件夹, 缺省目的是桌面; 如果有第四个参数, 该参数将被忽略}
{第四个参数是用常数的方式指定目的文件夹; 该系列常数定义在 ShlObj 单元, CSIDL_ 打头}
function CreateShortcut(Exe:string; Lnk:string = ''; Dir:string = ''; ID:Integer = -1):Boolean;
var
IObj: IUnknown;
ILnk: IShellLink;
IPFile: IPersistFile;
PIDL: PItemIDList;
InFolder: array[0..MAX_PATH] of Char;
LinkFileName: WideString;
begin
Result := False;
if not FileExists(Exe) then
Exit;
if Lnk = '' then
Lnk := ChangeFileExt(ExtractFileName(Exe), '');
IObj := CreateComObject(CLSID_ShellLink);
ILnk := IObj as IShellLink;
ILnk.SetPath(PChar(Exe));
ILnk.SetWorkingDirectory(PChar(ExtractFilePath(Exe)));
if (Dir = '') and (ID = -1) then
ID := CSIDL_DESKTOP;
if ID > -1 then
begin
SHGetSpecialFolderLocation(0, ID, PIDL);
SHGetPathFromIDList(PIDL, InFolder);
LinkFileName := Format('%s\%s.lnk', [InFolder, Lnk]);
end
else
begin
Dir := ExcludeTrailingPathDelimiter(Dir);
if not DirectoryExists(Dir) then
Exit;
LinkFileName := Format('%s\%s.lnk', [Dir, Lnk]);
end;
IPFile := IObj as IPersistFile;
if IPFile.Save(PWideChar(LinkFileName), False) = 0 then
Result := True;
end; {CreateShortcut 函数结束}
end.
|
{
Лабораторная работа № 6 Поиск компонент связности
Граф задан его матрицей смежности. Требуется определить количество компонент связности этого графа. При этом должны быть конкретно перечислены вершины, входящие в каждую компоненту связности.
Пользователю должна быть предоставлена возможность редактировать исходную матрицу, т.е. изменять исходный граф без выхода из программы. Предусмотреть также возможность изменения количества вершин.
При выполнении работы разрешается (даже рекомендуется!) использовать матрицу бинарных отношений из лабораторной работы №2.
Вход программы: число вершин графа и матрица смежности.
Выход: разбиение множества вершин на подмножества, соответствующие компонентам связности.
Дополнительно:
Заданный граф – ориентированный. Выполнять поиск компонент сильной связности.
}
program laba5;
uses Crt, SKUtil, Objects;
var
TopsCol: Integer; {Число вершин графа}
PMatr: MatrPtr; {Матрица смежности графа}
Queue: PQueue; {Очередь для обхода}
PList: PTops; {Список для хранения пройденных вершин}
{Функция вывода главного меню программы}
function CreateMenu: Char;
begin
clrscr;
Writeln('***** Поиск компонент связности неориентированного графа *****');
WriteLn('1 Ввод матрицы смежности графа');
WriteLn('2 Генерация матрицы смежности графа');
WriteLn('3 Просмотр матрицы смежности графа');
WriteLn('4 Поиск компонент связности графа');
Writeln('ESC - Выход');
CreateMenu := ReadKey;
end ;
{Процедура ожидания нажатие клавиши ESC либо ENTER}
procedure StopKey;
begin
WriteLn('Для продолжения нажмте клавишу ESC или ENTER...');
WriteLn;
while not (ReadKey in [#27, #13]) do;
end;
{Функция определения симметричности матрицы.}
function Is_Simmetr(TmpMatr: MatrPtr): Boolean;
var
i, j: Integer;
begin
Is_Simmetr := True;
With TmpMatr^ do begin
for i := 1 to RowValue do
for j := 1 to Colvalue do
if GetElement(TmpMatr, i, j) <> GetElement(TmpMatr, j, i) then begin
Is_Simmetr := False;
Break;
end;
end;
end;
procedure PrintMatr;
var
i, j: Integer;
s: string;
begin
if PMatr = nil then Exit;
with PMatr^ do begin
Write(' ');
for i := 1 to TopsCol do begin
Str(i, s);
Write('A' + s);
Write(' ');
end;
WriteLn;
for i := 0 to RowValue - 1 do begin
for j := 0 to ColValue do begin
Str(i + 1, s);
if (j = 0) and (i < TopsCol) then begin
Write('A' + s);
Write(' ');
end;
if (j > 0) then begin
Write(' ');
Write(GetElement(PMatr, i + 1, j));
end;
end;
WriteLn;
end;
end;
end;
procedure CreateMatrix;
var
i, j, k: Integer;
s1, s2: string;
begin
clrscr;
ClearMemMatrix(PMatr);
Write('Введите количество вершин графа: ');
Read(TopsCol);
WriteLn;
PMatr := CreateMatr(TopsCol, TopsCol);
with PMatr^ do begin
PrintMatr;
WriteLn;
for i := 1 to RowValue do begin
for j := 1 to ColValue do begin
Str(i, s1);
Str(j, s2);
repeat
Write('Введите элемент A(' + s1 + ',' + s2 + ') (Количество рёбер): ');
Read(k);
if (k < 0) then begin
WriteLn;
WriteLn;
WriteLn('Некорректный ввод! В матрице смежности должны быть элементов больее 0');
WriteLn;
WriteLn;
end;
Until (k >= 0);
SetElement(PMatr, i, j, k);
end;
end;
WriteLn;
WriteLn('Матрица смежности:');
PrintMatr;
WriteLn;
WriteLn;
if not is_simmetr(PMatr) then begin
ClearMemMatrix(PMatr); TopsCol := 0;
WriteLn('Матрица смежности неориентированного графа должна быть симметричной!');
WriteLn('Матрица смежности очищена.Необходимо повторить ввод матрицы.');
WriteLn;
WriteLn;
end ;
end;
StopKey;
end;
procedure GenerateMatr;
var
i, j: Integer;
begin
clrscr;
ClearMemMatrix(PMatr);
TopsCol := 7;
PMatr := CreateMatr(TopsCol, TopsCol);
with PMatr^ do begin
for i := 1 to RowValue do begin
for j := 1 to ColValue do begin
if ((i = 1) and (j = 3)) or
((i = 2) and (j = 5)) or
((i = 3) and (j = 1)) or
((i = 3) and (j = 4)) or
((i = 4) and (j = 3)) or
((i = 4) and (j = 7)) or
((i = 5) and (j = 2)) or
((i = 5) and (j = 6)) or
((i = 7) and (j = 4))
then
SetElement(PMatr, i, j, 1);
end;
end;
end;
WriteLn;
WriteLn('Матрица смежности');
PrintMatr;
StopKey;
end;
procedure ViewMatr;
begin
clrscr;
WriteLn('***** Матрица смежности графа *****');
WriteLn;
PrintMatr;
StopKey;
end;
procedure ClearList;
var
ps, ps1: PTops;
begin
ps := PList;
while ps <> nil do begin
ps1 := ps;
ps := ps1^.NextItem;
Dispose(ps1);
end;
PList := nil;
end;
procedure PutList(var TmpList: PTops; Co: Integer);
var
ps, ps1: PTops;
begin
ps := TmpList;
{Устанавливаем указатель в конец списка}
if ps <> nil then begin
while ps^.NextItem <> nil do
ps := ps^.NextItem;
end;
{Выделение память под элемент}
New(ps1);
ps1^.Co := Co;
ps1^.NextItem := nil;
if ps <> nil then
ps^.NextItem := ps1
else
TmpList := ps1;
end;
{Функция проверки наличия вершины в списке}
function RecExists(Co: Integer): Boolean;
var
Pt: PTops;
begin
RecExists := False;
Pt := PList;
while (pt <> nil) do begin
if (pt^.Co = Co) then begin
RecExists := True;
Break;
end;
pt := pt^.nextItem;
end;
end;
{Функция вывода компоненты связности на экран}
function GetTopsLink(TmpList: PTops): string;
var
s, s1: string;
pt: PTops;
begin
s1 := '';
pt := TmpList;
while pt <> nil do begin
if s1 <> '' then s1 := s1 + ' - ';
Str(pt^.Co, s);
s1 := s1 + 'A' + s;
pt := pt^.NextItem;
end;
GetTopsLink := s1;
end;
procedure isFindLink(StartNode: Integer);
var
i, j, x, k: Integer;
ps: PTops; {Список вершин в компоненте связности}
begin
Queue^.Clear; {Очищаем очередь}
i := StartNode; {Вершина, с которой начинаем обход}
Queue^.PutItem(i); {Заносим вершину в очередь}
PutList(PList, i); {Помечаем вершину}
ps := nil;
PutList(ps, i); {Заносим стартовую вершину в начало списка}
repeat
x := Queue^.GetItem;
with PMatr^ do begin
for j := 1 to ColValue do begin
k := GetElement(PMatr, x, j); {Проверим связь вершин по матрице смежности}
if (k > 0) then begin
if not RecExists(j) then begin
{Вершины с номерами X и J связаны, и вершина J еще не в очереди}
Queue^.PutItem(j); {Заносим вершину в очередь}
PutList(PList, j); {Помечаем вершину, как пройденную}
PutList(ps, j); {Заносим следующую вершину в список текущей компоненты связности}
end;
end;
end;
end;
until Queue^.Head = nil; {Выполняем обход, пока очередь не станет пустой}
{Вывод компоненты связности на экран}
WriteLn(GetTopsLink(ps));
end;
procedure SearchAllLinks;
var
i: Integer;
s, sl: string;
begin
clrscr;
WriteLn('***** Поиск компонент связности графа *****');
if TopsCol = 0 then begin
WriteLn('Не задан граф! Для поиска компонент связности необходимо задайть граф !');
StopKey;
Exit;
end;
ClearList; {Очиска списка}
WriteLn;
WriteLn('** Матрица смежности **');
PrintMatr;
WriteLn;
WriteLn('** Компоненты связности **');
WriteLn;
{Производим перебор по всем вершинам, и пытаемся от каждой найти маршруты}
for i := 1 to TopsCol do begin
if not RecExists(i) then
isFindLink(i);
end;
StopKey;
end;
var
ch: Char;
begin
PMatr := nil;
PList := nil;
Queue := nil ;
TopsCol := 0;
Queue := New(PQueue, Init);
repeat
ch := createMenu;
case ch of
'1': CreateMatrix;
'2': GenerateMatr;
'3': ViewMatr;
'4': SearchAllLinks;
end;
until ch = #27;
if PMatr <> nil then ClearMemMatrix(PMatr);
if PList <> nil then ClearList;
if Queue <> nil then Dispose(Queue);
end.
|
unit EntitiesData;
interface
uses
System.SysUtils, System.Classes, Data.DB, Data.Win.ADODB, System.Rtti;
type
TdmEntities = class(TDataModule)
dstEntities: TADODataSet;
dscEntities: TDataSource;
dstLandlord: TADODataSet;
dstLlPersonal: TADODataSet;
dscLlPersonal: TDataSource;
dstLlContact: TADODataSet;
dscLlContact: TDataSource;
dstImmHead: TADODataSet;
dstIHPersonal: TADODataSet;
dscIHPersonal: TDataSource;
dstIHContact: TADODataSet;
dscIHContact: TDataSource;
dstGroups: TADODataSet;
dscGroups: TDataSource;
dstParGroup: TADODataSet;
dscParGroup: TDataSource;
dstEmployers: TADODataSet;
dscEmployers: TDataSource;
dstRecipient: TADODataSet;
dstRcpPersonal: TADODataSet;
dscRcpPersonal: TDataSource;
dstReferee: TADODataSet;
dstRefPersonal: TADODataSet;
dscRefPersonal: TDataSource;
dstRefContact: TADODataSet;
dscRefContact: TDataSource;
dstGroupAttribute: TADODataSet;
dscGroupAttribute: TDataSource;
dstBranches: TADODataSet;
dscBranches: TDataSource;
procedure dstLandlordBeforeOpen(DataSet: TDataSet);
procedure dstLandlordBeforePost(DataSet: TDataSet);
procedure dstLlPersonalBeforeOpen(DataSet: TDataSet);
procedure dstLlPersonalBeforePost(DataSet: TDataSet);
procedure dstLlContactBeforeOpen(DataSet: TDataSet);
procedure dstLlContactBeforePost(DataSet: TDataSet);
procedure dstImmHeadBeforeOpen(DataSet: TDataSet);
procedure dstImmHeadBeforePost(DataSet: TDataSet);
procedure dstIHPersonalBeforeOpen(DataSet: TDataSet);
procedure dstIHPersonalBeforePost(DataSet: TDataSet);
procedure dstIHContactBeforeOpen(DataSet: TDataSet);
procedure dstIHContactBeforePost(DataSet: TDataSet);
procedure dstGroupsBeforePost(DataSet: TDataSet);
procedure dstGroupsNewRecord(DataSet: TDataSet);
procedure dstEmployersBeforePost(DataSet: TDataSet);
procedure dstRecipientBeforeOpen(DataSet: TDataSet);
procedure dstRecipientBeforePost(DataSet: TDataSet);
procedure dstRefereeBeforeOpen(DataSet: TDataSet);
procedure dstRefereeBeforePost(DataSet: TDataSet);
procedure dstRefPersonalBeforeOpen(DataSet: TDataSet);
procedure dstRefPersonalBeforePost(DataSet: TDataSet);
procedure dstRefContactBeforeOpen(DataSet: TDataSet);
procedure dstRefContactBeforePost(DataSet: TDataSet);
procedure dstGroupsAfterPost(DataSet: TDataSet);
procedure dstEmployersNewRecord(DataSet: TDataSet);
procedure dstEmployersAfterOpen(DataSet: TDataSet);
procedure dstEmployersAfterScroll(DataSet: TDataSet);
procedure dstEmployersAfterPost(DataSet: TDataSet);
procedure dstGroupAttributeBeforePost(DataSet: TDataSet);
procedure dstGroupsAfterOpen(DataSet: TDataSet);
procedure dstGroupAttributeNewRecord(DataSet: TDataSet);
procedure dstBranchesAfterScroll(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dmEntities: TdmEntities;
implementation
uses
AppData, Landlord, DBUtil, ImmediateHead, AppConstants,IFinanceGlobal,
Recipient, Referee, Employer, Group;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TdmEntities.dstLlContactBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := llord.Id;
end;
procedure TdmEntities.dstLlContactBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
DataSet.FieldByName('entity_id').AsString := llord.Id;
end;
procedure TdmEntities.dstBranchesAfterScroll(DataSet: TDataSet);
begin
dstParGroup.Filter := 'loc_code = ' + QuotedStr(DataSet.FieldByName('location_code').AsString);
end;
procedure TdmEntities.dstEmployersAfterOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Properties['Unique table'].Value := 'Employer';
end;
procedure TdmEntities.dstEmployersAfterPost(DataSet: TDataSet);
var
grpId: string;
begin
grpId := DataSet.FieldByName('grp_id').AsString;
RefreshDataSet(grpId,'grp_id',DataSet);
end;
procedure TdmEntities.dstEmployersAfterScroll(DataSet: TDataSet);
begin
with DataSet do
begin
grp := TGroup.Create;
grp.GroupId := FieldByName('grp_id').AsString;
grp.GroupName := FieldByName('grp_name').AsString;
emp := TEmployer.Create;
emp.Id := FieldByName('emp_id').AsString;
emp.Name := FieldByName('emp_name').AsString;
emp.Address := FieldByName('emp_add').AsString;
emp.Group := grp;
end;
end;
procedure TdmEntities.dstEmployersBeforePost(DataSet: TDataSet);
var
id: string;
begin
if DataSet.State = dsInsert then
begin
id := GetEmployerId;
DataSet.FieldByName('emp_id').AsString := id;
end;
end;
procedure TdmEntities.dstEmployersNewRecord(DataSet: TDataSet);
begin
with DataSet do
begin
FieldByName('loc_code').AsString := ifn.LocationCode;
end;
end;
procedure TdmEntities.dstGroupAttributeBeforePost(DataSet: TDataSet);
var
id: string;
begin
if DataSet.State = dsInsert then
begin
id := dstGroups.FieldByName('grp_id').AsString;
DataSet.FieldByName('grp_id').AsString := id;
end;
end;
procedure TdmEntities.dstGroupAttributeNewRecord(DataSet: TDataSet);
begin
with DataSet do
begin
FieldByName('is_gov').AsInteger := 1;
end;
end;
procedure TdmEntities.dstGroupsAfterOpen(DataSet: TDataSet);
begin
// open the attributes dataset
dstGroupAttribute.Open;
end;
procedure TdmEntities.dstGroupsAfterPost(DataSet: TDataSet);
begin
// refresh the parent group
dstParGroup.Requery;
end;
procedure TdmEntities.dstGroupsBeforePost(DataSet: TDataSet);
var
id: string;
begin
if DataSet.State = dsInsert then
begin
id := GetGroupId;
DataSet.FieldByName('grp_id').AsString := id;
end;
end;
procedure TdmEntities.dstGroupsNewRecord(DataSet: TDataSet);
begin
with DataSet do
begin
FieldByName('is_active').AsInteger := 1;
// FieldByName('loc_code').AsString := ifn.LocationCode;
end;
end;
procedure TdmEntities.dstIHContactBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := immHead.Id;
end;
procedure TdmEntities.dstIHContactBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then DataSet.FieldByName('entity_id').AsString := immHead.Id;
end;
procedure TdmEntities.dstIHPersonalBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := immHead.Id;
end;
procedure TdmEntities.dstIHPersonalBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then DataSet.FieldByName('entity_id').AsString := immHead.Id;
end;
procedure TdmEntities.dstImmHeadBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := immHead.Id;
end;
procedure TdmEntities.dstImmHeadBeforePost(DataSet: TDataSet);
var
id: string;
begin
if DataSet.State = dsInsert then
begin
id := GetEntityId;
DataSet.FieldByName('entity_id').AsString := id;
DataSet.FieldByName('entity_type').AsString :=
TRttiEnumerationType.GetName<TEntityTypes>(TEntityTypes.IH);
DataSet.FieldByName('loc_code').AsString := ifn.LocationCode;
SetCreatedFields(DataSet);
immHead.Id := id;
end;
end;
procedure TdmEntities.dstLandlordBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := llord.Id;
end;
procedure TdmEntities.dstLandlordBeforePost(DataSet: TDataSet);
var
id: string;
begin
if DataSet.State = dsInsert then
begin
id := GetEntityId;
DataSet.FieldByName('entity_id').AsString := id;
DataSet.FieldByName('entity_type').AsString :=
TRttiEnumerationType.GetName<TEntityTypes>(TEntityTypes.LL);
DataSet.FieldByName('loc_code').AsString := ifn.LocationCode;
SetCreatedFields(DataSet);
llord.Id := id;
end;
end;
procedure TdmEntities.dstLlPersonalBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := llord.Id;
end;
procedure TdmEntities.dstLlPersonalBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
DataSet.FieldByName('entity_id').AsString := llord.Id;
end;
procedure TdmEntities.dstRecipientBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := rcp.Id;
end;
procedure TdmEntities.dstRecipientBeforePost(DataSet: TDataSet);
var
id: string;
begin
if DataSet.State = dsInsert then
begin
id := GetEntityId;
DataSet.FieldByName('entity_id').AsString := id;
DataSet.FieldByName('entity_type').AsString :=
TRttiEnumerationType.GetName<TEntityTypes>(TEntityTypes.RP);
DataSet.FieldByName('loc_code').AsString := ifn.LocationCode;
SetCreatedFields(DataSet);
rcp.Id := id;
end;
end;
procedure TdmEntities.dstRefContactBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := ref.Id;
end;
procedure TdmEntities.dstRefContactBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then DataSet.FieldByName('entity_id').AsString := ref.Id;
end;
procedure TdmEntities.dstRefereeBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := ref.Id;
end;
procedure TdmEntities.dstRefereeBeforePost(DataSet: TDataSet);
var
id: string;
begin
if DataSet.State = dsInsert then
begin
id := GetEntityId;
DataSet.FieldByName('entity_id').AsString := id;
DataSet.FieldByName('entity_type').AsString :=
TRttiEnumerationType.GetName<TEntityTypes>(TEntityTypes.RF);
DataSet.FieldByName('loc_code').AsString := ifn.LocationCode;
SetCreatedFields(DataSet);
ref.Id := id;
end;
end;
procedure TdmEntities.dstRefPersonalBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := ref.Id;
end;
procedure TdmEntities.dstRefPersonalBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then DataSet.FieldByName('entity_id').AsString := ref.Id;
end;
end.
|
unit uresourcestring;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
resourcestring
rsTooManyRequestsTryAgainSoon = 'Too many Requests. Try again soon.';
rsErrorCantLoginTryGeneratingANewAPIKey =
'Error: Can''t login. Try generating a new API Key.';
rsErrorCantLogin = 'Can''t login.';
rsToday = 'TODAY';
rsYesterday = 'YESTERDAY';
rsErrorCantStopTimer = 'Error: Can''t stop timer.';
rsPleaseFillAllFields = 'Please fill all fields.';
rsThereMustBeAtLeastAMinuteOfDifferenceBetweenStartAndEndTime =
'There must be at least a minute of difference between start and end time.';
rsErrorCantDeleteTimeEntry = 'Error: Can''t delete time entry.';
rsErrorCantUpdateTimeEntry = 'Error: Can''t update time entry.';
rsErrorCantStartTimer = 'Error: Can''t start timer.';
rsErrorCantStartTimerTryStoppingCurrentTimerFirst =
'Error: Can''t start timer. Try stopping current timer first.';
rsStartTimer = 'Start Timer';
rsSaveEntry = 'Save Entry';
rsErrorCantCreateTask = 'Error: Can''t create task.';
rsPleaseEnterTaskDescription = 'Please enter task description.';
implementation
end.
|
unit JAWindow;
{$mode objfpc}{$H+}
interface
uses
{Amiga} Exec, amigados, Intuition, AGraphics, GadTools, Utility, picasso96api, cybergraphics,
{FPC} sysutils, math,
{JA} JATypes, JALog, JAScreen;
type
TJAWindowProperties = record
API : TJAGraphicsAPI;
Width : UInt16;
WidthMin : UInt16;
WidthMax : UInt16;
Height : UInt16;
HeightMin : UInt16;
HeightMax : UInt16;
Left : UInt16;
Top : UInt16;
Title : string;
Border : boolean;
end;
TJAWindow = record
Properties : TJAWindowProperties;
Screen : PJAScreen; {the screen this window is on}
{common to both intuition and picasso}
BorderLeft : UInt16;
BorderTop : UInt16;
BorderRight : UInt16;
BorderBottom : UInt16;
Window : pWindow;
RasterPort : pRastPort; {for the window bitmap}
ViewPort : pViewPort;
ColourMap : pColorMap;
UserPort : pMsgPort;
end;
PJAWindow = ^TJAWindow;
const
JAWindowPropertiesDefault : TJAWindowProperties = (
API : JAGraphicsAPI_Auto;
Width : 350;
WidthMin : 50;
WidthMax : 1000;
Height : 150;
HeightMin : 50;
HeightMax : 1000;
Left : 100;
Top : 100;
Title : 'JAWindow';
Border : true);
function JAWindowCreate(AWindowProperties : TJAWindowProperties; AScreen : PJAScreen) : PJAWindow;
function JAWindowDestroy(AWindow : PJAWindow) : boolean;
implementation
function JAWindowCreate(AWindowProperties : TJAWindowProperties; AScreen : PJAScreen) : PJAWindow;
var
WB : Pchar = 'Workbench';
//PubScreenName : Array [0..80] Of Char;
//template : string = 'Width=W/N,Height=H/N,Pubscreen=PS/K';
//vecarray : Array[0..2] of longint = (0,0,0);
//height,width : longint;
//rda : pRDArgs;
PIPErrorCode : longword;
//ANewWindow : TNewWindow;
begin
Result := PJAWindow(JAMemGet(SizeOf(TJAWindow)));
with Result^ do
begin
Properties := AWindowProperties;
Screen := AScreen;
case Properties.API of
JAGraphicsAPI_Intuition :
begin
Log('JAWindowCreate','Creating Intuition Window [%s] [%dx%dx%d]',[Properties.Title,Properties.Width,Properties.Height, round(power(2,AScreen^.Properties.Depth))]);
{create new window}
Window := OpenWindowTags(nil{@ANewWindow},[
//WA_PubScreen, astag(Result^.Screen^.Screen),
WA_CustomScreen, astag(Result^.Screen^.Screen),
WA_Title, AsTag(pchar(Result^.Properties.Title)),
WA_Left, AWindowProperties.Left,
Wa_Top, AWindowProperties.Top,
WA_Width, AWindowProperties.Width,
WA_Height, AWindowProperties.Height,
WA_MinWidth, AWindowProperties.WidthMin,
WA_MaxWidth, AWindowProperties.WidthMax,
WA_MinHeight, AWindowProperties.HeightMin,
WA_MaxHeight, AWindowProperties.HeightMax,
WA_Activate, ltrue,
WA_DragBar, ltrue,
WA_CloseGadget, ltrue,
WA_SizeGadget, ltrue,
WA_SizeBBottom, ltrue,
WA_GimmeZeroZero, longword(AWindowProperties.Border),
//WA_SuperBitmap, ltrue,
//WA_SimpleRefresh, ltrue,
//WA_SmartRefresh, ltrue,
WA_NoCareRefresh, ltrue,
//WA_Backdrop, ltrue,
//WA_Backfill, lfalse,
//WA_NewLookMenus, lfalse,
WA_ReportMouse, ltrue,
WA_RMBTrap, ltrue,
WA_IDCMP,
BUTTONIDCMP or
IDCMP_MOUSEMOVE or
IDCMP_MOUSEBUTTONS or
IDCMP_CLOSEWINDOW or
IDCMP_NEWSIZE or
IDCMP_RAWKEY or
IDCMP_VANILLAKEY or
IDCMP_MENUPICK or
IDCMP_INTUITICKS
// or IDCMP_REFRESHWINDOW
//WA_Flags, WFLG_WINDOWREFRESH or WFLG_REFRESHBITS
,TAG_END]);
if (Result^.Window = nil) then
begin
Log('JAWindowCreate','Failed To Create Intuition Window');
JAMemFree(Result,SizeOf(TJAWindow));
exit(nil);
end;
{store local references}
RasterPort := Window^.RPort;
RasterPort^.Flags := DBUFFER; {Indicate that the raster port is double buffered.}
ViewPort := @Screen^.Screen^.ViewPort;
UserPort := Window^.UserPort;
ColourMap := Viewport^.ColorMap;
//FreeColorMap(ViewPort^.ColorMap);
//ColourMap := GetColorMap(32);
////ViewPort^.ColorMap := ColourMap;
//ColourMap^.cm_vp := ViewPort;
//SetRGB4CM(ColourMap,50,15,0,0);
end;
JAGraphicsAPI_Picasso :
begin
Log('JAWindowCreate','Creating Picasso PIP Window [%s] [%dx%dx%d]',[Properties.Title,Properties.Width,Properties.Height, round(power(2,AScreen^.Properties.Depth))]);
//StrCopy(@PubScreenName,WB);
{rda := ReadArgs(pchar(template),@vecarray,Nil);
If rda<>Nil Then
begin
If (vecarray[0] <> 0) then width := plong(vecarray[0])^;
If (vecarray[1] <> 0) then height := long(@vecarray[1]);
If (vecarray[2] <> 0) then StrCopy(@PubScreenName,@vecarray[2]);
FreeArgs(rda);
Log('JAWindowCreate','ReadArgs Width = ' + inttostr(width));
Log('JAWindowCreate','ReadArgs Height = ' + inttostr(height));
Log('JAWindowCreate','ReadArgs PubScreenName = ' + PubScreenName);
end;}
//StrCopy(@PubScreenName,WB);
{P96PIP_SourceBitMap
P96PIP_SourceRPort
P96PIP_RenderFunc}
{
This is nothing special. RTG games can support windowed mode but using overlay adds some nice extra features compared to fullscreen/overlay mode:
- PIP overlay can support scaling for free. (This is very useful for video players)
- PIP overlay can support different color depths (overlay can for example use 16-bit mode when WB is using 32-bit mode)
Overlay is basically separate "fullscreen mode" overlayed in top of normal screen, position and size can be freely chosen. Overlays were supported in hardware in most VGA chips. Later models used 3D hardware to do the overlay and dropped the hardware level bitmap overlay support.
}
{open a picasso PIP window}
Result^.Window := p96PIP_OpenTags([
WA_CustomScreen, astag(Result^.Screen^.Screen),
P96PIP_ErrorCode, astag(@PIPErrorCode),
WA_Title, AsTag(pchar(Result^.Properties.Title)),
P96PIP_SourceFormat, long(RGBFB_R5G5B5),
//P96PIP_SourceFormat, long(RGBFB_R5G5B5),
//P96PIP_SourceFormat, long(RGBFF_R8G8B8),
P96PIP_SourceWidth, long(AWindowProperties.Width),
P96PIP_SourceHeight, long(AWindowProperties.Height),
P96PIP_AllowCropping, ltrue,
//P96PIP_Type, long(P96PIPT_MemoryWindow),
//P96PIP_Type, long(P96PIPT_VideoWindow),
//P96PIP_Width, long(AWindowProperties.Width),
//P96PIP_Height, long(AWindowProperties.Height),
WA_InnerWidth, long(AWindowProperties.Width),
WA_InnerHeight, long(AWindowProperties.Height),
//WA_Width, long(AWindowProperties.Width),
//WA_Height, long(AWindowProperties.Height),
WA_GimmeZeroZero, longword(AWindowProperties.Border),
WA_Activate, ltrue,
WA_NoCareRefresh, ltrue,
WA_SimpleRefresh,lTRUE,
WA_CloseGadget,lTRUE,
WA_ReportMouse, ltrue,
WA_RMBTrap, ltrue,
WA_IDCMP, BUTTONIDCMP or IDCMP_MOUSEMOVE or IDCMP_CLOSEWINDOW or IDCMP_NEWSIZE or IDCMP_VANILLAKEY or IDCMP_MENUPICK or IDCMP_INTUITICKS, //or IDCMP_REFRESHWINDOW,
TAG_DONE]);
if (Result^.Window = nil) then
begin
Log('JAWindowCreate','Failed To Create Picasso PIP Window [PIPErrorCode = %d]',[PIPErrorCode]);
JAMemFree(Result,SizeOf(TJAWindow));
exit(nil);
end;
{store local references}
p96PIP_GetTags(Window,[P96PIP_SourceRPort, AsTag(RasterPort), TAG_END]); {get the picasso pip window raster Port}
RasterPort^.Flags := DBUFFER; {Indicate that the raster port is double buffered.}
ViewPort := @Screen^.Screen^.ViewPort;
ColourMap := ViewPort^.Colormap;
UserPort := Window^.UserPort;
end;
end;
{for GimmieZeroZero}
BorderLeft := 0;
BorderTop := 0;
BorderRight := Properties.Width - (Window^.BorderRight + Window^.BorderLeft);
BorderBottom := Properties.Height - (Window^.BorderBottom + Window^.BorderTop);
//Result^.BorderLeft := Result^.Window^.BorderLeft;
//Result^.BorderTop := Result^.Window^.BorderTop;
{BorderLeft := FAmigaWindow^.BorderLeft;
BorderTop := FAmigaWindow^.BorderTop;
BorderRight := 300 - FAmigaWindow^.BorderRight;
BorderBottom := 150 - FAmigaWindow^.BorderBottom;}
end;
end;
function JAWindowDestroy(AWindow : PJAWindow) : boolean;
begin
if (AWindow=nil) then exit(false);
if (AWindow^.Window=nil) then exit(false);
{close the window}
case AWindow^.Properties.API of
JAGraphicsAPI_Intuition :
begin
Log('JAWindowDestroy','Destroying Intuition Window [%s]',[AWindow^.Properties.Title]);
CloseWindow(AWindow^.Window);
end;
JAGraphicsAPI_Picasso :
begin
Log('JAWindowDestroy','Destroying Picasso PIP Window [%s]',[AWindow^.Properties.Title]);
p96PIP_Close(AWindow^.Window);
end;
end;
{Free Strings}
SetLength(AWindow^.Properties.Title, 0);
JAMemFree(AWindow,SizeOf(TJAWindow));
Result := true;
end;
end.
|
unit uLd;
interface
uses uInterfaces;
type
// 索引,标题,顶层窗口句柄,绑定窗口句柄,是否进入android,进程PID,VBox进程PID
TLd = class
strict private
class function GetRunConsoleResult(FileName: string;
const Visibility: Integer; var mOutputs: string): Integer;
public
class var FilePath: string;
class var Visibility: Integer;
class constructor Create();
class procedure Launch(const index: Integer); // 启动模拟器
class procedure LaunchEx(const index: Integer; PackageName: string);
// 启动模拟器并打开应用
class procedure Quit(const index: Integer); // 退出模拟器
class procedure QuitAll(); // 退出所有模拟器
class procedure Reboot(const index: Integer); // 重启模拟器系统
class procedure RunApp(const index: Integer; PackageName: string); // 启动程序
class procedure KillApp(const index: Integer; PackageName: string);
class procedure SetProp(const index: Integer; key, value: string); // 设置属性
class function GetProp(const index: Integer; key: string = '';
value: string = ''): string; // 获得属性
class function Adb(const index: Integer; command: string): string;
class function ListPackages(const index: Integer): string;
// 不设置为''
class procedure Modify(const index, w, h, dpi, { <w,h,dpi>] // 自定义分辨率 }
cpu, { <1 | 2 | 3 | 4>] // cpu设置 }
memory: Integer; { 512 | 1024 | 2048 | 4096 | 8192> //内存设置 }
manufacturer { 手机厂商 } , model, { 手机型号 }
pnumber, { 手机号13812345678 }
imei, { <auto | 865166023949731>] // imei设置,auto就自动随机生成 }
imsi, { <auto | 460000000000000>] }
simserial, { <auto | 89860000000000000000>] }
androidid, { <auto | 0123456789abcdef>] }
mac, { <auto | 000000000000>] //12位m16进制mac地址 }
autorotate, { <1 | 0>] }
lockwindow { <1 | 0>] }
: string);
// list2一次性返回了多个信息,依次是:索引,标题,顶层窗口句柄,绑定窗口句柄,是否进入android,进程PID,VBox进程PID
class function List2(): string;
class function List2Ex(): TArray<TEmulatorInfo>; // 解析出最后结果
class function FindEmulator(const index: Integer): TEmulatorInfo;
class procedure DownCpu(const index: Integer;
const rate: Integer { 0~10 } ); // 降低cpu
class procedure InstallApp(const index: Integer; apkFileName: string);
// 安装应用
class procedure uninstallapp(const index: Integer; PackageName: string);
// 卸载应用
class procedure Backup(const index: Integer; FileName: string); // 备份
class procedure Restore(const index: Integer; FileName: string); // 还原
class procedure SortWnd(); // 排序窗口
class procedure GlobalSetting(const fps: Integer; { 模拟器帧率0~60 } // 全局设置
const audio: Integer; { 音频 1~10 }
const fastply: Integer; { 快速显示模式 1:0 }
const cleanmode: Integer { 干净模式,去除广告 1:0 }
);
class procedure Locate(const index: Integer; const Lng, Lat: Integer);
// 修改定位重启生效
class procedure Action(const index: Integer; key, value: string); // 执行一些操作
// 修改定位即时生效
class procedure LocateByAction(const index: Integer;
const Lng, Lat: Integer);
// 重命名
class procedure Rename(const index: Integer; title: string);
// 重启模拟器,启动后并打开 packagename 应用, null 表示不打开任何应用
class procedure RebootByAction(const index: Integer;
PackageName: string = 'null');
// 摇一摇
class procedure ShakeByAction(const index: Integer);
// 文字输入
class procedure InputByAction(const index: Integer; value: string);
// 断开和连接网络命令 offline connect
class procedure NetworkByAction(const index: Integer;
const IsConnect: Boolean);
class procedure Scan(const index: Integer; FileName: string);
// 备份应用
class procedure BackupApp(const index: Integer; PackageName: string;
FileName: string);
// 还原应用
class procedure RestoreApp(const index: Integer; PackageName: string;
FileName: string);
// 模拟器是否运行
class function IsRuning(const index: Integer): Boolean;
// 新增模拟器
class procedure Add(name: string);
// 复制模拟器
class procedure Copy(name: string; const FromIndex: Integer);
// 移除模拟器
class procedure Remove(const index: Integer);
//
// class procedure SetPropByFile(const index: Integer; key, value: Variant);
end;
implementation
uses
Winapi.Windows, System.SysUtils, Vcl.Forms, {qjson,} System.Types;
{ TLd }
class procedure TLd.Action(const index: Integer; key, value: string);
begin
WinExec(PAnsiChar(Ansistring
(Format('%s action --index %d --key %s --value %s', [FilePath, index, key,
value]))), Visibility);
end;
class function TLd.Adb(const index: Integer; command: string): string;
begin
GetRunConsoleResult
(PAnsiChar(Ansistring(Format('%s adb --index %d --command "%s"',
[FilePath, index, command]))), Visibility, Result);
end;
class procedure TLd.Add(name: string);
begin
WinExec(PAnsiChar(Ansistring(Format('%s add --name %s ', [FilePath, name]))),
Visibility);
end;
class procedure TLd.Backup(const index: Integer; FileName: string);
begin
WinExec(PAnsiChar(Ansistring(Format('%s backup --index %d --file %s',
[FilePath, index, FileName]))), Visibility);
end;
class procedure TLd.BackupApp(const index: Integer;
PackageName, FileName: string);
begin
WinExec(PAnsiChar(Ansistring
(Format('%s backup --index %d --packagename %s --file %s', [FilePath, index,
PackageName, FileName]))), Visibility);
end;
class procedure TLd.Copy(name: string; const FromIndex: Integer);
begin
WinExec(PAnsiChar(Ansistring(Format('%s add --name %s --from %d ',
[FilePath, name, FromIndex]))), Visibility);
end;
class constructor TLd.Create;
begin
FilePath := 'D:\Changzhi\dnplayer2\dnconsole.exe';
TLd.Visibility := 1;
end;
class procedure TLd.DownCpu(const index, rate: Integer);
begin
WinExec(PAnsiChar(Ansistring(Format('%s downcpu --index %d --rate %d',
[FilePath, index, rate]))), Visibility);
end;
class function TLd.FindEmulator(const index: Integer): TEmulatorInfo;
var
emulatorInfoArr: TArray<TEmulatorInfo>;
emulatorInfo: TEmulatorInfo;
begin
FillChar(Result, SizeOf(TEmulatorInfo), 0); // 0填充
emulatorInfoArr := TLd.List2Ex;
for emulatorInfo in emulatorInfoArr do
begin
if emulatorInfo.index = index then
Result := emulatorInfo;
end;
end;
class function TLd.GetProp(const index: Integer; key, value: string): string;
var
commandLine: string;
begin
if key.IsEmpty or value.IsEmpty then
begin
commandLine := Format('%s getprop --index 0', [FilePath])
end
else
begin
commandLine := Format('%s getprop --index 0 --key "%s" --value "%s"',
[FilePath, key, value])
end;
GetRunConsoleResult(commandLine, TLd.Visibility, Result);
end;
class function TLd.GetRunConsoleResult(FileName: string;
const Visibility: Integer; var mOutputs: string): Integer;
var
sa: TSecurityAttributes;
hReadPipe, hWritePipe: THandle;
ret: BOOL;
strBuff: array [0 .. 255] of Ansichar;
lngBytesread: DWORD;
WorkDir: string;
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
begin
FillChar(sa, SizeOf(sa), 0);
sa.nLength := SizeOf(sa);
sa.bInheritHandle := True;
sa.lpSecurityDescriptor := nil;
if not(CreatePipe(hReadPipe, hWritePipe, @sa, 0)) then
begin
Result := -2; // 通道创建失败
end;
WorkDir := ExtractFileDir(Application.ExeName);
FillChar(StartupInfo, SizeOf(StartupInfo), #0);
StartupInfo.cb := SizeOf(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
StartupInfo.wShowWindow := Visibility;
StartupInfo.hStdOutput := hWritePipe;
StartupInfo.hStdError := hWritePipe;
if not CreateProcess(nil, PChar(FileName), { pointer to command line string }
@sa, { pointer to process security attributes }
@sa, { pointer to thread security attributes }
True, { handle inheritance flag }
NORMAL_PRIORITY_CLASS, nil, { pointer to new environment block }
PChar(WorkDir), { pointer to current directory name, PChar }
StartupInfo, { pointer to STARTUPINFO }
ProcessInfo) { pointer to PROCESS_INF }
then
Result := INFINITE { -1 进程创建失败 }
else
begin
CloseHandle(hWritePipe);
mOutputs := '';
while ret do
begin
FillChar(strBuff, SizeOf(strBuff), #0);
ret := ReadFile(hReadPipe, strBuff, 256, lngBytesread, nil);
mOutputs := mOutputs + strBuff;
end;
Application.ProcessMessages;
// 等待console结束
WaitforSingleObject(ProcessInfo.hProcess, INFINITE);
GetExitCodeProcess(ProcessInfo.hProcess, Cardinal(Result));
CloseHandle(ProcessInfo.hProcess); { to prevent memory leaks }
CloseHandle(ProcessInfo.hThread);
CloseHandle(hReadPipe);
end;
end;
class procedure TLd.GlobalSetting(const fps, audio, fastply,
cleanmode: Integer);
var
comm: string;
begin
comm := Format('%s --fps %d --audio %d --fastplay %d --cleanmpde %d',
[FilePath, fps, audio, fastply, cleanmode]);
WinExec(PAnsiChar(Ansistring(comm)), Visibility);
end;
class procedure TLd.InputByAction(const index: Integer; value: string);
begin
Action(index, 'call.input', value);
end;
class procedure TLd.InstallApp(const index: Integer; apkFileName: string);
begin
WinExec(PAnsiChar(Ansistring(Format('%s installapp --index %d --filename %s',
[FilePath, index, apkFileName]))), Visibility);
end;
class function TLd.IsRuning(const index: Integer): Boolean;
var
r: string;
begin
Result := False;
GetRunConsoleResult(Format('%s isrunning --index %d', [FilePath, index]),
TLd.Visibility, r);
if r = 'runing' then
Result := True
else if r = 'stop' then
Result := False;
end;
class procedure TLd.KillApp(const index: Integer; PackageName: string);
begin
WinExec(PAnsiChar(Ansistring(Format('%s killapp --index %d --packagename %s',
[FilePath, index, PackageName]))), Visibility);
end;
class procedure TLd.Launch(const index: Integer);
begin
WinExec(PAnsiChar(Ansistring(Format('%s launch --index %d', [FilePath, index])
)), Visibility);
end;
class procedure TLd.LaunchEx(const index: Integer; PackageName: string);
begin
WinExec(PAnsiChar(Ansistring
(Format('%s launchex --index %d --packagename "%s"', [FilePath, index,
PackageName]))), Visibility);
end;
class function TLd.List2: string;
begin
GetRunConsoleResult(Format('%s list2', [FilePath]), TLd.Visibility, Result);
end;
class function TLd.ListPackages(const index: Integer): string;
begin
Result := Adb(index, 'shell pm list packages');
end;
class procedure TLd.Locate(const index, Lng, Lat: Integer);
begin
WinExec(PAnsiChar(Ansistring(Format('%s locate --index %d --LLI %d,%d',
[FilePath, index, Lng, Lat]))), Visibility);
end;
class procedure TLd.LocateByAction(const index, Lng, Lat: Integer);
begin
Action(index, 'call.locate', Format('%d,%d', [Lng, Lat]));
end;
class function TLd.List2Ex: TArray<TEmulatorInfo>;
var
sr: string;
sarrAll, sCurrArr: TArray<string>;
I: Integer;
s: string;
emulatorInfo: TEmulatorInfo;
begin
sr := List2();
sr := Trim(sr);
sarrAll := sr.Split([#10, #13]);
Result := [];
for s in sarrAll do
begin
sCurrArr := s.Split([',']);
if Length(sCurrArr) = 7 then
begin
emulatorInfo.index := sCurrArr[0].ToInteger;
emulatorInfo.title := sCurrArr[1];
emulatorInfo.ParentHwnd := sCurrArr[2].ToInteger;
emulatorInfo.BindHwnd := sCurrArr[3].ToInteger;
emulatorInfo.IsInAndroid := sCurrArr[4].ToBoolean();
emulatorInfo.Pid := sCurrArr[5].ToInteger();
emulatorInfo.VBpxPid := sCurrArr[6].ToInteger();
Result := Result + [emulatorInfo];
end;
end;
end;
class procedure TLd.Modify(const index, w, h, dpi, cpu, memory: Integer;
manufacturer, model, pnumber, imei, imsi, simserial, androidid, mac,
autorotate, lockwindow: string);
var
commandLine: string;
begin
commandLine := Format('%s modify --index %d', [TLd.FilePath, index]);
if (w > 0) and (h > 0) and (dpi > 0) then
commandLine := Format('%s --resolution %d,%d,%d', [commandLine, w, h, dpi]);
if cpu > 0 then
commandLine := Format('%s --cpu %d', [commandLine, cpu]);
if memory > 0 then
commandLine := Format('%s --memory %d', [commandLine, memory]);
if manufacturer <> '' then
commandLine := Format('%s --manufacturer %s', [commandLine, manufacturer]);
if model <> '' then
commandLine := Format('%s --model %s', [commandLine, model]);
if pnumber <> '' then
commandLine := Format('%s --pnumber %s', [commandLine, pnumber]);
if imei <> '' then
commandLine := Format('%s --imei %s', [commandLine, imei]);
if imsi <> '' then
commandLine := Format('%s --imsi %s', [commandLine, imsi]);
if simserial <> '' then
commandLine := Format('%s --simserial %s', [commandLine, simserial]);
if androidid <> '' then
commandLine := Format('%s --androidid %s', [commandLine, androidid]);
if mac <> '' then
commandLine := Format('%s --mac %s', [commandLine, mac]);
if autorotate <> '' then
commandLine := Format('%s --autorotate %s', [commandLine, autorotate]);
if lockwindow <> '' then
commandLine := Format('%s --lockwindow %s', [commandLine, lockwindow]);
WinExec(PAnsiChar(Ansistring(commandLine)), Visibility);
end;
class procedure TLd.NetworkByAction(const index: Integer;
const IsConnect: Boolean);
var
value: string;
begin
if IsConnect then
value := 'connect'
else
value := 'offline';
Action(index, 'call.network', value);
end;
class procedure TLd.Quit(const index: Integer);
begin
WinExec(PAnsiChar(Ansistring(Format('%s quit --index %d', [FilePath, index]))
), Visibility);
end;
class procedure TLd.QuitAll;
begin
WinExec(PAnsiChar(Ansistring(Format('%s quitall ', [FilePath]))), Visibility);
end;
class procedure TLd.Reboot(const index: Integer);
begin
WinExec(PAnsiChar(Ansistring(Format('%s reboot --index %d', [FilePath, index])
)), Visibility);
end;
class procedure TLd.RebootByAction(const index: Integer; PackageName: string);
begin
Action(index, 'call.reboot', Format('packagename/', ['%s']));
end;
class procedure TLd.Remove(const index: Integer);
begin
WinExec(PAnsiChar(Ansistring(Format('%s remove --index %d', [FilePath, index])
)), Visibility);
end;
class procedure TLd.Rename(const index: Integer; title: string);
begin
WinExec(PAnsiChar(Ansistring(Format('%s rename --index %d --title %s',
[FilePath, index, title]))), Visibility);
end;
class procedure TLd.Restore(const index: Integer; FileName: string);
begin
WinExec(PAnsiChar(Ansistring(Format('%s restore --index %d --file %s',
[FilePath, index, FileName]))), Visibility);
end;
class procedure TLd.RestoreApp(const index: Integer;
PackageName, FileName: string);
begin
WinExec(PAnsiChar(Ansistring
(Format('%s restoreapp --index %d --packagename %s --file %s',
[FilePath, index, PackageName, FileName]))), Visibility);
end;
class procedure TLd.RunApp(const index: Integer; PackageName: string);
begin
WinExec(PAnsiChar(Ansistring(Format('%s runapp --index %d --packagename %s',
[FilePath, index, PackageName]))), Visibility);
end;
class procedure TLd.Scan(const index: Integer; FileName: string);
begin
WinExec(PAnsiChar(Ansistring(Format('%s scan --index %d --file %s',
[FilePath, index, FileName]))), Visibility);
end;
class procedure TLd.SetProp(const index: Integer; key, value: string);
begin
WinExec(PAnsiChar(Ansistring
(Format('%s setprop --index %d --key "%s" --value "%s"', [FilePath, index,
key, value]))), Visibility);
end;
// class procedure TLd.SetPropByFile(const index: Integer; key, value: Variant);
// var
// js: TQJson;
// cfgFile: string;
// note: TQJson;
// begin
// js := TQJson.Create;
// try
// cfgFile := Format('%s\vms\config\leidian%d.config',
// [ExtractFileDir(FilePath), index]);
// if not FileExists(cfgFile) then
// Exit;
// js.LoadFromFile(cfgFile);
// note := js.ForceName(key);
//
// note.AsVariant := value;
//
// js.SaveToFile(cfgFile);
// finally
// js.Free;
// end;
//
// end;
class procedure TLd.ShakeByAction(const index: Integer);
begin
Action(index, 'call.shake', 'null');
end;
class procedure TLd.SortWnd;
begin
WinExec(PAnsiChar(Ansistring(Format('%s sortWnd', [FilePath]))), Visibility);
end;
class procedure TLd.uninstallapp(const index: Integer; PackageName: string);
begin
WinExec(PAnsiChar(Ansistring
(Format('%s uninstallapp --index %d --packagename %s', [FilePath, index,
PackageName]))), Visibility);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC Advantage Database Server metadata }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.ADSMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator;
type
TFDPhysADSMetadata = class (TFDPhysConnectionMetadata)
private
FFreeConnection: Boolean;
protected
function GetKind: TFDRDBMSKind; override;
function GetIsFileBased: Boolean; override;
function GetTxSavepoints: Boolean; override;
function GetTxNested: Boolean; override;
function GetEventSupported: Boolean; override;
function GetEventKinds: String; override;
function GetTruncateSupported: Boolean; override;
function GetParamNameMaxLength: Integer; override;
function GetNameParts: TFDPhysNameParts; override;
function GetNameCaseSensParts: TFDPhysNameParts; override;
function GetNameDefLowCaseParts: TFDPhysNameParts; override;
function GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; override;
function GetNamedParamMark: TFDPhysParamMark; override;
function GetInlineRefresh: Boolean; override;
function GetPositionedParamMark: TFDPhysParamMark; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function GetAsyncAbortSupported: Boolean; override;
function GetAsyncNativeTimeout: Boolean; override;
function GetDefValuesSupported: TFDPhysDefaultValues; override;
function GetLockNoWait: Boolean; override;
function GetNameQuotedCaseSensParts: TFDPhysNameParts; override;
function GetArrayExecMode: TFDPhysArrayExecMode; override;
function GetLimitOptions: TFDPhysLimitOptions; override;
function GetColumnOriginProvided: Boolean; override;
function InternalEscapeDate(const AStr: String): String; override;
function InternalEscapeDateTime(const AStr: String): String; override;
function InternalEscapeFloat(const AStr: String): String; override;
function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override;
function InternalEscapeTime(const AStr: String): String; override;
function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
public
constructor Create(const AConnectionObj: TFDPhysConnection;
AServerVersion, AClientVerison: TFDVersion; AFreeConn: Boolean);
end;
TFDPhysADSCommandGenerator = class(TFDPhysCommandGenerator)
protected
function GetSingleRowTable: String; override;
function GetRowId(var AAlias: String): String; override;
function GetInlineRefresh(const AStmt: String; ARequest: TFDUpdateRequest): String; override;
function GetIdentity(ASessionScope: Boolean): String; override;
function GetPessimisticLock: String; override;
function GetCall(const AName: String): String; override;
function GetSavepoint(const AName: String): String; override;
function GetRollbackToSavepoint(const AName: String): String; override;
function GetStoredProcCall(const ACatalog, ASchema, APackage, AProc: String;
AOverload: Word; ASPUsage: TFDPhysCommandKind): String; override;
function GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind; const ACatalog,
ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String; override;
function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer;
var AOptions: TFDPhysLimitOptions): String; override;
function GetColumnType(AColumn: TFDDatSColumn): String; override;
function GetMerge(AAction: TFDPhysMergeAction): String; override;
end;
implementation
uses
System.SysUtils, Data.DB,
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Param;
const
// Copied from FireDAC.Phys.ADSCli
ADS_MAX_OBJECT_NAME = 200; // maximum length of DD object name
ADS_MAX_FIELD_NAME = 128;
{-------------------------------------------------------------------------------}
{ TFDPhysADSMetadata }
{-------------------------------------------------------------------------------}
constructor TFDPhysADSMetadata.Create(const AConnectionObj: TFDPhysConnection;
AServerVersion, AClientVerison: TFDVersion; AFreeConn: Boolean);
begin
inherited Create(AConnectionObj, AServerVersion, AClientVerison, False);
FKeywords.CommaText := 'ADD,ALL,ALTER,AND,ANY,AS,ASC,AT,AVG,BEGIN,BETWEEN,' +
'BY,CASE,CAST,CLOSE,COLUMN,COMMIT,CONSTRAINT,COUNT,CREATE,CURSOR,' +
'DECLARE,DEFAULT,DELETE,DESC,DISTINCT,DROP,ELSE,END,ESCAPE,EXECUTE,' +
'EXISTS,FALSE,FETCH,FOR,FROM,FULL,FUNCTION,GRANT,GROUP,HAVING,IN,' +
'INDEX,INNER,INSERT,INTO,IS,JOIN,KEY,LEFT,LIKE,MAX,MERGE,MIN,NOT,NULL,' +
'OF,ON,OPEN,OR,ORDER,OUTER,OUTPUT,PRIMARY,PROCEDURE,RETURN,RETURNS,' +
'REVOKE,RIGHT,ROLLBACK,SAVEPOINT,SELECT,SET,SQL,SUM,TABLE,THEN,TO,' +
'TRANSACTION,TRUE,UNION,UNIQUE,UPDATE,USER,USING,VALUES,VIEW,WHEN,WHERE,WORK';
FFreeConnection := AFreeConn;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.Advantage;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetIsFileBased: Boolean;
begin
Result := FFreeConnection;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts;
begin
Result := [npCatalog];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetNameCaseSensParts: TFDPhysNameParts;
begin
Result := [npCatalog];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetParamNameMaxLength: Integer;
begin
Result := ADS_MAX_FIELD_NAME;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetNameParts: TFDPhysNameParts;
begin
Result := [npCatalog, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel;
ASide: TFDPhysNameQuoteSide): Char;
begin
Result := #0;
case AQuote of
ncDefault:
Result := '"';
ncSecond:
if ASide = nsLeft then
Result := '['
else
Result := ']';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetNamedParamMark: TFDPhysParamMark;
begin
Result := prName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetPositionedParamMark: TFDPhysParamMark;
begin
Result := prQMark;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetTxSavepoints: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetTxNested: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetEventSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetEventKinds: String;
begin
Result := S_FD_EventKind_ADS_Events;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetInlineRefresh: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetTruncateSupported: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
if GetServerVersion >= caADS12 then
Result := dvDefVals
else
Result := dvDef;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetLockNoWait: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
if GetServerVersion >= caADS10 then
Result := [soWithoutFrom, soInlineView]
else
Result := [soWithoutFrom];
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysADSMetadata.GetAsyncAbortSupported: Boolean;
begin
Result := True;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysADSMetadata.GetAsyncNativeTimeout: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetArrayExecMode: TFDPhysArrayExecMode;
begin
Result := aeUpToFirstError;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetLimitOptions: TFDPhysLimitOptions;
begin
if GetServerVersion >= caADS10 then
Result := [loSkip, loRows]
else
Result := [loRows];
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.GetColumnOriginProvided: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.InternalEscapeDate(const AStr: String): String;
begin
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS SQL_DATE)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS SQL_TIMESTAMP)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.InternalEscapeTime(const AStr: String): String;
begin
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS SQL_TIME)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.InternalEscapeFloat(const AStr: String): String;
begin
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS SQL_DOUBLE)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String;
var
sName: String;
A1, A2, A3, A4: String;
i: Integer;
function AddArgs: string;
begin
Result := '(' + AddEscapeSequenceArgs(ASeq) + ')';
end;
begin
sName := ASeq.FName;
if Length(ASeq.FArgs) >= 1 then begin
A1 := ASeq.FArgs[0];
if Length(ASeq.FArgs) >= 2 then begin
A2 := ASeq.FArgs[1];
if Length(ASeq.FArgs) >= 3 then begin
A3 := ASeq.FArgs[2];
if Length(ASeq.FArgs) >= 4 then
A4 := ASeq.FArgs[3];
end;
end;
end;
case ASeq.FFunc of
// the same
// char
efASCII,
efBIT_LENGTH,
efCHAR_LENGTH,
efCONCAT,
efCHAR,
efINSERT,
efLCASE,
efLEFT,
efLENGTH,
efLTRIM,
efLOCATE,
efOCTET_LENGTH,
efREPEAT,
efREPLACE,
efRIGHT,
efRTRIM,
efSPACE,
efSUBSTRING,
efUCASE,
// numeric
efACOS,
efASIN,
efATAN,
efATAN2,
efABS,
efCEILING,
efCOS,
efCOT,
efDEGREES,
efEXP,
efFLOOR,
efLOG,
efLOG10,
efMOD,
efPOWER,
efPI,
efRADIANS,
efSIGN,
efSIN,
efSQRT,
efTAN,
// date and time
efCURDATE,
efCURTIME,
efNOW,
efDAYNAME,
efDAYOFMONTH,
efDAYOFWEEK,
efDAYOFYEAR,
efHOUR,
efMINUTE,
efMONTH,
efMONTHNAME,
efQUARTER,
efSECOND,
efWEEK,
efYEAR:
Result := sName + AddArgs;
// char:
efPOSITION:
Result := sName + '(' + A1 + ' IN ' + A2 + ')';
// numeric
efRANDOM: Result := 'RAND' + AddArgs;
efROUND,
efTRUNCATE:
if A2 = '' then
Result := sName + '(' + A1 + ', 0)'
else
Result := sName + AddArgs;
// date and time
efEXTRACT:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
Result := sName + '(' + A1 + ' FROM ' + A2 + ')';
end;
efTIMESTAMPADD:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'FRAC_SECOND' then
A2 := '(' + A2 + ' / 1000)';
Result := sName + '(SQL_TSI_' + A1 + ', ' + A2 + ', ' + A3 + ')';
end;
efTIMESTAMPDIFF:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
Result := sName + '(SQL_TSI_' + A1 + ', ' + A2 + ', ' + A3 + ')';
if A1 = 'FRAC_SECOND' then
Result := '(CAST(' + Result + ' AS SQL_NUMERIC(20,0)) * 1000)';
end;
// system
efCATALOG: Result := 'DATABASE()';
efSCHEMA: Result := '''''';
efIF: Result := 'IIF' + AddArgs;
efIFNULL:
begin
A1 := UpperCase(Trim(A1));
if A1 = 'NULL' then
Result := A2
else
Result := sName + AddArgs;
end;
efDECODE:
begin
Result := 'CASE ' + ASeq.FArgs[0];
i := 1;
while i < Length(ASeq.FArgs) - 1 do begin
Result := Result + ' WHEN ' + ASeq.FArgs[i] + ' THEN ' + ASeq.FArgs[i + 1];
Inc(i, 2);
end;
if i = Length(ASeq.FArgs) - 1 then
Result := Result + ' ELSE ' + ASeq.FArgs[i];
Result := Result + ' END';
end;
efCONVERT:
begin
A2 := UpperCase(FDUnquote(Trim(A2), ''''));
if A2 = 'DATETIME' then
A2 := 'TIMESTAMP';
Result := sName + '(' + A1 + ', SQL_' + A2 + ')';
end;
else
UnsupportedEscape(ASeq);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSMetadata.InternalGetSQLCommandKind(
const ATokens: TStrings): TFDPhysCommandKind;
var
sToken: String;
begin
sToken := ATokens[0];
if sToken = 'DECLARE' then
Result := skExecute
else if sToken = 'BEGIN' then
if ATokens.Count = 1 then
Result := skNotResolved
else if (ATokens[1] = 'TRAN') or (ATokens[1] = 'TRANSACTION') then
Result := skStartTransaction
else
Result := inherited InternalGetSQLCommandKind(ATokens)
else if sToken = 'SHOW' then
if ATokens.Count = 1 then
Result := skNotResolved
else if ATokens[1] = 'PLAN' then
Result := skSelect
else
Result := inherited InternalGetSQLCommandKind(ATokens)
else if sToken = 'EXECUTE' then
if ATokens.Count < 3 then
Result := skNotResolved
else if ATokens[1] = 'PROCEDURE' then begin
if Copy(ATokens[2], 1, 7) = 'SP_DROP' then
Result := skDrop
else if Copy(ATokens[2], 1, 9) = 'SP_CREATE' then
Result := skCreate
else if Copy(ATokens[2], 1, 9) = 'SP_MODIFY' then
Result := skAlter
else
Result := skExecute;
end
else
Result := skExecute
else
Result := inherited InternalGetSQLCommandKind(ATokens);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysADSCommandGenerator }
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String;
begin
Result := GenerateSelect(False);
if Result <> '' then
Result := AStmt + ';' + BRK + Result
else
Result := AStmt;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetIdentity(ASessionScope: Boolean): String;
begin
if ASessionScope then
Result := 'LASTAUTOINC(CONNECTION)'
else
Result := 'LASTAUTOINC(STATEMENT)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetSingleRowTable: String;
begin
Result := 'SYSTEM.IOTA';
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetRowId(var AAlias: String): String;
begin
Result := 'ROWID';
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetPessimisticLock: String;
var
lNeedFrom: Boolean;
begin
Result := Result + 'SELECT ' + GetSelectList(True, False, lNeedFrom) +
' FROM ' + GetFrom + ' WHERE ' + GetWhere(False, True, False);
FCommandKind := skSelectForLock;
ASSERT(lNeedFrom);
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetSavepoint(const AName: String): String;
begin
Result := 'SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetRollbackToSavepoint(const AName: String): String;
begin
Result := 'ROLLBACK TO SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetCall(const AName: String): String;
begin
Result := 'EXECUTE PROCEDURE ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetStoredProcCall(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
var
i: Integer;
sInPar: String;
oParam: TFDParam;
lHasOutput, lHasResult: Boolean;
rName: TFDPhysParsedName;
sProc: String;
begin
sInPar := '';
lHasOutput := False;
lHasResult := False;
for i := 0 to FParams.Count - 1 do begin
oParam := FParams[i];
if oParam.ParamType in [ptUnknown, ptInput, ptInputOutput] then begin
if sInPar <> '' then
sInPar := sInPar + ', ';
sInPar := sInPar + ':' + oParam.SQLName;
end;
if oParam.ParamType in [ptOutput, ptInputOutput] then
lHasOutput := True
else if oParam.ParamType = ptResult then
lHasResult := True;
end;
if FCommandKind = skStoredProc then
if (ASPUsage = skStoredProcWithCrs) and lHasOutput then
FCommandKind := skStoredProcWithCrs
else
FCommandKind := skStoredProcNoCrs;
rName.FCatalog := ACatalog;
rName.FSchema := ASchema;
rName.FBaseObject := APackage;
rName.FObject := AProc;
sProc := FConnMeta.EncodeObjName(rName, FCommand, [eoQuote, eoNormalize]);
if lHasResult then
Result := 'SELECT ' + sProc + '(' + sInPar + ') FROM ' + GetSingleRowTable
else begin
Result := 'EXECUTE PROCEDURE ' + sProc + '(' + sInPar + ')';
if FCommandKind = skStoredProcWithCrs then
Result := 'SELECT A.* FROM (' + Result + ') A';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String;
var
lWasWhere: Boolean;
sKinds: String;
function AddParam(const AValue, AParam: String; ANull: Boolean = True): String;
var
oParam: TFDParam;
begin
if AValue <> '' then begin
Result := ':' + AParam;
oParam := GetParams.Add;
oParam.Name := AParam;
oParam.DataType := ftString;
oParam.Size := ADS_MAX_OBJECT_NAME;
end
else if ANull then
Result := 'NULL'
else
Result := '''''';
end;
procedure AddWhere(const ACond: String; const AParam: String = '');
var
oParam: TFDParam;
begin
if lWasWhere then
Result := Result + ' AND ' + ACond
else begin
Result := Result + ' WHERE ' + ACond;
lWasWhere := True;
end;
if AParam <> '' then begin
oParam := GetParams.Add;
oParam.Name := AParam;
oParam.DataType := ftString;
oParam.Size := ADS_MAX_OBJECT_NAME;
end;
end;
function EncodeDataType(const ATypeField, ALengthField, AScaleField: String): String;
function DT2Str(AType: TFDDataType): String;
begin
Result := IntToStr(Integer(AType));
end;
begin
Result :=
'CASE' +
' WHEN ' + ATypeField + ' = ''SHORT'' OR ' + ATypeField + ' = ''SHORTINT'' THEN ' + DT2Str(dtInt16) +
' WHEN ' + ATypeField + ' = ''INTEGER'' OR ' + ATypeField + ' = ''Integer'' THEN ' + DT2Str(dtInt32) +
' WHEN ' + ATypeField + ' = ''LONG'' THEN ' + DT2Str(dtInt64) +
' WHEN ' + ATypeField + ' = ''AUTOINC'' THEN ' + DT2Str(dtInt32) +
' WHEN ' + ATypeField + ' = ''ROWVERSION'' THEN ' + DT2Str(dtInt64) +
' WHEN ' + ATypeField + ' = ''DOUBLE'' THEN ' + DT2Str(dtDouble) +
' WHEN ' + ATypeField + ' = ''CURDOUBLE'' THEN ' + DT2Str(dtCurrency) +
' WHEN ' + ATypeField + ' = ''MONEY'' OR ' + ATypeField + ' = ''Money'' THEN ' + DT2Str(dtCurrency) +
' WHEN ' + ATypeField + ' = ''NUMERIC'' OR ' + ATypeField + ' = ''Numeric'' THEN ' +
'CASE' +
' WHEN (' + ALengthField + ' - 2 > 18) OR (' + AScaleField + ' > 4) THEN ' + DT2Str(dtBCD) +
' ELSE ' + DT2Str(dtFmtBCD) +
' END' +
' WHEN ' + ATypeField + ' = ''CHAR'' OR ' + ATypeField + ' = ''CHARACTER'' THEN ' + DT2Str(dtAnsiString) +
' WHEN ' + ATypeField + ' = ''CICHAR'' OR ' + ATypeField + ' = ''CICHARACTER'' THEN ' + DT2Str(dtAnsiString) +
' WHEN ' + ATypeField + ' = ''VARCHAR'' OR ' + ATypeField + ' = ''VARCHARFOX'' THEN ' + DT2Str(dtAnsiString) +
' WHEN ' + ATypeField + ' = ''NCHAR'' THEN ' + DT2Str(dtWideString) +
' WHEN ' + ATypeField + ' = ''NVARCHAR'' THEN ' + DT2Str(dtWideString) +
' WHEN ' + ATypeField + ' = ''MEMO'' OR ' + ATypeField + ' = ''Memo'' THEN ' + DT2Str(dtMemo) +
' WHEN ' + ATypeField + ' = ''NMEMO'' THEN ' + DT2Str(dtWideMemo) +
' WHEN ' + ATypeField + ' = ''RAW'' THEN ' + DT2Str(dtByteString) +
' WHEN ' + ATypeField + ' = ''VARBINARY'' OR ' + ATypeField + ' = ''VARBINARYFOX'' THEN ' + DT2Str(dtByteString) +
' WHEN ' + ATypeField + ' = ''BINARY'' OR ' + ATypeField + ' = ''BLOB'' THEN ' + DT2Str(dtBlob) +
' WHEN ' + ATypeField + ' = ''IMAGE'' THEN ' + DT2Str(dtBlob) +
' WHEN ' + ATypeField + ' = ''DATE'' THEN ' + DT2Str(dtDate) +
' WHEN ' + ATypeField + ' = ''SHORTDATE'' THEN ' + DT2Str(dtDate) +
' WHEN ' + ATypeField + ' = ''TIME'' THEN ' + DT2Str(dtTime) +
' WHEN ' + ATypeField + ' = ''TIMESTAMP'' THEN ' + DT2Str(dtDateTimeStamp) +
' WHEN ' + ATypeField + ' = ''MODTIME'' THEN ' + DT2Str(dtDateTimeStamp) +
' WHEN ' + ATypeField + ' = ''LOGICAL'' THEN ' + DT2Str(dtBoolean) +
' WHEN ' + ATypeField + ' = ''GUID'' THEN ' + DT2Str(dtGUID) +
' ELSE ' + DT2Str(dtUnknown) +
' END';
end;
function EncodeAttrs(const ATypeField, ANullFieldName, ADefFieldName: String): String;
function Attrs2Str(AAttrs: TFDDataAttributes): String;
begin
if AKind <> mkTableFields then
Exclude(AAttrs, caBase);
Result := IntToStr(PWord(@AAttrs)^);
end;
begin
Result :=
'(CASE' +
' WHEN ' + ATypeField + ' = ''AUTOINC'' THEN ' + Attrs2Str([caBase, caSearchable, caAutoInc]) +
' WHEN ' + ATypeField + ' = ''ROWVERSION'' THEN ' + Attrs2Str([caBase, caSearchable, caRowVersion, caReadOnly]) +
' WHEN ' + ATypeField + ' = ''CHAR'' OR ' + ATypeField + ' = ''CHARACTER'' THEN ' + Attrs2Str([caBase, caSearchable, caFixedLen]) +
' WHEN ' + ATypeField + ' = ''CICHAR'' OR ' + ATypeField + ' = ''CICHARACTER'' THEN ' + Attrs2Str([caBase, caSearchable, caFixedLen]) +
' WHEN ' + ATypeField + ' = ''NCHAR'' THEN ' + Attrs2Str([caBase, caSearchable, caFixedLen]) +
' WHEN ' + ATypeField + ' = ''MEMO'' OR ' + ATypeField + ' = ''Memo'' THEN ' + Attrs2Str([caBase, caBlobData]) +
' WHEN ' + ATypeField + ' = ''NMEMO'' THEN ' + Attrs2Str([caBase, caBlobData]) +
' WHEN ' + ATypeField + ' = ''RAW'' THEN ' + Attrs2Str([caBase, caSearchable, caFixedLen]) +
' WHEN ' + ATypeField + ' = ''BINARY'' OR ' + ATypeField + ' = ''BLOB'' THEN ' + Attrs2Str([caBase, caBlobData]) +
' WHEN ' + ATypeField + ' = ''IMAGE'' THEN ' + Attrs2Str([caBase, caBlobData]) +
' ELSE ' + Attrs2Str([caBase, caSearchable]) +
' END';
if ADefFieldName <> '' then
Result := Result +
' + CASE' +
' WHEN (' + ADefFieldName + ' IS NOT NULL) AND (TRIM(' + ADefFieldName + ') <> '''') AND ' +
'(TRIM(' + ADefFieldName + ') <> ''NULL'') THEN ' + Attrs2Str([caDefault]) +
' ELSE 0' +
' END';
if ANullFieldName <> '' then
Result := Result +
' + CASE' +
' WHEN (' + ANullFieldName + ' IS NOT NULL) AND (' + ANullFieldName + ' = 1) THEN ' + Attrs2Str([caAllowNull]) +
' ELSE 0' +
' END'
else
Result := Result +
' + ' + Attrs2Str([caAllowNull]);
Result := Result + ')';
end;
function EncodePrec(const ATypeField, APrecField: String): String;
begin
Result :=
'CASE' +
' WHEN ' + ATypeField + ' = ''CURDOUBLE'' THEN 15' +
' WHEN ' + ATypeField + ' = ''MONEY'' OR ' + ATypeField + ' = ''Money'' THEN 19' +
' WHEN ' + ATypeField + ' = ''NUMERIC'' OR ' + ATypeField + ' = ''Numeric'' THEN ' + APrecField +
' ELSE 0' +
' END';
end;
function EncodeScale(const ATypeField, AScaleField: String): String;
begin
Result :=
'CASE' +
' WHEN ' + ATypeField + ' = ''CURDOUBLE'' THEN 4' +
' WHEN ' + ATypeField + ' = ''MONEY'' OR ' + ATypeField + ' = ''Money'' THEN 4' +
' WHEN ' + ATypeField + ' = ''NUMERIC'' OR ' + ATypeField + ' = ''Numeric'' THEN ' + AScaleField +
' ELSE 0' +
' END';
end;
function EncodeLength(const ATypeField, ALengthField: String): String;
begin
Result :=
'CASE' +
' WHEN ' + ATypeField + ' = ''CHAR'' OR ' + ATypeField + ' = ''CHARACTER'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''CICHAR'' OR ' + ATypeField + ' = ''CICHARACTER'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''VARCHAR'' OR ' + ATypeField + ' = ''VARCHARFOX'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''NCHAR'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''NVARCHAR'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''RAW'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''VARBINARY'' OR ' + ATypeField + ' = ''VARBINARYFOX'' THEN ' + ALengthField +
' ELSE 0' +
' END';
end;
function EncodeRule(const ARuleField: String): String;
begin
Result :=
'CASE' +
' WHEN ' + ARuleField + ' = 0 THEN ' + IntToStr(Integer(ckCascade)) +
' WHEN ' + ARuleField + ' = 2 THEN ' + IntToStr(Integer(ckSetNull)) +
' WHEN ' + ARuleField + ' = 3 THEN ' + IntToStr(Integer(ckRestrict)) +
' WHEN ' + ARuleField + ' = 4 THEN ' + IntToStr(Integer(ckSetDefault)) +
' ELSE ' + IntToStr(Integer(ckNone)) +
' END';
end;
begin
lWasWhere := False;
Result := '';
case AKind of
mkCatalogs:
begin
Result := 'EXECUTE PROCEDURE sp_GetCatalogs()';
if FConnMeta.ServerVersion >= caADS10 then
Result := 'SELECT ROWNUM() AS RECNO, A.TABLE_CAT AS CATALOG_NAME ' +
'FROM (' + Result + ') A';
end;
mkSchemas:
;
mkTables:
begin
if FConnMeta.ServerVersion >= caADS10 then
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'CASE' +
' WHEN A.TABLE_TYPE = ''TABLE'' THEN ' + IntToStr(Integer(tkTable)) +
' WHEN A.TABLE_TYPE = ''VIEW'' THEN ' + IntToStr(Integer(tkView)) +
' WHEN A.TABLE_TYPE = ''SYSTEM TABLE'' THEN ' + IntToStr(Integer(tkTable)) +
' WHEN A.TABLE_TYPE = ''LOCAL TEMPORARY'' THEN ' + IntToStr(Integer(tkLocalTable)) +
' END AS TABLE_TYPE, ' +
'CASE' +
' WHEN A.TABLE_TYPE = ''SYSTEM TABLE'' THEN ' + IntToStr(Integer(osSystem)) +
' ELSE ' + IntToStr(Integer(osMy)) +
' END AS TABLE_SCOPE ' +
'FROM (';
Result := Result +
'EXECUTE PROCEDURE sp_GetTables(' + AddParam(ACatalog, 'CAT', False) +
', NULL, ' + AddParam(AWildcard, 'WIL');
sKinds := '';
if osMy in AObjectScopes then begin
if tkTable in ATableKinds then
sKinds := sKinds + 'TABLE;';
if tkView in ATableKinds then
sKinds := sKinds + 'VIEW;';
if tkLocalTable in ATableKinds then
sKinds := sKinds + 'LOCAL TEMPORARY;';
end;
if osSystem in AObjectScopes then
if tkTable in ATableKinds then
sKinds := sKinds + 'SYSTEM TABLE;';
if sKinds = '' then
sKinds := 'NONE;';
Result := Result + ', ''' + Copy(sKinds, 1, Length(sKinds) - 1) + ''')';
if FConnMeta.ServerVersion >= caADS10 then
Result := Result + ') A' +
' ORDER BY 4';
end;
mkTableFields:
begin
if FConnMeta.ServerVersion >= caADS10 then
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.COLUMN_NAME, ' +
'A.ORDINAL_POSITION AS COLUMN_POSITION, ' +
EncodeDataType('A.TYPE_NAME', 'A.COLUMN_SIZE', 'A.DECIMAL_DIGITS') + ' AS COLUMN_DATATYPE, ' +
'A.TYPE_NAME AS COLUMN_TYPENAME, ' +
EncodeAttrs('A.TYPE_NAME', 'A.NULLABLE', 'A.COLUMN_DEF') + ' AS COLUMN_ATTRIBUTES, ' +
EncodePrec('A.TYPE_NAME', 'A.COLUMN_SIZE') + ' AS COLUMN_PRECISION, ' +
EncodeScale('A.TYPE_NAME', 'A.DECIMAL_DIGITS') + ' AS COLUMN_SCALE, ' +
EncodeLength('A.TYPE_NAME', 'A.COLUMN_SIZE') + ' AS COLUMN_LENGTH ' +
'FROM (';
Result := Result +
'EXECUTE PROCEDURE sp_GetColumns(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ', ' + AddParam(AWildcard, 'WIL') +
')';
if FConnMeta.ServerVersion >= caADS10 then
Result := Result + ') A' +
' ORDER BY 6';
end;
mkIndexes:
if FConnMeta.ServerVersion >= caADS10 then begin
Result := 'SELECT DISTINCT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.INDEX_NAME, ' +
'B.PK_NAME AS CONSTRAINT_NAME, ' +
'CASE' +
' WHEN B.PK_NAME IS NOT NULL THEN 2' +
' WHEN NON_UNIQUE THEN 0' +
' ELSE 1 ' +
'END AS INDEX_TYPE ' +
'FROM (EXECUTE PROCEDURE sp_GetIndexInfo(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ', False, True)) A ' +
' LEFT OUTER JOIN' +
' (EXECUTE PROCEDURE sp_GetPrimaryKeys(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ')) B' +
' ON A.INDEX_NAME = B.PK_NAME ' +
'WHERE A.TYPE <> 0';
if AWildcard <> '' then
Result := Result + ' AND A.INDEX_NAME LIKE ' + AddParam(AWildcard, 'WIL');
Result := Result + ' ORDER BY 7 DESC, 5';
end
else
Result := 'EXECUTE PROCEDURE sp_GetIndexInfo(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ', False, True)';
mkIndexFields:
begin
if FConnMeta.ServerVersion >= caADS10 then
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.INDEX_NAME, ' +
'A.COLUMN_NAME, ' +
'A.ORDINAL_POSITION AS COLUMN_POSITION, ' +
'A.ASC_OR_DESC AS SORT_ORDER, ' +
'A.FILTER_CONDITION AS FILTER ' +
'FROM (';
Result := Result +
'EXECUTE PROCEDURE sp_GetIndexInfo(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(ABaseObject, 'BAS') + ', False, True)';
if FConnMeta.ServerVersion >= caADS10 then begin
Result := Result + ') A';
AddWhere('A.INDEX_NAME = :OBJ', 'OBJ');
if AWildcard <> '' then
AddWhere('A.COLUMN_NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 7';
end;
end;
mkPrimaryKey:
begin
if FConnMeta.ServerVersion >= caADS10 then
Result := 'SELECT DISTINCT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.PK_NAME AS INDEX_NAME, ' +
'A.PK_NAME AS CONSTRAINT_NAME, ' +
IntToStr(Integer(ikPrimaryKey)) + ' AS INDEX_TYPE ' +
'FROM (';
Result := Result +
'EXECUTE PROCEDURE sp_GetPrimaryKeys(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ')';
if FConnMeta.ServerVersion >= caADS10 then begin
Result := Result + ') A';
if AWildcard <> '' then
AddWhere('A.PK_NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 5';
end;
end;
mkPrimaryKeyFields:
begin
if FConnMeta.ServerVersion >= caADS10 then
Result := 'SELECT DISTINCT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.PK_NAME AS INDEX_NAME, ' +
'A.COLUMN_NAME AS COLUMN_NAME, ' +
'A.KEY_SEQ + 1 AS COLUMN_POSITION, ' +
'''A'' AS SORT_ORDER, ' +
'CAST(NULL AS SQL_VARCHAR(50)) AS FILTER ' +
'FROM (';
Result := Result +
'EXECUTE PROCEDURE sp_GetPrimaryKeys(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(ABaseObject, 'BAS') + ')';
if FConnMeta.ServerVersion >= caADS10 then begin
Result := Result + ') A';
if AWildcard <> '' then
AddWhere('A.COLUMN_NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 7';
end;
end;
mkForeignKeys:
begin
if FConnMeta.ServerVersion >= caADS10 then
Result := 'SELECT DISTINCT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.FKTABLE_CAT AS CATALOG_NAME, ' +
'A.FKTABLE_SCHEM AS SCHEMA_NAME, ' +
'A.FKTABLE_NAME, ' +
'A.FK_NAME AS FKEY_NAME, ' +
'A.PKTABLE_CAT AS PKEY_CATALOG_NAME, ' +
'A.PKTABLE_SCHEM AS PKEY_SCHEMA_NAME, ' +
'A.PKTABLE_NAME AS PKEY_TABLE_NAME, ' +
EncodeRule('A.DELETE_RULE') + ' AS DELETE_RULE, ' +
EncodeRule('A.UPDATE_RULE') + ' AS UPDATE_RULE ' +
'FROM (';
Result := Result +
'EXECUTE PROCEDURE sp_GetImportedKeys(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ')';
if FConnMeta.ServerVersion >= caADS10 then begin
Result := Result + ') A';
if AWildcard <> '' then
AddWhere('A.FK_NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 5';
end;
end;
mkForeignKeyFields:
begin
if FConnMeta.ServerVersion >= caADS10 then
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.FKTABLE_CAT AS CATALOG_NAME, ' +
'A.FKTABLE_SCHEM AS SCHEMA_NAME, ' +
'A.FKTABLE_NAME, ' +
'A.FK_NAME AS FKEY_NAME, ' +
'A.FKCOLUMN_NAME AS COLUMN_NAME, ' +
'A.PKCOLUMN_NAME AS PKEY_COLUMN_NAME, ' +
'A.KEY_SEQ + 1 AS COLUMN_POSITION ' +
'FROM (';
Result := Result +
'EXECUTE PROCEDURE sp_GetImportedKeys(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(ABaseObject, 'BAS') + ')';
if FConnMeta.ServerVersion >= caADS10 then begin
Result := Result + ') A';
AddWhere('A.FK_NAME = :OBJ', 'OBJ');
if AWildcard <> '' then
AddWhere('A.FKCOLUMN_NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 8';
end;
end;
mkPackages:
begin
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'CAST(NULL AS SQL_VARCHAR(200)) AS CATALOG_NAME, ' +
'CAST(NULL AS SQL_VARCHAR(200)) AS SCHEMA_NAME, ' +
'A.NAME AS PACKAGE_NAME, ' +
IntToStr(Integer(osMy)) + ' AS PACKAGE_SCOPE ' +
'FROM system.packages A ';
if not (osMy in AObjectScopes) then
AddWhere('0 = 1');
if AWildcard <> '' then
AddWhere('A.NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 4';
end;
mkProcs:
if FConnMeta.ServerVersion >= caADS10 then begin
if ABaseObject = '' then begin
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.PROCEDURE_CAT AS CATALOG_NAME, ' +
'A.PROCEDURE_SCHEM AS SCHEMA_NAME, ' +
'CAST(NULL AS SQL_VARCHAR(200)) AS PACK_NAME, ' +
'A.PROCEDURE_NAME AS PROC_NAME, ' +
'CAST(NULL AS SQL_INTEGER) AS OVERLOAD, ' +
IntToStr(Integer(pkProcedure)) + ' AS PROC_TYPE, ' +
IntToStr(Integer(osMy)) + ' AS PROC_SCOPE, ' +
'SUM(CASE WHEN B.COLUMN_TYPE IS NOT NULL AND B.COLUMN_TYPE = 1 THEN 1 ELSE 0 END) AS IN_PARAMS, ' +
'SUM(CASE WHEN B.COLUMN_TYPE IS NOT NULL AND B.COLUMN_TYPE = 3 THEN 1 ELSE 0 END) AS OUT_PARAMS ' +
'FROM (EXECUTE PROCEDURE sp_GetProcedures(' + AddParam(ACatalog, 'CAT') +
', NULL, NULL)) A ' +
'LEFT OUTER JOIN ' +
'(EXECUTE PROCEDURE sp_GetProcedureColumns(' + AddParam(ACatalog, 'CAT') +
', NULL, NULL, NULL)) B ' +
'ON TRIM(A.PROCEDURE_CAT) = TRIM(B.PROCEDURE_CAT) AND ' +
' TRIM(A.PROCEDURE_SCHEM) = TRIM(B.PROCEDURE_SCHEM) AND ' +
' TRIM(A.PROCEDURE_NAME) = TRIM(B.PROCEDURE_NAME) ';
if not (osMy in AObjectScopes) then
AddWhere('0 = 1');
if AWildcard <> '' then
AddWhere('A.PROCEDURE_NAME LIKE :WIL', 'WIL');
Result := Result +
' GROUP BY A.PROCEDURE_CAT, A.PROCEDURE_SCHEM, A.PROCEDURE_NAME ' +
'UNION ALL ';
end;
Result := Result +
'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'CAST(DATABASE() AS SQL_VARCHAR(200)) AS CATALOG_NAME, ' +
'CAST(NULL AS SQL_VARCHAR(200)) AS SCHEMA_NAME, ' +
'C.Package AS PACK_NAME, ' +
'C.Name AS PROC_NAME, ' +
'CAST(NULL AS SQL_INTEGER) AS OVERLOAD, ' +
IntToStr(Integer(pkFunction)) + ' AS PROC_TYPE, ' +
IntToStr(Integer(osMy)) + ' AS PROC_SCOPE, ' +
'-1 AS IN_PARAMS, ' +
'0 AS OUT_PARAMS ' +
'FROM system.functions C';
if ABaseObject = '' then
AddWhere('C.Package IS NULL')
else
AddWhere('C.Package = :BAS', 'BAS');
if not (osMy in AObjectScopes) then
AddWhere('0 = 1');
if AWildcard <> '' then
AddWhere('C.Name LIKE :WIL', 'WIL');
Result := Result +
' ORDER BY 4, 5';
end
else
if ABaseObject = '' then
Result := 'EXECUTE PROCEDURE sp_GetProcedures(' + AddParam(ACatalog, 'CAT') +
', NULL, NULL)'
else
Result := '';
mkProcArgs:
if ABaseObject <> '' then
Result := ''
else begin
if FConnMeta.ServerVersion >= caADS10 then
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.PROCEDURE_CAT AS CATALOG_NAME, ' +
'A.PROCEDURE_SCHEM AS SCHEMA_NAME, ' +
'CAST(NULL AS SQL_VARCHAR(200)) AS PACK_NAME, ' +
'A.PROCEDURE_NAME AS PROC_NAME, ' +
'CAST(NULL AS SQL_INTEGER) AS OVERLOAD, ' +
'A.COLUMN_NAME AS PARAM_NAME, ' +
'ROWNUM() AS PARAM_POSITION, ' +
'CASE WHEN A.COLUMN_TYPE = 1 THEN ' + IntToStr(Integer(ptInput)) +
'WHEN A.COLUMN_TYPE = 3 THEN ' + IntToStr(Integer(ptOutput)) + ' ELSE 0 END AS PARAM_TYPE, ' +
EncodeDataType('A.TYPE_NAME', 'A.LENGTH', 'A.SCALE') + ' AS PARAM_DATATYPE, ' +
'A.TYPE_NAME AS PARAM_TYPENAME, ' +
EncodeAttrs('A.TYPE_NAME', '', '') + ' AS PARAM_ATTRIBUTES, ' +
EncodePrec('A.TYPE_NAME', 'A.PRECISION') + ' AS PARAM_PRECISION, ' +
EncodeScale('A.TYPE_NAME', 'A.SCALE') + ' AS PARAM_SCALE, ' +
EncodeLength('A.TYPE_NAME', 'A.LENGTH') + ' AS PARAM_LENGTH ' +
'FROM (';
Result := Result +
'EXECUTE PROCEDURE sp_GetProcedureColumns(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ', NULL)';
if FConnMeta.ServerVersion >= caADS10 then begin
Result := Result + ') A';
if AWildcard <> '' then
AddWhere('A.COLUMN_NAME LIKE :WIL', 'WIL');
end;
end;
mkGenerators,
mkResultSetFields,
mkTableTypeFields:
;
else
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetLimitSelect(const ASQL: String;
ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String;
var
s: String;
iAfter: Integer;
begin
if (ASkip + ARows <> MAXINT) and
FDStartsWithKW(ASQL, 'SELECT', iAfter) and
not FDStartsWithKW(ASQL, 'SELECT TOP', iAfter) then begin
Result := 'SELECT TOP ';
s := UpperCase(ASQL);
if FConnMeta.ServerVersion < caADS10 then begin
Inc(ARows, ASkip);
if GetSQLOrderByPos > 0 then
if FDHasKW(s, 'UNION') or FDHasKW(s, 'MINUS') or FDHasKW(s, 'INTERSECT') or
FDHasKW(s, 'EXCEPT') then
Result := Result + IntToStr(ARows) +
' * FROM (' + BRK + Copy(ASQL, 1, GetSQLOrderByPos - 1) + BRK + ') A' + BRK +
Copy(ASQL, GetSQLOrderByPos, MAXINT)
else if FDStartsWithKW(ASQL, 'SELECT DISTINCT', iAfter) then
Result := 'SELECT TOP ' + IntToStr(ARows) +
' DISTINCT ' + Copy(ASQL, iAfter, MAXINT)
else
Result := Result + IntToStr(ARows) +
Copy(ASQL, iAfter, MAXINT)
else
if FDHasKW(s, 'UNION') or FDHasKW(s, 'MINUS') or FDHasKW(s, 'INTERSECT') or
FDHasKW(s, 'EXCEPT') then
Result := Result + IntToStr(ARows) +
' * FROM (' + BRK + ASQL + BRK + ') A'
else if FDStartsWithKW(ASQL, 'SELECT DISTINCT', iAfter) then
Result := 'SELECT TOP ' + IntToStr(ARows) +
' DISTINCT ' + Copy(ASQL, iAfter, MAXINT)
else
Result := Result + IntToStr(ARows) +
Copy(ASQL, iAfter, MAXINT);
end
else begin
if GetSQLOrderByPos > 0 then
if FDHasKW(s, 'UNION') or FDHasKW(s, 'MINUS') or FDHasKW(s, 'INTERSECT') or
FDHasKW(s, 'EXCEPT') then
Result := Result + IntToStr(ARows) + ' START AT ' + IntToStr(ASkip + 1) +
' * FROM (' + BRK + Copy(ASQL, 1, GetSQLOrderByPos - 1) + BRK + ') A' + BRK +
Copy(ASQL, GetSQLOrderByPos, MAXINT)
else if FDStartsWithKW(ASQL, 'SELECT DISTINCT', iAfter) then
Result := 'SELECT TOP ' + IntToStr(ARows) + ' START AT ' +
IntToStr(ASkip + 1) + ' DISTINCT ' + Copy(ASQL, iAfter, MAXINT)
else
Result := Result + IntToStr(ARows) + ' START AT ' + IntToStr(ASkip + 1) +
Copy(ASQL, iAfter, MAXINT)
else
if FDHasKW(s, 'UNION') or FDHasKW(s, 'MINUS') or FDHasKW(s, 'INTERSECT') or
FDHasKW(s, 'EXCEPT') then
Result := Result + IntToStr(ARows) + ' START AT ' + IntToStr(ASkip + 1) +
' * FROM (' + BRK + ASQL + BRK + ') A'
else if FDStartsWithKW(ASQL, 'SELECT DISTINCT', iAfter) then
Result := 'SELECT TOP ' + IntToStr(ARows) + ' START AT ' +
IntToStr(ASkip + 1) + ' DISTINCT ' + Copy(ASQL, iAfter, MAXINT)
else
Result := Result + IntToStr(ARows) + ' START AT ' + IntToStr(ASkip + 1) +
Copy(ASQL, iAfter, MAXINT);
end;
end
else begin
Result := ASQL;
AOptions := [];
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String;
var
eAttrs: TFDDataAttributes;
begin
eAttrs := AColumn.ActualAttributes;
if [caAutoInc, caRowVersion] * eAttrs <> [] then begin
if caAutoInc in AColumn.ActualAttributes then
Result := 'AUTOINC'
else if caRowVersion in AColumn.ActualAttributes then
Result := 'ROWVERSION';
Exit;
end;
case AColumn.DataType of
dtBoolean:
Result := 'LOGICAL';
dtSByte,
dtInt16,
dtByte:
Result := 'SHORTINT';
dtInt32,
dtUInt16:
Result := 'INTEGER';
dtInt64,
dtUInt32,
dtUInt64:
Result := 'LONG';
dtSingle,
dtDouble,
dtExtended:
Result := 'DOUBLE';
dtCurrency:
Result := 'MONEY';
dtBCD,
dtFmtBCD:
Result := 'NUMERIC' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1,
FOptions.FormatOptions.MaxBcdPrecision, 0);
dtTime:
Result := 'TIME';
dtDate:
Result := 'DATE';
dtDateTime,
dtDateTimeStamp:
Result := 'TIMESTAMP';
dtAnsiString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'CHAR'
else
Result := 'VARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtWideString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'NCHAR'
else
Result := 'NVARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtByteString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'RAW'
else
Result := 'VARBINARY';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtBlob,
dtHBlob,
dtHBFile:
Result := 'BINARY';
dtMemo,
dtHMemo:
Result := 'MEMO';
dtWideMemo,
dtXML,
dtWideHMemo:
Result := 'NMEMO';
dtGUID:
if FConnMeta.ServerVersion >= caADS12 then
Result := 'GUID'
else
Result := 'CHAR(38)';
dtUnknown,
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef,
dtParentRowRef,
dtObject:
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysADSCommandGenerator.GetMerge(AAction: TFDPhysMergeAction): String;
function GetMatched: String;
begin
Result := 'WHEN MATCHED THEN UPDATE SET ' + GetUpdate();
end;
function GetNotMatched: String;
begin
Result := 'WHEN NOT MATCHED THEN INSERT ' + GetInsert('');
end;
begin
Result := 'MERGE INTO ' + GetFrom + BRK + ' ON ' + GetWhere(False, True, False) + BRK;
case AAction of
maInsertUpdate: Result := Result + GetNotMatched() + BRK + GetMatched();
maInsertIgnore: Result := Result + GetNotMatched();
end;
end;
{-------------------------------------------------------------------------------}
initialization
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.Advantage, S_FD_ADS_RDBMS);
end.
|
unit uDemo;
interface
uses
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
//GLS
GLUtils,GLSCUDAContext, GLSCUDA, GLSCUDACompiler, GLFilePGM,
GLSCUDAUtility, GLGraphics, GLTextureFormat;
type
TForm1 = class(TForm)
GLSCUDACompiler1: TGLSCUDACompiler;
GLSCUDA1: TGLSCUDA;
GLSCUDADevice1: TGLSCUDADevice;
MainModule: TCUDAModule;
Button1: TButton;
Memo1: TMemo;
TurnPicture: TCUDAFunction;
Image: TCUDATexture;
TextureArray: TCUDAMemData;
ResultData: TCUDAMemData;
procedure TurnPictureParameterSetup(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
pgm: TGLPGMImage;
end;
var
Form1: TForm1;
Angle : Single = 0.5; // angle to rotate image by (in radians)
implementation
{$R *.dfm}
const
TestFileName = 'lena_bw.pgm';
OutFileName = 'lena_bw_out.pgm';
procedure TForm1.Button1Click(Sender: TObject);
var
timer: Cardinal;
bmp32: TGLBitmap32;
begin
if not InitCUTIL then
begin
Memo1.Lines.Add('Can''t load cutil32.dll');
exit;
end;
pgm.LoadFromFile( TestFileName );
bmp32 := TGLBitmap32.Create;
bmp32.Assign( pgm );
Memo1.Lines.Add(Format('File %s - loaded', [TestFileName]));
TextureArray.CopyFrom( bmp32 );
Memo1.Lines.Add('Copied from host to device array');
TurnPicture.Launch;
Memo1.Lines.Add('Warmup launch finished');
cutCreateTimer( timer );
cutStartTimer( timer );
TurnPicture.Launch;
cutStopTimer( timer );
Memo1.Lines.Add('Launch finished');
Memo1.Lines.Add(Format('Processing time: %f (ms)', [cutGetTimerValue( timer )] ));
Memo1.Lines.Add(Format('%.2f Mpixels/sec',
[(pgm.LevelWidth[0]*pgm.LevelHeight[0] / (cutGetTimerValue( timer) / 1000.0)) / 1e6]));
cutDeleteTimer( timer );
ResultData.CopyTo( bmp32 );
Memo1.Lines.Add('Copied from device global memory to host');
pgm.Assign( bmp32 );
pgm.SaveToFile( OutFileName );
Memo1.Lines.Add(Format('Saving result to %s - done', [OutFileName]));
bmp32.Free;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
pgm := TGLPGMImage.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
pgm.Destroy;
end;
procedure TForm1.TurnPictureParameterSetup(Sender: TObject);
begin
with TurnPicture do
begin
SetParam(ResultData);
SetParam(pgm.LevelWidth[0]);
SetParam(pgm.LevelHeight[0]);
SetParam(Angle);
SetParam(Image);
end;
end;
end.
|
{ Reads/writes GPX files
(C) 2019 Werner Pamler (user wp at Lazarus forum https://forum.lazarus.freepascal.org)
License: modified LGPL with linking exception (like RTL, FCL and LCL)
See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution,
for details about the license.
See also: https://wiki.lazarus.freepascal.org/FPC_modified_LGPL
}
unit mvGPX;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, laz2_DOM, laz2_XMLRead, DateUtils,
mvTypes, mvGpsObj;
type
TGpxReader = class
private
ID: Integer;
FMinLat, FMinLon, FMaxLat, FMaxLon: Double;
protected
procedure ReadExtensions(ANode: TDOMNode; ATrack: TGpsTrack);
function ReadPoint(ANode: TDOMNode): TGpsPoint;
procedure ReadRoute(ANode: TDOMNode; AList: TGpsObjectlist);
procedure ReadTrack(ANode: TDOMNode; AList: TGpsObjectList);
procedure ReadTracks(ANode: TDOMNode; AList: TGpsObjectList);
procedure ReadTrackSegment(ANode: TDOMNode; ATrack: TGpsTrack);
procedure ReadWayPoints(ANode: TDOMNode; AList: TGpsObjectList);
public
procedure LoadFromFile(AFileName: String; AList: TGpsObjectList; out ABounds: TRealArea);
procedure LoadFromStream(AStream: TStream; AList: TGpsObjectList; out ABounds: TRealArea);
end;
implementation
uses
Math,
mvExtraData;
var
PointSettings: TFormatSettings;
function ExtractISODateTime(AText: String): TDateTime;
type
TISODateRec = packed record
Y: array[0..3] of ansichar;
SepYM: ansichar;
M: array[0..1] of ansichar;
SepMD: ansichar;
D: array[0..1] of ansichar;
end;
PISODateRec = ^TISODateRec;
TISOTimeRec = packed record
H: array[0..1] of ansichar;
SepHM: ansichar;
M: array[0..1] of ansichar;
SepMS: ansiChar;
S: array[0..1] of ansichar;
DecSep: ansichar;
MS: array[0..2] of ansichar;
end;
PISOTimeRec = ^TISOTimeRec;
const
NUMBER: array['0'..'9'] of Integer = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
var
yr,mon,dy, hr,mn,sec,s1000: Integer;
begin
if Pos('T', AText) = 11 then begin
with PISODateRec(PChar(@AText[1]))^ do begin
yr := 1000*NUMBER[Y[0]] + 100*NUMBER[Y[1]] + 10*NUMBER[Y[2]] + NUMBER[Y[3]];
mon := 10*NUMBER[M[0]] + NUMBER[M[1]];
dy := 10*NUMBER[D[0]] + NUMBER[D[1]];
end;
with PISOTimeRec(PChar(@AText[12]))^ do begin
hr := 10*NUMBER[H[0]] + NUMBER[H[1]];
mn := 10*NUMBER[M[0]] + NUMBER[M[1]];
sec := 10*NUMBER[S[0]] + NUMBER[S[1]];
s1000 := 100*NUMBER[MS[0]] + 10*NUMBER[MS[1]] + NUMBER[MS[2]];
end;
Result := EncodeDate(yr, mon, dy) + EncodeTime(hr, mn, sec, s1000);
end else
if not TryStrToDateTime(AText, Result) then
Result := NO_DATE;
end;
function GetAttrValue(ANode: TDOMNode; AAttrName: string) : string;
var
i: LongWord;
Found: Boolean;
begin
Result := '';
if (ANode = nil) or (ANode.Attributes = nil) then
exit;
Found := false;
i := 0;
while not Found and (i < ANode.Attributes.Length) do begin
if ANode.Attributes.Item[i].NodeName = AAttrName then begin
Found := true;
Result := ANode.Attributes.Item[i].NodeValue;
end;
inc(i);
end;
end;
function GetNodeValue(ANode: TDOMNode): String;
var
child: TDOMNode;
begin
Result := '';
child := ANode.FirstChild;
if Assigned(child) and (child.NodeName = '#text') then
Result := child.NodeValue;
end;
function TryStrToGpxColor(AGpxText: String; out AColor: LongInt): Boolean;
type
PGpxColorRec = ^TGpxColorRec;
TGpxColorRec = record
r: array[0..1] of char;
g: array[0..1] of char;
b: array[0..1] of char;
end;
var
rv, gv, bv: Integer;
ch: Char;
begin
Result := false;
if Length(AGpxText) <> 6 then
exit;
for ch in AGpxText do
if not (ch in ['0'..'9', 'A'..'F', 'a'..'f']) then exit;
with PGpxColorRec(@AGpxText[1])^ do begin
rv := (ord(r[0]) - ord('0')) * 16 + ord(r[1]) - ord('0');
gv := (ord(g[0]) - ord('0')) * 16 + ord(g[1]) - ord('0');
bv := (ord(b[0]) - ord('0')) * 16 + ord(b[1]) - ord('0');
end;
AColor := rv + gv shl 8 + bv shl 16;
Result := true;
end;
{ TGpxReader }
procedure TGpxReader.LoadFromFile(AFileName: String; AList: TGpsObjectList;
out ABounds: TRealArea);
var
stream: TStream;
begin
stream := TFileStream.Create(AFileName, fmOpenRead + fmShareDenyNone);
try
LoadFromStream(stream, AList, ABounds);
finally
stream.Free;
end;
end;
procedure TGpxReader.LoadFromStream(AStream: TStream; AList: TGpsObjectList;
out ABounds: TRealArea);
var
doc: TXMLDocument = nil;
begin
try
ID := random(MaxInt - 1000) + 1000;
FMinLon := 9999; FMinLat := 9999;
FMaxLon := -9999; FMaxLat := -9999;
ReadXMLFile(doc, AStream);
ReadWayPoints(doc.DocumentElement.FindNode('wpt'), AList);
ReadTracks(doc.DocumentElement.FindNode('trk'), AList);
ReadRoute(doc.DocumentElement.FindNode('rte'), AList);
ABounds.TopLeft.Lon := FMinLon;
ABounds.TopLeft.Lat := FMaxLat;
ABounds.BottomRight.Lon := FMaxLon;
ABounds.BottomRight.Lat := FMinLat;
finally
doc.Free;
end;
end;
procedure TGpxReader.ReadExtensions(ANode: TDOMNode; ATrack: TGpsTrack);
var
linenode: TDOMNode;
childNode: TDOMNode;
nodeName: string;
color: LongInt;
w: Double = -1;
colorUsed: Boolean = false;
s: String;
begin
if ANode = nil then
exit;
lineNode := ANode.FirstChild;
while lineNode <> nil do begin
nodeName := lineNode.NodeName;
if nodeName = 'line' then begin
childNode := lineNode.FirstChild;
while childNode <> nil do begin
nodeName := childNode.NodeName;
s := GetNodeValue(childNode);
case nodeName of
'color':
if TryStrToGpxColor(s, color) then colorUsed := true;
'width':
TryStrToFloat(s, w, PointSettings);
end;
childNode := childNode.NextSibling;
end;
end;
lineNode := lineNode.NextSibling;
end;
if (w <> -1) or colorUsed then begin
if ATrack.ExtraData = nil then
ATrack.ExtraData := TTrackExtraData.Create(ID);
if (ATrack.ExtraData is TTrackExtraData) then begin
TTrackExtraData(ATrack.ExtraData).Width := w;
TTrackExtraData(ATrack.ExtraData).Color := color;
end;
end;
end;
function TGpxReader.ReadPoint(ANode: TDOMNode): TGpsPoint;
var
s, slon, slat, sName: String;
lon, lat, ele: Double;
dt: TDateTime;
node: TDOMNode;
nodeName: String;
begin
Result := nil;
if ANode = nil then
exit;
slon := GetAttrValue(ANode, 'lon');
slat := GetAttrValue(ANode, 'lat');
if (slon = '') or (slat = '') then
exit;
if not TryStrToFloat(slon, lon, PointSettings) then
exit;
if not TryStrToFloat(slat, lat, PointSettings) then
exit;
sName := '';
dt := NO_DATE;
ele := NO_ELE;
node := ANode.FirstChild;
while node <> nil do begin
nodeName := node.NodeName;
case nodeName of
'ele' :
begin
s := GetNodeValue(node);
if s <> '' then
TryStrToFloat(s, ele, PointSettings);
end;
'name':
sName := GetNodeValue(node);
'time':
begin
s := GetNodeValue(node);
if s <> '' then
dt := ExtractISODateTime(s);
end;
end;
node := node.NextSibling;
end;
Result := TGpsPoint.Create(lon, lat, ele, dt);
Result.Name := sname;
FMinLon := Min(FMinLon, lon);
FMaxLon := Max(FMaxLon, lon);
FMinLat := Min(FMinLat, lat);
FMaxLat := Max(FMaxLat, lat);
end;
procedure TGpxReader.ReadRoute(ANode: TDOMNode; AList: TGpsObjectlist);
var
trk: TGpsTrack;
nodeName: string;
pt: TGpsPoint;
trkName: String;
begin
if ANode = nil then
exit;
ANode := ANode.FirstChild;
if ANode = nil then
exit;
trk := TGpsTrack.Create;
while ANode <> nil do begin
nodeName := ANode.NodeName;
case nodeName of
'name':
trkName := GetNodeValue(ANode);
'rtept':
begin
pt := ReadPoint(ANode);
if pt <> nil then trk.Points.Add(pt);
end;
end;
ANode := ANode.NextSibling;
end;
trk.Name := trkName;
AList.Add(trk, ID);
end;
procedure TGpxReader.ReadTrack(ANode: TDOMNode; AList: TGpsObjectList);
var
trk: TGpsTrack;
nodeName: string;
pt: TGpsPoint;
trkName: String = '';
begin
if ANode = nil then
exit;
ANode := ANode.FirstChild;
if ANode = nil then
exit;
trk := TGpsTrack.Create;
while ANode <> nil do begin
nodeName := ANode.NodeName;
case nodeName of
'name':
trkName := GetNodeValue(ANode);
'trkseg':
ReadTrackSegment(ANode.FirstChild, trk);
'trkpt':
begin
pt := ReadPoint(ANode);
if pt <> nil then trk.Points.Add(pt);
end;
'extensions':
ReadExtensions(ANode, trk);
end;
ANode := ANode.NextSibling;
end;
trk.Name := trkName;
AList.Add(trk, ID);
end;
procedure TGpxReader.ReadTracks(ANode: TDOMNode; AList: TGpsObjectList);
var
nodeName: String;
begin
while ANode <> nil do begin
nodeName := ANode.NodeName;
if nodeName = 'trk' then
ReadTrack(ANode, AList);
ANode := ANode.NextSibling;
end;
end;
procedure TGpxReader.ReadTrackSegment(ANode: TDOMNode; ATrack: TGpsTrack);
var
gpsPt: TGpsPoint;
nodeName: String;
begin
while ANode <> nil do begin
nodeName := ANode.NodeName;
if nodeName = 'trkpt' then begin
gpsPt := ReadPoint(ANode);
if gpsPt <> nil then
ATrack.Points.Add(gpsPt);
end;
ANode := ANode.NextSibling;
end;
end;
procedure TGpxReader.ReadWayPoints(ANode: TDOMNode; AList: TGpsObjectList);
var
nodeName: String;
gpsPt: TGpsPoint;
begin
while ANode <> nil do begin
nodeName := ANode.NodeName;
if nodeName = 'wpt' then begin
gpsPt := ReadPoint(ANode);
if gpsPt <> nil then
AList.Add(gpsPt, ID);
end;
ANode := ANode.NextSibling;
end;
end;
initialization
PointSettings := DefaultFormatSettings;
PointSettings.DecimalSeparator := '.';
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 65520,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 102 Backtrack Method with many Bounds
}
program
AdditiveChain;
var
N : Integer;
BestL, Min : Integer;
C, BestC : array [1 .. 50] of Word;
I, J : Integer;
function LogCei (X : Real) : Integer;
begin
LogCei := Trunc((Ln(X) / Ln(2)) + 1 - 1E-10);
end;
procedure BT (L : Integer);
var
I, J : Integer;
begin
if C[L - 1] = N then
begin
if L - 1 <= BestL then
begin
BestL := L - 1;
BestC := C;
end;
Exit;
end;
if BestL = Min then Exit;
for I := L - 1 downto 1 do
begin
if Longint(C[L - 1]) shl (BestL - L) < N then Exit;
if C[I] <= C[L - 1] div 2 then
Break;
for J := I downto 1 do
begin
if C[I] + C[J] <= C[L - 1] then Break;
if C[I] + C[J] > N then Continue;
C[L] := C[I] + C[J];
BT(L + 1);
end;
end;
end;
procedure Solve;
begin
BestL := LogCei(N);
Min := BestL;
I := N;
while I <> 0 do
begin
Inc(BestL, I mod 2);
I := I div 2;
end;
C[1] := 1;
C[2] := 2;
C[3] := 3;
if BestL > LogCei(N) + 1 then
BT(4);
C[3] := 4;
BT(4);
end;
begin
Assign(Input, 'input.txt');
Reset(Input);
Assign(Output, 'output.txt');
Rewrite(Output);
while not Eof do
begin
Readln(N);
Solve;
for I := 1 to BestL do
Write(BestC[I], ' ');
Writeln;
Writeln;
end;
Close(Input);
Close(Output);
end.
|
unit ah_math;
{$i ah_def.inc }
(*$define nomath *)
(*$b-*) { I may make use of the shortcut boolean eval }
(*@/// interface *)
interface
{ Angular functions }
function tan(x:extended):extended;
function arctan2(a,b:extended):extended;
function arcsin(x:extended):extended;
function arccos(x:extended):extended;
{ Convert degree and radians }
function deg2rad(x:extended):extended;
function rad2deg(x:extended):extended;
{ Angular functions with degrees }
function sin_d(x:extended):extended;
function cos_d(x:extended):extended;
function tan_d(x:extended):extended;
function arctan2_d(a,b:extended):extended;
function arcsin_d(x:extended):extended;
function arccos_d(x:extended):extended;
function arctan_d(x:extended):extended;
{ Limit degree value into 0..360 range }
function put_in_360(x:extended):extended;
{ Modulo operation which returns the value in the range 1..b }
function adjusted_mod(a,b:integer):integer;
(*@\\\*)
(*@/// implementation *)
implementation
(*$ifndef nomath *)
uses
math;
(*$endif *)
(*@/// function deg2rad(x:extended):extended; *)
function deg2rad(x:extended):extended;
begin
result:=x/180*pi;
end;
(*@\\\*)
(*@/// function rad2deg(x:extended):extended; *)
function rad2deg(x:extended):extended;
begin
result:=x*180/pi;
end;
(*@\\\*)
(*$ifdef nomath *)
{ D1 has no unit math, so here are the needed functions }
(*@/// function tan(x:extended):extended; *)
function tan(x:extended):extended;
begin
result:=sin(x)/cos(x);
end;
(*@\\\*)
(*@/// function arctan2(a,b:extended):extended; *)
function arctan2(a,b:extended):extended;
begin
result:=arctan(a/b);
if b<0 then result:=result+pi;
end;
(*@\\\*)
(*@/// function arcsin(x:extended):extended; *)
function arcsin(x:extended):extended;
begin
result:=arctan(x/sqrt(1-x*x));
end;
(*@\\\*)
(*@/// function arccos(x:extended):extended; *)
function arccos(x:extended):extended;
begin
result:=pi/2-arcsin(x);
end;
(*@\\\*)
(*$else
(*@/// function tan(x:extended):extended; *)
function tan(x:extended):extended;
begin
result:=math.tan(x);
end;
(*@\\\*)
(*@/// function arctan2(a,b:extended):extended; *)
function arctan2(a,b:extended):extended;
begin
result:=math.arctan2(a,b);
end
(*@\\\*)
(*@/// function arcsin(x:extended):extended; *)
function arcsin(x:extended):extended;
begin
result:=math.arcsin(x);
end;
(*@\\\*)
(*@/// function arccos(x:extended):extended; *)
function arccos(x:extended):extended;
begin
result:=math.arccos(x);
end;
(*@\\\*)
(*$endif *)
{ Angular functions with degrees }
(*@/// function sin_d(x:extended):extended; *)
function sin_d(x:extended):extended;
begin
sin_d:=sin(deg2rad(put_in_360(x)));
end;
(*@\\\000000030E*)
(*@/// function cos_d(x:extended):extended; *)
function cos_d(x:extended):extended;
begin
cos_d:=cos(deg2rad(put_in_360(x)));
end;
(*@\\\000000030E*)
(*@/// function tan_d(x:extended):extended; *)
function tan_d(x:extended):extended;
begin
tan_d:=tan(deg2rad(put_in_360(x)));
end;
(*@\\\0000000324*)
(*@/// function arctan2_d(a,b:extended):extended; *)
function arctan2_d(a,b:extended):extended;
begin
result:=rad2deg(arctan2(a,b));
end;
(*@\\\0000000320*)
(*@/// function arcsin_d(x:extended):extended; *)
function arcsin_d(x:extended):extended;
begin
result:=rad2deg(arcsin(x));
end;
(*@\\\000000031D*)
(*@/// function arccos_d(x:extended):extended; *)
function arccos_d(x:extended):extended;
begin
result:=rad2deg(arccos(x));
end;
(*@\\\000000031D*)
(*@/// function arctan_d(x:extended):extended; *)
function arctan_d(x:extended):extended;
begin
result:=rad2deg(arctan(x));
end;
(*@\\\000000031E*)
(*@/// function put_in_360(x:extended):extended; *)
function put_in_360(x:extended):extended;
begin
result:=x-round(x/360)*360;
while result<0 do result:=result+360;
end;
(*@\\\*)
(*@/// function adjusted_mod(a,b:integer):integer; *)
function adjusted_mod(a,b:integer):integer;
begin
result:=a mod b;
while result<1 do
result:=result+b;
end;
(*@\\\*)
(*@\\\*)
(*$ifdef delphi_ge_2 *) (*$warnings off *) (*$endif *)
end.
(*@\\\003F000901000901000901000A01000701000011000701*)
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 7 O(N3) Simulation Method
}
program
AntiHash;
const
MaxN = 50;
var
N : Integer;
A, B : array [0 .. MaxN - 1] of Integer;
H, M : array [0 .. MaxN - 1] of Boolean;
I, J, K : Integer;
F : Text;
function Hash (X : Integer) : Integer;
var
I : Integer;
begin
I := X mod N;
while H[I] do
I := (I + 1) mod N;
Hash := I;
end;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N);
for I := 0 to N - 1 do
Readln(F, A[I]);
Close(F);
for I := 0 to N - 1 do
for J := 0 to N - 1 do
if not M[J] and (Hash(A[J]) = J) then
begin
M[J] := True;
B[I] := A[J];
H[J] := True;
Break;
end;
Assign(F, 'output.txt');
ReWrite(F);
for I := 0 to N - 1 do
Writeln(F, B[I]);
Close(F);
end. |
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit ResponseStreamImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
Classes,
DependencyIntf,
ResponseStreamIntf;
type
(*!----------------------------------------------
* adapter class having capability as
* HTTP response body
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-----------------------------------------------*)
TResponseStream = class(TInterfacedObject, IResponseStream, IDependency)
private
stream : TStream;
isOwned : boolean;
public
(*!------------------------------------
* constructor
*-------------------------------------
* @param streamInst instance of actual stream
* @param owned true if streamInst is owned, meaning, its
* memory will be deallocated when destructor
* is called
*-------------------------------------*)
constructor create(const streamInst : TStream; const owned : boolean = true);
(*!------------------------------------
* destructor
*-------------------------------------
* if isOwned true, streamInst memory
* will be deallocated when destructor
* is called
*-------------------------------------*)
destructor destroy(); override;
(*!------------------------------------
* read stream to buffer from current
* seek position
*-------------------------------------
* @param buffer pointer to buffer to store
* @param sizeToRead number of bytes to read
* @return number of bytes actually read
*-------------------------------------
* After read, implementation must advance its
* internal pointer position to actual number
* of bytes read
*-------------------------------------*)
function read(var buffer; const sizeToRead : longint) : longint;
(*!------------------------------------
* write buffer to stream
*-------------------------------------
* @param buffer pointer to buffer to write
* @param sizeToWrite number of bytes to write
* @return number of bytes actually written
*-------------------------------------*)
function write(const buffer; const sizeToWrite : longint) : longint;
(*!------------------------------------
* write string to stream
*-------------------------------------
* @param buffer string to write
* @return number of bytes actually written
*-------------------------------------*)
function write(const buffer : string) : longint;
(*!------------------------------------
* get stream size
*-------------------------------------
* @return size of stream in bytes
*-------------------------------------*)
function size() : int64;
(*!------------------------------------
* seek
*-------------------------------------
* @param offset in bytes to seek start from beginning
* @return actual offset
*-------------------------------------
* if offset >= stream size then it is capped
* to stream size-1
*-------------------------------------*)
function seek(const offset : longint) : int64;
end;
implementation
(*!------------------------------------
* constructor
*-------------------------------------
* @param streamInst instance of actual stream
* @param owned true if streamInst is owned, meaning, its
* memory will be deallocated when destructor
* is called
*-------------------------------------*)
constructor TResponseStream.create(const streamInst : TStream; const owned : boolean = true);
begin
stream := streamInst;
isOwned := owned;
end;
(*!------------------------------------
* destructor
*-------------------------------------
* if isOwned true, streamInst memory
* will be deallocated when destructor
* is called
*-------------------------------------*)
destructor TResponseStream.destroy();
begin
inherited destroy();
if (isOwned) then
begin
stream.free();
end;
end;
(*!------------------------------------
* read stream to buffer from current
* seek position
*-------------------------------------
* @param buffer pointer to buffer to store
* @param sizeToRead number of bytes to read
* @return number of bytes actually read
*-------------------------------------
* After read, implementation must advance its
* internal pointer position to actual number
* of bytes read
*-------------------------------------*)
function TResponseStream.read(var buffer; const sizeToRead : longint) : longint;
begin
result := stream.read(buffer, sizeToRead);
end;
(*!------------------------------------
* write buffer to stream
*-------------------------------------
* @param buffer pointer to buffer to write
* @param sizeToWrite number of bytes to write
* @return number of bytes actually written
*-------------------------------------*)
function TResponseStream.write(const buffer; const sizeToWrite : longint) : longint;
begin
result := stream.write(buffer, sizeToWrite);
end;
(*!------------------------------------
* write string to stream
*-------------------------------------
* @param buffer string to write
* @return number of bytes actually written
*-------------------------------------*)
function TResponseStream.write(const buffer : string) : longint;
begin
result := self.write(buffer[1], length(buffer));
end;
(*!------------------------------------
* get stream size
*-------------------------------------
* @return size of stream in bytes
*-------------------------------------*)
function TResponseStream.size() : int64;
begin
result := stream.size;
end;
(*!------------------------------------
* seek
*-------------------------------------
* @param offset in bytes to seek start from beginning
* @return actual offset
*-------------------------------------
* if offset >= stream size then it is capped
* to stream size-1
*-------------------------------------*)
function TResponseStream.seek(const offset : longint) : int64;
begin
result := stream.seek(offset, soFromBeginning);
end;
end.
|
unit Finance.Stocks;
interface
uses
Finance.interfaces,
System.JSON,
System.Generics.Collections;
type
TFinanceStocks = class(TInterfacedObject, iFinanceStocks)
private
FParent : iFinance;
FIBOVESPA : iFinanceStock;
FNASDAQ : iFinanceStock;
FCAC : iFinanceStock;
FNIKKEI : iFinanceStock;
public
constructor Create(Parent : iFinance);
destructor Destroy; override;
function GetIBOVESPA : iFinanceStock;
function GetNASDAQ : iFinanceStock;
function GetCAC : iFinanceStock;
function GetNIKKEI : iFinanceStock;
function SetJSON( value : TJSONObject) : iFinanceStocks;
function &End : iFinance;
end;
implementation
uses
Injection, Finance.Stock;
{ TFinanceStocks }
constructor TFinanceStocks.Create(Parent: iFinance);
begin
TInjection.Weak(@FParent, Parent);
FIBOVESPA := TFinanceStock.Create(Self);
FNASDAQ := TFinanceStock.Create(Self);
FCAC := TFinanceStock.Create(Self);
FNIKKEI := TFinanceStock.Create(Self);
end;
destructor TFinanceStocks.Destroy;
begin
inherited;
end;
function TFinanceStocks.&End: iFinance;
begin
Result := FParent;
end;
function TFinanceStocks.GetCAC: iFinanceStock;
begin
Result := FCAC;
end;
function TFinanceStocks.GetIBOVESPA: iFinanceStock;
begin
Result := FIBOVESPA
end;
function TFinanceStocks.GetNASDAQ: iFinanceStock;
begin
Result := FNASDAQ;
end;
function TFinanceStocks.GetNIKKEI: iFinanceStock;
begin
Result := FNIKKEI
end;
function TFinanceStocks.SetJSON(value: TJSONObject): iFinanceStocks;
begin
Result := Self;
FIBOVESPA.SetJSON(value.pairs[0]);
FNASDAQ.SetJSON(value.pairs[1]);
FCAC.SetJSON(value.pairs[2]);
FNIKKEI.SetJSON(value.pairs[3]);
end;
end.
|
{***********************************************************************
Unit IO_FILES.PAS v 1.05 0799
Delphi version : Delphi 3 / 4
You may use this sourcecode for your freewareproducts.
You may modify this sourcecode for your own use.
You may recompile this sourcecode for your own use.
Disclaimer of warranty: "This software is supplied as is. The author
disclaims all warranties, expressed or implied, including, without
limitation, the warranties of merchantability and of fitness for any
purpose. The author assumes no liability for damages, direct or
consequential, which may result from the use of this software."
All brand and product names are marks or registered marks of their
respective companies.
Please report bugs to:
Andreas Moser AMoser@amoser.de
Overview:
IO_files provides some functions and some classes for filehandling.
Classes:
TFileRecList: a class derived from TList that allows easy
access to the properties of every file.
The mainfunctions are:
procedure ReadFiles(Directory:String;FileMask:String;FileType:TFileType;SortBy:TSortOrder);
-> Read all files specified in FileMask and FileType from the given directory into
the TFileRecList.
The following functions returns the value of the file specified in 'Index':
function GetFileName(Index:Integer):String;
function GetFileSize(Index:Integer):Integer;
function GetFileDate(Index:Integer):TDateTime;
function GetFileAttr(Index:Integer):Integer;
function GetW32FileAttributes(Index:Integer):DWORD;
function GetW32FileName(Index:Integer):string;
function GetW32AlternateFileName(Index:Integer):string;
function GetW32CreationTime(Index:Integer):TDateTime;
function GetW32LastAccessTime(Index:Integer):TDateTime;
function GetW32LastWriteTime(Index:Integer):TDateTime;
To get the Index of a file knowing the filename just use:
function GetIndexOfFileName(Name:String):Integer;
To clear the FileRecList manually use:
procedure ClearFileRecList;
************************************************************************}
unit io_files;
interface
uses forms,windows,classes,filectrl,sysutils,Dialogs,Controls,ComCtrls;
const msgAskReadOnly='%s is read-only, try to delete ?';
msgAskForMoveReadOnly='%s is read-only, try to move ?';
msgAskForOverwrite='%s already exists, try to overwrite ?';
msgAskForRenameReadOnly='%s is read-only, try to rename ?';
msgAskForDelete='Delete %s ?';
type TProgressCallBack=function(Min,Max,Position:Integer):Boolean;
//** TFileRecList
type TSortOrder=(srtName,srtSize,srtDate,srtNone,srtExt);
type TExtInfo=class(TObject)
public
Archive:Boolean;
Reserved:string;
ID:LongInt;
end;
pExtInfo=^TExtInfo;
type TExtSearchRec=record
SRec:TSearchRec;
Path:String[255];
IsArchive:Boolean;
ID:LongInt;
end;
pSearchRecord=^TExtSearchRec;
EInvalidDest = class(EStreamError);
EFCantMove = class(EStreamError);
TSyncMode=(syBoth,sySrcToDst,syDstToSrc);
const
Attributes: array[TFileAttr] of Word = (faReadOnly, faHidden, faSysFile,
faVolumeID, faDirectory, faArchive, 0);
SInvalidDest = 'Destination %s does not exist';
SFCantMove = 'Cannot move file %s';
//-------------------------------------
//
// TFileRecList class interface
// A TList Class for keeping FileInfo records
//-------------------------------------
type
TFileRecList=class(TList)
public
function GetFileName(Index:Integer):String;
function GetFilePath(Index:Integer):String;
function GetCompleteFileName(Index:Integer):String;
function GetFileNameWOPATH(Index:Integer):String;
function GetFileSize(Index:Integer):Integer;
function GetFileDate(Index:Integer):TDateTime;
function GetFileAttr(Index:Integer):Integer;
function GetW32FileAttributes(Index:Integer):Integer;
function GetW32FileName(Index:Integer):string;
function GetW32AlternateFileName(Index:Integer):string;
function GetW32CreationTime(Index:Integer):TDateTime;
function GetW32LastAccessTime(Index:Integer):TDateTime;
function GetW32LastWriteTime(Index:Integer):TDateTime;
function GetSearchRec(Index:Integer):TExtSearchRec;
procedure ReadFiles(Directory:String;FileMask:String;FileType:TFileType;SortBy:TSortOrder);
Procedure ScanTreeForFiles(Const path: String; Const mask: String;SortBy:TSortOrder);
function AddExtSearchRec(const Path,FileName:String):Boolean;
function AddExtFakeRec(const Path,FileName:String;ArchiveFile:Boolean):Boolean;
function GetIndexOfFileName(Name:String):Integer;
function GetIndexOfFileNameWOPATH(Name:String):Integer;
function GetIndexOfFileNameCI(Name:String):Integer;
function GetIndexOfCompleteFileName(Name:String):Integer;
procedure ClearFileRecList;
end;
//-------------------------------------
//
// TIntegerList class interface
// A TList class like TStringList
//-------------------------------------
type TIntegerList =class(TList)
public
function AddInteger(Value:DWORD):Integer;
procedure DeleteInteger(Index:Integer);
function FindInteger(Value:DWord):Integer;
procedure ClearIntegerList;
end;
function SortName(Item1, Item2: Pointer): Integer;
function SortDate(Item1, Item2: Pointer): Integer;
function SortSize(Item1, Item2: Pointer): Integer;
function SortExt(Item1, Item2: Pointer): Integer;
//-------------------------------------
//
// Class independent function interface
//
//-------------------------------------
//--------------------
//
// Path functions
//
//--------------------
procedure ScanTreeForFiles(ResultList:TStringList;Const path: String; Const mask: String);
procedure ClearStringListWObjects(List:TSTringList);
procedure ScanTreeForPaths(ResultList:TStringList;Const path: String);
procedure SyncTwoDirectories(DirectoryOne,DirectoryTwo:String;FileMask:String;FileType:TFileType;SyncMode:TSyncMode;Callback:TProgressCallback);
procedure SyncTwoTrees(BaseDirOne,BaseDirTwo:String;FileMask:String;FileType:TFileType;SyncMode:TSyncMode;Callback:TProgressCallback);
function SwitchTwoFiles(FileNameOne,FileNameTwo:String):Boolean;
function RenameInsertFile(Directory,FileNameOne,FileNameTwo:string;CharToBeAdded:Char):String;
function CutDirectory(Directory:String;MinLength:Integer):String;
function CompareDirectory(Path1,Path2:String):Boolean;
function CompareDirectorySub(Path,SubPath:String):Boolean;
function ExtFileDirExists (Path:string):Boolean;
function ExtAddBackSlash(const Path:String):String;
function ExtRemoveBackSlash(const Directory:String):String;
function GetFDrive(Path:string):string;
function GetFPath(Path:string):string;
function GetLastPathPart(Path:string):string;
function DeleteLastPathPart(Path:string):string;
function IsDriveRemovable(Path:String;var ID:String; var Name:String):Boolean;
function GetVolumeName(Drive:string):string;
function GetVolumeIDName(Drive:string;var VolumeName:String; var Volume_id:Integer):Boolean;
function GetVolumeID(Drive:string):Integer;
//--------------------
//
// File functions
//
//--------------------
function ExtCopyFile(const Source, Destination: TFileName;AskForOverwrite:Boolean):Boolean;
function ExtMoveFile(const Source, Destination: TFileName;AskForOverwrite:Boolean):Boolean;
function ExtRenameFile(const OldName, NewName: TFileName):Boolean;
function ExtDeleteFile(const FileName:TFileName;var DeleteMode:Integer;IntoRecycleBin:Boolean):Boolean;
function ExtGetFileSize(const FileName: string): LongInt;
function ExtFileDateTime(const FileName: string): TDateTime;
function ExtHasAttr(const FileName: string; Attr: Word): Boolean;
function ExtExecuteFile(const FileName, Params, DefaultDir: string;ShowCmd: Integer): THandle;
function ExtCreateDir(const Path:String):Boolean;
function ExtGetTempFileName(Prefix,AlternatePath:String):string;
function ExtGetTempPath:string;
procedure GetDriveInfo;
function IsVolumeAvailable(Volume_Name:String):Boolean;
procedure RetrieveDriveInfo(Drive:Char);
//--------------------
//
// CRC functions
//
//--------------------
procedure MakeCRCTable;
function CRC32(crc:longint;buffer:PByteArray;length:Integer):DWord;
function CRC32File(FileName:String):Dword;
//--------------------
//
// Misc. functions
//
//--------------------
function ExtFillUpWithZero(Number:Integer;Digits:Integer):String;
function DeleteToRecycleBin(FileName:String):Boolean;
type
dtable_entry = record
Drive: String;
Volume_ID: Integer;
Volume_Name: String;
end;
var amOvrAll:Integer;
crc32tablecreated:Boolean;
crc_table : Array[0..255] of dword;
drive_table : Array [0..30] of dtable_entry;
drive_table_count : Integer;
implementation
uses ShellAPI,io_const;
//-------------------------------------
//
// Global sort functions for TFileRecList
//
//-------------------------------------
function SortSize(Item1, Item2: Pointer): Integer;
// -----------------------------------------------------------------------------
// Purpose : Sort filereclist by Srec.size
// Parameter : Pointer to the two processed items
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if pSearchRecord(Item1).SRec.Size < pSearchRecord(Item2).SRec.Size then Result:=-1
else
if pSearchRecord(Item1).SRec.Size > pSearchRecord(Item2).SRec.Size then Result:=1
else Result:=0;
end;
function SortDate(Item1, Item2: Pointer): Integer;
// -----------------------------------------------------------------------------
// Purpose : Sort filereclist by Srec.Date
// Parameter : Pointer to the two processed items
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if pSearchRecord(Item1).SRec.Time < pSearchRecord(Item2).SRec.Time then Result:=-1
else
if pSearchRecord(Item1).SRec.Time > pSearchRecord(Item2).SRec.Time then Result:=1
else Result:=0;
end;
function SortName(Item1, Item2: Pointer): Integer;
// -----------------------------------------------------------------------------
// Purpose : Sort filereclist by Srec.Name
// Parameter : Pointer to the two processed items
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if UpperCase(pSearchRecord(Item1).SRec.Name) < UpperCase(pSearchRecord(Item2).SRec.Name) then Result:=-1
else
if UpperCase(pSearchRecord(Item1).SRec.Name) > UpperCase(pSearchRecord(Item2).SRec.Name) then Result:=1
else Result:=0;
end;
function SortExt(Item1, Item2: Pointer): Integer;
// -----------------------------------------------------------------------------
// Purpose : Sort filereclist by Extension
// Parameter : Pointer to the two processed items
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if UpperCase(ExtractFileExt(pSearchRecord(Item1).SRec.Name)) < UpperCase(ExtractFileExt(pSearchRecord(Item2).SRec.Name)) then Result:=-1
else
if UpperCase(ExtractFileExt(pSearchRecord(Item1).SRec.Name)) > UpperCase(ExtractFileExt(pSearchRecord(Item2).SRec.Name)) then Result:=1
else Result:=0;
end;
//-------------------------------------
//
// TFileRecList class implementation
//
//-------------------------------------
function TFileRecList.GetFileName(Index:Integer):String;
// -----------------------------------------------------------------------------
// Purpose : Returns the Filename of SearchRecord
// Parameter : Index of record
// Result : The filename, '' if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if (Index>-1) and (Index<Count) then Result:=pSearchRecord(Items[Index])^.SRec.Name
else Result:='';
end;
function TFileRecList.GetFilePath(Index:Integer):String;
// -----------------------------------------------------------------------------
// Purpose : Returns the Path of SearchRecord
// Parameter : Index of record
// Result : The filename, '' if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if (Index>-1) and (Index<Count) then Result:=pSearchRecord(Items[Index])^.Path
else Result:='';
end;
function TFileRecList.GetCompleteFileName(Index:Integer):String;
// -----------------------------------------------------------------------------
// Purpose : Returns the Path of SearchRecord
// Parameter : Index of record
// Result : The filename, '' if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if (Index>-1) and (Index<Count) then Result:=ExtAddBackSlash(pSearchRecord(Items[Index])^.Path)+
ExtractFileName(pSearchRecord(Items[Index])^.SRec.Name)
else Result:='';
end;
function TFileRecList.GetFileNameWOPATH(Index:Integer):String;
// -----------------------------------------------------------------------------
// Purpose : Returns the Filename without path of SearchRecord
// Parameter : Index of record
// Result : The filename, '' if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if (Index>-1) and (Index<Count) then Result:=ExtractFileName(pSearchRecord(Items[Index])^.SRec.Name)
else Result:='';
end;
function TFileRecList.GetFileSize(Index:Integer):Integer;
// -----------------------------------------------------------------------------
// Purpose : Returns the Filesize of SearchRecord
// Parameter : Index of record
// Result : The filesize, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if (Index>-1) and (Index<Count) then Result:=pSearchRecord(Items[Index])^.SRec.Size
else Result:=-1;
end;
function TFileRecList.GetFileDate(Index:Integer):TDateTime;
// -----------------------------------------------------------------------------
// Purpose : Returns the Filedate of SearchRecord
// Parameter : Index of record
// Result : The filedate, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
Result:=-1;
if (Index>-1) and (Index<Count) then
if
pSearchRecord(Items[Index])^.SRec.Time<>0 then
Result:=FileDateToDateTime(pSearchRecord(Items[Index])^.SRec.Time)
else Result:=-1;
end;
function TFileRecList.GetFileAttr(Index:Integer):Integer;
// -----------------------------------------------------------------------------
// Purpose : Returns the fileattributes of SearchRecord
// Parameter : Index of record
// Result : The fileattributes, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if (Index>-1) and (Index<Count) then Result:=pSearchRecord(Items[Index])^.SRec.Attr
else Result:=-1;
end;
function TFileRecList.GetW32FileName(Index:Integer):String;
// -----------------------------------------------------------------------------
// Purpose : Returns the W32Filename of SearchRecord
// Parameter : Index of record
// Result : The filename, '' if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if (Index>-1) and (Index<Count) then Result:=pSearchRecord(Items[Index])^.SRec.FindData.cFileName
else Result:='';
end;
function TFileRecList.GetW32AlternateFileName(Index:Integer):String;
// -----------------------------------------------------------------------------
// Purpose : Returns the W32Filename of SearchRecord
// Parameter : Index of record
// Result : The filename, '' if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if (Index>-1) and (Index<Count) then Result:=pSearchRecord(Items[Index])^.SRec.FindData.cAlternateFileName
else Result:='';
end;
function TFileRecList.GetW32FileAttributes(Index:Integer):Integer;
// -----------------------------------------------------------------------------
// Purpose : Returns the W32FileAttributes of SearchRecord
// Parameter : Index of record
// Result : The fileattributes, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if (Index>-1) and (Index<Count) then Result:=pSearchRecord(Items[Index])^.SRec.FindData.dwFileAttributes
else Result:=-1;
end;
function TFileRecList.GetW32CreationTime(Index:Integer):TDateTime;
// -----------------------------------------------------------------------------
// Purpose : Returns the W32 file creationtime of SearchRecord
// Parameter : Index of record
// Result : The W32 file creationtime, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var t1:TFileTime;
t2:TSystemTime;
t3,t4:TDateTime;
begin
if (Index>-1) and (Index<Count) then begin
filetimetolocalfiletime(pSearchRecord(Items[Index])^.SRec.FindData.ftCreationTime,t1);
FileTimeToSystemTime(t1,t2);
t3:=EncodeDate(t2.wYear,t2.wMonth,t2.wDay);
t4:=EncodeTime(t2.wHour,t2.wMinute,t2.wSecond,t2.wMilliseconds);
Result:=t3+t4;
end
else Result:=-1;
end;
function TFileRecList.GetW32LastAccessTime(Index:Integer):TDateTime;
// -----------------------------------------------------------------------------
// Purpose : Returns the W32 file last access time of SearchRecord
// Parameter : Index of record
// Result : The W32 file last access time, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var t1:TFileTime;
t2:TSystemTime;
t3,t4:TDateTime;
begin
if (Index>-1) and (Index<Count) then begin
filetimetolocalfiletime(pSearchRecord(Items[Index])^.SRec.FindData.ftLastAccessTime,t1);
FileTimeToSystemTime(t1,t2);
t3:=EncodeDate(t2.wYear,t2.wMonth,t2.wDay);
t4:=EncodeTime(t2.wHour,t2.wMinute,t2.wSecond,t2.wMilliseconds);
Result:=t3+t4;
end
else Result:=-1;
end;
function TFileRecList.GetW32LastWriteTime(Index:Integer):TDateTime;
// -----------------------------------------------------------------------------
// Purpose : Returns the W32 file last write time of SearchRecord
// Parameter : Index of record
// Result : The W32 file last write time, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var t1:TFileTime;
t2:TSystemTime;
t3,t4:TDateTime;
begin
if (Index>-1) and (Index<Count) then begin
filetimetolocalfiletime(pSearchRecord(Items[Index])^.SRec.FindData.ftLastWriteTime,t1);
FileTimeToSystemTime(t1,t2);
t3:=EncodeDate(t2.wYear,t2.wMonth,t2.wDay);
t4:=EncodeTime(t2.wHour,t2.wMinute,t2.wSecond,t2.wMilliseconds);
Result:=t3+t4;
end
else Result:=-1;
end;
function TFileRecList.GetSearchRec(Index:Integer):TExtSearchRec;
// -----------------------------------------------------------------------------
// Purpose : Returns a SearchRecord
// Parameter : Index of record
// Result : SearchRecord
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
result:=pSearchRecord(Items[Index])^;
end;
procedure TFileRecList.ReadFiles(Directory:String;FileMask:String;FileType:TFileType;SortBy:TSortOrder);
// -----------------------------------------------------------------------------
// Purpose : Read the files of a directory to SearchRecList
// Parameter : Directory: the directory to be processed
// FileMask : the FileMask (e.g. '*.jpg')
// FileType : Mask file attributes
// SortBy : SortOrder (srtName,srtDate,srtSize)
// Result : -
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var
AttrIndex: TFileAttr;
FileExt: string;
MaskPtr: PChar;
Ptr: PChar;
AttrWord: Word;
FileInfo: TSearchRec;
pFileInfo:pSearchRecord;
begin
if DirectoryExists(Directory) then
begin
AttrWord := DDL_READWRITE;
for AttrIndex := ftReadOnly to ftArchive do
if AttrIndex in FileType then
AttrWord := AttrWord or Attributes[AttrIndex];
ChDir(Directory);
ClearFileRecList;
try
MaskPtr := PChar(FileMask);
while MaskPtr <> nil do
begin
Ptr := StrScan (MaskPtr, ';');
if Ptr <> nil then
Ptr^ := #0;
if FindFirst(MaskPtr, AttrWord, FileInfo) = 0 then
begin
repeat
if (ftNormal in FileType) or (FileInfo.Attr and AttrWord <> 0) then
begin
New(pFileInfo);
pFileInfo^.SRec:=FIleInfo;
pFileInfo^.IsArchive:=False;
pFileInfo^.ID:=0;
pFileInfo^.Path:=Directory;
Add(pFileInfo);
end
else
begin
FileExt := AnsiLowerCase(ExtractFileExt(FileInfo.Name));
end;
until FindNext(FileInfo) <> 0;
FindClose(FileInfo);
end;
if Ptr <> nil then
begin
Ptr^ := ';';
Inc (Ptr);
end;
MaskPtr := Ptr;
end;
case SortBy of
srtName:Sort(SortName);
srtSize:Sort(SortSize);
srtDate:Sort(SortDate);
srtExt:begin
Sort(SortName);
Sort(SortExt);
end;
end;
finally
end;
end;
end;
function TFileRecList.GetIndexOfFileName(Name:String):Integer;
// -----------------------------------------------------------------------------
// Purpose : Get the index of <Name> (case sensitive!)
// Parameter : Name : Filename
// Result : Index, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var j:Integer;
begin
result:=-1;
for j:=0 to Count-1 do
if pSearchRecord(Items[j])^.SRec.Name=Name then begin result:=j;break;end;
end;
function TFileRecList.GetIndexOfFileNameCI(Name:String):Integer;
// -----------------------------------------------------------------------------
// Purpose : Get the index of <Name> (case insensitive!)
// Parameter : name : FileName
// Result : Index, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var j:Integer;
begin
result:=-1;
for j:=0 to Count-1 do
if LowerCase(pSearchRecord(Items[j])^.SRec.Name)=LowerCase(Name) then begin result:=j;break;end;
end;
function TFileRecList.GetIndexOfFileNameWOPATH(Name:String):Integer;
// -----------------------------------------------------------------------------
// Purpose : Get the index of <Name> (case sensitive!)
// (this function removes the path from <Name>)
// Parameter : Name : Filename
// Result : Index, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var j:Integer;
begin
result:=-1;
for j:=0 to Count-1 do
if ExtractFileName(pSearchRecord(Items[j])^.SRec.Name)=Name then begin result:=j;break;end;
end;
function TFileRecList.GetIndexOfCompleteFileName(Name:String):Integer;
// -----------------------------------------------------------------------------
// Purpose : Get the index of <Path> and <Name> (case sensitive!)
// (this function removes the path from <Name>)
// Parameter : Name : Filename
// Result : Index, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var j:Integer;
begin
result:=-1;
for j:=0 to Count-1 do
if
CompareText(
ExtractFileName(pSearchRecord(Items[j])^.SRec.Name),
ExtractFileName(Name)
)=0
then
begin
if
CompareText( ExtAddBackSlash(
pSearchRecord(Items[j])^.Path),
ExtAddBackSlash(ExtractFileDir(Name))
) =0
then begin
result:=j;
break;
end;
end;
end;
Procedure TFileRecList.ScanTreeForFiles(Const path: String; Const mask: String;SortBy:TSortOrder);
// -----------------------------------------------------------------------------
// Purpose : Read the files of a directory tree to SearchRecList
// Parameter : path : the toplevel-directory to be processed
// Mask : the FileMask (e.g. '*.jpg')
// SortBy : SortOrder (srtName,srtDate,srtSize)
// Result : -
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
Var
fullpath: String;
pFileInfo:pSearchRecord;
MaskPtr: PChar;
Ptr: PChar;
Function Recurse( Var path: String; Const mask: String ): Boolean;
Var
FileInfo: TSearchRec;
retval: Integer;
oldlen: Integer;
Begin
Recurse := True;
oldlen := Length( path );
MaskPtr := PChar(Mask);
while MaskPtr <> nil do
begin
Ptr := StrScan (MaskPtr, ';');
if Ptr <> nil then Ptr^ := #0;
retval := FindFirst( path+maskptr, faAnyFile, FileInfo );
While retval = 0 Do Begin
If (FileInfo.Attr and (faDirectory or faVolumeID)) = 0 Then
begin
New(pFileInfo);
pFileInfo^.SRec:=FIleInfo;
pFileInfo^.IsArchive:=False;
pFileInfo^.ID:=0;
pFileInfo^.Path:=path;
Add(pFileInfo);
end;
retval := FindNext( FileInfo );
End;
FindClose( FileInfo );
if Ptr <> nil then
begin
Ptr^ := ';';
Inc (Ptr);
end;
MaskPtr := Ptr;
end;
If not Result Then Exit;
retval := FindFirst( path+'*.*', faDirectory, FileInfo );
While retval = 0 Do Begin
If (FileInfo.Attr and faDirectory) <> 0 Then
If (FileInfo.Name <> '.') and (FileInfo.Name <> '..') Then Begin
path := path + FileInfo.Name + '\';
If not Recurse( path, mask ) Then Begin
Result := False;
Break;
End;
System.Delete( path, oldlen+1, 255 );
End;
retval := FindNext( FileInfo );
End;
FindClose( FileInfo );
End;
Begin
ClearFileRecList;//ResultList.Clear;
If path = '' Then
GetDir(0, fullpath)
Else
fullpath := path;
If fullpath[Length(fullpath)] <> '\' Then
fullpath := fullpath + '\';
If mask = '' Then
Recurse( fullpath, '*.*' )
Else
Recurse( fullpath, mask );
case SortBy of
srtName:Sort(SortName);
srtSize:Sort(SortSize);
srtDate:Sort(SortDate);
srtExt:begin
Sort(SortName);
Sort(SortExt);
end;
end;
End;
function TFileRecList.AddExtSearchRec(const Path,FileName:String):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Add a file to the SearchRecList
// Note: Success only if file exists
// Parameter : Path, FileName
// Result : True on success, False on failure
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var Retval:Integer;
pFileInfo:pSearchRecord;
FileInfo: TSearchRec;
begin
Result:=false;
ChDir(Path);
retval := FindFirst( ExtAddBackSlash(path)+FileName, faAnyFile, FileInfo );
if retval = 0 then
Begin
If (FileInfo.Attr and (faDirectory or faVolumeID)) = 0 Then
begin
New(pFileInfo);
pFileInfo^.SRec:=FIleInfo;
pFileInfo^.IsArchive:=False;
pFileInfo^.ID:=0;
pFileInfo^.Path:=path;
Add(pFileInfo);
Result:=true;
end;
end;
FindClose( FileInfo );
end;
function TFileRecList.AddExtFakeRec(const Path,FileName:String;ArchiveFile:Boolean):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Add a fake file to the SearchRecList
// This means that the file must not exist
// NOTE: The only valid entries of this Record
// are Filename and Path
// Parameter : Path, FileName
// Result : True on success, False on failure
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var
pFileInfo:pSearchRecord;
begin
New(pFileInfo);
pFileInfo^.SRec.Name:=FileName;
pFileInfo^.IsArchive:=ArchiveFile;
pFileInfo^.ID:=0;
pFileInfo^.SRec.Time:=0;
StrCopy(pFileInfo^.SRec.FindData.cFileName,PChar(FileName));
pFileInfo^.Path:=path;
Add(pFileInfo);
Result:=true;
end;
procedure TFileRecList.ClearFileRecList;
// -----------------------------------------------------------------------------
// Purpose : Clear FileRecList
// Parameter : -
// Result : -
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var i:Integer;
begin
if Count>0 then
for i:=0 to Count-1 do
try
if Assigned(Items[i]) then
begin
pSearchRecord(Items[i]).SRec.Name:='';
Dispose(pSearchRecord(Items[i]));
end;
finally
Items[i]:=nil;
end;
Clear;
end;
//-------------------------------------
//
// TIntegerList class implementation
//
//-------------------------------------
function TIntegerList.AddInteger(Value:DWORD):Integer;
// -----------------------------------------------------------------------------
// Purpose : Add a Integer ( or DWORD)
// Parameter : Value
// Result : Index
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var p:PDWORD;
begin
New(p);
p^:=value;
result:=Add(p);
end;
function TIntegerList.FindInteger(Value:DWord):Integer;
// -----------------------------------------------------------------------------
// Purpose : Find the first Value
// Parameter : Value
// Result : Index, -1 if not found
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var i:Integer;
begin
result:=-1;
for i:=0 to Count-1 do
if pDWORD(Items[i])^=Value then
begin
result:=i;
end;
end;
procedure TIntegerList.DeleteInteger(Index:Integer);
// -----------------------------------------------------------------------------
// Purpose : Delete an entry
// Parameter : Index
// Result : -
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if Assigned(Items[Index]) then
Dispose(pDWord(Items[Index]));
end;
procedure TIntegerList.ClearIntegerList;
// -----------------------------------------------------------------------------
//
// Purpose : Clear the IntegerList
// Parameter : -
// Result : -
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var i:Integer;
begin
if Count>0 then
for i:=0 to Count-1 do
try
if Assigned(Items[i]) then
begin
Dispose(pDWord(Items[i]));
end;
finally
Items[i]:=nil;
end;
Clear;
end;
//-------------------------------------
//
// Global functions implementation
//
//-------------------------------------
//-----------------------
//
// Path functions implementation
//
//-----------------------
Procedure ScanTreeForFiles(ResultList:TStringList;Const path: String; Const mask: String);
// -----------------------------------------------------------------------------
// Purpose : Scan tree for files
// Parameter : ResultList : StringList where result will be stored
// Path : Top level directory
// Mask : FileMask
// Result : -
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
Var
fullpath: String;
MaskPtr: PChar;
Ptr: PChar;
Function Recurse( Var path: String; Const mask: String ): Boolean;
Var
FileInfo: TSearchRec;
retval: Integer;
oldlen: Integer;
Begin
Recurse := True;
oldlen := Length( path );
MaskPtr := PChar(Mask);
while MaskPtr <> nil do
begin
Ptr := StrScan (MaskPtr, ';');
if Ptr <> nil then Ptr^ := #0;
retval := FindFirst( path+maskptr, faAnyFile, FileInfo );
While retval = 0 Do Begin
If (FileInfo.Attr and (faDirectory or faVolumeID)) = 0 Then
ResultList.AddObject(path+FileInfo.Name,TExtInfo.Create);
retval := FindNext( FileInfo );
End;
FindClose( FileInfo );
if Ptr <> nil then
begin
Ptr^ := ';';
Inc (Ptr);
end;
MaskPtr := Ptr;
end;
If not Result Then Exit;
retval := FindFirst( path+'*.*', faDirectory, FileInfo );
While retval = 0 Do Begin
If (FileInfo.Attr and faDirectory) <> 0 Then
If (FileInfo.Name <> '.') and (FileInfo.Name <> '..') Then Begin
path := path + FileInfo.Name + '\';
If not Recurse( path, mask ) Then Begin
Result := False;
Break;
End;
Delete( path, oldlen+1, 255 );
End;
retval := FindNext( FileInfo );
End;
FindClose( FileInfo );
End;
Begin
ClearStringListWObjects(ResultList);
If path = '' Then
GetDir(0, fullpath)
Else
fullpath := path;
If fullpath[Length(fullpath)] <> '\' Then
fullpath := fullpath + '\';
If mask = '' Then
Recurse( fullpath, '*.*' )
Else
Recurse( fullpath, mask );
End;
procedure ScanTreeForPaths(ResultList:TStringList;Const path: String);
// -----------------------------------------------------------------------------
// Purpose : Scan tree for Paths
// Parameter : ResultList : StringList where result will be stored
// Path : Top level directory
// Result : -
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
Var
fullpath: String;
MaskPtr: PChar;
Ptr: PChar;
Function Recurse( Var path: String): Boolean;
Var
FileInfo: TSearchRec;
retval: Integer;
oldlen: Integer;
Begin
Recurse := True;
oldlen := Length( path );
MaskPtr := PChar('*.*');
while MaskPtr <> nil do
begin
Ptr := StrScan (MaskPtr, ';');
if Ptr <> nil then Ptr^ := #0;
retval := FindFirst( path+maskptr, faDirectory{faAnyFile}, FileInfo );
While retval = 0 Do Begin
If (FileInfo.Attr and (faDirectory {or faVolumeID)})) = faDirectory Then
If (FileInfo.Name <> '.') and (FileInfo.Name <> '..') then
ResultList.AddObject(path+FileInfo.Name,TExtInfo.Create);
retval := FindNext(FileInfo);
End;
FindClose( FileInfo );
if Ptr <> nil then
begin
Ptr^ := ';';
Inc (Ptr);
end;
MaskPtr := Ptr;
end;
If not Result Then Exit;
retval := FindFirst( path+'*.*', faDirectory, FileInfo );
While retval = 0 Do Begin
If (FileInfo.Attr and faDirectory) <> 0 Then
If (FileInfo.Name <> '.') and (FileInfo.Name <> '..') Then Begin
path := path + FileInfo.Name + '\';
If not Recurse( path) Then Begin
Result := False;
Break;
End;
Delete( path, oldlen+1, 255 );
End;
retval := FindNext( FileInfo );
End;
FindClose( FileInfo );
End;
Begin
ClearStringListWObjects(ResultList);
If path = '' Then
GetDir(0, fullpath)
Else
fullpath := path;
If fullpath[Length(fullpath)] <> '\' Then
fullpath := fullpath + '\';
// If mask = '' Then
Recurse( fullpath)
// Else
// Recurse( fullpath, mask );
End;
procedure SyncTwoDirectories(DirectoryOne,DirectoryTwo:String;FileMask:String;FileType:TFileType;SyncMode:TSyncMode;Callback:TProgressCallback);
// -----------------------------------------------------------------------------
// Purpose : Synchronize the contents of two directories
// Parameter : Filemask
// FileType
// SyncMode (syBoth,sySrcToDst,syDstToSrc)
// Result : -
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var vSrcList,vDstList:TFileRecList;
procedure intSwapString(s1,s2:String);
var s3:String;
begin
s3:=s1;
s1:=s2;
s2:=s3;
end;
procedure intSwap(sLst,dLst:TFileRecList);
var i:Integer;
begin
for i:=0 to sLst.Count-1 do
begin
if dLst.GetIndexOfFileNameWOPATH(sLst.GetFileNameWOPATh(i)) = -1 then
ExtCopyFile(ExtAddBackSlash(DirectoryOne)+sLst.GetFileNameWOPATh(i),
ExtAddBackSlash(DirectoryTwo)+sLst.GetFileNameWOPATh(i),False);
if Assigned(Callback) then if not Callback(0,sLst.Count-1,i) then Break;
end;
end;
begin
vSrcList:=TFileRecList.Create;
vDstList:=TFileRecList.Create;
try
vSrcList.ReadFiles(DirectoryOne,FileMask,FileType,srtNone);
vDstList.readFiles(DirectoryTwo,FileMask,FileType,srtNone);
case SyncMode of
syDstToSrc:Begin
intSwap(vDstList,vSrcList);
end;
sySrcToDst:Begin
intSwap(vSrcList,vDstList);
end;
syBoth: Begin
intSwap(vSrcList,vDstList);
intSwapString(DirectoryOne,DirectoryTwo);
intSwap(vDstList,vSrcList);
end;
end;
finally
vSrcList.ClearFileRecList;
vDstList.ClearFileRecList;
vDstList.Free;
vSrcList.Free;
end;
end;
procedure SyncTwoTrees(BaseDirOne,BaseDirTwo:String;FileMask:String;FileType:TFileType;SyncMode:TSyncMode;Callback:TProgressCallback);
// -----------------------------------------------------------------------------
// Purpose : Synchronize the contents of two directory trees
// Parameter : Filemask
// FileType
// SyncMode (syBoth,sySrcToDst,syDstToSrc)
// Result : -
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var vSrcList,vDstList:TStringList;
procedure intSwapString(var s1,s2:String);
var s3:String;
begin
s3:=s1;
s1:=s2;
s2:=s3;
end;
procedure intSwap(SrcList,DstList:TStringList);
var
i:Integer;
bd1,bd2,td:String;
begin
for i:=0 to SrcList.Count-1 do
begin
if Assigned(Callback) then if not Callback(0,SrcList.Count-1,i) then break;
td:='';
bd1:=SrcList.Strings[i];
Delete(bd1,1,Length(BaseDirOne));
bd2:=ExtractFileDir(ExtAddBackSlash(BaseDirTwo)+bd1);
if bd2<>td then begin
if not DirectoryExists(bd2) then begin
ExtCreateDir(bd2);
end;
td:=bd2;
end;
if not FileExists(ExtAddBackSlash(BaseDirTwo)+bd1)
then CopyFile(PChar(SrcList.Strings[i]),PChar(ExtAddBackSlash(BaseDirTwo)+bd1),false);
end;
end;
begin
vSrcList:=TStringList.Create;
vDstList:=TStringList.Create;
try
ScanTreeForFiles(vSrcList,BaseDirOne,FileMask);
ScanTreeForFiles(vDstList,BaseDirTwo,FileMask);
case SyncMode of
syDstToSrc:Begin
// intSwapString(BaseDirOne,BaseDirTwo);
intSwap(vDstList,vSrcList);
// intSwapString(BaseDirOne,BaseDirTwo);
end;
sySrcToDst:Begin
intSwap(vSrcList,vDstList);
end;
syBoth: Begin
intSwap(vSrcList,vDstList);
intSwapString(BaseDirOne,BaseDirTwo);
intSwap(vDstList,vSrcList);
intSwapString(BaseDirOne,BaseDirTwo);
end;
end;
finally
vSrcList.Free;
vDstList.Free;
end;
end;
function ExtAddBackSlash(const Path:String):String;
// -----------------------------------------------------------------------------
// Purpose : Add a '\' to a directory string
// Parameter : Path
// Result : Path +'\'
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if Path<>'' then
begin
if AnsiLastChar(Path)^ <> '\' then
Result := Path + '\'
else
Result := Path;
end else Result := '';
end;
function ExtRemoveBackSlash(const Directory:String):String;
// -----------------------------------------------------------------------------
// Purpose : Removes the last '\' from a directory string
// Parameter : Path
// Result : Path - '\'
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var tDir:String;
begin
tDir:=Directory;
if Directory[Length(Directory)]='\' then Delete(tDir,Length(tDir),1);
result:=tdir;
end;
function ExtFileDirExists (Path:string):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Checks if directory exists
// Parameter : Path
// Result : True if existent, else false
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var E : Integer;
begin
E := SetErrorMode(SEM_FAILCRITICALERRORS);
try
Result := GetFileAttributes(PChar(Path))=FILE_ATTRIBUTE_DIRECTORY; //<> -1;
finally
SetErrorMode(E);
end;
end;
function ExtCreateDir(const Path:String):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Create a directory
// Parameter : Path
// Result : True if succeeded, else false
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var Dir,Dir2,Dir3:String;
i:Integer;
begin
Result:=false;
Dir:=ExtAddBackSlash(Path);
if not DirectoryExists(Path) then
begin
Repeat
if Length(Dir)=0 then Break;
i:=Pos('\',Dir);
Dir3:=Copy(Dir,1,i-1);
Delete(Dir,1,i);
Dir2:=Dir2+Dir3+'\';
if not DirectoryExists(Dir2) then if not CreateDir(Dir2) then
begin
Result:=false;
Exit;
end else Result:=true;
until Pos('\',Dir) =0;
end;
end;
function GetFDrive(Path:string):string;
// -----------------------------------------------------------------------------
// Purpose : Get the drive of the path
// Parameter : Path
// Result : Drive
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if Length(Path)>1 then
result:=Copy(Path,1,2)
else result:='';
end;
function GetFPath(Path:string):string;
// -----------------------------------------------------------------------------
// Purpose : Extract the path like this example : '\TEST\'
// Parameter : Path
// Result : Extracted string
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
if Length(Path)>=3 then
result:=Copy(Path,3,Length(Path)-2)
else result:='';
end;
function IsDriveRemovable(Path:String; var ID:String; var Name:String):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Checks if a drive is a removable device
// Parameter : Path
// Result : True if succeeded, else false
// ID : the Volume-ID
// Name : the Volumename
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var
DriveType:Integer;
VolSer : DWord;
SysFlags : DWord;
MaxLen : DWORD;
Buf : string;
VolName : array[0..255] of char;
begin
Result:=False;
ID:='';
Name:='*';
buf:=GetFDrive(Path)+'\';
DriveType:=GetDriveType(PChar(buf));
// if (DriveType=DRIVE_CDROM) or (DriveType=DRIVE_REMOVABLE)
// then
begin
if GetVolumeInformation(pChar(Buf), VolName, 255,
@VolSer, MaxLen, SysFlags, nil, 0)
then
begin
ID:=IntToStr(VolSer);
Name:=StrPas(VolName);
if Name='' then Name:='*';
Result:=True;
end;
end;
end;
function GetVolumeName(Drive:string):string;
// -----------------------------------------------------------------------------
// Purpose : Get the volumename of a drive
// Parameter : Drive
// Result : Volumename
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var
VolSer : DWord;
SysFlags : DWord;
MaxLen : DWORD;
VolName : array[0..255] of char;
begin
Result:='';
if Length(Drive)>2 then Drive :=GetFDrive(Drive)+'\';
if GetVolumeInformation(pChar(Drive), VolName, 255,
@VolSer, MaxLen, SysFlags, nil, 0)
then
begin
Result:=StrPas(VolName);
end;
end;
function GetVolumeID(Drive:string):Integer;
// -----------------------------------------------------------------------------
// Purpose : Get the volumename of a drive
// Parameter : Drive
// Result : Volumename
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var
VolSer : DWord;
SysFlags : DWord;
MaxLen : DWORD;
VolName : array[0..255] of char;
begin
Result:=0;
if Length(Drive)>2 then Drive :=GetFDrive(Drive)+'\';
if GetVolumeInformation(pChar(Drive), VolName, 255,
@VolSer, MaxLen, SysFlags, nil, 0)
then
begin
Result:=VolSer;
end;
end;
function GetVolumeIDName(Drive:string;var VolumeName:String; var Volume_id:Integer):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Get the volumename of a drive
// Parameter : Drive
// Result : Volumename
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var
VolSer : DWord;
SysFlags : DWord;
MaxLen : DWORD;
VolName : array[0..255] of char;
begin
Result:=False;
if Length(Drive)>2 then Drive :=GetFDrive(Drive)+'\';
if GetVolumeInformation(pChar(Drive), VolName, 255,
@VolSer, MaxLen, SysFlags, nil, 0)
then
begin
Volume_id:=VolSer;
VolumeName:=StrPas(VolName);
Result:=True;
end;
end;
function CutDirectory(Directory : String;MinLength:Integer) : String;
// -----------------------------------------------------------------------------
// Purpose : Cut a directory string ( like : 'C:\..\..\')
// Parameter : Directory
// MinLength
// Result : Cutted string
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
Var
Count : Byte; Drive : String;
NPath : String;
Begin
Result:='';
if Length(Directory)<MinLength then
result :=Directory
else
begin
Count := 0;
Repeat
Count := Count + 1;
Until Directory[Count] = '\';
Drive := Copy(Directory,1, Count);
Count := Length(Directory);
Repeat
Count := Count - 1;
Until Directory[Count] = '\';
NPath := Copy(Directory,Count, Length(Directory)-(Count-1));
If Length(NPath) = 0 Then
Result := Drive
Else
Result := Drive + '..' + NPath;
end;
End;
function CompareDirectory(Path1,Path2:String):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Compare two directorystrings
// Parameter : Path1, Path2
// Result : True if equal
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
result:=false;
if StrComp(
PCHar(
UpperCase(ExtAddBackSlash(Path1))),
PCHar(
UpperCase(ExtAddBackSlash(Path2)))) = 0 then result:=true;
end;
function CompareDirectorySub(Path,SubPath:String):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Check if SubPath is below Path
// Parameter : Path1, Subpath
// Result : True if SubPath below Path
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var s:string;
begin
result:=false;
s:=Copy(SubPath,1,Length(Path));
if StrComp(
PCHar(
UpperCase(ExtAddBackSlash(Path))),
PCHar(
UpperCase(ExtAddBackSlash(s)))) = 0 then result:=true;
end;
//-----------------------
//
// File functions implementation
//
//-----------------------
function SwitchTwoFiles(FileNameOne,FileNameTwo:String):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Swith the filename of two files
// Parameter : FileNameOne FileNameTwo
// Result : True if succeeded
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
Var Mode:Integer;
begin
Result:=false;
if ExtCopyFile(FileNameOne,'~tmp1.tmp',false) then
if ExtCopyFile(FileNameTwo,'~tmp2.tmp',false) then
begin
Mode:=mrAll;
ExtDeleteFile(PChar(FileNameOne),Mode,False);
ExtDeleteFile(PChar(FileNameTwo),Mode,False);
ExtRenameFile('~tmp1.tmp',FileNameTwo);
ExtRenameFile('~tmp2.tmp',FileNameOne);
Result:=true;
end;
end;
function RenameInsertFile(Directory,FileNameOne,FileNameTwo:string;CharToBeAdded:Char):String;
// -----------------------------------------------------------------------------
//
// Purpose : Testing ....
//
// Parameter :
//
// Result :
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var
sList:TFileRecList;
s1,s2,s3:string;
begin
result:='';
if Directory<> GetCurrentDir then if DirectoryExists(Directory) then ChDir(Directory);
sList:=TFileRecList.Create;
try
FileNameOne:=ExtractFileName(FileNameOne);
FileNameTwo:=ExtractFileName(FileNameTwo);
sList.ReadFiles(Directory,'*.*',[ftNormal,ftHidden,ftReadOnly,ftSystem],srtName);
// s1:=Copy(FileNameTwo,1,Pos('.',FileNameTwo)-1);
// s0:=s1;
s2:=sList.GetFileName(sList.GetIndexOfFileName(FileNameTwo)-1);
s2:=Copy(s2,1,Pos('.',s2)-1);
s3:=sList.GetFileName(sList.GetIndexOfFileName(FileNameTwo));
s3:=Copy(s3,1,Pos('.',s3)-1);
if s2='' then s2:=s3;
s1:=s2;
if Length(s2)=Length(s3) then
begin
if s2[Length(s2)]>=s3[Length(s3)] then s1[Length(s1)]:=Chr(Ord(s2[Length(s2)])+1) else
s1:=s1+s1[Length(s1)]+s2[Length(s2)];
While FileExists(ExtAddBackSlash(Directory)+s1+ExtractFileExt(FileNameOne))
do s1:=s1+Chr(Ord(s2[Length(s2)])-1);
end
else if Length(s2)<Length(s3) then
begin
s1[Length(s1)]:=Chr(Ord(s2[Length(s2)])+1);
While FileExists(ExtAddBackSlash(Directory)+s1+ExtractFileExt(FileNameOne))
do s1:=s1+Chr(Ord(s2[Length(s2)]));
end
else begin
s1[Length(s1)]:=Chr(Ord(s2[Length(s2)])+1)
end;
s1:=s1+ExtractFileExt(FileNameOne);
amOvrAll:=8;
ExtRenameFile(FileNameOne,s1);
result:=s1;
finally
sList.ClearFileRecList;
sList.Free;
end;
end;
function ExtCopyFile(const Source, Destination: TFileName;AskForOverwrite:Boolean):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Copy file(s)
// Parameter : Sourcefilename, Destinationfilename
// AskForOverWrite: If false, existing files will be overwritten
// Result : True if succeeded
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
result:=false;
if AnsiCompareFileName(Source, Destination) <> 0 then
begin
if FileExists(Destination) then
begin
if AskForOverWrite then if MessageDlg(Format(msgAskForOverwrite,[Destination]),mtWarning,[mbYes,mbNo],0)
= IDNO then Exit;
FileSetAttr(Destination,0);
DeleteFile(PChar(Destination));
end;
result:=CopyFile(PChar(Source),PChar(Destination),false);
end;
end;
function ExtMoveFile(const Source, Destination: TFileName;AskForOverwrite:Boolean):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Move file(s)
// Parameter : Sourcefilename, Destinationfilename
// AskForOverWrite: If false, existing files will be overwritten
// Result : True if succeeded
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var AttrBuffer:DWORD;
begin
result:=false;
if AnsiCompareFileName(Source, Destination) <> 0 then
begin
if not RenameFile(Source, Destination) then { try just renaming }
begin
AttrBuffer:=FileGetAttr(Source);
if AskForOverWrite then
begin
if (FileGetAttr(Source) and faReadOnly)=faReadOnly then
if amOvrAll=8 then FileSetAttr(Source,0) else
begin
amOvrAll:=MessageDlg(Format(msgAskForMoveReadOnly,[Source]),mtWarning,[mbYes,mbNo,mbAll],0);
if (amOvrAll = IDYES) or (amOvrAll=8) then FileSetAttr(Source,0);
end;
if FileExists(Destination) then
if MessageDlg(Format(msgAskForOverwrite,[Destination]),mtWarning,[mbYes,mbNo],0)
= IDYES then
begin
FileSetAttr(Destination,0);
result:=MoveFile(PChar(Source),PChar(Destination));
if result then FileSetAttr(Destination,AttrBuffer);
end;
end else
begin
if FileExists(Destination) then
begin
if (FileGetAttr(Destination) and faReadOnly)=faReadOnly then FileSetAttr(Destination,0);
DeleteFile(PChar(Destination));
end;
result:=MoveFile(PChar(Source),PChar(Destination));
end;
end else result:=true;
end;
end;
function ExtDeleteFile(const FileName:TFileName;var DeleteMode:Integer;IntoRecycleBin:Boolean):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Delete file(s)
// Parameter : Filename
// DeleteMode (0 or mrAll (8))
// Result : True if succeeded
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
procedure Ask;
begin
DeleteMode:=MessageDlg(Format(msgAskForDelete,[FileName]),
mtConfirmation, [mbYes, mbNo, mbAll], 0);
end;
begin
result:=False;
if DeleteMode<>mrAll then Ask;
if (DeleteMode=mrAll) or (DeleteMode=mrYes) then
if FileExists(FileName) then
begin
if (FileGetAttr(FileName) and faReadOnly)=faReadOnly then
if amOvrAll=8 then FileSetAttr(FileName,0) else
begin
amOvrAll:=MessageDlg(Format(msgAskReadOnly,[FileName]),mtWarning,[mbYes,mbNo,mbAll],0);
if (amOvrAll = IDYES) or (amOvrAll=8) then FileSetAttr(FileName,0);
end;
if IntoRecycleBin then
result:=DeleteToRecycleBin(FileName) else
result:=DeleteFile(PChar(FileName));
end;
end;
function ExtRenameFile(const OldName, NewName: TFileName):Boolean;
// -----------------------------------------------------------------------------
// Purpose : Rename file(s)
// Parameter : OldName, NewName
// Result : True if succeeded
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var AttrBuffer:DWORD;
begin
result:=False;
if FileExists(OldName) and (AnsiCompareFileName(OldName,Newname) <> 0) then
begin
AttrBuffer:=FileGetAttr(Oldname);
if (AttrBuffer and faReadOnly)=faReadOnly then
if amOvrAll=8 then FileSetAttr(OldName,0) else
begin
amOvrAll:=MessageDlg(Format(msgAskForRenameReadOnly,[Oldname]),mtWarning,[mbYes,mbNo,mbAll],0);
if (amOvrAll = IDYES) or (amOvrAll=8) then FileSetAttr(OldName,0);
end;
result:=RenameFile(PChar(OldName),PChar(NewName));
if result then FileSetAttr(NewName,AttrBuffer) else FileSetAttr(Oldname,AttrBuffer);
end;
end;
function ExtGetFileSize(const FileName: string): LongInt;
// -----------------------------------------------------------------------------
// Purpose : Get the Filesize
// Parameter : Filename
// Result : Filesize in bytes
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var
SearchRec: TSearchRec;
begin
if FindFirst(ExpandFileName(FileName), faAnyFile, SearchRec) = 0 then
Result := SearchRec.Size
else Result := -1;
end;
function ExtFileDateTime(const FileName: string): System.TDateTime;
// -----------------------------------------------------------------------------
// Purpose : Get the Filedate
// Parameter : Filename
// Result : Filesize as TDateTime
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
Result := FileDateToDateTime(FileAge(FileName));
end;
function ExtHasAttr(const FileName: string; Attr: Word): Boolean;
// -----------------------------------------------------------------------------
// Purpose : Check if file has attribute(s)
// Parameter : Filename
// Result : True if file has the attribute(s)
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
begin
Result := (FileGetAttr(FileName) and Attr) = Attr;
end;
function ExtExecuteFile(const FileName, Params, DefaultDir: string;
ShowCmd: Integer): THandle;
// -----------------------------------------------------------------------------
// Purpose : Execute File
// Parameter : Filename , Params, Default directory
// Result : Handle of process
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
//var
// zFileName, zParams, zDir: array[0..79] of Char;
begin
Result:=0;
{Result := ShellExecute(Application.MainForm.Handle, nil,
StrPCopy(zFileName, FileName), StrPCopy(zParams, Params),
StrPCopy(zDir, DefaultDir), ShowCmd);}
end;
//-----------------------
//
// Misc functions implementation
//
//-----------------------
function ExtFillUpWithZero(Number:Integer;Digits:Integer):String;
// -----------------------------------------------------------------------------
// Purpose : Convert a Integer to string and fill up with n x NULL
// (e.g. 123 -> '000123')
// Parameter : Number, Digits
// Result : Resultstring
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var t,n:String;
i:Integer;
begin
result:='';
n:='';
t:=IntToStr(Number);
if Length(t)< Digits then
begin
for i:=Length(t) to Digits-1 do n:=n+'0';
result:=ConCat(n,t);
end
else if Length(t)=Digits then result:=t;
end;
//-----------------------
//
// CRC functions implementation
//
//-----------------------
procedure MakeCRCTable;
// -----------------------------------------------------------------------------
// Purpose : Create CRC table
// Parameter : -
// Result : -
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var ii,jj:Integer;
begin
if not crc32tablecreated then
begin
crc32tablecreated:=True;
for ii := 0 to 256-1 do
begin
crc_table [ii] := ii ;
for jj := 0 to 8-1 do
begin
if ((crc_table [ii] and 1) = 0)
then crc_table [ii]:= crc_table [ii] shr 1
else
crc_table [ii] := $EDB88320 xor (crc_table [ii] shr 1) ;
end;
end;
end;
end;
function CRC32 (crc:longint;buffer:PByteArray;length:Integer):DWord;
// -----------------------------------------------------------------------------
// Purpose : CRC32 sub function
// Parameter : internal used
// Result : internal used
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var ii:Integer;
c:LongInt;
begin
if not crc32tablecreated then MakeCRCTable;
c:=crc;
for ii := 0 to length-1 do
c:=(c shr 8) xor crc_table[buffer[ii] xor (c and $ff)];
result:= c;
end;
function CRC32File (FileName: string):DWord;
// -----------------------------------------------------------------------------
// Purpose : Create the CRC32 of a file
// Parameter : Filename
// Result : CRC32
//
// (c) July 1999 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
var
BytesRead: INTEGER;
CRC32Val: DWORD;
CRCStream :TFileStream;
ByteArray: Array [0..1023] of Byte;
begin
if not crc32tablecreated then MakeCRCTable;
if FileExists(FileName) then
begin
CRCStream:=TFileStream.Create(FileName,fmOpenRead);
try
CRC32Val := $FFFFFFFF;
repeat
ZeroMemory(@ByteArray,SizeOf(ByteArray));
BytesRead:=CRCStream.Read(ByteArray,SizeOf(ByteArray));
if BytesRead > 0
then begin
CRC32Val:=CRC32 (CRC32Val,@ByteArray,BytesRead);
end;
until BytesRead = 0;
CRC32Val := not CRC32Val;
finally
CRCStream.Free;
end;
result:=CRC32Val;
end else result:=0;
end;
function DeleteToRecycleBin(Filename:String):Boolean;
Var T:TSHFileOpStruct;
begin
FillChar( T, SizeOf( T ), 0 );
With T do
Begin
Wnd:=Application.MainForm.Handle;
wFunc:=FO_DELETE;
pFrom:=Pchar(Filename+#0#0);
fFlags:=FOF_ALLOWUNDO+FOF_NOCONFIRMATION;
End;
result:= true ;
SHFileOperation(T);
end;
procedure ClearStringListWObjects(List:TSTringList);
var i:Integer;
begin
if List.Count>0 then for i:=List.Count-1 downto 0
do
if Assigned(List.Objects[i]) then
// if fSelList.Objects[i] is TExtInfo then
try
List.Objects[i].Free;
finally
List.Objects[i]:=nil;
end;
List.Clear;
end;
function GetLastPathPart(Path:string):string;
var idx:Integer;
begin
Path:=ExtRemoveBackSlash(Path);
result:='';
while True do
begin
idx:=Pos('\',Path);
if idx >0 then
Delete(Path,1,idx)
else
begin
Result:=Path;
break;
end;
end;
end;
function DeleteLastPathPart(Path:string):string;
var idx:Integer;
buf:string;
begin
Path:=ExtRemoveBackSlash(Path);
result:='';
while True do
begin
idx:=Pos('\',Path);
if idx >0 then
begin
buf:=buf+Copy(Path,1,idx);
Delete(Path,1,idx);
end
else
begin
Result:=buf;
break;
end;
end;
end;
function ExtGetTempFileName(Prefix,AlternatePath:String):string;
var Path:Array [0..255] of Byte;
FileName:Array [0..255] of Byte;
BufferLength:DWORD;
r:UINT;
begin
if GetTempPath(BufferLength,@Path) = 0 then
begin
r:=GetTempFileName(@PAth,PChar(Prefix),0,@FileName);
end
else
r:=GetTempFileName(PChar(AlternatePath),PChar(Prefix),0,@FileName);
//if r =0 then result:='' else result := StrPas(@FileName);
if r =0 then result:='' else result := PWideChar(@FileName);
end;
function ExtGetTempPath:string;
begin
end;
procedure GetDriveInfo;
var
__buf:array [0..30*4] of Char;
__r,__i,__j:Integer;
__st:string;
E:Integer;
begin
for __i:=0 to 30*4 do __buf[__i]:=CHar(32);
__r:=GetLogicalDriveStrings(30*4,@__buf);
__j:=0;
E:=SetErrorMode(SEM_FAILCRITICALERRORS);
for __i:=0 to __r div 4
do begin
drive_table[__j].Drive:=UpperCase(__buf[4*__i]+__buf[4*__i+1]);
if (drive_table[__j].Drive<>'A:') and (drive_table[__j].Drive<>'B:')
then
begin
drive_table[__j].Volume_ID:=GetVolumeID(drive_table[__j].Drive);
drive_table[__j].Volume_Name:=GetVolumeName(drive_table[__j].Drive);
end;
inc(__j);
end;
drive_table_count:=__j;
SetErrorMode(E);
end;
function IsVolumeAvailable(Volume_Name:String):Boolean;
var i:Integer;
begin
result:=false;
for i:=0 to drive_table_count-1 do
if AnsiCompareText(Volume_Name,drive_table[i].Volume_Name)=0 then result:=true;
end;
procedure RetrieveDriveInfo(Drive:Char);
var i:Integer;
begin
for i:=0 to drive_table_count-1 do
if drive_table[i].Drive[1]=Drive then
begin
drive_table[i].Volume_ID:=GetVolumeID(drive_table[i].Drive);
drive_table[i].Volume_Name:=GetVolumeName(drive_table[i].Drive);
break;
end;
end;
end.
|
unit Mant_TipoGestion;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Ventana3, Vcl.ComCtrls, Vcl.ExtCtrls,
Vcl.StdCtrls, Vcl.Buttons, Data.DB, Vcl.Grids, Vcl.DBGrids, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.Mask, Vcl.DBCtrls, FireDAC.Stan.Async, FireDAC.DApt;
type
TfrmTipoGestion = class(TfrmVentana)
Panel1: TPanel;
Panel2: TPanel;
Splitter1: TSplitter;
Panel17: TPanel;
Image2: TImage;
sb_gestion_nueva: TSpeedButton;
sb_gestion_salvar: TSpeedButton;
sb_gestion_unDo: TSpeedButton;
sb_gestion_Editar: TSpeedButton;
grp_gestion: TGroupBox;
DBGrid1: TDBGrid;
dts_tipoGestiones: TDataSource;
mt_tipogestion: TFDMemTable;
Descripcion: TDBEdit;
dts_mtipogestion: TDataSource;
Label2: TLabel;
mt_tipogestionid_tipo: TFDAutoIncField;
mt_tipogestiondescripcion: TStringField;
mt_tipogestionarea: TIntegerField;
mt_tipogestionguid: TStringField;
mt_tipogestionactiva: TBooleanField;
DBCheckBox1: TDBCheckBox;
dts_areas: TDataSource;
dbl_area: TDBLookupComboBox;
Label4: TLabel;
ActualizarGestion: TFDQuery;
ActualizarGestionid_tipo: TFDAutoIncField;
ActualizarGestiondescripcion: TStringField;
ActualizarGestionactiva: TBooleanField;
ActualizarGestionarea: TIntegerField;
ActualizarGestionguid: TStringField;
Label1: TLabel;
DBEdit1: TDBEdit;
procedure FormShow(Sender: TObject);
procedure cargargestion;
Procedure CargarGestiones;
procedure dts_tipoGestionesDataChange(Sender: TObject; Field: TField);
procedure sb_gestion_nuevaClick(Sender: TObject);
procedure sb_gestion_EditarClick(Sender: TObject);
procedure sb_gestion_salvarClick(Sender: TObject);
procedure sb_gestion_unDoClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmTipoGestion: TfrmTipoGestion;
implementation
{$R *.dfm}
uses dm;
procedure TfrmTipoGestion.cargargestion;
Var
i : integer;
begin
//---
mt_tipoGestion.Close;
mt_tipogestion.Open;
mt_tipogestion.Append;
for I := 0 to dm1.tipoGestiones.FieldCount -1 do
begin
mt_tipogestion.Fields[i].Value := dm1.tipoGestiones.fields[i].Value;
end;
sb_gestion_nueva.Enabled := true;
sb_gestion_Editar.Enabled := False;
grp_gestion.Enabled := false;
mt_tipogestion .first;
if not mt_tipogestion.Eof then
sb_gestion_Editar.Enabled := true;
end;
procedure TfrmTipoGestion.CargarGestiones;
begin
dm1.tipoGestiones.Close;
dm1.tipoGestiones.Open();
end;
procedure TfrmTipoGestion.dts_tipoGestionesDataChange(Sender: TObject;
Field: TField);
begin
inherited;
cargargestion;
sb_gestion_nueva.Enabled := true;
sb_gestion_Editar.Enabled := false;
if not mt_tipogestion.eof then
sb_gestion_Editar.Enabled := true;
sb_gestion_salvar.Enabled := false;
sb_gestion_unDo.Enabled:= false;
grp_gestion.Enabled := false;
end;
procedure TfrmTipoGestion.FormShow(Sender: TObject);
begin
inherited;
cargarGestiones;
//-- asi esta bien
//--- ahora hace falta hacer el llamdo desde el menu ... que esta en el formulario principal (sIB)
dm1.areas.Close;
dm1.areas.Open();
end;
procedure TfrmTipoGestion.sb_gestion_EditarClick(Sender: TObject);
begin
inherited;
sb_gestion_salvar.Enabled := true;
sb_gestion_unDo.Enabled:= true;
sb_gestion_Editar.Enabled:= false;
sb_gestion_nueva.Enabled:= false;
mt_tipogestion.First;
if not mt_tipogestion.eof then
begin
mt_tipogestion.Edit;
grp_gestion.Enabled := True;
Descripcion.SetFocus;
end
else
grp_gestion.Enabled := False;
end;
procedure TfrmTipoGestion.sb_gestion_nuevaClick(Sender: TObject);
begin
inherited;
mt_tipogestion.Close;
mt_tipogestion.Open;
mt_tipogestion.Append;
sb_gestion_salvar.Enabled := true;
sb_gestion_unDo.Enabled:= true;
sb_gestion_nueva.Enabled:= false;
sb_gestion_Editar.Enabled := false;
grp_gestion.Enabled := True;
Descripcion.SetFocus;
end;
procedure TfrmTipoGestion.sb_gestion_salvarClick(Sender: TObject);
var
i : integer;
MyClass: TComponent;
_continuar : Boolean;
_guid : String;
begin
inherited;
sb_gestion_Editar.Enabled := true;
sb_gestion_nueva.Enabled:= true;
sb_gestion_salvar.Enabled := false;
sb_gestion_unDo.Enabled:= false;
_Continuar := true;
//--- Validacion de rol
//----
if not dm1.sib.InTransaction then
dm1.sib.StartTransaction ;
//---
if mt_tipogestion.State = dsInsert then
begin
_guid := dm1._guid ;
mt_tipogestion.Post;
ActualizarGestion.Close;
ActualizarGestion.Open;
ActualizarGestion.Append;
end
Else
if mt_tipoGestion.State = dsEdit then //---Modo de edicion
Begin
mt_tipogestion.Post;
ActualizarGestion.Close;
ActualizarGestion.Params [0].AsInteger := mt_tipogestionid_tipo.AsInteger ;
ActualizarGestion.Open();
ActualizarGestion.First;
if ActualizarGestion.eof then
Begin
ActualizarGestion.close;
_continuar := False;
End
Else
Begin
if ActualizarGestionguid.AsString = '' then
_guid := dm1._guid
else
_guid := ActualizarGestionguid.AsString ;
ActualizarGestion.edit;
End;
End
Else
_Continuar := False;
if _Continuar then
Begin
try
For I := 1 to mt_tipogestion.FieldCount -1 do
Begin
ActualizarGestion.Fields[i].Value := mt_tipogestion.Fields[i].Value ;
End;
ActualizarGestionguid.AsString := _guid ;
ActualizarGestion.Post;
dm1.sib.Commit;
CargarGestiones;
dm1.tipoGestiones.Locate('guid',_guid);
cargarGestion;
Except
on e:exception do
Begin
ShowMessage('Error al insertar tipo de Gestion...'+e.Message );
dm1.sib.Rollback ;
End;
end;
End;
end;
procedure TfrmTipoGestion.sb_gestion_unDoClick(Sender: TObject);
begin
inherited;
cargargestion ;
sb_gestion_Editar.Enabled := true;
sb_gestion_nueva.Enabled:= true;
sb_gestion_salvar.Enabled := false;
sb_gestion_unDo.Enabled:= false;
end;
end.
|
unit xSortAction;
interface
uses xDBActionBase, xSortInfo, System.Classes, System.SysUtils, FireDAC.Stan.Param,
xFunction;
type
TSortAction = class(TDBActionBase)
public
/// <summary>
/// 获取最大编号
/// </summary>
function GetMaxSN : Integer;
/// <summary>
/// 添加题库
/// </summary>
procedure AddSort(ASort : TSortInfo);
/// <summary>
/// 删除题库
/// </summary>
procedure DelSort(nSortID: Integer); overload;
procedure DelSort(ASort : TSortInfo); overload;
/// <summary>
/// 修改题库
/// </summary>
procedure EditSort(ASort : TSortInfo);
/// <summary>
/// 清空题库
/// </summary>
procedure ClearSort;
/// <summary>
/// 加载题库
/// </summary>
procedure LoadSort(slList :TStringList);
end;
implementation
{ TSortAction }
procedure TSortAction.AddSort(ASort: TSortInfo);
const
C_SQL = 'insert into SortInfo ( SortID, SortName, SortRemark' +
') values ( %d, :SortName, :SortRemark )';
begin
if Assigned(ASort) then
begin
with ASort, FQuery.Params do
begin
FQuery.Sql.Text := Format( C_SQL, [ Sortid ] );
ParamByName( 'SortName' ).Value := Sortname ;
ParamByName( 'SortRemark' ).Value := Sortremark;
end;
ExecSQL;
end;
end;
procedure TSortAction.ClearSort;
begin
FQuery.Sql.Text := 'delete from SortInfo';
ExecSQL;
end;
procedure TSortAction.DelSort(ASort: TSortInfo);
begin
if Assigned(ASort) then
begin
DelSort(ASort.SortID);
end;
end;
procedure TSortAction.DelSort(nSortID: Integer);
const
C_SQL = 'delete from SortInfo where SortID = %d';
begin
FQuery.Sql.Text := Format( C_SQL, [ nSortID ] );
ExecSQL;
end;
procedure TSortAction.EditSort(ASort: TSortInfo);
const
C_SQL = 'update SortInfo set SortName = :SortName,' +
'SortRemark = :SortRemark where SortID = %d';
begin
if Assigned(ASort) then
begin
with ASort, FQuery.Params do
begin
FQuery.Sql.Text := Format( C_SQL, [ Sortid ] );
ParamByName( 'SortName' ).Value := Sortname ;
ParamByName( 'SortRemark' ).Value := Sortremark;
end;
ExecSQL;
end;
end;
function TSortAction.GetMaxSN: Integer;
const
C_SQL = 'select max(SortID) as MaxSN from SortInfo';
begin
FQuery.Open(C_SQL);
if FQuery.RecordCount = 1 then
Result := FQuery.FieldByName('MaxSN').AsInteger
else
Result := 0;
FQuery.Close;
end;
procedure TSortAction.LoadSort(slList: TStringList);
var
ASortInfo : TSortInfo;
begin
if Assigned(slList) then
begin
ClearStringList(slList);
FQuery.Open('select * from SortInfo');
while not FQuery.Eof do
begin
ASortInfo := TSortInfo.Create;
with ASortInfo, FQuery do
begin
Sortid := FieldByName( 'SortID' ).AsInteger;
Sortname := FieldByName( 'SortName' ).AsString;
Sortremark := FieldByName( 'SortRemark' ).AsString;
end;
slList.AddObject('', ASortInfo);
FQuery.Next;
end;
FQuery.Close;
end;
end;
end.
|
{$R-,S-,I-}
unit DrawPics;
(* A unit to load graphical pictures *)
(* Formats supported : *)
(* BSAVE Pic Format 320 x 200 x 004 *)
(* PC/Microsoft Paintbrush .PCX files : 320 x 200 x 004 *)
(* PC/Microsoft Paintbrush .PCX files : 640 x 350 x 016 *)
(* PC/Microsoft Paintbrush .PCX files : 320 x 200 x 256 *)
interface
const
PaletteExt : string[04] = '.PAL'; {palette file extension}
type
DrawError = (NoError, IOError, BadFormat, PaletteMissing);
var
LastDrawMode : Word;
function FindLastDrawMode : Word;
{ DOS call 10, 0F; Read Video Mode }
inline($B4/$0F/ { MOV AH, 0F }
$CD/$10/ { INT 10 }
$24/$7F/ { AND AL, 7F -- mask high bit set by EGA}
$30/$E4); { XOR AH, AH -- pass back only AL}
procedure DrawMode(ModeNum : Word);
function DrawPic(FileName : string) : DrawError;
(*-------------------------------------------------------------------------*)
implementation
procedure SetDrawMode(ModeNum : Word);
{ DOS call 10, 00; Set Video Mode }
inline($58/ { POP AX -- Put ModeNum in AX }
$B4/$00/ { MOV AH, 00 }
$CD/$10); { INT 10 }
procedure DrawMode(ModeNum : Word);
begin
if LastDrawMode <> ModeNum then begin
SetDrawMode(ModeNum);
LastDrawMode := FindLastDrawMode;
end;
end;
{.PA}
function MapsSelected : Byte;
{ Returns the number of bit planes enabled for writing }
const
EgaBase = $A000; { Base address of EGA graphics memory }
AddrReg = $3CE; { Port address of EGA graphics 1 & 2 address register }
SetResetReg = $3CF; { Port address of EGA Set/Reset register }
ReadMapReg = $04; { Index of EGA Read Map select register }
var
BitMap : Integer;
MemByte : Byte;
EnabledPlanes : Byte;
begin
EnabledPlanes := 0;
Port[AddrReg] := ReadMapReg;
for BitMap := 0 to 3 do
begin
Port[SetResetReg] := BitMap;
MemByte := Mem[EgaBase:0000]; { Read a dummy byte from bit plane }
Mem[EgaBase:0000] := not(MemByte); { Write the byte back inverted }
if Mem[EgaBase:0000] <> MemByte then { This plane is selected }
begin
EnabledPlanes := EnabledPlanes or (1 shl BitMap);
Mem[EgaBase:0000] := MemByte; { Reset original byte read }
end;
end;
MapsSelected := EnabledPlanes;
end;
procedure WriteToEGAScreen(BitMap : Integer; Address : Pointer;
From : Pointer; Reps : Word);
const
SeqAddrReg = $3C4; { Port address of EGA sequencer address register }
ResetReg = $3C5; { Port address of EGA sequencer reset register }
MapMaskReg = $02; { Index of EGA sequencer Map Mask register }
var
MapsEnabled : Byte;
begin
MapsEnabled := MapsSelected; { Save originally selected write planes }
{ Enables writing to one of the EGA's Bit planes 1..4 }
Port[SeqAddrReg] := MapMaskReg;
Port[ResetReg] := 1 shl Pred(BitMap);
Move(From^, Address^, Reps);
Port[ResetReg] := MapsEnabled; { Restore originally selected write planes }
end;
{.PA}
function Draw_BSAVE_Format(FileName : string) : Boolean;
type
PICHdr = string[7];
const
Picval : PICHdr = #$FD#$00#$B8#$00#$00#$00#$40;
var
fp : file;
Picheader : PICHdr;
actually_read : Integer;
CGABuf : Byte absolute $B800 : $0000; {screen location for CGA}
begin
Draw_BSAVE_Format := False;
Assign(fp, FileName);
Reset(fp, 1);
if IoResult <> 0 then Exit;
Picheader[0] := #7;
BlockRead(fp, Picheader[1], 7, actually_read);
if Picheader = Picval then begin
Draw_BSAVE_Format := True;
DrawMode($04);
BlockRead(fp, CGABuf, 16384, actually_read);
end;
Close(fp);
end;
{.PA}
const
inbuf = 16384; {amount to read at a time}
type
PCXtypes = (idunno, cga, t320x200x256, ega);
PCXHdr = record
manufacturer : Byte;
version : Byte;
encode_mode : Byte;
bits_per_pixel : Byte;
start_x : Word;
start_y : Word;
end_x : Word;
end_y : Word;
x_resolution : Word;
y_resolution : Word;
palette_RGB : array[1..48] of Byte;
vmode : Byte; {ignored}
planes : Byte;
bytes_per_line : Word;
unused : array[1..60] of Byte;
end;
BigArray = array[0..MaxInt] of Byte;
var
ABuf : BigArray absolute $A000 : $0000; {screen location for EGA}
CGABuf : BigArray absolute $B800 : $0000; {screen location for CGA}
fp : file;
hold : array[1..inbuf] of Byte;
athold : Word;
filebytes : LongInt;
header : PCXHdr;
{.PA}
procedure encget(var inbyte : Byte; var Reps : Word);
var
actually_read : Integer;
begin
Inc(athold);
Dec(filebytes);
if athold > inbuf then begin
BlockRead(fp, hold, inbuf, actually_read);
athold := 1;
end;
{ $c0 masks first two bytes for 11xxxxxx --- $c0 = ($c0 and hold[athold])}
if hold[athold] >= $c0 then begin
{ $3f masks last five bytes for xxx11111 }
Reps := $3f and hold[athold];
Inc(athold);
Dec(filebytes);
if athold > inbuf then begin
BlockRead(fp, hold, inbuf, actually_read);
athold := 1;
end;
end
else
Reps := 1;
inbyte := hold[athold];
end;
{.PA}
procedure ReadPaint(readtype : PCXtypes);
const
DrawAt : array[1..4] of Word = (0, 80, 160, 240);
var
byte_cnt : Integer;
ScanCount : Word;
ScanEven : Boolean;
Startat : Word;
Reps : Word;
data : Byte;
EGARow : array[0..639] of Byte;
BitPlane : Word;
begin
athold := inbuf;
byte_cnt := 0;
ScanCount := 0;
ScanEven := True;
Startat := $0000;
BitPlane := 1;
while filebytes > 0 do begin
encget(data, Reps);
case readtype of
t320x200x256 :
begin {this section for 256 color 320x200}
FillChar(ABuf[byte_cnt], Reps, data);
Inc(byte_cnt, Reps);
end;
ega :
begin {this section for 16 color 640x350}
FillChar(EGARow[byte_cnt], Reps, data);
Inc(byte_cnt, Reps);
{ see if we have filled a row; THEN write it }
if (byte_cnt >= 320) or (filebytes = 0) then begin
for BitPlane := 1 to 4 do
WriteToEGAScreen(BitPlane, @ABuf[Startat], @EGARow[DrawAt[BitPlane]], 80);
Dec(byte_cnt, 320);
if byte_cnt > 0 then Move(EGARow[320], EGARow[0], byte_cnt);
Inc(Startat, 80);
end;
end;
cga :
begin {this section for CGA}
FillChar(CGABuf[Startat+byte_cnt], Reps, data);
Inc(byte_cnt, Reps);
{ see if we have filled a row }
if byte_cnt = 80 then begin
byte_cnt := 0;
ScanEven := not ScanEven;
if ScanEven then begin
Inc(ScanCount, 80);
Startat := $0000+ScanCount;
end
else
Startat := $2000+ScanCount;
end
end;
end;
end;
end;
{.PA}
procedure SetPaletteBlock(SegBlock, OfsBlock : Word);
{ DOS Call 10, 10, 12 -- Set Block of Color Registers }
inline($B8/$12/$10/ { MOV AX, $1012 }
$BB/$00/$00/ { MOV BX, 0 -- first register to set }
$B9/$00/$01/ { MOV CX, 256 -- # registers to set }
$5A/ { POP DX -- offset of block }
$07/ { POP ES -- segment of block }
$CD/$10); { INT 10 }
function ChangePalette256(PaletteName : string) : DrawError;
type
ColorType = record
Rvalue : Byte;
Gvalue : Byte;
Bvalue : Byte;
end;
PaletteType = array[0..255] of ColorType;
var
PalTable : PaletteType;
Pfile : file of PaletteType;
PeriodAt : Byte;
begin
ChangePalette256 := NoError;
PeriodAt := Pos('.', PaletteName);
if PeriodAt > 0 then PaletteName[0] := Chr(Pred(PeriodAt));
PaletteName := PaletteName+PaletteExt;
Assign(Pfile, PaletteName);
Reset(Pfile);
if IoResult = 0 then begin
Read(Pfile, PalTable);
Close(Pfile);
SetPaletteBlock(Seg(PalTable), Ofs(PalTable));
end
else ChangePalette256 := PaletteMissing;
end;
{.PA}
procedure SetEGAColor(SetColor : Word);
{ DOS Call 10, 10, 00 -- Set Color Register }
inline($B8/$00/$10/ { MOV AX, $1000 }
$5B/ { POP BX -- BL: color, BH: value }
$CD/$10); { INT 10 }
procedure ChangePaletteEGA;
const
SetBit1 = 32;
SetBit2 = 4;
SetBits = 36;
type
BxReg = record bl : Byte; bh : Byte; end;
var
Count : Byte;
SubCount : Word;
S : BxReg;
SetColor : Word absolute S;
begin
Count := 0;
repeat
S.bl := Count div 3; {bl is color number 0-15}
S.bh := 0; {bh is color value 0 to 63}
{set Red (32,4), Green (16,2), or Blue (8,1)}
for SubCount := 0 to 2 do begin
Inc(Count);
case header.palette_RGB[Count] of
0 : S.bh := S.bh or 0;
85 : S.bh := S.bh or (SetBit1 shr SubCount);
170 : S.bh := S.bh or (SetBit2 shr SubCount);
255 : S.bh := S.bh or (SetBits shr SubCount);
end;
end;
SetEGAColor(SetColor);
until Count = 48;
end;
{.PA}
function DrawPic(FileName : string) : DrawError;
var
PCXtype : PCXtypes;
Result : DrawError;
actually_read : Integer;
begin
DrawPic := NoError;
Result := NoError;
if Draw_BSAVE_Format(FileName) then Exit;
Assign(fp, FileName);
Reset(fp, 1);
if IoResult <> 0 then Result := IOError;
filebytes := FileSize(fp);
Dec(filebytes, 128);
BlockRead(fp, header, 128, actually_read);
{Determine PCX type}
PCXtype := idunno;
if header.manufacturer = $0A then
case header.bits_per_pixel of
8 : PCXtype := t320x200x256;
2 : PCXtype := cga;
1 : PCXtype := ega;
end;
case PCXtype of
idunno : Result := BadFormat;
t320x200x256 : begin
DrawMode($13);
Result := ChangePalette256(FileName);
end;
cga : DrawMode($04);
ega : begin
DrawMode($10);
ChangePaletteEGA;
end;
end;
if Result = NoError then ReadPaint(PCXtype);
Close(fp);
if IoResult <> 0 then Result := IOError;
DrawPic := Result;
end;
begin
LastDrawMode := FindLastDrawMode;
end.
|
{
Minimum Average Weight Cycle
Karp Algorithm O(N3)
Input:
G: Directed weighted simple connected graph (No Edge = Infinity)
N: Number of vertices
Output:
MAW: Average weight of minimum cycle
CycleLen: Length of cycle
Cycle: Vertices of cycle
NoAnswer: Graph does not have directed cycle (NoAnswer->MAW = Infinity)
Note:
G should be connected
Reference:
CLR
By Behdad
}
program
MinimumAverageWeightCycle;
const
MaxN = 100 + 2;
Infinity = 10000;
var
N: Integer;
G, P, Ans: array [0 .. MaxN, 0 .. MaxN] of Integer;
MAW : Extended;
CycleLen: Integer;
Cycle: array [1 .. MaxN] of Integer;
NoAnswer : Boolean;
procedure MAWC;
var
I, J, K, Q, L : Integer;
S: Integer;
T, T2: Extended;
Flag : Boolean;
begin
for I := 0 to N do
for J := 0 to N do
P[I, J] := Infinity;
S := 1;
P[S, 0] := 0;
Ans[S, 0] := S;
L := 0;
repeat
Inc(L);
Flag := True;
for I := 1 to N do
for J := 1 to N do
if (G[I, J] < Infinity) and (G[I, J] + P[I, L - 1] < P[J, L]) then
begin
P[J, L] := G[I, J] + P[I, L - 1];
Ans[J, L] := I;
Flag := False;
end;
until (L = N) or Flag;
MAW := Infinity;
for I := 1 to N do
if (P[I, N] < Infinity) then
begin
T2 := (P[I, N] - P[I, 0]) / N;
if P[I, 0] >= Infinity then
T2 := 0;
L := 0;
for J := 1 to N - 1 do
if P[I, J] < Infinity then
begin
T := (P[I, N] - P[I, J]) / (N - J);
if T > T2 then
begin
T2 := T;
L := J;
end;
end;
if T2 < MAW then
begin
MAW := T2;
Q := I;
end;
end;
FillChar(G[0], SizeOf(G[0]), 0);
K := Q;
I := 0;
L := N;
J := N;
while J >= 0 do
begin
if G[0, K] = 1 then
begin
I := K;
Break;
end;
G[0, K] := 1;
K := Ans[K, J];
Dec(J);
end;
if I <> 0 then
begin
K := Q;
while K <> I do
begin
K := Ans[K, L];
Dec(L);
end;
end;
CycleLen := 0;
NoAnswer := MAW >= Infinity;
if not NoAnswer and (I <> 0) then
begin
J := 1;
T := 0;
repeat
G[J, 0] := K;
Inc(J);
K := Ans[K, L];
Dec(L);
until K = I;
G[J, 0] := G[1, 0];
for I := J downto 2 do
begin
Inc(CycleLen);
Cycle[CycleLen] := G[I, 0];
end;
end;
end;
begin
MAWC;
end.
|
unit FC.Trade.Trader.TRSIMA.M15;
{$I Compiler.inc}
interface
uses
Classes, Math,Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions,
StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators,
Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage,
StockChart.Definitions.Drawing,Graphics;
type
IStockTraderTRSIMA_M15 = interface
['{1D9D4481-8715-428F-A8D3-731B610EF67A}']
end;
TStockTraderTRSIMA_M15 = class (TStockTraderBase,IStockTraderTRSIMA_M15)
private
FRSI_M1_Black: ISCIndicatorTRSIMA;
FRSI_M1_Blue: ISCIndicatorTRSIMA;
FRSI_M1_Pink: ISCIndicatorTRSIMA;
FRSI_M15_Black: ISCIndicatorTRSIMA;
FRSI_M15_Blue: ISCIndicatorTRSIMA;
FRSI_M15_Pink: ISCIndicatorTRSIMA;
FRSI_H1_Black: ISCIndicatorTRSIMA;
FRSI_H1_Blue: ISCIndicatorTRSIMA;
FRSI_H1_Pink: ISCIndicatorTRSIMA;
FRSI_H4_Black: ISCIndicatorTRSIMA;
FRSI_H4_Blue: ISCIndicatorTRSIMA;
FRSI_H4_Pink: ISCIndicatorTRSIMA;
FRSI_D1_Black: ISCIndicatorTRSIMA;
FRSI_D1_Blue: ISCIndicatorTRSIMA;
FRSI_D1_Pink: ISCIndicatorTRSIMA;
FLastOrderM15Index: integer;
FSkipM15Index : integer;
FOrderBuyM15Signals: integer;
FOrderSellM15Signals: integer;
FLastUpdateTime : TDateTime;
FPropIncreateOrdersOnLoss : TPropertyYesNo;
protected
function Spread: TSCRealNumber;
function ToPrice(aPoints: integer): TSCRealNumber;
procedure AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); overload;
procedure AddMessageAndSetMark(const aMarkType: TSCChartMarkKind; const aMessage: string; aMessageColor: TColor=clDefault);overload;
procedure SetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string);
function GetRecommendedLots: TStockOrderLots; override;
procedure Calculate(const aTime: TDateTime);
public
procedure SetProject(const aValue : IStockProject); override;
procedure OnBeginWorkSession; override;
function GetSignals(const aRSI_Black: ISCIndicatorTRSIMA; aRSI_Blue: ISCIndicatorTRSIMA; aRSI_Pink: ISCIndicatorTRSIMA; aIndex: integer; aShowAlerts: boolean; out aRSIChangedBlack,aRSIChangedBlue,aRSIChangedPink: boolean): integer;
//Посчитать
procedure UpdateStep2(const aTime: TDateTime); override;
constructor Create; override;
destructor Destroy; override;
procedure Dispose; override;
end;
implementation
uses Variants,DateUtils, SystemService, Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message,
StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory,
FC.DataUtils;
{ TStockTraderTRSIMA_M15 }
procedure TStockTraderTRSIMA_M15.AddMessageAndSetMark(const aMarkType: TSCChartMarkKind; const aMessage: string;
aMessageColor: TColor);
begin
GetBroker.AddMessage(aMessage,aMessageColor);
AddMarkToCharts(GetBroker.GetCurrentTime,
GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid),
aMarkType,aMessage);
end;
constructor TStockTraderTRSIMA_M15.Create;
begin
inherited Create;
FPropIncreateOrdersOnLoss := TPropertyYesNo.Create('Lots\Dynamic','Increase on Loss',self);
FPropIncreateOrdersOnLoss.Value:=False;
RegisterProperties([FPropIncreateOrdersOnLoss]);
// UnRegisterProperties([PropTrailingStop,PropTrailingStopDescend,PropMinimizationRiskType]);
end;
destructor TStockTraderTRSIMA_M15.Destroy;
begin
inherited;
end;
procedure TStockTraderTRSIMA_M15.Dispose;
begin
inherited;
FreeAndNil(FPropIncreateOrdersOnLoss);
end;
procedure TStockTraderTRSIMA_M15.OnBeginWorkSession;
begin
inherited;
FLastOrderM15Index:=0;
FSkipM15Index:=0;
FLastUpdateTime:=0;
FOrderBuyM15Signals:=0;
FOrderSellM15Signals:=0;
end;
procedure TStockTraderTRSIMA_M15.SetMark(const aOrder: IStockOrder;const aMarkType: TSCChartMarkKind; const aMessage: string);
begin
AddMarkToCharts(GetBroker.GetCurrentTime,
GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid),
aMarkType,aMessage);
end;
procedure TStockTraderTRSIMA_M15.SetProject(const aValue: IStockProject);
var
aCreated: boolean;
begin
if GetProject=aValue then
exit;
inherited;
if aValue <> nil then
begin
//M15
FRSI_M1_Black:=CreateOrFindIndicator(aValue.GetStockChart(sti1),ISCIndicatorTRSIMA,'RSI_BLACK'+'_'+StockTimeIntervalNames[sti1],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_M1_Black.SetPeriod(12);
FRSI_M1_Black.GetTrendCorrectionMA.SetPeriod(55);
FRSI_M1_Black.SetTrendCorrectionEnabled(true);
FRSI_M1_Black.GetMA.SetPeriod(21);
FRSI_M1_Black.SetColor(clBlack);
end;
FRSI_M1_Blue:=CreateOrFindIndicator(aValue.GetStockChart(sti1),ISCIndicatorTRSIMA,'RSI_BLUE'+'_'+StockTimeIntervalNames[sti1],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_M1_Blue.SetPeriod(12);
FRSI_M1_Blue.GetTrendCorrectionMA.SetPeriod(84);
FRSI_M1_Blue.SetTrendCorrectionEnabled(true);
FRSI_M1_Blue.GetMA.SetPeriod(21);
FRSI_M1_Blue.SetColor(clBlue);
end;
FRSI_M1_Pink:=CreateOrFindIndicator(aValue.GetStockChart(sti1),ISCIndicatorTRSIMA,'RSI_PINK'+'_'+StockTimeIntervalNames[sti1],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_M1_Pink.SetPeriod(12);
FRSI_M1_Pink.GetTrendCorrectionMA.SetPeriod(1);
FRSI_M1_Pink.SetTrendCorrectionEnabled(false);
FRSI_M1_Pink.GetMA.SetPeriod(21);
FRSI_M1_Pink.SetColor(clWebPlum);
end;
//M15
FRSI_M15_Black:=CreateOrFindIndicator(aValue.GetStockChart(sti15),ISCIndicatorTRSIMA,'RSI_BLACK'+'_'+StockTimeIntervalNames[sti15],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_M15_Black.SetPeriod(12);
FRSI_M15_Black.GetTrendCorrectionMA.SetPeriod(55);
FRSI_M15_Black.SetTrendCorrectionEnabled(true);
FRSI_M15_Black.GetMA.SetPeriod(21);
FRSI_M15_Black.SetColor(clBlack);
end;
FRSI_M15_Blue:=CreateOrFindIndicator(aValue.GetStockChart(sti15),ISCIndicatorTRSIMA,'RSI_BLUE'+'_'+StockTimeIntervalNames[sti15],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_M15_Blue.SetPeriod(12);
FRSI_M15_Blue.GetTrendCorrectionMA.SetPeriod(84);
FRSI_M15_Blue.SetTrendCorrectionEnabled(true);
FRSI_M15_Blue.GetMA.SetPeriod(21);
FRSI_M15_Blue.SetColor(clBlue);
end;
FRSI_M15_Pink:=CreateOrFindIndicator(aValue.GetStockChart(sti15),ISCIndicatorTRSIMA,'RSI_PINK'+'_'+StockTimeIntervalNames[sti15],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_M15_Pink.SetPeriod(12);
FRSI_M15_Pink.GetTrendCorrectionMA.SetPeriod(1);
FRSI_M15_Pink.SetTrendCorrectionEnabled(false);
FRSI_M15_Pink.GetMA.SetPeriod(21);
FRSI_M15_Pink.SetColor(clWebPlum);
end;
//H1
FRSI_H1_Black:=CreateOrFindIndicator(aValue.GetStockChart(sti60),ISCIndicatorTRSIMA,'RSI_BLACK'+'_'+StockTimeIntervalNames[sti60],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_H1_Black.SetPeriod(12);
FRSI_H1_Black.GetTrendCorrectionMA.SetPeriod(55);
FRSI_H1_Black.SetTrendCorrectionEnabled(true);
FRSI_H1_Black.GetMA.SetPeriod(21);
FRSI_H1_Black.SetColor(clBlack);
end;
FRSI_H1_Blue:=CreateOrFindIndicator(aValue.GetStockChart(sti60),ISCIndicatorTRSIMA,'RSI_BLUE'+'_'+StockTimeIntervalNames[sti60],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_H1_Blue.SetPeriod(12);
FRSI_H1_Blue.GetTrendCorrectionMA.SetPeriod(84);
FRSI_H1_Blue.SetTrendCorrectionEnabled(true);
FRSI_H1_Blue.GetMA.SetPeriod(21);
FRSI_H1_Blue.SetColor(clBlue);
end;
FRSI_H1_Pink:=CreateOrFindIndicator(aValue.GetStockChart(sti60),ISCIndicatorTRSIMA,'RSI_PINK'+'_'+StockTimeIntervalNames[sti60],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_H1_Pink.SetPeriod(12);
FRSI_H1_Pink.GetTrendCorrectionMA.SetPeriod(1);
FRSI_H1_Pink.SetTrendCorrectionEnabled(false);
FRSI_H1_Pink.GetMA.SetPeriod(21);
FRSI_H1_Pink.SetColor(clWebPlum);
end;
//H4
FRSI_H4_Black:=CreateOrFindIndicator(aValue.GetStockChart(sti240),ISCIndicatorTRSIMA,'RSI_BLACK'+'_'+StockTimeIntervalNames[sti240],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_H4_Black.SetPeriod(12);
FRSI_H4_Black.GetTrendCorrectionMA.SetPeriod(55);
FRSI_H4_Black.SetTrendCorrectionEnabled(true);
FRSI_H4_Black.GetMA.SetPeriod(21);
FRSI_H4_Black.SetColor(clBlack);
end;
FRSI_H4_Blue:=CreateOrFindIndicator(aValue.GetStockChart(sti240),ISCIndicatorTRSIMA,'RSI_BLUE'+'_'+StockTimeIntervalNames[sti240],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_H4_Blue.SetPeriod(12);
FRSI_H4_Blue.GetTrendCorrectionMA.SetPeriod(84);
FRSI_H4_Blue.SetTrendCorrectionEnabled(true);
FRSI_H4_Blue.GetMA.SetPeriod(21);
FRSI_H4_Blue.SetColor(clBlue);
end;
FRSI_H4_Pink:=CreateOrFindIndicator(aValue.GetStockChart(sti240),ISCIndicatorTRSIMA,'RSI_PINK'+'_'+StockTimeIntervalNames[sti240],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_H4_Pink.SetPeriod(12);
FRSI_H4_Pink.GetTrendCorrectionMA.SetPeriod(1);
FRSI_H4_Pink.SetTrendCorrectionEnabled(false);
FRSI_H4_Pink.GetMA.SetPeriod(21);
FRSI_H4_Pink.SetColor(clWebPlum);
end;
//D1
FRSI_D1_Black:=CreateOrFindIndicator(aValue.GetStockChart(sti1440),ISCIndicatorTRSIMA,'RSI_BLACK'+'_'+StockTimeIntervalNames[sti1440],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_D1_Black.SetPeriod(12);
FRSI_D1_Black.GetTrendCorrectionMA.SetPeriod(55);
FRSI_D1_Black.SetTrendCorrectionEnabled(true);
FRSI_D1_Black.GetMA.SetPeriod(21);
FRSI_D1_Black.SetColor(clBlack);
end;
FRSI_D1_Blue:=CreateOrFindIndicator(aValue.GetStockChart(sti1440),ISCIndicatorTRSIMA,'RSI_BLUE'+'_'+StockTimeIntervalNames[sti1440],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_D1_Blue.SetPeriod(12);
FRSI_D1_Blue.GetTrendCorrectionMA.SetPeriod(84);
FRSI_D1_Blue.SetTrendCorrectionEnabled(true);
FRSI_D1_Blue.GetMA.SetPeriod(21);
FRSI_D1_Blue.SetColor(clBlue);
end;
FRSI_D1_Pink:=CreateOrFindIndicator(aValue.GetStockChart(sti1440),ISCIndicatorTRSIMA,'RSI_PINK'+'_'+StockTimeIntervalNames[sti1440],true, aCreated) as ISCIndicatorTRSIMA;
if aCreated then
begin
FRSI_D1_Pink.SetPeriod(12);
FRSI_D1_Pink.GetTrendCorrectionMA.SetPeriod(1);
FRSI_D1_Pink.SetTrendCorrectionEnabled(false);
FRSI_D1_Pink.GetMA.SetPeriod(21);
FRSI_D1_Pink.SetColor(clWebPlum);
end;
//FRSI_M15:=CreateOrFindIndicator(aValue.GetStockChart(sti15),ISCIndicatorTRSIMA,'RSI'+'_'+StockTimeIntervalNames[sti15],true, aCreated) as ISCIndicatorTRSIMA;
//FMA84_M1:=CreateOrFindIndicator(aValue.GetStockChart(sti1),ISCIndicatorMA,'MA84'+'_'+StockTimeIntervalNames[sti1],true, aCreated) as ISCIndicatorMA;
//Ничего не нашли, создадим нового эксперта
if aCreated then
begin
//FMA84_M1.SetPeriod(84);
end;
end;
end;
function TStockTraderTRSIMA_M15.ToPrice(aPoints: integer): TSCRealNumber;
begin
result:=GetBroker.PointToPrice(GetSymbol,1);
end;
function TStockTraderTRSIMA_M15.Spread: TSCRealNumber;
begin
result:=GetBroker.PointToPrice(GetSymbol,GetBroker.GetMarketInfo(GetSymbol).Spread);
end;
function TStockTraderTRSIMA_M15.GetRecommendedLots: TStockOrderLots;
var
aOrders: IStockOrderCollection;
i: Integer;
x: integer;
begin
result:=inherited GetRecommendedLots;
if FPropIncreateOrdersOnLoss.Value then
begin
x:=1;
aOrders:=GetBroker.GetAllOrders;
for i :=aOrders.Count - 1 downto 0 do
begin
if aOrders[i].GetState=osClosed then
begin
if aOrders[i].GetCurrentProfit<0 then
begin
result:=result+aOrders[i].GetLots/x; //(inherited GetRecommendedLots/x);
x:=x*2;
if result>inherited GetRecommendedLots*5 then
break;
end
else begin
break;
end;
end;
end;
end;
result:=RoundTo(result,-2);
end;
function TStockTraderTRSIMA_M15.GetSignals(const aRSI_Black: ISCIndicatorTRSIMA; aRSI_Blue, aRSI_Pink: ISCIndicatorTRSIMA; aIndex: integer; aShowAlerts: boolean; out aRSIChangedBlack,aRSIChangedBlue,aRSIChangedPink: boolean): integer;
var
aRSIValueBlack,aRSIValueBlue,aRSIValuePink: TSCRealNumber;
aRSIValueBlack_1,aRSIValueBlue_1,aRSIValuePink_1: TSCRealNumber;
begin
result:=0;
aRSIValueBlack:=aRSI_Black.GetValue(aIndex);
aRSIValueBlue:=aRSI_Blue.GetValue(aIndex);
aRSIValuePink:=aRSI_Pink.GetValue(aIndex);
aRSIValueBlack_1:=aRSI_Black.GetValue(aIndex-1);
aRSIValueBlue_1:=aRSI_Blue.GetValue(aIndex-1);
aRSIValuePink_1:=aRSI_Pink.GetValue(aIndex-1);
//Анализ BUY
aRSIChangedBlack:=(aRSIValueBlack>=50) and (aRSIValueBlack_1<50);
aRSIChangedBlue:= (aRSIValueBlue>=50) and (aRSIValueBlue_1<50);
aRSIChangedPink:= (aRSIValuePink>=50) and (aRSIValuePink_1<50);
if aRSIChangedBlack or aRSIChangedBlue or aRSIChangedPink then
begin
result:= integer(aRSIValueBlack>=50)+integer(aRSIValueBlue>=50)+integer(aRSIValuePink>=50);
//Слишком далеко Pink, не похоже на правду
if (result=2) and (aRSIValuePink<20) then
result:=0;
if result>=2 then
begin
//Если поменялся Blue или Black, и при этом Pink уже отчскочил от верхней границы, то игнорируем сигнал
if (aRSIChangedBlack or aRSIChangedBlue) and (aRSI_Pink.GetLastSide(aIndex,1)=1) then
begin
if aShowAlerts then
AddMessageAndSetMark(mkStop,'Reject opening BUY: RSI H1 on top',clRed);
result:=0;
end
end;
end;
if result<>0 then
exit;
//Анализ SELL
aRSIChangedBlack:=(aRSIValueBlack<=50) and (aRSIValueBlack_1>50);
aRSIChangedBlue:= (aRSIValueBlue<=50) and (aRSIValueBlue_1>50);
aRSIChangedPink:= (aRSIValuePink<=50) and (aRSIValuePink_1>50);
if aRSIChangedBlack or aRSIChangedBlue or aRSIChangedPink then
begin
result:=integer(aRSIValueBlack<=50) + integer(aRSIValueBlue<=50) + integer(aRSIValuePink<=50);
if (result=2) and (aRSIValuePink>80) then
result:=0;
if result>=2 then
begin
//Если поменялся Blue или Black, и при этом Pink уже отчскочил нижней от границы, то игнорируем сигнал
if (aRSIChangedBlack or aRSIChangedBlue) and (aRSI_Pink.GetLastSide(aIndex,1)=-1) then
begin
if aShowAlerts then
AddMessageAndSetMark(mkStop,'Reject opening SELL: RSI H1 on bottom',clRed);
result:=0;
end;
end;
result:=-result;
end;
end;
procedure TStockTraderTRSIMA_M15.UpdateStep2(const aTime: TDateTime);
begin
Calculate(aTime);
end;
procedure TStockTraderTRSIMA_M15.Calculate(const aTime: TDateTime);
var
aIdxM15 : integer;
aOpen,aClose : integer;
aSignals,aSignalsPrev: integer;
i: integer;
aRSIChangedBlack,aRSIChangedBlue,aRSIChangedPink: boolean;
aRSIChangedBlack2,aRSIChangedBlue2,aRSIChangedPink2: boolean;
begin
RemoveClosedOrders;
//Не чаще одного раза в минуту
if (aTime-FLastUpdateTime)*MinsPerDay<1 then
exit;
FLastUpdateTime:=aTime;
aIdxM15:=TStockDataUtils.FindBar(FRSI_M15_Black.GetInputData,aTime,sti15);
if aIdxM15=FSkipM15Index then
exit;
if aIdxM15=FLastOrderM15Index then
exit;
if (aIdxM15<>-1) and (aIdxM15>=100) then
begin
aOpen:=0;
aClose:=0;
aSignals:=GetSignals(FRSI_M15_Black,FRSI_M15_Blue,FRSI_M15_Pink,aIdxM15,true,aRSIChangedBlack,aRSIChangedBlue,aRSIChangedPink);
//open buy, close sell -------------------------------------------
if aSignals>0 then
begin
if (aIdxM15-FLastOrderM15Index)<=2 then
begin
FSkipM15Index:=aIdxM15;
AddMessageAndSetMark(mkStop,'Reject opening BUY: too close to previous order',clRed);
aSignals:=0;
end;
//нужно проверить, когда был последний переворот, если ближе 12 часов - пропускаем
if (aSignals=2) then
begin
for i:=aIdxM15-1 downto aIdxM15-12 do
begin
aSignalsPrev := GetSignals(FRSI_M15_Black,FRSI_M15_Blue,FRSI_M15_Pink,i,false,aRSIChangedBlack2,aRSIChangedBlue2,aRSIChangedPink2);
if (aSignalsPrev<=-2) then
begin
AddMessageAndSetMark(mkStop,'Reject opening BUY: Too close to previous opposite signal',clRed);
aSignals:=0;
break;
end;
end
end;
//Посмотрим, а не остаточное ли это явление, Pink может быть уже давно вверху, и тогда покупать опасно
if (aSignals=2) and (aRSIChangedBlue) and not (aRSIChangedPink) and (FRSI_M15_Pink.GetValue(aIdxM15)>50) then
begin
for i:=aIdxM15-1 downto 0 do
begin
//Если где-то Pink был снизу - нормально
if FRSI_M15_Pink.GetValue(i)<50 then
break;
aSignalsPrev := GetSignals(FRSI_M15_Black,FRSI_M15_Blue,FRSI_M15_Pink,i,false,aRSIChangedBlack2,aRSIChangedBlue2,aRSIChangedPink2);
//Нашли предыдущее пересечение вверх, а за это время Pink так и не опустился
if (aSignalsPrev>=2) then
begin
AddMessageAndSetMark(mkAttention,'Reject opening BUY: Pink is too high and too long',clRed);
aSignals:=0;
break;
end;
end
end;
if aSignals>=2 then
begin
aOpen:=1;
aClose:=-1;
end;
end;
if aSignals<0 then
begin
if (aIdxM15-FLastOrderM15Index)<=2 then
begin
FSkipM15Index:=aIdxM15;
AddMessageAndSetMark(mkStop,'Reject opening SELL: too close to previous order',clRed);
aSignals:=0;
end;
if (aSignals=-2) then
begin
for i:=aIdxM15-1 downto aIdxM15-12 do
begin
aSignalsPrev := GetSignals(FRSI_M15_Black,FRSI_M15_Blue,FRSI_M15_Pink,i,false,aRSIChangedBlack2,aRSIChangedBlue2,aRSIChangedPink2);
if (aSignalsPrev>=2) then
begin
AddMessageAndSetMark(mkStop,'Reject opening SELL: Too close to previous opposite signal',clRed);
aSignals:=0;
break;
end;
end
end;
//Посмотрим, а не остаточное ли это явление, Pink может быть уже давно внизу, и тогда продавать опасно
if (aSignals=-2) and (aRSIChangedBlue) and not (aRSIChangedPink) and (FRSI_M15_Pink.GetValue(aIdxM15)<50) then
begin
for i:=aIdxM15-1 downto 0 do
begin
//Если где-то Pink был сверху - нормально
if FRSI_M15_Pink.GetValue(i)>50 then
break;
aSignalsPrev := GetSignals(FRSI_M15_Black,FRSI_M15_Blue,FRSI_M15_Pink,i,false,aRSIChangedBlack2,aRSIChangedBlue2,aRSIChangedPink2);
//Нашли предыдущее пересечение вниз, а за это время Pink так и не поднялся
if (aSignalsPrev<=-2) then
begin
AddMessageAndSetMark(mkAttention,'Reject opening SELL: Pink is too low and too long',clRed);
aSignals:=0;
break;
end;
end
end;
if aSignals<=-2 then
begin
aOpen:=-1;
aClose:=1;
end;
end;
if aClose=-1 then
CloseAllSellOrders('')
else if aClose=1 then
CloseAllBuyOrders('');
if aOpen<>0 then
begin
//BUY
if (aOpen=1) {and (LastOrderType<>lotBuy)} then
begin
inc(FOrderBuyM15Signals);
FOrderSellM15Signals:=0;
OpenOrder(okBuy);
FLastOrderM15Index:=aIdxM15;
end
//SELL
else if (aOpen=-1) {and (LastOrderType<>lotSell)} then
begin
inc(FOrderSellM15Signals);
FOrderBuyM15Signals:=0;
OpenOrder(okSell);
FLastOrderM15Index:=aIdxM15;
end;
end;
end;
end;
procedure TStockTraderTRSIMA_M15.AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string);
begin
GetBroker.AddMessage(aOrder,aMessage);
AddMarkToCharts(GetBroker.GetCurrentTime,
GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid),
aMarkType,aMessage);
end;
initialization
FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','TRSIMA M15',TStockTraderTRSIMA_M15,IStockTraderTRSIMA_M15);
end.
|
unit ClientsFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, Db, DBTables, DBGrids, ExtCtrls, DBCtrls, Menus,
StdCtrls, Buttons, ComCtrls, ClientFrm, Common, SearchFrm, Basbn, Utilits,
BtrDS, CommCons;
type
TClientsForm = class(TDataBaseForm)
DataSource: TDataSource;
DBGrid: TDBGrid;
StatusBar: TStatusBar;
BtnPanel: TPanel;
OkBtn: TBitBtn;
CancelBtn: TBitBtn;
NameEdit: TEdit;
SearchIndexComboBox: TComboBox;
ChildMenu: TMainMenu;
OperItem: TMenuItem;
FindItem: TMenuItem;
InsItem: TMenuItem;
DelItem: TMenuItem;
EditBreaker: TMenuItem;
NameLabel: TLabel;
EditItem: TMenuItem;
CopyItem: TMenuItem;
EditPopupMenu: TPopupMenu;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure NameEditChange(Sender: TObject);
procedure SearchIndexComboBoxChange(Sender: TObject);
procedure BtnPanelResize(Sender: TObject);
procedure FindItemClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure InsItemClick(Sender: TObject);
procedure EditItemClick(Sender: TObject);
procedure DelItemClick(Sender: TObject);
procedure CopyItemClick(Sender: TObject);
procedure DBGridDblClick(Sender: TObject);
private
procedure EditClient(CopyCurrent, New: Boolean);
public
SearchForm: TSearchForm;
procedure TakeTabPrintData(var PrintDocRec: TPrintDocRec; var FormList: TList); override;
end;
var
ObjList: TList;
const
ClientsForm: TClientsForm = nil;
implementation
{$R *.DFM}
{procedure TClientForm.AfterScrollDS(DataSet: TDataSet);
begin
NameEdit.Text:=DataSet.Fields.Fields[5].AsString;
end;}
procedure TClientsForm.FormCreate(Sender: TObject);
begin
ObjList.Add(Self);
DataSource.DataSet := GlobalBase(biClient) as TClientDataSet;
DefineGridCaptions(DBGrid, PatternDir+'Clients.tab');
SearchForm := TSearchForm.Create(Self);
SearchForm.SourceDBGrid := DBGrid;
SearchIndexComboBox.ItemIndex := 2;
SearchIndexComboBoxChange(Sender);
TakeMenuItems(OperItem, EditPopupMenu.Items);
EditPopupMenu.Images := ChildMenu.Images;
end;
procedure TClientsForm.FormDestroy(Sender: TObject);
begin
ObjList.Remove(Self);
if Self=ClientsForm then ClientsForm := nil;
end;
procedure TClientsForm.TakeTabPrintData(var PrintDocRec: TPrintDocRec; var FormList: TList);
begin
inherited;
PrintDocRec.DBGrid := Self.DBGrid;
end;
procedure TClientsForm.NameEditChange(Sender: TObject);
var
Inn: TInn;
ClientName: TClientName;
I,Err: Integer;
SearchData: packed record Bik: LongInt; Acc: TAccount end;
S: string;
begin
case SearchIndexComboBox.ItemIndex of
0:
begin
NameEdit.MaxLength := 10+SizeOf(SearchData.Acc);
S := NameEdit.Text;
I := Pos('/',S);
FillChar(SearchData.Acc, SizeOf(SearchData.Acc), #0);
if I>0 then
begin
StrPLCopy(SearchData.Acc, Copy(S,I+1,Length(S)-I), SizeOf(SearchData.Acc));
S:=Copy(S, 1, I-1);
end;
Val(S, I, Err);
SearchData.Bik := FillDigTo(I, 8);
TBtrDataSet(DataSource.DataSet).LocateBtrRecordByIndex(SearchData, 0, bsGe);
end;
1:
begin
NameEdit.MaxLength := SizeOf(Inn);
FillChar(Inn, SizeOf(Inn), #0);
StrPCopy(Inn, NameEdit.Text);
(DataSource.DataSet as TBtrDataSet).LocateBtrRecordByIndex(Inn, 1, bsGe);
end;
2:
begin
NameEdit.MaxLength := SizeOf(TClientName);
FillChar(ClientName, SizeOf(TClientName), #0);
StrPLCopy(ClientName, NameEdit.Text, SizeOf(TClientName)-1);
WinToDos(ClientName);
(DataSource.DataSet as TBtrDataSet).LocateBtrRecordByIndex(ClientName,
2, bsGe);
end;
end;
end;
procedure TClientsForm.SearchIndexComboBoxChange(Sender: TObject);
var
AllowMultiSel: Boolean;
Opt: TDBGridOptions;
begin
(DataSource.DataSet as TBtrDataSet).IndexNum := SearchIndexComboBox.ItemIndex;
case SearchIndexComboBox.ItemIndex of
0: NameEdit.MaxLength := 10+SizeOf(TAccount);
1: NameEdit.MaxLength := SizeOf(TInn);
2: NameEdit.MaxLength := clMaxVar;
else
NameEdit.MaxLength := 15;
end;
AllowMultiSel := SearchIndexComboBox.ItemIndex=0;
Opt := DBGrid.Options;
if (dgMultiSelect in Opt)<>AllowMultiSel then
begin
if AllowMultiSel then
Include(Opt, dgMultiSelect)
else
Exclude(Opt, dgMultiSelect);
DBGrid.Options := Opt;
end;
end;
const
BtnDist=6;
procedure TClientsForm.BtnPanelResize(Sender: TObject);
begin
CancelBtn.Left:=BtnPanel.ClientWidth-CancelBtn.Width-2*BtnDist;
OkBtn.Left:=CancelBtn.Left-OkBtn.Width-BtnDist;
end;
procedure TClientsForm.FindItemClick(Sender: TObject);
begin
SearchForm.ShowModal;
end;
procedure TClientsForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if FormStyle=fsMDIChild then Action:=caFree;
end;
procedure TClientsForm.EditClient(CopyCurrent, New: Boolean);
var
ClientForm: TClientForm;
ClientRec: TNewClientRec;
T: array[0..512] of Char;
Editing: Boolean;
{I: Integer;}
begin
if not DataSource.DataSet.IsEmpty or (New and not CopyCurrent) then
begin
ClientForm := TClientForm.Create(Self);
with ClientForm do
begin
if CopyCurrent then
TClientDataSet(DataSource.DataSet).GetBtrRecord(PChar(@ClientRec))
else
FillChar(ClientRec,SizeOf(ClientRec),#0);
with ClientRec do
begin
DosToWin(clNameC);
StrLCopy(T, clAccC, SizeOf(clAccC));
RsEdit.Text := StrPas(T);
BikEdit.Text := IntToStr(clCodeB);
StrLCopy(T, clInn, SizeOf(clInn));
InnEdit.Text := StrPas(T);
StrLCopy(T, clKpp, SizeOf(clKpp));
KppEdit.Text := StrPas(T);
NameMemo.Text := StrPas(clNameC);
end;
Editing := True;
while Editing and (ShowModal = mrOk) do
begin
Editing := False;
if not UpdateClient(RsEdit.Text, StrToInt(BikEdit.Text), NameMemo.Text,
InnEdit.Text, KppEdit.Text, False, True) then
begin
Editing := True;
MessageBox(Handle, 'Невозможно обновить запись', 'Редактирование',
MB_OK + MB_ICONERROR);
end;
end;
Free;
end;
end;
end;
procedure TClientsForm.InsItemClick(Sender: TObject);
begin
EditClient(False, True);
end;
procedure TClientsForm.EditItemClick(Sender: TObject);
begin
if FormStyle = fsMDIChild then
EditClient(True, False)
else
ModalResult := mrOk;
end;
procedure TClientsForm.CopyItemClick(Sender: TObject);
begin
EditClient(True, True)
end;
procedure TClientsForm.DelItemClick(Sender: TObject);
const
MesTitle: PChar = 'Удаление';
var
N: Integer;
begin
if not DataSource.DataSet.IsEmpty then
begin
DBGrid.SelectedRows.Refresh;
N := DBGrid.SelectedRows.Count;
if (N<2) and (MessageBox(Handle, PChar('Клиент будет удален. Вы уверены?'),
MesTitle, MB_YESNOCANCEL + MB_ICONQUESTION) = IDYES)
or (N>=2) and (MessageBox(Handle, PChar('Будет удалено клиентов: '
+IntToStr(DBGrid.SelectedRows.Count)+#13#10'Вы уверены?'),
MesTitle, MB_YESNOCANCEL + MB_ICONQUESTION) = IDYES) then
begin
if N>0 then
begin
DBGrid.SelectedRows.Delete;
DBGrid.SelectedRows.Refresh;
end
else
DataSource.DataSet.Delete;
end;
end;
end;
procedure TClientsForm.DBGridDblClick(Sender: TObject);
begin
EditItemClick(Sender)
end;
end.
|
(***********************************************************)
(* xPLRFX *)
(* part of Digital Home Server project *)
(* http://www.digitalhomeserver.net *)
(* info@digitalhomeserver.net *)
(***********************************************************)
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, LazSerial, Forms, Controls, Graphics, Dialogs,
StdCtrls, uxPLRFX, uxPLRFXMessages, u_xpl_custom_listener, u_xpl_config,
u_xpl_message, u_xpl_common, u_xpl_custom_message, u_xpl_messages,
u_xpl_application;
type
{ TMainForm }
TMainForm = class(TForm)
AboutButton: TButton;
ConnectButton: TButton;
Comport: TLazSerial;
ComportEdit: TEdit;
CloseButton: TButton;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
Label1: TLabel;
StatusLabel: TLabel;
ReadMemo: TMemo;
ReceiveMemo: TMemo;
procedure AboutButtonClick(Sender: TObject);
procedure CloseButtonClick(Sender: TObject);
procedure ComportRxData(Sender: TObject);
procedure ConnectButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ private declarations }
FTempStr : String;
CurPos : Integer;
xPLRFX : TxPLRFX;
xPLMessages : TxPLRFXMessages;
public
{ public declarations }
end;
{ TxPLexecListener }
TxPLexecListener = class(TxPLCustomListener)
private
program_list : TxPLConfigItem;
public
constructor Create(const aOwner : TComponent); reintroduce;
//procedure OnFindClass(Reader: TReader; const AClassName: string; var ComponentClass: TComponentClass); override;
procedure UpdateConfig; override;
procedure RawProcess(const aMessage : TxPLMessage);
procedure Process(const aMessage : TxPLMessage);
published
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
Uses uxPLRFXConst
, u_xpl_header
, u_xpl_body
, uxPLConst
, About
;
{ TxPLListener }
const // ======================================================================
rsStatus = 'status';
rsReturn = 'return';
rsStarted = 'started';
rsXpl_execStar = '%s: started program %s';
rsProgram = 'program';
rsArg = 'arg';
rsFinished = 'finished';
rsFailed = 'failed';
rsXplexecFaile = '%s: failed to start %s: %s';
rsIgnoredUnabl = '%s : unable to find security declaration of %s';
// ============================================================================
{ TxPLexecListener }
constructor TxPLexecListener.Create(const aOwner: TComponent);
begin
inherited Create(aOwner);
include(fComponentStyle,csSubComponent);
FilterSet.AddValues(['*.*.*.*.*.*']);
Config.DefineItem(rsProgram, TxPLConfigItemType.option, 16);
OnPreProcessMsg := @RawProcess;
end;
procedure TxPLexecListener.UpdateConfig;
begin
inherited UpdateConfig;
if Config.IsValid then begin
OnxPLReceived := @Process;
program_list := Config.ConfigItems.FindItemName(rsProgram);
end
else OnxPLReceived := nil;
end;
procedure TxPLexecListener.Process(const aMessage: TxPLMessage);
var
Buffer : BytesArray;
Count : Integer;
Len : Integer;
begin
if aMessage.MessageType = cmnd then
begin
try
MainForm.xPLRFX.xPL2RFX(aMessage,Buffer);
Count := Buffer[0]+1;
MainForm.ComPort.WriteBuffer(Buffer,Count);
uxPLRFXConst.Log('||||||||||||||||||||||||||||||||||||||||||||||||||||||');
uxPLRFXConst.Log('Received xPL Message : '+aMessage.RawXPL);
uxPLRFXConst.Log('RFX Data : '+BytesArrayToStr(Buffer));
MainForm.ReceiveMemo.Lines.Add('Received xPL Message : ');
MainForm.ReceiveMemo.Lines.Add(aMessage.RawxPL);
MainForm.ReceiveMemo.Lines.Add('RFX Data : '+Copy(BytesArrayToStr(Buffer),1,Buffer[0]*2));
MainForm.ReceiveMemo.Lines.Add('=========================================================');
except
;
end;
end;
end;
procedure TxPLexecListener.RawProcess(const aMessage: TxPLMessage);
begin
end;
{ TMainForm }
var
InputString : String;
ExpectedBytes : Integer = 0;
ReceivedBytes : Integer;
procedure TMainForm.ComportRxData(Sender: TObject);
var
Str, TempStr : String;
LogString : String;
Data : BytesArray;
i,j : Integer;
b : Byte;
begin
// We received a string of data
Str := Comport.ReadData;
// Convert to hex string
for i := 1 to Length(Str) do
begin
// If ExpectedBytes = 0 then first character contains expected bytes
if ExpectedBytes = 0 then
ExpectedBytes := Ord(Str[i]);
InputString := InputString + InttoHex(Ord(Str[i]),2);
ReceivedBytes := ReceivedBytes + 1;
if ReceivedBytes >= ExpectedBytes+1 then
begin
// Feed it to the xPLRFX parser
try
xPLMessages.Clear;
TempStr := Copy(InputString,1,(ReceivedBytes)*2);
LogString := xPLRFX.RFX2xPL(HexToBytes(TempStr),xPLMessages);
ReadMemo.Lines.Add('Received '+ LogString);
ReadMemo.Lines.Add('RFX Data : '+TempStr);
Log('===========================================================');
Log('Received'+LogString);
Log('RFXData : '+TempStr);
// See if we have xPL Messages
for j := 0 to xPLMessages.Count-1 do
begin
TxPLExecListener(xPLApplication).Send(xPLMessages[j]);
ReadMemo.Lines.Add('xPL Message '+IntToStr(j));
ReadMemo.Lines.Add(xPLMessages[j].RawXPL);
Log('Sent '+xPLMessages[j].RawxPL);
end;
ReadMemo.Lines.Add('=========================================================');
except
// Code is unknown or not implemented, leave it like this
;
end;
// Cut of the part which is already translated
InputString := Copy(InputString,(ReceivedBytes+1)*2,Length(InputString));
ReceivedBytes := 0;
ExpectedBytes := 0;
end;
end;
end;
procedure TMainForm.CloseButtonClick(Sender: TObject);
begin
Comport.Close;
StatusLabel.Caption := 'Disconnected';
end;
procedure TMainForm.AboutButtonClick(Sender: TObject);
begin
AboutForm.ShowModal;
end;
procedure TMainForm.ConnectButtonClick(Sender: TObject);
var
Buffer : array[0..14] of byte;
i : Integer;
begin
// Open the serial port
Comport.Device := ComportEdit.Text;
try
// Open the com port
Comport.Open;
// Initialize the RFXtrx433
StatusLabel.Caption := 'Initializing...';
Application.ProcessMessages;;
Buffer[0] := $0D;
for i := 1 to 13 do
Buffer[i] := $00;
Comport.WriteBuffer(Buffer,14);
Sleep(1000);
Comport.ReadData;
Buffer[3] := $01;
Buffer[4] := $02;
Comport.WriteBuffer(Buffer,14);
StatusLabel.Caption := 'Connected';
except
ShowMessage('Could not open serial port');
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
// Open the logfile
OpenLog;
// Create the gateway object
xPLRFX := TxPLRFX.Create;
xPLMessages := TxPLRFXMessages.Create;
// Instantiate xPL listener
InstanceInitStyle := iisRandom;
xPLApplication := TxPLExecListener.Create(Application);
TxPLExecListener(xPLApplication).Listen;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
CloseLog;
xPLRFX.Free;
xPLMessages.Free;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC PostgreSQL driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$IF DEFINED(IOS) OR DEFINED(ANDROID)}
{$HPPEMIT LINKUNIT}
{$ELSE}
{$IFDEF WIN32}
{$HPPEMIT '#pragma link "FireDAC.Phys.PG.obj"'}
{$ELSE}
{$HPPEMIT '#pragma link "FireDAC.Phys.PG.o"'}
{$ENDIF}
{$ENDIF}
unit FireDAC.Phys.PG;
interface
uses
System.Types, System.Classes,
FireDAC.Phys;
type
[ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidLinux)]
TFDPhysPgDriverLink = class(TFDPhysDriverLink)
protected
function GetBaseDriverID: String; override;
end;
{-------------------------------------------------------------------------------}
implementation
uses
System.Variants, System.SysUtils, System.Math, Data.DB, Data.SqlTimSt,
System.DateUtils,
FireDAC.Stan.Intf, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.Stan.Option,
FireDAC.Stan.Util, FireDAC.Stan.Consts, FireDAC.Stan.Factory,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.PGMeta, FireDAC.Phys.SQLGenerator,
FireDAC.Phys.PGCli, FireDAC.Phys.PGWrapper, FireDAC.Phys.PgDef;
type
TFDPhysPgDriver = class;
TFDPhysPgConnection = class;
TFDPhysPgTransaction = class;
TFDPhysPgEventAlerter = class;
TFDPhysPgCommand = class;
TFDPhysPGCliHandles = array [0..1] of Pointer;
PFDPhysPGCliHandles = ^TFDPhysPGCliHandles;
TFDPhysPgDriver = class(TFDPhysDriver)
private
FLib: TPgLib;
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
procedure InternalLoad; override;
procedure InternalUnload; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
function GetCliObj: Pointer; override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
public
constructor Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); override;
destructor Destroy; override;
end;
TFDPhysPgConnection = class(TFDPhysConnection)
private
FEnv: TPgEnv;
FConnection: TPgConnection;
FServerVersion: TFDVersion;
FOidAsBlob: TFDPGOidAsBlob;
FExtendedMetadata: Boolean;
FCliHandles: TFDPhysPGCliHandles;
FUseMonthsBetween: Boolean;
FMetaCatalog: String;
FBackslashEscape: Boolean;
FArrayScanSample: Integer;
FArrayDefSize: Integer;
FGUIDEndian: TEndian;
function BuildPgConnectString(const AConnectionDef: IFDStanConnectionDef): String;
procedure UpdateCurrentMeta;
function AdjustOIDasBLOB(const ATypeName, ANameSpace: String;
var ADataType: TFDDataType; var AAttrs: TFDDataAttributes): Boolean;
protected
procedure InternalConnect; override;
procedure InternalSetMeta; override;
procedure InternalDisconnect; override;
procedure InternalChangePassword(const AUserName, AOldPassword,
ANewPassword: String); override;
function InternalCreateTransaction: TFDPhysTransaction; override;
function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override;
function InternalCreateCommand: TFDPhysCommand; override;
function InternalCreateMetadata: TObject; override;
function InternalCreateCommandGenerator(const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; override;
{$IFDEF FireDAC_MONITOR}
procedure InternalTracingChanged; override;
{$ENDIF}
procedure InternalExecuteDirect(const ASQL: String; ATransaction: TFDPhysTransaction); override;
procedure GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind); override;
function GetItemCount: Integer; override;
function GetMessages: EFDDBEngineException; override;
function GetCliObj: Pointer; override;
function InternalGetCliHandle: Pointer; override;
function GetLastAutoGenValue(const AName: String): Variant; override;
public
constructor Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); override;
destructor Destroy; override;
property PgConnection: TPgConnection read FConnection;
end;
TFDPhysPgTransaction = class(TFDPhysTransaction)
protected
procedure InternalStartTransaction(ATxID: LongWord); override;
procedure InternalCommit(ATxID: LongWord); override;
procedure InternalRollback(ATxID: LongWord); override;
procedure InternalChanged; override;
procedure InternalCheckState(ACommandObj: TFDPhysCommand; ASuccess: Boolean); override;
procedure InternalNotify(ANotification: TFDPhysTxNotification; ACommandObj: TFDPhysCommand); override;
end;
TFDPhysPgEventAlerter = class(TFDPhysEventAlerter)
private
FWaitConnection: IFDPhysConnection;
FWaitThread: TThread;
protected
// TFDPhysEventAlerter
procedure InternalAllocHandle; override;
procedure InternalRegister; override;
procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override;
procedure InternalAbortJob; override;
procedure InternalUnregister; override;
procedure InternalReleaseHandle; override;
procedure InternalSignal(const AEvent: String; const AArgument: Variant); override;
end;
PFDPgParInfoRec = ^TFDPgParInfoRec;
PFDPgVecInfoRec = ^TFDPgVecInfoRec;
PFDPgColInfoRec = ^TFDPgColInfoRec;
PFDPgRecInfoRec = ^TFDPgRecInfoRec;
PFDProcArgRec = ^TFDProcArgRec;
TFDPgParInfoRec = record
FPgParamIndex: Integer;
FParamIndex: Integer;
FOutSQLDataType: OID;
FDestDataType: TFDDataType;
FSrcDataType: TFDDataType;
FOutDataType: TFDDataType;
FSrcFieldType: TFieldType;
FSrcSize: LongWord;
FSrcPrec: Integer;
FSrcScale: Integer;
FParamType: TParamType;
FVecInfo: PFDPgVecInfoRec;
end;
TFDPgVecInfoRec = record
FParInfos: array of TFDPgParInfoRec;
end;
TFDPgColInfoRec = record
FName: String;
FPos: Integer;
FLen: LongWord;
FPrec,
FScale: Integer;
FSrcSQLDataType: Oid;
FSrcDataType,
FDestDataType: TFDDataType;
FAttrs: TFDDataAttributes;
FField: TPgField;
FOriginSchemaName,
FOriginTabName,
FOriginColName: String;
FTableCol: Integer;
FTableOid: Oid;
FInPK: WordBool;
FRecInfo: PFDPgRecInfoRec;
end;
TFDPgRecInfoRec = record
FColInfos: array of TFDPgColInfoRec;
// next members are actually temporary variables
FColIndex: Integer;
FFixedLength: Integer;
FParentColName: String;
end;
TFDProcArgRec = record
FName: String;
FParamType: TParamType;
FTypeOid: Oid;
end;
TFDProcArgRecs = array of TFDProcArgRec;
TFDPhysPgSPDescriber = class(TObject)
private
FCommand: TFDPhysPgCommand;
FName: TFDPhysParsedName;
procedure CreateParam(AName: String; AParamType: TParamType; ATypeOid: Oid);
public
constructor Create(ACommand: TFDPhysPgCommand; const AName: TFDPhysParsedName);
procedure CreateParams;
procedure ReadProcArgs(var AProcArgs: TFDProcArgRecs);
end;
TFDPhysPgCommand = class(TFDPhysCommand)
private
FStmt: TPgStatement;
FBaseStmt: TPgStatement;
FBaseVecInfo: TFDPgVecInfoRec;
FBaseRecInfo: TFDPgRecInfoRec;
FCurrentRecInfo: PFDPgRecInfoRec;
FInfoStack: TFDPtrList;
FCursorCanceled: Boolean;
FCursors: array of String;
FActiveCrs: Integer;
FMetaProcName: String;
FMetaProcOverload: Word;
FOidAsBlob: Boolean;
FStmtParamsCount: Integer;
FPreparedBatchSize: Integer;
FResultSetMode: Integer;
function GetConnection: TFDPhysPgConnection;
function FDType2SQL(AType: TFDDataType; const ATypeName: String; AArray: Boolean): Oid;
procedure SQL2FDColInfo(ASQLTypeOid: Oid; ASQLLen: LongWord; ASQLPrec,
ASQLScale: Integer; AParamType: TParamType; out AType: TFDDataType;
var AAttrs: TFDDataAttributes; out ALen: LongWord; out APrec, AScale: Integer;
AFmtOpts: TFDFormatOptions);
function CreateStmt: TPgStatement;
function UseExecDirect: Boolean;
procedure CreateParamInfos;
procedure DestroyParamInfos;
function CheckFixedArray(AField: TPgField; var ALen: Integer): Boolean;
procedure CreateColInfos;
procedure DestroyColInfos;
procedure CheckColInfos;
function BuildColumnName(ApRecInfo: PFDPgRecInfoRec; ApColInfo: PFDPgColInfoRec): String;
procedure SetParamValue(AFmtOpts: TFDFormatOptions; AParam: TFDParam;
APgParam: TPgParam; ApInfo: PFDPgParInfoRec; AParIndex: Integer);
procedure SetParamValues(AParIndex: Integer = 0);
procedure GetParamValues(AParIndex: Integer);
procedure ExecuteBatchInsert(ATimes, AOffset: Integer; var ACount: TFDCounter);
procedure DoExecute(ATimes, AOffset: Integer; var ACount: TFDCounter);
function CheckArray(ASize: Integer): Boolean;
procedure FetchRow(ApRecInfo: PFDPgRecInfoRec; ATable: TFDDatSTable;
AParentRow: TFDDatSRow);
procedure FetchTableFieldsRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow);
procedure FetchProcsRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow);
function FetchSPParamRows(ATable: TFDDatSTable; AParentRow: TFDDatSRow): Integer;
protected
procedure InternalPrepare; override;
function InternalUseStandardMetadata: Boolean; override;
function InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean; override;
function InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean; override;
procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override;
function InternalOpen(var ACount: TFDCounter): Boolean; override;
function InternalNextRecordSet: Boolean; override;
function InternalFetchRowSet(ATable: TFDDatSTable; AParentRow: TFDDatSRow;
ARowsetSize: LongWord): LongWord; override;
procedure InternalAbort; override;
procedure InternalClose; override;
procedure InternalUnprepare; override;
function GetCliObj: Pointer; override;
public
constructor Create(AConnectionObj: TFDPhysConnection);
destructor Destroy; override;
property PgConnection: TFDPhysPgConnection read GetConnection;
property PgStatement: TPgStatement read FStmt;
end;
const
S_FD_CharacterSets = 'BIG5;EUC_CN;EUC_JP;EUC_KR;EUC_TW;GB18030;GBK;ISO_8859_5;' +
'ISO_8859_6;ISO_8859_7;ISO_8859_8;JOHAB;KOI8;LATIN1;LATIN2;LATIN3;LATIN4;LATIN5;' +
'LATIN6;LATIN7;LATIN8;LATIN9;LATIN10;MULE_INTERNAL;SJIS;SQL_ASCII;UHC;UTF8;' +
'WIN866;WIN874;WIN1250;WIN1251;WIN1252;WIN1256;WIN1258';
S_FD_Choose = 'Choose';
S_FD_Error = 'Error';
S_FD_BYTEA = 'BYTEA';
{-------------------------------------------------------------------------------}
{ TFDPhysIBDriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysPgDriverLink.GetBaseDriverID: String;
begin
Result := S_FD_PgId;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysIBDriver }
{-------------------------------------------------------------------------------}
constructor TFDPhysPgDriver.Create(AManager: TFDPhysManager;
const ADriverDef: IFDStanDefinition);
begin
inherited Create(AManager, ADriverDef);
FLib := TPgLib.Create(FDPhysManagerObj);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysPgDriver.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FLib);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgDriver.InternalLoad;
var
sHome, sLib: String;
begin
sHome := '';
sLib := '';
GetVendorParams(sHome, sLib);
FLib.Load(sHome, sLib);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgDriver.InternalUnload;
begin
FLib.Unload;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgDriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysPgConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
class function TFDPhysPgDriver.GetBaseDriverID: String;
begin
Result := S_FD_PgId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysPgDriver.GetBaseDriverDesc: String;
begin
Result := 'PostgreSQL';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysPgDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.PostgreSQL;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysPgDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysPGConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgDriver.GetCliObj: Pointer;
begin
Result := FLib;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
begin
Result := inherited GetConnParams(AKeys, AParams);
oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + '''');
if oView.Rows.Count = 1 then begin
oView.Rows[0].BeginEdit;
oView.Rows[0].SetValues('LoginIndex', 4);
oView.Rows[0].EndEdit;
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, S_FD_Local, S_FD_Local, S_FD_ConnParam_Common_Server, 2]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Port, '@I', '5432', S_FD_ConnParam_Common_Port, 3]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_LoginTimeout, '@I', '0', S_FD_ConnParam_Common_LoginTimeout, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_CharacterSet, S_FD_CharacterSets, '', S_FD_ConnParam_Common_CharacterSet, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_ExtendedMetadata, '@L', S_FD_False, S_FD_ConnParam_Common_ExtendedMetadata, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_PG_OidAsBlob, S_FD_No + ';' + S_FD_Yes + ';' + S_FD_Choose, S_FD_Choose, S_FD_ConnParam_PG_OidAsBlob, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_PG_UnknownFormat, S_FD_Error + ';' + S_FD_BYTEA, S_FD_Error, S_FD_ConnParam_PG_UnknownFormat, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_PG_ArrayScanSample, '@S', '0;5', S_FD_ConnParam_PG_ArrayScanSample, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_ApplicationName, '@S', '', S_FD_ConnParam_Common_ApplicationName, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_PG_PGAdvanced, '@S', '', S_FD_ConnParam_PG_PGAdvanced, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefSchema, '@S', 'public', S_FD_ConnParam_Common_MetaDefSchema, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurSchema, '@S', '', S_FD_ConnParam_Common_MetaCurSchema, -1]);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysPgConnection }
{-------------------------------------------------------------------------------}
constructor TFDPhysPgConnection.Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost);
begin
inherited Create(ADriverObj, AConnHost);
FEnv := TPgEnv.Create(TFDPhysPgDriver(DriverObj).FLib, Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysPgConnection.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FEnv);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.InternalCreateTransaction: TFDPhysTransaction;
begin
Result := TFDPhysPgTransaction.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter;
begin
if CompareText(AEventKind, S_FD_EventKind_PG_Events) = 0 then
Result := TFDPhysPgEventAlerter.Create(Self, AEventKind)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.InternalCreateCommand: TFDPhysCommand;
begin
Result := TFDPhysPgCommand.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.InternalCreateMetadata: TObject;
begin
Result := TFDPhysPgMetadata.Create(Self, FServerVersion,
TFDPhysPgDriver(DriverObj).FLib.Version,
(FConnection <> nil) and (FConnection.Encoder.Encoding in [ecUTF8, ecUTF16]),
FExtendedMetadata, FUseMonthsBetween, FBackslashEscape);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
if ACommand <> nil then
Result := TFDPhysPgCommandGenerator.Create(ACommand)
else
Result := TFDPhysPgCommandGenerator.Create(Self);
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
procedure TFDPhysPgConnection.InternalTracingChanged;
begin
if FEnv <> nil then begin
FEnv.Monitor := FMonitor;
FEnv.Tracing := FTracing;
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.BuildPgConnectString(const AConnectionDef: IFDStanConnectionDef): String;
function IsIpAddress(const AAddr: String): Boolean;
var
i, iVal, iCode, iCnt: Integer;
aStr: TArray<String>;
begin
iCnt := 0;
aStr := AAddr.Split(['.'], TStringSplitOptions.ExcludeEmpty);
for i := 0 to Length(aStr) - 1 do begin
Val(aStr[i], iVal, iCode);
if (iCode = 0) and (iVal <= 255) then
Inc(iCnt)
else
Break;
end;
Result := (iCnt = 4);
end;
procedure Add(const AParam: String);
var
sName, sValue: String;
i: Integer;
begin
i := Pos('=', AParam);
if i > 0 then begin
sName := Copy(AParam, 1, i - 1);
sValue := Copy(AParam, i + 1, MaxInt);
sValue := StringReplace(sValue, '\', '\\', [rfReplaceAll]);
sValue := StringReplace(sValue, '''', '\''', [rfReplaceAll]);
if Pos(' ', sValue) > 0 then
sValue := '''' + sValue + '''';
end
else begin
sName := AParam;
sValue := '''''';
end;
if Result <> '' then
Result := Result + ' ';
Result := Result + sName + '=' + sValue;
end;
var
oParams: TFDPhysPGConnectionDefParams;
i: Integer;
sAdv: String;
begin
oParams := AConnectionDef.Params as TFDPhysPGConnectionDefParams;
Result := '';
i := 1;
sAdv := oParams.PGAdvanced;
while i <= Length(sAdv) do
Add(FDExtractFieldName(sAdv, i));
if AConnectionDef.HasValue(S_FD_ConnParam_Common_Server) then
if IsIpAddress(oParams.Server) then
Add('hostaddr=' + oParams.Server)
else
Add('host=' + oParams.Server);
if AConnectionDef.HasValue(S_FD_ConnParam_Common_Port) then
Add('port=' + IntToStr(oParams.Port));
if AConnectionDef.HasValue(S_FD_ConnParam_Common_Database) then
Add('dbname=' + oParams.Database);
if AConnectionDef.HasValue(S_FD_ConnParam_Common_UserName) then
Add('user=' + oParams.UserName);
if AConnectionDef.HasValue(S_FD_ConnParam_Common_Password) then
Add('password=' + oParams.Password);
if AConnectionDef.HasValue(S_FD_ConnParam_Common_LoginTimeout) then
Add('connect_timeout=' + IntToStr(oParams.LoginTimeout));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgConnection.InternalConnect;
var
oParams: TFDPhysPGConnectionDefParams;
pCliHandles: PFDPhysPGCliHandles;
sSample: String;
i: Integer;
sEncPassword: String;
procedure SetEncoder(const AEncoding: String);
begin
if SameText(AEncoding, 'UTF8') or SameText(AEncoding, 'UNICODE') then
FConnection.Encoder.Encoding := ecUTF8
else
FConnection.Encoder.Encoding := ecANSI;
end;
begin
oParams := ConnectionDef.Params as TFDPhysPGConnectionDefParams;
if InternalGetSharedCliHandle() <> nil then begin
pCliHandles := PFDPhysPGCliHandles(InternalGetSharedCliHandle());
FConnection := TPgConnection.CreateUsingHandle(FEnv, pCliHandles^[0],
pCliHandles^[1], Self);
end
else
FConnection := TPgConnection.Create(FEnv, Self);
{$IFDEF FireDAC_MONITOR}
InternalTracingChanged;
{$ENDIF}
if InternalGetSharedCliHandle() = nil then begin
SetEncoder(ConnectionDef.AsString[S_FD_ConnParam_Common_CharacterSet]);
FConnection.Connect(BuildPgConnectString(ConnectionDef));
if ConnectionDef.HasValue(S_FD_ConnParam_Common_CharacterSet) then
FConnection.ClientEncoding := ConnectionDef.AsString[S_FD_ConnParam_Common_CharacterSet];
if oParams.NewPassword <> '' then begin
sEncPassword := FConnection.EncryptPassword(oParams.NewPassword, oParams.UserName, '');
InternalExecuteDirect('ALTER USER ' + oParams.UserName +
' PASSWORD ''' + sEncPassword + '''', nil);
end;
end;
FServerVersion := FConnection.ServerVersion;
SetEncoder(FConnection.ClientEncoding);
FExtendedMetadata := oParams.ExtendedMetadata;
FOidAsBlob := oParams.OidAsBlob;
if oParams.UnknownFormat = ufBYTEA then
FConnection.UnknownFormat := SQL_BYTEA
else
FConnection.UnknownFormat := 0;
sSample := oParams.ArrayScanSample;
if sSample <> '' then begin
i := 1;
FArrayScanSample := StrToIntDef(FDExtractFieldName(sSample, i), 0);
FArrayDefSize := StrToIntDef(FDExtractFieldName(sSample, i), 5);
end
else begin
FArrayScanSample := 0;
FArrayDefSize := 0;
end;
FGUIDEndian := oParams.GUIDEndian;
if (FServerVersion >= svPGSQL090000) and
ConnectionDef.HasValue(S_FD_ConnParam_Common_ApplicationName) then
InternalExecuteDirect('SET APPLICATION_NAME TO ''' + oParams.ApplicationName + '''', nil);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgConnection.InternalSetMeta;
begin
inherited InternalSetMeta;
if FCurrentSchema = '' then
UpdateCurrentMeta;
if FDefaultSchema = '' then
FDefaultSchema := 'public';
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgConnection.InternalDisconnect;
begin
FDFreeAndNil(FConnection);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgConnection.InternalChangePassword(const AUserName,
AOldPassword, ANewPassword: String);
var
oConnDef: IFDStanConnectionDef;
oConn: TPgConnection;
sEncPassword: String;
begin
FDCreateInterface(IFDStanConnectionDef, oConnDef);
oConnDef.ParentDefinition := ConnectionDef;
oConnDef.Params.UserName := AUserName;
oConnDef.Params.Password := AOldPassword;
oConn := TPgConnection.Create(FEnv, Self);
try
oConn.Connect(BuildPgConnectString(oConnDef));
sEncPassword := oConn.EncryptPassword(ANewPassword, oConnDef.Params.UserName, '');
oConn.ExecuteQuery('ALTER USER ' + oConnDef.Params.UserName +
' PASSWORD ''' + sEncPassword + '''');
finally
FDFree(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgConnection.InternalExecuteDirect(const ASQL: String;
ATransaction: TFDPhysTransaction);
begin
FConnection.ExecuteQuery(ASQL);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.GetLastAutoGenValue(const AName: String): Variant;
begin
if (FConnection <> nil) and (AName = '') then
if FConnection.LastInsertOid = InvalidOid then
Result := Null
else
Result := FConnection.LastInsertOid
else
Result := inherited GetLastAutoGenValue(AName);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.GetItemCount: Integer;
begin
Result := inherited GetItemCount;
if FEnv <> nil then begin
Inc(Result, 3);
if FConnection <> nil then
Inc(Result, 9);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgConnection.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
begin
if AIndex < inherited GetItemCount then
inherited GetItem(AIndex, AName, AValue, AKind)
else
case AIndex - inherited GetItemCount of
0:
begin
AName := 'Client brand';
if FEnv.Lib.Brand = pbRegular then
AValue := 'PostgreSQL regular'
else
AValue := 'Enterprise DB';
AKind := ikClientInfo;
end;
1:
begin
AName := 'Client version';
AValue := Integer(FEnv.Lib.Version);
AKind := ikClientInfo;
end;
2:
begin
AName := 'Client DLL name';
AValue := FEnv.Lib.DLLName;
AKind := ikClientInfo;
end;
3:
begin
AName := 'Server version';
AValue := FConnection.SERVER_VERSION;
AKind := ikSessionInfo;
end;
4:
begin
AName := 'Server encoding';
AValue := FConnection.SERVER_ENCODING;
AKind := ikSessionInfo;
end;
5:
begin
AName := 'Client encoding';
AValue := FConnection.CLIENT_ENCODING;
AKind := ikSessionInfo;
end;
6:
begin
AName := 'Is superuser';
AValue := FConnection.IS_SUPERUSER;
AKind := ikSessionInfo;
end;
7:
begin
AName := 'Session authorization';
AValue := FConnection.SESSION_AUTHORIZATION;
AKind := ikSessionInfo;
end;
8:
begin
AName := 'Date style';
AValue := FConnection.DATESTYLE;
AKind := ikSessionInfo;
end;
9:
begin
AName := 'Integer date/times';
AValue := FConnection.INTEGER_DATETIMES;
AKind := ikSessionInfo;
end;
10:
begin
AName := 'Time zone';
AValue := FConnection.TIMEZONE;
AKind := ikSessionInfo;
end;
11:
begin
AName := 'Standard conforming strings';
AValue := FConnection.STANDARD_CONFORMING_STRINGS;
AKind := ikSessionInfo;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.GetMessages: EFDDBEngineException;
begin
if FConnection <> nil then
Result := FConnection.Notices
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.GetCliObj: Pointer;
begin
Result := FConnection;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.InternalGetCliHandle: Pointer;
begin
if FConnection <> nil then begin
FCliHandles[0] := FConnection.FHandle;
FCliHandles[1] := @FConnection.FStmtIDCounter;
Result := @FCliHandles;
end
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgConnection.UpdateCurrentMeta;
var
oStmt: TPgStatement;
dt: TDateTime;
sTS: String;
iLen: LongWord;
iUseMonths: Integer;
rTS: TSQLTimeStamp;
begin
FConnection.TimeZoneOffset := 0;
FUseMonthsBetween := False;
dt := Now();
sTS := FormatDateTime('yyyy''-''mm''-''dd hh'':''nn'':''ss', dt);
oStmt := TPgStatement.Create(FConnection, Self);
try
oStmt.PrepareSQL('SELECT CURRENT_DATABASE(), CURRENT_SCHEMA(), ''' + sTS + '''::TIMESTAMPTZ, ' +
'(SELECT MIN(1) FROM PG_CATALOG.PG_PROC WHERE PRONAME = ''months_between''), ' +
'(SELECT SETTING FROM PG_CATALOG.PG_SETTINGS WHERE NAME = ''standard_conforming_strings'')');
oStmt.Execute;
oStmt.DescribeFields;
oStmt.Fetch;
FMetaCatalog := oStmt.Fields[0].GetAsString;
FCurrentSchema := oStmt.Fields[1].GetAsString;
if oStmt.ResultFormat = 1 then
if oStmt.Fields[2].GetData(@rTS, iLen) then begin
dt := dt - SQLTimeStampToDateTime(rTS);
if dt >= 0 then
dt := dt + OneSecond
else
dt := dt - OneSecond;
FConnection.TimeZoneOffset := Trunc(dt / OneHour);
FUseMonthsBetween := (oStmt.Fields[3].GetData(@iUseMonths, iLen) and (iUseMonths = 1));
end;
FBackslashEscape := SameText(oStmt.Fields[4].GetAsString, 'off');
finally
FDFree(oStmt);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgConnection.AdjustOIDasBLOB(const ATypeName, ANameSpace: String;
var ADataType: TFDDataType; var AAttrs: TFDDataAttributes): Boolean;
begin
Result :=
(FOidAsBlob = oabYes) or (FOidAsBlob = oabChoose) and (
// large object column must have a specially named domain
(CompareText(ATypeName, 'LO') = 0) or
(CompareText(ATypeName, 'LARGEOBJECT') = 0) or
(CompareText(ATypeName, 'BLOB') = 0)
) and not (
// large object column cannot be in the dictionary
(CompareText(ANameSpace, 'information_schema') = 0) or
(CompareText(ANameSpace, 'pg_catalog') = 0)
);
if Result then begin
AAttrs := AAttrs - [caSearchable] + [caBlobData];
ADataType := dtHBlob;
end
else begin
AAttrs := AAttrs + [caSearchable] - [caBlobData];
ADataType := dtUInt32;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysPgTransaction }
{-------------------------------------------------------------------------------}
procedure TFDPhysPgTransaction.InternalStartTransaction(ATxID: LongWord);
begin
TFDPhysPgConnection(ConnectionObj).InternalExecuteDirect('BEGIN', nil);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgTransaction.InternalCommit(ATxID: LongWord);
begin
DisconnectCommands(nil, dmRelease);
TFDPhysPgConnection(ConnectionObj).InternalExecuteDirect('COMMIT', nil);
if Retaining then
InternalStartTransaction(ATxID);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgTransaction.InternalRollback(ATxID: LongWord);
begin
DisconnectCommands(nil, dmRelease);
TFDPhysPgConnection(ConnectionObj).InternalExecuteDirect('ROLLBACK', nil);
if Retaining then
InternalStartTransaction(ATxID);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgTransaction.InternalChanged;
var
sSQL: String;
begin
sSQL := '';
if GetOptions.Isolation <> xiUnspecified then begin
sSQL := sSQL + ' ISOLATION LEVEL ';
case GetOptions.Isolation of
xiDirtyRead:
sSQL := sSQL + 'READ UNCOMMITTED';
xiReadCommitted:
sSQL := sSQL + 'READ COMMITTED';
xiRepeatableRead,
xiSnapshot:
sSQL := sSQL + 'REPEATABLE READ';
xiSerializible:
sSQL := sSQL + 'SERIALIZABLE';
end;
end;
if GetOptions.ReadOnly then
sSQL := sSQL + ' READ ONLY';
if sSQL <> '' then
TFDPhysPgConnection(ConnectionObj).InternalExecuteDirect(
'SET SESSION CHARACTERISTICS AS TRANSACTION' + sSQL, nil);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgTransaction.InternalCheckState(ACommandObj: TFDPhysCommand;
ASuccess: Boolean);
var
oCmd: TFDPhysPgCommand;
begin
oCmd := TFDPhysPgCommand(ACommandObj);
if (oCmd.PgConnection.PgConnection <> nil) and
(GetActive <> (oCmd.PgConnection.PgConnection.TransactionStatus = PQTRANS_INTRANS)) then
case oCmd.PgConnection.PgConnection.TransactionStatus of
PQTRANS_IDLE:
TransactionFinished;
PQTRANS_INTRANS:
TransactionStarted;
PQTRANS_INERROR:
if GetNestingLevel = 1 then begin
// Seting FState to csRecovering is needed to avoid fetching by
// datasets. They will set FSourceEOF to True without fetching.
oCmd.PgConnection.Lock;
try
oCmd.PgConnection.FState := csRecovering;
DisconnectCommands(nil, dmOffline);
finally
if oCmd.PgConnection.FState = csRecovering then
oCmd.PgConnection.FState := csConnected;
oCmd.PgConnection.UnLock;
end;
// Now application must explicitly Commit / Rollback failed transaction
// TransactionFinished;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgTransaction.InternalNotify(ANotification: TFDPhysTxNotification;
ACommandObj: TFDPhysCommand);
var
lInherited: Boolean;
begin
lInherited := False;
case ANotification of
cpBeforeCmdExecute:
if TFDPhysPgCommand(ACommandObj).GetCommandKind in [skCommit, skRollback] then
DisconnectCommands(nil, dmRelease)
else if (TFDPhysPgCommand(ACommandObj).GetCommandKind = skStoredProcWithCrs) and
(TFDPhysPgCommand(ACommandObj).PgStatement.RowsetSize >= 0) then begin
if GetOptions.AutoStart and not GetActive then begin
StartTransaction;
FIDAutoCommit := GetSerialID;
end
end
else
lInherited := True;
cpAfterCmdExecuteSuccess,
cpAfterCmdExecuteFailure:
if (TFDPhysPgCommand(ACommandObj).GetCommandKind = skStoredProcWithCrs) and
(TFDPhysPgCommand(ACommandObj).PgStatement.RowsetSize >= 0) then begin
if GetOptions.AutoStop and GetActive and
(not (xoIfAutoStarted in GetOptions.StopOptions) or
(FIDAutoCommit <> 0) and (FIDAutoCommit = GetSerialID)) then
// allowunprepare, force, success
CheckStoping(not (ANotification in [cpAfterCmdUnprepare, cpAfterCmdPrepareFailure]),
not (xoIfCmdsInactive in GetOptions.StopOptions),
not (ANotification in [cpAfterCmdPrepareFailure, cpAfterCmdExecuteFailure]));
end
else
lInherited := True;
else
lInherited := True;
end;
if lInherited then
inherited InternalNotify(ANotification, ACommandObj);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysPgEventMessage }
{-------------------------------------------------------------------------------}
type
TFDPhysPgEventMessage = class(TFDPhysEventMessage)
private
FName: String;
FProcID: Integer;
FParam: String;
public
constructor Create(const AName: String; AProcID: Integer; const AParam: String);
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysPgEventMessage.Create(const AName: String; AProcID: Integer;
const AParam: String);
begin
inherited Create;
FName := AName;
FProcID := AProcID;
FParam := AParam;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysPgEventThread }
{-------------------------------------------------------------------------------}
type
TFDPhysPgEventThread = class(TThread)
private
[weak] FAlerter: TFDPhysPgEventAlerter;
protected
procedure Execute; override;
public
constructor Create(AAlerter: TFDPhysPgEventAlerter);
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysPgEventThread.Create(AAlerter: TFDPhysPgEventAlerter);
begin
inherited Create(False);
FAlerter := AAlerter;
FreeOnTerminate := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysPgEventThread.Destroy;
begin
FAlerter.FWaitThread := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgEventThread.Execute;
var
oConn: TPgConnection;
sName, sParam: String;
iProcID: Integer;
begin
while not Terminated and FAlerter.IsRunning do
try
oConn := TPgConnection(FAlerter.FWaitConnection.CliObj);
if oConn.CheckForInput() then
while oConn.ReadNotifies(sName, iProcID, sParam) do
FAlerter.FMsgThread.EnqueueMsg(TFDPhysPgEventMessage.Create(
sName, iProcID, sParam));
except
on E: EFDDBEngineException do
if E.Kind <> ekCmdAborted then begin
Terminate;
FAlerter.AbortJob;
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysPgEventAlerter }
{-------------------------------------------------------------------------------}
procedure TFDPhysPgEventAlerter.InternalAllocHandle;
begin
FWaitConnection := GetConnection.Clone;
if FWaitConnection.State = csDisconnected then
FWaitConnection.Open;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgEventAlerter.InternalRegister;
var
i: Integer;
oCmd: IFDPhysCommand;
begin
FWaitConnection.CreateCommand(oCmd);
SetupCommand(oCmd);
for i := 0 to GetNames.Count - 1 do begin
oCmd.Prepare('LISTEN ' + GetNames[i]);
oCmd.Execute();
end;
FWaitThread := TFDPhysPgEventThread.Create(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgEventAlerter.InternalHandle(AEventMessage: TFDPhysEventMessage);
var
oMsg: TFDPhysPgEventMessage;
begin
oMsg := TFDPhysPgEventMessage(AEventMessage);
InternalHandleEvent(oMsg.FName, VarArrayOf([oMsg.FProcID, oMsg.FParam]));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgEventAlerter.InternalAbortJob;
begin
if FWaitThread <> nil then begin
FWaitThread.Terminate;
TPgConnection(FWaitConnection.CliObj).Abort;
while (FWaitThread <> nil) and (FWaitThread.ThreadID <> TThread.Current.ThreadID) do
Sleep(1);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgEventAlerter.InternalUnregister;
var
i: Integer;
oCmd: IFDPhysCommand;
begin
FWaitConnection.CreateCommand(oCmd);
SetupCommand(oCmd);
for i := 0 to GetNames.Count - 1 do begin
oCmd.Prepare('UNLISTEN ' + GetNames[i]);
oCmd.Execute();
end;
FWaitThread := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgEventAlerter.InternalReleaseHandle;
begin
FWaitConnection := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgEventAlerter.InternalSignal(const AEvent: String;
const AArgument: Variant);
var
oCmd: IFDPhysCommand;
sCmd: String;
begin
FWaitConnection.CreateCommand(oCmd);
SetupCommand(oCmd);
sCmd := 'NOTIFY ' + AEvent;
if not VarIsEmpty(AArgument) then
if TFDPhysPgConnection(ConnectionObj).FServerVersion >= svPGSQL090000 then
sCmd := sCmd + ', ' + QuotedStr(VarToStr(AArgument))
else
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_PGId]);
oCmd.Prepare(sCmd);
oCmd.Execute();
end;
{-------------------------------------------------------------------------------}
{ TFDPhysPgSPDesriber }
{-------------------------------------------------------------------------------}
constructor TFDPhysPgSPDescriber.Create(ACommand: TFDPhysPgCommand;
const AName: TFDPhysParsedName);
begin
inherited Create;
FCommand := ACommand;
FName := AName;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgSPDescriber.CreateParams;
var
i: Integer;
oProcArgs: TFDProcArgRecs;
pArg: PFDProcArgRec;
begin
ReadProcArgs(oProcArgs);
for i := 0 to Length(oProcArgs) - 1 do begin
pArg := @oProcArgs[i];
CreateParam(pArg^.FName, pArg^.FParamType, pArg^.FTypeOid);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgSPDescriber.CreateParam(AName: String; AParamType: TParamType; ATypeOid: Oid);
var
uiSize: LongWord;
iPrec, iScale: Integer;
eSrcFDDataType, eDestFDDataType: TFDDataType;
eDestDataType: TFieldType;
eSrcAttrs: TFDDataAttributes;
uiDestSize: LongWord;
iDestPrec, iDestScale: Integer;
oType: TPgType;
i: Integer;
oParam: TFDParam;
oFmt: TFDFormatOptions;
oMbr: TPgMember;
begin
uiSize := 0;
iPrec := 0;
iScale := 0;
eSrcAttrs := [];
FCommand.SQL2FDColInfo(ATypeOid, 0, 0, 0, AParamType, eSrcFDDataType, eSrcAttrs,
uiSize, iPrec, iScale, FCommand.FOptions.FormatOptions);
if eSrcFDDataType <> dtUnknown then begin
oType := FCommand.PgConnection.FConnection.TypesManager.Types[ATypeOid];
oParam := FCommand.GetParams.Add;
try
oParam.Name := AName;
oParam.Position := oParam.Index + 1;
oParam.ParamType := AParamType;
oFmt := FCommand.FOptions.FormatOptions;
eDestFDDataType := dtUnknown;
eDestDataType := ftUnknown;
uiDestSize := 0;
iDestPrec := 0;
iDestScale := 0;
oFmt.ResolveDataType(AName, oType.Name, eSrcFDDataType, uiSize, iPrec, iScale,
eDestFDDataType, uiSize, True);
oFmt.ColumnDef2FieldDef(eDestFDDataType, uiSize, iPrec, iScale, eSrcAttrs,
eDestDataType, uiDestSize, iDestPrec, iDestScale);
except
FDFree(oParam);
raise;
end;
oParam.DataType := eDestDataType;
oParam.FDDataType := eDestFDDataType;
oParam.Size := uiDestSize;
oParam.Precision := iDestPrec;
oParam.NumericScale := iDestScale;
if (paArray in oType.Attrs) and (Length(oType.Members) = 1) then
oParam.ArrayType := atTable;
end
else
if AParamType = ptResult then begin
oType := FCommand.PgConnection.FConnection.TypesManager.Types[ATypeOid];
for i := 0 to Length(oType.Members) - 1 do begin
oMbr := oType.Members[i];
CreateParam(oMbr.Name, AParamType, oMbr.TypeOid);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgSPDescriber.ReadProcArgs(var AProcArgs: TFDProcArgRecs);
function SplitTextArray(const AStr: String): TFDStringArray;
var
i: Integer;
iPrevPos: Integer;
iIndex: Integer;
iLen: Integer;
begin
iIndex := 0;
iPrevPos := 1;
iLen := Length(AStr);
if iLen = 0 then
Exit;
SetLength(Result, iLen shr 1 + 1);
for i := 1 to iLen do
if AStr[i] = ';' then begin
Result[iIndex] := Copy(AStr, iPrevPos, i - iPrevPos);
iPrevPos := i + 1;
Inc(iIndex);
end;
Result[iIndex] := Copy(AStr, iPrevPos, Length(AStr));
SetLength(Result, iIndex + 1);
end;
var
i: Integer;
iIndex, iOverload: Integer;
sParamName, sParamType: String;
sParamTypes, sDataTypes, sParamNames: TFDStringArray;
bHasOutParams: Boolean;
iResTypeOid: Oid;
oPgStmt: TPgStatement;
oPgPar: TPgParam;
oGen: IFDPhysCommandGenerator;
begin
sParamNames := nil;
sDataTypes := nil;
sParamTypes := nil;
oPgStmt := TPgStatement.Create(FCommand.PgConnection.FConnection, Self);
try
FCommand.CreateCommandGenerator(oGen);
oPgStmt.Params.Count := 2;
oPgPar := oPgStmt.Params[0];
oPgPar.TypeOid := SQL_NAME;
oPgPar.Size := 70;
oPgPar.Encoding := ecUTF16;
oPgPar.SetData(PChar(FName.FObject), Length(FName.FObject));
oPgPar := oPgStmt.Params[1];
oPgPar.TypeOID := SQL_INT4;
oPgPar.Size := SizeOf(Integer);
iOverload := FCommand.GetOverload();
oPgPar.SetData(@iOverload, SizeOf(iOverload));
oPgStmt.PrepareSQL(oGen.GenerateSelectMetaInfo(mkProcArgs,
FName.FCatalog, FName.FSchema, FName.FBaseObject, FName.FObject,
FCommand.GetWildcard(), FCommand.GetObjectScopes(), FCommand.GetTableKinds(),
FCommand.GetOverload()));
oPgStmt.Execute;
oPgStmt.DescribeFields;
if not oPgStmt.Fetch then
FDException(Self, [S_FD_LPhys, S_FD_PGId], er_FD_PgProcNotFound,
[Trim(FCommand.GetCommandText)]);
iIndex := 0;
bHasOutParams := False;
sParamNames := SplitTextArray(oPgStmt.Fields[5].GetAsString);
sDataTypes := SplitTextArray(oPgStmt.Fields[3].GetAsString);
if Length(sDataTypes) = 0 then
sDataTypes := SplitTextArray(oPgStmt.Fields[2].GetAsString);
sParamTypes := SplitTextArray(oPgStmt.Fields[4].GetAsString);
for i := 0 to Length(sDataTypes) - 1 do begin
if Length(sParamTypes) > i then
sParamType := sParamTypes[i]
else
sParamType := 'i';
if Length(sParamNames) > i then
sParamName := sParamNames[i]
else
sParamName := '';
SetLength(AProcArgs, iIndex + 1);
AProcArgs[iIndex].FName := sParamName;
AProcArgs[iIndex].FTypeOid := StrToIntDef(sDataTypes[i], 0);
if sParamType = 'i' then
AProcArgs[iIndex].FParamType := ptInput
else
if sParamType = 'b' then
AProcArgs[iIndex].FParamType := ptInputOutput
else
if (sParamType = 'o') or (sParamType = 't') then
AProcArgs[iIndex].FParamType := ptOutput
else
ASSERT(False);
if AProcArgs[iIndex].FParamType = ptOutput then
bHasOutParams := True;
Inc(iIndex);
end;
if not bHasOutParams and oPgStmt.Fields[1].GetData(@iResTypeOid) then
if iResTypeOid <> SQL_VOID then begin
SetLength(AProcArgs, iIndex + 1);
AProcArgs[iIndex].FName := 'result';
AProcArgs[iIndex].FParamType := ptResult;
AProcArgs[iIndex].FTypeOid := iResTypeOid;
end;
finally
FDFree(oPgStmt);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysPgCommand }
{-------------------------------------------------------------------------------}
constructor TFDPhysPgCommand.Create(AConnectionObj: TFDPhysConnection);
begin
inherited Create(AConnectionObj);
FInfoStack := TFDPtrList.Create;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysPgCommand.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FInfoStack);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.GetCliObj: Pointer;
begin
Result := FStmt;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.GetConnection: TFDPhysPgConnection;
begin
Result := TFDPhysPgConnection(FConnectionObj);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.UseExecDirect: Boolean;
begin
Result := (FOptions.ResourceOptions.DirectExecute) or
(GetCommandKind in [skSet, skSetSchema, skCreate, skDrop, skAlter, skOther,
skStartTransaction, skCommit, skRollback]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.InternalPrepare;
var
rName: TFDPhysParsedName;
oConnMeta: IFDPhysConnectionMetadata;
oDesc: TFDPhysPgSPDescriber;
begin
FInfoStack.Clear;
FActiveCrs := -1;
GetConnection.CreateMetadata(oConnMeta);
// generate metadata SQL command
if GetMetaInfoKind <> mkNone then begin
if GetMetaInfoKind = mkProcArgs then
// A select meta info command will be executed right in InternalFetchRowSet,
// inside of FetchSPParamRows
FDbCommandText := ''
else begin
GetSelectMetaInfoParams(rName);
// To restrict schema in GetSelectMetaInfo to an explicitly specified one,
// clear implicitly specified 'public'.
if (GetMetaInfoKind in [mkTables, mkPackages, mkProcs, mkGenerators]) and
(GetSchemaName = '') and (CompareText(rName.FSchema, 'public') = 0) then
rName.FSchema := '';
GenerateSelectMetaInfo(rName);
end;
if FDbCommandText = '' then
Exit;
end
// generate stored proc call SQL command
else if GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs] then begin
FDbCommandText := '';
if fiMeta in FOptions.FetchOptions.Items then begin
oConnMeta.DecodeObjName(Trim(GetCommandText()), rName, Self, [doNormalize, doUnquote]);
GetParams.Clear;
oDesc := TFDPhysPgSPDescriber.Create(Self, rName);
try
oDesc.CreateParams;
finally
FDFree(oDesc);
end;
end;
if FDbCommandText = '' then begin
oConnMeta.DecodeObjName(Trim(GetCommandText()), rName, Self, []);
GenerateStoredProcCall(rName, GetCommandKind);
end;
end;
// adjust SQL command
GenerateLimitSelect();
GenerateParamMarkers();
FOidAsBlob := False;
case PgConnection.FOidAsBlob of
oabYes:
FOidAsBlob := True;
oabChoose:
if (GetMetaInfoKind = mkNone) and
oConnMeta.DecodeObjName(GetSourceObjectName, rName, Self,
[doNormalize, doUnquote, doNotRaise]) then
FOidAsBlob := not ((CompareText(rName.FSchema, 'pg_catalog') = 0) or
(CompareText(rName.FSchema, 'information_schema') = 0) or
(CompareText(Copy(rName.FObject, 1, 3), 'pg_') = 0));
end;
FStmt := CreateStmt;
FBaseStmt := FStmt;
// describe params
if GetParams.Count > 0 then
CreateParamInfos;
if not UseExecDirect then
FStmt.PrepareSQL(FDbCommandText);
FCursorCanceled := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.FDType2SQL(AType: TFDDataType; const ATypeName: String;
AArray: Boolean): Oid;
begin
if ATypeName <> '' then
Result := PgConnection.FConnection.TypesManager.TypeByName(ATypeName).Id
else
case AType of
dtSByte,
dtByte,
dtInt16,
dtUInt16:
Result := SQL_INT2;
dtInt32,
dtUInt32:
Result := SQL_INT4;
dtInt64,
dtUInt64:
Result := SQL_INT8;
dtSingle:
Result := SQL_FLOAT4;
dtDouble,
dtExtended:
Result := SQL_FLOAT8;
dtCurrency:
Result := SQL_CASH;
dtBCD,
dtFmtBcd:
Result := SQL_NUMERIC;
dtAnsiString,
dtWideString:
Result := SQL_VARCHAR;
dtMemo,
dtWideMemo,
dtHMemo,
dtWideHMemo:
Result := SQL_TEXT;
dtXML:
Result := SQL_XML;
dtByteString,
dtBlob,
dtHBFile:
Result := SQL_BYTEA;
dtHBlob:
Result := SQL_OID;
dtDate:
Result := SQL_DATE;
dtTime:
Result := SQL_TIME;
dtDateTime,
dtDateTimeStamp:
Result := SQL_TIMESTAMP;
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS:
Result := SQL_INTERVAL;
dtBoolean:
Result := SQL_BOOL;
dtCursorRef:
Result := SQL_REFCURSOR;
dtGUID:
Result := SQL_UUID;
else
Result := SQL_UNKNOWN;
end;
if AArray and (Result <> SQL_UNKNOWN) and
not (paArray in PgConnection.FConnection.TypesManager.Types[Result].Attrs) then
Result := PgConnection.FConnection.TypesManager.Arrays[Result].Id;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.SQL2FDColInfo(ASQLTypeOID: Oid; ASQLLen: LongWord;
ASQLPrec, ASQLScale: Integer; AParamType: TParamType; out AType: TFDDataType;
var AAttrs: TFDDataAttributes; out ALen: LongWord; out APrec, AScale: Integer;
AFmtOpts: TFDFormatOptions);
var
oType: TPgType;
begin
AType := dtUnknown;
ALen := 0;
APrec := 0;
AScale := 0;
Exclude(AAttrs, caFixedLen);
Exclude(AAttrs, caBlobData);
Include(AAttrs, caSearchable);
case ASQLTypeOid of
SQL_INT2,
SQL_SMGR:
AType := dtInt16;
SQL_INT4:
AType := dtInt32;
SQL_INT8:
AType := dtInt64;
SQL_FLOAT4:
AType := dtSingle;
SQL_FLOAT8:
AType := dtDouble;
SQL_CASH:
begin
APrec := 19;
AScale := 4;
AType := dtCurrency;
end;
SQL_NUMERIC:
begin
APrec := ASQLPrec;
AScale := ASQLScale;
if AFmtOpts.IsFmtBcd(APrec, AScale) or
// this information is not provided for SP
((APrec = 0) and (AScale = 0)) then
AType := dtFmtBCD
else
AType := dtBCD;
end;
SQL_CHAR,
SQL_BPCHAR,
SQL_VARCHAR,
SQL_NAME,
SQL_ACLITEM,
SQL_VOID:
if ASQLLen <= AFmtOpts.MaxStringSize then begin
ALen := ASQLLen;
if PgConnection.FConnection.Encoder.Encoding = ecUTF8 then
AType := dtWideString
else
AType := dtAnsiString;
if paFixed in PgConnection.FConnection.TypesManager.Types[ASQLTypeOID].Attrs then
Include(AAttrs, caFixedLen);
end
else begin
if PgConnection.FConnection.Encoder.Encoding = ecUTF8 then
AType := dtWideMemo
else
AType := dtMemo;
Include(AAttrs, caBlobData);
end;
SQL_MACADDR,
SQL_MACADDR8,
SQL_CIDR,
SQL_INET:
if UseExecDirect then begin
ALen := ASQLLen;
if PgConnection.FConnection.Encoder.Encoding = ecUTF8 then
AType := dtWideString
else
AType := dtAnsiString;
end
else begin
AType := dtByteString;
ALen := ASQLLen;
end;
SQL_BIT:
begin
AType := dtByteString;
ALen := ASQLLen;
Include(AAttrs, caFixedLen);
end;
SQL_VARBIT:
begin
AType := dtByteString;
ALen := ASQLLen;
end;
SQL_UNKNOWN:
begin
ALen := AFmtOpts.MaxStringSize;
if PgConnection.FConnection.Encoder.Encoding = ecUTF8 then
AType := dtWideString
else
AType := dtAnsiString;
end;
SQL_TEXT,
SQL_JSON,
SQL_JSONB:
begin
if PgConnection.FConnection.Encoder.Encoding = ecUTF8 then
AType := dtWideMemo
else
AType := dtMemo;
Include(AAttrs, caBlobData);
if ASQLTypeOid = SQL_TEXT then
Exclude(AAttrs, caSearchable);
end;
SQL_XML:
begin
AType := dtXML;
Include(AAttrs, caBlobData);
end;
SQL_BYTEA:
begin
AType := dtBlob;
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end;
SQL_ANY:
begin
AType := dtByteString;
ALen := ASQLLen;
end;
SQL_DATE:
AType := dtDate;
SQL_TIME,
SQL_TIMETZ:
begin
AType := dtTime;
if (ASQLScale >= 0) and (ASQLScale < 3) then
AScale := C_FD_ScaleFactor[3 - ASQLScale];
end;
SQL_TIMESTAMP,
SQL_TIMESTAMPTZ,
SQL_RELTIME,
SQL_ABSTIME:
begin
AType := dtDateTimeStamp;
if (ASQLScale >= 0) and (ASQLScale < 3) then
AScale := C_FD_ScaleFactor[3 - ASQLScale];
end;
SQL_INTERVAL:
begin
AType := dtTimeIntervalFull;
if (ASQLScale >= 0) and (ASQLScale < 3) then
AScale := C_FD_ScaleFactor[3 - ASQLScale];
end;
SQL_BOOL:
AType := dtBoolean;
SQL_OID:
if FOidAsBlob and (FResultSetMode <> 2) and ([caROWID, caReadOnly] * AAttrs = []) then begin
AType := dtHBlob;
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end
else
AType := dtUInt32;
SQL_XID,
SQL_CID,
SQL_REGPROC,
SQL_REGPROCEDURE,
SQL_REGOPER,
SQL_REGOPERATOR,
SQL_REGCLASS,
SQL_REGTYPE:
AType := dtUInt32;
SQL_TID:
begin
AType := dtByteString;
ALen := SizeOf(Tid);
Include(AAttrs, caFixedLen);
end;
SQL_REFCURSOR:
AType := dtCursorRef;
SQL_UUID:
AType := dtGUID;
else
oType := PgConnection.FConnection.TypesManager.Types[ASQLTypeOID];
if paArray in oType.Attrs then
SQL2FDColInfo(oType.Members[0].TypeOid, ASQLLen, ASQLPrec, ASQLScale,
AParamType, AType, AAttrs, ALen, APrec, AScale, AFmtOpts)
else if paEnum in oType.Attrs then begin
if PgConnection.FConnection.Encoder.Encoding = ecUTF8 then
AType := dtWideString
else
AType := dtAnsiString;
ALen := NAMEMAXLEN;
end
else if (paRecord in oType.Attrs) and (AParamType <> ptResult) or
(paRange in oType.Attrs) then begin
AType := dtRowRef;
Exclude(AAttrs, caSearchable);
end
else if ASQLTypeOID <> oType.Id then begin
if ASQLLen = 0 then
ASQLLen := oType.PGSize;
SQL2FDColInfo(oType.Id, ASQLLen, ASQLPrec, ASQLScale, AParamType,
AType, AAttrs, ALen, APrec, AScale, AFmtOpts);
end
else begin
ASQLTypeOid := PgConnection.FConnection.UnknownFormat;
if (ASQLTypeOid = 0) and (paBlob in oType.Attrs) then
if paString in oType.Attrs then
ASQLTypeOid := SQL_TEXT
else
ASQLTypeOid := SQL_BYTEA;
if ASQLTypeOid = 0 then
AType := dtUnknown
else
SQL2FDColInfo(ASQLTypeOid, ASQLLen, ASQLPrec, ASQLScale, AParamType,
AType, AAttrs, ALen, APrec, AScale, AFmtOpts);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.CreateStmt: TPgStatement;
var
oFmt: TFDFormatOptions;
oFtch: TFDFetchOptions;
begin
Result := TPgStatement.Create(PgConnection.FConnection, Self);
oFmt := FOptions.FormatOptions;
oFtch := FOptions.FetchOptions;
Result.StrsTrim := oFmt.StrsTrim;
Result.StrsEmpty2Null := oFmt.StrsEmpty2Null;
Result.StrsTrim2Len := oFmt.StrsTrim2Len;
Result.GUIDEndian := PgConnection.FGUIDEndian;
if (oFtch.Mode in [fmManual, fmOnDemand]) and (oFtch.CursorKind <> ckDefault) and
(GetCommandKind <> skStoredProcNoCrs) and not FOptions.ResourceOptions.DirectExecute then
Result.RowsetSize := oFtch.ActualRowsetSize
else
Result.RowsetSize := -1;
Result.WithHold := (GetCommandKind <> skSelectForLock) and
not PgConnection.GetTransaction.Active or (oFtch.CursorKind = ckStatic);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.CreateParamInfos;
var
i: Integer;
oFmtOpts: TFDFormatOptions;
oParams: TFDParams;
oParam: TFDParam;
iPgParIndex, iPgParRef: Integer;
oPgParam: TPgParam;
eDestFldType: TFieldType;
eAttrs: TFDDataAttributes;
iPrec, iScale: Integer;
iLen: LongWord;
pInfo: PFDPgParInfoRec;
begin
oFmtOpts := FOptions.FormatOptions;
oParams := GetParams;
iPgParIndex := 0;
for i := 0 to oParams.Count - 1 do
if oParams[i].ParamType in [ptUnknown, ptInput, ptInputOutput] then
Inc(iPgParIndex);
FStmt.Params.Count := iPgParIndex;
SetLength(FBaseVecInfo.FParInfos, iPgParIndex);
iPgParIndex := 0;
for i := 0 to oParams.Count - 1 do begin
oParam := oParams[i];
if oParam.ParamType in [ptUnknown, ptInput, ptInputOutput] then begin
pInfo := @FBaseVecInfo.FParInfos[iPgParIndex];
case GetParams.BindMode of
pbByName: iPgParRef := iPgParIndex;
pbByNumber: iPgParRef := oParam.Position - 1;
else iPgParRef := -1;
end;
if (iPgParRef >= 0) and (iPgParRef < FStmt.Params.Count) then begin
oPgParam := FStmt.Params[iPgParRef];
pInfo^.FPgParamIndex := iPgParRef;
pInfo^.FParamIndex := i;
pInfo^.FParamType := oParam.ParamType;
if oParam.DataType = ftUnknown then
ParTypeUnknownError(oParam);
pInfo^.FSrcFieldType := oParam.DataType;
oFmtOpts.ResolveFieldType('', oParam.DataTypeName, oParam.DataType,
oParam.FDDataType, oParam.Size, oParam.Precision, oParam.NumericScale,
eDestFldType, pInfo^.FSrcSize, pInfo^.FSrcPrec, pInfo^.FSrcScale,
pInfo^.FSrcDataType, pInfo^.FDestDataType, False);
pInfo^.FOutSQLDataType := FDType2SQL(pInfo^.FDestDataType,
oParam.DataTypeName, oParam.ArrayType = atTable);
eAttrs := [];
SQL2FDColInfo(pInfo^.FOutSQLDataType, pInfo^.FSrcSize, pInfo^.FSrcPrec,
pInfo^.FSrcScale, pInfo^.FParamType, pInfo^.FOutDataType, eAttrs,
iLen, iPrec, iScale, oFmtOpts);
if oPgParam.DumpLabel = '' then
oPgParam.DumpLabel := oParam.DisplayName;
oPgParam.TypeOID := pInfo^.FOutSQLDataType;
oPgParam.Size := pInfo^.FSrcSize;
if pInfo^.FOutDataType in [dtWideString, dtWideMemo, dtXML, dtWideHMemo] then
oPgParam.Encoding := ecUTF16
else
oPgParam.Encoding := ecANSI;
end;
Inc(iPgParIndex);
end;
FStmtParamsCount := iPgParIndex;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.DestroyParamInfos;
begin
SetLength(FBaseVecInfo.FParInfos, 0);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.CheckFixedArray(AField: TPgField; var ALen: Integer): Boolean;
var
i, iLBound, iHBound: Integer;
lClosed: Boolean;
iPrevRow: Int64;
begin
ALen := 0;
Result := False;
if not ((paArray in AField.TypeRef.Attrs) and (PgConnection.FArrayScanSample > 0) and
(Length(AField.TypeRef.Members) > 0) and not (paArray in AField.TypeRef.Members[0].TypeRef.Attrs)) then
Exit;
iPrevRow := FStmt.CurrentRow;
try
for i := 0 to Min(FStmt.RowsSelected, PgConnection.FArrayScanSample) - 1 do begin
FStmt.CurrentRow := i;
if AField.GetArrayBounds(iLBound, iHBound, lClosed) then
ALen := Max(ALen, iHBound - iLBound + 1);
end;
if ALen > 0 then
Result := True
else if PgConnection.FArrayDefSize > 0 then begin
ALen := PgConnection.FArrayDefSize;
Result := True;
end;
finally
FStmt.CurrentRow := iPrevRow;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.CreateColInfos;
var
lGetDSInfo: Boolean;
i: Integer;
oFmtOpts: TFDFormatOptions;
oFetchOpts: TFDFetchOptions;
oField: TPgField;
sTableOid, sTablesOids: String;
iAttrs: Integer;
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
j: Integer;
V: Variant;
iBaseTableOid: Oid;
pInfo: PFDPgColInfoRec;
oRow: TFDDatSRow;
iLen: Integer;
procedure CreateRecInfo(ADsField: TPgField; AType: TPgType;
var ARecInfo: TFDPgRecInfoRec);
function Def(AVal, ADef: Integer): Integer;
begin
if AVal <= 0 then
Result := ADef
else
Result := AVal;
end;
var
i, nFields: Integer;
pInfo: PFDPgColInfoRec;
oMember: TPgMember;
oField: TPgField;
iLen: Integer;
begin
ARecInfo.FColIndex := 0;
nFields := Length(AType.Members);
SetLength(ARecInfo.FColInfos, nFields);
for i := 0 to nFields - 1 do begin
pInfo := @ARecInfo.FColInfos[i];
oMember := AType.Members[i];
oField := ADsField.Fields[i];
pInfo^.FField := oField;
pInfo^.FName := oMember.Name;
pInfo^.FPos := i + 1;
pInfo^.FSrcSQLDataType := oMember.TypeOid;
pInfo^.FAttrs := oMember.Attrs;
if [paArray, paRecord, paRange] * oMember.TypeRef.Attrs <> [] then begin
if paRecord in oField.TypeRef.Attrs then
pInfo^.FSrcDataType := dtRowRef
else if paRange in oField.TypeRef.Attrs then begin
Include(pInfo^.FAttrs, caReadOnly);
pInfo^.FSrcDataType := dtRowRef;
end
else begin
Include(pInfo^.FAttrs, caReadOnly);
if oMember.TypeRef.IsFlatFixedArray then begin
pInfo^.FSrcDataType := dtArrayRef;
pInfo^.FLen := oMember.TypeRef.FixedLen;
end
else if CheckFixedArray(oField, iLen) then begin
pInfo^.FSrcDataType := dtArrayRef;
pInfo^.FLen := iLen;
end
else
pInfo^.FSrcDataType := dtRowSetRef;
end;
GetMem(pInfo^.FRecInfo, SizeOf(TFDPgRecInfoRec));
FillChar(pInfo^.FRecInfo^, SizeOf(TFDPgRecInfoRec), 0);
CreateRecInfo(oField, oMember.TypeRef, pInfo^.FRecInfo^);
end
else
SQL2FDColInfo(oMember.TypeOid, Def(oMember.Len, oField.Len),
Def(oMember.Prec, oField.Prec), Def(oMember.Scale, oField.Scale),
ptUnknown, pInfo^.FSrcDataType, pInfo^.FAttrs, pInfo^.FLen,
pInfo^.FPrec, pInfo^.FScale, oFmtOpts);
end;
end;
procedure MapRecInfoTypes(var ARecInfo: TFDPgRecInfoRec);
var
i: Integer;
pInfo: PFDPgColInfoRec;
begin
for i := 0 to Length(ARecInfo.FColInfos) - 1 do begin
pInfo := @ARecInfo.FColInfos[i];
// mapping data types
if GetMetaInfoKind = mkNone then
oFmtOpts.ResolveDataType(pInfo^.FName,
PgConnection.FConnection.TypesManager.Types[pInfo^.FSrcSQLDataType].Name,
pInfo^.FSrcDataType, pInfo^.FLen, pInfo^.FPrec, pInfo^.FScale,
pInfo^.FDestDataType, pInfo^.FLen, True)
else
pInfo^.FDestDataType := pInfo^.FSrcDataType;
if not CheckFetchColumn(pInfo^.FSrcDataType, pInfo^.FAttrs) then
pInfo^.FField := nil;
if pInfo^.FRecInfo <> nil then
MapRecInfoTypes(pInfo^.FRecInfo^);
end;
end;
begin
oFmtOpts := FOptions.FormatOptions;
oFetchOpts := FOptions.FetchOptions;
sTablesOids := '';
iBaseTableOid := InvalidOid;
lGetDSInfo := (GetMetaInfoKind = mkNone) and (fiMeta in oFetchOpts.Items) and
PgConnection.FExtendedMetadata and (FResultSetMode = 0);
SetLength(FBaseRecInfo.FColInfos, FStmt.Fields.Count);
FBaseRecInfo.FColIndex := 0;
for i := 0 to Length(FBaseRecInfo.FColInfos) - 1 do begin
oField := FStmt.Fields[i];
pInfo := @FBaseRecInfo.FColInfos[i];
pInfo^.FField := oField;
pInfo^.FName := oField.Name;
pInfo^.FPos := i + 1;
pInfo^.FTableOid := oField.TableOid;
pInfo^.FTableCol := oField.TableCol;
pInfo^.FSrcSQLDataType := oField.TypeOid;
pInfo^.FInPK := False;
pInfo^.FAttrs := [caAllowNull];
if iBaseTableOid = InvalidOid then
iBaseTableOid := pInfo^.FTableOid;
if lGetDSInfo then begin
if (pInfo^.FTableOid <> InvalidOid) and (pInfo^.FTableCol >= 0) then begin
sTableOid := IntToStr(pInfo^.FTableOid);
if Pos(sTableOid, sTablesOids) = 0 then begin
if sTablesOids <> '' then
sTablesOids := sTablesOids + ', ';
sTablesOids := sTablesOids + sTableOid;
end;
end;
end
else begin
if pInfo^.FTableCol = 0 then begin
Include(pInfo^.FAttrs, caExpr);
Include(pInfo^.FAttrs, caReadOnly);
end
else if (pInfo^.FTableCol > 0) and (iBaseTableOid = pInfo^.FTableOid) then
Include(pInfo^.FAttrs, caBase);
end;
// system columns
if pInfo^.FTableCol < 0 then begin
Include(pInfo^.FAttrs, caReadOnly);
case oField.TableCol of
SelfItemPointerAttributeNumber:
begin
Include(pInfo^.FAttrs, caVolatile);
pInfo^.FOriginColName := 'ctid';
end;
ObjectIdAttributeNumber:
begin
Include(pInfo^.FAttrs, caROWID);
pInfo^.FOriginColName := 'oid';
end;
MinTransactionIdAttributeNumber:
begin
Include(pInfo^.FAttrs, caVolatile);
pInfo^.FOriginColName := 'xmin';
end;
MinCommandIdAttributeNumber:
begin
Include(pInfo^.FAttrs, caVolatile);
pInfo^.FOriginColName := 'cmin';
end;
MaxTransactionIdAttributeNumber:
begin
Include(pInfo^.FAttrs, caVolatile);
pInfo^.FOriginColName := 'xmax';
end;
MaxCommandIdAttributeNumber:
begin
Include(pInfo^.FAttrs, caVolatile);
pInfo^.FOriginColName := 'cmax';
end;
TableOidAttributeNumber:
begin
Include(pInfo^.FAttrs, caDefault);
pInfo^.FOriginColName := 'tableoid';
end;
else
ASSERT(False);
end;
end;
if [paArray, paRecord, paRange] * oField.TypeRef.Attrs <> [] then begin
if paRecord in oField.TypeRef.Attrs then
pInfo^.FSrcDataType := dtRowRef
else if paRange in oField.TypeRef.Attrs then begin
Include(pInfo^.FAttrs, caReadOnly);
pInfo^.FSrcDataType := dtRowRef;
end
else begin
Include(pInfo^.FAttrs, caReadOnly);
if oField.TypeRef.IsFlatFixedArray then begin
pInfo^.FSrcDataType := dtArrayRef;
pInfo^.FLen := oField.TypeRef.FixedLen;
end
else if CheckFixedArray(oField, iLen) then begin
pInfo^.FSrcDataType := dtArrayRef;
pInfo^.FLen := iLen;
end
else
pInfo^.FSrcDataType := dtRowSetRef;
end;
GetMem(pInfo^.FRecInfo, SizeOf(TFDPgRecInfoRec));
FillChar(pInfo^.FRecInfo^, SizeOf(TFDPgRecInfoRec), 0);
CreateRecInfo(oField, oField.TypeRef, pInfo^.FRecInfo^);
end
else
SQL2FDColInfo(pInfo^.FSrcSQLDataType, oField.Len, oField.Prec, oField.Scale,
ptUnknown, pInfo^.FSrcDataType, pInfo^.FAttrs, pInfo^.FLen, pInfo^.FPrec,
pInfo^.FScale, oFmtOpts);
end;
// There are possible optimizations:
// - if any non-system OID, then ask for domain -> LO
// - if no system OID, then ask for PK
if lGetDSInfo and (sTablesOids <> '') then begin
GetConnection.CreateMetadata(oConnMeta);
oView := oConnMeta.GetResultSetFields(sTablesOids);
try
for i := 0 to Length(FBaseRecInfo.FColInfos) - 1 do begin
pInfo := @FBaseRecInfo.FColInfos[i];
if (pInfo^.FTableOid <> InvalidOid) and (pInfo^.FTableCol >= 0) then begin
j := oView.Find([pInfo^.FTableOid,
pInfo^.FTableCol], 'ATTRELID;ATTNUM', []);
if j <> -1 then begin
oRow := oView.Rows[j];
pInfo^.FOriginSchemaName := oRow.AsString['NSPNAME'];
pInfo^.FOriginTabName := oRow.AsString['RELNAME'];
pInfo^.FOriginColName := oRow.AsString['ATTNAME'];
V := oRow.ValueS['ATTRS'];
if not VarIsNull(V) then begin
iAttrs := V;
pInfo^.FAttrs := pInfo^.FAttrs - [caAllowNull, caReadOnly, caROWID] +
TFDDataAttributes(Pointer(@iAttrs)^);
if (iBaseTableOid <> InvalidOid) and (iBaseTableOid <> pInfo^.FTableOid) then
pInfo^.FAttrs := pInfo^.FAttrs + [caAllowNull];
end;
if not VarIsNull(oRow.ValueS['INDISPRIMARY']) then
pInfo^.FInPK := True;
if paOID in PgConnection.FConnection.TypesManager.Types[pInfo^.FSrcSQLDataType].Attrs then
PgConnection.AdjustOIDasBLOB(oRow.AsString['TYPNAME'], pInfo^.FOriginSchemaName,
pInfo^.FSrcDataType, pInfo^.FAttrs);
end;
end;
end;
finally
FDClearMetaView(oView, oFetchOpts);
end;
end;
MapRecInfoTypes(FBaseRecInfo);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.DestroyColInfos;
procedure DestroyRecInfo(var ARecInfo: TFDPgRecInfoRec);
var
i: Integer;
pInfo: PFDPgColInfoRec;
begin
ARecInfo.FParentColName := '';
for i := 0 to Length(ARecInfo.FColInfos) - 1 do begin
pInfo := @ARecInfo.FColInfos[i];
if pInfo^.FRecInfo <> nil then begin
DestroyRecInfo(pInfo^.FRecInfo^);
FreeMem(pInfo^.FRecInfo, SizeOf(TFDPgRecInfoRec));
pInfo^.FRecInfo := nil;
end;
end;
SetLength(ARecInfo.FColInfos, 0);
end;
begin
DestroyRecInfo(FBaseRecInfo);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.CheckColInfos;
begin
if (FStmt.Fields.Count > 0) and (Length(FBaseRecInfo.FColInfos) = 0) then
CreateColInfos;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.SetParamValue(AFmtOpts: TFDFormatOptions; AParam: TFDParam;
APgParam: TPgParam; ApInfo: PFDPgParInfoRec; AParIndex: Integer);
var
pData: PByte;
iSize, iSrcSize: LongWord;
oBlob: TPgLargeObject;
oExtStr, oIntStr: TStream;
eStreamMode: TFDStreamMode;
lExtStream: Boolean;
i: Integer;
function CreateBlob(AMode: TFDStreamMode): TPgLargeObject;
begin
Result := TPgLargeObject.Create(GetConnection.FConnection, AMode, Self);
Result.CreateObj;
Result.Open;
end;
begin
pData := nil;
iSize := 0;
// null
if (AParam.DataType <> ftStream) and AParam.IsNulls[AParIndex] then
APgParam.SetData(nil, 0)
// assign BLOB stream
else if AParam.IsStreams[AParIndex] then begin
oExtStr := AParam.AsStreams[AParIndex];
lExtStream := (oExtStr <> nil) and
not ((oExtStr is TPgLargeObjectStream) and (TPgLargeObjectStream(oExtStr).LargeObject.OwningObj = Self));
if (AParam.DataType <> ftStream) and not lExtStream or
(ApInfo^.FOutDataType <> dtHBlob) then
UnsupParamObjError(AParam);
if lExtStream then
eStreamMode := smOpenWrite
else
eStreamMode := AParam.StreamMode;
oBlob := CreateBlob(eStreamMode);
oIntStr := TPgLargeObjectStream.Create(oBlob);
try
if lExtStream then
oIntStr.CopyFrom(oExtStr, -1)
else
AParam.AsStreams[AParIndex] := oIntStr;
APgParam.SetData(@oBlob.FObjOid, SizeOf(oBlob.FObjOid), True);
finally
if lExtStream then
FDFree(oIntStr);
end;
end
// assign array
else if (AParam.ArrayType = atTable) and (APgParam.ArrayIndex = -1) then begin
APgParam.SetArrayBounds(0, AParam.ArraySize - 1);
try
for i := 0 to AParam.ArraySize - 1 do begin
APgParam.ArrayIndex := i;
SetParamValue(AFmtOpts, AParam, APgParam, ApInfo, i);
end;
finally
APgParam.ArrayIndex := -1;
end;
end
// conversion is not required
else if ApInfo^.FSrcDataType = ApInfo^.FOutDataType then begin
if ApInfo^.FOutDataType = dtHBlob then begin
oBlob := CreateBlob(smOpenWrite);
try
AParam.GetBlobRawData(iSize, pData, AParIndex);
oBlob.Write(pData, iSize);
APgParam.SetData(@oBlob.FObjOid, SizeOf(oBlob.FObjOid), True);
finally
FDFree(oBlob);
end;
end
// byte string data, then optimizing - get data directly
else if ApInfo^.FOutDataType in [dtAnsiString, dtWideString, dtMemo, dtWideMemo,
dtXML, dtBlob, dtByteString] then begin
AParam.GetBlobRawData(iSize, pData, AParIndex);
APgParam.SetData(pData, iSize, True);
end
else begin
iSize := AParam.GetDataLength(AParIndex);
FBuffer.Check(iSize);
AParam.GetData(FBuffer.Ptr, AParIndex);
APgParam.SetData(FBuffer.Ptr, iSize);
end;
end
// conversion is required
else begin
// calculate buffer size to move param values
iSrcSize := AParam.GetDataLength(AParIndex);
FBuffer.Extend(iSrcSize, iSize, ApInfo^.FSrcDataType, ApInfo^.FOutDataType);
// get, convert and set parameter value
AParam.GetData(FBuffer.Ptr, AParIndex);
AFmtOpts.ConvertRawData(ApInfo^.FSrcDataType, ApInfo^.FOutDataType,
FBuffer.Ptr, iSrcSize, FBuffer.FBuffer, FBuffer.Size, iSize,
PgConnection.FConnection.Encoder);
if ApInfo^.FOutDataType = dtHBlob then begin
oBlob := CreateBlob(smOpenWrite);
try
oBlob.Write(FBuffer.Ptr, iSize);
APgParam.SetData(@oBlob.FObjOid, SizeOf(oBlob.FObjOid), True);
finally
FDFree(oBlob);
end;
end
else
APgParam.SetData(FBuffer.Ptr, iSize);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.SetParamValues(AParIndex: Integer = 0);
var
oFmtOpts: TFDFormatOptions;
oParams: TFDParams;
oParam: TFDParam;
oPgParam: TPgParam;
i: Integer;
pParInfo: PFDPgParInfoRec;
begin
oParams := GetParams;
if oParams.Count = 0 then
Exit;
oFmtOpts := GetOptions.FormatOptions;
for i := 0 to Length(FBaseVecInfo.FParInfos) - 1 do begin
pParInfo := @FBaseVecInfo.FParInfos[i];
oParam := oParams[pParInfo^.FParamIndex];
if (pParInfo^.FPgParamIndex <> -1) and
(oParam.DataType <> ftCursor) and
(oParam.ParamType in [ptInput, ptInputOutput, ptUnknown]) then begin
oPgParam := FStmt.Params[pParInfo^.FPgParamIndex];
CheckParamMatching(oParam, pParInfo^.FSrcFieldType, pParInfo^.FParamType, 0);
SetParamValue(oFmtOpts, oParam, oPgParam, pParInfo, AParIndex);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.GetParamValues(AParIndex: Integer);
var
oTab: TFDDatSTable;
i, iParBase, iPar, iCrs: Integer;
oParams: TFDParams;
oPar: TFDParam;
ePrevState: TFDPhysCommandState;
rState: TFDDatSLoadState;
iArrIndex: Integer;
procedure AssignParamValue(AParam: TFDParam; AParIndex: Integer;
ARow: TFDDatSRow; AColIndex: Integer);
var
v: Variant;
eStreamMode: TFDStreamMode;
oBlob: TPgLargeObject;
lExtStream: Boolean;
oExtStr, oIntStr: TStream;
begin
v := ARow.GetData(AColIndex);
if AParam.IsStreams[AParIndex] and not VarIsNull(v) then begin
oExtStr := AParam.AsStreams[AParIndex];
lExtStream := (oExtStr <> nil) and
not ((oExtStr is TPgLargeObjectStream) and (TPgLargeObjectStream(oExtStr).LargeObject.OwningObj = Self));
if (AParam.DataType <> ftStream) and not lExtStream or
(ARow.Table.Columns[AColIndex].DataType <> dtUInt32) then
UnsupParamObjError(AParam);
if lExtStream then
eStreamMode := smOpenWrite
else
eStreamMode := AParam.StreamMode;
oBlob := TPgLargeObject.Create(GetConnection.FConnection, eStreamMode, Self, v);
oIntStr := TPgLargeObjectStream.Create(oBlob);
try
oBlob.Open;
if lExtStream then
oExtStr.CopyFrom(oIntStr, -1)
else
AParam.AsStreams[AParIndex] := oIntStr;
finally
if lExtStream then
FDFree(oIntStr);
end;
end
else
AParam.Values[AParIndex] := v;
end;
function CheckParamStreams: Boolean;
var
i: Integer;
oPar: TFDParam;
begin
Result := False;
for i := 0 to oParams.Count - 1 do begin
oPar := oParams[i];
if (oPar.ParamType in [ptOutput, ptInputOutput, ptResult]) and
oPar.IsStreams[AParIndex] then begin
Result := True;
Break;
end;
end;
end;
begin
FStmt.DescribeFields;
if (FStmt.Fields.Count = 0) or (FStmt.Fields[0].TypeOID = SQL_UNKNOWN) then
Exit;
oParams := GetParams;
oTab := TFDDatSTable.Create;
if CheckParamStreams then
FResultSetMode := 2
else
FResultSetMode := 1;
ePrevState := GetState;
SetState(csOpen);
try
CheckColInfos;
oTab.Setup(FOptions);
FStmt.Fetch;
Define(oTab);
if oTab.Columns.Count > 0 then begin
oTab.BeginLoadData(rState, lmHavyFetching);
try
FetchRow(@FBaseRecInfo, oTab, nil);
if GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs] then begin
// SP parameters are binded by name
for i := 0 to oTab.Columns.Count - 1 do begin
oPar := oParams.FindParam(oTab.Columns[i].Name);
if (oPar <> nil) and (oPar.ParamType in [ptOutput, ptInputOutput, ptResult]) then
AssignParamValue(oPar, AParIndex, oTab.Rows[0], i);
end;
end
else begin
// RETURNING ... {INTO ...} parameters are binded by position
iArrIndex := AParIndex - 1;
iParBase := -2;
repeat
Inc(iArrIndex);
if iParBase <> -2 then
FetchRow(@FBaseRecInfo, oTab, nil)
else begin
iParBase := -1;
for i := 0 to oParams.Count - 1 do
if oParams[i].ParamType in [ptOutput, ptInputOutput, ptResult] then begin
iParBase := i;
Break;
end;
end;
iPar := iParBase;
if iPar <> -1 then
for i := 0 to oTab.Columns.Count - 1 do begin
while iPar < oParams.Count do begin
oPar := oParams[iPar];
Inc(iPar);
if oPar.ParamType in [ptOutput, ptInputOutput] then begin
AssignParamValue(oPar, iArrIndex, oTab.Rows[iArrIndex - AParIndex], i);
Break;
end;
end;
if iPar >= oParams.Count then
Break;
end;
until not FStmt.Fetch;
end;
finally
oTab.EndLoadData(rState);
end;
end;
if GetCommandKind = skStoredProcWithCrs then begin
// grab cursor names
iCrs := 0;
for i := 0 to FStmt.Fields.Count - 1 do
if FStmt.Fields[i].TypeOid = SQL_REFCURSOR then
Inc(iCrs);
SetLength(FCursors, iCrs);
iCrs := 0;
for i := 0 to FStmt.Fields.Count - 1 do
if FStmt.Fields[i].TypeOid = SQL_REFCURSOR then begin
FCursors[iCrs] := FStmt.Fields[i].GetAsString;
Inc(iCrs);
end;
end;
finally
DestroyColInfos;
SetState(ePrevState);
FResultSetMode := 0;
FDFree(oTab);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.InternalUseStandardMetadata: Boolean;
begin
Result := not PgConnection.FExtendedMetadata;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.BuildColumnName(ApRecInfo: PFDPgRecInfoRec; ApColInfo: PFDPgColInfoRec): String;
begin
if (ApRecInfo^.FParentColName <> '') and
(ApColInfo^.FField <> nil) and (ApColInfo^.FField.ParentField <> nil) and
(paArray in ApColInfo^.FField.ParentField.TypeRef.Attrs) then
if ApRecInfo^.FFixedLength > 0 then
Result := ApRecInfo^.FParentColName + '[' + IntToStr(ApRecInfo^.FColIndex) + ']'
else
Result := ApRecInfo^.FParentColName + '[]'
else
Result := ApColInfo^.FName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean;
var
pColInfo: PFDPgColInfoRec;
sParName: String;
begin
Result := OpenBlocked;
if ATabInfo.FSourceID = -1 then begin
ATabInfo.FSourceName := GetCommandText;
ATabInfo.FSourceID := 1;
FCurrentRecInfo := @FBaseRecInfo;
FCurrentRecInfo^.FColIndex := 0;
FCurrentRecInfo^.FFixedLength := 0;
FCurrentRecInfo^.FParentColName := '';
end
else begin
pColInfo := @FCurrentRecInfo^.FColInfos[ATabInfo.FSourceID - 1];
ATabInfo.FSourceName := pColInfo^.FName;
ATabInfo.FSourceID := ATabInfo.FSourceID;
sParName := BuildColumnName(FCurrentRecInfo, pColInfo);
FInfoStack.Add(FCurrentRecInfo);
FCurrentRecInfo := pColInfo^.FRecInfo;
FCurrentRecInfo^.FColIndex := 0;
FCurrentRecInfo^.FFixedLength := pColInfo^.FLen;
FCurrentRecInfo^.FParentColName := sParName;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean;
var
iCol: Integer;
pColInfo: PFDPgColInfoRec;
begin
if (FCurrentRecInfo^.FFixedLength > 0) and
(FCurrentRecInfo^.FColIndex < FCurrentRecInfo^.FFixedLength * Length(FCurrentRecInfo^.FColInfos)) or
(FCurrentRecInfo^.FFixedLength = 0) and
(FCurrentRecInfo^.FColIndex < Length(FCurrentRecInfo^.FColInfos)) then begin
iCol := FCurrentRecInfo^.FColIndex mod Length(FCurrentRecInfo^.FColInfos);
pColInfo := @FCurrentRecInfo^.FColInfos[iCol];
AColInfo.FSourceName := BuildColumnName(FCurrentRecInfo, pColInfo);
AColInfo.FSourceID := pColInfo^.FPos;
AColInfo.FSourceType := pColInfo^.FSrcDataType;
if (pColInfo^.FField <> nil) and
([paRecord, paRange, paEnum, paCast] * pColInfo^.FField.TypeRef.Attrs <> []) then
AColInfo.FSourceTypeName := pColInfo^.FField.TypeRef.Name
else
AColInfo.FSourceTypeName := '';
AColInfo.FOriginTabName.FSchema := pColInfo^.FOriginSchemaName;
AColInfo.FOriginTabName.FObject := pColInfo^.FOriginTabName;
AColInfo.FOriginColName := pColInfo^.FOriginColName;
AColInfo.FType := pColInfo^.FDestDataType;
AColInfo.FLen := pColInfo^.FLen;
AColInfo.FPrec := pColInfo^.FPrec;
AColInfo.FScale := pColInfo^.FScale;
AColInfo.FAttrs := pColInfo^.FAttrs;
AColInfo.FForceAddOpts := [];
if pColInfo^.FInPK then
Include(AColInfo.FForceAddOpts, coInKey);
Inc(FCurrentRecInfo^.FColIndex);
Result := True;
end
else begin
if FInfoStack.Count > 0 then begin
FCurrentRecInfo := PFDPgRecInfoRec(FInfoStack.Last);
FInfoStack.Delete(FInfoStack.Count - 1);
end;
Result := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.ExecuteBatchInsert(ATimes, AOffset: Integer;
var ACount: TFDCounter);
var
sBatchSQL: String;
iBatchSQLPos: Integer;
pParInfo: PFDPgParInfoRec;
procedure W(const AStr: String);
var
iLen: Integer;
begin
iLen := Length(AStr);
if iBatchSQLPos + iLen > Length(sBatchSQL) then
SetLength(sBatchSQL, Length(sBatchSQL) * 2);
Move(PChar(AStr)^, (PChar(sBatchSQL) + iBatchSQLPos)^, iLen * SizeOf(Char));
Inc(iBatchSQLPos, iLen);
end;
procedure C(AIndex, ACount: Integer);
begin
if iBatchSQLPos + ACount > Length(sBatchSQL) then
SetLength(sBatchSQL, Length(sBatchSQL) * 2);
Move((PChar(FDBCommandText) + AIndex)^, (PChar(sBatchSQL) + iBatchSQLPos)^, ACount * SizeOf(Char));
Inc(iBatchSQLPos, ACount);
end;
var
oFmtOpts: TFDFormatOptions;
oParams: TFDParams;
oParam: TFDParam;
oPgParam: TPgParam;
oSrcPgParam: TPgParam;
i, j, iParamCnt: Integer;
lIsDollar: Boolean;
lIsParam: Boolean;
iDollarPos: Integer;
aParamsPos: array of Integer;
iBatchParamInd: Integer;
iBatchSize: Integer;
begin
oParams := GetParams;
iBatchSize := ATimes - AOffset;
if not CheckArray(iBatchSize) then begin
if GetCommandKind in [skDelete, skInsert, skUpdate, skMerge] then begin
iParamCnt := 0;
for i := 0 to oParams.Count - 1 do
if oParams[i].ParamType in [ptUnknown, ptInput, ptInputOutput] then
Inc(iParamCnt);
end
else
iParamCnt := oParams.Count;
lIsDollar := False;
lIsParam := False;
iDollarPos := 1;
i := FSQLValuesPos;
j := 1;
SetLength(aParamsPos, iParamCnt * 2 + 2);
aParamsPos[0] := FSQLValuesPos + 5;
while i <= FSQLValuesPosEnd do begin
case FDBCommandText[i] of
'$':
begin
lIsDollar := not lIsDollar;
if lIsDollar then
iDollarPos := i;
end;
'0'..'9':
lIsParam := lIsDollar;
else
if lIsParam then begin
aParamsPos[j] := iDollarPos - 2;
aParamsPos[j + 1] := i - 1;
Inc(j, 2);
end;
lIsDollar := False;
lIsParam := False;
end;
Inc(i);
end;
ASSERT(j = Length(aParamsPos) - 1);
aParamsPos[j] := FSQLValuesPosEnd - 1;
iBatchSQLPos := 0;
iBatchParamInd := 1;
SetLength(sBatchSQL, 16384);
C(0, FSQLValuesPos + 5);
for j := 0 to iBatchSize - 1 do begin
if j > 0 then
W(',');
C(aParamsPos[0], aParamsPos[1] - aParamsPos[0] + 1);
for i := 1 to Length(aParamsPos) div 2 - 1 do begin
W('$');
W(IntToStr(iBatchParamInd));
C(aParamsPos[i * 2], aParamsPos[i * 2 + 1] - aParamsPos[i * 2] + 1);
Inc(iBatchParamInd);
end;
end;
C(FSQLValuesPosEnd, Length(FDBCommandText) - FSQLValuesPosEnd);
SetLength(sBatchSQL, iBatchSQLPos);
FStmt.Params.Count := FStmtParamsCount * iBatchSize;
for i := 0 to iBatchSize - 1 do
for j := 0 to FStmtParamsCount - 1 do begin
oSrcPgParam := FStmt.Params[j];
oPgParam := FStmt.Params[i * iParamCnt + j];
oPgParam.TypeOid := oSrcPgParam.TypeOid;
oPgParam.Encoding := oSrcPgParam.Encoding;
oPgParam.Size := oSrcPgParam.Size;
oPgParam.DumpLabel := Format('%s [%d]', [oSrcPgParam.DumpLabel, j]);
end;
FStmt.PrepareSQL(sBatchSQL);
end;
oFmtOpts := GetOptions.FormatOptions;
for i := 0 to iBatchSize - 1 do
for j := 0 to Length(FBaseVecInfo.FParInfos) - 1 do begin
oParam := oParams[j];
pParInfo := @FBaseVecInfo.FParInfos[j];
oPgParam := FStmt.Params[i * FStmtParamsCount + pParInfo^.FPgParamIndex];
SetParamValue(oFmtOpts, oParam, oPgParam, pParInfo, i + AOffset);
end;
FStmt.Execute;
Inc(ACount, iBatchSize);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.CheckArray(ASize: Integer): Boolean;
begin
Result := (ASize = 1) and (FPreparedBatchSize <= 1) or
(ASize = FPreparedBatchSize);
if not Result then begin
FStmt.Unprepare;
FPreparedBatchSize := ASize;
if ASize = 1 then begin
FStmt.Params.Count := FStmtParamsCount;
FStmt.PrepareSQL(FDBCommandText);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.DoExecute(ATimes, AOffset: Integer; var ACount: TFDCounter);
var
i: Integer;
iTimes: Integer;
iCount: TFDCounter;
begin
if ATimes - AOffset > 1 then begin
if (PgConnection.FServerVersion >= svPGSQL080100) and
(GetCommandKind = skInsert) and (FSQLValuesPos > 0) then begin
ExecuteBatchInsert(ATimes, AOffset, ACount);
GetParamValues(AOffset);
end
else begin
if ATimes > GetParams.ArraySize then
iTimes := GetParams.ArraySize
else
iTimes := ATimes;
for i := AOffset to iTimes - 1 do begin
iCount := 0;
try
DoExecute(i + 1, i, iCount);
finally
Inc(ACount, iCount);
end;
CheckExact(ATimes = 1, 1, 0, iCount, False);
end;
end;
end
else begin
CheckArray(1);
SetParamValues(AOffset);
try
try
if UseExecDirect then
FStmt.ExecuteDirect(FDbCommandText)
else
FStmt.Execute;
except
on E: EPgNativeException do begin
E.Errors[0].RowIndex := AOffset;
raise;
end;
end;
finally
Inc(ACount, FStmt.RowsAffected);
end;
GetParamValues(AOffset);
FStmt.Close;
if GetCommandKind = skSetSchema then
PgConnection.UpdateCurrentMeta;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.InternalExecute(ATimes, AOffset: Integer;
var ACount: TFDCounter);
begin
ACount := 0;
DoExecute(ATimes, AOffset, ACount);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.InternalOpen(var ACount: TFDCounter): Boolean;
begin
ACount := 0;
if not GetNextRecordSet then
FActiveCrs := -1;
if GetMetaInfoKind = mkProcArgs then begin
Result := True;
Exit;
end
else if (GetMetaInfoKind <> mkNone) and (FDbCommandText = '') then begin
Result := False;
Exit;
end
else if not FCursorCanceled then begin
Result := True;
Exit;
end;
if GetMetaInfoKind = mkProcs then begin
FMetaProcName := '';
FMetaProcOverload := 0;
end;
SetParamValues;
if GetCommandKind = skStoredProcWithCrs then begin
if FActiveCrs = - 1 then begin
FActiveCrs := 0;
try
if UseExecDirect then
FStmt.ExecuteDirect(FDbCommandText)
else
FStmt.Execute;
finally
Inc(ACount, FStmt.RowsAffected);
end;
GetParamValues(0);
end;
ASSERT(FActiveCrs < Length(FCursors));
FStmt := CreateStmt;
try
FStmt.PrepareCursor(FCursors[FActiveCrs]);
except
FDFreeAndNil(FStmt);
raise;
end;
end;
try
try
if UseExecDirect and (GetCommandKind <> skStoredProcWithCrs) then
FStmt.ExecuteDirect(FDbCommandText)
else
FStmt.Execute;
finally
Inc(ACount, FStmt.RowsAffected);
end;
FStmt.DescribeFields;
CheckColInfos;
Result := Length(FBaseRecInfo.FColInfos) > 0;
FCursorCanceled := False;
except
FCursorCanceled := True;
InternalClose;
raise;
end;
if GetCommandKind = skSetSchema then
PgConnection.UpdateCurrentMeta;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.InternalNextRecordSet: Boolean;
var
iCount: TFDCounter;
begin
if FActiveCrs < 0 then begin
Result := False;
Exit;
end;
if FActiveCrs < Length(FCursors) then
Inc(FActiveCrs);
if FActiveCrs < Length(FCursors) then
Result := InternalOpen(iCount)
else begin
InternalClose;
Result := False;
FCursorCanceled := True;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.FetchRow(ApRecInfo: PFDPgRecInfoRec;
ATable: TFDDatSTable; AParentRow: TFDDatSRow);
var
oRow: TFDDatSRow;
[unsafe] oCol: TFDDatSColumn;
oFmtOpts: TFDFormatOptions;
pColInfo: PFDPgColInfoRec;
j: Integer;
lMetadata: Boolean;
procedure ProcessColumn(AColIndex: Integer; ARow: TFDDatSRow;
ApInfo: PFDPgColInfoRec);
var
pData: Pointer;
iSize, iDestSize: LongWord;
iOid: Integer;
oBlob: TPgLargeObject;
iLBound, iHBound, i: Integer;
oNestedTable: TFDDatSTable;
oNestedRow: TFDDatSRow;
lClosed: Boolean;
begin
pData := nil;
iSize := 0;
if (ApInfo^.FField = nil) or not CheckFetchColumn(ApInfo^.FSrcDataType, ApInfo^.FAttrs) then
Exit
// null
else if not ApInfo^.FField.GetData(pData, iSize, True) then
ARow.SetData(AColIndex, nil, 0)
// composite type
else if ApInfo^.FDestDataType = dtRowRef then begin
oNestedTable := ARow.Table.Columns[AColIndex].NestedTable;
FetchRow(ApInfo^.FRecInfo, oNestedTable, ARow);
end
// unbound array
else if ApInfo^.FDestDataType = dtRowSetRef then begin
ApInfo^.FField.GetArrayBounds(iLBound, iHBound, lClosed);
if iHBound - iLBound >= 0 then begin
oNestedTable := ARow.Table.Columns[AColIndex].NestedTable;
try
for i := iLBound to iHBound do begin
ApInfo^.FField.ArrayIndex := i;
FetchRow(ApInfo^.FRecInfo, oNestedTable, ARow);
end;
if lClosed then begin
ApInfo^.FField.ArrayIndex := 0;
FetchRow(ApInfo^.FRecInfo, oNestedTable, ARow);
end;
finally
ApInfo^.FField.ArrayIndex := -1;
end;
end;
ARow.Fetched[AColIndex] := True;
end
// constrained array
else if ApInfo^.FDestDataType = dtArrayRef then begin
ApInfo^.FField.GetArrayBounds(iLBound, iHBound, lClosed);
if iHBound - iLBound >= 0 then begin
oNestedTable := ARow.Table.Columns[AColIndex].NestedTable;
oNestedRow := oNestedTable.NewRow(False);
try
for i := iLBound to Min(iLBound + oNestedTable.Columns.Count - 2, iHBound) do begin
ApInfo^.FField.ArrayIndex := i;
ProcessColumn(i - iLBound, oNestedRow, @ApInfo^.FRecInfo.FColInfos[0]);
end;
ApInfo^.FField.ArrayIndex := -1;
oNestedRow.ParentRow := ARow;
oNestedTable.Rows.Add(oNestedRow);
except
ApInfo^.FField.ArrayIndex := -1;
FDFree(oNestedRow);
raise;
end;
end;
ARow.Fetched[AColIndex] := True;
end
// conversion is not required
else if ApInfo^.FSrcDataType = ApInfo^.FDestDataType then
if ApInfo^.FDestDataType = dtHBlob then begin
if ApInfo^.FField.GetData(@iOid, iSize) then begin
oBlob := TPgLargeObject.Create(GetConnection.FConnection, smOpenRead, Self, iOid);
try
oBlob.Open;
iSize := oBlob.Len;
pData := ARow.BeginDirectWriteBlob(AColIndex, iSize);
try
if iSize > 0 then
oBlob.Read(pData, iSize);
finally
ARow.EndDirectWriteBlob(AColIndex, iSize);
end;
finally
FDFree(oBlob);
end;
end
end
else if ApInfo^.FDestDataType in [dtAnsiString, dtWideString, dtMemo, dtWideMemo,
dtXML, dtBlob, dtByteString] then
ARow.SetData(AColIndex, pData, iSize)
else begin
FBuffer.Check(iSize);
ApInfo^.FField.GetData(FBuffer.FBuffer, iSize, False);
ARow.SetData(AColIndex, FBuffer.Ptr, iSize);
end
// conversion is required
else begin
FBuffer.Check((iSize + 1) * SizeOf(WideChar));
ApInfo^.FField.GetData(FBuffer.FBuffer, iSize);
iDestSize := 0;
oFmtOpts.ConvertRawData(ApInfo^.FSrcDataType, ApInfo^.FDestDataType,
FBuffer.Ptr, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize,
PgConnection.FConnection.Encoder);
ARow.SetData(AColIndex, FBuffer.Ptr, iDestSize);
end;
end;
procedure ProcessMetaColumn(AColIndex: Integer; ARow: TFDDatSRow;
ApInfo: PFDPgColInfoRec);
var
pData: Pointer;
iSize, iDestSize: Longword;
begin
pData := nil;
iSize := 0;
if AColIndex = 0 then
ARow.SetData(0, ATable.Rows.Count + 1)
else if not ApInfo^.FField.GetData(pData, iSize, True) then
ARow.SetData(AColIndex, nil, 0)
else if ApInfo^.FDestDataType in [dtAnsiString, dtWideString, dtMemo, dtWideMemo,
dtXML, dtBlob, dtByteString] then begin
if iSize > ATable.Columns[AColIndex].Size then
iSize := ATable.Columns[AColIndex].Size;
if ApInfo^.FDestDatatype in C_FD_AnsiTypes then begin
FBuffer.Check(iSize * SizeOf(WideChar));
oFmtOpts.ConvertRawData(dtAnsiString, dtWideString,
pData, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize,
PgConnection.FConnection.Encoder);
ARow.SetData(AColIndex, FBuffer.Ptr, iDestSize);
end
else
ARow.SetData(AColIndex, pData, iSize);
end
else begin
FBuffer.Check(iSize);
ApInfo^.FField.GetData(FBuffer.FBuffer, iSize, False);
iDestSize := 0;
if ApInfo^.FDestDataType in [dtUInt16, dtUInt32, dtInt16, dtInt32,
dtSingle, dtDouble, dtBCD, dtFmtBCD] then
oFmtOpts.ConvertRawData(ApInfo^.FSrcDataType, ATable.Columns[AColIndex].DataType,
FBuffer.Ptr, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize,
PgConnection.FConnection.Encoder);
ARow.SetData(AColIndex, FBuffer.Ptr, iDestSize);
end;
end;
begin
oFmtOpts := FOptions.FormatOptions;
oRow := ATable.NewRow(False);
lMetadata := GetMetaInfoKind <> mkNone;
try
for j := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns[j];
if oCol.SourceID > 0 then begin
pColInfo := @ApRecInfo^.FColInfos[oCol.SourceID - 1];
if lMetadata then
ProcessMetaColumn(j, oRow, pColInfo)
else
ProcessColumn(j, oRow, pColInfo);
end;
end;
if AParentRow <> nil then begin
oRow.ParentRow := AParentRow;
AParentRow.Fetched[ATable.Columns.ParentCol] := True;
end;
ATable.Rows.Add(oRow);
except
FDFree(oRow);
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.FetchTableFieldsRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow);
var
oRow: TFDDatSRow;
eType: TFDDataType;
eAttrs: TFDDataAttributes;
iTypeOid: Oid;
iAttrs: Word;
iLen: LongWord;
iPrec: Integer;
iScale: Integer;
begin
FetchRow(@FBaseRecInfo, ATable, AParentRow);
oRow := ATable.Rows[ATable.Rows.Count - 1];
iAttrs := oRow.GetData(8);
eAttrs := TFDDataAttributes(Pointer(@iAttrs)^);
iTypeOid := LongWord(oRow.GetData(6));
SQL2FDColInfo(iTypeOid, oRow.GetData(11), oRow.GetData(9), oRow.GetData(10),
ptUnknown, eType, eAttrs, iLen, iPrec, iScale, FOptions.FormatOptions);
if paOID in PgConnection.FConnection.TypesManager.Types[iTypeOid].Attrs then
PgConnection.AdjustOIDasBLOB(oRow.GetData(7), oRow.GetData(2), eType, eAttrs);
oRow.SetData(6, Integer(eType));
oRow.SetData(8, PWord(@eAttrs)^);
oRow.SetData(9, iPrec);
oRow.SetData(10, iScale);
oRow.SetData(11, Integer(iLen));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.FetchProcsRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow);
var
sProcName: String;
oRow: TFDDatSRow;
begin
FetchRow(@FBaseRecInfo, ATable, AParentRow);
oRow := ATable.Rows[ATable.Rows.Count - 1];
sProcName := oRow.GetData(4);
if sProcName = FMetaProcName then
Inc(FMetaProcOverload)
else begin
FMetaProcName := sProcName;
FMetaProcOverload := 0;
end;
if FMetaProcOverload > 0 then
oRow.SetData(5, FMetaProcOverload);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.FetchSPParamRows(ATable: TFDDatSTable; AParentRow: TFDDatSRow): Integer;
var
iRecNo: Integer;
i: Integer;
oConnMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
oProcArgs: TFDProcArgRecs;
oDesc: TFDPhysPgSPDescriber;
pArg: PFDProcArgRec;
procedure AddParam(const AParamName: String; ATypeOID: Integer; AParamType: TParamType);
var
oRow: TFDDatSRow;
eType: TFDDataType;
eAttrs: TFDDataAttributes;
iPrec: Integer;
iScale: Integer;
uiLen: LongWord;
oType: TPgType;
begin
eType := dtUnknown;
iPrec := 0;
iScale := 0;
eAttrs := [caAllowNull];
SQL2FDColInfo(ATypeOID, 0, 0, 0, AParamType, eType, eAttrs, uiLen, iPrec,
iScale, FOptions.FormatOptions);
try
oType := PgConnection.FConnection.TypesManager.Types[ATypeOID];
except
oType := nil;
end;
oRow := ATable.NewRow(False);
oRow.SetData(0, iRecNo);
if rName.FCatalog = '' then
oRow.SetData(1, PgConnection.FMetaCatalog)
else
oRow.SetData(1, rName.FCatalog);
oRow.SetData(2, rName.FSchema);
oRow.SetData(3, nil, 0);
oRow.SetData(4, rName.FObject);
oRow.SetData(5, GetOverload);
oRow.SetData(6, AParamName);
oRow.SetData(7, Smallint(iRecNo));
oRow.SetData(8, Smallint(AParamType));
oRow.SetData(9, Smallint(eType));
if oType <> nil then
oRow.SetData(10, oType.Name)
else
oRow.SetData(10, nil, 0);
oRow.SetData(11, PWord(@eAttrs)^);
oRow.SetData(12, 0);
oRow.SetData(13, 0);
oRow.SetData(14, uiLen);
ATable.Rows.Add(oRow);
Inc(iRecNo);
end;
begin
FConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(Trim(GetCommandText), rName, Self, [doNormalize, doUnquote]);
CheckMetaInfoParams(rName);
oDesc := TFDPhysPgSPDescriber.Create(Self, rName);
try
oDesc.ReadProcArgs(oProcArgs);
finally
FDFree(oDesc);
end;
iRecNo := 1;
for i := 0 to Length(oProcArgs) - 1 do begin
pArg := @oProcArgs[i];
AddParam(pArg^.FName, pArg^.FTypeOid, pArg^.FParamType);
end;
Result := Length(oProcArgs);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommand.InternalFetchRowSet(ATable: TFDDatSTable; AParentRow: TFDDatSRow;
ARowsetSize: LongWord): LongWord;
var
i: LongWord;
begin
Result := 0;
if GetMetaInfoKind = mkProcArgs then
Result := FetchSPParamRows(ATable, AParentRow)
else
for i := 1 to ARowsetSize do begin
if not FStmt.Fetch then
Break;
case GetMetaInfoKind of
mkTableFields: FetchTableFieldsRow(ATable, AParentRow);
mkProcs: FetchProcsRow(ATable, AParentRow);
else FetchRow(@FBaseRecInfo, ATable, AParentRow);
end;
Inc(Result);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.InternalAbort;
begin
TFDPhysPgConnection(FConnectionObj).FConnection.Abort;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.InternalClose;
begin
if (FStmt <> nil) and not FCursorCanceled then begin
FCursorCanceled := True;
DestroyColInfos;
FStmt.Close;
end;
if FStmt <> FBaseStmt then begin
FDFree(FStmt);
FStmt := FBaseStmt;
end;
if not GetNextRecordSet then begin
if FBaseStmt <> nil then
FBaseStmt.Close;
FActiveCrs := -1;
end;
FInfoStack.Clear;
FCurrentRecInfo := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgCommand.InternalUnprepare;
begin
FPreparedBatchSize := 0;
if FStmt = nil then
Exit;
FBaseStmt := nil;
FStmt.Unprepare;
DestroyParamInfos;
DestroyColInfos;
FDFreeAndNil(FStmt);
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysPgDriver);
finalization
FDUnregisterDriverClass(TFDPhysPgDriver);
end.
|
unit UTableBox;
// UTableBox.pas - Contains a tablename combobox
// Copyright (c) 2000. All Rights Reserved.
// by Software Conceptions, Inc. Okemos, MI USA (800) 471-5890
// Written by Paul Kimmel
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs,
DBTables, StdCtrls;
type
TDatabaseName = string;
TCustomTableBox = class(TCustomComboBox)
private
{ Private declarations }
FSession: TSession;
FDatabaseName: TDatabaseName;
protected
{ Protected declarations }
procedure DropDown; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure SetSession(const Value: TSession);
procedure SetDatabaseName(const Value: TDatabaseName);
public
{ Public declarations }
property Text;
property OnChange;
property Session: TSession read FSession write SetSession;
property DatabaseName: TDatabaseName read FDatabaseName
write SetDatabaseName;
end;
TTableBox = class(TCustomTableBox)
published
{ Published declarations }
property Text;
property OnChange;
property Session;
property DatabaseName;
end;
var
Session: TSession;
//procedure Register;
implementation
//procedure Register;
//begin
//RegisterComponents('zhshll', [TTableBox]);
//end;
{ TTableBox }
procedure TCustomTableBox.DropDown;
begin
inherited;
if(FSession = Nil) then FSession := DBTables.Session;
if(Items.Count = 0) then
FSession.GetTableNames(FDatabaseName, '*.*', True, True, Items);
end;
procedure TCustomTableBox.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if(Operation = opRemove) and (AComponent = FSession) then
Session := Nil;
end;
procedure TCustomTableBox.SetDatabaseName(const Value: TDatabaseName);
begin
FDatabaseName := Value;
end;
procedure TCustomTableBox.SetSession(const Value: TSession);
begin
if(Value = FSession) then exit;
Items.Clear;
FSession := Value;
UTableBox.Session := Value;
end;
end.
|
unit strings_0;
interface
implementation
var S: String;
procedure Test;
begin
S := 'ABCD';
end;
initialization
Test();
finalization
Assert(S = 'ABCD');
end. |
program soucet_polynomu;
type polynom = record
koeficient, exponent: integer;
dalsi: pointer;
end;
Pa = ^polynom;
var p1, p2, p, pom: Pa;
procedure vytvor_polynom(var s: Pa);
{Vytvoří polynom}
var vstup: integer;
pom, akt: Pa;
begin
new(pom);
s := pom;
akt := s;
pom ^.exponent := -1;
vstup := 0;
while vstup <> -1 do
begin
writeln('Zadejte dvojici koeficient a exponent, -1 pro ukončení');
read(vstup);
if vstup <> -1 then
begin
new(pom);
akt^.dalsi := pom;
pom^.koeficient := vstup;
read(vstup);
pom^.exponent := vstup;
akt := akt^.dalsi;
end;
end;
akt^.dalsi := s;
end;
procedure vypis_polynom(s: Pa);
{Vypíše obsah polynomu}
var akt: Pa;
begin
writeln('Začínám výpis');
akt := s^.dalsi;
while akt^.exponent <> -1 do
begin
write('koeficient: ');
write(akt^.koeficient);
write(' exponent: ');
writeln(akt^.exponent);
akt := akt^.dalsi;
end;
end;
procedure secti_polynomy(p1, p2, vysledek: Pa);
{Sečte dva polynomy a vytvoří nový, původní zachová}
var p1_akt, p2_akt, vysl_akt, pom: Pa;
begin
p1_akt := p1^.dalsi;
p2_akt := p2^.dalsi;
new(pom);
vysledek := pom;
pom^.exponent := -1;
pom^.dalsi := vysledek;
vysl_akt := vysledek;
while (p1_akt^.exponent <> -1) and (p2_akt^.exponent <> -1) do
begin
writeln('oba polynomy jsou nenulové');
if p1_akt^.exponent > p2_akt^.exponent then
begin
writeln('zapisuji p2');
new(pom);
vysl_akt^.dalsi := pom;
pom^.koeficient := p1_akt^.koeficient;
pom^.exponent := p1_akt^.exponent;
p1_akt := p1_akt^.dalsi;
end;
if p2_akt^.exponent > p1_akt^.exponent then
begin
writeln('zapisuji p1');
new(pom);
vysl_akt^.dalsi := pom;
pom^.koeficient := p2_akt^.koeficient;
pom^.exponent := p2_akt^.exponent;
p2_akt := p2_akt^.dalsi;
end;
if p1_akt^.exponent = p2_akt^.exponent then
begin
writeln('zapisuji součet');
if p1_akt^.koeficient + p2_akt^.koeficient <> 0 then
begin
new(pom);
vysl_akt^.dalsi := pom;
pom^.koeficient := p1^.koeficient + p2^.koeficient;
pom^.exponent := p1^.exponent;
end;
p1_akt := p1_akt^.dalsi;
p2_akt := p2_akt^.dalsi;
end;
end;
while p1_akt^.exponent <> -1 do
begin
writeln('p2 je nulový');
new(pom);
vysl_akt^.dalsi := pom;
pom^.koeficient := p1^.koeficient;
pom^.exponent := p1^.exponent;
p1_akt := p1_akt^.dalsi;
end;
while p2_akt^.exponent <> -1 do
begin
writeln('p1 je nulový');
new(pom);
vysl_akt^.dalsi := pom;
pom^.koeficient := p2^.koeficient;
pom^.exponent := p2^.exponent;
p2_akt := p2_akt^.dalsi;
end;
vysl_akt^.dalsi := vysledek;
writeln('cyklím výsledek');
end;
begin
new(p1);
p1^.exponent := -1;
new(pom);
p1^.dalsi := pom;
pom^.exponent := 5;
pom^.koeficient := 5;
pom^.dalsi := p1;
new(p2);
p2^.exponent := -1;
new(pom);
p2^.dalsi := pom;
pom^.exponent := 5;
pom^.koeficient := 5;
pom^.dalsi := p2;
secti_polynomy(p1,p2,p);
vypis_polynom(p1);
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC DBX 4 Bridge driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Phys.TDBX;
interface
uses
System.Classes,
FireDAC.Phys.TDBXBase;
type
TFDPhysTDBXDriverLink = class;
[ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidiOS or pfidAndroid)]
TFDPhysTDBXDriverLink = class(TFDPhysTDBXBaseDriverLink)
protected
function GetBaseDriverID: String; override;
end;
{-------------------------------------------------------------------------------}
implementation
uses
System.SysUtils, System.IniFiles, Data.DBXCommon, System.Variants,
FireDAC.Stan.Intf, FireDAC.Stan.Consts, FireDAC.Stan.Util,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.SQLGenerator, FireDAC.Phys.Meta,
{$IFNDEF FireDAC_MOBILE}
FireDAC.Phys.MSAccMeta, FireDAC.Phys.MSSQLMeta, FireDAC.Phys.MySQLMeta,
FireDAC.Phys.OracleMeta, FireDAC.Phys.DB2Meta, FireDAC.Phys.ASAMeta,
FireDAC.Phys.ADSMeta, FireDAC.Phys.PGMeta, FireDAC.Phys.NexusMeta,
FireDAC.Phys.InfxMeta,
{$ENDIF}
FireDAC.Phys.TDBXMeta, FireDAC.Phys.IBMeta, FireDAC.Phys.SQLiteMeta,
FireDAC.Phys.TDBXDef;
type
TFDPhysTDBXDriver = class;
TFDPhysTDBXConnection = class;
TFDPhysTDBXDriver = class(TFDPhysTDBXDriverBase)
private
function GetDriverParams(AKeys: TStrings): TStrings;
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
end;
TFDPhysTDBXConnection = class(TFDPhysTDBXConnectionBase)
protected
function InternalCreateMetadata: TObject; override;
function InternalCreateCommandGenerator(const ACommand: IFDPhysCommand):
TFDPhysCommandGenerator; override;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysTDBXDriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysTDBXDriverLink.GetBaseDriverID: String;
begin
Result := S_FD_TDBXId;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysTDBXDriver }
{-------------------------------------------------------------------------------}
class function TFDPhysTDBXDriver.GetBaseDriverID: String;
begin
Result := S_FD_TDBXId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysTDBXDriver.GetBaseDriverDesc: String;
begin
Result := 'dbExpress Data Source';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysTDBXDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.Other;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysTDBXDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysTDBXConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXDriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysTDBXConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXDriver.GetDriverParams(AKeys: TStrings): TStrings;
var
sDrv: String;
oIni: TCustomIniFile;
i, j: Integer;
oTab: TFDDatSTable;
begin
Result := TFDStringList.Create;
try
sDrv := FDUnquote(AKeys.Values[TDBXPropertyNames.DriverName]);
if sDrv <> '' then begin
oIni := TMemIniFile.Create(CfgFile);
try
oIni.ReadSectionValues(sDrv, Result);
oTab := inherited GetConnParams(AKeys, nil);
try
for i := oTab.Rows.Count - 1 downto 0 do begin
j := Result.IndexOfName(oTab.Rows[i].GetData('Name'));
if j <> -1 then
Result.Delete(j);
end;
finally
FDFree(oTab);
end;
finally
FDFree(oIni);
end;
end;
except
FDFree(Result);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
oList, oList2: TStrings;
oIni: TCustomIniFile;
i: Integer;
sName: String;
oManMeta: IFDPhysManagerMetadata;
begin
Result := inherited GetConnParams(AKeys, AParams);
oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + '''');
if oView.Rows.Count = 1 then begin
oView.Rows[0].BeginEdit;
oView.Rows[0].SetValues('LoginIndex', 2);
oView.Rows[0].EndEdit;
end;
oIni := TIniFile.Create(CfgFile);
oList := TFDStringList.Create('"', ';');
try
oIni.ReadSection(TDBXPropertyNames.InstalledDrivers, oList);
Result.Rows.Add([Unassigned, TDBXPropertyNames.DriverName, oList.DelimitedText, '', TDBXPropertyNames.DriverName, -1]);
finally
FDFree(oList);
FDFree(oIni);
end;
oList := GetDriverParams(AKeys);
try
for i := 0 to oList.Count - 1 do begin
sName := oList.KeyNames[i];
oIni := TMemIniFile.Create(CfgFile);
oList2 := TFDStringList.Create('"', ';');
try
oIni.ReadSection(sName, oList2);
Result.Rows.Add([Unassigned, sName, oList2.DelimitedText, oList.ValueFromIndex[i], sName, -1]);
finally
FDFree(oList2);
FDFree(oIni);
end;
end;
finally
FDFree(oList);
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefCatalog, '@S', '', S_FD_ConnParam_Common_MetaDefCatalog, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefSchema, '@S', '', S_FD_ConnParam_Common_MetaDefSchema, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurCatalog, '@S', '', S_FD_ConnParam_Common_MetaCurCatalog, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurSchema, '@S', '', S_FD_ConnParam_Common_MetaCurSchema, -1]);
oList := TStringList.Create(#0, ';');
try
FDPhysManager.CreateMetadata(oManMeta);
oManMeta.GetRDBMSNames(oList);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_RDBMS, oList.DelimitedText, '', S_FD_ConnParam_Common_RDBMS, -1]);
finally
FDFree(oList);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysTDBXConnection }
{-------------------------------------------------------------------------------}
function TFDPhysTDBXConnection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
if ACommand <> nil then
case GetRDBMSKindFromAlias of
{$IFNDEF FireDAC_MOBILE}
TFDRDBMSKinds.Oracle: Result := TFDPhysOraCommandGenerator.Create(ACommand, False);
TFDRDBMSKinds.MSSQL: Result := TFDPhysMSSQLCommandGenerator.Create(ACommand);
TFDRDBMSKinds.MSAccess: Result := TFDPhysMSAccCommandGenerator.Create(ACommand);
TFDRDBMSKinds.MySQL: Result := TFDPhysMySQLCommandGenerator.Create(ACommand);
TFDRDBMSKinds.Db2: Result := TFDPhysDb2CommandGenerator.Create(ACommand);
TFDRDBMSKinds.SQLAnywhere: Result := TFDPhysASACommandGenerator.Create(ACommand);
TFDRDBMSKinds.Advantage: Result := TFDPhysADSCommandGenerator.Create(ACommand);
TFDRDBMSKinds.PostgreSQL: Result := TFDPhysPgCommandGenerator.Create(ACommand);
TFDRDBMSKinds.NexusDB: Result := TFDPhysNexusCommandGenerator.Create(ACommand);
TFDRDBMSKinds.Informix: Result := TFDPhysInfxCommandGenerator.Create(ACommand);
{$ENDIF}
TFDRDBMSKinds.Interbase,
TFDRDBMSKinds.Firebird: Result := TFDPhysIBCommandGenerator.Create(ACommand, 0, ecANSI);
TFDRDBMSKinds.SQLite: Result := TFDPhysSQLiteCommandGenerator.Create(ACommand);
else Result := TFDPhysCommandGenerator.Create(ACommand);
end
else
case GetRDBMSKindFromAlias of
{$IFNDEF FireDAC_MOBILE}
TFDRDBMSKinds.Oracle: Result := TFDPhysOraCommandGenerator.Create(Self, False);
TFDRDBMSKinds.MSSQL: Result := TFDPhysMSSQLCommandGenerator.Create(Self);
TFDRDBMSKinds.MSAccess: Result := TFDPhysMSAccCommandGenerator.Create(Self);
TFDRDBMSKinds.MySQL: Result := TFDPhysMySQLCommandGenerator.Create(Self);
TFDRDBMSKinds.Db2: Result := TFDPhysDb2CommandGenerator.Create(Self);
TFDRDBMSKinds.SQLAnywhere: Result := TFDPhysASACommandGenerator.Create(Self);
TFDRDBMSKinds.Advantage: Result := TFDPhysADSCommandGenerator.Create(Self);
TFDRDBMSKinds.PostgreSQL: Result := TFDPhysPgCommandGenerator.Create(Self);
TFDRDBMSKinds.NexusDB: Result := TFDPhysNexusCommandGenerator.Create(Self);
TFDRDBMSKinds.Informix: Result := TFDPhysInfxCommandGenerator.Create(Self);
{$ENDIF}
TFDRDBMSKinds.Interbase,
TFDRDBMSKinds.Firebird: Result := TFDPhysIBCommandGenerator.Create(Self, 0, ecANSI);
TFDRDBMSKinds.SQLite: Result := TFDPhysSQLiteCommandGenerator.Create(Self);
else Result := TFDPhysCommandGenerator.Create(Self);
end
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXConnection.InternalCreateMetadata: TObject;
var
iSQLDialect: Integer;
iClntVer: TFDVersion;
eBrand: TFDPhysIBBrand;
begin
if (DbxConnection <> nil) and (DbxConnection is TDBXConnection) then
iClntVer := FDVerStr2Int(TDBXConnection(DbxConnection).ProductVersion)
else
iClntVer := 0;
case GetRDBMSKindFromAlias of
{$IFNDEF FireDAC_MOBILE}
TFDRDBMSKinds.Oracle: Result := TFDPhysOraMetadata.Create(Self, iClntVer, iClntVer, False);
TFDRDBMSKinds.MSSQL: Result := TFDPhysMSSQLMetadata.Create(Self, False, True, True, True,
False, 0, iClntVer, False);
TFDRDBMSKinds.MSAccess: Result := TFDPhysMSAccMetadata.Create(Self, 0, iClntVer, GetKeywords);
TFDRDBMSKinds.MySQL: Result := TFDPhysMySQLMetadata.Create(Self, False, 0, iClntVer,
[nmCaseSens, nmDBApply], False);
TFDRDBMSKinds.Db2: Result := TFDPhysDb2Metadata.Create(Self, 0, iClntVer, GetKeywords, False, True);
TFDRDBMSKinds.SQLAnywhere: Result := TFDPhysASAMetadata.Create(Self, 0, iClntVer, GetKeywords);
TFDRDBMSKinds.Advantage: Result := TFDPhysADSMetadata.Create(Self, 0, iClntVer, True);
TFDRDBMSKinds.PostgreSQL: Result := TFDPhysPgMetadata.Create(Self, 0, iClntVer, False, False, False, True);
TFDRDBMSKinds.NexusDB: Result := TFDPhysNexusMetadata.Create(Self, 0, iClntVer);
TFDRDBMSKinds.Informix: Result := TFDPhysInfxMetadata.Create(Self, 0, iClntVer,
GetKeywords, False, True);
{$ENDIF}
TFDRDBMSKinds.Interbase,
TFDRDBMSKinds.Firebird:
begin
iSQLDialect := ConnectionDef.AsInteger[S_FD_ConnParam_IB_SQLDialect];
if iSQLDialect = 0 then
iSQLDialect := 3;
if CompareText(DriverName, 'firebird') = 0 then
eBrand := ibFirebird
else
eBrand := ibInterbase;
Result := TFDPhysIBMetadata.Create(Self, eBrand, 0, iClntVer, iSQLDialect, False);
end;
TFDRDBMSKinds.SQLite: Result := TFDPhysSQLiteMetadata.Create(Self, sbSQLite, 0,
iClntVer, False, False);
else
if (DbxConnection <> nil) and DbxConnection.IsOpen then
Result := TFDPhysTDBXMetadata.Create(Self, GetKeywords)
else
Result := TFDPhysConnectionMetadata.Create(Self, 0, 0, False);
end;
end;
{-------------------------------------------------------------------------------}
initialization
try
TDBXConnectionFactory.GetConnectionFactory;
// if previous line passed OK, then TDBX is installed correctly
FDRegisterDriverClass(TFDPhysTDBXDriver);
except
// none
end;
finalization
FDUnregisterDriverClass(TFDPhysTDBXDriver);
end.
|
unit Threads.TcpServer;
interface
uses Windows, Classes, SysUtils, Threads.Base, blcksock, WinSock, GMGlobals, GMSocket, GeomerLastValue, Connection.Base;
type
TGMTCPServerThread = class;
TGMTCPServerDaemon = class(TGMThread)
private
FPort: int;
FServerSocket: TTCPBlockSocket;
FGlvBuffer: TGeomerLastValuesBuffer;
protected
procedure SafeExecute; override;
function CreateClientSocketThread(clientSocket: TSocket; glvBuffer: TGeomerLastValuesBuffer): TGMTCPServerThread; virtual;
public
constructor Create(port: int; glvBuffer: TGeomerLastValuesBuffer);
destructor Destroy; override;
function Listen(): bool;
end;
TGMTCPServerThread = class(TGMThread)
private
FClientSocket: TTCPBlockSocket;
FGMSocket: TGeomerSocket;
FStartTime: UInt64;
FInitialSendTimeDelay: int;
FInitialCurrentTimeSent: bool;
FLastDataRead: UInt64;
protected
property GMSocket: TGeomerSocket read FGMSocket;
procedure SafeExecute; override;
function CreateGMSocket(clientSocket: TTCPBlockSocket; glvBuffer: TGeomerLastValuesBuffer): TGeomerSocket; virtual;
function ReadAndParseDataBlock: TCheckCOMResult; virtual;
procedure BackgroundWork; virtual;
function SendInitialCurrentTime: bool; virtual;
function SocketLocked: bool;
public
constructor Create(clientSocket: TSocket; glvBuffer: TGeomerLastValuesBuffer);
destructor Destroy; override;
end;
implementation
uses
EsLogging, Winapi.ActiveX, System.Math, GMConst;
{ TGMTCPServerDaemon }
constructor TGMTCPServerDaemon.Create(port: int; glvBuffer: TGeomerLastValuesBuffer);
begin
inherited Create(true);
FPort := port;
FGlvBuffer := glvBuffer;
FServerSocket := TTCPBlockSocket.Create;
end;
function TGMTCPServerDaemon.CreateClientSocketThread(clientSocket: TSocket; glvBuffer: TGeomerLastValuesBuffer): TGMTCPServerThread;
begin
Result := TGMTCPServerThread.Create(clientSocket, glvBuffer)
end;
destructor TGMTCPServerDaemon.Destroy;
begin
FServerSocket.Free();
end;
function TGMTCPServerDaemon.Listen: bool;
begin
if FServerSocket.Socket <> INVALID_SOCKET then
Exit(true);
DefaultLogger.Info('Start on port %d', [FPort]);
FServerSocket.CreateSocket();
if FServerSocket.LastError = 0 then
begin
FServerSocket.Bind('0.0.0.0', IntToStr(FPort));
if FServerSocket.LastError = 0 then
FServerSocket.Listen();
end;
Result := FServerSocket.LastError = 0;
if Result then
begin
DefaultLogger.Info('Listen on port %d', [FPort]);
Start();
end
else
DefaultLogger.Error('Failed Listen on port %d - %s', [FPort, FServerSocket.LastErrorDesc]);
end;
procedure TGMTCPServerDaemon.SafeExecute;
var
clientSocket: TSocket;
begin
while not Terminated do
begin
if FServerSocket.CanRead(1000) then
begin
clientSocket := FServerSocket.Accept();
if FServerSocket.LastError = 0 then
CreateClientSocketThread(clientSocket, FGlvBuffer)
else
DefaultLogger.Error(FServerSocket.LastErrorDesc);
end
else
if FServerSocket.LastError <> 0 then
begin
DefaultLogger.Error(FServerSocket.LastErrorDesc);
Exit;
end;
SleepThread(10);
end;
end;
{ TGMTCPServerThread }
function TGMTCPServerThread.CreateGMSocket(clientSocket: TTCPBlockSocket; glvBuffer: TGeomerLastValuesBuffer): TGeomerSocket;
begin
Result := TGeomerSocket.Create(clientSocket, glvBuffer);
end;
constructor TGMTCPServerThread.Create(clientSocket: TSocket; glvBuffer: TGeomerLastValuesBuffer);
begin
inherited Create(false);
FClientSocket := TTCPBlockSocket.Create;
FClientSocket.Socket := clientSocket;
FGMSocket := CreateGMSocket(FClientSocket, glvBuffer);
FInitialSendTimeDelay := 5;
FInitialCurrentTimeSent := false;
FLastDataRead := 0;
FreeOnTerminate := true;
end;
destructor TGMTCPServerThread.Destroy;
begin
FGMSocket.Free();
FClientSocket.Free();
inherited;
end;
function TGMTCPServerThread.ReadAndParseDataBlock(): TCheckCOMResult;
begin
Result := ccrEmpty;
case FGMSocket.SocketObjectType of
OBJ_TYPE_UNKNOWN,
OBJ_TYPE_CLIENT,
OBJ_TYPE_GM,
OBJ_TYPE_REMOTE_SRV,
OBJ_TYPE_K105:
Result := FGMSocket.ReadAndParseDataBlock();
end;
end;
procedure TGMTCPServerThread.BackgroundWork();
begin
FGMSocket.BackgroundWork();
end;
function TGMTCPServerThread.SendInitialCurrentTime: bool;
begin
if FInitialCurrentTimeSent or (NowGM() - FStartTime < FInitialSendTimeDelay) then
Exit(true);
DefaultLogger.Info('SendCurrentTime');
Result := FGMSocket.SendCurrentTime() = 0;
FInitialCurrentTimeSent := true;
end;
function TGMTCPServerThread.SocketLocked: bool;
begin
Result := FGMSocket.Locked();
end;
procedure TGMTCPServerThread.SafeExecute;
var
res: TCheckCOMResult;
FLastLockTime: UInt64;
begin
CoInitialize(nil);
try
FClientSocket.GetSins();
FStartTime := NowGM();
FLastLockTime := 0;
while not Terminated do
begin
if SocketLocked() then
begin
if FLastLockTime = 0 then
FLastLockTime := GetTickCount64();
if GetTickCount64() - FLastLockTime > 300 * 1000 then
begin
DefaultLogger.Info('Too long lock, breaking');
break;
end;
SleepThread(10);
continue;
end
else
FLastLockTime := 0;
res := ReadAndParseDataBlock();
if res = ccrError then
break;
BackgroundWork();
FLastDataRead := GMSocket.LastReadUTime;
if (FLastDataRead = 0) and not SendInitialCurrentTime() then
begin
DefaultLogger.Info('SendInitialCurrentTime failed');
break;
end;
if Abs(NowGM() - Max(FLastDataRead, FStartTime)) > 300 then
begin
DefaultLogger.Info('Too long idle, breaking');
break;
end;
SleepThread(10);
end;
finally
CoUninitialize();
end;
end;
end.
|
unit MediaPlayerImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB, MPlayer;
type
TMediaPlayerX = class(TActiveXControl, IMediaPlayerX)
private
{ Private declarations }
FDelphiControl: TMediaPlayer;
FEvents: IMediaPlayerXEvents;
procedure ClickEvent(Sender: TObject; Button: TMPBtnType;
var DoDefault: Boolean);
procedure NotifyEvent(Sender: TObject);
procedure PostClickEvent(Sender: TObject; Button: TMPBtnType);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_AutoEnable: WordBool; safecall;
function Get_AutoOpen: WordBool; safecall;
function Get_AutoRewind: WordBool; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DeviceID: Smallint; safecall;
function Get_DeviceType: TxMPDeviceTypes; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_Enabled: WordBool; safecall;
function Get_EndPos: Integer; safecall;
function Get_Error: Integer; safecall;
function Get_ErrorMessage: WideString; safecall;
function Get_FileName: WideString; safecall;
function Get_Frames: Integer; safecall;
function Get_Length: Integer; safecall;
function Get_Mode: TxMPModes; safecall;
function Get_Notify: WordBool; safecall;
function Get_NotifyValue: TxMPNotifyValues; safecall;
function Get_Position: Integer; safecall;
function Get_Shareable: WordBool; safecall;
function Get_Start: Integer; safecall;
function Get_StartPos: Integer; safecall;
function Get_TimeFormat: TxMPTimeFormats; safecall;
function Get_Tracks: Integer; safecall;
function Get_Visible: WordBool; safecall;
function Get_Wait: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure AboutBox; safecall;
procedure Back; safecall;
procedure Close; safecall;
procedure Eject; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Next; safecall;
procedure Open; safecall;
procedure Pause; safecall;
procedure PauseOnly; safecall;
procedure Play; safecall;
procedure Previous; safecall;
procedure Resume; safecall;
procedure Rewind; safecall;
procedure Save; safecall;
procedure Set_AutoEnable(Value: WordBool); safecall;
procedure Set_AutoOpen(Value: WordBool); safecall;
procedure Set_AutoRewind(Value: WordBool); safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DeviceType(Value: TxMPDeviceTypes); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_EndPos(Value: Integer); safecall;
procedure Set_FileName(const Value: WideString); safecall;
procedure Set_Frames(Value: Integer); safecall;
procedure Set_Notify(Value: WordBool); safecall;
procedure Set_Position(Value: Integer); safecall;
procedure Set_Shareable(Value: WordBool); safecall;
procedure Set_StartPos(Value: Integer); safecall;
procedure Set_TimeFormat(Value: TxMPTimeFormats); safecall;
procedure Set_Visible(Value: WordBool); safecall;
procedure Set_Wait(Value: WordBool); safecall;
procedure StartRecording; safecall;
procedure Step; safecall;
procedure Stop; safecall;
end;
implementation
uses ComObj, About16;
{ TMediaPlayerX }
procedure TMediaPlayerX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_MediaPlayerXPage); }
end;
procedure TMediaPlayerX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IMediaPlayerXEvents;
end;
procedure TMediaPlayerX.InitializeControl;
begin
FDelphiControl := Control as TMediaPlayer;
FDelphiControl.OnClick := ClickEvent;
FDelphiControl.OnNotify := NotifyEvent;
FDelphiControl.OnPostClick := PostClickEvent;
end;
function TMediaPlayerX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TMediaPlayerX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TMediaPlayerX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TMediaPlayerX.Get_AutoEnable: WordBool;
begin
Result := FDelphiControl.AutoEnable;
end;
function TMediaPlayerX.Get_AutoOpen: WordBool;
begin
Result := FDelphiControl.AutoOpen;
end;
function TMediaPlayerX.Get_AutoRewind: WordBool;
begin
Result := FDelphiControl.AutoRewind;
end;
function TMediaPlayerX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TMediaPlayerX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TMediaPlayerX.Get_DeviceID: Smallint;
begin
Result := Smallint(FDelphiControl.DeviceID);
end;
function TMediaPlayerX.Get_DeviceType: TxMPDeviceTypes;
begin
Result := Ord(FDelphiControl.DeviceType);
end;
function TMediaPlayerX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TMediaPlayerX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TMediaPlayerX.Get_EndPos: Integer;
begin
Result := FDelphiControl.EndPos;
end;
function TMediaPlayerX.Get_Error: Integer;
begin
Result := FDelphiControl.Error;
end;
function TMediaPlayerX.Get_ErrorMessage: WideString;
begin
Result := WideString(FDelphiControl.ErrorMessage);
end;
function TMediaPlayerX.Get_FileName: WideString;
begin
Result := WideString(FDelphiControl.FileName);
end;
function TMediaPlayerX.Get_Frames: Integer;
begin
Result := FDelphiControl.Frames;
end;
function TMediaPlayerX.Get_Length: Integer;
begin
Result := FDelphiControl.Length;
end;
function TMediaPlayerX.Get_Mode: TxMPModes;
begin
Result := Ord(FDelphiControl.Mode);
end;
function TMediaPlayerX.Get_Notify: WordBool;
begin
Result := FDelphiControl.Notify;
end;
function TMediaPlayerX.Get_NotifyValue: TxMPNotifyValues;
begin
Result := Ord(FDelphiControl.NotifyValue);
end;
function TMediaPlayerX.Get_Position: Integer;
begin
Result := FDelphiControl.Position;
end;
function TMediaPlayerX.Get_Shareable: WordBool;
begin
Result := FDelphiControl.Shareable;
end;
function TMediaPlayerX.Get_Start: Integer;
begin
Result := FDelphiControl.Start;
end;
function TMediaPlayerX.Get_StartPos: Integer;
begin
Result := FDelphiControl.StartPos;
end;
function TMediaPlayerX.Get_TimeFormat: TxMPTimeFormats;
begin
Result := Ord(FDelphiControl.TimeFormat);
end;
function TMediaPlayerX.Get_Tracks: Integer;
begin
Result := FDelphiControl.Tracks;
end;
function TMediaPlayerX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TMediaPlayerX.Get_Wait: WordBool;
begin
Result := FDelphiControl.Wait;
end;
function TMediaPlayerX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TMediaPlayerX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TMediaPlayerX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TMediaPlayerX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TMediaPlayerX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TMediaPlayerX.AboutBox;
begin
ShowMediaPlayerXAbout;
end;
procedure TMediaPlayerX.Back;
begin
FDelphiControl.Back;
end;
procedure TMediaPlayerX.Close;
begin
FDelphiControl.Close;
end;
procedure TMediaPlayerX.Eject;
begin
FDelphiControl.Eject;
end;
procedure TMediaPlayerX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TMediaPlayerX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TMediaPlayerX.Next;
begin
FDelphiControl.Next;
end;
procedure TMediaPlayerX.Open;
begin
FDelphiControl.Open;
end;
procedure TMediaPlayerX.Pause;
begin
FDelphiControl.Pause;
end;
procedure TMediaPlayerX.PauseOnly;
begin
FDelphiControl.PauseOnly;
end;
procedure TMediaPlayerX.Play;
begin
FDelphiControl.Play;
end;
procedure TMediaPlayerX.Previous;
begin
FDelphiControl.Previous;
end;
procedure TMediaPlayerX.Resume;
begin
FDelphiControl.Resume;
end;
procedure TMediaPlayerX.Rewind;
begin
FDelphiControl.Rewind;
end;
procedure TMediaPlayerX.Save;
begin
FDelphiControl.Save;
end;
procedure TMediaPlayerX.Set_AutoEnable(Value: WordBool);
begin
FDelphiControl.AutoEnable := Value;
end;
procedure TMediaPlayerX.Set_AutoOpen(Value: WordBool);
begin
FDelphiControl.AutoOpen := Value;
end;
procedure TMediaPlayerX.Set_AutoRewind(Value: WordBool);
begin
FDelphiControl.AutoRewind := Value;
end;
procedure TMediaPlayerX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TMediaPlayerX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TMediaPlayerX.Set_DeviceType(Value: TxMPDeviceTypes);
begin
FDelphiControl.DeviceType := TMPDeviceTypes(Value);
end;
procedure TMediaPlayerX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TMediaPlayerX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TMediaPlayerX.Set_EndPos(Value: Integer);
begin
FDelphiControl.EndPos := Value;
end;
procedure TMediaPlayerX.Set_FileName(const Value: WideString);
begin
FDelphiControl.FileName := String(Value);
end;
procedure TMediaPlayerX.Set_Frames(Value: Integer);
begin
FDelphiControl.Frames := Value;
end;
procedure TMediaPlayerX.Set_Notify(Value: WordBool);
begin
FDelphiControl.Notify := Value;
end;
procedure TMediaPlayerX.Set_Position(Value: Integer);
begin
FDelphiControl.Position := Value;
end;
procedure TMediaPlayerX.Set_Shareable(Value: WordBool);
begin
FDelphiControl.Shareable := Value;
end;
procedure TMediaPlayerX.Set_StartPos(Value: Integer);
begin
FDelphiControl.StartPos := Value;
end;
procedure TMediaPlayerX.Set_TimeFormat(Value: TxMPTimeFormats);
begin
FDelphiControl.TimeFormat := TMPTimeFormats(Value);
end;
procedure TMediaPlayerX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TMediaPlayerX.Set_Wait(Value: WordBool);
begin
FDelphiControl.Wait := Value;
end;
procedure TMediaPlayerX.StartRecording;
begin
FDelphiControl.StartRecording;
end;
procedure TMediaPlayerX.Step;
begin
FDelphiControl.Step;
end;
procedure TMediaPlayerX.Stop;
begin
FDelphiControl.Stop;
end;
procedure TMediaPlayerX.ClickEvent(Sender: TObject; Button: TMPBtnType;
var DoDefault: Boolean);
var
TempDoDefault: WordBool;
begin
TempDoDefault := WordBool(DoDefault);
if FEvents <> nil then FEvents.OnClick(TxMPBtnType(Button), TempDoDefault);
DoDefault := Boolean(TempDoDefault);
end;
procedure TMediaPlayerX.NotifyEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnNotify;
end;
procedure TMediaPlayerX.PostClickEvent(Sender: TObject;
Button: TMPBtnType);
begin
if FEvents <> nil then FEvents.OnPostClick(TxMPBtnType(Button));
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TMediaPlayerX,
TMediaPlayer,
Class_MediaPlayerX,
16,
'{695CDB52-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
unit Model.Customer;
interface
uses
System.Generics.Collections, iORM.Attributes, Model.PhoneNumber;
type
[ioEntity]
TCustomer = class
private
FID: Integer;
FFirstName: String;
FLastName: String;
FAddress: String;
FNumbers: TObjectList<TPhoneNumber>;
function GetFullName: String;
public
constructor Create;
destructor Destroy; override;
property ID:Integer read FID write FID;
property FirstName: String read FFirstName write FFirstName;
property LastName: String read FLastName write FLastName;
property Address:String read FAddress write FAddress;
[ioHasMany(TPhoneNumber, 'CustomerID')]
property Numbers:TObjectList<TPhoneNumber> read FNumbers write FNumbers;
[ioSkip]
property FullName:String read GetFullName;
end;
implementation
{ TCustomer }
constructor TCustomer.Create;
begin
FNumbers := TObjectList<TPhoneNumber>.Create;
end;
destructor TCustomer.Destroy;
begin
FNumbers.Free;
inherited;
end;
function TCustomer.GetFullName: String;
begin
Result := FFirstName + ' ' + FLastName;
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
// 公司信息设置
//主要实现:
// 公司信息设置
//-----------------------------------------------------------------------------}
unit untEasyCompanySet;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, untEasyPlateDBFormExt, atScript, atScripter, ActnList, ImgList,
untEasyToolBar, untEasyToolBarStylers, ExtCtrls, untEasyGroupBox;
//插件导出函数
function ShowBplForm(AParamList: TStrings): TForm; stdcall; exports ShowBplForm;
type
TfrmEasyCompanySet = class(TfrmEasyPlateDBFormExt)
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmEasyCompanySet: TfrmEasyCompanySet;
implementation
{$R *.dfm}
//引出函数实现
function ShowBplForm(AParamList: TStrings): TForm;
begin
frmEasyCompanySet := TfrmEasyCompanySet.Create(Application);
if frmEasyCompanySet.FormStyle <> fsMDIChild then
frmEasyCompanySet.FormStyle := fsMDIChild;
if frmEasyCompanySet.WindowState <> wsMaximized then
frmEasyCompanySet.WindowState := wsMaximized;
Result := frmEasyCompanySet;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Tabs, Vcl.StdCtrls, DateUtils, ShellApi, IniFiles,
Vcl.ComCtrls;
type
TForm1 = class(TForm)
PageControl1: TPageControl;
Общение: TTabSheet;
Учение: TTabSheet;
Memo1: TMemo;
Teach_Answer: TLabeledEdit;
Memo2: TMemo;
User_Enter_Text: TEdit;
Say: TButton;
Teach_check: TButton;
Teach_Add: TButton;
Настройки: TTabSheet;
User_Name: TLabeledEdit;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
Robot_Name: TLabeledEdit;
Save_Options: TButton;
Memo3: TMemo;
Teach_Words: TLabeledEdit;
Clear_Memo2: TButton;
Change_Words: TButton;
Insert_Robot_Name_Code: TButton;
Insert_User_Name_Code: TButton;
GroupBox3: TGroupBox;
GroupBox4: TGroupBox;
GroupBox5: TGroupBox;
CheckBox1: TCheckBox;
TabSheet1: TTabSheet;
Label1: TLabel;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure SayClick(Sender: TObject);
procedure Teach_checkClick(Sender: TObject);
procedure Clear_Memo2Click(Sender: TObject);
procedure Teach_AddClick(Sender: TObject);
procedure Change_WordsClick(Sender: TObject);
procedure Insert_User_Name_CodeClick(Sender: TObject);
procedure Insert_Robot_Name_CodeClick(Sender: TObject);
procedure Save_OptionsClick(Sender: TObject);
private
procedure Robot_Say(Say: String; i: integer);
procedure User_Say(Say: String; i: integer);
procedure FindAnswer;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
IniFile: TIniFile;
implementation
{$R *.dfm}
type Words_Type = array of String;
const Robot_Name_Code = '#ROBOT_NAME#';
const User_Name_Code = '#USER_NAME#';
// \/:*?"<>|
const sign_1 = '#sign_1#'; // \
const sign_2 = '#sign_2#'; // /
const sign_3 = '#sign_3#'; // :
const sign_4 = '#sign_4#'; // *
const sign_5 = '#sign_5#'; // ?
const sign_6 = '#sign_6#'; // "
const sign_7 = '#sign_7#'; // <
const sign_8 = '#sign_8#'; // >
const sign_9 = '#sign_9#'; // |
// 1-\ 2-/ 3-: 4-* 5-? 6-" 7-< 8-> 9-|
var AppPath, AppName: String;
File_Answer: TextFile;
Path: String;
function GetMonth: String;
begin
Result := DateToStr(Date);
Delete(Result, 1, Pos('.', Result));
end;
procedure SaveData;
begin
Path := ExtractFilePath(Application.ExeName) + 'Data' + '\';
if DirectoryExists(Path) = FALSE then
CreateDir(Path);
if DirectoryExists(Path + GetMonth) = FALSE then
CreateDir(Path + GetMonth);
if FileExists(Path + GetMonth + '\' + DateToStr(Date)) then
begin
//Memo1.Lines.LoadFromFile(Path + GetMonth + '\' + DateToStr(Date));
//ListBox1.Items.LoadFromFile(ExtractFilePath(Application.ExeName) + '\' + File_Today_Name);
//SoundsChoose.Items.LoadFromFile(ExtractFilePath(Application.ExeName) + '\' + File_Name);
//SoundsChooseForAlarmOnce.Items.LoadFromFile(ExtractFilePath(Application.ExeName) + '\' + File_Name);
end
else
begin
AssignFile(File_Answer, Path + GetMonth + '\' + DateToStr(Date));
ReWrite(File_Answer);
CloseFile(File_Answer);
end;
end;
function ReplaseText(Text, Substr, Replace_To: String): String;
var S: String;
insert_index: integer;
begin
S := Text;
insert_index := Pos(Substr, S);
Delete(S, insert_index, Length(Substr));
Insert(Replace_To, S, insert_index);
Result := S;
end;
procedure TForm1.Robot_Say(Say: String; i: integer);
begin
if Pos(sign_1, Say) <> 0 then
begin
Say := ReplaseText(Say, sign_1, '\');
end;
if Pos(sign_2, Say) <> 0 then
begin
Say := ReplaseText(Say, sign_2, '/');
end;
if Pos(sign_3, Say) <> 0 then
begin
Say := ReplaseText(Say, sign_3, ':');
end;
if Pos(sign_4, Say) <> 0 then
begin
Say := ReplaseText(Say, sign_4, '*');
end;
if Pos(sign_5, Say) <> 0 then
begin
Say := ReplaseText(Say, sign_5, '?');
end;
if Pos(sign_6, Say) <> 0 then
begin
Say := ReplaseText(Say, sign_6, '"');
end;
if Pos(sign_7, Say) <> 0 then
begin
Say := ReplaseText(Say, sign_7, '<');
end;
if Pos(sign_8, Say) <> 0 then
begin
Say := ReplaseText(Say, sign_8, '>');
end;
if Pos(sign_9, Say) <> 0 then
begin
Say := ReplaseText(Say, sign_9, '|');
end;
if Pos(Robot_Name_Code, Say) <> 0 then
begin
Say := ReplaseText(Say, Robot_Name_Code, Robot_Name.Text);
end;
if Pos(User_Name_Code, Say) <> 0 then
begin
Say := ReplaseText(Say, User_Name_Code, User_Name.Text);
end;
case i of
1:
begin
Memo1.Lines.Add(' - ' + Trim(Robot_Name.Text) + ' говорит: ' + Trim(Say));
exit;
end;
2:
begin
Memo2.Lines.Add(' - ' + Trim(Robot_Name.Text) + ' говорит: ' + Trim(Say));
exit;
end;
end;
end;
procedure TForm1.User_Say(Say: String; i: integer);
begin
case i of
1:
begin
Memo1.Lines.Add(' - ' + Trim(User_Name.Text) + ' говорит: ' + Trim(Say));
exit;
end;
2:
begin
Memo2.Lines.Add(' - ' + Trim(User_Name.Text) + ' говорит: ' + Trim(Say));
exit;
end;
end;
end;
function FillWordsArray(Say: String): Words_Type;
var i: integer;
Words: Words_Type;
begin
Trim(Say);
if Pos('\', Say) <> 0 then // 1-\ 2-/ 3-: 4-* 5-? 6-" 7-< 8-> 9-|
Say := ReplaseText(Say, '\', sign_1);
if Pos('/', Say) <> 0 then
Say := ReplaseText(Say, '/', sign_2);
if Pos(':', Say) <> 0 then
Say := ReplaseText(Say, ':', sign_3);
if Pos('*', Say) <> 0 then
Say := ReplaseText(Say, '*', sign_4);
if Pos('?', Say) <> 0 then
Say := ReplaseText(Say, '?', sign_5);
if Pos('"', Say) <> 0 then
Say := ReplaseText(Say, '"', sign_6);
if Pos('<', Say) <> 0 then
Say := ReplaseText(Say, '<', sign_7);
if Pos('>', Say) <> 0 then
Say := ReplaseText(Say, '>', sign_8);
if Pos('|', Say) <> 0 then
Say := ReplaseText(Say, '|', sign_9);
while Length(Say) <> 0 do
begin
SetLength(Words, Length(Words) + 1);
if Pos(' ', Say) = 0 then
Words[Length(Words) - 1] := Copy(Say, 1, Length(Say))
else
Words[Length(Words) - 1] := Copy(Say, 1, Pos(' ', Say) - 1);
if Pos(' ', Say) = 0 then
Delete(Say, 1, Length(Say))
else
Delete(Say, 1, Pos(' ', Say));
end;
Result := Words;
end;
function CreatePathFromWords(Words: Words_Type): String;
var Path: String;
i: integer;
begin
for I := 0 to High(Words) do
Path := Path + Words[i] + '\';
Result := Path;
end;
procedure TForm1.Change_WordsClick(Sender: TObject);
var Words: Words_Type;
Words_Path: String;
begin
Words := FillWordsArray(Teach_Words.Text);
Words_Path := CreatePathFromWords(Words);
Path := ExtractFilePath(Application.ExeName) + 'Data' + '\';
if FileExists(Path + Words_Path + 'default.txt') then
begin
ShellExecute(0, 'Open', PChar(Path + Words_Path + 'default.txt'), '', nil, 1);
end
else
ShowMessage('Нужный файл не был найден');
end;
procedure TForm1.Clear_Memo2Click(Sender: TObject);
begin
Memo2.Clear;
end;
procedure TForm1.FindAnswer;
var Words: Words_Type;
Words_Path, Words_Path_Relative, Answer: String;
i: integer;
begin
Words := FillWordsArray(User_Enter_Text.Text);
Words_Path := CreatePathFromWords(Words);
Path := ExtractFilePath(Application.ExeName) + 'Data' + '\';
if DirectoryExists(Path) = FALSE then
CreateDir(Path);
if FileExists(Path + Words_Path + 'default.txt') then
begin
Memo3.Lines.LoadFromFile(Path + Words_Path + 'default.txt');
if Memo3.Lines.Count = 0 then
begin
PageControl1.TabIndex := 1;
Teach_Words.Text := Trim(User_Enter_Text.Text);
end
else
begin
User_Say(User_Enter_Text.Text, 1);
Robot_Say(Memo3.Lines[Random(Memo3.Lines.Count)], 1);
end;
end
else
begin
for I := 0 to High(Words) do
begin
Words_Path_Relative := Words_Path_Relative + Words[i] + '\';
if DirectoryExists(Path + Words_Path_Relative) = FALSE then
CreateDir(Path + Words_Path_Relative);
end;
AssignFile(File_Answer, Path + Words_Path + 'default.txt');
ReWrite(File_Answer);
CloseFile(File_Answer);
Memo3.Lines.LoadFromFile(Path + Words_Path + 'default.txt');
if Memo3.Lines.Count = 0 then
begin
PageControl1.TabIndex := 1;
Teach_Words.Text := Trim(User_Enter_Text.Text);
Teach_Answer.Clear;
Teach_Answer.SetFocus;
end
else
begin
User_Say(User_Enter_Text.Text, 1);
Robot_Say(Memo3.Lines[Random(Memo3.Lines.Count)], 1);
end;
end;
end;
procedure TForm1.Save_OptionsClick(Sender: TObject);
begin
IniFile.WriteString('DATA','USER NAME', User_Name.Text);
IniFile.WriteString('DATA','ROBOT NAME', Robot_Name.Text);
if CheckBox1.Checked then
IniFile.WriteBool('OPTIONS','Hello', TRUE)
else
IniFile.WriteBool('OPTIONS','Hello', FALSE);
if CheckBox2.Checked then
IniFile.WriteBool('OPTIONS','Clear', TRUE)
else
IniFile.WriteBool('OPTIONS','Clear', FALSE);
if CheckBox3.Checked then
IniFile.WriteBool('OPTIONS','Clear 2', TRUE)
else
IniFile.WriteBool('OPTIONS','Clear 2', FALSE);
end;
procedure TForm1.SayClick(Sender: TObject);
var Words: Words_Type;
begin
if Length(Trim(User_Enter_Text.Text)) <> 0 then
FindAnswer;
User_Enter_Text.Clear;
end;
procedure TForm1.Teach_AddClick(Sender: TObject);
var Words: Words_Type;
Words_Path, Words_Path_Relative: String;
i: integer;
begin
if (Length(Trim(Teach_Words.Text)) <> 0) and (Length(Trim(Teach_Answer.Text)) <> 0) then
begin
Words := FillWordsArray(Teach_Words.Text);
Words_Path := CreatePathFromWords(Words);
Path := ExtractFilePath(Application.ExeName) + 'Data' + '\';
if DirectoryExists(Path) = FALSE then
CreateDir(Path);
if FileExists(Path + Words_Path + 'default.txt') then
begin
Memo3.Lines.LoadFromFile(Path + Words_Path + 'default.txt');
if Memo3.Lines.IndexOf(Trim(Teach_Answer.Text)) < 0 then
begin
Memo3.Lines.Add(Trim(Teach_Answer.Text));
Memo3.Lines.SaveToFile(Path + Words_Path + 'default.txt');
Memo2.Lines.Add('**** ЗАПИСЬ [' + Trim(Teach_Answer.Text) + '] УСПЕШНО ДОБАВЛЕНА ****');
end
else
Memo2.Lines.Add('**** ЗАПИСЬ [' + Trim(Teach_Answer.Text) + '] УЖЕ СУЩЕСТВУЕТ ****');
end
else
begin
for I := 0 to High(Words) do
begin
Words_Path_Relative := Words_Path_Relative + Words[i] + '\';
if DirectoryExists(Path + Words_Path_Relative) = FALSE then
CreateDir(Path + Words_Path_Relative);
end;
AssignFile(File_Answer, Path + Words_Path + 'default.txt');
ReWrite(File_Answer);
CloseFile(File_Answer);
Memo3.Lines.LoadFromFile(Path + Words_Path + 'default.txt');
if Memo3.Lines.IndexOf(Trim(Teach_Answer.Text)) < 0 then
begin
Memo3.Lines.Add(Trim(Teach_Answer.Text));
Memo3.Lines.SaveToFile(Path + Words_Path + 'default.txt');
Memo2.Lines.Add('**** ЗАПИСЬ [' + Trim(Teach_Answer.Text) + '] УСПЕШНО ДОБАВЛЕНА ****');
end
else
Memo2.Lines.Add('**** ЗАПИСЬ [' + Trim(Teach_Answer.Text) + '] УЖЕ СУЩЕСТВУЕТ ****');
end;
if CheckBox2.Checked then
begin
Teach_Words.Clear;
Teach_Answer.Clear;
end;
if CheckBox3.Checked then
begin
Teach_Answer.Clear;
end;
end
else
ShowMessage('Одно из полей пустое!');
end;
procedure TForm1.Teach_checkClick(Sender: TObject);
begin
if (Length(Trim(Teach_Words.Text)) <> 0) and (Length(Trim(Teach_Answer.Text)) <> 0) then
begin
User_Say(Trim(Teach_Words.Text), 2);
Robot_Say(Trim(Teach_Answer.Text), 2);
end
else
ShowMessage('Одно из полей пустое!');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
IniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + '\' + 'Options.ini');
User_Name.Text := IniFile.ReadString('DATA','USER NAME', 'Хозяин');
Robot_Name.Text := IniFile.ReadString('DATA','ROBOT NAME', 'Джек');
CheckBox1.Checked := IniFile.ReadBool('OPTIONS','Hello', FALSE);
CheckBox2.Checked := IniFile.ReadBool('OPTIONS','Clear', FALSE);
CheckBox3.Checked := IniFile.ReadBool('OPTIONS','Clear 2', TRUE);
PageControl1.TabIndex := 0;
//Memo1.Lines.Add('Привет ' + User_Name.Text + ', тебя приветствует робот ' + Robot_Name.Text + '! Я обещаю, что буду прилежно учиться всему, что ты сочтёшь для меня полезным! Ну, давай, я весь в внимании ;)');
if not CheckBox1.Checked then
Robot_Say('Привет ' + User_Name.Text + ', тебя приветствует робот ' + Robot_Name.Text + '! Я обещаю, что буду прилежно учиться всему, что ты сочтёшь для меня полезным! Ну, давай пообщаемся ;)', 1);
Label1.Caption := 'Программа искусственного интеллекта "' + Form1.Caption + '"' + #13#10 + //' + #13#10 + '
#13#10 + #13#10 + 'Авторское право © 2012 Кучеров Р. М.' + #13#10 +
'Надеюсь, большинство прав защищено.' + #13#10 + #13#10 +
'Любую критику, вопросы, предложения - ' + #13#10 +
'с радостью почитаю по адресу quoe@mail.ru'
end;
procedure TForm1.Insert_Robot_Name_CodeClick(Sender: TObject);
begin
Teach_Answer.Text := Teach_Answer.Text + Robot_Name_Code + ' ';
end;
procedure TForm1.Insert_User_Name_CodeClick(Sender: TObject);
begin
Teach_Answer.Text := Teach_Answer.Text + User_Name_Code + ' ';
end;
end.
|
unit uNexusDBUtils;
interface
uses
Variants,
nxsdNativeVariantConverter,
SysUtils,
nxsdTypes,
nxllTypes,
nxllUtils,
nxllMemoryManager,
nxsqlProxies,
nxsdDataDictionary,
nxsdServerEngine,
nxsrServerEngine;
type
TnxNativeField = object
private
nfOldData : PnxByteArray;
nfNewData : PnxByteArray;
nfOffSet : Integer;
nfField : Integer;
nfLen : Integer;
nfLogRecLenAlign : Integer;
function GetNewNull: Boolean;
function GetOldNull: Boolean;
procedure SetNewNull(const Value: Boolean);
procedure SetOldNull(const Value: Boolean);
protected
function NewData: PnxByteArray;
function OldData: PnxByteArray;
public
function FieldType: TnxFieldType; virtual;
property OldNull: Boolean
read GetOldNull write SetOldNull;
property NewNull: Boolean
read GetNewNull write SetNewNull;
function Changed: Boolean;
end;
TnxBooleanField = object (TnxNativeField)
private
function GetNewValue: Boolean;
procedure SetNewValue(const Value: Boolean);
public
function FieldType: TnxFieldType; virtual;
function OldValue : Boolean;
property NewValue: Boolean
read GetNewValue write SetNewValue;
end;
TnxByteField = object (TnxNativeField)
private
function GetNewValue: Byte;
procedure SetNewValue(const Value: Byte);
public
function FieldType: TnxFieldType; virtual;
function OldValue: Byte;
property NewValue: Byte
read GetNewValue write SetNewValue;
end;
TnxWord16Field = object ( TnxNativeField )
private
function GetNewValue: TnxWord16;
procedure SetNewValue(const Value: TnxWord16);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxWord16;
property NewValue: TnxWord16
read GetNewValue write SetNewValue;
end;
TnxWord32Field = object ( TnxNativeField )
private
function GetNewValue: TnxWord32;
procedure SetNewValue(const Value: TnxWord32);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxWord32;
property NewValue: TnxWord32
read GetNewValue write SetNewValue;
end;
TnxInt8Field = object ( TnxNativeField )
private
function GetNewValue: TnxInt8;
procedure SetNewValue(const Value: TnxInt8);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxInt8;
property NewValue: TnxInt8
read GetNewValue write SetNewValue;
end;
TnxInt16Field = object ( TnxNativeField )
private
function GetNewValue: TnxInt16;
procedure SetNewValue(const Value: TnxInt16);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxInt16;
property NewValue : TnxInt16
read GetNewValue write SetNewValue;
end;
TnxInt32Field = object ( TnxNativeField )
private
function GetNewValue: TnxInt32;
procedure SetNewValue(const Value: TnxInt32);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxInt32;
property NewValue: TnxInt32
read GetNewValue write SetNewValue;
end;
TnxInt64Field = object ( TnxNativeField )
private
function GetNewValue: TnxInt64;
procedure SetNewValue(const Value: TnxInt64);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxInt64;
property NewValue: TnxInt64
read GetNewValue write SetNewValue;
end;
TnxAutoIncField = object ( TnxWord32Field )
public
function FieldType: TnxFieldType; virtual;
end;
TnxSingleField = object ( TnxNativeField )
private
function GetNewValue: TnxSingle;
procedure SetNewValue(const Value: TnxSingle);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxSingle;
property NewValue: TnxSingle
read GetNewValue write SetNewValue;
end;
TnxDoubleField = object ( TnxNativeField )
private
function GetNewValue: TnxDouble;
procedure SetNewValue(const Value: TnxDouble);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxDouble;
property NewValue: TnxDouble
read GetNewValue write SetNewValue;
end;
TnxExtendedField = object ( TnxNativeField )
private
function GetNewValue: TnxExtended;
procedure SetNewValue(const Value: TnxExtended);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxExtended;
property NewValue: TnxExtended
read GetNewValue write SetNewValue;
end;
TnxCurrencyField = object ( TnxNativeField )
private
function GetNewValue: TnxCurrency;
procedure SetNewValue(const Value: TnxCurrency);
public
function FieldType: TnxFieldType; virtual;
function OldValue : TnxCurrency;
property NewValue : TnxCurrency
read GetNewValue write SetNewValue;
end;
TnxDateField = object ( TnxNativeField )
private
function GetNewValue: TnxDate;
procedure SetNewValue(const Value: TnxDate);
public
function FieldType: TnxFieldType; virtual;
function OldValue : TnxDate;
property NewValue : TnxDate
read GetNewValue write SetNewValue;
end;
TnxTimeField = object ( TnxNativeField )
private
function GetNewValue: TnxTime;
procedure SetNewValue(const Value: TnxTime);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxTime;
property NewValue: TnxTime
read GetNewValue write SetNewValue;
end;
TnxDateTimeField = object ( TnxNativeField )
private
function GetNewValue: TnxDateTime;
procedure SetNewValue(const Value: TnxDateTime);
public
function FieldType: TnxFieldType; virtual;
function OldValue: TnxDateTime;
property NewValue: TnxDateTime
read GetNewValue write SetNewValue;
end;
TnxShortStringField = object ( TnxNativeField )
private
function GetNewValue: ShortString;
procedure SetNewValue(const Value: ShortString);
public
function FieldType: TnxFieldType; virtual;
function OldValue : ShortString;
property NewValue: ShortString
read GetNewValue write SetNewValue;
end;
TnxNullStringField = object ( TnxNativeField )
private
function GetNewValue: String;
procedure SetNewValue(const Value: String);
public
function FieldType: TnxFieldType; virtual;
function OldData: String;
property NewValue: String
read GetNewValue write SetNewValue;
end;
TnxHelpCursor = class
private
FOpenMode : Boolean;
FActive : Boolean;
FDB : TnxServerDatabase;
FName : String;
procedure SetActive(const Value: Boolean);
public
FBuffer : PnxByteArray;
FOldData : PnxByteArray;
FNewData : PnxByteArray;
FKeyData1 : PnxByteArray;
FKeyData2 : PnxByteArray;
FCursor : TnxServerBaseCursor;
FDictionary : TnxDataDictionary;
constructor Create(aOldData, aNewData, aKey1, aKey2: PnxByteArray; aCursor: TnxServerBaseCursor);
constructor CreateOpen(aName: String; aDB: TnxServerDatabase);
destructor Destroy; override;
function GetValue(aFieldName: String; aData: PnxByteArray; aDefValue: Variant): Variant;
function NewValue(aFieldName: String; aDefValue: Variant): Variant;
function OldValue(aFieldName: String; aDefValue: Variant): Variant;
procedure SetValueCustom(aFieldName: String; aValue: Variant; aData: PnxByteArray);
procedure SetValue(aFieldName: String; aValue: Variant);
procedure SetKey1(aFieldName: String; aValue: Variant);
procedure SetKey2(aFieldName: String; aValue: Variant);
function GetNext: Boolean;
function Last: Boolean;
function Prior: Boolean;
function Next: Boolean;
function LeByte(aFieldName: String; aNew: Boolean=True): Byte;
function LeCurrency(aFieldName: String; aNew: Boolean=True): Currency;
// function LeDateTime(aFieldName: String; aNew: Boolean=True): TDateTime;
function LeDouble(aFieldName: String; aNew: Boolean=True): Double;
function LeInteger(aFieldName: String; aNew: Boolean=True): Integer;
function LeWord(aFieldName: String; aNew: Boolean=True): Word;
function LeWord32(aFieldName: String; aNew: Boolean=True): Cardinal;
function LeBool(aFieldName: String; aNew: Boolean=True): Boolean;
procedure SetDateTimeField(aFieldName: String; aValue: TDateTime; aData: PnxByteArray = nil);
procedure ModifyNewData;
procedure InsertNewData;
procedure DeleteRec;
function FindKey(aCount: Integer): Boolean;
function FindNearest(aCount: Integer; aPreferLess: Boolean): Boolean;
function SelIndex(aName: String): Boolean;
function SetRange(aCount: Integer; aKeyExcl: Boolean=True): Boolean;
procedure InitRecord(var aData: PnxByteArray);
property Dict: TnxDataDictionary
read FDictionary;
property Active: Boolean
read FActive write SetActive;
property Cursor: TnxServerBaseCursor
read FCursor;
property NewData: PnxByteArray
read FNewData;
end;
function nxLoadFieldDef(var Field: TnxNativeField; aName: String; aDict: TnxDataDictionary; aOldData, aNewData: PnxByteArray): Boolean;
implementation
{ TnxBooleanField }
type
THackFields = class(TnxFieldsDescriptor);
function nxLoadFieldDef(var Field: TnxNativeField; aName: String; aDict: TnxDataDictionary; aOldData, aNewData: PnxByteArray): Boolean;
begin
with Field do begin
nfField := aDict.GetFieldFromName(aName);
Result := (nfField>=0);
if not Result then Exit;
with aDict.FieldsDescriptor.FieldDescriptor[nfField] do begin
nfOffSet := fdOffset;
nfLen := fdLength;
nfLogRecLenAlign := THackFields(aDict.FieldsDescriptor).fsdLogRecLenAlign;
end;
nfOldData := aOldData;
nfNewData := aNewData;
end;
Result := True;
end;
function TnxBooleanField.FieldType: TnxFieldType;
begin
Result := nxtBoolean;
end;
function TnxBooleanField.GetNewValue: Boolean;
begin
Result := Boolean(NewData^[0]);
end;
function TnxBooleanField.OldValue: Boolean;
begin
if Assigned(nfOldData) then
Result := Boolean(OldData^[0]) else
Result := False;
end;
procedure TnxBooleanField.SetNewValue(const Value: Boolean);
begin
Boolean(NewData^[0]) := Value;
end;
{ TnxCharField }
{ TnxNullString }
function TnxNullStringField.FieldType: TnxFieldType;
begin
Result := nxtNullString;
end;
{ TnxShortString }
function TnxShortStringField.FieldType: TnxFieldType;
begin
Result := nxtShortString;
end;
{ TnxDateTime }
function TnxDateTimeField.FieldType: TnxFieldType;
begin
Result := nxtDateTime;
end;
{ TnxDate }
function TnxDateField.FieldType: TnxFieldType;
begin
Result := nxtDate;
end;
{ TnxCurrency }
function TnxCurrencyField.FieldType: TnxFieldType;
begin
Result := nxtCurrency;
end;
{ TnxDouble }
function TnxDoubleField.FieldType: TnxFieldType;
begin
Result := nxtDouble;
end;
{ TnxSingle }
function TnxSingleField.FieldType: TnxFieldType;
begin
Result := nxtSingle;
end;
{ TnxAutoInc }
function TnxAutoIncField.FieldType: TnxFieldType;
begin
Result := nxtAutoInc;
end;
{ TnxInt64 }
function TnxInt64Field.FieldType: TnxFieldType;
begin
Result := nxtInt64;
end;
{ TnxInt32 }
function TnxInt32Field.FieldType: TnxFieldType;
begin
Result := nxtInt32;
end;
{ TnxInt16 }
function TnxInt16Field.FieldType: TnxFieldType;
begin
Result := nxtInt16;
end;
{ TnxInt8Field }
function TnxInt8Field.FieldType: TnxFieldType;
begin
Result := nxtInt8;
end;
function TnxInt8Field.GetNewValue: TnxInt8;
begin
Result := TnxInt8(nfNewData^[nfOffSet]);
end;
function TnxInt8Field.OldValue: TnxInt8;
begin
if nfOldData=nil then
Result := 0 else
Result := TnxInt8(nfOldData^[nfOffSet]);
end;
procedure TnxInt8Field.SetNewValue(const Value: TnxInt8);
begin
TnxInt8(nfNewData^[nfOffSet]) := Value;
end;
{ TnxWord16Field }
function TnxWord16Field.FieldType: TnxFieldType;
begin
Result := nxtWord16;
end;
function TnxWord16Field.GetNewValue: TnxWord16;
begin
Result := PWord(NewData)^;
end;
function TnxWord16Field.OldValue: TnxWord16;
begin
if nfOldData=nil then
Result := 0 else
Result := PWord(OldData)^;
end;
procedure TnxWord16Field.SetNewValue(const Value: TnxWord16);
begin
PWord(NewData)^:= Value;
end;
{ TnxByteField }
function TnxByteField.FieldType: TnxFieldType;
begin
Result := nxtByte;
end;
function TnxByteField.GetNewValue: Byte;
begin
Result := nfNewData^[nfOffSet];
end;
function TnxByteField.OldValue: Byte;
begin
if nfOldData=nil then
Result := 0 else
Result := nfOldData^[nfOffSet];
end;
procedure TnxByteField.SetNewValue(const Value: Byte);
begin
nfNewData^[nfOffSet] := Value;
end;
{ TnxNativeField }
function TnxNativeField.Changed: Boolean;
function ValueDif: Boolean;
var I : Integer;
begin
for I := 0 to nfLen-1 do
if nfOldData^[nfOffSet+I]<>nfNewData^[nfOffSet+I] then begin
Result := True;
Exit;
end;
Result := False;
end;
begin
if NewNull and OldNull then
Result := False else
Result := (NewNull or OldNull) or ValueDif;
end;
function TnxNativeField.FieldType: TnxFieldType;
begin
Result := nxtBoolean;
end;
function TnxNativeField.GetNewNull: Boolean;
begin
Result := (nfNewData = nil) or
nxIsBitSet(PnxByteArray(@nfNewData^[nfLogRecLenAlign]), nfField);
end;
function TnxNativeField.GetOldNull: Boolean;
begin
Result := (nfOldData = nil) or
nxIsBitSet(PnxByteArray(@nfOldData^[nfLogRecLenAlign]), nfField);
end;
function TnxNativeField.NewData: PnxByteArray;
begin
Result := @nfNewData^[nfOffSet];
end;
function TnxNativeField.OldData: PnxByteArray;
begin
REsult := @nfOldData^[nfOffSet];
end;
procedure TnxNativeField.SetNewNull(const Value: Boolean);
begin
nxSetBit(PnxByteArray(@nfNewData^[nfLogRecLenAlign]), nfField);
FillChar(nfNewData^[nfOffset], nfLen, 0);
end;
procedure TnxNativeField.SetOldNull(const Value: Boolean);
begin
nxSetBit(PnxByteArray(@nfOldData^[nfLogRecLenAlign]), nfField);
FillChar(nfOldData^[nfOffset], nfLen, 0);
end;
{ TnxWord32Field }
function TnxWord32Field.FieldType: TnxFieldType;
begin
Result := nxtWord32;
end;
{ TnxExtended }
function TnxExtendedField.FieldType: TnxFieldType;
begin
Result := nxtExtended;
end;
{ TnxTime }
function TnxTimeField.FieldType: TnxFieldType;
begin
Result := nxtTime;
end;
function TnxWord32Field.GetNewValue: TnxWord32;
begin
Result := TnxWord32(nfNewData^[nfOffSet]);
end;
function TnxWord32Field.OldValue: TnxWord32;
begin
if nfOldData=nil then
Result := 0 else
Result := TnxWord32(nfOldData^[nfOffSet]);
end;
procedure TnxWord32Field.SetNewValue(const Value: TnxWord32);
begin
PnxWord32(NewData)^:= Value;
end;
function TnxInt16Field.GetNewValue: TnxInt16;
begin
Result := TnxInt16(nfNewData^[nfOffSet]);
end;
function TnxInt16Field.OldValue: TnxInt16;
begin
if nfOldData=nil then
Result := 0 else
Result := TnxInt16(nfOldData^[nfOffSet]);
end;
procedure TnxInt16Field.SetNewValue(const Value: TnxInt16);
begin
PnxInt16(NewData)^ := Value;
end;
function TnxInt32Field.GetNewValue: TnxInt32;
begin
Result := TnxInt32(nfNewData^[nfOffSet]);
end;
function TnxInt32Field.OldValue: TnxInt32;
begin
if nfOldData=nil then
Result := 0 else
Result := TnxInt32(nfOldData^[nfOffSet]);
end;
procedure TnxInt32Field.SetNewValue(const Value: TnxInt32);
begin
PnxInt32(NewData)^ := Value;
end;
function TnxInt64Field.GetNewValue: TnxInt64;
begin
Result := TnxInt64(nfNewData^[nfOffSet]);
end;
function TnxInt64Field.OldValue: TnxInt64;
begin
if nfOldData=nil then
Result := 0 else
Result := TnxInt64(nfNewData^[nfOffSet]);
end;
procedure TnxInt64Field.SetNewValue(const Value: TnxInt64);
begin
PnxInt64(NewData)^ := Value;
end;
function TnxSingleField.GetNewValue: TnxSingle;
begin
Result := PnxSingle(NewData)^;
end;
function TnxSingleField.OldValue: TnxSingle;
begin
if nfOldData=nil then
Result := 0 else
Result := PnxSingle(OldData)^;
end;
procedure TnxSingleField.SetNewValue(const Value: TnxSingle);
begin
PnxSingle(NewData)^ := Value;
end;
function TnxDoubleField.GetNewValue: TnxDouble;
begin
Result := PnxDouble(NewData)^;
end;
function TnxDoubleField.OldValue: TnxDouble;
begin
if nfOldData=nil then
Result := 0 else
Result := PnxDouble(OldData)^;
end;
procedure TnxDoubleField.SetNewValue(const Value: TnxDouble);
begin
PnxDouble(NewData)^ := Value;
end;
function TnxExtendedField.GetNewValue: TnxExtended;
begin
Result := PnxExtended(NewData)^;
end;
function TnxExtendedField.OldValue: TnxExtended;
begin
if nfOldData=nil then
Result := 0 else
Result := PnxExtended(OldData)^;
end;
procedure TnxExtendedField.SetNewValue(const Value: TnxExtended);
begin
PnxExtended(NewData)^ := Value;
end;
function TnxCurrencyField.GetNewValue: TnxCurrency;
begin
Result := PnxCurrency(NewData)^;
end;
function TnxCurrencyField.OldValue: TnxCurrency;
begin
if nfOldData=nil then
Result := 0 else
Result := PnxCurrency(OldData)^;
end;
procedure TnxCurrencyField.SetNewValue(const Value: TnxCurrency);
begin
PnxCurrency(NewData)^ := Value;
end;
function TnxDateField.GetNewValue: TnxDate;
begin
Result := PnxDate(NewData)^;
end;
function TnxDateField.OldValue: TnxDate;
begin
if nfOldData=nil then
Result := 0 else
Result := PnxDate(OldData)^;
end;
procedure TnxDateField.SetNewValue(const Value: TnxDate);
begin
PnxDate(NewData)^ := Value;
end;
function TnxTimeField.GetNewValue: TnxTime;
begin
Result := PnxTime(NewData)^;
end;
function TnxTimeField.OldValue: TnxTime;
begin
if nfOldData=nil then
Result := 0 else
Result := PnxTime(OldData)^;
end;
procedure TnxTimeField.SetNewValue(const Value: TnxTime);
begin
PnxTime(NewData)^ := Value;
end;
function TnxDateTimeField.GetNewValue: TnxDateTime;
begin
Result := PnxDateTime(NewData)^;
end;
function TnxDateTimeField.OldValue: TnxDateTime;
begin
if nfOldData=nil then
Result := 0 else
Result := PnxDateTime(OldData)^;
end;
procedure TnxDateTimeField.SetNewValue(const Value: TnxDateTime);
begin
PnxDateTime(NewData)^ := Value;
end;
function TnxShortStringField.GetNewValue: ShortString;
begin
Result := PShortString(NewData)^;
end;
function TnxShortStringField.OldValue: ShortString;
begin
if nfOldData=nil then
Result := '' else
Result := PShortString(OldData)^;
end;
procedure TnxShortStringField.SetNewValue(const Value: ShortString);
var S: ShortString;
begin
S := Value;
if Length(S)>nfLen-1 then
S := Copy(S, 1, nfLen-1);
FillChar(NewData^, nfLen, 0);
NewData^[0] := Length(S);
if S <> '' then
Move(S[1], NewData[1], Length(S));
end;
function TnxNullStringField.GetNewValue: String;
begin
Result := StrPas(PAnsiChar(NewData))
end;
function TnxNullStringField.OldData: String;
begin
if nfOldData=nil then
Result := '' else
Result := StrPas(PAnsiChar(OldData));
end;
procedure TnxNullStringField.SetNewValue(const Value: String);
var
S: string;
L: Integer;
begin
S := Value;
L := Length(S);
if L>nfLen-1 then S := Copy(S, 1, nfLen-1);
FillChar(NewData^, nfLen, 0);
if S <> '' then
Move(S[1], NewData^[0], Length(S));
end;
{ TnxHelpCursor }
type
THackCursor = class ( TnxServerBaseCursor );
constructor TnxHelpCursor.Create(aOldData, aNewData, aKey1, aKey2: PnxByteArray;
aCursor: TnxServerBaseCursor);
begin
nxGetMem(FBuffer, 1024);
Fillchar(FBuffer^, 1024, 0);
FCursor := aCursor;
FDictionary := THackCursor(aCursor).ac_GetDictionary;
FOldData := aOldData;
FNewData := aNewData;
FKeyData1 := aKey1;
FKeyData2 := aKey2;
FOpenMode := False;
end;
constructor TnxHelpCursor.CreateOpen(aName: String; aDB: TnxServerDatabase);
begin
nxGetMem(FBuffer, 1024);
Fillchar(FBuffer^, 1024, 0);
FCursor := nil;
FDictionary := nil;
FOldData := nil;
FNewData := nil;
FKeyData1 := nil;
FKeyData2 := nil;
FOpenMode := True;
FName := aName;
FDB := aDB;
FActive := False;
end;
procedure TnxHelpCursor.DeleteRec;
begin
FCursor.RecordDelete(FNewData);
end;
destructor TnxHelpCursor.Destroy;
begin
nxFreeMem(FBuffer);
SetActive(False);
inherited;
end;
function TnxHelpCursor.FindKey(aCount: Integer): Boolean;
var I: Integer;
begin
I := FCursor.RecordGetForKey(aCount, 0, False, FKeyData1, FNewData, False, True);
Result := (I=0);
end;
function TnxHelpCursor.FindNearest(aCount: Integer;
aPreferLess: Boolean): Boolean;
var
I : Integer;
sa : TnxSearchKeyAction;
function GetRec: Boolean;
begin
if sa = skaSmallerEqual then
Result := (FCursor.RecordGetPrior(nxltNoLock, FNewData)=0) else
Result := (FCursor.RecordGetNext(nxltNoLock, FNewData)=0);
end;
begin
if aPreferLess then
sa := skaSmallerEqual else
sa := skaGreaterEqual;
Result := (FCursor.SetToKey(sa, aCount, 0, False, FKeyData1)=0);
if Result then
Result := GetRec;
if not Result then begin
if sa = skaSmallerEqual then
sa := skaGreaterEqual else
sa := skaSmallerEqual;
Result := (FCursor.SetToKey(sa, aCount, 0, False, FKeyData1)=0);
if Result then
Result := GetRec;
end;
end;
function TnxHelpCursor.GetNext: Boolean;
begin
Result := (FCursor.RecordGetNext(nxltNoLock, FNewData)=0);
end;
function TnxHelpCursor.GetValue(aFieldName: String; aData: PnxByteArray;
aDefValue: Variant): Variant;
var
aField: Integer;
aNull: Boolean;
begin
if (aData=nil) then begin
Result := null;
Exit;
end;
with FCursor, FDictionary.FieldsDescriptor do begin
Result := FDictionary.FieldsDescriptor.FieldByNameAsVariant[aData, aFieldName];
if Result=null then
Result := aDefValue ;
end;
end;
procedure TnxHelpCursor.InitRecord(var aData: PnxByteArray);
begin
if aData=nil then
nxGetMem(aData, Dict.FieldsDescriptor.RecordLength);
Dict.FieldsDescriptor.InitRecord(aData);
end;
procedure TnxHelpCursor.InsertNewData;
var Erro: Integer;
begin
Erro := FCursor.RecordInsert(nxltNoLock, FNewData);
if Erro<>0 then
raise Exception.Create('Error '+IntToStr(Erro)+' on InsertNewData on table "'+FName+'"');
end;
function TnxHelpCursor.Last: Boolean;
var erro: integer;
begin
Result := (FCursor.SetToEnd=0);
if Result then
Result := Prior;
end;
function TnxHelpCursor.LeBool(aFieldName: String; aNew: Boolean): Boolean;
var
aField: Integer;
aData : PnxByteArray;
begin
if aNew then
aData := FNewData else
aData := FOldData;
with FCursor.TableDescriptor, FieldsDescriptor do
if (aData=nil) or IsRecordFieldNull(GetFieldFromName(aFieldName), aData) then
Result := False else
Result := Boolean(GetRecordFieldForFilter(GetFieldFromName(aFieldName), aData)^);
end;
function TnxHelpCursor.LeByte(aFieldName: String; aNew: Boolean): Byte;
var
aField: Integer;
aData : PnxByteArray;
begin
if aNew then
aData := FNewData else
aData := FOldData;
with FCursor.TableDescriptor, FieldsDescriptor do
if (aData=nil) or IsRecordFieldNull(GetFieldFromName(aFieldName), aData) then
Result := 0 else
Result := Byte(GetRecordFieldForFilter(GetFieldFromName(aFieldName), aData)^);
end;
function TnxHelpCursor.LeCurrency(aFieldName: String; aNew: Boolean): Currency;
var
aField: Integer;
aData : PnxByteArray;
begin
if aNew then
aData := FNewData else
aData := FOldData;
with FCursor.TableDescriptor, FieldsDescriptor do
if (aData=nil) or IsRecordFieldNull(GetFieldFromName(aFieldName), aData) then
Result := 0 else
Result := Currency(GetRecordFieldForFilter(GetFieldFromName(aFieldName), aData)^);
end;
{function TnxHelpCursor.LeDateTime(aFieldName: String; aNew: Boolean): TDateTime;
var
aField: Integer;
aData : PnxByteArray;
begin
if aNew then
aData := FNewData else
aData := FOldData;
with FCursor.TableDescriptor, FieldsDescriptor do
if (aData=nil) or IsRecordFieldNull(GetFieldFromName(aFieldName), aData) then
Result := 0 else
Result := TimeStampToDateTime(MSecsToTimeStamp(Comp(GetRecordFieldForFilter(GetFieldFromName(aFieldName), aData)^)));
end;}
function TnxHelpCursor.LeDouble(aFieldName: String; aNew: Boolean): Double;
var
aField: Integer;
aData : PnxByteArray;
begin
if aNew then
aData := FNewData else
aData := FOldData;
with FCursor.TableDescriptor, FieldsDescriptor do
if (aData=nil) or IsRecordFieldNull(GetFieldFromName(aFieldName), aData) then
Result := 0 else
Result := Double(GetRecordFieldForFilter(GetFieldFromName(aFieldName), aData)^);
end;
function TnxHelpCursor.LeInteger(aFieldName: String; aNew: Boolean): Integer;
var
aField: Integer;
aData : PnxByteArray;
begin
if aNew then
aData := FNewData else
aData := FOldData;
with FCursor.TableDescriptor, FieldsDescriptor do
if (aData=nil) or IsRecordFieldNull(GetFieldFromName(aFieldName), aData) then
Result := 0 else
Result := Integer(GetRecordFieldForFilter(GetFieldFromName(aFieldName), aData)^);
end;
function TnxHelpCursor.LeWord(aFieldName: String; aNew: Boolean): Word;
var
aField: Integer;
aData : PnxByteArray;
begin
if aNew then
aData := FNewData else
aData := FOldData;
with FCursor.TableDescriptor, FieldsDescriptor do
if (aData=nil) or IsRecordFieldNull(GetFieldFromName(aFieldName), aData) then
Result := 0 else
Result := Word(GetRecordFieldForFilter(GetFieldFromName(aFieldName), aData)^);
end;
function TnxHelpCursor.LeWord32(aFieldName: String; aNew: Boolean): Cardinal;
var
aField: Integer;
aData : PnxByteArray;
begin
if aNew then
aData := FNewData else
aData := FOldData;
with FCursor.TableDescriptor, FieldsDescriptor do
if (aData=nil) or IsRecordFieldNull(GetFieldFromName(aFieldName), aData) then
Result := 0 else
Result := Cardinal(GetRecordFieldForFilter(GetFieldFromName(aFieldName), aData)^);
end;
function TnxHelpCursor.NewValue(aFieldName: String; aDefValue: Variant): Variant;
begin
Result := GetValue(aFieldName, FNewData, aDefValue);
end;
function TnxHelpCursor.Next: Boolean;
begin
Result := (FCursor.RecordGetNext(nxltNoLock, FNewData)=0);
end;
function TnxHelpCursor.OldValue(aFieldName: String;
aDefValue: Variant): Variant;
begin
Result := GetValue(aFieldName, FOlddata, aDefValue);
end;
function TnxHelpCursor.Prior: Boolean;
begin
Result := (FCursor.RecordGetPrior(nxltNoLock, FNewData)=0);
end;
procedure TnxHelpCursor.ModifyNewData;
begin
FCursor.RecordModify(FNewData, True);
end;
function TnxHelpCursor.SelIndex(aName: String): Boolean;
begin
Result := (FCursor.SwitchToIndex(aName, -1, False)=0);
end;
procedure TnxHelpCursor.SetActive(const Value: Boolean);
var aCursor: TnxAbstractCursor;
begin
if not FOpenMode then Exit;
if FActive=Value then Exit;
if not Value then begin
nxFreeMem(FNewData);
FNewData := nil;
if Assigned(FOldData) then begin
nxFreeMem(FOldData);
FOldData := nil;
end;
if Assigned(FKeyData1) then begin
nxFreeMem(FKeyData1);
FKeyData1 := nil;
end;
if Assigned(FKeyData2) then begin
nxFreeMem(FKeyData2);
FKeyData2 := nil;
end;
FreeAndNil(FCursor);
end else begin
FCursor := nil;
FDictionary := nil;
if FDB.CursorOpen(aCursor, FName, '', omReadWrite, smShared, 10000)<>0 then Exit;
FCursor := TnxServerBaseCursor(aCursor);
try
FDictionary := THackCursor(FCursor).ac_GetDictionary;
nxGetMem(FNewData, FDictionary.FieldsDescriptor.RecordLength);
InitRecord(FNewData);
except
FreeAndNil(FCursor);
end;
end;
FActive := Value;
end;
procedure TnxHelpCursor.SetDateTimeField(aFieldName: String; aValue: TDateTime;
aData: PnxByteArray = nil);
var C: Comp;
begin
if aData=nil then aData := FNewData;
C := TimeStampToMSecs(DateTimeToTimeStamp(aValue));
with FCursor.TableDescriptor, FieldsDescriptor do
SetRecordField(GetFieldFromName(aFieldName), aData, @C);
end;
procedure TnxHelpCursor.SetKey1(aFieldName: String; aValue: Variant);
begin
if FKeyData1=nil then
InitRecord(FKeyData1);
SetValueCustom(aFieldName, aValue, FKeyData1);
end;
procedure TnxHelpCursor.SetKey2(aFieldName: String; aValue: Variant);
begin
if FKeyData2=nil then
InitRecord(FKeyData2);
SetValueCustom(aFieldName, aValue, FKeyData2);
end;
function TnxHelpCursor.SetRange(aCount: Integer; aKeyExcl: Boolean = True): Boolean;
begin
Result := (FCursor.RangeSet(aCount, 0, False, FKeyData1, True, aCount, 0, False, FKeyData2, True)=0)
end;
procedure TnxHelpCursor.SetValue(aFieldName: String; aValue: Variant);
begin
SetValueCustom(aFieldName, aValue, FNewData);
end;
procedure TnxHelpCursor.SetValueCustom(aFieldName: String; aValue: Variant;
aData: PnxByteArray);
begin
FDictionary.FieldsDescriptor.FieldByNameAsVariant[aData, aFieldName] := aValue;
end;
end.
|
unit MonitorWaitStackFix;
{
Fixes TMonitor event stack
See https://en.delphipraxis.net/topic/2824-revisiting-tthreadedqueue-and-tmonitor/
for discussion.
}
{$DEFINE DEBUG_OUTPUT}
{$DEFINE DEBUG_CONSOLEWRITE}
interface
{$IFDEF DEBUG_CONSOLEWRITE}
Uses
System.SyncObjs;
{$ENDIF DEBUG_CONSOLEWRITE}
{$IFDEF DEBUG_CONSOLEWRITE}
var
ConsoleWriteLock: TSpinLock;
{$ENDIF DEBUG_CONSOLEWRITE}
implementation
uses
WinApi.Windows,
System.SysUtils;
{$IFDEF DEBUG_OUTPUT}
procedure DebugWrite(S: String);
begin
{$IFDEF DEBUG_CONSOLEWRITE}
ConsoleWriteLock.Enter;
try
WriteLn(S);
finally
ConsoleWriteLock.Exit;
end;
{$ELSE DEBUG_CONSOLEWRITE}
OutputDebugString(PChar(S));
{$ENDIF DEBUG_CONSOLEWRITE}
end;
{$ENDIF DEBUG_OUTPUT}
{====================== Patched TMonitorSupport below =========================}
{ This section provides the required support to the TMonitor record in System. }
type
PEventItemHolder = ^TEventItemHolder;
TEventItemHolder = record
Next: PEventItemHolder;
Event: Pointer;
end align {$IFDEF CPUX64}16{$ELSE CPUX64}8{$ENDIF CPUX64};
TEventStack = record
Head: PEventItemHolder;
Counter: NativeInt;
procedure Push(EventItem: PEventItemHolder);
function Pop: PEventItemHolder;
end align {$IFDEF CPUX64}16{$ELSE CPUX64}8{$ENDIF CPUX64};
// taken from OmniThreadLibrary and adapted.
// either 8-byte or 16-byte CAS, depending on the platform;
// destination must be propely aligned (8- or 16-byte)
//function CAS(const oldData: pointer; oldReference: NativeInt; newData: pointer;
// newReference: NativeInt; var destination): boolean;
//asm
//{$IFNDEF CPUX64}
// push edi
// push ebx
// mov ebx, newData
// mov ecx, newReference
// mov edi, destination
// lock cmpxchg8b qword ptr [edi]
// pop ebx
// pop edi
//{$ELSE CPUX64}
// .pushnv rbx
// mov rax, oldData
// mov rbx, newData
// mov rcx, newReference
// mov r8, [destination]
// lock cmpxchg16b [r8]
//{$ENDIF CPUX64}
// setz al
//end; { CAS }
// Delphi's InterlockedCompareExchange128 is broken
{$IFDEF Win64}
function InterlockedCompareExchange128(Destination: Pointer; ExchangeHigh, ExchangeLow: Int64; ComparandResult: Pointer): boolean;
// The parameters are in the RCX, RDX, R8 and R9 registers per the MS x64 calling convention:
// RCX Destination
// RDX ExchangeHigh
// R8 ExchangeLow
// R9 ComparandResult
//
// CMPXCHG16B requires the following register setup:
// RDX:RAX ComparandResult.High:ComparandResult.Low
// RCX:RBX ExchangeHigh:ExchangeLow
// See: https://www.felixcloutier.com/x86/cmpxchg8b:cmpxchg16b
asm
.PUSHNV RBX
MOV R10,Destination // RCX
MOV RBX,ExchangeLow // R8
MOV RCX,ExchangeHigh // RDX
MOV RDX,[ComparandResult+8] // R9
MOV RAX,[ComparandResult] // R9
LOCK CMPXCHG16B [R10]
MOV [ComparandResult+8],RDX // R9
MOV [ComparandResult],RAX // R9
SETZ AL
end;
{$ENDIF Win64}
function InterlockedCompareExchange(var Dest: TEventStack; const NewValue, CurrentValue: TEventStack): Boolean;
begin
//Result := CAS(CurrentValue.Head, CurrentValue.Counter, NewValue.Head, NewValue.Counter, Dest);
{$IFDEF CPUX64}
Result := InterlockedCompareExchange128(@Dest, NewValue.Counter, Int64(NewValue.Head), @CurrentValue);
{$ELSE CPUX64}
Result := InterlockedCompareExchange64(Int64(Dest), Int64(NewValue), Int64(CurrentValue)) = Int64(CurrentValue);
{$ENDIF CPUX64}
end;
procedure TEventStack.Push(EventItem: PEventItemHolder);
var
Current, Next: TEventStack;
begin
repeat
Current := Self;
EventItem.Next := Current.Head;
Next.Head := EventItem;
Next.Counter := Current.Counter + 1;
until InterlockedCompareExchange(Self, Next, Current);
end;
function TEventStack.Pop: PEventItemHolder;
var
Current, Next: TEventStack;
begin
repeat
Current := Self;
if (Current.Head = nil) then
Exit(nil);
Next.Head := Current.Head.Next;
Next.Counter := Current.Counter + 1;
until InterlockedCompareExchange(Self, Next, Current);
Result := Current.Head;
end;
var
EventCache: TEventStack = (Head: nil; Counter: 0);
EventItemHolders: TEventStack = (Head: nil; Counter: 0);
{$IFDEF DEBUG_OUTPUT}
NewWaitObjCount: NativeUInt = 0;
{$ENDIF DEBUG_OUTPUT}
function NewWaitObj: Pointer;
var
EventItem: PEventItemHolder;
begin
{$IFDEF DEBUG_OUTPUT}
AtomicIncrement(NewWaitObjCount);
if NewWaitObjCount mod 100000 = 0 then
DebugWrite(Format('New Wait objects created: %d', [NewWaitObjCount]));
{$ENDIF DEBUG_OUTPUT}
EventItem := EventCache.Pop;
if EventItem <> nil then
begin
{$IFDEF DEBUG_OUTPUT}
if EventItem.Event = nil then
DebugWrite('NewWaitObj EventItem.Event is nil');
{$ENDIF DEBUG_OUTPUT}
Result := EventItem.Event;
EventItem.Event := nil;
EventItemHolders.Push(EventItem);
end else begin
Result := Pointer(CreateEvent(nil, False, False, nil));
{$IFDEF DEBUG_OUTPUT}
if not Assigned(Result) Then
DebugWrite('NewWaitObj CreateEvent failure');
{$ENDIF DEBUG_OUTPUT}
end;
{$IFDEF DEBUG_OUTPUT}
if not ResetEvent(THandle(Result))then
DebugWrite('ResetEvent returned false');
{$ELSE DEBUG_OUTPUT}
ResetEvent(THandle(Result)
{$ENDIF DEBUG_OUTPUT}
end;
procedure FreeWaitObj(WaitObject: Pointer);
var
EventItem: PEventItemHolder;
begin
EventItem := EventItemHolders.Pop;
if EventItem = nil then
New(EventItem);
EventItem.Event := WaitObject;
{$IFDEF DEBUG_OUTPUT}
if not Assigned(EventItem.Event) then
DebugWrite('FreeWaitObj WaitObject is nil');
{$ENDIF DEBUG_OUTPUT}
EventCache.Push(EventItem);
end;
procedure CleanStack(Stack: PEventItemHolder);
var
Walker: PEventItemHolder;
begin
Walker := Stack;
while Walker <> nil do
begin
Stack := Walker.Next;
if Walker.Event <> nil then
CloseHandle(THandle(Walker.Event));
Dispose(Walker);
Walker := Stack;
end;
end;
function WaitOrSignalObj(SignalObject, WaitObject: Pointer; Timeout: Cardinal): Cardinal;
begin
if (SignalObject <> nil) and (WaitObject = nil) then
begin
Result := 0;
SetEvent(THandle(SignalObject));
end else if (WaitObject <> nil) and (SignalObject = nil) then begin
Result := WaitForSingleObject(THandle(WaitObject), Timeout);
{$IFDEF DEBUG_OUTPUT}
if (Result <> WAIT_TIMEOUT) and (Result <> WAIT_OBJECT_0) then
DebugWrite('WaitOrSignalObj returned: ' + Result.ToString );
{$ENDIF DEBUG_OUTPUT}
end
else
Result := 1;
end;
initialization
{$IFDEF DEBUG_CONSOLEWRITE}
ConsoleWriteLock := TSpinLock.Create(True);
{$ENDIF DEBUG_CONSOLEWRITE}
System.MonitorSupport.NewWaitObject := NewWaitObj;
System.MonitorSupport.FreeWaitObject := FreeWaitObj;
System.MonitorSupport.WaitOrSignalObject := WaitOrSignalObj;
finalization
CleanStack(AtomicExchange(Pointer(EventCache.Head), nil));
CleanStack(AtomicExchange(Pointer(EventItemHolders.Head), nil));
end.
|
unit UPacketManager;
interface
uses
Windows, Classes, SyncObjs ,GD_Utils,UProtocol;
const
C_SEND_PACKET = 1000;
C_RECV_PACKET = 1001;
C_PACKET_HANDLE_BREAK = -1;
type
FPacketProc = Procedure (_PacketObject:PPacketObject) of object;
TPacketNode = Class
HandleName:String;
PacketType:Cardinal;
Proc:FPacketProc;
End;
TPacketManager = class
private
Cri:TCriticalSection;
List:TList;
Procedure OnPacketHandle(PacketType:Cardinal;_PacketObject:PPacketObject);
function GetListCount: Cardinal;
public
constructor Create();
Function AddItem(PacketType:Cardinal;HandleName:string; Proc:FPacketProc):Bool;
Procedure OnSendHandle(_PacketObject:PPacketObject);
Procedure OnRecvHandle(_PacketObject:PPacketObject);
property HandleCount:Cardinal read GetListCount;
end;
var
Packet:TPacketManager;
implementation
{ TPacketManager }
function TPacketManager.AddItem(PacketType: Cardinal; HandleName:string; Proc: FPacketProc): Bool;
var
pNode:TPacketNode;
begin
try
pNode:=TPacketNode.Create;
pNode.HandleName := HandleName;
pNode.PacketType := PacketType;
pNode.Proc := Proc;
Dbgprint('Add Packet Handle[Name:%s Proc:0x%X]',[HandleName,Cardinal(@Proc)]);
Cri.Enter;
List.Add(pNode);
Cri.Leave;
Result:=True;
Except
Result:=False;
end;
end;
constructor TPacketManager.Create;
begin
List:=TList.Create;
Cri:=TCriticalSection.Create;
end;
function TPacketManager.GetListCount: Cardinal;
begin
Result:=List.Count;
end;
procedure TPacketManager.OnPacketHandle(PacketType:Cardinal;_PacketObject:PPacketObject);
var
i:Integer;
pNode:TPacketNode;
begin
Cri.Enter;
for i := 0 to List.Count - 1 do
begin
pNode := List[i];
if pNode.PacketType = PacketType then
begin
if Assigned(pNode.Proc) then
begin
// Dbgprint('OnPacket[%s] - %X',[pNode.HandleName,Cardinal(@pNode.Proc)]);
pNode.Proc(_PacketObject);
end;
end;
end;
Cri.Leave;
end;
procedure TPacketManager.OnRecvHandle(_PacketObject:PPacketObject);
begin
OnPacketHandle(C_RECV_PACKET,_PacketObject);
end;
procedure TPacketManager.OnSendHandle(_PacketObject:PPacketObject);
begin
OnPacketHandle(C_SEND_PACKET,_PacketObject);
end;
initialization
Packet:=TPacketManager.Create;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.